ImageProcessor.cs 29 KB

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