Merge branch 'j.lechner/schedule-generator' into 'main'

feat: add schedule generator for news, songs and ads

Closes #8

See merge request julian/blockwoche3.1-radiosender!8
This commit is contained in:
Julian Lechner committed 2026-11-23 09:48:35 +00:00
commit 4866545f3a
3 files changed
+298

No files matched your search

+15
View File
@@ -0,0 +1,15 @@
namespace Radiosender.Models;
public enum ScheduleItemKind
{
Song,
News,
Ad,
Moderator,
}
/// <summary>One entry of the broadcast plan. <see cref="Song"/> is set only for <see cref="ScheduleItemKind.Song"/>.</summary>
public record ScheduleItem(ScheduleItemKind Kind, string Title, DateTime Start, TimeSpan Duration, Song? Song = null)
{
public DateTime End => Start + Duration;
}
@@ -0,0 +1,137 @@
using Radiosender.Models;
namespace Radiosender.Services;
public record ScheduleOptions
{
public TimeSpan NewsDuration { get; init; } = TimeSpan.FromMinutes(5);
/// <summary>Upper limit for ads and moderator talk together, per hour.</summary>
public TimeSpan MaxFillerPerHour { get; init; } = TimeSpan.FromMinutes(20);
/// <summary>Ads and moderator talk planned at least per half hour, so the music is broken up.</summary>
public TimeSpan MinFillerPerHalfHour { get; init; } = TimeSpan.FromMinutes(2);
/// <summary>Longest run of consecutive ad items. Must be below 20 minutes.</summary>
public TimeSpan MaxAdBlock { get; init; } = TimeSpan.FromMinutes(5);
/// <summary>Random song picks tried per half hour before giving up.</summary>
public int Attempts { get; init; } = 1000;
}
public class ScheduleException(string message) : Exception(message);
/// <summary>
/// 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.
/// </summary>
public class ScheduleGenerator(ScheduleOptions options, Random random)
{
private static readonly TimeSpan HalfHour = TimeSpan.FromMinutes(30);
public ScheduleGenerator() : this(new ScheduleOptions(), Random.Shared)
{
}
public IReadOnlyList<ScheduleItem> Generate(DateTime start, int hours, IReadOnlyList<Song> songs)
{
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.");
var items = new List<ScheduleItem>();
for (var slotStart = start; slotStart < start.AddHours(hours); slotStart += HalfHour)
{
items.Add(new ScheduleItem(ScheduleItemKind.News, "News", slotStart, options.NewsDuration));
items.AddRange(BuildSlot(slotStart + options.NewsDuration, HalfHour - options.NewsDuration, playable));
}
return items;
}
private List<ScheduleItem> BuildSlot(DateTime slotStart, TimeSpan length, List<Song> 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++)
{
var picked = PickSongs(length - minFiller, songs);
var gap = length - Sum(picked);
if (picked.Count > 0 && gap <= maxFiller)
return Arrange(slotStart, picked, BuildFiller(gap));
}
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<Song> PickSongs(TimeSpan budget, List<Song> songs)
{
var picked = new List<Song>();
var left = budget;
while (true)
{
var fitting = songs.Where(s => s.Duration <= left && (picked.Count == 0 || s.Id != picked[^1].Id || songs.Count == 1)).ToList();
if (fitting.Count == 0)
return picked;
var song = fitting[random.Next(fitting.Count)];
picked.Add(song);
left -= song.Duration;
}
}
// Alternates ad and moderator items, so ads never run back to back.
private List<(ScheduleItemKind Kind, string Title, TimeSpan Duration)> BuildFiller(TimeSpan gap)
{
var filler = new List<(ScheduleItemKind, string, TimeSpan)>();
var nextIsAd = true;
while (gap > 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;
}
return filler;
}
// Spreads the filler between songs; the slot always ends with a song.
private static List<ScheduleItem> Arrange(DateTime start, List<Song> songs, List<(ScheduleItemKind Kind, string Title, TimeSpan Duration)> filler)
{
var items = new List<ScheduleItem>();
var time = start;
var fillerIndex = 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;
}
return items;
}
private T Pick<TSource, T>(IReadOnlyList<TSource> source, Func<TSource, T> map) => map(source[random.Next(source.Count)]);
private static TimeSpan Sum(IEnumerable<Song> songs) => songs.Aggregate(TimeSpan.Zero, (total, s) => total + s.Duration);
private static TimeSpan Min(TimeSpan a, TimeSpan b) => a < b ? a : b;
}
@@ -0,0 +1,146 @@
using Radiosender.Models;
using Radiosender.Services;
namespace Radiosender.Tests;
public class ScheduleGeneratorTests
{
private static readonly DateTime Start = new(2026, 11, 23, 14, 0, 0);
// Realistic lengths with odd seconds, so exact fits only work through the filler.
private static readonly IReadOnlyList<Song> Library =
[
Song(1, 3 * 60 + 12), Song(2, 4 * 60 + 5), Song(3, 2 * 60 + 47), Song(4, 5 * 60 + 31),
Song(5, 3 * 60 + 58), Song(6, 3 * 60 + 3), Song(7, 6 * 60 + 9), Song(8, 2 * 60 + 21),
];
private static Song Song(long id, int seconds) =>
new() { Id = id, Title = $"Song {id}", Artist = "Artist", Duration = TimeSpan.FromSeconds(seconds) };
private static IReadOnlyList<ScheduleItem> Generate(int seed, int hours = 3, ScheduleOptions? options = null) =>
new ScheduleGenerator(options ?? new ScheduleOptions(), new Random(seed)).Generate(Start, hours, Library);
public static TheoryData<int> Seeds => [1, 2, 3, 42, 1234];
[Theory]
[MemberData(nameof(Seeds))]
public void Items_AreContiguousAndCoverExactlyTheHours(int seed)
{
var items = Generate(seed);
Assert.Equal(Start, items[0].Start);
for (var i = 1; i < items.Count; i++)
Assert.Equal(items[i - 1].End, items[i].Start);
Assert.Equal(Start.AddHours(3), items[^1].End);
}
[Theory]
[MemberData(nameof(Seeds))]
public void News_RunsFiveMinutesAtFullAndHalfHour(int seed)
{
var news = Generate(seed).Where(i => i.Kind == ScheduleItemKind.News).ToList();
Assert.Equal(6, news.Count);
for (var n = 0; n < news.Count; n++)
{
Assert.Equal(Start.AddMinutes(30 * n), news[n].Start);
Assert.Equal(TimeSpan.FromMinutes(5), news[n].Duration);
}
}
[Theory]
[MemberData(nameof(Seeds))]
public void ASongEndsExactlyWhenEachNewsStartsAndAtTheEnd(int seed)
{
var items = Generate(seed);
for (var i = 1; i < items.Count; i++)
{
if (items[i].Kind != ScheduleItemKind.News)
continue;
Assert.Equal(ScheduleItemKind.Song, items[i - 1].Kind);
Assert.Equal(items[i].Start, items[i - 1].End);
}
Assert.Equal(ScheduleItemKind.Song, items[^1].Kind);
}
[Theory]
[MemberData(nameof(Seeds))]
public void SongsAreNeverCutAndComeFromTheLibrary(int seed)
{
foreach (var song in Generate(seed).Where(i => i.Kind == ScheduleItemKind.Song))
{
Assert.Contains(song.Song!, Library);
Assert.Equal(song.Song!.Duration, song.Duration);
}
}
[Theory]
[MemberData(nameof(Seeds))]
public void AdsAndModeratorStayWithinTwentyMinutesPerHour(int seed)
{
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);
Assert.InRange(filler, TimeSpan.FromMinutes(2), TimeSpan.FromMinutes(20));
}
}
[Theory]
[MemberData(nameof(Seeds))]
public void NoAdBlockIsLongerThanTheConfiguredMaximum(int seed)
{
var options = new ScheduleOptions { MaxAdBlock = TimeSpan.FromMinutes(1) };
var block = TimeSpan.Zero;
foreach (var item in Generate(seed, options: options))
{
block = item.Kind == ScheduleItemKind.Ad ? block + item.Duration : TimeSpan.Zero;
Assert.True(block <= options.MaxAdBlock, $"Ad block of {block} at {item.Start:HH:mm:ss}");
}
}
[Fact]
public void Generate_ProducesDifferentPlansForDifferentSeeds()
{
var a = Generate(1).Select(i => i.Title);
var b = Generate(2).Select(i => i.Title);
Assert.NotEqual(a, b);
}
[Fact]
public void Generate_ThrowsWhenSongsAreTooLongForAnySlot()
{
Song[] longSongs = [Song(1, 24 * 60), Song(2, 26 * 60)];
var generator = new ScheduleGenerator(new ScheduleOptions(), new Random(1));
Assert.Throws<ScheduleException>(() => generator.Generate(Start, 1, longSongs));
}
[Fact]
public void Generate_ThrowsForEmptyLibrary()
{
var generator = new ScheduleGenerator(new ScheduleOptions(), new Random(1));
Assert.Throws<ScheduleException>(() => generator.Generate(Start, 1, []));
}
[Fact]
public void Generate_RejectsInvalidInput()
{
var generator = new ScheduleGenerator(new ScheduleOptions(), new Random(1));
Assert.Throws<ArgumentOutOfRangeException>(() => generator.Generate(Start, 0, Library));
Assert.Throws<ArgumentException>(() => generator.Generate(Start.AddMinutes(15), 1, Library));
Assert.Throws<ArgumentException>(() =>
new ScheduleGenerator(new ScheduleOptions { MaxAdBlock = TimeSpan.FromMinutes(20) }, new Random(1)).Generate(Start, 1, Library));
}
}