ImageProcessor.cs 27 KB

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