SkiaEncoder.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.IO;
  5. using BlurHashSharp.SkiaSharp;
  6. using MediaBrowser.Common.Configuration;
  7. using MediaBrowser.Common.Extensions;
  8. using MediaBrowser.Controller.Drawing;
  9. using MediaBrowser.Controller.Extensions;
  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 static bool HasDiacritics(string text)
  129. => !string.Equals(text, text.RemoveDiacritics(), StringComparison.Ordinal);
  130. private bool RequiresSpecialCharacterHack(string path)
  131. {
  132. for (int i = 0; i < path.Length; i++)
  133. {
  134. if (char.GetUnicodeCategory(path[i]) == UnicodeCategory.OtherLetter)
  135. {
  136. return true;
  137. }
  138. }
  139. return HasDiacritics(path);
  140. }
  141. private string NormalizePath(string path)
  142. {
  143. if (!RequiresSpecialCharacterHack(path))
  144. {
  145. return path;
  146. }
  147. var tempPath = Path.Combine(_appPaths.TempDirectory, Guid.NewGuid() + Path.GetExtension(path));
  148. var directory = Path.GetDirectoryName(tempPath) ?? throw new ResourceNotFoundException($"Provided path ({tempPath}) is not valid.");
  149. Directory.CreateDirectory(directory);
  150. File.Copy(path, tempPath, true);
  151. return tempPath;
  152. }
  153. private static SKEncodedOrigin GetSKEncodedOrigin(ImageOrientation? orientation)
  154. {
  155. if (!orientation.HasValue)
  156. {
  157. return SKEncodedOrigin.TopLeft;
  158. }
  159. return orientation.Value switch
  160. {
  161. ImageOrientation.TopRight => SKEncodedOrigin.TopRight,
  162. ImageOrientation.RightTop => SKEncodedOrigin.RightTop,
  163. ImageOrientation.RightBottom => SKEncodedOrigin.RightBottom,
  164. ImageOrientation.LeftTop => SKEncodedOrigin.LeftTop,
  165. ImageOrientation.LeftBottom => SKEncodedOrigin.LeftBottom,
  166. ImageOrientation.BottomRight => SKEncodedOrigin.BottomRight,
  167. ImageOrientation.BottomLeft => SKEncodedOrigin.BottomLeft,
  168. _ => SKEncodedOrigin.TopLeft
  169. };
  170. }
  171. /// <summary>
  172. /// Decode an image.
  173. /// </summary>
  174. /// <param name="path">The filepath of the image to decode.</param>
  175. /// <param name="forceCleanBitmap">Whether to force clean the bitmap.</param>
  176. /// <param name="orientation">The orientation of the image.</param>
  177. /// <param name="origin">The detected origin of the image.</param>
  178. /// <returns>The resulting bitmap of the image.</returns>
  179. internal SKBitmap? Decode(string path, bool forceCleanBitmap, ImageOrientation? orientation, out SKEncodedOrigin origin)
  180. {
  181. if (!File.Exists(path))
  182. {
  183. throw new FileNotFoundException("File not found", path);
  184. }
  185. var requiresTransparencyHack = _transparentImageTypes.Contains(Path.GetExtension(path));
  186. if (requiresTransparencyHack || forceCleanBitmap)
  187. {
  188. using SKCodec codec = SKCodec.Create(NormalizePath(path), out SKCodecResult res);
  189. if (res != SKCodecResult.Success)
  190. {
  191. origin = GetSKEncodedOrigin(orientation);
  192. return null;
  193. }
  194. // create the bitmap
  195. var bitmap = new SKBitmap(codec.Info.Width, codec.Info.Height, !requiresTransparencyHack);
  196. // decode
  197. _ = codec.GetPixels(bitmap.Info, bitmap.GetPixels());
  198. origin = codec.EncodedOrigin;
  199. return bitmap;
  200. }
  201. var resultBitmap = SKBitmap.Decode(NormalizePath(path));
  202. if (resultBitmap == null)
  203. {
  204. return Decode(path, true, orientation, out origin);
  205. }
  206. // If we have to resize these they often end up distorted
  207. if (resultBitmap.ColorType == SKColorType.Gray8)
  208. {
  209. using (resultBitmap)
  210. {
  211. return Decode(path, true, orientation, out origin);
  212. }
  213. }
  214. origin = SKEncodedOrigin.TopLeft;
  215. return resultBitmap;
  216. }
  217. private SKBitmap? GetBitmap(string path, bool autoOrient, ImageOrientation? orientation)
  218. {
  219. if (autoOrient)
  220. {
  221. var bitmap = Decode(path, true, orientation, out var origin);
  222. if (bitmap != null && origin != SKEncodedOrigin.TopLeft)
  223. {
  224. using (bitmap)
  225. {
  226. return OrientImage(bitmap, origin);
  227. }
  228. }
  229. return bitmap;
  230. }
  231. return Decode(path, false, orientation, out _);
  232. }
  233. private SKBitmap OrientImage(SKBitmap bitmap, SKEncodedOrigin origin)
  234. {
  235. var needsFlip = origin == SKEncodedOrigin.LeftBottom
  236. || origin == SKEncodedOrigin.LeftTop
  237. || origin == SKEncodedOrigin.RightBottom
  238. || origin == SKEncodedOrigin.RightTop;
  239. var rotated = needsFlip
  240. ? new SKBitmap(bitmap.Height, bitmap.Width)
  241. : new SKBitmap(bitmap.Width, bitmap.Height);
  242. using var surface = new SKCanvas(rotated);
  243. var midX = (float)rotated.Width / 2;
  244. var midY = (float)rotated.Height / 2;
  245. switch (origin)
  246. {
  247. case SKEncodedOrigin.TopRight:
  248. surface.Scale(-1, 1, midX, midY);
  249. break;
  250. case SKEncodedOrigin.BottomRight:
  251. surface.RotateDegrees(180, midX, midY);
  252. break;
  253. case SKEncodedOrigin.BottomLeft:
  254. surface.Scale(1, -1, midX, midY);
  255. break;
  256. case SKEncodedOrigin.LeftTop:
  257. surface.Translate(0, -rotated.Height);
  258. surface.Scale(1, -1, midX, midY);
  259. surface.RotateDegrees(-90);
  260. break;
  261. case SKEncodedOrigin.RightTop:
  262. surface.Translate(rotated.Width, 0);
  263. surface.RotateDegrees(90);
  264. break;
  265. case SKEncodedOrigin.RightBottom:
  266. surface.Translate(rotated.Width, 0);
  267. surface.Scale(1, -1, midX, midY);
  268. surface.RotateDegrees(90);
  269. break;
  270. case SKEncodedOrigin.LeftBottom:
  271. surface.Translate(0, rotated.Height);
  272. surface.RotateDegrees(-90);
  273. break;
  274. }
  275. surface.DrawBitmap(bitmap, 0, 0);
  276. return rotated;
  277. }
  278. /// <summary>
  279. /// Resizes an image on the CPU, by utilizing a surface and canvas.
  280. ///
  281. /// The convolutional matrix kernel used in this resize function gives a (light) sharpening effect.
  282. /// 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).
  283. /// </summary>
  284. /// <param name="source">The source bitmap.</param>
  285. /// <param name="targetInfo">This specifies the target size and other information required to create the surface.</param>
  286. /// <param name="isAntialias">This enables anti-aliasing on the SKPaint instance.</param>
  287. /// <param name="isDither">This enables dithering on the SKPaint instance.</param>
  288. /// <returns>The resized image.</returns>
  289. internal static SKImage ResizeImage(SKBitmap source, SKImageInfo targetInfo, bool isAntialias = false, bool isDither = false)
  290. {
  291. using var surface = SKSurface.Create(targetInfo);
  292. using var canvas = surface.Canvas;
  293. using var paint = new SKPaint
  294. {
  295. FilterQuality = SKFilterQuality.High,
  296. IsAntialias = isAntialias,
  297. IsDither = isDither
  298. };
  299. var kernel = new float[9]
  300. {
  301. 0, -.1f, 0,
  302. -.1f, 1.4f, -.1f,
  303. 0, -.1f, 0,
  304. };
  305. var kernelSize = new SKSizeI(3, 3);
  306. var kernelOffset = new SKPointI(1, 1);
  307. paint.ImageFilter = SKImageFilter.CreateMatrixConvolution(
  308. kernelSize,
  309. kernel,
  310. 1f,
  311. 0f,
  312. kernelOffset,
  313. SKShaderTileMode.Clamp,
  314. true);
  315. canvas.DrawBitmap(
  316. source,
  317. SKRect.Create(0, 0, source.Width, source.Height),
  318. SKRect.Create(0, 0, targetInfo.Width, targetInfo.Height),
  319. paint);
  320. return surface.Snapshot();
  321. }
  322. /// <inheritdoc/>
  323. public string EncodeImage(string inputPath, DateTime dateModified, string outputPath, bool autoOrient, ImageOrientation? orientation, int quality, ImageProcessingOptions options, ImageFormat outputFormat)
  324. {
  325. if (inputPath.Length == 0)
  326. {
  327. throw new ArgumentException("String can't be empty.", nameof(inputPath));
  328. }
  329. if (outputPath.Length == 0)
  330. {
  331. throw new ArgumentException("String can't be empty.", nameof(outputPath));
  332. }
  333. var skiaOutputFormat = GetImageFormat(outputFormat);
  334. var hasBackgroundColor = !string.IsNullOrWhiteSpace(options.BackgroundColor);
  335. var hasForegroundColor = !string.IsNullOrWhiteSpace(options.ForegroundLayer);
  336. var blur = options.Blur ?? 0;
  337. var hasIndicator = options.AddPlayedIndicator || options.UnplayedCount.HasValue || !options.PercentPlayed.Equals(0);
  338. using var bitmap = GetBitmap(inputPath, autoOrient, orientation);
  339. if (bitmap == null)
  340. {
  341. throw new InvalidDataException($"Skia unable to read image {inputPath}");
  342. }
  343. var originalImageSize = new ImageDimensions(bitmap.Width, bitmap.Height);
  344. if (options.HasDefaultOptions(inputPath, originalImageSize) && !autoOrient)
  345. {
  346. // Just spit out the original file if all the options are default
  347. return inputPath;
  348. }
  349. var newImageSize = ImageHelper.GetNewImageSize(options, originalImageSize);
  350. var width = newImageSize.Width;
  351. var height = newImageSize.Height;
  352. // scale image (the FromImage creates a copy)
  353. var imageInfo = new SKImageInfo(width, height, bitmap.ColorType, bitmap.AlphaType, bitmap.ColorSpace);
  354. using var resizedBitmap = SKBitmap.FromImage(ResizeImage(bitmap, imageInfo));
  355. // If all we're doing is resizing then we can stop now
  356. if (!hasBackgroundColor && !hasForegroundColor && blur == 0 && !hasIndicator)
  357. {
  358. var outputDirectory = Path.GetDirectoryName(outputPath) ?? throw new ArgumentException($"Provided path ({outputPath}) is not valid.", nameof(outputPath));
  359. Directory.CreateDirectory(outputDirectory);
  360. using var outputStream = new SKFileWStream(outputPath);
  361. using var pixmap = new SKPixmap(new SKImageInfo(width, height), resizedBitmap.GetPixels());
  362. resizedBitmap.Encode(outputStream, skiaOutputFormat, quality);
  363. return outputPath;
  364. }
  365. // create bitmap to use for canvas drawing used to draw into bitmap
  366. using var saveBitmap = new SKBitmap(width, height);
  367. using var canvas = new SKCanvas(saveBitmap);
  368. // set background color if present
  369. if (hasBackgroundColor)
  370. {
  371. canvas.Clear(SKColor.Parse(options.BackgroundColor));
  372. }
  373. // Add blur if option is present
  374. if (blur > 0)
  375. {
  376. // create image from resized bitmap to apply blur
  377. using var paint = new SKPaint();
  378. using var filter = SKImageFilter.CreateBlur(blur, blur);
  379. paint.ImageFilter = filter;
  380. canvas.DrawBitmap(resizedBitmap, SKRect.Create(width, height), paint);
  381. }
  382. else
  383. {
  384. // draw resized bitmap onto canvas
  385. canvas.DrawBitmap(resizedBitmap, SKRect.Create(width, height));
  386. }
  387. // If foreground layer present then draw
  388. if (hasForegroundColor)
  389. {
  390. if (!double.TryParse(options.ForegroundLayer, out double opacity))
  391. {
  392. opacity = .4;
  393. }
  394. canvas.DrawColor(new SKColor(0, 0, 0, (byte)((1 - opacity) * 0xFF)), SKBlendMode.SrcOver);
  395. }
  396. if (hasIndicator)
  397. {
  398. DrawIndicator(canvas, width, height, options);
  399. }
  400. var directory = Path.GetDirectoryName(outputPath) ?? throw new ArgumentException($"Provided path ({outputPath}) is not valid.", nameof(outputPath));
  401. Directory.CreateDirectory(directory);
  402. using (var outputStream = new SKFileWStream(outputPath))
  403. {
  404. using (var pixmap = new SKPixmap(new SKImageInfo(width, height), saveBitmap.GetPixels()))
  405. {
  406. pixmap.Encode(outputStream, skiaOutputFormat, quality);
  407. }
  408. }
  409. return outputPath;
  410. }
  411. /// <inheritdoc/>
  412. public void CreateImageCollage(ImageCollageOptions options, string? libraryName)
  413. {
  414. double ratio = (double)options.Width / options.Height;
  415. if (ratio >= 1.4)
  416. {
  417. new StripCollageBuilder(this).BuildThumbCollage(options.InputPaths, options.OutputPath, options.Width, options.Height, libraryName);
  418. }
  419. else if (ratio >= .9)
  420. {
  421. new StripCollageBuilder(this).BuildSquareCollage(options.InputPaths, options.OutputPath, options.Width, options.Height);
  422. }
  423. else
  424. {
  425. // TODO: Create Poster collage capability
  426. new StripCollageBuilder(this).BuildSquareCollage(options.InputPaths, options.OutputPath, options.Width, options.Height);
  427. }
  428. }
  429. private void DrawIndicator(SKCanvas canvas, int imageWidth, int imageHeight, ImageProcessingOptions options)
  430. {
  431. try
  432. {
  433. var currentImageSize = new ImageDimensions(imageWidth, imageHeight);
  434. if (options.AddPlayedIndicator)
  435. {
  436. PlayedIndicatorDrawer.DrawPlayedIndicator(canvas, currentImageSize);
  437. }
  438. else if (options.UnplayedCount.HasValue)
  439. {
  440. UnplayedCountIndicator.DrawUnplayedCountIndicator(canvas, currentImageSize, options.UnplayedCount.Value);
  441. }
  442. if (options.PercentPlayed > 0)
  443. {
  444. PercentPlayedDrawer.Process(canvas, currentImageSize, options.PercentPlayed);
  445. }
  446. }
  447. catch (Exception ex)
  448. {
  449. _logger.LogError(ex, "Error drawing indicator overlay");
  450. }
  451. }
  452. }
  453. }