SkiaEncoder.cs 24 KB

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