TrickplayManager.cs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643
  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.Database.Implementations;
  11. using Jellyfin.Database.Implementations.Entities;
  12. using MediaBrowser.Common.Configuration;
  13. using MediaBrowser.Controller.Configuration;
  14. using MediaBrowser.Controller.Drawing;
  15. using MediaBrowser.Controller.Entities;
  16. using MediaBrowser.Controller.IO;
  17. using MediaBrowser.Controller.MediaEncoding;
  18. using MediaBrowser.Controller.Trickplay;
  19. using MediaBrowser.Model.Configuration;
  20. using MediaBrowser.Model.Entities;
  21. using MediaBrowser.Model.IO;
  22. using Microsoft.EntityFrameworkCore;
  23. using Microsoft.Extensions.Logging;
  24. namespace Jellyfin.Server.Implementations.Trickplay;
  25. /// <summary>
  26. /// ITrickplayManager implementation.
  27. /// </summary>
  28. public class TrickplayManager : ITrickplayManager
  29. {
  30. private readonly ILogger<TrickplayManager> _logger;
  31. private readonly IMediaEncoder _mediaEncoder;
  32. private readonly IFileSystem _fileSystem;
  33. private readonly EncodingHelper _encodingHelper;
  34. private readonly IServerConfigurationManager _config;
  35. private readonly IImageEncoder _imageEncoder;
  36. private readonly IDbContextFactory<JellyfinDbContext> _dbProvider;
  37. private readonly IApplicationPaths _appPaths;
  38. private readonly IPathManager _pathManager;
  39. private static readonly AsyncNonKeyedLocker _resourcePool = new(1);
  40. private static readonly string[] _trickplayImgExtensions = [".jpg"];
  41. /// <summary>
  42. /// Initializes a new instance of the <see cref="TrickplayManager"/> class.
  43. /// </summary>
  44. /// <param name="logger">The logger.</param>
  45. /// <param name="mediaEncoder">The media encoder.</param>
  46. /// <param name="fileSystem">The file system.</param>
  47. /// <param name="encodingHelper">The encoding helper.</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. /// <param name="pathManager">The path manager.</param>
  53. public TrickplayManager(
  54. ILogger<TrickplayManager> logger,
  55. IMediaEncoder mediaEncoder,
  56. IFileSystem fileSystem,
  57. EncodingHelper encodingHelper,
  58. IServerConfigurationManager config,
  59. IImageEncoder imageEncoder,
  60. IDbContextFactory<JellyfinDbContext> dbProvider,
  61. IApplicationPaths appPaths,
  62. IPathManager pathManager)
  63. {
  64. _logger = logger;
  65. _mediaEncoder = mediaEncoder;
  66. _fileSystem = fileSystem;
  67. _encodingHelper = encodingHelper;
  68. _config = config;
  69. _imageEncoder = imageEncoder;
  70. _dbProvider = dbProvider;
  71. _appPaths = appPaths;
  72. _pathManager = pathManager;
  73. }
  74. /// <inheritdoc />
  75. public async Task MoveGeneratedTrickplayDataAsync(Video video, LibraryOptions libraryOptions, CancellationToken cancellationToken)
  76. {
  77. var options = _config.Configuration.TrickplayOptions;
  78. if (!CanGenerateTrickplay(video, options.Interval, libraryOptions))
  79. {
  80. return;
  81. }
  82. var existingTrickplayResolutions = await GetTrickplayResolutions(video.Id).ConfigureAwait(false);
  83. foreach (var resolution in existingTrickplayResolutions)
  84. {
  85. cancellationToken.ThrowIfCancellationRequested();
  86. var existingResolution = resolution.Key;
  87. var tileWidth = resolution.Value.TileWidth;
  88. var tileHeight = resolution.Value.TileHeight;
  89. var shouldBeSavedWithMedia = libraryOptions is not null && libraryOptions.SaveTrickplayWithMedia;
  90. var localOutputDir = new DirectoryInfo(GetTrickplayDirectory(video, tileWidth, tileHeight, existingResolution, false));
  91. var mediaOutputDir = new DirectoryInfo(GetTrickplayDirectory(video, tileWidth, tileHeight, existingResolution, true));
  92. if (shouldBeSavedWithMedia && localOutputDir.Exists)
  93. {
  94. var localDirFiles = localOutputDir.EnumerateFiles();
  95. var mediaDirExists = mediaOutputDir.Exists;
  96. if (localDirFiles.Any() && ((mediaDirExists && mediaOutputDir.EnumerateFiles().Any()) || !mediaDirExists))
  97. {
  98. // Move images from local dir to media dir
  99. MoveContent(localOutputDir.FullName, mediaOutputDir.FullName);
  100. _logger.LogInformation("Moved trickplay images for {ItemName} to {Location}", video.Name, mediaOutputDir);
  101. }
  102. }
  103. else if (!shouldBeSavedWithMedia && mediaOutputDir.Exists)
  104. {
  105. var mediaDirFiles = mediaOutputDir.EnumerateFiles();
  106. var localDirExists = localOutputDir.Exists;
  107. if (mediaDirFiles.Any() && ((localDirExists && localOutputDir.EnumerateFiles().Any()) || !localDirExists))
  108. {
  109. // Move images from media dir to local dir
  110. MoveContent(mediaOutputDir.FullName, localOutputDir.FullName);
  111. _logger.LogInformation("Moved trickplay images for {ItemName} to {Location}", video.Name, localOutputDir);
  112. }
  113. }
  114. }
  115. }
  116. private void MoveContent(string sourceFolder, string destinationFolder)
  117. {
  118. _fileSystem.MoveDirectory(sourceFolder, destinationFolder);
  119. var parent = Directory.GetParent(sourceFolder);
  120. if (parent is not null)
  121. {
  122. var parentContent = parent.EnumerateDirectories();
  123. if (!parentContent.Any())
  124. {
  125. parent.Delete();
  126. }
  127. }
  128. }
  129. /// <inheritdoc />
  130. public async Task RefreshTrickplayDataAsync(Video video, bool replace, LibraryOptions libraryOptions, CancellationToken cancellationToken)
  131. {
  132. _logger.LogDebug("Trickplay refresh for {ItemId} (replace existing: {Replace})", video.Id, replace);
  133. var options = _config.Configuration.TrickplayOptions;
  134. if (options.Interval < 1000)
  135. {
  136. _logger.LogWarning("Trickplay image interval {Interval} is too small, reset to the minimum valid value of 1000", options.Interval);
  137. options.Interval = 1000;
  138. }
  139. foreach (var width in options.WidthResolutions)
  140. {
  141. cancellationToken.ThrowIfCancellationRequested();
  142. await RefreshTrickplayDataInternal(
  143. video,
  144. replace,
  145. width,
  146. options,
  147. libraryOptions,
  148. cancellationToken).ConfigureAwait(false);
  149. }
  150. }
  151. private async Task RefreshTrickplayDataInternal(
  152. Video video,
  153. bool replace,
  154. int width,
  155. TrickplayOptions options,
  156. LibraryOptions libraryOptions,
  157. CancellationToken cancellationToken)
  158. {
  159. if (!CanGenerateTrickplay(video, options.Interval, libraryOptions))
  160. {
  161. return;
  162. }
  163. var imgTempDir = string.Empty;
  164. using (await _resourcePool.LockAsync(cancellationToken).ConfigureAwait(false))
  165. {
  166. try
  167. {
  168. // Extract images
  169. // Note: Media sources under parent items exist as their own video/item as well. Only use this video stream for trickplay.
  170. var mediaSource = video.GetMediaSources(false).FirstOrDefault(source => Guid.Parse(source.Id).Equals(video.Id));
  171. if (mediaSource is null)
  172. {
  173. _logger.LogDebug("Found no matching media source for item {ItemId}", video.Id);
  174. return;
  175. }
  176. var mediaPath = mediaSource.Path;
  177. if (!File.Exists(mediaPath))
  178. {
  179. _logger.LogWarning("Media not found at {Path} for item {ItemID}", mediaPath, video.Id);
  180. return;
  181. }
  182. // We support video backdrops, but we should not generate trickplay images for them
  183. var parentDirectory = Directory.GetParent(mediaPath);
  184. if (parentDirectory is not null && string.Equals(parentDirectory.Name, "backdrops", StringComparison.OrdinalIgnoreCase))
  185. {
  186. _logger.LogDebug("Ignoring backdrop media found at {Path} for item {ItemID}", mediaPath, video.Id);
  187. return;
  188. }
  189. // The width has to be even, otherwise a lot of filters will not be able to sample it
  190. var actualWidth = 2 * (width / 2);
  191. // Force using the video width when the trickplay setting has a too large width
  192. if (mediaSource.VideoStream.Width is not null && mediaSource.VideoStream.Width < width)
  193. {
  194. _logger.LogWarning("Video width {VideoWidth} is smaller than trickplay setting {TrickPlayWidth}, using video width for thumbnails", mediaSource.VideoStream.Width, width);
  195. actualWidth = 2 * ((int)mediaSource.VideoStream.Width / 2);
  196. }
  197. var tileWidth = options.TileWidth;
  198. var tileHeight = options.TileHeight;
  199. var saveWithMedia = libraryOptions is not null && libraryOptions.SaveTrickplayWithMedia;
  200. var outputDir = new DirectoryInfo(GetTrickplayDirectory(video, tileWidth, tileHeight, actualWidth, saveWithMedia));
  201. // Import existing trickplay tiles
  202. if (!replace && outputDir.Exists)
  203. {
  204. var existingFiles = outputDir.GetFiles();
  205. if (existingFiles.Length > 0)
  206. {
  207. var hasTrickplayResolution = await HasTrickplayResolutionAsync(video.Id, actualWidth).ConfigureAwait(false);
  208. if (hasTrickplayResolution)
  209. {
  210. _logger.LogDebug("Found existing trickplay files for {ItemId}.", video.Id);
  211. return;
  212. }
  213. // Import tiles
  214. var localTrickplayInfo = new TrickplayInfo
  215. {
  216. ItemId = video.Id,
  217. Width = width,
  218. Interval = options.Interval,
  219. TileWidth = options.TileWidth,
  220. TileHeight = options.TileHeight,
  221. ThumbnailCount = existingFiles.Length,
  222. Height = 0,
  223. Bandwidth = 0
  224. };
  225. foreach (var tile in existingFiles)
  226. {
  227. var image = _imageEncoder.GetImageSize(tile.FullName);
  228. localTrickplayInfo.Height = Math.Max(localTrickplayInfo.Height, (int)Math.Ceiling((double)image.Height / localTrickplayInfo.TileHeight));
  229. var bitrate = (int)Math.Ceiling((decimal)tile.Length * 8 / localTrickplayInfo.TileWidth / localTrickplayInfo.TileHeight / (localTrickplayInfo.Interval / 1000));
  230. localTrickplayInfo.Bandwidth = Math.Max(localTrickplayInfo.Bandwidth, bitrate);
  231. }
  232. await SaveTrickplayInfo(localTrickplayInfo).ConfigureAwait(false);
  233. _logger.LogDebug("Imported existing trickplay files for {ItemId}.", video.Id);
  234. return;
  235. }
  236. }
  237. // Generate trickplay tiles
  238. var mediaStream = mediaSource.VideoStream;
  239. var container = mediaSource.Container;
  240. _logger.LogInformation("Creating trickplay files at {Width} width, for {Path} [ID: {ItemId}]", actualWidth, mediaPath, video.Id);
  241. imgTempDir = await _mediaEncoder.ExtractVideoImagesOnIntervalAccelerated(
  242. mediaPath,
  243. container,
  244. mediaSource,
  245. mediaStream,
  246. actualWidth,
  247. TimeSpan.FromMilliseconds(options.Interval),
  248. options.EnableHwAcceleration,
  249. options.EnableHwEncoding,
  250. options.ProcessThreads,
  251. options.Qscale,
  252. options.ProcessPriority,
  253. options.EnableKeyFrameOnlyExtraction,
  254. _encodingHelper,
  255. cancellationToken).ConfigureAwait(false);
  256. if (string.IsNullOrEmpty(imgTempDir) || !Directory.Exists(imgTempDir))
  257. {
  258. throw new InvalidOperationException("Null or invalid directory from media encoder.");
  259. }
  260. var images = _fileSystem.GetFiles(imgTempDir, _trickplayImgExtensions, false, false)
  261. .Select(i => i.FullName)
  262. .OrderBy(i => i)
  263. .ToList();
  264. // Create tiles
  265. var trickplayInfo = CreateTiles(images, actualWidth, options, outputDir.FullName);
  266. // Save tiles info
  267. try
  268. {
  269. if (trickplayInfo is not null)
  270. {
  271. trickplayInfo.ItemId = video.Id;
  272. await SaveTrickplayInfo(trickplayInfo).ConfigureAwait(false);
  273. _logger.LogInformation("Finished creation of trickplay files for {0}", mediaPath);
  274. }
  275. else
  276. {
  277. throw new InvalidOperationException("Null trickplay tiles info from CreateTiles.");
  278. }
  279. }
  280. catch (Exception ex)
  281. {
  282. _logger.LogError(ex, "Error while saving trickplay tiles info.");
  283. // Make sure no files stay in metadata folders on failure
  284. // if tiles info wasn't saved.
  285. outputDir.Delete(true);
  286. }
  287. }
  288. catch (Exception ex)
  289. {
  290. _logger.LogError(ex, "Error creating trickplay images.");
  291. }
  292. finally
  293. {
  294. if (!string.IsNullOrEmpty(imgTempDir))
  295. {
  296. Directory.Delete(imgTempDir, true);
  297. }
  298. }
  299. }
  300. }
  301. /// <inheritdoc />
  302. public TrickplayInfo CreateTiles(IReadOnlyList<string> images, int width, TrickplayOptions options, string outputDir)
  303. {
  304. if (images.Count == 0)
  305. {
  306. throw new ArgumentException("Can't create trickplay from 0 images.");
  307. }
  308. var workDir = Path.Combine(_appPaths.TempDirectory, "trickplay_" + Guid.NewGuid().ToString("N"));
  309. Directory.CreateDirectory(workDir);
  310. var trickplayInfo = new TrickplayInfo
  311. {
  312. Width = width,
  313. Interval = options.Interval,
  314. TileWidth = options.TileWidth,
  315. TileHeight = options.TileHeight,
  316. ThumbnailCount = images.Count,
  317. // Set during image generation
  318. Height = 0,
  319. Bandwidth = 0
  320. };
  321. /*
  322. * Generate trickplay tiles from sets of thumbnails
  323. */
  324. var imageOptions = new ImageCollageOptions
  325. {
  326. Width = trickplayInfo.TileWidth,
  327. Height = trickplayInfo.TileHeight
  328. };
  329. var thumbnailsPerTile = trickplayInfo.TileWidth * trickplayInfo.TileHeight;
  330. var requiredTiles = (int)Math.Ceiling((double)images.Count / thumbnailsPerTile);
  331. for (int i = 0; i < requiredTiles; i++)
  332. {
  333. // Set output/input paths
  334. var tilePath = Path.Combine(workDir, $"{i}.jpg");
  335. imageOptions.OutputPath = tilePath;
  336. imageOptions.InputPaths = images.Skip(i * thumbnailsPerTile).Take(Math.Min(thumbnailsPerTile, images.Count - (i * thumbnailsPerTile))).ToList();
  337. // Generate image and use returned height for tiles info
  338. var height = _imageEncoder.CreateTrickplayTile(imageOptions, options.JpegQuality, trickplayInfo.Width, trickplayInfo.Height != 0 ? trickplayInfo.Height : null);
  339. if (trickplayInfo.Height == 0)
  340. {
  341. trickplayInfo.Height = height;
  342. }
  343. // Update bitrate
  344. var bitrate = (int)Math.Ceiling(new FileInfo(tilePath).Length * 8m / trickplayInfo.TileWidth / trickplayInfo.TileHeight / (trickplayInfo.Interval / 1000m));
  345. trickplayInfo.Bandwidth = Math.Max(trickplayInfo.Bandwidth, bitrate);
  346. }
  347. /*
  348. * Move trickplay tiles to output directory
  349. */
  350. Directory.CreateDirectory(Directory.GetParent(outputDir)!.FullName);
  351. // Replace existing tiles if they already exist
  352. if (Directory.Exists(outputDir))
  353. {
  354. Directory.Delete(outputDir, true);
  355. }
  356. _fileSystem.MoveDirectory(workDir, outputDir);
  357. return trickplayInfo;
  358. }
  359. private bool CanGenerateTrickplay(Video video, int interval, LibraryOptions libraryOptions)
  360. {
  361. var videoType = video.VideoType;
  362. if (videoType == VideoType.Iso || videoType == VideoType.Dvd || videoType == VideoType.BluRay)
  363. {
  364. return false;
  365. }
  366. if (video.IsPlaceHolder)
  367. {
  368. return false;
  369. }
  370. if (video.IsShortcut)
  371. {
  372. return false;
  373. }
  374. if (!video.IsCompleteMedia)
  375. {
  376. return false;
  377. }
  378. if (!video.RunTimeTicks.HasValue || video.RunTimeTicks.Value < TimeSpan.FromMilliseconds(interval).Ticks)
  379. {
  380. return false;
  381. }
  382. if (libraryOptions is null || !libraryOptions.EnableTrickplayImageExtraction)
  383. {
  384. return false;
  385. }
  386. // Can't extract images if there are no video streams
  387. return video.GetMediaStreams().Count > 0;
  388. }
  389. /// <inheritdoc />
  390. public async Task<Dictionary<int, TrickplayInfo>> GetTrickplayResolutions(Guid itemId)
  391. {
  392. var trickplayResolutions = new Dictionary<int, TrickplayInfo>();
  393. var dbContext = await _dbProvider.CreateDbContextAsync().ConfigureAwait(false);
  394. await using (dbContext.ConfigureAwait(false))
  395. {
  396. var trickplayInfos = await dbContext.TrickplayInfos
  397. .AsNoTracking()
  398. .Where(i => i.ItemId.Equals(itemId))
  399. .ToListAsync()
  400. .ConfigureAwait(false);
  401. foreach (var info in trickplayInfos)
  402. {
  403. trickplayResolutions[info.Width] = info;
  404. }
  405. }
  406. return trickplayResolutions;
  407. }
  408. /// <inheritdoc />
  409. public async Task<IReadOnlyList<TrickplayInfo>> GetTrickplayItemsAsync(int limit, int offset)
  410. {
  411. IReadOnlyList<TrickplayInfo> trickplayItems;
  412. var dbContext = await _dbProvider.CreateDbContextAsync().ConfigureAwait(false);
  413. await using (dbContext.ConfigureAwait(false))
  414. {
  415. trickplayItems = await dbContext.TrickplayInfos
  416. .AsNoTracking()
  417. .OrderBy(i => i.ItemId)
  418. .Skip(offset)
  419. .Take(limit)
  420. .ToListAsync()
  421. .ConfigureAwait(false);
  422. }
  423. return trickplayItems;
  424. }
  425. /// <inheritdoc />
  426. public async Task SaveTrickplayInfo(TrickplayInfo info)
  427. {
  428. var dbContext = await _dbProvider.CreateDbContextAsync().ConfigureAwait(false);
  429. await using (dbContext.ConfigureAwait(false))
  430. {
  431. var oldInfo = await dbContext.TrickplayInfos.FindAsync(info.ItemId, info.Width).ConfigureAwait(false);
  432. if (oldInfo is not null)
  433. {
  434. dbContext.TrickplayInfos.Remove(oldInfo);
  435. }
  436. dbContext.Add(info);
  437. await dbContext.SaveChangesAsync().ConfigureAwait(false);
  438. }
  439. }
  440. /// <inheritdoc />
  441. public async Task DeleteTrickplayDataAsync(Guid itemId, CancellationToken cancellationToken)
  442. {
  443. var dbContext = await _dbProvider.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
  444. await dbContext.TrickplayInfos.Where(i => i.ItemId.Equals(itemId)).ExecuteDeleteAsync(cancellationToken).ConfigureAwait(false);
  445. }
  446. /// <inheritdoc />
  447. public async Task<Dictionary<string, Dictionary<int, TrickplayInfo>>> GetTrickplayManifest(BaseItem item)
  448. {
  449. var trickplayManifest = new Dictionary<string, Dictionary<int, TrickplayInfo>>();
  450. foreach (var mediaSource in item.GetMediaSources(false))
  451. {
  452. if (mediaSource.IsRemote || !Guid.TryParse(mediaSource.Id, out var mediaSourceId))
  453. {
  454. continue;
  455. }
  456. var trickplayResolutions = await GetTrickplayResolutions(mediaSourceId).ConfigureAwait(false);
  457. if (trickplayResolutions.Count > 0)
  458. {
  459. trickplayManifest[mediaSource.Id] = trickplayResolutions;
  460. }
  461. }
  462. return trickplayManifest;
  463. }
  464. /// <inheritdoc />
  465. public async Task<string> GetTrickplayTilePathAsync(BaseItem item, int width, int index, bool saveWithMedia)
  466. {
  467. var trickplayResolutions = await GetTrickplayResolutions(item.Id).ConfigureAwait(false);
  468. if (trickplayResolutions is not null && trickplayResolutions.TryGetValue(width, out var trickplayInfo))
  469. {
  470. return Path.Combine(GetTrickplayDirectory(item, trickplayInfo.TileWidth, trickplayInfo.TileHeight, width, saveWithMedia), index + ".jpg");
  471. }
  472. return string.Empty;
  473. }
  474. /// <inheritdoc />
  475. public async Task<string?> GetHlsPlaylist(Guid itemId, int width, string? apiKey)
  476. {
  477. var trickplayResolutions = await GetTrickplayResolutions(itemId).ConfigureAwait(false);
  478. if (trickplayResolutions is not null && trickplayResolutions.TryGetValue(width, out var trickplayInfo))
  479. {
  480. var builder = new StringBuilder(128);
  481. if (trickplayInfo.ThumbnailCount > 0)
  482. {
  483. const string urlFormat = "{0}.jpg?MediaSourceId={1}&ApiKey={2}";
  484. const string decimalFormat = "{0:0.###}";
  485. var resolution = $"{trickplayInfo.Width}x{trickplayInfo.Height}";
  486. var layout = $"{trickplayInfo.TileWidth}x{trickplayInfo.TileHeight}";
  487. var thumbnailsPerTile = trickplayInfo.TileWidth * trickplayInfo.TileHeight;
  488. var thumbnailDuration = trickplayInfo.Interval / 1000d;
  489. var infDuration = thumbnailDuration * thumbnailsPerTile;
  490. var tileCount = (int)Math.Ceiling((decimal)trickplayInfo.ThumbnailCount / thumbnailsPerTile);
  491. builder
  492. .AppendLine("#EXTM3U")
  493. .Append("#EXT-X-TARGETDURATION:")
  494. .AppendLine(tileCount.ToString(CultureInfo.InvariantCulture))
  495. .AppendLine("#EXT-X-VERSION:7")
  496. .AppendLine("#EXT-X-MEDIA-SEQUENCE:1")
  497. .AppendLine("#EXT-X-PLAYLIST-TYPE:VOD")
  498. .AppendLine("#EXT-X-IMAGES-ONLY");
  499. for (int i = 0; i < tileCount; i++)
  500. {
  501. // All tiles prior to the last must contain full amount of thumbnails (no black).
  502. if (i == tileCount - 1)
  503. {
  504. thumbnailsPerTile = trickplayInfo.ThumbnailCount - (i * thumbnailsPerTile);
  505. infDuration = thumbnailDuration * thumbnailsPerTile;
  506. }
  507. // EXTINF
  508. builder
  509. .Append("#EXTINF:")
  510. .AppendFormat(CultureInfo.InvariantCulture, decimalFormat, infDuration)
  511. .AppendLine(",");
  512. // EXT-X-TILES
  513. builder
  514. .Append("#EXT-X-TILES:RESOLUTION=")
  515. .Append(resolution)
  516. .Append(",LAYOUT=")
  517. .Append(layout)
  518. .Append(",DURATION=")
  519. .AppendFormat(CultureInfo.InvariantCulture, decimalFormat, thumbnailDuration)
  520. .AppendLine();
  521. // URL
  522. builder
  523. .AppendFormat(
  524. CultureInfo.InvariantCulture,
  525. urlFormat,
  526. i.ToString(CultureInfo.InvariantCulture),
  527. itemId.ToString("N"),
  528. apiKey)
  529. .AppendLine();
  530. }
  531. builder.AppendLine("#EXT-X-ENDLIST");
  532. return builder.ToString();
  533. }
  534. }
  535. return null;
  536. }
  537. /// <inheritdoc />
  538. public string GetTrickplayDirectory(BaseItem item, int tileWidth, int tileHeight, int width, bool saveWithMedia = false)
  539. {
  540. var path = _pathManager.GetTrickplayDirectory(item, saveWithMedia);
  541. var subdirectory = string.Format(
  542. CultureInfo.InvariantCulture,
  543. "{0} - {1}x{2}",
  544. width.ToString(CultureInfo.InvariantCulture),
  545. tileWidth.ToString(CultureInfo.InvariantCulture),
  546. tileHeight.ToString(CultureInfo.InvariantCulture));
  547. return Path.Combine(path, subdirectory);
  548. }
  549. private async Task<bool> HasTrickplayResolutionAsync(Guid itemId, int width)
  550. {
  551. var dbContext = await _dbProvider.CreateDbContextAsync().ConfigureAwait(false);
  552. await using (dbContext.ConfigureAwait(false))
  553. {
  554. return await dbContext.TrickplayInfos
  555. .AsNoTracking()
  556. .Where(i => i.ItemId.Equals(itemId))
  557. .AnyAsync(i => i.Width == width)
  558. .ConfigureAwait(false);
  559. }
  560. }
  561. }