SkiaEncoder.cs 23 KB

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