2
0

ImageProcessor.cs 33 KB

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