Revert "Use Jellyfins MediaSegmentType (#344)"

This reverts commit 29ee3e0bc861d128f4f691d7eb8d159da28eab43.
This commit is contained in:
rlauu 2024-10-16 16:05:59 +02:00
parent 29ee3e0bc8
commit ca9a167ad5
31 changed files with 1079 additions and 1050 deletions

View File

@ -6,7 +6,6 @@ using System;
using System.Collections.Generic;
using ConfusedPolarBear.Plugin.IntroSkipper.Analyzers;
using ConfusedPolarBear.Plugin.IntroSkipper.Data;
using Jellyfin.Data.Enums;
using Microsoft.Extensions.Logging;
using Xunit;
@ -64,7 +63,7 @@ public class TestAudioFingerprinting
var actual = FFmpegWrapper.Fingerprint(
QueueEpisode("audio/big_buck_bunny_intro.mp3"),
MediaSegmentType.Intro);
AnalysisMode.Introduction);
Assert.Equal(expected, actual);
}
@ -84,7 +83,7 @@ public class TestAudioFingerprinting
{77, 5},
};
var actual = FFmpegWrapper.CreateInvertedIndex(Guid.NewGuid(), fpr, MediaSegmentType.Intro);
var actual = FFmpegWrapper.CreateInvertedIndex(Guid.NewGuid(), fpr, AnalysisMode.Introduction);
Assert.Equal(expected, actual);
}
@ -96,8 +95,8 @@ public class TestAudioFingerprinting
var lhsEpisode = QueueEpisode("audio/big_buck_bunny_intro.mp3");
var rhsEpisode = QueueEpisode("audio/big_buck_bunny_clip.mp3");
var lhsFingerprint = FFmpegWrapper.Fingerprint(lhsEpisode, MediaSegmentType.Intro);
var rhsFingerprint = FFmpegWrapper.Fingerprint(rhsEpisode, MediaSegmentType.Intro);
var lhsFingerprint = FFmpegWrapper.Fingerprint(lhsEpisode, AnalysisMode.Introduction);
var rhsFingerprint = FFmpegWrapper.Fingerprint(rhsEpisode, AnalysisMode.Introduction);
var (lhs, rhs) = chromaprint.CompareEpisodes(
lhsEpisode.EpisodeId,

View File

@ -5,7 +5,6 @@ using System.Collections.Generic;
using System.Collections.ObjectModel;
using ConfusedPolarBear.Plugin.IntroSkipper.Analyzers;
using ConfusedPolarBear.Plugin.IntroSkipper.Data;
using Jellyfin.Data.Enums;
using MediaBrowser.Model.Entities;
using Microsoft.Extensions.Logging;
using Xunit;
@ -20,8 +19,8 @@ public class TestChapterAnalyzer
[InlineData("Introduction")]
public void TestIntroductionExpression(string chapterName)
{
var chapters = CreateChapters(chapterName, MediaSegmentType.Intro);
var introChapter = FindChapter(chapters, MediaSegmentType.Intro);
var chapters = CreateChapters(chapterName, AnalysisMode.Introduction);
var introChapter = FindChapter(chapters, AnalysisMode.Introduction);
Assert.NotNull(introChapter);
Assert.Equal(60, introChapter.Start);
@ -36,34 +35,34 @@ public class TestChapterAnalyzer
[InlineData("Credits")]
public void TestEndCreditsExpression(string chapterName)
{
var chapters = CreateChapters(chapterName, MediaSegmentType.Outro);
var creditsChapter = FindChapter(chapters, MediaSegmentType.Outro);
var chapters = CreateChapters(chapterName, AnalysisMode.Credits);
var creditsChapter = FindChapter(chapters, AnalysisMode.Credits);
Assert.NotNull(creditsChapter);
Assert.Equal(1890, creditsChapter.Start);
Assert.Equal(2000, creditsChapter.End);
}
private Segment? FindChapter(Collection<ChapterInfo> chapters, MediaSegmentType mode)
private Segment? FindChapter(Collection<ChapterInfo> chapters, AnalysisMode mode)
{
var logger = new LoggerFactory().CreateLogger<ChapterAnalyzer>();
var analyzer = new ChapterAnalyzer(logger);
var config = new Configuration.PluginConfiguration();
var expression = mode == MediaSegmentType.Intro ?
var expression = mode == AnalysisMode.Introduction ?
config.ChapterAnalyzerIntroductionPattern :
config.ChapterAnalyzerEndCreditsPattern;
return analyzer.FindMatchingChapter(new() { Duration = 2000 }, chapters, expression, mode);
}
private Collection<ChapterInfo> CreateChapters(string name, MediaSegmentType mode)
private Collection<ChapterInfo> CreateChapters(string name, AnalysisMode mode)
{
var chapters = new[]{
CreateChapter("Cold Open", 0),
CreateChapter(mode == MediaSegmentType.Intro ? name : "Introduction", 60),
CreateChapter(mode == AnalysisMode.Introduction ? name : "Introduction", 60),
CreateChapter("Main Episode", 90),
CreateChapter(mode == MediaSegmentType.Outro ? name : "Credits", 1890)
CreateChapter(mode == AnalysisMode.Credits ? name : "Credits", 1890)
};
return new(new List<ChapterInfo>(chapters));

View File

@ -1,6 +1,5 @@
using System;
using ConfusedPolarBear.Plugin.IntroSkipper.Data;
using ConfusedPolarBear.Plugin.IntroSkipper.Manager;
using Xunit;
namespace ConfusedPolarBear.Plugin.IntroSkipper.Tests;

View File

@ -3,11 +3,10 @@ using System.Collections.Generic;
using System.Linq;
using ConfusedPolarBear.Plugin.IntroSkipper.Configuration;
using ConfusedPolarBear.Plugin.IntroSkipper.Data;
using Jellyfin.Data.Enums;
using Microsoft.Extensions.Logging;
namespace ConfusedPolarBear.Plugin.IntroSkipper.Analyzers
{
namespace ConfusedPolarBear.Plugin.IntroSkipper;
/// <summary>
/// Analyzer Helper.
/// </summary>
@ -37,7 +36,7 @@ namespace ConfusedPolarBear.Plugin.IntroSkipper.Analyzers
public Dictionary<Guid, Segment> AdjustIntroTimes(
IReadOnlyList<QueuedEpisode> episodes,
IReadOnlyDictionary<Guid, Segment> originalIntros,
MediaSegmentType mode)
AnalysisMode mode)
{
return episodes
.Where(episode => originalIntros.TryGetValue(episode.EpisodeId, out var _))
@ -46,7 +45,7 @@ namespace ConfusedPolarBear.Plugin.IntroSkipper.Analyzers
episode => AdjustIntroForEpisode(episode, originalIntros[episode.EpisodeId], mode));
}
private Segment AdjustIntroForEpisode(QueuedEpisode episode, Segment originalIntro, MediaSegmentType mode)
private Segment AdjustIntroForEpisode(QueuedEpisode episode, Segment originalIntro, AnalysisMode mode)
{
_logger.LogTrace("{Name} original intro: {Start} - {End}", episode.Name, originalIntro.Start, originalIntro.End);
@ -54,7 +53,7 @@ namespace ConfusedPolarBear.Plugin.IntroSkipper.Analyzers
var originalIntroStart = new TimeRange(Math.Max(0, (int)originalIntro.Start - 5), (int)originalIntro.Start + 10);
var originalIntroEnd = new TimeRange((int)originalIntro.End - 10, Math.Min(episode.Duration, (int)originalIntro.End + 5));
if (!AdjustIntroBasedOnChapters(episode, adjustedIntro, originalIntroStart, originalIntroEnd) && mode == MediaSegmentType.Intro)
if (!AdjustIntroBasedOnChapters(episode, adjustedIntro, originalIntroStart, originalIntroEnd) && mode == AnalysisMode.Introduction)
{
AdjustIntroBasedOnSilence(episode, adjustedIntro, originalIntroEnd);
}
@ -115,4 +114,3 @@ namespace ConfusedPolarBear.Plugin.IntroSkipper.Analyzers
silenceRange.Start >= adjustedIntro.Start;
}
}
}

View File

@ -4,7 +4,6 @@ using System.Linq;
using System.Threading;
using ConfusedPolarBear.Plugin.IntroSkipper.Configuration;
using ConfusedPolarBear.Plugin.IntroSkipper.Data;
using Jellyfin.Data.Enums;
using Microsoft.Extensions.Logging;
namespace ConfusedPolarBear.Plugin.IntroSkipper.Analyzers;
@ -42,10 +41,10 @@ public class BlackFrameAnalyzer : IMediaFileAnalyzer
/// <inheritdoc />
public IReadOnlyList<QueuedEpisode> AnalyzeMediaFiles(
IReadOnlyList<QueuedEpisode> analysisQueue,
MediaSegmentType mode,
AnalysisMode mode,
CancellationToken cancellationToken)
{
if (mode != MediaSegmentType.Outro)
if (mode != AnalysisMode.Credits)
{
throw new NotImplementedException("mode must equal Credits");
}

View File

@ -1,12 +1,12 @@
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;
using ConfusedPolarBear.Plugin.IntroSkipper.Configuration;
using ConfusedPolarBear.Plugin.IntroSkipper.Data;
using Jellyfin.Data.Enums;
using MediaBrowser.Model.Entities;
using Microsoft.Extensions.Logging;
@ -26,7 +26,7 @@ public class ChapterAnalyzer(ILogger<ChapterAnalyzer> logger) : IMediaFileAnalyz
/// <inheritdoc />
public IReadOnlyList<QueuedEpisode> AnalyzeMediaFiles(
IReadOnlyList<QueuedEpisode> analysisQueue,
MediaSegmentType mode,
AnalysisMode mode,
CancellationToken cancellationToken)
{
var skippableRanges = new Dictionary<Guid, Segment>();
@ -34,7 +34,7 @@ public class ChapterAnalyzer(ILogger<ChapterAnalyzer> logger) : IMediaFileAnalyz
// Episode analysis queue.
var episodeAnalysisQueue = new List<QueuedEpisode>(analysisQueue);
var expression = mode == MediaSegmentType.Intro ?
var expression = mode == AnalysisMode.Introduction ?
Plugin.Instance!.Configuration.ChapterAnalyzerIntroductionPattern :
Plugin.Instance!.Configuration.ChapterAnalyzerEndCreditsPattern;
@ -83,7 +83,7 @@ public class ChapterAnalyzer(ILogger<ChapterAnalyzer> logger) : IMediaFileAnalyz
QueuedEpisode episode,
IReadOnlyList<ChapterInfo> chapters,
string expression,
MediaSegmentType mode)
AnalysisMode mode)
{
var count = chapters.Count;
if (count == 0)
@ -92,7 +92,7 @@ public class ChapterAnalyzer(ILogger<ChapterAnalyzer> logger) : IMediaFileAnalyz
}
var config = Plugin.Instance?.Configuration ?? new PluginConfiguration();
var reversed = mode != MediaSegmentType.Intro;
var reversed = mode != AnalysisMode.Introduction;
var (minDuration, maxDuration) = reversed
? (config.MinimumCreditsDuration, config.MaximumCreditsDuration)
: (config.MinimumIntroDuration, config.MaximumIntroDuration);

View File

@ -6,7 +6,6 @@ using System.Numerics;
using System.Threading;
using ConfusedPolarBear.Plugin.IntroSkipper.Configuration;
using ConfusedPolarBear.Plugin.IntroSkipper.Data;
using Jellyfin.Data.Enums;
using Microsoft.Extensions.Logging;
namespace ConfusedPolarBear.Plugin.IntroSkipper.Analyzers;
@ -32,7 +31,7 @@ public class ChromaprintAnalyzer : IMediaFileAnalyzer
private readonly ILogger<ChromaprintAnalyzer> _logger;
private MediaSegmentType _mediaSegmentType;
private AnalysisMode _analysisMode;
/// <summary>
/// Initializes a new instance of the <see cref="ChromaprintAnalyzer"/> class.
@ -52,7 +51,7 @@ public class ChromaprintAnalyzer : IMediaFileAnalyzer
/// <inheritdoc />
public IReadOnlyList<QueuedEpisode> AnalyzeMediaFiles(
IReadOnlyList<QueuedEpisode> analysisQueue,
MediaSegmentType mode,
AnalysisMode mode,
CancellationToken cancellationToken)
{
// All intros for this season.
@ -67,7 +66,7 @@ public class ChromaprintAnalyzer : IMediaFileAnalyzer
// Episodes that were analyzed and do not have an introduction.
var episodesWithoutIntros = episodeAnalysisQueue.Where(e => !e.State.IsAnalyzed(mode)).ToList();
_mediaSegmentType = mode;
_analysisMode = mode;
if (episodesWithoutIntros.Count == 0 || episodeAnalysisQueue.Count <= 1)
{
@ -97,7 +96,7 @@ public class ChromaprintAnalyzer : IMediaFileAnalyzer
fingerprintCache[episode.EpisodeId] = FFmpegWrapper.Fingerprint(episode, mode);
// Use reversed fingerprints for credits
if (_mediaSegmentType == MediaSegmentType.Outro)
if (_analysisMode == AnalysisMode.Credits)
{
Array.Reverse(fingerprintCache[episode.EpisodeId]);
}
@ -140,7 +139,7 @@ public class ChromaprintAnalyzer : IMediaFileAnalyzer
// - the introduction exceeds the configured limit
if (
!remainingIntro.Valid ||
(_mediaSegmentType == MediaSegmentType.Intro && remainingIntro.Duration > Plugin.Instance!.Configuration.MaximumIntroDuration))
(_analysisMode == AnalysisMode.Introduction && remainingIntro.Duration > Plugin.Instance!.Configuration.MaximumIntroDuration))
{
continue;
}
@ -154,7 +153,7 @@ public class ChromaprintAnalyzer : IMediaFileAnalyzer
* To fix this, the starting and ending times need to be switched, as they were previously reversed
* and subtracted from the episode duration to get the reported time range.
*/
if (_mediaSegmentType == MediaSegmentType.Outro)
if (_analysisMode == AnalysisMode.Credits)
{
// Calculate new values for the current intro
double currentOriginalIntroStart = currentIntro.Start;
@ -203,9 +202,9 @@ public class ChromaprintAnalyzer : IMediaFileAnalyzer
// Adjust all introduction times.
var analyzerHelper = new AnalyzerHelper(_logger);
seasonIntros = analyzerHelper.AdjustIntroTimes(analysisQueue, seasonIntros, _mediaSegmentType);
seasonIntros = analyzerHelper.AdjustIntroTimes(analysisQueue, seasonIntros, _analysisMode);
Plugin.Instance!.UpdateTimestamps(seasonIntros, _mediaSegmentType);
Plugin.Instance!.UpdateTimestamps(seasonIntros, _analysisMode);
return episodeAnalysisQueue;
}
@ -297,8 +296,8 @@ public class ChromaprintAnalyzer : IMediaFileAnalyzer
var rhsRanges = new List<TimeRange>();
// Generate inverted indexes for the left and right episodes.
var lhsIndex = FFmpegWrapper.CreateInvertedIndex(lhsId, lhsPoints, _mediaSegmentType);
var rhsIndex = FFmpegWrapper.CreateInvertedIndex(rhsId, rhsPoints, _mediaSegmentType);
var lhsIndex = FFmpegWrapper.CreateInvertedIndex(lhsId, lhsPoints, _analysisMode);
var rhsIndex = FFmpegWrapper.CreateInvertedIndex(rhsId, rhsPoints, _analysisMode);
var indexShifts = new HashSet<int>();
// For all audio points in the left episode, check if the right episode has a point which matches exactly.

View File

@ -1,7 +1,6 @@
using System.Collections.Generic;
using System.Threading;
using ConfusedPolarBear.Plugin.IntroSkipper.Data;
using Jellyfin.Data.Enums;
namespace ConfusedPolarBear.Plugin.IntroSkipper.Analyzers;
@ -19,6 +18,6 @@ public interface IMediaFileAnalyzer
/// <returns>Collection of media files that were **unsuccessfully analyzed**.</returns>
public IReadOnlyList<QueuedEpisode> AnalyzeMediaFiles(
IReadOnlyList<QueuedEpisode> analysisQueue,
MediaSegmentType mode,
AnalysisMode mode,
CancellationToken cancellationToken);
}

View File

@ -1,7 +1,7 @@
using System.Collections.Generic;
using System.Threading;
using ConfusedPolarBear.Plugin.IntroSkipper.Data;
using Jellyfin.Data.Enums;
using Microsoft.Extensions.Logging;
namespace ConfusedPolarBear.Plugin.IntroSkipper.Analyzers;
@ -10,10 +10,21 @@ namespace ConfusedPolarBear.Plugin.IntroSkipper.Analyzers;
/// </summary>
public class SegmentAnalyzer : IMediaFileAnalyzer
{
private readonly ILogger<SegmentAnalyzer> _logger;
/// <summary>
/// Initializes a new instance of the <see cref="SegmentAnalyzer"/> class.
/// </summary>
/// <param name="logger">Logger.</param>
public SegmentAnalyzer(ILogger<SegmentAnalyzer> logger)
{
_logger = logger;
}
/// <inheritdoc />
public IReadOnlyList<QueuedEpisode> AnalyzeMediaFiles(
IReadOnlyList<QueuedEpisode> analysisQueue,
MediaSegmentType mode,
AnalysisMode mode,
CancellationToken cancellationToken)
{
return analysisQueue;

View File

@ -1035,16 +1035,16 @@
// Update the editor for the first and second episodes
timestampEditor.style.display = "unset";
document.querySelector("#editLeftEpisodeTitle").textContent = leftEpisode.text;
document.querySelector("#editLeftIntroEpisodeStartEdit").value = leftEpisodeJson.Intro.Start;
document.querySelector("#editLeftIntroEpisodeEndEdit").value = leftEpisodeJson.Intro.End;
document.querySelector("#editLeftCreditEpisodeStartEdit").value = leftEpisodeJson.Outro.Start;
document.querySelector("#editLeftCreditEpisodeEndEdit").value = leftEpisodeJson.Outro.End;
document.querySelector("#editLeftIntroEpisodeStartEdit").value = leftEpisodeJson.Introduction.Start;
document.querySelector("#editLeftIntroEpisodeEndEdit").value = leftEpisodeJson.Introduction.End;
document.querySelector("#editLeftCreditEpisodeStartEdit").value = leftEpisodeJson.Credits.Start;
document.querySelector("#editLeftCreditEpisodeEndEdit").value = leftEpisodeJson.Credits.End;
document.querySelector("#editRightEpisodeTitle").textContent = rightEpisode.text;
document.querySelector("#editRightIntroEpisodeStartEdit").value = rightEpisodeJson.Intro.Start;
document.querySelector("#editRightIntroEpisodeEndEdit").value = rightEpisodeJson.Intro.End;
document.querySelector("#editRightCreditEpisodeStartEdit").value = rightEpisodeJson.Outro.Start;
document.querySelector("#editRightCreditEpisodeEndEdit").value = rightEpisodeJson.Outro.End;
document.querySelector("#editRightIntroEpisodeStartEdit").value = rightEpisodeJson.Introduction.Start;
document.querySelector("#editRightIntroEpisodeEndEdit").value = rightEpisodeJson.Introduction.End;
document.querySelector("#editRightCreditEpisodeStartEdit").value = rightEpisodeJson.Credits.Start;
document.querySelector("#editRightCreditEpisodeEndEdit").value = rightEpisodeJson.Credits.End;
// Update display inputs
const inputs = document.querySelectorAll('#timestampEditor input[type="number"]');
@ -1259,11 +1259,11 @@
selectEpisode1.addEventListener("change", episodeChanged);
selectEpisode2.addEventListener("change", episodeChanged);
btnEraseIntroTimestamps.addEventListener("click", (e) => {
eraseTimestamps("Intro");
eraseTimestamps("Introduction");
e.preventDefault();
});
btnEraseCreditTimestamps.addEventListener("click", (e) => {
eraseTimestamps("Outro");
eraseTimestamps("Credits");
e.preventDefault();
});
btnSeasonEraseTimestamps.addEventListener("click", () => {
@ -1317,11 +1317,11 @@
const lhsId = selectEpisode1.options[selectEpisode1.selectedIndex].value;
const newLhs = {
Intro: {
Introduction: {
Start: getEditValue("editLeftIntroEpisodeStartEdit"),
End: getEditValue("editLeftIntroEpisodeEndEdit"),
},
Outro: {
Credits: {
Start: getEditValue("editLeftCreditEpisodeStartEdit"),
End: getEditValue("editLeftCreditEpisodeEndEdit"),
},
@ -1329,11 +1329,11 @@
const rhsId = selectEpisode2.options[selectEpisode2.selectedIndex].value;
const newRhs = {
Intro: {
Introduction: {
Start: getEditValue("editRightIntroEpisodeStartEdit"),
End: getEditValue("editRightIntroEpisodeEndEdit"),
},
Outro: {
Credits: {
Start: getEditValue("editRightCreditEpisodeStartEdit"),
End: getEditValue("editRightCreditEpisodeEndEdit"),
},

View File

@ -186,8 +186,8 @@ const introSkipper = {
<span class="material-icons skip_next"></span>
</button>
`;
this.skipButton.dataset.Intro = config.SkipButtonIntroText;
this.skipButton.dataset.Outro = config.SkipButtonEndCreditsText;
this.skipButton.dataset.Introduction = config.SkipButtonIntroText;
this.skipButton.dataset.Credits = config.SkipButtonEndCreditsText;
const controls = document.querySelector("div#videoOsdPage");
controls.appendChild(this.skipButton);
},
@ -270,7 +270,7 @@ const introSkipper = {
}, 500);
};
this.videoPlayer.addEventListener('seeked', seekedHandler);
this.videoPlayer.currentTime = segment.SegmentType === "Outro" && this.videoPlayer.duration - segment.IntroEnd < 3
this.videoPlayer.currentTime = segment.SegmentType === "Credits" && this.videoPlayer.duration - segment.IntroEnd < 3
? this.videoPlayer.duration + 10
: segment.IntroEnd;
},
@ -391,11 +391,11 @@ const introSkipper = {
this.setTimeInputs(skipperFields);
},
updateSkipperFields(skipperFields) {
const { Intro = {}, Outro = {} } = this.skipperData;
skipperFields.querySelector('#introStartEdit').value = Intro.Start || 0;
skipperFields.querySelector('#introEndEdit').value = Intro.End || 0;
skipperFields.querySelector('#creditsStartEdit').value = Outro.Start || 0;
skipperFields.querySelector('#creditsEndEdit').value = Outro.End || 0;
const { Introduction = {}, Credits = {} } = this.skipperData;
skipperFields.querySelector('#introStartEdit').value = Introduction.Start || 0;
skipperFields.querySelector('#introEndEdit').value = Introduction.End || 0;
skipperFields.querySelector('#creditsStartEdit').value = Credits.Start || 0;
skipperFields.querySelector('#creditsEndEdit').value = Credits.End || 0;
},
attachSaveListener(metadataFormFields) {
const saveButton = metadataFormFields.querySelector('.formDialogFooter .btnSave');
@ -441,20 +441,20 @@ const introSkipper = {
},
async saveSkipperData() {
const newTimestamps = {
Intro: {
Introduction: {
Start: parseFloat(document.getElementById('introStartEdit').value || 0),
End: parseFloat(document.getElementById('introEndEdit').value || 0)
},
Outro: {
Credits: {
Start: parseFloat(document.getElementById('creditsStartEdit').value || 0),
End: parseFloat(document.getElementById('creditsEndEdit').value || 0)
}
};
const { Intro = {}, Outro = {} } = this.skipperData;
if (newTimestamps.Intro.Start !== (Intro.Start || 0) ||
newTimestamps.Intro.End !== (Intro.End || 0) ||
newTimestamps.Outro.Start !== (Outro.Start || 0) ||
newTimestamps.Outro.End !== (Outro.End || 0)) {
const { Introduction = {}, Credits = {} } = this.skipperData;
if (newTimestamps.Introduction.Start !== (Introduction.Start || 0) ||
newTimestamps.Introduction.End !== (Introduction.End || 0) ||
newTimestamps.Credits.Start !== (Credits.Start || 0) ||
newTimestamps.Credits.End !== (Credits.End || 0)) {
const response = await this.secureFetch(`Episode/${this.currentEpisodeId}/Timestamps`, "POST", JSON.stringify(newTimestamps));
this.d(response.ok ? 'Timestamps updated successfully' : 'Failed to update timestamps:', response.status);
} else {

View File

@ -23,4 +23,8 @@
<EmbeddedResource Include="Configuration\visualizer.js" />
<EmbeddedResource Include="Configuration\inject.js" />
</ItemGroup>
<ItemGroup>
<Folder Include="Manager\" />
<Folder Include="Services\" />
</ItemGroup>
</Project>

View File

@ -3,7 +3,6 @@ using System.Collections.Generic;
using System.Net.Mime;
using ConfusedPolarBear.Plugin.IntroSkipper.Configuration;
using ConfusedPolarBear.Plugin.IntroSkipper.Data;
using Jellyfin.Data.Enums;
using MediaBrowser.Common.Api;
using MediaBrowser.Controller.Entities.TV;
using Microsoft.AspNetCore.Authorization;
@ -38,7 +37,7 @@ public class SkipIntroController : ControllerBase
[HttpGet("Episode/{id}/IntroTimestamps/v1")]
public ActionResult<Intro> GetIntroTimestamps(
[FromRoute] Guid id,
[FromQuery] MediaSegmentType mode = MediaSegmentType.Intro)
[FromQuery] AnalysisMode mode = AnalysisMode.Introduction)
{
var intro = GetIntro(id, mode);
@ -81,8 +80,8 @@ public class SkipIntroController : ControllerBase
Plugin.Instance!.Credits[id] = new Segment(id, cr);
}
Plugin.Instance!.SaveTimestamps(MediaSegmentType.Intro);
Plugin.Instance!.SaveTimestamps(MediaSegmentType.Outro);
Plugin.Instance!.SaveTimestamps(AnalysisMode.Introduction);
Plugin.Instance!.SaveTimestamps(AnalysisMode.Credits);
return NoContent();
}
@ -126,18 +125,18 @@ public class SkipIntroController : ControllerBase
/// <response code="200">Skippable segments dictionary.</response>
/// <returns>Dictionary of skippable segments.</returns>
[HttpGet("Episode/{id}/IntroSkipperSegments")]
public ActionResult<Dictionary<MediaSegmentType, Intro>> GetSkippableSegments([FromRoute] Guid id)
public ActionResult<Dictionary<AnalysisMode, Intro>> GetSkippableSegments([FromRoute] Guid id)
{
var segments = new Dictionary<MediaSegmentType, Intro>();
var segments = new Dictionary<AnalysisMode, Intro>();
if (GetIntro(id, MediaSegmentType.Intro) is Intro intro)
if (GetIntro(id, AnalysisMode.Introduction) is Intro intro)
{
segments[MediaSegmentType.Intro] = intro;
segments[AnalysisMode.Introduction] = intro;
}
if (GetIntro(id, MediaSegmentType.Outro) is Intro credits)
if (GetIntro(id, AnalysisMode.Credits) is Intro credits)
{
segments[MediaSegmentType.Outro] = credits;
segments[AnalysisMode.Credits] = credits;
}
return segments;
@ -147,7 +146,7 @@ public class SkipIntroController : ControllerBase
/// <param name="id">Unique identifier of this episode.</param>
/// <param name="mode">Mode.</param>
/// <returns>Intro object if the provided item has an intro, null otherwise.</returns>
private static Intro? GetIntro(Guid id, MediaSegmentType mode)
private static Intro? GetIntro(Guid id, AnalysisMode mode)
{
try
{
@ -188,13 +187,13 @@ public class SkipIntroController : ControllerBase
/// <returns>No content.</returns>
[Authorize(Policy = Policies.RequiresElevation)]
[HttpPost("Intros/EraseTimestamps")]
public ActionResult ResetIntroTimestamps([FromQuery] MediaSegmentType mode, [FromQuery] bool eraseCache = false)
public ActionResult ResetIntroTimestamps([FromQuery] AnalysisMode mode, [FromQuery] bool eraseCache = false)
{
if (mode == MediaSegmentType.Intro)
if (mode == AnalysisMode.Introduction)
{
Plugin.Instance!.Intros.Clear();
}
else if (mode == MediaSegmentType.Outro)
else if (mode == AnalysisMode.Credits)
{
Plugin.Instance!.Credits.Clear();
}

View File

@ -4,7 +4,6 @@ using System.Globalization;
using System.Linq;
using System.Net.Mime;
using ConfusedPolarBear.Plugin.IntroSkipper.Data;
using Jellyfin.Data.Enums;
using MediaBrowser.Common.Api;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
@ -115,8 +114,8 @@ public class VisualizationController(ILogger<VisualizationController> logger) :
return new IgnoreListItem(Guid.Empty)
{
IgnoreIntro = seasonIds.All(seasonId => Plugin.Instance!.IsIgnored(seasonId, MediaSegmentType.Intro)),
IgnoreCredits = seasonIds.All(seasonId => Plugin.Instance!.IsIgnored(seasonId, MediaSegmentType.Outro))
IgnoreIntro = seasonIds.All(seasonId => Plugin.Instance!.IsIgnored(seasonId, AnalysisMode.Introduction)),
IgnoreCredits = seasonIds.All(seasonId => Plugin.Instance!.IsIgnored(seasonId, AnalysisMode.Credits))
};
}
@ -159,7 +158,7 @@ public class VisualizationController(ILogger<VisualizationController> logger) :
{
if (needle.EpisodeId == id)
{
return FFmpegWrapper.Fingerprint(needle, MediaSegmentType.Intro);
return FFmpegWrapper.Fingerprint(needle, AnalysisMode.Introduction);
}
}
}
@ -202,7 +201,7 @@ public class VisualizationController(ILogger<VisualizationController> logger) :
}
}
Plugin.Instance!.SaveTimestamps(MediaSegmentType.Intro | MediaSegmentType.Outro);
Plugin.Instance!.SaveTimestamps(AnalysisMode.Introduction | AnalysisMode.Credits);
return NoContent();
}
@ -282,7 +281,7 @@ public class VisualizationController(ILogger<VisualizationController> logger) :
{
var tr = new TimeRange(timestamps.IntroStart, timestamps.IntroEnd);
Plugin.Instance!.Intros[id] = new Segment(id, tr);
Plugin.Instance.SaveTimestamps(MediaSegmentType.Intro);
Plugin.Instance.SaveTimestamps(AnalysisMode.Introduction);
}
return NoContent();

View File

@ -0,0 +1,17 @@
namespace ConfusedPolarBear.Plugin.IntroSkipper.Data;
/// <summary>
/// Type of media file analysis to perform.
/// </summary>
public enum AnalysisMode
{
/// <summary>
/// Detect introduction sequences.
/// </summary>
Introduction,
/// <summary>
/// Detect credits.
/// </summary>
Credits,
}

View File

@ -1,7 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Jellyfin.Data.Enums;
namespace ConfusedPolarBear.Plugin.IntroSkipper.Data;
@ -10,61 +7,44 @@ namespace ConfusedPolarBear.Plugin.IntroSkipper.Data;
/// </summary>
public class EpisodeState
{
private readonly Dictionary<MediaSegmentType, (bool Analyzed, bool Blacklisted)> _states = [];
private readonly bool[] _analyzedStates = new bool[2];
/// <summary>
/// Initializes a new instance of the <see cref="EpisodeState"/> class.
/// </summary>
public EpisodeState() =>
Array.ForEach(Enum.GetValues<MediaSegmentType>(), mode => _states[mode] = default);
private readonly bool[] _blacklistedStates = new bool[2];
/// <summary>
/// Checks if the specified analysis mode has been analyzed.
/// </summary>
/// <param name="mode">The analysis mode to check.</param>
/// <returns>True if the mode has been analyzed, false otherwise.</returns>
public bool IsAnalyzed(MediaSegmentType mode) => _states[mode].Analyzed;
/// <summary>
/// Checks if the specified analysis mode has been blacklisted.
/// </summary>
/// <param name="mode">The analysis mode to check.</param>
/// <returns>True if the mode has been blacklisted, false otherwise.</returns>
public bool IsBlacklisted(MediaSegmentType mode) => _states[mode].Blacklisted;
public bool IsAnalyzed(AnalysisMode mode) => _analyzedStates[(int)mode];
/// <summary>
/// Sets the analyzed state for the specified analysis mode.
/// </summary>
/// <param name="mode">The analysis mode to set.</param>
/// <param name="value">The analyzed state to set.</param>
public void SetAnalyzed(MediaSegmentType mode, bool value) =>
_states[mode] = (value, _states[mode].Blacklisted);
public void SetAnalyzed(AnalysisMode mode, bool value) => _analyzedStates[(int)mode] = value;
/// <summary>
/// Checks if the specified analysis mode has been blacklisted.
/// </summary>
/// <param name="mode">The analysis mode to check.</param>
/// <returns>True if the mode has been blacklisted, false otherwise.</returns>
public bool IsBlacklisted(AnalysisMode mode) => _blacklistedStates[(int)mode];
/// <summary>
/// Sets the blacklisted state for the specified analysis mode.
/// </summary>
/// <param name="mode">The analysis mode to set.</param>
/// <param name="value">The blacklisted state to set.</param>
public void SetBlacklisted(MediaSegmentType mode, bool value) =>
_states[mode] = (_states[mode].Analyzed, value);
public void SetBlacklisted(AnalysisMode mode, bool value) => _blacklistedStates[(int)mode] = value;
/// <summary>
/// Resets all states to their default values.
/// Resets the analyzed states.
/// </summary>
public void ResetStates() =>
Array.ForEach(Enum.GetValues<MediaSegmentType>(), mode => _states[mode] = default);
/// <summary>
/// Gets all modes that have been analyzed.
/// </summary>
/// <returns>An IEnumerable of analyzed MediaSegmentTypes.</returns>
public IEnumerable<MediaSegmentType> GetAnalyzedModes() =>
_states.Where(kvp => kvp.Value.Analyzed).Select(kvp => kvp.Key);
/// <summary>
/// Gets all modes that have been blacklisted.
/// </summary>
/// <returns>An IEnumerable of blacklisted MediaSegmentTypes.</returns>
public IEnumerable<MediaSegmentType> GetBlacklistedModes() =>
_states.Where(kvp => kvp.Value.Blacklisted).Select(kvp => kvp.Key);
public void ResetStates()
{
Array.Clear(_analyzedStates);
Array.Clear(_blacklistedStates);
}
}

View File

@ -1,6 +1,5 @@
using System;
using System.Runtime.Serialization;
using Jellyfin.Data.Enums;
namespace ConfusedPolarBear.Plugin.IntroSkipper.Data;
@ -60,14 +59,14 @@ public class IgnoreListItem
/// </summary>
/// <param name="mode">Analysis mode.</param>
/// <param name="value">Value to set.</param>
public void Toggle(MediaSegmentType mode, bool value)
public void Toggle(AnalysisMode mode, bool value)
{
switch (mode)
{
case MediaSegmentType.Intro:
case AnalysisMode.Introduction:
IgnoreIntro = value;
break;
case MediaSegmentType.Outro:
case AnalysisMode.Credits:
IgnoreCredits = value;
break;
}
@ -78,12 +77,12 @@ public class IgnoreListItem
/// </summary>
/// <param name="mode">Analysis mode.</param>
/// <returns>True if ignored, false otherwise.</returns>
public bool IsIgnored(MediaSegmentType mode)
public bool IsIgnored(AnalysisMode mode)
{
return mode switch
{
MediaSegmentType.Intro => IgnoreIntro,
MediaSegmentType.Outro => IgnoreCredits,
AnalysisMode.Introduction => IgnoreIntro,
AnalysisMode.Credits => IgnoreCredits,
_ => false,
};
}

View File

@ -7,7 +7,6 @@ using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using ConfusedPolarBear.Plugin.IntroSkipper.Data;
using Jellyfin.Data.Enums;
using Microsoft.Extensions.Logging;
namespace ConfusedPolarBear.Plugin.IntroSkipper;
@ -34,7 +33,7 @@ public static partial class FFmpegWrapper
private static Dictionary<string, string> ChromaprintLogs { get; set; } = [];
private static ConcurrentDictionary<(Guid Id, MediaSegmentType Mode), Dictionary<uint, int>> InvertedIndexCache { get; set; } = new();
private static ConcurrentDictionary<(Guid Id, AnalysisMode Mode), Dictionary<uint, int>> InvertedIndexCache { get; set; } = new();
/// <summary>
/// Check that the installed version of ffmpeg supports chromaprint.
@ -110,16 +109,16 @@ public static partial class FFmpegWrapper
/// <param name="episode">Queued episode to fingerprint.</param>
/// <param name="mode">Portion of media file to fingerprint. Introduction = first 25% / 10 minutes and Credits = last 4 minutes.</param>
/// <returns>Numerical fingerprint points.</returns>
public static uint[] Fingerprint(QueuedEpisode episode, MediaSegmentType mode)
public static uint[] Fingerprint(QueuedEpisode episode, AnalysisMode mode)
{
int start, end;
if (mode == MediaSegmentType.Intro)
if (mode == AnalysisMode.Introduction)
{
start = 0;
end = episode.IntroFingerprintEnd;
}
else if (mode == MediaSegmentType.Outro)
else if (mode == AnalysisMode.Credits)
{
start = episode.CreditsFingerprintStart;
end = episode.Duration;
@ -139,7 +138,7 @@ public static partial class FFmpegWrapper
/// <param name="fingerprint">Chromaprint fingerprint.</param>
/// <param name="mode">Mode.</param>
/// <returns>Inverted index.</returns>
public static Dictionary<uint, int> CreateInvertedIndex(Guid id, uint[] fingerprint, MediaSegmentType mode)
public static Dictionary<uint, int> CreateInvertedIndex(Guid id, uint[] fingerprint, AnalysisMode mode)
{
if (InvertedIndexCache.TryGetValue((id, mode), out var cached))
{
@ -469,7 +468,7 @@ public static partial class FFmpegWrapper
/// <param name="start">Time (in seconds) relative to the start of the file to start fingerprinting from.</param>
/// <param name="end">Time (in seconds) relative to the start of the file to stop fingerprinting at.</param>
/// <returns>Numerical fingerprint points.</returns>
private static uint[] Fingerprint(QueuedEpisode episode, MediaSegmentType mode, int start, int end)
private static uint[] Fingerprint(QueuedEpisode episode, AnalysisMode mode, int start, int end)
{
// Try to load this episode from cache before running ffmpeg.
if (LoadCachedFingerprint(episode, mode, out uint[] cachedFingerprint))
@ -523,7 +522,7 @@ public static partial class FFmpegWrapper
/// <returns>true if the episode was successfully loaded from cache, false on any other error.</returns>
private static bool LoadCachedFingerprint(
QueuedEpisode episode,
MediaSegmentType mode,
AnalysisMode mode,
out uint[] fingerprint)
{
fingerprint = Array.Empty<uint>();
@ -579,7 +578,7 @@ public static partial class FFmpegWrapper
/// <param name="fingerprint">Fingerprint of the episode to store.</param>
private static void CacheFingerprint(
QueuedEpisode episode,
MediaSegmentType mode,
AnalysisMode mode,
List<uint> fingerprint)
{
// Bail out if caching isn't enabled.
@ -628,11 +627,11 @@ public static partial class FFmpegWrapper
/// Remove cached fingerprints from disk by mode.
/// </summary>
/// <param name="mode">Analysis mode.</param>
public static void DeleteCacheFiles(MediaSegmentType mode)
public static void DeleteCacheFiles(AnalysisMode mode)
{
foreach (var filePath in Directory.EnumerateFiles(Plugin.Instance!.FingerprintCachePath))
{
var shouldDelete = (mode == MediaSegmentType.Intro)
var shouldDelete = (mode == AnalysisMode.Introduction)
? !filePath.Contains("credit", StringComparison.OrdinalIgnoreCase)
&& !filePath.Contains("blackframes", StringComparison.OrdinalIgnoreCase)
: filePath.Contains("credit", StringComparison.OrdinalIgnoreCase)
@ -652,18 +651,18 @@ public static partial class FFmpegWrapper
/// <param name="episode">Episode.</param>
/// <param name="mode">Analysis mode.</param>
/// <returns>Path.</returns>
public static string GetFingerprintCachePath(QueuedEpisode episode, MediaSegmentType mode)
public static string GetFingerprintCachePath(QueuedEpisode episode, AnalysisMode mode)
{
var basePath = Path.Join(
Plugin.Instance!.FingerprintCachePath,
episode.EpisodeId.ToString("N"));
if (mode == MediaSegmentType.Intro)
if (mode == AnalysisMode.Introduction)
{
return basePath;
}
if (mode == MediaSegmentType.Outro)
if (mode == AnalysisMode.Credits)
{
return basePath + "-credits";
}

View File

@ -6,7 +6,7 @@ using System.Runtime.Serialization;
using System.Xml;
using ConfusedPolarBear.Plugin.IntroSkipper.Data;
namespace ConfusedPolarBear.Plugin.IntroSkipper.Helper
namespace ConfusedPolarBear.Plugin.IntroSkipper
{
internal sealed class XmlSerializationHelper
{

View File

@ -4,8 +4,8 @@ using System.IO;
using ConfusedPolarBear.Plugin.IntroSkipper.Data;
using Microsoft.Extensions.Logging;
namespace ConfusedPolarBear.Plugin.IntroSkipper.Manager
{
namespace ConfusedPolarBear.Plugin.IntroSkipper;
/// <summary>
/// Update EDL files associated with a list of episodes.
/// </summary>
@ -114,4 +114,3 @@ namespace ConfusedPolarBear.Plugin.IntroSkipper.Manager
return Path.ChangeExtension(mediaPath, "edl");
}
}
}

View File

@ -10,8 +10,8 @@ using MediaBrowser.Controller.Entities.TV;
using MediaBrowser.Controller.Library;
using Microsoft.Extensions.Logging;
namespace ConfusedPolarBear.Plugin.IntroSkipper.Manager
{
namespace ConfusedPolarBear.Plugin.IntroSkipper;
/// <summary>
/// Manages enqueuing library items for analysis.
/// </summary>
@ -241,50 +241,56 @@ namespace ConfusedPolarBear.Plugin.IntroSkipper.Manager
/// <param name="candidates">Queued media items.</param>
/// <param name="modes">Analysis mode.</param>
/// <returns>Media items that have been verified to exist in Jellyfin and in storage.</returns>
public (IReadOnlyList<QueuedEpisode> VerifiedItems, IReadOnlyCollection<MediaSegmentType> RequiredModes)
VerifyQueue(IReadOnlyList<QueuedEpisode> candidates, IReadOnlyCollection<MediaSegmentType> modes)
public (IReadOnlyList<QueuedEpisode> VerifiedItems, IReadOnlyCollection<AnalysisMode> RequiredModes)
VerifyQueue(IReadOnlyList<QueuedEpisode> candidates, IReadOnlyCollection<AnalysisMode> modes)
{
var verified = new List<QueuedEpisode>();
var reqModes = new HashSet<MediaSegmentType>(modes);
var reqModes = new HashSet<AnalysisMode>();
foreach (var candidate in candidates)
{
try
{
if (!File.Exists(Plugin.Instance!.GetItemPath(candidate.EpisodeId)))
var path = Plugin.Instance!.GetItemPath(candidate.EpisodeId);
if (!File.Exists(path))
{
continue;
}
verified.Add(candidate);
reqModes.ExceptWith(candidate.State.GetAnalyzedModes());
reqModes.ExceptWith(candidate.State.GetBlacklistedModes());
if (reqModes.Remove(MediaSegmentType.Intro) && Plugin.Instance.Intros.ContainsKey(candidate.EpisodeId))
foreach (var mode in modes)
{
candidate.State.SetAnalyzed(MediaSegmentType.Intro, true);
if (candidate.State.IsAnalyzed(mode) || candidate.State.IsBlacklisted(mode))
{
continue;
}
bool isAnalyzed = mode == AnalysisMode.Introduction
? Plugin.Instance!.Intros.ContainsKey(candidate.EpisodeId)
: Plugin.Instance!.Credits.ContainsKey(candidate.EpisodeId);
if (isAnalyzed)
{
candidate.State.SetAnalyzed(mode, true);
}
else
{
reqModes.Add(MediaSegmentType.Intro);
reqModes.Add(mode);
}
if (reqModes.Remove(MediaSegmentType.Outro) && Plugin.Instance.Credits.ContainsKey(candidate.EpisodeId))
{
candidate.State.SetAnalyzed(MediaSegmentType.Outro, true);
}
else
{
reqModes.Add(MediaSegmentType.Outro);
}
}
catch (Exception ex)
{
_logger.LogDebug("Skipping analysis of {Name} ({Id}): {Exception}", candidate.Name, candidate.EpisodeId, ex);
_logger.LogDebug(
"Skipping analysis of {Name} ({Id}): {Exception}",
candidate.Name,
candidate.EpisodeId,
ex);
}
}
return (verified, reqModes);
}
}
}

View File

@ -6,8 +6,6 @@ using System.Linq;
using System.Text.RegularExpressions;
using ConfusedPolarBear.Plugin.IntroSkipper.Configuration;
using ConfusedPolarBear.Plugin.IntroSkipper.Data;
using ConfusedPolarBear.Plugin.IntroSkipper.Helper;
using Jellyfin.Data.Enums;
using MediaBrowser.Common;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Common.Plugins;
@ -184,16 +182,16 @@ public class Plugin : BasePlugin<PluginConfiguration>, IHasWebPages
/// Save timestamps to disk.
/// </summary>
/// <param name="mode">Mode.</param>
public void SaveTimestamps(MediaSegmentType mode)
public void SaveTimestamps(AnalysisMode mode)
{
List<Segment> introList = [];
var filePath = mode == MediaSegmentType.Intro
var filePath = mode == AnalysisMode.Introduction
? _introPath
: _creditsPath;
lock (_introsLock)
{
introList.AddRange(mode == MediaSegmentType.Intro
introList.AddRange(mode == AnalysisMode.Introduction
? Instance!.Intros.Values
: Instance!.Credits.Values);
}
@ -237,7 +235,7 @@ public class Plugin : BasePlugin<PluginConfiguration>, IHasWebPages
/// <param name="id">Item id.</param>
/// <param name="mode">Mode.</param>
/// <returns>True if ignored, false otherwise.</returns>
public bool IsIgnored(Guid id, MediaSegmentType mode)
public bool IsIgnored(Guid id, AnalysisMode mode)
{
return Instance!.IgnoreList.TryGetValue(id, out var item) && item.IsIgnored(mode);
}
@ -314,9 +312,9 @@ public class Plugin : BasePlugin<PluginConfiguration>, IHasWebPages
/// <param name="id">Item id.</param>
/// <param name="mode">Mode.</param>
/// <returns>Intro.</returns>
internal static Segment GetIntroByMode(Guid id, MediaSegmentType mode)
internal static Segment GetIntroByMode(Guid id, AnalysisMode mode)
{
return mode == MediaSegmentType.Intro
return mode == AnalysisMode.Introduction
? Instance!.Intros[id]
: Instance!.Credits[id];
}
@ -375,15 +373,15 @@ public class Plugin : BasePlugin<PluginConfiguration>, IHasWebPages
/// <returns>State of this item.</returns>
internal EpisodeState GetState(Guid id) => EpisodeStates.GetOrAdd(id, _ => new EpisodeState());
internal void UpdateTimestamps(IReadOnlyDictionary<Guid, Segment> newTimestamps, MediaSegmentType mode)
internal void UpdateTimestamps(IReadOnlyDictionary<Guid, Segment> newTimestamps, AnalysisMode mode)
{
foreach (var intro in newTimestamps)
{
if (mode == MediaSegmentType.Intro)
if (mode == AnalysisMode.Introduction)
{
Instance!.Intros.AddOrUpdate(intro.Key, intro.Value, (key, oldValue) => intro.Value);
}
else if (mode == MediaSegmentType.Outro)
else if (mode == AnalysisMode.Credits)
{
Instance!.Credits.AddOrUpdate(intro.Key, intro.Value, (key, oldValue) => intro.Value);
}
@ -406,8 +404,8 @@ public class Plugin : BasePlugin<PluginConfiguration>, IHasWebPages
}
}
SaveTimestamps(MediaSegmentType.Intro);
SaveTimestamps(MediaSegmentType.Outro);
SaveTimestamps(AnalysisMode.Introduction);
SaveTimestamps(AnalysisMode.Credits);
}
private void MigrateRepoUrl(IServerConfigurationManager serverConfiguration)

View File

@ -1,5 +1,4 @@
using ConfusedPolarBear.Plugin.IntroSkipper.Providers;
using ConfusedPolarBear.Plugin.IntroSkipper.Services;
using MediaBrowser.Controller;
using MediaBrowser.Controller.Plugins;
using Microsoft.Extensions.DependencyInjection;

View File

@ -6,8 +6,6 @@ using System.Threading;
using System.Threading.Tasks;
using ConfusedPolarBear.Plugin.IntroSkipper.Analyzers;
using ConfusedPolarBear.Plugin.IntroSkipper.Data;
using ConfusedPolarBear.Plugin.IntroSkipper.Manager;
using Jellyfin.Data.Enums;
using MediaBrowser.Controller.Library;
using Microsoft.Extensions.Logging;
@ -18,7 +16,7 @@ namespace ConfusedPolarBear.Plugin.IntroSkipper.ScheduledTasks;
/// </summary>
public class BaseItemAnalyzerTask
{
private readonly IReadOnlyCollection<MediaSegmentType> _modes;
private readonly IReadOnlyCollection<AnalysisMode> _analysisModes;
private readonly ILogger _logger;
@ -34,12 +32,12 @@ public class BaseItemAnalyzerTask
/// <param name="loggerFactory">Logger factory.</param>
/// <param name="libraryManager">Library manager.</param>
public BaseItemAnalyzerTask(
IReadOnlyCollection<MediaSegmentType> modes,
IReadOnlyCollection<AnalysisMode> modes,
ILogger logger,
ILoggerFactory loggerFactory,
ILibraryManager libraryManager)
{
_modes = modes;
_analysisModes = modes;
_logger = logger;
_loggerFactory = loggerFactory;
_libraryManager = libraryManager;
@ -81,7 +79,7 @@ public class BaseItemAnalyzerTask
queue = queue.Where(kvp => seasonsToAnalyze.Contains(kvp.Key)).ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
}
int totalQueued = queue.Sum(kvp => kvp.Value.Count) * _modes.Count;
int totalQueued = queue.Sum(kvp => kvp.Value.Count) * _analysisModes.Count;
if (totalQueued == 0)
{
throw new FingerprintException(
@ -107,7 +105,7 @@ public class BaseItemAnalyzerTask
// of the current media items were deleted from Jellyfin since the task was started.
var (episodes, requiredModes) = queueManager.VerifyQueue(
season.Value,
_modes.Where(m => !Plugin.Instance!.IsIgnored(season.Key, m)).ToList());
_analysisModes.Where(m => !Plugin.Instance!.IsIgnored(season.Key, m)).ToList());
if (episodes.Count == 0)
{
@ -122,13 +120,13 @@ public class BaseItemAnalyzerTask
first.SeriesName,
first.SeasonNumber);
Interlocked.Add(ref totalProcessed, episodes.Count * _modes.Count); // Update total Processed directly
Interlocked.Add(ref totalProcessed, episodes.Count * _analysisModes.Count); // Update total Processed directly
progress.Report(totalProcessed * 100 / totalQueued);
return;
}
if (_modes.Count != requiredModes.Count)
if (_analysisModes.Count != requiredModes.Count)
{
Interlocked.Add(ref totalProcessed, episodes.Count);
progress.Report(totalProcessed * 100 / totalQueued); // Partial analysis some modes have already been analyzed
@ -141,7 +139,7 @@ public class BaseItemAnalyzerTask
return;
}
foreach (MediaSegmentType mode in requiredModes)
foreach (AnalysisMode mode in requiredModes)
{
var analyzed = AnalyzeItems(episodes, mode, cancellationToken);
Interlocked.Add(ref totalProcessed, analyzed);
@ -183,7 +181,7 @@ public class BaseItemAnalyzerTask
/// <returns>Number of items that were successfully analyzed.</returns>
private int AnalyzeItems(
IReadOnlyList<QueuedEpisode> items,
MediaSegmentType mode,
AnalysisMode mode,
CancellationToken cancellationToken)
{
var totalItems = items.Count;
@ -218,7 +216,7 @@ public class BaseItemAnalyzerTask
analyzers.Add(new ChromaprintAnalyzer(_loggerFactory.CreateLogger<ChromaprintAnalyzer>()));
}
if (mode == MediaSegmentType.Outro)
if (mode == AnalysisMode.Credits)
{
analyzers.Add(new BlackFrameAnalyzer(_loggerFactory.CreateLogger<BlackFrameAnalyzer>()));
}

View File

@ -4,7 +4,6 @@ using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using ConfusedPolarBear.Plugin.IntroSkipper.Manager;
using MediaBrowser.Controller.Library;
using MediaBrowser.Model.Tasks;
using Microsoft.Extensions.Logging;
@ -14,22 +13,29 @@ namespace ConfusedPolarBear.Plugin.IntroSkipper.ScheduledTasks;
/// <summary>
/// Analyze all television episodes for introduction sequences.
/// </summary>
/// <remarks>
public class CleanCacheTask : IScheduledTask
{
private readonly ILogger<CleanCacheTask> _logger;
private readonly ILoggerFactory _loggerFactory;
private readonly ILibraryManager _libraryManager;
/// <summary>
/// Initializes a new instance of the <see cref="CleanCacheTask"/> class.
/// </remarks>
/// </summary>
/// <param name="loggerFactory">Logger factory.</param>
/// <param name="libraryManager">Library manager.</param>
/// <param name="logger">Logger.</param>
public class CleanCacheTask(
public CleanCacheTask(
ILogger<CleanCacheTask> logger,
ILoggerFactory loggerFactory,
ILibraryManager libraryManager) : IScheduledTask
ILibraryManager libraryManager)
{
private readonly ILogger<CleanCacheTask> _logger = logger;
private readonly ILoggerFactory _loggerFactory = loggerFactory;
private readonly ILibraryManager _libraryManager = libraryManager;
_logger = logger;
_loggerFactory = loggerFactory;
_libraryManager = libraryManager;
}
/// <summary>
/// Gets the task name.

View File

@ -1,8 +1,9 @@
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Threading;
using System.Threading.Tasks;
using Jellyfin.Data.Enums;
using ConfusedPolarBear.Plugin.IntroSkipper.Data;
using MediaBrowser.Controller.Library;
using MediaBrowser.Model.Tasks;
using Microsoft.Extensions.Logging;
@ -13,22 +14,29 @@ namespace ConfusedPolarBear.Plugin.IntroSkipper.ScheduledTasks;
/// Analyze all television episodes for credits.
/// TODO: analyze all media files.
/// </summary>
/// <remarks>
public class DetectCreditsTask : IScheduledTask
{
private readonly ILogger<DetectCreditsTask> _logger;
private readonly ILoggerFactory _loggerFactory;
private readonly ILibraryManager _libraryManager;
/// <summary>
/// Initializes a new instance of the <see cref="DetectCreditsTask"/> class.
/// </remarks>
/// </summary>
/// <param name="loggerFactory">Logger factory.</param>
/// <param name="libraryManager">Library manager.</param>
/// <param name="logger">Logger.</param>
public class DetectCreditsTask(
public DetectCreditsTask(
ILogger<DetectCreditsTask> logger,
ILoggerFactory loggerFactory,
ILibraryManager libraryManager) : IScheduledTask
ILibraryManager libraryManager)
{
private readonly ILogger<DetectCreditsTask> _logger = logger;
private readonly ILoggerFactory _loggerFactory = loggerFactory;
private readonly ILibraryManager _libraryManager = libraryManager;
_logger = logger;
_loggerFactory = loggerFactory;
_libraryManager = libraryManager;
}
/// <summary>
/// Gets the task name.
@ -74,7 +82,7 @@ public class DetectCreditsTask(
{
_logger.LogInformation("Scheduled Task is starting");
var modes = new List<MediaSegmentType> { MediaSegmentType.Outro };
var modes = new List<AnalysisMode> { AnalysisMode.Credits };
var baseCreditAnalyzer = new BaseItemAnalyzerTask(
modes,

View File

@ -1,8 +1,9 @@
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Threading;
using System.Threading.Tasks;
using Jellyfin.Data.Enums;
using ConfusedPolarBear.Plugin.IntroSkipper.Data;
using MediaBrowser.Controller.Library;
using MediaBrowser.Model.Tasks;
using Microsoft.Extensions.Logging;
@ -12,22 +13,29 @@ namespace ConfusedPolarBear.Plugin.IntroSkipper.ScheduledTasks;
/// <summary>
/// Analyze all television episodes for introduction sequences.
/// </summary>
/// <remarks>
public class DetectIntrosCreditsTask : IScheduledTask
{
private readonly ILogger<DetectIntrosCreditsTask> _logger;
private readonly ILoggerFactory _loggerFactory;
private readonly ILibraryManager _libraryManager;
/// <summary>
/// Initializes a new instance of the <see cref="DetectIntrosCreditsTask"/> class.
/// </remarks>
/// </summary>
/// <param name="loggerFactory">Logger factory.</param>
/// <param name="libraryManager">Library manager.</param>
/// <param name="logger">Logger.</param>
public class DetectIntrosCreditsTask(
public DetectIntrosCreditsTask(
ILogger<DetectIntrosCreditsTask> logger,
ILoggerFactory loggerFactory,
ILibraryManager libraryManager) : IScheduledTask
ILibraryManager libraryManager)
{
private readonly ILogger<DetectIntrosCreditsTask> _logger = logger;
private readonly ILoggerFactory _loggerFactory = loggerFactory;
private readonly ILibraryManager _libraryManager = libraryManager;
_logger = logger;
_loggerFactory = loggerFactory;
_libraryManager = libraryManager;
}
/// <summary>
/// Gets the task name.
@ -73,7 +81,7 @@ public class DetectIntrosCreditsTask(
{
_logger.LogInformation("Scheduled Task is starting");
var modes = new List<MediaSegmentType> { MediaSegmentType.Intro, MediaSegmentType.Outro };
var modes = new List<AnalysisMode> { AnalysisMode.Introduction, AnalysisMode.Credits };
var baseIntroAnalyzer = new BaseItemAnalyzerTask(
modes,

View File

@ -1,8 +1,9 @@
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Threading;
using System.Threading.Tasks;
using Jellyfin.Data.Enums;
using ConfusedPolarBear.Plugin.IntroSkipper.Data;
using MediaBrowser.Controller.Library;
using MediaBrowser.Model.Tasks;
using Microsoft.Extensions.Logging;
@ -12,22 +13,29 @@ namespace ConfusedPolarBear.Plugin.IntroSkipper.ScheduledTasks;
/// <summary>
/// Analyze all television episodes for introduction sequences.
/// </summary>
/// <remarks>
public class DetectIntrosTask : IScheduledTask
{
private readonly ILogger<DetectIntrosTask> _logger;
private readonly ILoggerFactory _loggerFactory;
private readonly ILibraryManager _libraryManager;
/// <summary>
/// Initializes a new instance of the <see cref="DetectIntrosTask"/> class.
/// </remarks>
/// </summary>
/// <param name="loggerFactory">Logger factory.</param>
/// <param name="libraryManager">Library manager.</param>
/// <param name="logger">Logger.</param>
public class DetectIntrosTask(
public DetectIntrosTask(
ILogger<DetectIntrosTask> logger,
ILoggerFactory loggerFactory,
ILibraryManager libraryManager) : IScheduledTask
ILibraryManager libraryManager)
{
private readonly ILogger<DetectIntrosTask> _logger = logger;
private readonly ILoggerFactory _loggerFactory = loggerFactory;
private readonly ILibraryManager _libraryManager = libraryManager;
_logger = logger;
_loggerFactory = loggerFactory;
_libraryManager = libraryManager;
}
/// <summary>
/// Gets the task name.
@ -73,7 +81,7 @@ public class DetectIntrosTask(
{
_logger.LogInformation("Scheduled Task is starting");
var modes = new List<MediaSegmentType> { MediaSegmentType.Intro };
var modes = new List<AnalysisMode> { AnalysisMode.Introduction };
var baseIntroAnalyzer = new BaseItemAnalyzerTask(
modes,

View File

@ -15,8 +15,8 @@ using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Timer = System.Timers.Timer;
namespace ConfusedPolarBear.Plugin.IntroSkipper.Services
{
namespace ConfusedPolarBear.Plugin.IntroSkipper;
/// <summary>
/// Automatically skip past introduction sequences.
/// Commands clients to seek to the end of the intro as soon as they start playing it.
@ -33,6 +33,7 @@ namespace ConfusedPolarBear.Plugin.IntroSkipper.Services
ILogger<AutoSkip> logger) : IHostedService, IDisposable
{
private readonly object _sentSeekCommandLock = new();
private ILogger<AutoSkip> _logger = logger;
private IUserDataManager _userDataManager = userDataManager;
private ISessionManager _sessionManager = sessionManager;
@ -227,4 +228,3 @@ namespace ConfusedPolarBear.Plugin.IntroSkipper.Services
return Task.CompletedTask;
}
}
}

View File

@ -15,8 +15,8 @@ using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Timer = System.Timers.Timer;
namespace ConfusedPolarBear.Plugin.IntroSkipper.Services
{
namespace ConfusedPolarBear.Plugin.IntroSkipper;
/// <summary>
/// Automatically skip past credit sequences.
/// Commands clients to seek to the end of the credits as soon as they start playing it.
@ -33,6 +33,7 @@ namespace ConfusedPolarBear.Plugin.IntroSkipper.Services
ILogger<AutoSkipCredits> logger) : IHostedService, IDisposable
{
private readonly object _sentSeekCommandLock = new();
private ILogger<AutoSkipCredits> _logger = logger;
private IUserDataManager _userDataManager = userDataManager;
private ISessionManager _sessionManager = sessionManager;
@ -227,4 +228,3 @@ namespace ConfusedPolarBear.Plugin.IntroSkipper.Services
return Task.CompletedTask;
}
}
}

View File

@ -3,9 +3,8 @@ using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using ConfusedPolarBear.Plugin.IntroSkipper.Configuration;
using ConfusedPolarBear.Plugin.IntroSkipper.Manager;
using ConfusedPolarBear.Plugin.IntroSkipper.Data;
using ConfusedPolarBear.Plugin.IntroSkipper.ScheduledTasks;
using Jellyfin.Data.Enums;
using MediaBrowser.Controller.Entities.TV;
using MediaBrowser.Controller.Library;
using MediaBrowser.Model.Entities;
@ -262,18 +261,18 @@ public sealed class Entrypoint : IHostedService, IDisposable
_analyzeAgain = false;
var progress = new Progress<double>();
var modes = new List<MediaSegmentType>();
var modes = new List<AnalysisMode>();
var tasklogger = _loggerFactory.CreateLogger("DefaultLogger");
if (_config.AutoDetectIntros)
{
modes.Add(MediaSegmentType.Intro);
modes.Add(AnalysisMode.Introduction);
tasklogger = _loggerFactory.CreateLogger<DetectIntrosTask>();
}
if (_config.AutoDetectCredits)
{
modes.Add(MediaSegmentType.Outro);
modes.Add(AnalysisMode.Credits);
tasklogger = modes.Count == 2
? _loggerFactory.CreateLogger<DetectIntrosCreditsTask>()
: _loggerFactory.CreateLogger<DetectCreditsTask>();