SkiaEncoder.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604
  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 var codec = SKCodec.Create(NormalizePath(path));
  240. if (codec == null)
  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. if (origin == SKEncodedOrigin.Default)
  296. {
  297. return bitmap;
  298. }
  299. var needsFlip = origin == SKEncodedOrigin.LeftBottom
  300. || origin == SKEncodedOrigin.LeftTop
  301. || origin == SKEncodedOrigin.RightBottom
  302. || origin == SKEncodedOrigin.RightTop;
  303. var rotated = needsFlip
  304. ? new SKBitmap(bitmap.Height, bitmap.Width)
  305. : new SKBitmap(bitmap.Width, bitmap.Height);
  306. using var surface = new SKCanvas(rotated);
  307. var midX = (float)rotated.Width / 2;
  308. var midY = (float)rotated.Height / 2;
  309. switch (origin)
  310. {
  311. case SKEncodedOrigin.TopRight:
  312. surface.Scale(-1, 1, midX, midY);
  313. break;
  314. case SKEncodedOrigin.BottomRight:
  315. surface.RotateDegrees(180, midX, midY);
  316. break;
  317. case SKEncodedOrigin.BottomLeft:
  318. surface.Scale(1, -1, midX, midY);
  319. break;
  320. case SKEncodedOrigin.LeftTop:
  321. surface.Translate(0, -rotated.Height);
  322. surface.Scale(1, -1, midX, midY);
  323. surface.RotateDegrees(-90);
  324. break;
  325. case SKEncodedOrigin.RightTop:
  326. surface.Translate(rotated.Width, 0);
  327. surface.RotateDegrees(90);
  328. break;
  329. case SKEncodedOrigin.RightBottom:
  330. surface.Translate(rotated.Width, 0);
  331. surface.Scale(1, -1, midX, midY);
  332. surface.RotateDegrees(90);
  333. break;
  334. case SKEncodedOrigin.LeftBottom:
  335. surface.Translate(0, rotated.Height);
  336. surface.RotateDegrees(-90);
  337. break;
  338. }
  339. surface.DrawBitmap(bitmap, 0, 0);
  340. return rotated;
  341. }
  342. /// <summary>
  343. /// Resizes an image on the CPU, by utilizing a surface and canvas.
  344. ///
  345. /// The convolutional matrix kernel used in this resize function gives a (light) sharpening effect.
  346. /// 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).
  347. /// </summary>
  348. /// <param name="source">The source bitmap.</param>
  349. /// <param name="targetInfo">This specifies the target size and other information required to create the surface.</param>
  350. /// <param name="isAntialias">This enables anti-aliasing on the SKPaint instance.</param>
  351. /// <param name="isDither">This enables dithering on the SKPaint instance.</param>
  352. /// <returns>The resized image.</returns>
  353. internal static SKImage ResizeImage(SKBitmap source, SKImageInfo targetInfo, bool isAntialias = false, bool isDither = false)
  354. {
  355. using var surface = SKSurface.Create(targetInfo);
  356. using var canvas = surface.Canvas;
  357. using var paint = new SKPaint
  358. {
  359. FilterQuality = SKFilterQuality.High,
  360. IsAntialias = isAntialias,
  361. IsDither = isDither
  362. };
  363. var kernel = new float[9]
  364. {
  365. 0, -.1f, 0,
  366. -.1f, 1.4f, -.1f,
  367. 0, -.1f, 0,
  368. };
  369. var kernelSize = new SKSizeI(3, 3);
  370. var kernelOffset = new SKPointI(1, 1);
  371. paint.ImageFilter = SKImageFilter.CreateMatrixConvolution(
  372. kernelSize,
  373. kernel,
  374. 1f,
  375. 0f,
  376. kernelOffset,
  377. SKShaderTileMode.Clamp,
  378. true);
  379. canvas.DrawBitmap(
  380. source,
  381. SKRect.Create(0, 0, source.Width, source.Height),
  382. SKRect.Create(0, 0, targetInfo.Width, targetInfo.Height),
  383. paint);
  384. return surface.Snapshot();
  385. }
  386. /// <inheritdoc/>
  387. public string EncodeImage(string inputPath, DateTime dateModified, string outputPath, bool autoOrient, ImageOrientation? orientation, int quality, ImageProcessingOptions options, ImageFormat selectedOutputFormat)
  388. {
  389. if (inputPath.Length == 0)
  390. {
  391. throw new ArgumentException("String can't be empty.", nameof(inputPath));
  392. }
  393. if (outputPath.Length == 0)
  394. {
  395. throw new ArgumentException("String can't be empty.", nameof(outputPath));
  396. }
  397. var skiaOutputFormat = GetImageFormat(selectedOutputFormat);
  398. var hasBackgroundColor = !string.IsNullOrWhiteSpace(options.BackgroundColor);
  399. var hasForegroundColor = !string.IsNullOrWhiteSpace(options.ForegroundLayer);
  400. var blur = options.Blur ?? 0;
  401. var hasIndicator = options.AddPlayedIndicator || options.UnplayedCount.HasValue || !options.PercentPlayed.Equals(0);
  402. using var bitmap = GetBitmap(inputPath, options.CropWhiteSpace, autoOrient, orientation);
  403. if (bitmap == null)
  404. {
  405. throw new InvalidDataException($"Skia unable to read image {inputPath}");
  406. }
  407. var originalImageSize = new ImageDimensions(bitmap.Width, bitmap.Height);
  408. if (!options.CropWhiteSpace
  409. && options.HasDefaultOptions(inputPath, originalImageSize)
  410. && !autoOrient)
  411. {
  412. // Just spit out the original file if all the options are default
  413. return inputPath;
  414. }
  415. var newImageSize = ImageHelper.GetNewImageSize(options, originalImageSize);
  416. var width = newImageSize.Width;
  417. var height = newImageSize.Height;
  418. // scale image (the FromImage creates a copy)
  419. var imageInfo = new SKImageInfo(width, height, bitmap.ColorType, bitmap.AlphaType, bitmap.ColorSpace);
  420. using var resizedBitmap = SKBitmap.FromImage(ResizeImage(bitmap, imageInfo));
  421. // If all we're doing is resizing then we can stop now
  422. if (!hasBackgroundColor && !hasForegroundColor && blur == 0 && !hasIndicator)
  423. {
  424. var outputDirectory = Path.GetDirectoryName(outputPath) ?? throw new ArgumentException($"Provided path ({outputPath}) is not valid.", nameof(outputPath));
  425. Directory.CreateDirectory(outputDirectory);
  426. using var outputStream = new SKFileWStream(outputPath);
  427. using var pixmap = new SKPixmap(new SKImageInfo(width, height), resizedBitmap.GetPixels());
  428. resizedBitmap.Encode(outputStream, skiaOutputFormat, quality);
  429. return outputPath;
  430. }
  431. // create bitmap to use for canvas drawing used to draw into bitmap
  432. using var saveBitmap = new SKBitmap(width, height);
  433. using var canvas = new SKCanvas(saveBitmap);
  434. // set background color if present
  435. if (hasBackgroundColor)
  436. {
  437. canvas.Clear(SKColor.Parse(options.BackgroundColor));
  438. }
  439. // Add blur if option is present
  440. if (blur > 0)
  441. {
  442. // create image from resized bitmap to apply blur
  443. using var paint = new SKPaint();
  444. using var filter = SKImageFilter.CreateBlur(blur, blur);
  445. paint.ImageFilter = filter;
  446. canvas.DrawBitmap(resizedBitmap, SKRect.Create(width, height), paint);
  447. }
  448. else
  449. {
  450. // draw resized bitmap onto canvas
  451. canvas.DrawBitmap(resizedBitmap, SKRect.Create(width, height));
  452. }
  453. // If foreground layer present then draw
  454. if (hasForegroundColor)
  455. {
  456. if (!double.TryParse(options.ForegroundLayer, out double opacity))
  457. {
  458. opacity = .4;
  459. }
  460. canvas.DrawColor(new SKColor(0, 0, 0, (byte)((1 - opacity) * 0xFF)), SKBlendMode.SrcOver);
  461. }
  462. if (hasIndicator)
  463. {
  464. DrawIndicator(canvas, width, height, options);
  465. }
  466. var directory = Path.GetDirectoryName(outputPath) ?? throw new ArgumentException($"Provided path ({outputPath}) is not valid.", nameof(outputPath));
  467. Directory.CreateDirectory(directory);
  468. using (var outputStream = new SKFileWStream(outputPath))
  469. {
  470. using (var pixmap = new SKPixmap(new SKImageInfo(width, height), saveBitmap.GetPixels()))
  471. {
  472. pixmap.Encode(outputStream, skiaOutputFormat, quality);
  473. }
  474. }
  475. return outputPath;
  476. }
  477. /// <inheritdoc/>
  478. public void CreateImageCollage(ImageCollageOptions options, string? libraryName)
  479. {
  480. double ratio = (double)options.Width / options.Height;
  481. if (ratio >= 1.4)
  482. {
  483. new StripCollageBuilder(this).BuildThumbCollage(options.InputPaths, options.OutputPath, options.Width, options.Height, libraryName);
  484. }
  485. else if (ratio >= .9)
  486. {
  487. new StripCollageBuilder(this).BuildSquareCollage(options.InputPaths, options.OutputPath, options.Width, options.Height);
  488. }
  489. else
  490. {
  491. // TODO: Create Poster collage capability
  492. new StripCollageBuilder(this).BuildSquareCollage(options.InputPaths, options.OutputPath, options.Width, options.Height);
  493. }
  494. }
  495. private void DrawIndicator(SKCanvas canvas, int imageWidth, int imageHeight, ImageProcessingOptions options)
  496. {
  497. try
  498. {
  499. var currentImageSize = new ImageDimensions(imageWidth, imageHeight);
  500. if (options.AddPlayedIndicator)
  501. {
  502. PlayedIndicatorDrawer.DrawPlayedIndicator(canvas, currentImageSize);
  503. }
  504. else if (options.UnplayedCount.HasValue)
  505. {
  506. UnplayedCountIndicator.DrawUnplayedCountIndicator(canvas, currentImageSize, options.UnplayedCount.Value);
  507. }
  508. if (options.PercentPlayed > 0)
  509. {
  510. PercentPlayedDrawer.Process(canvas, currentImageSize, options.PercentPlayed);
  511. }
  512. }
  513. catch (Exception ex)
  514. {
  515. _logger.LogError(ex, "Error drawing indicator overlay");
  516. }
  517. }
  518. }
  519. }