TrickplayManager.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Threading;
  7. using System.Threading.Tasks;
  8. using MediaBrowser.Controller.Configuration;
  9. using MediaBrowser.Controller.Entities;
  10. using MediaBrowser.Controller.Library;
  11. using MediaBrowser.Controller.MediaEncoding;
  12. using MediaBrowser.Controller.Persistence;
  13. using MediaBrowser.Controller.Trickplay;
  14. using MediaBrowser.Model.Configuration;
  15. using MediaBrowser.Model.Entities;
  16. using MediaBrowser.Model.IO;
  17. using Microsoft.Extensions.Logging;
  18. using SkiaSharp;
  19. namespace MediaBrowser.Providers.Trickplay;
  20. /// <summary>
  21. /// ITrickplayManager implementation.
  22. /// </summary>
  23. public class TrickplayManager : ITrickplayManager
  24. {
  25. private readonly ILogger<TrickplayManager> _logger;
  26. private readonly IItemRepository _itemRepo;
  27. private readonly IMediaEncoder _mediaEncoder;
  28. private readonly IFileSystem _fileSystem;
  29. private readonly EncodingHelper _encodingHelper;
  30. private readonly ILibraryManager _libraryManager;
  31. private readonly IServerConfigurationManager _config;
  32. private static readonly SemaphoreSlim _resourcePool = new(1, 1);
  33. private static readonly string[] _trickplayImgExtensions = { ".jpg" };
  34. /// <summary>
  35. /// Initializes a new instance of the <see cref="TrickplayManager"/> class.
  36. /// </summary>
  37. /// <param name="logger">The logger.</param>
  38. /// <param name="itemRepo">The item repository.</param>
  39. /// <param name="mediaEncoder">The media encoder.</param>
  40. /// <param name="fileSystem">The file systen.</param>
  41. /// <param name="encodingHelper">The encoding helper.</param>
  42. /// <param name="libraryManager">The library manager.</param>
  43. /// <param name="config">The server configuration manager.</param>
  44. public TrickplayManager(
  45. ILogger<TrickplayManager> logger,
  46. IItemRepository itemRepo,
  47. IMediaEncoder mediaEncoder,
  48. IFileSystem fileSystem,
  49. EncodingHelper encodingHelper,
  50. ILibraryManager libraryManager,
  51. IServerConfigurationManager config)
  52. {
  53. _logger = logger;
  54. _itemRepo = itemRepo;
  55. _mediaEncoder = mediaEncoder;
  56. _fileSystem = fileSystem;
  57. _encodingHelper = encodingHelper;
  58. _libraryManager = libraryManager;
  59. _config = config;
  60. }
  61. /// <inheritdoc />
  62. public async Task RefreshTrickplayDataAsync(Video video, bool replace, CancellationToken cancellationToken)
  63. {
  64. _logger.LogDebug("Trickplay refresh for {ItemId} (replace existing: {Replace})", video.Id, replace);
  65. var options = _config.Configuration.TrickplayOptions;
  66. foreach (var width in options.WidthResolutions)
  67. {
  68. cancellationToken.ThrowIfCancellationRequested();
  69. await RefreshTrickplayDataInternal(
  70. video,
  71. replace,
  72. width,
  73. options,
  74. cancellationToken).ConfigureAwait(false);
  75. }
  76. }
  77. private async Task RefreshTrickplayDataInternal(
  78. Video video,
  79. bool replace,
  80. int width,
  81. TrickplayOptions options,
  82. CancellationToken cancellationToken)
  83. {
  84. if (!CanGenerateTrickplay(video, options.Interval))
  85. {
  86. return;
  87. }
  88. var imgTempDir = string.Empty;
  89. var outputDir = GetTrickplayDirectory(video, width);
  90. await _resourcePool.WaitAsync(cancellationToken).ConfigureAwait(false);
  91. try
  92. {
  93. if (!replace && Directory.Exists(outputDir) && GetTilesResolutions(video.Id).ContainsKey(width))
  94. {
  95. _logger.LogDebug("Found existing trickplay files for {ItemId}. Exiting.", video.Id);
  96. return;
  97. }
  98. // Extract images
  99. // Note: Media sources under parent items exist as their own video/item as well. Only use this video stream for trickplay.
  100. var mediaSource = video.GetMediaSources(false).Find(source => Guid.Parse(source.Id).Equals(video.Id));
  101. if (mediaSource is null)
  102. {
  103. _logger.LogDebug("Found no matching media source for item {ItemId}", video.Id);
  104. return;
  105. }
  106. var mediaPath = mediaSource.Path;
  107. var mediaStream = mediaSource.VideoStream;
  108. var container = mediaSource.Container;
  109. _logger.LogInformation("Creating trickplay files at {Width} width, for {Path} [ID: {ItemId}]", width, mediaPath, video.Id);
  110. imgTempDir = await _mediaEncoder.ExtractVideoImagesOnIntervalAccelerated(
  111. mediaPath,
  112. container,
  113. mediaSource,
  114. mediaStream,
  115. width,
  116. TimeSpan.FromMilliseconds(options.Interval),
  117. options.EnableHwAcceleration,
  118. options.ProcessThreads,
  119. options.Qscale,
  120. options.ProcessPriority,
  121. _encodingHelper,
  122. cancellationToken).ConfigureAwait(false);
  123. if (string.IsNullOrEmpty(imgTempDir) || !Directory.Exists(imgTempDir))
  124. {
  125. throw new InvalidOperationException("Null or invalid directory from media encoder.");
  126. }
  127. var images = _fileSystem.GetFiles(imgTempDir, _trickplayImgExtensions, false, false)
  128. .OrderBy(i => i.FullName)
  129. .ToList();
  130. // Create tiles
  131. var tilesTempDir = Path.Combine(imgTempDir, Guid.NewGuid().ToString("N"));
  132. var tilesInfo = CreateTiles(images, width, options, tilesTempDir, outputDir);
  133. // Save tiles info
  134. try
  135. {
  136. if (tilesInfo is not null)
  137. {
  138. SaveTilesInfo(video.Id, tilesInfo);
  139. _logger.LogInformation("Finished creation of trickplay files for {0}", mediaPath);
  140. }
  141. else
  142. {
  143. throw new InvalidOperationException("Null trickplay tiles info from CreateTiles.");
  144. }
  145. }
  146. catch (Exception ex)
  147. {
  148. _logger.LogError(ex, "Error while saving trickplay tiles info.");
  149. // Make sure no files stay in metadata folders on failure
  150. // if tiles info wasn't saved.
  151. Directory.Delete(outputDir, true);
  152. }
  153. }
  154. catch (Exception ex)
  155. {
  156. _logger.LogError(ex, "Error creating trickplay images.");
  157. }
  158. finally
  159. {
  160. _resourcePool.Release();
  161. if (!string.IsNullOrEmpty(imgTempDir))
  162. {
  163. Directory.Delete(imgTempDir, true);
  164. }
  165. }
  166. }
  167. private TrickplayTilesInfo CreateTiles(List<FileSystemMetadata> images, int width, TrickplayOptions options, string workDir, string outputDir)
  168. {
  169. if (images.Count == 0)
  170. {
  171. throw new InvalidOperationException("Can't create trickplay from 0 images.");
  172. }
  173. Directory.CreateDirectory(workDir);
  174. var tilesInfo = new TrickplayTilesInfo
  175. {
  176. Width = width,
  177. Interval = options.Interval,
  178. TileWidth = options.TileWidth,
  179. TileHeight = options.TileHeight,
  180. TileCount = 0,
  181. Bandwidth = 0
  182. };
  183. var firstImg = SKBitmap.Decode(images[0].FullName);
  184. if (firstImg == null)
  185. {
  186. throw new InvalidDataException("Could not decode image data.");
  187. }
  188. tilesInfo.Height = firstImg.Height;
  189. if (tilesInfo.Width != firstImg.Width)
  190. {
  191. throw new InvalidOperationException("Image width does not match config width.");
  192. }
  193. /*
  194. * Generate grids of trickplay image tiles
  195. */
  196. var imgNo = 0;
  197. var i = 0;
  198. while (i < images.Count)
  199. {
  200. var tileGrid = new SKBitmap(tilesInfo.Width * tilesInfo.TileWidth, tilesInfo.Height * tilesInfo.TileHeight);
  201. using (var canvas = new SKCanvas(tileGrid))
  202. {
  203. for (var y = 0; y < tilesInfo.TileHeight; y++)
  204. {
  205. for (var x = 0; x < tilesInfo.TileWidth; x++)
  206. {
  207. if (i >= images.Count)
  208. {
  209. break;
  210. }
  211. var img = SKBitmap.Decode(images[i].FullName);
  212. if (img == null)
  213. {
  214. throw new InvalidDataException("Could not decode image data.");
  215. }
  216. if (tilesInfo.Width != img.Width)
  217. {
  218. throw new InvalidOperationException("Image width does not match config width.");
  219. }
  220. if (tilesInfo.Height != img.Height)
  221. {
  222. throw new InvalidOperationException("Image height does not match first image height.");
  223. }
  224. canvas.DrawBitmap(img, x * tilesInfo.Width, y * tilesInfo.Height);
  225. tilesInfo.TileCount++;
  226. i++;
  227. }
  228. }
  229. }
  230. // Output each tile grid to singular file
  231. var tileGridPath = Path.Combine(workDir, $"{imgNo}.jpg");
  232. using (var stream = File.OpenWrite(tileGridPath))
  233. {
  234. tileGrid.Encode(stream, SKEncodedImageFormat.Jpeg, options.JpegQuality);
  235. }
  236. var bitrate = (int)Math.Ceiling((decimal)new FileInfo(tileGridPath).Length * 8 / tilesInfo.TileWidth / tilesInfo.TileHeight / (tilesInfo.Interval / 1000));
  237. tilesInfo.Bandwidth = Math.Max(tilesInfo.Bandwidth, bitrate);
  238. imgNo++;
  239. }
  240. /*
  241. * Move trickplay tiles to output directory
  242. */
  243. Directory.CreateDirectory(outputDir);
  244. // Replace existing tile grids if they already exist
  245. if (Directory.Exists(outputDir))
  246. {
  247. Directory.Delete(outputDir, true);
  248. }
  249. MoveDirectory(workDir, outputDir);
  250. return tilesInfo;
  251. }
  252. private bool CanGenerateTrickplay(Video video, int interval)
  253. {
  254. var videoType = video.VideoType;
  255. if (videoType == VideoType.Iso || videoType == VideoType.Dvd || videoType == VideoType.BluRay)
  256. {
  257. return false;
  258. }
  259. if (video.IsPlaceHolder)
  260. {
  261. return false;
  262. }
  263. if (video.IsShortcut)
  264. {
  265. return false;
  266. }
  267. if (!video.IsCompleteMedia)
  268. {
  269. return false;
  270. }
  271. if (!video.RunTimeTicks.HasValue || video.RunTimeTicks.Value < TimeSpan.FromMilliseconds(interval).Ticks)
  272. {
  273. return false;
  274. }
  275. var libraryOptions = _libraryManager.GetLibraryOptions(video);
  276. if (libraryOptions is not null)
  277. {
  278. if (!libraryOptions.EnableTrickplayImageExtraction)
  279. {
  280. return false;
  281. }
  282. }
  283. else
  284. {
  285. return false;
  286. }
  287. // Can't extract images if there are no video streams
  288. return video.GetMediaStreams().Count > 0;
  289. }
  290. /// <inheritdoc />
  291. public Dictionary<int, TrickplayTilesInfo> GetTilesResolutions(Guid itemId)
  292. {
  293. return _itemRepo.GetTilesResolutions(itemId);
  294. }
  295. /// <inheritdoc />
  296. public void SaveTilesInfo(Guid itemId, TrickplayTilesInfo tilesInfo)
  297. {
  298. _itemRepo.SaveTilesInfo(itemId, tilesInfo);
  299. }
  300. /// <inheritdoc />
  301. public Dictionary<Guid, Dictionary<int, TrickplayTilesInfo>> GetTrickplayManifest(BaseItem item)
  302. {
  303. return _itemRepo.GetTrickplayManifest(item);
  304. }
  305. /// <inheritdoc />
  306. public string GetTrickplayTilePath(BaseItem item, int width, int index)
  307. {
  308. return Path.Combine(GetTrickplayDirectory(item, width), index + ".jpg");
  309. }
  310. private string GetTrickplayDirectory(BaseItem item, int? width = null)
  311. {
  312. var path = Path.Combine(item.GetInternalMetadataPath(), "trickplay");
  313. return width.HasValue ? Path.Combine(path, width.Value.ToString(CultureInfo.InvariantCulture)) : path;
  314. }
  315. private void MoveDirectory(string source, string destination)
  316. {
  317. try
  318. {
  319. Directory.Move(source, destination);
  320. }
  321. catch (IOException)
  322. {
  323. // Cross device move requires a copy
  324. Directory.CreateDirectory(destination);
  325. foreach (string file in Directory.GetFiles(source))
  326. {
  327. File.Copy(file, Path.Join(destination, Path.GetFileName(file)), true);
  328. }
  329. Directory.Delete(source, true);
  330. }
  331. }
  332. }