SkiaEncoder.cs 24 KB

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