SkiaEncoder.cs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685
  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 Microsoft.Extensions.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.LogInformation("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. using (var subset = image.Subset(newRect))
  155. {
  156. return SKBitmap.FromImage(subset);
  157. }
  158. }
  159. public ImageSize GetImageSize(string path)
  160. {
  161. using (var s = new SKFileStream(path))
  162. using (var codec = SKCodec.Create(s))
  163. {
  164. var info = codec.Info;
  165. return new ImageSize
  166. {
  167. Width = info.Width,
  168. Height = info.Height
  169. };
  170. }
  171. }
  172. private static bool HasDiacritics(string text)
  173. {
  174. return !String.Equals(text, text.RemoveDiacritics(), StringComparison.Ordinal);
  175. }
  176. private static bool RequiresSpecialCharacterHack(string path)
  177. {
  178. if (_localizationManager.HasUnicodeCategory(path, UnicodeCategory.OtherLetter))
  179. {
  180. return true;
  181. }
  182. if (HasDiacritics(path))
  183. {
  184. return true;
  185. }
  186. return false;
  187. }
  188. private static string NormalizePath(string path, IFileSystem fileSystem)
  189. {
  190. if (!RequiresSpecialCharacterHack(path))
  191. {
  192. return path;
  193. }
  194. var tempPath = Path.Combine(_appPaths.TempDirectory, Guid.NewGuid() + Path.GetExtension(path) ?? string.Empty);
  195. fileSystem.CreateDirectory(fileSystem.GetDirectoryName(tempPath));
  196. fileSystem.CopyFile(path, tempPath, true);
  197. return tempPath;
  198. }
  199. private static SKEncodedOrigin GetSKEncodedOrigin(ImageOrientation? orientation)
  200. {
  201. if (!orientation.HasValue)
  202. {
  203. return SKEncodedOrigin.TopLeft;
  204. }
  205. switch (orientation.Value)
  206. {
  207. case ImageOrientation.TopRight:
  208. return SKEncodedOrigin.TopRight;
  209. case ImageOrientation.RightTop:
  210. return SKEncodedOrigin.RightTop;
  211. case ImageOrientation.RightBottom:
  212. return SKEncodedOrigin.RightBottom;
  213. case ImageOrientation.LeftTop:
  214. return SKEncodedOrigin.LeftTop;
  215. case ImageOrientation.LeftBottom:
  216. return SKEncodedOrigin.LeftBottom;
  217. case ImageOrientation.BottomRight:
  218. return SKEncodedOrigin.BottomRight;
  219. case ImageOrientation.BottomLeft:
  220. return SKEncodedOrigin.BottomLeft;
  221. default:
  222. return SKEncodedOrigin.TopLeft;
  223. }
  224. }
  225. private static string[] TransparentImageTypes = new string[] { ".png", ".gif", ".webp" };
  226. internal static SKBitmap Decode(string path, bool forceCleanBitmap, IFileSystem fileSystem, ImageOrientation? orientation, out SKEncodedOrigin origin)
  227. {
  228. if (!fileSystem.FileExists(path))
  229. {
  230. throw new FileNotFoundException("File not found", path);
  231. }
  232. var requiresTransparencyHack = TransparentImageTypes.Contains(Path.GetExtension(path) ?? string.Empty);
  233. if (requiresTransparencyHack || forceCleanBitmap)
  234. {
  235. using (var stream = new SKFileStream(NormalizePath(path, fileSystem)))
  236. using (var codec = SKCodec.Create(stream))
  237. {
  238. if (codec == null)
  239. {
  240. origin = GetSKEncodedOrigin(orientation);
  241. return null;
  242. }
  243. // create the bitmap
  244. var bitmap = new SKBitmap(codec.Info.Width, codec.Info.Height, !requiresTransparencyHack);
  245. if (bitmap != null)
  246. {
  247. // decode
  248. codec.GetPixels(bitmap.Info, bitmap.GetPixels());
  249. origin = codec.EncodedOrigin;
  250. }
  251. else
  252. {
  253. origin = GetSKEncodedOrigin(orientation);
  254. }
  255. return bitmap;
  256. }
  257. }
  258. var resultBitmap = SKBitmap.Decode(NormalizePath(path, fileSystem));
  259. if (resultBitmap == null)
  260. {
  261. return Decode(path, true, fileSystem, orientation, out origin);
  262. }
  263. // If we have to resize these they often end up distorted
  264. if (resultBitmap.ColorType == SKColorType.Gray8)
  265. {
  266. using (resultBitmap)
  267. {
  268. return Decode(path, true, fileSystem, orientation, out origin);
  269. }
  270. }
  271. origin = SKEncodedOrigin.TopLeft;
  272. return resultBitmap;
  273. }
  274. private SKBitmap GetBitmap(string path, bool cropWhitespace, bool forceAnalyzeBitmap, ImageOrientation? orientation, out SKEncodedOrigin origin)
  275. {
  276. if (cropWhitespace)
  277. {
  278. using (var bitmap = Decode(path, forceAnalyzeBitmap, _fileSystem, orientation, out origin))
  279. {
  280. return CropWhiteSpace(bitmap);
  281. }
  282. }
  283. return Decode(path, forceAnalyzeBitmap, _fileSystem, orientation, out origin);
  284. }
  285. private SKBitmap GetBitmap(string path, bool cropWhitespace, bool autoOrient, ImageOrientation? orientation)
  286. {
  287. SKEncodedOrigin origin;
  288. if (autoOrient)
  289. {
  290. var bitmap = GetBitmap(path, cropWhitespace, true, orientation, out origin);
  291. if (bitmap != null)
  292. {
  293. if (origin != SKEncodedOrigin.TopLeft)
  294. {
  295. using (bitmap)
  296. {
  297. return OrientImage(bitmap, origin);
  298. }
  299. }
  300. }
  301. return bitmap;
  302. }
  303. return GetBitmap(path, cropWhitespace, false, orientation, out origin);
  304. }
  305. private SKBitmap OrientImage(SKBitmap bitmap, SKEncodedOrigin origin)
  306. {
  307. //var transformations = {
  308. // 2: { rotate: 0, flip: true},
  309. // 3: { rotate: 180, flip: false},
  310. // 4: { rotate: 180, flip: true},
  311. // 5: { rotate: 90, flip: true},
  312. // 6: { rotate: 90, flip: false},
  313. // 7: { rotate: 270, flip: true},
  314. // 8: { rotate: 270, flip: false},
  315. //}
  316. switch (origin)
  317. {
  318. case SKEncodedOrigin.TopRight:
  319. {
  320. var rotated = new SKBitmap(bitmap.Width, bitmap.Height);
  321. using (var surface = new SKCanvas(rotated))
  322. {
  323. surface.Translate(rotated.Width, 0);
  324. surface.Scale(-1, 1);
  325. surface.DrawBitmap(bitmap, 0, 0);
  326. }
  327. return rotated;
  328. }
  329. case SKEncodedOrigin.BottomRight:
  330. {
  331. var rotated = new SKBitmap(bitmap.Width, bitmap.Height);
  332. using (var surface = new SKCanvas(rotated))
  333. {
  334. float px = bitmap.Width;
  335. px /= 2;
  336. float py = bitmap.Height;
  337. py /= 2;
  338. surface.RotateDegrees(180, px, py);
  339. surface.DrawBitmap(bitmap, 0, 0);
  340. }
  341. return rotated;
  342. }
  343. case SKEncodedOrigin.BottomLeft:
  344. {
  345. var rotated = new SKBitmap(bitmap.Width, bitmap.Height);
  346. using (var surface = new SKCanvas(rotated))
  347. {
  348. float px = bitmap.Width;
  349. px /= 2;
  350. float py = bitmap.Height;
  351. py /= 2;
  352. surface.Translate(rotated.Width, 0);
  353. surface.Scale(-1, 1);
  354. surface.RotateDegrees(180, px, py);
  355. surface.DrawBitmap(bitmap, 0, 0);
  356. }
  357. return rotated;
  358. }
  359. case SKEncodedOrigin.LeftTop:
  360. {
  361. // TODO: Remove dual canvases, had trouble with flipping
  362. using (var rotated = new SKBitmap(bitmap.Height, bitmap.Width))
  363. {
  364. using (var surface = new SKCanvas(rotated))
  365. {
  366. surface.Translate(rotated.Width, 0);
  367. surface.RotateDegrees(90);
  368. surface.DrawBitmap(bitmap, 0, 0);
  369. }
  370. var flippedBitmap = new SKBitmap(rotated.Width, rotated.Height);
  371. using (var flippedCanvas = new SKCanvas(flippedBitmap))
  372. {
  373. flippedCanvas.Translate(flippedBitmap.Width, 0);
  374. flippedCanvas.Scale(-1, 1);
  375. flippedCanvas.DrawBitmap(rotated, 0, 0);
  376. }
  377. return flippedBitmap;
  378. }
  379. }
  380. case SKEncodedOrigin.RightTop:
  381. {
  382. var rotated = new SKBitmap(bitmap.Height, bitmap.Width);
  383. using (var surface = new SKCanvas(rotated))
  384. {
  385. surface.Translate(rotated.Width, 0);
  386. surface.RotateDegrees(90);
  387. surface.DrawBitmap(bitmap, 0, 0);
  388. }
  389. return rotated;
  390. }
  391. case SKEncodedOrigin.RightBottom:
  392. {
  393. // TODO: Remove dual canvases, had trouble with flipping
  394. using (var rotated = new SKBitmap(bitmap.Height, bitmap.Width))
  395. {
  396. using (var surface = new SKCanvas(rotated))
  397. {
  398. surface.Translate(0, rotated.Height);
  399. surface.RotateDegrees(270);
  400. surface.DrawBitmap(bitmap, 0, 0);
  401. }
  402. var flippedBitmap = new SKBitmap(rotated.Width, rotated.Height);
  403. using (var flippedCanvas = new SKCanvas(flippedBitmap))
  404. {
  405. flippedCanvas.Translate(flippedBitmap.Width, 0);
  406. flippedCanvas.Scale(-1, 1);
  407. flippedCanvas.DrawBitmap(rotated, 0, 0);
  408. }
  409. return flippedBitmap;
  410. }
  411. }
  412. case SKEncodedOrigin.LeftBottom:
  413. {
  414. var rotated = new SKBitmap(bitmap.Height, bitmap.Width);
  415. using (var surface = new SKCanvas(rotated))
  416. {
  417. surface.Translate(0, rotated.Height);
  418. surface.RotateDegrees(270);
  419. surface.DrawBitmap(bitmap, 0, 0);
  420. }
  421. return rotated;
  422. }
  423. default:
  424. return bitmap;
  425. }
  426. }
  427. public string EncodeImage(string inputPath, DateTime dateModified, string outputPath, bool autoOrient, ImageOrientation? orientation, int quality, ImageProcessingOptions options, ImageFormat selectedOutputFormat)
  428. {
  429. if (string.IsNullOrWhiteSpace(inputPath))
  430. {
  431. throw new ArgumentNullException("inputPath");
  432. }
  433. if (string.IsNullOrWhiteSpace(inputPath))
  434. {
  435. throw new ArgumentNullException("outputPath");
  436. }
  437. var skiaOutputFormat = GetImageFormat(selectedOutputFormat);
  438. var hasBackgroundColor = !string.IsNullOrWhiteSpace(options.BackgroundColor);
  439. var hasForegroundColor = !string.IsNullOrWhiteSpace(options.ForegroundLayer);
  440. var blur = options.Blur ?? 0;
  441. var hasIndicator = options.AddPlayedIndicator || options.UnplayedCount.HasValue || !options.PercentPlayed.Equals(0);
  442. using (var bitmap = GetBitmap(inputPath, options.CropWhiteSpace, autoOrient, orientation))
  443. {
  444. if (bitmap == null)
  445. {
  446. throw new ArgumentOutOfRangeException(string.Format("Skia unable to read image {0}", inputPath));
  447. }
  448. //_logger.LogInformation("Color type {0}", bitmap.Info.ColorType);
  449. var originalImageSize = new ImageSize(bitmap.Width, bitmap.Height);
  450. if (!options.CropWhiteSpace && options.HasDefaultOptions(inputPath, originalImageSize) && !autoOrient)
  451. {
  452. // Just spit out the original file if all the options are default
  453. return inputPath;
  454. }
  455. var newImageSize = ImageHelper.GetNewImageSize(options, originalImageSize);
  456. var width = Convert.ToInt32(Math.Round(newImageSize.Width));
  457. var height = Convert.ToInt32(Math.Round(newImageSize.Height));
  458. using (var resizedBitmap = new SKBitmap(width, height))//, bitmap.ColorType, bitmap.AlphaType))
  459. {
  460. // scale image
  461. bitmap.ScalePixels(resizedBitmap, SKFilterQuality.High);
  462. // If all we're doing is resizing then we can stop now
  463. if (!hasBackgroundColor && !hasForegroundColor && blur == 0 && !hasIndicator)
  464. {
  465. _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(outputPath));
  466. using (var outputStream = new SKFileWStream(outputPath))
  467. {
  468. using (var pixmap = new SKPixmap(new SKImageInfo(width, height), resizedBitmap.GetPixels()))
  469. {
  470. pixmap.Encode(outputStream, skiaOutputFormat, quality);
  471. return outputPath;
  472. }
  473. }
  474. }
  475. // create bitmap to use for canvas drawing used to draw into bitmap
  476. using (var saveBitmap = new SKBitmap(width, height))//, bitmap.ColorType, bitmap.AlphaType))
  477. using (var canvas = new SKCanvas(saveBitmap))
  478. {
  479. // set background color if present
  480. if (hasBackgroundColor)
  481. {
  482. canvas.Clear(SKColor.Parse(options.BackgroundColor));
  483. }
  484. // Add blur if option is present
  485. if (blur > 0)
  486. {
  487. // create image from resized bitmap to apply blur
  488. using (var paint = new SKPaint())
  489. using (var filter = SKImageFilter.CreateBlur(blur, blur))
  490. {
  491. paint.ImageFilter = filter;
  492. canvas.DrawBitmap(resizedBitmap, SKRect.Create(width, height), paint);
  493. }
  494. }
  495. else
  496. {
  497. // draw resized bitmap onto canvas
  498. canvas.DrawBitmap(resizedBitmap, SKRect.Create(width, height));
  499. }
  500. // If foreground layer present then draw
  501. if (hasForegroundColor)
  502. {
  503. if (!Double.TryParse(options.ForegroundLayer, out double opacity))
  504. {
  505. opacity = .4;
  506. }
  507. canvas.DrawColor(new SKColor(0, 0, 0, (Byte)((1 - opacity) * 0xFF)), SKBlendMode.SrcOver);
  508. }
  509. if (hasIndicator)
  510. {
  511. DrawIndicator(canvas, width, height, options);
  512. }
  513. _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(outputPath));
  514. using (var outputStream = new SKFileWStream(outputPath))
  515. {
  516. using (var pixmap = new SKPixmap(new SKImageInfo(width, height), saveBitmap.GetPixels()))
  517. {
  518. pixmap.Encode(outputStream, skiaOutputFormat, quality);
  519. }
  520. }
  521. }
  522. }
  523. }
  524. return outputPath;
  525. }
  526. public void CreateImageCollage(ImageCollageOptions options)
  527. {
  528. double ratio = options.Width;
  529. ratio /= options.Height;
  530. if (ratio >= 1.4)
  531. {
  532. new StripCollageBuilder(_appPaths, _fileSystem).BuildThumbCollage(options.InputPaths, options.OutputPath, options.Width, options.Height);
  533. }
  534. else if (ratio >= .9)
  535. {
  536. new StripCollageBuilder(_appPaths, _fileSystem).BuildSquareCollage(options.InputPaths, options.OutputPath, options.Width, options.Height);
  537. }
  538. else
  539. {
  540. // @todo create Poster collage capability
  541. new StripCollageBuilder(_appPaths, _fileSystem).BuildSquareCollage(options.InputPaths, options.OutputPath, options.Width, options.Height);
  542. }
  543. }
  544. private void DrawIndicator(SKCanvas canvas, int imageWidth, int imageHeight, ImageProcessingOptions options)
  545. {
  546. try
  547. {
  548. var currentImageSize = new ImageSize(imageWidth, imageHeight);
  549. if (options.AddPlayedIndicator)
  550. {
  551. new PlayedIndicatorDrawer(_appPaths, _httpClientFactory(), _fileSystem).DrawPlayedIndicator(canvas, currentImageSize);
  552. }
  553. else if (options.UnplayedCount.HasValue)
  554. {
  555. new UnplayedCountIndicator(_appPaths, _httpClientFactory(), _fileSystem).DrawUnplayedCountIndicator(canvas, currentImageSize, options.UnplayedCount.Value);
  556. }
  557. if (options.PercentPlayed > 0)
  558. {
  559. new PercentPlayedDrawer().Process(canvas, currentImageSize, options.PercentPlayed);
  560. }
  561. }
  562. catch (Exception ex)
  563. {
  564. _logger.LogError(ex, "Error drawing indicator overlay");
  565. }
  566. }
  567. public string Name
  568. {
  569. get { return "Skia"; }
  570. }
  571. public bool SupportsImageCollageCreation
  572. {
  573. get { return true; }
  574. }
  575. public bool SupportsImageEncoding
  576. {
  577. get { return true; }
  578. }
  579. }
  580. }