ImageProcessor.cs 28 KB

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