ImageProcessor.cs 28 KB

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