ImageProcessor.cs 28 KB

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