SkiaEncoder.cs 21 KB

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