SkiaEncoder.cs 25 KB

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