ImageProcessor.cs 27 KB

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