SkiaEncoder.cs 25 KB

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