ImageProcessor.cs 33 KB

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