ImageProcessor.cs 32 KB

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