< Summary - Jellyfin

Information
Class: Jellyfin.Server.Migrations.Routines.MigrateKeyframeData
Assembly: jellyfin
File(s): /srv/git/jellyfin/Jellyfin.Server/Migrations/Routines/20250421000000_MigrateKeyframeData.cs
Line coverage
0%
Covered lines: 0
Uncovered lines: 69
Coverable lines: 69
Total lines: 178
Line coverage: 0%
Branch coverage
0%
Covered branches: 0
Total branches: 16
Branch coverage: 0%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Coverage history

Coverage history 0 25 50 75 100 5/31/2026 - 12:15:44 AM Line coverage: 0% (0/67) Branch coverage: 0% (0/16) Total lines: 16911/13/2026 - 12:19:51 AM Line coverage: 0% (0/69) Branch coverage: 0% (0/16) Total lines: 178 5/31/2026 - 12:15:44 AM Line coverage: 0% (0/67) Branch coverage: 0% (0/16) Total lines: 16911/13/2026 - 12:19:51 AM Line coverage: 0% (0/69) Branch coverage: 0% (0/16) Total lines: 178

Coverage delta

Coverage delta 1 -1

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.cctor()100%210%
.ctor(...)100%210%
get_KeyframeCachePath()100%210%
PerformAsync(...)100%210%
PerformCore()0%110100%
TryGetKeyframeData(...)0%2040%
GetCachePath(...)100%210%
TryReadFromCache(...)0%620%

File(s)

/srv/git/jellyfin/Jellyfin.Server/Migrations/Routines/20250421000000_MigrateKeyframeData.cs

#LineLine coverage
 1using System;
 2using System.Diagnostics;
 3using System.Diagnostics.CodeAnalysis;
 4using System.Globalization;
 5using System.IO;
 6using System.Linq;
 7using System.Text.Json;
 8using System.Threading;
 9using System.Threading.Tasks;
 10using Jellyfin.Data.Enums;
 11using Jellyfin.Database.Implementations;
 12using Jellyfin.Database.Implementations.Entities;
 13using Jellyfin.Extensions.Json;
 14using Jellyfin.Server.ServerSetupApp;
 15using MediaBrowser.Common.Configuration;
 16using MediaBrowser.Common.Extensions;
 17using Microsoft.EntityFrameworkCore;
 18using Microsoft.Extensions.Logging;
 19
 20namespace Jellyfin.Server.Migrations.Routines;
 21
 22/// <summary>
 23/// Migration to move extracted files to the new directories.
 24/// </summary>
 25[JellyfinMigration("2025-04-21T00:00:00", nameof(MigrateKeyframeData))]
 26public class MigrateKeyframeData : IDatabaseMigrationRoutine
 27{
 28    private readonly IStartupLogger _logger;
 29    private readonly IApplicationPaths _appPaths;
 30    private readonly IDbContextFactory<JellyfinDbContext> _dbProvider;
 031    private static readonly JsonSerializerOptions _jsonOptions = JsonDefaults.Options;
 32
 33    /// <summary>
 34    /// Initializes a new instance of the <see cref="MigrateKeyframeData"/> class.
 35    /// </summary>
 36    /// <param name="startupLogger">The startup logger for Startup UI intigration.</param>
 37    /// <param name="appPaths">Instance of the <see cref="IApplicationPaths"/> interface.</param>
 38    /// <param name="dbProvider">The EFCore db factory.</param>
 39    public MigrateKeyframeData(
 40        IStartupLogger<MigrateKeyframeData> startupLogger,
 41        IApplicationPaths appPaths,
 42        IDbContextFactory<JellyfinDbContext> dbProvider)
 43    {
 044        _logger = startupLogger;
 045        _appPaths = appPaths;
 046        _dbProvider = dbProvider;
 047    }
 48
 049    private string KeyframeCachePath => Path.Combine(_appPaths.DataPath, "keyframes");
 50
 51    /// <inheritdoc />
 52    public Task PerformAsync(CancellationToken cancellationToken)
 53    {
 54        // This routine predates the async interface and has not been ported to async database access yet.
 055        PerformCore();
 056        return Task.CompletedTask;
 57    }
 58
 59    private void PerformCore()
 60    {
 61        const int Limit = 5000;
 062        int itemCount = 0, offset = 0;
 63
 064        var sw = Stopwatch.StartNew();
 65
 066        using var context = _dbProvider.CreateDbContext();
 067        var baseQuery = context.BaseItems.Where(b => b.MediaType == MediaType.Video.ToString() && !b.IsVirtualItem && !b
 068        var records = baseQuery.Count();
 069        _logger.LogInformation("Checking {Count} items for importable keyframe data.", records);
 70
 071        context.KeyframeData.ExecuteDelete();
 072        using var transaction = context.Database.BeginTransaction();
 73        do
 74        {
 075            var results = baseQuery.Skip(offset).Take(Limit).Select(b => new Tuple<Guid, string?>(b.Id, b.Path)).ToList(
 076            foreach (var result in results)
 77            {
 078                if (TryGetKeyframeData(result.Item1, result.Item2, out var data))
 79                {
 080                    itemCount++;
 081                    context.KeyframeData.Add(data);
 82                }
 83            }
 84
 085            offset += Limit;
 086            if (offset > records)
 87            {
 088                offset = records;
 89            }
 90
 091            _logger.LogInformation("Checked: {Count} - Imported: {Items} - Time: {Time}", offset, itemCount, sw.Elapsed)
 092        } while (offset < records);
 93
 094        context.SaveChanges();
 095        transaction.Commit();
 96
 097        _logger.LogInformation("Imported keyframes for {Count} items in {Time}", itemCount, sw.Elapsed);
 98
 099        if (Directory.Exists(KeyframeCachePath))
 100        {
 0101            Directory.Delete(KeyframeCachePath, true);
 102        }
 0103    }
 104
 105    private bool TryGetKeyframeData(Guid id, string? path, [NotNullWhen(true)] out KeyframeData? data)
 106    {
 0107        data = null;
 0108        if (!string.IsNullOrEmpty(path))
 109        {
 0110            var cachePath = GetCachePath(KeyframeCachePath, path);
 0111            if (TryReadFromCache(cachePath, out var keyframeData))
 112            {
 0113                data = new()
 0114                {
 0115                    ItemId = id,
 0116                    KeyframeTicks = keyframeData.KeyframeTicks.ToList(),
 0117                    TotalDuration = keyframeData.TotalDuration
 0118                };
 119
 0120                return true;
 121            }
 122        }
 123
 0124        return false;
 125    }
 126
 127    private string? GetCachePath(string keyframeCachePath, string filePath)
 128    {
 129        DateTime? lastWriteTimeUtc;
 130        try
 131        {
 0132            lastWriteTimeUtc = File.GetLastWriteTimeUtc(filePath);
 0133        }
 0134        catch (ArgumentOutOfRangeException e)
 135        {
 0136            _logger.LogDebug("Skipping {Path}: {Exception}", filePath, e.Message);
 0137            return null;
 138        }
 0139        catch (UnauthorizedAccessException e)
 140        {
 0141            _logger.LogDebug("Skipping {Path}: {Exception}", filePath, e.Message);
 0142            return null;
 143        }
 0144        catch (IOException e)
 145        {
 0146            _logger.LogDebug("Skipping {Path}: {Exception}", filePath, e.Message);
 147
 0148            return null;
 149        }
 150
 0151        ReadOnlySpan<char> filename = (filePath + "_" + lastWriteTimeUtc.Value.Ticks.ToString(CultureInfo.InvariantCultu
 0152        var prefix = filename[..1];
 153
 0154        return Path.Join(keyframeCachePath, prefix, filename);
 0155    }
 156
 157    private bool TryReadFromCache(string? cachePath, [NotNullWhen(true)] out MediaEncoding.Keyframes.KeyframeData? cache
 158    {
 0159        if (File.Exists(cachePath))
 160        {
 161            try
 162            {
 0163                var bytes = File.ReadAllBytes(cachePath);
 0164                cachedResult = JsonSerializer.Deserialize<MediaEncoding.Keyframes.KeyframeData>(bytes, _jsonOptions);
 165
 0166                return cachedResult is not null;
 167            }
 0168            catch (JsonException jsonException)
 169            {
 0170                _logger.LogWarning(jsonException, "Failed to read {Path}", cachePath);
 0171            }
 172        }
 173
 0174        cachedResult = null;
 175
 0176        return false;
 0177    }
 178}