SkiaEncoder.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  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. /// <inheritdoc/>
  341. public string EncodeImage(string inputPath, DateTime dateModified, string outputPath, bool autoOrient, ImageOrientation? orientation, int quality, ImageProcessingOptions options, ImageFormat selectedOutputFormat)
  342. {
  343. if (inputPath.Length == 0)
  344. {
  345. throw new ArgumentException("String can't be empty.", nameof(inputPath));
  346. }
  347. if (outputPath.Length == 0)
  348. {
  349. throw new ArgumentException("String can't be empty.", nameof(outputPath));
  350. }
  351. var skiaOutputFormat = GetImageFormat(selectedOutputFormat);
  352. var hasBackgroundColor = !string.IsNullOrWhiteSpace(options.BackgroundColor);
  353. var hasForegroundColor = !string.IsNullOrWhiteSpace(options.ForegroundLayer);
  354. var blur = options.Blur ?? 0;
  355. var hasIndicator = options.AddPlayedIndicator || options.UnplayedCount.HasValue || !options.PercentPlayed.Equals(0);
  356. using var bitmap = GetBitmap(inputPath, options.CropWhiteSpace, autoOrient, orientation);
  357. if (bitmap == null)
  358. {
  359. throw new InvalidDataException($"Skia unable to read image {inputPath}");
  360. }
  361. var originalImageSize = new ImageDimensions(bitmap.Width, bitmap.Height);
  362. if (!options.CropWhiteSpace
  363. && options.HasDefaultOptions(inputPath, originalImageSize)
  364. && !autoOrient)
  365. {
  366. // Just spit out the original file if all the options are default
  367. return inputPath;
  368. }
  369. var newImageSize = ImageHelper.GetNewImageSize(options, originalImageSize);
  370. var width = newImageSize.Width;
  371. var height = newImageSize.Height;
  372. using var resizedBitmap = new SKBitmap(width, height, bitmap.ColorType, bitmap.AlphaType);
  373. // scale image
  374. bitmap.ScalePixels(resizedBitmap, SKFilterQuality.High);
  375. // If all we're doing is resizing then we can stop now
  376. if (!hasBackgroundColor && !hasForegroundColor && blur == 0 && !hasIndicator)
  377. {
  378. Directory.CreateDirectory(Path.GetDirectoryName(outputPath));
  379. using var outputStream = new SKFileWStream(outputPath);
  380. using var pixmap = new SKPixmap(new SKImageInfo(width, height), resizedBitmap.GetPixels());
  381. pixmap.Encode(outputStream, skiaOutputFormat, quality);
  382. return outputPath;
  383. }
  384. // create bitmap to use for canvas drawing used to draw into bitmap
  385. using var saveBitmap = new SKBitmap(width, height);
  386. using var canvas = new SKCanvas(saveBitmap);
  387. // set background color if present
  388. if (hasBackgroundColor)
  389. {
  390. canvas.Clear(SKColor.Parse(options.BackgroundColor));
  391. }
  392. // Add blur if option is present
  393. if (blur > 0)
  394. {
  395. // create image from resized bitmap to apply blur
  396. using var paint = new SKPaint();
  397. using var filter = SKImageFilter.CreateBlur(blur, blur);
  398. paint.ImageFilter = filter;
  399. canvas.DrawBitmap(resizedBitmap, SKRect.Create(width, height), paint);
  400. }
  401. else
  402. {
  403. // draw resized bitmap onto canvas
  404. canvas.DrawBitmap(resizedBitmap, SKRect.Create(width, height));
  405. }
  406. // If foreground layer present then draw
  407. if (hasForegroundColor)
  408. {
  409. if (!double.TryParse(options.ForegroundLayer, out double opacity))
  410. {
  411. opacity = .4;
  412. }
  413. canvas.DrawColor(new SKColor(0, 0, 0, (byte)((1 - opacity) * 0xFF)), SKBlendMode.SrcOver);
  414. }
  415. if (hasIndicator)
  416. {
  417. DrawIndicator(canvas, width, height, options);
  418. }
  419. Directory.CreateDirectory(Path.GetDirectoryName(outputPath));
  420. using (var outputStream = new SKFileWStream(outputPath))
  421. {
  422. using (var pixmap = new SKPixmap(new SKImageInfo(width, height), saveBitmap.GetPixels()))
  423. {
  424. pixmap.Encode(outputStream, skiaOutputFormat, quality);
  425. }
  426. }
  427. return outputPath;
  428. }
  429. /// <inheritdoc/>
  430. public void CreateImageCollage(ImageCollageOptions options)
  431. {
  432. double ratio = (double)options.Width / options.Height;
  433. if (ratio >= 1.4)
  434. {
  435. new StripCollageBuilder(this).BuildThumbCollage(options.InputPaths, options.OutputPath, options.Width, options.Height);
  436. }
  437. else if (ratio >= .9)
  438. {
  439. new StripCollageBuilder(this).BuildSquareCollage(options.InputPaths, options.OutputPath, options.Width, options.Height);
  440. }
  441. else
  442. {
  443. // TODO: Create Poster collage capability
  444. new StripCollageBuilder(this).BuildSquareCollage(options.InputPaths, options.OutputPath, options.Width, options.Height);
  445. }
  446. }
  447. private void DrawIndicator(SKCanvas canvas, int imageWidth, int imageHeight, ImageProcessingOptions options)
  448. {
  449. try
  450. {
  451. var currentImageSize = new ImageDimensions(imageWidth, imageHeight);
  452. if (options.AddPlayedIndicator)
  453. {
  454. PlayedIndicatorDrawer.DrawPlayedIndicator(canvas, currentImageSize);
  455. }
  456. else if (options.UnplayedCount.HasValue)
  457. {
  458. UnplayedCountIndicator.DrawUnplayedCountIndicator(canvas, currentImageSize, options.UnplayedCount.Value);
  459. }
  460. if (options.PercentPlayed > 0)
  461. {
  462. PercentPlayedDrawer.Process(canvas, currentImageSize, options.PercentPlayed);
  463. }
  464. }
  465. catch (Exception ex)
  466. {
  467. _logger.LogError(ex, "Error drawing indicator overlay");
  468. }
  469. }
  470. }
  471. }