SkiaEncoder.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665
  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(
  30. ILogger<SkiaEncoder> logger,
  31. IApplicationPaths appPaths)
  32. {
  33. _logger = logger;
  34. _appPaths = appPaths;
  35. }
  36. /// <inheritdoc/>
  37. public string Name => "Skia";
  38. /// <inheritdoc/>
  39. public bool SupportsImageCollageCreation => true;
  40. /// <inheritdoc/>
  41. public bool SupportsImageEncoding => true;
  42. /// <inheritdoc/>
  43. public IReadOnlyCollection<string> SupportedInputFormats =>
  44. new HashSet<string>(StringComparer.OrdinalIgnoreCase)
  45. {
  46. "jpeg",
  47. "jpg",
  48. "png",
  49. "dng",
  50. "webp",
  51. "gif",
  52. "bmp",
  53. "ico",
  54. "astc",
  55. "ktx",
  56. "pkm",
  57. "wbmp",
  58. // TODO: check if these are supported on multiple platforms
  59. // https://github.com/google/skia/blob/master/infra/bots/recipes/test.py#L454
  60. // working on windows at least
  61. "cr2",
  62. "nef",
  63. "arw"
  64. };
  65. /// <inheritdoc/>
  66. public IReadOnlyCollection<ImageFormat> SupportedOutputFormats
  67. => new HashSet<ImageFormat>() { ImageFormat.Webp, ImageFormat.Jpg, ImageFormat.Png };
  68. /// <summary>
  69. /// Check if the native lib is available.
  70. /// </summary>
  71. /// <returns>True if the native lib is available, otherwise false.</returns>
  72. public static bool IsNativeLibAvailable()
  73. {
  74. try
  75. {
  76. // test an operation that requires the native library
  77. SKPMColor.PreMultiply(SKColors.Black);
  78. return true;
  79. }
  80. catch (Exception)
  81. {
  82. return false;
  83. }
  84. }
  85. private static bool IsTransparent(SKColor color)
  86. => (color.Red == 255 && color.Green == 255 && color.Blue == 255) || color.Alpha == 0;
  87. /// <summary>
  88. /// Convert a <see cref="ImageFormat"/> to a <see cref="SKEncodedImageFormat"/>.
  89. /// </summary>
  90. /// <param name="selectedFormat">The format to convert.</param>
  91. /// <returns>The converted format.</returns>
  92. public static SKEncodedImageFormat GetImageFormat(ImageFormat selectedFormat)
  93. {
  94. switch (selectedFormat)
  95. {
  96. case ImageFormat.Bmp:
  97. return SKEncodedImageFormat.Bmp;
  98. case ImageFormat.Jpg:
  99. return SKEncodedImageFormat.Jpeg;
  100. case ImageFormat.Gif:
  101. return SKEncodedImageFormat.Gif;
  102. case ImageFormat.Webp:
  103. return SKEncodedImageFormat.Webp;
  104. default:
  105. return SKEncodedImageFormat.Png;
  106. }
  107. }
  108. private static bool IsTransparentRow(SKBitmap bmp, int row)
  109. {
  110. for (var i = 0; i < bmp.Width; ++i)
  111. {
  112. if (!IsTransparent(bmp.GetPixel(i, row)))
  113. {
  114. return false;
  115. }
  116. }
  117. return true;
  118. }
  119. private static bool IsTransparentColumn(SKBitmap bmp, int col)
  120. {
  121. for (var i = 0; i < bmp.Height; ++i)
  122. {
  123. if (!IsTransparent(bmp.GetPixel(col, i)))
  124. {
  125. return false;
  126. }
  127. }
  128. return true;
  129. }
  130. private SKBitmap CropWhiteSpace(SKBitmap bitmap)
  131. {
  132. var topmost = 0;
  133. for (int row = 0; row < bitmap.Height; ++row)
  134. {
  135. if (IsTransparentRow(bitmap, row))
  136. {
  137. topmost = row + 1;
  138. }
  139. else
  140. {
  141. break;
  142. }
  143. }
  144. int bottommost = bitmap.Height;
  145. for (int row = bitmap.Height - 1; row >= 0; --row)
  146. {
  147. if (IsTransparentRow(bitmap, row))
  148. {
  149. bottommost = row;
  150. }
  151. else
  152. {
  153. break;
  154. }
  155. }
  156. int leftmost = 0, rightmost = bitmap.Width;
  157. for (int col = 0; col < bitmap.Width; ++col)
  158. {
  159. if (IsTransparentColumn(bitmap, col))
  160. {
  161. leftmost = col + 1;
  162. }
  163. else
  164. {
  165. break;
  166. }
  167. }
  168. for (int col = bitmap.Width - 1; col >= 0; --col)
  169. {
  170. if (IsTransparentColumn(bitmap, col))
  171. {
  172. rightmost = col;
  173. }
  174. else
  175. {
  176. break;
  177. }
  178. }
  179. var newRect = SKRectI.Create(leftmost, topmost, rightmost - leftmost, bottommost - topmost);
  180. using var image = SKImage.FromBitmap(bitmap);
  181. using var subset = image.Subset(newRect);
  182. return SKBitmap.FromImage(subset);
  183. }
  184. /// <inheritdoc />
  185. /// <exception cref="ArgumentNullException">The path is null.</exception>
  186. /// <exception cref="FileNotFoundException">The path is not valid.</exception>
  187. /// <exception cref="SkiaCodecException">The file at the specified path could not be used to generate a codec.</exception>
  188. public ImageDimensions GetImageSize(string path)
  189. {
  190. if (!File.Exists(path))
  191. {
  192. throw new FileNotFoundException("File not found", path);
  193. }
  194. using var codec = SKCodec.Create(path, out SKCodecResult result);
  195. EnsureSuccess(result);
  196. var info = codec.Info;
  197. return new ImageDimensions(info.Width, info.Height);
  198. }
  199. /// <inheritdoc />
  200. /// <exception cref="ArgumentNullException">The path is null.</exception>
  201. /// <exception cref="FileNotFoundException">The path is not valid.</exception>
  202. /// <exception cref="SkiaCodecException">The file at the specified path could not be used to generate a codec.</exception>
  203. public string GetImageBlurHash(int xComp, int yComp, string path)
  204. {
  205. if (path == null)
  206. {
  207. throw new ArgumentNullException(nameof(path));
  208. }
  209. return BlurHashEncoder.Encode(xComp, yComp, path);
  210. }
  211. private static bool HasDiacritics(string text)
  212. => !string.Equals(text, text.RemoveDiacritics(), StringComparison.Ordinal);
  213. private bool RequiresSpecialCharacterHack(string path)
  214. {
  215. for (int i = 0; i < path.Length; i++)
  216. {
  217. if (char.GetUnicodeCategory(path[i]) == UnicodeCategory.OtherLetter)
  218. {
  219. return true;
  220. }
  221. }
  222. if (HasDiacritics(path))
  223. {
  224. return true;
  225. }
  226. return false;
  227. }
  228. private string NormalizePath(string path)
  229. {
  230. if (!RequiresSpecialCharacterHack(path))
  231. {
  232. return path;
  233. }
  234. var tempPath = Path.Combine(_appPaths.TempDirectory, Guid.NewGuid() + Path.GetExtension(path));
  235. Directory.CreateDirectory(Path.GetDirectoryName(tempPath));
  236. File.Copy(path, tempPath, true);
  237. return tempPath;
  238. }
  239. private static SKEncodedOrigin GetSKEncodedOrigin(ImageOrientation? orientation)
  240. {
  241. if (!orientation.HasValue)
  242. {
  243. return SKEncodedOrigin.TopLeft;
  244. }
  245. switch (orientation.Value)
  246. {
  247. case ImageOrientation.TopRight:
  248. return SKEncodedOrigin.TopRight;
  249. case ImageOrientation.RightTop:
  250. return SKEncodedOrigin.RightTop;
  251. case ImageOrientation.RightBottom:
  252. return SKEncodedOrigin.RightBottom;
  253. case ImageOrientation.LeftTop:
  254. return SKEncodedOrigin.LeftTop;
  255. case ImageOrientation.LeftBottom:
  256. return SKEncodedOrigin.LeftBottom;
  257. case ImageOrientation.BottomRight:
  258. return SKEncodedOrigin.BottomRight;
  259. case ImageOrientation.BottomLeft:
  260. return SKEncodedOrigin.BottomLeft;
  261. default:
  262. return SKEncodedOrigin.TopLeft;
  263. }
  264. }
  265. /// <summary>
  266. /// Decode an image.
  267. /// </summary>
  268. /// <param name="path">The filepath of the image to decode.</param>
  269. /// <param name="forceCleanBitmap">Whether to force clean the bitmap.</param>
  270. /// <param name="orientation">The orientation of the image.</param>
  271. /// <param name="origin">The detected origin of the image.</param>
  272. /// <returns>The resulting bitmap of the image.</returns>
  273. internal SKBitmap? Decode(string path, bool forceCleanBitmap, ImageOrientation? orientation, out SKEncodedOrigin origin)
  274. {
  275. if (!File.Exists(path))
  276. {
  277. throw new FileNotFoundException("File not found", path);
  278. }
  279. var requiresTransparencyHack = _transparentImageTypes.Contains(Path.GetExtension(path));
  280. if (requiresTransparencyHack || forceCleanBitmap)
  281. {
  282. using var codec = SKCodec.Create(NormalizePath(path));
  283. if (codec == null)
  284. {
  285. origin = GetSKEncodedOrigin(orientation);
  286. return null;
  287. }
  288. // create the bitmap
  289. var bitmap = new SKBitmap(codec.Info.Width, codec.Info.Height, !requiresTransparencyHack);
  290. // decode
  291. _ = codec.GetPixels(bitmap.Info, bitmap.GetPixels());
  292. origin = codec.EncodedOrigin;
  293. return bitmap;
  294. }
  295. var resultBitmap = SKBitmap.Decode(NormalizePath(path));
  296. if (resultBitmap == null)
  297. {
  298. return Decode(path, true, orientation, out origin);
  299. }
  300. // If we have to resize these they often end up distorted
  301. if (resultBitmap.ColorType == SKColorType.Gray8)
  302. {
  303. using (resultBitmap)
  304. {
  305. return Decode(path, true, orientation, out origin);
  306. }
  307. }
  308. origin = SKEncodedOrigin.TopLeft;
  309. return resultBitmap;
  310. }
  311. private SKBitmap? GetBitmap(string path, bool cropWhitespace, bool forceAnalyzeBitmap, ImageOrientation? orientation, out SKEncodedOrigin origin)
  312. {
  313. if (cropWhitespace)
  314. {
  315. using var bitmap = Decode(path, forceAnalyzeBitmap, orientation, out origin);
  316. if (bitmap == null)
  317. {
  318. return null;
  319. }
  320. return CropWhiteSpace(bitmap);
  321. }
  322. return Decode(path, forceAnalyzeBitmap, orientation, out origin);
  323. }
  324. private SKBitmap? GetBitmap(string path, bool cropWhitespace, bool autoOrient, ImageOrientation? orientation)
  325. {
  326. if (autoOrient)
  327. {
  328. var bitmap = GetBitmap(path, cropWhitespace, true, orientation, out var origin);
  329. if (bitmap != null && origin != SKEncodedOrigin.TopLeft)
  330. {
  331. using (bitmap)
  332. {
  333. return OrientImage(bitmap, origin);
  334. }
  335. }
  336. return bitmap;
  337. }
  338. return GetBitmap(path, cropWhitespace, false, orientation, out _);
  339. }
  340. private SKBitmap OrientImage(SKBitmap bitmap, SKEncodedOrigin origin)
  341. {
  342. switch (origin)
  343. {
  344. case SKEncodedOrigin.TopRight:
  345. {
  346. var rotated = new SKBitmap(bitmap.Width, bitmap.Height);
  347. using var surface = new SKCanvas(rotated);
  348. surface.Translate(rotated.Width, 0);
  349. surface.Scale(-1, 1);
  350. surface.DrawBitmap(bitmap, 0, 0);
  351. return rotated;
  352. }
  353. case SKEncodedOrigin.BottomRight:
  354. {
  355. var rotated = new SKBitmap(bitmap.Width, bitmap.Height);
  356. using var surface = new SKCanvas(rotated);
  357. float px = (float)bitmap.Width / 2;
  358. float py = (float)bitmap.Height / 2;
  359. surface.RotateDegrees(180, px, py);
  360. surface.DrawBitmap(bitmap, 0, 0);
  361. return rotated;
  362. }
  363. case SKEncodedOrigin.BottomLeft:
  364. {
  365. var rotated = new SKBitmap(bitmap.Width, bitmap.Height);
  366. using var surface = new SKCanvas(rotated);
  367. float px = (float)bitmap.Width / 2;
  368. float py = (float)bitmap.Height / 2;
  369. surface.Translate(rotated.Width, 0);
  370. surface.Scale(-1, 1);
  371. surface.RotateDegrees(180, px, py);
  372. surface.DrawBitmap(bitmap, 0, 0);
  373. return rotated;
  374. }
  375. case SKEncodedOrigin.LeftTop:
  376. {
  377. // TODO: Remove dual canvases, had trouble with flipping
  378. using var rotated = new SKBitmap(bitmap.Height, bitmap.Width);
  379. using (var surface = new SKCanvas(rotated))
  380. {
  381. surface.Translate(rotated.Width, 0);
  382. surface.RotateDegrees(90);
  383. surface.DrawBitmap(bitmap, 0, 0);
  384. }
  385. var flippedBitmap = new SKBitmap(rotated.Width, rotated.Height);
  386. using (var flippedCanvas = new SKCanvas(flippedBitmap))
  387. {
  388. flippedCanvas.Translate(flippedBitmap.Width, 0);
  389. flippedCanvas.Scale(-1, 1);
  390. flippedCanvas.DrawBitmap(rotated, 0, 0);
  391. }
  392. return flippedBitmap;
  393. }
  394. case SKEncodedOrigin.RightTop:
  395. {
  396. var rotated = new SKBitmap(bitmap.Height, bitmap.Width);
  397. using var surface = new SKCanvas(rotated);
  398. surface.Translate(rotated.Width, 0);
  399. surface.RotateDegrees(90);
  400. surface.DrawBitmap(bitmap, 0, 0);
  401. return rotated;
  402. }
  403. case SKEncodedOrigin.RightBottom:
  404. {
  405. // TODO: Remove dual canvases, had trouble with flipping
  406. using var rotated = new SKBitmap(bitmap.Height, bitmap.Width);
  407. using (var surface = new SKCanvas(rotated))
  408. {
  409. surface.Translate(0, rotated.Height);
  410. surface.RotateDegrees(270);
  411. surface.DrawBitmap(bitmap, 0, 0);
  412. }
  413. var flippedBitmap = new SKBitmap(rotated.Width, rotated.Height);
  414. using (var flippedCanvas = new SKCanvas(flippedBitmap))
  415. {
  416. flippedCanvas.Translate(flippedBitmap.Width, 0);
  417. flippedCanvas.Scale(-1, 1);
  418. flippedCanvas.DrawBitmap(rotated, 0, 0);
  419. }
  420. return flippedBitmap;
  421. }
  422. case SKEncodedOrigin.LeftBottom:
  423. {
  424. var rotated = new SKBitmap(bitmap.Height, bitmap.Width);
  425. using var surface = new SKCanvas(rotated);
  426. surface.Translate(0, rotated.Height);
  427. surface.RotateDegrees(270);
  428. surface.DrawBitmap(bitmap, 0, 0);
  429. return rotated;
  430. }
  431. default: return bitmap;
  432. }
  433. }
  434. /// <inheritdoc/>
  435. public string EncodeImage(string inputPath, DateTime dateModified, string outputPath, bool autoOrient, ImageOrientation? orientation, int quality, ImageProcessingOptions options, ImageFormat selectedOutputFormat)
  436. {
  437. if (inputPath.Length == 0)
  438. {
  439. throw new ArgumentException("String can't be empty.", nameof(inputPath));
  440. }
  441. if (outputPath.Length == 0)
  442. {
  443. throw new ArgumentException("String can't be empty.", nameof(outputPath));
  444. }
  445. var skiaOutputFormat = GetImageFormat(selectedOutputFormat);
  446. var hasBackgroundColor = !string.IsNullOrWhiteSpace(options.BackgroundColor);
  447. var hasForegroundColor = !string.IsNullOrWhiteSpace(options.ForegroundLayer);
  448. var blur = options.Blur ?? 0;
  449. var hasIndicator = options.AddPlayedIndicator || options.UnplayedCount.HasValue || !options.PercentPlayed.Equals(0);
  450. using var bitmap = GetBitmap(inputPath, options.CropWhiteSpace, autoOrient, orientation);
  451. if (bitmap == null)
  452. {
  453. throw new InvalidDataException($"Skia unable to read image {inputPath}");
  454. }
  455. var originalImageSize = new ImageDimensions(bitmap.Width, bitmap.Height);
  456. if (!options.CropWhiteSpace
  457. && options.HasDefaultOptions(inputPath, originalImageSize)
  458. && !autoOrient)
  459. {
  460. // Just spit out the original file if all the options are default
  461. return inputPath;
  462. }
  463. var newImageSize = ImageHelper.GetNewImageSize(options, originalImageSize);
  464. var width = newImageSize.Width;
  465. var height = newImageSize.Height;
  466. using var resizedBitmap = new SKBitmap(width, height, bitmap.ColorType, bitmap.AlphaType);
  467. // scale image
  468. bitmap.ScalePixels(resizedBitmap, SKFilterQuality.High);
  469. // If all we're doing is resizing then we can stop now
  470. if (!hasBackgroundColor && !hasForegroundColor && blur == 0 && !hasIndicator)
  471. {
  472. Directory.CreateDirectory(Path.GetDirectoryName(outputPath));
  473. using var outputStream = new SKFileWStream(outputPath);
  474. using var pixmap = new SKPixmap(new SKImageInfo(width, height), resizedBitmap.GetPixels());
  475. pixmap.Encode(outputStream, skiaOutputFormat, quality);
  476. return outputPath;
  477. }
  478. // create bitmap to use for canvas drawing used to draw into bitmap
  479. using var saveBitmap = new SKBitmap(width, height);
  480. using var canvas = new SKCanvas(saveBitmap);
  481. // set background color if present
  482. if (hasBackgroundColor)
  483. {
  484. canvas.Clear(SKColor.Parse(options.BackgroundColor));
  485. }
  486. // Add blur if option is present
  487. if (blur > 0)
  488. {
  489. // create image from resized bitmap to apply blur
  490. using var paint = new SKPaint();
  491. using var filter = SKImageFilter.CreateBlur(blur, blur);
  492. paint.ImageFilter = filter;
  493. canvas.DrawBitmap(resizedBitmap, SKRect.Create(width, height), paint);
  494. }
  495. else
  496. {
  497. // draw resized bitmap onto canvas
  498. canvas.DrawBitmap(resizedBitmap, SKRect.Create(width, height));
  499. }
  500. // If foreground layer present then draw
  501. if (hasForegroundColor)
  502. {
  503. if (!double.TryParse(options.ForegroundLayer, out double opacity))
  504. {
  505. opacity = .4;
  506. }
  507. canvas.DrawColor(new SKColor(0, 0, 0, (byte)((1 - opacity) * 0xFF)), SKBlendMode.SrcOver);
  508. }
  509. if (hasIndicator)
  510. {
  511. DrawIndicator(canvas, width, height, options);
  512. }
  513. Directory.CreateDirectory(Path.GetDirectoryName(outputPath));
  514. using (var outputStream = new SKFileWStream(outputPath))
  515. {
  516. using (var pixmap = new SKPixmap(new SKImageInfo(width, height), saveBitmap.GetPixels()))
  517. {
  518. pixmap.Encode(outputStream, skiaOutputFormat, quality);
  519. }
  520. }
  521. return outputPath;
  522. }
  523. /// <inheritdoc/>
  524. public void CreateImageCollage(ImageCollageOptions options)
  525. {
  526. double ratio = (double)options.Width / options.Height;
  527. if (ratio >= 1.4)
  528. {
  529. new StripCollageBuilder(this).BuildThumbCollage(options.InputPaths, options.OutputPath, options.Width, options.Height);
  530. }
  531. else if (ratio >= .9)
  532. {
  533. new StripCollageBuilder(this).BuildSquareCollage(options.InputPaths, options.OutputPath, options.Width, options.Height);
  534. }
  535. else
  536. {
  537. // TODO: Create Poster collage capability
  538. new StripCollageBuilder(this).BuildSquareCollage(options.InputPaths, options.OutputPath, options.Width, options.Height);
  539. }
  540. }
  541. private void DrawIndicator(SKCanvas canvas, int imageWidth, int imageHeight, ImageProcessingOptions options)
  542. {
  543. try
  544. {
  545. var currentImageSize = new ImageDimensions(imageWidth, imageHeight);
  546. if (options.AddPlayedIndicator)
  547. {
  548. PlayedIndicatorDrawer.DrawPlayedIndicator(canvas, currentImageSize);
  549. }
  550. else if (options.UnplayedCount.HasValue)
  551. {
  552. UnplayedCountIndicator.DrawUnplayedCountIndicator(canvas, currentImageSize, options.UnplayedCount.Value);
  553. }
  554. if (options.PercentPlayed > 0)
  555. {
  556. PercentPlayedDrawer.Process(canvas, currentImageSize, options.PercentPlayed);
  557. }
  558. }
  559. catch (Exception ex)
  560. {
  561. _logger.LogError(ex, "Error drawing indicator overlay");
  562. }
  563. }
  564. }
  565. }