ImageProcessor.cs 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773
  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, options.Indicator);
  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. DrawIndicator(thumbnailGraph, newWidth, newHeight, options.Indicator);
  151. var outputFormat = GetOutputFormat(originalImage, options.OutputFormat);
  152. using (var outputMemoryStream = new MemoryStream())
  153. {
  154. // Save to the memory stream
  155. thumbnail.Save(outputFormat, outputMemoryStream, quality);
  156. var bytes = outputMemoryStream.ToArray();
  157. var outputTask = toStream.WriteAsync(bytes, 0, bytes.Length);
  158. // kick off a task to cache the result
  159. var cacheTask = CacheResizedImage(cacheFilePath, bytes);
  160. await Task.WhenAll(outputTask, cacheTask).ConfigureAwait(false);
  161. }
  162. }
  163. }
  164. }
  165. }
  166. }
  167. }
  168. finally
  169. {
  170. semaphore.Release();
  171. }
  172. }
  173. private WatchedIndicatorDrawer _watchedDrawer;
  174. private void DrawIndicator(Graphics graphics, int imageWidth, int imageHeight, ImageOverlay indicator)
  175. {
  176. if (indicator == ImageOverlay.Watched)
  177. {
  178. _watchedDrawer = _watchedDrawer ?? (_watchedDrawer = new WatchedIndicatorDrawer());
  179. var currentImageSize = new Size(imageWidth, imageHeight);
  180. _watchedDrawer.Process(graphics, currentImageSize);
  181. }
  182. }
  183. /// <summary>
  184. /// Gets the output format.
  185. /// </summary>
  186. /// <param name="image">The image.</param>
  187. /// <param name="outputFormat">The output format.</param>
  188. /// <returns>ImageFormat.</returns>
  189. private ImageFormat GetOutputFormat(Image image, ImageOutputFormat outputFormat)
  190. {
  191. switch (outputFormat)
  192. {
  193. case ImageOutputFormat.Bmp:
  194. return ImageFormat.Bmp;
  195. case ImageOutputFormat.Gif:
  196. return ImageFormat.Gif;
  197. case ImageOutputFormat.Jpg:
  198. return ImageFormat.Jpeg;
  199. case ImageOutputFormat.Png:
  200. return ImageFormat.Png;
  201. default:
  202. return image.RawFormat;
  203. }
  204. }
  205. /// <summary>
  206. /// Crops whitespace from an image, caches the result, and returns the cached path
  207. /// </summary>
  208. /// <param name="originalImagePath">The original image path.</param>
  209. /// <param name="dateModified">The date modified.</param>
  210. /// <returns>System.String.</returns>
  211. private async Task<string> GetWhitespaceCroppedImage(string originalImagePath, DateTime dateModified)
  212. {
  213. var name = originalImagePath;
  214. name += "datemodified=" + dateModified.Ticks;
  215. var croppedImagePath = GetCachePath(_croppedWhitespaceImageCachePath, name, Path.GetExtension(originalImagePath));
  216. var semaphore = GetLock(croppedImagePath);
  217. await semaphore.WaitAsync().ConfigureAwait(false);
  218. // Check again in case of contention
  219. if (File.Exists(croppedImagePath))
  220. {
  221. semaphore.Release();
  222. return croppedImagePath;
  223. }
  224. try
  225. {
  226. using (var fileStream = new FileStream(originalImagePath, FileMode.Open, FileAccess.Read, FileShare.Read, StreamDefaults.DefaultFileStreamBufferSize, true))
  227. {
  228. // Copy to memory stream to avoid Image locking file
  229. using (var memoryStream = new MemoryStream())
  230. {
  231. await fileStream.CopyToAsync(memoryStream).ConfigureAwait(false);
  232. using (var originalImage = (Bitmap)Image.FromStream(memoryStream, true, false))
  233. {
  234. var outputFormat = originalImage.RawFormat;
  235. using (var croppedImage = originalImage.CropWhitespace())
  236. {
  237. var parentPath = Path.GetDirectoryName(croppedImagePath);
  238. if (!Directory.Exists(parentPath))
  239. {
  240. Directory.CreateDirectory(parentPath);
  241. }
  242. using (var outputStream = new FileStream(croppedImagePath, FileMode.Create, FileAccess.Write, FileShare.Read))
  243. {
  244. croppedImage.Save(outputFormat, outputStream, 100);
  245. }
  246. }
  247. }
  248. }
  249. }
  250. }
  251. catch (Exception ex)
  252. {
  253. // We have to have a catch-all here because some of the .net image methods throw a plain old Exception
  254. _logger.ErrorException("Error cropping image {0}", ex, originalImagePath);
  255. return originalImagePath;
  256. }
  257. finally
  258. {
  259. semaphore.Release();
  260. }
  261. return croppedImagePath;
  262. }
  263. /// <summary>
  264. /// Caches the resized image.
  265. /// </summary>
  266. /// <param name="cacheFilePath">The cache file path.</param>
  267. /// <param name="bytes">The bytes.</param>
  268. private async Task CacheResizedImage(string cacheFilePath, byte[] bytes)
  269. {
  270. var parentPath = Path.GetDirectoryName(cacheFilePath);
  271. if (!Directory.Exists(parentPath))
  272. {
  273. Directory.CreateDirectory(parentPath);
  274. }
  275. // Save to the cache location
  276. using (var cacheFileStream = new FileStream(cacheFilePath, FileMode.Create, FileAccess.Write, FileShare.Read, StreamDefaults.DefaultFileStreamBufferSize, FileOptions.Asynchronous))
  277. {
  278. // Save to the filestream
  279. await cacheFileStream.WriteAsync(bytes, 0, bytes.Length).ConfigureAwait(false);
  280. }
  281. }
  282. /// <summary>
  283. /// Gets the cache file path based on a set of parameters
  284. /// </summary>
  285. private string GetCacheFilePath(string originalPath, ImageSize outputSize, int quality, DateTime dateModified, ImageOutputFormat format, ImageOverlay overlay)
  286. {
  287. var filename = originalPath;
  288. filename += "width=" + outputSize.Width;
  289. filename += "height=" + outputSize.Height;
  290. filename += "quality=" + quality;
  291. filename += "datemodified=" + dateModified.Ticks;
  292. if (format != ImageOutputFormat.Original)
  293. {
  294. filename += "format=" + format;
  295. }
  296. if (overlay != ImageOverlay.None)
  297. {
  298. filename += "overlay=" + overlay;
  299. }
  300. return GetCachePath(_resizedImageCachePath, filename, Path.GetExtension(originalPath));
  301. }
  302. /// <summary>
  303. /// Gets the size of the image.
  304. /// </summary>
  305. /// <param name="path">The path.</param>
  306. /// <returns>ImageSize.</returns>
  307. public ImageSize GetImageSize(string path)
  308. {
  309. return GetImageSize(path, File.GetLastWriteTimeUtc(path));
  310. }
  311. /// <summary>
  312. /// Gets the size of the image.
  313. /// </summary>
  314. /// <param name="path">The path.</param>
  315. /// <param name="imageDateModified">The image date modified.</param>
  316. /// <returns>ImageSize.</returns>
  317. /// <exception cref="System.ArgumentNullException">path</exception>
  318. public ImageSize GetImageSize(string path, DateTime imageDateModified)
  319. {
  320. if (string.IsNullOrEmpty(path))
  321. {
  322. throw new ArgumentNullException("path");
  323. }
  324. var name = path + "datemodified=" + imageDateModified.Ticks;
  325. ImageSize size;
  326. if (!_cachedImagedSizes.TryGetValue(name, out size))
  327. {
  328. size = GetImageSizeInternal(name, path);
  329. _cachedImagedSizes.AddOrUpdate(name, size, (keyName, oldValue) => size);
  330. }
  331. return size;
  332. }
  333. /// <summary>
  334. /// Gets the image size internal.
  335. /// </summary>
  336. /// <param name="cacheKey">The cache key.</param>
  337. /// <param name="path">The path.</param>
  338. /// <returns>ImageSize.</returns>
  339. private ImageSize GetImageSizeInternal(string cacheKey, string path)
  340. {
  341. // Now check the file system cache
  342. var fullCachePath = GetCachePath(_imageSizeCachePath, cacheKey, ".txt");
  343. try
  344. {
  345. var result = File.ReadAllText(fullCachePath).Split('|').Select(i => double.Parse(i, UsCulture)).ToArray();
  346. return new ImageSize { Width = result[0], Height = result[1] };
  347. }
  348. catch (IOException)
  349. {
  350. // Cache file doesn't exist or is currently being written to
  351. }
  352. var syncLock = GetObjectLock(fullCachePath);
  353. lock (syncLock)
  354. {
  355. try
  356. {
  357. var result = File.ReadAllText(fullCachePath)
  358. .Split('|')
  359. .Select(i => double.Parse(i, UsCulture))
  360. .ToArray();
  361. return new ImageSize { Width = result[0], Height = result[1] };
  362. }
  363. catch (FileNotFoundException)
  364. {
  365. // Cache file doesn't exist no biggie
  366. }
  367. catch (DirectoryNotFoundException)
  368. {
  369. // Cache file doesn't exist no biggie
  370. }
  371. var size = ImageHeader.GetDimensions(path, _logger);
  372. var parentPath = Path.GetDirectoryName(fullCachePath);
  373. if (!Directory.Exists(parentPath))
  374. {
  375. Directory.CreateDirectory(parentPath);
  376. }
  377. // Update the file system cache
  378. File.WriteAllText(fullCachePath, size.Width.ToString(UsCulture) + @"|" + size.Height.ToString(UsCulture));
  379. return new ImageSize { Width = size.Width, Height = size.Height };
  380. }
  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="imagePath">The image path.</param>
  388. /// <returns>Guid.</returns>
  389. /// <exception cref="System.ArgumentNullException">item</exception>
  390. public Guid GetImageCacheTag(BaseItem item, ImageType imageType, string imagePath)
  391. {
  392. if (item == null)
  393. {
  394. throw new ArgumentNullException("item");
  395. }
  396. if (string.IsNullOrEmpty(imagePath))
  397. {
  398. throw new ArgumentNullException("imagePath");
  399. }
  400. var dateModified = item.GetImageDateModified(imagePath);
  401. var supportedEnhancers = GetSupportedEnhancers(item, imageType);
  402. return GetImageCacheTag(item, imageType, imagePath, dateModified, supportedEnhancers);
  403. }
  404. /// <summary>
  405. /// Gets the image cache tag.
  406. /// </summary>
  407. /// <param name="item">The item.</param>
  408. /// <param name="imageType">Type of the image.</param>
  409. /// <param name="originalImagePath">The original image path.</param>
  410. /// <param name="dateModified">The date modified of the original image file.</param>
  411. /// <param name="imageEnhancers">The image enhancers.</param>
  412. /// <returns>Guid.</returns>
  413. /// <exception cref="System.ArgumentNullException">item</exception>
  414. public Guid GetImageCacheTag(BaseItem item, ImageType imageType, string originalImagePath, DateTime dateModified, IEnumerable<IImageEnhancer> imageEnhancers)
  415. {
  416. if (item == null)
  417. {
  418. throw new ArgumentNullException("item");
  419. }
  420. if (imageEnhancers == null)
  421. {
  422. throw new ArgumentNullException("imageEnhancers");
  423. }
  424. if (string.IsNullOrEmpty(originalImagePath))
  425. {
  426. throw new ArgumentNullException("originalImagePath");
  427. }
  428. // Cache name is created with supported enhancers combined with the last config change so we pick up new config changes
  429. var cacheKeys = imageEnhancers.Select(i => i.GetConfigurationCacheKey(item, imageType)).ToList();
  430. cacheKeys.Add(originalImagePath + dateModified.Ticks);
  431. return string.Join("|", cacheKeys.ToArray()).GetMD5();
  432. }
  433. private async Task<Tuple<string, DateTime>> GetEnhancedImage(string originalImagePath, DateTime dateModified, BaseItem item,
  434. ImageType imageType, int imageIndex,
  435. List<IImageEnhancer> enhancers)
  436. {
  437. try
  438. {
  439. // Enhance if we have enhancers
  440. var ehnancedImagePath = await GetEnhancedImageInternal(originalImagePath, dateModified, item, imageType, imageIndex, enhancers).ConfigureAwait(false);
  441. // If the path changed update dateModified
  442. if (!ehnancedImagePath.Equals(originalImagePath, StringComparison.OrdinalIgnoreCase))
  443. {
  444. dateModified = File.GetLastWriteTimeUtc(ehnancedImagePath);
  445. return new Tuple<string, DateTime>(ehnancedImagePath, dateModified);
  446. }
  447. }
  448. catch (Exception ex)
  449. {
  450. _logger.Error("Error enhancing image", ex);
  451. }
  452. return new Tuple<string, DateTime>(originalImagePath, dateModified);
  453. }
  454. /// <summary>
  455. /// Runs an image through the image enhancers, caches the result, and returns the cached path
  456. /// </summary>
  457. /// <param name="originalImagePath">The original image path.</param>
  458. /// <param name="dateModified">The date modified of the original image file.</param>
  459. /// <param name="item">The item.</param>
  460. /// <param name="imageType">Type of the image.</param>
  461. /// <param name="imageIndex">Index of the image.</param>
  462. /// <param name="supportedEnhancers">The supported enhancers.</param>
  463. /// <returns>System.String.</returns>
  464. /// <exception cref="System.ArgumentNullException">originalImagePath</exception>
  465. private async Task<string> GetEnhancedImageInternal(string originalImagePath, DateTime dateModified, BaseItem item, ImageType imageType, int imageIndex, List<IImageEnhancer> supportedEnhancers)
  466. {
  467. if (string.IsNullOrEmpty(originalImagePath))
  468. {
  469. throw new ArgumentNullException("originalImagePath");
  470. }
  471. if (item == null)
  472. {
  473. throw new ArgumentNullException("item");
  474. }
  475. var cacheGuid = GetImageCacheTag(item, imageType, originalImagePath, dateModified, supportedEnhancers);
  476. // All enhanced images are saved as png to allow transparency
  477. var enhancedImagePath = GetCachePath(_enhancedImageCachePath, cacheGuid + ".png");
  478. var semaphore = GetLock(enhancedImagePath);
  479. await semaphore.WaitAsync().ConfigureAwait(false);
  480. // Check again in case of contention
  481. if (File.Exists(enhancedImagePath))
  482. {
  483. semaphore.Release();
  484. return enhancedImagePath;
  485. }
  486. try
  487. {
  488. using (var fileStream = new FileStream(originalImagePath, FileMode.Open, FileAccess.Read, FileShare.Read, StreamDefaults.DefaultFileStreamBufferSize, true))
  489. {
  490. // Copy to memory stream to avoid Image locking file
  491. using (var memoryStream = new MemoryStream())
  492. {
  493. await fileStream.CopyToAsync(memoryStream).ConfigureAwait(false);
  494. using (var originalImage = Image.FromStream(memoryStream, true, false))
  495. {
  496. //Pass the image through registered enhancers
  497. using (var newImage = await ExecuteImageEnhancers(supportedEnhancers, originalImage, item, imageType, imageIndex).ConfigureAwait(false))
  498. {
  499. var parentDirectory = Path.GetDirectoryName(enhancedImagePath);
  500. if (!Directory.Exists(parentDirectory))
  501. {
  502. Directory.CreateDirectory(parentDirectory);
  503. }
  504. //And then save it in the cache
  505. using (var outputStream = new FileStream(enhancedImagePath, FileMode.Create, FileAccess.Write, FileShare.Read))
  506. {
  507. newImage.Save(ImageFormat.Png, outputStream, 100);
  508. }
  509. }
  510. }
  511. }
  512. }
  513. }
  514. finally
  515. {
  516. semaphore.Release();
  517. }
  518. return enhancedImagePath;
  519. }
  520. /// <summary>
  521. /// Executes the image enhancers.
  522. /// </summary>
  523. /// <param name="imageEnhancers">The image enhancers.</param>
  524. /// <param name="originalImage">The original image.</param>
  525. /// <param name="item">The item.</param>
  526. /// <param name="imageType">Type of the image.</param>
  527. /// <param name="imageIndex">Index of the image.</param>
  528. /// <returns>Task{EnhancedImage}.</returns>
  529. private async Task<Image> ExecuteImageEnhancers(IEnumerable<IImageEnhancer> imageEnhancers, Image originalImage, BaseItem item, ImageType imageType, int imageIndex)
  530. {
  531. var result = originalImage;
  532. // Run the enhancers sequentially in order of priority
  533. foreach (var enhancer in imageEnhancers)
  534. {
  535. var typeName = enhancer.GetType().Name;
  536. try
  537. {
  538. result = await enhancer.EnhanceImageAsync(item, result, imageType, imageIndex).ConfigureAwait(false);
  539. }
  540. catch (Exception ex)
  541. {
  542. _logger.ErrorException("{0} failed enhancing {1}", ex, typeName, item.Name);
  543. throw;
  544. }
  545. }
  546. return result;
  547. }
  548. /// <summary>
  549. /// The _semaphoreLocks
  550. /// </summary>
  551. private readonly ConcurrentDictionary<string, object> _locks = new ConcurrentDictionary<string, object>();
  552. /// <summary>
  553. /// Gets the lock.
  554. /// </summary>
  555. /// <param name="filename">The filename.</param>
  556. /// <returns>System.Object.</returns>
  557. private object GetObjectLock(string filename)
  558. {
  559. return _locks.GetOrAdd(filename, key => new object());
  560. }
  561. /// <summary>
  562. /// The _semaphoreLocks
  563. /// </summary>
  564. private readonly ConcurrentDictionary<string, SemaphoreSlim> _semaphoreLocks = new ConcurrentDictionary<string, SemaphoreSlim>();
  565. /// <summary>
  566. /// Gets the lock.
  567. /// </summary>
  568. /// <param name="filename">The filename.</param>
  569. /// <returns>System.Object.</returns>
  570. private SemaphoreSlim GetLock(string filename)
  571. {
  572. return _semaphoreLocks.GetOrAdd(filename, key => new SemaphoreSlim(1, 1));
  573. }
  574. /// <summary>
  575. /// Gets the cache path.
  576. /// </summary>
  577. /// <param name="path">The path.</param>
  578. /// <param name="uniqueName">Name of the unique.</param>
  579. /// <param name="fileExtension">The file extension.</param>
  580. /// <returns>System.String.</returns>
  581. /// <exception cref="System.ArgumentNullException">
  582. /// path
  583. /// or
  584. /// uniqueName
  585. /// or
  586. /// fileExtension
  587. /// </exception>
  588. public string GetCachePath(string path, string uniqueName, string fileExtension)
  589. {
  590. if (string.IsNullOrEmpty(path))
  591. {
  592. throw new ArgumentNullException("path");
  593. }
  594. if (string.IsNullOrEmpty(uniqueName))
  595. {
  596. throw new ArgumentNullException("uniqueName");
  597. }
  598. if (string.IsNullOrEmpty(fileExtension))
  599. {
  600. throw new ArgumentNullException("fileExtension");
  601. }
  602. var filename = uniqueName.GetMD5() + fileExtension;
  603. return GetCachePath(path, filename);
  604. }
  605. /// <summary>
  606. /// Gets the cache path.
  607. /// </summary>
  608. /// <param name="path">The path.</param>
  609. /// <param name="filename">The filename.</param>
  610. /// <returns>System.String.</returns>
  611. /// <exception cref="System.ArgumentNullException">
  612. /// path
  613. /// or
  614. /// filename
  615. /// </exception>
  616. public string GetCachePath(string path, string filename)
  617. {
  618. if (string.IsNullOrEmpty(path))
  619. {
  620. throw new ArgumentNullException("path");
  621. }
  622. if (string.IsNullOrEmpty(filename))
  623. {
  624. throw new ArgumentNullException("filename");
  625. }
  626. var prefix = filename.Substring(0, 1);
  627. path = Path.Combine(path, prefix);
  628. return Path.Combine(path, filename);
  629. }
  630. public IEnumerable<IImageEnhancer> GetSupportedEnhancers(BaseItem item, ImageType imageType)
  631. {
  632. return ImageEnhancers.Where(i =>
  633. {
  634. try
  635. {
  636. return i.Supports(item as BaseItem, imageType);
  637. }
  638. catch (Exception ex)
  639. {
  640. _logger.ErrorException("Error in image enhancer: {0}", ex, i.GetType().Name);
  641. return false;
  642. }
  643. }).ToList();
  644. }
  645. }
  646. }