ImageProcessor.cs 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Threading;
  7. using System.Threading.Tasks;
  8. using Emby.Drawing.Common;
  9. using MediaBrowser.Common.Extensions;
  10. using MediaBrowser.Controller;
  11. using MediaBrowser.Controller.Drawing;
  12. using MediaBrowser.Controller.Entities;
  13. using MediaBrowser.Controller.Library;
  14. using MediaBrowser.Controller.MediaEncoding;
  15. using MediaBrowser.Controller.Providers;
  16. using MediaBrowser.Model.Drawing;
  17. using MediaBrowser.Model.Entities;
  18. using MediaBrowser.Model.Extensions;
  19. using MediaBrowser.Model.IO;
  20. using MediaBrowser.Model.Net;
  21. using MediaBrowser.Model.Serialization;
  22. using MediaBrowser.Model.Threading;
  23. using Microsoft.Extensions.Logging;
  24. namespace Emby.Drawing
  25. {
  26. /// <summary>
  27. /// Class ImageProcessor
  28. /// </summary>
  29. public class ImageProcessor : IImageProcessor, IDisposable
  30. {
  31. /// <summary>
  32. /// The us culture
  33. /// </summary>
  34. protected readonly CultureInfo UsCulture = new CultureInfo("en-US");
  35. /// <summary>
  36. /// Gets the list of currently registered image processors
  37. /// Image processors are specialized metadata providers that run after the normal ones
  38. /// </summary>
  39. /// <value>The image enhancers.</value>
  40. public IImageEnhancer[] ImageEnhancers { get; private set; }
  41. /// <summary>
  42. /// The _logger
  43. /// </summary>
  44. private readonly ILogger _logger;
  45. private readonly IFileSystem _fileSystem;
  46. private readonly IJsonSerializer _jsonSerializer;
  47. private readonly IServerApplicationPaths _appPaths;
  48. private IImageEncoder _imageEncoder;
  49. private readonly Func<ILibraryManager> _libraryManager;
  50. private readonly Func<IMediaEncoder> _mediaEncoder;
  51. public ImageProcessor(ILogger logger,
  52. IServerApplicationPaths appPaths,
  53. IFileSystem fileSystem,
  54. IJsonSerializer jsonSerializer,
  55. IImageEncoder imageEncoder,
  56. Func<ILibraryManager> libraryManager, ITimerFactory timerFactory, Func<IMediaEncoder> mediaEncoder)
  57. {
  58. _logger = logger;
  59. _fileSystem = fileSystem;
  60. _jsonSerializer = jsonSerializer;
  61. _imageEncoder = imageEncoder;
  62. _libraryManager = libraryManager;
  63. _mediaEncoder = mediaEncoder;
  64. _appPaths = appPaths;
  65. ImageEnhancers = new IImageEnhancer[] { };
  66. ImageHelper.ImageProcessor = this;
  67. }
  68. public IImageEncoder ImageEncoder
  69. {
  70. get => _imageEncoder;
  71. set
  72. {
  73. if (value == null)
  74. {
  75. throw new ArgumentNullException(nameof(value));
  76. }
  77. _imageEncoder = value;
  78. }
  79. }
  80. public string[] SupportedInputFormats =>
  81. new string[]
  82. {
  83. "tiff",
  84. "tif",
  85. "jpeg",
  86. "jpg",
  87. "png",
  88. "aiff",
  89. "cr2",
  90. "crw",
  91. // Remove until supported
  92. //"nef",
  93. "orf",
  94. "pef",
  95. "arw",
  96. "webp",
  97. "gif",
  98. "bmp",
  99. "erf",
  100. "raf",
  101. "rw2",
  102. "nrw",
  103. "dng",
  104. "ico",
  105. "astc",
  106. "ktx",
  107. "pkm",
  108. "wbmp"
  109. };
  110. public bool SupportsImageCollageCreation => _imageEncoder.SupportsImageCollageCreation;
  111. private string ResizedImageCachePath => Path.Combine(_appPaths.ImageCachePath, "resized-images");
  112. private string EnhancedImageCachePath => Path.Combine(_appPaths.ImageCachePath, "enhanced-images");
  113. public void AddParts(IEnumerable<IImageEnhancer> enhancers)
  114. {
  115. ImageEnhancers = enhancers.ToArray();
  116. }
  117. public async Task ProcessImage(ImageProcessingOptions options, Stream toStream)
  118. {
  119. var file = await ProcessImage(options).ConfigureAwait(false);
  120. using (var fileStream = _fileSystem.GetFileStream(file.Item1, FileOpenMode.Open, FileAccessMode.Read, FileShareMode.Read, true))
  121. {
  122. await fileStream.CopyToAsync(toStream).ConfigureAwait(false);
  123. }
  124. }
  125. public ImageFormat[] GetSupportedImageOutputFormats()
  126. {
  127. return _imageEncoder.SupportedOutputFormats;
  128. }
  129. private readonly string[] TransparentImageTypes = new string[] { ".png", ".webp", ".gif" };
  130. public bool SupportsTransparency(string path)
  131. {
  132. return TransparentImageTypes.Contains(Path.GetExtension(path) ?? string.Empty);
  133. }
  134. public async Task<Tuple<string, string, DateTime>> ProcessImage(ImageProcessingOptions options)
  135. {
  136. if (options == null)
  137. {
  138. throw new ArgumentNullException(nameof(options));
  139. }
  140. var originalImage = options.Image;
  141. var item = options.Item;
  142. if (!originalImage.IsLocalFile)
  143. {
  144. if (item == null)
  145. {
  146. item = _libraryManager().GetItemById(options.ItemId);
  147. }
  148. originalImage = await _libraryManager().ConvertImageToLocal(item, originalImage, options.ImageIndex).ConfigureAwait(false);
  149. }
  150. var originalImagePath = originalImage.Path;
  151. var dateModified = originalImage.DateModified;
  152. var originalImageSize = originalImage.Width > 0 && originalImage.Height > 0 ? new ImageSize(originalImage.Width, originalImage.Height) : (ImageSize?)null;
  153. if (!_imageEncoder.SupportsImageEncoding)
  154. {
  155. return new Tuple<string, string, DateTime>(originalImagePath, MimeTypes.GetMimeType(originalImagePath), dateModified);
  156. }
  157. var supportedImageInfo = await GetSupportedImage(originalImagePath, dateModified).ConfigureAwait(false);
  158. originalImagePath = supportedImageInfo.Item1;
  159. dateModified = supportedImageInfo.Item2;
  160. var requiresTransparency = TransparentImageTypes.Contains(Path.GetExtension(originalImagePath) ?? string.Empty);
  161. if (options.Enhancers.Length > 0)
  162. {
  163. if (item == null)
  164. {
  165. item = _libraryManager().GetItemById(options.ItemId);
  166. }
  167. var tuple = await GetEnhancedImage(new ItemImageInfo
  168. {
  169. DateModified = dateModified,
  170. Type = originalImage.Type,
  171. Path = originalImagePath
  172. }, requiresTransparency, item, options.ImageIndex, options.Enhancers, CancellationToken.None).ConfigureAwait(false);
  173. originalImagePath = tuple.Item1;
  174. dateModified = tuple.Item2;
  175. requiresTransparency = tuple.Item3;
  176. // TODO: Get this info
  177. originalImageSize = null;
  178. }
  179. var photo = item as Photo;
  180. var autoOrient = false;
  181. ImageOrientation? orientation = null;
  182. if (photo != null)
  183. {
  184. if (photo.Orientation.HasValue)
  185. {
  186. if (photo.Orientation.Value != ImageOrientation.TopLeft)
  187. {
  188. autoOrient = true;
  189. orientation = photo.Orientation;
  190. }
  191. }
  192. else
  193. {
  194. // Orientation unknown, so do it
  195. autoOrient = true;
  196. orientation = photo.Orientation;
  197. }
  198. }
  199. if (options.HasDefaultOptions(originalImagePath, originalImageSize) && (!autoOrient || !options.RequiresAutoOrientation))
  200. {
  201. // Just spit out the original file if all the options are default
  202. return new Tuple<string, string, DateTime>(originalImagePath, MimeTypes.GetMimeType(originalImagePath), dateModified);
  203. }
  204. //ImageSize? originalImageSize = GetSavedImageSize(originalImagePath, dateModified);
  205. //if (originalImageSize.HasValue && options.HasDefaultOptions(originalImagePath, originalImageSize.Value) && !autoOrient)
  206. //{
  207. // // Just spit out the original file if all the options are default
  208. // _logger.LogInformation("Returning original image {0}", originalImagePath);
  209. // return new ValueTuple<string, string, DateTime>(originalImagePath, MimeTypes.GetMimeType(originalImagePath), dateModified);
  210. //}
  211. var newSize = ImageHelper.GetNewImageSize(options, null);
  212. var quality = options.Quality;
  213. var outputFormat = GetOutputFormat(options.SupportedOutputFormats, requiresTransparency);
  214. var cacheFilePath = GetCacheFilePath(originalImagePath, newSize, quality, dateModified, outputFormat, options.AddPlayedIndicator, options.PercentPlayed, options.UnplayedCount, options.Blur, options.BackgroundColor, options.ForegroundLayer);
  215. CheckDisposed();
  216. var lockInfo = GetLock(cacheFilePath);
  217. await lockInfo.Lock.WaitAsync().ConfigureAwait(false);
  218. try
  219. {
  220. if (!_fileSystem.FileExists(cacheFilePath))
  221. {
  222. if (options.CropWhiteSpace && !SupportsTransparency(originalImagePath))
  223. {
  224. options.CropWhiteSpace = false;
  225. }
  226. var resultPath = _imageEncoder.EncodeImage(originalImagePath, dateModified, cacheFilePath, autoOrient, orientation, quality, options, outputFormat);
  227. if (string.Equals(resultPath, originalImagePath, StringComparison.OrdinalIgnoreCase))
  228. {
  229. return new Tuple<string, string, DateTime>(originalImagePath, MimeTypes.GetMimeType(originalImagePath), dateModified);
  230. }
  231. return new Tuple<string, string, DateTime>(cacheFilePath, GetMimeType(outputFormat, cacheFilePath), _fileSystem.GetLastWriteTimeUtc(cacheFilePath));
  232. }
  233. return new Tuple<string, string, DateTime>(cacheFilePath, GetMimeType(outputFormat, cacheFilePath), _fileSystem.GetLastWriteTimeUtc(cacheFilePath));
  234. }
  235. catch (ArgumentOutOfRangeException ex)
  236. {
  237. // Decoder failed to decode it
  238. #if DEBUG
  239. _logger.LogError(ex, "Error encoding image");
  240. #endif
  241. // Just spit out the original file if all the options are default
  242. return new Tuple<string, string, DateTime>(originalImagePath, MimeTypes.GetMimeType(originalImagePath), dateModified);
  243. }
  244. catch (Exception ex)
  245. {
  246. // If it fails for whatever reason, return the original image
  247. _logger.LogError(ex, "Error encoding image");
  248. // Just spit out the original file if all the options are default
  249. return new Tuple<string, string, DateTime>(originalImagePath, MimeTypes.GetMimeType(originalImagePath), dateModified);
  250. }
  251. finally
  252. {
  253. ReleaseLock(cacheFilePath, lockInfo);
  254. }
  255. }
  256. private ImageFormat GetOutputFormat(ImageFormat[] clientSupportedFormats, bool requiresTransparency)
  257. {
  258. var serverFormats = GetSupportedImageOutputFormats();
  259. // Client doesn't care about format, so start with webp if supported
  260. if (serverFormats.Contains(ImageFormat.Webp) && clientSupportedFormats.Contains(ImageFormat.Webp))
  261. {
  262. return ImageFormat.Webp;
  263. }
  264. // If transparency is needed and webp isn't supported, than png is the only option
  265. if (requiresTransparency && clientSupportedFormats.Contains(ImageFormat.Png))
  266. {
  267. return ImageFormat.Png;
  268. }
  269. foreach (var format in clientSupportedFormats)
  270. {
  271. if (serverFormats.Contains(format))
  272. {
  273. return format;
  274. }
  275. }
  276. // We should never actually get here
  277. return ImageFormat.Jpg;
  278. }
  279. private void CopyFile(string src, string destination)
  280. {
  281. try
  282. {
  283. _fileSystem.CopyFile(src, destination, true);
  284. }
  285. catch
  286. {
  287. }
  288. }
  289. private string GetMimeType(ImageFormat format, string path)
  290. {
  291. if (format == ImageFormat.Bmp)
  292. {
  293. return MimeTypes.GetMimeType("i.bmp");
  294. }
  295. if (format == ImageFormat.Gif)
  296. {
  297. return MimeTypes.GetMimeType("i.gif");
  298. }
  299. if (format == ImageFormat.Jpg)
  300. {
  301. return MimeTypes.GetMimeType("i.jpg");
  302. }
  303. if (format == ImageFormat.Png)
  304. {
  305. return MimeTypes.GetMimeType("i.png");
  306. }
  307. if (format == ImageFormat.Webp)
  308. {
  309. return MimeTypes.GetMimeType("i.webp");
  310. }
  311. return MimeTypes.GetMimeType(path);
  312. }
  313. /// <summary>
  314. /// Increment this when there's a change requiring caches to be invalidated
  315. /// </summary>
  316. private const string Version = "3";
  317. /// <summary>
  318. /// Gets the cache file path based on a set of parameters
  319. /// </summary>
  320. private string GetCacheFilePath(string originalPath, ImageSize outputSize, int quality, DateTime dateModified, ImageFormat format, bool addPlayedIndicator, double percentPlayed, int? unwatchedCount, int? blur, string backgroundColor, string foregroundLayer)
  321. {
  322. var filename = originalPath;
  323. filename += "width=" + outputSize.Width;
  324. filename += "height=" + outputSize.Height;
  325. filename += "quality=" + quality;
  326. filename += "datemodified=" + dateModified.Ticks;
  327. filename += "f=" + format;
  328. if (addPlayedIndicator)
  329. {
  330. filename += "pl=true";
  331. }
  332. if (percentPlayed > 0)
  333. {
  334. filename += "p=" + percentPlayed;
  335. }
  336. if (unwatchedCount.HasValue)
  337. {
  338. filename += "p=" + unwatchedCount.Value;
  339. }
  340. if (blur.HasValue)
  341. {
  342. filename += "blur=" + blur.Value;
  343. }
  344. if (!string.IsNullOrEmpty(backgroundColor))
  345. {
  346. filename += "b=" + backgroundColor;
  347. }
  348. if (!string.IsNullOrEmpty(foregroundLayer))
  349. {
  350. filename += "fl=" + foregroundLayer;
  351. }
  352. filename += "v=" + Version;
  353. return GetCachePath(ResizedImageCachePath, filename, "." + format.ToString().ToLower());
  354. }
  355. public ImageSize GetImageSize(BaseItem item, ItemImageInfo info)
  356. {
  357. return GetImageSize(item, info, false, true);
  358. }
  359. public ImageSize GetImageSize(BaseItem item, ItemImageInfo info, bool allowSlowMethods, bool updateItem)
  360. {
  361. var width = info.Width;
  362. var height = info.Height;
  363. if (height > 0 && width > 0)
  364. {
  365. return new ImageSize
  366. {
  367. Width = width,
  368. Height = height
  369. };
  370. }
  371. var path = info.Path;
  372. _logger.LogInformation("Getting image size for item {0} {1}", item.GetType().Name, path);
  373. var size = GetImageSize(path, allowSlowMethods);
  374. info.Height = Convert.ToInt32(size.Height);
  375. info.Width = Convert.ToInt32(size.Width);
  376. if (updateItem)
  377. {
  378. _libraryManager().UpdateImages(item);
  379. }
  380. return size;
  381. }
  382. public ImageSize GetImageSize(string path)
  383. {
  384. return GetImageSize(path, true);
  385. }
  386. /// <summary>
  387. /// Gets the size of the image.
  388. /// </summary>
  389. private ImageSize GetImageSize(string path, bool allowSlowMethod)
  390. {
  391. if (string.IsNullOrEmpty(path))
  392. {
  393. throw new ArgumentNullException(nameof(path));
  394. }
  395. try
  396. {
  397. return ImageHeader.GetDimensions(path, _logger, _fileSystem);
  398. }
  399. catch
  400. {
  401. if (!allowSlowMethod)
  402. {
  403. throw;
  404. }
  405. }
  406. return _imageEncoder.GetImageSize(path);
  407. }
  408. /// <summary>
  409. /// Gets the image cache tag.
  410. /// </summary>
  411. /// <param name="item">The item.</param>
  412. /// <param name="image">The image.</param>
  413. /// <returns>Guid.</returns>
  414. /// <exception cref="ArgumentNullException">item</exception>
  415. public string GetImageCacheTag(BaseItem item, ItemImageInfo image)
  416. {
  417. var supportedEnhancers = GetSupportedEnhancers(item, image.Type);
  418. return GetImageCacheTag(item, image, supportedEnhancers);
  419. }
  420. public string GetImageCacheTag(BaseItem item, ChapterInfo chapter)
  421. {
  422. try
  423. {
  424. return GetImageCacheTag(item, new ItemImageInfo
  425. {
  426. Path = chapter.ImagePath,
  427. Type = ImageType.Chapter,
  428. DateModified = chapter.ImageDateModified
  429. });
  430. }
  431. catch
  432. {
  433. return null;
  434. }
  435. }
  436. /// <summary>
  437. /// Gets the image cache tag.
  438. /// </summary>
  439. /// <param name="item">The item.</param>
  440. /// <param name="image">The image.</param>
  441. /// <param name="imageEnhancers">The image enhancers.</param>
  442. /// <returns>Guid.</returns>
  443. /// <exception cref="ArgumentNullException">item</exception>
  444. public string GetImageCacheTag(BaseItem item, ItemImageInfo image, IImageEnhancer[] imageEnhancers)
  445. {
  446. var originalImagePath = image.Path;
  447. var dateModified = image.DateModified;
  448. var imageType = image.Type;
  449. // Optimization
  450. if (imageEnhancers.Length == 0)
  451. {
  452. return (originalImagePath + dateModified.Ticks).GetMD5().ToString("N");
  453. }
  454. // Cache name is created with supported enhancers combined with the last config change so we pick up new config changes
  455. var cacheKeys = imageEnhancers.Select(i => i.GetConfigurationCacheKey(item, imageType)).ToList();
  456. cacheKeys.Add(originalImagePath + dateModified.Ticks);
  457. return string.Join("|", cacheKeys.ToArray()).GetMD5().ToString("N");
  458. }
  459. private async Task<ValueTuple<string, DateTime>> GetSupportedImage(string originalImagePath, DateTime dateModified)
  460. {
  461. var inputFormat = (Path.GetExtension(originalImagePath) ?? string.Empty)
  462. .TrimStart('.')
  463. .Replace("jpeg", "jpg", StringComparison.OrdinalIgnoreCase);
  464. // These are just jpg files renamed as tbn
  465. if (string.Equals(inputFormat, "tbn", StringComparison.OrdinalIgnoreCase))
  466. {
  467. return new ValueTuple<string, DateTime>(originalImagePath, dateModified);
  468. }
  469. if (!_imageEncoder.SupportedInputFormats.Contains(inputFormat, StringComparer.OrdinalIgnoreCase))
  470. {
  471. try
  472. {
  473. var filename = (originalImagePath + dateModified.Ticks.ToString(UsCulture)).GetMD5().ToString("N");
  474. var cacheExtension = _mediaEncoder().SupportsEncoder("libwebp") ? ".webp" : ".png";
  475. var outputPath = Path.Combine(_appPaths.ImageCachePath, "converted-images", filename + cacheExtension);
  476. var file = _fileSystem.GetFileInfo(outputPath);
  477. if (!file.Exists)
  478. {
  479. await _mediaEncoder().ConvertImage(originalImagePath, outputPath).ConfigureAwait(false);
  480. dateModified = _fileSystem.GetLastWriteTimeUtc(outputPath);
  481. }
  482. else
  483. {
  484. dateModified = file.LastWriteTimeUtc;
  485. }
  486. originalImagePath = outputPath;
  487. }
  488. catch (Exception ex)
  489. {
  490. _logger.LogError(ex, "Image conversion failed for {originalImagePath}", originalImagePath);
  491. }
  492. }
  493. return new ValueTuple<string, DateTime>(originalImagePath, dateModified);
  494. }
  495. /// <summary>
  496. /// Gets the enhanced image.
  497. /// </summary>
  498. /// <param name="item">The item.</param>
  499. /// <param name="imageType">Type of the image.</param>
  500. /// <param name="imageIndex">Index of the image.</param>
  501. /// <returns>Task{System.String}.</returns>
  502. public async Task<string> GetEnhancedImage(BaseItem item, ImageType imageType, int imageIndex)
  503. {
  504. var enhancers = GetSupportedEnhancers(item, imageType);
  505. var imageInfo = item.GetImageInfo(imageType, imageIndex);
  506. var inputImageSupportsTransparency = SupportsTransparency(imageInfo.Path);
  507. var result = await GetEnhancedImage(imageInfo, inputImageSupportsTransparency, item, imageIndex, enhancers, CancellationToken.None);
  508. return result.Item1;
  509. }
  510. private async Task<ValueTuple<string, DateTime, bool>> GetEnhancedImage(ItemImageInfo image,
  511. bool inputImageSupportsTransparency,
  512. BaseItem item,
  513. int imageIndex,
  514. IImageEnhancer[] enhancers,
  515. CancellationToken cancellationToken)
  516. {
  517. var originalImagePath = image.Path;
  518. var dateModified = image.DateModified;
  519. var imageType = image.Type;
  520. try
  521. {
  522. var cacheGuid = GetImageCacheTag(item, image, enhancers);
  523. // Enhance if we have enhancers
  524. var enhancedImageInfo = await GetEnhancedImageInternal(originalImagePath, item, imageType, imageIndex, enhancers, cacheGuid, cancellationToken).ConfigureAwait(false);
  525. var enhancedImagePath = enhancedImageInfo.Item1;
  526. // If the path changed update dateModified
  527. if (!string.Equals(enhancedImagePath, originalImagePath, StringComparison.OrdinalIgnoreCase))
  528. {
  529. var treatmentRequiresTransparency = enhancedImageInfo.Item2;
  530. return new ValueTuple<string, DateTime, bool>(enhancedImagePath, _fileSystem.GetLastWriteTimeUtc(enhancedImagePath), treatmentRequiresTransparency);
  531. }
  532. }
  533. catch (Exception ex)
  534. {
  535. _logger.LogError(ex, "Error enhancing image");
  536. }
  537. return new ValueTuple<string, DateTime, bool>(originalImagePath, dateModified, inputImageSupportsTransparency);
  538. }
  539. /// <summary>
  540. /// Gets the enhanced image internal.
  541. /// </summary>
  542. /// <param name="originalImagePath">The original image path.</param>
  543. /// <param name="item">The item.</param>
  544. /// <param name="imageType">Type of the image.</param>
  545. /// <param name="imageIndex">Index of the image.</param>
  546. /// <param name="supportedEnhancers">The supported enhancers.</param>
  547. /// <param name="cacheGuid">The cache unique identifier.</param>
  548. /// <returns>Task&lt;System.String&gt;.</returns>
  549. /// <exception cref="ArgumentNullException">
  550. /// originalImagePath
  551. /// or
  552. /// item
  553. /// </exception>
  554. private async Task<ValueTuple<string, bool>> GetEnhancedImageInternal(string originalImagePath,
  555. BaseItem item,
  556. ImageType imageType,
  557. int imageIndex,
  558. IImageEnhancer[] supportedEnhancers,
  559. string cacheGuid,
  560. CancellationToken cancellationToken)
  561. {
  562. if (string.IsNullOrEmpty(originalImagePath))
  563. {
  564. throw new ArgumentNullException(nameof(originalImagePath));
  565. }
  566. if (item == null)
  567. {
  568. throw new ArgumentNullException(nameof(item));
  569. }
  570. var treatmentRequiresTransparency = false;
  571. foreach (var enhancer in supportedEnhancers)
  572. {
  573. if (!treatmentRequiresTransparency)
  574. {
  575. treatmentRequiresTransparency = enhancer.GetEnhancedImageInfo(item, originalImagePath, imageType, imageIndex).RequiresTransparency;
  576. }
  577. }
  578. // All enhanced images are saved as png to allow transparency
  579. var cacheExtension = _imageEncoder.SupportedOutputFormats.Contains(ImageFormat.Webp) ?
  580. ".webp" :
  581. (treatmentRequiresTransparency ? ".png" : ".jpg");
  582. var enhancedImagePath = GetCachePath(EnhancedImageCachePath, cacheGuid + cacheExtension);
  583. var lockInfo = GetLock(enhancedImagePath);
  584. await lockInfo.Lock.WaitAsync(cancellationToken).ConfigureAwait(false);
  585. try
  586. {
  587. // Check again in case of contention
  588. if (_fileSystem.FileExists(enhancedImagePath))
  589. {
  590. return new ValueTuple<string, bool>(enhancedImagePath, treatmentRequiresTransparency);
  591. }
  592. _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(enhancedImagePath));
  593. await ExecuteImageEnhancers(supportedEnhancers, originalImagePath, enhancedImagePath, item, imageType, imageIndex).ConfigureAwait(false);
  594. return new ValueTuple<string, bool>(enhancedImagePath, treatmentRequiresTransparency);
  595. }
  596. finally
  597. {
  598. ReleaseLock(enhancedImagePath, lockInfo);
  599. }
  600. }
  601. /// <summary>
  602. /// Executes the image enhancers.
  603. /// </summary>
  604. /// <param name="imageEnhancers">The image enhancers.</param>
  605. /// <param name="inputPath">The input path.</param>
  606. /// <param name="outputPath">The output path.</param>
  607. /// <param name="item">The item.</param>
  608. /// <param name="imageType">Type of the image.</param>
  609. /// <param name="imageIndex">Index of the image.</param>
  610. /// <returns>Task{EnhancedImage}.</returns>
  611. private async Task ExecuteImageEnhancers(IEnumerable<IImageEnhancer> imageEnhancers, string inputPath, string outputPath, BaseItem item, ImageType imageType, int imageIndex)
  612. {
  613. // Run the enhancers sequentially in order of priority
  614. foreach (var enhancer in imageEnhancers)
  615. {
  616. await enhancer.EnhanceImageAsync(item, inputPath, outputPath, imageType, imageIndex).ConfigureAwait(false);
  617. // Feed the output into the next enhancer as input
  618. inputPath = outputPath;
  619. }
  620. }
  621. /// <summary>
  622. /// Gets the cache path.
  623. /// </summary>
  624. /// <param name="path">The path.</param>
  625. /// <param name="uniqueName">Name of the unique.</param>
  626. /// <param name="fileExtension">The file extension.</param>
  627. /// <returns>System.String.</returns>
  628. /// <exception cref="ArgumentNullException">
  629. /// path
  630. /// or
  631. /// uniqueName
  632. /// or
  633. /// fileExtension
  634. /// </exception>
  635. public string GetCachePath(string path, string uniqueName, string fileExtension)
  636. {
  637. if (string.IsNullOrEmpty(path))
  638. {
  639. throw new ArgumentNullException(nameof(path));
  640. }
  641. if (string.IsNullOrEmpty(uniqueName))
  642. {
  643. throw new ArgumentNullException(nameof(uniqueName));
  644. }
  645. if (string.IsNullOrEmpty(fileExtension))
  646. {
  647. throw new ArgumentNullException(nameof(fileExtension));
  648. }
  649. var filename = uniqueName.GetMD5() + fileExtension;
  650. return GetCachePath(path, filename);
  651. }
  652. /// <summary>
  653. /// Gets the cache path.
  654. /// </summary>
  655. /// <param name="path">The path.</param>
  656. /// <param name="filename">The filename.</param>
  657. /// <returns>System.String.</returns>
  658. /// <exception cref="ArgumentNullException">
  659. /// path
  660. /// or
  661. /// filename
  662. /// </exception>
  663. public string GetCachePath(string path, string filename)
  664. {
  665. if (string.IsNullOrEmpty(path))
  666. {
  667. throw new ArgumentNullException(nameof(path));
  668. }
  669. if (string.IsNullOrEmpty(filename))
  670. {
  671. throw new ArgumentNullException(nameof(filename));
  672. }
  673. var prefix = filename.Substring(0, 1);
  674. path = Path.Combine(path, prefix);
  675. return Path.Combine(path, filename);
  676. }
  677. public void CreateImageCollage(ImageCollageOptions options)
  678. {
  679. _logger.LogInformation("Creating image collage and saving to {0}", options.OutputPath);
  680. _imageEncoder.CreateImageCollage(options);
  681. _logger.LogInformation("Completed creation of image collage and saved to {0}", options.OutputPath);
  682. }
  683. public IImageEnhancer[] GetSupportedEnhancers(BaseItem item, ImageType imageType)
  684. {
  685. List<IImageEnhancer> list = null;
  686. foreach (var i in ImageEnhancers)
  687. {
  688. try
  689. {
  690. if (i.Supports(item, imageType))
  691. {
  692. if (list == null)
  693. {
  694. list = new List<IImageEnhancer>();
  695. }
  696. list.Add(i);
  697. }
  698. }
  699. catch (Exception ex)
  700. {
  701. _logger.LogError(ex, "Error in image enhancer: {0}", i.GetType().Name);
  702. }
  703. }
  704. return list == null ? Array.Empty<IImageEnhancer>() : list.ToArray();
  705. }
  706. private Dictionary<string, LockInfo> _locks = new Dictionary<string, LockInfo>();
  707. private class LockInfo
  708. {
  709. public SemaphoreSlim Lock = new SemaphoreSlim(1, 1);
  710. public int Count = 1;
  711. }
  712. private LockInfo GetLock(string key)
  713. {
  714. lock (_locks)
  715. {
  716. if (_locks.TryGetValue(key, out var info))
  717. {
  718. info.Count++;
  719. }
  720. else
  721. {
  722. info = new LockInfo();
  723. _locks[key] = info;
  724. }
  725. return info;
  726. }
  727. }
  728. private void ReleaseLock(string key, LockInfo info)
  729. {
  730. info.Lock.Release();
  731. lock (_locks)
  732. {
  733. info.Count--;
  734. if (info.Count <= 0)
  735. {
  736. _locks.Remove(key);
  737. info.Lock.Dispose();
  738. }
  739. }
  740. }
  741. private bool _disposed;
  742. public void Dispose()
  743. {
  744. _disposed = true;
  745. var disposable = _imageEncoder as IDisposable;
  746. if (disposable != null)
  747. {
  748. disposable.Dispose();
  749. }
  750. }
  751. private void CheckDisposed()
  752. {
  753. if (_disposed)
  754. {
  755. throw new ObjectDisposedException(GetType().Name);
  756. }
  757. }
  758. }
  759. }