ImageProcessor.cs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782
  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.IO;
  18. using MediaBrowser.Model.Net;
  19. using Microsoft.Extensions.Logging;
  20. namespace Emby.Drawing
  21. {
  22. /// <summary>
  23. /// Class ImageProcessor.
  24. /// </summary>
  25. public class ImageProcessor : IImageProcessor, IDisposable
  26. {
  27. // Increment this when there's a change requiring caches to be invalidated
  28. private const string Version = "3";
  29. private static readonly HashSet<string> _transparentImageTypes
  30. = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { ".png", ".webp", ".gif" };
  31. /// <summary>
  32. /// The _logger
  33. /// </summary>
  34. private readonly ILogger _logger;
  35. private readonly IFileSystem _fileSystem;
  36. private readonly IServerApplicationPaths _appPaths;
  37. private IImageEncoder _imageEncoder;
  38. private readonly Func<ILibraryManager> _libraryManager;
  39. private readonly Func<IMediaEncoder> _mediaEncoder;
  40. private readonly Dictionary<string, LockInfo> _locks = new Dictionary<string, LockInfo>();
  41. private bool _disposed = false;
  42. /// <summary>
  43. ///
  44. /// </summary>
  45. /// <param name="logger"></param>
  46. /// <param name="appPaths"></param>
  47. /// <param name="fileSystem"></param>
  48. /// <param name="imageEncoder"></param>
  49. /// <param name="libraryManager"></param>
  50. /// <param name="mediaEncoder"></param>
  51. public ImageProcessor(
  52. ILogger<ImageProcessor> logger,
  53. IServerApplicationPaths appPaths,
  54. IFileSystem fileSystem,
  55. IImageEncoder imageEncoder,
  56. Func<ILibraryManager> libraryManager,
  57. Func<IMediaEncoder> mediaEncoder)
  58. {
  59. _logger = logger;
  60. _fileSystem = fileSystem;
  61. _imageEncoder = imageEncoder;
  62. _libraryManager = libraryManager;
  63. _mediaEncoder = mediaEncoder;
  64. _appPaths = appPaths;
  65. ImageEnhancers = Array.Empty<IImageEnhancer>();
  66. ImageHelper.ImageProcessor = this;
  67. }
  68. private string ResizedImageCachePath => Path.Combine(_appPaths.ImageCachePath, "resized-images");
  69. private string EnhancedImageCachePath => Path.Combine(_appPaths.ImageCachePath, "enhanced-images");
  70. /// <inheritdoc />
  71. public IReadOnlyCollection<string> SupportedInputFormats =>
  72. new HashSet<string>(StringComparer.OrdinalIgnoreCase)
  73. {
  74. "tiff",
  75. "tif",
  76. "jpeg",
  77. "jpg",
  78. "png",
  79. "aiff",
  80. "cr2",
  81. "crw",
  82. // Remove until supported
  83. //"nef",
  84. "orf",
  85. "pef",
  86. "arw",
  87. "webp",
  88. "gif",
  89. "bmp",
  90. "erf",
  91. "raf",
  92. "rw2",
  93. "nrw",
  94. "dng",
  95. "ico",
  96. "astc",
  97. "ktx",
  98. "pkm",
  99. "wbmp"
  100. };
  101. /// <inheritdoc />
  102. public IReadOnlyCollection<IImageEnhancer> ImageEnhancers { get; set; }
  103. /// <inheritdoc />
  104. public bool SupportsImageCollageCreation => _imageEncoder.SupportsImageCollageCreation;
  105. /// <inheritdoc />
  106. public IImageEncoder ImageEncoder
  107. {
  108. get => _imageEncoder;
  109. set => _imageEncoder = value ?? throw new ArgumentNullException(nameof(value));
  110. }
  111. /// <inheritdoc />
  112. public async Task ProcessImage(ImageProcessingOptions options, Stream toStream)
  113. {
  114. var file = await ProcessImage(options).ConfigureAwait(false);
  115. using (var fileStream = new FileStream(file.Item1, FileMode.Open, FileAccess.Read, FileShare.Read, IODefaults.FileStreamBufferSize, true))
  116. {
  117. await fileStream.CopyToAsync(toStream).ConfigureAwait(false);
  118. }
  119. }
  120. /// <inheritdoc />
  121. public IReadOnlyCollection<ImageFormat> GetSupportedImageOutputFormats()
  122. => _imageEncoder.SupportedOutputFormats;
  123. /// <inheritdoc />
  124. public bool SupportsTransparency(string path)
  125. => _transparentImageTypes.Contains(Path.GetExtension(path));
  126. /// <inheritdoc />
  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.Count > 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(IReadOnlyCollection<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. /// Gets the cache file path based on a set of parameters
  275. /// </summary>
  276. 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)
  277. {
  278. var filename = originalPath
  279. + "width=" + outputSize.Width
  280. + "height=" + outputSize.Height
  281. + "quality=" + quality
  282. + "datemodified=" + dateModified.Ticks
  283. + "f=" + format;
  284. if (addPlayedIndicator)
  285. {
  286. filename += "pl=true";
  287. }
  288. if (percentPlayed > 0)
  289. {
  290. filename += "p=" + percentPlayed;
  291. }
  292. if (unwatchedCount.HasValue)
  293. {
  294. filename += "p=" + unwatchedCount.Value;
  295. }
  296. if (blur.HasValue)
  297. {
  298. filename += "blur=" + blur.Value;
  299. }
  300. if (!string.IsNullOrEmpty(backgroundColor))
  301. {
  302. filename += "b=" + backgroundColor;
  303. }
  304. if (!string.IsNullOrEmpty(foregroundLayer))
  305. {
  306. filename += "fl=" + foregroundLayer;
  307. }
  308. filename += "v=" + Version;
  309. return GetCachePath(ResizedImageCachePath, filename, "." + format.ToString().ToLowerInvariant());
  310. }
  311. /// <inheritdoc />
  312. public ImageDimensions GetImageDimensions(BaseItem item, ItemImageInfo info)
  313. => GetImageDimensions(item, info, true);
  314. /// <inheritdoc />
  315. public ImageDimensions GetImageDimensions(BaseItem item, ItemImageInfo info, bool updateItem)
  316. {
  317. int width = info.Width;
  318. int height = info.Height;
  319. if (height > 0 && width > 0)
  320. {
  321. return new ImageDimensions(width, height);
  322. }
  323. string path = info.Path;
  324. _logger.LogInformation("Getting image size for item {ItemType} {Path}", item.GetType().Name, path);
  325. ImageDimensions size = GetImageDimensions(path);
  326. info.Width = size.Width;
  327. info.Height = size.Height;
  328. if (updateItem)
  329. {
  330. _libraryManager().UpdateImages(item);
  331. }
  332. return size;
  333. }
  334. /// <inheritdoc />
  335. public ImageDimensions GetImageDimensions(string path)
  336. => _imageEncoder.GetImageSize(path);
  337. /// <inheritdoc />
  338. public string GetImageCacheTag(BaseItem item, ItemImageInfo image)
  339. {
  340. var supportedEnhancers = GetSupportedEnhancers(item, image.Type).ToArray();
  341. return GetImageCacheTag(item, image, supportedEnhancers);
  342. }
  343. /// <inheritdoc />
  344. public string GetImageCacheTag(BaseItem item, ChapterInfo chapter)
  345. {
  346. try
  347. {
  348. return GetImageCacheTag(item, new ItemImageInfo
  349. {
  350. Path = chapter.ImagePath,
  351. Type = ImageType.Chapter,
  352. DateModified = chapter.ImageDateModified
  353. });
  354. }
  355. catch
  356. {
  357. return null;
  358. }
  359. }
  360. /// <inheritdoc />
  361. public string GetImageCacheTag(BaseItem item, ItemImageInfo image, IReadOnlyCollection<IImageEnhancer> imageEnhancers)
  362. {
  363. string originalImagePath = image.Path;
  364. DateTime dateModified = image.DateModified;
  365. ImageType imageType = image.Type;
  366. // Optimization
  367. if (imageEnhancers.Count == 0)
  368. {
  369. return (originalImagePath + dateModified.Ticks).GetMD5().ToString("N", CultureInfo.InvariantCulture);
  370. }
  371. // Cache name is created with supported enhancers combined with the last config change so we pick up new config changes
  372. var cacheKeys = imageEnhancers.Select(i => i.GetConfigurationCacheKey(item, imageType)).ToList();
  373. cacheKeys.Add(originalImagePath + dateModified.Ticks);
  374. return string.Join("|", cacheKeys).GetMD5().ToString("N", CultureInfo.InvariantCulture);
  375. }
  376. private async Task<(string path, DateTime dateModified)> GetSupportedImage(string originalImagePath, DateTime dateModified)
  377. {
  378. var inputFormat = Path.GetExtension(originalImagePath)
  379. .TrimStart('.')
  380. .Replace("jpeg", "jpg", StringComparison.OrdinalIgnoreCase);
  381. // These are just jpg files renamed as tbn
  382. if (string.Equals(inputFormat, "tbn", StringComparison.OrdinalIgnoreCase))
  383. {
  384. return (originalImagePath, dateModified);
  385. }
  386. if (!_imageEncoder.SupportedInputFormats.Contains(inputFormat))
  387. {
  388. try
  389. {
  390. string filename = (originalImagePath + dateModified.Ticks.ToString(CultureInfo.InvariantCulture)).GetMD5().ToString("N", CultureInfo.InvariantCulture);
  391. string cacheExtension = _mediaEncoder().SupportsEncoder("libwebp") ? ".webp" : ".png";
  392. var outputPath = Path.Combine(_appPaths.ImageCachePath, "converted-images", filename + cacheExtension);
  393. var file = _fileSystem.GetFileInfo(outputPath);
  394. if (!file.Exists)
  395. {
  396. await _mediaEncoder().ConvertImage(originalImagePath, outputPath).ConfigureAwait(false);
  397. dateModified = _fileSystem.GetLastWriteTimeUtc(outputPath);
  398. }
  399. else
  400. {
  401. dateModified = file.LastWriteTimeUtc;
  402. }
  403. originalImagePath = outputPath;
  404. }
  405. catch (Exception ex)
  406. {
  407. _logger.LogError(ex, "Image conversion failed for {Path}", originalImagePath);
  408. }
  409. }
  410. return (originalImagePath, dateModified);
  411. }
  412. /// <inheritdoc />
  413. public async Task<string> GetEnhancedImage(BaseItem item, ImageType imageType, int imageIndex)
  414. {
  415. var enhancers = GetSupportedEnhancers(item, imageType).ToArray();
  416. ItemImageInfo imageInfo = item.GetImageInfo(imageType, imageIndex);
  417. bool inputImageSupportsTransparency = SupportsTransparency(imageInfo.Path);
  418. var result = await GetEnhancedImage(imageInfo, inputImageSupportsTransparency, item, imageIndex, enhancers, CancellationToken.None);
  419. return result.path;
  420. }
  421. private async Task<(string path, DateTime dateModified, bool transparent)> GetEnhancedImage(
  422. ItemImageInfo image,
  423. bool inputImageSupportsTransparency,
  424. BaseItem item,
  425. int imageIndex,
  426. IReadOnlyCollection<IImageEnhancer> enhancers,
  427. CancellationToken cancellationToken)
  428. {
  429. var originalImagePath = image.Path;
  430. var dateModified = image.DateModified;
  431. var imageType = image.Type;
  432. try
  433. {
  434. var cacheGuid = GetImageCacheTag(item, image, enhancers);
  435. // Enhance if we have enhancers
  436. var enhancedImageInfo = await GetEnhancedImageInternal(originalImagePath, item, imageType, imageIndex, enhancers, cacheGuid, cancellationToken).ConfigureAwait(false);
  437. string enhancedImagePath = enhancedImageInfo.path;
  438. // If the path changed update dateModified
  439. if (!string.Equals(enhancedImagePath, originalImagePath, StringComparison.OrdinalIgnoreCase))
  440. {
  441. var treatmentRequiresTransparency = enhancedImageInfo.transparent;
  442. return (enhancedImagePath, _fileSystem.GetLastWriteTimeUtc(enhancedImagePath), treatmentRequiresTransparency);
  443. }
  444. }
  445. catch (Exception ex)
  446. {
  447. _logger.LogError(ex, "Error enhancing image");
  448. }
  449. return (originalImagePath, dateModified, inputImageSupportsTransparency);
  450. }
  451. /// <summary>
  452. /// Gets the enhanced image internal.
  453. /// </summary>
  454. /// <param name="originalImagePath">The original image path.</param>
  455. /// <param name="item">The item.</param>
  456. /// <param name="imageType">Type of the image.</param>
  457. /// <param name="imageIndex">Index of the image.</param>
  458. /// <param name="supportedEnhancers">The supported enhancers.</param>
  459. /// <param name="cacheGuid">The cache unique identifier.</param>
  460. /// <param name="cancellationToken">The cancellation token.</param>
  461. /// <returns>Task&lt;System.String&gt;.</returns>
  462. /// <exception cref="ArgumentNullException">
  463. /// originalImagePath
  464. /// or
  465. /// item
  466. /// </exception>
  467. private async Task<(string path, bool transparent)> GetEnhancedImageInternal(
  468. string originalImagePath,
  469. BaseItem item,
  470. ImageType imageType,
  471. int imageIndex,
  472. IReadOnlyCollection<IImageEnhancer> supportedEnhancers,
  473. string cacheGuid,
  474. CancellationToken cancellationToken = default)
  475. {
  476. if (string.IsNullOrEmpty(originalImagePath))
  477. {
  478. throw new ArgumentNullException(nameof(originalImagePath));
  479. }
  480. if (item == null)
  481. {
  482. throw new ArgumentNullException(nameof(item));
  483. }
  484. var treatmentRequiresTransparency = false;
  485. foreach (var enhancer in supportedEnhancers)
  486. {
  487. if (!treatmentRequiresTransparency)
  488. {
  489. treatmentRequiresTransparency = enhancer.GetEnhancedImageInfo(item, originalImagePath, imageType, imageIndex).RequiresTransparency;
  490. }
  491. }
  492. // All enhanced images are saved as png to allow transparency
  493. string cacheExtension = _imageEncoder.SupportedOutputFormats.Contains(ImageFormat.Webp) ?
  494. ".webp" :
  495. (treatmentRequiresTransparency ? ".png" : ".jpg");
  496. string enhancedImagePath = GetCachePath(EnhancedImageCachePath, cacheGuid + cacheExtension);
  497. LockInfo lockInfo = GetLock(enhancedImagePath);
  498. await lockInfo.Lock.WaitAsync(cancellationToken).ConfigureAwait(false);
  499. try
  500. {
  501. // Check again in case of contention
  502. if (File.Exists(enhancedImagePath))
  503. {
  504. return (enhancedImagePath, treatmentRequiresTransparency);
  505. }
  506. Directory.CreateDirectory(Path.GetDirectoryName(enhancedImagePath));
  507. await ExecuteImageEnhancers(supportedEnhancers, originalImagePath, enhancedImagePath, item, imageType, imageIndex).ConfigureAwait(false);
  508. return (enhancedImagePath, treatmentRequiresTransparency);
  509. }
  510. finally
  511. {
  512. ReleaseLock(enhancedImagePath, lockInfo);
  513. }
  514. }
  515. /// <summary>
  516. /// Executes the image enhancers.
  517. /// </summary>
  518. /// <param name="imageEnhancers">The image enhancers.</param>
  519. /// <param name="inputPath">The input path.</param>
  520. /// <param name="outputPath">The output path.</param>
  521. /// <param name="item">The item.</param>
  522. /// <param name="imageType">Type of the image.</param>
  523. /// <param name="imageIndex">Index of the image.</param>
  524. /// <returns>Task{EnhancedImage}.</returns>
  525. private static async Task ExecuteImageEnhancers(IEnumerable<IImageEnhancer> imageEnhancers, string inputPath, string outputPath, BaseItem item, ImageType imageType, int imageIndex)
  526. {
  527. // Run the enhancers sequentially in order of priority
  528. foreach (var enhancer in imageEnhancers)
  529. {
  530. await enhancer.EnhanceImageAsync(item, inputPath, outputPath, imageType, imageIndex).ConfigureAwait(false);
  531. // Feed the output into the next enhancer as input
  532. inputPath = outputPath;
  533. }
  534. }
  535. /// <summary>
  536. /// Gets the cache path.
  537. /// </summary>
  538. /// <param name="path">The path.</param>
  539. /// <param name="uniqueName">Name of the unique.</param>
  540. /// <param name="fileExtension">The file extension.</param>
  541. /// <returns>System.String.</returns>
  542. /// <exception cref="ArgumentNullException">
  543. /// path
  544. /// or
  545. /// uniqueName
  546. /// or
  547. /// fileExtension
  548. /// </exception>
  549. public string GetCachePath(string path, string uniqueName, string fileExtension)
  550. {
  551. if (string.IsNullOrEmpty(path))
  552. {
  553. throw new ArgumentNullException(nameof(path));
  554. }
  555. if (string.IsNullOrEmpty(uniqueName))
  556. {
  557. throw new ArgumentNullException(nameof(uniqueName));
  558. }
  559. if (string.IsNullOrEmpty(fileExtension))
  560. {
  561. throw new ArgumentNullException(nameof(fileExtension));
  562. }
  563. var filename = uniqueName.GetMD5() + fileExtension;
  564. return GetCachePath(path, filename);
  565. }
  566. /// <summary>
  567. /// Gets the cache path.
  568. /// </summary>
  569. /// <param name="path">The path.</param>
  570. /// <param name="filename">The filename.</param>
  571. /// <returns>System.String.</returns>
  572. /// <exception cref="ArgumentNullException">
  573. /// path
  574. /// or
  575. /// filename
  576. /// </exception>
  577. public string GetCachePath(string path, string filename)
  578. {
  579. if (string.IsNullOrEmpty(path))
  580. {
  581. throw new ArgumentNullException(nameof(path));
  582. }
  583. if (string.IsNullOrEmpty(filename))
  584. {
  585. throw new ArgumentNullException(nameof(filename));
  586. }
  587. var prefix = filename.Substring(0, 1);
  588. return Path.Combine(path, prefix, filename);
  589. }
  590. /// <inheritdoc />
  591. public void CreateImageCollage(ImageCollageOptions options)
  592. {
  593. _logger.LogInformation("Creating image collage and saving to {Path}", options.OutputPath);
  594. _imageEncoder.CreateImageCollage(options);
  595. _logger.LogInformation("Completed creation of image collage and saved to {Path}", options.OutputPath);
  596. }
  597. /// <inheritdoc />
  598. public IEnumerable<IImageEnhancer> GetSupportedEnhancers(BaseItem item, ImageType imageType)
  599. {
  600. foreach (var i in ImageEnhancers)
  601. {
  602. if (i.Supports(item, imageType))
  603. {
  604. yield return i;
  605. }
  606. }
  607. }
  608. private class LockInfo
  609. {
  610. public SemaphoreSlim Lock = new SemaphoreSlim(1, 1);
  611. public int Count = 1;
  612. }
  613. private LockInfo GetLock(string key)
  614. {
  615. lock (_locks)
  616. {
  617. if (_locks.TryGetValue(key, out LockInfo info))
  618. {
  619. info.Count++;
  620. }
  621. else
  622. {
  623. info = new LockInfo();
  624. _locks[key] = info;
  625. }
  626. return info;
  627. }
  628. }
  629. private void ReleaseLock(string key, LockInfo info)
  630. {
  631. info.Lock.Release();
  632. lock (_locks)
  633. {
  634. info.Count--;
  635. if (info.Count <= 0)
  636. {
  637. _locks.Remove(key);
  638. info.Lock.Dispose();
  639. }
  640. }
  641. }
  642. /// <inheritdoc />
  643. public void Dispose()
  644. {
  645. _disposed = true;
  646. var disposable = _imageEncoder as IDisposable;
  647. if (disposable != null)
  648. {
  649. disposable.Dispose();
  650. }
  651. }
  652. private void CheckDisposed()
  653. {
  654. if (_disposed)
  655. {
  656. throw new ObjectDisposedException(GetType().Name);
  657. }
  658. }
  659. }
  660. }