feat(schedule): aim for target minutes and plan from any start time

The generator takes targets for ads and moderator talk per hour. It tries
several hundred random song picks per half hour, keeps the one that leaves
closest to the target, and lets the second half hour make up for the first.
A start between two news times gets a lead-in of music. News, ad and
moderator items start without a title.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
fraujulianandClaude Fable 5.2 committed 2026-11-23 14:22:46 +01:00
1 parent e5c4d0e720
commit 5193427629
3 files changed
+278 -87

No files matched your search

+9
View File
@@ -12,4 +12,13 @@ public enum ScheduleItemKind
public record ScheduleItem(ScheduleItemKind Kind, string Title, DateTime Start, TimeSpan Duration, Song? Song = null) public record ScheduleItem(ScheduleItemKind Kind, string Title, DateTime Start, TimeSpan Duration, Song? Song = null)
{ {
public DateTime End => Start + Duration; public DateTime End => Start + Duration;
/// <summary>The kind as the user reads it.</summary>
public string KindName => Kind switch
{
ScheduleItemKind.News => "Nachrichten",
ScheduleItemKind.Ad => "Werbung",
ScheduleItemKind.Moderator => "Moderation",
_ => "Song",
};
} }
+176 -75
View File
@@ -6,71 +6,115 @@ public record ScheduleOptions
{ {
public TimeSpan NewsDuration { get; init; } = TimeSpan.FromMinutes(5); public TimeSpan NewsDuration { get; init; } = TimeSpan.FromMinutes(5);
/// <summary>Upper limit for ads and moderator talk together, per hour.</summary> /// <summary>Target for ads per hour. Met as closely as the song lengths allow.</summary>
public TimeSpan MaxFillerPerHour { get; init; } = TimeSpan.FromMinutes(20); public TimeSpan AdsPerHour { get; init; } = TimeSpan.FromMinutes(20);
/// <summary>Ads and moderator talk planned at least per half hour, so the music is broken up.</summary> /// <summary>Target for moderator talk per hour. Met as closely as the song lengths allow.</summary>
public TimeSpan MinFillerPerHalfHour { get; init; } = TimeSpan.FromMinutes(2); public TimeSpan ModeratorPerHour { get; init; } = TimeSpan.FromMinutes(10);
/// <summary>Longest run of consecutive ad items. Must be below 20 minutes.</summary> /// <summary>Longest single ad item; longer ad time is split and separated by moderator talk or songs.</summary>
public TimeSpan MaxAdBlock { get; init; } = TimeSpan.FromMinutes(5); public TimeSpan MaxAdBlock { get; init; } = TimeSpan.FromMinutes(5);
/// <summary>Random song picks tried per half hour before giving up.</summary> /// <summary>Random song picks tried per half hour; the one closest to the targets wins.</summary>
public int Attempts { get; init; } = 1000; public int Attempts { get; init; } = 400;
} }
public class ScheduleException(string message) : Exception(message); public class ScheduleException(string message) : Exception(message);
/// <summary> /// <summary>
/// Builds the plan in half-hour slots: news at :00 and :30, then random songs, with ads and /// Builds the plan in half-hour slots: news at :00 and :30, then random songs with ads and moderator talk
/// moderator talk sized so that the last song of each slot ends exactly when the next news starts. /// 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.
/// </summary> /// </summary>
public class ScheduleGenerator(ScheduleOptions options, Random random) public class ScheduleGenerator(ScheduleOptions options, Random random)
{ {
/// <summary>Can be replaced at any time, e.g. from the settings page; the next plan uses the new values.</summary>
public ScheduleOptions Options { get; set; } = options;
private static readonly TimeSpan HalfHour = TimeSpan.FromMinutes(30); 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) public ScheduleGenerator() : this(new ScheduleOptions(), Random.Shared)
{ {
} }
/// <summary>
/// Plans <paramref name="hours"/> full hours. They begin at <paramref name="start"/> if that is :00 or :30,
/// otherwise at the next :00 or :30 after a lead-in of music.
/// </summary>
public IReadOnlyList<ScheduleItem> Generate(DateTime start, int hours, IReadOnlyList<Song> songs) public IReadOnlyList<ScheduleItem> Generate(DateTime start, int hours, IReadOnlyList<Song> songs)
{ {
var options = Options; // one consistent set of values for the whole plan
if (hours < 1) if (hours < 1)
throw new ArgumentOutOfRangeException(nameof(hours), "At least one full hour is required."); 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)) if (options.MaxAdBlock <= TimeSpan.Zero || options.MaxAdBlock >= TimeSpan.FromMinutes(20))
throw new ArgumentException("MaxAdBlock must be between 0 and 20 minutes.", nameof(options)); throw new ArgumentException("MaxAdBlock must be between 0 and 20 minutes.", nameof(options));
var playable = songs.Where(s => s.Duration > TimeSpan.Zero).ToList(); var playable = songs.Where(s => s.Duration > TimeSpan.Zero).ToList();
if (playable.Count == 0) 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<ScheduleItem>(); var items = new List<ScheduleItem>();
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)); if (slotStart.Minute == 0)
items.AddRange(BuildSlot(slotStart + options.NewsDuration, HalfHour - options.NewsDuration, playable)); 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; return items;
} }
private List<ScheduleItem> BuildSlot(DateTime slotStart, TimeSpan length, List<Song> songs) private List<ScheduleItem> BuildLeadIn(ScheduleOptions options, DateTime start, TimeSpan length, List<Song> songs)
{ {
// Half of the hourly limit per slot keeps every hour within MaxFillerPerHour. // The targets shrink with the lead-in: half of a half hour gets half of the ads.
var maxFiller = options.MaxFillerPerHour / 2; var share = length / HalfHour;
var minFiller = options.MinFillerPerHalfHour < maxFiller ? options.MinFillerPerHalfHour : maxFiller; try
for (var attempt = 0; attempt < options.Attempts; attempt++)
{ {
var picked = PickSongs(length - minFiller, songs); return BuildSlot(options, start, length, options.AdsPerHour / 2 * share, options.ModeratorPerHour / 2 * share, songs);
var gap = length - Sum(picked);
if (picked.Count > 0 && gap <= maxFiller)
return Arrange(slotStart, picked, BuildFiller(gap));
} }
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( private List<ScheduleItem> BuildSlot(
$"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."); ScheduleOptions options, DateTime slotStart, TimeSpan length, TimeSpan adTarget, TimeSpan moderatorTarget, List<Song> 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);
} }
/// <summary> /// <summary>
@@ -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. /// rebuilds the rest of its half-hour slot, so the last song still ends exactly when the next news starts.
/// Items before <paramref name="index"/> and all later slots stay as they are. /// Items before <paramref name="index"/> and all later slots stay as they are.
/// </summary> /// </summary>
/// <exception cref="ScheduleException">The song does not fit before the next news, or the rest cannot be filled.</exception> /// <exception cref="ScheduleException">The song does not fit before the next news.</exception>
public IReadOnlyList<ScheduleItem> Replace(IReadOnlyList<ScheduleItem> plan, int index, Song requested, IReadOnlyList<Song> songs) public IReadOnlyList<ScheduleItem> Replace(IReadOnlyList<ScheduleItem> plan, int index, Song requested, IReadOnlyList<Song> songs)
{ {
ArgumentOutOfRangeException.ThrowIfNegative(index); ArgumentOutOfRangeException.ThrowIfNegative(index);
ArgumentOutOfRangeException.ThrowIfGreaterThanOrEqual(index, plan.Count); ArgumentOutOfRangeException.ThrowIfGreaterThanOrEqual(index, plan.Count);
if (plan[index].Kind == ScheduleItemKind.News) 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) 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 slotStartIndex = LastIndexOf(plan, index, ScheduleItemKind.News); // -1 if the plan does not start with news
var nextNewsIndex = IndexOf(plan, index, ScheduleItemKind.News); var nextNewsIndex = IndexOf(plan, index, ScheduleItemKind.News);
@@ -96,27 +140,20 @@ public class ScheduleGenerator(ScheduleOptions options, Random random)
if (requested.Duration > length) if (requested.Duration > length)
throw new ScheduleException( 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 prefix = plan.Take(index).ToList();
var prefixFiller = Sum(prefix.Skip(slotStartIndex + 1).Where(i => i.Kind is ScheduleItemKind.Ad or ScheduleItemKind.Moderator)); var slotPrefix = prefix.Skip(slotStartIndex + 1).ToList();
var maxGap = options.MaxFillerPerHour / 2 - prefixFiller; 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 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++) var (picked, gap) = PickBest(options, length, Min(adTarget + moderatorTarget, length), playable, requested);
{ var (ads, moderator) = Split(options, gap, adTarget, moderatorTarget);
List<Song> picked = [requested, .. PickSongs(length - requested.Duration, playable, requested)]; IEnumerable<ScheduleItem> rest = nextNewsIndex < 0 ? [] : plan.Skip(nextNewsIndex);
var gap = length - Sum(picked); return [.. prefix, .. Arrange(options, start, picked, ads, moderator, keepFirstSongFirst: true), .. rest];
if (gap <= maxGap)
{
IEnumerable<ScheduleItem> 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.");
} }
private static int IndexOf(IReadOnlyList<ScheduleItem> plan, int from, ScheduleItemKind kind) private static int IndexOf(IReadOnlyList<ScheduleItem> plan, int from, ScheduleItemKind kind)
@@ -133,6 +170,27 @@ public class ScheduleGenerator(ScheduleOptions options, Random random)
return -1; 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<Song> Songs, TimeSpan Gap) PickBest(
ScheduleOptions options, TimeSpan length, TimeSpan target, List<Song> songs, Song? first = null)
{
var fixedTime = first?.Duration ?? TimeSpan.Zero;
var budget = Max(length - fixedTime - target, TimeSpan.Zero);
(List<Song> Songs, TimeSpan Gap)? best = null;
for (var attempt = 0; attempt < options.Attempts; attempt++)
{
var more = PickSongs(budget, songs, first);
List<Song> 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<Song> PickSongs(TimeSpan budget, List<Song> songs, Song? previous = null) private List<Song> PickSongs(TimeSpan budget, List<Song> songs, Song? previous = null)
{ {
var picked = new List<Song>(); var picked = new List<Song>();
@@ -149,52 +207,95 @@ public class ScheduleGenerator(ScheduleOptions options, Random random)
} }
} }
// Alternates ad and moderator items, so ads never run back to back. // Shares the leftover time between ads and moderator talk in the ratio of their targets.
private List<(ScheduleItemKind Kind, string Title, TimeSpan Duration)> BuildFiller(TimeSpan gap, bool startWithAd = true) private static (TimeSpan Ads, TimeSpan Moderator) Split(ScheduleOptions options, TimeSpan gap, TimeSpan adTarget, TimeSpan moderatorTarget)
{ {
var filler = new List<(ScheduleItemKind, string, TimeSpan)>(); if (adTarget + moderatorTarget <= TimeSpan.Zero)
var nextIsAd = startWithAd;
while (gap > TimeSpan.Zero)
{ {
(ScheduleItemKind kind, string title, TimeSpan duration) = nextIsAd // This slot has nothing left to aim for; fall back to the hourly ratio, or to talk alone.
? Pick(PlaceholderContent.AdSpots, a => (ScheduleItemKind.Ad, a.Title, Min(a.Duration, options.MaxAdBlock))) adTarget = options.AdsPerHour;
: Pick(PlaceholderContent.ModeratorSegments, m => (ScheduleItemKind.Moderator, m.Title, m.Duration)); moderatorTarget = options.ModeratorPerHour;
duration = Min(duration, gap); // shortcut: the last placeholder is cut to fit; fine while they have no audio if (adTarget + moderatorTarget <= TimeSpan.Zero)
filler.Add((kind, title, duration)); return (TimeSpan.Zero, gap);
gap -= duration;
nextIsAd = !nextIsAd;
} }
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. // Lays out the slot: songs with breaks in between, each break "moderator, ad, moderator, ad ...".
private static List<ScheduleItem> Arrange(DateTime start, List<Song> songs, List<(ScheduleItemKind Kind, string Title, TimeSpan Duration)> filler) // 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<ScheduleItem> Arrange(
ScheduleOptions options, DateTime start, List<Song> 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<ScheduleItem>(); var items = new List<ScheduleItem>();
var time = start; 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++) 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. // Break n sits before the song at its share of the way through the slot.
var until = filler.Count * (i + 1) / songs.Count; while (nextBreak < breaks && i == firstBreakSong + nextBreak * breakSlots / breaks)
for (; fillerIndex < until; fillerIndex++) AddBreak(nextBreak++);
{ Add(ScheduleItemKind.Song, songs[i].Duration, songs[i]);
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;
} }
// No songs at all: the slot is ads and talk only.
while (nextBreak < breaks)
AddBreak(nextBreak++);
return items; return items;
} }
private T Pick<TSource, T>(IReadOnlyList<TSource> source, Func<TSource, T> 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<TimeSpan> Pieces(TimeSpan total, int count)
{
var pieces = new List<TimeSpan>();
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<Song> songs) => songs.Aggregate(TimeSpan.Zero, (total, s) => total + s.Duration); private static TimeSpan Sum(IEnumerable<Song> songs) => songs.Aggregate(TimeSpan.Zero, (total, s) => total + s.Duration);
private static TimeSpan Sum(IEnumerable<ScheduleItem> items) => items.Aggregate(TimeSpan.Zero, (total, i) => total + i.Duration); private static TimeSpan Sum(IEnumerable<ScheduleItem> 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 Min(TimeSpan a, TimeSpan b) => a < b ? a : b;
private static TimeSpan Max(TimeSpan a, TimeSpan b) => a > b ? a : b;
} }
@@ -75,21 +75,29 @@ public class ScheduleGeneratorTests
} }
} }
private static TimeSpan Total(IEnumerable<ScheduleItem> 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] [Theory]
[MemberData(nameof(Seeds))] [MemberData(nameof(Seeds))]
public void AdsAndModeratorStayWithinTwentyMinutesPerHour(int seed) public void AdsAndModeratorMeetTheirTargetsPerHour(int seed)
{ {
var options = new ScheduleOptions();
var items = Generate(seed); var items = Generate(seed);
for (var hour = 0; hour < 3; hour++) for (var hour = 0; hour < 3; hour++)
{ {
var from = Start.AddHours(hour); var from = Start.AddHours(hour);
var filler = items var inHour = items.Where(i => i.Start >= from && i.Start < from.AddHours(1)).ToList();
.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);
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))] [MemberData(nameof(Seeds))]
public void NoAdBlockIsLongerThanTheConfiguredMaximum(int seed) 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 options = new ScheduleOptions { MaxAdBlock = TimeSpan.FromMinutes(1) };
var block = TimeSpan.Zero; var block = TimeSpan.Zero;
@@ -133,13 +142,87 @@ public class ScheduleGeneratorTests
Assert.Throws<ScheduleException>(() => generator.Generate(Start, 1, [])); Assert.Throws<ScheduleException>(() => 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] [Fact]
public void Generate_RejectsInvalidInput() public void Generate_RejectsInvalidInput()
{ {
var generator = new ScheduleGenerator(new ScheduleOptions(), new Random(1)); var generator = new ScheduleGenerator(new ScheduleOptions(), new Random(1));
Assert.Throws<ArgumentOutOfRangeException>(() => generator.Generate(Start, 0, Library)); Assert.Throws<ArgumentOutOfRangeException>(() => generator.Generate(Start, 0, Library));
Assert.Throws<ArgumentException>(() => generator.Generate(Start.AddMinutes(15), 1, Library));
Assert.Throws<ArgumentException>(() => Assert.Throws<ArgumentException>(() =>
new ScheduleGenerator(new ScheduleOptions { MaxAdBlock = TimeSpan.FromMinutes(20) }, new Random(1)).Generate(Start, 1, Library)); new ScheduleGenerator(new ScheduleOptions { MaxAdBlock = TimeSpan.FromMinutes(20) }, new Random(1)).Generate(Start, 1, Library));
} }
@@ -171,7 +254,7 @@ public class ScheduleGeneratorTests
[Theory] [Theory]
[MemberData(nameof(Seeds))] [MemberData(nameof(Seeds))]
public void Replace_KeepsFillerLimitsAndNoAdsBackToBack(int seed) public void Replace_KeepsTheSlotOnTimeAndNoAdsBackToBack(int seed)
{ {
var plan = Generate(seed, hours: 1); var plan = Generate(seed, hours: 1);
// Every non-news item in the first half hour, so prefixes with filler are covered too. // 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); } try { swapped = Generator(seed).Replace(plan, index, Request, Library); }
catch (ScheduleException) { continue; } // too little time left before the news catch (ScheduleException) { continue; } // too little time left before the news
var filler = swapped.Where(i => i.Kind is ScheduleItemKind.Ad or ScheduleItemKind.Moderator) Assert.Equal(plan[^1].End, swapped[^1].End);
.Aggregate(TimeSpan.Zero, (sum, i) => sum + i.Duration);
Assert.True(filler <= TimeSpan.FromMinutes(20), $"{filler} filler after swap at {index}");
for (var i = 1; i < swapped.Count; i++) for (var i = 1; i < swapped.Count; i++)
Assert.False(swapped[i - 1].Kind == ScheduleItemKind.Ad && swapped[i].Kind == ScheduleItemKind.Ad, Assert.False(swapped[i - 1].Kind == ScheduleItemKind.Ad && swapped[i].Kind == ScheduleItemKind.Ad,
$"Ads back to back at {swapped[i].Start:HH:mm:ss}"); $"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 tooLong = Song(98, 25 * 60);
var ex = Assert.Throws<ScheduleException>(() => Generator(1).Replace(plan, beforeNews, tooLong, Library)); var ex = Assert.Throws<ScheduleException>(() => Generator(1).Replace(plan, beforeNews, tooLong, Library));
Assert.Contains("does not fit", ex.Message); Assert.Contains("passt nicht", ex.Message);
} }
[Fact] [Fact]