SkiaEncoder.cs 23 KB

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