SkiaEncoder.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610
  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. };
  51. }
  52. }
  53. public ImageFormat[] SupportedOutputFormats
  54. {
  55. get
  56. {
  57. return new[] { ImageFormat.Webp, ImageFormat.Gif, ImageFormat.Jpg, ImageFormat.Png, ImageFormat.Bmp };
  58. }
  59. }
  60. private void LogVersion()
  61. {
  62. // test an operation that requires the native library
  63. SKPMColor.PreMultiply(SKColors.Black);
  64. _logger.Info("SkiaSharp version: " + GetVersion());
  65. }
  66. public static string GetVersion()
  67. {
  68. return typeof(SKBitmap).GetTypeInfo().Assembly.GetName().Version.ToString();
  69. }
  70. private static bool IsTransparent(SKColor color)
  71. {
  72. return (color.Red == 255 && color.Green == 255 && color.Blue == 255) || color.Alpha == 0;
  73. }
  74. public static SKEncodedImageFormat GetImageFormat(ImageFormat selectedFormat)
  75. {
  76. switch (selectedFormat)
  77. {
  78. case ImageFormat.Bmp:
  79. return SKEncodedImageFormat.Bmp;
  80. case ImageFormat.Jpg:
  81. return SKEncodedImageFormat.Jpeg;
  82. case ImageFormat.Gif:
  83. return SKEncodedImageFormat.Gif;
  84. case ImageFormat.Webp:
  85. return SKEncodedImageFormat.Webp;
  86. default:
  87. return SKEncodedImageFormat.Png;
  88. }
  89. }
  90. private static bool IsTransparentRow(SKBitmap bmp, int row)
  91. {
  92. for (var i = 0; i < bmp.Width; ++i)
  93. {
  94. if (!IsTransparent(bmp.GetPixel(i, row)))
  95. {
  96. return false;
  97. }
  98. }
  99. return true;
  100. }
  101. private static bool IsTransparentColumn(SKBitmap bmp, int col)
  102. {
  103. for (var i = 0; i < bmp.Height; ++i)
  104. {
  105. if (!IsTransparent(bmp.GetPixel(col, i)))
  106. {
  107. return false;
  108. }
  109. }
  110. return true;
  111. }
  112. private SKBitmap CropWhiteSpace(SKBitmap bitmap)
  113. {
  114. var topmost = 0;
  115. for (int row = 0; row < bitmap.Height; ++row)
  116. {
  117. if (IsTransparentRow(bitmap, row))
  118. topmost = row + 1;
  119. else break;
  120. }
  121. int bottommost = bitmap.Height;
  122. for (int row = bitmap.Height - 1; row >= 0; --row)
  123. {
  124. if (IsTransparentRow(bitmap, row))
  125. bottommost = row;
  126. else break;
  127. }
  128. int leftmost = 0, rightmost = bitmap.Width;
  129. for (int col = 0; col < bitmap.Width; ++col)
  130. {
  131. if (IsTransparentColumn(bitmap, col))
  132. leftmost = col + 1;
  133. else
  134. break;
  135. }
  136. for (int col = bitmap.Width - 1; col >= 0; --col)
  137. {
  138. if (IsTransparentColumn(bitmap, col))
  139. rightmost = col;
  140. else
  141. break;
  142. }
  143. var newRect = SKRectI.Create(leftmost, topmost, rightmost - leftmost, bottommost - topmost);
  144. using (var image = SKImage.FromBitmap(bitmap))
  145. {
  146. using (var subset = image.Subset(newRect))
  147. {
  148. return SKBitmap.FromImage(subset);
  149. }
  150. }
  151. }
  152. public ImageSize GetImageSize(string path)
  153. {
  154. using (var s = new SKFileStream(path))
  155. {
  156. using (var codec = SKCodec.Create(s))
  157. {
  158. var info = codec.Info;
  159. return new ImageSize
  160. {
  161. Width = info.Width,
  162. Height = info.Height
  163. };
  164. }
  165. }
  166. }
  167. private static string[] TransparentImageTypes = new string[] { ".png", ".gif", ".webp" };
  168. internal static SKBitmap Decode(string path, bool forceCleanBitmap, out SKCodecOrigin origin)
  169. {
  170. var requiresTransparencyHack = TransparentImageTypes.Contains(Path.GetExtension(path) ?? string.Empty);
  171. if (requiresTransparencyHack || forceCleanBitmap)
  172. {
  173. using (var stream = new SKFileStream(path))
  174. {
  175. using (var codec = SKCodec.Create(stream))
  176. {
  177. if (codec == null)
  178. {
  179. origin = SKCodecOrigin.TopLeft;
  180. return null;
  181. }
  182. // create the bitmap
  183. var bitmap = new SKBitmap(codec.Info.Width, codec.Info.Height, !requiresTransparencyHack);
  184. if (bitmap != null)
  185. {
  186. // decode
  187. codec.GetPixels(bitmap.Info, bitmap.GetPixels());
  188. origin = codec.Origin;
  189. }
  190. else
  191. {
  192. origin = SKCodecOrigin.TopLeft;
  193. }
  194. return bitmap;
  195. }
  196. }
  197. }
  198. var resultBitmap = SKBitmap.Decode(path);
  199. if (resultBitmap == null)
  200. {
  201. return Decode(path, true, out origin);
  202. }
  203. // If we have to resize these they often end up distorted
  204. if (resultBitmap.ColorType == SKColorType.Gray8)
  205. {
  206. using (resultBitmap)
  207. {
  208. return Decode(path, true, out origin);
  209. }
  210. }
  211. origin = SKCodecOrigin.TopLeft;
  212. return resultBitmap;
  213. }
  214. private SKBitmap GetBitmap(string path, bool cropWhitespace, bool forceAnalyzeBitmap, out SKCodecOrigin origin)
  215. {
  216. if (cropWhitespace)
  217. {
  218. using (var bitmap = Decode(path, forceAnalyzeBitmap, out origin))
  219. {
  220. return CropWhiteSpace(bitmap);
  221. }
  222. }
  223. return Decode(path, forceAnalyzeBitmap, out origin);
  224. }
  225. private SKBitmap GetBitmap(string path, bool cropWhitespace, bool autoOrient)
  226. {
  227. SKCodecOrigin origin;
  228. if (autoOrient)
  229. {
  230. var bitmap = GetBitmap(path, cropWhitespace, true, out origin);
  231. if (bitmap != null)
  232. {
  233. if (origin != SKCodecOrigin.TopLeft)
  234. {
  235. using (bitmap)
  236. {
  237. return OrientImage(bitmap, origin);
  238. }
  239. }
  240. }
  241. return bitmap;
  242. }
  243. return GetBitmap(path, cropWhitespace, false, out origin);
  244. }
  245. private SKBitmap OrientImage(SKBitmap bitmap, SKCodecOrigin origin)
  246. {
  247. //var transformations = {
  248. // 2: { rotate: 0, flip: true},
  249. // 3: { rotate: 180, flip: false},
  250. // 4: { rotate: 180, flip: true},
  251. // 5: { rotate: 90, flip: true},
  252. // 6: { rotate: 90, flip: false},
  253. // 7: { rotate: 270, flip: true},
  254. // 8: { rotate: 270, flip: false},
  255. //}
  256. switch (origin)
  257. {
  258. case SKCodecOrigin.TopRight:
  259. {
  260. var rotated = new SKBitmap(bitmap.Width, bitmap.Height);
  261. using (var surface = new SKCanvas(rotated))
  262. {
  263. surface.Translate(rotated.Width, 0);
  264. surface.Scale(-1, 1);
  265. surface.DrawBitmap(bitmap, 0, 0);
  266. }
  267. return rotated;
  268. }
  269. case SKCodecOrigin.BottomRight:
  270. {
  271. var rotated = new SKBitmap(bitmap.Width, bitmap.Height);
  272. using (var surface = new SKCanvas(rotated))
  273. {
  274. float px = bitmap.Width;
  275. px /= 2;
  276. float py = bitmap.Height;
  277. py /= 2;
  278. surface.RotateDegrees(180, px, py);
  279. surface.DrawBitmap(bitmap, 0, 0);
  280. }
  281. return rotated;
  282. }
  283. case SKCodecOrigin.BottomLeft:
  284. {
  285. var rotated = new SKBitmap(bitmap.Width, bitmap.Height);
  286. using (var surface = new SKCanvas(rotated))
  287. {
  288. float px = bitmap.Width;
  289. px /= 2;
  290. float py = bitmap.Height;
  291. py /= 2;
  292. surface.Translate(rotated.Width, 0);
  293. surface.Scale(-1, 1);
  294. surface.RotateDegrees(180, px, py);
  295. surface.DrawBitmap(bitmap, 0, 0);
  296. }
  297. return rotated;
  298. }
  299. case SKCodecOrigin.LeftTop:
  300. {
  301. // TODO: Remove dual canvases, had trouble with flipping
  302. using (var rotated = new SKBitmap(bitmap.Height, bitmap.Width))
  303. {
  304. using (var surface = new SKCanvas(rotated))
  305. {
  306. surface.Translate(rotated.Width, 0);
  307. surface.RotateDegrees(90);
  308. surface.DrawBitmap(bitmap, 0, 0);
  309. }
  310. var flippedBitmap = new SKBitmap(rotated.Width, rotated.Height);
  311. using (var flippedCanvas = new SKCanvas(flippedBitmap))
  312. {
  313. flippedCanvas.Translate(flippedBitmap.Width, 0);
  314. flippedCanvas.Scale(-1, 1);
  315. flippedCanvas.DrawBitmap(rotated, 0, 0);
  316. }
  317. return flippedBitmap;
  318. }
  319. }
  320. case SKCodecOrigin.RightTop:
  321. {
  322. var rotated = new SKBitmap(bitmap.Height, bitmap.Width);
  323. using (var surface = new SKCanvas(rotated))
  324. {
  325. surface.Translate(rotated.Width, 0);
  326. surface.RotateDegrees(90);
  327. surface.DrawBitmap(bitmap, 0, 0);
  328. }
  329. return rotated;
  330. }
  331. case SKCodecOrigin.RightBottom:
  332. {
  333. // TODO: Remove dual canvases, had trouble with flipping
  334. using (var rotated = new SKBitmap(bitmap.Height, bitmap.Width))
  335. {
  336. using (var surface = new SKCanvas(rotated))
  337. {
  338. surface.Translate(0, rotated.Height);
  339. surface.RotateDegrees(270);
  340. surface.DrawBitmap(bitmap, 0, 0);
  341. }
  342. var flippedBitmap = new SKBitmap(rotated.Width, rotated.Height);
  343. using (var flippedCanvas = new SKCanvas(flippedBitmap))
  344. {
  345. flippedCanvas.Translate(flippedBitmap.Width, 0);
  346. flippedCanvas.Scale(-1, 1);
  347. flippedCanvas.DrawBitmap(rotated, 0, 0);
  348. }
  349. return flippedBitmap;
  350. }
  351. }
  352. case SKCodecOrigin.LeftBottom:
  353. {
  354. var rotated = new SKBitmap(bitmap.Height, bitmap.Width);
  355. using (var surface = new SKCanvas(rotated))
  356. {
  357. surface.Translate(0, rotated.Height);
  358. surface.RotateDegrees(270);
  359. surface.DrawBitmap(bitmap, 0, 0);
  360. }
  361. return rotated;
  362. }
  363. default:
  364. return bitmap;
  365. }
  366. }
  367. public string EncodeImage(string inputPath, DateTime dateModified, string outputPath, bool autoOrient, ImageOrientation? orientation, int quality, ImageProcessingOptions options, ImageFormat selectedOutputFormat)
  368. {
  369. if (string.IsNullOrWhiteSpace(inputPath))
  370. {
  371. throw new ArgumentNullException("inputPath");
  372. }
  373. if (string.IsNullOrWhiteSpace(inputPath))
  374. {
  375. throw new ArgumentNullException("outputPath");
  376. }
  377. var skiaOutputFormat = GetImageFormat(selectedOutputFormat);
  378. var hasBackgroundColor = !string.IsNullOrWhiteSpace(options.BackgroundColor);
  379. var hasForegroundColor = !string.IsNullOrWhiteSpace(options.ForegroundLayer);
  380. var blur = options.Blur ?? 0;
  381. var hasIndicator = options.AddPlayedIndicator || options.UnplayedCount.HasValue || !options.PercentPlayed.Equals(0);
  382. using (var bitmap = GetBitmap(inputPath, options.CropWhiteSpace, autoOrient))
  383. {
  384. if (bitmap == null)
  385. {
  386. throw new ArgumentOutOfRangeException(string.Format("Skia unable to read image {0}", inputPath));
  387. }
  388. //_logger.Info("Color type {0}", bitmap.Info.ColorType);
  389. var originalImageSize = new ImageSize(bitmap.Width, bitmap.Height);
  390. ImageHelper.SaveImageSize(inputPath, dateModified, originalImageSize);
  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. }