SkiaEncoder.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.IO;
  5. using BlurHashSharp.SkiaSharp;
  6. using Diacritics.Extensions;
  7. using MediaBrowser.Common.Configuration;
  8. using MediaBrowser.Common.Extensions;
  9. using MediaBrowser.Controller.Drawing;
  10. using MediaBrowser.Model.Drawing;
  11. using Microsoft.Extensions.Logging;
  12. using SkiaSharp;
  13. using static Jellyfin.Drawing.Skia.SkiaHelper;
  14. namespace Jellyfin.Drawing.Skia
  15. {
  16. /// <summary>
  17. /// Image encoder that uses <see cref="SkiaSharp"/> to manipulate images.
  18. /// </summary>
  19. public class SkiaEncoder : IImageEncoder
  20. {
  21. private static readonly HashSet<string> _transparentImageTypes
  22. = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { ".png", ".gif", ".webp" };
  23. private readonly ILogger<SkiaEncoder> _logger;
  24. private readonly IApplicationPaths _appPaths;
  25. /// <summary>
  26. /// Initializes a new instance of the <see cref="SkiaEncoder"/> class.
  27. /// </summary>
  28. /// <param name="logger">The application logger.</param>
  29. /// <param name="appPaths">The application paths.</param>
  30. public SkiaEncoder(ILogger<SkiaEncoder> logger, IApplicationPaths appPaths)
  31. {
  32. _logger = logger;
  33. _appPaths = appPaths;
  34. }
  35. /// <inheritdoc/>
  36. public string Name => "Skia";
  37. /// <inheritdoc/>
  38. public bool SupportsImageCollageCreation => true;
  39. /// <inheritdoc/>
  40. public bool SupportsImageEncoding => true;
  41. /// <inheritdoc/>
  42. public IReadOnlyCollection<string> SupportedInputFormats =>
  43. new HashSet<string>(StringComparer.OrdinalIgnoreCase)
  44. {
  45. "jpeg",
  46. "jpg",
  47. "png",
  48. "dng",
  49. "webp",
  50. "gif",
  51. "bmp",
  52. "ico",
  53. "astc",
  54. "ktx",
  55. "pkm",
  56. "wbmp",
  57. // TODO: check if these are supported on multiple platforms
  58. // https://github.com/google/skia/blob/master/infra/bots/recipes/test.py#L454
  59. // working on windows at least
  60. "cr2",
  61. "nef",
  62. "arw"
  63. };
  64. /// <inheritdoc/>
  65. public IReadOnlyCollection<ImageFormat> SupportedOutputFormats
  66. => new HashSet<ImageFormat>() { ImageFormat.Webp, ImageFormat.Jpg, ImageFormat.Png };
  67. /// <summary>
  68. /// Check if the native lib is available.
  69. /// </summary>
  70. /// <returns>True if the native lib is available, otherwise false.</returns>
  71. public static bool IsNativeLibAvailable()
  72. {
  73. try
  74. {
  75. // test an operation that requires the native library
  76. SKPMColor.PreMultiply(SKColors.Black);
  77. return true;
  78. }
  79. catch (Exception)
  80. {
  81. return false;
  82. }
  83. }
  84. /// <summary>
  85. /// Convert a <see cref="ImageFormat"/> to a <see cref="SKEncodedImageFormat"/>.
  86. /// </summary>
  87. /// <param name="selectedFormat">The format to convert.</param>
  88. /// <returns>The converted format.</returns>
  89. public static SKEncodedImageFormat GetImageFormat(ImageFormat selectedFormat)
  90. {
  91. return selectedFormat switch
  92. {
  93. ImageFormat.Bmp => SKEncodedImageFormat.Bmp,
  94. ImageFormat.Jpg => SKEncodedImageFormat.Jpeg,
  95. ImageFormat.Gif => SKEncodedImageFormat.Gif,
  96. ImageFormat.Webp => SKEncodedImageFormat.Webp,
  97. _ => SKEncodedImageFormat.Png
  98. };
  99. }
  100. /// <inheritdoc />
  101. /// <exception cref="ArgumentNullException">The path is null.</exception>
  102. /// <exception cref="FileNotFoundException">The path is not valid.</exception>
  103. /// <exception cref="SkiaCodecException">The file at the specified path could not be used to generate a codec.</exception>
  104. public ImageDimensions GetImageSize(string path)
  105. {
  106. if (!File.Exists(path))
  107. {
  108. throw new FileNotFoundException("File not found", path);
  109. }
  110. using var codec = SKCodec.Create(path, out SKCodecResult result);
  111. EnsureSuccess(result);
  112. var info = codec.Info;
  113. return new ImageDimensions(info.Width, info.Height);
  114. }
  115. /// <inheritdoc />
  116. /// <exception cref="ArgumentNullException">The path is null.</exception>
  117. /// <exception cref="FileNotFoundException">The path is not valid.</exception>
  118. /// <exception cref="SkiaCodecException">The file at the specified path could not be used to generate a codec.</exception>
  119. public string GetImageBlurHash(int xComp, int yComp, string path)
  120. {
  121. if (path == null)
  122. {
  123. throw new ArgumentNullException(nameof(path));
  124. }
  125. // Any larger than 128x128 is too slow and there's no visually discernible difference
  126. return BlurHashEncoder.Encode(xComp, yComp, path, 128, 128);
  127. }
  128. private bool RequiresSpecialCharacterHack(string path)
  129. {
  130. for (int i = 0; i < path.Length; i++)
  131. {
  132. if (char.GetUnicodeCategory(path[i]) == UnicodeCategory.OtherLetter)
  133. {
  134. return true;
  135. }
  136. }
  137. return path.HasDiacritics();
  138. }
  139. private string NormalizePath(string path)
  140. {
  141. if (!RequiresSpecialCharacterHack(path))
  142. {
  143. return path;
  144. }
  145. var tempPath = Path.Combine(_appPaths.TempDirectory, Guid.NewGuid() + Path.GetExtension(path));
  146. var directory = Path.GetDirectoryName(tempPath) ?? throw new ResourceNotFoundException($"Provided path ({tempPath}) is not valid.");
  147. Directory.CreateDirectory(directory);
  148. File.Copy(path, tempPath, true);
  149. return tempPath;
  150. }
  151. private static SKEncodedOrigin GetSKEncodedOrigin(ImageOrientation? orientation)
  152. {
  153. if (!orientation.HasValue)
  154. {
  155. return SKEncodedOrigin.TopLeft;
  156. }
  157. return orientation.Value switch
  158. {
  159. ImageOrientation.TopRight => SKEncodedOrigin.TopRight,
  160. ImageOrientation.RightTop => SKEncodedOrigin.RightTop,
  161. ImageOrientation.RightBottom => SKEncodedOrigin.RightBottom,
  162. ImageOrientation.LeftTop => SKEncodedOrigin.LeftTop,
  163. ImageOrientation.LeftBottom => SKEncodedOrigin.LeftBottom,
  164. ImageOrientation.BottomRight => SKEncodedOrigin.BottomRight,
  165. ImageOrientation.BottomLeft => SKEncodedOrigin.BottomLeft,
  166. _ => SKEncodedOrigin.TopLeft
  167. };
  168. }
  169. /// <summary>
  170. /// Decode an image.
  171. /// </summary>
  172. /// <param name="path">The filepath of the image to decode.</param>
  173. /// <param name="forceCleanBitmap">Whether to force clean the bitmap.</param>
  174. /// <param name="orientation">The orientation of the image.</param>
  175. /// <param name="origin">The detected origin of the image.</param>
  176. /// <returns>The resulting bitmap of the image.</returns>
  177. internal SKBitmap? Decode(string path, bool forceCleanBitmap, ImageOrientation? orientation, out SKEncodedOrigin origin)
  178. {
  179. if (!File.Exists(path))
  180. {
  181. throw new FileNotFoundException("File not found", path);
  182. }
  183. var requiresTransparencyHack = _transparentImageTypes.Contains(Path.GetExtension(path));
  184. if (requiresTransparencyHack || forceCleanBitmap)
  185. {
  186. using SKCodec codec = SKCodec.Create(NormalizePath(path), out SKCodecResult res);
  187. if (res != SKCodecResult.Success)
  188. {
  189. origin = GetSKEncodedOrigin(orientation);
  190. return null;
  191. }
  192. // create the bitmap
  193. var bitmap = new SKBitmap(codec.Info.Width, codec.Info.Height, !requiresTransparencyHack);
  194. // decode
  195. _ = codec.GetPixels(bitmap.Info, bitmap.GetPixels());
  196. origin = codec.EncodedOrigin;
  197. return bitmap;
  198. }
  199. var resultBitmap = SKBitmap.Decode(NormalizePath(path));
  200. if (resultBitmap == null)
  201. {
  202. return Decode(path, true, orientation, out origin);
  203. }
  204. // If we have to resize these they often end up distorted
  205. if (resultBitmap.ColorType == SKColorType.Gray8)
  206. {
  207. using (resultBitmap)
  208. {
  209. return Decode(path, true, orientation, out origin);
  210. }
  211. }
  212. origin = SKEncodedOrigin.TopLeft;
  213. return resultBitmap;
  214. }
  215. private SKBitmap? GetBitmap(string path, bool autoOrient, ImageOrientation? orientation)
  216. {
  217. if (autoOrient)
  218. {
  219. var bitmap = Decode(path, true, orientation, out var origin);
  220. if (bitmap != null && origin != SKEncodedOrigin.TopLeft)
  221. {
  222. using (bitmap)
  223. {
  224. return OrientImage(bitmap, origin);
  225. }
  226. }
  227. return bitmap;
  228. }
  229. return Decode(path, false, orientation, out _);
  230. }
  231. private SKBitmap OrientImage(SKBitmap bitmap, SKEncodedOrigin origin)
  232. {
  233. var needsFlip = origin == SKEncodedOrigin.LeftBottom
  234. || origin == SKEncodedOrigin.LeftTop
  235. || origin == SKEncodedOrigin.RightBottom
  236. || origin == SKEncodedOrigin.RightTop;
  237. var rotated = needsFlip
  238. ? new SKBitmap(bitmap.Height, bitmap.Width)
  239. : new SKBitmap(bitmap.Width, bitmap.Height);
  240. using var surface = new SKCanvas(rotated);
  241. var midX = (float)rotated.Width / 2;
  242. var midY = (float)rotated.Height / 2;
  243. switch (origin)
  244. {
  245. case SKEncodedOrigin.TopRight:
  246. surface.Scale(-1, 1, midX, midY);
  247. break;
  248. case SKEncodedOrigin.BottomRight:
  249. surface.RotateDegrees(180, midX, midY);
  250. break;
  251. case SKEncodedOrigin.BottomLeft:
  252. surface.Scale(1, -1, midX, midY);
  253. break;
  254. case SKEncodedOrigin.LeftTop:
  255. surface.Translate(0, -rotated.Height);
  256. surface.Scale(1, -1, midX, midY);
  257. surface.RotateDegrees(-90);
  258. break;
  259. case SKEncodedOrigin.RightTop:
  260. surface.Translate(rotated.Width, 0);
  261. surface.RotateDegrees(90);
  262. break;
  263. case SKEncodedOrigin.RightBottom:
  264. surface.Translate(rotated.Width, 0);
  265. surface.Scale(1, -1, midX, midY);
  266. surface.RotateDegrees(90);
  267. break;
  268. case SKEncodedOrigin.LeftBottom:
  269. surface.Translate(0, rotated.Height);
  270. surface.RotateDegrees(-90);
  271. break;
  272. }
  273. surface.DrawBitmap(bitmap, 0, 0);
  274. return rotated;
  275. }
  276. /// <summary>
  277. /// Resizes an image on the CPU, by utilizing a surface and canvas.
  278. ///
  279. /// The convolutional matrix kernel used in this resize function gives a (light) sharpening effect.
  280. /// This technique is similar to effect that can be created using for example the [Convolution matrix filter in GIMP](https://docs.gimp.org/2.10/en/gimp-filter-convolution-matrix.html).
  281. /// </summary>
  282. /// <param name="source">The source bitmap.</param>
  283. /// <param name="targetInfo">This specifies the target size and other information required to create the surface.</param>
  284. /// <param name="isAntialias">This enables anti-aliasing on the SKPaint instance.</param>
  285. /// <param name="isDither">This enables dithering on the SKPaint instance.</param>
  286. /// <returns>The resized image.</returns>
  287. internal static SKImage ResizeImage(SKBitmap source, SKImageInfo targetInfo, bool isAntialias = false, bool isDither = false)
  288. {
  289. using var surface = SKSurface.Create(targetInfo);
  290. using var canvas = surface.Canvas;
  291. using var paint = new SKPaint
  292. {
  293. FilterQuality = SKFilterQuality.High,
  294. IsAntialias = isAntialias,
  295. IsDither = isDither
  296. };
  297. var kernel = new float[9]
  298. {
  299. 0, -.1f, 0,
  300. -.1f, 1.4f, -.1f,
  301. 0, -.1f, 0,
  302. };
  303. var kernelSize = new SKSizeI(3, 3);
  304. var kernelOffset = new SKPointI(1, 1);
  305. paint.ImageFilter = SKImageFilter.CreateMatrixConvolution(
  306. kernelSize,
  307. kernel,
  308. 1f,
  309. 0f,
  310. kernelOffset,
  311. SKShaderTileMode.Clamp,
  312. true);
  313. canvas.DrawBitmap(
  314. source,
  315. SKRect.Create(0, 0, source.Width, source.Height),
  316. SKRect.Create(0, 0, targetInfo.Width, targetInfo.Height),
  317. paint);
  318. return surface.Snapshot();
  319. }
  320. /// <inheritdoc/>
  321. public string EncodeImage(string inputPath, DateTime dateModified, string outputPath, bool autoOrient, ImageOrientation? orientation, int quality, ImageProcessingOptions options, ImageFormat outputFormat)
  322. {
  323. if (inputPath.Length == 0)
  324. {
  325. throw new ArgumentException("String can't be empty.", nameof(inputPath));
  326. }
  327. if (outputPath.Length == 0)
  328. {
  329. throw new ArgumentException("String can't be empty.", nameof(outputPath));
  330. }
  331. var skiaOutputFormat = GetImageFormat(outputFormat);
  332. var hasBackgroundColor = !string.IsNullOrWhiteSpace(options.BackgroundColor);
  333. var hasForegroundColor = !string.IsNullOrWhiteSpace(options.ForegroundLayer);
  334. var blur = options.Blur ?? 0;
  335. var hasIndicator = options.AddPlayedIndicator || options.UnplayedCount.HasValue || !options.PercentPlayed.Equals(0);
  336. using var bitmap = GetBitmap(inputPath, autoOrient, orientation);
  337. if (bitmap == null)
  338. {
  339. throw new InvalidDataException($"Skia unable to read image {inputPath}");
  340. }
  341. var originalImageSize = new ImageDimensions(bitmap.Width, bitmap.Height);
  342. if (options.HasDefaultOptions(inputPath, originalImageSize) && !autoOrient)
  343. {
  344. // Just spit out the original file if all the options are default
  345. return inputPath;
  346. }
  347. var newImageSize = ImageHelper.GetNewImageSize(options, originalImageSize);
  348. var width = newImageSize.Width;
  349. var height = newImageSize.Height;
  350. // scale image (the FromImage creates a copy)
  351. var imageInfo = new SKImageInfo(width, height, bitmap.ColorType, bitmap.AlphaType, bitmap.ColorSpace);
  352. using var resizedBitmap = SKBitmap.FromImage(ResizeImage(bitmap, imageInfo));
  353. // If all we're doing is resizing then we can stop now
  354. if (!hasBackgroundColor && !hasForegroundColor && blur == 0 && !hasIndicator)
  355. {
  356. var outputDirectory = Path.GetDirectoryName(outputPath) ?? throw new ArgumentException($"Provided path ({outputPath}) is not valid.", nameof(outputPath));
  357. Directory.CreateDirectory(outputDirectory);
  358. using var outputStream = new SKFileWStream(outputPath);
  359. using var pixmap = new SKPixmap(new SKImageInfo(width, height), resizedBitmap.GetPixels());
  360. resizedBitmap.Encode(outputStream, skiaOutputFormat, quality);
  361. return outputPath;
  362. }
  363. // create bitmap to use for canvas drawing used to draw into bitmap
  364. using var saveBitmap = new SKBitmap(width, height);
  365. using var canvas = new SKCanvas(saveBitmap);
  366. // set background color if present
  367. if (hasBackgroundColor)
  368. {
  369. canvas.Clear(SKColor.Parse(options.BackgroundColor));
  370. }
  371. // Add blur if option is present
  372. if (blur > 0)
  373. {
  374. // create image from resized bitmap to apply blur
  375. using var paint = new SKPaint();
  376. using var filter = SKImageFilter.CreateBlur(blur, blur);
  377. paint.ImageFilter = filter;
  378. canvas.DrawBitmap(resizedBitmap, SKRect.Create(width, height), paint);
  379. }
  380. else
  381. {
  382. // draw resized bitmap onto canvas
  383. canvas.DrawBitmap(resizedBitmap, SKRect.Create(width, height));
  384. }
  385. // If foreground layer present then draw
  386. if (hasForegroundColor)
  387. {
  388. if (!double.TryParse(options.ForegroundLayer, out double opacity))
  389. {
  390. opacity = .4;
  391. }
  392. canvas.DrawColor(new SKColor(0, 0, 0, (byte)((1 - opacity) * 0xFF)), SKBlendMode.SrcOver);
  393. }
  394. if (hasIndicator)
  395. {
  396. DrawIndicator(canvas, width, height, options);
  397. }
  398. var directory = Path.GetDirectoryName(outputPath) ?? throw new ArgumentException($"Provided path ({outputPath}) is not valid.", nameof(outputPath));
  399. Directory.CreateDirectory(directory);
  400. using (var outputStream = new SKFileWStream(outputPath))
  401. {
  402. using (var pixmap = new SKPixmap(new SKImageInfo(width, height), saveBitmap.GetPixels()))
  403. {
  404. pixmap.Encode(outputStream, skiaOutputFormat, quality);
  405. }
  406. }
  407. return outputPath;
  408. }
  409. /// <inheritdoc/>
  410. public void CreateImageCollage(ImageCollageOptions options, string? libraryName)
  411. {
  412. double ratio = (double)options.Width / options.Height;
  413. if (ratio >= 1.4)
  414. {
  415. new StripCollageBuilder(this).BuildThumbCollage(options.InputPaths, options.OutputPath, options.Width, options.Height, libraryName);
  416. }
  417. else if (ratio >= .9)
  418. {
  419. new StripCollageBuilder(this).BuildSquareCollage(options.InputPaths, options.OutputPath, options.Width, options.Height);
  420. }
  421. else
  422. {
  423. // TODO: Create Poster collage capability
  424. new StripCollageBuilder(this).BuildSquareCollage(options.InputPaths, options.OutputPath, options.Width, options.Height);
  425. }
  426. }
  427. private void DrawIndicator(SKCanvas canvas, int imageWidth, int imageHeight, ImageProcessingOptions options)
  428. {
  429. try
  430. {
  431. var currentImageSize = new ImageDimensions(imageWidth, imageHeight);
  432. if (options.AddPlayedIndicator)
  433. {
  434. PlayedIndicatorDrawer.DrawPlayedIndicator(canvas, currentImageSize);
  435. }
  436. else if (options.UnplayedCount.HasValue)
  437. {
  438. UnplayedCountIndicator.DrawUnplayedCountIndicator(canvas, currentImageSize, options.UnplayedCount.Value);
  439. }
  440. if (options.PercentPlayed > 0)
  441. {
  442. PercentPlayedDrawer.Process(canvas, currentImageSize, options.PercentPlayed);
  443. }
  444. }
  445. catch (Exception ex)
  446. {
  447. _logger.LogError(ex, "Error drawing indicator overlay");
  448. }
  449. }
  450. }
  451. }