TrickplayManager.cs 25 KB

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