ImageProcessor.cs 34 KB

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