ImageProcessor.cs 28 KB

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