SkiaEncoder.cs 23 KB

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