ImageProcessor.cs 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818
  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 IReadOnlyCollection<string> SupportedInputFormats =>
  77. new HashSet<string>(StringComparer.OrdinalIgnoreCase)
  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 IReadOnlyCollection<ImageFormat> GetSupportedImageOutputFormats()
  122. => _imageEncoder.SupportedOutputFormats;
  123. private static readonly HashSet<string> TransparentImageTypes
  124. = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { ".png", ".webp", ".gif" };
  125. public bool SupportsTransparency(string path)
  126. => TransparentImageTypes.Contains(Path.GetExtension(path));
  127. public async Task<(string path, string mimeType, DateTime dateModified)> ProcessImage(ImageProcessingOptions options)
  128. {
  129. if (options == null)
  130. {
  131. throw new ArgumentNullException(nameof(options));
  132. }
  133. ItemImageInfo originalImage = options.Image;
  134. BaseItem item = options.Item;
  135. if (!originalImage.IsLocalFile)
  136. {
  137. if (item == null)
  138. {
  139. item = _libraryManager().GetItemById(options.ItemId);
  140. }
  141. originalImage = await _libraryManager().ConvertImageToLocal(item, originalImage, options.ImageIndex).ConfigureAwait(false);
  142. }
  143. string originalImagePath = originalImage.Path;
  144. DateTime dateModified = originalImage.DateModified;
  145. ImageDimensions? originalImageSize = null;
  146. if (originalImage.Width > 0 && originalImage.Height > 0)
  147. {
  148. originalImageSize = new ImageDimensions(originalImage.Width, originalImage.Height);
  149. }
  150. if (!_imageEncoder.SupportsImageEncoding)
  151. {
  152. return (originalImagePath, MimeTypes.GetMimeType(originalImagePath), dateModified);
  153. }
  154. var supportedImageInfo = await GetSupportedImage(originalImagePath, dateModified).ConfigureAwait(false);
  155. originalImagePath = supportedImageInfo.path;
  156. if (!File.Exists(originalImagePath))
  157. {
  158. return (originalImagePath, MimeTypes.GetMimeType(originalImagePath), dateModified);
  159. }
  160. dateModified = supportedImageInfo.dateModified;
  161. bool requiresTransparency = TransparentImageTypes.Contains(Path.GetExtension(originalImagePath));
  162. if (options.Enhancers.Length > 0)
  163. {
  164. if (item == null)
  165. {
  166. item = _libraryManager().GetItemById(options.ItemId);
  167. }
  168. var tuple = await GetEnhancedImage(new ItemImageInfo
  169. {
  170. DateModified = dateModified,
  171. Type = originalImage.Type,
  172. Path = originalImagePath
  173. }, requiresTransparency, item, options.ImageIndex, options.Enhancers, CancellationToken.None).ConfigureAwait(false);
  174. originalImagePath = tuple.path;
  175. dateModified = tuple.dateModified;
  176. requiresTransparency = tuple.transparent;
  177. // TODO: Get this info
  178. originalImageSize = null;
  179. }
  180. bool autoOrient = false;
  181. ImageOrientation? orientation = null;
  182. if (item is Photo photo)
  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 (originalImagePath, MimeTypes.GetMimeType(originalImagePath), dateModified);
  203. }
  204. ImageDimensions newSize = ImageHelper.GetNewImageSize(options, null);
  205. int quality = options.Quality;
  206. ImageFormat outputFormat = GetOutputFormat(options.SupportedOutputFormats, requiresTransparency);
  207. string cacheFilePath = GetCacheFilePath(originalImagePath, newSize, quality, dateModified, outputFormat, options.AddPlayedIndicator, options.PercentPlayed, options.UnplayedCount, options.Blur, options.BackgroundColor, options.ForegroundLayer);
  208. CheckDisposed();
  209. LockInfo lockInfo = GetLock(cacheFilePath);
  210. await lockInfo.Lock.WaitAsync().ConfigureAwait(false);
  211. try
  212. {
  213. if (!File.Exists(cacheFilePath))
  214. {
  215. if (options.CropWhiteSpace && !SupportsTransparency(originalImagePath))
  216. {
  217. options.CropWhiteSpace = false;
  218. }
  219. string resultPath = _imageEncoder.EncodeImage(originalImagePath, dateModified, cacheFilePath, autoOrient, orientation, quality, options, outputFormat);
  220. if (string.Equals(resultPath, originalImagePath, StringComparison.OrdinalIgnoreCase))
  221. {
  222. return (originalImagePath, MimeTypes.GetMimeType(originalImagePath), dateModified);
  223. }
  224. }
  225. return (cacheFilePath, GetMimeType(outputFormat, cacheFilePath), _fileSystem.GetLastWriteTimeUtc(cacheFilePath));
  226. }
  227. catch (Exception ex)
  228. {
  229. // If it fails for whatever reason, return the original image
  230. _logger.LogError(ex, "Error encoding image");
  231. return (originalImagePath, MimeTypes.GetMimeType(originalImagePath), dateModified);
  232. }
  233. finally
  234. {
  235. ReleaseLock(cacheFilePath, lockInfo);
  236. }
  237. }
  238. private ImageFormat GetOutputFormat(ImageFormat[] clientSupportedFormats, bool requiresTransparency)
  239. {
  240. var serverFormats = GetSupportedImageOutputFormats();
  241. // Client doesn't care about format, so start with webp if supported
  242. if (serverFormats.Contains(ImageFormat.Webp) && clientSupportedFormats.Contains(ImageFormat.Webp))
  243. {
  244. return ImageFormat.Webp;
  245. }
  246. // If transparency is needed and webp isn't supported, than png is the only option
  247. if (requiresTransparency && clientSupportedFormats.Contains(ImageFormat.Png))
  248. {
  249. return ImageFormat.Png;
  250. }
  251. foreach (var format in clientSupportedFormats)
  252. {
  253. if (serverFormats.Contains(format))
  254. {
  255. return format;
  256. }
  257. }
  258. // We should never actually get here
  259. return ImageFormat.Jpg;
  260. }
  261. private string GetMimeType(ImageFormat format, string path)
  262. {
  263. switch(format)
  264. {
  265. case ImageFormat.Bmp: return MimeTypes.GetMimeType("i.bmp");
  266. case ImageFormat.Gif: return MimeTypes.GetMimeType("i.gif");
  267. case ImageFormat.Jpg: return MimeTypes.GetMimeType("i.jpg");
  268. case ImageFormat.Png: return MimeTypes.GetMimeType("i.png");
  269. case ImageFormat.Webp: return MimeTypes.GetMimeType("i.webp");
  270. default: return MimeTypes.GetMimeType(path);
  271. }
  272. }
  273. /// <summary>
  274. /// Increment this when there's a change requiring caches to be invalidated
  275. /// </summary>
  276. private const string Version = "3";
  277. /// <summary>
  278. /// Gets the cache file path based on a set of parameters
  279. /// </summary>
  280. 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)
  281. {
  282. var filename = originalPath
  283. + "width=" + outputSize.Width
  284. + "height=" + outputSize.Height
  285. + "quality=" + quality
  286. + "datemodified=" + dateModified.Ticks
  287. + "f=" + format;
  288. if (addPlayedIndicator)
  289. {
  290. filename += "pl=true";
  291. }
  292. if (percentPlayed > 0)
  293. {
  294. filename += "p=" + percentPlayed;
  295. }
  296. if (unwatchedCount.HasValue)
  297. {
  298. filename += "p=" + unwatchedCount.Value;
  299. }
  300. if (blur.HasValue)
  301. {
  302. filename += "blur=" + blur.Value;
  303. }
  304. if (!string.IsNullOrEmpty(backgroundColor))
  305. {
  306. filename += "b=" + backgroundColor;
  307. }
  308. if (!string.IsNullOrEmpty(foregroundLayer))
  309. {
  310. filename += "fl=" + foregroundLayer;
  311. }
  312. filename += "v=" + Version;
  313. return GetCachePath(ResizedImageCachePath, filename, "." + format.ToString().ToLowerInvariant());
  314. }
  315. public ImageDimensions GetImageDimensions(BaseItem item, ItemImageInfo info)
  316. => GetImageDimensions(item, info, true);
  317. public ImageDimensions GetImageDimensions(BaseItem item, ItemImageInfo info, bool updateItem)
  318. {
  319. int width = info.Width;
  320. int height = info.Height;
  321. if (height > 0 && width > 0)
  322. {
  323. return new ImageDimensions(width, height);
  324. }
  325. string path = info.Path;
  326. _logger.LogInformation("Getting image size for item {ItemType} {Path}", item.GetType().Name, path);
  327. ImageDimensions size = GetImageDimensions(path);
  328. info.Width = size.Width;
  329. info.Height = size.Height;
  330. if (updateItem)
  331. {
  332. _libraryManager().UpdateImages(item);
  333. }
  334. return size;
  335. }
  336. /// <summary>
  337. /// Gets the size of the image.
  338. /// </summary>
  339. public ImageDimensions GetImageDimensions(string path)
  340. => _imageEncoder.GetImageSize(path);
  341. /// <summary>
  342. /// Gets the image cache tag.
  343. /// </summary>
  344. /// <param name="item">The item.</param>
  345. /// <param name="image">The image.</param>
  346. /// <returns>Guid.</returns>
  347. /// <exception cref="ArgumentNullException">item</exception>
  348. public string GetImageCacheTag(BaseItem item, ItemImageInfo image)
  349. {
  350. var supportedEnhancers = GetSupportedEnhancers(item, image.Type);
  351. return GetImageCacheTag(item, image, supportedEnhancers);
  352. }
  353. public string GetImageCacheTag(BaseItem item, ChapterInfo chapter)
  354. {
  355. try
  356. {
  357. return GetImageCacheTag(item, new ItemImageInfo
  358. {
  359. Path = chapter.ImagePath,
  360. Type = ImageType.Chapter,
  361. DateModified = chapter.ImageDateModified
  362. });
  363. }
  364. catch
  365. {
  366. return null;
  367. }
  368. }
  369. /// <summary>
  370. /// Gets the image cache tag.
  371. /// </summary>
  372. /// <param name="item">The item.</param>
  373. /// <param name="image">The image.</param>
  374. /// <param name="imageEnhancers">The image enhancers.</param>
  375. /// <returns>Guid.</returns>
  376. /// <exception cref="ArgumentNullException">item</exception>
  377. public string GetImageCacheTag(BaseItem item, ItemImageInfo image, IImageEnhancer[] imageEnhancers)
  378. {
  379. string originalImagePath = image.Path;
  380. DateTime dateModified = image.DateModified;
  381. ImageType imageType = image.Type;
  382. // Optimization
  383. if (imageEnhancers.Length == 0)
  384. {
  385. return (originalImagePath + dateModified.Ticks).GetMD5().ToString("N");
  386. }
  387. // Cache name is created with supported enhancers combined with the last config change so we pick up new config changes
  388. var cacheKeys = imageEnhancers.Select(i => i.GetConfigurationCacheKey(item, imageType)).ToList();
  389. cacheKeys.Add(originalImagePath + dateModified.Ticks);
  390. return string.Join("|", cacheKeys).GetMD5().ToString("N");
  391. }
  392. private async Task<(string path, DateTime dateModified)> GetSupportedImage(string originalImagePath, DateTime dateModified)
  393. {
  394. var inputFormat = Path.GetExtension(originalImagePath)
  395. .TrimStart('.')
  396. .Replace("jpeg", "jpg", StringComparison.OrdinalIgnoreCase);
  397. // These are just jpg files renamed as tbn
  398. if (string.Equals(inputFormat, "tbn", StringComparison.OrdinalIgnoreCase))
  399. {
  400. return (originalImagePath, dateModified);
  401. }
  402. if (!_imageEncoder.SupportedInputFormats.Contains(inputFormat))
  403. {
  404. try
  405. {
  406. string filename = (originalImagePath + dateModified.Ticks.ToString(UsCulture)).GetMD5().ToString("N");
  407. string cacheExtension = _mediaEncoder().SupportsEncoder("libwebp") ? ".webp" : ".png";
  408. var outputPath = Path.Combine(_appPaths.ImageCachePath, "converted-images", filename + cacheExtension);
  409. var file = _fileSystem.GetFileInfo(outputPath);
  410. if (!file.Exists)
  411. {
  412. await _mediaEncoder().ConvertImage(originalImagePath, outputPath).ConfigureAwait(false);
  413. dateModified = _fileSystem.GetLastWriteTimeUtc(outputPath);
  414. }
  415. else
  416. {
  417. dateModified = file.LastWriteTimeUtc;
  418. }
  419. originalImagePath = outputPath;
  420. }
  421. catch (Exception ex)
  422. {
  423. _logger.LogError(ex, "Image conversion failed for {Path}", originalImagePath);
  424. }
  425. }
  426. return (originalImagePath, dateModified);
  427. }
  428. /// <summary>
  429. /// Gets the enhanced image.
  430. /// </summary>
  431. /// <param name="item">The item.</param>
  432. /// <param name="imageType">Type of the image.</param>
  433. /// <param name="imageIndex">Index of the image.</param>
  434. /// <returns>Task{System.String}.</returns>
  435. public async Task<string> GetEnhancedImage(BaseItem item, ImageType imageType, int imageIndex)
  436. {
  437. var enhancers = GetSupportedEnhancers(item, imageType);
  438. ItemImageInfo imageInfo = item.GetImageInfo(imageType, imageIndex);
  439. bool inputImageSupportsTransparency = SupportsTransparency(imageInfo.Path);
  440. var result = await GetEnhancedImage(imageInfo, inputImageSupportsTransparency, item, imageIndex, enhancers, CancellationToken.None);
  441. return result.path;
  442. }
  443. private async Task<(string path, DateTime dateModified, bool transparent)> GetEnhancedImage(
  444. ItemImageInfo image,
  445. bool inputImageSupportsTransparency,
  446. BaseItem item,
  447. int imageIndex,
  448. IImageEnhancer[] enhancers,
  449. CancellationToken cancellationToken)
  450. {
  451. var originalImagePath = image.Path;
  452. var dateModified = image.DateModified;
  453. var imageType = image.Type;
  454. try
  455. {
  456. var cacheGuid = GetImageCacheTag(item, image, enhancers);
  457. // Enhance if we have enhancers
  458. var enhancedImageInfo = await GetEnhancedImageInternal(originalImagePath, item, imageType, imageIndex, enhancers, cacheGuid, cancellationToken).ConfigureAwait(false);
  459. string enhancedImagePath = enhancedImageInfo.path;
  460. // If the path changed update dateModified
  461. if (!string.Equals(enhancedImagePath, originalImagePath, StringComparison.OrdinalIgnoreCase))
  462. {
  463. var treatmentRequiresTransparency = enhancedImageInfo.transparent;
  464. return (enhancedImagePath, _fileSystem.GetLastWriteTimeUtc(enhancedImagePath), treatmentRequiresTransparency);
  465. }
  466. }
  467. catch (Exception ex)
  468. {
  469. _logger.LogError(ex, "Error enhancing image");
  470. }
  471. return (originalImagePath, dateModified, inputImageSupportsTransparency);
  472. }
  473. /// <summary>
  474. /// Gets the enhanced image internal.
  475. /// </summary>
  476. /// <param name="originalImagePath">The original image path.</param>
  477. /// <param name="item">The item.</param>
  478. /// <param name="imageType">Type of the image.</param>
  479. /// <param name="imageIndex">Index of the image.</param>
  480. /// <param name="supportedEnhancers">The supported enhancers.</param>
  481. /// <param name="cacheGuid">The cache unique identifier.</param>
  482. /// <returns>Task&lt;System.String&gt;.</returns>
  483. /// <exception cref="ArgumentNullException">
  484. /// originalImagePath
  485. /// or
  486. /// item
  487. /// </exception>
  488. private async Task<(string path, bool transparent)> GetEnhancedImageInternal(
  489. string originalImagePath,
  490. BaseItem item,
  491. ImageType imageType,
  492. int imageIndex,
  493. IImageEnhancer[] supportedEnhancers,
  494. string cacheGuid,
  495. CancellationToken cancellationToken)
  496. {
  497. if (string.IsNullOrEmpty(originalImagePath))
  498. {
  499. throw new ArgumentNullException(nameof(originalImagePath));
  500. }
  501. if (item == null)
  502. {
  503. throw new ArgumentNullException(nameof(item));
  504. }
  505. var treatmentRequiresTransparency = false;
  506. foreach (var enhancer in supportedEnhancers)
  507. {
  508. if (!treatmentRequiresTransparency)
  509. {
  510. treatmentRequiresTransparency = enhancer.GetEnhancedImageInfo(item, originalImagePath, imageType, imageIndex).RequiresTransparency;
  511. }
  512. }
  513. // All enhanced images are saved as png to allow transparency
  514. string cacheExtension = _imageEncoder.SupportedOutputFormats.Contains(ImageFormat.Webp) ?
  515. ".webp" :
  516. (treatmentRequiresTransparency ? ".png" : ".jpg");
  517. string enhancedImagePath = GetCachePath(EnhancedImageCachePath, cacheGuid + cacheExtension);
  518. LockInfo lockInfo = GetLock(enhancedImagePath);
  519. await lockInfo.Lock.WaitAsync(cancellationToken).ConfigureAwait(false);
  520. try
  521. {
  522. // Check again in case of contention
  523. if (File.Exists(enhancedImagePath))
  524. {
  525. return (enhancedImagePath, treatmentRequiresTransparency);
  526. }
  527. Directory.CreateDirectory(Path.GetDirectoryName(enhancedImagePath));
  528. await ExecuteImageEnhancers(supportedEnhancers, originalImagePath, enhancedImagePath, item, imageType, imageIndex).ConfigureAwait(false);
  529. return (enhancedImagePath, treatmentRequiresTransparency);
  530. }
  531. finally
  532. {
  533. ReleaseLock(enhancedImagePath, lockInfo);
  534. }
  535. }
  536. /// <summary>
  537. /// Executes the image enhancers.
  538. /// </summary>
  539. /// <param name="imageEnhancers">The image enhancers.</param>
  540. /// <param name="inputPath">The input path.</param>
  541. /// <param name="outputPath">The output path.</param>
  542. /// <param name="item">The item.</param>
  543. /// <param name="imageType">Type of the image.</param>
  544. /// <param name="imageIndex">Index of the image.</param>
  545. /// <returns>Task{EnhancedImage}.</returns>
  546. private static async Task ExecuteImageEnhancers(IEnumerable<IImageEnhancer> imageEnhancers, string inputPath, string outputPath, BaseItem item, ImageType imageType, int imageIndex)
  547. {
  548. // Run the enhancers sequentially in order of priority
  549. foreach (var enhancer in imageEnhancers)
  550. {
  551. await enhancer.EnhanceImageAsync(item, inputPath, outputPath, imageType, imageIndex).ConfigureAwait(false);
  552. // Feed the output into the next enhancer as input
  553. inputPath = outputPath;
  554. }
  555. }
  556. /// <summary>
  557. /// Gets the cache path.
  558. /// </summary>
  559. /// <param name="path">The path.</param>
  560. /// <param name="uniqueName">Name of the unique.</param>
  561. /// <param name="fileExtension">The file extension.</param>
  562. /// <returns>System.String.</returns>
  563. /// <exception cref="ArgumentNullException">
  564. /// path
  565. /// or
  566. /// uniqueName
  567. /// or
  568. /// fileExtension
  569. /// </exception>
  570. public string GetCachePath(string path, string uniqueName, string fileExtension)
  571. {
  572. if (string.IsNullOrEmpty(path))
  573. {
  574. throw new ArgumentNullException(nameof(path));
  575. }
  576. if (string.IsNullOrEmpty(uniqueName))
  577. {
  578. throw new ArgumentNullException(nameof(uniqueName));
  579. }
  580. if (string.IsNullOrEmpty(fileExtension))
  581. {
  582. throw new ArgumentNullException(nameof(fileExtension));
  583. }
  584. var filename = uniqueName.GetMD5() + fileExtension;
  585. return GetCachePath(path, filename);
  586. }
  587. /// <summary>
  588. /// Gets the cache path.
  589. /// </summary>
  590. /// <param name="path">The path.</param>
  591. /// <param name="filename">The filename.</param>
  592. /// <returns>System.String.</returns>
  593. /// <exception cref="ArgumentNullException">
  594. /// path
  595. /// or
  596. /// filename
  597. /// </exception>
  598. public string GetCachePath(string path, string filename)
  599. {
  600. if (string.IsNullOrEmpty(path))
  601. {
  602. throw new ArgumentNullException(nameof(path));
  603. }
  604. if (string.IsNullOrEmpty(filename))
  605. {
  606. throw new ArgumentNullException(nameof(filename));
  607. }
  608. var prefix = filename.Substring(0, 1);
  609. return Path.Combine(path, prefix, filename);
  610. }
  611. public void CreateImageCollage(ImageCollageOptions options)
  612. {
  613. _logger.LogInformation("Creating image collage and saving to {Path}", options.OutputPath);
  614. _imageEncoder.CreateImageCollage(options);
  615. _logger.LogInformation("Completed creation of image collage and saved to {Path}", options.OutputPath);
  616. }
  617. public IImageEnhancer[] GetSupportedEnhancers(BaseItem item, ImageType imageType)
  618. {
  619. List<IImageEnhancer> list = null;
  620. foreach (var i in ImageEnhancers)
  621. {
  622. try
  623. {
  624. if (i.Supports(item, imageType))
  625. {
  626. if (list == null)
  627. {
  628. list = new List<IImageEnhancer>();
  629. }
  630. list.Add(i);
  631. }
  632. }
  633. catch (Exception ex)
  634. {
  635. _logger.LogError(ex, "Error in image enhancer: {0}", i.GetType().Name);
  636. }
  637. }
  638. return list == null ? Array.Empty<IImageEnhancer>() : list.ToArray();
  639. }
  640. private Dictionary<string, LockInfo> _locks = new Dictionary<string, LockInfo>();
  641. private class LockInfo
  642. {
  643. public SemaphoreSlim Lock = new SemaphoreSlim(1, 1);
  644. public int Count = 1;
  645. }
  646. private LockInfo GetLock(string key)
  647. {
  648. lock (_locks)
  649. {
  650. if (_locks.TryGetValue(key, out LockInfo info))
  651. {
  652. info.Count++;
  653. }
  654. else
  655. {
  656. info = new LockInfo();
  657. _locks[key] = info;
  658. }
  659. return info;
  660. }
  661. }
  662. private void ReleaseLock(string key, LockInfo info)
  663. {
  664. info.Lock.Release();
  665. lock (_locks)
  666. {
  667. info.Count--;
  668. if (info.Count <= 0)
  669. {
  670. _locks.Remove(key);
  671. info.Lock.Dispose();
  672. }
  673. }
  674. }
  675. private bool _disposed;
  676. public void Dispose()
  677. {
  678. _disposed = true;
  679. var disposable = _imageEncoder as IDisposable;
  680. if (disposable != null)
  681. {
  682. disposable.Dispose();
  683. }
  684. }
  685. private void CheckDisposed()
  686. {
  687. if (_disposed)
  688. {
  689. throw new ObjectDisposedException(GetType().Name);
  690. }
  691. }
  692. }
  693. }