SkiaEncoder.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664
  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 ImageSize 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 ImageSize
  154. {
  155. Width = info.Width,
  156. Height = info.Height
  157. };
  158. }
  159. }
  160. private static bool HasDiacritics(string text)
  161. {
  162. return !string.Equals(text, text.RemoveDiacritics(), StringComparison.Ordinal);
  163. }
  164. private static bool RequiresSpecialCharacterHack(string path)
  165. {
  166. if (_localizationManager.HasUnicodeCategory(path, UnicodeCategory.OtherLetter))
  167. {
  168. return true;
  169. }
  170. if (HasDiacritics(path))
  171. {
  172. return true;
  173. }
  174. return false;
  175. }
  176. private static string NormalizePath(string path, IFileSystem fileSystem)
  177. {
  178. if (!RequiresSpecialCharacterHack(path))
  179. {
  180. return path;
  181. }
  182. var tempPath = Path.Combine(_appPaths.TempDirectory, Guid.NewGuid() + Path.GetExtension(path) ?? string.Empty);
  183. fileSystem.CreateDirectory(fileSystem.GetDirectoryName(tempPath));
  184. fileSystem.CopyFile(path, tempPath, true);
  185. return tempPath;
  186. }
  187. private static SKEncodedOrigin GetSKEncodedOrigin(ImageOrientation? orientation)
  188. {
  189. if (!orientation.HasValue)
  190. {
  191. return SKEncodedOrigin.TopLeft;
  192. }
  193. switch (orientation.Value)
  194. {
  195. case ImageOrientation.TopRight:
  196. return SKEncodedOrigin.TopRight;
  197. case ImageOrientation.RightTop:
  198. return SKEncodedOrigin.RightTop;
  199. case ImageOrientation.RightBottom:
  200. return SKEncodedOrigin.RightBottom;
  201. case ImageOrientation.LeftTop:
  202. return SKEncodedOrigin.LeftTop;
  203. case ImageOrientation.LeftBottom:
  204. return SKEncodedOrigin.LeftBottom;
  205. case ImageOrientation.BottomRight:
  206. return SKEncodedOrigin.BottomRight;
  207. case ImageOrientation.BottomLeft:
  208. return SKEncodedOrigin.BottomLeft;
  209. default:
  210. return SKEncodedOrigin.TopLeft;
  211. }
  212. }
  213. private static string[] TransparentImageTypes = new string[] { ".png", ".gif", ".webp" };
  214. internal static SKBitmap Decode(string path, bool forceCleanBitmap, IFileSystem fileSystem, ImageOrientation? orientation, out SKEncodedOrigin origin)
  215. {
  216. if (!fileSystem.FileExists(path))
  217. {
  218. throw new FileNotFoundException("File not found", path);
  219. }
  220. var requiresTransparencyHack = TransparentImageTypes.Contains(Path.GetExtension(path) ?? string.Empty);
  221. if (requiresTransparencyHack || forceCleanBitmap)
  222. {
  223. using (var stream = new SKFileStream(NormalizePath(path, fileSystem)))
  224. using (var codec = SKCodec.Create(stream))
  225. {
  226. if (codec == null)
  227. {
  228. origin = GetSKEncodedOrigin(orientation);
  229. return null;
  230. }
  231. // create the bitmap
  232. var bitmap = new SKBitmap(codec.Info.Width, codec.Info.Height, !requiresTransparencyHack);
  233. if (bitmap != null)
  234. {
  235. // decode
  236. codec.GetPixels(bitmap.Info, bitmap.GetPixels());
  237. origin = codec.EncodedOrigin;
  238. }
  239. else
  240. {
  241. origin = GetSKEncodedOrigin(orientation);
  242. }
  243. return bitmap;
  244. }
  245. }
  246. var resultBitmap = SKBitmap.Decode(NormalizePath(path, fileSystem));
  247. if (resultBitmap == null)
  248. {
  249. return Decode(path, true, fileSystem, 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, fileSystem, 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, _fileSystem, orientation, out origin))
  267. {
  268. return CropWhiteSpace(bitmap);
  269. }
  270. }
  271. return Decode(path, forceAnalyzeBitmap, _fileSystem, 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)
  280. {
  281. if (origin != SKEncodedOrigin.TopLeft)
  282. {
  283. using (bitmap)
  284. {
  285. return OrientImage(bitmap, origin);
  286. }
  287. }
  288. }
  289. return bitmap;
  290. }
  291. return GetBitmap(path, cropWhitespace, false, orientation, out origin);
  292. }
  293. private SKBitmap OrientImage(SKBitmap bitmap, SKEncodedOrigin origin)
  294. {
  295. //var transformations = {
  296. // 2: { rotate: 0, flip: true},
  297. // 3: { rotate: 180, flip: false},
  298. // 4: { rotate: 180, flip: true},
  299. // 5: { rotate: 90, flip: true},
  300. // 6: { rotate: 90, flip: false},
  301. // 7: { rotate: 270, flip: true},
  302. // 8: { rotate: 270, flip: false},
  303. //}
  304. switch (origin)
  305. {
  306. case SKEncodedOrigin.TopRight:
  307. {
  308. var rotated = new SKBitmap(bitmap.Width, bitmap.Height);
  309. using (var surface = new SKCanvas(rotated))
  310. {
  311. surface.Translate(rotated.Width, 0);
  312. surface.Scale(-1, 1);
  313. surface.DrawBitmap(bitmap, 0, 0);
  314. }
  315. return rotated;
  316. }
  317. case SKEncodedOrigin.BottomRight:
  318. {
  319. var rotated = new SKBitmap(bitmap.Width, bitmap.Height);
  320. using (var surface = new SKCanvas(rotated))
  321. {
  322. float px = bitmap.Width;
  323. px /= 2;
  324. float py = bitmap.Height;
  325. py /= 2;
  326. surface.RotateDegrees(180, px, py);
  327. surface.DrawBitmap(bitmap, 0, 0);
  328. }
  329. return rotated;
  330. }
  331. case SKEncodedOrigin.BottomLeft:
  332. {
  333. var rotated = new SKBitmap(bitmap.Width, bitmap.Height);
  334. using (var surface = new SKCanvas(rotated))
  335. {
  336. float px = bitmap.Width;
  337. px /= 2;
  338. float py = bitmap.Height;
  339. py /= 2;
  340. surface.Translate(rotated.Width, 0);
  341. surface.Scale(-1, 1);
  342. surface.RotateDegrees(180, px, py);
  343. surface.DrawBitmap(bitmap, 0, 0);
  344. }
  345. return rotated;
  346. }
  347. case SKEncodedOrigin.LeftTop:
  348. {
  349. // TODO: Remove dual canvases, had trouble with flipping
  350. using (var rotated = new SKBitmap(bitmap.Height, bitmap.Width))
  351. {
  352. using (var surface = new SKCanvas(rotated))
  353. {
  354. surface.Translate(rotated.Width, 0);
  355. surface.RotateDegrees(90);
  356. surface.DrawBitmap(bitmap, 0, 0);
  357. }
  358. var flippedBitmap = new SKBitmap(rotated.Width, rotated.Height);
  359. using (var flippedCanvas = new SKCanvas(flippedBitmap))
  360. {
  361. flippedCanvas.Translate(flippedBitmap.Width, 0);
  362. flippedCanvas.Scale(-1, 1);
  363. flippedCanvas.DrawBitmap(rotated, 0, 0);
  364. }
  365. return flippedBitmap;
  366. }
  367. }
  368. case SKEncodedOrigin.RightTop:
  369. {
  370. var rotated = new SKBitmap(bitmap.Height, bitmap.Width);
  371. using (var surface = new SKCanvas(rotated))
  372. {
  373. surface.Translate(rotated.Width, 0);
  374. surface.RotateDegrees(90);
  375. surface.DrawBitmap(bitmap, 0, 0);
  376. }
  377. return rotated;
  378. }
  379. case SKEncodedOrigin.RightBottom:
  380. {
  381. // TODO: Remove dual canvases, had trouble with flipping
  382. using (var rotated = new SKBitmap(bitmap.Height, bitmap.Width))
  383. {
  384. using (var surface = new SKCanvas(rotated))
  385. {
  386. surface.Translate(0, rotated.Height);
  387. surface.RotateDegrees(270);
  388. surface.DrawBitmap(bitmap, 0, 0);
  389. }
  390. var flippedBitmap = new SKBitmap(rotated.Width, rotated.Height);
  391. using (var flippedCanvas = new SKCanvas(flippedBitmap))
  392. {
  393. flippedCanvas.Translate(flippedBitmap.Width, 0);
  394. flippedCanvas.Scale(-1, 1);
  395. flippedCanvas.DrawBitmap(rotated, 0, 0);
  396. }
  397. return flippedBitmap;
  398. }
  399. }
  400. case SKEncodedOrigin.LeftBottom:
  401. {
  402. var rotated = new SKBitmap(bitmap.Height, bitmap.Width);
  403. using (var surface = new SKCanvas(rotated))
  404. {
  405. surface.Translate(0, rotated.Height);
  406. surface.RotateDegrees(270);
  407. surface.DrawBitmap(bitmap, 0, 0);
  408. }
  409. return rotated;
  410. }
  411. default:
  412. return bitmap;
  413. }
  414. }
  415. public string EncodeImage(string inputPath, DateTime dateModified, string outputPath, bool autoOrient, ImageOrientation? orientation, int quality, ImageProcessingOptions options, ImageFormat selectedOutputFormat)
  416. {
  417. if (string.IsNullOrWhiteSpace(inputPath))
  418. {
  419. throw new ArgumentNullException(nameof(inputPath));
  420. }
  421. if (string.IsNullOrWhiteSpace(inputPath))
  422. {
  423. throw new ArgumentNullException(nameof(outputPath));
  424. }
  425. var skiaOutputFormat = GetImageFormat(selectedOutputFormat);
  426. var hasBackgroundColor = !string.IsNullOrWhiteSpace(options.BackgroundColor);
  427. var hasForegroundColor = !string.IsNullOrWhiteSpace(options.ForegroundLayer);
  428. var blur = options.Blur ?? 0;
  429. var hasIndicator = options.AddPlayedIndicator || options.UnplayedCount.HasValue || !options.PercentPlayed.Equals(0);
  430. using (var bitmap = GetBitmap(inputPath, options.CropWhiteSpace, autoOrient, orientation))
  431. {
  432. if (bitmap == null)
  433. {
  434. throw new ArgumentOutOfRangeException(string.Format("Skia unable to read image {0}", inputPath));
  435. }
  436. //_logger.LogInformation("Color type {0}", bitmap.Info.ColorType);
  437. var originalImageSize = new ImageSize(bitmap.Width, bitmap.Height);
  438. if (!options.CropWhiteSpace && options.HasDefaultOptions(inputPath, originalImageSize) && !autoOrient)
  439. {
  440. // Just spit out the original file if all the options are default
  441. return inputPath;
  442. }
  443. var newImageSize = ImageHelper.GetNewImageSize(options, originalImageSize);
  444. var width = Convert.ToInt32(Math.Round(newImageSize.Width));
  445. var height = Convert.ToInt32(Math.Round(newImageSize.Height));
  446. using (var resizedBitmap = new SKBitmap(width, height))//, bitmap.ColorType, bitmap.AlphaType))
  447. {
  448. // scale image
  449. bitmap.ScalePixels(resizedBitmap, SKFilterQuality.High);
  450. // If all we're doing is resizing then we can stop now
  451. if (!hasBackgroundColor && !hasForegroundColor && blur == 0 && !hasIndicator)
  452. {
  453. _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(outputPath));
  454. using (var outputStream = new SKFileWStream(outputPath))
  455. {
  456. using (var pixmap = new SKPixmap(new SKImageInfo(width, height), resizedBitmap.GetPixels()))
  457. {
  458. pixmap.Encode(outputStream, skiaOutputFormat, quality);
  459. return outputPath;
  460. }
  461. }
  462. }
  463. // create bitmap to use for canvas drawing used to draw into bitmap
  464. using (var saveBitmap = new SKBitmap(width, height))//, bitmap.ColorType, bitmap.AlphaType))
  465. using (var canvas = new SKCanvas(saveBitmap))
  466. {
  467. // set background color if present
  468. if (hasBackgroundColor)
  469. {
  470. canvas.Clear(SKColor.Parse(options.BackgroundColor));
  471. }
  472. // Add blur if option is present
  473. if (blur > 0)
  474. {
  475. // create image from resized bitmap to apply blur
  476. using (var paint = new SKPaint())
  477. using (var filter = SKImageFilter.CreateBlur(blur, blur))
  478. {
  479. paint.ImageFilter = filter;
  480. canvas.DrawBitmap(resizedBitmap, SKRect.Create(width, height), paint);
  481. }
  482. }
  483. else
  484. {
  485. // draw resized bitmap onto canvas
  486. canvas.DrawBitmap(resizedBitmap, SKRect.Create(width, height));
  487. }
  488. // If foreground layer present then draw
  489. if (hasForegroundColor)
  490. {
  491. if (!double.TryParse(options.ForegroundLayer, out double opacity))
  492. {
  493. opacity = .4;
  494. }
  495. canvas.DrawColor(new SKColor(0, 0, 0, (byte)((1 - opacity) * 0xFF)), SKBlendMode.SrcOver);
  496. }
  497. if (hasIndicator)
  498. {
  499. DrawIndicator(canvas, width, height, options);
  500. }
  501. _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(outputPath));
  502. using (var outputStream = new SKFileWStream(outputPath))
  503. {
  504. using (var pixmap = new SKPixmap(new SKImageInfo(width, height), saveBitmap.GetPixels()))
  505. {
  506. pixmap.Encode(outputStream, skiaOutputFormat, quality);
  507. }
  508. }
  509. }
  510. }
  511. }
  512. return outputPath;
  513. }
  514. public void CreateImageCollage(ImageCollageOptions options)
  515. {
  516. double ratio = options.Width;
  517. ratio /= options.Height;
  518. if (ratio >= 1.4)
  519. {
  520. new StripCollageBuilder(_appPaths, _fileSystem).BuildThumbCollage(options.InputPaths, options.OutputPath, options.Width, options.Height);
  521. }
  522. else if (ratio >= .9)
  523. {
  524. new StripCollageBuilder(_appPaths, _fileSystem).BuildSquareCollage(options.InputPaths, options.OutputPath, options.Width, options.Height);
  525. }
  526. else
  527. {
  528. // @todo create Poster collage capability
  529. new StripCollageBuilder(_appPaths, _fileSystem).BuildSquareCollage(options.InputPaths, options.OutputPath, options.Width, options.Height);
  530. }
  531. }
  532. private void DrawIndicator(SKCanvas canvas, int imageWidth, int imageHeight, ImageProcessingOptions options)
  533. {
  534. try
  535. {
  536. var currentImageSize = new ImageSize(imageWidth, imageHeight);
  537. if (options.AddPlayedIndicator)
  538. {
  539. PlayedIndicatorDrawer.DrawPlayedIndicator(canvas, currentImageSize);
  540. }
  541. else if (options.UnplayedCount.HasValue)
  542. {
  543. UnplayedCountIndicator.DrawUnplayedCountIndicator(canvas, currentImageSize, options.UnplayedCount.Value);
  544. }
  545. if (options.PercentPlayed > 0)
  546. {
  547. PercentPlayedDrawer.Process(canvas, currentImageSize, options.PercentPlayed);
  548. }
  549. }
  550. catch (Exception ex)
  551. {
  552. _logger.LogError(ex, "Error drawing indicator overlay");
  553. }
  554. }
  555. public string Name => "Skia";
  556. public bool SupportsImageCollageCreation => true;
  557. public bool SupportsImageEncoding => true;
  558. }
  559. }