ImageProcessor.cs 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937
  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);
  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, newWidth, newHeight, quality, options, outputFormat);
  216. }
  217. }
  218. finally
  219. {
  220. if (imageProcessingLockTaken)
  221. {
  222. _imageProcessingSemaphore.Release();
  223. }
  224. semaphore.Release();
  225. }
  226. return new Tuple<string, string>(cacheFilePath, GetMimeType(outputFormat, cacheFilePath));
  227. }
  228. private string GetMimeType(ImageFormat format, string path)
  229. {
  230. if (format == ImageFormat.Bmp)
  231. {
  232. return MimeTypes.GetMimeType("i.bmp");
  233. }
  234. if (format == ImageFormat.Gif)
  235. {
  236. return MimeTypes.GetMimeType("i.gif");
  237. }
  238. if (format == ImageFormat.Jpg)
  239. {
  240. return MimeTypes.GetMimeType("i.jpg");
  241. }
  242. if (format == ImageFormat.Png)
  243. {
  244. return MimeTypes.GetMimeType("i.png");
  245. }
  246. if (format == ImageFormat.Webp)
  247. {
  248. return MimeTypes.GetMimeType("i.webp");
  249. }
  250. return MimeTypes.GetMimeType(path);
  251. }
  252. private ImageSize GetNewImageSize(ImageProcessingOptions options, ImageSize? originalImageSize)
  253. {
  254. if (originalImageSize.HasValue)
  255. {
  256. // Determine the output size based on incoming parameters
  257. var newSize = DrawingUtils.Resize(originalImageSize.Value, options.Width, options.Height, options.MaxWidth, options.MaxHeight);
  258. return newSize;
  259. }
  260. return GetSizeEstimate(options);
  261. }
  262. private ImageSize GetSizeEstimate(ImageProcessingOptions options)
  263. {
  264. if (options.Width.HasValue && options.Height.HasValue)
  265. {
  266. return new ImageSize(options.Width.Value, options.Height.Value);
  267. }
  268. var aspect = GetEstimatedAspectRatio(options.Image.Type);
  269. var width = options.Width ?? options.MaxWidth;
  270. if (width.HasValue)
  271. {
  272. var heightValue = aspect / width.Value;
  273. return new ImageSize(width.Value, Convert.ToInt32(heightValue));
  274. }
  275. var height = options.Height ?? options.MaxHeight ?? 200;
  276. var widthValue = aspect * height;
  277. return new ImageSize(Convert.ToInt32(widthValue), height);
  278. }
  279. private double GetEstimatedAspectRatio(ImageType type)
  280. {
  281. switch (type)
  282. {
  283. case ImageType.Art:
  284. case ImageType.Backdrop:
  285. case ImageType.Chapter:
  286. case ImageType.Screenshot:
  287. case ImageType.Thumb:
  288. return 1.78;
  289. case ImageType.Banner:
  290. return 5.4;
  291. case ImageType.Box:
  292. case ImageType.BoxRear:
  293. case ImageType.Disc:
  294. case ImageType.Menu:
  295. return 1;
  296. case ImageType.Logo:
  297. return 2.58;
  298. case ImageType.Primary:
  299. return .667;
  300. default:
  301. return 1;
  302. }
  303. }
  304. private ImageFormat GetOutputFormat(ImageFormat requestedFormat)
  305. {
  306. if (requestedFormat == ImageFormat.Webp && !_imageEncoder.SupportedOutputFormats.Contains(ImageFormat.Webp))
  307. {
  308. return ImageFormat.Png;
  309. }
  310. return requestedFormat;
  311. }
  312. /// <summary>
  313. /// Crops whitespace from an image, caches the result, and returns the cached path
  314. /// </summary>
  315. private async Task<Tuple<string, DateTime>> GetWhitespaceCroppedImage(string originalImagePath, DateTime dateModified)
  316. {
  317. var name = originalImagePath;
  318. name += "datemodified=" + dateModified.Ticks;
  319. var croppedImagePath = GetCachePath(CroppedWhitespaceImageCachePath, name, Path.GetExtension(originalImagePath));
  320. var semaphore = GetLock(croppedImagePath);
  321. await semaphore.WaitAsync().ConfigureAwait(false);
  322. // Check again in case of contention
  323. if (_fileSystem.FileExists(croppedImagePath))
  324. {
  325. semaphore.Release();
  326. return GetResult(croppedImagePath);
  327. }
  328. var imageProcessingLockTaken = false;
  329. try
  330. {
  331. _fileSystem.CreateDirectory(Path.GetDirectoryName(croppedImagePath));
  332. await _imageProcessingSemaphore.WaitAsync().ConfigureAwait(false);
  333. imageProcessingLockTaken = true;
  334. _imageEncoder.CropWhiteSpace(originalImagePath, croppedImagePath);
  335. }
  336. catch (NotImplementedException)
  337. {
  338. // No need to spam the log with an error message
  339. return new Tuple<string, DateTime>(originalImagePath, dateModified);
  340. }
  341. catch (Exception ex)
  342. {
  343. // We have to have a catch-all here because some of the .net image methods throw a plain old Exception
  344. _logger.ErrorException("Error cropping image {0}", ex, originalImagePath);
  345. return new Tuple<string, DateTime>(originalImagePath, dateModified);
  346. }
  347. finally
  348. {
  349. if (imageProcessingLockTaken)
  350. {
  351. _imageProcessingSemaphore.Release();
  352. }
  353. semaphore.Release();
  354. }
  355. return GetResult(croppedImagePath);
  356. }
  357. private Tuple<string, DateTime> GetResult(string path)
  358. {
  359. return new Tuple<string, DateTime>(path, _fileSystem.GetLastWriteTimeUtc(path));
  360. }
  361. /// <summary>
  362. /// Increment this when there's a change requiring caches to be invalidated
  363. /// </summary>
  364. private const string Version = "3";
  365. /// <summary>
  366. /// Gets the cache file path based on a set of parameters
  367. /// </summary>
  368. private string GetCacheFilePath(string originalPath, ImageSize outputSize, int quality, DateTime dateModified, ImageFormat format, bool addPlayedIndicator, double percentPlayed, int? unwatchedCount, string backgroundColor)
  369. {
  370. var filename = originalPath;
  371. filename += "width=" + outputSize.Width;
  372. filename += "height=" + outputSize.Height;
  373. filename += "quality=" + quality;
  374. filename += "datemodified=" + dateModified.Ticks;
  375. filename += "f=" + format;
  376. if (addPlayedIndicator)
  377. {
  378. filename += "pl=true";
  379. }
  380. if (percentPlayed > 0)
  381. {
  382. filename += "p=" + percentPlayed;
  383. }
  384. if (unwatchedCount.HasValue)
  385. {
  386. filename += "p=" + unwatchedCount.Value;
  387. }
  388. if (!string.IsNullOrEmpty(backgroundColor))
  389. {
  390. filename += "b=" + backgroundColor;
  391. }
  392. filename += "v=" + Version;
  393. return GetCachePath(ResizedImageCachePath, filename, "." + format.ToString().ToLower());
  394. }
  395. public ImageSize GetImageSize(ItemImageInfo info)
  396. {
  397. return GetImageSize(info.Path, info.DateModified, false);
  398. }
  399. public ImageSize GetImageSize(string path)
  400. {
  401. return GetImageSize(path, _fileSystem.GetLastWriteTimeUtc(path), false);
  402. }
  403. /// <summary>
  404. /// Gets the size of the image.
  405. /// </summary>
  406. /// <param name="path">The path.</param>
  407. /// <param name="imageDateModified">The image date modified.</param>
  408. /// <param name="allowSlowMethod">if set to <c>true</c> [allow slow method].</param>
  409. /// <returns>ImageSize.</returns>
  410. /// <exception cref="System.ArgumentNullException">path</exception>
  411. private ImageSize GetImageSize(string path, DateTime imageDateModified, bool allowSlowMethod)
  412. {
  413. if (string.IsNullOrEmpty(path))
  414. {
  415. throw new ArgumentNullException("path");
  416. }
  417. var name = path + "datemodified=" + imageDateModified.Ticks;
  418. ImageSize size;
  419. var cacheHash = name.GetMD5();
  420. if (!_cachedImagedSizes.TryGetValue(cacheHash, out size))
  421. {
  422. size = GetImageSizeInternal(path, allowSlowMethod);
  423. if (size.Width > 0 && size.Height > 0)
  424. {
  425. StartSaveImageSizeTimer();
  426. _cachedImagedSizes.AddOrUpdate(cacheHash, size, (keyName, oldValue) => size);
  427. }
  428. }
  429. return size;
  430. }
  431. /// <summary>
  432. /// Gets the image size internal.
  433. /// </summary>
  434. /// <param name="path">The path.</param>
  435. /// <param name="allowSlowMethod">if set to <c>true</c> [allow slow method].</param>
  436. /// <returns>ImageSize.</returns>
  437. private ImageSize GetImageSizeInternal(string path, bool allowSlowMethod)
  438. {
  439. try
  440. {
  441. using (var file = TagLib.File.Create(path))
  442. {
  443. var image = file as TagLib.Image.File;
  444. var properties = image.Properties;
  445. return new ImageSize
  446. {
  447. Height = properties.PhotoHeight,
  448. Width = properties.PhotoWidth
  449. };
  450. }
  451. }
  452. catch
  453. {
  454. }
  455. return ImageHeader.GetDimensions(path, _logger, _fileSystem);
  456. }
  457. private readonly Timer _saveImageSizeTimer;
  458. private const int SaveImageSizeTimeout = 5000;
  459. private readonly object _saveImageSizeLock = new object();
  460. private void StartSaveImageSizeTimer()
  461. {
  462. _saveImageSizeTimer.Change(SaveImageSizeTimeout, Timeout.Infinite);
  463. }
  464. private void SaveImageSizeCallback(object state)
  465. {
  466. lock (_saveImageSizeLock)
  467. {
  468. try
  469. {
  470. var path = ImageSizeFile;
  471. _fileSystem.CreateDirectory(Path.GetDirectoryName(path));
  472. _jsonSerializer.SerializeToFile(_cachedImagedSizes, path);
  473. }
  474. catch (Exception ex)
  475. {
  476. _logger.ErrorException("Error saving image size file", ex);
  477. }
  478. }
  479. }
  480. private string ImageSizeFile
  481. {
  482. get
  483. {
  484. return Path.Combine(_appPaths.DataPath, "imagesizes.json");
  485. }
  486. }
  487. /// <summary>
  488. /// Gets the image cache tag.
  489. /// </summary>
  490. /// <param name="item">The item.</param>
  491. /// <param name="image">The image.</param>
  492. /// <returns>Guid.</returns>
  493. /// <exception cref="System.ArgumentNullException">item</exception>
  494. public string GetImageCacheTag(IHasImages item, ItemImageInfo image)
  495. {
  496. if (item == null)
  497. {
  498. throw new ArgumentNullException("item");
  499. }
  500. if (image == null)
  501. {
  502. throw new ArgumentNullException("image");
  503. }
  504. var supportedEnhancers = GetSupportedEnhancers(item, image.Type);
  505. return GetImageCacheTag(item, image, supportedEnhancers.ToList());
  506. }
  507. /// <summary>
  508. /// Gets the image cache tag.
  509. /// </summary>
  510. /// <param name="item">The item.</param>
  511. /// <param name="image">The image.</param>
  512. /// <param name="imageEnhancers">The image enhancers.</param>
  513. /// <returns>Guid.</returns>
  514. /// <exception cref="System.ArgumentNullException">item</exception>
  515. public string GetImageCacheTag(IHasImages item, ItemImageInfo image, List<IImageEnhancer> imageEnhancers)
  516. {
  517. if (item == null)
  518. {
  519. throw new ArgumentNullException("item");
  520. }
  521. if (imageEnhancers == null)
  522. {
  523. throw new ArgumentNullException("imageEnhancers");
  524. }
  525. if (image == null)
  526. {
  527. throw new ArgumentNullException("image");
  528. }
  529. var originalImagePath = image.Path;
  530. var dateModified = image.DateModified;
  531. var imageType = image.Type;
  532. // Optimization
  533. if (imageEnhancers.Count == 0)
  534. {
  535. return (originalImagePath + dateModified.Ticks).GetMD5().ToString("N");
  536. }
  537. // Cache name is created with supported enhancers combined with the last config change so we pick up new config changes
  538. var cacheKeys = imageEnhancers.Select(i => i.GetConfigurationCacheKey(item, imageType)).ToList();
  539. cacheKeys.Add(originalImagePath + dateModified.Ticks);
  540. return string.Join("|", cacheKeys.ToArray()).GetMD5().ToString("N");
  541. }
  542. /// <summary>
  543. /// Gets the enhanced image.
  544. /// </summary>
  545. /// <param name="item">The item.</param>
  546. /// <param name="imageType">Type of the image.</param>
  547. /// <param name="imageIndex">Index of the image.</param>
  548. /// <returns>Task{System.String}.</returns>
  549. public async Task<string> GetEnhancedImage(IHasImages item, ImageType imageType, int imageIndex)
  550. {
  551. var enhancers = GetSupportedEnhancers(item, imageType).ToList();
  552. var imageInfo = item.GetImageInfo(imageType, imageIndex);
  553. var result = await GetEnhancedImage(imageInfo, item, imageIndex, enhancers);
  554. return result.Item1;
  555. }
  556. private async Task<Tuple<string, DateTime>> GetEnhancedImage(ItemImageInfo image,
  557. IHasImages item,
  558. int imageIndex,
  559. List<IImageEnhancer> enhancers)
  560. {
  561. var originalImagePath = image.Path;
  562. var dateModified = image.DateModified;
  563. var imageType = image.Type;
  564. try
  565. {
  566. var cacheGuid = GetImageCacheTag(item, image, enhancers);
  567. // Enhance if we have enhancers
  568. var ehnancedImagePath = await GetEnhancedImageInternal(originalImagePath, item, imageType, imageIndex, enhancers, cacheGuid).ConfigureAwait(false);
  569. // If the path changed update dateModified
  570. if (!ehnancedImagePath.Equals(originalImagePath, StringComparison.OrdinalIgnoreCase))
  571. {
  572. return GetResult(ehnancedImagePath);
  573. }
  574. }
  575. catch (Exception ex)
  576. {
  577. _logger.Error("Error enhancing image", ex);
  578. }
  579. return new Tuple<string, DateTime>(originalImagePath, dateModified);
  580. }
  581. /// <summary>
  582. /// Gets the enhanced image internal.
  583. /// </summary>
  584. /// <param name="originalImagePath">The original image path.</param>
  585. /// <param name="item">The item.</param>
  586. /// <param name="imageType">Type of the image.</param>
  587. /// <param name="imageIndex">Index of the image.</param>
  588. /// <param name="supportedEnhancers">The supported enhancers.</param>
  589. /// <param name="cacheGuid">The cache unique identifier.</param>
  590. /// <returns>Task&lt;System.String&gt;.</returns>
  591. /// <exception cref="ArgumentNullException">
  592. /// originalImagePath
  593. /// or
  594. /// item
  595. /// </exception>
  596. private async Task<string> GetEnhancedImageInternal(string originalImagePath,
  597. IHasImages item,
  598. ImageType imageType,
  599. int imageIndex,
  600. IEnumerable<IImageEnhancer> supportedEnhancers,
  601. string cacheGuid)
  602. {
  603. if (string.IsNullOrEmpty(originalImagePath))
  604. {
  605. throw new ArgumentNullException("originalImagePath");
  606. }
  607. if (item == null)
  608. {
  609. throw new ArgumentNullException("item");
  610. }
  611. // All enhanced images are saved as png to allow transparency
  612. var enhancedImagePath = GetCachePath(EnhancedImageCachePath, cacheGuid + ".png");
  613. var semaphore = GetLock(enhancedImagePath);
  614. await semaphore.WaitAsync().ConfigureAwait(false);
  615. // Check again in case of contention
  616. if (_fileSystem.FileExists(enhancedImagePath))
  617. {
  618. semaphore.Release();
  619. return enhancedImagePath;
  620. }
  621. var imageProcessingLockTaken = false;
  622. try
  623. {
  624. _fileSystem.CreateDirectory(Path.GetDirectoryName(enhancedImagePath));
  625. await _imageProcessingSemaphore.WaitAsync().ConfigureAwait(false);
  626. imageProcessingLockTaken = true;
  627. await ExecuteImageEnhancers(supportedEnhancers, originalImagePath, enhancedImagePath, item, imageType, imageIndex).ConfigureAwait(false);
  628. }
  629. finally
  630. {
  631. if (imageProcessingLockTaken)
  632. {
  633. _imageProcessingSemaphore.Release();
  634. }
  635. semaphore.Release();
  636. }
  637. return enhancedImagePath;
  638. }
  639. /// <summary>
  640. /// Executes the image enhancers.
  641. /// </summary>
  642. /// <param name="imageEnhancers">The image enhancers.</param>
  643. /// <param name="inputPath">The input path.</param>
  644. /// <param name="outputPath">The output path.</param>
  645. /// <param name="item">The item.</param>
  646. /// <param name="imageType">Type of the image.</param>
  647. /// <param name="imageIndex">Index of the image.</param>
  648. /// <returns>Task{EnhancedImage}.</returns>
  649. private async Task ExecuteImageEnhancers(IEnumerable<IImageEnhancer> imageEnhancers, string inputPath, string outputPath, IHasImages item, ImageType imageType, int imageIndex)
  650. {
  651. // Run the enhancers sequentially in order of priority
  652. foreach (var enhancer in imageEnhancers)
  653. {
  654. var typeName = enhancer.GetType().Name;
  655. try
  656. {
  657. await enhancer.EnhanceImageAsync(item, inputPath, outputPath, imageType, imageIndex).ConfigureAwait(false);
  658. }
  659. catch (Exception ex)
  660. {
  661. _logger.ErrorException("{0} failed enhancing {1}", ex, typeName, item.Name);
  662. throw;
  663. }
  664. // Feed the output into the next enhancer as input
  665. inputPath = outputPath;
  666. }
  667. }
  668. /// <summary>
  669. /// The _semaphoreLocks
  670. /// </summary>
  671. private readonly ConcurrentDictionary<string, SemaphoreSlim> _semaphoreLocks = new ConcurrentDictionary<string, SemaphoreSlim>();
  672. /// <summary>
  673. /// Gets the lock.
  674. /// </summary>
  675. /// <param name="filename">The filename.</param>
  676. /// <returns>System.Object.</returns>
  677. private SemaphoreSlim GetLock(string filename)
  678. {
  679. return _semaphoreLocks.GetOrAdd(filename, key => new SemaphoreSlim(1, 1));
  680. }
  681. /// <summary>
  682. /// Gets the cache path.
  683. /// </summary>
  684. /// <param name="path">The path.</param>
  685. /// <param name="uniqueName">Name of the unique.</param>
  686. /// <param name="fileExtension">The file extension.</param>
  687. /// <returns>System.String.</returns>
  688. /// <exception cref="System.ArgumentNullException">
  689. /// path
  690. /// or
  691. /// uniqueName
  692. /// or
  693. /// fileExtension
  694. /// </exception>
  695. public string GetCachePath(string path, string uniqueName, string fileExtension)
  696. {
  697. if (string.IsNullOrEmpty(path))
  698. {
  699. throw new ArgumentNullException("path");
  700. }
  701. if (string.IsNullOrEmpty(uniqueName))
  702. {
  703. throw new ArgumentNullException("uniqueName");
  704. }
  705. if (string.IsNullOrEmpty(fileExtension))
  706. {
  707. throw new ArgumentNullException("fileExtension");
  708. }
  709. var filename = uniqueName.GetMD5() + fileExtension;
  710. return GetCachePath(path, filename);
  711. }
  712. /// <summary>
  713. /// Gets the cache path.
  714. /// </summary>
  715. /// <param name="path">The path.</param>
  716. /// <param name="filename">The filename.</param>
  717. /// <returns>System.String.</returns>
  718. /// <exception cref="System.ArgumentNullException">
  719. /// path
  720. /// or
  721. /// filename
  722. /// </exception>
  723. public string GetCachePath(string path, string filename)
  724. {
  725. if (string.IsNullOrEmpty(path))
  726. {
  727. throw new ArgumentNullException("path");
  728. }
  729. if (string.IsNullOrEmpty(filename))
  730. {
  731. throw new ArgumentNullException("filename");
  732. }
  733. var prefix = filename.Substring(0, 1);
  734. path = Path.Combine(path, prefix);
  735. return Path.Combine(path, filename);
  736. }
  737. public async Task CreateImageCollage(ImageCollageOptions options)
  738. {
  739. await _imageProcessingSemaphore.WaitAsync().ConfigureAwait(false);
  740. try
  741. {
  742. _logger.Info("Creating image collage and saving to {0}", options.OutputPath);
  743. _imageEncoder.CreateImageCollage(options);
  744. _logger.Info("Completed creation of image collage and saved to {0}", options.OutputPath);
  745. }
  746. finally
  747. {
  748. _imageProcessingSemaphore.Release();
  749. }
  750. }
  751. public IEnumerable<IImageEnhancer> GetSupportedEnhancers(IHasImages item, ImageType imageType)
  752. {
  753. return ImageEnhancers.Where(i =>
  754. {
  755. try
  756. {
  757. return i.Supports(item, imageType);
  758. }
  759. catch (Exception ex)
  760. {
  761. _logger.ErrorException("Error in image enhancer: {0}", ex, i.GetType().Name);
  762. return false;
  763. }
  764. });
  765. }
  766. private bool _disposed;
  767. public void Dispose()
  768. {
  769. _disposed = true;
  770. _imageEncoder.Dispose();
  771. _saveImageSizeTimer.Dispose();
  772. }
  773. private void CheckDisposed()
  774. {
  775. if (_disposed)
  776. {
  777. throw new ObjectDisposedException(GetType().Name);
  778. }
  779. }
  780. }
  781. }