ImageProcessor.cs 29 KB

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