260 lines
9.8 KiB
C#
Raw Normal View History

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
2024-08-31 18:56:48 +02:00
using ConfusedPolarBear.Plugin.IntroSkipper.Analyzers;
using ConfusedPolarBear.Plugin.IntroSkipper.Data;
2024-10-16 16:20:21 +02:00
using ConfusedPolarBear.Plugin.IntroSkipper.Manager;
using MediaBrowser.Controller.Library;
using Microsoft.Extensions.Logging;
2024-08-31 18:56:48 +02:00
namespace ConfusedPolarBear.Plugin.IntroSkipper.ScheduledTasks;
2024-04-20 12:58:29 +02:00
/// <summary>
/// Common code shared by all media item analyzer tasks.
/// </summary>
public class BaseItemAnalyzerTask
{
private readonly IReadOnlyCollection<AnalysisMode> _analysisModes;
private readonly ILogger _logger;
private readonly ILoggerFactory _loggerFactory;
private readonly ILibraryManager _libraryManager;
private readonly MediaSegmentUpdateManager _mediaSegmentUpdateManager;
/// <summary>
/// Initializes a new instance of the <see cref="BaseItemAnalyzerTask"/> class.
/// </summary>
/// <param name="modes">Analysis mode.</param>
/// <param name="logger">Task logger.</param>
/// <param name="loggerFactory">Logger factory.</param>
/// <param name="libraryManager">Library manager.</param>
/// <param name="mediaSegmentUpdateManager">MediaSegmentUpdateManager.</param>
public BaseItemAnalyzerTask(
IReadOnlyCollection<AnalysisMode> modes,
ILogger logger,
ILoggerFactory loggerFactory,
ILibraryManager libraryManager,
MediaSegmentUpdateManager mediaSegmentUpdateManager)
{
_analysisModes = modes;
_logger = logger;
_loggerFactory = loggerFactory;
_libraryManager = libraryManager;
_mediaSegmentUpdateManager = mediaSegmentUpdateManager;
if (Plugin.Instance!.Configuration.EdlAction != EdlAction.None)
{
EdlManager.Initialize(_logger);
}
}
/// <summary>
/// Analyze all media items on the server.
/// </summary>
/// <param name="progress">Progress.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <param name="seasonsToAnalyze">Season Ids to analyze.</param>
/// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
public async Task AnalyzeItems(
IProgress<double> progress,
CancellationToken cancellationToken,
2024-09-25 17:23:25 +02:00
IReadOnlyCollection<Guid>? seasonsToAnalyze = null)
{
2024-03-19 20:58:48 -04:00
var ffmpegValid = FFmpegWrapper.CheckFFmpegVersion();
2024-03-04 08:58:15 -05:00
// Assert that ffmpeg with chromaprint is installed
if (Plugin.Instance!.Configuration.WithChromaprint && !ffmpegValid)
2024-03-04 08:58:15 -05:00
{
throw new FingerprintException(
2024-03-05 17:27:39 -05:00
"Analysis terminated! Chromaprint is not enabled in the current ffmpeg. If Jellyfin is running natively, install jellyfin-ffmpeg5. If Jellyfin is running in a container, upgrade to version 10.8.0 or newer.");
2024-03-04 08:58:15 -05:00
}
var queueManager = new QueueManager(
_loggerFactory.CreateLogger<QueueManager>(),
_libraryManager);
var queue = queueManager.GetMediaItems();
// Filter the queue based on seasonsToAnalyze
2024-09-25 17:23:25 +02:00
if (seasonsToAnalyze is { Count: > 0 })
{
2024-09-25 17:23:25 +02:00
queue = queue.Where(kvp => seasonsToAnalyze.Contains(kvp.Key)).ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
}
int totalQueued = queue.Sum(kvp => kvp.Value.Count) * _analysisModes.Count;
if (totalQueued == 0)
{
throw new FingerprintException(
"No libraries selected for analysis. Please visit the plugin settings to configure.");
}
if (Plugin.Instance!.Configuration.EdlAction != EdlAction.None)
{
EdlManager.LogConfiguration();
}
var totalProcessed = 0;
2024-04-20 12:58:29 +02:00
var options = new ParallelOptions
{
MaxDegreeOfParallelism = Plugin.Instance.Configuration.MaxParallelism,
CancellationToken = cancellationToken
};
await Parallel.ForEachAsync(queue, options, async (season, ct) =>
{
var updateManagers = false;
// Since the first run of the task can run for multiple hours, ensure that none
// of the current media items were deleted from Jellyfin since the task was started.
var (episodes, requiredModes) = queueManager.VerifyQueue(
season.Value,
_analysisModes.Where(m => !Plugin.Instance!.IsIgnored(season.Key, m)).ToList());
2024-09-25 17:23:25 +02:00
if (episodes.Count == 0)
{
return;
}
var first = episodes[0];
2024-09-25 17:23:25 +02:00
if (requiredModes.Count == 0)
{
_logger.LogDebug(
"All episodes in {Name} season {Season} have already been analyzed",
first.SeriesName,
first.SeasonNumber);
Interlocked.Add(ref totalProcessed, episodes.Count * _analysisModes.Count); // Update total Processed directly
progress.Report(totalProcessed * 100 / totalQueued);
}
else if (_analysisModes.Count != requiredModes.Count)
{
2024-09-25 17:23:25 +02:00
Interlocked.Add(ref totalProcessed, episodes.Count);
progress.Report(totalProcessed * 100 / totalQueued); // Partial analysis some modes have already been analyzed
}
try
{
2024-10-20 10:26:38 +02:00
ct.ThrowIfCancellationRequested();
foreach (AnalysisMode mode in requiredModes)
{
var analyzed = AnalyzeItems(episodes, mode, ct);
Interlocked.Add(ref totalProcessed, analyzed);
updateManagers = analyzed > 0 || updateManagers;
progress.Report(totalProcessed * 100 / totalQueued);
}
}
2024-10-20 10:26:38 +02:00
catch (OperationCanceledException ex)
{
_logger.LogDebug(ex, "Analysis cancelled");
}
catch (FingerprintException ex)
{
_logger.LogWarning(
"Unable to analyze {Series} season {Season}: unable to fingerprint: {Ex}",
first.SeriesName,
first.SeasonNumber,
ex);
}
2024-10-20 10:26:38 +02:00
catch (Exception ex)
{
_logger.LogError(ex, "An unexpected error occurred during analysis");
throw;
}
if (Plugin.Instance.Configuration.RegenerateMediaSegments || (updateManagers && Plugin.Instance.Configuration.UpdateMediaSegments))
{
await _mediaSegmentUpdateManager.UpdateMediaSegmentsAsync(episodes, ct).ConfigureAwait(false);
}
if (Plugin.Instance.Configuration.RegenerateEdlFiles || (updateManagers && Plugin.Instance.Configuration.EdlAction != EdlAction.None))
{
EdlManager.UpdateEDLFiles(episodes);
}
}).ConfigureAwait(false);
if (Plugin.Instance.Configuration.RegenerateMediaSegments || Plugin.Instance.Configuration.RegenerateEdlFiles)
{
_logger.LogInformation("Turning Mediasegment/EDL file regeneration flag off");
Plugin.Instance.Configuration.RegenerateMediaSegments = false;
2024-04-20 12:21:07 +02:00
Plugin.Instance.Configuration.RegenerateEdlFiles = false;
Plugin.Instance.SaveConfiguration();
}
}
/// <summary>
/// Analyze a group of media items for skippable segments.
/// </summary>
/// <param name="items">Media items to analyze.</param>
/// <param name="mode">Analysis mode.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>Number of items that were successfully analyzed.</returns>
private int AnalyzeItems(
IReadOnlyList<QueuedEpisode> items,
AnalysisMode mode,
CancellationToken cancellationToken)
{
var totalItems = items.Count(e => !e.State.IsAnalyzed(mode));
// Only analyze specials (season 0) if the user has opted in.
var first = items[0];
if (!first.IsMovie && first.SeasonNumber == 0 && !Plugin.Instance!.Configuration.AnalyzeSeasonZero)
{
return 0;
}
// Remove from Blacklist
foreach (var item in items.Where(e => e.State.IsBlacklisted(mode)))
{
item.State.SetBlacklisted(mode, false);
}
_logger.LogInformation(
"[Mode: {Mode}] Analyzing {Count} files from {Name} season {Season}",
mode,
items.Count,
first.SeriesName,
first.SeasonNumber);
var analyzers = new Collection<IMediaFileAnalyzer>
{
new ChapterAnalyzer(_loggerFactory.CreateLogger<ChapterAnalyzer>())
};
if (first.IsAnime && Plugin.Instance!.Configuration.WithChromaprint && !first.IsMovie)
2024-09-25 17:23:25 +02:00
{
analyzers.Add(new ChromaprintAnalyzer(_loggerFactory.CreateLogger<ChromaprintAnalyzer>()));
}
2024-09-25 17:23:25 +02:00
if (mode == AnalysisMode.Credits)
{
2024-09-25 17:23:25 +02:00
analyzers.Add(new BlackFrameAnalyzer(_loggerFactory.CreateLogger<BlackFrameAnalyzer>()));
}
if (!first.IsAnime && Plugin.Instance!.Configuration.WithChromaprint && !first.IsMovie)
2024-09-25 17:23:25 +02:00
{
analyzers.Add(new ChromaprintAnalyzer(_loggerFactory.CreateLogger<ChromaprintAnalyzer>()));
}
// Use each analyzer to find skippable ranges in all media files, removing successfully
// analyzed items from the queue.
foreach (var analyzer in analyzers)
{
items = analyzer.AnalyzeMediaFiles(items, mode, cancellationToken);
2024-10-20 10:26:38 +02:00
cancellationToken.ThrowIfCancellationRequested();
}
// Add items without intros/credits to blacklist.
foreach (var item in items.Where(e => !e.State.IsAnalyzed(mode)))
{
item.State.SetBlacklisted(mode, true);
totalItems -= 1;
}
2023-02-02 03:52:31 -06:00
return totalItems;
}
}