SkiaEncoder.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657
  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. // decode
  234. codec.GetPixels(bitmap.Info, bitmap.GetPixels());
  235. origin = codec.EncodedOrigin;
  236. return bitmap;
  237. }
  238. }
  239. var resultBitmap = SKBitmap.Decode(NormalizePath(path, fileSystem));
  240. if (resultBitmap == null)
  241. {
  242. return Decode(path, true, fileSystem, orientation, out origin);
  243. }
  244. // If we have to resize these they often end up distorted
  245. if (resultBitmap.ColorType == SKColorType.Gray8)
  246. {
  247. using (resultBitmap)
  248. {
  249. return Decode(path, true, fileSystem, orientation, out origin);
  250. }
  251. }
  252. origin = SKEncodedOrigin.TopLeft;
  253. return resultBitmap;
  254. }
  255. private SKBitmap GetBitmap(string path, bool cropWhitespace, bool forceAnalyzeBitmap, ImageOrientation? orientation, out SKEncodedOrigin origin)
  256. {
  257. if (cropWhitespace)
  258. {
  259. using (var bitmap = Decode(path, forceAnalyzeBitmap, _fileSystem, orientation, out origin))
  260. {
  261. return CropWhiteSpace(bitmap);
  262. }
  263. }
  264. return Decode(path, forceAnalyzeBitmap, _fileSystem, orientation, out origin);
  265. }
  266. private SKBitmap GetBitmap(string path, bool cropWhitespace, bool autoOrient, ImageOrientation? orientation)
  267. {
  268. SKEncodedOrigin origin;
  269. if (autoOrient)
  270. {
  271. var bitmap = GetBitmap(path, cropWhitespace, true, orientation, out origin);
  272. if (bitmap != null)
  273. {
  274. if (origin != SKEncodedOrigin.TopLeft)
  275. {
  276. using (bitmap)
  277. {
  278. return OrientImage(bitmap, origin);
  279. }
  280. }
  281. }
  282. return bitmap;
  283. }
  284. return GetBitmap(path, cropWhitespace, false, orientation, out origin);
  285. }
  286. private SKBitmap OrientImage(SKBitmap bitmap, SKEncodedOrigin origin)
  287. {
  288. //var transformations = {
  289. // 2: { rotate: 0, flip: true},
  290. // 3: { rotate: 180, flip: false},
  291. // 4: { rotate: 180, flip: true},
  292. // 5: { rotate: 90, flip: true},
  293. // 6: { rotate: 90, flip: false},
  294. // 7: { rotate: 270, flip: true},
  295. // 8: { rotate: 270, flip: false},
  296. //}
  297. switch (origin)
  298. {
  299. case SKEncodedOrigin.TopRight:
  300. {
  301. var rotated = new SKBitmap(bitmap.Width, bitmap.Height);
  302. using (var surface = new SKCanvas(rotated))
  303. {
  304. surface.Translate(rotated.Width, 0);
  305. surface.Scale(-1, 1);
  306. surface.DrawBitmap(bitmap, 0, 0);
  307. }
  308. return rotated;
  309. }
  310. case SKEncodedOrigin.BottomRight:
  311. {
  312. var rotated = new SKBitmap(bitmap.Width, bitmap.Height);
  313. using (var surface = new SKCanvas(rotated))
  314. {
  315. float px = bitmap.Width;
  316. px /= 2;
  317. float py = bitmap.Height;
  318. py /= 2;
  319. surface.RotateDegrees(180, px, py);
  320. surface.DrawBitmap(bitmap, 0, 0);
  321. }
  322. return rotated;
  323. }
  324. case SKEncodedOrigin.BottomLeft:
  325. {
  326. var rotated = new SKBitmap(bitmap.Width, bitmap.Height);
  327. using (var surface = new SKCanvas(rotated))
  328. {
  329. float px = bitmap.Width;
  330. px /= 2;
  331. float py = bitmap.Height;
  332. py /= 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:
  405. return bitmap;
  406. }
  407. }
  408. public string EncodeImage(string inputPath, DateTime dateModified, string outputPath, bool autoOrient, ImageOrientation? orientation, int quality, ImageProcessingOptions options, ImageFormat selectedOutputFormat)
  409. {
  410. if (string.IsNullOrWhiteSpace(inputPath))
  411. {
  412. throw new ArgumentNullException(nameof(inputPath));
  413. }
  414. if (string.IsNullOrWhiteSpace(inputPath))
  415. {
  416. throw new ArgumentNullException(nameof(outputPath));
  417. }
  418. var skiaOutputFormat = GetImageFormat(selectedOutputFormat);
  419. var hasBackgroundColor = !string.IsNullOrWhiteSpace(options.BackgroundColor);
  420. var hasForegroundColor = !string.IsNullOrWhiteSpace(options.ForegroundLayer);
  421. var blur = options.Blur ?? 0;
  422. var hasIndicator = options.AddPlayedIndicator || options.UnplayedCount.HasValue || !options.PercentPlayed.Equals(0);
  423. using (var bitmap = GetBitmap(inputPath, options.CropWhiteSpace, autoOrient, orientation))
  424. {
  425. if (bitmap == null)
  426. {
  427. throw new ArgumentOutOfRangeException(string.Format("Skia unable to read image {0}", inputPath));
  428. }
  429. //_logger.LogInformation("Color type {0}", bitmap.Info.ColorType);
  430. var originalImageSize = new ImageSize(bitmap.Width, bitmap.Height);
  431. if (!options.CropWhiteSpace && options.HasDefaultOptions(inputPath, originalImageSize) && !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 = Convert.ToInt32(Math.Round(newImageSize.Width));
  438. var height = Convert.ToInt32(Math.Round(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. _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(outputPath));
  447. using (var outputStream = new SKFileWStream(outputPath))
  448. {
  449. using (var pixmap = new SKPixmap(new SKImageInfo(width, height), resizedBitmap.GetPixels()))
  450. {
  451. pixmap.Encode(outputStream, skiaOutputFormat, quality);
  452. return outputPath;
  453. }
  454. }
  455. }
  456. // create bitmap to use for canvas drawing used to draw into bitmap
  457. using (var saveBitmap = new SKBitmap(width, height))//, bitmap.ColorType, bitmap.AlphaType))
  458. using (var canvas = new SKCanvas(saveBitmap))
  459. {
  460. // set background color if present
  461. if (hasBackgroundColor)
  462. {
  463. canvas.Clear(SKColor.Parse(options.BackgroundColor));
  464. }
  465. // Add blur if option is present
  466. if (blur > 0)
  467. {
  468. // create image from resized bitmap to apply blur
  469. using (var paint = new SKPaint())
  470. using (var filter = SKImageFilter.CreateBlur(blur, blur))
  471. {
  472. paint.ImageFilter = filter;
  473. canvas.DrawBitmap(resizedBitmap, SKRect.Create(width, height), paint);
  474. }
  475. }
  476. else
  477. {
  478. // draw resized bitmap onto canvas
  479. canvas.DrawBitmap(resizedBitmap, SKRect.Create(width, height));
  480. }
  481. // If foreground layer present then draw
  482. if (hasForegroundColor)
  483. {
  484. if (!double.TryParse(options.ForegroundLayer, out double opacity))
  485. {
  486. opacity = .4;
  487. }
  488. canvas.DrawColor(new SKColor(0, 0, 0, (byte)((1 - opacity) * 0xFF)), SKBlendMode.SrcOver);
  489. }
  490. if (hasIndicator)
  491. {
  492. DrawIndicator(canvas, width, height, options);
  493. }
  494. _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(outputPath));
  495. using (var outputStream = new SKFileWStream(outputPath))
  496. {
  497. using (var pixmap = new SKPixmap(new SKImageInfo(width, height), saveBitmap.GetPixels()))
  498. {
  499. pixmap.Encode(outputStream, skiaOutputFormat, quality);
  500. }
  501. }
  502. }
  503. }
  504. }
  505. return outputPath;
  506. }
  507. public void CreateImageCollage(ImageCollageOptions options)
  508. {
  509. double ratio = options.Width;
  510. ratio /= options.Height;
  511. if (ratio >= 1.4)
  512. {
  513. new StripCollageBuilder(_appPaths, _fileSystem).BuildThumbCollage(options.InputPaths, options.OutputPath, options.Width, options.Height);
  514. }
  515. else if (ratio >= .9)
  516. {
  517. new StripCollageBuilder(_appPaths, _fileSystem).BuildSquareCollage(options.InputPaths, options.OutputPath, options.Width, options.Height);
  518. }
  519. else
  520. {
  521. // @todo create Poster collage capability
  522. new StripCollageBuilder(_appPaths, _fileSystem).BuildSquareCollage(options.InputPaths, options.OutputPath, options.Width, options.Height);
  523. }
  524. }
  525. private void DrawIndicator(SKCanvas canvas, int imageWidth, int imageHeight, ImageProcessingOptions options)
  526. {
  527. try
  528. {
  529. var currentImageSize = new ImageSize(imageWidth, imageHeight);
  530. if (options.AddPlayedIndicator)
  531. {
  532. PlayedIndicatorDrawer.DrawPlayedIndicator(canvas, currentImageSize);
  533. }
  534. else if (options.UnplayedCount.HasValue)
  535. {
  536. UnplayedCountIndicator.DrawUnplayedCountIndicator(canvas, currentImageSize, options.UnplayedCount.Value);
  537. }
  538. if (options.PercentPlayed > 0)
  539. {
  540. PercentPlayedDrawer.Process(canvas, currentImageSize, options.PercentPlayed);
  541. }
  542. }
  543. catch (Exception ex)
  544. {
  545. _logger.LogError(ex, "Error drawing indicator overlay");
  546. }
  547. }
  548. public string Name => "Skia";
  549. public bool SupportsImageCollageCreation => true;
  550. public bool SupportsImageEncoding => true;
  551. }
  552. }