2
0

SkiaEncoder.cs 22 KB

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