ImageProcessor.cs 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757
  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 System;
  11. using System.Collections.Concurrent;
  12. using System.Collections.Generic;
  13. using System.Drawing;
  14. using System.Drawing.Drawing2D;
  15. using System.Drawing.Imaging;
  16. using System.Globalization;
  17. using System.IO;
  18. using System.Linq;
  19. using System.Threading;
  20. using System.Threading.Tasks;
  21. namespace MediaBrowser.Server.Implementations.Drawing
  22. {
  23. /// <summary>
  24. /// Class ImageProcessor
  25. /// </summary>
  26. public class ImageProcessor : IImageProcessor
  27. {
  28. /// <summary>
  29. /// The us culture
  30. /// </summary>
  31. protected readonly CultureInfo UsCulture = new CultureInfo("en-US");
  32. /// <summary>
  33. /// The _cached imaged sizes
  34. /// </summary>
  35. private readonly ConcurrentDictionary<string, ImageSize> _cachedImagedSizes = new ConcurrentDictionary<string, ImageSize>();
  36. /// <summary>
  37. /// Gets the list of currently registered image processors
  38. /// Image processors are specialized metadata providers that run after the normal ones
  39. /// </summary>
  40. /// <value>The image enhancers.</value>
  41. public IEnumerable<IImageEnhancer> ImageEnhancers { get; private set; }
  42. /// <summary>
  43. /// The _logger
  44. /// </summary>
  45. private readonly ILogger _logger;
  46. /// <summary>
  47. /// The _app paths
  48. /// </summary>
  49. private readonly IServerApplicationPaths _appPaths;
  50. private readonly string _imageSizeCachePath;
  51. private readonly string _croppedWhitespaceImageCachePath;
  52. private readonly string _enhancedImageCachePath;
  53. private readonly string _resizedImageCachePath;
  54. public ImageProcessor(ILogger logger, IServerApplicationPaths appPaths)
  55. {
  56. _logger = logger;
  57. _appPaths = appPaths;
  58. _imageSizeCachePath = Path.Combine(_appPaths.ImageCachePath, "image-sizes");
  59. _croppedWhitespaceImageCachePath = Path.Combine(_appPaths.ImageCachePath, "cropped-images");
  60. _enhancedImageCachePath = Path.Combine(_appPaths.ImageCachePath, "enhanced-images");
  61. _resizedImageCachePath = Path.Combine(_appPaths.ImageCachePath, "resized-images");
  62. }
  63. public void AddParts(IEnumerable<IImageEnhancer> enhancers)
  64. {
  65. ImageEnhancers = enhancers.ToArray();
  66. }
  67. public async Task ProcessImage(ImageProcessingOptions options, Stream toStream)
  68. {
  69. if (options == null)
  70. {
  71. throw new ArgumentNullException("options");
  72. }
  73. if (toStream == null)
  74. {
  75. throw new ArgumentNullException("toStream");
  76. }
  77. var originalImagePath = options.OriginalImagePath;
  78. var dateModified = options.OriginalImageDateModified;
  79. if (options.CropWhiteSpace)
  80. {
  81. originalImagePath = await GetWhitespaceCroppedImage(originalImagePath, dateModified).ConfigureAwait(false);
  82. }
  83. // No enhancement - don't cache
  84. if (options.Enhancers.Count > 0)
  85. {
  86. var tuple = await GetEnhancedImage(originalImagePath, dateModified, options.Item, options.ImageType, options.ImageIndex, options.Enhancers).ConfigureAwait(false);
  87. originalImagePath = tuple.Item1;
  88. dateModified = tuple.Item2;
  89. }
  90. var originalImageSize = GetImageSize(originalImagePath, dateModified);
  91. // Determine the output size based on incoming parameters
  92. var newSize = DrawingUtils.Resize(originalImageSize, options.Width, options.Height, options.MaxWidth, options.MaxHeight);
  93. var quality = options.Quality ?? 90;
  94. var cacheFilePath = GetCacheFilePath(originalImagePath, newSize, quality, dateModified, options.OutputFormat);
  95. try
  96. {
  97. using (var fileStream = new FileStream(cacheFilePath, FileMode.Open, FileAccess.Read, FileShare.Read, StreamDefaults.DefaultFileStreamBufferSize, FileOptions.Asynchronous))
  98. {
  99. await fileStream.CopyToAsync(toStream).ConfigureAwait(false);
  100. return;
  101. }
  102. }
  103. catch (IOException)
  104. {
  105. // Cache file doesn't exist or is currently being written ro
  106. }
  107. var semaphore = GetLock(cacheFilePath);
  108. await semaphore.WaitAsync().ConfigureAwait(false);
  109. // Check again in case of lock contention
  110. if (File.Exists(cacheFilePath))
  111. {
  112. try
  113. {
  114. using (var fileStream = new FileStream(cacheFilePath, FileMode.Open, FileAccess.Read, FileShare.Read, StreamDefaults.DefaultFileStreamBufferSize, FileOptions.Asynchronous))
  115. {
  116. await fileStream.CopyToAsync(toStream).ConfigureAwait(false);
  117. return;
  118. }
  119. }
  120. finally
  121. {
  122. semaphore.Release();
  123. }
  124. }
  125. try
  126. {
  127. using (var fileStream = new FileStream(originalImagePath, FileMode.Open, FileAccess.Read, FileShare.Read, StreamDefaults.DefaultFileStreamBufferSize, true))
  128. {
  129. // Copy to memory stream to avoid Image locking file
  130. using (var memoryStream = new MemoryStream())
  131. {
  132. await fileStream.CopyToAsync(memoryStream).ConfigureAwait(false);
  133. using (var originalImage = Image.FromStream(memoryStream, true, false))
  134. {
  135. var newWidth = Convert.ToInt32(newSize.Width);
  136. var newHeight = Convert.ToInt32(newSize.Height);
  137. // Graphics.FromImage will throw an exception if the PixelFormat is Indexed, so we need to handle that here
  138. using (var thumbnail = !ImageExtensions.IsPixelFormatSupportedByGraphicsObject(originalImage.PixelFormat) ? new Bitmap(originalImage, newWidth, newHeight) : new Bitmap(newWidth, newHeight, originalImage.PixelFormat))
  139. {
  140. // Preserve the original resolution
  141. thumbnail.SetResolution(originalImage.HorizontalResolution, originalImage.VerticalResolution);
  142. using (var thumbnailGraph = Graphics.FromImage(thumbnail))
  143. {
  144. thumbnailGraph.CompositingQuality = CompositingQuality.HighQuality;
  145. thumbnailGraph.SmoothingMode = SmoothingMode.HighQuality;
  146. thumbnailGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;
  147. thumbnailGraph.PixelOffsetMode = PixelOffsetMode.HighQuality;
  148. thumbnailGraph.CompositingMode = CompositingMode.SourceOver;
  149. thumbnailGraph.DrawImage(originalImage, 0, 0, newWidth, newHeight);
  150. var outputFormat = GetOutputFormat(originalImage, options.OutputFormat);
  151. using (var outputMemoryStream = new MemoryStream())
  152. {
  153. // Save to the memory stream
  154. thumbnail.Save(outputFormat, outputMemoryStream, quality);
  155. var bytes = outputMemoryStream.ToArray();
  156. var outputTask = toStream.WriteAsync(bytes, 0, bytes.Length);
  157. // kick off a task to cache the result
  158. var cacheTask = CacheResizedImage(cacheFilePath, bytes);
  159. await Task.WhenAll(outputTask, cacheTask).ConfigureAwait(false);
  160. }
  161. }
  162. }
  163. }
  164. }
  165. }
  166. }
  167. finally
  168. {
  169. semaphore.Release();
  170. }
  171. }
  172. /// <summary>
  173. /// Gets the output format.
  174. /// </summary>
  175. /// <param name="image">The image.</param>
  176. /// <param name="outputFormat">The output format.</param>
  177. /// <returns>ImageFormat.</returns>
  178. private ImageFormat GetOutputFormat(Image image, ImageOutputFormat outputFormat)
  179. {
  180. switch (outputFormat)
  181. {
  182. case ImageOutputFormat.Bmp:
  183. return ImageFormat.Bmp;
  184. case ImageOutputFormat.Gif:
  185. return ImageFormat.Gif;
  186. case ImageOutputFormat.Jpg:
  187. return ImageFormat.Jpeg;
  188. case ImageOutputFormat.Png:
  189. return ImageFormat.Png;
  190. default:
  191. return image.RawFormat;
  192. }
  193. }
  194. /// <summary>
  195. /// Crops whitespace from an image, caches the result, and returns the cached path
  196. /// </summary>
  197. /// <param name="originalImagePath">The original image path.</param>
  198. /// <param name="dateModified">The date modified.</param>
  199. /// <returns>System.String.</returns>
  200. private async Task<string> GetWhitespaceCroppedImage(string originalImagePath, DateTime dateModified)
  201. {
  202. var name = originalImagePath;
  203. name += "datemodified=" + dateModified.Ticks;
  204. var croppedImagePath = GetCachePath(_croppedWhitespaceImageCachePath, name, Path.GetExtension(originalImagePath));
  205. var semaphore = GetLock(croppedImagePath);
  206. await semaphore.WaitAsync().ConfigureAwait(false);
  207. // Check again in case of contention
  208. if (File.Exists(croppedImagePath))
  209. {
  210. semaphore.Release();
  211. return croppedImagePath;
  212. }
  213. try
  214. {
  215. using (var fileStream = new FileStream(originalImagePath, FileMode.Open, FileAccess.Read, FileShare.Read, StreamDefaults.DefaultFileStreamBufferSize, true))
  216. {
  217. // Copy to memory stream to avoid Image locking file
  218. using (var memoryStream = new MemoryStream())
  219. {
  220. await fileStream.CopyToAsync(memoryStream).ConfigureAwait(false);
  221. using (var originalImage = (Bitmap)Image.FromStream(memoryStream, true, false))
  222. {
  223. var outputFormat = originalImage.RawFormat;
  224. using (var croppedImage = originalImage.CropWhitespace())
  225. {
  226. var parentPath = Path.GetDirectoryName(croppedImagePath);
  227. if (!Directory.Exists(parentPath))
  228. {
  229. Directory.CreateDirectory(parentPath);
  230. }
  231. using (var outputStream = new FileStream(croppedImagePath, FileMode.Create, FileAccess.Write, FileShare.Read))
  232. {
  233. croppedImage.Save(outputFormat, outputStream, 100);
  234. }
  235. }
  236. }
  237. }
  238. }
  239. }
  240. catch (Exception ex)
  241. {
  242. // We have to have a catch-all here because some of the .net image methods throw a plain old Exception
  243. _logger.ErrorException("Error cropping image {0}", ex, originalImagePath);
  244. return originalImagePath;
  245. }
  246. finally
  247. {
  248. semaphore.Release();
  249. }
  250. return croppedImagePath;
  251. }
  252. /// <summary>
  253. /// Caches the resized image.
  254. /// </summary>
  255. /// <param name="cacheFilePath">The cache file path.</param>
  256. /// <param name="bytes">The bytes.</param>
  257. private async Task CacheResizedImage(string cacheFilePath, byte[] bytes)
  258. {
  259. var parentPath = Path.GetDirectoryName(cacheFilePath);
  260. if (!Directory.Exists(parentPath))
  261. {
  262. Directory.CreateDirectory(parentPath);
  263. }
  264. // Save to the cache location
  265. using (var cacheFileStream = new FileStream(cacheFilePath, FileMode.Create, FileAccess.Write, FileShare.Read, StreamDefaults.DefaultFileStreamBufferSize, FileOptions.Asynchronous))
  266. {
  267. // Save to the filestream
  268. await cacheFileStream.WriteAsync(bytes, 0, bytes.Length).ConfigureAwait(false);
  269. }
  270. }
  271. /// <summary>
  272. /// Gets the cache file path based on a set of parameters
  273. /// </summary>
  274. /// <param name="originalPath">The path to the original image file</param>
  275. /// <param name="outputSize">The size to output the image in</param>
  276. /// <param name="quality">Quality level, from 0-100. Currently only applies to JPG. The default value should suffice.</param>
  277. /// <param name="dateModified">The last modified date of the image</param>
  278. /// <returns>System.String.</returns>
  279. private string GetCacheFilePath(string originalPath, ImageSize outputSize, int quality, DateTime dateModified, ImageOutputFormat format)
  280. {
  281. var filename = originalPath;
  282. filename += "width=" + outputSize.Width;
  283. filename += "height=" + outputSize.Height;
  284. filename += "quality=" + quality;
  285. filename += "datemodified=" + dateModified.Ticks;
  286. if (format != ImageOutputFormat.Original)
  287. {
  288. filename += "format=" + format;
  289. }
  290. return GetCachePath(_resizedImageCachePath, filename, Path.GetExtension(originalPath));
  291. }
  292. /// <summary>
  293. /// Gets the size of the image.
  294. /// </summary>
  295. /// <param name="path">The path.</param>
  296. /// <returns>ImageSize.</returns>
  297. public ImageSize GetImageSize(string path)
  298. {
  299. return GetImageSize(path, File.GetLastWriteTimeUtc(path));
  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. /// <returns>ImageSize.</returns>
  307. /// <exception cref="System.ArgumentNullException">path</exception>
  308. public ImageSize GetImageSize(string path, DateTime imageDateModified)
  309. {
  310. if (string.IsNullOrEmpty(path))
  311. {
  312. throw new ArgumentNullException("path");
  313. }
  314. var name = path + "datemodified=" + imageDateModified.Ticks;
  315. ImageSize size;
  316. if (!_cachedImagedSizes.TryGetValue(name, out size))
  317. {
  318. size = GetImageSizeInternal(name, path);
  319. _cachedImagedSizes.AddOrUpdate(name, size, (keyName, oldValue) => size);
  320. }
  321. return size;
  322. }
  323. /// <summary>
  324. /// Gets the image size internal.
  325. /// </summary>
  326. /// <param name="cacheKey">The cache key.</param>
  327. /// <param name="path">The path.</param>
  328. /// <returns>ImageSize.</returns>
  329. private ImageSize GetImageSizeInternal(string cacheKey, string path)
  330. {
  331. // Now check the file system cache
  332. var fullCachePath = GetCachePath(_imageSizeCachePath, cacheKey, ".txt");
  333. try
  334. {
  335. var result = File.ReadAllText(fullCachePath).Split('|').Select(i => double.Parse(i, UsCulture)).ToArray();
  336. return new ImageSize { Width = result[0], Height = result[1] };
  337. }
  338. catch (IOException)
  339. {
  340. // Cache file doesn't exist or is currently being written to
  341. }
  342. var syncLock = GetObjectLock(fullCachePath);
  343. lock (syncLock)
  344. {
  345. try
  346. {
  347. var result = File.ReadAllText(fullCachePath)
  348. .Split('|')
  349. .Select(i => double.Parse(i, UsCulture))
  350. .ToArray();
  351. return new ImageSize { Width = result[0], Height = result[1] };
  352. }
  353. catch (FileNotFoundException)
  354. {
  355. // Cache file doesn't exist no biggie
  356. }
  357. catch (DirectoryNotFoundException)
  358. {
  359. // Cache file doesn't exist no biggie
  360. }
  361. var size = ImageHeader.GetDimensions(path, _logger);
  362. var parentPath = Path.GetDirectoryName(fullCachePath);
  363. if (!Directory.Exists(parentPath))
  364. {
  365. Directory.CreateDirectory(parentPath);
  366. }
  367. // Update the file system cache
  368. File.WriteAllText(fullCachePath, size.Width.ToString(UsCulture) + @"|" + size.Height.ToString(UsCulture));
  369. return new ImageSize { Width = size.Width, Height = size.Height };
  370. }
  371. }
  372. /// <summary>
  373. /// Gets the image cache tag.
  374. /// </summary>
  375. /// <param name="item">The item.</param>
  376. /// <param name="imageType">Type of the image.</param>
  377. /// <param name="imagePath">The image path.</param>
  378. /// <returns>Guid.</returns>
  379. /// <exception cref="System.ArgumentNullException">item</exception>
  380. public Guid GetImageCacheTag(BaseItem item, ImageType imageType, string imagePath)
  381. {
  382. if (item == null)
  383. {
  384. throw new ArgumentNullException("item");
  385. }
  386. if (string.IsNullOrEmpty(imagePath))
  387. {
  388. throw new ArgumentNullException("imagePath");
  389. }
  390. var dateModified = item.GetImageDateModified(imagePath);
  391. var supportedEnhancers = GetSupportedEnhancers(item, imageType);
  392. return GetImageCacheTag(item, imageType, imagePath, dateModified, supportedEnhancers);
  393. }
  394. /// <summary>
  395. /// Gets the image cache tag.
  396. /// </summary>
  397. /// <param name="item">The item.</param>
  398. /// <param name="imageType">Type of the image.</param>
  399. /// <param name="originalImagePath">The original image path.</param>
  400. /// <param name="dateModified">The date modified of the original image file.</param>
  401. /// <param name="imageEnhancers">The image enhancers.</param>
  402. /// <returns>Guid.</returns>
  403. /// <exception cref="System.ArgumentNullException">item</exception>
  404. public Guid GetImageCacheTag(BaseItem item, ImageType imageType, string originalImagePath, DateTime dateModified, IEnumerable<IImageEnhancer> imageEnhancers)
  405. {
  406. if (item == null)
  407. {
  408. throw new ArgumentNullException("item");
  409. }
  410. if (imageEnhancers == null)
  411. {
  412. throw new ArgumentNullException("imageEnhancers");
  413. }
  414. if (string.IsNullOrEmpty(originalImagePath))
  415. {
  416. throw new ArgumentNullException("originalImagePath");
  417. }
  418. // Cache name is created with supported enhancers combined with the last config change so we pick up new config changes
  419. var cacheKeys = imageEnhancers.Select(i => i.GetConfigurationCacheKey(item, imageType)).ToList();
  420. cacheKeys.Add(originalImagePath + dateModified.Ticks);
  421. return string.Join("|", cacheKeys.ToArray()).GetMD5();
  422. }
  423. private async Task<Tuple<string,DateTime>> GetEnhancedImage(string originalImagePath, DateTime dateModified, BaseItem item,
  424. ImageType imageType, int imageIndex,
  425. List<IImageEnhancer> enhancers)
  426. {
  427. try
  428. {
  429. // Enhance if we have enhancers
  430. var ehnancedImagePath = await GetEnhancedImageInternal(originalImagePath, dateModified, item, imageType, imageIndex, enhancers).ConfigureAwait(false);
  431. // If the path changed update dateModified
  432. if (!ehnancedImagePath.Equals(originalImagePath, StringComparison.OrdinalIgnoreCase))
  433. {
  434. dateModified = File.GetLastWriteTimeUtc(ehnancedImagePath);
  435. return new Tuple<string, DateTime>(ehnancedImagePath, dateModified);
  436. }
  437. }
  438. catch (Exception ex)
  439. {
  440. _logger.Error("Error enhancing image", ex);
  441. }
  442. return new Tuple<string, DateTime>(originalImagePath, dateModified);
  443. }
  444. /// <summary>
  445. /// Runs an image through the image enhancers, caches the result, and returns the cached path
  446. /// </summary>
  447. /// <param name="originalImagePath">The original image path.</param>
  448. /// <param name="dateModified">The date modified of the original image file.</param>
  449. /// <param name="item">The item.</param>
  450. /// <param name="imageType">Type of the image.</param>
  451. /// <param name="imageIndex">Index of the image.</param>
  452. /// <param name="supportedEnhancers">The supported enhancers.</param>
  453. /// <returns>System.String.</returns>
  454. /// <exception cref="System.ArgumentNullException">originalImagePath</exception>
  455. private async Task<string> GetEnhancedImageInternal(string originalImagePath, DateTime dateModified, BaseItem item, ImageType imageType, int imageIndex, List<IImageEnhancer> supportedEnhancers)
  456. {
  457. if (string.IsNullOrEmpty(originalImagePath))
  458. {
  459. throw new ArgumentNullException("originalImagePath");
  460. }
  461. if (item == null)
  462. {
  463. throw new ArgumentNullException("item");
  464. }
  465. var cacheGuid = GetImageCacheTag(item, imageType, originalImagePath, dateModified, supportedEnhancers);
  466. // All enhanced images are saved as png to allow transparency
  467. var enhancedImagePath = GetCachePath(_enhancedImageCachePath, cacheGuid + ".png");
  468. var semaphore = GetLock(enhancedImagePath);
  469. await semaphore.WaitAsync().ConfigureAwait(false);
  470. // Check again in case of contention
  471. if (File.Exists(enhancedImagePath))
  472. {
  473. semaphore.Release();
  474. return enhancedImagePath;
  475. }
  476. try
  477. {
  478. using (var fileStream = new FileStream(originalImagePath, FileMode.Open, FileAccess.Read, FileShare.Read, StreamDefaults.DefaultFileStreamBufferSize, true))
  479. {
  480. // Copy to memory stream to avoid Image locking file
  481. using (var memoryStream = new MemoryStream())
  482. {
  483. await fileStream.CopyToAsync(memoryStream).ConfigureAwait(false);
  484. using (var originalImage = Image.FromStream(memoryStream, true, false))
  485. {
  486. //Pass the image through registered enhancers
  487. using (var newImage = await ExecuteImageEnhancers(supportedEnhancers, originalImage, item, imageType, imageIndex).ConfigureAwait(false))
  488. {
  489. var parentDirectory = Path.GetDirectoryName(enhancedImagePath);
  490. if (!Directory.Exists(parentDirectory))
  491. {
  492. Directory.CreateDirectory(parentDirectory);
  493. }
  494. //And then save it in the cache
  495. using (var outputStream = new FileStream(enhancedImagePath, FileMode.Create, FileAccess.Write, FileShare.Read))
  496. {
  497. newImage.Save(ImageFormat.Png, outputStream, 100);
  498. }
  499. }
  500. }
  501. }
  502. }
  503. }
  504. finally
  505. {
  506. semaphore.Release();
  507. }
  508. return enhancedImagePath;
  509. }
  510. /// <summary>
  511. /// Executes the image enhancers.
  512. /// </summary>
  513. /// <param name="imageEnhancers">The image enhancers.</param>
  514. /// <param name="originalImage">The original image.</param>
  515. /// <param name="item">The item.</param>
  516. /// <param name="imageType">Type of the image.</param>
  517. /// <param name="imageIndex">Index of the image.</param>
  518. /// <returns>Task{EnhancedImage}.</returns>
  519. private async Task<Image> ExecuteImageEnhancers(IEnumerable<IImageEnhancer> imageEnhancers, Image originalImage, BaseItem item, ImageType imageType, int imageIndex)
  520. {
  521. var result = originalImage;
  522. // Run the enhancers sequentially in order of priority
  523. foreach (var enhancer in imageEnhancers)
  524. {
  525. var typeName = enhancer.GetType().Name;
  526. try
  527. {
  528. result = await enhancer.EnhanceImageAsync(item, result, imageType, imageIndex).ConfigureAwait(false);
  529. }
  530. catch (Exception ex)
  531. {
  532. _logger.ErrorException("{0} failed enhancing {1}", ex, typeName, item.Name);
  533. throw;
  534. }
  535. }
  536. return result;
  537. }
  538. /// <summary>
  539. /// The _semaphoreLocks
  540. /// </summary>
  541. private readonly ConcurrentDictionary<string, object> _locks = new ConcurrentDictionary<string, object>();
  542. /// <summary>
  543. /// Gets the lock.
  544. /// </summary>
  545. /// <param name="filename">The filename.</param>
  546. /// <returns>System.Object.</returns>
  547. private object GetObjectLock(string filename)
  548. {
  549. return _locks.GetOrAdd(filename, key => new object());
  550. }
  551. /// <summary>
  552. /// The _semaphoreLocks
  553. /// </summary>
  554. private readonly ConcurrentDictionary<string, SemaphoreSlim> _semaphoreLocks = new ConcurrentDictionary<string, SemaphoreSlim>();
  555. /// <summary>
  556. /// Gets the lock.
  557. /// </summary>
  558. /// <param name="filename">The filename.</param>
  559. /// <returns>System.Object.</returns>
  560. private SemaphoreSlim GetLock(string filename)
  561. {
  562. return _semaphoreLocks.GetOrAdd(filename, key => new SemaphoreSlim(1, 1));
  563. }
  564. /// <summary>
  565. /// Gets the cache path.
  566. /// </summary>
  567. /// <param name="path">The path.</param>
  568. /// <param name="uniqueName">Name of the unique.</param>
  569. /// <param name="fileExtension">The file extension.</param>
  570. /// <returns>System.String.</returns>
  571. /// <exception cref="System.ArgumentNullException">
  572. /// path
  573. /// or
  574. /// uniqueName
  575. /// or
  576. /// fileExtension
  577. /// </exception>
  578. public string GetCachePath(string path, string uniqueName, string fileExtension)
  579. {
  580. if (string.IsNullOrEmpty(path))
  581. {
  582. throw new ArgumentNullException("path");
  583. }
  584. if (string.IsNullOrEmpty(uniqueName))
  585. {
  586. throw new ArgumentNullException("uniqueName");
  587. }
  588. if (string.IsNullOrEmpty(fileExtension))
  589. {
  590. throw new ArgumentNullException("fileExtension");
  591. }
  592. var filename = uniqueName.GetMD5() + fileExtension;
  593. return GetCachePath(path, filename);
  594. }
  595. /// <summary>
  596. /// Gets the cache path.
  597. /// </summary>
  598. /// <param name="path">The path.</param>
  599. /// <param name="filename">The filename.</param>
  600. /// <returns>System.String.</returns>
  601. /// <exception cref="System.ArgumentNullException">
  602. /// path
  603. /// or
  604. /// filename
  605. /// </exception>
  606. public string GetCachePath(string path, string filename)
  607. {
  608. if (string.IsNullOrEmpty(path))
  609. {
  610. throw new ArgumentNullException("path");
  611. }
  612. if (string.IsNullOrEmpty(filename))
  613. {
  614. throw new ArgumentNullException("filename");
  615. }
  616. var prefix = filename.Substring(0, 1);
  617. path = Path.Combine(path, prefix);
  618. return Path.Combine(path, filename);
  619. }
  620. public IEnumerable<IImageEnhancer> GetSupportedEnhancers(BaseItem item, ImageType imageType)
  621. {
  622. return ImageEnhancers.Where(i =>
  623. {
  624. try
  625. {
  626. return i.Supports(item as BaseItem, imageType);
  627. }
  628. catch (Exception ex)
  629. {
  630. _logger.ErrorException("Error in image enhancer: {0}", ex, i.GetType().Name);
  631. return false;
  632. }
  633. }).ToList();
  634. }
  635. }
  636. }