2
0

ImageProcessor.cs 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976
  1. using MediaBrowser.Common.Extensions;
  2. using MediaBrowser.Common.IO;
  3. using MediaBrowser.Controller;
  4. using MediaBrowser.Controller.Drawing;
  5. using MediaBrowser.Controller.Entities;
  6. using MediaBrowser.Controller.Providers;
  7. using MediaBrowser.Model.Drawing;
  8. using MediaBrowser.Model.Entities;
  9. using MediaBrowser.Model.Logging;
  10. using MediaBrowser.Model.Serialization;
  11. using System;
  12. using System.Collections.Concurrent;
  13. using System.Collections.Generic;
  14. using System.Globalization;
  15. using System.IO;
  16. using System.Linq;
  17. using System.Threading;
  18. using System.Threading.Tasks;
  19. using CommonIO;
  20. using Emby.Drawing.Common;
  21. using MediaBrowser.Controller.Library;
  22. using MediaBrowser.Model.Net;
  23. namespace Emby.Drawing
  24. {
  25. /// <summary>
  26. /// Class ImageProcessor
  27. /// </summary>
  28. public class ImageProcessor : IImageProcessor, IDisposable
  29. {
  30. /// <summary>
  31. /// The us culture
  32. /// </summary>
  33. protected readonly CultureInfo UsCulture = new CultureInfo("en-US");
  34. /// <summary>
  35. /// The _cached imaged sizes
  36. /// </summary>
  37. private readonly ConcurrentDictionary<Guid, ImageSize> _cachedImagedSizes;
  38. /// <summary>
  39. /// Gets the list of currently registered image processors
  40. /// Image processors are specialized metadata providers that run after the normal ones
  41. /// </summary>
  42. /// <value>The image enhancers.</value>
  43. public IEnumerable<IImageEnhancer> ImageEnhancers { get; private set; }
  44. /// <summary>
  45. /// The _logger
  46. /// </summary>
  47. private readonly ILogger _logger;
  48. private readonly IFileSystem _fileSystem;
  49. private readonly IJsonSerializer _jsonSerializer;
  50. private readonly IServerApplicationPaths _appPaths;
  51. private readonly IImageEncoder _imageEncoder;
  52. private readonly SemaphoreSlim _imageProcessingSemaphore;
  53. private readonly Func<ILibraryManager> _libraryManager;
  54. public ImageProcessor(ILogger logger,
  55. IServerApplicationPaths appPaths,
  56. IFileSystem fileSystem,
  57. IJsonSerializer jsonSerializer,
  58. IImageEncoder imageEncoder,
  59. int maxConcurrentImageProcesses, Func<ILibraryManager> libraryManager)
  60. {
  61. _logger = logger;
  62. _fileSystem = fileSystem;
  63. _jsonSerializer = jsonSerializer;
  64. _imageEncoder = imageEncoder;
  65. _libraryManager = libraryManager;
  66. _appPaths = appPaths;
  67. ImageEnhancers = new List<IImageEnhancer>();
  68. _saveImageSizeTimer = new Timer(SaveImageSizeCallback, null, Timeout.Infinite, Timeout.Infinite);
  69. Dictionary<Guid, ImageSize> sizeDictionary;
  70. try
  71. {
  72. sizeDictionary = jsonSerializer.DeserializeFromFile<Dictionary<Guid, ImageSize>>(ImageSizeFile) ??
  73. new Dictionary<Guid, ImageSize>();
  74. }
  75. catch (FileNotFoundException)
  76. {
  77. // No biggie
  78. sizeDictionary = new Dictionary<Guid, ImageSize>();
  79. }
  80. catch (DirectoryNotFoundException)
  81. {
  82. // No biggie
  83. sizeDictionary = new Dictionary<Guid, ImageSize>();
  84. }
  85. catch (Exception ex)
  86. {
  87. logger.ErrorException("Error parsing image size cache file", ex);
  88. sizeDictionary = new Dictionary<Guid, ImageSize>();
  89. }
  90. _cachedImagedSizes = new ConcurrentDictionary<Guid, ImageSize>(sizeDictionary);
  91. _logger.Info("ImageProcessor started with {0} max concurrent image processes", maxConcurrentImageProcesses);
  92. _imageProcessingSemaphore = new SemaphoreSlim(maxConcurrentImageProcesses, maxConcurrentImageProcesses);
  93. }
  94. public string[] SupportedInputFormats
  95. {
  96. get
  97. {
  98. return _imageEncoder.SupportedInputFormats;
  99. }
  100. }
  101. public bool SupportsImageCollageCreation
  102. {
  103. get
  104. {
  105. return _imageEncoder.SupportsImageCollageCreation;
  106. }
  107. }
  108. private string ResizedImageCachePath
  109. {
  110. get
  111. {
  112. return Path.Combine(_appPaths.ImageCachePath, "resized-images");
  113. }
  114. }
  115. private string EnhancedImageCachePath
  116. {
  117. get
  118. {
  119. return Path.Combine(_appPaths.ImageCachePath, "enhanced-images");
  120. }
  121. }
  122. private string CroppedWhitespaceImageCachePath
  123. {
  124. get
  125. {
  126. return Path.Combine(_appPaths.ImageCachePath, "cropped-images");
  127. }
  128. }
  129. public void AddParts(IEnumerable<IImageEnhancer> enhancers)
  130. {
  131. ImageEnhancers = enhancers.ToArray();
  132. }
  133. public async Task ProcessImage(ImageProcessingOptions options, Stream toStream)
  134. {
  135. var file = await ProcessImage(options).ConfigureAwait(false);
  136. using (var fileStream = _fileSystem.GetFileStream(file.Item1, FileMode.Open, FileAccess.Read, FileShare.Read, true))
  137. {
  138. await fileStream.CopyToAsync(toStream).ConfigureAwait(false);
  139. }
  140. }
  141. public ImageFormat[] GetSupportedImageOutputFormats()
  142. {
  143. return _imageEncoder.SupportedOutputFormats;
  144. }
  145. public async Task<Tuple<string, string>> ProcessImage(ImageProcessingOptions options)
  146. {
  147. if (options == null)
  148. {
  149. throw new ArgumentNullException("options");
  150. }
  151. var originalImage = options.Image;
  152. if (!originalImage.IsLocalFile)
  153. {
  154. originalImage = await _libraryManager().ConvertImageToLocal(options.Item, originalImage, options.ImageIndex).ConfigureAwait(false);
  155. }
  156. var originalImagePath = originalImage.Path;
  157. if (!_imageEncoder.SupportsImageEncoding)
  158. {
  159. return new Tuple<string, string>(originalImagePath, MimeTypes.GetMimeType(originalImagePath));
  160. }
  161. var dateModified = originalImage.DateModified;
  162. if (options.CropWhiteSpace && _imageEncoder.SupportsImageEncoding)
  163. {
  164. var tuple = await GetWhitespaceCroppedImage(originalImagePath, dateModified).ConfigureAwait(false);
  165. originalImagePath = tuple.Item1;
  166. dateModified = tuple.Item2;
  167. }
  168. if (options.Enhancers.Count > 0)
  169. {
  170. var tuple = await GetEnhancedImage(new ItemImageInfo
  171. {
  172. DateModified = dateModified,
  173. Type = originalImage.Type,
  174. Path = originalImagePath
  175. }, options.Item, options.ImageIndex, options.Enhancers).ConfigureAwait(false);
  176. originalImagePath = tuple.Item1;
  177. dateModified = tuple.Item2;
  178. }
  179. if (options.HasDefaultOptions(originalImagePath))
  180. {
  181. // Just spit out the original file if all the options are default
  182. return new Tuple<string, string>(originalImagePath, MimeTypes.GetMimeType(originalImagePath));
  183. }
  184. ImageSize? originalImageSize;
  185. try
  186. {
  187. originalImageSize = GetImageSize(originalImagePath, dateModified, true);
  188. if (options.HasDefaultOptions(originalImagePath, originalImageSize.Value))
  189. {
  190. // Just spit out the original file if all the options are default
  191. return new Tuple<string, string>(originalImagePath, MimeTypes.GetMimeType(originalImagePath));
  192. }
  193. }
  194. catch
  195. {
  196. originalImageSize = null;
  197. }
  198. var newSize = GetNewImageSize(options, originalImageSize);
  199. var quality = options.Quality;
  200. var outputFormat = GetOutputFormat(options.SupportedOutputFormats[0]);
  201. var cacheFilePath = GetCacheFilePath(originalImagePath, newSize, quality, dateModified, outputFormat, options.AddPlayedIndicator, options.PercentPlayed, options.UnplayedCount, options.BackgroundColor, options.ForegroundLayer);
  202. var semaphore = GetLock(cacheFilePath);
  203. await semaphore.WaitAsync().ConfigureAwait(false);
  204. var imageProcessingLockTaken = false;
  205. try
  206. {
  207. CheckDisposed();
  208. if (!_fileSystem.FileExists(cacheFilePath))
  209. {
  210. var newWidth = Convert.ToInt32(newSize.Width);
  211. var newHeight = Convert.ToInt32(newSize.Height);
  212. _fileSystem.CreateDirectory(Path.GetDirectoryName(cacheFilePath));
  213. await _imageProcessingSemaphore.WaitAsync().ConfigureAwait(false);
  214. imageProcessingLockTaken = true;
  215. _imageEncoder.EncodeImage(originalImagePath, cacheFilePath, AutoOrient(options.Item), newWidth, newHeight, quality, options, outputFormat);
  216. }
  217. return new Tuple<string, string>(cacheFilePath, GetMimeType(outputFormat, cacheFilePath));
  218. }
  219. catch (Exception ex)
  220. {
  221. // If it fails for whatever reason, return the original image
  222. _logger.ErrorException("Error encoding image", ex);
  223. // Just spit out the original file if all the options are default
  224. return new Tuple<string, string>(originalImagePath, MimeTypes.GetMimeType(originalImagePath));
  225. }
  226. finally
  227. {
  228. if (imageProcessingLockTaken)
  229. {
  230. _imageProcessingSemaphore.Release();
  231. }
  232. semaphore.Release();
  233. }
  234. }
  235. private bool AutoOrient(IHasImages item)
  236. {
  237. var photo = item as Photo;
  238. if (photo != null && photo.Orientation.HasValue)
  239. {
  240. return true;
  241. }
  242. return false;
  243. }
  244. //private static int[][] OPERATIONS = new int[][] {
  245. // TopLeft
  246. //new int[] { 0, NONE},
  247. // TopRight
  248. //new int[] { 0, HORIZONTAL},
  249. //new int[] {180, NONE},
  250. // LeftTop
  251. //new int[] { 0, VERTICAL},
  252. //new int[] { 90, HORIZONTAL},
  253. // RightTop
  254. //new int[] { 90, NONE},
  255. //new int[] {-90, HORIZONTAL},
  256. //new int[] {-90, NONE},
  257. //};
  258. private string GetMimeType(ImageFormat format, string path)
  259. {
  260. if (format == ImageFormat.Bmp)
  261. {
  262. return MimeTypes.GetMimeType("i.bmp");
  263. }
  264. if (format == ImageFormat.Gif)
  265. {
  266. return MimeTypes.GetMimeType("i.gif");
  267. }
  268. if (format == ImageFormat.Jpg)
  269. {
  270. return MimeTypes.GetMimeType("i.jpg");
  271. }
  272. if (format == ImageFormat.Png)
  273. {
  274. return MimeTypes.GetMimeType("i.png");
  275. }
  276. if (format == ImageFormat.Webp)
  277. {
  278. return MimeTypes.GetMimeType("i.webp");
  279. }
  280. return MimeTypes.GetMimeType(path);
  281. }
  282. private ImageSize GetNewImageSize(ImageProcessingOptions options, ImageSize? originalImageSize)
  283. {
  284. if (originalImageSize.HasValue)
  285. {
  286. // Determine the output size based on incoming parameters
  287. var newSize = DrawingUtils.Resize(originalImageSize.Value, options.Width, options.Height, options.MaxWidth, options.MaxHeight);
  288. return newSize;
  289. }
  290. return GetSizeEstimate(options);
  291. }
  292. private ImageSize GetSizeEstimate(ImageProcessingOptions options)
  293. {
  294. if (options.Width.HasValue && options.Height.HasValue)
  295. {
  296. return new ImageSize(options.Width.Value, options.Height.Value);
  297. }
  298. var aspect = GetEstimatedAspectRatio(options.Image.Type);
  299. var width = options.Width ?? options.MaxWidth;
  300. if (width.HasValue)
  301. {
  302. var heightValue = aspect / width.Value;
  303. return new ImageSize(width.Value, Convert.ToInt32(heightValue));
  304. }
  305. var height = options.Height ?? options.MaxHeight ?? 200;
  306. var widthValue = aspect * height;
  307. return new ImageSize(Convert.ToInt32(widthValue), height);
  308. }
  309. private double GetEstimatedAspectRatio(ImageType type)
  310. {
  311. switch (type)
  312. {
  313. case ImageType.Art:
  314. case ImageType.Backdrop:
  315. case ImageType.Chapter:
  316. case ImageType.Screenshot:
  317. case ImageType.Thumb:
  318. return 1.78;
  319. case ImageType.Banner:
  320. return 5.4;
  321. case ImageType.Box:
  322. case ImageType.BoxRear:
  323. case ImageType.Disc:
  324. case ImageType.Menu:
  325. return 1;
  326. case ImageType.Logo:
  327. return 2.58;
  328. case ImageType.Primary:
  329. return .667;
  330. default:
  331. return 1;
  332. }
  333. }
  334. private ImageFormat GetOutputFormat(ImageFormat requestedFormat)
  335. {
  336. if (requestedFormat == ImageFormat.Webp && !_imageEncoder.SupportedOutputFormats.Contains(ImageFormat.Webp))
  337. {
  338. return ImageFormat.Png;
  339. }
  340. return requestedFormat;
  341. }
  342. /// <summary>
  343. /// Crops whitespace from an image, caches the result, and returns the cached path
  344. /// </summary>
  345. private async Task<Tuple<string, DateTime>> GetWhitespaceCroppedImage(string originalImagePath, DateTime dateModified)
  346. {
  347. var name = originalImagePath;
  348. name += "datemodified=" + dateModified.Ticks;
  349. var croppedImagePath = GetCachePath(CroppedWhitespaceImageCachePath, name, Path.GetExtension(originalImagePath));
  350. var semaphore = GetLock(croppedImagePath);
  351. await semaphore.WaitAsync().ConfigureAwait(false);
  352. // Check again in case of contention
  353. if (_fileSystem.FileExists(croppedImagePath))
  354. {
  355. semaphore.Release();
  356. return GetResult(croppedImagePath);
  357. }
  358. var imageProcessingLockTaken = false;
  359. try
  360. {
  361. _fileSystem.CreateDirectory(Path.GetDirectoryName(croppedImagePath));
  362. await _imageProcessingSemaphore.WaitAsync().ConfigureAwait(false);
  363. imageProcessingLockTaken = true;
  364. _imageEncoder.CropWhiteSpace(originalImagePath, croppedImagePath);
  365. }
  366. catch (NotImplementedException)
  367. {
  368. // No need to spam the log with an error message
  369. return new Tuple<string, DateTime>(originalImagePath, dateModified);
  370. }
  371. catch (Exception ex)
  372. {
  373. // We have to have a catch-all here because some of the .net image methods throw a plain old Exception
  374. _logger.ErrorException("Error cropping image {0}", ex, originalImagePath);
  375. return new Tuple<string, DateTime>(originalImagePath, dateModified);
  376. }
  377. finally
  378. {
  379. if (imageProcessingLockTaken)
  380. {
  381. _imageProcessingSemaphore.Release();
  382. }
  383. semaphore.Release();
  384. }
  385. return GetResult(croppedImagePath);
  386. }
  387. private Tuple<string, DateTime> GetResult(string path)
  388. {
  389. return new Tuple<string, DateTime>(path, _fileSystem.GetLastWriteTimeUtc(path));
  390. }
  391. /// <summary>
  392. /// Increment this when there's a change requiring caches to be invalidated
  393. /// </summary>
  394. private const string Version = "3";
  395. /// <summary>
  396. /// Gets the cache file path based on a set of parameters
  397. /// </summary>
  398. private string GetCacheFilePath(string originalPath, ImageSize outputSize, int quality, DateTime dateModified, ImageFormat format, bool addPlayedIndicator, double percentPlayed, int? unwatchedCount, string backgroundColor, string foregroundLayer)
  399. {
  400. var filename = originalPath;
  401. filename += "width=" + outputSize.Width;
  402. filename += "height=" + outputSize.Height;
  403. filename += "quality=" + quality;
  404. filename += "datemodified=" + dateModified.Ticks;
  405. filename += "f=" + format;
  406. if (addPlayedIndicator)
  407. {
  408. filename += "pl=true";
  409. }
  410. if (percentPlayed > 0)
  411. {
  412. filename += "p=" + percentPlayed;
  413. }
  414. if (unwatchedCount.HasValue)
  415. {
  416. filename += "p=" + unwatchedCount.Value;
  417. }
  418. if (!string.IsNullOrEmpty(backgroundColor))
  419. {
  420. filename += "b=" + backgroundColor;
  421. }
  422. if (!string.IsNullOrEmpty(foregroundLayer))
  423. {
  424. filename += "fl=" + foregroundLayer;
  425. }
  426. filename += "v=" + Version;
  427. return GetCachePath(ResizedImageCachePath, filename, "." + format.ToString().ToLower());
  428. }
  429. public ImageSize GetImageSize(ItemImageInfo info)
  430. {
  431. return GetImageSize(info.Path, info.DateModified, false);
  432. }
  433. public ImageSize GetImageSize(string path)
  434. {
  435. return GetImageSize(path, _fileSystem.GetLastWriteTimeUtc(path), false);
  436. }
  437. /// <summary>
  438. /// Gets the size of the image.
  439. /// </summary>
  440. /// <param name="path">The path.</param>
  441. /// <param name="imageDateModified">The image date modified.</param>
  442. /// <param name="allowSlowMethod">if set to <c>true</c> [allow slow method].</param>
  443. /// <returns>ImageSize.</returns>
  444. /// <exception cref="System.ArgumentNullException">path</exception>
  445. private ImageSize GetImageSize(string path, DateTime imageDateModified, bool allowSlowMethod)
  446. {
  447. if (string.IsNullOrEmpty(path))
  448. {
  449. throw new ArgumentNullException("path");
  450. }
  451. var name = path + "datemodified=" + imageDateModified.Ticks;
  452. ImageSize size;
  453. var cacheHash = name.GetMD5();
  454. if (!_cachedImagedSizes.TryGetValue(cacheHash, out size))
  455. {
  456. size = GetImageSizeInternal(path, allowSlowMethod);
  457. if (size.Width > 0 && size.Height > 0)
  458. {
  459. StartSaveImageSizeTimer();
  460. _cachedImagedSizes.AddOrUpdate(cacheHash, size, (keyName, oldValue) => size);
  461. }
  462. }
  463. return size;
  464. }
  465. /// <summary>
  466. /// Gets the image size internal.
  467. /// </summary>
  468. /// <param name="path">The path.</param>
  469. /// <param name="allowSlowMethod">if set to <c>true</c> [allow slow method].</param>
  470. /// <returns>ImageSize.</returns>
  471. private ImageSize GetImageSizeInternal(string path, bool allowSlowMethod)
  472. {
  473. try
  474. {
  475. using (var file = TagLib.File.Create(path))
  476. {
  477. var image = file as TagLib.Image.File;
  478. var properties = image.Properties;
  479. return new ImageSize
  480. {
  481. Height = properties.PhotoHeight,
  482. Width = properties.PhotoWidth
  483. };
  484. }
  485. }
  486. catch
  487. {
  488. }
  489. return ImageHeader.GetDimensions(path, _logger, _fileSystem);
  490. }
  491. private readonly Timer _saveImageSizeTimer;
  492. private const int SaveImageSizeTimeout = 5000;
  493. private readonly object _saveImageSizeLock = new object();
  494. private void StartSaveImageSizeTimer()
  495. {
  496. _saveImageSizeTimer.Change(SaveImageSizeTimeout, Timeout.Infinite);
  497. }
  498. private void SaveImageSizeCallback(object state)
  499. {
  500. lock (_saveImageSizeLock)
  501. {
  502. try
  503. {
  504. var path = ImageSizeFile;
  505. _fileSystem.CreateDirectory(Path.GetDirectoryName(path));
  506. _jsonSerializer.SerializeToFile(_cachedImagedSizes, path);
  507. }
  508. catch (Exception ex)
  509. {
  510. _logger.ErrorException("Error saving image size file", ex);
  511. }
  512. }
  513. }
  514. private string ImageSizeFile
  515. {
  516. get
  517. {
  518. return Path.Combine(_appPaths.DataPath, "imagesizes.json");
  519. }
  520. }
  521. /// <summary>
  522. /// Gets the image cache tag.
  523. /// </summary>
  524. /// <param name="item">The item.</param>
  525. /// <param name="image">The image.</param>
  526. /// <returns>Guid.</returns>
  527. /// <exception cref="System.ArgumentNullException">item</exception>
  528. public string GetImageCacheTag(IHasImages item, ItemImageInfo image)
  529. {
  530. if (item == null)
  531. {
  532. throw new ArgumentNullException("item");
  533. }
  534. if (image == null)
  535. {
  536. throw new ArgumentNullException("image");
  537. }
  538. var supportedEnhancers = GetSupportedEnhancers(item, image.Type);
  539. return GetImageCacheTag(item, image, supportedEnhancers.ToList());
  540. }
  541. /// <summary>
  542. /// Gets the image cache tag.
  543. /// </summary>
  544. /// <param name="item">The item.</param>
  545. /// <param name="image">The image.</param>
  546. /// <param name="imageEnhancers">The image enhancers.</param>
  547. /// <returns>Guid.</returns>
  548. /// <exception cref="System.ArgumentNullException">item</exception>
  549. public string GetImageCacheTag(IHasImages item, ItemImageInfo image, List<IImageEnhancer> imageEnhancers)
  550. {
  551. if (item == null)
  552. {
  553. throw new ArgumentNullException("item");
  554. }
  555. if (imageEnhancers == null)
  556. {
  557. throw new ArgumentNullException("imageEnhancers");
  558. }
  559. if (image == null)
  560. {
  561. throw new ArgumentNullException("image");
  562. }
  563. var originalImagePath = image.Path;
  564. var dateModified = image.DateModified;
  565. var imageType = image.Type;
  566. // Optimization
  567. if (imageEnhancers.Count == 0)
  568. {
  569. return (originalImagePath + dateModified.Ticks).GetMD5().ToString("N");
  570. }
  571. // Cache name is created with supported enhancers combined with the last config change so we pick up new config changes
  572. var cacheKeys = imageEnhancers.Select(i => i.GetConfigurationCacheKey(item, imageType)).ToList();
  573. cacheKeys.Add(originalImagePath + dateModified.Ticks);
  574. return string.Join("|", cacheKeys.ToArray()).GetMD5().ToString("N");
  575. }
  576. /// <summary>
  577. /// Gets the enhanced image.
  578. /// </summary>
  579. /// <param name="item">The item.</param>
  580. /// <param name="imageType">Type of the image.</param>
  581. /// <param name="imageIndex">Index of the image.</param>
  582. /// <returns>Task{System.String}.</returns>
  583. public async Task<string> GetEnhancedImage(IHasImages item, ImageType imageType, int imageIndex)
  584. {
  585. var enhancers = GetSupportedEnhancers(item, imageType).ToList();
  586. var imageInfo = item.GetImageInfo(imageType, imageIndex);
  587. var result = await GetEnhancedImage(imageInfo, item, imageIndex, enhancers);
  588. return result.Item1;
  589. }
  590. private async Task<Tuple<string, DateTime>> GetEnhancedImage(ItemImageInfo image,
  591. IHasImages item,
  592. int imageIndex,
  593. List<IImageEnhancer> enhancers)
  594. {
  595. var originalImagePath = image.Path;
  596. var dateModified = image.DateModified;
  597. var imageType = image.Type;
  598. try
  599. {
  600. var cacheGuid = GetImageCacheTag(item, image, enhancers);
  601. // Enhance if we have enhancers
  602. var ehnancedImagePath = await GetEnhancedImageInternal(originalImagePath, item, imageType, imageIndex, enhancers, cacheGuid).ConfigureAwait(false);
  603. // If the path changed update dateModified
  604. if (!ehnancedImagePath.Equals(originalImagePath, StringComparison.OrdinalIgnoreCase))
  605. {
  606. return GetResult(ehnancedImagePath);
  607. }
  608. }
  609. catch (Exception ex)
  610. {
  611. _logger.Error("Error enhancing image", ex);
  612. }
  613. return new Tuple<string, DateTime>(originalImagePath, dateModified);
  614. }
  615. /// <summary>
  616. /// Gets the enhanced image internal.
  617. /// </summary>
  618. /// <param name="originalImagePath">The original image path.</param>
  619. /// <param name="item">The item.</param>
  620. /// <param name="imageType">Type of the image.</param>
  621. /// <param name="imageIndex">Index of the image.</param>
  622. /// <param name="supportedEnhancers">The supported enhancers.</param>
  623. /// <param name="cacheGuid">The cache unique identifier.</param>
  624. /// <returns>Task&lt;System.String&gt;.</returns>
  625. /// <exception cref="ArgumentNullException">
  626. /// originalImagePath
  627. /// or
  628. /// item
  629. /// </exception>
  630. private async Task<string> GetEnhancedImageInternal(string originalImagePath,
  631. IHasImages item,
  632. ImageType imageType,
  633. int imageIndex,
  634. IEnumerable<IImageEnhancer> supportedEnhancers,
  635. string cacheGuid)
  636. {
  637. if (string.IsNullOrEmpty(originalImagePath))
  638. {
  639. throw new ArgumentNullException("originalImagePath");
  640. }
  641. if (item == null)
  642. {
  643. throw new ArgumentNullException("item");
  644. }
  645. // All enhanced images are saved as png to allow transparency
  646. var enhancedImagePath = GetCachePath(EnhancedImageCachePath, cacheGuid + ".png");
  647. var semaphore = GetLock(enhancedImagePath);
  648. await semaphore.WaitAsync().ConfigureAwait(false);
  649. // Check again in case of contention
  650. if (_fileSystem.FileExists(enhancedImagePath))
  651. {
  652. semaphore.Release();
  653. return enhancedImagePath;
  654. }
  655. var imageProcessingLockTaken = false;
  656. try
  657. {
  658. _fileSystem.CreateDirectory(Path.GetDirectoryName(enhancedImagePath));
  659. await _imageProcessingSemaphore.WaitAsync().ConfigureAwait(false);
  660. imageProcessingLockTaken = true;
  661. await ExecuteImageEnhancers(supportedEnhancers, originalImagePath, enhancedImagePath, item, imageType, imageIndex).ConfigureAwait(false);
  662. }
  663. finally
  664. {
  665. if (imageProcessingLockTaken)
  666. {
  667. _imageProcessingSemaphore.Release();
  668. }
  669. semaphore.Release();
  670. }
  671. return enhancedImagePath;
  672. }
  673. /// <summary>
  674. /// Executes the image enhancers.
  675. /// </summary>
  676. /// <param name="imageEnhancers">The image enhancers.</param>
  677. /// <param name="inputPath">The input path.</param>
  678. /// <param name="outputPath">The output path.</param>
  679. /// <param name="item">The item.</param>
  680. /// <param name="imageType">Type of the image.</param>
  681. /// <param name="imageIndex">Index of the image.</param>
  682. /// <returns>Task{EnhancedImage}.</returns>
  683. private async Task ExecuteImageEnhancers(IEnumerable<IImageEnhancer> imageEnhancers, string inputPath, string outputPath, IHasImages item, ImageType imageType, int imageIndex)
  684. {
  685. // Run the enhancers sequentially in order of priority
  686. foreach (var enhancer in imageEnhancers)
  687. {
  688. var typeName = enhancer.GetType().Name;
  689. try
  690. {
  691. await enhancer.EnhanceImageAsync(item, inputPath, outputPath, imageType, imageIndex).ConfigureAwait(false);
  692. }
  693. catch (Exception ex)
  694. {
  695. _logger.ErrorException("{0} failed enhancing {1}", ex, typeName, item.Name);
  696. throw;
  697. }
  698. // Feed the output into the next enhancer as input
  699. inputPath = outputPath;
  700. }
  701. }
  702. /// <summary>
  703. /// The _semaphoreLocks
  704. /// </summary>
  705. private readonly ConcurrentDictionary<string, SemaphoreSlim> _semaphoreLocks = new ConcurrentDictionary<string, SemaphoreSlim>();
  706. /// <summary>
  707. /// Gets the lock.
  708. /// </summary>
  709. /// <param name="filename">The filename.</param>
  710. /// <returns>System.Object.</returns>
  711. private SemaphoreSlim GetLock(string filename)
  712. {
  713. return _semaphoreLocks.GetOrAdd(filename, key => new SemaphoreSlim(1, 1));
  714. }
  715. /// <summary>
  716. /// Gets the cache path.
  717. /// </summary>
  718. /// <param name="path">The path.</param>
  719. /// <param name="uniqueName">Name of the unique.</param>
  720. /// <param name="fileExtension">The file extension.</param>
  721. /// <returns>System.String.</returns>
  722. /// <exception cref="System.ArgumentNullException">
  723. /// path
  724. /// or
  725. /// uniqueName
  726. /// or
  727. /// fileExtension
  728. /// </exception>
  729. public string GetCachePath(string path, string uniqueName, string fileExtension)
  730. {
  731. if (string.IsNullOrEmpty(path))
  732. {
  733. throw new ArgumentNullException("path");
  734. }
  735. if (string.IsNullOrEmpty(uniqueName))
  736. {
  737. throw new ArgumentNullException("uniqueName");
  738. }
  739. if (string.IsNullOrEmpty(fileExtension))
  740. {
  741. throw new ArgumentNullException("fileExtension");
  742. }
  743. var filename = uniqueName.GetMD5() + fileExtension;
  744. return GetCachePath(path, filename);
  745. }
  746. /// <summary>
  747. /// Gets the cache path.
  748. /// </summary>
  749. /// <param name="path">The path.</param>
  750. /// <param name="filename">The filename.</param>
  751. /// <returns>System.String.</returns>
  752. /// <exception cref="System.ArgumentNullException">
  753. /// path
  754. /// or
  755. /// filename
  756. /// </exception>
  757. public string GetCachePath(string path, string filename)
  758. {
  759. if (string.IsNullOrEmpty(path))
  760. {
  761. throw new ArgumentNullException("path");
  762. }
  763. if (string.IsNullOrEmpty(filename))
  764. {
  765. throw new ArgumentNullException("filename");
  766. }
  767. var prefix = filename.Substring(0, 1);
  768. path = Path.Combine(path, prefix);
  769. return Path.Combine(path, filename);
  770. }
  771. public async Task CreateImageCollage(ImageCollageOptions options)
  772. {
  773. await _imageProcessingSemaphore.WaitAsync().ConfigureAwait(false);
  774. try
  775. {
  776. _logger.Info("Creating image collage and saving to {0}", options.OutputPath);
  777. _imageEncoder.CreateImageCollage(options);
  778. _logger.Info("Completed creation of image collage and saved to {0}", options.OutputPath);
  779. }
  780. finally
  781. {
  782. _imageProcessingSemaphore.Release();
  783. }
  784. }
  785. public IEnumerable<IImageEnhancer> GetSupportedEnhancers(IHasImages item, ImageType imageType)
  786. {
  787. return ImageEnhancers.Where(i =>
  788. {
  789. try
  790. {
  791. return i.Supports(item, imageType);
  792. }
  793. catch (Exception ex)
  794. {
  795. _logger.ErrorException("Error in image enhancer: {0}", ex, i.GetType().Name);
  796. return false;
  797. }
  798. });
  799. }
  800. private bool _disposed;
  801. public void Dispose()
  802. {
  803. _disposed = true;
  804. _imageEncoder.Dispose();
  805. _saveImageSizeTimer.Dispose();
  806. }
  807. private void CheckDisposed()
  808. {
  809. if (_disposed)
  810. {
  811. throw new ObjectDisposedException(GetType().Name);
  812. }
  813. }
  814. }
  815. }