SkiaEncoder.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680
  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 codec = SKCodec.Create(NormalizePath(path)))
  269. {
  270. if (codec == null)
  271. {
  272. origin = GetSKEncodedOrigin(orientation);
  273. return null;
  274. }
  275. // create the bitmap
  276. var bitmap = new SKBitmap(codec.Info.Width, codec.Info.Height, !requiresTransparencyHack);
  277. // decode
  278. _ = codec.GetPixels(bitmap.Info, bitmap.GetPixels());
  279. origin = codec.EncodedOrigin;
  280. return bitmap;
  281. }
  282. }
  283. var resultBitmap = SKBitmap.Decode(NormalizePath(path));
  284. if (resultBitmap == null)
  285. {
  286. return Decode(path, true, orientation, out origin);
  287. }
  288. // If we have to resize these they often end up distorted
  289. if (resultBitmap.ColorType == SKColorType.Gray8)
  290. {
  291. using (resultBitmap)
  292. {
  293. return Decode(path, true, orientation, out origin);
  294. }
  295. }
  296. origin = SKEncodedOrigin.TopLeft;
  297. return resultBitmap;
  298. }
  299. private SKBitmap GetBitmap(string path, bool cropWhitespace, bool forceAnalyzeBitmap, ImageOrientation? orientation, out SKEncodedOrigin origin)
  300. {
  301. if (cropWhitespace)
  302. {
  303. using (var bitmap = Decode(path, forceAnalyzeBitmap, orientation, out origin))
  304. {
  305. return CropWhiteSpace(bitmap);
  306. }
  307. }
  308. return Decode(path, forceAnalyzeBitmap, orientation, out origin);
  309. }
  310. private SKBitmap GetBitmap(string path, bool cropWhitespace, bool autoOrient, ImageOrientation? orientation)
  311. {
  312. SKEncodedOrigin origin;
  313. if (autoOrient)
  314. {
  315. var bitmap = GetBitmap(path, cropWhitespace, true, orientation, out origin);
  316. if (bitmap != null && origin != SKEncodedOrigin.TopLeft)
  317. {
  318. using (bitmap)
  319. {
  320. return OrientImage(bitmap, origin);
  321. }
  322. }
  323. return bitmap;
  324. }
  325. return GetBitmap(path, cropWhitespace, false, orientation, out origin);
  326. }
  327. private SKBitmap OrientImage(SKBitmap bitmap, SKEncodedOrigin origin)
  328. {
  329. switch (origin)
  330. {
  331. case SKEncodedOrigin.TopRight:
  332. {
  333. var rotated = new SKBitmap(bitmap.Width, bitmap.Height);
  334. using (var surface = new SKCanvas(rotated))
  335. {
  336. surface.Translate(rotated.Width, 0);
  337. surface.Scale(-1, 1);
  338. surface.DrawBitmap(bitmap, 0, 0);
  339. }
  340. return rotated;
  341. }
  342. case SKEncodedOrigin.BottomRight:
  343. {
  344. var rotated = new SKBitmap(bitmap.Width, bitmap.Height);
  345. using (var surface = new SKCanvas(rotated))
  346. {
  347. float px = (float)bitmap.Width / 2;
  348. float py = (float)bitmap.Height / 2;
  349. surface.RotateDegrees(180, px, py);
  350. surface.DrawBitmap(bitmap, 0, 0);
  351. }
  352. return rotated;
  353. }
  354. case SKEncodedOrigin.BottomLeft:
  355. {
  356. var rotated = new SKBitmap(bitmap.Width, bitmap.Height);
  357. using (var surface = new SKCanvas(rotated))
  358. {
  359. float px = (float)bitmap.Width / 2;
  360. float py = (float)bitmap.Height / 2;
  361. surface.Translate(rotated.Width, 0);
  362. surface.Scale(-1, 1);
  363. surface.RotateDegrees(180, px, py);
  364. surface.DrawBitmap(bitmap, 0, 0);
  365. }
  366. return rotated;
  367. }
  368. case SKEncodedOrigin.LeftTop:
  369. {
  370. // TODO: Remove dual canvases, had trouble with flipping
  371. using (var rotated = new SKBitmap(bitmap.Height, bitmap.Width))
  372. {
  373. using (var surface = new SKCanvas(rotated))
  374. {
  375. surface.Translate(rotated.Width, 0);
  376. surface.RotateDegrees(90);
  377. surface.DrawBitmap(bitmap, 0, 0);
  378. }
  379. var flippedBitmap = new SKBitmap(rotated.Width, rotated.Height);
  380. using (var flippedCanvas = new SKCanvas(flippedBitmap))
  381. {
  382. flippedCanvas.Translate(flippedBitmap.Width, 0);
  383. flippedCanvas.Scale(-1, 1);
  384. flippedCanvas.DrawBitmap(rotated, 0, 0);
  385. }
  386. return flippedBitmap;
  387. }
  388. }
  389. case SKEncodedOrigin.RightTop:
  390. {
  391. var rotated = new SKBitmap(bitmap.Height, bitmap.Width);
  392. using (var surface = new SKCanvas(rotated))
  393. {
  394. surface.Translate(rotated.Width, 0);
  395. surface.RotateDegrees(90);
  396. surface.DrawBitmap(bitmap, 0, 0);
  397. }
  398. return rotated;
  399. }
  400. case SKEncodedOrigin.RightBottom:
  401. {
  402. // TODO: Remove dual canvases, had trouble with flipping
  403. using (var rotated = new SKBitmap(bitmap.Height, bitmap.Width))
  404. {
  405. using (var surface = new SKCanvas(rotated))
  406. {
  407. surface.Translate(0, rotated.Height);
  408. surface.RotateDegrees(270);
  409. surface.DrawBitmap(bitmap, 0, 0);
  410. }
  411. var flippedBitmap = new SKBitmap(rotated.Width, rotated.Height);
  412. using (var flippedCanvas = new SKCanvas(flippedBitmap))
  413. {
  414. flippedCanvas.Translate(flippedBitmap.Width, 0);
  415. flippedCanvas.Scale(-1, 1);
  416. flippedCanvas.DrawBitmap(rotated, 0, 0);
  417. }
  418. return flippedBitmap;
  419. }
  420. }
  421. case SKEncodedOrigin.LeftBottom:
  422. {
  423. var rotated = new SKBitmap(bitmap.Height, bitmap.Width);
  424. using (var surface = new SKCanvas(rotated))
  425. {
  426. surface.Translate(0, rotated.Height);
  427. surface.RotateDegrees(270);
  428. surface.DrawBitmap(bitmap, 0, 0);
  429. }
  430. return rotated;
  431. }
  432. default: return bitmap;
  433. }
  434. }
  435. /// <inheritdoc/>
  436. public string EncodeImage(string inputPath, DateTime dateModified, string outputPath, bool autoOrient, ImageOrientation? orientation, int quality, ImageProcessingOptions options, ImageFormat selectedOutputFormat)
  437. {
  438. if (string.IsNullOrWhiteSpace(inputPath))
  439. {
  440. throw new ArgumentNullException(nameof(inputPath));
  441. }
  442. if (string.IsNullOrWhiteSpace(inputPath))
  443. {
  444. throw new ArgumentNullException(nameof(outputPath));
  445. }
  446. var skiaOutputFormat = GetImageFormat(selectedOutputFormat);
  447. var hasBackgroundColor = !string.IsNullOrWhiteSpace(options.BackgroundColor);
  448. var hasForegroundColor = !string.IsNullOrWhiteSpace(options.ForegroundLayer);
  449. var blur = options.Blur ?? 0;
  450. var hasIndicator = options.AddPlayedIndicator || options.UnplayedCount.HasValue || !options.PercentPlayed.Equals(0);
  451. using (var bitmap = GetBitmap(inputPath, options.CropWhiteSpace, autoOrient, orientation))
  452. {
  453. if (bitmap == null)
  454. {
  455. throw new ArgumentOutOfRangeException($"Skia unable to read image {inputPath}");
  456. }
  457. var originalImageSize = new ImageDimensions(bitmap.Width, bitmap.Height);
  458. if (!options.CropWhiteSpace
  459. && options.HasDefaultOptions(inputPath, originalImageSize)
  460. && !autoOrient)
  461. {
  462. // Just spit out the original file if all the options are default
  463. return inputPath;
  464. }
  465. var newImageSize = ImageHelper.GetNewImageSize(options, originalImageSize);
  466. var width = newImageSize.Width;
  467. var height = newImageSize.Height;
  468. using (var resizedBitmap = new SKBitmap(width, height, bitmap.ColorType, bitmap.AlphaType))
  469. {
  470. // scale image
  471. bitmap.ScalePixels(resizedBitmap, SKFilterQuality.High);
  472. // If all we're doing is resizing then we can stop now
  473. if (!hasBackgroundColor && !hasForegroundColor && blur == 0 && !hasIndicator)
  474. {
  475. Directory.CreateDirectory(Path.GetDirectoryName(outputPath));
  476. using (var outputStream = new SKFileWStream(outputPath))
  477. using (var pixmap = new SKPixmap(new SKImageInfo(width, height), resizedBitmap.GetPixels()))
  478. {
  479. pixmap.Encode(outputStream, skiaOutputFormat, quality);
  480. return outputPath;
  481. }
  482. }
  483. // create bitmap to use for canvas drawing used to draw into bitmap
  484. using (var saveBitmap = new SKBitmap(width, height)) // , bitmap.ColorType, bitmap.AlphaType))
  485. using (var canvas = new SKCanvas(saveBitmap))
  486. {
  487. // set background color if present
  488. if (hasBackgroundColor)
  489. {
  490. canvas.Clear(SKColor.Parse(options.BackgroundColor));
  491. }
  492. // Add blur if option is present
  493. if (blur > 0)
  494. {
  495. // create image from resized bitmap to apply blur
  496. using (var paint = new SKPaint())
  497. using (var filter = SKImageFilter.CreateBlur(blur, blur))
  498. {
  499. paint.ImageFilter = filter;
  500. canvas.DrawBitmap(resizedBitmap, SKRect.Create(width, height), paint);
  501. }
  502. }
  503. else
  504. {
  505. // draw resized bitmap onto canvas
  506. canvas.DrawBitmap(resizedBitmap, SKRect.Create(width, height));
  507. }
  508. // If foreground layer present then draw
  509. if (hasForegroundColor)
  510. {
  511. if (!double.TryParse(options.ForegroundLayer, out double opacity))
  512. {
  513. opacity = .4;
  514. }
  515. canvas.DrawColor(new SKColor(0, 0, 0, (byte)((1 - opacity) * 0xFF)), SKBlendMode.SrcOver);
  516. }
  517. if (hasIndicator)
  518. {
  519. DrawIndicator(canvas, width, height, options);
  520. }
  521. Directory.CreateDirectory(Path.GetDirectoryName(outputPath));
  522. using (var outputStream = new SKFileWStream(outputPath))
  523. {
  524. using (var pixmap = new SKPixmap(new SKImageInfo(width, height), saveBitmap.GetPixels()))
  525. {
  526. pixmap.Encode(outputStream, skiaOutputFormat, quality);
  527. }
  528. }
  529. }
  530. }
  531. }
  532. return outputPath;
  533. }
  534. /// <inheritdoc/>
  535. public void CreateImageCollage(ImageCollageOptions options)
  536. {
  537. double ratio = (double)options.Width / options.Height;
  538. if (ratio >= 1.4)
  539. {
  540. new StripCollageBuilder(this).BuildThumbCollage(options.InputPaths, options.OutputPath, options.Width, options.Height);
  541. }
  542. else if (ratio >= .9)
  543. {
  544. new StripCollageBuilder(this).BuildSquareCollage(options.InputPaths, options.OutputPath, options.Width, options.Height);
  545. }
  546. else
  547. {
  548. // TODO: Create Poster collage capability
  549. new StripCollageBuilder(this).BuildSquareCollage(options.InputPaths, options.OutputPath, options.Width, options.Height);
  550. }
  551. }
  552. private void DrawIndicator(SKCanvas canvas, int imageWidth, int imageHeight, ImageProcessingOptions options)
  553. {
  554. try
  555. {
  556. var currentImageSize = new ImageDimensions(imageWidth, imageHeight);
  557. if (options.AddPlayedIndicator)
  558. {
  559. PlayedIndicatorDrawer.DrawPlayedIndicator(canvas, currentImageSize);
  560. }
  561. else if (options.UnplayedCount.HasValue)
  562. {
  563. UnplayedCountIndicator.DrawUnplayedCountIndicator(canvas, currentImageSize, options.UnplayedCount.Value);
  564. }
  565. if (options.PercentPlayed > 0)
  566. {
  567. PercentPlayedDrawer.Process(canvas, currentImageSize, options.PercentPlayed);
  568. }
  569. }
  570. catch (Exception ex)
  571. {
  572. _logger.LogError(ex, "Error drawing indicator overlay");
  573. }
  574. }
  575. }
  576. }