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