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