282 lines
9.5 KiB
C#
Raw Normal View History

2022-05-01 00:33:22 -05:00
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
2022-09-27 22:28:12 -05:00
using System.IO;
2022-05-01 00:33:22 -05:00
using System.Threading;
using System.Threading.Tasks;
2022-06-22 22:03:34 -05:00
using MediaBrowser.Controller.Library;
2022-05-01 00:33:22 -05:00
using MediaBrowser.Model.Tasks;
using Microsoft.Extensions.Logging;
namespace ConfusedPolarBear.Plugin.IntroSkipper;
/// <summary>
/// Analyze all television episodes for introduction sequences.
2022-05-01 00:33:22 -05:00
/// </summary>
2022-11-02 17:07:45 -05:00
public class DetectIntroductionsTask : IScheduledTask
{
2022-11-02 17:07:45 -05:00
private readonly ILogger<DetectIntroductionsTask> _logger;
2022-10-28 02:25:57 -05:00
private readonly ILoggerFactory _loggerFactory;
2022-06-22 22:03:34 -05:00
private readonly ILibraryManager? _libraryManager;
2022-05-01 00:33:22 -05:00
/// <summary>
2022-11-02 17:07:45 -05:00
/// Initializes a new instance of the <see cref="DetectIntroductionsTask"/> class.
2022-05-01 00:33:22 -05:00
/// </summary>
2022-06-22 22:03:34 -05:00
/// <param name="loggerFactory">Logger factory.</param>
/// <param name="libraryManager">Library manager.</param>
2022-11-02 17:07:45 -05:00
public DetectIntroductionsTask(
2022-09-25 17:07:11 -05:00
ILoggerFactory loggerFactory,
ILibraryManager libraryManager) : this(loggerFactory)
2022-05-01 00:33:22 -05:00
{
2022-06-22 22:03:34 -05:00
_libraryManager = libraryManager;
}
/// <summary>
2022-11-02 17:07:45 -05:00
/// Initializes a new instance of the <see cref="DetectIntroductionsTask"/> class.
2022-06-22 22:03:34 -05:00
/// </summary>
/// <param name="loggerFactory">Logger factory.</param>
2022-11-02 17:07:45 -05:00
public DetectIntroductionsTask(ILoggerFactory loggerFactory)
2022-06-22 22:03:34 -05:00
{
2022-11-02 17:07:45 -05:00
_logger = loggerFactory.CreateLogger<DetectIntroductionsTask>();
2022-10-28 02:25:57 -05:00
_loggerFactory = loggerFactory;
2022-06-22 22:03:34 -05:00
EdlManager.Initialize(_logger);
2022-05-01 00:33:22 -05:00
}
/// <summary>
/// Gets the task name.
2022-05-01 00:33:22 -05:00
/// </summary>
2022-08-25 01:00:02 -05:00
public string Name => "Detect Introductions";
2022-05-01 00:33:22 -05:00
/// <summary>
/// Gets the task category.
2022-05-01 00:33:22 -05:00
/// </summary>
public string Category => "Intro Skipper";
/// <summary>
/// Gets the task description.
2022-05-01 00:33:22 -05:00
/// </summary>
public string Description => "Analyzes the audio of all television episodes to find introduction sequences.";
/// <summary>
/// Gets the task key.
2022-05-01 00:33:22 -05:00
/// </summary>
2022-08-25 01:00:02 -05:00
public string Key => "CPBIntroSkipperDetectIntroductions";
2022-05-01 00:33:22 -05:00
/// <summary>
2022-06-22 22:03:34 -05:00
/// Analyze all episodes in the queue. Only one instance of this task should be run at a time.
2022-05-01 00:33:22 -05:00
/// </summary>
/// <param name="progress">Task progress.</param>
2022-05-01 00:33:22 -05:00
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>Task.</returns>
2022-05-01 00:33:22 -05:00
public Task ExecuteAsync(IProgress<double> progress, CancellationToken cancellationToken)
{
2022-06-22 22:03:34 -05:00
if (_libraryManager is null)
{
throw new InvalidOperationException("Library manager must not be null");
}
// Make sure the analysis queue matches what's currently in Jellyfin.
2022-10-28 02:25:57 -05:00
var queueManager = new QueueManager(
_loggerFactory.CreateLogger<QueueManager>(),
_libraryManager);
var queue = queueManager.EnqueueAllEpisodes();
if (queue.Count == 0)
{
throw new FingerprintException(
"No episodes to analyze. If you are limiting the list of libraries to analyze, check that all library names have been spelled correctly.");
}
2022-06-24 00:02:08 -05:00
// Log EDL settings
EdlManager.LogConfiguration();
2022-09-02 23:42:32 -05:00
var totalProcessed = 0;
var options = new ParallelOptions()
{
MaxDegreeOfParallelism = Plugin.Instance!.Configuration.MaxParallelism
};
2022-05-17 02:06:34 -05:00
2022-07-25 22:03:06 -05:00
// TODO: if the queue is modified while the task is running, the task will fail.
// clone the queue before running the task to prevent this.
2022-06-24 00:02:08 -05:00
// Analyze all episodes in the queue using the degrees of parallelism the user specified.
2022-05-17 02:06:34 -05:00
Parallel.ForEach(queue, options, (season) =>
{
var (episodes, unanalyzed) = VerifyEpisodes(season.Value.AsReadOnly());
2022-09-27 22:28:12 -05:00
if (episodes.Count == 0)
{
return;
}
2022-09-25 17:07:11 -05:00
var first = episodes[0];
var writeEdl = false;
if (!unanalyzed)
{
_logger.LogDebug(
"All episodes in {Name} season {Season} have already been analyzed",
first.SeriesName,
first.SeasonNumber);
return;
}
try
{
2022-09-02 23:42:32 -05:00
if (cancellationToken.IsCancellationRequested)
{
return;
}
// Increment totalProcessed by the number of episodes in this season that were actually analyzed
// (instead of just using the number of episodes in the current season).
var analyzed = AnalyzeSeason(episodes, cancellationToken);
Interlocked.Add(ref totalProcessed, analyzed);
2022-06-24 00:02:08 -05:00
writeEdl = analyzed > 0 || Plugin.Instance!.Configuration.RegenerateEdlFiles;
}
catch (FingerprintException ex)
{
_logger.LogWarning(
"Unable to analyze {Series} season {Season}: unable to fingerprint: {Ex}",
first.SeriesName,
first.SeasonNumber,
ex);
}
catch (KeyNotFoundException ex)
{
_logger.LogWarning(
"Unable to analyze {Series} season {Season}: cache miss: {Ex}",
first.SeriesName,
first.SeasonNumber,
ex);
}
if (writeEdl && Plugin.Instance!.Configuration.EdlAction != EdlAction.None)
{
2022-09-25 17:07:11 -05:00
EdlManager.UpdateEDLFiles(episodes);
}
var total = Plugin.Instance!.TotalQueued;
if (total > 0)
{
progress.Report((totalProcessed * 100) / total);
}
2022-05-16 17:06:46 -05:00
});
2022-05-13 01:28:06 -05:00
2022-06-24 00:02:08 -05:00
// Turn the regenerate EDL flag off after the scan completes.
if (Plugin.Instance!.Configuration.RegenerateEdlFiles)
{
_logger.LogInformation("Turning EDL file regeneration flag off");
Plugin.Instance!.Configuration.RegenerateEdlFiles = false;
Plugin.Instance!.SaveConfiguration();
}
2022-05-13 01:28:06 -05:00
return Task.CompletedTask;
}
2022-09-27 22:28:12 -05:00
/// <summary>
/// Verify that all episodes in a season exist in Jellyfin and as a file in storage.
2022-10-31 01:00:39 -05:00
/// TODO: FIXME: move to queue manager.
2022-09-27 22:28:12 -05:00
/// </summary>
/// <param name="candidates">QueuedEpisodes.</param>
/// <returns>Verified QueuedEpisodes and a flag indicating if any episode in this season has not been analyzed yet.</returns>
private (
ReadOnlyCollection<QueuedEpisode> VerifiedEpisodes,
bool AnyUnanalyzed)
VerifyEpisodes(ReadOnlyCollection<QueuedEpisode> candidates)
2022-09-27 22:28:12 -05:00
{
var unanalyzed = false;
2022-09-27 22:28:12 -05:00
var verified = new List<QueuedEpisode>();
foreach (var candidate in candidates)
{
try
{
// Verify that the episode exists in Jellyfin and in storage
2022-09-27 22:28:12 -05:00
var path = Plugin.Instance!.GetItemPath(candidate.EpisodeId);
if (File.Exists(path))
{
verified.Add(candidate);
}
// Flag this season for analysis if the current episode hasn't been analyzed yet
if (!Plugin.Instance.Intros.ContainsKey(candidate.EpisodeId))
{
unanalyzed = true;
}
2022-09-27 22:28:12 -05:00
}
catch (Exception ex)
{
_logger.LogDebug(
"Skipping analysis of {Name} ({Id}): {Exception}",
candidate.Name,
candidate.EpisodeId,
ex);
}
}
return (verified.AsReadOnly(), unanalyzed);
2022-09-27 22:28:12 -05:00
}
/// <summary>
/// Fingerprints all episodes in the provided season and stores the timestamps of all introductions.
/// </summary>
2022-08-25 22:11:39 -05:00
/// <param name="episodes">Episodes in this season.</param>
/// <param name="cancellationToken">Cancellation token provided by the scheduled task.</param>
/// <returns>Number of episodes from the provided season that were analyzed.</returns>
private int AnalyzeSeason(
2022-08-30 02:18:05 -05:00
ReadOnlyCollection<QueuedEpisode> episodes,
2022-05-13 01:28:06 -05:00
CancellationToken cancellationToken)
{
// Skip seasons with an insufficient number of episodes.
if (episodes.Count <= 1)
2022-05-13 01:28:06 -05:00
{
2022-08-30 02:18:05 -05:00
return episodes.Count;
2022-05-13 01:28:06 -05:00
}
// Only analyze specials (season 0) if the user has opted in.
2022-08-25 22:11:39 -05:00
var first = episodes[0];
if (first.SeasonNumber == 0 && !Plugin.Instance!.Configuration.AnalyzeSeasonZero)
{
return 0;
}
2022-08-25 22:11:39 -05:00
2022-08-25 01:37:57 -05:00
_logger.LogInformation(
"Analyzing {Count} episodes from {Name} season {Season}",
2022-08-25 22:11:39 -05:00
episodes.Count,
2022-08-25 01:37:57 -05:00
first.SeriesName,
first.SeasonNumber);
2022-05-13 01:28:06 -05:00
// Chapter analyzer
var chapter = new ChapterAnalyzer(_loggerFactory.CreateLogger<ChapterAnalyzer>());
episodes = chapter.AnalyzeMediaFiles(episodes, AnalysisMode.Introduction, cancellationToken);
2022-10-28 02:25:57 -05:00
// Analyze the season with Chromaprint
var chromaprint = new ChromaprintAnalyzer(_loggerFactory.CreateLogger<ChromaprintAnalyzer>());
chromaprint.AnalyzeMediaFiles(episodes, AnalysisMode.Introduction, cancellationToken);
2022-08-30 02:18:05 -05:00
return episodes.Count;
2022-05-01 00:33:22 -05:00
}
/// <summary>
/// Get task triggers.
/// </summary>
/// <returns>Task triggers.</returns>
2022-05-01 00:33:22 -05:00
public IEnumerable<TaskTriggerInfo> GetDefaultTriggers()
{
return new[]
{
new TaskTriggerInfo
{
Type = TaskTriggerInfo.TriggerDaily,
TimeOfDayTicks = TimeSpan.FromHours(0).Ticks
2022-05-01 00:33:22 -05:00
}
};
}
}