SkiaEncoder.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612
  1. using MediaBrowser.Common.Configuration;
  2. using MediaBrowser.Common.Net;
  3. using MediaBrowser.Controller.Drawing;
  4. using MediaBrowser.Model.Drawing;
  5. using MediaBrowser.Model.IO;
  6. using MediaBrowser.Model.Logging;
  7. using SkiaSharp;
  8. using System;
  9. using System.IO;
  10. using System.Linq;
  11. using System.Reflection;
  12. using System.Threading.Tasks;
  13. namespace Emby.Drawing.Skia
  14. {
  15. public class SkiaEncoder : IImageEncoder
  16. {
  17. private readonly ILogger _logger;
  18. private readonly IApplicationPaths _appPaths;
  19. private readonly Func<IHttpClient> _httpClientFactory;
  20. private readonly IFileSystem _fileSystem;
  21. public SkiaEncoder(ILogger logger, IApplicationPaths appPaths, Func<IHttpClient> httpClientFactory, IFileSystem fileSystem)
  22. {
  23. _logger = logger;
  24. _appPaths = appPaths;
  25. _httpClientFactory = httpClientFactory;
  26. _fileSystem = fileSystem;
  27. LogVersion();
  28. }
  29. public string[] SupportedInputFormats
  30. {
  31. get
  32. {
  33. // Some common file name extensions for RAW picture files include: .cr2, .crw, .dng, .nef, .orf, .rw2, .pef, .arw, .sr2, .srf, and .tif.
  34. return 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. // working on windows at least
  49. "cr2",
  50. "nef"
  51. };
  52. }
  53. }
  54. public ImageFormat[] SupportedOutputFormats
  55. {
  56. get
  57. {
  58. return new[] { ImageFormat.Webp, ImageFormat.Gif, ImageFormat.Jpg, ImageFormat.Png, ImageFormat.Bmp };
  59. }
  60. }
  61. private void LogVersion()
  62. {
  63. // test an operation that requires the native library
  64. SKPMColor.PreMultiply(SKColors.Black);
  65. _logger.Info("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. {
  147. using (var subset = image.Subset(newRect))
  148. {
  149. return SKBitmap.FromImage(subset);
  150. }
  151. }
  152. }
  153. public ImageSize GetImageSize(string path)
  154. {
  155. using (var s = new SKFileStream(path))
  156. {
  157. using (var codec = SKCodec.Create(s))
  158. {
  159. var info = codec.Info;
  160. return new ImageSize
  161. {
  162. Width = info.Width,
  163. Height = info.Height
  164. };
  165. }
  166. }
  167. }
  168. private static string[] TransparentImageTypes = new string[] { ".png", ".gif", ".webp" };
  169. internal static SKBitmap Decode(string path, bool forceCleanBitmap, out SKCodecOrigin origin)
  170. {
  171. var requiresTransparencyHack = TransparentImageTypes.Contains(Path.GetExtension(path) ?? string.Empty);
  172. if (requiresTransparencyHack || forceCleanBitmap)
  173. {
  174. using (var stream = new SKFileStream(path))
  175. {
  176. using (var codec = SKCodec.Create(stream))
  177. {
  178. if (codec == null)
  179. {
  180. origin = SKCodecOrigin.TopLeft;
  181. return null;
  182. }
  183. // create the bitmap
  184. var bitmap = new SKBitmap(codec.Info.Width, codec.Info.Height, !requiresTransparencyHack);
  185. if (bitmap != null)
  186. {
  187. // decode
  188. codec.GetPixels(bitmap.Info, bitmap.GetPixels());
  189. origin = codec.Origin;
  190. }
  191. else
  192. {
  193. origin = SKCodecOrigin.TopLeft;
  194. }
  195. return bitmap;
  196. }
  197. }
  198. }
  199. var resultBitmap = SKBitmap.Decode(path);
  200. if (resultBitmap == null)
  201. {
  202. return Decode(path, true, out origin);
  203. }
  204. // If we have to resize these they often end up distorted
  205. if (resultBitmap.ColorType == SKColorType.Gray8)
  206. {
  207. using (resultBitmap)
  208. {
  209. return Decode(path, true, out origin);
  210. }
  211. }
  212. origin = SKCodecOrigin.TopLeft;
  213. return resultBitmap;
  214. }
  215. private SKBitmap GetBitmap(string path, bool cropWhitespace, bool forceAnalyzeBitmap, out SKCodecOrigin origin)
  216. {
  217. if (cropWhitespace)
  218. {
  219. using (var bitmap = Decode(path, forceAnalyzeBitmap, out origin))
  220. {
  221. return CropWhiteSpace(bitmap);
  222. }
  223. }
  224. return Decode(path, forceAnalyzeBitmap, out origin);
  225. }
  226. private SKBitmap GetBitmap(string path, bool cropWhitespace, bool autoOrient)
  227. {
  228. SKCodecOrigin origin;
  229. if (autoOrient)
  230. {
  231. var bitmap = GetBitmap(path, cropWhitespace, true, out origin);
  232. if (bitmap != null)
  233. {
  234. if (origin != SKCodecOrigin.TopLeft)
  235. {
  236. using (bitmap)
  237. {
  238. return OrientImage(bitmap, origin);
  239. }
  240. }
  241. }
  242. return bitmap;
  243. }
  244. return GetBitmap(path, cropWhitespace, false, out origin);
  245. }
  246. private SKBitmap OrientImage(SKBitmap bitmap, SKCodecOrigin origin)
  247. {
  248. //var transformations = {
  249. // 2: { rotate: 0, flip: true},
  250. // 3: { rotate: 180, flip: false},
  251. // 4: { rotate: 180, flip: true},
  252. // 5: { rotate: 90, flip: true},
  253. // 6: { rotate: 90, flip: false},
  254. // 7: { rotate: 270, flip: true},
  255. // 8: { rotate: 270, flip: false},
  256. //}
  257. switch (origin)
  258. {
  259. case SKCodecOrigin.TopRight:
  260. {
  261. var rotated = new SKBitmap(bitmap.Width, bitmap.Height);
  262. using (var surface = new SKCanvas(rotated))
  263. {
  264. surface.Translate(rotated.Width, 0);
  265. surface.Scale(-1, 1);
  266. surface.DrawBitmap(bitmap, 0, 0);
  267. }
  268. return rotated;
  269. }
  270. case SKCodecOrigin.BottomRight:
  271. {
  272. var rotated = new SKBitmap(bitmap.Width, bitmap.Height);
  273. using (var surface = new SKCanvas(rotated))
  274. {
  275. float px = bitmap.Width;
  276. px /= 2;
  277. float py = bitmap.Height;
  278. py /= 2;
  279. surface.RotateDegrees(180, px, py);
  280. surface.DrawBitmap(bitmap, 0, 0);
  281. }
  282. return rotated;
  283. }
  284. case SKCodecOrigin.BottomLeft:
  285. {
  286. var rotated = new SKBitmap(bitmap.Width, bitmap.Height);
  287. using (var surface = new SKCanvas(rotated))
  288. {
  289. float px = bitmap.Width;
  290. px /= 2;
  291. float py = bitmap.Height;
  292. py /= 2;
  293. surface.Translate(rotated.Width, 0);
  294. surface.Scale(-1, 1);
  295. surface.RotateDegrees(180, px, py);
  296. surface.DrawBitmap(bitmap, 0, 0);
  297. }
  298. return rotated;
  299. }
  300. case SKCodecOrigin.LeftTop:
  301. {
  302. // TODO: Remove dual canvases, had trouble with flipping
  303. using (var rotated = new SKBitmap(bitmap.Height, bitmap.Width))
  304. {
  305. using (var surface = new SKCanvas(rotated))
  306. {
  307. surface.Translate(rotated.Width, 0);
  308. surface.RotateDegrees(90);
  309. surface.DrawBitmap(bitmap, 0, 0);
  310. }
  311. var flippedBitmap = new SKBitmap(rotated.Width, rotated.Height);
  312. using (var flippedCanvas = new SKCanvas(flippedBitmap))
  313. {
  314. flippedCanvas.Translate(flippedBitmap.Width, 0);
  315. flippedCanvas.Scale(-1, 1);
  316. flippedCanvas.DrawBitmap(rotated, 0, 0);
  317. }
  318. return flippedBitmap;
  319. }
  320. }
  321. case SKCodecOrigin.RightTop:
  322. {
  323. var rotated = new SKBitmap(bitmap.Height, bitmap.Width);
  324. using (var surface = new SKCanvas(rotated))
  325. {
  326. surface.Translate(rotated.Width, 0);
  327. surface.RotateDegrees(90);
  328. surface.DrawBitmap(bitmap, 0, 0);
  329. }
  330. return rotated;
  331. }
  332. case SKCodecOrigin.RightBottom:
  333. {
  334. // TODO: Remove dual canvases, had trouble with flipping
  335. using (var rotated = new SKBitmap(bitmap.Height, bitmap.Width))
  336. {
  337. using (var surface = new SKCanvas(rotated))
  338. {
  339. surface.Translate(0, rotated.Height);
  340. surface.RotateDegrees(270);
  341. surface.DrawBitmap(bitmap, 0, 0);
  342. }
  343. var flippedBitmap = new SKBitmap(rotated.Width, rotated.Height);
  344. using (var flippedCanvas = new SKCanvas(flippedBitmap))
  345. {
  346. flippedCanvas.Translate(flippedBitmap.Width, 0);
  347. flippedCanvas.Scale(-1, 1);
  348. flippedCanvas.DrawBitmap(rotated, 0, 0);
  349. }
  350. return flippedBitmap;
  351. }
  352. }
  353. case SKCodecOrigin.LeftBottom:
  354. {
  355. var rotated = new SKBitmap(bitmap.Height, bitmap.Width);
  356. using (var surface = new SKCanvas(rotated))
  357. {
  358. surface.Translate(0, rotated.Height);
  359. surface.RotateDegrees(270);
  360. surface.DrawBitmap(bitmap, 0, 0);
  361. }
  362. return rotated;
  363. }
  364. default:
  365. return bitmap;
  366. }
  367. }
  368. public string EncodeImage(string inputPath, DateTime dateModified, string outputPath, bool autoOrient, ImageOrientation? orientation, int quality, ImageProcessingOptions options, ImageFormat selectedOutputFormat)
  369. {
  370. if (string.IsNullOrWhiteSpace(inputPath))
  371. {
  372. throw new ArgumentNullException("inputPath");
  373. }
  374. if (string.IsNullOrWhiteSpace(inputPath))
  375. {
  376. throw new ArgumentNullException("outputPath");
  377. }
  378. var skiaOutputFormat = GetImageFormat(selectedOutputFormat);
  379. var hasBackgroundColor = !string.IsNullOrWhiteSpace(options.BackgroundColor);
  380. var hasForegroundColor = !string.IsNullOrWhiteSpace(options.ForegroundLayer);
  381. var blur = options.Blur ?? 0;
  382. var hasIndicator = options.AddPlayedIndicator || options.UnplayedCount.HasValue || !options.PercentPlayed.Equals(0);
  383. using (var bitmap = GetBitmap(inputPath, options.CropWhiteSpace, autoOrient))
  384. {
  385. if (bitmap == null)
  386. {
  387. throw new ArgumentOutOfRangeException(string.Format("Skia unable to read image {0}", inputPath));
  388. }
  389. //_logger.Info("Color type {0}", bitmap.Info.ColorType);
  390. var originalImageSize = new ImageSize(bitmap.Width, bitmap.Height);
  391. if (!options.CropWhiteSpace && options.HasDefaultOptions(inputPath, originalImageSize) && !autoOrient)
  392. {
  393. // Just spit out the original file if all the options are default
  394. return inputPath;
  395. }
  396. var newImageSize = ImageHelper.GetNewImageSize(options, originalImageSize);
  397. var width = Convert.ToInt32(Math.Round(newImageSize.Width));
  398. var height = Convert.ToInt32(Math.Round(newImageSize.Height));
  399. using (var resizedBitmap = new SKBitmap(width, height))//, bitmap.ColorType, bitmap.AlphaType))
  400. {
  401. // scale image
  402. var resizeMethod = SKBitmapResizeMethod.Lanczos3;
  403. bitmap.Resize(resizedBitmap, resizeMethod);
  404. // If all we're doing is resizing then we can stop now
  405. if (!hasBackgroundColor && !hasForegroundColor && blur == 0 && !hasIndicator)
  406. {
  407. using (var outputStream = new SKFileWStream(outputPath))
  408. {
  409. resizedBitmap.Encode(outputStream, skiaOutputFormat, quality);
  410. return outputPath;
  411. }
  412. }
  413. // create bitmap to use for canvas drawing
  414. using (var saveBitmap = new SKBitmap(width, height))//, bitmap.ColorType, bitmap.AlphaType))
  415. {
  416. // create canvas used to draw into bitmap
  417. using (var canvas = new SKCanvas(saveBitmap))
  418. {
  419. // set background color if present
  420. if (hasBackgroundColor)
  421. {
  422. canvas.Clear(SKColor.Parse(options.BackgroundColor));
  423. }
  424. // Add blur if option is present
  425. if (blur > 0)
  426. {
  427. using (var paint = new SKPaint())
  428. {
  429. // create image from resized bitmap to apply blur
  430. using (var filter = SKImageFilter.CreateBlur(blur, blur))
  431. {
  432. paint.ImageFilter = filter;
  433. canvas.DrawBitmap(resizedBitmap, SKRect.Create(width, height), paint);
  434. }
  435. }
  436. }
  437. else
  438. {
  439. // draw resized bitmap onto canvas
  440. canvas.DrawBitmap(resizedBitmap, SKRect.Create(width, height));
  441. }
  442. // If foreground layer present then draw
  443. if (hasForegroundColor)
  444. {
  445. Double opacity;
  446. if (!Double.TryParse(options.ForegroundLayer, out opacity)) opacity = .4;
  447. canvas.DrawColor(new SKColor(0, 0, 0, (Byte)((1 - opacity) * 0xFF)), SKBlendMode.SrcOver);
  448. }
  449. if (hasIndicator)
  450. {
  451. DrawIndicator(canvas, width, height, options);
  452. }
  453. using (var outputStream = new SKFileWStream(outputPath))
  454. {
  455. saveBitmap.Encode(outputStream, skiaOutputFormat, quality);
  456. }
  457. }
  458. }
  459. }
  460. }
  461. return outputPath;
  462. }
  463. public void CreateImageCollage(ImageCollageOptions options)
  464. {
  465. double ratio = options.Width;
  466. ratio /= options.Height;
  467. if (ratio >= 1.4)
  468. {
  469. new StripCollageBuilder(_appPaths, _fileSystem).BuildThumbCollage(options.InputPaths, options.OutputPath, options.Width, options.Height);
  470. }
  471. else if (ratio >= .9)
  472. {
  473. new StripCollageBuilder(_appPaths, _fileSystem).BuildSquareCollage(options.InputPaths, options.OutputPath, options.Width, options.Height);
  474. }
  475. else
  476. {
  477. // @todo create Poster collage capability
  478. new StripCollageBuilder(_appPaths, _fileSystem).BuildSquareCollage(options.InputPaths, options.OutputPath, options.Width, options.Height);
  479. }
  480. }
  481. private void DrawIndicator(SKCanvas canvas, int imageWidth, int imageHeight, ImageProcessingOptions options)
  482. {
  483. try
  484. {
  485. var currentImageSize = new ImageSize(imageWidth, imageHeight);
  486. if (options.AddPlayedIndicator)
  487. {
  488. var task = new PlayedIndicatorDrawer(_appPaths, _httpClientFactory(), _fileSystem).DrawPlayedIndicator(canvas, currentImageSize);
  489. Task.WaitAll(task);
  490. }
  491. else if (options.UnplayedCount.HasValue)
  492. {
  493. new UnplayedCountIndicator(_appPaths, _httpClientFactory(), _fileSystem).DrawUnplayedCountIndicator(canvas, currentImageSize, options.UnplayedCount.Value);
  494. }
  495. if (options.PercentPlayed > 0)
  496. {
  497. new PercentPlayedDrawer().Process(canvas, currentImageSize, options.PercentPlayed);
  498. }
  499. }
  500. catch (Exception ex)
  501. {
  502. _logger.ErrorException("Error drawing indicator overlay", ex);
  503. }
  504. }
  505. public string Name
  506. {
  507. get { return "Skia"; }
  508. }
  509. public bool SupportsImageCollageCreation
  510. {
  511. get { return true; }
  512. }
  513. public bool SupportsImageEncoding
  514. {
  515. get { return true; }
  516. }
  517. }
  518. }