SkiaEncoder.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521
  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. };
  49. }
  50. }
  51. public ImageFormat[] SupportedOutputFormats
  52. {
  53. get
  54. {
  55. return new[] { ImageFormat.Webp, ImageFormat.Gif, ImageFormat.Jpg, ImageFormat.Png, ImageFormat.Bmp };
  56. }
  57. }
  58. private void LogVersion()
  59. {
  60. // test an operation that requires the native library
  61. SKPMColor.PreMultiply(SKColors.Black);
  62. _logger.Info("SkiaSharp version: " + GetVersion());
  63. }
  64. public static string GetVersion()
  65. {
  66. return typeof(SKBitmap).GetTypeInfo().Assembly.GetName().Version.ToString();
  67. }
  68. private static bool IsWhiteSpace(SKColor color)
  69. {
  70. return (color.Red == 255 && color.Green == 255 && color.Blue == 255) || color.Alpha == 0;
  71. }
  72. public static SKEncodedImageFormat GetImageFormat(ImageFormat selectedFormat)
  73. {
  74. switch (selectedFormat)
  75. {
  76. case ImageFormat.Bmp:
  77. return SKEncodedImageFormat.Bmp;
  78. case ImageFormat.Jpg:
  79. return SKEncodedImageFormat.Jpeg;
  80. case ImageFormat.Gif:
  81. return SKEncodedImageFormat.Gif;
  82. case ImageFormat.Webp:
  83. return SKEncodedImageFormat.Webp;
  84. default:
  85. return SKEncodedImageFormat.Png;
  86. }
  87. }
  88. private static bool IsAllWhiteRow(SKBitmap bmp, int row)
  89. {
  90. for (var i = 0; i < bmp.Width; ++i)
  91. {
  92. if (!IsWhiteSpace(bmp.GetPixel(i, row)))
  93. {
  94. return false;
  95. }
  96. }
  97. return true;
  98. }
  99. private static bool IsAllWhiteColumn(SKBitmap bmp, int col)
  100. {
  101. for (var i = 0; i < bmp.Height; ++i)
  102. {
  103. if (!IsWhiteSpace(bmp.GetPixel(col, i)))
  104. {
  105. return false;
  106. }
  107. }
  108. return true;
  109. }
  110. private SKBitmap CropWhiteSpace(SKBitmap bitmap)
  111. {
  112. var topmost = 0;
  113. for (int row = 0; row < bitmap.Height; ++row)
  114. {
  115. if (IsAllWhiteRow(bitmap, row))
  116. topmost = row + 1;
  117. else break;
  118. }
  119. int bottommost = bitmap.Height;
  120. for (int row = bitmap.Height - 1; row >= 0; --row)
  121. {
  122. if (IsAllWhiteRow(bitmap, row))
  123. bottommost = row;
  124. else break;
  125. }
  126. int leftmost = 0, rightmost = bitmap.Width;
  127. for (int col = 0; col < bitmap.Width; ++col)
  128. {
  129. if (IsAllWhiteColumn(bitmap, col))
  130. leftmost = col + 1;
  131. else
  132. break;
  133. }
  134. for (int col = bitmap.Width - 1; col >= 0; --col)
  135. {
  136. if (IsAllWhiteColumn(bitmap, col))
  137. rightmost = col;
  138. else
  139. break;
  140. }
  141. var newRect = SKRectI.Create(leftmost, topmost, rightmost - leftmost, bottommost - topmost);
  142. using (var image = SKImage.FromBitmap(bitmap))
  143. {
  144. using (var subset = image.Subset(newRect))
  145. {
  146. return SKBitmap.FromImage(subset);
  147. }
  148. }
  149. }
  150. public ImageSize GetImageSize(string path)
  151. {
  152. using (var s = new SKFileStream(path))
  153. {
  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. }
  165. private string[] TransparentImageTypes = new string[] { ".png", ".gif", ".webp" };
  166. private SKBitmap Decode(string path, bool forceCleanBitmap, out SKCodecOrigin origin)
  167. {
  168. var requiresTransparencyHack = TransparentImageTypes.Contains(Path.GetExtension(path) ?? string.Empty);
  169. if (requiresTransparencyHack || forceCleanBitmap)
  170. {
  171. using (var stream = new SKFileStream(path))
  172. {
  173. var codec = SKCodec.Create(stream);
  174. // create the bitmap
  175. var bitmap = new SKBitmap(codec.Info.Width, codec.Info.Height, !requiresTransparencyHack);
  176. // decode
  177. codec.GetPixels(bitmap.Info, bitmap.GetPixels());
  178. origin = codec.Origin;
  179. return bitmap;
  180. }
  181. }
  182. var resultBitmap = SKBitmap.Decode(path);
  183. if (resultBitmap == null)
  184. {
  185. return Decode(path, true, out origin);
  186. }
  187. // If we have to resize these they often end up distorted
  188. if (resultBitmap.ColorType == SKColorType.Gray8)
  189. {
  190. using (resultBitmap)
  191. {
  192. return Decode(path, true, out origin);
  193. }
  194. }
  195. origin = SKCodecOrigin.TopLeft;
  196. return resultBitmap;
  197. }
  198. private SKBitmap GetBitmap(string path, bool cropWhitespace, bool forceAnalyzeBitmap, out SKCodecOrigin origin)
  199. {
  200. if (cropWhitespace)
  201. {
  202. using (var bitmap = Decode(path, forceAnalyzeBitmap, out origin))
  203. {
  204. return CropWhiteSpace(bitmap);
  205. }
  206. }
  207. return Decode(path, forceAnalyzeBitmap, out origin);
  208. }
  209. private SKBitmap GetBitmap(string path, bool cropWhitespace, bool autoOrient, ImageOrientation? orientation)
  210. {
  211. SKCodecOrigin origin;
  212. if (autoOrient)
  213. {
  214. var bitmap = GetBitmap(path, cropWhitespace, true, out origin);
  215. if (origin != SKCodecOrigin.TopLeft)
  216. {
  217. using (bitmap)
  218. {
  219. return RotateAndFlip(bitmap, origin);
  220. }
  221. }
  222. return bitmap;
  223. }
  224. return GetBitmap(path, cropWhitespace, false, out origin);
  225. }
  226. private SKBitmap RotateAndFlip(SKBitmap original, SKCodecOrigin origin)
  227. {
  228. // these are the origins that represent a 90 degree turn in some fashion
  229. var differentOrientations = new SKCodecOrigin[]
  230. {
  231. SKCodecOrigin.LeftBottom,
  232. SKCodecOrigin.LeftTop,
  233. SKCodecOrigin.RightBottom,
  234. SKCodecOrigin.RightTop
  235. };
  236. // check if we need to turn the image
  237. bool isDifferentOrientation = differentOrientations.Any(o => o == origin);
  238. // define new width/height
  239. var width = isDifferentOrientation ? original.Height : original.Width;
  240. var height = isDifferentOrientation ? original.Width : original.Height;
  241. var bitmap = new SKBitmap(width, height, true);
  242. // todo: the stuff in this switch statement should be rewritten to use pointers
  243. switch (origin)
  244. {
  245. case SKCodecOrigin.LeftBottom:
  246. for (var x = 0; x < original.Width; x++)
  247. for (var y = 0; y < original.Height; y++)
  248. bitmap.SetPixel(y, original.Width - 1 - x, original.GetPixel(x, y));
  249. break;
  250. case SKCodecOrigin.RightTop:
  251. for (var x = 0; x < original.Width; x++)
  252. for (var y = 0; y < original.Height; y++)
  253. bitmap.SetPixel(original.Height - 1 - y, x, original.GetPixel(x, y));
  254. break;
  255. case SKCodecOrigin.RightBottom:
  256. for (var x = 0; x < original.Width; x++)
  257. for (var y = 0; y < original.Height; y++)
  258. bitmap.SetPixel(original.Height - 1 - y, original.Width - 1 - x, original.GetPixel(x, y));
  259. break;
  260. case SKCodecOrigin.LeftTop:
  261. for (var x = 0; x < original.Width; x++)
  262. for (var y = 0; y < original.Height; y++)
  263. bitmap.SetPixel(y, x, original.GetPixel(x, y));
  264. break;
  265. case SKCodecOrigin.BottomLeft:
  266. for (var x = 0; x < original.Width; x++)
  267. for (var y = 0; y < original.Height; y++)
  268. bitmap.SetPixel(x, original.Height - 1 - y, original.GetPixel(x, y));
  269. break;
  270. case SKCodecOrigin.BottomRight:
  271. for (var x = 0; x < original.Width; x++)
  272. for (var y = 0; y < original.Height; y++)
  273. bitmap.SetPixel(original.Width - 1 - x, original.Height - 1 - y, original.GetPixel(x, y));
  274. break;
  275. case SKCodecOrigin.TopRight:
  276. for (var x = 0; x < original.Width; x++)
  277. for (var y = 0; y < original.Height; y++)
  278. bitmap.SetPixel(original.Width - 1 - x, y, original.GetPixel(x, y));
  279. break;
  280. }
  281. return bitmap;
  282. }
  283. public string EncodeImage(string inputPath, DateTime dateModified, string outputPath, bool autoOrient, ImageOrientation? orientation, int quality, ImageProcessingOptions options, ImageFormat selectedOutputFormat)
  284. {
  285. if (string.IsNullOrWhiteSpace(inputPath))
  286. {
  287. throw new ArgumentNullException("inputPath");
  288. }
  289. if (string.IsNullOrWhiteSpace(inputPath))
  290. {
  291. throw new ArgumentNullException("outputPath");
  292. }
  293. var skiaOutputFormat = GetImageFormat(selectedOutputFormat);
  294. var hasBackgroundColor = !string.IsNullOrWhiteSpace(options.BackgroundColor);
  295. var hasForegroundColor = !string.IsNullOrWhiteSpace(options.ForegroundLayer);
  296. var blur = options.Blur ?? 0;
  297. var hasIndicator = options.AddPlayedIndicator || options.UnplayedCount.HasValue || !options.PercentPlayed.Equals(0);
  298. using (var bitmap = GetBitmap(inputPath, options.CropWhiteSpace, autoOrient, orientation))
  299. {
  300. if (bitmap == null)
  301. {
  302. throw new Exception(string.Format("Skia unable to read image {0}", inputPath));
  303. }
  304. //_logger.Info("Color type {0}", bitmap.Info.ColorType);
  305. var originalImageSize = new ImageSize(bitmap.Width, bitmap.Height);
  306. ImageHelper.SaveImageSize(inputPath, dateModified, originalImageSize);
  307. if (!options.CropWhiteSpace && options.HasDefaultOptions(inputPath, originalImageSize) && !autoOrient)
  308. {
  309. // Just spit out the original file if all the options are default
  310. return inputPath;
  311. }
  312. var newImageSize = ImageHelper.GetNewImageSize(options, originalImageSize);
  313. var width = Convert.ToInt32(Math.Round(newImageSize.Width));
  314. var height = Convert.ToInt32(Math.Round(newImageSize.Height));
  315. using (var resizedBitmap = new SKBitmap(width, height))//, bitmap.ColorType, bitmap.AlphaType))
  316. {
  317. // scale image
  318. var resizeMethod = SKBitmapResizeMethod.Lanczos3;
  319. bitmap.Resize(resizedBitmap, resizeMethod);
  320. // If all we're doing is resizing then we can stop now
  321. if (!hasBackgroundColor && !hasForegroundColor && blur == 0 && !hasIndicator)
  322. {
  323. using (var outputStream = new SKFileWStream(outputPath))
  324. {
  325. resizedBitmap.Encode(outputStream, skiaOutputFormat, quality);
  326. return outputPath;
  327. }
  328. }
  329. // create bitmap to use for canvas drawing
  330. using (var saveBitmap = new SKBitmap(width, height))//, bitmap.ColorType, bitmap.AlphaType))
  331. {
  332. // create canvas used to draw into bitmap
  333. using (var canvas = new SKCanvas(saveBitmap))
  334. {
  335. // set background color if present
  336. if (hasBackgroundColor)
  337. {
  338. canvas.Clear(SKColor.Parse(options.BackgroundColor));
  339. }
  340. // Add blur if option is present
  341. if (blur > 0)
  342. {
  343. using (var paint = new SKPaint())
  344. {
  345. // create image from resized bitmap to apply blur
  346. using (var filter = SKImageFilter.CreateBlur(blur, blur))
  347. {
  348. paint.ImageFilter = filter;
  349. canvas.DrawBitmap(resizedBitmap, SKRect.Create(width, height), paint);
  350. }
  351. }
  352. }
  353. else
  354. {
  355. // draw resized bitmap onto canvas
  356. canvas.DrawBitmap(resizedBitmap, SKRect.Create(width, height));
  357. }
  358. // If foreground layer present then draw
  359. if (hasForegroundColor)
  360. {
  361. Double opacity;
  362. if (!Double.TryParse(options.ForegroundLayer, out opacity)) opacity = .4;
  363. canvas.DrawColor(new SKColor(0, 0, 0, (Byte)((1 - opacity) * 0xFF)), SKBlendMode.SrcOver);
  364. }
  365. if (hasIndicator)
  366. {
  367. DrawIndicator(canvas, width, height, options);
  368. }
  369. using (var outputStream = new SKFileWStream(outputPath))
  370. {
  371. saveBitmap.Encode(outputStream, skiaOutputFormat, quality);
  372. }
  373. }
  374. }
  375. }
  376. }
  377. return outputPath;
  378. }
  379. public void CreateImageCollage(ImageCollageOptions options)
  380. {
  381. double ratio = options.Width;
  382. ratio /= options.Height;
  383. if (ratio >= 1.4)
  384. {
  385. new StripCollageBuilder(_appPaths, _fileSystem).BuildThumbCollage(options.InputPaths, options.OutputPath, options.Width, options.Height);
  386. }
  387. else if (ratio >= .9)
  388. {
  389. new StripCollageBuilder(_appPaths, _fileSystem).BuildSquareCollage(options.InputPaths, options.OutputPath, options.Width, options.Height);
  390. }
  391. else
  392. {
  393. // @todo create Poster collage capability
  394. new StripCollageBuilder(_appPaths, _fileSystem).BuildSquareCollage(options.InputPaths, options.OutputPath, options.Width, options.Height);
  395. }
  396. }
  397. private void DrawIndicator(SKCanvas canvas, int imageWidth, int imageHeight, ImageProcessingOptions options)
  398. {
  399. try
  400. {
  401. var currentImageSize = new ImageSize(imageWidth, imageHeight);
  402. if (options.AddPlayedIndicator)
  403. {
  404. var task = new PlayedIndicatorDrawer(_appPaths, _httpClientFactory(), _fileSystem).DrawPlayedIndicator(canvas, currentImageSize);
  405. Task.WaitAll(task);
  406. }
  407. else if (options.UnplayedCount.HasValue)
  408. {
  409. new UnplayedCountIndicator(_appPaths, _httpClientFactory(), _fileSystem).DrawUnplayedCountIndicator(canvas, currentImageSize, options.UnplayedCount.Value);
  410. }
  411. if (options.PercentPlayed > 0)
  412. {
  413. new PercentPlayedDrawer().Process(canvas, currentImageSize, options.PercentPlayed);
  414. }
  415. }
  416. catch (Exception ex)
  417. {
  418. _logger.ErrorException("Error drawing indicator overlay", ex);
  419. }
  420. }
  421. public string Name
  422. {
  423. get { return "Skia"; }
  424. }
  425. public void Dispose()
  426. {
  427. }
  428. public bool SupportsImageCollageCreation
  429. {
  430. get { return true; }
  431. }
  432. public bool SupportsImageEncoding
  433. {
  434. get { return true; }
  435. }
  436. }
  437. }