SkiaEncoder.cs 22 KB

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