SkiaEncoder.cs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690
  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. using MediaBrowser.Controller.Extensions;
  14. using System.Globalization;
  15. using MediaBrowser.Model.Globalization;
  16. namespace Emby.Drawing.Skia
  17. {
  18. public class SkiaEncoder : IImageEncoder
  19. {
  20. private readonly ILogger _logger;
  21. private static IApplicationPaths _appPaths;
  22. private readonly Func<IHttpClient> _httpClientFactory;
  23. private readonly IFileSystem _fileSystem;
  24. private static ILocalizationManager _localizationManager;
  25. public SkiaEncoder(ILogger logger, IApplicationPaths appPaths, Func<IHttpClient> httpClientFactory, IFileSystem fileSystem, ILocalizationManager localizationManager)
  26. {
  27. _logger = logger;
  28. _appPaths = appPaths;
  29. _httpClientFactory = httpClientFactory;
  30. _fileSystem = fileSystem;
  31. _localizationManager = localizationManager;
  32. LogVersion();
  33. }
  34. public string[] SupportedInputFormats
  35. {
  36. get
  37. {
  38. // Some common file name extensions for RAW picture files include: .cr2, .crw, .dng, .nef, .orf, .rw2, .pef, .arw, .sr2, .srf, and .tif.
  39. return new[]
  40. {
  41. "jpeg",
  42. "jpg",
  43. "png",
  44. "dng",
  45. "webp",
  46. "gif",
  47. "bmp",
  48. "ico",
  49. "astc",
  50. "ktx",
  51. "pkm",
  52. "wbmp",
  53. // TODO
  54. // Are all of these supported? https://github.com/google/skia/blob/master/infra/bots/recipes/test.py#L454
  55. // working on windows at least
  56. "cr2",
  57. "nef",
  58. "arw"
  59. };
  60. }
  61. }
  62. public ImageFormat[] SupportedOutputFormats
  63. {
  64. get
  65. {
  66. return new[] { ImageFormat.Webp, ImageFormat.Jpg, ImageFormat.Png };
  67. }
  68. }
  69. private void LogVersion()
  70. {
  71. // test an operation that requires the native library
  72. SKPMColor.PreMultiply(SKColors.Black);
  73. _logger.Info("SkiaSharp version: " + GetVersion());
  74. }
  75. public static string GetVersion()
  76. {
  77. return typeof(SKBitmap).GetTypeInfo().Assembly.GetName().Version.ToString();
  78. }
  79. private static bool IsTransparent(SKColor color)
  80. {
  81. return (color.Red == 255 && color.Green == 255 && color.Blue == 255) || color.Alpha == 0;
  82. }
  83. public static SKEncodedImageFormat GetImageFormat(ImageFormat selectedFormat)
  84. {
  85. switch (selectedFormat)
  86. {
  87. case ImageFormat.Bmp:
  88. return SKEncodedImageFormat.Bmp;
  89. case ImageFormat.Jpg:
  90. return SKEncodedImageFormat.Jpeg;
  91. case ImageFormat.Gif:
  92. return SKEncodedImageFormat.Gif;
  93. case ImageFormat.Webp:
  94. return SKEncodedImageFormat.Webp;
  95. default:
  96. return SKEncodedImageFormat.Png;
  97. }
  98. }
  99. private static bool IsTransparentRow(SKBitmap bmp, int row)
  100. {
  101. for (var i = 0; i < bmp.Width; ++i)
  102. {
  103. if (!IsTransparent(bmp.GetPixel(i, row)))
  104. {
  105. return false;
  106. }
  107. }
  108. return true;
  109. }
  110. private static bool IsTransparentColumn(SKBitmap bmp, int col)
  111. {
  112. for (var i = 0; i < bmp.Height; ++i)
  113. {
  114. if (!IsTransparent(bmp.GetPixel(col, i)))
  115. {
  116. return false;
  117. }
  118. }
  119. return true;
  120. }
  121. private SKBitmap CropWhiteSpace(SKBitmap bitmap)
  122. {
  123. var topmost = 0;
  124. for (int row = 0; row < bitmap.Height; ++row)
  125. {
  126. if (IsTransparentRow(bitmap, row))
  127. topmost = row + 1;
  128. else break;
  129. }
  130. int bottommost = bitmap.Height;
  131. for (int row = bitmap.Height - 1; row >= 0; --row)
  132. {
  133. if (IsTransparentRow(bitmap, row))
  134. bottommost = row;
  135. else break;
  136. }
  137. int leftmost = 0, rightmost = bitmap.Width;
  138. for (int col = 0; col < bitmap.Width; ++col)
  139. {
  140. if (IsTransparentColumn(bitmap, col))
  141. leftmost = col + 1;
  142. else
  143. break;
  144. }
  145. for (int col = bitmap.Width - 1; col >= 0; --col)
  146. {
  147. if (IsTransparentColumn(bitmap, col))
  148. rightmost = col;
  149. else
  150. break;
  151. }
  152. var newRect = SKRectI.Create(leftmost, topmost, rightmost - leftmost, bottommost - topmost);
  153. using (var image = SKImage.FromBitmap(bitmap))
  154. {
  155. using (var subset = image.Subset(newRect))
  156. {
  157. return SKBitmap.FromImage(subset);
  158. }
  159. }
  160. }
  161. public ImageSize GetImageSize(string path)
  162. {
  163. using (var s = new SKFileStream(path))
  164. {
  165. using (var codec = SKCodec.Create(s))
  166. {
  167. var info = codec.Info;
  168. return new ImageSize
  169. {
  170. Width = info.Width,
  171. Height = info.Height
  172. };
  173. }
  174. }
  175. }
  176. private static bool HasDiacritics(string text)
  177. {
  178. return !String.Equals(text, text.RemoveDiacritics(), StringComparison.Ordinal);
  179. }
  180. private static bool RequiresSpecialCharacterHack(string path)
  181. {
  182. if (_localizationManager.HasUnicodeCategory(path, UnicodeCategory.OtherLetter))
  183. {
  184. return true;
  185. }
  186. if (HasDiacritics(path))
  187. {
  188. return true;
  189. }
  190. return false;
  191. }
  192. private static string NormalizePath(string path, IFileSystem fileSystem)
  193. {
  194. if (!RequiresSpecialCharacterHack(path))
  195. {
  196. return path;
  197. }
  198. var tempPath = Path.Combine(_appPaths.TempDirectory, Guid.NewGuid() + Path.GetExtension(path) ?? string.Empty);
  199. fileSystem.CreateDirectory(fileSystem.GetDirectoryName(tempPath));
  200. fileSystem.CopyFile(path, tempPath, true);
  201. return tempPath;
  202. }
  203. private static SKCodecOrigin GetSKCodecOrigin(ImageOrientation? orientation)
  204. {
  205. if (!orientation.HasValue)
  206. {
  207. return SKCodecOrigin.TopLeft;
  208. }
  209. switch (orientation.Value)
  210. {
  211. case ImageOrientation.TopRight:
  212. return SKCodecOrigin.TopRight;
  213. case ImageOrientation.RightTop:
  214. return SKCodecOrigin.RightTop;
  215. case ImageOrientation.RightBottom:
  216. return SKCodecOrigin.RightBottom;
  217. case ImageOrientation.LeftTop:
  218. return SKCodecOrigin.LeftTop;
  219. case ImageOrientation.LeftBottom:
  220. return SKCodecOrigin.LeftBottom;
  221. case ImageOrientation.BottomRight:
  222. return SKCodecOrigin.BottomRight;
  223. case ImageOrientation.BottomLeft:
  224. return SKCodecOrigin.BottomLeft;
  225. default:
  226. return SKCodecOrigin.TopLeft;
  227. }
  228. }
  229. private static string[] TransparentImageTypes = new string[] { ".png", ".gif", ".webp" };
  230. internal static SKBitmap Decode(string path, bool forceCleanBitmap, IFileSystem fileSystem, ImageOrientation? orientation, out SKCodecOrigin origin)
  231. {
  232. if (!fileSystem.FileExists(path))
  233. {
  234. throw new FileNotFoundException("File not found", path);
  235. }
  236. var requiresTransparencyHack = TransparentImageTypes.Contains(Path.GetExtension(path) ?? string.Empty);
  237. if (requiresTransparencyHack || forceCleanBitmap)
  238. {
  239. using (var stream = new SKFileStream(NormalizePath(path, fileSystem)))
  240. {
  241. using (var codec = SKCodec.Create(stream))
  242. {
  243. if (codec == null)
  244. {
  245. origin = GetSKCodecOrigin(orientation);
  246. return null;
  247. }
  248. // create the bitmap
  249. var bitmap = new SKBitmap(codec.Info.Width, codec.Info.Height, !requiresTransparencyHack);
  250. if (bitmap != null)
  251. {
  252. // decode
  253. codec.GetPixels(bitmap.Info, bitmap.GetPixels());
  254. origin = codec.Origin;
  255. }
  256. else
  257. {
  258. origin = GetSKCodecOrigin(orientation);
  259. }
  260. return bitmap;
  261. }
  262. }
  263. }
  264. var resultBitmap = SKBitmap.Decode(NormalizePath(path, fileSystem));
  265. if (resultBitmap == null)
  266. {
  267. return Decode(path, true, fileSystem, orientation, out origin);
  268. }
  269. // If we have to resize these they often end up distorted
  270. if (resultBitmap.ColorType == SKColorType.Gray8)
  271. {
  272. using (resultBitmap)
  273. {
  274. return Decode(path, true, fileSystem, orientation, out origin);
  275. }
  276. }
  277. origin = SKCodecOrigin.TopLeft;
  278. return resultBitmap;
  279. }
  280. private SKBitmap GetBitmap(string path, bool cropWhitespace, bool forceAnalyzeBitmap, ImageOrientation? orientation, out SKCodecOrigin origin)
  281. {
  282. if (cropWhitespace)
  283. {
  284. using (var bitmap = Decode(path, forceAnalyzeBitmap, _fileSystem, orientation, out origin))
  285. {
  286. return CropWhiteSpace(bitmap);
  287. }
  288. }
  289. return Decode(path, forceAnalyzeBitmap, _fileSystem, orientation, out origin);
  290. }
  291. private SKBitmap GetBitmap(string path, bool cropWhitespace, bool autoOrient, ImageOrientation? orientation)
  292. {
  293. SKCodecOrigin origin;
  294. if (autoOrient)
  295. {
  296. var bitmap = GetBitmap(path, cropWhitespace, true, orientation, out origin);
  297. if (bitmap != null)
  298. {
  299. if (origin != SKCodecOrigin.TopLeft)
  300. {
  301. using (bitmap)
  302. {
  303. return OrientImage(bitmap, origin);
  304. }
  305. }
  306. }
  307. return bitmap;
  308. }
  309. return GetBitmap(path, cropWhitespace, false, orientation, out origin);
  310. }
  311. private SKBitmap OrientImage(SKBitmap bitmap, SKCodecOrigin origin)
  312. {
  313. //var transformations = {
  314. // 2: { rotate: 0, flip: true},
  315. // 3: { rotate: 180, flip: false},
  316. // 4: { rotate: 180, flip: true},
  317. // 5: { rotate: 90, flip: true},
  318. // 6: { rotate: 90, flip: false},
  319. // 7: { rotate: 270, flip: true},
  320. // 8: { rotate: 270, flip: false},
  321. //}
  322. switch (origin)
  323. {
  324. case SKCodecOrigin.TopRight:
  325. {
  326. var rotated = new SKBitmap(bitmap.Width, bitmap.Height);
  327. using (var surface = new SKCanvas(rotated))
  328. {
  329. surface.Translate(rotated.Width, 0);
  330. surface.Scale(-1, 1);
  331. surface.DrawBitmap(bitmap, 0, 0);
  332. }
  333. return rotated;
  334. }
  335. case SKCodecOrigin.BottomRight:
  336. {
  337. var rotated = new SKBitmap(bitmap.Width, bitmap.Height);
  338. using (var surface = new SKCanvas(rotated))
  339. {
  340. float px = bitmap.Width;
  341. px /= 2;
  342. float py = bitmap.Height;
  343. py /= 2;
  344. surface.RotateDegrees(180, px, py);
  345. surface.DrawBitmap(bitmap, 0, 0);
  346. }
  347. return rotated;
  348. }
  349. case SKCodecOrigin.BottomLeft:
  350. {
  351. var rotated = new SKBitmap(bitmap.Width, bitmap.Height);
  352. using (var surface = new SKCanvas(rotated))
  353. {
  354. float px = bitmap.Width;
  355. px /= 2;
  356. float py = bitmap.Height;
  357. py /= 2;
  358. surface.Translate(rotated.Width, 0);
  359. surface.Scale(-1, 1);
  360. surface.RotateDegrees(180, px, py);
  361. surface.DrawBitmap(bitmap, 0, 0);
  362. }
  363. return rotated;
  364. }
  365. case SKCodecOrigin.LeftTop:
  366. {
  367. // TODO: Remove dual canvases, had trouble with flipping
  368. using (var rotated = new SKBitmap(bitmap.Height, bitmap.Width))
  369. {
  370. using (var surface = new SKCanvas(rotated))
  371. {
  372. surface.Translate(rotated.Width, 0);
  373. surface.RotateDegrees(90);
  374. surface.DrawBitmap(bitmap, 0, 0);
  375. }
  376. var flippedBitmap = new SKBitmap(rotated.Width, rotated.Height);
  377. using (var flippedCanvas = new SKCanvas(flippedBitmap))
  378. {
  379. flippedCanvas.Translate(flippedBitmap.Width, 0);
  380. flippedCanvas.Scale(-1, 1);
  381. flippedCanvas.DrawBitmap(rotated, 0, 0);
  382. }
  383. return flippedBitmap;
  384. }
  385. }
  386. case SKCodecOrigin.RightTop:
  387. {
  388. var rotated = new SKBitmap(bitmap.Height, bitmap.Width);
  389. using (var surface = new SKCanvas(rotated))
  390. {
  391. surface.Translate(rotated.Width, 0);
  392. surface.RotateDegrees(90);
  393. surface.DrawBitmap(bitmap, 0, 0);
  394. }
  395. return rotated;
  396. }
  397. case SKCodecOrigin.RightBottom:
  398. {
  399. // TODO: Remove dual canvases, had trouble with flipping
  400. using (var rotated = new SKBitmap(bitmap.Height, bitmap.Width))
  401. {
  402. using (var surface = new SKCanvas(rotated))
  403. {
  404. surface.Translate(0, rotated.Height);
  405. surface.RotateDegrees(270);
  406. surface.DrawBitmap(bitmap, 0, 0);
  407. }
  408. var flippedBitmap = new SKBitmap(rotated.Width, rotated.Height);
  409. using (var flippedCanvas = new SKCanvas(flippedBitmap))
  410. {
  411. flippedCanvas.Translate(flippedBitmap.Width, 0);
  412. flippedCanvas.Scale(-1, 1);
  413. flippedCanvas.DrawBitmap(rotated, 0, 0);
  414. }
  415. return flippedBitmap;
  416. }
  417. }
  418. case SKCodecOrigin.LeftBottom:
  419. {
  420. var rotated = new SKBitmap(bitmap.Height, bitmap.Width);
  421. using (var surface = new SKCanvas(rotated))
  422. {
  423. surface.Translate(0, rotated.Height);
  424. surface.RotateDegrees(270);
  425. surface.DrawBitmap(bitmap, 0, 0);
  426. }
  427. return rotated;
  428. }
  429. default:
  430. return bitmap;
  431. }
  432. }
  433. public string EncodeImage(string inputPath, DateTime dateModified, string outputPath, bool autoOrient, ImageOrientation? orientation, int quality, ImageProcessingOptions options, ImageFormat selectedOutputFormat)
  434. {
  435. if (string.IsNullOrWhiteSpace(inputPath))
  436. {
  437. throw new ArgumentNullException("inputPath");
  438. }
  439. if (string.IsNullOrWhiteSpace(inputPath))
  440. {
  441. throw new ArgumentNullException("outputPath");
  442. }
  443. var skiaOutputFormat = GetImageFormat(selectedOutputFormat);
  444. var hasBackgroundColor = !string.IsNullOrWhiteSpace(options.BackgroundColor);
  445. var hasForegroundColor = !string.IsNullOrWhiteSpace(options.ForegroundLayer);
  446. var blur = options.Blur ?? 0;
  447. var hasIndicator = options.AddPlayedIndicator || options.UnplayedCount.HasValue || !options.PercentPlayed.Equals(0);
  448. using (var bitmap = GetBitmap(inputPath, options.CropWhiteSpace, autoOrient, orientation))
  449. {
  450. if (bitmap == null)
  451. {
  452. throw new ArgumentOutOfRangeException(string.Format("Skia unable to read image {0}", inputPath));
  453. }
  454. //_logger.Info("Color type {0}", bitmap.Info.ColorType);
  455. var originalImageSize = new ImageSize(bitmap.Width, bitmap.Height);
  456. if (!options.CropWhiteSpace && options.HasDefaultOptions(inputPath, originalImageSize) && !autoOrient)
  457. {
  458. // Just spit out the original file if all the options are default
  459. return inputPath;
  460. }
  461. var newImageSize = ImageHelper.GetNewImageSize(options, originalImageSize);
  462. var width = Convert.ToInt32(Math.Round(newImageSize.Width));
  463. var height = Convert.ToInt32(Math.Round(newImageSize.Height));
  464. using (var resizedBitmap = new SKBitmap(width, height))//, bitmap.ColorType, bitmap.AlphaType))
  465. {
  466. // scale image
  467. var resizeMethod = SKBitmapResizeMethod.Lanczos3;
  468. bitmap.Resize(resizedBitmap, resizeMethod);
  469. // If all we're doing is resizing then we can stop now
  470. if (!hasBackgroundColor && !hasForegroundColor && blur == 0 && !hasIndicator)
  471. {
  472. _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(outputPath));
  473. using (var outputStream = new SKFileWStream(outputPath))
  474. {
  475. resizedBitmap.Encode(outputStream, skiaOutputFormat, quality);
  476. return outputPath;
  477. }
  478. }
  479. // create bitmap to use for canvas drawing
  480. using (var saveBitmap = new SKBitmap(width, height))//, bitmap.ColorType, bitmap.AlphaType))
  481. {
  482. // create canvas used to draw into bitmap
  483. using (var canvas = new SKCanvas(saveBitmap))
  484. {
  485. // set background color if present
  486. if (hasBackgroundColor)
  487. {
  488. canvas.Clear(SKColor.Parse(options.BackgroundColor));
  489. }
  490. // Add blur if option is present
  491. if (blur > 0)
  492. {
  493. using (var paint = new SKPaint())
  494. {
  495. // create image from resized bitmap to apply blur
  496. using (var filter = SKImageFilter.CreateBlur(blur, blur))
  497. {
  498. paint.ImageFilter = filter;
  499. canvas.DrawBitmap(resizedBitmap, SKRect.Create(width, height), paint);
  500. }
  501. }
  502. }
  503. else
  504. {
  505. // draw resized bitmap onto canvas
  506. canvas.DrawBitmap(resizedBitmap, SKRect.Create(width, height));
  507. }
  508. // If foreground layer present then draw
  509. if (hasForegroundColor)
  510. {
  511. Double opacity;
  512. if (!Double.TryParse(options.ForegroundLayer, out opacity)) opacity = .4;
  513. canvas.DrawColor(new SKColor(0, 0, 0, (Byte)((1 - opacity) * 0xFF)), SKBlendMode.SrcOver);
  514. }
  515. if (hasIndicator)
  516. {
  517. DrawIndicator(canvas, width, height, options);
  518. }
  519. _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(outputPath));
  520. using (var outputStream = new SKFileWStream(outputPath))
  521. {
  522. saveBitmap.Encode(outputStream, skiaOutputFormat, quality);
  523. }
  524. }
  525. }
  526. }
  527. }
  528. return outputPath;
  529. }
  530. public void CreateImageCollage(ImageCollageOptions options)
  531. {
  532. double ratio = options.Width;
  533. ratio /= options.Height;
  534. if (ratio >= 1.4)
  535. {
  536. new StripCollageBuilder(_appPaths, _fileSystem).BuildThumbCollage(options.InputPaths, options.OutputPath, options.Width, options.Height);
  537. }
  538. else if (ratio >= .9)
  539. {
  540. new StripCollageBuilder(_appPaths, _fileSystem).BuildSquareCollage(options.InputPaths, options.OutputPath, options.Width, options.Height);
  541. }
  542. else
  543. {
  544. // @todo create Poster collage capability
  545. new StripCollageBuilder(_appPaths, _fileSystem).BuildSquareCollage(options.InputPaths, options.OutputPath, options.Width, options.Height);
  546. }
  547. }
  548. private void DrawIndicator(SKCanvas canvas, int imageWidth, int imageHeight, ImageProcessingOptions options)
  549. {
  550. try
  551. {
  552. var currentImageSize = new ImageSize(imageWidth, imageHeight);
  553. if (options.AddPlayedIndicator)
  554. {
  555. new PlayedIndicatorDrawer(_appPaths, _httpClientFactory(), _fileSystem).DrawPlayedIndicator(canvas, currentImageSize);
  556. }
  557. else if (options.UnplayedCount.HasValue)
  558. {
  559. new UnplayedCountIndicator(_appPaths, _httpClientFactory(), _fileSystem).DrawUnplayedCountIndicator(canvas, currentImageSize, options.UnplayedCount.Value);
  560. }
  561. if (options.PercentPlayed > 0)
  562. {
  563. new PercentPlayedDrawer().Process(canvas, currentImageSize, options.PercentPlayed);
  564. }
  565. }
  566. catch (Exception ex)
  567. {
  568. _logger.ErrorException("Error drawing indicator overlay", ex);
  569. }
  570. }
  571. public string Name
  572. {
  573. get { return "Skia"; }
  574. }
  575. public bool SupportsImageCollageCreation
  576. {
  577. get { return true; }
  578. }
  579. public bool SupportsImageEncoding
  580. {
  581. get { return true; }
  582. }
  583. }
  584. }