diff --git a/src/Radiosender/Controllers/ScheduleController.cs b/src/Radiosender/Controllers/ScheduleController.cs index ef7f063..1272d4e 100644 --- a/src/Radiosender/Controllers/ScheduleController.cs +++ b/src/Radiosender/Controllers/ScheduleController.cs @@ -81,4 +81,30 @@ public class ScheduleController } public void Stop() => _engine.Stop(); + + /// All songs in the library, for the song request picker. + public IReadOnlyList LibrarySongs() => _songs.GetAll(); + + /// + /// Hot swap: plays the song in place of the item at . + /// The rest of that half hour is rebuilt so the next news still starts on time; works while playing. + /// + /// The item cannot be replaced or the song does not fit. + public IReadOnlyList Swap(int index, long songId) + { + if (Plan.Count == 0) + throw new ScheduleException("Create a schedule first."); + if (index < 0 || index >= Plan.Count) + throw new ScheduleException("Select an item in the schedule."); + if (IsPlaying && index <= CurrentIndex) + throw new ScheduleException("This item is already on air or over. Choose a later item."); + var song = _songs.GetById(songId) ?? throw new ScheduleException("The song is no longer in the library."); + + var plan = _generator.Replace(Plan, index, song, _songs.GetAll()); + // The engine may have moved on while the plan was rebuilt. + if (IsPlaying && !_engine.ReplaceUpcoming(plan, index)) + throw new ScheduleException("This item went on air in the meantime. Choose a later item."); + Plan = plan; + return plan; + } } diff --git a/src/Radiosender/Services/PlaybackEngine.cs b/src/Radiosender/Services/PlaybackEngine.cs index 530c188..3c0cdb6 100644 --- a/src/Radiosender/Services/PlaybackEngine.cs +++ b/src/Radiosender/Services/PlaybackEngine.cs @@ -61,6 +61,21 @@ public sealed class PlaybackEngine } } + /// + /// Hot swap: switches to while playing. Items before + /// must be unchanged. Returns false if the item at has already started. + /// + public bool ReplaceUpcoming(IReadOnlyList items, int fromIndex) + { + lock (_lock) + { + if (IsRunning && CurrentIndex >= fromIndex) + return false; + Items = items; + return true; + } + } + /// Stops playback. Waits until the running schedule has ended. public void Stop() { @@ -90,11 +105,17 @@ public sealed class PlaybackEngine { try { - for (var i = 0; i < Items.Count; i++) + for (var i = 0; ; i++) { token.ThrowIfCancellationRequested(); - var item = Items[i]; - CurrentIndex = i; + ScheduleItem item; + // Under the lock so ReplaceUpcoming cannot swap the item that is about to start. + lock (_lock) + { + if (i >= Items.Count) break; + item = Items[i]; + CurrentIndex = i; + } ItemStarted?.Invoke(this, (i, item)); if (item.Kind == ScheduleItemKind.Song && item.Song is not null) diff --git a/src/Radiosender/Services/ScheduleGenerator.cs b/src/Radiosender/Services/ScheduleGenerator.cs index d91ab94..358165a 100644 --- a/src/Radiosender/Services/ScheduleGenerator.cs +++ b/src/Radiosender/Services/ScheduleGenerator.cs @@ -73,13 +73,74 @@ public class ScheduleGenerator(ScheduleOptions options, Random random) $"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 PickSongs(TimeSpan budget, List songs) + /// + /// Hot swap: puts at in place of that item and + /// 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. + 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."); + if (requested.Duration <= TimeSpan.Zero) + throw new ScheduleException("The requested song has no duration."); + + var slotStartIndex = LastIndexOf(plan, index, ScheduleItemKind.News); // -1 if the plan does not start with news + var nextNewsIndex = IndexOf(plan, index, ScheduleItemKind.News); + var slotEnd = nextNewsIndex < 0 ? plan[^1].End : plan[nextNewsIndex].Start; + var start = plan[index].Start; + var length = slotEnd - start; + + 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."); + + 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 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."); + } + + private static int IndexOf(IReadOnlyList plan, int from, ScheduleItemKind kind) + { + for (var i = from; i < plan.Count; i++) + if (plan[i].Kind == kind) return i; + return -1; + } + + private static int LastIndexOf(IReadOnlyList plan, int before, ScheduleItemKind kind) + { + for (var i = before - 1; i >= 0; i--) + if (plan[i].Kind == kind) return i; + return -1; + } + + private List PickSongs(TimeSpan budget, List songs, Song? previous = null) { var picked = new List(); 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(); + var last = picked.Count > 0 ? picked[^1] : previous; + var fitting = songs.Where(s => s.Duration <= left && (last is null || s.Id != last.Id || songs.Count == 1)).ToList(); if (fitting.Count == 0) return picked; var song = fitting[random.Next(fitting.Count)]; @@ -89,10 +150,10 @@ 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) + private List<(ScheduleItemKind Kind, string Title, TimeSpan Duration)> BuildFiller(TimeSpan gap, bool startWithAd = true) { var filler = new List<(ScheduleItemKind, string, TimeSpan)>(); - var nextIsAd = true; + var nextIsAd = startWithAd; while (gap > TimeSpan.Zero) { (ScheduleItemKind kind, string title, TimeSpan duration) = nextIsAd @@ -133,5 +194,7 @@ public class ScheduleGenerator(ScheduleOptions options, Random random) 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; } diff --git a/src/Radiosender/Views/Pages/SchedulePage.xaml b/src/Radiosender/Views/Pages/SchedulePage.xaml index b4e5cfc..0b90f55 100644 --- a/src/Radiosender/Views/Pages/SchedulePage.xaml +++ b/src/Radiosender/Views/Pages/SchedulePage.xaml @@ -37,6 +37,7 @@ + @@ -135,23 +136,81 @@ + + + + + + + + + + + + + + + AutomationProperties.Name="Schedule timeline" + SelectionChanged="OnTimelineSelectionChanged"> + + + + + + + + + + + + - + - - + + + + + + + + - + @@ -159,7 +218,7 @@ s.Artist).ThenBy(s => s.Title) + .Select(s => new SongOption(s.Id, $"{(string.IsNullOrWhiteSpace(s.Artist) ? s.Title : $"{s.Artist} - {s.Title}")} ({s.Duration:m\\:ss})")) + .ToList(); + ShowCurrent(); _progressTimer.Start(); } @@ -62,10 +69,31 @@ public partial class SchedulePage : Page { ShowMessage(InfoBarSeverity.Error, "Could not create the schedule", ex.Message); } - ShowPlan(); ShowCurrent(); } + private void OnSwap(object sender, RoutedEventArgs e) + { + if (Timeline.SelectedItem is not TimelineRow row || RequestSong.SelectedItem is not SongOption song) + return; + try + { + var plan = _controller.Swap(row.Index, song.Id); + var placed = plan[row.Index]; + ShowMessage(InfoBarSeverity.Success, "Song request planned", + $"\"{placed.Title}\" plays at {placed.Start:HH:mm:ss} instead of \"{row.Item.Title}\". The rest of that half hour was replanned, the news stays on time."); + } + catch (ScheduleException ex) + { + ShowMessage(InfoBarSeverity.Error, "Could not play the request", ex.Message); + } + ShowCurrent(); + } + + private void OnRequestChanged(object sender, SelectionChangedEventArgs e) => UpdateButtons(); + + private void OnTimelineSelectionChanged(object sender, SelectionChangedEventArgs e) => UpdateButtons(); + private void OnStart(object sender, RoutedEventArgs e) { Message.IsOpen = false; @@ -96,25 +124,30 @@ public partial class SchedulePage : Page ShowCurrent(); }); - private void ShowPlan() - { - Timeline.ItemsSource = _controller.Plan; - EmptyText.Visibility = _controller.Plan.Count == 0 ? Visibility.Visible : Visibility.Collapsed; - } - + // Rebuilds the rows from the controller; the selection is the user's swap target and is kept. private void ShowCurrent() { var item = _controller.CurrentItem; - UpdateButtons(); + var current = _controller.CurrentIndex; + var plan = _controller.Plan; + + var selected = Timeline.SelectedIndex; + var rows = plan.Select((p, i) => new TimelineRow(i, p, i == current)).ToList(); + Timeline.ItemsSource = rows; + Timeline.SelectedIndex = selected < rows.Count ? selected : -1; + // Follow the broadcast when it moves on; otherwise keep the user's row in view. + if (current != _scrolledTo && current >= 0 && current < rows.Count) + Timeline.ScrollIntoView(rows[current]); + else if (Timeline.SelectedItem is { } row) + Timeline.ScrollIntoView(row); + _scrolledTo = current; + EmptyText.Visibility = plan.Count == 0 ? Visibility.Visible : Visibility.Collapsed; NowKind.Content = item; NowKind.Visibility = item is null ? Visibility.Collapsed : Visibility.Visible; NowTitle.Text = item?.Title ?? "Nothing on air"; - Timeline.SelectedIndex = _controller.CurrentIndex; - if (Timeline.SelectedItem is { } selected) - Timeline.ScrollIntoView(selected); - + UpdateButtons(); UpdateProgress(); } @@ -123,6 +156,18 @@ public partial class SchedulePage : Page var playing = _controller.IsPlaying; StartButton.IsEnabled = !playing && _controller.Plan.Count > 0; StopButton.IsEnabled = playing; + + var row = Timeline.SelectedItem as TimelineRow; + var blocker = row switch + { + null => "Select an upcoming item in the schedule.", + { Item.Kind: ScheduleItemKind.News } => "News cannot be replaced.", + _ when playing && row.Index <= _controller.CurrentIndex => "This item is already on air or over.", + _ when RequestSong.SelectedItem is null => "Choose a song from the library.", + _ => null, + }; + SwapHint.Text = blocker ?? $"Replaces the item at {row!.Item.Start:HH:mm:ss}."; + SwapButton.IsEnabled = blocker is null; } private void UpdateProgress() @@ -146,4 +191,8 @@ public partial class SchedulePage : Page Message.Message = text; Message.IsOpen = true; } + + private sealed record TimelineRow(int Index, ScheduleItem Item, bool IsCurrent); + + private sealed record SongOption(long Id, string Label); } diff --git a/tests/Radiosender.Tests/PlaybackEngineTests.cs b/tests/Radiosender.Tests/PlaybackEngineTests.cs index 650dd64..4549f20 100644 --- a/tests/Radiosender.Tests/PlaybackEngineTests.cs +++ b/tests/Radiosender.Tests/PlaybackEngineTests.cs @@ -159,4 +159,33 @@ public class PlaybackEngineTests Assert.Equal(["c.mp3"], player.Played); } -} + + [Fact] + public async Task ReplaceUpcoming_PlaysTheNewItemsButNotOverItemsAlreadyStarted() + { + var player = new FakePlayer(); + var news = new TaskCompletionSource(); + var first = true; + // The first delay is the news; it waits until released. Song timeouts never fire. + Task Delay(TimeSpan d, CancellationToken t) + { + if (first) { first = false; return news.Task.WaitAsync(t); } + return d > TimeSpan.FromSeconds(180) ? Task.Delay(Timeout.Infinite, t) : Task.CompletedTask; + } + var engine = new PlaybackEngine(player, Delay); + var started = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var finished = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + engine.ItemStarted += (_, _) => started.TrySetResult(); + engine.Finished += (_, _) => finished.TrySetResult(); + + engine.Start(Plan); + await started.Task.WaitAsync(Wait); + IReadOnlyList swapped = [Plan[0], SongItem("request.mp3", 200), .. Plan.Skip(2)]; + + Assert.False(engine.ReplaceUpcoming(swapped, 0)); + Assert.True(engine.ReplaceUpcoming(swapped, 1)); + news.SetResult(); + await finished.Task.WaitAsync(Wait); + + Assert.Equal(["request.mp3", "b.mp3"], player.Played); + }} diff --git a/tests/Radiosender.Tests/ScheduleControllerTests.cs b/tests/Radiosender.Tests/ScheduleControllerTests.cs index cf29a17..68b1698 100644 --- a/tests/Radiosender.Tests/ScheduleControllerTests.cs +++ b/tests/Radiosender.Tests/ScheduleControllerTests.cs @@ -114,4 +114,49 @@ public sealed class ScheduleControllerTests : IDisposable Assert.False(controller.IsPlaying); Assert.Null(controller.CurrentItem); } -} + + [Fact] + public void Swap_ReplacesAnItemBeforeStart() + { + AddSongs(); + var controller = Create(); + controller.CreatePlan(1); + var request = _songs.GetAll()[3]; + + var plan = controller.Swap(1, request.Id); + + Assert.Equal(request.Id, plan[1].Song!.Id); + Assert.Same(plan, controller.Plan); + } + + [Fact] + public async Task Swap_WhilePlayingRejectsTheItemOnAirAndAcceptsALaterOne() + { + AddSongs(); + var hold = new TaskCompletionSource(); + var controller = Create((_, token) => hold.Task.WaitAsync(token)); + controller.CreatePlan(1); + var first = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + controller.ItemStarted += (_, _) => first.TrySetResult(); + var request = _songs.GetAll()[3]; + + controller.Start(); + await first.Task.WaitAsync(TimeSpan.FromSeconds(5)); + + var onAir = Assert.Throws(() => controller.Swap(0, request.Id)); + Assert.Contains("already on air", onAir.Message); + controller.Swap(1, request.Id); + Assert.Equal(request.Id, controller.Plan[1].Song!.Id); + controller.Stop(); + } + + [Fact] + public void Swap_RejectsUnknownSongAndMissingPlan() + { + AddSongs(); + var controller = Create(); + Assert.Throws(() => controller.Swap(1, _songs.GetAll()[0].Id)); + + controller.CreatePlan(1); + Assert.Throws(() => controller.Swap(1, 12345)); + }} diff --git a/tests/Radiosender.Tests/ScheduleGeneratorTests.cs b/tests/Radiosender.Tests/ScheduleGeneratorTests.cs index 66e5027..d96323d 100644 --- a/tests/Radiosender.Tests/ScheduleGeneratorTests.cs +++ b/tests/Radiosender.Tests/ScheduleGeneratorTests.cs @@ -143,4 +143,69 @@ public class ScheduleGeneratorTests Assert.Throws(() => new ScheduleGenerator(new ScheduleOptions { MaxAdBlock = TimeSpan.FromMinutes(20) }, new Random(1)).Generate(Start, 1, Library)); } -} + + private static readonly Song Request = Song(99, 4 * 60 + 17); + + private static ScheduleGenerator Generator(int seed) => new(new ScheduleOptions(), new Random(seed)); + + [Theory] + [MemberData(nameof(Seeds))] + public void Replace_PutsTheSongInPlaceAndKeepsEverythingElseOnTime(int seed) + { + var plan = Generate(seed, hours: 2); + var index = 1; // first item after the 14:00 news + var nextNews = plan.Select((p, i) => (p, i)).First(x => x.i > index && x.p.Kind == ScheduleItemKind.News).i; + + var swapped = Generator(seed).Replace(plan, index, Request, Library); + + Assert.Equal(plan.Take(index), swapped.Take(index)); + Assert.Equal(Request, swapped[index].Song); + Assert.Equal(plan[index].Start, swapped[index].Start); + // Later slots are untouched, so the next news is still at 14:30. + var swappedNews = swapped.Select((p, i) => (p, i)).First(x => x.i > index && x.p.Kind == ScheduleItemKind.News).i; + Assert.Equal(plan.Skip(nextNews), swapped.Skip(swappedNews)); + Assert.Equal(ScheduleItemKind.Song, swapped[swappedNews - 1].Kind); + for (var i = 1; i < swapped.Count; i++) + Assert.Equal(swapped[i - 1].End, swapped[i].Start); + } + + [Theory] + [MemberData(nameof(Seeds))] + public void Replace_KeepsFillerLimitsAndNoAdsBackToBack(int seed) + { + var plan = Generate(seed, hours: 1); + // Every non-news item in the first half hour, so prefixes with filler are covered too. + var last = plan.Select((p, i) => (p, i)).First(x => x.i > 0 && x.p.Kind == ScheduleItemKind.News).i; + for (var index = 1; index < last; index++) + { + IReadOnlyList swapped; + 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}"); + 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}"); + } + } + + [Fact] + public void Replace_RejectsSongThatDoesNotFitBeforeTheNews() + { + var plan = Generate(1, hours: 1); + var beforeNews = plan.Select((p, i) => (p, i)).First(x => x.i > 0 && x.p.Kind == ScheduleItemKind.News).i - 1; + var tooLong = Song(98, 25 * 60); + + var ex = Assert.Throws(() => Generator(1).Replace(plan, beforeNews, tooLong, Library)); + Assert.Contains("does not fit", ex.Message); + } + + [Fact] + public void Replace_RejectsNews() + { + var plan = Generate(1, hours: 1); + + Assert.Throws(() => Generator(1).Replace(plan, 0, Request, Library)); + }}