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. };
  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 IsTransparent(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 IsTransparentRow(SKBitmap bmp, int row)
  89. {
  90. for (var i = 0; i < bmp.Width; ++i)
  91. {
  92. if (!IsTransparent(bmp.GetPixel(i, row)))
  93. {
  94. return false;
  95. }
  96. }
  97. return true;
  98. }
  99. private static bool IsTransparentColumn(SKBitmap bmp, int col)
  100. {
  101. for (var i = 0; i < bmp.Height; ++i)
  102. {
  103. if (!IsTransparent(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 (IsTransparentRow(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 (IsTransparentRow(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 (IsTransparentColumn(bitmap, col))
  130. leftmost = col + 1;
  131. else
  132. break;
  133. }
  134. for (int col = bitmap.Width - 1; col >= 0; --col)
  135. {
  136. if (IsTransparentColumn(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 static string[] TransparentImageTypes = new string[] { ".png", ".gif", ".webp" };
  166. internal static 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. if (codec == null)
  175. {
  176. origin = SKCodecOrigin.TopLeft;
  177. return null;
  178. }
  179. // create the bitmap
  180. var bitmap = new SKBitmap(codec.Info.Width, codec.Info.Height, !requiresTransparencyHack);
  181. if (bitmap != null)
  182. {
  183. // decode
  184. codec.GetPixels(bitmap.Info, bitmap.GetPixels());
  185. origin = codec.Origin;
  186. }
  187. else
  188. {
  189. origin = SKCodecOrigin.TopLeft;
  190. }
  191. return bitmap;
  192. }
  193. }
  194. var resultBitmap = SKBitmap.Decode(path);
  195. if (resultBitmap == null)
  196. {
  197. return Decode(path, true, out origin);
  198. }
  199. // If we have to resize these they often end up distorted
  200. if (resultBitmap.ColorType == SKColorType.Gray8)
  201. {
  202. using (resultBitmap)
  203. {
  204. return Decode(path, true, out origin);
  205. }
  206. }
  207. origin = SKCodecOrigin.TopLeft;
  208. return resultBitmap;
  209. }
  210. private SKBitmap GetBitmap(string path, bool cropWhitespace, bool forceAnalyzeBitmap, out SKCodecOrigin origin)
  211. {
  212. if (cropWhitespace)
  213. {
  214. using (var bitmap = Decode(path, forceAnalyzeBitmap, out origin))
  215. {
  216. return CropWhiteSpace(bitmap);
  217. }
  218. }
  219. return Decode(path, forceAnalyzeBitmap, out origin);
  220. }
  221. private SKBitmap GetBitmap(string path, bool cropWhitespace, bool autoOrient)
  222. {
  223. SKCodecOrigin origin;
  224. if (autoOrient)
  225. {
  226. var bitmap = GetBitmap(path, cropWhitespace, true, out origin);
  227. if (bitmap != null)
  228. {
  229. if (origin != SKCodecOrigin.TopLeft)
  230. {
  231. using (bitmap)
  232. {
  233. return OrientImage(bitmap, origin);
  234. }
  235. }
  236. }
  237. return bitmap;
  238. }
  239. return GetBitmap(path, cropWhitespace, false, out origin);
  240. }
  241. private SKBitmap OrientImage(SKBitmap bitmap, SKCodecOrigin origin)
  242. {
  243. //var transformations = {
  244. // 2: { rotate: 0, flip: true},
  245. // 3: { rotate: 180, flip: false},
  246. // 4: { rotate: 180, flip: true},
  247. // 5: { rotate: 90, flip: true},
  248. // 6: { rotate: 90, flip: false},
  249. // 7: { rotate: 270, flip: true},
  250. // 8: { rotate: 270, flip: false},
  251. //}
  252. switch (origin)
  253. {
  254. case SKCodecOrigin.TopRight:
  255. {
  256. var rotated = new SKBitmap(bitmap.Width, bitmap.Height);
  257. using (var surface = new SKCanvas(rotated))
  258. {
  259. surface.Translate(rotated.Width, 0);
  260. surface.Scale(-1, 1);
  261. surface.DrawBitmap(bitmap, 0, 0);
  262. }
  263. return rotated;
  264. }
  265. case SKCodecOrigin.BottomRight:
  266. {
  267. var rotated = new SKBitmap(bitmap.Width, bitmap.Height);
  268. using (var surface = new SKCanvas(rotated))
  269. {
  270. float px = bitmap.Width;
  271. px /= 2;
  272. float py = bitmap.Height;
  273. py /= 2;
  274. surface.RotateDegrees(180, px, py);
  275. surface.DrawBitmap(bitmap, 0, 0);
  276. }
  277. return rotated;
  278. }
  279. case SKCodecOrigin.BottomLeft:
  280. {
  281. var rotated = new SKBitmap(bitmap.Width, bitmap.Height);
  282. using (var surface = new SKCanvas(rotated))
  283. {
  284. float px = bitmap.Width;
  285. px /= 2;
  286. float py = bitmap.Height;
  287. py /= 2;
  288. surface.Translate(rotated.Width, 0);
  289. surface.Scale(-1, 1);
  290. surface.RotateDegrees(180, px, py);
  291. surface.DrawBitmap(bitmap, 0, 0);
  292. }
  293. return rotated;
  294. }
  295. case SKCodecOrigin.LeftTop:
  296. {
  297. // TODO: Remove dual canvases, had trouble with flipping
  298. using (var rotated = new SKBitmap(bitmap.Height, bitmap.Width))
  299. {
  300. using (var surface = new SKCanvas(rotated))
  301. {
  302. surface.Translate(rotated.Width, 0);
  303. surface.RotateDegrees(90);
  304. surface.DrawBitmap(bitmap, 0, 0);
  305. }
  306. var flippedBitmap = new SKBitmap(rotated.Width, rotated.Height);
  307. using (var flippedCanvas = new SKCanvas(flippedBitmap))
  308. {
  309. flippedCanvas.Translate(flippedBitmap.Width, 0);
  310. flippedCanvas.Scale(-1, 1);
  311. flippedCanvas.DrawBitmap(rotated, 0, 0);
  312. }
  313. return flippedBitmap;
  314. }
  315. }
  316. case SKCodecOrigin.RightTop:
  317. {
  318. var rotated = new SKBitmap(bitmap.Height, bitmap.Width);
  319. using (var surface = new SKCanvas(rotated))
  320. {
  321. surface.Translate(rotated.Width, 0);
  322. surface.RotateDegrees(90);
  323. surface.DrawBitmap(bitmap, 0, 0);
  324. }
  325. return rotated;
  326. }
  327. case SKCodecOrigin.RightBottom:
  328. {
  329. // TODO: Remove dual canvases, had trouble with flipping
  330. using (var rotated = new SKBitmap(bitmap.Height, bitmap.Width))
  331. {
  332. using (var surface = new SKCanvas(rotated))
  333. {
  334. surface.Translate(0, rotated.Height);
  335. surface.RotateDegrees(270);
  336. surface.DrawBitmap(bitmap, 0, 0);
  337. }
  338. var flippedBitmap = new SKBitmap(rotated.Width, rotated.Height);
  339. using (var flippedCanvas = new SKCanvas(flippedBitmap))
  340. {
  341. flippedCanvas.Translate(flippedBitmap.Width, 0);
  342. flippedCanvas.Scale(-1, 1);
  343. flippedCanvas.DrawBitmap(rotated, 0, 0);
  344. }
  345. return flippedBitmap;
  346. }
  347. }
  348. case SKCodecOrigin.LeftBottom:
  349. {
  350. var rotated = new SKBitmap(bitmap.Height, bitmap.Width);
  351. using (var surface = new SKCanvas(rotated))
  352. {
  353. surface.Translate(0, rotated.Height);
  354. surface.RotateDegrees(270);
  355. surface.DrawBitmap(bitmap, 0, 0);
  356. }
  357. return rotated;
  358. }
  359. default:
  360. return bitmap;
  361. }
  362. }
  363. public string EncodeImage(string inputPath, DateTime dateModified, string outputPath, bool autoOrient, ImageOrientation? orientation, int quality, ImageProcessingOptions options, ImageFormat selectedOutputFormat)
  364. {
  365. if (string.IsNullOrWhiteSpace(inputPath))
  366. {
  367. throw new ArgumentNullException("inputPath");
  368. }
  369. if (string.IsNullOrWhiteSpace(inputPath))
  370. {
  371. throw new ArgumentNullException("outputPath");
  372. }
  373. var skiaOutputFormat = GetImageFormat(selectedOutputFormat);
  374. var hasBackgroundColor = !string.IsNullOrWhiteSpace(options.BackgroundColor);
  375. var hasForegroundColor = !string.IsNullOrWhiteSpace(options.ForegroundLayer);
  376. var blur = options.Blur ?? 0;
  377. var hasIndicator = options.AddPlayedIndicator || options.UnplayedCount.HasValue || !options.PercentPlayed.Equals(0);
  378. using (var bitmap = GetBitmap(inputPath, options.CropWhiteSpace, autoOrient))
  379. {
  380. if (bitmap == null)
  381. {
  382. throw new ArgumentOutOfRangeException(string.Format("Skia unable to read image {0}", inputPath));
  383. }
  384. //_logger.Info("Color type {0}", bitmap.Info.ColorType);
  385. var originalImageSize = new ImageSize(bitmap.Width, bitmap.Height);
  386. ImageHelper.SaveImageSize(inputPath, dateModified, originalImageSize);
  387. if (!options.CropWhiteSpace && options.HasDefaultOptions(inputPath, originalImageSize) && !autoOrient)
  388. {
  389. // Just spit out the original file if all the options are default
  390. return inputPath;
  391. }
  392. var newImageSize = ImageHelper.GetNewImageSize(options, originalImageSize);
  393. var width = Convert.ToInt32(Math.Round(newImageSize.Width));
  394. var height = Convert.ToInt32(Math.Round(newImageSize.Height));
  395. using (var resizedBitmap = new SKBitmap(width, height))//, bitmap.ColorType, bitmap.AlphaType))
  396. {
  397. // scale image
  398. var resizeMethod = SKBitmapResizeMethod.Lanczos3;
  399. bitmap.Resize(resizedBitmap, resizeMethod);
  400. // If all we're doing is resizing then we can stop now
  401. if (!hasBackgroundColor && !hasForegroundColor && blur == 0 && !hasIndicator)
  402. {
  403. using (var outputStream = new SKFileWStream(outputPath))
  404. {
  405. resizedBitmap.Encode(outputStream, skiaOutputFormat, quality);
  406. return outputPath;
  407. }
  408. }
  409. // create bitmap to use for canvas drawing
  410. using (var saveBitmap = new SKBitmap(width, height))//, bitmap.ColorType, bitmap.AlphaType))
  411. {
  412. // create canvas used to draw into bitmap
  413. using (var canvas = new SKCanvas(saveBitmap))
  414. {
  415. // set background color if present
  416. if (hasBackgroundColor)
  417. {
  418. canvas.Clear(SKColor.Parse(options.BackgroundColor));
  419. }
  420. // Add blur if option is present
  421. if (blur > 0)
  422. {
  423. using (var paint = new SKPaint())
  424. {
  425. // create image from resized bitmap to apply blur
  426. using (var filter = SKImageFilter.CreateBlur(blur, blur))
  427. {
  428. paint.ImageFilter = filter;
  429. canvas.DrawBitmap(resizedBitmap, SKRect.Create(width, height), paint);
  430. }
  431. }
  432. }
  433. else
  434. {
  435. // draw resized bitmap onto canvas
  436. canvas.DrawBitmap(resizedBitmap, SKRect.Create(width, height));
  437. }
  438. // If foreground layer present then draw
  439. if (hasForegroundColor)
  440. {
  441. Double opacity;
  442. if (!Double.TryParse(options.ForegroundLayer, out opacity)) opacity = .4;
  443. canvas.DrawColor(new SKColor(0, 0, 0, (Byte)((1 - opacity) * 0xFF)), SKBlendMode.SrcOver);
  444. }
  445. if (hasIndicator)
  446. {
  447. DrawIndicator(canvas, width, height, options);
  448. }
  449. using (var outputStream = new SKFileWStream(outputPath))
  450. {
  451. saveBitmap.Encode(outputStream, skiaOutputFormat, quality);
  452. }
  453. }
  454. }
  455. }
  456. }
  457. return outputPath;
  458. }
  459. public void CreateImageCollage(ImageCollageOptions options)
  460. {
  461. double ratio = options.Width;
  462. ratio /= options.Height;
  463. if (ratio >= 1.4)
  464. {
  465. new StripCollageBuilder(_appPaths, _fileSystem).BuildThumbCollage(options.InputPaths, options.OutputPath, options.Width, options.Height);
  466. }
  467. else if (ratio >= .9)
  468. {
  469. new StripCollageBuilder(_appPaths, _fileSystem).BuildSquareCollage(options.InputPaths, options.OutputPath, options.Width, options.Height);
  470. }
  471. else
  472. {
  473. // @todo create Poster collage capability
  474. new StripCollageBuilder(_appPaths, _fileSystem).BuildSquareCollage(options.InputPaths, options.OutputPath, options.Width, options.Height);
  475. }
  476. }
  477. private void DrawIndicator(SKCanvas canvas, int imageWidth, int imageHeight, ImageProcessingOptions options)
  478. {
  479. try
  480. {
  481. var currentImageSize = new ImageSize(imageWidth, imageHeight);
  482. if (options.AddPlayedIndicator)
  483. {
  484. var task = new PlayedIndicatorDrawer(_appPaths, _httpClientFactory(), _fileSystem).DrawPlayedIndicator(canvas, currentImageSize);
  485. Task.WaitAll(task);
  486. }
  487. else if (options.UnplayedCount.HasValue)
  488. {
  489. new UnplayedCountIndicator(_appPaths, _httpClientFactory(), _fileSystem).DrawUnplayedCountIndicator(canvas, currentImageSize, options.UnplayedCount.Value);
  490. }
  491. if (options.PercentPlayed > 0)
  492. {
  493. new PercentPlayedDrawer().Process(canvas, currentImageSize, options.PercentPlayed);
  494. }
  495. }
  496. catch (Exception ex)
  497. {
  498. _logger.ErrorException("Error drawing indicator overlay", ex);
  499. }
  500. }
  501. public string Name
  502. {
  503. get { return "Skia"; }
  504. }
  505. public void Dispose()
  506. {
  507. }
  508. public bool SupportsImageCollageCreation
  509. {
  510. get { return true; }
  511. }
  512. public bool SupportsImageEncoding
  513. {
  514. get { return true; }
  515. }
  516. }
  517. }