SkiaEncoder.cs 25 KB

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