ImageProcessor.cs 33 KB

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