ImageProcessor.cs 29 KB

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