ImageProcessor.cs 31 KB

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