SkiaEncoder.cs 24 KB

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