ImageProcessor.cs 33 KB

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