SkiaEncoder.cs 24 KB

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