TrickplayManager.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Text;
  7. using System.Threading;
  8. using System.Threading.Tasks;
  9. using Jellyfin.Data.Entities;
  10. using MediaBrowser.Common.Configuration;
  11. using MediaBrowser.Controller.Configuration;
  12. using MediaBrowser.Controller.Drawing;
  13. using MediaBrowser.Controller.Entities;
  14. using MediaBrowser.Controller.Library;
  15. using MediaBrowser.Controller.MediaEncoding;
  16. using MediaBrowser.Controller.Trickplay;
  17. using MediaBrowser.Model.Configuration;
  18. using MediaBrowser.Model.Entities;
  19. using MediaBrowser.Model.IO;
  20. using Microsoft.EntityFrameworkCore;
  21. using Microsoft.Extensions.Logging;
  22. namespace Jellyfin.Server.Implementations.Trickplay;
  23. /// <summary>
  24. /// ITrickplayManager implementation.
  25. /// </summary>
  26. public class TrickplayManager : ITrickplayManager
  27. {
  28. private readonly ILogger<TrickplayManager> _logger;
  29. private readonly IMediaEncoder _mediaEncoder;
  30. private readonly IFileSystem _fileSystem;
  31. private readonly EncodingHelper _encodingHelper;
  32. private readonly ILibraryManager _libraryManager;
  33. private readonly IServerConfigurationManager _config;
  34. private readonly IImageEncoder _imageEncoder;
  35. private readonly IDbContextFactory<JellyfinDbContext> _dbProvider;
  36. private readonly IApplicationPaths _appPaths;
  37. private static readonly SemaphoreSlim _resourcePool = new(1, 1);
  38. private static readonly string[] _trickplayImgExtensions = { ".jpg" };
  39. /// <summary>
  40. /// Initializes a new instance of the <see cref="TrickplayManager"/> class.
  41. /// </summary>
  42. /// <param name="logger">The logger.</param>
  43. /// <param name="mediaEncoder">The media encoder.</param>
  44. /// <param name="fileSystem">The file systen.</param>
  45. /// <param name="encodingHelper">The encoding helper.</param>
  46. /// <param name="libraryManager">The library manager.</param>
  47. /// <param name="config">The server configuration manager.</param>
  48. /// <param name="imageEncoder">The image encoder.</param>
  49. /// <param name="dbProvider">The database provider.</param>
  50. /// <param name="appPaths">The application paths.</param>
  51. public TrickplayManager(
  52. ILogger<TrickplayManager> logger,
  53. IMediaEncoder mediaEncoder,
  54. IFileSystem fileSystem,
  55. EncodingHelper encodingHelper,
  56. ILibraryManager libraryManager,
  57. IServerConfigurationManager config,
  58. IImageEncoder imageEncoder,
  59. IDbContextFactory<JellyfinDbContext> dbProvider,
  60. IApplicationPaths appPaths)
  61. {
  62. _logger = logger;
  63. _mediaEncoder = mediaEncoder;
  64. _fileSystem = fileSystem;
  65. _encodingHelper = encodingHelper;
  66. _libraryManager = libraryManager;
  67. _config = config;
  68. _imageEncoder = imageEncoder;
  69. _dbProvider = dbProvider;
  70. _appPaths = appPaths;
  71. }
  72. /// <inheritdoc />
  73. public async Task RefreshTrickplayDataAsync(Video video, bool replace, CancellationToken cancellationToken)
  74. {
  75. _logger.LogDebug("Trickplay refresh for {ItemId} (replace existing: {Replace})", video.Id, replace);
  76. var options = _config.Configuration.TrickplayOptions;
  77. foreach (var width in options.WidthResolutions)
  78. {
  79. cancellationToken.ThrowIfCancellationRequested();
  80. await RefreshTrickplayDataInternal(
  81. video,
  82. replace,
  83. width,
  84. options,
  85. cancellationToken).ConfigureAwait(false);
  86. }
  87. }
  88. private async Task RefreshTrickplayDataInternal(
  89. Video video,
  90. bool replace,
  91. int width,
  92. TrickplayOptions options,
  93. CancellationToken cancellationToken)
  94. {
  95. if (!CanGenerateTrickplay(video, options.Interval))
  96. {
  97. return;
  98. }
  99. var imgTempDir = string.Empty;
  100. var outputDir = GetTrickplayDirectory(video, width);
  101. await _resourcePool.WaitAsync(cancellationToken).ConfigureAwait(false);
  102. try
  103. {
  104. if (!replace && Directory.Exists(outputDir) && (await GetTrickplayResolutions(video.Id).ConfigureAwait(false)).ContainsKey(width))
  105. {
  106. _logger.LogDebug("Found existing trickplay files for {ItemId}. Exiting.", video.Id);
  107. return;
  108. }
  109. // Extract images
  110. // Note: Media sources under parent items exist as their own video/item as well. Only use this video stream for trickplay.
  111. var mediaSource = video.GetMediaSources(false).Find(source => Guid.Parse(source.Id).Equals(video.Id));
  112. if (mediaSource is null)
  113. {
  114. _logger.LogDebug("Found no matching media source for item {ItemId}", video.Id);
  115. return;
  116. }
  117. var mediaPath = mediaSource.Path;
  118. var mediaStream = mediaSource.VideoStream;
  119. var container = mediaSource.Container;
  120. _logger.LogInformation("Creating trickplay files at {Width} width, for {Path} [ID: {ItemId}]", width, mediaPath, video.Id);
  121. imgTempDir = await _mediaEncoder.ExtractVideoImagesOnIntervalAccelerated(
  122. mediaPath,
  123. container,
  124. mediaSource,
  125. mediaStream,
  126. width,
  127. TimeSpan.FromMilliseconds(options.Interval),
  128. options.EnableHwAcceleration,
  129. options.ProcessThreads,
  130. options.Qscale,
  131. options.ProcessPriority,
  132. _encodingHelper,
  133. cancellationToken).ConfigureAwait(false);
  134. if (string.IsNullOrEmpty(imgTempDir) || !Directory.Exists(imgTempDir))
  135. {
  136. throw new InvalidOperationException("Null or invalid directory from media encoder.");
  137. }
  138. var images = _fileSystem.GetFiles(imgTempDir, _trickplayImgExtensions, false, false)
  139. .Select(i => i.FullName)
  140. .OrderBy(i => i)
  141. .ToList();
  142. // Create tiles
  143. var trickplayInfo = CreateTiles(images, width, options, outputDir);
  144. // Save tiles info
  145. try
  146. {
  147. if (trickplayInfo is not null)
  148. {
  149. trickplayInfo.ItemId = video.Id;
  150. await SaveTrickplayInfo(trickplayInfo).ConfigureAwait(false);
  151. _logger.LogInformation("Finished creation of trickplay files for {0}", mediaPath);
  152. }
  153. else
  154. {
  155. throw new InvalidOperationException("Null trickplay tiles info from CreateTiles.");
  156. }
  157. }
  158. catch (Exception ex)
  159. {
  160. _logger.LogError(ex, "Error while saving trickplay tiles info.");
  161. // Make sure no files stay in metadata folders on failure
  162. // if tiles info wasn't saved.
  163. Directory.Delete(outputDir, true);
  164. }
  165. }
  166. catch (Exception ex)
  167. {
  168. _logger.LogError(ex, "Error creating trickplay images.");
  169. }
  170. finally
  171. {
  172. _resourcePool.Release();
  173. if (!string.IsNullOrEmpty(imgTempDir))
  174. {
  175. Directory.Delete(imgTempDir, true);
  176. }
  177. }
  178. }
  179. /// <inheritdoc />
  180. public TrickplayInfo CreateTiles(List<string> images, int width, TrickplayOptions options, string outputDir)
  181. {
  182. if (images.Count == 0)
  183. {
  184. throw new ArgumentException("Can't create trickplay from 0 images.");
  185. }
  186. var workDir = Path.Combine(_appPaths.TempDirectory, Guid.NewGuid().ToString("N"));
  187. Directory.CreateDirectory(workDir);
  188. var trickplayInfo = new TrickplayInfo
  189. {
  190. Width = width,
  191. Interval = options.Interval,
  192. TileWidth = options.TileWidth,
  193. TileHeight = options.TileHeight,
  194. ThumbnailCount = images.Count,
  195. // Set during image generation
  196. Height = 0,
  197. Bandwidth = 0
  198. };
  199. /*
  200. * Generate trickplay tiles from sets of thumbnails
  201. */
  202. var imageOptions = new ImageCollageOptions
  203. {
  204. Width = trickplayInfo.TileWidth,
  205. Height = trickplayInfo.TileHeight
  206. };
  207. var thumbnailsPerTile = trickplayInfo.TileWidth * trickplayInfo.TileHeight;
  208. var requiredTiles = (int)Math.Ceiling((double)images.Count / thumbnailsPerTile);
  209. for (int i = 0; i < requiredTiles; i++)
  210. {
  211. // Set output/input paths
  212. var tilePath = Path.Combine(workDir, $"{i}.jpg");
  213. imageOptions.OutputPath = tilePath;
  214. imageOptions.InputPaths = images.GetRange(i * thumbnailsPerTile, Math.Min(thumbnailsPerTile, images.Count - (i * thumbnailsPerTile)));
  215. // Generate image and use returned height for tiles info
  216. var height = _imageEncoder.CreateTrickplayTile(imageOptions, options.JpegQuality, trickplayInfo.Width, trickplayInfo.Height != 0 ? trickplayInfo.Height : null);
  217. if (trickplayInfo.Height == 0)
  218. {
  219. trickplayInfo.Height = height;
  220. }
  221. // Update bitrate
  222. var bitrate = (int)Math.Ceiling((decimal)new FileInfo(tilePath).Length * 8 / trickplayInfo.TileWidth / trickplayInfo.TileHeight / (trickplayInfo.Interval / 1000));
  223. trickplayInfo.Bandwidth = Math.Max(trickplayInfo.Bandwidth, bitrate);
  224. }
  225. /*
  226. * Move trickplay tiles to output directory
  227. */
  228. Directory.CreateDirectory(Directory.GetParent(outputDir)!.FullName);
  229. // Replace existing tiles if they already exist
  230. if (Directory.Exists(outputDir))
  231. {
  232. Directory.Delete(outputDir, true);
  233. }
  234. MoveDirectory(workDir, outputDir);
  235. return trickplayInfo;
  236. }
  237. private bool CanGenerateTrickplay(Video video, int interval)
  238. {
  239. var videoType = video.VideoType;
  240. if (videoType == VideoType.Iso || videoType == VideoType.Dvd || videoType == VideoType.BluRay)
  241. {
  242. return false;
  243. }
  244. if (video.IsPlaceHolder)
  245. {
  246. return false;
  247. }
  248. if (video.IsShortcut)
  249. {
  250. return false;
  251. }
  252. if (!video.IsCompleteMedia)
  253. {
  254. return false;
  255. }
  256. if (!video.RunTimeTicks.HasValue || video.RunTimeTicks.Value < TimeSpan.FromMilliseconds(interval).Ticks)
  257. {
  258. return false;
  259. }
  260. var libraryOptions = _libraryManager.GetLibraryOptions(video);
  261. if (libraryOptions is null || !libraryOptions.EnableTrickplayImageExtraction)
  262. {
  263. return false;
  264. }
  265. // Can't extract images if there are no video streams
  266. return video.GetMediaStreams().Count > 0;
  267. }
  268. /// <inheritdoc />
  269. public async Task<Dictionary<int, TrickplayInfo>> GetTrickplayResolutions(Guid itemId)
  270. {
  271. var trickplayResolutions = new Dictionary<int, TrickplayInfo>();
  272. var dbContext = await _dbProvider.CreateDbContextAsync().ConfigureAwait(false);
  273. await using (dbContext.ConfigureAwait(false))
  274. {
  275. var trickplayInfos = await dbContext.TrickplayInfos
  276. .AsNoTracking()
  277. .Where(i => i.ItemId.Equals(itemId))
  278. .ToListAsync()
  279. .ConfigureAwait(false);
  280. foreach (var info in trickplayInfos)
  281. {
  282. trickplayResolutions[info.Width] = info;
  283. }
  284. }
  285. return trickplayResolutions;
  286. }
  287. /// <inheritdoc />
  288. public async Task SaveTrickplayInfo(TrickplayInfo info)
  289. {
  290. var dbContext = await _dbProvider.CreateDbContextAsync().ConfigureAwait(false);
  291. await using (dbContext.ConfigureAwait(false))
  292. {
  293. var oldInfo = await dbContext.TrickplayInfos.FindAsync(info.ItemId, info.Width).ConfigureAwait(false);
  294. if (oldInfo is not null)
  295. {
  296. dbContext.TrickplayInfos.Remove(oldInfo);
  297. }
  298. dbContext.Add(info);
  299. await dbContext.SaveChangesAsync().ConfigureAwait(false);
  300. }
  301. }
  302. /// <inheritdoc />
  303. public async Task<Dictionary<string, Dictionary<int, TrickplayInfo>>> GetTrickplayManifest(BaseItem item)
  304. {
  305. var trickplayManifest = new Dictionary<string, Dictionary<int, TrickplayInfo>>();
  306. foreach (var mediaSource in item.GetMediaSources(false))
  307. {
  308. var mediaSourceId = Guid.Parse(mediaSource.Id);
  309. var trickplayResolutions = await GetTrickplayResolutions(mediaSourceId).ConfigureAwait(false);
  310. if (trickplayResolutions.Count > 0)
  311. {
  312. trickplayManifest[mediaSource.Id] = trickplayResolutions;
  313. }
  314. }
  315. return trickplayManifest;
  316. }
  317. /// <inheritdoc />
  318. public string GetTrickplayTilePath(BaseItem item, int width, int index)
  319. {
  320. return Path.Combine(GetTrickplayDirectory(item, width), index + ".jpg");
  321. }
  322. /// <inheritdoc />
  323. public async Task<string?> GetHlsPlaylist(Guid itemId, int width, string? apiKey)
  324. {
  325. var trickplayResolutions = await GetTrickplayResolutions(itemId).ConfigureAwait(false);
  326. if (trickplayResolutions is not null && trickplayResolutions.TryGetValue(width, out var trickplayInfo))
  327. {
  328. var builder = new StringBuilder(128);
  329. if (trickplayInfo.ThumbnailCount > 0)
  330. {
  331. const string urlFormat = "Trickplay/{0}/{1}.jpg?MediaSourceId={2}&api_key={3}";
  332. const string decimalFormat = "{0:0.###}";
  333. var resolution = $"{trickplayInfo.Width}x{trickplayInfo.Height}";
  334. var layout = $"{trickplayInfo.TileWidth}x{trickplayInfo.TileHeight}";
  335. var thumbnailsPerTile = trickplayInfo.TileWidth * trickplayInfo.TileHeight;
  336. var thumbnailDuration = trickplayInfo.Interval / 1000d;
  337. var infDuration = thumbnailDuration * thumbnailsPerTile;
  338. var tileCount = (int)Math.Ceiling((decimal)trickplayInfo.ThumbnailCount / thumbnailsPerTile);
  339. builder
  340. .AppendLine("#EXTM3U")
  341. .Append("#EXT-X-TARGETDURATION:")
  342. .AppendLine(tileCount.ToString(CultureInfo.InvariantCulture))
  343. .AppendLine("#EXT-X-VERSION:7")
  344. .AppendLine("#EXT-X-MEDIA-SEQUENCE:1")
  345. .AppendLine("#EXT-X-PLAYLIST-TYPE:VOD")
  346. .AppendLine("#EXT-X-IMAGES-ONLY");
  347. for (int i = 0; i < tileCount; i++)
  348. {
  349. // All tiles prior to the last must contain full amount of thumbnails (no black).
  350. if (i == tileCount - 1)
  351. {
  352. thumbnailsPerTile = trickplayInfo.ThumbnailCount - (i * thumbnailsPerTile);
  353. infDuration = thumbnailDuration * thumbnailsPerTile;
  354. }
  355. // EXTINF
  356. builder
  357. .Append("#EXTINF:")
  358. .AppendFormat(CultureInfo.InvariantCulture, decimalFormat, infDuration)
  359. .AppendLine(",");
  360. // EXT-X-TILES
  361. builder
  362. .Append("#EXT-X-TILES:RESOLUTION=")
  363. .Append(resolution)
  364. .Append(",LAYOUT=")
  365. .Append(layout)
  366. .Append(",DURATION=")
  367. .AppendFormat(CultureInfo.InvariantCulture, decimalFormat, thumbnailDuration)
  368. .AppendLine();
  369. // URL
  370. builder
  371. .AppendFormat(
  372. CultureInfo.InvariantCulture,
  373. urlFormat,
  374. width.ToString(CultureInfo.InvariantCulture),
  375. i.ToString(CultureInfo.InvariantCulture),
  376. itemId.ToString("N"),
  377. apiKey)
  378. .AppendLine();
  379. }
  380. builder.AppendLine("#EXT-X-ENDLIST");
  381. return builder.ToString();
  382. }
  383. }
  384. return null;
  385. }
  386. private string GetTrickplayDirectory(BaseItem item, int? width = null)
  387. {
  388. var path = Path.Combine(item.GetInternalMetadataPath(), "trickplay");
  389. return width.HasValue ? Path.Combine(path, width.Value.ToString(CultureInfo.InvariantCulture)) : path;
  390. }
  391. private void MoveDirectory(string source, string destination)
  392. {
  393. try
  394. {
  395. Directory.Move(source, destination);
  396. }
  397. catch (IOException)
  398. {
  399. // Cross device move requires a copy
  400. Directory.CreateDirectory(destination);
  401. foreach (string file in Directory.GetFiles(source))
  402. {
  403. File.Copy(file, Path.Join(destination, Path.GetFileName(file)), true);
  404. }
  405. Directory.Delete(source, true);
  406. }
  407. }
  408. }