diff --git a/ErsatzTV.Core.Tests/Scheduling/Goldens/PlayoutBuildGoldenTests.cs b/ErsatzTV.Core.Tests/Scheduling/Goldens/PlayoutBuildGoldenTests.cs index c888541be..08f9652e2 100644 --- a/ErsatzTV.Core.Tests/Scheduling/Goldens/PlayoutBuildGoldenTests.cs +++ b/ErsatzTV.Core.Tests/Scheduling/Goldens/PlayoutBuildGoldenTests.cs @@ -169,6 +169,60 @@ public class PlayoutBuildGoldenTests await CompareGolden("classic-clock-padded.txt", items, titles); // identical to the item-pad-only golden } + // #392: the schedule-level pad + OFFLINE advance is shared machinery — AddFiller records the offline + // target and every scheduler honors it. The offline goldens only exercise PlayoutModeSchedulerOne, so + // these invariant tests cover Flood / Duration / Multiple across a 2-day window (two midnight crossings) + // to prove the offline advance AND its day-seam anchor survival are not One-specific. No golden files: + // the invariants (boundary alignment of every content item, zero filler emitted, and resumption on a + // boundary on both later days) fully pin the behavior and are the exact thing the day-seam clamp fix + // must preserve. If the day-boundary anchor clamp wrongly discarded an offline advance, the first + // content item after a midnight would land mid-interval and fail here. + [TestCase("Flood")] + [TestCase("Duration")] + [TestCase("Multiple")] + public async Task Schedule_clock_padded_offline_multimode(string mode) + { + List items = await BuildSchedulePaddedModePlayout(mode); + + List content = items + .Where(i => i.FillerKind == FillerKind.None) + .OrderBy(i => i.Start) + .ToList(); + + // Sanity: a 2-day window over sub-hour content must yield many items spanning >1 day. + content.Count.ShouldBeGreaterThan(10); + content.Select(i => i.Start.Date).Distinct().Count().ShouldBeGreaterThan(2); + + // Offline variant: NO filler of any kind is emitted (gaps up to the boundary are left offline). + items.ShouldNotContain(i => i.FillerKind != FillerKind.None, $"[{mode}] offline pad must emit no filler"); + + // Every content item begins on a :15 boundary. The very first item is the raw anchor at the pinned + // Start (06:00, itself a :15 boundary); every later item — including the first of day 2 and day 3 — + // is on a boundary only because the preceding item's offline pad advanced the clock to it AND the + // day-boundary anchor clamp preserved that advance across each midnight seam. + foreach (PlayoutItem item in content) + { + (item.Start.Minute % 15).ShouldBe( + 0, + $"[{mode}] content item at {item.Start:yyyy-MM-dd HH:mm:ss} is not on a :15 boundary"); + item.Start.Second.ShouldBe(0, $"[{mode}] content item at {item.Start:yyyy-MM-dd HH:mm:ss} is not second-aligned"); + } + + // Explicit day-seam assertion: the first content item on each day after the first still lands on a + // boundary (this is precisely what regressed before the clamp fix, once per simulated midnight). + List firstOfEachDay = content + .GroupBy(i => i.Start.Date) + .OrderBy(g => g.Key) + .Select(g => g.OrderBy(i => i.Start).First()) + .ToList(); + foreach (PlayoutItem dayStart in firstOfEachDay.Skip(1)) + { + (dayStart.Start.Minute % 15).ShouldBe( + 0, + $"[{mode}] first content item of {dayStart.Start:yyyy-MM-dd} at {dayStart.Start:HH:mm:ss} resumed mid-interval"); + } + } + // Classic + PlaybackOrder.Shuffle: exercises PlayoutBuilder's call into the shuffle-source helper // (GetGroupedMediaItemsForShuffle) that #380 moves to ShuffleSourceBuilder, plus the wiring into // ShuffledMediaCollectionEnumerator. Unlike the chronological fixture, shuffle output depends on the @@ -1206,6 +1260,176 @@ public class PlayoutBuildGoldenTests TimeSpan.Zero); } + // #392: schedule-level pad + offline advance for a NON-One scheduler (Flood / Duration / Multiple). + // Same shape as SeedSchedulePaddedData (no item-level Pad filler, no FallbackFiller → offline), only the + // ProgramScheduleItem subtype differs. Reuses GetSchedulePaddedReferenceData for the build query. + private async Task> BuildSchedulePaddedModePlayout(string mode) + { + var cancellationToken = CancellationToken.None; + + int playoutId = await SeedSchedulePaddedModeData(cancellationToken, mode); + + var builder = new PlayoutBuilder( + new ConfigElementRepository(_dbContextFactory), + new MediaCollectionRepository(Substitute.For(), _dbContextFactory), + new TelevisionRepository(_dbContextFactory, NullLogger.Instance), + new ArtistRepository(_dbContextFactory), + Substitute.For(), + new MockFileSystem(), + Substitute.For(), + NullLogger.Instance); + + await using TvContext context = _dbContextFactory.CreateDbContext(); + + Playout playout = await context.Playouts + .Include(p => p.ProgramScheduleAnchors) + .ThenInclude(a => a.EnumeratorState) + .Include(p => p.FillGroupIndices) + .ThenInclude(fgi => fgi.EnumeratorState) + .SingleAsync(p => p.Id == playoutId, cancellationToken); + + PlayoutReferenceData referenceData = await GetSchedulePaddedReferenceData(context, playoutId); + + Either result = await builder.Build( + playout, + referenceData, + PlayoutBuildResult.Empty, + PlayoutBuildMode.Reset, + Start, + Start.AddDays(2), + cancellationToken); + + PlayoutBuildResult buildResult = result.Match( + r => r, + error => throw new AssertionException($"Build returned error: {error.Value}")); + + return buildResult.AddedItems; + } + + private async Task SeedSchedulePaddedModeData(CancellationToken cancellationToken, string mode) + { + await using TvContext context = _dbContextFactory.CreateDbContext(); + + // Per-mode suffix + GUID keep unique constraints from colliding across fixtures in the shared DB. + string guid = mode switch + { + "Flood" => "00000000-0000-0000-0000-00000000000a", + "Duration" => "00000000-0000-0000-0000-00000000000b", + "Multiple" => "00000000-0000-0000-0000-00000000000c", + _ => throw new ArgumentException($"Unsupported mode {mode}", nameof(mode)) + }; + + var path = new LibraryPath { Path = $"Schedule Padded Mode LibraryPath {mode}" }; + var library = new LocalLibrary + { + MediaKind = LibraryMediaKind.Movies, + Paths = new List { path }, + MediaSource = new LocalMediaSource() + }; + await context.Libraries.AddAsync(library, cancellationToken); + await context.SaveChangesAsync(cancellationToken); + + // Sub-15-min durations (7/11/13) so each padded item occupies exactly one :15 slot. This makes a + // whole :15-multiple block (Duration's 3h) tile exactly with no leftover — Duration therefore never + // packs a final item unpadded to fill the block (its fill-the-duration contract legitimately + // overrides per-item clock-pad when content straddles a :15, which would obscure the pad/seam signal + // this test is pinning). Every mode then holds the same strict boundary invariant. + int[] durationsMinutes = [7, 11, 13]; + var movies = new List(); + for (var i = 1; i <= 3; i++) + { + movies.Add(new Movie + { + MediaVersions = new List { new() { Duration = TimeSpan.FromMinutes(durationsMinutes[i - 1]) } }, + MovieMetadata = new List + { + new() { Title = $"Schedule Padded Mode Movie {mode} {i:D2}", ReleaseDate = new DateTime(2020, 1, 1).AddDays(i) } + }, + LibraryPath = path, + LibraryPathId = path.Id + }); + } + + await context.Movies.AddRangeAsync(movies, cancellationToken); + await context.SaveChangesAsync(cancellationToken); + + var contentCollection = new Collection + { + Name = $"Schedule Padded Mode Content Collection {mode}", + MediaItems = movies.Cast().ToList() + }; + await context.Collections.AddAsync(contentCollection, cancellationToken); + await context.SaveChangesAsync(cancellationToken); + + ProgramScheduleItem scheduleItem = mode switch + { + "Flood" => new ProgramScheduleItemFlood + { + Collection = contentCollection, + CollectionId = contentCollection.Id, + CollectionType = CollectionType.Collection, + PlaybackOrder = PlaybackOrder.Chronological + }, + "Duration" => new ProgramScheduleItemDuration + { + Collection = contentCollection, + CollectionId = contentCollection.Id, + CollectionType = CollectionType.Collection, + PlayoutDuration = TimeSpan.FromHours(3), + TailMode = TailMode.Offline, + PlaybackOrder = PlaybackOrder.Chronological + }, + "Multiple" => new ProgramScheduleItemMultiple + { + Collection = contentCollection, + CollectionId = contentCollection.Id, + CollectionType = CollectionType.Collection, + MultipleMode = MultipleMode.Count, + Count = "3", + PlaybackOrder = PlaybackOrder.Chronological + }, + _ => throw new ArgumentException($"Unsupported mode {mode}", nameof(mode)) + }; + + var scheduleItems = new List { scheduleItem }; + + var ffmpegProfile = new FFmpegProfile { Name = $"Schedule Padded Mode FFmpeg Profile {mode}" }; + await context.FFmpegProfiles.AddAsync(ffmpegProfile, cancellationToken); + await context.SaveChangesAsync(cancellationToken); + + var channel = new Channel(Guid.Parse(guid)) + { + Name = $"Schedule Padded Mode Channel {mode}", + Number = mode switch { "Flood" => "10", "Duration" => "11", _ => "12" }, + FFmpegProfile = ffmpegProfile, + FFmpegProfileId = ffmpegProfile.Id + }; + await context.Channels.AddAsync(channel, cancellationToken); + await context.SaveChangesAsync(cancellationToken); + + var schedule = new ProgramSchedule + { + Name = $"Schedule Padded Mode Schedule {mode}", + Items = scheduleItems, + PadToNearestMinute = 15 + }; + await context.ProgramSchedules.AddAsync(schedule, cancellationToken); + await context.SaveChangesAsync(cancellationToken); + + var playout = new Playout + { + Channel = channel, + ChannelId = channel.Id, + ProgramSchedule = schedule, + ProgramScheduleId = schedule.Id, + ScheduleKind = PlayoutScheduleKind.Classic + }; + await context.Playouts.AddAsync(playout, cancellationToken); + await context.SaveChangesAsync(cancellationToken); + + return playout.Id; + } + // --- Block builder --- // // BlockPlayoutBuilder maps template times-of-day to absolute instants via diff --git a/ErsatzTV.Core/Scheduling/PlayoutBuilder.cs b/ErsatzTV.Core/Scheduling/PlayoutBuilder.cs index 6c41ee242..496351e67 100644 --- a/ErsatzTV.Core/Scheduling/PlayoutBuilder.cs +++ b/ErsatzTV.Core/Scheduling/PlayoutBuilder.cs @@ -829,6 +829,12 @@ public class PlayoutBuilder : IPlayoutBuilder var timeCount = new Dictionary(); + // #392: exact clock-boundary target the LAST scheduled item advanced CurrentTime to when a + // schedule-level pad left an offline gap (no filler). The post-loop anchor clamp reads this by + // exact CurrentTime equality so the offline advance survives the day seam — precise (tied to the + // real offline-pad signal), not a magnitude heuristic. + DateTimeOffset? lastClockPadOfflineTarget = null; + // loop until we're done filling the desired amount of time while (playoutBuilderState.CurrentTime < playoutFinish && !cancellationToken.IsCancellationRequested) { @@ -903,6 +909,10 @@ public class PlayoutBuilder : IPlayoutBuilder (PlayoutBuilderState nextState, List playoutItems, PlayoutBuildWarnings warnings) = schedulerResult; + // #392: remember the last scheduler's offline-pad target (null unless the final scheduled item + // advanced CurrentTime to a clock boundary with no filler); the anchor clamp below reads it. + lastClockPadOfflineTarget = schedulerResult.ClockPadOfflineTarget; + result.Warnings.Merge(warnings); // if we completed a multiple/duration block, move to the next fill group @@ -949,14 +959,16 @@ public class PlayoutBuilder : IPlayoutBuilder { // #392: a schedule-level clock pad can legitimately advance CurrentTime past the last added // item with NO corresponding filler item (an intentional offline gap up to the next clock - // boundary). Bound the exemption to one pad interval so it can never mask an unrelated - // runaway CurrentTime; anything larger still gets clamped back to the real content end. - bool isBoundedOfflinePadAdvance = - activeSchedule.PadToNearestMinute is int scheduleMinutes && - scheduleMinutes > 0 && - playoutBuilderState.CurrentTime - maxStartTime <= TimeSpan.FromMinutes(scheduleMinutes); + // boundary). Exempt the clamp ONLY when CurrentTime is exactly the offline-pad target the + // final scheduled item recorded — a precise signal, not a magnitude heuristic. Any other + // advance (a Duration/Flood/Multiple block ending short of its natural end, a hard-stop, a + // tail-filler advance) changes CurrentTime away from that target, so it still clamps back to + // the real content end and persists the correct NextStart. + bool isOfflinePadAdvance = + lastClockPadOfflineTarget is { } offlinePadTarget && + playoutBuilderState.CurrentTime == offlinePadTarget; - if (!isBoundedOfflinePadAdvance) + if (!isOfflinePadAdvance) { playoutBuilderState = playoutBuilderState with { CurrentTime = maxStartTime }; } diff --git a/ErsatzTV.Core/Scheduling/PlayoutModeSchedulerDuration.cs b/ErsatzTV.Core/Scheduling/PlayoutModeSchedulerDuration.cs index bf9801d2b..0bda5911c 100644 --- a/ErsatzTV.Core/Scheduling/PlayoutModeSchedulerDuration.cs +++ b/ErsatzTV.Core/Scheduling/PlayoutModeSchedulerDuration.cs @@ -36,6 +36,7 @@ public class PlayoutModeSchedulerDuration(ILogger logger) var willFinishInTime = true; Option durationUntil = None; var discardAttempts = 0; + DateTimeOffset? clockPadOfflineTarget = null; IMediaCollectionEnumerator contentEnumerator = collectionEnumerators[CollectionKey.ForScheduleItem(scheduleItem)]; @@ -219,9 +220,11 @@ public class PlayoutModeSchedulerDuration(ILogger logger) // } DateTimeOffset itemEndTimeWithFiller = maybePlayoutItems.Max(pi => pi.FinishOffset); + DateTimeOffset? itemClockPadOfflineTarget = null; if (clockPadTarget is { } durPadTarget && durPadTarget > itemEndTimeWithFiller) { itemEndTimeWithFiller = durPadTarget; + itemClockPadOfflineTarget = durPadTarget; } willFinishInTime = itemStartTime > durationFinish || @@ -230,6 +233,7 @@ public class PlayoutModeSchedulerDuration(ILogger logger) { // LogScheduledItem(scheduleItem, mediaItem, itemStartTime); playoutItems.AddRange(maybePlayoutItems); + clockPadOfflineTarget = itemClockPadOfflineTarget; nextState = nextState with { @@ -354,7 +358,10 @@ public class PlayoutModeSchedulerDuration(ILogger logger) nextState = nextState with { NextGuideGroup = nextState.IncrementGuideGroup }; - return new PlayoutSchedulerResult(nextState, playoutItems, warnings); + return new PlayoutSchedulerResult(nextState, playoutItems, warnings) + { + ClockPadOfflineTarget = clockPadOfflineTarget + }; } protected override string SchedulingContextName => "Duration"; diff --git a/ErsatzTV.Core/Scheduling/PlayoutModeSchedulerFlood.cs b/ErsatzTV.Core/Scheduling/PlayoutModeSchedulerFlood.cs index 1df89fbee..3825d1856 100644 --- a/ErsatzTV.Core/Scheduling/PlayoutModeSchedulerFlood.cs +++ b/ErsatzTV.Core/Scheduling/PlayoutModeSchedulerFlood.cs @@ -23,6 +23,7 @@ public class PlayoutModeSchedulerFlood(ILogger logger) : PlayoutModeSchedulerBas PlayoutBuilderState nextState = playoutBuilderState; var willFinishInTime = true; + DateTimeOffset? clockPadOfflineTarget = null; IMediaCollectionEnumerator contentEnumerator = collectionEnumerators[CollectionKey.ForScheduleItem(scheduleItem)]; @@ -122,9 +123,11 @@ public class PlayoutModeSchedulerFlood(ILogger logger) : PlayoutModeSchedulerBas cancellationToken); DateTimeOffset itemEndTimeWithFiller = maybePlayoutItems.Max(pi => pi.FinishOffset); + DateTimeOffset? itemClockPadOfflineTarget = null; if (clockPadTarget is { } floodPadTarget && floodPadTarget > itemEndTimeWithFiller) { itemEndTimeWithFiller = floodPadTarget; + itemClockPadOfflineTarget = floodPadTarget; } // if the next schedule item is supposed to start during this item, @@ -135,6 +138,7 @@ public class PlayoutModeSchedulerFlood(ILogger logger) : PlayoutModeSchedulerBas if (willFinishInTime) { playoutItems.AddRange(maybePlayoutItems); + clockPadOfflineTarget = itemClockPadOfflineTarget; // LogScheduledItem(scheduleItem, mediaItem, itemStartTime); nextState = nextState with @@ -208,7 +212,10 @@ public class PlayoutModeSchedulerFlood(ILogger logger) : PlayoutModeSchedulerBas nextState = nextState with { NextGuideGroup = nextState.IncrementGuideGroup }; - return new PlayoutSchedulerResult(nextState, playoutItems, warnings); + return new PlayoutSchedulerResult(nextState, playoutItems, warnings) + { + ClockPadOfflineTarget = clockPadOfflineTarget + }; } protected override string SchedulingContextName => "Flood"; diff --git a/ErsatzTV.Core/Scheduling/PlayoutModeSchedulerMultiple.cs b/ErsatzTV.Core/Scheduling/PlayoutModeSchedulerMultiple.cs index 313b8ac92..a8735ad9c 100644 --- a/ErsatzTV.Core/Scheduling/PlayoutModeSchedulerMultiple.cs +++ b/ErsatzTV.Core/Scheduling/PlayoutModeSchedulerMultiple.cs @@ -77,6 +77,8 @@ public class PlayoutModeSchedulerMultiple(Map collectionItem } } + DateTimeOffset? clockPadOfflineTarget = null; + while (contentEnumerator.Current.IsSome && nextState.MultipleRemaining > 0 && nextState.CurrentTime < hardStop) { @@ -149,6 +151,11 @@ public class PlayoutModeSchedulerMultiple(Map collectionItem if (clockPadTarget is { } mulPadTarget && mulPadTarget > multipleEnd) { multipleEnd = mulPadTarget; + clockPadOfflineTarget = mulPadTarget; + } + else + { + clockPadOfflineTarget = null; } nextState = nextState with @@ -211,7 +218,10 @@ public class PlayoutModeSchedulerMultiple(Map collectionItem nextState = nextState with { NextGuideGroup = nextState.IncrementGuideGroup }; - return new PlayoutSchedulerResult(nextState, playoutItems, warnings); + return new PlayoutSchedulerResult(nextState, playoutItems, warnings) + { + ClockPadOfflineTarget = clockPadOfflineTarget + }; } protected override string SchedulingContextName => "Multiple"; diff --git a/ErsatzTV.Core/Scheduling/PlayoutModeSchedulerOne.cs b/ErsatzTV.Core/Scheduling/PlayoutModeSchedulerOne.cs index 4c3b089b6..1cf0251e2 100644 --- a/ErsatzTV.Core/Scheduling/PlayoutModeSchedulerOne.cs +++ b/ErsatzTV.Core/Scheduling/PlayoutModeSchedulerOne.cs @@ -92,9 +92,11 @@ public class PlayoutModeSchedulerOne(ILogger logger) : PlayoutModeSchedulerBase< cancellationToken); DateTimeOffset oneEnd = playoutItems.Max(pi => pi.FinishOffset); + DateTimeOffset? clockPadOfflineTarget = null; if (clockPadTarget is { } onePadTarget && onePadTarget > oneEnd) { oneEnd = onePadTarget; + clockPadOfflineTarget = onePadTarget; } PlayoutBuilderState nextState = playoutBuilderState with @@ -139,7 +141,10 @@ public class PlayoutModeSchedulerOne(ILogger logger) : PlayoutModeSchedulerBase< nextState = nextState with { NextGuideGroup = nextState.IncrementGuideGroup }; - return new PlayoutSchedulerResult(nextState, playoutItems, warnings); + return new PlayoutSchedulerResult(nextState, playoutItems, warnings) + { + ClockPadOfflineTarget = clockPadOfflineTarget + }; } return new PlayoutSchedulerResult(playoutBuilderState, [], warnings); diff --git a/ErsatzTV.Core/Scheduling/PlayoutSchedulerResult.cs b/ErsatzTV.Core/Scheduling/PlayoutSchedulerResult.cs index 6a2b50d04..1f9f30967 100644 --- a/ErsatzTV.Core/Scheduling/PlayoutSchedulerResult.cs +++ b/ErsatzTV.Core/Scheduling/PlayoutSchedulerResult.cs @@ -5,4 +5,11 @@ namespace ErsatzTV.Core.Scheduling; public record PlayoutSchedulerResult( PlayoutBuilderState State, List PlayoutItems, - PlayoutBuildWarnings Warnings); + PlayoutBuildWarnings Warnings) +{ + // #392: the exact clock-boundary target the last scheduled item advanced CurrentTime to when a + // schedule-level pad left an OFFLINE gap (no filler emitted). Non-null ONLY for such an advance; the + // day-boundary anchor clamp in PlayoutBuilder reads it (by exact CurrentTime equality) so an offline + // pad advance survives the seam. Transient/in-memory only — never serialized to the PlayoutAnchor. + public DateTimeOffset? ClockPadOfflineTarget { get; init; } +}