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