TrickplayManager.cs 25 KB

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