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:
1 parent
e5c4d0e720
commit
5193427629
3 files changed
+278
-87
No files matched your search
@@ -6,71 +6,115 @@ 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>Target for ads per hour. Met as closely as the song lengths allow.</summary>
|
||||
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>
|
||||
public TimeSpan MinFillerPerHalfHour { get; init; } = TimeSpan.FromMinutes(2);
|
||||
/// <summary>Target for moderator talk per hour. Met as closely as the song lengths allow.</summary>
|
||||
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);
|
||||
|
||||
/// <summary>Random song picks tried per half hour before giving up.</summary>
|
||||
public int Attempts { get; init; } = 1000;
|
||||
/// <summary>Random song picks tried per half hour; the one closest to the targets wins.</summary>
|
||||
public int Attempts { get; init; } = 400;
|
||||
}
|
||||
|
||||
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.
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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);
|
||||
|
||||
// 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)
|
||||
{
|
||||
}
|
||||
|
||||
/// <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)
|
||||
{
|
||||
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<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));
|
||||
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<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.
|
||||
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<ScheduleItem> BuildSlot(
|
||||
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>
|
||||
@@ -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 <paramref name="index"/> and all later slots stay as they are.
|
||||
/// </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)
|
||||
{
|
||||
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<Song> picked = [requested, .. PickSongs(length - requested.Duration, playable, requested)];
|
||||
var gap = length - Sum(picked);
|
||||
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.");
|
||||
var (picked, gap) = PickBest(options, length, Min(adTarget + moderatorTarget, length), playable, requested);
|
||||
var (ads, moderator) = Split(options, gap, adTarget, moderatorTarget);
|
||||
IEnumerable<ScheduleItem> rest = nextNewsIndex < 0 ? [] : plan.Skip(nextNewsIndex);
|
||||
return [.. prefix, .. Arrange(options, start, picked, ads, moderator, keepFirstSongFirst: true), .. rest];
|
||||
}
|
||||
|
||||
private static int IndexOf(IReadOnlyList<ScheduleItem> 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<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)
|
||||
{
|
||||
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.
|
||||
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<ScheduleItem> Arrange(DateTime start, List<Song> 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<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 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<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<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 Max(TimeSpan a, TimeSpan b) => a > b ? a : b;
|
||||
}
|
||||
Reference in new issue
Block a user