TrickplayManager.cs 25 KB

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