refactor(cleanup): comments, files and outdated code

This commit is contained in:
fraujulian committed 2026-11-26 08:24:19 +01:00
1 parent 7a9ba99a27
commit e81257eca6
64 files changed
+503 -888

No files matched your search

+15 -17
View File
@@ -1,29 +1,31 @@
using System.Windows; using System.Net.Http;
using System.Windows;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Radiosender.Controllers; using Radiosender.Controllers;
using Radiosender.Services; using Radiosender.Services.Audio;
using Radiosender.Services.Library;
using Radiosender.Services.Providers;
using Radiosender.Services.Scheduling;
using Radiosender.Services.Settings;
using Radiosender.Views; using Radiosender.Views;
using Radiosender.Views.Pages; using Radiosender.Views.Pages;
namespace Radiosender; namespace Radiosender;
/// <summary>Composition root: wires every service, controller and page once, at startup.</summary>
public partial class App : Application public partial class App : Application
{ {
private ServiceProvider? _services; private ServiceProvider? _services;
private static ServiceProvider BuildServices() private static ServiceProvider BuildServices()
{ {
var services = new ServiceCollection(); ServiceCollection services = new();
// One instance each for the whole app. The schedule controller in particular must be shared, // Singletons: broadcast must survive page switches.
// so a running broadcast keeps going while the user switches pages.
services.AddSingleton(_ => new SongRepository(SongRepository.DefaultDatabasePath)); services.AddSingleton(_ => new SongRepository(SongRepository.DefaultDatabasePath));
services.AddSingleton(_ => new ScheduleGenerator()); services.AddSingleton(_ => new ScheduleGenerator());
services.AddSingleton(provider => new SettingsStore( services.AddSingleton(provider => new SettingsStore(
provider.GetRequiredService<ScheduleGenerator>(), provider.GetRequiredService<ProgramOutput>(), AppSettings.DefaultPath)); provider.GetRequiredService<ScheduleGenerator>(), provider.GetRequiredService<ProgramOutput>(), AppSettings.DefaultPath));
services.AddSingleton(_ => new PlaybackEngine()); services.AddSingleton(_ => new PlaybackEngine());
// The one audio channel that songs and the microphone share.
services.AddSingleton(_ => ProgramOutput.Instance); services.AddSingleton(_ => ProgramOutput.Instance);
services.AddSingleton<Microphone>(); services.AddSingleton<Microphone>();
services.AddSingleton(provider => new ScheduleController( services.AddSingleton(provider => new ScheduleController(
@@ -31,32 +33,29 @@ public partial class App : Application
provider.GetRequiredService<ScheduleGenerator>(), provider.GetRequiredService<ScheduleGenerator>(),
provider.GetRequiredService<PlaybackEngine>(), provider.GetRequiredService<PlaybackEngine>(),
() => DateTime.Now)); () => DateTime.Now));
// One HttpClient for all providers and downloads.
services.AddSingleton(_ => services.AddSingleton(_ =>
{ {
var http = new System.Net.Http.HttpClient { Timeout = TimeSpan.FromSeconds(20) }; var http = new HttpClient { Timeout = TimeSpan.FromSeconds(20) };
http.DefaultRequestHeaders.UserAgent.ParseAdd("Radiosender/1.0"); http.DefaultRequestHeaders.UserAgent.ParseAdd("Radiosender/1.0");
return http; return http;
}); });
// Music providers: add a line here for each new IMusicProvider; the import page lists them all. // Import page lists providers in this order.
services.AddSingleton<IMusicProvider, OpenverseProvider>(); services.AddSingleton<IMusicProvider, OpenverseProvider>();
services.AddSingleton<IMusicProvider, InternetArchiveProvider>(); services.AddSingleton<IMusicProvider, InternetArchiveProvider>();
// The station's own library; listed only while laut.fm is switched on in the settings.
services.AddSingleton<IMusicProvider>(provider => new LautFmProvider( services.AddSingleton<IMusicProvider>(provider => new LautFmProvider(
provider.GetRequiredService<System.Net.Http.HttpClient>(), () => provider.GetRequiredService<SettingsStore>().Current)); provider.GetRequiredService<HttpClient>(), () => provider.GetRequiredService<SettingsStore>().Current));
services.AddSingleton(provider => new LiveController( services.AddSingleton(provider => new LiveController(
provider.GetRequiredService<ScheduleController>(), provider.GetRequiredService<ScheduleController>(),
provider.GetRequiredService<SettingsStore>(), provider.GetRequiredService<SettingsStore>(),
provider.GetRequiredService<ProgramOutput>(), provider.GetRequiredService<ProgramOutput>(),
provider.GetRequiredService<System.Net.Http.HttpClient>(), provider.GetRequiredService<HttpClient>(),
() => DateTime.Now)); () => DateTime.Now));
services.AddSingleton(provider => new TrackDownloader(provider.GetRequiredService<System.Net.Http.HttpClient>(), TrackDownloader.DefaultMusicFolder)); services.AddSingleton(provider => new TrackDownloader(provider.GetRequiredService<HttpClient>(), TrackDownloader.DefaultMusicFolder));
services.AddSingleton<OnlineImportController>(); services.AddSingleton<OnlineImportController>();
services.AddSingleton(provider => new SongImportService(provider.GetRequiredService<SongRepository>(), SongImportService.DefaultMusicDirectory)); services.AddSingleton(provider => new SongImportService(provider.GetRequiredService<SongRepository>(), SongImportService.DefaultMusicDirectory));
services.AddSingleton<UploadController>(); services.AddSingleton<UploadController>();
services.AddSingleton<LibraryController>(); services.AddSingleton<LibraryController>();
// Pages are created anew on every navigation, as before; they hold only view state.
services.AddSingleton<MainWindow>(); services.AddSingleton<MainWindow>();
services.AddTransient<SchedulePage>(); services.AddTransient<SchedulePage>();
services.AddTransient<LibraryPage>(); services.AddTransient<LibraryPage>();
@@ -70,9 +69,8 @@ public partial class App : Application
{ {
base.OnStartup(e); base.OnStartup(e);
_services = BuildServices(); _services = BuildServices();
// Loads the settings: the generator gets its minutes per hour before the first plan, the audio output its devices. // Eager: applies settings to generator and audio output before first plan.
_services.GetRequiredService<SettingsStore>(); _services.GetRequiredService<SettingsStore>();
// Follow the Windows setting: light, dark or a high-contrast theme.
Wpf.Ui.Appearance.ApplicationThemeManager.ApplySystemTheme(); Wpf.Ui.Appearance.ApplicationThemeManager.ApplySystemTheme();
_services.GetRequiredService<MainWindow>().Show(); _services.GetRequiredService<MainWindow>().Show();
} }
+1 -8
View File
@@ -1,10 +1,3 @@
using System.Windows; using System.Windows;
[assembly:ThemeInfo( [assembly: ThemeInfo(ResourceDictionaryLocation.None, ResourceDictionaryLocation.SourceAssembly)]
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
@@ -1,11 +1,10 @@
using Radiosender.Models; using Radiosender.Models;
using Radiosender.Services; using Radiosender.Services.Library;
namespace Radiosender.Controllers; namespace Radiosender.Controllers;
public class LibraryController(SongRepository repository) public class LibraryController(SongRepository repository)
{ {
/// <summary>Returns all songs whose title or artist contains <paramref name="query"/> (case-insensitive).</summary>
public IReadOnlyList<Song> Search(string? query) public IReadOnlyList<Song> Search(string? query)
{ {
var songs = repository.GetAll(); var songs = repository.GetAll();
@@ -13,14 +12,10 @@ public class LibraryController(SongRepository repository)
return songs; return songs;
query = query.Trim(); query = query.Trim();
return songs return [.. songs.Where(s => s.Title.Contains(query, StringComparison.OrdinalIgnoreCase)
.Where(s => s.Title.Contains(query, StringComparison.OrdinalIgnoreCase) || s.Artist.Contains(query, StringComparison.OrdinalIgnoreCase))];
|| s.Artist.Contains(query, StringComparison.OrdinalIgnoreCase))
.ToList();
} }
/// <summary>Writes the editable metadata; file path, duration and source keep their stored values.</summary>
/// <returns><c>false</c> if the song no longer exists.</returns>
public bool Update(long id, string title, string artist, string? license, string? attribution) public bool Update(long id, string title, string artist, string? license, string? attribution)
{ {
ArgumentException.ThrowIfNullOrWhiteSpace(title); ArgumentException.ThrowIfNullOrWhiteSpace(title);
@@ -37,6 +32,5 @@ public class LibraryController(SongRepository repository)
return repository.Update(song); return repository.Update(song);
} }
/// <returns><c>false</c> if the song no longer exists.</returns>
public bool Delete(long id) => repository.Delete(id); public bool Delete(long id) => repository.Delete(id);
} }
+7 -13
View File
@@ -1,13 +1,11 @@
using System.Net.Http; using System.Net.Http;
using NAudio.Wave; using NAudio.Wave;
using Radiosender.Services; using Radiosender.Services.Audio;
using Radiosender.Services.Settings;
using Radiosender.Services.Streaming;
namespace Radiosender.Controllers; namespace Radiosender.Controllers;
/// <summary>
/// Sends the broadcast mix live to laut.fm, independent of the plan: whatever is on air goes out,
/// and each item that starts sets the stream title.
/// </summary>
public class LiveController public class LiveController
{ {
private readonly ScheduleController _schedule; private readonly ScheduleController _schedule;
@@ -30,19 +28,15 @@ public class LiveController
_schedule.ItemStarted += (_, _) => SendCurrentTitle(); _schedule.ItemStarted += (_, _) => SendCurrentTitle();
} }
/// <summary>laut.fm is switched on in the settings.</summary>
public bool IsEnabled => _settings.Current.LautFmEnabled; public bool IsEnabled => _settings.Current.LautFmEnabled;
public bool IsLive => _stream is not null; public bool IsLive => _stream is not null;
/// <summary> // Background thread.
/// Something went wrong: the stream broke (then <see cref="IsLive"/> is false) or a title was not taken.
/// Raised on a background thread.
/// </summary>
public event EventHandler<string>? Problem; public event EventHandler<string>? Problem;
/// <exception cref="LiveStreamException">laut.fm is off or cannot be reached, or the login was refused.</exception> /// <exception cref="LiveStreamException">laut.fm off, unreachable, or login refused.</exception>
/// <exception cref="NAudio.MmException">No audio output device can be opened; the broadcast device sets the pace.</exception> /// <exception cref="NAudio.MmException">No audio output device.</exception>
public async Task StartAsync(CancellationToken cancellationToken = default) public async Task StartAsync(CancellationToken cancellationToken = default)
{ {
if (IsLive) if (IsLive)
@@ -74,7 +68,7 @@ public class LiveController
public void Stop() => Stop(null); public void Stop() => Stop(null);
// With a stream given, stops only if that one is still the current stream. // only != null: stop only if still current stream.
private void Stop(IcecastStream? only) private void Stop(IcecastStream? only)
{ {
IcecastStream stream; IcecastStream stream;
@@ -1,22 +1,19 @@
using System.IO; using System.IO;
using Radiosender.Models; using Radiosender.Models;
using Radiosender.Services; using Radiosender.Services.Library;
using Radiosender.Services.Providers;
namespace Radiosender.Controllers; namespace Radiosender.Controllers;
/// <summary>Searches the registered music providers and imports their results into the library.</summary>
public class OnlineImportController(IEnumerable<IMusicProvider> providers, TrackDownloader downloader, SongRepository songs) public class OnlineImportController(IEnumerable<IMusicProvider> providers, TrackDownloader downloader, SongRepository songs)
{ {
private readonly IReadOnlyList<IMusicProvider> _providers = providers.ToList(); private readonly IReadOnlyList<IMusicProvider> _providers = [.. providers];
/// <summary>The providers registered in <c>App</c> that are available now, in registration order.</summary> public IReadOnlyList<IMusicProvider> Providers => [.. _providers.Where(provider => provider.IsAvailable)];
public IReadOnlyList<IMusicProvider> Providers => _providers.Where(provider => provider.IsAvailable).ToList();
/// <summary>Ids of the provider results that are already in the library.</summary>
public IReadOnlySet<string> ImportedIds() => songs.GetExternalIds(); public IReadOnlySet<string> ImportedIds() => songs.GetExternalIds();
/// <summary>Downloads the track and stores it as a song with its license and attribution.</summary> /// <exception cref="MusicProviderException">Track not importable or download failed.</exception>
/// <exception cref="MusicProviderException">The track cannot be imported or the download failed.</exception>
public async Task<Song> ImportAsync(MusicTrack track, CancellationToken cancellationToken = default) public async Task<Song> ImportAsync(MusicTrack track, CancellationToken cancellationToken = default)
{ {
if (track.Duration is not { } duration) if (track.Duration is not { } duration)
@@ -1,25 +1,22 @@
using Radiosender.Models; using Radiosender.Models;
using Radiosender.Services; using Radiosender.Services.Audio;
using Radiosender.Services.Library;
using Radiosender.Services.Scheduling;
namespace Radiosender.Controllers; namespace Radiosender.Controllers;
/// <summary> // Events fire on engine thread; views marshal with Dispatcher.BeginInvoke.
/// Creates the broadcast plan and drives its playback. One instance lives for the whole app
/// (registered as a singleton in <see cref="App"/>), so the plan survives page navigation.
/// </summary>
/// <remarks>Events come from the playback engine's thread pool; views marshal with <c>Dispatcher.BeginInvoke</c>.</remarks>
public class ScheduleController public class ScheduleController
{ {
public const int MaxHours = 24; private const int MaxHours = 24;
/// <summary>How far ahead an unlimited plan always reaches.</summary> private const int UnlimitedLookaheadHours = 5;
public const int UnlimitedLookaheadHours = 5;
private readonly SongRepository _songs; private readonly SongRepository _songs;
private readonly ScheduleGenerator _generator; private readonly ScheduleGenerator _generator;
private readonly PlaybackEngine _engine; private readonly PlaybackEngine _engine;
private readonly Func<DateTime> _now; private readonly Func<DateTime> _now;
// Guards Plan against a song request (UI thread) racing the hourly extension (engine thread). // Plan edits (UI thread) vs. hourly extension (engine thread).
private readonly Lock _planLock = new(); private readonly Lock _planLock = new();
private DateTime _itemStartedAt; private DateTime _itemStartedAt;
@@ -45,34 +42,26 @@ public class ScheduleController
public IReadOnlyList<ScheduleItem> Plan { get; private set; } = []; public IReadOnlyList<ScheduleItem> Plan { get; private set; } = [];
/// <summary><c>true</c> for a plan without an end: it grows by an hour whenever less than
/// <see cref="UnlimitedLookaheadHours"/> hours are left.</summary>
public bool IsUnlimited { get; private set; } public bool IsUnlimited { get; private set; }
public bool IsPlaying => _engine.IsRunning; public bool IsPlaying => _engine.IsRunning;
public int CurrentIndex => _engine.CurrentIndex; public int CurrentIndex => _engine.CurrentIndex;
/// <summary>The item on air, or <c>null</c> when nothing plays.</summary>
public ScheduleItem? CurrentItem => CurrentIndex is var i && i >= 0 && i < _engine.Items.Count ? _engine.Items[i] : null; public ScheduleItem? CurrentItem => CurrentIndex is var i && i >= 0 && i < _engine.Items.Count ? _engine.Items[i] : null;
/// <summary>Time since the current item started, capped at its duration.</summary>
public TimeSpan CurrentElapsed => CurrentItem is { } item public TimeSpan CurrentElapsed => CurrentItem is { } item
? TimeSpan.FromTicks(Math.Clamp((_now() - _itemStartedAt).Ticks, 0, item.Duration.Ticks)) ? TimeSpan.FromTicks(Math.Clamp((_now() - _itemStartedAt).Ticks, 0, item.Duration.Ticks))
: TimeSpan.Zero; : TimeSpan.Zero;
/// <summary>Playback volume from 0 to 1.</summary>
public float Volume public float Volume
{ {
get => MusicPlayer.Instance.Volume; get => MusicPlayer.Instance.Volume;
set => MusicPlayer.Instance.Volume = value; set => MusicPlayer.Instance.Volume = value;
} }
/// <summary> // hours null = unlimited; start null = next full hour.
/// Plans <paramref name="hours"/> full hours with the songs in the library; <c>null</c> plans without an end. /// <exception cref="ScheduleException">Library cannot fill the plan.</exception>
/// The plan begins at <paramref name="start"/>, or at the next full hour when that is <c>null</c>.
/// </summary>
/// <exception cref="ScheduleException">The library cannot fill the plan.</exception>
public IReadOnlyList<ScheduleItem> CreatePlan(int? hours, DateTime? start = null) public IReadOnlyList<ScheduleItem> CreatePlan(int? hours, DateTime? start = null)
{ {
if (hours is { } h) if (hours is { } h)
@@ -83,7 +72,6 @@ public class ScheduleController
var now = _now(); var now = _now();
var nextHour = new DateTime(now.Year, now.Month, now.Day, now.Hour, 0, 0, now.Kind).AddHours(1); var nextHour = new DateTime(now.Year, now.Month, now.Day, now.Hour, 0, 0, now.Kind).AddHours(1);
// Whole seconds, so the timeline and the item ends stay on the second.
var from = start is { } s ? new DateTime(s.Ticks - s.Ticks % TimeSpan.TicksPerSecond, s.Kind) : nextHour; var from = start is { } s ? new DateTime(s.Ticks - s.Ticks % TimeSpan.TicksPerSecond, s.Kind) : nextHour;
Stop(); Stop();
var plan = _generator.Generate(from, hours ?? UnlimitedLookaheadHours, _songs.GetAll()); var plan = _generator.Generate(from, hours ?? UnlimitedLookaheadHours, _songs.GetAll());
@@ -95,16 +83,14 @@ public class ScheduleController
return plan; return plan;
} }
/// <summary>Plans from this moment and goes on air at once; music leads up to the first news at :00 or :30.</summary> /// <exception cref="ScheduleException">Library cannot fill the plan.</exception>
/// <exception cref="ScheduleException">The library cannot fill the plan.</exception>
public void StartNow(int? hours) public void StartNow(int? hours)
{ {
CreatePlan(hours, _now()); CreatePlan(hours, _now());
_engine.Start(Plan); _engine.Start(Plan);
} }
// Runs on the engine thread whenever an item starts. // Engine thread. shortcut: played items stay in Plan (~20/h), trim if broadcasts run for weeks.
// shortcut: played items stay in the plan (about 20 per hour); trim them if broadcasts run for weeks.
private void ExtendIfUnlimited() private void ExtendIfUnlimited()
{ {
if (!IsUnlimited) if (!IsUnlimited)
@@ -114,12 +100,12 @@ public class ScheduleController
lock (_planLock) lock (_planLock)
{ {
var plan = Plan; var plan = Plan;
if (plan.Count == 0) // the user removed every item if (plan.Count == 0)
return; return;
var until = _now().AddHours(UnlimitedLookaheadHours); var until = _now().AddHours(UnlimitedLookaheadHours);
while (plan[^1].End < until) while (plan[^1].End < until)
plan = [.. plan, .. _generator.Generate(plan[^1].End, 1, _songs.GetAll())]; plan = [.. plan, .. _generator.Generate(plan[^1].End, 1, _songs.GetAll())];
// Only appends, so the engine keeps everything up to the old end. // Append only: engine keeps items up to old end.
if (!ReferenceEquals(plan, Plan) && _engine.ReplaceUpcoming(plan, Plan.Count)) if (!ReferenceEquals(plan, Plan) && _engine.ReplaceUpcoming(plan, Plan.Count))
Plan = plan; Plan = plan;
} }
@@ -130,13 +116,8 @@ public class ScheduleController
} }
} }
/// <summary>Planned start of the next item while the broadcast waits for it, otherwise <c>null</c>.</summary>
public DateTime? WaitingUntil => CurrentItem is null ? _engine.WaitingUntil : null; public DateTime? WaitingUntil => CurrentItem is null ? _engine.WaitingUntil : null;
/// <summary>
/// Goes on air with the plan on the real clock: waits for the planned start, or joins at the next item
/// when the plan has already begun.
/// </summary>
public void Start() public void Start()
{ {
if (Plan.Count == 0) if (Plan.Count == 0)
@@ -148,11 +129,7 @@ public class ScheduleController
public void Stop() => _engine.Stop(); public void Stop() => _engine.Stop();
/// <summary> // Next news/moderator item within its lead time; null lead = kind off.
/// The next news or moderator item that is due for a reminder while the broadcast runs: it starts within
/// the lead time of its kind. <c>null</c> as lead time switches that kind off. Returns <c>null</c> when
/// nothing is due.
/// </summary>
public ScheduleItem? UpcomingSpeech(TimeSpan? newsLead, TimeSpan? moderatorLead) public ScheduleItem? UpcomingSpeech(TimeSpan? newsLead, TimeSpan? moderatorLead)
{ {
if (!IsPlaying) if (!IsPlaying)
@@ -177,8 +154,7 @@ public class ScheduleController
return null; return null;
} }
/// <summary>Moves the item at <paramref name="index"/> by <paramref name="offset"/> positions; later items shift in time.</summary> /// <exception cref="ScheduleException">Item on air/over, or target outside plan.</exception>
/// <exception cref="ScheduleException">An affected item is already on air or over, or the target is outside the plan.</exception>
public IReadOnlyList<ScheduleItem> Move(int index, int offset) public IReadOnlyList<ScheduleItem> Move(int index, int offset)
{ {
var target = index + offset; var target = index + offset;
@@ -192,19 +168,17 @@ public class ScheduleController
}); });
} }
/// <summary>Removes the item at <paramref name="index"/>; later items move up in time.</summary> /// <exception cref="ScheduleException">Item on air or over.</exception>
/// <exception cref="ScheduleException">The item is already on air or over.</exception>
public IReadOnlyList<ScheduleItem> Remove(int index) => Change(index, change: items => items.RemoveAt(index)); public IReadOnlyList<ScheduleItem> Remove(int index) => Change(index, change: items => items.RemoveAt(index));
/// <summary>Ends the item on air now: its length becomes the time it has run, and the next item starts.</summary> /// <exception cref="ScheduleException">Nothing on air.</exception>
/// <exception cref="ScheduleException">Nothing is on air.</exception>
public IReadOnlyList<ScheduleItem> EndCurrentNow() public IReadOnlyList<ScheduleItem> EndCurrentNow()
{ {
var index = CurrentIndex; var index = CurrentIndex;
if (CurrentItem is null) if (CurrentItem is null)
throw new ScheduleException("Es ist nichts auf Sendung."); throw new ScheduleException("Es ist nichts auf Sendung.");
var now = _now(); var now = _now();
// Whole seconds, like every other time in the plan; the next start is then not in the future. // Whole seconds: next start not in the future.
var end = new DateTime(now.Ticks - now.Ticks % TimeSpan.TicksPerSecond, now.Kind); var end = new DateTime(now.Ticks - now.Ticks % TimeSpan.TicksPerSecond, now.Kind);
return Change(index, currentAllowed: true, change: items => return Change(index, currentAllowed: true, change: items =>
{ {
@@ -213,11 +187,7 @@ public class ScheduleController
}); });
} }
/// <summary> /// <exception cref="ScheduleException">Edit not allowed for item, or item over.</exception>
/// Sets the title of a news, ad or moderator item, and the length of a news or moderator item;
/// later items shift in time. Also works for the item on air: its new length counts from its start.
/// </summary>
/// <exception cref="ScheduleException">The item cannot be edited that way, or is already over.</exception>
public IReadOnlyList<ScheduleItem> EditItem(int index, string title, TimeSpan duration) => Change(index, currentAllowed: true, change: items => public IReadOnlyList<ScheduleItem> EditItem(int index, string title, TimeSpan duration) => Change(index, currentAllowed: true, change: items =>
{ {
var item = items[index]; var item = items[index];
@@ -230,9 +200,7 @@ public class ScheduleController
items[index] = item with { Title = title.Trim(), Duration = duration }; items[index] = item with { Title = title.Trim(), Duration = duration };
}); });
// Manual edits ripple: from the first changed position on, every item starts when the one before ends. // Ripple re-time from firstChanged; news may leave :00/:30 (intended).
// News can therefore leave :00 and :30; that is the user's call.
// currentAllowed: the item on air may change too; the engine is then told to re-time it.
private IReadOnlyList<ScheduleItem> Change(int firstChanged, Action<List<ScheduleItem>> change, bool currentAllowed = false) private IReadOnlyList<ScheduleItem> Change(int firstChanged, Action<List<ScheduleItem>> change, bool currentAllowed = false)
{ {
lock (_planLock) lock (_planLock)
@@ -245,7 +213,7 @@ public class ScheduleController
? "Dieses Element ist auf Sendung. Es kann bearbeitet oder beendet, aber nicht verschoben oder entfernt werden." ? "Dieses Element ist auf Sendung. Es kann bearbeitet oder beendet, aber nicht verschoben oder entfernt werden."
: "Dieses Element ist bereits vorbei. Ein späteres wählen."); : "Dieses Element ist bereits vorbei. Ein späteres wählen.");
var items = Plan.ToList(); List<ScheduleItem> items = [.. Plan];
var start = items[firstChanged].Start; var start = items[firstChanged].Start;
change(items); change(items);
for (var i = firstChanged; i < items.Count; i++) for (var i = firstChanged; i < items.Count; i++)
@@ -261,14 +229,10 @@ public class ScheduleController
} }
} }
/// <summary>All songs in the library, for the song request picker.</summary>
public IReadOnlyList<Song> LibrarySongs() => _songs.GetAll(); public IReadOnlyList<Song> LibrarySongs() => _songs.GetAll();
/// <summary> // Hot swap: rest of half hour rebuilt so next news stays on time.
/// Hot swap: plays the song <paramref name="songId"/> in place of the item at <paramref name="index"/>. /// <exception cref="ScheduleException">Item not replaceable or song does not fit.</exception>
/// The rest of that half hour is rebuilt so the next news still starts on time; works while playing.
/// </summary>
/// <exception cref="ScheduleException">The item cannot be replaced or the song does not fit.</exception>
public IReadOnlyList<ScheduleItem> Swap(int index, long songId) public IReadOnlyList<ScheduleItem> Swap(int index, long songId)
{ {
lock (_planLock) lock (_planLock)
@@ -282,7 +246,6 @@ public class ScheduleController
var song = _songs.GetById(songId) ?? throw new ScheduleException("Der Song ist nicht mehr in der Bibliothek."); var song = _songs.GetById(songId) ?? throw new ScheduleException("Der Song ist nicht mehr in der Bibliothek.");
var plan = _generator.Replace(Plan, index, song, _songs.GetAll()); 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)) if (IsPlaying && !_engine.ReplaceUpcoming(plan, index))
throw new ScheduleException("Dieses Element ist inzwischen auf Sendung gegangen. Ein späteres wählen."); throw new ScheduleException("Dieses Element ist inzwischen auf Sendung gegangen. Ein späteres wählen.");
Plan = plan; Plan = plan;
@@ -1,16 +1,13 @@
using Radiosender.Models; using Radiosender.Models;
using Radiosender.Services; using Radiosender.Services.Library;
namespace Radiosender.Controllers; namespace Radiosender.Controllers;
/// <param name="Song">The saved song, or <c>null</c> when the upload failed.</param>
public record UploadResult(bool Success, string Message, Song? Song = null);
public class UploadController(SongImportService importService) public class UploadController(SongImportService importService)
{ {
public static string FileDialogFilter { get; } = "Audiodateien (*.mp3;*.wav)|*.mp3;*.wav"; public static string FileDialogFilter { get; } = "Audiodateien (*.mp3;*.wav)|*.mp3;*.wav";
/// <summary>Imports one file; failures come back as a result, so a batch can go on with the next file.</summary> // Never throws: batch continues with next file.
public UploadResult Upload(string filePath) public UploadResult Upload(string filePath)
{ {
try try
@@ -0,0 +1,5 @@
using Radiosender.Models;
namespace Radiosender.Controllers;
public record UploadResult(bool Success, string Message, Song? Song = null);
+1 -10
View File
@@ -1,33 +1,24 @@
namespace Radiosender.Models; namespace Radiosender.Models;
/// <summary>One search result of a music provider, in the shape the import works with.</summary>
public record MusicTrack public record MusicTrack
{ {
/// <summary> // Unique across providers (prefix with provider name, Openverse unprefixed); empty if none.
/// Identifies the track so it is not imported twice. Must be unique across all providers: a new provider
/// prefixes its ids with its own name. Empty when the provider has no id.
/// </summary>
public string Id { get; init; } = ""; public string Id { get; init; } = "";
public string Title { get; init; } = ""; public string Title { get; init; } = "";
public string? Creator { get; init; } public string? Creator { get; init; }
/// <summary>Direct https link to the audio file.</summary>
public string Url { get; init; } = ""; public string Url { get; init; } = "";
/// <summary>File extension without the dot, e.g. "mp3"; unknown ones are saved as mp3.</summary>
public string? FileType { get; init; } public string? FileType { get; init; }
/// <summary>Readable license name, for example "CC BY 4.0".</summary>
public string License { get; init; } = ""; public string License { get; init; } = "";
public string? Attribution { get; init; } public string? Attribution { get; init; }
/// <summary>Length of the track; <c>null</c> when the provider does not know it.</summary>
public TimeSpan? Duration { get; init; } public TimeSpan? Duration { get; init; }
/// <summary>Songs need a duration for scheduling, so results without one cannot be imported.</summary>
public bool CanImport => Duration is not null; public bool CanImport => Duration is not null;
public string DurationText => Duration?.ToString(@"m\:ss") ?? "unbekannt"; public string DurationText => Duration?.ToString(@"m\:ss") ?? "unbekannt";
+8 -11
View File
@@ -1,45 +1,42 @@
using System.Net;
using System.Text.Json.Serialization; using System.Text.Json.Serialization;
namespace Radiosender.Models; namespace Radiosender.Models;
/// <summary>One audio result of the Openverse search API (fields as documented at api.openverse.org/v1).</summary> // Openverse sends some texts HTML-encoded: decoded on init.
/// <remarks>Openverse sends some texts HTML-encoded (&amp;amp;), so the text fields decode on assignment.</remarks>
public class OpenverseTrack public class OpenverseTrack
{ {
public string Id { get; init; } = ""; public string Id { get; init; } = "";
public string Title { get; init => field = System.Net.WebUtility.HtmlDecode(value); } = ""; public string Title { get; init => field = WebUtility.HtmlDecode(value); } = "";
public string? Creator { get; init => field = System.Net.WebUtility.HtmlDecode(value); } public string? Creator { get; init => field = WebUtility.HtmlDecode(value); }
public string Url { get; init; } = ""; public string Url { get; init; } = "";
[JsonPropertyName("filetype")] [JsonPropertyName("filetype")]
public string? FileType { get; init; } public string? FileType { get; init; }
public string License { get; init; } = ""; public string License { get; init; } = "";
public string? LicenseVersion { get; init; } public string? LicenseVersion { get; init; }
public string? Attribution { get; init => field = System.Net.WebUtility.HtmlDecode(value); } public string? Attribution { get; init => field = WebUtility.HtmlDecode(value); }
/// <summary>Length in milliseconds; Openverse leaves it empty for some results.</summary>
[JsonPropertyName("duration")] [JsonPropertyName("duration")]
public int? DurationMs { get; init; } public int? DurationMs { get; init; }
[JsonIgnore] [JsonIgnore]
public TimeSpan? Duration => DurationMs > 0 ? TimeSpan.FromMilliseconds(DurationMs.Value) : null; public TimeSpan? Duration => DurationMs > 0 ? TimeSpan.FromMilliseconds(DurationMs.Value) : null;
private string LicenseName => License.ToLowerInvariant() switch
/// <summary>Readable license name, for example "CC BY 4.0", "CC0 1.0" or "Public Domain Mark 1.0".</summary>
public string LicenseName => License.ToLowerInvariant() switch
{ {
"cc0" => $"CC0 {LicenseVersion}".Trim(), "cc0" => $"CC0 {LicenseVersion}".Trim(),
"pdm" => $"Public Domain Mark {LicenseVersion}".Trim(), "pdm" => $"Public Domain Mark {LicenseVersion}".Trim(),
_ => $"CC {License.ToUpperInvariant()} {LicenseVersion}".Trim(), _ => $"CC {License.ToUpperInvariant()} {LicenseVersion}".Trim(),
}; };
/// <summary>The result in the provider-neutral shape. Openverse ids are stored as they come.</summary> // Openverse ids stay unprefixed, unlike other providers.
public MusicTrack ToMusicTrack() => new() public MusicTrack ToMusicTrack() => new()
{ {
Id = Id, Id = Id,
Title = Title, Title = Title,
Creator = Creator, Creator = Creator,
Url = Url, Url = Url,
// Openverse reports some MP3 files as "mp32". // Openverse reports some MP3s as "mp32".
FileType = FileType?.ToLowerInvariant() is "mp32" ? "mp3" : FileType, FileType = FileType?.ToLowerInvariant() is "mp32" ? "mp3" : FileType,
License = LicenseName, License = LicenseName,
Attribution = Attribution, Attribution = Attribution,
-10
View File
@@ -1,19 +1,9 @@
namespace Radiosender.Models; 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 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 public string KindName => Kind switch
{ {
ScheduleItemKind.News => "Nachrichten", ScheduleItemKind.News => "Nachrichten",
@@ -0,0 +1,9 @@
namespace Radiosender.Models;
public enum ScheduleItemKind
{
Song,
News,
Ad,
Moderator,
}
-10
View File
@@ -1,13 +1,5 @@
namespace Radiosender.Models; namespace Radiosender.Models;
public enum SongSource
{
Upload,
/// <summary>Downloaded from a music provider such as Openverse.</summary>
Online,
}
public class Song public class Song
{ {
public long Id { get; set; } public long Id { get; set; }
@@ -18,7 +10,5 @@ public class Song
public SongSource Source { get; set; } public SongSource Source { get; set; }
public string? License { get; set; } public string? License { get; set; }
public string? Attribution { get; set; } public string? Attribution { get; set; }
/// <summary>Id of the provider result the song was imported from (<see cref="MusicTrack.Id"/>), so it is not imported twice.</summary>
public string? ExternalId { get; set; } public string? ExternalId { get; set; }
} }
+7
View File
@@ -0,0 +1,7 @@
namespace Radiosender.Models;
public enum SongSource
{
Upload,
Online,
}
@@ -0,0 +1,7 @@
namespace Radiosender.Services.Audio;
public enum AudioSource
{
Music,
Microphone,
}
@@ -0,0 +1,10 @@
namespace Radiosender.Services.Audio;
public interface IAudioPlayer
{
event EventHandler? TrackFinished;
void Play(string filePath);
void Stop();
}
@@ -1,8 +1,7 @@
using NAudio.Wave; using NAudio.Wave;
namespace Radiosender.Services; namespace Radiosender.Services.Audio;
/// <summary>Puts the default recording device on air through the <see cref="ProgramOutput"/>, so the speaker can talk over or between items.</summary>
public sealed class Microphone(ProgramOutput output) : IDisposable public sealed class Microphone(ProgramOutput output) : IDisposable
{ {
private readonly Lock _lock = new(); private readonly Lock _lock = new();
@@ -14,7 +13,7 @@ public sealed class Microphone(ProgramOutput output) : IDisposable
get { lock (_lock) return _capture is not null; } get { lock (_lock) return _capture is not null; }
} }
/// <exception cref="InvalidOperationException">No microphone or no output device can be opened; the message can be shown to the user.</exception> /// <exception cref="InvalidOperationException">No mic or output device; message is user-facing.</exception>
public void TurnOn() public void TurnOn()
{ {
lock (_lock) lock (_lock)
@@ -25,7 +24,7 @@ public sealed class Microphone(ProgramOutput output) : IDisposable
throw new InvalidOperationException("Es wurde kein Mikrofon gefunden."); throw new InvalidOperationException("Es wurde kein Mikrofon gefunden.");
var capture = new WaveIn { WaveFormat = new WaveFormat(44100, 16, 1), BufferMilliseconds = 30 }; var capture = new WaveIn { WaveFormat = new WaveFormat(44100, 16, 1), BufferMilliseconds = 30 };
// A short buffer that drops what it cannot hold: speech must not fall further and further behind. // Short dropping buffer: speech must not drift further behind.
var buffer = new BufferedWaveProvider(capture.WaveFormat, TimeSpan.FromMilliseconds(300)) { DiscardOnBufferOverflow = true }; var buffer = new BufferedWaveProvider(capture.WaveFormat, TimeSpan.FromMilliseconds(300)) { DiscardOnBufferOverflow = true };
capture.DataAvailable += (_, e) => buffer.AddSamples(e.Buffer, 0, e.BytesRecorded); capture.DataAvailable += (_, e) => buffer.AddSamples(e.Buffer, 0, e.BytesRecorded);
try try
@@ -49,7 +48,7 @@ public sealed class Microphone(ProgramOutput output) : IDisposable
if (_input is not null) if (_input is not null)
output.Remove(_input); output.Remove(_input);
_input = null; _input = null;
_capture?.Dispose(); // stops the recording _capture?.Dispose();
_capture = null; _capture = null;
} }
} }
@@ -0,0 +1,112 @@
using System.IO;
using NAudio.Wave;
namespace Radiosender.Services.Audio;
// Events: thread pool, never UI thread. WPF: marshal via Dispatcher before touching UI.
public sealed class MusicPlayer : IAudioPlayer
{
private static readonly Lazy<MusicPlayer> LazyInstance = new(() => new MusicPlayer());
private readonly ProgramOutput _output = ProgramOutput.Instance;
private readonly Lock _lock = new();
private AudioFileReader? _reader;
private ISampleProvider? _input;
private float _volume = 1f;
private MusicPlayer()
{
// Audio thread must not wait for _lock (Stop holds it while waiting for that thread) -> thread pool.
_output.InputEnded += (_, input) => ThreadPool.QueueUserWorkItem(_ => OnInputEnded(input));
AppDomain.CurrentDomain.ProcessExit += (_, _) => Stop();
}
public static MusicPlayer Instance => LazyInstance.Value;
/// <summary>Not raised by <see cref="Stop"/> or by <see cref="Play"/> replacing a track.</summary>
public event EventHandler? TrackFinished;
public bool IsPlaying
{
get { lock (_lock) return _input is not null; }
}
public TimeSpan Duration
{
get { lock (_lock) return _reader?.TotalTime ?? TimeSpan.Zero; }
}
public float Volume
{
get { lock (_lock) return _volume; }
set
{
ArgumentOutOfRangeException.ThrowIfLessThan(value, 0f);
ArgumentOutOfRangeException.ThrowIfGreaterThan(value, 1f);
lock (_lock)
{
_volume = value;
_reader?.Volume = value;
}
}
}
public void Play(string filePath)
{
ArgumentException.ThrowIfNullOrWhiteSpace(filePath);
lock (_lock)
{
Release();
if (!File.Exists(filePath))
throw new FileNotFoundException($"Audiodatei nicht gefunden: {filePath}", filePath);
try
{
_reader = new AudioFileReader(filePath) { Volume = _volume };
_input = _output.Add(_reader, AudioSource.Music);
}
catch (Exception ex) when (ex is not (OutOfMemoryException or NAudio.MmException))
{
Release();
throw new InvalidDataException($"Audiodatei kann nicht gelesen werden: {filePath}", ex);
}
catch
{
Release(); // no output device: file must not stay open
throw;
}
}
}
public void Stop()
{
lock (_lock) Release();
}
// Caller holds _lock. Clearing _input first: Stop/replace never raise TrackFinished.
private void Release()
{
if (_input is not null)
{
// Returns after audio thread let go of reader -> safe to dispose below.
_output.Remove(_input);
_input = null;
}
_reader?.Dispose();
_reader = null;
}
private void OnInputEnded(ISampleProvider input)
{
lock (_lock)
{
if (!ReferenceEquals(input, _input)) return;
Release();
}
TrackFinished?.Invoke(this, EventArgs.Empty);
}
}
@@ -1,46 +1,29 @@
using NAudio.Wave; using NAudio.Wave;
namespace Radiosender.Services; namespace Radiosender.Services.Audio;
/// <summary>What an input of the mixer is; the levels differ by kind.</summary>
public enum AudioSource
{
Music,
Microphone,
}
/// <summary>
/// Mixes every input twice in one pass: once for the listeners (the broadcast) and once for the person at
/// the desk (the monitor). Each input is read only once, so both mixes stay in step.
/// </summary>
public sealed class ProgramMixer public sealed class ProgramMixer
{ {
private readonly Lock _lock = new(); private readonly Lock _lock = new();
private readonly List<(ISampleProvider Input, AudioSource Kind)> _inputs = []; private readonly List<(ISampleProvider Input, AudioSource Kind)> _inputs = [];
private float[] _scratch = []; private float[] _scratch = [];
// Written by the UI thread, read by the audio thread; a level that arrives one block late is fine. // UI thread writes, audio thread reads; one block late is fine.
private volatile float _musicForOthers = 1f; private volatile float _musicForOthers = 1f;
private volatile float _microphoneForOthers = 1f; private volatile float _microphoneForOthers = 1f;
private volatile float _musicForMe = 1f; private volatile float _musicForMe = 1f;
private volatile bool _listenToBroadcast = true; private volatile bool _listenToBroadcast = true;
/// <summary> /// <summary>Audio thread, under mixer lock: return at once, never call back into the mixer.</summary>
/// Raised when an input has played to its end and was dropped. Comes from the audio thread while the
/// mixer is busy: handlers must return at once and must not call back into the mixer.
/// </summary>
public event EventHandler<ISampleProvider>? InputEnded; public event EventHandler<ISampleProvider>? InputEnded;
/// <summary>How loud the music is on the broadcast, from 0 to 1.</summary>
public float MusicForOthers { get => _musicForOthers; set => _musicForOthers = Level(value); } public float MusicForOthers { get => _musicForOthers; set => _musicForOthers = Level(value); }
/// <summary>How loud the microphone is on the broadcast, from 0 to 1.</summary>
public float MicrophoneForOthers { get => _microphoneForOthers; set => _microphoneForOthers = Level(value); } public float MicrophoneForOthers { get => _microphoneForOthers; set => _microphoneForOthers = Level(value); }
/// <summary>How loud the music is on the monitor, from 0 to 1. The monitor never carries the microphone: hearing oneself late is distracting.</summary> // Monitor never carries the mic: hearing oneself late distracts.
public float MusicForMe { get => _musicForMe; set => _musicForMe = Level(value); } public float MusicForMe { get => _musicForMe; set => _musicForMe = Level(value); }
/// <summary>When set, the monitor is an exact copy of the broadcast and <see cref="MusicForMe"/> has no effect.</summary>
public bool ListenToBroadcast { get => _listenToBroadcast; set => _listenToBroadcast = value; } public bool ListenToBroadcast { get => _listenToBroadcast; set => _listenToBroadcast = value; }
public void Add(ISampleProvider input, AudioSource kind) public void Add(ISampleProvider input, AudioSource kind)
@@ -48,13 +31,12 @@ public sealed class ProgramMixer
lock (_lock) _inputs.Add((input, kind)); lock (_lock) _inputs.Add((input, kind));
} }
/// <summary>Returns once the audio thread no longer reads from the input.</summary> /// <summary>Returns once the audio thread no longer reads the input.</summary>
public void Remove(ISampleProvider input) public void Remove(ISampleProvider input)
{ {
lock (_lock) _inputs.RemoveAll(entry => ReferenceEquals(entry.Input, input)); lock (_lock) _inputs.RemoveAll(entry => ReferenceEquals(entry.Input, input));
} }
/// <summary>Fills both buffers, which must have the same length, with the next block of each mix.</summary>
public void Mix(Span<float> broadcast, Span<float> monitor) public void Mix(Span<float> broadcast, Span<float> monitor)
{ {
broadcast.Clear(); broadcast.Clear();
@@ -85,12 +67,17 @@ public sealed class ProgramMixer
} }
} }
// Two loud inputs can add up past full scale, which would distort harshly on the device. Clamp(broadcast);
for (var n = 0; n < broadcast.Length; n++) if (copyBroadcast)
{ broadcast.CopyTo(monitor);
broadcast[n] = Math.Clamp(broadcast[n], -1f, 1f); else
monitor[n] = copyBroadcast ? broadcast[n] : Math.Clamp(monitor[n], -1f, 1f); Clamp(monitor);
} }
private static void Clamp(Span<float> samples)
{
foreach (ref var sample in samples)
sample = Math.Clamp(sample, -1f, 1f);
} }
private static float Level(float value) private static float Level(float value)
@@ -2,19 +2,13 @@ using System.Runtime.InteropServices;
using NAudio.Wave; using NAudio.Wave;
using NAudio.Wave.SampleProviders; using NAudio.Wave.SampleProviders;
namespace Radiosender.Services; namespace Radiosender.Services.Audio;
/// <summary> // On-air channel only; speaker-only cues (alert tone, import preview) stay off it.
/// The station's audio channel: everything that goes on air (songs, the microphone) is mixed here.
/// The broadcast mix plays on one device for the listeners. A second device, if one is chosen, plays
/// the monitor mix for the person at the desk; without it the one device plays the monitor mix.
/// Cues for the speaker only, like the alert tone and the import preview, stay off this channel.
/// </summary>
public sealed class ProgramOutput public sealed class ProgramOutput
{ {
private static readonly Lazy<ProgramOutput> LazyInstance = new(() => new ProgramOutput()); private static readonly Lazy<ProgramOutput> LazyInstance = new(() => new ProgramOutput());
/// <summary>All inputs are converted to this format before mixing.</summary>
public static WaveFormat Format { get; } = WaveFormat.CreateIeeeFloatWaveFormat(44100, 2); public static WaveFormat Format { get; } = WaveFormat.CreateIeeeFloatWaveFormat(44100, 2);
private readonly Lock _lock = new(); private readonly Lock _lock = new();
@@ -28,27 +22,19 @@ public sealed class ProgramOutput
private ProgramOutput() private ProgramOutput()
{ {
Mixer.InputEnded += (_, input) => InputEnded?.Invoke(this, input); Mixer.InputEnded += (_, input) => InputEnded?.Invoke(this, input);
// Releases the audio devices when the app exits.
AppDomain.CurrentDomain.ProcessExit += (_, _) => { lock (_lock) CloseDevices(); }; AppDomain.CurrentDomain.ProcessExit += (_, _) => { lock (_lock) CloseDevices(); };
} }
public static ProgramOutput Instance => LazyInstance.Value; public static ProgramOutput Instance => LazyInstance.Value;
/// <summary>The levels of both mixes.</summary>
public ProgramMixer Mixer { get; } = new(); public ProgramMixer Mixer { get; } = new();
/// <summary>Same as <see cref="ProgramMixer.InputEnded"/>: raised on the audio thread, handlers must return at once.</summary> /// <summary>Audio thread: handlers must return at once.</summary>
public event EventHandler<ISampleProvider>? InputEnded; public event EventHandler<ISampleProvider>? InputEnded;
/// <summary>Names of the playback devices Windows offers, for the settings page.</summary>
public static IReadOnlyList<string> DeviceNames() => public static IReadOnlyList<string> DeviceNames() =>
Enumerable.Range(0, WaveOut.DeviceCount).Select(i => WaveOut.GetCapabilities(i).ProductName).ToList(); [.. Enumerable.Range(0, WaveOut.DeviceCount).Select(i => WaveOut.GetCapabilities(i).ProductName)];
/// <summary>
/// Chooses the devices by name: <c>null</c> for the broadcast means the Windows default device,
/// <c>null</c> for the monitor means no device of its own. Devices that are already open are reopened.
/// A name that no longer exists counts as <c>null</c>.
/// </summary>
/// <exception cref="NAudio.MmException">A device cannot be opened.</exception> /// <exception cref="NAudio.MmException">A device cannot be opened.</exception>
public void UseDevices(string? broadcast, string? monitor) public void UseDevices(string? broadcast, string? monitor)
{ {
@@ -63,47 +49,28 @@ public sealed class ProgramOutput
} }
} }
/// <summary>Puts a source on air and opens the output devices on first use.</summary> /// <exception cref="NotSupportedException">More than two channels.</exception>
/// <returns>The input as the mixer knows it; pass it to <see cref="Remove"/> and compare it in <see cref="InputEnded"/>.</returns> /// <exception cref="NAudio.MmException">No output device can be opened.</exception>
/// <exception cref="NotSupportedException">The source has more than two channels.</exception>
/// <exception cref="NAudio.MmException">No audio output device can be opened.</exception>
public ISampleProvider Add(ISampleProvider source, AudioSource kind) public ISampleProvider Add(ISampleProvider source, AudioSource kind)
{ {
var input = ToProgramFormat(source); var input = ToProgramFormat(source);
lock (_lock) lock (_lock) EnsureStarted();
{
if (!_started)
{
OpenDevices();
_started = true;
}
}
Mixer.Add(input, kind); Mixer.Add(input, kind);
return input; return input;
} }
/// <summary> /// <exception cref="NAudio.MmException">No output device can be opened.</exception>
/// Starts a copy of the broadcast mix for a live stream and opens the output devices if needed, because
/// the broadcast device sets the pace. Only one feed at a time: a new one replaces the old.
/// </summary>
/// <exception cref="NAudio.MmException">No audio output device can be opened.</exception>
public BufferedWaveProvider OpenLiveFeed() public BufferedWaveProvider OpenLiveFeed()
{ {
// Holds a few seconds; if the reader falls behind, the newest audio is dropped instead of piling up.
var feed = new BufferedWaveProvider(Format, TimeSpan.FromSeconds(5)) { DiscardOnBufferOverflow = true, ReadFully = false }; var feed = new BufferedWaveProvider(Format, TimeSpan.FromSeconds(5)) { DiscardOnBufferOverflow = true, ReadFully = false };
lock (_lock) lock (_lock)
{ {
if (!_started) EnsureStarted();
{
OpenDevices();
_started = true;
}
_liveFeed = feed; _liveFeed = feed;
} }
return feed; return feed;
} }
/// <summary>Stops copying into the feed from <see cref="OpenLiveFeed"/>.</summary>
public void CloseLiveFeed(BufferedWaveProvider feed) public void CloseLiveFeed(BufferedWaveProvider feed)
{ {
lock (_lock) lock (_lock)
@@ -113,10 +80,8 @@ public sealed class ProgramOutput
} }
} }
/// <summary>Takes an input off air. Returns once the audio thread no longer reads from it.</summary>
public void Remove(ISampleProvider input) => Mixer.Remove(input); public void Remove(ISampleProvider input) => Mixer.Remove(input);
/// <summary>Converts mono to stereo and any sample rate to the channel's 44.1 kHz.</summary>
public static ISampleProvider ToProgramFormat(ISampleProvider source) public static ISampleProvider ToProgramFormat(ISampleProvider source)
{ {
if (source.WaveFormat.Channels > 2) if (source.WaveFormat.Channels > 2)
@@ -128,13 +93,21 @@ public sealed class ProgramOutput
return source; return source;
} }
// Caller holds _lock.
private void EnsureStarted()
{
if (_started)
return;
OpenDevices();
_started = true;
}
// Caller holds _lock. // Caller holds _lock.
private void OpenDevices() private void OpenDevices()
{ {
var names = DeviceNames().ToList(); var names = DeviceNames().ToList();
var broadcast = _broadcastName is null ? -1 : names.IndexOf(_broadcastName); // -1 is the Windows default device var broadcast = _broadcastName is null ? -1 : names.IndexOf(_broadcastName); // -1 = Windows default
var monitor = _monitorName is null ? -1 : names.IndexOf(_monitorName); var monitor = _monitorName is null ? -1 : names.IndexOf(_monitorName);
// The same device twice would only play both mixes on top of each other.
if (monitor == broadcast || (broadcast == -1 && monitor == 0 && names.Count == 1)) if (monitor == broadcast || (broadcast == -1 && monitor == 0 && names.Count == 1))
monitor = -1; monitor = -1;
@@ -142,14 +115,11 @@ public sealed class ProgramOutput
{ {
if (monitor < 0) if (monitor < 0)
{ {
// One device: the person at the desk hears the monitor mix; nothing is sent anywhere else.
_broadcastDevice = Open(broadcast, new Tap(this, null)); _broadcastDevice = Open(broadcast, new Tap(this, null));
} }
else else
{ {
// The broadcast device sets the pace. Each block it asks for also yields the monitor block, // Broadcast device paces; monitor gets a short dropping buffer so clock drift never adds delay.
// which waits in a short buffer for the second device. The buffer drops what it cannot hold,
// so the two device clocks drifting apart never builds up a delay.
var monitorBuffer = new BufferedWaveProvider(Format, TimeSpan.FromMilliseconds(300)) { DiscardOnBufferOverflow = true }; var monitorBuffer = new BufferedWaveProvider(Format, TimeSpan.FromMilliseconds(300)) { DiscardOnBufferOverflow = true };
_broadcastDevice = Open(broadcast, new Tap(this, monitorBuffer)); _broadcastDevice = Open(broadcast, new Tap(this, monitorBuffer));
_monitorDevice = Open(monitor, monitorBuffer.ToSampleProvider()); _monitorDevice = Open(monitor, monitorBuffer.ToSampleProvider());
@@ -164,7 +134,7 @@ public sealed class ProgramOutput
private static WaveOut Open(int deviceNumber, ISampleProvider source) private static WaveOut Open(int deviceNumber, ISampleProvider source)
{ {
// Three buffers of 50 ms: short enough that live speech does not lag noticeably. // 3 x 50 ms: live speech must not lag noticeably.
var device = new WaveOut { DeviceNumber = deviceNumber, BufferMilliseconds = 50, NumberOfBuffers = 3 }; var device = new WaveOut { DeviceNumber = deviceNumber, BufferMilliseconds = 50, NumberOfBuffers = 3 };
try try
{ {
@@ -188,10 +158,7 @@ public sealed class ProgramOutput
_monitorDevice = null; _monitorDevice = null;
} }
/// <summary> // Pacing device source. With buffer: plays broadcast, feeds monitor. Without: plays monitor. Broadcast always to live feed.
/// What the pacing device plays. With a monitor buffer it plays the broadcast mix and feeds the buffer;
/// without one it plays the monitor mix itself. Either way the broadcast mix also goes to the live feed, if there is one.
/// </summary>
private sealed class Tap(ProgramOutput output, BufferedWaveProvider? monitorBuffer) : ISampleProvider private sealed class Tap(ProgramOutput output, BufferedWaveProvider? monitorBuffer) : ISampleProvider
{ {
private float[] _other = []; private float[] _other = [];
-11
View File
@@ -1,11 +0,0 @@
namespace Radiosender.Services;
/// <summary>The part of <see cref="MusicPlayer"/> the playback engine needs; lets tests run without audio.</summary>
public interface IAudioPlayer
{
event EventHandler? TrackFinished;
void Play(string filePath);
void Stop();
}
@@ -1,23 +0,0 @@
using Radiosender.Models;
namespace Radiosender.Services;
/// <summary>Error of a music provider or a download, with a message that can be shown to the user as is.</summary>
public class MusicProviderException(string message, Exception? inner = null) : Exception(message, inner);
/// <summary>
/// A catalog of music that can be searched online. To add one, implement this interface and register the
/// class in <c>App</c>; the import page lists every registered provider. Downloading and storing the
/// results is the same for all providers and not part of this interface.
/// </summary>
public interface IMusicProvider
{
/// <summary>Name shown to the user, for example "Openverse".</summary>
string Name { get; }
/// <summary>Whether the import page offers this provider now; one that needs a setting can hide itself.</summary>
bool IsAvailable => true;
/// <exception cref="MusicProviderException">The search failed.</exception>
Task<IReadOnlyList<MusicTrack>> SearchAsync(string query, CancellationToken cancellationToken = default);
}
@@ -0,0 +1,3 @@
namespace Radiosender.Services.Library;
public class SongImportException(string message, Exception? innerException = null) : Exception(message, innerException);
@@ -2,18 +2,14 @@ using System.IO;
using NAudio.Wave; using NAudio.Wave;
using Radiosender.Models; using Radiosender.Models;
namespace Radiosender.Services; namespace Radiosender.Services.Library;
/// <summary>An import failure with a message that can be shown to the user.</summary>
public class SongImportException(string message, Exception? innerException = null) : Exception(message, innerException);
/// <summary>Copies an uploaded MP3 or WAV file into the music folder and saves it as a song.</summary>
public class SongImportService(SongRepository songs, string musicDirectory) public class SongImportService(SongRepository songs, string musicDirectory)
{ {
public static string DefaultMusicDirectory { get; } = Path.Combine( public static string DefaultMusicDirectory { get; } = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Radiosender", "Music"); Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Radiosender", "Music");
public static IReadOnlyList<string> SupportedExtensions { get; } = [".mp3", ".wav"]; private static IReadOnlyList<string> SupportedExtensions { get; } = [".mp3", ".wav"];
/// <exception cref="SongImportException">The file is not a readable MP3 or WAV file with audio.</exception> /// <exception cref="SongImportException">The file is not a readable MP3 or WAV file with audio.</exception>
public Song Import(string sourcePath) public Song Import(string sourcePath)
@@ -74,7 +70,7 @@ public class SongImportService(SongRepository songs, string musicDirectory)
} }
catch (Exception e) catch (Exception e)
{ {
// NAudio and Media Foundation throw many unrelated exception types for corrupt files. // NAudio/Media Foundation throw many unrelated types on corrupt files.
throw new SongImportException("Die Datei ist keine lesbare MP3- oder WAV-Datei.", e); throw new SongImportException("Die Datei ist keine lesbare MP3- oder WAV-Datei.", e);
} }
@@ -3,12 +3,9 @@ using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Radiosender.Models; using Radiosender.Models;
namespace Radiosender.Services; namespace Radiosender.Services.Library;
/// <summary> // Fresh DbContext per call: safe from any thread.
/// The music library in a SQLite file, accessed through Entity Framework Core.
/// Every call uses its own short-lived context, so the repository can be used from any thread.
/// </summary>
public class SongRepository public class SongRepository
{ {
public static string DefaultDatabasePath { get; } = Path.Combine( public static string DefaultDatabasePath { get; } = Path.Combine(
@@ -23,12 +20,10 @@ public class SongRepository
.UseSqlite(new SqliteConnectionStringBuilder { DataSource = databasePath }.ToString()) .UseSqlite(new SqliteConnectionStringBuilder { DataSource = databasePath }.ToString())
.Options; .Options;
// Creates the file and the table on first start; an existing database is left as it is.
using var context = Open(); using var context = Open();
context.Database.EnsureCreated(); context.Database.EnsureCreated();
} }
/// <summary>Ids of all provider results that are already in the library.</summary>
public IReadOnlySet<string> GetExternalIds() public IReadOnlySet<string> GetExternalIds()
{ {
using var context = Open(); using var context = Open();
@@ -47,9 +42,7 @@ public class SongRepository
return context.Songs.AsNoTracking().FirstOrDefault(s => s.Id == id); return context.Songs.AsNoTracking().FirstOrDefault(s => s.Id == id);
} }
/// <summary>Inserts the song and sets its <see cref="Song.Id"/>.</summary> /// <exception cref="DbUpdateException">Rejected, e.g. duplicate external id.</exception>
/// <exception cref="ArgumentException">The song has no duration.</exception>
/// <exception cref="DbUpdateException">The database rejected the song, e.g. a second song with the same external id.</exception>
public void Add(Song song) public void Add(Song song)
{ {
RequireDuration(song); RequireDuration(song);
@@ -58,9 +51,7 @@ public class SongRepository
context.SaveChanges(); context.SaveChanges();
} }
/// <summary>Stores everything except the external id, which never changes after the import.</summary> // ExternalId never changes after import.
/// <returns><c>false</c> if no song with this id exists.</returns>
/// <exception cref="ArgumentException">The song has no duration.</exception>
public bool Update(Song song) public bool Update(Song song)
{ {
RequireDuration(song); RequireDuration(song);
@@ -75,7 +66,6 @@ public class SongRepository
.SetProperty(x => x.Attribution, song.Attribution)) == 1; .SetProperty(x => x.Attribution, song.Attribution)) == 1;
} }
/// <returns><c>false</c> if no song with this id exists.</returns>
public bool Delete(long id) public bool Delete(long id)
{ {
using var context = Open(); using var context = Open();
@@ -84,14 +74,12 @@ public class SongRepository
private LibraryContext Open() => new(_options); private LibraryContext Open() => new(_options);
// Songs need a length for scheduling. Checked here, so the rule does not depend on the database schema.
private static void RequireDuration(Song song) private static void RequireDuration(Song song)
{ {
if (song.Duration <= TimeSpan.Zero) if (song.Duration <= TimeSpan.Zero)
throw new ArgumentException("A song needs a duration longer than zero.", nameof(song)); throw new ArgumentException("A song needs a duration longer than zero.", nameof(song));
} }
/// <summary>Maps <see cref="Song"/> to the table <c>Songs</c>.</summary>
private sealed class LibraryContext(DbContextOptions<LibraryContext> options) : DbContext(options) private sealed class LibraryContext(DbContextOptions<LibraryContext> options) : DbContext(options)
{ {
public DbSet<Song> Songs => Set<Song>(); public DbSet<Song> Songs => Set<Song>();
@@ -100,14 +88,12 @@ public class SongRepository
{ {
var song = modelBuilder.Entity<Song>(); var song = modelBuilder.Entity<Song>();
song.ToTable("Songs"); song.ToTable("Songs");
// Stored as whole milliseconds in the column the first version of the app created. // Legacy column names from v1; keep for existing databases.
song.Property(s => s.Duration) song.Property(s => s.Duration)
.HasColumnName("DurationMs") .HasColumnName("DurationMs")
.HasConversion(duration => (long)duration.TotalMilliseconds, milliseconds => TimeSpan.FromMilliseconds(milliseconds)); .HasConversion(duration => (long)duration.TotalMilliseconds, milliseconds => TimeSpan.FromMilliseconds(milliseconds));
// The column keeps the name it got when Openverse was the only provider.
song.Property(s => s.ExternalId).HasColumnName("OpenverseId"); song.Property(s => s.ExternalId).HasColumnName("OpenverseId");
// One song per provider result, also if two imports of the same track race. // Unique also under racing imports; SQLite allows many NULLs.
// SQLite allows any number of rows without an id in a unique index.
song.HasIndex(s => s.ExternalId).IsUnique(); song.HasIndex(s => s.ExternalId).IsUnique();
} }
} }
-176
View File
@@ -1,176 +0,0 @@
using System.IO;
using NAudio.Wave;
namespace Radiosender.Services;
/// <summary>
/// Plays one audio file at a time on the <see cref="ProgramOutput"/>, the station's audio channel.
/// </summary>
/// <remarks>
/// <see cref="TrackFinished"/> and <see cref="PositionChanged"/> are raised on a thread-pool thread,
/// never on the WPF UI thread. WPF callers must marshal with <c>Dispatcher.Invoke</c> or
/// <c>Dispatcher.BeginInvoke</c> before touching UI elements.
/// </remarks>
public sealed class MusicPlayer : IAudioPlayer
{
private static readonly Lazy<MusicPlayer> LazyInstance = new(() => new MusicPlayer());
private static readonly TimeSpan PositionInterval = TimeSpan.FromMilliseconds(250);
private readonly ProgramOutput _output = ProgramOutput.Instance;
private readonly Lock _lock = new();
private AudioFileReader? _reader;
private ISampleProvider? _input; // the reader as it sits in the mixer; null while paused
private Timer? _positionTimer;
private float _volume = 1f;
private MusicPlayer()
{
// The mixer reports the end of a track on the audio thread, which must not wait for _lock:
// Stop holds _lock while it waits for that thread. So the work moves to the thread pool.
_output.InputEnded += (_, input) => ThreadPool.QueueUserWorkItem(_ => OnInputEnded(input));
// Releases the file when the app exits.
AppDomain.CurrentDomain.ProcessExit += (_, _) => Stop();
}
public static MusicPlayer Instance => LazyInstance.Value;
/// <summary>Raised when a track reaches its end. Not raised by <see cref="Stop"/> or by <see cref="Play"/> replacing a track.</summary>
public event EventHandler? TrackFinished;
/// <summary>Raised about every 250 ms while a track is playing, with the current position.</summary>
public event EventHandler<TimeSpan>? PositionChanged;
public bool IsPlaying
{
get { lock (_lock) return _input is not null; }
}
public TimeSpan Position
{
get { lock (_lock) return _reader?.CurrentTime ?? TimeSpan.Zero; }
}
public TimeSpan Duration
{
get { lock (_lock) return _reader?.TotalTime ?? TimeSpan.Zero; }
}
/// <summary>
/// Volume of the music from 0 (silent) to 1 (full), before it reaches the mixer, so it applies to listeners and
/// monitor alike. Kept across tracks; the microphone is not affected.
/// </summary>
public float Volume
{
get { lock (_lock) return _volume; }
set
{
ArgumentOutOfRangeException.ThrowIfLessThan(value, 0f);
ArgumentOutOfRangeException.ThrowIfGreaterThan(value, 1f);
lock (_lock)
{
_volume = value;
if (_reader is not null) _reader.Volume = value;
}
}
}
/// <summary>Stops the current track and starts playing <paramref name="filePath"/>.</summary>
/// <exception cref="FileNotFoundException">The file does not exist.</exception>
/// <exception cref="InvalidDataException">The file is not a readable audio file.</exception>
public void Play(string filePath)
{
ArgumentException.ThrowIfNullOrWhiteSpace(filePath);
lock (_lock)
{
Release();
if (!File.Exists(filePath))
throw new FileNotFoundException($"Audiodatei nicht gefunden: {filePath}", filePath);
try
{
_reader = new AudioFileReader(filePath) { Volume = _volume };
_input = _output.Add(_reader, AudioSource.Music);
}
catch (Exception ex) when (ex is not (OutOfMemoryException or NAudio.MmException))
{
Release();
throw new InvalidDataException($"Audiodatei kann nicht gelesen werden: {filePath}", ex);
}
catch
{
Release(); // no output device: the file must not stay open
throw;
}
_positionTimer = new Timer(OnPositionTimer, null, PositionInterval, PositionInterval);
}
}
public void Pause()
{
lock (_lock)
{
if (_input is null) return;
_output.Remove(_input);
_input = null;
}
}
public void Resume()
{
lock (_lock)
{
if (_reader is not null && _input is null) _input = _output.Add(_reader, AudioSource.Music);
}
}
/// <summary>Stops playback and releases the file. Does not raise <see cref="TrackFinished"/>.</summary>
public void Stop()
{
lock (_lock) Release();
}
// Caller holds _lock. Clearing _input first keeps Stop and track replacement from raising TrackFinished.
private void Release()
{
_positionTimer?.Dispose();
_positionTimer = null;
if (_input is not null)
{
// Returns once the audio thread has let go of the reader, so disposing it below is safe.
_output.Remove(_input);
_input = null;
}
_reader?.Dispose();
_reader = null;
}
private void OnInputEnded(ISampleProvider input)
{
lock (_lock)
{
// Another input of the channel, or a track that Stop or Play already replaced.
if (!ReferenceEquals(input, _input)) return;
Release();
}
TrackFinished?.Invoke(this, EventArgs.Empty);
}
private void OnPositionTimer(object? state)
{
TimeSpan position;
lock (_lock)
{
if (_input is null || _reader is null) return;
position = _reader.CurrentTime;
}
PositionChanged?.Invoke(this, position);
}
}
@@ -0,0 +1,14 @@
using Radiosender.Models;
namespace Radiosender.Services.Providers;
// New provider: implement and register in App; import page lists all registered.
public interface IMusicProvider
{
string Name { get; }
bool IsAvailable => true;
/// <exception cref="MusicProviderException">Search failed.</exception>
Task<IReadOnlyList<MusicTrack>> SearchAsync(string query, CancellationToken cancellationToken = default);
}
@@ -4,18 +4,15 @@ using System.Text.Json;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using Radiosender.Models; using Radiosender.Models;
namespace Radiosender.Services; namespace Radiosender.Services.Providers;
/// <summary> // Search returns items (often albums); each item's file list is fetched, every MP3 is one result.
/// Searches the Internet Archive for Creative Commons licensed MP3 audio. The search API returns items
/// (often whole albums), so each item's file list is fetched as well and every MP3 becomes one result.
/// </summary>
public partial class InternetArchiveProvider(HttpClient http) : IMusicProvider public partial class InternetArchiveProvider(HttpClient http) : IMusicProvider
{ {
private const string SearchUrl = "https://archive.org/advancedsearch.php"; private const string SearchUrl = "https://archive.org/advancedsearch.php";
private const string MetadataUrl = "https://archive.org/metadata/"; private const string MetadataUrl = "https://archive.org/metadata/";
// One request per item follows the search, so the item count stays small. // One extra request per item: keep small.
private const int Items = 8; private const int Items = 8;
private const int TracksPerItem = 5; private const int TracksPerItem = 5;
@@ -23,7 +20,7 @@ public partial class InternetArchiveProvider(HttpClient http) : IMusicProvider
public async Task<IReadOnlyList<MusicTrack>> SearchAsync(string query, CancellationToken cancellationToken = default) public async Task<IReadOnlyList<MusicTrack>> SearchAsync(string query, CancellationToken cancellationToken = default)
{ {
// The query language is Lucene; its operators are taken out of the user's words so they cannot change the filter. // Strip Lucene operators: user input must not change the filter.
var words = string.Join(' ', LuceneSyntax().Replace(query, " ").Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries)); var words = string.Join(' ', LuceneSyntax().Replace(query, " ").Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries));
if (words.Length == 0) if (words.Length == 0)
return []; return [];
@@ -36,12 +33,12 @@ public partial class InternetArchiveProvider(HttpClient http) : IMusicProvider
throw new MusicProviderException($"{Name}-Suche fehlgeschlagen: unerwartete Antwort."); throw new MusicProviderException($"{Name}-Suche fehlgeschlagen: unerwartete Antwort.");
var perItem = await Task.WhenAll(docs.EnumerateArray().Select(doc => TracksOfAsync(doc, cancellationToken))); var perItem = await Task.WhenAll(docs.EnumerateArray().Select(doc => TracksOfAsync(doc, cancellationToken)));
return perItem.SelectMany(tracks => tracks).ToList(); return [.. perItem.SelectMany(tracks => tracks)];
} }
private async Task<List<MusicTrack>> TracksOfAsync(JsonElement item, CancellationToken cancellationToken) private async Task<List<MusicTrack>> TracksOfAsync(JsonElement item, CancellationToken cancellationToken)
{ {
var tracks = new List<MusicTrack>(); List<MusicTrack> tracks = [];
if (ProviderParsing.Text(item, "identifier") is not { } identifier) if (ProviderParsing.Text(item, "identifier") is not { } identifier)
return tracks; return tracks;
@@ -69,11 +66,10 @@ public partial class InternetArchiveProvider(HttpClient http) : IMusicProvider
continue; continue;
var title = ProviderParsing.Text(file, "title") ?? Path.GetFileNameWithoutExtension(name); var title = ProviderParsing.Text(file, "title") ?? Path.GetFileNameWithoutExtension(name);
var creator = ProviderParsing.Text(file, "creator") ?? ProviderParsing.Text(file, "artist") ?? ProviderParsing.Text(item, "creator"); var creator = ProviderParsing.Text(file, "creator") ?? ProviderParsing.Text(file, "artist") ?? ProviderParsing.Text(item, "creator");
// A file name can contain folders; every part is escaped on its own. // Name may contain folders: escape each segment.
var path = string.Join('/', name.Split('/').Select(Uri.EscapeDataString)); var path = string.Join('/', name.Split('/').Select(Uri.EscapeDataString));
tracks.Add(new MusicTrack tracks.Add(new MusicTrack
{ {
// Prefixed, so the id cannot collide with one from another provider.
Id = $"archive:{identifier}/{name}", Id = $"archive:{identifier}/{name}",
Title = title, Title = title,
Creator = creator, Creator = creator,
@@ -1,20 +1,17 @@
using System.Net.Http; using System.Net.Http;
using System.Text.Json; using System.Text.Json;
using Radiosender.Models; using Radiosender.Models;
using Radiosender.Services.Settings;
namespace Radiosender.Services; namespace Radiosender.Services.Providers;
/// <summary> // Unofficial Radioadmin API with the user's token; may change without notice.
/// Searches the music library of the user's laut.fm station, so laut.fm tracks can be imported next to
/// local songs. Uses the API behind Radioadmin with the user's login token. laut.fm does not publish
/// this API for other programs, so it can change without notice.
/// </summary>
public class LautFmProvider(HttpClient http, Func<AppSettings> settings) : IMusicProvider public class LautFmProvider(HttpClient http, Func<AppSettings> settings) : IMusicProvider
{ {
public const string ApiBase = "https://api.radioadmin.laut.fm/"; private const string ApiBase = "https://api.radioadmin.laut.fm/";
// Radioadmin sends track searches to its own host ("searchHost" in radioadmin.laut.fm/client/_/config.json). // Track search has its own host: "searchHost" in radioadmin.laut.fm/client/_/config.json.
public const string SearchBase = "https://search.api.radioadmin.laut.fm/"; private const string SearchBase = "https://search.api.radioadmin.laut.fm/";
public string Name => "laut.fm"; public string Name => "laut.fm";
@@ -30,12 +27,12 @@ public class LautFmProvider(HttpClient http, Func<AppSettings> settings) : IMusi
if (words.Length == 0) if (words.Length == 0)
return []; return [];
// The API filters one field at a time, so title and artist are two searches. // API filters one field per request: title and artist separately.
var url = $"{SearchBase}stations/{Uri.EscapeDataString(station)}/tracks?"; var url = $"{SearchBase}stations/{Uri.EscapeDataString(station)}/tracks?";
var results = await Task.WhenAll( var results = await Task.WhenAll(
SearchFieldAsync($"{url}title={Uri.EscapeDataString(words)}", current.LautFmToken, cancellationToken), SearchFieldAsync($"{url}title={Uri.EscapeDataString(words)}", current.LautFmToken, cancellationToken),
SearchFieldAsync($"{url}artist={Uri.EscapeDataString(words)}", current.LautFmToken, cancellationToken)); SearchFieldAsync($"{url}artist={Uri.EscapeDataString(words)}", current.LautFmToken, cancellationToken));
return results.SelectMany(tracks => tracks).DistinctBy(track => track.Id).ToList(); return [.. results.SelectMany(tracks => tracks).DistinctBy(track => track.Id)];
} }
private async Task<List<MusicTrack>> SearchFieldAsync(string url, string token, CancellationToken cancellationToken) private async Task<List<MusicTrack>> SearchFieldAsync(string url, string token, CancellationToken cancellationToken)
@@ -44,7 +41,7 @@ public class LautFmProvider(HttpClient http, Func<AppSettings> settings) : IMusi
if (!json.RootElement.TryGetProperty("tracks", out var tracks) || tracks.ValueKind != JsonValueKind.Array) if (!json.RootElement.TryGetProperty("tracks", out var tracks) || tracks.ValueKind != JsonValueKind.Array)
throw new MusicProviderException($"{Name}-Suche fehlgeschlagen: unerwartete Antwort."); throw new MusicProviderException($"{Name}-Suche fehlgeschlagen: unerwartete Antwort.");
var result = new List<MusicTrack>(); List<MusicTrack> result = [];
foreach (var track in tracks.EnumerateArray()) foreach (var track in tracks.EnumerateArray())
{ {
if (ProviderParsing.Text(track, "id") is not { } id if (ProviderParsing.Text(track, "id") is not { } id
@@ -53,13 +50,11 @@ public class LautFmProvider(HttpClient http, Func<AppSettings> settings) : IMusi
continue; continue;
result.Add(new MusicTrack result.Add(new MusicTrack
{ {
// Prefixed, so the id cannot collide with one from another provider.
Id = $"lautfm:{id}", Id = $"lautfm:{id}",
Title = title, Title = title,
Creator = ProviderParsing.Text(track, "artist"), Creator = ProviderParsing.Text(track, "artist"),
Url = audio, Url = audio,
FileType = "mp3", FileType = "mp3",
// The station's tracks are licensed by laut.fm for broadcasting on laut.fm only.
License = "laut.fm (nur fĂĽr laut.fm)", License = "laut.fm (nur fĂĽr laut.fm)",
Duration = ProviderParsing.Duration(ProviderParsing.Text(track, "duration")), Duration = ProviderParsing.Duration(ProviderParsing.Text(track, "duration")),
}); });
@@ -67,7 +62,7 @@ public class LautFmProvider(HttpClient http, Func<AppSettings> settings) : IMusi
return result; return result;
} }
// The link the Radioadmin player uses; it needs no login. Relative links are taken against the API. // Radioadmin player link, no login; relative to ApiBase; https only.
private static string? PrelistenUrl(JsonElement track) private static string? PrelistenUrl(JsonElement track)
{ {
if (!track.TryGetProperty("_links", out var links) || links.ValueKind != JsonValueKind.Object if (!track.TryGetProperty("_links", out var links) || links.ValueKind != JsonValueKind.Object
@@ -0,0 +1,3 @@
namespace Radiosender.Services.Providers;
public class MusicProviderException(string message, Exception? inner = null) : Exception(message, inner);
@@ -4,9 +4,8 @@ using System.Net.Http.Json;
using System.Text.Json; using System.Text.Json;
using Radiosender.Models; using Radiosender.Models;
namespace Radiosender.Services; namespace Radiosender.Services.Providers;
/// <summary>Searches the Openverse audio catalog anonymously.</summary>
public class OpenverseProvider(HttpClient http) : IMusicProvider public class OpenverseProvider(HttpClient http) : IMusicProvider
{ {
private const string SearchUrl = "https://api.openverse.org/v1/audio/"; private const string SearchUrl = "https://api.openverse.org/v1/audio/";
@@ -1,16 +1,14 @@
using System.Globalization; using System.Globalization;
using System.Net;
using System.Net.Http; using System.Net.Http;
using System.Text.Json; using System.Text.Json;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
namespace Radiosender.Services; namespace Radiosender.Services.Providers;
/// <summary>Helpers for JSON-based music providers: fetching, and reading licenses and durations.</summary>
internal static partial class ProviderParsing internal static partial class ProviderParsing
{ {
/// <summary>Fetches <paramref name="url"/> and parses it as JSON, whatever content type the server names.</summary> /// <exception cref="MusicProviderException">Request failed or answer is not JSON.</exception>
/// <param name="bearerToken">Sent as the Authorization header when set.</param>
/// <exception cref="MusicProviderException">The request failed or the answer is not JSON.</exception>
public static async Task<JsonDocument> GetJsonAsync(HttpClient http, string url, string provider, CancellationToken cancellationToken, string? bearerToken = null) public static async Task<JsonDocument> GetJsonAsync(HttpClient http, string url, string provider, CancellationToken cancellationToken, string? bearerToken = null)
{ {
try try
@@ -19,11 +17,11 @@ internal static partial class ProviderParsing
if (bearerToken is not null) if (bearerToken is not null)
request.Headers.Authorization = new("Bearer", bearerToken); request.Headers.Authorization = new("Bearer", bearerToken);
using var response = await http.SendAsync(request, cancellationToken); using var response = await http.SendAsync(request, cancellationToken);
if (response.StatusCode is System.Net.HttpStatusCode.Unauthorized or System.Net.HttpStatusCode.Forbidden && bearerToken is not null) if (response.StatusCode is HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden && bearerToken is not null)
throw new MusicProviderException($"{provider} hat die Anmeldung abgelehnt. Den Token in den Einstellungen prĂĽfen."); throw new MusicProviderException($"{provider} hat die Anmeldung abgelehnt. Den Token in den Einstellungen prĂĽfen.");
if (!response.IsSuccessStatusCode) if (!response.IsSuccessStatusCode)
throw new MusicProviderException($"{provider} hat HTTP {(int)response.StatusCode} geliefert."); throw new MusicProviderException($"{provider} hat HTTP {(int)response.StatusCode} geliefert.");
// Parsed without looking at the content type: not every API labels its JSON as such. // Content type ignored: not every API labels JSON.
return JsonDocument.Parse(await response.Content.ReadAsStringAsync(cancellationToken)); return JsonDocument.Parse(await response.Content.ReadAsStringAsync(cancellationToken));
} }
catch (Exception e) when (e is not MusicProviderException && !cancellationToken.IsCancellationRequested) catch (Exception e) when (e is not MusicProviderException && !cancellationToken.IsCancellationRequested)
@@ -37,10 +35,7 @@ internal static partial class ProviderParsing
} }
} }
/// <summary> // String, number digits, or first array entry (Archive: one creator as string, several as list).
/// The property as text: a string as it is, a number as its digits, and the first entry of a list
/// (the Internet Archive sends one creator as a string and several as a list). Otherwise <c>null</c>.
/// </summary>
public static string? Text(JsonElement element, string property) public static string? Text(JsonElement element, string property)
{ {
if (element.ValueKind != JsonValueKind.Object || !element.TryGetProperty(property, out var value)) if (element.ValueKind != JsonValueKind.Object || !element.TryGetProperty(property, out var value))
@@ -49,14 +44,13 @@ internal static partial class ProviderParsing
value = value.EnumerateArray().FirstOrDefault(); value = value.EnumerateArray().FirstOrDefault();
var text = value.ValueKind switch var text = value.ValueKind switch
{ {
JsonValueKind.String => System.Net.WebUtility.HtmlDecode(value.GetString()), JsonValueKind.String => WebUtility.HtmlDecode(value.GetString()),
JsonValueKind.Number => value.GetRawText(), JsonValueKind.Number => value.GetRawText(),
_ => null, _ => null,
}; };
return string.IsNullOrWhiteSpace(text) ? null : text.Trim(); return string.IsNullOrWhiteSpace(text) ? null : text.Trim();
} }
/// <summary>Readable name for a Creative Commons license URL, e.g. "CC BY-NC 3.0"; <c>null</c> for anything else.</summary>
public static string? License(string? url) public static string? License(string? url)
{ {
if (url is null) if (url is null)
@@ -68,7 +62,7 @@ internal static partial class ProviderParsing
return null; return null;
} }
/// <summary>Reads "2:36", "05:32", "1:02:03" or seconds such as "3808.26"; <c>null</c> when it is none of them.</summary> // "2:36", "1:02:03" or seconds "3808.26".
public static TimeSpan? Duration(string? text) public static TimeSpan? Duration(string? text)
{ {
if (string.IsNullOrWhiteSpace(text)) if (string.IsNullOrWhiteSpace(text))
@@ -81,7 +75,7 @@ internal static partial class ProviderParsing
return null; return null;
seconds = seconds * 60 + value; seconds = seconds * 60 + value;
} }
// An upper bound keeps a nonsense value from overflowing TimeSpan. // Upper bound: no TimeSpan overflow on nonsense.
return parts.Length <= 3 && seconds is > 0 and < 86400 ? TimeSpan.FromSeconds(seconds) : null; return parts.Length <= 3 && seconds is > 0 and < 86400 ? TimeSpan.FromSeconds(seconds) : null;
} }
@@ -2,9 +2,8 @@ using System.IO;
using System.Net.Http; using System.Net.Http;
using Radiosender.Models; using Radiosender.Models;
namespace Radiosender.Services; namespace Radiosender.Services.Providers;
/// <summary>Downloads the audio file of a <see cref="MusicTrack"/> into the music folder, for any provider.</summary>
public class TrackDownloader(HttpClient http, string musicFolder) public class TrackDownloader(HttpClient http, string musicFolder)
{ {
public static string DefaultMusicFolder { get; } = Path.Combine( public static string DefaultMusicFolder { get; } = Path.Combine(
@@ -14,15 +13,10 @@ public class TrackDownloader(HttpClient http, string musicFolder)
private static readonly HashSet<string> KnownExtensions = ["mp3", "ogg", "oga", "wav", "flac", "m4a", "aac", "opus"]; private static readonly HashSet<string> KnownExtensions = ["mp3", "ogg", "oga", "wav", "flac", "m4a", "aac", "opus"];
/// <summary>Limit for the whole download; <see cref="HttpClient.Timeout"/> only covers the response headers here.</summary> // Whole download; HttpClient.Timeout only covers headers (ResponseHeadersRead).
public TimeSpan DownloadTimeout { get; init; } = TimeSpan.FromMinutes(3); private static readonly TimeSpan DownloadTimeout = TimeSpan.FromMinutes(3);
/// <summary> /// <exception cref="MusicProviderException">Download failed or file not acceptable.</exception>
/// Downloads <see cref="MusicTrack.Url"/> into the music folder under a new, unique file name.
/// On any failure no file is left behind.
/// </summary>
/// <returns>Full path of the downloaded file.</returns>
/// <exception cref="MusicProviderException">The download failed or the file is not acceptable.</exception>
public async Task<string> DownloadAsync(MusicTrack track, CancellationToken cancellationToken = default) public async Task<string> DownloadAsync(MusicTrack track, CancellationToken cancellationToken = default)
{ {
if (!Uri.TryCreate(track.Url, UriKind.Absolute, out var uri) || uri.Scheme != Uri.UriSchemeHttps) if (!Uri.TryCreate(track.Url, UriKind.Absolute, out var uri) || uri.Scheme != Uri.UriSchemeHttps)
@@ -58,7 +52,7 @@ public class TrackDownloader(HttpClient http, string musicFolder)
} }
catch (Exception e) catch (Exception e)
{ {
// "await using" in the try block has already closed the file here. // await using already closed the file.
if (path is not null) if (path is not null)
File.Delete(path); File.Delete(path);
if (e is MusicProviderException || cancellationToken.IsCancellationRequested) if (e is MusicProviderException || cancellationToken.IsCancellationRequested)
@@ -81,7 +75,7 @@ public class TrackDownloader(HttpClient http, string musicFolder)
{ {
var candidate = Path.Combine(musicFolder, i == 1 ? $"{name}.{extension}" : $"{name} ({i}).{extension}"); var candidate = Path.Combine(musicFolder, i == 1 ? $"{name}.{extension}" : $"{name} ({i}).{extension}");
if (File.Exists(candidate)) continue; if (File.Exists(candidate)) continue;
// CreateNew never overwrites; path is only reported once this call owns the file. // CreateNew never overwrites; path set only once owned.
var stream = new FileStream(candidate, FileMode.CreateNew, FileAccess.Write, FileShare.None, 81920, useAsync: true); var stream = new FileStream(candidate, FileMode.CreateNew, FileAccess.Write, FileShare.None, 81920, useAsync: true);
path = candidate; path = candidate;
return stream; return stream;
@@ -1,69 +1,46 @@
using Radiosender.Models; using Radiosender.Models;
using Radiosender.Services.Audio;
namespace Radiosender.Services; namespace Radiosender.Services.Scheduling;
/// <summary> // Songs never cut. Events: thread pool; WPF use BeginInvoke, not Invoke (Stop waits -> deadlock).
/// Runs a generated schedule on the real clock: each item starts at its planned time, or right after the public sealed class PlaybackEngine(IAudioPlayer player, Func<TimeSpan, CancellationToken, Task> delay, Func<DateTime> now)
/// previous item if that one ran late. Songs play through the audio player, news, ads and moderator
/// placeholders are held for their duration. Songs are never cut.
/// </summary>
/// <remarks>
/// Events are raised on the engine's thread-pool thread. WPF callers must marshal with
/// <c>Dispatcher.BeginInvoke</c>, not <c>Dispatcher.Invoke</c>: <see cref="Stop"/> waits for that thread,
/// so a handler that blocks on the UI thread while the UI calls Stop would deadlock.
/// </remarks>
public sealed class PlaybackEngine
{ {
// Extra time before a song counts as stuck, e.g. after an audio device error that never raises TrackFinished. // Stuck-song grace, e.g. device error that never raises TrackFinished.
private static readonly TimeSpan SongGrace = TimeSpan.FromSeconds(10); private static readonly TimeSpan SongGrace = TimeSpan.FromSeconds(10);
// An item that started at most this long ago still plays when the broadcast starts, e.g. a click right after 15:00. // Item started at most this long ago still plays on start (click right after 15:00).
private static readonly TimeSpan LateStart = TimeSpan.FromSeconds(5); private static readonly TimeSpan LateStart = TimeSpan.FromSeconds(5);
private readonly IAudioPlayer _player; private readonly IAudioPlayer _player = player;
private readonly Func<TimeSpan, CancellationToken, Task> _delay; private readonly Func<TimeSpan, CancellationToken, Task> _delay = delay;
private readonly Func<DateTime> _now; private readonly Func<DateTime> _now = now;
private readonly Lock _lock = new(); private readonly Lock _lock = new();
private CancellationTokenSource? _cts; private CancellationTokenSource? _cts;
private Task _run = Task.CompletedTask; private Task _run = Task.CompletedTask;
// Completed by ReplaceCurrent to wake the wait of the item on air; a new one per wait. // Set by ReplaceCurrent to wake the on-air wait; new one per wait.
private TaskCompletionSource? _currentChanged; private TaskCompletionSource? _currentChanged;
public PlaybackEngine() : this(MusicPlayer.Instance, Task.Delay, () => DateTime.Now) public PlaybackEngine() : this(MusicPlayer.Instance, Task.Delay, () => DateTime.Now)
{ {
} }
public PlaybackEngine(IAudioPlayer player, Func<TimeSpan, CancellationToken, Task> delay, Func<DateTime> now)
{
_player = player;
_delay = delay;
_now = now;
}
/// <summary>Raised when an item starts, with its index in <see cref="Items"/>.</summary>
public event EventHandler<(int Index, ScheduleItem Item)>? ItemStarted; public event EventHandler<(int Index, ScheduleItem Item)>? ItemStarted;
/// <summary>Raised when a song cannot be played; the engine then moves on to the next item.</summary>
public event EventHandler<(ScheduleItem Item, Exception Error)>? ItemFailed; public event EventHandler<(ScheduleItem Item, Exception Error)>? ItemFailed;
/// <summary>Raised after the last item has ended. Not raised by <see cref="Stop"/>.</summary> /// <summary>Not raised by <see cref="Stop"/>.</summary>
public event EventHandler? Finished; public event EventHandler? Finished;
public IReadOnlyList<ScheduleItem> Items { get; private set; } = []; public IReadOnlyList<ScheduleItem> Items { get; private set; } = [];
/// <summary>Index of the item that is playing, or -1 when the engine is not running.</summary>
public int CurrentIndex { get; private set; } = -1; public int CurrentIndex { get; private set; } = -1;
public bool IsRunning => !_run.IsCompleted; public bool IsRunning => !_run.IsCompleted;
/// <summary>Planned start the engine waits for, or <c>null</c> when it is not waiting.</summary>
public DateTime? WaitingUntil { get; private set; } public DateTime? WaitingUntil { get; private set; }
/// <summary>
/// Stops any running schedule and starts <paramref name="items"/> on the clock. Items that should have
/// started earlier are skipped; before the first planned start the engine waits.
/// </summary>
public void Start(IReadOnlyList<ScheduleItem> items) public void Start(IReadOnlyList<ScheduleItem> items)
{ {
Stop(); Stop();
@@ -76,10 +53,7 @@ public sealed class PlaybackEngine
} }
} }
/// <summary> /// <summary>Items before <paramref name="fromIndex"/> must be unchanged. False if that item already started.</summary>
/// Hot swap: switches to <paramref name="items"/> while playing. Items before <paramref name="fromIndex"/>
/// must be unchanged. Returns <c>false</c> if the item at <paramref name="fromIndex"/> has already started.
/// </summary>
public bool ReplaceUpcoming(IReadOnlyList<ScheduleItem> items, int fromIndex) public bool ReplaceUpcoming(IReadOnlyList<ScheduleItem> items, int fromIndex)
{ {
lock (_lock) lock (_lock)
@@ -91,12 +65,7 @@ public sealed class PlaybackEngine
} }
} }
/// <summary> /// <summary>On-air item changed: hold item gets new length from its start, song ends at once. False if not on air.</summary>
/// Switches to <paramref name="items"/> while the item at <paramref name="index"/> is on air and that item
/// itself changed: a news, ad or moderator item then runs for its new length, counted from when it started,
/// and a song ends at once. Items before <paramref name="index"/> must be unchanged. Returns <c>false</c>
/// if that item is not the one on air.
/// </summary>
public bool ReplaceCurrent(IReadOnlyList<ScheduleItem> items, int index) public bool ReplaceCurrent(IReadOnlyList<ScheduleItem> items, int index)
{ {
lock (_lock) lock (_lock)
@@ -109,7 +78,6 @@ public sealed class PlaybackEngine
} }
} }
/// <summary>Stops playback. Waits until the running schedule has ended.</summary>
public void Stop() public void Stop()
{ {
Task run; Task run;
@@ -151,7 +119,6 @@ public sealed class PlaybackEngine
if (item.Start < skipBefore) if (item.Start < skipBefore)
continue; continue;
// Early items wait for their slot, so the news hits :00 and :30; late items start right away.
var wait = item.Start - _now(); var wait = item.Start - _now();
if (wait > TimeSpan.Zero) if (wait > TimeSpan.Zero)
{ {
@@ -160,7 +127,7 @@ public sealed class PlaybackEngine
finally { WaitingUntil = null; } finally { WaitingUntil = null; }
} }
// Under the lock so ReplaceUpcoming cannot swap the item that is about to start. // Lock: ReplaceUpcoming must not swap the item about to start.
lock (_lock) lock (_lock)
{ {
if (i >= Items.Count) break; if (i >= Items.Count) break;
@@ -184,8 +151,6 @@ public sealed class PlaybackEngine
} }
} }
// Keeps a news, ad or moderator item on air for its length. ReplaceCurrent can change that length
// meanwhile; the wait then starts over with what is left.
private async Task HoldAsync(int index, CancellationToken token) private async Task HoldAsync(int index, CancellationToken token)
{ {
var startedAt = _now(); var startedAt = _now();
@@ -202,11 +167,11 @@ public sealed class PlaybackEngine
return; return;
using var wait = CancellationTokenSource.CreateLinkedTokenSource(token); using var wait = CancellationTokenSource.CreateLinkedTokenSource(token);
var delay = _delay(remaining, wait.Token); var elapsed = _delay(remaining, wait.Token);
var done = await Task.WhenAny(delay, changed.Task); var done = await Task.WhenAny(elapsed, changed.Task);
wait.Cancel(); await wait.CancelAsync();
token.ThrowIfCancellationRequested(); token.ThrowIfCancellationRequested();
if (done == delay) if (done == elapsed)
return; return;
} }
} }
@@ -234,9 +199,8 @@ public sealed class PlaybackEngine
changed = _currentChanged = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); changed = _currentChanged = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(token); using var timeout = CancellationTokenSource.CreateLinkedTokenSource(token);
var stuck = _delay(item.Duration + SongGrace, timeout.Token); var stuck = _delay(item.Duration + SongGrace, timeout.Token);
// changed: the user ended the song early; the finally block stops the player.
var done = await Task.WhenAny(finished.Task, stuck, changed.Task); var done = await Task.WhenAny(finished.Task, stuck, changed.Task);
timeout.Cancel(); await timeout.CancelAsync();
token.ThrowIfCancellationRequested(); token.ThrowIfCancellationRequested();
if (done == stuck) if (done == stuck)
ItemFailed?.Invoke(this, (item, new TimeoutException($"Der Song wurde nicht rechtzeitig fertig: {item.Title}"))); ItemFailed?.Invoke(this, (item, new TimeoutException($"Der Song wurde nicht rechtzeitig fertig: {item.Title}")));
@@ -244,7 +208,7 @@ public sealed class PlaybackEngine
finally finally
{ {
_player.TrackFinished -= OnFinished; _player.TrackFinished -= OnFinished;
// On cancel, timeout or a failed start the song has not ended by itself. // Cancel, timeout, or user ended song (changed): stop player.
if (!finished.Task.IsCompleted) _player.Stop(); if (!finished.Task.IsCompleted) _player.Stop();
} }
} }
@@ -0,0 +1,3 @@
namespace Radiosender.Services.Scheduling;
public class ScheduleException(string message) : Exception(message);
@@ -1,71 +1,40 @@
using Radiosender.Models; using Radiosender.Models;
namespace Radiosender.Services; namespace Radiosender.Services.Scheduling;
public record ScheduleOptions // Half-hour slots: news at :00/:30; last song ends exactly at next news; ads/talk fill the rest.
{
public TimeSpan NewsDuration { get; init; } = TimeSpan.FromMinutes(5);
/// <summary>Target for ads per hour. Met as closely as the song lengths allow.</summary>
public TimeSpan AdsPerHour { get; init; } = TimeSpan.FromMinutes(20);
/// <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 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; 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
/// 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) 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; 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); 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 var options = Options; // snapshot: Options can be swapped mid-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 (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(); List<Song> playable = [.. songs.Where(s => s.Duration > TimeSpan.Zero)];
if (playable.Count == 0) if (playable.Count == 0)
throw new ScheduleException("Die Bibliothek enthält keine Songs zum Planen."); throw new ScheduleException("Die Bibliothek enthält keine Songs zum Planen.");
var items = new List<ScheduleItem>(); List<ScheduleItem> items = [];
var firstNews = new DateTime((start.Ticks + HalfHour.Ticks - 1) / HalfHour.Ticks * HalfHour.Ticks, start.Kind); var firstNews = new DateTime((start.Ticks + HalfHour.Ticks - 1) / HalfHour.Ticks * HalfHour.Ticks, start.Kind);
if (firstNews > start) if (firstNews > start)
items.AddRange(BuildLeadIn(options, start, firstNews - start, playable)); items.AddRange(BuildLeadIn(options, start, firstNews - start, playable));
var adHalf = options.AdsPerHour / 2; var adHalf = options.AdsPerHour / 2;
var moderatorHalf = options.ModeratorPerHour / 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. // :00 slot over/under target; :30 slot compensates.
var adOver = TimeSpan.Zero; var adOver = TimeSpan.Zero;
var moderatorOver = TimeSpan.Zero; var moderatorOver = TimeSpan.Zero;
for (var slotStart = firstNews; slotStart < firstNews.AddHours(hours); slotStart += HalfHour) for (var slotStart = firstNews; slotStart < firstNews.AddHours(hours); slotStart += HalfHour)
@@ -88,7 +57,6 @@ public class ScheduleGenerator(ScheduleOptions options, Random random)
private List<ScheduleItem> BuildLeadIn(ScheduleOptions options, DateTime start, TimeSpan length, List<Song> songs) private List<ScheduleItem> BuildLeadIn(ScheduleOptions options, DateTime start, TimeSpan length, List<Song> songs)
{ {
// The targets shrink with the lead-in: half of a half hour gets half of the ads.
var share = length / HalfHour; var share = length / HalfHour;
try try
{ {
@@ -96,7 +64,7 @@ public class ScheduleGenerator(ScheduleOptions options, Random random)
} }
catch (ScheduleException) when (length <= (options.AdsPerHour + options.ModeratorPerHour) / 2) catch (ScheduleException) when (length <= (options.AdsPerHour + options.ModeratorPerHour) / 2)
{ {
// Too short for any song: the moderator talks until the news. // Too short for any song: moderator fills.
return [new ScheduleItem(ScheduleItemKind.Moderator, "", start, length)]; return [new ScheduleItem(ScheduleItemKind.Moderator, "", start, length)];
} }
} }
@@ -108,7 +76,6 @@ public class ScheduleGenerator(ScheduleOptions options, Random random)
return []; return [];
var target = Min(adTarget + moderatorTarget, length); var target = Min(adTarget + moderatorTarget, length);
var (picked, gap) = PickBest(options, length, target, songs); 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) if (picked.Count == 0 && target < length)
throw new ScheduleException( 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."); $"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.");
@@ -117,12 +84,8 @@ public class ScheduleGenerator(ScheduleOptions options, Random random)
return Arrange(options, slotStart, picked, ads, moderator, keepFirstSongFirst: false); return Arrange(options, slotStart, picked, ads, moderator, keepFirstSongFirst: false);
} }
/// <summary> // Hot swap: rebuilds rest of the slot only; earlier items and later slots stay.
/// Hot swap: puts <paramref name="requested"/> at <paramref name="index"/> in place of that item and /// <exception cref="ScheduleException">Song does not fit before next news.</exception>
/// 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.</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);
@@ -142,13 +105,13 @@ public class ScheduleGenerator(ScheduleOptions options, Random random)
throw new ScheduleException( throw new ScheduleException(
$"\"{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."); $"\"{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. // Ads/talk already in this slot count against its targets.
var options = Options; var options = Options;
var prefix = plan.Take(index).ToList(); List<ScheduleItem> prefix = [.. plan.Take(index)];
var slotPrefix = prefix.Skip(slotStartIndex + 1).ToList(); List<ScheduleItem> slotPrefix = [.. prefix.Skip(slotStartIndex + 1)];
var adTarget = Max(options.AdsPerHour / 2 - Sum(slotPrefix.Where(i => i.Kind == ScheduleItemKind.Ad)), TimeSpan.Zero); 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 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(); List<Song> playable = [.. songs.Where(s => s.Duration > TimeSpan.Zero)];
var (picked, gap) = PickBest(options, length, Min(adTarget + moderatorTarget, length), playable, requested); var (picked, gap) = PickBest(options, length, Min(adTarget + moderatorTarget, length), playable, requested);
var (ads, moderator) = Split(options, gap, adTarget, moderatorTarget); var (ads, moderator) = Split(options, gap, adTarget, moderatorTarget);
@@ -170,8 +133,7 @@ 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 // Picks never exceed music budget, so gap >= target; smallest gap wins.
// moderator talk. Picks never go over the music time, so the leftover is the target or more.
private (List<Song> Songs, TimeSpan Gap) PickBest( private (List<Song> Songs, TimeSpan Gap) PickBest(
ScheduleOptions options, TimeSpan length, TimeSpan target, List<Song> songs, Song? first = null) ScheduleOptions options, TimeSpan length, TimeSpan target, List<Song> songs, Song? first = null)
{ {
@@ -193,12 +155,12 @@ public class ScheduleGenerator(ScheduleOptions options, Random random)
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>(); List<Song> picked = [];
var left = budget; var left = budget;
while (true) while (true)
{ {
var last = picked.Count > 0 ? picked[^1] : previous; 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(); List<Song> fitting = [.. songs.Where(s => s.Duration <= left && (last is null || s.Id != last.Id || songs.Count == 1))];
if (fitting.Count == 0) if (fitting.Count == 0)
return picked; return picked;
var song = fitting[random.Next(fitting.Count)]; var song = fitting[random.Next(fitting.Count)];
@@ -207,12 +169,11 @@ public class ScheduleGenerator(ScheduleOptions options, Random random)
} }
} }
// Shares the leftover time between ads and moderator talk in the ratio of their targets. // Gap split in target ratio; no target left: hourly ratio, else talk only.
private static (TimeSpan Ads, TimeSpan Moderator) Split(ScheduleOptions options, TimeSpan gap, TimeSpan adTarget, TimeSpan moderatorTarget) private static (TimeSpan Ads, TimeSpan Moderator) Split(ScheduleOptions options, TimeSpan gap, TimeSpan adTarget, TimeSpan moderatorTarget)
{ {
if (adTarget + moderatorTarget <= TimeSpan.Zero) if (adTarget + moderatorTarget <= TimeSpan.Zero)
{ {
// This slot has nothing left to aim for; fall back to the hourly ratio, or to talk alone.
adTarget = options.AdsPerHour; adTarget = options.AdsPerHour;
moderatorTarget = options.ModeratorPerHour; moderatorTarget = options.ModeratorPerHour;
if (adTarget + moderatorTarget <= TimeSpan.Zero) if (adTarget + moderatorTarget <= TimeSpan.Zero)
@@ -223,29 +184,25 @@ public class ScheduleGenerator(ScheduleOptions options, Random random)
return (ads, gap - ads); return (ads, gap - ads);
} }
// Lays out the slot: songs with breaks in between, each break "moderator, ad, moderator, ad ...". // Breaks "moderator, ad, moderator, ad..." between songs; ads <= MaxAdBlock, never back to back; slot ends with a song.
// 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( private static List<ScheduleItem> Arrange(
ScheduleOptions options, DateTime start, List<Song> songs, TimeSpan ads, TimeSpan moderator, bool keepFirstSongFirst) ScheduleOptions options, DateTime start, List<Song> songs, TimeSpan ads, TimeSpan moderator, bool keepFirstSongFirst)
{ {
var adPieces = Pieces(ads, (int)Math.Ceiling(ads / options.MaxAdBlock)); 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 moderatorPieces = Pieces(moderator, adPieces.Count > 0 ? adPieces.Count : (int)Math.Ceiling(moderator / TimeSpan.FromMinutes(5)));
var pairs = Math.Max(adPieces.Count, moderatorPieces.Count); 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. // Hot swap: requested song stays first, breaks start after it.
var firstBreakSong = keepFirstSongFirst && songs.Count > 1 ? 1 : 0; var firstBreakSong = keepFirstSongFirst && songs.Count > 1 ? 1 : 0;
var breakSlots = Math.Max(songs.Count - firstBreakSong, 1); var breakSlots = Math.Max(songs.Count - firstBreakSong, 1);
var breaks = Math.Min(pairs, breakSlots); var breaks = Math.Min(pairs, breakSlots);
var items = new List<ScheduleItem>(); List<ScheduleItem> items = [];
var time = start; var time = start;
void Add(ScheduleItemKind kind, TimeSpan duration, Song? song = null) void Add(ScheduleItemKind kind, TimeSpan duration, Song? song = null)
{ {
if (duration <= TimeSpan.Zero) if (duration <= TimeSpan.Zero)
return; 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}"; var title = song is null ? "" : string.IsNullOrWhiteSpace(song.Artist) ? song.Title : $"{song.Artist} - {song.Title}";
items.Add(new ScheduleItem(kind, title, time, duration, song)); items.Add(new ScheduleItem(kind, title, time, duration, song));
time += duration; time += duration;
@@ -254,7 +211,6 @@ public class ScheduleGenerator(ScheduleOptions options, Random random)
var pair = 0; var pair = 0;
void AddBreak(int number) 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; var until = number == breaks - 1 ? pairs : pairs * (number + 1) / breaks;
for (; pair < until; pair++) for (; pair < until; pair++)
{ {
@@ -266,24 +222,21 @@ public class ScheduleGenerator(ScheduleOptions options, Random random)
var nextBreak = 0; var nextBreak = 0;
for (var i = 0; i < songs.Count; i++) for (var i = 0; i < songs.Count; i++)
{ {
// Break n sits before the song at its share of the way through the slot.
while (nextBreak < breaks && i == firstBreakSong + nextBreak * breakSlots / breaks) while (nextBreak < breaks && i == firstBreakSong + nextBreak * breakSlots / breaks)
AddBreak(nextBreak++); AddBreak(nextBreak++);
Add(ScheduleItemKind.Song, songs[i].Duration, songs[i]); Add(ScheduleItemKind.Song, songs[i].Duration, songs[i]);
} }
// No songs at all: the slot is ads and talk only.
while (nextBreak < breaks) while (nextBreak < breaks)
AddBreak(nextBreak++); AddBreak(nextBreak++);
return items; return items;
} }
// Cuts a time into pieces of whole seconds that differ by at most one second, so no piece grows past // Whole-second pieces differing by <= 1 s, so none exceeds the limit; sub-second rest goes to last piece.
// 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) private static List<TimeSpan> Pieces(TimeSpan total, int count)
{ {
var pieces = new List<TimeSpan>();
if (total <= TimeSpan.Zero || count < 1) if (total <= TimeSpan.Zero || count < 1)
return pieces; return [];
List<TimeSpan> pieces = [];
var seconds = (long)Math.Floor(total.TotalSeconds); var seconds = (long)Math.Floor(total.TotalSeconds);
for (var i = 0; i < count; i++) for (var i = 0; i < count; i++)
pieces.Add(TimeSpan.FromSeconds(seconds / count + (i < seconds % count ? 1 : 0))); pieces.Add(TimeSpan.FromSeconds(seconds / count + (i < seconds % count ? 1 : 0)));
@@ -0,0 +1,14 @@
namespace Radiosender.Services.Scheduling;
public record ScheduleOptions
{
public TimeSpan NewsDuration { get; init; } = TimeSpan.FromMinutes(5);
public TimeSpan AdsPerHour { get; init; } = TimeSpan.FromMinutes(20);
public TimeSpan ModeratorPerHour { get; init; } = TimeSpan.FromMinutes(10);
public TimeSpan MaxAdBlock { get; init; } = TimeSpan.FromMinutes(5);
public int Attempts { get; init; } = 400;
}
@@ -3,51 +3,42 @@ using System.Security.Cryptography;
using System.Text; using System.Text;
using System.Text.Json; using System.Text.Json;
using System.Text.Json.Serialization; using System.Text.Json.Serialization;
using Radiosender.Services.Scheduling;
namespace Radiosender.Services; namespace Radiosender.Services.Settings;
/// <summary>What the user can change on the Settings page. The defaults are the values the app shipped with.</summary>
public record AppSettings public record AppSettings
{ {
public const int MinAlertSeconds = 5; private const int MinAlertSeconds = 5;
public const int MaxAlertSeconds = 300; private const int MaxAlertSeconds = 300;
private static readonly JsonSerializerOptions WriteOptions = new() { WriteIndented = true };
public bool NewsAlert { get; init; } = true; public bool NewsAlert { get; init; } = true;
/// <summary>How long before a news item the reminder appears.</summary>
public int NewsAlertSeconds { get; init; } = 30; public int NewsAlertSeconds { get; init; } = 30;
public bool NewsAlertSound { get; init; } = true; public bool NewsAlertSound { get; init; } = true;
public bool ModeratorAlert { get; init; } = true; public bool ModeratorAlert { get; init; } = true;
/// <summary>How long before a moderator item the reminder appears.</summary>
public int ModeratorAlertSeconds { get; init; } = 30; public int ModeratorAlertSeconds { get; init; } = 30;
public bool ModeratorAlertSound { get; init; } = true; public bool ModeratorAlertSound { get; init; } = true;
/// <summary>News time per hour, split over the two news at :00 and :30.</summary>
public int NewsMinutesPerHour { get; init; } = 10; public int NewsMinutesPerHour { get; init; } = 10;
/// <summary>Target; the plan gets as close as the song lengths allow.</summary>
public int ModeratorMinutesPerHour { get; init; } = 10; public int ModeratorMinutesPerHour { get; init; } = 10;
/// <summary>Target; the plan gets as close as the song lengths allow.</summary>
public int AdMinutesPerHour { get; init; } = 20; public int AdMinutesPerHour { get; init; } = 20;
/// <summary>Playback device for the listeners; <c>null</c> is the Windows default device.</summary> public string? BroadcastDevice { get; init; } // null: Windows default device
public string? BroadcastDevice { get; init; }
/// <summary>Playback device for the person at the desk; <c>null</c> means no device of its own.</summary> public string? MonitorDevice { get; init; } // null: no monitor device
public string? MonitorDevice { get; init; }
/// <summary>Streaming to laut.fm and its library on the Import page; the Live button shows only while this is on.</summary>
public bool LautFmEnabled { get; init; } public bool LautFmEnabled { get; init; }
/// <summary>The station's id in Radioadmin, needed for the library.</summary>
public string LautFmStationId { get; init; } = ""; public string LautFmStationId { get; init; } = "";
/// <summary>Live access data from Radioadmin, "Live senden".</summary>
public string LautFmHost { get; init; } = ""; public string LautFmHost { get; init; } = "";
public int LautFmPort { get; init; } = 8080; public int LautFmPort { get; init; } = 8080;
@@ -56,11 +47,10 @@ public record AppSettings
public string LautFmUser { get; init; } = "source"; public string LautFmUser { get; init; } = "source";
/// <summary>Kept in memory as is; the file only holds it encrypted for the Windows user.</summary> // Secrets: plain in memory, DPAPI-encrypted in the file via the Protected* properties.
[JsonIgnore] [JsonIgnore]
public string LautFmPassword { get; init; } = ""; public string LautFmPassword { get; init; } = "";
/// <summary>The Radioadmin login token for the library; stored encrypted like the password.</summary>
[JsonIgnore] [JsonIgnore]
public string LautFmToken { get; init; } = ""; public string LautFmToken { get; init; } = "";
@@ -70,13 +60,12 @@ public record AppSettings
[JsonInclude, JsonPropertyName("LautFmToken")] [JsonInclude, JsonPropertyName("LautFmToken")]
private string? ProtectedLautFmToken { get => Protect(LautFmToken); init => LautFmToken = Unprotect(value); } private string? ProtectedLautFmToken { get => Protect(LautFmToken); init => LautFmToken = Unprotect(value); }
// Records print every property; the password and token stay out of logs and debugger views. // Record ToString would leak secrets into logs/debugger.
public override string ToString() => nameof(AppSettings); public override string ToString() => nameof(AppSettings);
public static string DefaultPath { get; } = Path.Combine( public static string DefaultPath { get; } = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Radiosender", "settings.json"); Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Radiosender", "settings.json");
/// <summary>The first problem with these values as a message for the user, or <c>null</c> when they are fine.</summary>
public string? Validate() public string? Validate()
{ {
if (NewsAlertSeconds is < MinAlertSeconds or > MaxAlertSeconds || ModeratorAlertSeconds is < MinAlertSeconds or > MaxAlertSeconds) if (NewsAlertSeconds is < MinAlertSeconds or > MaxAlertSeconds || ModeratorAlertSeconds is < MinAlertSeconds or > MaxAlertSeconds)
@@ -108,7 +97,6 @@ public record AppSettings
ModeratorPerHour = TimeSpan.FromMinutes(ModeratorMinutesPerHour), ModeratorPerHour = TimeSpan.FromMinutes(ModeratorMinutesPerHour),
}; };
/// <summary>Reads the settings; a missing, unreadable or invalid file gives the defaults.</summary>
public static AppSettings Load(string path) public static AppSettings Load(string path)
{ {
try try
@@ -122,20 +110,18 @@ public record AppSettings
} }
} }
/// <exception cref="IOException">The file cannot be written.</exception>
/// <exception cref="UnauthorizedAccessException">The file cannot be written.</exception>
public void Save(string path) public void Save(string path)
{ {
Directory.CreateDirectory(Path.GetDirectoryName(path)!); Directory.CreateDirectory(Path.GetDirectoryName(path)!);
File.WriteAllText(path, JsonSerializer.Serialize(this, new JsonSerializerOptions { WriteIndented = true })); File.WriteAllText(path, JsonSerializer.Serialize(this, WriteOptions));
} }
// DPAPI: only this Windows user on this computer can read the value back. // DPAPI: only this Windows user on this machine can decrypt.
private static string? Protect(string secret) => secret.Length == 0 private static string? Protect(string secret) => secret.Length == 0
? null ? null
: Convert.ToBase64String(ProtectedData.Protect(Encoding.UTF8.GetBytes(secret), null, DataProtectionScope.CurrentUser)); : Convert.ToBase64String(ProtectedData.Protect(Encoding.UTF8.GetBytes(secret), null, DataProtectionScope.CurrentUser));
// A value from another user or computer cannot be read; the user enters it again. // Other user/machine: unreadable, user re-enters it.
private static string Unprotect(string? stored) private static string Unprotect(string? stored)
{ {
if (string.IsNullOrEmpty(stored)) if (string.IsNullOrEmpty(stored))
@@ -1,9 +1,8 @@
namespace Radiosender.Services; using Radiosender.Services.Audio;
using Radiosender.Services.Scheduling;
namespace Radiosender.Services.Settings;
/// <summary>
/// The current <see cref="AppSettings"/> for the whole app. Loads them at startup and, on every save,
/// writes the file and hands the minutes per hour to the schedule generator and the devices to the audio output.
/// </summary>
public class SettingsStore public class SettingsStore
{ {
private readonly ScheduleGenerator _generator; private readonly ScheduleGenerator _generator;
@@ -17,19 +16,18 @@ public class SettingsStore
_path = path; _path = path;
Current = AppSettings.Load(path); Current = AppSettings.Load(path);
_generator.Options = Current.ToScheduleOptions(); _generator.Options = Current.ToScheduleOptions();
// Nothing is open yet at startup, so this cannot fail here. // Nothing open at startup: cannot fail.
_output.UseDevices(Current.BroadcastDevice, Current.MonitorDevice); _output.UseDevices(Current.BroadcastDevice, Current.MonitorDevice);
} }
public AppSettings Current { get; private set; } public AppSettings Current { get; private set; }
/// <summary>Stores the settings and applies them: alerts and audio devices at once, minutes per hour from the next plan on.</summary> /// <exception cref="System.IO.IOException">File not writable.</exception>
/// <exception cref="System.IO.IOException">The settings file cannot be written.</exception> /// <exception cref="UnauthorizedAccessException">File not writable.</exception>
/// <exception cref="UnauthorizedAccessException">The settings file cannot be written.</exception> /// <exception cref="NAudio.MmException">Device cannot be opened; nothing saved.</exception>
/// <exception cref="NAudio.MmException">A chosen audio device cannot be opened; nothing was saved.</exception>
public void Save(AppSettings settings) public void Save(AppSettings settings)
{ {
// Devices first: if one cannot be opened, the old settings stay in the file. // Devices first: on failure the file keeps the old settings.
if (settings.BroadcastDevice != Current.BroadcastDevice || settings.MonitorDevice != Current.MonitorDevice) if (settings.BroadcastDevice != Current.BroadcastDevice || settings.MonitorDevice != Current.MonitorDevice)
{ {
try try
@@ -5,33 +5,11 @@ using System.Text;
using NAudio.MediaFoundation; using NAudio.MediaFoundation;
using NAudio.Wave; using NAudio.Wave;
namespace Radiosender.Services; namespace Radiosender.Services.Streaming;
/// <summary>Error of a live stream, with a message that can be shown to the user as is.</summary>
public class LiveStreamException(string message, Exception? inner = null) : Exception(message, inner);
/// <summary>Where and how a live source logs in. laut.fm shows these values in Radioadmin under "Live senden".</summary>
public record IcecastTarget(string Host, int Port, string Mount, string User, string Password)
{
public string Path => Mount.StartsWith('/') ? Mount : "/" + Mount;
public static IcecastTarget From(AppSettings settings) => new(
settings.LautFmHost.Trim(), settings.LautFmPort, settings.LautFmMount.Trim(), settings.LautFmUser.Trim(), settings.LautFmPassword);
/// <summary>Value of the Basic authorization header.</summary>
public string Credentials => Convert.ToBase64String(Encoding.UTF8.GetBytes($"{User}:{Password}"));
// The password stays out of logs and debugger views.
public override string ToString() => $"{User}@{Host}:{Port}{Path}";
}
/// <summary>
/// A source connection to an Icecast server, which is what laut.fm takes for live broadcasts.
/// Reads 32-bit float audio from a feed and sends it as MP3 at 128 kbit/s until disposed.
/// </summary>
public sealed class IcecastStream : IDisposable public sealed class IcecastStream : IDisposable
{ {
public const int Bitrate = 128_000; private const int Bitrate = 128_000;
private static readonly TimeSpan ConnectTimeout = TimeSpan.FromSeconds(10); private static readonly TimeSpan ConnectTimeout = TimeSpan.FromSeconds(10);
private readonly TcpClient _client; private readonly TcpClient _client;
@@ -46,17 +24,13 @@ public sealed class IcecastStream : IDisposable
_thread = new Thread(Run) { IsBackground = true, Name = "Icecast stream" }; _thread = new Thread(Run) { IsBackground = true, Name = "Icecast stream" };
} }
/// <summary>The connection broke or the encoder stopped. Raised on the stream's own thread.</summary> /// <summary>Raised on the stream's own thread.</summary>
public event EventHandler<string>? Failed; public event EventHandler<string>? Failed;
/// <summary>Logs in at the server and starts sending.</summary> /// <exception cref="LiveStreamException">Server unreachable or login refused.</exception>
/// <param name="target">Server and login.</param>
/// <param name="feed">32-bit float audio that returns 0 bytes while nothing new is there, like <see cref="BufferedWaveProvider"/>.</param>
/// <param name="cancellationToken">Cancels the login.</param>
/// <exception cref="LiveStreamException">The server cannot be reached or refused the login.</exception>
public static async Task<IcecastStream> ConnectAsync(IcecastTarget target, IWaveProvider feed, CancellationToken cancellationToken = default) public static async Task<IcecastStream> ConnectAsync(IcecastTarget target, IWaveProvider feed, CancellationToken cancellationToken = default)
{ {
// These values end up in the request line and headers; a line break there would change the request. // Security: values go into request line/headers; a line break would inject headers.
if (new[] { target.Host, target.Path, target.User }.Any(value => value.Any(c => char.IsWhiteSpace(c) || char.IsControl(c))) if (new[] { target.Host, target.Path, target.User }.Any(value => value.Any(c => char.IsWhiteSpace(c) || char.IsControl(c)))
|| target.User.Contains(':')) || target.User.Contains(':'))
throw new LiveStreamException("Server, Mountpoint oder Benutzer enthalten ungĂĽltige Zeichen."); throw new LiveStreamException("Server, Mountpoint oder Benutzer enthalten ungĂĽltige Zeichen.");
@@ -109,11 +83,10 @@ public sealed class IcecastStream : IDisposable
} }
} }
/// <summary>Sets the title listeners see, through the server's admin interface with the same login.</summary>
/// <exception cref="LiveStreamException">The server did not take the title.</exception> /// <exception cref="LiveStreamException">The server did not take the title.</exception>
public static async Task UpdateTitleAsync(HttpClient http, IcecastTarget target, string title, CancellationToken cancellationToken = default) public static async Task UpdateTitleAsync(HttpClient http, IcecastTarget target, string title, CancellationToken cancellationToken = default)
{ {
// Plain http, like the source connection itself: Icecast takes sources without TLS. // Plain http like the source connection: Icecast takes sources without TLS.
var url = new UriBuilder(Uri.UriSchemeHttp, target.Host, target.Port, "/admin/metadata") var url = new UriBuilder(Uri.UriSchemeHttp, target.Host, target.Port, "/admin/metadata")
{ {
Query = $"mount={Uri.EscapeDataString(target.Path)}&mode=updinfo&song={Uri.EscapeDataString(title)}", Query = $"mount={Uri.EscapeDataString(target.Path)}&mode=updinfo&song={Uri.EscapeDataString(title)}",
@@ -132,12 +105,11 @@ public sealed class IcecastStream : IDisposable
} }
} }
/// <summary>Stops sending and closes the connection.</summary>
public void Dispose() public void Dispose()
{ {
_stopping = true; _stopping = true;
_reader.Stop(); _reader.Stop();
// The encoder ends once the reader returns 0; a stalled connection is cut by closing the socket. // Encoder ends when reader returns 0; stalled connection is cut by closing the socket.
if (Thread.CurrentThread != _thread && _thread.IsAlive) if (Thread.CurrentThread != _thread && _thread.IsAlive)
_thread.Join(TimeSpan.FromSeconds(2)); _thread.Join(TimeSpan.FromSeconds(2));
_client.Dispose(); _client.Dispose();
@@ -158,7 +130,7 @@ public sealed class IcecastStream : IDisposable
} }
catch (Exception ex) catch (Exception ex)
{ {
// While stopping, closing the socket under the encoder is expected. // Stopping: socket closed under the encoder is expected.
if (!_stopping) if (!_stopping)
Failed?.Invoke(this, ex is LiveStreamException ? ex.Message : $"Verbindung zu laut.fm verloren: {ex.Message}"); Failed?.Invoke(this, ex is LiveStreamException ? ex.Message : $"Verbindung zu laut.fm verloren: {ex.Message}");
} }
@@ -175,14 +147,13 @@ public sealed class IcecastStream : IDisposable
throw new LiveStreamException("Der Server hat die Verbindung ohne gĂĽltige Antwort beendet."); throw new LiveStreamException("Der Server hat die Verbindung ohne gĂĽltige Antwort beendet.");
header.Append(Encoding.ASCII.GetString(buffer, 0, read)); header.Append(Encoding.ASCII.GetString(buffer, 0, read));
} }
// "HTTP/1.1 100 Continue" or "HTTP/1.0 200 OK"
var parts = header.ToString().Split(' ', 3); var parts = header.ToString().Split(' ', 3);
return parts.Length >= 2 && int.TryParse(parts[1], out var status) return parts.Length >= 2 && int.TryParse(parts[1], out var status)
? status ? status
: throw new LiveStreamException("Der Server hat ungĂĽltig geantwortet."); : throw new LiveStreamException("Der Server hat ungĂĽltig geantwortet.");
} }
/// <summary>Waits for audio instead of ending when the feed is empty, so the encoder keeps going in real time.</summary> // Empty feed: wait instead of ending, so the encoder runs in real time.
private sealed class FeedReader(IWaveProvider feed) : IWaveProvider private sealed class FeedReader(IWaveProvider feed) : IWaveProvider
{ {
private volatile bool _stopped; private volatile bool _stopped;
@@ -200,7 +171,7 @@ public sealed class IcecastStream : IDisposable
return read; return read;
Thread.Sleep(10); Thread.Sleep(10);
} }
return 0; // the encoder finishes and returns return 0; // encoder finishes
} }
} }
} }
@@ -0,0 +1,17 @@
using System.Text;
using Radiosender.Services.Settings;
namespace Radiosender.Services.Streaming;
public record IcecastTarget(string Host, int Port, string Mount, string User, string Password)
{
public string Path => Mount.StartsWith('/') ? Mount : "/" + Mount;
public static IcecastTarget From(AppSettings settings) => new(
settings.LautFmHost.Trim(), settings.LautFmPort, settings.LautFmMount.Trim(), settings.LautFmUser.Trim(), settings.LautFmPassword);
public string Credentials => Convert.ToBase64String(Encoding.UTF8.GetBytes($"{User}:{Password}"));
// Security: keeps the password out of logs and debugger views.
public override string ToString() => $"{User}@{Host}:{Port}{Path}";
}
@@ -0,0 +1,4 @@
namespace Radiosender.Services.Streaming;
/// <summary>Message is shown to the user as is.</summary>
public class LiveStreamException(string message, Exception? inner = null) : Exception(message, inner);
@@ -1,15 +1,12 @@
using Radiosender.Models; using Radiosender.Models;
namespace Radiosender.Services; namespace Radiosender.Services.Streaming;
/// <summary> // laut.fm: title AdBreak starts an ad break, max once per 15 min; later ads keep their own title.
/// The stream title for each item. laut.fm starts its ad break when the title is "START_AD_BREAK" and
/// wants that at most once in 15 minutes, so later ad items within that time keep their own title.
/// </summary>
public class StreamTitles(Func<DateTime> now) public class StreamTitles(Func<DateTime> now)
{ {
public const string AdBreak = "START_AD_BREAK"; public const string AdBreak = "START_AD_BREAK";
public static readonly TimeSpan MinAdBreakSpacing = TimeSpan.FromMinutes(15); private static readonly TimeSpan MinAdBreakSpacing = TimeSpan.FromMinutes(15);
private DateTime? _lastAdBreak; private DateTime? _lastAdBreak;
+6 -16
View File
@@ -7,34 +7,25 @@ using System.Windows.Media;
namespace Radiosender.Views; namespace Radiosender.Views;
/// <summary>Sizes the text columns of a list so that every row can be read in full.</summary>
public static class GridColumns public static class GridColumns
{ {
// Cell padding on both sides plus a little air, so the text never touches the next column.
private const double Slack = 28; private const double Slack = 28;
// Rows use this size when no row exists yet to ask.
private const double DefaultFontSize = 14; private const double DefaultFontSize = 14;
// The width from the XAML stays the minimum, so an empty or short list keeps its designed look. // XAML width = minimum.
private static readonly ConditionalWeakTable<GridViewColumn, object> MinWidths = []; private static readonly ConditionalWeakTable<GridViewColumn, object> MinWidths = [];
// Laying out text is the slow part and the same titles come up on every refresh, so widths are remembered. // Assumes one shared font. shortcut: never trimmed, clear if libraries reach 100k+ songs.
// All lists share one font. shortcut: never trimmed; clear it if libraries reach hundreds of thousands of songs.
private static readonly Dictionary<string, double> TextWidths = []; private static readonly Dictionary<string, double> TextWidths = [];
/// <summary> // Measures all rows: lists are virtualized, built-in auto width misses off-screen rows.
/// Widens each column with a <see cref="GridViewColumn.DisplayMemberBinding"/> to its longest text over
/// all rows, not only the visible ones: the lists are virtualized, so the built-in auto width would miss
/// rows that are scrolled out of view. Columns with a cell template keep their width, and so do columns
/// with a string format: those show times, which always have the same length.
/// </summary>
public static void Fit(ListView list) public static void Fit(ListView list)
{ {
if (list.View is not GridView view) if (list.View is not GridView view)
return; return;
// The rows have their own font size, so a realized row is asked rather than the list. // Rows have own font size: ask realized row, not list.
var row = list.ItemContainerGenerator.ContainerFromIndex(0) as Control; var row = list.ItemContainerGenerator.ContainerFromIndex(0) as Control;
var typeface = new Typeface(row?.FontFamily ?? list.FontFamily, FontStyles.Normal, FontWeights.Normal, FontStretches.Normal); var typeface = new Typeface(row?.FontFamily ?? list.FontFamily, FontStyles.Normal, FontWeights.Normal, FontStretches.Normal);
var fontSize = row?.FontSize ?? DefaultFontSize; var fontSize = row?.FontSize ?? DefaultFontSize;
@@ -63,13 +54,12 @@ public static class GridColumns
} }
var fitted = Math.Max(min, Math.Ceiling(widest + Slack)); var fitted = Math.Max(min, Math.Ceiling(widest + Slack));
if (column.Width != fitted) // setting it triggers a layout pass if (column.Width != fitted) // set triggers layout pass
column.Width = fitted; column.Width = fitted;
} }
} }
// Follows a simple property path such as "Item.Title". A binding on a probe element would not do: // Reflection, not probe binding: binding resolves only once in the visual tree.
// it only resolves once the element is part of the window.
private static string Text(object? value, string[] properties) private static string Text(object? value, string[] properties)
{ {
foreach (var property in properties) foreach (var property in properties)
+2 -7
View File
@@ -3,7 +3,7 @@ using NAudio.Wave;
using NAudio.Wave.SampleProviders; using NAudio.Wave.SampleProviders;
using Radiosender.Controllers; using Radiosender.Controllers;
using Radiosender.Models; using Radiosender.Models;
using Radiosender.Services; using Radiosender.Services.Settings;
using Radiosender.Views.Pages; using Radiosender.Views.Pages;
using Wpf.Ui.Controls; using Wpf.Ui.Controls;
@@ -21,16 +21,13 @@ public partial class MainWindow : FluentWindow
_schedule = schedule; _schedule = schedule;
_settings = settings; _settings = settings;
InitializeComponent(); InitializeComponent();
// The navigation view asks the container for each page, so pages get their controllers injected.
RootNavigation.SetServiceProvider(services); RootNavigation.SetServiceProvider(services);
// Re-themes the app when the user switches the Windows theme while it runs.
Wpf.Ui.Appearance.SystemThemeWatcher.Watch(this); Wpf.Ui.Appearance.SystemThemeWatcher.Watch(this);
Loaded += (_, _) => RootNavigation.Navigate(typeof(SchedulePage)); Loaded += (_, _) => RootNavigation.Navigate(typeof(SchedulePage));
_reminderTimer.Tick += (_, _) => RemindSpeaker(); _reminderTimer.Tick += (_, _) => RemindSpeaker();
_reminderTimer.Start(); _reminderTimer.Start();
} }
// Shortly before news or moderator talk goes on air, the person at the microphone gets a heads-up.
private void RemindSpeaker() private void RemindSpeaker()
{ {
var settings = _settings.Current; var settings = _settings.Current;
@@ -43,7 +40,6 @@ public partial class MainWindow : FluentWindow
var what = item.KindName; var what = item.KindName;
if (isNews ? settings.NewsAlertSound : settings.ModeratorAlertSound) if (isNews ? settings.NewsAlertSound : settings.ModeratorAlertSound)
PlayBing(); PlayBing();
// A dialog in the middle of the screen that stays until OK is clicked; the broadcast keeps running behind it.
_ = new Wpf.Ui.Controls.MessageBox _ = new Wpf.Ui.Controls.MessageBox
{ {
Title = "Gleich bist du dran.", Title = "Gleich bist du dran.",
@@ -54,7 +50,6 @@ public partial class MainWindow : FluentWindow
}.ShowDialogAsync(); }.ShowDialogAsync();
} }
// A short generated tone on its own output, so it sounds over the running broadcast.
private static void PlayBing() private static void PlayBing()
{ {
try try
@@ -68,7 +63,7 @@ public partial class MainWindow : FluentWindow
} }
catch (Exception ex) when (ex is NAudio.MmException or InvalidOperationException) catch (Exception ex) when (ex is NAudio.MmException or InvalidOperationException)
{ {
// No audio device: the dialog still reminds the speaker. // No audio device: dialog still reminds.
} }
} }
} }
+8 -21
View File
@@ -7,22 +7,21 @@ using Microsoft.Win32;
using NAudio.Wave; using NAudio.Wave;
using Radiosender.Controllers; using Radiosender.Controllers;
using Radiosender.Models; using Radiosender.Models;
using Radiosender.Services; using Radiosender.Services.Providers;
using Wpf.Ui.Controls; using Wpf.Ui.Controls;
namespace Radiosender.Views.Pages; namespace Radiosender.Views.Pages;
/// <summary>Adds music to the library from local files or from an online provider; both list their results in one place.</summary>
public partial class ImportPage : Page public partial class ImportPage : Page
{ {
private readonly OnlineImportController _online; private readonly OnlineImportController _online;
private readonly UploadController _upload; private readonly UploadController _upload;
private readonly ObservableCollection<SessionRow> _session = []; private readonly ObservableCollection<SessionRow> _session = [];
// Preview has its own output, so it never interrupts a running broadcast. // Own output: never interrupts broadcast.
private WaveOut? _previewOutput; private WaveOut? _previewOutput;
private MediaFoundationReader? _previewReader; private MediaFoundationReader? _previewReader;
private int _previewId; // changes on every start and stop; a late callback with an old id is ignored private int _previewId; // bumped on start/stop; late callbacks with old id ignored
private bool _uploading; private bool _uploading;
private bool _busy; private bool _busy;
private bool _previewing; private bool _previewing;
@@ -32,7 +31,6 @@ public partial class ImportPage : Page
_online = online; _online = online;
_upload = upload; _upload = upload;
InitializeComponent(); InitializeComponent();
// One provider needs no choice: the tab carries its name. Several get a list next to the search box.
var providers = _online.Providers; var providers = _online.Providers;
ProviderBox.ItemsSource = providers; ProviderBox.ItemsSource = providers;
ProviderBox.SelectedIndex = providers.Count > 0 ? 0 : -1; ProviderBox.SelectedIndex = providers.Count > 0 ? 0 : -1;
@@ -48,8 +46,6 @@ public partial class ImportPage : Page
}; };
} }
// ---- From computer ----
private async void OnChooseFiles(object sender, RoutedEventArgs e) private async void OnChooseFiles(object sender, RoutedEventArgs e)
{ {
var dialog = new OpenFileDialog { Filter = UploadController.FileDialogFilter, Multiselect = true }; var dialog = new OpenFileDialog { Filter = UploadController.FileDialogFilter, Multiselect = true };
@@ -75,7 +71,6 @@ public partial class ImportPage : Page
await UploadAsync(paths); await UploadAsync(paths);
} }
// Files are imported one by one on a pool thread; each result shows up as soon as it is known.
private async Task UploadAsync(IReadOnlyList<string> paths) private async Task UploadAsync(IReadOnlyList<string> paths)
{ {
if (paths.Count == 0) return; if (paths.Count == 0) return;
@@ -104,8 +99,6 @@ public partial class ImportPage : Page
} }
} }
// ---- Online providers ----
private ResultRow? Selected => Results.SelectedItem as ResultRow; private ResultRow? Selected => Results.SelectedItem as ResultRow;
private void OnQueryKeyDown(object sender, KeyEventArgs e) private void OnQueryKeyDown(object sender, KeyEventArgs e)
@@ -141,8 +134,7 @@ public partial class ImportPage : Page
} }
} }
// One button: starts the preview, or stops the running one. // NAudio, not WPF MediaPlayer: MediaPlayer cannot open https.
// NAudio, not WPF's MediaPlayer: that one cannot open https URLs.
private async void OnPreview(object sender, RoutedEventArgs e) private async void OnPreview(object sender, RoutedEventArgs e)
{ {
if (_previewing) if (_previewing)
@@ -157,7 +149,6 @@ public partial class ImportPage : Page
var id = ++_previewId; var id = ++_previewId;
try try
{ {
// Connects to the server, so it runs off the UI thread. The file is streamed, nothing is saved.
var reader = await Task.Run(() => new MediaFoundationReader(uri.AbsoluteUri)); var reader = await Task.Run(() => new MediaFoundationReader(uri.AbsoluteUri));
if (id != _previewId) // stopped or page left in the meantime if (id != _previewId) // stopped or page left in the meantime
{ {
@@ -200,7 +191,7 @@ public partial class ImportPage : Page
_previewOutput = null; _previewOutput = null;
_previewReader = null; _previewReader = null;
SetPreviewing(false); SetPreviewing(false);
// Disposing waits for the audio thread, which can sit in a network read; not on the UI thread. // Off UI thread: Dispose waits for audio thread, may block in network read.
if (output is not null || reader is not null) if (output is not null || reader is not null)
Task.Run(() => Task.Run(() =>
{ {
@@ -211,10 +202,9 @@ public partial class ImportPage : Page
private void OnResultDoubleClick(object sender, MouseButtonEventArgs e) => OnImport(sender, e); private void OnResultDoubleClick(object sender, MouseButtonEventArgs e) => OnImport(sender, e);
// Everything selected that can still be imported. private List<ResultRow> Importable => [.. Results.SelectedItems.OfType<ResultRow>().Where(r => r.CanImport)];
private List<ResultRow> Importable => Results.SelectedItems.OfType<ResultRow>().Where(r => r.CanImport).ToList();
// One after the other: providers limit anonymous requests, and each result shows up as soon as it is done. // Sequential: providers rate-limit anonymous requests.
private async void OnImport(object sender, RoutedEventArgs e) private async void OnImport(object sender, RoutedEventArgs e)
{ {
var rows = Importable; var rows = Importable;
@@ -240,7 +230,7 @@ public partial class ImportPage : Page
} }
catch (Exception ex) when (ex is MusicProviderException or Microsoft.EntityFrameworkCore.DbUpdateException) catch (Exception ex) when (ex is MusicProviderException or Microsoft.EntityFrameworkCore.DbUpdateException)
{ {
// The database error text is technical and English; the usual cause is a song that is already stored. // DB error text is technical English; usual cause: song already stored.
var reason = ex is MusicProviderException ? ex.Message : "Der Song konnte nicht in der Bibliothek gespeichert werden."; var reason = ex is MusicProviderException ? ex.Message : "Der Song konnte nicht in der Bibliothek gespeichert werden.";
_session.Insert(0, SessionRow.Failed(row.Track.Title, reason)); _session.Insert(0, SessionRow.Failed(row.Track.Title, reason));
failed++; failed++;
@@ -283,7 +273,6 @@ public partial class ImportPage : Page
var importable = Importable.Count; var importable = Importable.Count;
ImportButton.IsEnabled = !_busy && importable > 0; ImportButton.IsEnabled = !_busy && importable > 0;
ImportButton.Content = importable > 1 ? $"{importable} in Bibliothek importieren" : "In Bibliothek importieren"; ImportButton.Content = importable > 1 ? $"{importable} in Bibliothek importieren" : "In Bibliothek importieren";
// Why the selection cannot be imported ("In Bibliothek", "Keine Dauer"); shown on the disabled button.
ImportButton.ToolTip = importable == 0 && Selected is { } blocked ? blocked.Status : null; ImportButton.ToolTip = importable == 0 && Selected is { } blocked ? blocked.Status : null;
} }
@@ -295,8 +284,6 @@ public partial class ImportPage : Page
Message.IsOpen = true; Message.IsOpen = true;
} }
// ---- Shared ----
private void OnOpenLibrary(object sender, RoutedEventArgs e) => private void OnOpenLibrary(object sender, RoutedEventArgs e) =>
(Window.GetWindow(this) as MainWindow)?.RootNavigation.Navigate(typeof(LibraryPage)); (Window.GetWindow(this) as MainWindow)?.RootNavigation.Navigate(typeof(LibraryPage));
@@ -19,7 +19,6 @@ public partial class LibraryPage : Page
private Song? Selected => SongList.SelectedItem as Song; private Song? Selected => SongList.SelectedItem as Song;
// Loaded fires on every navigation to the page, so the list is reloaded from the database each time.
private void OnLoaded(object sender, RoutedEventArgs e) => Refresh(); private void OnLoaded(object sender, RoutedEventArgs e) => Refresh();
private void OnSearchChanged(object sender, TextChangedEventArgs e) => Refresh(); private void OnSearchChanged(object sender, TextChangedEventArgs e) => Refresh();
@@ -4,7 +4,9 @@ using System.Windows.Controls;
using System.Windows.Threading; using System.Windows.Threading;
using Radiosender.Controllers; using Radiosender.Controllers;
using Radiosender.Models; using Radiosender.Models;
using Radiosender.Services; using Radiosender.Services.Audio;
using Radiosender.Services.Scheduling;
using Radiosender.Services.Streaming;
using Wpf.Ui.Controls; using Wpf.Ui.Controls;
namespace Radiosender.Views.Pages; namespace Radiosender.Views.Pages;
@@ -17,16 +19,14 @@ public partial class SchedulePage : Page
private int _scrolledTo = -1; private int _scrolledTo = -1;
private bool _shownPlaying; private bool _shownPlaying;
// Weekday names in the start list follow the interface language, not the Windows setting. // UI language, not Windows culture.
private static readonly System.Globalization.CultureInfo German = new("de-DE"); private static readonly System.Globalization.CultureInfo German = new("de-DE");
// Bound once and updated row by row, so a click never rebuilds the whole list.
private readonly ObservableCollection<TimelineRow> _rows = []; private readonly ObservableCollection<TimelineRow> _rows = [];
// A controller call is running on a pool thread; the buttons that would collide with it are off.
private bool _working; private bool _working;
// Optimistic state: what the user just asked for, shown before the engine has caught up. // Optimistic: shown before engine catches up.
private bool? _expectPlaying; private bool? _expectPlaying;
private readonly Microphone _microphone; private readonly Microphone _microphone;
@@ -41,7 +41,7 @@ public partial class SchedulePage : Page
_mixer = output.Mixer; _mixer = output.Mixer;
InitializeComponent(); InitializeComponent();
Timeline.ItemsSource = _rows; Timeline.ItemsSource = _rows;
// Also refreshes the buttons: Finished can arrive just before the engine reports it stopped. // Buttons too: Finished can arrive before engine reports stopped.
_progressTimer.Tick += (_, _) => _progressTimer.Tick += (_, _) =>
{ {
UpdateButtons(); UpdateButtons();
@@ -49,7 +49,6 @@ public partial class SchedulePage : Page
}; };
} }
// The page can be shown again while a broadcast runs, so it always rebuilds from the controller.
private void OnLoaded(object sender, RoutedEventArgs e) private void OnLoaded(object sender, RoutedEventArgs e)
{ {
_controller.ItemStarted += OnItemStarted; _controller.ItemStarted += OnItemStarted;
@@ -65,13 +64,12 @@ public partial class SchedulePage : Page
ListenToBroadcastBox.IsChecked = _mixer.ListenToBroadcast; ListenToBroadcastBox.IsChecked = _mixer.ListenToBroadcast;
MusicForMeSlider.IsEnabled = !_mixer.ListenToBroadcast; MusicForMeSlider.IsEnabled = !_mixer.ListenToBroadcast;
_loading = false; _loading = false;
ShowMicrophone(); // it stays on while the user visits other pages ShowMicrophone();
ShowLive(); ShowLive();
FillStartTimes(); FillStartTimes();
if (_controller.Plan.Count > 0) if (_controller.Plan.Count > 0)
UnlimitedBox.IsChecked = _controller.IsUnlimited; UnlimitedBox.IsChecked = _controller.IsUnlimited;
// The library can change on other pages.
RequestSong.ItemsSource = _controller.LibrarySongs() RequestSong.ItemsSource = _controller.LibrarySongs()
.OrderBy(s => s.Artist).ThenBy(s => s.Title) .OrderBy(s => 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})")) .Select(s => new SongOption(s.Id, $"{(string.IsNullOrWhiteSpace(s.Artist) ? s.Title : $"{s.Artist} - {s.Title}")} ({s.Duration:m\\:ss})"))
@@ -90,7 +88,7 @@ public partial class SchedulePage : Page
_progressTimer.Stop(); _progressTimer.Stop();
} }
// The next 12 full hours; rebuilt when the list opens, so it never offers a past hour. // Rebuilt on dropdown open: never offers a past hour.
private void FillStartTimes() private void FillStartTimes()
{ {
var selected = (StartBox.SelectedItem as StartOption)?.Time; var selected = (StartBox.SelectedItem as StartOption)?.Time;
@@ -128,10 +126,6 @@ public partial class SchedulePage : Page
}); });
} }
/// <summary>
/// Runs a controller call that can take a moment (planning, waiting for the audio thread to stop)
/// off the UI thread, so the window stays responsive. Returns <c>false</c> after showing the error.
/// </summary>
private async Task<bool> RunAsync(string errorTitle, Action work) private async Task<bool> RunAsync(string errorTitle, Action work)
{ {
_working = true; _working = true;
@@ -171,7 +165,6 @@ public partial class SchedulePage : Page
private void OnMoveDown(object sender, RoutedEventArgs e) => MoveSelected(1); private void OnMoveDown(object sender, RoutedEventArgs e) => MoveSelected(1);
// The selection follows the item, so it can be moved several steps in a row.
private void MoveSelected(int offset) => ChangeSelected(row => private void MoveSelected(int offset) => ChangeSelected(row =>
{ {
_controller.Move(row.Index, offset); _controller.Move(row.Index, offset);
@@ -185,7 +178,6 @@ public partial class SchedulePage : Page
_mixer.MusicForOthers = (float)MusicForOthersSlider.Value; _mixer.MusicForOthers = (float)MusicForOthersSlider.Value;
_mixer.MicrophoneForOthers = (float)MicrophoneForOthersSlider.Value; _mixer.MicrophoneForOthers = (float)MicrophoneForOthersSlider.Value;
_mixer.ListenToBroadcast = ListenToBroadcastBox.IsChecked == true; _mixer.ListenToBroadcast = ListenToBroadcastBox.IsChecked == true;
// While the monitor copies the broadcast, its own music level has no effect.
MusicForMeSlider.IsEnabled = !_mixer.ListenToBroadcast; MusicForMeSlider.IsEnabled = !_mixer.ListenToBroadcast;
} }
@@ -195,7 +187,6 @@ public partial class SchedulePage : Page
MicButton.IsEnabled = false; MicButton.IsEnabled = false;
try try
{ {
// Opening the devices can take a moment, so it runs off the UI thread.
await Task.Run(() => await Task.Run(() =>
{ {
if (turnOn) _microphone.TurnOn(); if (turnOn) _microphone.TurnOn();
@@ -214,7 +205,6 @@ public partial class SchedulePage : Page
private void ShowMicrophone() private void ShowMicrophone()
{ {
var on = _microphone.IsOn; var on = _microphone.IsOn;
// The label names the action; the red button shows that the microphone is live.
MicButton.Content = on ? "Mikro aus" : "Mikro ein"; MicButton.Content = on ? "Mikro aus" : "Mikro ein";
MicButton.Icon = new SymbolIcon(on ? SymbolRegular.MicOff24 : SymbolRegular.Mic24); MicButton.Icon = new SymbolIcon(on ? SymbolRegular.MicOff24 : SymbolRegular.Mic24);
MicButton.Appearance = on ? ControlAppearance.Danger : ControlAppearance.Secondary; MicButton.Appearance = on ? ControlAppearance.Danger : ControlAppearance.Secondary;
@@ -232,7 +222,6 @@ public partial class SchedulePage : Page
} }
else else
{ {
// Opening the devices and the connection can take a moment, so it runs off the UI thread.
await Task.Run(() => _live.StartAsync()); await Task.Run(() => _live.StartAsync());
Message.IsOpen = false; Message.IsOpen = false;
} }
@@ -245,7 +234,7 @@ public partial class SchedulePage : Page
ShowLive(); ShowLive();
} }
// Comes from a background thread; the stream may have ended. // Background thread.
private void OnLiveProblem(object? sender, string message) => Dispatcher.BeginInvoke(() => private void OnLiveProblem(object? sender, string message) => Dispatcher.BeginInvoke(() =>
{ {
ShowMessage(InfoBarSeverity.Warning, "laut.fm", message); ShowMessage(InfoBarSeverity.Warning, "laut.fm", message);
@@ -255,7 +244,7 @@ public partial class SchedulePage : Page
private void ShowLive() private void ShowLive()
{ {
var live = _live.IsLive; var live = _live.IsLive;
// Stays visible while live, so a stream can be stopped after laut.fm was switched off. // Visible while live: stoppable after laut.fm was switched off.
LiveButton.Visibility = _live.IsEnabled || live ? Visibility.Visible : Visibility.Collapsed; LiveButton.Visibility = _live.IsEnabled || live ? Visibility.Visible : Visibility.Collapsed;
LiveButton.Content = live ? "Live beenden" : "Live"; LiveButton.Content = live ? "Live beenden" : "Live";
LiveButton.Appearance = live ? ControlAppearance.Danger : ControlAppearance.Secondary; LiveButton.Appearance = live ? ControlAppearance.Danger : ControlAppearance.Secondary;
@@ -308,7 +297,6 @@ public partial class SchedulePage : Page
private async void OnPlayToggle(object sender, RoutedEventArgs e) private async void OnPlayToggle(object sender, RoutedEventArgs e)
{ {
var stop = _controller.IsPlaying; var stop = _controller.IsPlaying;
// The button and the card switch at once; stopping waits for the audio thread in the background.
_expectPlaying = !stop; _expectPlaying = !stop;
if (stop) if (stop)
NowKind.Visibility = Visibility.Collapsed; NowKind.Visibility = Visibility.Collapsed;
@@ -321,7 +309,7 @@ public partial class SchedulePage : Page
if (!_loading) _controller.Volume = (float)e.NewValue; if (!_loading) _controller.Volume = (float)e.NewValue;
} }
// Engine events arrive on a pool thread. BeginInvoke, not Invoke: Stop waits for that thread. // BeginInvoke, not Invoke: engine Stop waits for this pool thread -> deadlock.
private void OnItemStarted(object? sender, int index) => Dispatcher.BeginInvoke(ShowCurrent); private void OnItemStarted(object? sender, int index) => Dispatcher.BeginInvoke(ShowCurrent);
private void OnItemFailed(object? sender, string message) => private void OnItemFailed(object? sender, string message) =>
@@ -333,7 +321,6 @@ public partial class SchedulePage : Page
ShowCurrent(); ShowCurrent();
}); });
// Syncs the rows with the controller; the selection is the user's swap target and is kept.
private void ShowCurrent() private void ShowCurrent()
{ {
var item = _controller.CurrentItem; var item = _controller.CurrentItem;
@@ -341,7 +328,7 @@ public partial class SchedulePage : Page
var plan = _controller.Plan; var plan = _controller.Plan;
var selected = Timeline.SelectedIndex; var selected = Timeline.SelectedIndex;
// Rows are records: only the ones whose content changed are replaced. // Replace changed rows only: keeps selection (swap target).
for (var i = 0; i < plan.Count; i++) for (var i = 0; i < plan.Count; i++)
{ {
var updated = new TimelineRow(i, plan[i], i == current); var updated = new TimelineRow(i, plan[i], i == current);
@@ -352,12 +339,10 @@ public partial class SchedulePage : Page
} }
while (_rows.Count > plan.Count) while (_rows.Count > plan.Count)
_rows.RemoveAt(_rows.Count - 1); _rows.RemoveAt(_rows.Count - 1);
var rows = _rows;
GridColumns.Fit(Timeline); GridColumns.Fit(Timeline);
Timeline.SelectedIndex = selected < rows.Count ? selected : -1; 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)
if (current != _scrolledTo && current >= 0 && current < rows.Count) Timeline.ScrollIntoView(_rows[current]);
Timeline.ScrollIntoView(rows[current]);
else if (Timeline.SelectedItem is { } row) else if (Timeline.SelectedItem is { } row)
Timeline.ScrollIntoView(row); Timeline.ScrollIntoView(row);
_scrolledTo = current; _scrolledTo = current;
@@ -376,7 +361,6 @@ public partial class SchedulePage : Page
var playing = _expectPlaying ?? _controller.IsPlaying; var playing = _expectPlaying ?? _controller.IsPlaying;
PlayButton.IsEnabled = !_working && (playing || _controller.Plan.Count > 0); PlayButton.IsEnabled = !_working && (playing || _controller.Plan.Count > 0);
CreateButton.IsEnabled = StartNowButton.IsEnabled = !_working; CreateButton.IsEnabled = StartNowButton.IsEnabled = !_working;
// Called every timer tick, so the label and icon change only with the state.
if (playing != _shownPlaying) if (playing != _shownPlaying)
{ {
_shownPlaying = playing; _shownPlaying = playing;
@@ -386,7 +370,6 @@ public partial class SchedulePage : Page
var row = Timeline.SelectedItem as TimelineRow; var row = Timeline.SelectedItem as TimelineRow;
// Only items that are not on air or over can be moved or removed; the one on air can still be edited.
var count = _controller.Plan.Count; var count = _controller.Plan.Count;
var current = _controller.CurrentIndex; var current = _controller.CurrentIndex;
bool Editable(int i) => !_working && i >= 0 && i < count && (!playing || i > current); bool Editable(int i) => !_working && i >= 0 && i < count && (!playing || i > current);
@@ -406,7 +389,6 @@ public partial class SchedulePage : Page
_ => null, _ => null,
}; };
SwapHint.Text = blocker ?? $"Ersetzt das Element um {row!.Item.Start:HH:mm:ss}."; SwapHint.Text = blocker ?? $"Ersetzt das Element um {row!.Item.Start:HH:mm:ss}.";
// The hint only matters once a song is chosen.
var requested = RequestSong.SelectedItem is not null; var requested = RequestSong.SelectedItem is not null;
SwapHint.Visibility = requested ? Visibility.Visible : Visibility.Collapsed; SwapHint.Visibility = requested ? Visibility.Visible : Visibility.Collapsed;
SwapButton.IsEnabled = !_working && requested && blocker is null; SwapButton.IsEnabled = !_working && requested && blocker is null;
@@ -417,7 +399,7 @@ public partial class SchedulePage : Page
if (_expectPlaying == false || _controller.CurrentItem is not { } item) if (_expectPlaying == false || _controller.CurrentItem is not { } item)
{ {
NowProgress.Value = 0; NowProgress.Value = 0;
// Checked here, not in ShowCurrent: the engine starts waiting a moment after Start. // Here, not in ShowCurrent: engine starts waiting shortly after Start.
var waiting = _expectPlaying == false ? null : _controller.WaitingUntil; var waiting = _expectPlaying == false ? null : _controller.WaitingUntil;
NowTitle.Text = waiting is { } at ? $"Auf Sendung um {at:HH:mm:ss}" : "Nichts auf Sendung"; NowTitle.Text = waiting is { } at ? $"Auf Sendung um {at:HH:mm:ss}" : "Nichts auf Sendung";
NowTime.Text = " "; NowTime.Text = " ";
@@ -1,12 +1,12 @@
using System.IO; using System.IO;
using System.Windows; using System.Windows;
using System.Windows.Controls; using System.Windows.Controls;
using Radiosender.Services; using Radiosender.Services.Audio;
using Radiosender.Services.Settings;
using Wpf.Ui.Controls; using Wpf.Ui.Controls;
namespace Radiosender.Views.Pages; namespace Radiosender.Views.Pages;
/// <summary>Edits <see cref="AppSettings"/>. Nothing changes until Save.</summary>
public partial class SettingsPage : Page public partial class SettingsPage : Page
{ {
private readonly SettingsStore _store; private readonly SettingsStore _store;
@@ -17,16 +17,14 @@ public partial class SettingsPage : Page
InitializeComponent(); InitializeComponent();
} }
// Loaded fires on every navigation to the page, so unsaved edits from an earlier visit are dropped.
private void OnLoaded(object sender, RoutedEventArgs e) => Show(_store.Current); private void OnLoaded(object sender, RoutedEventArgs e) => Show(_store.Current);
// First entry of each list: the choice that names no device. // Index 0 of each list = no device name (null).
private const string DefaultDevice = "Windows-Standardgerät"; private const string DefaultDevice = "Windows-Standardgerät";
private const string NoDevice = "Kein eigenes Gerät"; private const string NoDevice = "Kein eigenes Gerät";
private void Show(AppSettings settings) private void Show(AppSettings settings)
{ {
// Read again on every visit, so a headset plugged in meanwhile shows up.
var devices = ProgramOutput.DeviceNames().ToList(); var devices = ProgramOutput.DeviceNames().ToList();
BroadcastDeviceBox.ItemsSource = devices.Prepend(DefaultDevice).ToList(); BroadcastDeviceBox.ItemsSource = devices.Prepend(DefaultDevice).ToList();
MonitorDeviceBox.ItemsSource = devices.Prepend(NoDevice).ToList(); MonitorDeviceBox.ItemsSource = devices.Prepend(NoDevice).ToList();
@@ -52,11 +50,10 @@ public partial class SettingsPage : Page
OnLautFmChanged(this, new RoutedEventArgs()); OnLautFmChanged(this, new RoutedEventArgs());
} }
// The access fields only matter while laut.fm is on.
private void OnLautFmChanged(object sender, RoutedEventArgs e) => private void OnLautFmChanged(object sender, RoutedEventArgs e) =>
LautFmFields.Visibility = LautFmSwitch.IsChecked == true ? Visibility.Visible : Visibility.Collapsed; LautFmFields.Visibility = LautFmSwitch.IsChecked == true ? Visibility.Visible : Visibility.Collapsed;
// An emptied number box counts as its default. // Empty number box -> default.
private static AppSettings Defaults { get; } = new(); private static AppSettings Defaults { get; } = new();
private AppSettings Read() => new() private AppSettings Read() => new()
@@ -5,10 +5,6 @@ using Wpf.Ui.Controls;
namespace Radiosender.Views; namespace Radiosender.Views;
/// <summary>
/// Dialog for the title of a news, ad or moderator item and, for news and moderator items, its length.
/// Only collects input; the caller changes the schedule.
/// </summary>
public partial class ScheduleItemEditWindow : FluentWindow public partial class ScheduleItemEditWindow : FluentWindow
{ {
private static readonly string[] DurationFormats = [@"m\:ss", @"mm\:ss"]; private static readonly string[] DurationFormats = [@"m\:ss", @"mm\:ss"];
@@ -20,7 +16,6 @@ public partial class ScheduleItemEditWindow : FluentWindow
TitleBox.Text = item.Title; TitleBox.Text = item.Title;
DurationBox.Text = item.Duration.ToString(@"m\:ss"); DurationBox.Text = item.Duration.ToString(@"m\:ss");
Duration = item.Duration; Duration = item.Duration;
// Ads keep their length.
DurationLabel.IsEnabled = DurationBox.IsEnabled = item.Kind is ScheduleItemKind.News or ScheduleItemKind.Moderator; DurationLabel.IsEnabled = DurationBox.IsEnabled = item.Kind is ScheduleItemKind.News or ScheduleItemKind.Moderator;
} }
@@ -4,7 +4,6 @@ using Wpf.Ui.Controls;
namespace Radiosender.Views; namespace Radiosender.Views;
/// <summary>Dialog for the editable song metadata. Only collects input; saving is done by the caller.</summary>
public partial class SongEditWindow : FluentWindow public partial class SongEditWindow : FluentWindow
{ {
public SongEditWindow(Song song) public SongEditWindow(Song song)
+1 -1
View File
@@ -1,4 +1,4 @@
using Radiosender.Services; using Radiosender.Services.Settings;
namespace Radiosender.Tests; namespace Radiosender.Tests;
@@ -0,0 +1,12 @@
using NAudio.Wave;
namespace Radiosender.Tests;
/// <summary>Skips the test on machines without an audio output device (for example CI agents).</summary>
public sealed class AudioDeviceFactAttribute : FactAttribute
{
public AudioDeviceFactAttribute()
{
if (WaveOut.DeviceCount == 0) Skip = "No audio output device available.";
}
}
+5 -1
View File
@@ -5,7 +5,11 @@ using NAudio.Wave;
using NAudio.Wave.SampleProviders; using NAudio.Wave.SampleProviders;
using Radiosender.Controllers; using Radiosender.Controllers;
using Radiosender.Models; using Radiosender.Models;
using Radiosender.Services; using Radiosender.Services.Audio;
using Radiosender.Services.Library;
using Radiosender.Services.Providers;
using Radiosender.Services.Settings;
using Radiosender.Services.Streaming;
namespace Radiosender.Tests; namespace Radiosender.Tests;
@@ -1,7 +1,7 @@
using Microsoft.Data.Sqlite; using Microsoft.Data.Sqlite;
using Radiosender.Controllers; using Radiosender.Controllers;
using Radiosender.Models; using Radiosender.Models;
using Radiosender.Services; using Radiosender.Services.Library;
namespace Radiosender.Tests; namespace Radiosender.Tests;
+2 -35
View File
@@ -1,18 +1,9 @@
using System.IO; using System.IO;
using NAudio.Wave; using NAudio.Wave;
using Radiosender.Services; using Radiosender.Services.Audio;
namespace Radiosender.Tests; namespace Radiosender.Tests;
/// <summary>Skips the test on machines without an audio output device (for example CI agents).</summary>
public sealed class AudioDeviceFactAttribute : FactAttribute
{
public AudioDeviceFactAttribute()
{
if (WaveOut.DeviceCount == 0) Skip = "No audio output device available.";
}
}
public sealed class MusicPlayerTests : IDisposable public sealed class MusicPlayerTests : IDisposable
{ {
private readonly string _directory = Path.Combine(Path.GetTempPath(), "radiosender-tests", Guid.NewGuid().ToString("N")); private readonly string _directory = Path.Combine(Path.GetTempPath(), "radiosender-tests", Guid.NewGuid().ToString("N"));
@@ -50,25 +41,6 @@ public sealed class MusicPlayerTests : IDisposable
Assert.Throws<NotSupportedException>(() => ProgramOutput.ToProgramFormat(new NAudio.Wave.SampleProviders.SignalGenerator(44100, 6))); Assert.Throws<NotSupportedException>(() => ProgramOutput.ToProgramFormat(new NAudio.Wave.SampleProviders.SignalGenerator(44100, 6)));
} }
[AudioDeviceFact]
public void PauseAndResume_KeepThePosition()
{
var player = MusicPlayer.Instance;
player.Play(CreateWav(TimeSpan.FromSeconds(3)));
Thread.Sleep(400);
player.Pause();
Assert.False(player.IsPlaying);
var paused = player.Position;
Thread.Sleep(300);
Assert.Equal(paused, player.Position);
player.Resume();
Assert.True(player.IsPlaying);
Thread.Sleep(400);
Assert.True(player.Position > paused);
}
[AudioDeviceFact] [AudioDeviceFact]
public void Play_TwoTracksInARow_RaisesTrackFinishedOnlyForTheSecond() public void Play_TwoTracksInARow_RaisesTrackFinishedOnlyForTheSecond()
{ {
@@ -162,29 +134,24 @@ public sealed class MusicPlayerTests : IDisposable
} }
[AudioDeviceFact] [AudioDeviceFact]
public void Play_ShortWav_RaisesTrackFinishedAndPositionChanged() public void Play_ShortWav_RaisesTrackFinished()
{ {
var player = MusicPlayer.Instance; var player = MusicPlayer.Instance;
using var finished = new ManualResetEventSlim(); using var finished = new ManualResetEventSlim();
var positionChanged = false;
EventHandler finishedHandler = (_, _) => finished.Set(); EventHandler finishedHandler = (_, _) => finished.Set();
EventHandler<TimeSpan> positionHandler = (_, _) => positionChanged = true;
player.TrackFinished += finishedHandler; player.TrackFinished += finishedHandler;
player.PositionChanged += positionHandler;
try try
{ {
player.Play(CreateWav(TimeSpan.FromSeconds(0.6))); player.Play(CreateWav(TimeSpan.FromSeconds(0.6)));
Assert.InRange(player.Duration.TotalSeconds, 0.59, 0.61); Assert.InRange(player.Duration.TotalSeconds, 0.59, 0.61);
Assert.True(finished.Wait(TimeSpan.FromSeconds(5)), "TrackFinished was not raised."); Assert.True(finished.Wait(TimeSpan.FromSeconds(5)), "TrackFinished was not raised.");
Assert.True(positionChanged);
Assert.False(player.IsPlaying); Assert.False(player.IsPlaying);
Assert.Equal(TimeSpan.Zero, player.Duration); Assert.Equal(TimeSpan.Zero, player.Duration);
} }
finally finally
{ {
player.TrackFinished -= finishedHandler; player.TrackFinished -= finishedHandler;
player.PositionChanged -= positionHandler;
} }
} }
} }
@@ -1,6 +1,6 @@
using System.Net; using System.Net;
using System.Text; using System.Text;
using Radiosender.Services; using Radiosender.Services.Providers;
namespace Radiosender.Tests; namespace Radiosender.Tests;
+2 -1
View File
@@ -3,7 +3,8 @@ using System.Text;
using Microsoft.Data.Sqlite; using Microsoft.Data.Sqlite;
using Radiosender.Controllers; using Radiosender.Controllers;
using Radiosender.Models; using Radiosender.Models;
using Radiosender.Services; using Radiosender.Services.Library;
using Radiosender.Services.Providers;
namespace Radiosender.Tests; namespace Radiosender.Tests;
@@ -1,6 +1,7 @@
using System.Collections.Concurrent; using System.Collections.Concurrent;
using Radiosender.Models; using Radiosender.Models;
using Radiosender.Services; using Radiosender.Services.Audio;
using Radiosender.Services.Scheduling;
namespace Radiosender.Tests; namespace Radiosender.Tests;
+1 -1
View File
@@ -1,5 +1,5 @@
using NAudio.Wave; using NAudio.Wave;
using Radiosender.Services; using Radiosender.Services.Audio;
namespace Radiosender.Tests; namespace Radiosender.Tests;
@@ -1,7 +1,9 @@
using Microsoft.Data.Sqlite; using Microsoft.Data.Sqlite;
using Radiosender.Controllers; using Radiosender.Controllers;
using Radiosender.Models; using Radiosender.Models;
using Radiosender.Services; using Radiosender.Services.Audio;
using Radiosender.Services.Library;
using Radiosender.Services.Scheduling;
namespace Radiosender.Tests; namespace Radiosender.Tests;
@@ -1,5 +1,5 @@
using Radiosender.Models; using Radiosender.Models;
using Radiosender.Services; using Radiosender.Services.Scheduling;
namespace Radiosender.Tests; namespace Radiosender.Tests;
@@ -1,7 +1,7 @@
using Microsoft.Data.Sqlite; using Microsoft.Data.Sqlite;
using NAudio.Wave; using NAudio.Wave;
using Radiosender.Models; using Radiosender.Models;
using Radiosender.Services; using Radiosender.Services.Library;
namespace Radiosender.Tests; namespace Radiosender.Tests;
@@ -1,7 +1,7 @@
using Microsoft.Data.Sqlite; using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Radiosender.Models; using Radiosender.Models;
using Radiosender.Services; using Radiosender.Services.Library;
namespace Radiosender.Tests; namespace Radiosender.Tests;