ImageProcessor.cs 33 KB

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