ImageProcessor.cs 31 KB

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