MigrateKeyframeData.cs 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Diagnostics.CodeAnalysis;
  5. using System.Globalization;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Text.Json;
  9. using Jellyfin.Data.Enums;
  10. using Jellyfin.Database.Implementations;
  11. using Jellyfin.Database.Implementations.Entities;
  12. using Jellyfin.Extensions.Json;
  13. using MediaBrowser.Common.Configuration;
  14. using MediaBrowser.Common.Extensions;
  15. using MediaBrowser.Controller.Entities;
  16. using MediaBrowser.Controller.Library;
  17. using Microsoft.EntityFrameworkCore;
  18. using Microsoft.Extensions.Logging;
  19. namespace Jellyfin.Server.Migrations.Routines;
  20. /// <summary>
  21. /// Migration to move extracted files to the new directories.
  22. /// </summary>
  23. public class MigrateKeyframeData : IDatabaseMigrationRoutine
  24. {
  25. private readonly ILibraryManager _libraryManager;
  26. private readonly ILogger<MoveTrickplayFiles> _logger;
  27. private readonly IApplicationPaths _appPaths;
  28. private readonly IDbContextFactory<JellyfinDbContext> _dbProvider;
  29. private static readonly JsonSerializerOptions _jsonOptions = JsonDefaults.Options;
  30. /// <summary>
  31. /// Initializes a new instance of the <see cref="MigrateKeyframeData"/> class.
  32. /// </summary>
  33. /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
  34. /// <param name="logger">The logger.</param>
  35. /// <param name="appPaths">Instance of the <see cref="IApplicationPaths"/> interface.</param>
  36. /// <param name="dbProvider">The EFCore db factory.</param>
  37. public MigrateKeyframeData(
  38. ILibraryManager libraryManager,
  39. ILogger<MoveTrickplayFiles> logger,
  40. IApplicationPaths appPaths,
  41. IDbContextFactory<JellyfinDbContext> dbProvider)
  42. {
  43. _libraryManager = libraryManager;
  44. _logger = logger;
  45. _appPaths = appPaths;
  46. _dbProvider = dbProvider;
  47. }
  48. private string KeyframeCachePath => Path.Combine(_appPaths.DataPath, "keyframes");
  49. /// <inheritdoc />
  50. public Guid Id => new("EA4bCAE1-09A4-428E-9B90-4B4FD2EA1B24");
  51. /// <inheritdoc />
  52. public string Name => "MigrateKeyframeData";
  53. /// <inheritdoc />
  54. public bool PerformOnNewInstall => false;
  55. /// <inheritdoc />
  56. public void Perform()
  57. {
  58. const int Limit = 100;
  59. int itemCount = 0, offset = 0, previousCount;
  60. var sw = Stopwatch.StartNew();
  61. var itemsQuery = new InternalItemsQuery
  62. {
  63. MediaTypes = [MediaType.Video],
  64. SourceTypes = [SourceType.Library],
  65. IsVirtualItem = false,
  66. IsFolder = false
  67. };
  68. using var context = _dbProvider.CreateDbContext();
  69. context.KeyframeData.ExecuteDelete();
  70. using var transaction = context.Database.BeginTransaction();
  71. List<KeyframeData> keyframes = [];
  72. do
  73. {
  74. var result = _libraryManager.GetItemsResult(itemsQuery);
  75. _logger.LogInformation("Importing keyframes for {Count} items", result.TotalRecordCount);
  76. var items = result.Items;
  77. previousCount = items.Count;
  78. offset += Limit;
  79. foreach (var item in items)
  80. {
  81. if (TryGetKeyframeData(item, out var data))
  82. {
  83. keyframes.Add(data);
  84. }
  85. if (++itemCount % 10_000 == 0)
  86. {
  87. context.KeyframeData.AddRange(keyframes);
  88. keyframes.Clear();
  89. _logger.LogInformation("Imported keyframes for {Count} items in {Time}", itemCount, sw.Elapsed);
  90. }
  91. }
  92. } while (previousCount == Limit);
  93. context.KeyframeData.AddRange(keyframes);
  94. context.SaveChanges();
  95. transaction.Commit();
  96. _logger.LogInformation("Imported keyframes for {Count} items in {Time}", itemCount, sw.Elapsed);
  97. if (Directory.Exists(KeyframeCachePath))
  98. {
  99. Directory.Delete(KeyframeCachePath, true);
  100. }
  101. }
  102. private bool TryGetKeyframeData(BaseItem item, [NotNullWhen(true)] out KeyframeData? data)
  103. {
  104. data = null;
  105. var path = item.Path;
  106. if (!string.IsNullOrEmpty(path))
  107. {
  108. var cachePath = GetCachePath(KeyframeCachePath, path);
  109. if (TryReadFromCache(cachePath, out var keyframeData))
  110. {
  111. data = new()
  112. {
  113. ItemId = item.Id,
  114. KeyframeTicks = keyframeData.KeyframeTicks.ToList(),
  115. TotalDuration = keyframeData.TotalDuration
  116. };
  117. return true;
  118. }
  119. }
  120. return false;
  121. }
  122. private string? GetCachePath(string keyframeCachePath, string filePath)
  123. {
  124. DateTime? lastWriteTimeUtc;
  125. try
  126. {
  127. lastWriteTimeUtc = File.GetLastWriteTimeUtc(filePath);
  128. }
  129. catch (IOException e)
  130. {
  131. _logger.LogDebug("Skipping {Path}: {Exception}", filePath, e.Message);
  132. return null;
  133. }
  134. ReadOnlySpan<char> filename = (filePath + "_" + lastWriteTimeUtc.Value.Ticks.ToString(CultureInfo.InvariantCulture)).GetMD5() + ".json";
  135. var prefix = filename[..1];
  136. return Path.Join(keyframeCachePath, prefix, filename);
  137. }
  138. private static bool TryReadFromCache(string? cachePath, [NotNullWhen(true)] out MediaEncoding.Keyframes.KeyframeData? cachedResult)
  139. {
  140. if (File.Exists(cachePath))
  141. {
  142. var bytes = File.ReadAllBytes(cachePath);
  143. cachedResult = JsonSerializer.Deserialize<MediaEncoding.Keyframes.KeyframeData>(bytes, _jsonOptions);
  144. return cachedResult is not null;
  145. }
  146. cachedResult = null;
  147. return false;
  148. }
  149. }