diff --git a/src/Radiosender/Models/ScheduleItem.cs b/src/Radiosender/Models/ScheduleItem.cs index acf506d..e8e2d5a 100644 --- a/src/Radiosender/Models/ScheduleItem.cs +++ b/src/Radiosender/Models/ScheduleItem.cs @@ -12,4 +12,13 @@ public enum ScheduleItemKind public record ScheduleItem(ScheduleItemKind Kind, string Title, DateTime Start, TimeSpan Duration, Song? Song = null) { public DateTime End => Start + Duration; + + /// The kind as the user reads it. + public string KindName => Kind switch + { + ScheduleItemKind.News => "Nachrichten", + ScheduleItemKind.Ad => "Werbung", + ScheduleItemKind.Moderator => "Moderation", + _ => "Song", + }; } diff --git a/src/Radiosender/Services/ScheduleGenerator.cs b/src/Radiosender/Services/ScheduleGenerator.cs index 358165a..596c179 100644 --- a/src/Radiosender/Services/ScheduleGenerator.cs +++ b/src/Radiosender/Services/ScheduleGenerator.cs @@ -6,71 +6,115 @@ public record ScheduleOptions { public TimeSpan NewsDuration { get; init; } = TimeSpan.FromMinutes(5); - /// Upper limit for ads and moderator talk together, per hour. - public TimeSpan MaxFillerPerHour { get; init; } = TimeSpan.FromMinutes(20); + /// Target for ads per hour. Met as closely as the song lengths allow. + public TimeSpan AdsPerHour { get; init; } = TimeSpan.FromMinutes(20); - /// Ads and moderator talk planned at least per half hour, so the music is broken up. - public TimeSpan MinFillerPerHalfHour { get; init; } = TimeSpan.FromMinutes(2); + /// Target for moderator talk per hour. Met as closely as the song lengths allow. + public TimeSpan ModeratorPerHour { get; init; } = TimeSpan.FromMinutes(10); - /// Longest run of consecutive ad items. Must be below 20 minutes. + /// Longest single ad item; longer ad time is split and separated by moderator talk or songs. public TimeSpan MaxAdBlock { get; init; } = TimeSpan.FromMinutes(5); - /// Random song picks tried per half hour before giving up. - public int Attempts { get; init; } = 1000; + /// Random song picks tried per half hour; the one closest to the targets wins. + public int Attempts { get; init; } = 400; } public class ScheduleException(string message) : Exception(message); /// -/// Builds the plan in half-hour slots: news at :00 and :30, then random songs, with ads and -/// moderator talk sized so that the last song of each slot ends exactly when the next news starts. +/// Builds the plan in half-hour slots: news at :00 and :30, then random songs with ads and moderator talk +/// in between. The last song of each slot ends exactly when the next news starts, so the ad and moderator +/// time is whatever the songs leave; the generator picks songs that leave as close to the targets as it can +/// and evens out the difference in the second half of the hour. +/// A start between two news times gets a lead-in without news up to the next :00 or :30. /// public class ScheduleGenerator(ScheduleOptions options, Random random) { + /// Can be replaced at any time, e.g. from the settings page; the next plan uses the new values. + public ScheduleOptions Options { get; set; } = options; + private static readonly TimeSpan HalfHour = TimeSpan.FromMinutes(30); + // A pick that misses the target by this little is taken at once. + private static readonly TimeSpan CloseEnough = TimeSpan.FromSeconds(1); + public ScheduleGenerator() : this(new ScheduleOptions(), Random.Shared) { } + /// + /// Plans full hours. They begin at if that is :00 or :30, + /// otherwise at the next :00 or :30 after a lead-in of music. + /// public IReadOnlyList Generate(DateTime start, int hours, IReadOnlyList songs) { + var options = Options; // one consistent set of values for the whole plan if (hours < 1) throw new ArgumentOutOfRangeException(nameof(hours), "At least one full hour is required."); - if (start.Minute != 0 || start.Second != 0 || start.Millisecond != 0 || start.Microsecond != 0) - throw new ArgumentException("The schedule must start at a full hour.", nameof(start)); if (options.MaxAdBlock <= TimeSpan.Zero || options.MaxAdBlock >= TimeSpan.FromMinutes(20)) throw new ArgumentException("MaxAdBlock must be between 0 and 20 minutes.", nameof(options)); var playable = songs.Where(s => s.Duration > TimeSpan.Zero).ToList(); if (playable.Count == 0) - throw new ScheduleException("The music library has no songs to plan with."); + throw new ScheduleException("Die Bibliothek enthält keine Songs zum Planen."); var items = new List(); - for (var slotStart = start; slotStart < start.AddHours(hours); slotStart += HalfHour) + var firstNews = new DateTime((start.Ticks + HalfHour.Ticks - 1) / HalfHour.Ticks * HalfHour.Ticks, start.Kind); + if (firstNews > start) + items.AddRange(BuildLeadIn(options, start, firstNews - start, playable)); + + var adHalf = options.AdsPerHour / 2; + var moderatorHalf = options.ModeratorPerHour / 2; + // How far the :00 slot ended up over (or under) its half of the hour; the :30 slot makes up for it. + var adOver = TimeSpan.Zero; + var moderatorOver = TimeSpan.Zero; + for (var slotStart = firstNews; slotStart < firstNews.AddHours(hours); slotStart += HalfHour) { - items.Add(new ScheduleItem(ScheduleItemKind.News, "News", slotStart, options.NewsDuration)); - items.AddRange(BuildSlot(slotStart + options.NewsDuration, HalfHour - options.NewsDuration, playable)); + if (slotStart.Minute == 0) + adOver = moderatorOver = TimeSpan.Zero; + + var news = Min(options.NewsDuration, HalfHour); + if (news > TimeSpan.Zero) + items.Add(new ScheduleItem(ScheduleItemKind.News, "", slotStart, news)); + var slot = BuildSlot(options, slotStart + news, HalfHour - news, + Max(adHalf - adOver, TimeSpan.Zero), Max(moderatorHalf - moderatorOver, TimeSpan.Zero), playable); + items.AddRange(slot); + + adOver = Sum(slot.Where(i => i.Kind == ScheduleItemKind.Ad)) - adHalf; + moderatorOver = Sum(slot.Where(i => i.Kind == ScheduleItemKind.Moderator)) - moderatorHalf; } return items; } - private List BuildSlot(DateTime slotStart, TimeSpan length, List songs) + private List BuildLeadIn(ScheduleOptions options, DateTime start, TimeSpan length, List songs) { - // Half of the hourly limit per slot keeps every hour within MaxFillerPerHour. - var maxFiller = options.MaxFillerPerHour / 2; - var minFiller = options.MinFillerPerHalfHour < maxFiller ? options.MinFillerPerHalfHour : maxFiller; - - for (var attempt = 0; attempt < options.Attempts; attempt++) + // The targets shrink with the lead-in: half of a half hour gets half of the ads. + var share = length / HalfHour; + try { - var picked = PickSongs(length - minFiller, songs); - var gap = length - Sum(picked); - if (picked.Count > 0 && gap <= maxFiller) - return Arrange(slotStart, picked, BuildFiller(gap)); + return BuildSlot(options, start, length, options.AdsPerHour / 2 * share, options.ModeratorPerHour / 2 * share, songs); } + catch (ScheduleException) when (length <= (options.AdsPerHour + options.ModeratorPerHour) / 2) + { + // Too short for any song: the moderator talks until the news. + return [new ScheduleItem(ScheduleItemKind.Moderator, "", start, length)]; + } + } - throw new ScheduleException( - $"No combination of songs fills the slot at {slotStart:HH:mm} so that the last song ends on time. Add more songs, especially shorter ones."); + private List BuildSlot( + ScheduleOptions options, DateTime slotStart, TimeSpan length, TimeSpan adTarget, TimeSpan moderatorTarget, List songs) + { + if (length <= TimeSpan.Zero) + return []; + var target = Min(adTarget + moderatorTarget, length); + var (picked, gap) = PickBest(options, length, target, songs); + // No song at all is only right when the targets leave no room for music. + if (picked.Count == 0 && target < length) + throw new ScheduleException( + $"Keine Song-Kombination füllt den Abschnitt ab {slotStart:HH:mm} so, dass der letzte Song pünktlich endet. Mehr Songs hinzufügen, vor allem kürzere."); + + var (ads, moderator) = Split(options, gap, adTarget, moderatorTarget); + return Arrange(options, slotStart, picked, ads, moderator, keepFirstSongFirst: false); } /// @@ -78,15 +122,15 @@ public class ScheduleGenerator(ScheduleOptions options, Random random) /// rebuilds the rest of its half-hour slot, so the last song still ends exactly when the next news starts. /// Items before and all later slots stay as they are. /// - /// The song does not fit before the next news, or the rest cannot be filled. + /// The song does not fit before the next news. public IReadOnlyList Replace(IReadOnlyList plan, int index, Song requested, IReadOnlyList songs) { ArgumentOutOfRangeException.ThrowIfNegative(index); ArgumentOutOfRangeException.ThrowIfGreaterThanOrEqual(index, plan.Count); if (plan[index].Kind == ScheduleItemKind.News) - throw new ScheduleException("News cannot be replaced."); + throw new ScheduleException("Nachrichten können nicht ersetzt werden."); if (requested.Duration <= TimeSpan.Zero) - throw new ScheduleException("The requested song has no duration."); + throw new ScheduleException("Der gewünschte Song hat keine Dauer."); var slotStartIndex = LastIndexOf(plan, index, ScheduleItemKind.News); // -1 if the plan does not start with news var nextNewsIndex = IndexOf(plan, index, ScheduleItemKind.News); @@ -96,27 +140,20 @@ public class ScheduleGenerator(ScheduleOptions options, Random random) if (requested.Duration > length) throw new ScheduleException( - $"\"{requested.Title}\" ({requested.Duration:m\\:ss}) does not fit before the news at {slotEnd:HH:mm}; only {length:m\\:ss} are left. Choose an earlier item."); + $"\"{requested.Title}\" ({requested.Duration:m\\:ss}) passt nicht vor die Nachrichten um {slotEnd:HH:mm}; es sind nur noch {length:m\\:ss} übrig. Ein früheres Element wählen."); + // What the slot has already spent on ads and moderator talk before the request counts against its targets. + var options = Options; var prefix = plan.Take(index).ToList(); - var prefixFiller = Sum(prefix.Skip(slotStartIndex + 1).Where(i => i.Kind is ScheduleItemKind.Ad or ScheduleItemKind.Moderator)); - var maxGap = options.MaxFillerPerHour / 2 - prefixFiller; + var slotPrefix = prefix.Skip(slotStartIndex + 1).ToList(); + var adTarget = Max(options.AdsPerHour / 2 - Sum(slotPrefix.Where(i => i.Kind == ScheduleItemKind.Ad)), TimeSpan.Zero); + var moderatorTarget = Max(options.ModeratorPerHour / 2 - Sum(slotPrefix.Where(i => i.Kind == ScheduleItemKind.Moderator)), TimeSpan.Zero); var playable = songs.Where(s => s.Duration > TimeSpan.Zero).ToList(); - var startWithAd = prefix.Count == 0 || prefix[^1].Kind != ScheduleItemKind.Ad; - for (var attempt = 0; attempt < options.Attempts; attempt++) - { - List picked = [requested, .. PickSongs(length - requested.Duration, playable, requested)]; - var gap = length - Sum(picked); - if (gap <= maxGap) - { - IEnumerable rest = nextNewsIndex < 0 ? [] : plan.Skip(nextNewsIndex); - return [.. prefix, .. Arrange(start, picked, BuildFiller(gap, startWithAd)), .. rest]; - } - } - - throw new ScheduleException( - $"After \"{requested.Title}\" the slot up to {slotEnd:HH:mm} cannot be filled without exceeding the ad limit. Choose another item or song."); + var (picked, gap) = PickBest(options, length, Min(adTarget + moderatorTarget, length), playable, requested); + var (ads, moderator) = Split(options, gap, adTarget, moderatorTarget); + IEnumerable rest = nextNewsIndex < 0 ? [] : plan.Skip(nextNewsIndex); + return [.. prefix, .. Arrange(options, start, picked, ads, moderator, keepFirstSongFirst: true), .. rest]; } private static int IndexOf(IReadOnlyList plan, int from, ScheduleItemKind kind) @@ -133,6 +170,27 @@ public class ScheduleGenerator(ScheduleOptions options, Random random) return -1; } + // Tries random song picks and keeps the one whose leftover time is closest to the target for ads and + // moderator talk. Picks never go over the music time, so the leftover is the target or more. + private (List Songs, TimeSpan Gap) PickBest( + ScheduleOptions options, TimeSpan length, TimeSpan target, List songs, Song? first = null) + { + var fixedTime = first?.Duration ?? TimeSpan.Zero; + var budget = Max(length - fixedTime - target, TimeSpan.Zero); + (List Songs, TimeSpan Gap)? best = null; + for (var attempt = 0; attempt < options.Attempts; attempt++) + { + var more = PickSongs(budget, songs, first); + List picked = first is null ? more : [first, .. more]; + var gap = length - Sum(picked); + if (best is null || gap < best.Value.Gap) + best = (picked, gap); + if (gap - target <= CloseEnough || budget == TimeSpan.Zero) + break; + } + return best ?? ([], length); + } + private List PickSongs(TimeSpan budget, List songs, Song? previous = null) { var picked = new List(); @@ -149,52 +207,95 @@ public class ScheduleGenerator(ScheduleOptions options, Random random) } } - // Alternates ad and moderator items, so ads never run back to back. - private List<(ScheduleItemKind Kind, string Title, TimeSpan Duration)> BuildFiller(TimeSpan gap, bool startWithAd = true) + // Shares the leftover time between ads and moderator talk in the ratio of their targets. + private static (TimeSpan Ads, TimeSpan Moderator) Split(ScheduleOptions options, TimeSpan gap, TimeSpan adTarget, TimeSpan moderatorTarget) { - var filler = new List<(ScheduleItemKind, string, TimeSpan)>(); - var nextIsAd = startWithAd; - while (gap > TimeSpan.Zero) + if (adTarget + moderatorTarget <= TimeSpan.Zero) { - (ScheduleItemKind kind, string title, TimeSpan duration) = nextIsAd - ? Pick(PlaceholderContent.AdSpots, a => (ScheduleItemKind.Ad, a.Title, Min(a.Duration, options.MaxAdBlock))) - : Pick(PlaceholderContent.ModeratorSegments, m => (ScheduleItemKind.Moderator, m.Title, m.Duration)); - duration = Min(duration, gap); // shortcut: the last placeholder is cut to fit; fine while they have no audio - filler.Add((kind, title, duration)); - gap -= duration; - nextIsAd = !nextIsAd; + // This slot has nothing left to aim for; fall back to the hourly ratio, or to talk alone. + adTarget = options.AdsPerHour; + moderatorTarget = options.ModeratorPerHour; + if (adTarget + moderatorTarget <= TimeSpan.Zero) + return (TimeSpan.Zero, gap); } - return filler; + var ads = TimeSpan.FromSeconds(Math.Round(gap.TotalSeconds * (adTarget / (adTarget + moderatorTarget)))); + ads = Min(ads, gap); + return (ads, gap - ads); } - // Spreads the filler between songs; the slot always ends with a song. - private static List Arrange(DateTime start, List songs, List<(ScheduleItemKind Kind, string Title, TimeSpan Duration)> filler) + // Lays out the slot: songs with breaks in between, each break "moderator, ad, moderator, ad ...". + // Ads are cut into pieces of at most MaxAdBlock and never follow each other directly as long as there + // is moderator talk or a song to put between them. The slot always ends with a song. + private static List Arrange( + ScheduleOptions options, DateTime start, List songs, TimeSpan ads, TimeSpan moderator, bool keepFirstSongFirst) { + var adPieces = Pieces(ads, (int)Math.Ceiling(ads / options.MaxAdBlock)); + // One moderator piece in front of every ad piece; without ads, one piece per five minutes of talk. + var moderatorPieces = Pieces(moderator, adPieces.Count > 0 ? adPieces.Count : (int)Math.Ceiling(moderator / TimeSpan.FromMinutes(5))); + var pairs = Math.Max(adPieces.Count, moderatorPieces.Count); + + // A hot swap keeps the requested song at its position, so breaks start after it when another song follows. + var firstBreakSong = keepFirstSongFirst && songs.Count > 1 ? 1 : 0; + var breakSlots = Math.Max(songs.Count - firstBreakSong, 1); + var breaks = Math.Min(pairs, breakSlots); + var items = new List(); var time = start; - var fillerIndex = 0; + void Add(ScheduleItemKind kind, TimeSpan duration, Song? song = null) + { + if (duration <= TimeSpan.Zero) + return; + // News, ads and moderator items start without a title; the user can name them in the timeline. + var title = song is null ? "" : string.IsNullOrWhiteSpace(song.Artist) ? song.Title : $"{song.Artist} - {song.Title}"; + items.Add(new ScheduleItem(kind, title, time, duration, song)); + time += duration; + } + + var pair = 0; + void AddBreak(int number) + { + // Pairs are dealt out evenly; the last break takes what is left. + var until = number == breaks - 1 ? pairs : pairs * (number + 1) / breaks; + for (; pair < until; pair++) + { + if (pair < moderatorPieces.Count) Add(ScheduleItemKind.Moderator, moderatorPieces[pair]); + if (pair < adPieces.Count) Add(ScheduleItemKind.Ad, adPieces[pair]); + } + } + + var nextBreak = 0; for (var i = 0; i < songs.Count; i++) { - // Filler goes before song i; the share grows with i so it ends up spread over the slot. - var until = filler.Count * (i + 1) / songs.Count; - for (; fillerIndex < until; fillerIndex++) - { - var f = filler[fillerIndex]; - items.Add(new ScheduleItem(f.Kind, f.Title, time, f.Duration)); - time += f.Duration; - } - var title = string.IsNullOrWhiteSpace(songs[i].Artist) ? songs[i].Title : $"{songs[i].Artist} - {songs[i].Title}"; - items.Add(new ScheduleItem(ScheduleItemKind.Song, title, time, songs[i].Duration, songs[i])); - time += songs[i].Duration; + // Break n sits before the song at its share of the way through the slot. + while (nextBreak < breaks && i == firstBreakSong + nextBreak * breakSlots / breaks) + AddBreak(nextBreak++); + Add(ScheduleItemKind.Song, songs[i].Duration, songs[i]); } + // No songs at all: the slot is ads and talk only. + while (nextBreak < breaks) + AddBreak(nextBreak++); return items; } - private T Pick(IReadOnlyList source, Func map) => map(source[random.Next(source.Count)]); + // Cuts a time into pieces of whole seconds that differ by at most one second, so no piece grows past + // the limit the count was chosen for. A fraction of a second goes to the last piece. + private static List Pieces(TimeSpan total, int count) + { + var pieces = new List(); + if (total <= TimeSpan.Zero || count < 1) + return pieces; + var seconds = (long)Math.Floor(total.TotalSeconds); + for (var i = 0; i < count; i++) + pieces.Add(TimeSpan.FromSeconds(seconds / count + (i < seconds % count ? 1 : 0))); + pieces[^1] += total - TimeSpan.FromSeconds(seconds); + return pieces; + } private static TimeSpan Sum(IEnumerable songs) => songs.Aggregate(TimeSpan.Zero, (total, s) => total + s.Duration); private static TimeSpan Sum(IEnumerable items) => items.Aggregate(TimeSpan.Zero, (total, i) => total + i.Duration); private static TimeSpan Min(TimeSpan a, TimeSpan b) => a < b ? a : b; + + private static TimeSpan Max(TimeSpan a, TimeSpan b) => a > b ? a : b; } diff --git a/tests/Radiosender.Tests/ScheduleGeneratorTests.cs b/tests/Radiosender.Tests/ScheduleGeneratorTests.cs index d96323d..550146a 100644 --- a/tests/Radiosender.Tests/ScheduleGeneratorTests.cs +++ b/tests/Radiosender.Tests/ScheduleGeneratorTests.cs @@ -75,21 +75,29 @@ public class ScheduleGeneratorTests } } + private static TimeSpan Total(IEnumerable items, ScheduleItemKind kind) => + TimeSpan.FromTicks(items.Where(i => i.Kind == kind).Sum(i => i.Duration.Ticks)); + + // The targets are met as closely as the songs allow; with this library that is within a few seconds per hour. + private static readonly TimeSpan TargetTolerance = TimeSpan.FromSeconds(15); + + private static void AssertNear(TimeSpan expected, TimeSpan actual, string what) => + Assert.True((actual - expected).Duration() <= TargetTolerance, $"{what}: {actual}, target {expected}"); + [Theory] [MemberData(nameof(Seeds))] - public void AdsAndModeratorStayWithinTwentyMinutesPerHour(int seed) + public void AdsAndModeratorMeetTheirTargetsPerHour(int seed) { + var options = new ScheduleOptions(); var items = Generate(seed); for (var hour = 0; hour < 3; hour++) { var from = Start.AddHours(hour); - var filler = items - .Where(i => i.Start >= from && i.Start < from.AddHours(1)) - .Where(i => i.Kind is ScheduleItemKind.Ad or ScheduleItemKind.Moderator) - .Aggregate(TimeSpan.Zero, (sum, i) => sum + i.Duration); + var inHour = items.Where(i => i.Start >= from && i.Start < from.AddHours(1)).ToList(); - Assert.InRange(filler, TimeSpan.FromMinutes(2), TimeSpan.FromMinutes(20)); + AssertNear(options.AdsPerHour, Total(inHour, ScheduleItemKind.Ad), $"ads in hour {hour}"); + AssertNear(options.ModeratorPerHour, Total(inHour, ScheduleItemKind.Moderator), $"moderator in hour {hour}"); } } @@ -97,6 +105,7 @@ public class ScheduleGeneratorTests [MemberData(nameof(Seeds))] public void NoAdBlockIsLongerThanTheConfiguredMaximum(int seed) { + // Moderator talk separates the ad pieces, so ten one-minute ads per half hour never run together. var options = new ScheduleOptions { MaxAdBlock = TimeSpan.FromMinutes(1) }; var block = TimeSpan.Zero; @@ -133,13 +142,87 @@ public class ScheduleGeneratorTests Assert.Throws(() => generator.Generate(Start, 1, [])); } + [Theory] + [MemberData(nameof(Seeds))] + public void Generate_FromAnOddTimeLeadsInWithMusicUpToTheFirstNews(int seed) + { + var start = Start.AddMinutes(37).AddSeconds(12); + var items = new ScheduleGenerator(new ScheduleOptions(), new Random(seed)).Generate(start, 1, Library); + + Assert.Equal(start, items[0].Start); + for (var i = 1; i < items.Count; i++) + Assert.Equal(items[i - 1].End, items[i].Start); + var firstNews = items.ToList().FindIndex(i => i.Kind == ScheduleItemKind.News); + Assert.Equal(Start.AddHours(1), items[firstNews].Start); + Assert.Equal(ScheduleItemKind.Song, items[firstNews - 1].Kind); + Assert.Equal(Start.AddHours(2), items[^1].End); + } + + [Fact] + public void Generate_FillsALeadInTooShortForASongWithModeratorTalk() + { + var start = Start.AddMinutes(28); + var items = new ScheduleGenerator(new ScheduleOptions(), new Random(1)).Generate(start, 1, Library); + + Assert.Equal(ScheduleItemKind.Moderator, items[0].Kind); + Assert.Equal(TimeSpan.FromMinutes(2), items[0].Duration); + Assert.Equal(ScheduleItemKind.News, items[1].Kind); + Assert.Equal(Start.AddMinutes(90), items[^1].End); + } + + [Fact] + public void Generate_LeavesNewsAdAndModeratorTitlesEmpty() + { + var items = Generate(1); + + Assert.All(items, i => Assert.Equal(i.Kind != ScheduleItemKind.Song, i.Title.Length == 0)); + } + + [Theory] + [MemberData(nameof(Seeds))] + public void Generate_FollowsChangedTargets(int seed) + { + var options = new ScheduleOptions + { + NewsDuration = TimeSpan.FromMinutes(3), + AdsPerHour = TimeSpan.FromMinutes(4), + ModeratorPerHour = TimeSpan.FromMinutes(12), + }; + var items = Generate(seed, hours: 2, options); + + Assert.All(items.Where(i => i.Kind == ScheduleItemKind.News), n => Assert.Equal(TimeSpan.FromMinutes(3), n.Duration)); + for (var hour = 0; hour < 2; hour++) + { + var inHour = items.Where(i => i.Start >= Start.AddHours(hour) && i.Start < Start.AddHours(hour + 1)).ToList(); + AssertNear(options.AdsPerHour, Total(inHour, ScheduleItemKind.Ad), $"ads in hour {hour}"); + AssertNear(options.ModeratorPerHour, Total(inHour, ScheduleItemKind.Moderator), $"moderator in hour {hour}"); + } + Assert.Equal(Start.AddHours(2), items[^1].End); + } + + [Fact] + public void Generate_FillsAnHourWithoutMusicWhenTheTargetsTakeAllOfIt() + { + var options = new ScheduleOptions + { + NewsDuration = TimeSpan.FromMinutes(5), + AdsPerHour = TimeSpan.FromMinutes(20), + ModeratorPerHour = TimeSpan.FromMinutes(30), + }; + var items = Generate(1, hours: 1, options); + + Assert.DoesNotContain(items, i => i.Kind == ScheduleItemKind.Song); + Assert.Equal(TimeSpan.FromMinutes(20), Total(items, ScheduleItemKind.Ad)); + Assert.Equal(TimeSpan.FromMinutes(30), Total(items, ScheduleItemKind.Moderator)); + Assert.Equal(Start.AddHours(1), items[^1].End); + } + [Fact] public void Generate_RejectsInvalidInput() { var generator = new ScheduleGenerator(new ScheduleOptions(), new Random(1)); Assert.Throws(() => generator.Generate(Start, 0, Library)); - Assert.Throws(() => generator.Generate(Start.AddMinutes(15), 1, Library)); Assert.Throws(() => new ScheduleGenerator(new ScheduleOptions { MaxAdBlock = TimeSpan.FromMinutes(20) }, new Random(1)).Generate(Start, 1, Library)); } @@ -171,7 +254,7 @@ public class ScheduleGeneratorTests [Theory] [MemberData(nameof(Seeds))] - public void Replace_KeepsFillerLimitsAndNoAdsBackToBack(int seed) + public void Replace_KeepsTheSlotOnTimeAndNoAdsBackToBack(int seed) { var plan = Generate(seed, hours: 1); // Every non-news item in the first half hour, so prefixes with filler are covered too. @@ -182,9 +265,7 @@ public class ScheduleGeneratorTests try { swapped = Generator(seed).Replace(plan, index, Request, Library); } catch (ScheduleException) { continue; } // too little time left before the news - var filler = swapped.Where(i => i.Kind is ScheduleItemKind.Ad or ScheduleItemKind.Moderator) - .Aggregate(TimeSpan.Zero, (sum, i) => sum + i.Duration); - Assert.True(filler <= TimeSpan.FromMinutes(20), $"{filler} filler after swap at {index}"); + Assert.Equal(plan[^1].End, swapped[^1].End); for (var i = 1; i < swapped.Count; i++) Assert.False(swapped[i - 1].Kind == ScheduleItemKind.Ad && swapped[i].Kind == ScheduleItemKind.Ad, $"Ads back to back at {swapped[i].Start:HH:mm:ss}"); @@ -199,7 +280,7 @@ public class ScheduleGeneratorTests var tooLong = Song(98, 25 * 60); var ex = Assert.Throws(() => Generator(1).Replace(plan, beforeNews, tooLong, Library)); - Assert.Contains("does not fit", ex.Message); + Assert.Contains("passt nicht", ex.Message); } [Fact]