ImageProcessor.cs 33 KB

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