ImageProcessor.cs 28 KB

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