ImageProcessor.cs 30 KB

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