TrickplayManager.cs 18 KB

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