ImageProcessor.cs 34 KB

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