ImageProcessor.cs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822
  1. using Emby.Drawing.Common;
  2. using MediaBrowser.Common.Extensions;
  3. using MediaBrowser.Common.IO;
  4. using MediaBrowser.Controller;
  5. using MediaBrowser.Controller.Drawing;
  6. using MediaBrowser.Controller.Entities;
  7. using MediaBrowser.Controller.Providers;
  8. using MediaBrowser.Model.Drawing;
  9. using MediaBrowser.Model.Entities;
  10. using MediaBrowser.Model.Logging;
  11. using MediaBrowser.Model.Serialization;
  12. using System;
  13. using System.Collections.Concurrent;
  14. using System.Collections.Generic;
  15. using System.Globalization;
  16. using System.IO;
  17. using System.Linq;
  18. using System.Threading;
  19. using System.Threading.Tasks;
  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 (!File.Exists(cacheFilePath))
  181. {
  182. var newWidth = Convert.ToInt32(newSize.Width);
  183. var newHeight = Convert.ToInt32(newSize.Height);
  184. Directory.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 (File.Exists(croppedImagePath))
  222. {
  223. semaphore.Release();
  224. return GetResult(croppedImagePath);
  225. }
  226. var imageProcessingLockTaken = false;
  227. try
  228. {
  229. Directory.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, File.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. _cachedImagedSizes.AddOrUpdate(cacheHash, size, (keyName, oldValue) => size);
  322. }
  323. return size;
  324. }
  325. /// <summary>
  326. /// Gets the image size internal.
  327. /// </summary>
  328. /// <param name="path">The path.</param>
  329. /// <param name="allowSlowMethod">if set to <c>true</c> [allow slow method].</param>
  330. /// <returns>ImageSize.</returns>
  331. private ImageSize GetImageSizeInternal(string path, bool allowSlowMethod)
  332. {
  333. ImageSize size;
  334. try
  335. {
  336. size = ImageHeader.GetDimensions(path, _logger, _fileSystem);
  337. }
  338. catch
  339. {
  340. if (!allowSlowMethod)
  341. {
  342. throw;
  343. }
  344. //_logger.Info("Failed to read image header for {0}. Doing it the slow way.", path);
  345. CheckDisposed();
  346. size = _imageEncoder.GetImageSize(path);
  347. }
  348. StartSaveImageSizeTimer();
  349. return size;
  350. }
  351. private readonly Timer _saveImageSizeTimer;
  352. private const int SaveImageSizeTimeout = 5000;
  353. private readonly object _saveImageSizeLock = new object();
  354. private void StartSaveImageSizeTimer()
  355. {
  356. _saveImageSizeTimer.Change(SaveImageSizeTimeout, Timeout.Infinite);
  357. }
  358. private void SaveImageSizeCallback(object state)
  359. {
  360. lock (_saveImageSizeLock)
  361. {
  362. try
  363. {
  364. var path = ImageSizeFile;
  365. Directory.CreateDirectory(Path.GetDirectoryName(path));
  366. _jsonSerializer.SerializeToFile(_cachedImagedSizes, path);
  367. }
  368. catch (Exception ex)
  369. {
  370. _logger.ErrorException("Error saving image size file", ex);
  371. }
  372. }
  373. }
  374. private string ImageSizeFile
  375. {
  376. get
  377. {
  378. return Path.Combine(_appPaths.DataPath, "imagesizes.json");
  379. }
  380. }
  381. /// <summary>
  382. /// Gets the image cache tag.
  383. /// </summary>
  384. /// <param name="item">The item.</param>
  385. /// <param name="image">The image.</param>
  386. /// <returns>Guid.</returns>
  387. /// <exception cref="System.ArgumentNullException">item</exception>
  388. public string GetImageCacheTag(IHasImages item, ItemImageInfo image)
  389. {
  390. if (item == null)
  391. {
  392. throw new ArgumentNullException("item");
  393. }
  394. if (image == null)
  395. {
  396. throw new ArgumentNullException("image");
  397. }
  398. var supportedEnhancers = GetSupportedEnhancers(item, image.Type);
  399. return GetImageCacheTag(item, image, supportedEnhancers.ToList());
  400. }
  401. /// <summary>
  402. /// Gets the image cache tag.
  403. /// </summary>
  404. /// <param name="item">The item.</param>
  405. /// <param name="image">The image.</param>
  406. /// <param name="imageEnhancers">The image enhancers.</param>
  407. /// <returns>Guid.</returns>
  408. /// <exception cref="System.ArgumentNullException">item</exception>
  409. public string GetImageCacheTag(IHasImages item, ItemImageInfo image, List<IImageEnhancer> imageEnhancers)
  410. {
  411. if (item == null)
  412. {
  413. throw new ArgumentNullException("item");
  414. }
  415. if (imageEnhancers == null)
  416. {
  417. throw new ArgumentNullException("imageEnhancers");
  418. }
  419. if (image == null)
  420. {
  421. throw new ArgumentNullException("image");
  422. }
  423. var originalImagePath = image.Path;
  424. var dateModified = image.DateModified;
  425. var imageType = image.Type;
  426. // Optimization
  427. if (imageEnhancers.Count == 0)
  428. {
  429. return (originalImagePath + dateModified.Ticks).GetMD5().ToString("N");
  430. }
  431. // Cache name is created with supported enhancers combined with the last config change so we pick up new config changes
  432. var cacheKeys = imageEnhancers.Select(i => i.GetConfigurationCacheKey(item, imageType)).ToList();
  433. cacheKeys.Add(originalImagePath + dateModified.Ticks);
  434. return string.Join("|", cacheKeys.ToArray()).GetMD5().ToString("N");
  435. }
  436. /// <summary>
  437. /// Gets the enhanced image.
  438. /// </summary>
  439. /// <param name="item">The item.</param>
  440. /// <param name="imageType">Type of the image.</param>
  441. /// <param name="imageIndex">Index of the image.</param>
  442. /// <returns>Task{System.String}.</returns>
  443. public async Task<string> GetEnhancedImage(IHasImages item, ImageType imageType, int imageIndex)
  444. {
  445. var enhancers = GetSupportedEnhancers(item, imageType).ToList();
  446. var imageInfo = item.GetImageInfo(imageType, imageIndex);
  447. var result = await GetEnhancedImage(imageInfo, item, imageIndex, enhancers);
  448. return result.Item1;
  449. }
  450. private async Task<Tuple<string, DateTime>> GetEnhancedImage(ItemImageInfo image,
  451. IHasImages item,
  452. int imageIndex,
  453. List<IImageEnhancer> enhancers)
  454. {
  455. var originalImagePath = image.Path;
  456. var dateModified = image.DateModified;
  457. var imageType = image.Type;
  458. try
  459. {
  460. var cacheGuid = GetImageCacheTag(item, image, enhancers);
  461. // Enhance if we have enhancers
  462. var ehnancedImagePath = await GetEnhancedImageInternal(originalImagePath, item, imageType, imageIndex, enhancers, cacheGuid).ConfigureAwait(false);
  463. // If the path changed update dateModified
  464. if (!ehnancedImagePath.Equals(originalImagePath, StringComparison.OrdinalIgnoreCase))
  465. {
  466. return GetResult(ehnancedImagePath);
  467. }
  468. }
  469. catch (Exception ex)
  470. {
  471. _logger.Error("Error enhancing image", ex);
  472. }
  473. return new Tuple<string, DateTime>(originalImagePath, dateModified);
  474. }
  475. /// <summary>
  476. /// Gets the enhanced image internal.
  477. /// </summary>
  478. /// <param name="originalImagePath">The original image path.</param>
  479. /// <param name="item">The item.</param>
  480. /// <param name="imageType">Type of the image.</param>
  481. /// <param name="imageIndex">Index of the image.</param>
  482. /// <param name="supportedEnhancers">The supported enhancers.</param>
  483. /// <param name="cacheGuid">The cache unique identifier.</param>
  484. /// <returns>Task&lt;System.String&gt;.</returns>
  485. /// <exception cref="ArgumentNullException">
  486. /// originalImagePath
  487. /// or
  488. /// item
  489. /// </exception>
  490. private async Task<string> GetEnhancedImageInternal(string originalImagePath,
  491. IHasImages item,
  492. ImageType imageType,
  493. int imageIndex,
  494. IEnumerable<IImageEnhancer> supportedEnhancers,
  495. string cacheGuid)
  496. {
  497. if (string.IsNullOrEmpty(originalImagePath))
  498. {
  499. throw new ArgumentNullException("originalImagePath");
  500. }
  501. if (item == null)
  502. {
  503. throw new ArgumentNullException("item");
  504. }
  505. // All enhanced images are saved as png to allow transparency
  506. var enhancedImagePath = GetCachePath(EnhancedImageCachePath, cacheGuid + ".png");
  507. var semaphore = GetLock(enhancedImagePath);
  508. await semaphore.WaitAsync().ConfigureAwait(false);
  509. // Check again in case of contention
  510. if (File.Exists(enhancedImagePath))
  511. {
  512. semaphore.Release();
  513. return enhancedImagePath;
  514. }
  515. var imageProcessingLockTaken = false;
  516. try
  517. {
  518. Directory.CreateDirectory(Path.GetDirectoryName(enhancedImagePath));
  519. await _imageProcessingSemaphore.WaitAsync().ConfigureAwait(false);
  520. imageProcessingLockTaken = true;
  521. await ExecuteImageEnhancers(supportedEnhancers, originalImagePath, enhancedImagePath, item, imageType, imageIndex).ConfigureAwait(false);
  522. }
  523. finally
  524. {
  525. if (imageProcessingLockTaken)
  526. {
  527. _imageProcessingSemaphore.Release();
  528. }
  529. semaphore.Release();
  530. }
  531. return enhancedImagePath;
  532. }
  533. /// <summary>
  534. /// Executes the image enhancers.
  535. /// </summary>
  536. /// <param name="imageEnhancers">The image enhancers.</param>
  537. /// <param name="inputPath">The input path.</param>
  538. /// <param name="outputPath">The output path.</param>
  539. /// <param name="item">The item.</param>
  540. /// <param name="imageType">Type of the image.</param>
  541. /// <param name="imageIndex">Index of the image.</param>
  542. /// <returns>Task{EnhancedImage}.</returns>
  543. private async Task ExecuteImageEnhancers(IEnumerable<IImageEnhancer> imageEnhancers, string inputPath, string outputPath, IHasImages item, ImageType imageType, int imageIndex)
  544. {
  545. // Run the enhancers sequentially in order of priority
  546. foreach (var enhancer in imageEnhancers)
  547. {
  548. var typeName = enhancer.GetType().Name;
  549. try
  550. {
  551. await enhancer.EnhanceImageAsync(item, inputPath, outputPath, imageType, imageIndex).ConfigureAwait(false);
  552. }
  553. catch (Exception ex)
  554. {
  555. _logger.ErrorException("{0} failed enhancing {1}", ex, typeName, item.Name);
  556. throw;
  557. }
  558. // Feed the output into the next enhancer as input
  559. inputPath = outputPath;
  560. }
  561. }
  562. /// <summary>
  563. /// The _semaphoreLocks
  564. /// </summary>
  565. private readonly ConcurrentDictionary<string, SemaphoreSlim> _semaphoreLocks = new ConcurrentDictionary<string, SemaphoreSlim>();
  566. /// <summary>
  567. /// Gets the lock.
  568. /// </summary>
  569. /// <param name="filename">The filename.</param>
  570. /// <returns>System.Object.</returns>
  571. private SemaphoreSlim GetLock(string filename)
  572. {
  573. return _semaphoreLocks.GetOrAdd(filename, key => new SemaphoreSlim(1, 1));
  574. }
  575. /// <summary>
  576. /// Gets the cache path.
  577. /// </summary>
  578. /// <param name="path">The path.</param>
  579. /// <param name="uniqueName">Name of the unique.</param>
  580. /// <param name="fileExtension">The file extension.</param>
  581. /// <returns>System.String.</returns>
  582. /// <exception cref="System.ArgumentNullException">
  583. /// path
  584. /// or
  585. /// uniqueName
  586. /// or
  587. /// fileExtension
  588. /// </exception>
  589. public string GetCachePath(string path, string uniqueName, string fileExtension)
  590. {
  591. if (string.IsNullOrEmpty(path))
  592. {
  593. throw new ArgumentNullException("path");
  594. }
  595. if (string.IsNullOrEmpty(uniqueName))
  596. {
  597. throw new ArgumentNullException("uniqueName");
  598. }
  599. if (string.IsNullOrEmpty(fileExtension))
  600. {
  601. throw new ArgumentNullException("fileExtension");
  602. }
  603. var filename = uniqueName.GetMD5() + fileExtension;
  604. return GetCachePath(path, filename);
  605. }
  606. /// <summary>
  607. /// Gets the cache path.
  608. /// </summary>
  609. /// <param name="path">The path.</param>
  610. /// <param name="filename">The filename.</param>
  611. /// <returns>System.String.</returns>
  612. /// <exception cref="System.ArgumentNullException">
  613. /// path
  614. /// or
  615. /// filename
  616. /// </exception>
  617. public string GetCachePath(string path, string filename)
  618. {
  619. if (string.IsNullOrEmpty(path))
  620. {
  621. throw new ArgumentNullException("path");
  622. }
  623. if (string.IsNullOrEmpty(filename))
  624. {
  625. throw new ArgumentNullException("filename");
  626. }
  627. var prefix = filename.Substring(0, 1);
  628. path = Path.Combine(path, prefix);
  629. return Path.Combine(path, filename);
  630. }
  631. public async Task CreateImageCollage(ImageCollageOptions options)
  632. {
  633. await _imageProcessingSemaphore.WaitAsync().ConfigureAwait(false);
  634. try
  635. {
  636. _logger.Debug("Creating image collage and saving to {0}", options.OutputPath);
  637. _imageEncoder.CreateImageCollage(options);
  638. _logger.Debug("Completed creation of image collage and saved to {0}", options.OutputPath);
  639. }
  640. finally
  641. {
  642. _imageProcessingSemaphore.Release();
  643. }
  644. }
  645. public IEnumerable<IImageEnhancer> GetSupportedEnhancers(IHasImages item, ImageType imageType)
  646. {
  647. return ImageEnhancers.Where(i =>
  648. {
  649. try
  650. {
  651. return i.Supports(item, imageType);
  652. }
  653. catch (Exception ex)
  654. {
  655. _logger.ErrorException("Error in image enhancer: {0}", ex, i.GetType().Name);
  656. return false;
  657. }
  658. });
  659. }
  660. private bool _disposed;
  661. public void Dispose()
  662. {
  663. _disposed = true;
  664. _imageEncoder.Dispose();
  665. _saveImageSizeTimer.Dispose();
  666. }
  667. private void CheckDisposed()
  668. {
  669. if (_disposed)
  670. {
  671. throw new ObjectDisposedException(GetType().Name);
  672. }
  673. }
  674. }
  675. }