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