SkiaEncoder.cs 25 KB

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