SkiaEncoder.cs 24 KB

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