ImageProcessor.cs 27 KB

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