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 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. public SkiaEncoder(
  29. ILogger<SkiaEncoder> logger,
  30. IApplicationPaths appPaths,
  31. ILocalizationManager localizationManager)
  32. {
  33. _logger = logger;
  34. _appPaths = appPaths;
  35. _localizationManager = localizationManager;
  36. }
  37. /// <inheritdoc/>
  38. public string Name => "Skia";
  39. /// <inheritdoc/>
  40. public bool SupportsImageCollageCreation => true;
  41. /// <inheritdoc/>
  42. public bool SupportsImageEncoding => true;
  43. /// <inheritdoc/>
  44. public IReadOnlyCollection<string> SupportedInputFormats =>
  45. new HashSet<string>(StringComparer.OrdinalIgnoreCase)
  46. {
  47. "jpeg",
  48. "jpg",
  49. "png",
  50. "dng",
  51. "webp",
  52. "gif",
  53. "bmp",
  54. "ico",
  55. "astc",
  56. "ktx",
  57. "pkm",
  58. "wbmp",
  59. // TODO
  60. // Are all of these supported? https://github.com/google/skia/blob/master/infra/bots/recipes/test.py#L454
  61. // working on windows at least
  62. "cr2",
  63. "nef",
  64. "arw"
  65. };
  66. /// <inheritdoc/>
  67. public IReadOnlyCollection<ImageFormat> SupportedOutputFormats
  68. => new HashSet<ImageFormat>() { ImageFormat.Webp, ImageFormat.Jpg, ImageFormat.Png };
  69. /// <summary>
  70. /// Test to determine if the native lib is available
  71. /// </summary>
  72. public static void TestSkia()
  73. {
  74. // test an operation that requires the native library
  75. SKPMColor.PreMultiply(SKColors.Black);
  76. }
  77. private static bool IsTransparent(SKColor color)
  78. => (color.Red == 255 && color.Green == 255 && color.Blue == 255) || color.Alpha == 0;
  79. /// <summary>
  80. /// Convert a <see cref="ImageFormat"/> to a <see cref="SKEncodedImageFormat"/>.
  81. /// </summary>
  82. /// <param name="selectedFormat">The format to convert.</param>
  83. /// <returns>The converted format.</returns>
  84. public static SKEncodedImageFormat GetImageFormat(ImageFormat selectedFormat)
  85. {
  86. switch (selectedFormat)
  87. {
  88. case ImageFormat.Bmp:
  89. return SKEncodedImageFormat.Bmp;
  90. case ImageFormat.Jpg:
  91. return SKEncodedImageFormat.Jpeg;
  92. case ImageFormat.Gif:
  93. return SKEncodedImageFormat.Gif;
  94. case ImageFormat.Webp:
  95. return SKEncodedImageFormat.Webp;
  96. default:
  97. return SKEncodedImageFormat.Png;
  98. }
  99. }
  100. private static bool IsTransparentRow(SKBitmap bmp, int row)
  101. {
  102. for (var i = 0; i < bmp.Width; ++i)
  103. {
  104. if (!IsTransparent(bmp.GetPixel(i, row)))
  105. {
  106. return false;
  107. }
  108. }
  109. return true;
  110. }
  111. private static bool IsTransparentColumn(SKBitmap bmp, int col)
  112. {
  113. for (var i = 0; i < bmp.Height; ++i)
  114. {
  115. if (!IsTransparent(bmp.GetPixel(col, i)))
  116. {
  117. return false;
  118. }
  119. }
  120. return true;
  121. }
  122. private SKBitmap CropWhiteSpace(SKBitmap bitmap)
  123. {
  124. var topmost = 0;
  125. for (int row = 0; row < bitmap.Height; ++row)
  126. {
  127. if (IsTransparentRow(bitmap, row))
  128. {
  129. topmost = row + 1;
  130. }
  131. else
  132. {
  133. break;
  134. }
  135. }
  136. int bottommost = bitmap.Height;
  137. for (int row = bitmap.Height - 1; row >= 0; --row)
  138. {
  139. if (IsTransparentRow(bitmap, row))
  140. {
  141. bottommost = row;
  142. }
  143. else
  144. {
  145. break;
  146. }
  147. }
  148. int leftmost = 0, rightmost = bitmap.Width;
  149. for (int col = 0; col < bitmap.Width; ++col)
  150. {
  151. if (IsTransparentColumn(bitmap, col))
  152. {
  153. leftmost = col + 1;
  154. }
  155. else
  156. {
  157. break;
  158. }
  159. }
  160. for (int col = bitmap.Width - 1; col >= 0; --col)
  161. {
  162. if (IsTransparentColumn(bitmap, col))
  163. {
  164. rightmost = col;
  165. }
  166. else
  167. {
  168. break;
  169. }
  170. }
  171. var newRect = SKRectI.Create(leftmost, topmost, rightmost - leftmost, bottommost - topmost);
  172. using (var image = SKImage.FromBitmap(bitmap))
  173. using (var subset = image.Subset(newRect))
  174. {
  175. return SKBitmap.FromImage(subset);
  176. }
  177. }
  178. /// <inheritdoc />
  179. /// <exception cref="ArgumentNullException">If path is null.</exception>
  180. /// <exception cref="FileNotFoundException">If the path is not valid.</exception>
  181. /// <exception cref="SkiaCodecException">If the file at the specified path could not be used to generate a codec.</exception>
  182. public ImageDimensions GetImageSize(string path)
  183. {
  184. if (path == null)
  185. {
  186. throw new ArgumentNullException(nameof(path));
  187. }
  188. if (!File.Exists(path))
  189. {
  190. throw new FileNotFoundException("File not found", path);
  191. }
  192. using (var codec = SKCodec.Create(path, out SKCodecResult result))
  193. {
  194. EnsureSuccess(result);
  195. var info = codec.Info;
  196. return new ImageDimensions(info.Width, info.Height);
  197. }
  198. }
  199. private static bool HasDiacritics(string text)
  200. => !string.Equals(text, text.RemoveDiacritics(), StringComparison.Ordinal);
  201. private bool RequiresSpecialCharacterHack(string path)
  202. {
  203. if (_localizationManager.HasUnicodeCategory(path, UnicodeCategory.OtherLetter))
  204. {
  205. return true;
  206. }
  207. if (HasDiacritics(path))
  208. {
  209. return true;
  210. }
  211. return false;
  212. }
  213. private string NormalizePath(string path)
  214. {
  215. if (!RequiresSpecialCharacterHack(path))
  216. {
  217. return path;
  218. }
  219. var tempPath = Path.Combine(_appPaths.TempDirectory, Guid.NewGuid() + Path.GetExtension(path) ?? string.Empty);
  220. Directory.CreateDirectory(Path.GetDirectoryName(tempPath));
  221. File.Copy(path, tempPath, true);
  222. return tempPath;
  223. }
  224. private static SKEncodedOrigin GetSKEncodedOrigin(ImageOrientation? orientation)
  225. {
  226. if (!orientation.HasValue)
  227. {
  228. return SKEncodedOrigin.TopLeft;
  229. }
  230. switch (orientation.Value)
  231. {
  232. case ImageOrientation.TopRight:
  233. return SKEncodedOrigin.TopRight;
  234. case ImageOrientation.RightTop:
  235. return SKEncodedOrigin.RightTop;
  236. case ImageOrientation.RightBottom:
  237. return SKEncodedOrigin.RightBottom;
  238. case ImageOrientation.LeftTop:
  239. return SKEncodedOrigin.LeftTop;
  240. case ImageOrientation.LeftBottom:
  241. return SKEncodedOrigin.LeftBottom;
  242. case ImageOrientation.BottomRight:
  243. return SKEncodedOrigin.BottomRight;
  244. case ImageOrientation.BottomLeft:
  245. return SKEncodedOrigin.BottomLeft;
  246. default:
  247. return SKEncodedOrigin.TopLeft;
  248. }
  249. }
  250. internal SKBitmap Decode(string path, bool forceCleanBitmap, ImageOrientation? orientation, out SKEncodedOrigin origin)
  251. {
  252. if (!File.Exists(path))
  253. {
  254. throw new FileNotFoundException("File not found", path);
  255. }
  256. var requiresTransparencyHack = _transparentImageTypes.Contains(Path.GetExtension(path));
  257. if (requiresTransparencyHack || forceCleanBitmap)
  258. {
  259. using (var stream = new SKFileStream(NormalizePath(path)))
  260. using (var codec = SKCodec.Create(stream))
  261. {
  262. if (codec == null)
  263. {
  264. origin = GetSKEncodedOrigin(orientation);
  265. return null;
  266. }
  267. // create the bitmap
  268. var bitmap = new SKBitmap(codec.Info.Width, codec.Info.Height, !requiresTransparencyHack);
  269. // decode
  270. _ = codec.GetPixels(bitmap.Info, bitmap.GetPixels());
  271. origin = codec.EncodedOrigin;
  272. return bitmap;
  273. }
  274. }
  275. var resultBitmap = SKBitmap.Decode(NormalizePath(path));
  276. if (resultBitmap == null)
  277. {
  278. return Decode(path, true, orientation, out origin);
  279. }
  280. // If we have to resize these they often end up distorted
  281. if (resultBitmap.ColorType == SKColorType.Gray8)
  282. {
  283. using (resultBitmap)
  284. {
  285. return Decode(path, true, orientation, out origin);
  286. }
  287. }
  288. origin = SKEncodedOrigin.TopLeft;
  289. return resultBitmap;
  290. }
  291. private SKBitmap GetBitmap(string path, bool cropWhitespace, bool forceAnalyzeBitmap, ImageOrientation? orientation, out SKEncodedOrigin origin)
  292. {
  293. if (cropWhitespace)
  294. {
  295. using (var bitmap = Decode(path, forceAnalyzeBitmap, orientation, out origin))
  296. {
  297. return CropWhiteSpace(bitmap);
  298. }
  299. }
  300. return Decode(path, forceAnalyzeBitmap, orientation, out origin);
  301. }
  302. private SKBitmap GetBitmap(string path, bool cropWhitespace, bool autoOrient, ImageOrientation? orientation)
  303. {
  304. SKEncodedOrigin origin;
  305. if (autoOrient)
  306. {
  307. var bitmap = GetBitmap(path, cropWhitespace, true, orientation, out origin);
  308. if (bitmap != null && origin != SKEncodedOrigin.TopLeft)
  309. {
  310. using (bitmap)
  311. {
  312. return OrientImage(bitmap, origin);
  313. }
  314. }
  315. return bitmap;
  316. }
  317. return GetBitmap(path, cropWhitespace, false, orientation, out origin);
  318. }
  319. private SKBitmap OrientImage(SKBitmap bitmap, SKEncodedOrigin origin)
  320. {
  321. //var transformations = {
  322. // 2: { rotate: 0, flip: true},
  323. // 3: { rotate: 180, flip: false},
  324. // 4: { rotate: 180, flip: true},
  325. // 5: { rotate: 90, flip: true},
  326. // 6: { rotate: 90, flip: false},
  327. // 7: { rotate: 270, flip: true},
  328. // 8: { rotate: 270, flip: false},
  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. }