SkiaEncoder.cs 22 KB

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