Merge branch 'j.lechner/lautfm' into 'main'

feat: stream live to laut.fm and import from its library

Closes #15

See merge request julian/blockwoche3.1-radiosender!15
This commit is contained in:
Julian Lechner committed 2026-11-25 07:38:58 +00:00
commit 816b902aca
22 files changed
+1820 -97

No files matched your search

+41 -8
View File
@@ -7,6 +7,7 @@ WPF desktop app that plans and plays a radio program for a chosen number of full
- Windows
- .NET SDK 10
- An audio output device for playback
- A microphone, if you want to talk on air
## Build and run
@@ -28,7 +29,7 @@ The interface is in German. This section names the controls as they appear on sc
1. **Import**: one page for both ways of adding music. Every result, added or failed, is listed under "Importiert" as soon as there is one, with a link to the library.
- **Vom Computer**: drop MP3 or WAV files on the page or click **Dateien auswählen...**; several files at once are fine. The app copies each file into the music folder, reads title and artist from the file tags and measures the duration. A file that fails is reported and the others still get imported.
- **Online**: choose Openverse or the Internet Archive in the list next to the search box. Search the catalog, preview a result and import it with **In Bibliothek importieren** or a double-click. Select several results with Ctrl or Shift to import them in one go; they are downloaded one after the other. The app downloads the file and stores its license and attribution with the song. Results that are already in the library or have no duration cannot be imported; the tooltip of the disabled button says why.
- **Online**: choose Openverse, the Internet Archive or, while laut.fm is switched on, laut.fm in the list next to the search box. Search the catalog, preview a result and import it with **In Bibliothek importieren** or a double-click. Select several results with Ctrl or Shift to import them in one go; they are downloaded one after the other. The app downloads the file and stores its license and attribution with the song. Results that are already in the library or have no duration cannot be imported; the tooltip of the disabled button says why.
2. **Bibliothek**: lists and searches all songs. Edit title, artist, license and attribution, or delete a song.
3. **Sendeplan** (the start page):
1. Choose the start (one of the next 12 full hours) and the number of hours (1 to 24), then click **Plan erstellen**.
@@ -38,9 +39,12 @@ The interface is in German. This section names the controls as they appear on sc
3. **Start** puts the plan on air on the real clock. Before the planned start the now-playing card shows when the broadcast begins; if the plan has already begun, playback joins at the next item. The same button then reads **Stopp** and ends it. The now-playing card shows the current item, its progress and the volume.
4. **Edit the timeline**: select an upcoming row and use the buttons above the list to move it up or down, edit it, or remove it (trash icon). News, ad and moderator items have no title until you give them one; news and moderator items can also change their length. A double-click opens the editor too. Every item after a change follows on without a gap. The item on air can be edited too, but not moved or removed; **Jetzt beenden** in the now-playing card ends it at once and starts the next item.
5. **Speaking reminder**: 30 seconds before a news or moderator item goes on air, a dialog in the middle of the screen reminds you on any page and stays until you click **OK**.
6. **Songwunsch**: choose a song, select an upcoming row in the timeline and click **Auswahl ersetzen**. This also works while the broadcast is running.
6. **Microphone**: **Mikro ein** in the now-playing card puts the default microphone on air, also over running music; the button turns red and reads **Mikro aus**. It works with or without a broadcast and stays on while you visit other pages.
7. **Mix levels**, below the now-playing row: **Musik für andere** and **Ich für andere** set how loud the music and the microphone are for the listeners, **Musik für mich** how loud the music is on your own device. **Sendung 1:1 hören** lets you hear exactly what the listeners hear. The slider next to the loudspeaker stays the overall music volume.
8. **Songwunsch**: choose a song, select an upcoming row in the timeline and click **Auswahl ersetzen**. This also works while the broadcast is running.
9. **Live** (only while laut.fm is switched on): sends everything on air, songs and microphone, live to your laut.fm station. It does not depend on the plan; the button turns red and reads **Live beenden**. See [laut.fm](#lautfm).
4. **Einstellungen** (bottom left): switch the speaking alert on or off for news and for moderator talk, set how many seconds before the start it appears and whether it plays a bing sound. Set the minutes per hour for news, moderator talk and ads (defaults 10, 10 and 20); together they can take at most 60 minutes. **Zurücksetzen** puts the default values into the form, **Speichern** stores them in `settings.json` next to the database. Alerts change at once; minutes per hour apply to the next schedule.
4. **Einstellungen** (bottom left): switch the speaking alert on or off for news and for moderator talk, set how many seconds before the start it appears and whether it plays a bing sound. Choose the playback device for the broadcast (for the listeners) and, if you have a second one such as headphones, the device for yourself. Set the minutes per hour for news, moderator talk and ads (defaults 10, 10 and 20); together they can take at most 60 minutes. **Zurücksetzen** puts the default values into the form, **Speichern** stores them in `settings.json` next to the database. Alerts change at once; minutes per hour apply to the next schedule. The **laut.fm** switch turns on live streaming and the station's library; its fields are described under [laut.fm](#lautfm).
News, ads and moderator talk are placeholders: the app shows them in the timeline and keeps silent for their duration, so the speaker can talk live.
@@ -65,7 +69,7 @@ The app follows the MVC pattern and uses [WPF UI](https://github.com/lepoco/wpfu
| --- | --- | --- |
| Model | `src/Radiosender/Models` | `Song`, `ScheduleItem`, `MusicTrack`, `OpenverseTrack` |
| View | `src/Radiosender/Views` | `MainWindow` with navigation, one page per feature, `SongEditWindow` |
| Controller | `src/Radiosender/Controllers` | `LibraryController`, `UploadController`, `OnlineImportController`, `ScheduleController` |
| Controller | `src/Radiosender/Controllers` | `LibraryController`, `UploadController`, `OnlineImportController`, `ScheduleController`, `LiveController` |
| Services | `src/Radiosender/Services` | database, audio, schedule logic and API access used by the controllers |
Views only handle input and display. They call a controller, and the controller works with the models and services. `App` is the composition root: it registers every service, controller and page in a `Microsoft.Extensions.DependencyInjection` container, and the navigation view asks that container for each page, so pages get their controllers through the constructor. The `SongRepository` and the `ScheduleController` are singletons. A running broadcast therefore keeps playing when the user switches pages.
@@ -74,13 +78,17 @@ Main services:
- `SongRepository`: CRUD for songs in SQLite through Entity Framework Core, without SQL in the code
- `SongImportService`: copies an uploaded file into the music folder, reads its tags with TagLibSharp and its duration with NAudio
- `IMusicProvider`: an online catalog that can be searched. `OpenverseProvider` uses the anonymous Openverse API and `InternetArchiveProvider` the Internet Archive search, limited to Creative Commons licensed MP3 files.
- `IMusicProvider`: an online catalog that can be searched. `OpenverseProvider` uses the anonymous Openverse API and `InternetArchiveProvider` the Internet Archive search, limited to Creative Commons licensed MP3 files. `LautFmProvider` searches the library of the user's laut.fm station.
- `TrackDownloader`: downloads a search result into the music folder, the same way for every provider
- `MusicPlayer`: the audio player as a singleton (`MusicPlayer.Instance`, private constructor). It plays files with NAudio.
- `ProgramMixer`: mixes songs and the microphone twice in one pass, once for the listeners and once for the person at the desk, each with its own levels
- `ProgramOutput`: the station's audio channel. It plays the broadcast mix on one device and, if a second device is chosen, the monitor mix on that one
- `MusicPlayer`: the audio player as a singleton (`MusicPlayer.Instance`, private constructor). It reads files with NAudio and plays them on the `ProgramOutput`
- `Microphone`: captures the default recording device and puts it on the `ProgramOutput`
- `ScheduleGenerator`: builds the plan and handles song requests
- `PlaybackEngine`: runs the plan item by item on a background thread and plays songs through `MusicPlayer`
- `IcecastStream`: logs in at an Icecast server as a live source, encodes a copy of the broadcast mix to MP3 with Windows Media Foundation and sends it. `LiveController` starts and stops it and sets the stream title for each item through `StreamTitles`
Tests are in `tests/Radiosender.Tests` (xUnit). They cover the repository, import, Openverse parsing, the generator rules, the playback engine and the schedule controller.
Tests are in `tests/Radiosender.Tests` (xUnit). They cover the repository, import, Openverse parsing, the generator rules, the playback engine, the schedule controller and laut.fm (settings, Icecast login, ad trigger, track parsing).
## Adding a music provider
@@ -89,6 +97,7 @@ Online sources sit behind `IMusicProvider`, so a new one needs no change to the
1. Write a class that implements `IMusicProvider`: a `Name` for the interface and `SearchAsync`, which returns `MusicTrack` items (title, creator, https link to the audio file, license, attribution, duration).
2. Give every track an `Id` that no other provider uses, for example prefixed with the provider name. Openverse ids are stored as they come.
3. Register the class in `App.BuildServices` with `services.AddSingleton<IMusicProvider, YourProvider>()`.
4. A provider that depends on a setting can return `false` from `IsAvailable`; the import page then leaves it out.
With one provider the import tab carries its name. With several, the tab is called "Online" and a list next to the search box chooses the provider.
@@ -118,6 +127,28 @@ For each downloaded track the app stores the license (for example `CC BY 4.0`) a
| The player really plays music | `MusicPlayer` with NAudio | Done |
| C#, WPF with MVC, WPF UI | .NET 10, folders above, WPF UI 4.3 | Done |
## laut.fm
With laut.fm switched on in the settings, the app streams live to a [laut.fm](https://laut.fm) station and offers the station's music on the Import page.
1. In Radioadmin, open **Live senden** and copy server, port, mountpoint, user and password into the laut.fm card on the Settings page. Save.
2. For the library, enter the station id and the Radioadmin token. The token is the value of `laut.fm.api.token` in the browser's local storage after logging in to Radioadmin (developer tools).
3. On the Sendeplan page, **Live** connects to laut.fm and sends the broadcast mix as MP3 at 128 kbit/s. laut.fm then plays the live stream instead of the station's regular program.
The app connects as an Icecast source (`PUT` to the mountpoint with the user and password). Each item that starts sets the stream title: `Artist - Title` for songs and the item title otherwise. Ad items send `START_AD_BREAK`, which laut.fm needs to start its ad break; the app sends it at most once every 15 minutes, as laut.fm requires.
Password and token are stored in `settings.json` encrypted with Windows DPAPI for the current Windows user. Another user or computer cannot read them and has to enter them again.
Risks:
- The library uses the API behind Radioadmin (`api.radioadmin.laut.fm`). laut.fm does not publish it for other programs, so it can change or stop working without notice, and the token expires when Radioadmin logs out.
- The import downloads the prelisten link that Radioadmin uses. Whether that is the full track or a shorter preview has not been checked against a real station.
- laut.fm licenses the station's music for broadcasting on laut.fm. Imported laut.fm tracks are marked with that license and must not be played anywhere else.
- Nothing here has been tested against a real laut.fm account. The tests run against a local fake server. If laut.fm expects a different format or login method, the settings show the error but do not adapt.
- The source connection and the title updates use plain HTTP, like every Icecast source client, so the live password crosses the network unencrypted.
- The MP3 encoder comes with Windows. Windows "N" editions lack it until the Media Feature Pack is installed; **Live** then reports the missing encoder.
- laut.fm wants the ad trigger at least once every half hour. With 0 ad minutes per hour the plan has no ad items and the app never sends it.
## Known limitations
- **Waiting for the start**: a plan made with **Plan erstellen** starts at a full hour, so after **Start** the app stays silent until then. **Jetzt starten** avoids the wait.
@@ -128,5 +159,7 @@ For each downloaded track the app stores the license (for example `CC BY 4.0`) a
- **Internet Archive**: one search asks for up to 8 items and then for the file list of each, and shows at most 5 MP3 files per item. Results can include long recordings; the 50 MB download limit applies.
- **Very old libraries**: a `radiosender.db` from before the Openverse import has no `OpenverseId` column and is not upgraded. Delete the file and import the music again.
- **Deleting a song** removes it from the library but keeps its file in the `Music` folder.
- **Placeholders** have no audio.
- **Placeholders** have no audio; news and moderator talk are spoken live through the microphone.
- **Microphone**: uses the default Windows recording device. With loudspeakers next to the microphone the room hears itself and can start to howl, so use headphones. Speech arrives about a fifth of a second late. The alert tone and the import preview are not part of the program channel.
- **Two mixes need two devices**: with one playback device you hear your own mix, or the broadcast mix while **Sendung 1:1 hören** is on, and nobody else hears anything different. Your own mix never contains the microphone. With two devices their clocks can drift, which shows as a rare tiny dropout on the second device. The mix levels are not stored and start at full on every launch.
- **Targets** for ads and moderator talk are missed by the time the songs cannot fill, usually a few seconds per hour; a small library or only long songs make that more.
+16 -2
View File
@@ -20,8 +20,12 @@ public partial class App : Application
// so a running broadcast keeps going while the user switches pages.
services.AddSingleton(_ => new SongRepository(SongRepository.DefaultDatabasePath));
services.AddSingleton(_ => new ScheduleGenerator());
services.AddSingleton(provider => new SettingsStore(provider.GetRequiredService<ScheduleGenerator>(), AppSettings.DefaultPath));
services.AddSingleton(provider => new SettingsStore(
provider.GetRequiredService<ScheduleGenerator>(), provider.GetRequiredService<ProgramOutput>(), AppSettings.DefaultPath));
services.AddSingleton(_ => new PlaybackEngine());
// The one audio channel that songs and the microphone share.
services.AddSingleton(_ => ProgramOutput.Instance);
services.AddSingleton<Microphone>();
services.AddSingleton(provider => new ScheduleController(
provider.GetRequiredService<SongRepository>(),
provider.GetRequiredService<ScheduleGenerator>(),
@@ -37,6 +41,15 @@ public partial class App : Application
// Music providers: add a line here for each new IMusicProvider; the import page lists them all.
services.AddSingleton<IMusicProvider, OpenverseProvider>();
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(
provider.GetRequiredService<System.Net.Http.HttpClient>(), () => provider.GetRequiredService<SettingsStore>().Current));
services.AddSingleton(provider => new LiveController(
provider.GetRequiredService<ScheduleController>(),
provider.GetRequiredService<SettingsStore>(),
provider.GetRequiredService<ProgramOutput>(),
provider.GetRequiredService<System.Net.Http.HttpClient>(),
() => DateTime.Now));
services.AddSingleton(provider => new TrackDownloader(provider.GetRequiredService<System.Net.Http.HttpClient>(), TrackDownloader.DefaultMusicFolder));
services.AddSingleton<OnlineImportController>();
services.AddSingleton(provider => new SongImportService(provider.GetRequiredService<SongRepository>(), SongImportService.DefaultMusicDirectory));
@@ -57,7 +70,7 @@ public partial class App : Application
{
base.OnStartup(e);
_services = BuildServices();
// Loads the settings and gives the generator its minutes per hour before the first plan.
// Loads the settings: the generator gets its minutes per hour before the first plan, the audio output its devices.
_services.GetRequiredService<SettingsStore>();
// Follow the Windows setting: light, dark or a high-contrast theme.
Wpf.Ui.Appearance.ApplicationThemeManager.ApplySystemTheme();
@@ -66,6 +79,7 @@ public partial class App : Application
protected override void OnExit(ExitEventArgs e)
{
_services?.GetRequiredService<LiveController>().Stop();
_services?.GetRequiredService<ScheduleController>().Stop();
_services?.Dispose();
base.OnExit(e);
@@ -0,0 +1,120 @@
using System.Net.Http;
using NAudio.Wave;
using Radiosender.Services;
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
{
private readonly ScheduleController _schedule;
private readonly SettingsStore _settings;
private readonly ProgramOutput _output;
private readonly HttpClient _http;
private readonly StreamTitles _titles;
private readonly Lock _lock = new();
private IcecastStream? _stream;
private BufferedWaveProvider? _feed;
private IcecastTarget? _target;
public LiveController(ScheduleController schedule, SettingsStore settings, ProgramOutput output, HttpClient http, Func<DateTime> now)
{
_schedule = schedule;
_settings = settings;
_output = output;
_http = http;
_titles = new StreamTitles(now);
_schedule.ItemStarted += (_, _) => SendCurrentTitle();
}
/// <summary>laut.fm is switched on in the settings.</summary>
public bool IsEnabled => _settings.Current.LautFmEnabled;
public bool IsLive => _stream is not null;
/// <summary>
/// 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;
/// <exception cref="LiveStreamException">laut.fm is off or cannot be reached, or the login was refused.</exception>
/// <exception cref="NAudio.MmException">No audio output device can be opened; the broadcast device sets the pace.</exception>
public async Task StartAsync(CancellationToken cancellationToken = default)
{
if (IsLive)
return;
var settings = _settings.Current;
if (!settings.LautFmEnabled)
throw new LiveStreamException("laut.fm ist in den Einstellungen ausgeschaltet.");
var target = IcecastTarget.From(settings);
var feed = _output.OpenLiveFeed();
IcecastStream stream;
try
{
stream = await IcecastStream.ConnectAsync(target, feed, cancellationToken);
}
catch
{
_output.CloseLiveFeed(feed);
throw;
}
stream.Failed += OnFailed;
lock (_lock)
{
_stream = stream;
_feed = feed;
_target = target;
}
SendCurrentTitle();
}
public void Stop() => Stop(null);
// With a stream given, stops only if that one is still the current stream.
private void Stop(IcecastStream? only)
{
IcecastStream stream;
BufferedWaveProvider feed;
lock (_lock)
{
if (_stream is null || _feed is null || (only is not null && _stream != only))
return;
(stream, feed) = (_stream, _feed);
(_stream, _feed, _target) = (null, null, null);
}
stream.Failed -= OnFailed;
stream.Dispose();
_output.CloseLiveFeed(feed);
}
private void OnFailed(object? sender, string message)
{
Stop(sender as IcecastStream);
Problem?.Invoke(this, message);
}
private async void SendCurrentTitle()
{
IcecastTarget target;
string title;
lock (_lock)
{
if (_target is null || _schedule.CurrentItem is not { } item)
return;
target = _target;
title = _titles.For(item);
}
try
{
await IcecastStream.UpdateTitleAsync(_http, target, title);
}
catch (LiveStreamException ex)
{
Problem?.Invoke(this, ex.Message);
}
}
}
@@ -7,8 +7,10 @@ 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)
{
/// <summary>Every provider registered in <c>App</c>, in registration order.</summary>
public IReadOnlyList<IMusicProvider> Providers { get; } = providers.ToList();
private readonly IReadOnlyList<IMusicProvider> _providers = providers.ToList();
/// <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).ToList();
/// <summary>Ids of the provider results that are already in the library.</summary>
public IReadOnlySet<string> ImportedIds() => songs.GetExternalIds();
+72
View File
@@ -1,5 +1,8 @@
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace Radiosender.Services;
@@ -32,6 +35,44 @@ public record AppSettings
/// <summary>Target; the plan gets as close as the song lengths allow.</summary>
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; }
/// <summary>Playback device for the person at the desk; <c>null</c> means no device of its own.</summary>
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; }
/// <summary>The station's id in Radioadmin, needed for the library.</summary>
public string LautFmStationId { get; init; } = "";
/// <summary>Live access data from Radioadmin, "Live senden".</summary>
public string LautFmHost { get; init; } = "";
public int LautFmPort { get; init; } = 8080;
public string LautFmMount { get; init; } = "";
public string LautFmUser { get; init; } = "source";
/// <summary>Kept in memory as is; the file only holds it encrypted for the Windows user.</summary>
[JsonIgnore]
public string LautFmPassword { get; init; } = "";
/// <summary>The Radioadmin login token for the library; stored encrypted like the password.</summary>
[JsonIgnore]
public string LautFmToken { get; init; } = "";
[JsonInclude, JsonPropertyName("LautFmPassword")]
private string? ProtectedLautFmPassword { get => Protect(LautFmPassword); init => LautFmPassword = Unprotect(value); }
[JsonInclude, JsonPropertyName("LautFmToken")]
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.
public override string ToString() => nameof(AppSettings);
public static string DefaultPath { get; } = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Radiosender", "settings.json");
@@ -46,6 +87,17 @@ public record AppSettings
return "Minuten pro Stunde dürfen nicht negativ sein.";
if (NewsMinutesPerHour + ModeratorMinutesPerHour + AdMinutesPerHour > 60)
return "Nachrichten, Moderation und Werbung dürfen zusammen höchstens 60 Minuten pro Stunde dauern.";
if (LautFmEnabled)
{
if (string.IsNullOrWhiteSpace(LautFmHost) || Uri.CheckHostName(LautFmHost.Trim()) == UriHostNameType.Unknown)
return "Für laut.fm fehlt ein gültiger Server.";
if (LautFmPort is < 1 or > 65535)
return "Der laut.fm-Port muss zwischen 1 und 65535 liegen.";
if (string.IsNullOrWhiteSpace(LautFmMount))
return "Für laut.fm fehlt der Mountpoint.";
if (LautFmToken.Length > 0 && string.IsNullOrWhiteSpace(LautFmStationId))
return "Für die laut.fm-Bibliothek fehlt die Stations-ID.";
}
return null;
}
@@ -77,4 +129,24 @@ public record AppSettings
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
File.WriteAllText(path, JsonSerializer.Serialize(this, new JsonSerializerOptions { WriteIndented = true }));
}
// DPAPI: only this Windows user on this computer can read the value back.
private static string? Protect(string secret) => secret.Length == 0
? null
: 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.
private static string Unprotect(string? stored)
{
if (string.IsNullOrEmpty(stored))
return "";
try
{
return Encoding.UTF8.GetString(ProtectedData.Unprotect(Convert.FromBase64String(stored), null, DataProtectionScope.CurrentUser));
}
catch (Exception ex) when (ex is CryptographicException or FormatException)
{
return "";
}
}
}
@@ -15,6 +15,9 @@ 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);
}
+206
View File
@@ -0,0 +1,206 @@
using System.IO;
using System.Net.Http;
using System.Net.Sockets;
using System.Text;
using NAudio.MediaFoundation;
using NAudio.Wave;
namespace Radiosender.Services;
/// <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 const int Bitrate = 128_000;
private static readonly TimeSpan ConnectTimeout = TimeSpan.FromSeconds(10);
private readonly TcpClient _client;
private readonly FeedReader _reader;
private readonly Thread _thread;
private volatile bool _stopping;
private IcecastStream(TcpClient client, IWaveProvider feed)
{
_client = client;
_reader = new FeedReader(feed);
_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>
public event EventHandler<string>? Failed;
/// <summary>Logs in at the server and starts sending.</summary>
/// <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)
{
// These values end up in the request line and headers; a line break there would change the request.
if (new[] { target.Host, target.Path, target.User }.Any(value => value.Any(c => char.IsWhiteSpace(c) || char.IsControl(c)))
|| target.User.Contains(':'))
throw new LiveStreamException("Server, Mountpoint oder Benutzer enthalten ungültige Zeichen.");
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
timeout.CancelAfter(ConnectTimeout);
var client = new TcpClient();
try
{
await client.ConnectAsync(target.Host, target.Port, timeout.Token);
var network = client.GetStream();
var request =
$"PUT {target.Path} HTTP/1.1\r\n" +
$"Host: {target.Host}:{target.Port}\r\n" +
$"Authorization: Basic {target.Credentials}\r\n" +
"User-Agent: Radiosender/1.0\r\n" +
"Content-Type: audio/mpeg\r\n" +
"Ice-Public: 0\r\n" +
$"Ice-Bitrate: {Bitrate / 1000}\r\n" +
"Expect: 100-continue\r\n\r\n";
await network.WriteAsync(Encoding.ASCII.GetBytes(request), timeout.Token);
var status = await ReadStatusAsync(network, timeout.Token);
if (status is not (100 or 200))
{
throw new LiveStreamException(status switch
{
401 => "laut.fm hat die Anmeldung abgelehnt: Benutzer oder Passwort stimmen nicht.",
403 => "laut.fm nimmt gerade keinen Livestream an: Der Mountpoint ist belegt oder nicht freigeschaltet.",
404 => "Diesen Mountpoint gibt es auf dem Server nicht.",
_ => $"Der Server hat den Livestream abgelehnt (HTTP {status}).",
});
}
var stream = new IcecastStream(client, feed);
stream._thread.Start();
return stream;
}
catch (Exception ex)
{
client.Dispose();
if (ex is LiveStreamException || cancellationToken.IsCancellationRequested)
throw;
throw ex switch
{
OperationCanceledException => new LiveStreamException("Der laut.fm-Server antwortet nicht.", ex),
SocketException or IOException => new LiveStreamException($"Keine Verbindung zum laut.fm-Server: {ex.Message}", ex),
_ => ex,
};
}
}
/// <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>
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.
var url = new UriBuilder(Uri.UriSchemeHttp, target.Host, target.Port, "/admin/metadata")
{
Query = $"mount={Uri.EscapeDataString(target.Path)}&mode=updinfo&song={Uri.EscapeDataString(title)}",
}.Uri;
using var request = new HttpRequestMessage(HttpMethod.Get, url);
request.Headers.Authorization = new("Basic", target.Credentials);
try
{
using var response = await http.SendAsync(request, cancellationToken);
if (!response.IsSuccessStatusCode)
throw new LiveStreamException($"laut.fm hat den Titel nicht angenommen (HTTP {(int)response.StatusCode}).");
}
catch (Exception ex) when (ex is HttpRequestException or TaskCanceledException && !cancellationToken.IsCancellationRequested)
{
throw new LiveStreamException($"Der Titel konnte nicht an laut.fm gesendet werden: {ex.Message}", ex);
}
}
/// <summary>Stops sending and closes the connection.</summary>
public void Dispose()
{
_stopping = true;
_reader.Stop();
// The encoder ends once the reader returns 0; a stalled connection is cut by closing the socket.
if (Thread.CurrentThread != _thread && _thread.IsAlive)
_thread.Join(TimeSpan.FromSeconds(2));
_client.Dispose();
}
private void Run()
{
try
{
MediaFoundationApi.Startup();
var pcm = _reader.ToSampleProvider().ToWaveProvider16();
var mediaType = MediaFoundationEncoder.SelectMediaType(AudioSubtypes.MFAudioFormat_MP3, pcm.WaveFormat, Bitrate)
?? throw new LiveStreamException("Windows hat keinen MP3-Encoder.");
using var encoder = new MediaFoundationEncoder(mediaType);
encoder.Encode(_client.GetStream(), pcm, TranscodeContainerTypes.MFTranscodeContainerType_MP3);
if (!_stopping)
Failed?.Invoke(this, "Der Livestream wurde unerwartet beendet.");
}
catch (Exception ex)
{
// While stopping, closing the socket under the encoder is expected.
if (!_stopping)
Failed?.Invoke(this, ex is LiveStreamException ? ex.Message : $"Verbindung zu laut.fm verloren: {ex.Message}");
}
}
private static async Task<int> ReadStatusAsync(NetworkStream network, CancellationToken cancellationToken)
{
var header = new StringBuilder();
var buffer = new byte[512];
while (!header.ToString().Contains("\r\n\r\n"))
{
var read = await network.ReadAsync(buffer, cancellationToken);
if (read == 0 || header.Length > 8192)
throw new LiveStreamException("Der Server hat die Verbindung ohne gültige Antwort beendet.");
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);
return parts.Length >= 2 && int.TryParse(parts[1], out var status)
? status
: 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>
private sealed class FeedReader(IWaveProvider feed) : IWaveProvider
{
private volatile bool _stopped;
public WaveFormat WaveFormat => feed.WaveFormat;
public void Stop() => _stopped = true;
public int Read(Span<byte> buffer)
{
while (!_stopped)
{
var read = feed.Read(buffer);
if (read > 0)
return read;
Thread.Sleep(10);
}
return 0; // the encoder finishes and returns
}
}
}
@@ -0,0 +1,78 @@
using System.Net.Http;
using System.Text.Json;
using Radiosender.Models;
namespace Radiosender.Services;
/// <summary>
/// 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 const string ApiBase = "https://api.radioadmin.laut.fm/";
public string Name => "laut.fm";
public bool IsAvailable => settings().LautFmEnabled;
public async Task<IReadOnlyList<MusicTrack>> SearchAsync(string query, CancellationToken cancellationToken = default)
{
var current = settings();
var station = current.LautFmStationId.Trim();
if (current.LautFmToken.Length == 0 || station.Length == 0)
throw new MusicProviderException("Für die laut.fm-Bibliothek fehlen Stations-ID oder Token in den Einstellungen.");
var words = query.Trim();
if (words.Length == 0)
return [];
// The API filters one field at a time, so title and artist are two searches.
var url = $"{ApiBase}stations/{Uri.EscapeDataString(station)}/tracks?";
var results = await Task.WhenAll(
SearchFieldAsync($"{url}title={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();
}
private async Task<List<MusicTrack>> SearchFieldAsync(string url, string token, CancellationToken cancellationToken)
{
using var json = await ProviderParsing.GetJsonAsync(http, url, Name, cancellationToken, token);
if (!json.RootElement.TryGetProperty("tracks", out var tracks) || tracks.ValueKind != JsonValueKind.Array)
throw new MusicProviderException($"{Name}-Suche fehlgeschlagen: unerwartete Antwort.");
var result = new List<MusicTrack>();
foreach (var track in tracks.EnumerateArray())
{
if (ProviderParsing.Text(track, "id") is not { } id
|| ProviderParsing.Text(track, "title") is not { } title
|| PrelistenUrl(track) is not { } audio)
continue;
result.Add(new MusicTrack
{
// Prefixed, so the id cannot collide with one from another provider.
Id = $"lautfm:{id}",
Title = title,
Creator = ProviderParsing.Text(track, "artist"),
Url = audio,
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)",
Duration = ProviderParsing.Duration(ProviderParsing.Text(track, "duration")),
});
}
return result;
}
// The link the Radioadmin player uses; it needs no login. Relative links are taken against the API.
private static string? PrelistenUrl(JsonElement track)
{
if (!track.TryGetProperty("_links", out var links) || links.ValueKind != JsonValueKind.Object
|| !links.TryGetProperty("prelisten_authless", out var link)
|| ProviderParsing.Text(link, "href") is not { } href
|| !Uri.TryCreate(new Uri(ApiBase), href, out var uri)
|| uri.Scheme != Uri.UriSchemeHttps)
return null;
return uri.AbsoluteUri;
}
}
+58
View File
@@ -0,0 +1,58 @@
using NAudio.Wave;
namespace Radiosender.Services;
/// <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
{
private readonly Lock _lock = new();
private WaveIn? _capture;
private ISampleProvider? _input;
public bool IsOn
{
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>
public void TurnOn()
{
lock (_lock)
{
if (_capture is not null)
return;
if (WaveIn.DeviceCount == 0)
throw new InvalidOperationException("Es wurde kein Mikrofon gefunden.");
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.
var buffer = new BufferedWaveProvider(capture.WaveFormat, TimeSpan.FromMilliseconds(300)) { DiscardOnBufferOverflow = true };
capture.DataAvailable += (_, e) => buffer.AddSamples(e.Buffer, 0, e.BytesRecorded);
try
{
capture.StartRecording();
_input = output.Add(buffer.ToSampleProvider(), AudioSource.Microphone);
}
catch (Exception e) when (e is NAudio.MmException or NotSupportedException)
{
capture.Dispose();
throw new InvalidOperationException($"Das Mikrofon konnte nicht eingeschaltet werden: {e.Message}", e);
}
_capture = capture;
}
}
public void TurnOff()
{
lock (_lock)
{
if (_input is not null)
output.Remove(_input);
_input = null;
_capture?.Dispose(); // stops the recording
_capture = null;
}
}
public void Dispose() => TurnOff();
}
+33 -31
View File
@@ -4,7 +4,7 @@ using NAudio.Wave;
namespace Radiosender.Services;
/// <summary>
/// Plays one audio file at a time through the default output device.
/// 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,
@@ -17,15 +17,19 @@ public sealed class MusicPlayer : IAudioPlayer
private static readonly TimeSpan PositionInterval = TimeSpan.FromMilliseconds(250);
private readonly ProgramOutput _output = ProgramOutput.Instance;
private readonly Lock _lock = new();
private WaveOut? _output;
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()
{
// Releases the audio device when the app exits.
// 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();
}
@@ -39,7 +43,7 @@ public sealed class MusicPlayer : IAudioPlayer
public bool IsPlaying
{
get { lock (_lock) return _output?.PlaybackState == PlaybackState.Playing; }
get { lock (_lock) return _input is not null; }
}
public TimeSpan Position
@@ -52,7 +56,10 @@ public sealed class MusicPlayer : IAudioPlayer
get { lock (_lock) return _reader?.TotalTime ?? TimeSpan.Zero; }
}
/// <summary>Playback volume from 0 (silent) to 1 (full). Kept across tracks.</summary>
/// <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; }
@@ -85,25 +92,20 @@ public sealed class MusicPlayer : IAudioPlayer
try
{
_reader = new AudioFileReader(filePath) { Volume = _volume };
_input = _output.Add(_reader, AudioSource.Music);
}
catch (Exception ex) when (ex is not OutOfMemoryException)
catch (Exception ex) when (ex is not (OutOfMemoryException or NAudio.MmException))
{
Release();
throw new InvalidDataException($"Audiodatei kann nicht gelesen werden: {filePath}", ex);
}
try
{
_output = new WaveOut();
_output.PlaybackStopped += OnPlaybackStopped;
_output.Init(_reader);
_output.Play();
_positionTimer = new Timer(OnPositionTimer, null, PositionInterval, PositionInterval);
}
catch
{
Release();
Release(); // no output device: the file must not stay open
throw;
}
_positionTimer = new Timer(OnPositionTimer, null, PositionInterval, PositionInterval);
}
}
@@ -111,7 +113,9 @@ public sealed class MusicPlayer : IAudioPlayer
{
lock (_lock)
{
if (_output?.PlaybackState == PlaybackState.Playing) _output.Pause();
if (_input is null) return;
_output.Remove(_input);
_input = null;
}
}
@@ -119,45 +123,43 @@ public sealed class MusicPlayer : IAudioPlayer
{
lock (_lock)
{
if (_output?.PlaybackState == PlaybackState.Paused) _output.Play();
if (_reader is not null && _input is null) _input = _output.Add(_reader, AudioSource.Music);
}
}
/// <summary>Stops playback and releases the file and audio device. Does not raise <see cref="TrackFinished"/>.</summary>
/// <summary>Stops playback and releases the file. Does not raise <see cref="TrackFinished"/>.</summary>
public void Stop()
{
lock (_lock) Release();
}
// Caller holds _lock. Unsubscribing first keeps Stop and track replacement from raising TrackFinished.
// Caller holds _lock. Clearing _input first keeps Stop and track replacement from raising TrackFinished.
private void Release()
{
_positionTimer?.Dispose();
_positionTimer = null;
if (_output is not null)
if (_input is not null)
{
_output.PlaybackStopped -= OnPlaybackStopped;
_output.Dispose();
_output = 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 OnPlaybackStopped(object? sender, StoppedEventArgs e)
private void OnInputEnded(ISampleProvider input)
{
lock (_lock)
{
// A stale event from an output that Stop or Play already released.
if (!ReferenceEquals(sender, _output)) return;
// Another input of the channel, or a track that Stop or Play already replaced.
if (!ReferenceEquals(input, _input)) return;
Release();
}
// An exception means a device error, not a natural end of the track.
if (e.Exception is null)
ThreadPool.QueueUserWorkItem(_ => TrackFinished?.Invoke(this, EventArgs.Empty));
TrackFinished?.Invoke(this, EventArgs.Empty);
}
private void OnPositionTimer(object? state)
@@ -165,7 +167,7 @@ public sealed class MusicPlayer : IAudioPlayer
TimeSpan position;
lock (_lock)
{
if (_output?.PlaybackState != PlaybackState.Playing || _reader is null) return;
if (_input is null || _reader is null) return;
position = _reader.CurrentTime;
}
+102
View File
@@ -0,0 +1,102 @@
using NAudio.Wave;
namespace Radiosender.Services;
/// <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
{
private readonly Lock _lock = new();
private readonly List<(ISampleProvider Input, AudioSource Kind)> _inputs = [];
private float[] _scratch = [];
// Written by the UI thread, read by the audio thread; a level that arrives one block late is fine.
private volatile float _musicForOthers = 1f;
private volatile float _microphoneForOthers = 1f;
private volatile float _musicForMe = 1f;
private volatile bool _listenToBroadcast = true;
/// <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;
/// <summary>How loud the music is on the broadcast, from 0 to 1.</summary>
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); }
/// <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>
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 void Add(ISampleProvider input, AudioSource kind)
{
lock (_lock) _inputs.Add((input, kind));
}
/// <summary>Returns once the audio thread no longer reads from the input.</summary>
public void Remove(ISampleProvider 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)
{
broadcast.Clear();
monitor.Clear();
if (_scratch.Length < broadcast.Length)
_scratch = new float[broadcast.Length];
var block = _scratch.AsSpan(0, broadcast.Length);
var copyBroadcast = _listenToBroadcast;
lock (_lock)
{
for (var i = _inputs.Count - 1; i >= 0; i--)
{
var (input, kind) = _inputs[i];
var read = input.Read(block);
var forOthers = kind == AudioSource.Music ? _musicForOthers : _microphoneForOthers;
var forMe = kind == AudioSource.Music ? _musicForMe : 0f;
for (var n = 0; n < read; n++)
{
broadcast[n] += block[n] * forOthers;
monitor[n] += block[n] * forMe;
}
if (read < block.Length)
{
_inputs.RemoveAt(i);
InputEnded?.Invoke(this, input);
}
}
}
// Two loud inputs can add up past full scale, which would distort harshly on the device.
for (var n = 0; n < broadcast.Length; n++)
{
broadcast[n] = Math.Clamp(broadcast[n], -1f, 1f);
monitor[n] = copyBroadcast ? broadcast[n] : Math.Clamp(monitor[n], -1f, 1f);
}
}
private static float Level(float value)
{
ArgumentOutOfRangeException.ThrowIfLessThan(value, 0f);
ArgumentOutOfRangeException.ThrowIfGreaterThan(value, 1f);
return value;
}
}
+223
View File
@@ -0,0 +1,223 @@
using System.Runtime.InteropServices;
using NAudio.Wave;
using NAudio.Wave.SampleProviders;
namespace Radiosender.Services;
/// <summary>
/// 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
{
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);
private readonly Lock _lock = new();
private string? _broadcastName;
private string? _monitorName;
private bool _started;
private WaveOut? _broadcastDevice;
private WaveOut? _monitorDevice;
private volatile BufferedWaveProvider? _liveFeed;
private ProgramOutput()
{
Mixer.InputEnded += (_, input) => InputEnded?.Invoke(this, input);
// Releases the audio devices when the app exits.
AppDomain.CurrentDomain.ProcessExit += (_, _) => { lock (_lock) CloseDevices(); };
}
public static ProgramOutput Instance => LazyInstance.Value;
/// <summary>The levels of both mixes.</summary>
public ProgramMixer Mixer { get; } = new();
/// <summary>Same as <see cref="ProgramMixer.InputEnded"/>: raised on the audio thread, handlers must return at once.</summary>
public event EventHandler<ISampleProvider>? InputEnded;
/// <summary>Names of the playback devices Windows offers, for the settings page.</summary>
public static IReadOnlyList<string> DeviceNames() =>
Enumerable.Range(0, WaveOut.DeviceCount).Select(i => WaveOut.GetCapabilities(i).ProductName).ToList();
/// <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>
public void UseDevices(string? broadcast, string? monitor)
{
lock (_lock)
{
_broadcastName = broadcast;
_monitorName = monitor;
if (!_started)
return;
CloseDevices();
OpenDevices();
}
}
/// <summary>Puts a source on air and opens the output devices on first use.</summary>
/// <returns>The input as the mixer knows it; pass it to <see cref="Remove"/> and compare it in <see cref="InputEnded"/>.</returns>
/// <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)
{
var input = ToProgramFormat(source);
lock (_lock)
{
if (!_started)
{
OpenDevices();
_started = true;
}
}
Mixer.Add(input, kind);
return input;
}
/// <summary>
/// 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()
{
// 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 };
lock (_lock)
{
if (!_started)
{
OpenDevices();
_started = true;
}
_liveFeed = feed;
}
return feed;
}
/// <summary>Stops copying into the feed from <see cref="OpenLiveFeed"/>.</summary>
public void CloseLiveFeed(BufferedWaveProvider feed)
{
lock (_lock)
{
if (_liveFeed == feed)
_liveFeed = null;
}
}
/// <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);
/// <summary>Converts mono to stereo and any sample rate to the channel's 44.1 kHz.</summary>
public static ISampleProvider ToProgramFormat(ISampleProvider source)
{
if (source.WaveFormat.Channels > 2)
throw new NotSupportedException("Audio with more than two channels is not supported.");
if (source.WaveFormat.Channels == 1)
source = new MonoToStereoSampleProvider(source);
if (source.WaveFormat.SampleRate != Format.SampleRate)
source = new WdlResamplingSampleProvider(source, Format.SampleRate);
return source;
}
// Caller holds _lock.
private void OpenDevices()
{
var names = DeviceNames().ToList();
var broadcast = _broadcastName is null ? -1 : names.IndexOf(_broadcastName); // -1 is the Windows default device
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))
monitor = -1;
try
{
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));
}
else
{
// The broadcast device sets the pace. Each block it asks for also yields the monitor block,
// 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 };
_broadcastDevice = Open(broadcast, new Tap(this, monitorBuffer));
_monitorDevice = Open(monitor, monitorBuffer.ToSampleProvider());
}
}
catch
{
CloseDevices();
throw;
}
}
private static WaveOut Open(int deviceNumber, ISampleProvider source)
{
// Three buffers of 50 ms: short enough that live speech does not lag noticeably.
var device = new WaveOut { DeviceNumber = deviceNumber, BufferMilliseconds = 50, NumberOfBuffers = 3 };
try
{
device.Init(source);
device.Play();
return device;
}
catch
{
device.Dispose();
throw;
}
}
// Caller holds _lock.
private void CloseDevices()
{
_broadcastDevice?.Dispose();
_broadcastDevice = null;
_monitorDevice?.Dispose();
_monitorDevice = null;
}
/// <summary>
/// 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 float[] _other = [];
public WaveFormat WaveFormat => Format;
public int Read(Span<float> buffer)
{
if (_other.Length < buffer.Length)
_other = new float[buffer.Length];
var other = _other.AsSpan(0, buffer.Length);
Span<float> broadcast;
if (monitorBuffer is null)
{
output.Mixer.Mix(other, buffer);
broadcast = other;
}
else
{
output.Mixer.Mix(buffer, other);
monitorBuffer.AddSamples(MemoryMarshal.AsBytes(other));
broadcast = buffer;
}
output._liveFeed?.AddSamples(MemoryMarshal.AsBytes(broadcast));
return buffer.Length; // never ends: silence while nothing is on air
}
}
}
+8 -2
View File
@@ -9,12 +9,18 @@ namespace Radiosender.Services;
internal static partial class ProviderParsing
{
/// <summary>Fetches <paramref name="url"/> and parses it as JSON, whatever content type the server names.</summary>
/// <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)
public static async Task<JsonDocument> GetJsonAsync(HttpClient http, string url, string provider, CancellationToken cancellationToken, string? bearerToken = null)
{
try
{
using var response = await http.GetAsync(url, cancellationToken);
using var request = new HttpRequestMessage(HttpMethod.Get, url);
if (bearerToken is not null)
request.Headers.Authorization = new("Bearer", bearerToken);
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)
throw new MusicProviderException($"{provider} hat die Anmeldung abgelehnt. Den Token in den Einstellungen prüfen.");
if (!response.IsSuccessStatusCode)
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.
+21 -3
View File
@@ -2,28 +2,46 @@ namespace Radiosender.Services;
/// <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.
/// writes the file and hands the minutes per hour to the schedule generator and the devices to the audio output.
/// </summary>
public class SettingsStore
{
private readonly ScheduleGenerator _generator;
private readonly ProgramOutput _output;
private readonly string _path;
public SettingsStore(ScheduleGenerator generator, string path)
public SettingsStore(ScheduleGenerator generator, ProgramOutput output, string path)
{
_generator = generator;
_output = output;
_path = path;
Current = AppSettings.Load(path);
_generator.Options = Current.ToScheduleOptions();
// Nothing is open yet at startup, so this cannot fail here.
_output.UseDevices(Current.BroadcastDevice, Current.MonitorDevice);
}
public AppSettings Current { get; private set; }
/// <summary>Stores the settings and applies them: alerts at once, minutes per hour from the next plan on.</summary>
/// <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">The settings file cannot be written.</exception>
/// <exception cref="UnauthorizedAccessException">The settings file cannot be written.</exception>
/// <exception cref="NAudio.MmException">A chosen audio device cannot be opened; nothing was saved.</exception>
public void Save(AppSettings settings)
{
// Devices first: if one cannot be opened, the old settings stay in the file.
if (settings.BroadcastDevice != Current.BroadcastDevice || settings.MonitorDevice != Current.MonitorDevice)
{
try
{
_output.UseDevices(settings.BroadcastDevice, settings.MonitorDevice);
}
catch (NAudio.MmException)
{
_output.UseDevices(Current.BroadcastDevice, Current.MonitorDevice);
throw;
}
}
settings.Save(_path);
Current = settings;
_generator.Options = settings.ToScheduleOptions();
+30
View File
@@ -0,0 +1,30 @@
using Radiosender.Models;
namespace Radiosender.Services;
/// <summary>
/// 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 const string AdBreak = "START_AD_BREAK";
public static readonly TimeSpan MinAdBreakSpacing = TimeSpan.FromMinutes(15);
private DateTime? _lastAdBreak;
public string For(ScheduleItem item)
{
if (item.Kind == ScheduleItemKind.Ad)
{
var time = now();
if (_lastAdBreak is not { } last || time - last >= MinAdBreakSpacing)
{
_lastAdBreak = time;
return AdBreak;
}
return item.Title;
}
return item.Song is { } song ? $"{song.Artist} - {song.Title}" : item.Title;
}
}
+140 -46
View File
@@ -86,6 +86,16 @@
Icon="{ui:SymbolIcon Play24}"
ToolTip="Plant ab diesem Moment und geht sofort auf Sendung. Die Startzeit wird ignoriert."
Click="OnStartNow" />
<!-- Only while laut.fm is on: sends the program live to the station, independent of the plan. -->
<ui:Button x:Name="LiveButton"
MinWidth="100"
Margin="8,8,0,0"
VerticalAlignment="Center"
Content="Live"
Icon="{ui:SymbolIcon Live24}"
ToolTip="Sendet alles, was auf Sendung ist, live auf deine laut.fm-Station."
Visibility="Collapsed"
Click="OnLiveToggle" />
</WrapPanel>
<ui:InfoBar x:Name="Message"
@@ -94,47 +104,47 @@
IsClosable="True"
IsOpen="False" />
<!-- Now playing -->
<!-- Now playing: what is on air and its buttons on top, the mixing desk below -->
<Border Grid.Row="3"
Margin="0,16,0,16"
Padding="16"
Padding="20,16,20,12"
CornerRadius="8"
BorderThickness="1"
BorderBrush="{DynamicResource CardStrokeColorDefaultBrush}"
Background="{DynamicResource CardBackgroundFillColorDefaultBrush}">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<StackPanel>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<StackPanel Grid.Column="0">
<ui:TextBlock FontTypography="Caption"
Foreground="{DynamicResource TextFillColorSecondaryBrush}"
Text="Läuft gerade" />
<StackPanel Margin="0,4,0,0" Orientation="Horizontal">
<ContentPresenter x:Name="NowKind"
VerticalAlignment="Center"
ContentTemplate="{StaticResource KindChip}"
Visibility="Collapsed" />
<ui:TextBlock x:Name="NowTitle"
Margin="8,0,0,0"
FontTypography="Subtitle"
TextTrimming="CharacterEllipsis"
Text="Nichts auf Sendung" />
<StackPanel VerticalAlignment="Center">
<ui:TextBlock FontTypography="Caption"
Foreground="{DynamicResource TextFillColorSecondaryBrush}"
Text="Läuft gerade" />
<DockPanel Margin="0,4,0,0">
<ContentPresenter x:Name="NowKind"
Margin="0,0,8,0"
VerticalAlignment="Center"
ContentTemplate="{StaticResource KindChip}"
Visibility="Collapsed" />
<ui:TextBlock x:Name="NowTitle"
FontTypography="Subtitle"
TextTrimming="CharacterEllipsis"
Text="Nichts auf Sendung" />
</DockPanel>
</StackPanel>
<ProgressBar x:Name="NowProgress"
Margin="0,12,0,0"
AutomationProperties.Name="Fortschritt des aktuellen Elements"
Maximum="1" />
<ui:TextBlock x:Name="NowTime"
Margin="0,6,0,0"
Foreground="{DynamicResource TextFillColorSecondaryBrush}"
Text=" " />
</StackPanel>
<StackPanel Grid.Column="1" Margin="24,0,0,0" VerticalAlignment="Center">
<StackPanel HorizontalAlignment="Right" Orientation="Horizontal">
<StackPanel Grid.Column="1" Margin="24,0,0,0" VerticalAlignment="Center" Orientation="Horizontal">
<!-- Live microphone on the program channel; label and icon say whether it is on. -->
<ui:Button x:Name="MicButton"
MinWidth="120"
Margin="0,0,20,0"
Content="Mikro ein"
Icon="{ui:SymbolIcon Mic24}"
ToolTip="Schaltet das Mikrofon auf Sendung, auch über laufende Musik."
Click="OnMicToggle" />
<ui:Button x:Name="EndNowButton"
Content="Jetzt beenden"
Icon="{ui:SymbolIcon Next24}"
@@ -150,21 +160,105 @@
IsEnabled="False"
Click="OnPlayToggle" />
</StackPanel>
<StackPanel Margin="0,12,0,0" Orientation="Horizontal">
<ui:SymbolIcon VerticalAlignment="Center" Symbol="Speaker224" />
<Slider x:Name="VolumeSlider"
Width="140"
Margin="8,0,0,0"
VerticalAlignment="Center"
AutomationProperties.Name="Lautstärke"
Minimum="0"
Maximum="1"
SmallChange="0.05"
LargeChange="0.1"
ValueChanged="OnVolumeChanged" />
</Grid>
<ProgressBar x:Name="NowProgress"
Margin="0,14,0,0"
AutomationProperties.Name="Fortschritt des aktuellen Elements"
Maximum="1" />
<ui:TextBlock x:Name="NowTime"
Margin="0,6,0,0"
Foreground="{DynamicResource TextFillColorSecondaryBrush}"
Text=" " />
<Border Height="1" Margin="0,4,0,14" Background="{DynamicResource CardStrokeColorDefaultBrush}" />
<!-- Mixing desk: three groups of the same width, each a heading with its levels.
The groups wrap below each other on a narrow window. -->
<WrapPanel x:Name="MixPanel" Grid.IsSharedSizeScope="True">
<WrapPanel.Resources>
<Style TargetType="Slider" BasedOn="{StaticResource {x:Type Slider}}">
<Setter Property="Margin" Value="12,0,0,0" />
<Setter Property="VerticalAlignment" Value="Center" />
<Setter Property="Minimum" Value="0" />
<Setter Property="Maximum" Value="1" />
<Setter Property="SmallChange" Value="0.05" />
<Setter Property="LargeChange" Value="0.1" />
</Style>
<Style x:Key="Group" TargetType="StackPanel">
<Setter Property="Width" Value="208" />
<Setter Property="Margin" Value="0,0,28,8" />
</Style>
<Style x:Key="Heading" TargetType="ui:TextBlock">
<Setter Property="FontTypography" Value="Caption" />
<Setter Property="Foreground" Value="{DynamicResource TextFillColorSecondaryBrush}" />
<Setter Property="Margin" Value="0,0,0,4" />
</Style>
</WrapPanel.Resources>
<StackPanel Style="{StaticResource Group}">
<ui:TextBlock Style="{StaticResource Heading}" Text="Sendung (für andere)" />
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" SharedSizeGroup="MixLabel" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="32" />
<RowDefinition Height="32" />
</Grid.RowDefinitions>
<ui:TextBlock VerticalAlignment="Center" Text="Musik" />
<Slider x:Name="MusicForOthersSlider" Grid.Column="1"
AutomationProperties.Name="Musik für andere" ValueChanged="OnMixChanged" />
<ui:TextBlock Grid.Row="1" VerticalAlignment="Center" Text="Mikrofon" />
<Slider x:Name="MicrophoneForOthersSlider" Grid.Row="1" Grid.Column="1"
AutomationProperties.Name="Mikrofon für andere" ValueChanged="OnMixChanged" />
</Grid>
</StackPanel>
</StackPanel>
</Grid>
<StackPanel Style="{StaticResource Group}">
<ui:TextBlock Style="{StaticResource Heading}" Text="Für mich" />
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" SharedSizeGroup="MixLabel" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="32" />
<RowDefinition Height="32" />
</Grid.RowDefinitions>
<ui:TextBlock VerticalAlignment="Center" Text="Musik" />
<Slider x:Name="MusicForMeSlider" Grid.Column="1"
AutomationProperties.Name="Musik für mich" ValueChanged="OnMixChanged" />
<CheckBox x:Name="ListenToBroadcastBox"
Grid.Row="1" Grid.ColumnSpan="2"
MinWidth="0"
Padding="8,0,0,0"
VerticalAlignment="Center"
Content="Sendung 1:1 hören"
ToolTip="Du hörst genau das, was andere hören: gleiche Lautstärke von dir, Musik und allem anderen."
Checked="OnMixChanged"
Unchecked="OnMixChanged" />
</Grid>
</StackPanel>
<StackPanel Style="{StaticResource Group}" Margin="0,0,0,8">
<ui:TextBlock Style="{StaticResource Heading}" Text="Musik gesamt" />
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" SharedSizeGroup="MixLabel" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="32" />
</Grid.RowDefinitions>
<ui:TextBlock VerticalAlignment="Center" Text="Lautstärke" />
<Slider x:Name="VolumeSlider" Grid.Column="1"
AutomationProperties.Name="Lautstärke der Musik gesamt" ValueChanged="OnVolumeChanged" />
</Grid>
</StackPanel>
</WrapPanel>
</StackPanel>
</Border>
<!-- Song request (hot swap) on the left, actions for the selected timeline row on the right -->
@@ -29,9 +29,16 @@ public partial class SchedulePage : Page
// Optimistic state: what the user just asked for, shown before the engine has caught up.
private bool? _expectPlaying;
public SchedulePage(ScheduleController controller)
private readonly Microphone _microphone;
private readonly ProgramMixer _mixer;
private readonly LiveController _live;
public SchedulePage(ScheduleController controller, Microphone microphone, ProgramOutput output, LiveController live)
{
_controller = controller;
_live = live;
_microphone = microphone;
_mixer = output.Mixer;
InitializeComponent();
Timeline.ItemsSource = _rows;
// Also refreshes the buttons: Finished can arrive just before the engine reports it stopped.
@@ -48,10 +55,18 @@ public partial class SchedulePage : Page
_controller.ItemStarted += OnItemStarted;
_controller.ItemFailed += OnItemFailed;
_controller.Finished += OnFinished;
_live.Problem += OnLiveProblem;
_loading = true;
VolumeSlider.Value = _controller.Volume;
MusicForMeSlider.Value = _mixer.MusicForMe;
MusicForOthersSlider.Value = _mixer.MusicForOthers;
MicrophoneForOthersSlider.Value = _mixer.MicrophoneForOthers;
ListenToBroadcastBox.IsChecked = _mixer.ListenToBroadcast;
MusicForMeSlider.IsEnabled = !_mixer.ListenToBroadcast;
_loading = false;
ShowMicrophone(); // it stays on while the user visits other pages
ShowLive();
FillStartTimes();
if (_controller.Plan.Count > 0)
UnlimitedBox.IsChecked = _controller.IsUnlimited;
@@ -71,6 +86,7 @@ public partial class SchedulePage : Page
_controller.ItemStarted -= OnItemStarted;
_controller.ItemFailed -= OnItemFailed;
_controller.Finished -= OnFinished;
_live.Problem -= OnLiveProblem;
_progressTimer.Stop();
}
@@ -162,6 +178,90 @@ public partial class SchedulePage : Page
Timeline.SelectedIndex = row.Index + offset;
});
private void OnMixChanged(object sender, RoutedEventArgs e)
{
if (_loading) return;
_mixer.MusicForMe = (float)MusicForMeSlider.Value;
_mixer.MusicForOthers = (float)MusicForOthersSlider.Value;
_mixer.MicrophoneForOthers = (float)MicrophoneForOthersSlider.Value;
_mixer.ListenToBroadcast = ListenToBroadcastBox.IsChecked == true;
// While the monitor copies the broadcast, its own music level has no effect.
MusicForMeSlider.IsEnabled = !_mixer.ListenToBroadcast;
}
private async void OnMicToggle(object sender, RoutedEventArgs e)
{
var turnOn = !_microphone.IsOn;
MicButton.IsEnabled = false;
try
{
// Opening the devices can take a moment, so it runs off the UI thread.
await Task.Run(() =>
{
if (turnOn) _microphone.TurnOn();
else _microphone.TurnOff();
});
Message.IsOpen = false;
}
catch (InvalidOperationException ex)
{
ShowMessage(InfoBarSeverity.Error, "Mikrofon nicht verfügbar", ex.Message);
}
MicButton.IsEnabled = true;
ShowMicrophone();
}
private void ShowMicrophone()
{
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.Icon = new SymbolIcon(on ? SymbolRegular.MicOff24 : SymbolRegular.Mic24);
MicButton.Appearance = on ? ControlAppearance.Danger : ControlAppearance.Secondary;
System.Windows.Automation.AutomationProperties.SetName(MicButton, on ? "Mikrofon ausschalten, es ist auf Sendung" : "Mikrofon einschalten");
}
private async void OnLiveToggle(object sender, RoutedEventArgs e)
{
LiveButton.IsEnabled = false;
try
{
if (_live.IsLive)
{
await Task.Run(_live.Stop);
}
else
{
// Opening the devices and the connection can take a moment, so it runs off the UI thread.
await Task.Run(() => _live.StartAsync());
Message.IsOpen = false;
}
}
catch (Exception ex) when (ex is LiveStreamException or NAudio.MmException)
{
ShowMessage(InfoBarSeverity.Error, "Live nicht möglich", ex.Message);
}
LiveButton.IsEnabled = true;
ShowLive();
}
// Comes from a background thread; the stream may have ended.
private void OnLiveProblem(object? sender, string message) => Dispatcher.BeginInvoke(() =>
{
ShowMessage(InfoBarSeverity.Warning, "laut.fm", message);
ShowLive();
});
private void ShowLive()
{
var live = _live.IsLive;
// Stays visible while live, so a stream can be stopped after laut.fm was switched off.
LiveButton.Visibility = _live.IsEnabled || live ? Visibility.Visible : Visibility.Collapsed;
LiveButton.Content = live ? "Live beenden" : "Live";
LiveButton.Appearance = live ? ControlAppearance.Danger : ControlAppearance.Secondary;
System.Windows.Automation.AutomationProperties.SetName(LiveButton, live ? "Livestream zu laut.fm beenden, er läuft" : "Livestream zu laut.fm starten");
}
private void OnEndNow(object sender, RoutedEventArgs e)
{
try
@@ -90,6 +90,34 @@
</Grid>
</Border>
<!-- Audio devices -->
<Border Style="{StaticResource Card}">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="220" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<ui:TextBlock Grid.ColumnSpan="2" FontTypography="BodyStrong" Text="Audio-Ausgabe" />
<Label Grid.Row="1" Margin="0,12,0,0" VerticalAlignment="Center"
Content="Sendung (für andere)" Target="{Binding ElementName=BroadcastDeviceBox}" />
<ComboBox x:Name="BroadcastDeviceBox" Grid.Row="1" Grid.Column="1" Margin="0,12,0,0"
AutomationProperties.Name="Ausgabegerät für die Sendung" />
<Label Grid.Row="2" Margin="0,8,0,0" VerticalAlignment="Center"
Content="Für mich (Kopfhörer)" Target="{Binding ElementName=MonitorDeviceBox}" />
<ComboBox x:Name="MonitorDeviceBox" Grid.Row="2" Grid.Column="1" Margin="0,8,0,0"
AutomationProperties.Name="Ausgabegerät für mich" />
<ui:TextBlock Grid.Row="3" Grid.ColumnSpan="2" Margin="0,12,0,0" TextWrapping="Wrap"
Foreground="{DynamicResource TextFillColorSecondaryBrush}"
Text="Getrennte Lautstärken für dich und für andere brauchen zwei verschiedene Geräte. Mit nur einem Gerät hörst du deinen eigenen Mix." />
</Grid>
</Border>
<!-- Minutes per hour -->
<Border Style="{StaticResource Card}">
<Grid>
@@ -126,6 +154,74 @@
</Grid>
</Border>
<!-- laut.fm: live streaming and the station's library -->
<Border Style="{StaticResource Card}">
<StackPanel>
<ui:ToggleSwitch x:Name="LautFmSwitch" Content="laut.fm"
Checked="OnLautFmChanged" Unchecked="OnLautFmChanged" />
<ui:TextBlock Margin="0,8,0,0" TextWrapping="Wrap"
Foreground="{DynamicResource TextFillColorSecondaryBrush}"
Text="Sendet live auf deine laut.fm-Station und bietet ihre Musik beim Import an. Im Plan erscheint dann der Button „Live“." />
<Grid x:Name="LautFmFields" Margin="0,4,0,0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="220" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<ui:TextBlock Margin="0,12,0,0" Grid.ColumnSpan="2" FontTypography="BodyStrong" Text="Live senden" />
<Label Grid.Row="1" Margin="0,8,0,0" VerticalAlignment="Center"
Content="Server" Target="{Binding ElementName=LautFmHostBox}" />
<ui:TextBox x:Name="LautFmHostBox" Grid.Row="1" Grid.Column="1" Margin="0,8,0,0"
AutomationProperties.Name="laut.fm-Server" />
<Label Grid.Row="2" Margin="0,8,0,0" VerticalAlignment="Center"
Content="Port" Target="{Binding ElementName=LautFmPortBox}" />
<ui:NumberBox x:Name="LautFmPortBox" Grid.Row="2" Grid.Column="1" Margin="0,8,0,0"
Width="130" HorizontalAlignment="Left" Minimum="1" Maximum="65535"
MaxDecimalPlaces="0" SmallChange="1" ClearButtonEnabled="False"
AutomationProperties.Name="laut.fm-Port" />
<Label Grid.Row="3" Margin="0,8,0,0" VerticalAlignment="Center"
Content="Mountpoint" Target="{Binding ElementName=LautFmMountBox}" />
<ui:TextBox x:Name="LautFmMountBox" Grid.Row="3" Grid.Column="1" Margin="0,8,0,0"
AutomationProperties.Name="laut.fm-Mountpoint" />
<Label Grid.Row="4" Margin="0,8,0,0" VerticalAlignment="Center"
Content="Benutzer" Target="{Binding ElementName=LautFmUserBox}" />
<ui:TextBox x:Name="LautFmUserBox" Grid.Row="4" Grid.Column="1" Margin="0,8,0,0"
AutomationProperties.Name="laut.fm-Benutzer" />
<Label Grid.Row="5" Margin="0,8,0,0" VerticalAlignment="Center"
Content="Passwort" Target="{Binding ElementName=LautFmPasswordBox}" />
<ui:PasswordBox x:Name="LautFmPasswordBox" Grid.Row="5" Grid.Column="1" Margin="0,8,0,0"
AutomationProperties.Name="laut.fm-Passwort" />
<ui:TextBlock Grid.Row="6" Grid.ColumnSpan="2" Margin="0,8,0,0" TextWrapping="Wrap"
Foreground="{DynamicResource TextFillColorSecondaryBrush}"
Text="Diese Werte stehen in Radioadmin unter „Live senden“." />
<ui:TextBlock Grid.Row="7" Margin="0,16,0,0" Grid.ColumnSpan="2" FontTypography="BodyStrong" Text="Bibliothek" />
<Label Grid.Row="8" Margin="0,8,0,0" VerticalAlignment="Center"
Content="Stations-ID" Target="{Binding ElementName=LautFmStationBox}" />
<ui:TextBox x:Name="LautFmStationBox" Grid.Row="8" Grid.Column="1" Margin="0,8,0,0"
AutomationProperties.Name="laut.fm-Stations-ID" />
<Label Grid.Row="9" Margin="0,8,0,0" VerticalAlignment="Center"
Content="Radioadmin-Token" Target="{Binding ElementName=LautFmTokenBox}" />
<ui:PasswordBox x:Name="LautFmTokenBox" Grid.Row="9" Grid.Column="1" Margin="0,8,0,0"
AutomationProperties.Name="Radioadmin-Token"
ToolTip="Nach dem Login in Radioadmin in den Entwicklertools des Browsers: Lokaler Speicher, Schlüssel laut.fm.api.token." />
</Grid>
<ui:TextBlock x:Name="LautFmHint" Margin="0,12,0,0" TextWrapping="Wrap"
Foreground="{DynamicResource TextFillColorSecondaryBrush}"
Text="Passwort und Token werden verschlüsselt für deinen Windows-Benutzer gespeichert. Die Bibliothek nutzt eine nicht offizielle laut.fm-Schnittstelle und kann ohne Vorwarnung ausfallen." />
</StackPanel>
</Border>
<StackPanel Margin="0,4,0,0" Orientation="Horizontal">
<ui:Button Appearance="Primary" MinWidth="110" Content="Speichern" Icon="{ui:SymbolIcon Save24}" Click="OnSave" />
<ui:Button Margin="8,0,0,0" MinWidth="110" Content="Zurücksetzen" Icon="{ui:SymbolIcon ArrowReset24}"
@@ -20,8 +20,18 @@ public partial class SettingsPage : Page
// 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);
// First entry of each list: the choice that names no device.
private const string DefaultDevice = "Windows-Standardgerät";
private const string NoDevice = "Kein eigenes Gerät";
private void Show(AppSettings settings)
{
// Read again on every visit, so a headset plugged in meanwhile shows up.
var devices = ProgramOutput.DeviceNames().ToList();
BroadcastDeviceBox.ItemsSource = devices.Prepend(DefaultDevice).ToList();
MonitorDeviceBox.ItemsSource = devices.Prepend(NoDevice).ToList();
BroadcastDeviceBox.SelectedIndex = devices.IndexOf(settings.BroadcastDevice ?? "") + 1;
MonitorDeviceBox.SelectedIndex = devices.IndexOf(settings.MonitorDevice ?? "") + 1;
NewsAlertSwitch.IsChecked = settings.NewsAlert;
NewsSecondsBox.Value = settings.NewsAlertSeconds;
NewsSoundBox.IsChecked = settings.NewsAlertSound;
@@ -31,8 +41,21 @@ public partial class SettingsPage : Page
NewsMinutesBox.Value = settings.NewsMinutesPerHour;
ModeratorMinutesBox.Value = settings.ModeratorMinutesPerHour;
AdMinutesBox.Value = settings.AdMinutesPerHour;
LautFmSwitch.IsChecked = settings.LautFmEnabled;
LautFmHostBox.Text = settings.LautFmHost;
LautFmPortBox.Value = settings.LautFmPort;
LautFmMountBox.Text = settings.LautFmMount;
LautFmUserBox.Text = settings.LautFmUser;
LautFmPasswordBox.Password = settings.LautFmPassword;
LautFmStationBox.Text = settings.LautFmStationId;
LautFmTokenBox.Password = settings.LautFmToken;
OnLautFmChanged(this, new RoutedEventArgs());
}
// The access fields only matter while laut.fm is on.
private void OnLautFmChanged(object sender, RoutedEventArgs e) =>
LautFmFields.Visibility = LautFmSwitch.IsChecked == true ? Visibility.Visible : Visibility.Collapsed;
// An emptied number box counts as its default.
private static AppSettings Defaults { get; } = new();
@@ -47,6 +70,16 @@ public partial class SettingsPage : Page
NewsMinutesPerHour = (int)(NewsMinutesBox.Value ?? Defaults.NewsMinutesPerHour),
ModeratorMinutesPerHour = (int)(ModeratorMinutesBox.Value ?? Defaults.ModeratorMinutesPerHour),
AdMinutesPerHour = (int)(AdMinutesBox.Value ?? Defaults.AdMinutesPerHour),
BroadcastDevice = BroadcastDeviceBox.SelectedIndex > 0 ? (string)BroadcastDeviceBox.SelectedItem : null,
MonitorDevice = MonitorDeviceBox.SelectedIndex > 0 ? (string)MonitorDeviceBox.SelectedItem : null,
LautFmEnabled = LautFmSwitch.IsChecked == true,
LautFmHost = LautFmHostBox.Text.Trim(),
LautFmPort = (int)(LautFmPortBox.Value ?? Defaults.LautFmPort),
LautFmMount = LautFmMountBox.Text.Trim(),
LautFmUser = LautFmUserBox.Text.Trim(),
LautFmPassword = LautFmPasswordBox.Password,
LautFmStationId = LautFmStationBox.Text.Trim(),
LautFmToken = LautFmTokenBox.Password.Trim(),
};
private void OnSave(object sender, RoutedEventArgs e)
@@ -63,6 +96,10 @@ public partial class SettingsPage : Page
_store.Save(settings);
ShowMessage(InfoBarSeverity.Success, "Gespeichert", "Minuten pro Stunde gelten für den nächsten Plan.");
}
catch (NAudio.MmException)
{
ShowMessage(InfoBarSeverity.Error, "Nicht gespeichert", "Ein gewähltes Audiogerät konnte nicht geöffnet werden. Die bisherigen Geräte bleiben aktiv.");
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
ShowMessage(InfoBarSeverity.Error, "Nicht gespeichert", ex.Message);
+256
View File
@@ -0,0 +1,256 @@
using System.Net;
using System.Net.Sockets;
using System.Text;
using NAudio.Wave;
using NAudio.Wave.SampleProviders;
using Radiosender.Controllers;
using Radiosender.Models;
using Radiosender.Services;
namespace Radiosender.Tests;
public sealed class LautFmTests : IDisposable
{
private readonly string _directory = Path.Combine(Path.GetTempPath(), "radiosender-tests", Guid.NewGuid().ToString("N"));
private static readonly AppSettings Live = new()
{
LautFmEnabled = true,
LautFmHost = "live.example.test",
LautFmPort = 8080,
LautFmMount = "/station",
LautFmUser = "source",
LautFmPassword = "geheim-passwort",
LautFmStationId = "123",
LautFmToken = "geheimer-token",
};
public void Dispose()
{
Microsoft.Data.Sqlite.SqliteConnection.ClearAllPools();
if (Directory.Exists(_directory))
Directory.Delete(_directory, recursive: true);
}
[Fact]
public void Settings_CheckTheLiveDataOnlyWhenSwitchedOn()
{
Assert.Null(Live.Validate());
Assert.Null(new AppSettings { LautFmEnabled = false, LautFmHost = "" }.Validate());
Assert.Contains("Server", (Live with { LautFmHost = "" }).Validate());
Assert.Contains("Port", (Live with { LautFmPort = 0 }).Validate());
Assert.Contains("Mountpoint", (Live with { LautFmMount = " " }).Validate());
Assert.Contains("Stations-ID", (Live with { LautFmStationId = "" }).Validate());
Assert.Null((Live with { LautFmStationId = "", LautFmToken = "" }).Validate()); // live only, no library
}
[Fact]
public void Settings_StoreSecretsEncrypted()
{
var file = Path.Combine(_directory, "settings.json");
Live.Save(file);
var text = System.IO.File.ReadAllText(file);
var loaded = AppSettings.Load(file);
Assert.DoesNotContain(Live.LautFmPassword, text);
Assert.DoesNotContain(Live.LautFmToken, text);
Assert.Contains("\"LautFmPassword\"", text);
Assert.Equal(Live, loaded);
Assert.Equal("geheim-passwort", loaded.LautFmPassword);
Assert.DoesNotContain("geheim", Live.ToString());
}
[Fact]
public void Settings_SecretsThatCannotBeDecryptedAreEmpty()
{
var file = Path.Combine(_directory, "settings.json");
Directory.CreateDirectory(_directory);
System.IO.File.WriteAllText(file, """{"LautFmPassword":"bm90IGVuY3J5cHRlZA==","LautFmToken":"%%%"}""");
var loaded = AppSettings.Load(file);
Assert.Equal("", loaded.LautFmPassword);
Assert.Equal("", loaded.LautFmToken);
}
[Fact]
public void StreamTitles_SendTheAdTriggerAtMostEvery15Minutes()
{
var now = new DateTime(2026, 11, 25, 12, 0, 0);
var titles = new StreamTitles(() => now);
var ad = new ScheduleItem(ScheduleItemKind.Ad, "Werbung", now, TimeSpan.FromMinutes(2));
Assert.Equal(StreamTitles.AdBreak, titles.For(ad));
now = now.AddMinutes(2);
Assert.Equal("Werbung", titles.For(ad)); // second ad of the same break
now = now.AddMinutes(12);
Assert.Equal("Werbung", titles.For(ad)); // 14 minutes after the trigger
now = now.AddMinutes(1);
Assert.Equal(StreamTitles.AdBreak, titles.For(ad));
var song = new Song { Title = "Lied", Artist = "Band", Duration = TimeSpan.FromMinutes(3), FilePath = "x.mp3" };
Assert.Equal("Band - Lied", titles.For(new ScheduleItem(ScheduleItemKind.Song, "Lied", now, song.Duration, song)));
Assert.Equal("Nachrichten", titles.For(new ScheduleItem(ScheduleItemKind.News, "Nachrichten", now, TimeSpan.FromMinutes(5))));
}
[Fact]
public async Task Icecast_LogsInWithPutAndSendsMp3()
{
using var listener = new TcpListener(IPAddress.Loopback, 0);
listener.Start();
var port = ((IPEndPoint)listener.LocalEndpoint).Port;
var server = Task.Run(async () =>
{
using var client = await listener.AcceptTcpClientAsync();
var network = client.GetStream();
var header = await ReadHeaderAsync(network);
await network.WriteAsync("HTTP/1.1 100 Continue\r\n\r\n"u8.ToArray());
var audio = new MemoryStream();
var buffer = new byte[4096];
while (audio.Length < 4000)
{
var read = await network.ReadAsync(buffer);
if (read == 0)
break;
audio.Write(buffer, 0, read);
}
return (header, audio.ToArray());
});
using var stream = await IcecastStream.ConnectAsync(new IcecastTarget("127.0.0.1", port, "live", "source", "pw"), Feed());
var (header, audio) = await server.WaitAsync(TimeSpan.FromSeconds(20));
Assert.StartsWith("PUT /live HTTP/1.1\r\n", header);
Assert.Contains($"Authorization: Basic {Convert.ToBase64String("source:pw"u8.ToArray())}\r\n", header);
Assert.Contains("Content-Type: audio/mpeg\r\n", header);
Assert.True(audio.Length >= 4000, $"only {audio.Length} bytes of audio arrived");
}
[Fact]
public async Task Icecast_RefusedLoginIsAReadableError()
{
using var listener = new TcpListener(IPAddress.Loopback, 0);
listener.Start();
var port = ((IPEndPoint)listener.LocalEndpoint).Port;
var server = Task.Run(async () =>
{
using var client = await listener.AcceptTcpClientAsync();
var network = client.GetStream();
await ReadHeaderAsync(network);
await network.WriteAsync("HTTP/1.1 401 Authentication Required\r\n\r\n"u8.ToArray());
});
var error = await Assert.ThrowsAsync<LiveStreamException>(() =>
IcecastStream.ConnectAsync(new IcecastTarget("127.0.0.1", port, "/live", "source", "falsch"), Feed()));
await server;
Assert.Contains("Passwort", error.Message);
}
[Fact]
public async Task Icecast_RejectsLineBreaksInTheRequest()
{
await Assert.ThrowsAsync<LiveStreamException>(() =>
IcecastStream.ConnectAsync(new IcecastTarget("127.0.0.1", 1, "live\r\nX: y", "source", "pw"), Feed()));
}
[Fact]
public async Task Icecast_TitleGoesToTheAdminInterface()
{
HttpRequestMessage? sent = null;
var http = new HttpClient(new FakeHandler(request =>
{
sent = request;
return new HttpResponseMessage(HttpStatusCode.OK);
}));
await IcecastStream.UpdateTitleAsync(http, new IcecastTarget("live.example.test", 8080, "station", "source", "pw"), StreamTitles.AdBreak);
Assert.Equal("http://live.example.test:8080/admin/metadata?mount=%2Fstation&mode=updinfo&song=START_AD_BREAK", sent!.RequestUri!.AbsoluteUri);
Assert.Equal("Basic", sent.Headers.Authorization!.Scheme);
}
[Fact]
public async Task Provider_SearchesTitleAndArtistWithTheToken()
{
var requests = new List<HttpRequestMessage>();
var provider = new LautFmProvider(new HttpClient(new FakeHandler(request =>
{
lock (requests)
requests.Add(request);
return Json("""
{"tracks":[
{"id":7,"title":"Sommer","artist":"Band","duration":184,"_links":{"prelisten_authless":{"href":"/tracks/7/prelisten"}}},
{"id":8,"title":"Ohne Link","artist":"Band","duration":100,"_links":{}},
{"id":9,"title":"Unsicher","artist":"Band","duration":100,"_links":{"prelisten_authless":{"href":"http://example.test/9.mp3"}}}
],"_links":{}}
""");
})), () => Live);
var tracks = await provider.SearchAsync("Sommer");
var track = Assert.Single(tracks); // the same track from both searches, once; links that are missing or not https are skipped
Assert.Equal("lautfm:7", track.Id);
Assert.Equal("Sommer", track.Title);
Assert.Equal("Band", track.Creator);
Assert.Equal(TimeSpan.FromSeconds(184), track.Duration);
Assert.Equal("https://api.radioadmin.laut.fm/tracks/7/prelisten", track.Url);
Assert.Equal(2, requests.Count);
Assert.All(requests, r => Assert.Equal("Bearer geheimer-token", r.Headers.Authorization!.ToString()));
Assert.Contains(requests, r => r.RequestUri!.AbsoluteUri == "https://api.radioadmin.laut.fm/stations/123/tracks?title=Sommer");
Assert.Contains(requests, r => r.RequestUri!.AbsoluteUri == "https://api.radioadmin.laut.fm/stations/123/tracks?artist=Sommer");
}
[Fact]
public async Task Provider_ExplainsMissingOrRefusedLogin()
{
var refused = new LautFmProvider(new HttpClient(new FakeHandler(_ => new HttpResponseMessage(HttpStatusCode.Unauthorized))), () => Live);
var missing = new LautFmProvider(new HttpClient(new FakeHandler(_ => Json("{}"))), () => Live with { LautFmToken = "" });
Assert.Contains("Token", (await Assert.ThrowsAsync<MusicProviderException>(() => refused.SearchAsync("x"))).Message);
Assert.Contains("Token", (await Assert.ThrowsAsync<MusicProviderException>(() => missing.SearchAsync("x"))).Message);
}
[Fact]
public void ImportPage_ListsLautFmOnlyWhileSwitchedOn()
{
var settings = Live with { LautFmEnabled = false };
var lautFm = new LautFmProvider(new HttpClient(new FakeHandler(_ => Json("{}"))), () => settings);
var http = new HttpClient(new FakeHandler(_ => Json("{}")));
var controller = new OnlineImportController(
[new OpenverseProvider(http), lautFm], new TrackDownloader(http, _directory), new SongRepository(Path.Combine(_directory, "test.db")));
Assert.Equal(["Openverse"], controller.Providers.Select(p => p.Name));
settings = Live;
Assert.Equal(["Openverse", "laut.fm"], controller.Providers.Select(p => p.Name));
}
// Three seconds of a tone, then nothing new: like the live feed of a quiet program.
private static BufferedWaveProvider Feed()
{
var feed = new BufferedWaveProvider(ProgramOutput.Format, TimeSpan.FromSeconds(10)) { ReadFully = false };
var tone = new SignalGenerator(44100, 2) { Frequency = 440, Gain = 0.2 };
var samples = new float[44100 * 2 * 3];
tone.Read(samples);
feed.AddSamples(System.Runtime.InteropServices.MemoryMarshal.AsBytes(samples.AsSpan()));
return feed;
}
private static async Task<string> ReadHeaderAsync(NetworkStream network)
{
var header = new StringBuilder();
var buffer = new byte[1];
while (!header.ToString().EndsWith("\r\n\r\n") && await network.ReadAsync(buffer) == 1)
header.Append((char)buffer[0]);
return header.ToString();
}
private static HttpResponseMessage Json(string json) => new(HttpStatusCode.OK) { Content = new StringContent(json) };
private sealed class FakeHandler(Func<HttpRequestMessage, HttpResponseMessage> respond) : HttpMessageHandler
{
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) =>
Task.FromResult(respond(request));
}
}
+58 -2
View File
@@ -26,9 +26,9 @@ public sealed class MusicPlayerTests : IDisposable
}
// Writes a short, quiet sine tone as 16-bit mono PCM.
private string CreateWav(TimeSpan length)
private string CreateWav(TimeSpan length, string name = "tone.wav")
{
var path = Path.Combine(_directory, "tone.wav");
var path = Path.Combine(_directory, name);
var format = new WaveFormat(44100, 16, 1);
using var writer = new WaveFileWriter(path, format);
var samples = (int)(format.SampleRate * length.TotalSeconds);
@@ -37,6 +37,62 @@ public sealed class MusicPlayerTests : IDisposable
return path;
}
[Fact]
public void ProgramOutput_ConvertsInputsToItsFormat()
{
var mono = new NAudio.Wave.SampleProviders.SignalGenerator(22050, 1);
var converted = ProgramOutput.ToProgramFormat(mono);
Assert.Equal(44100, converted.WaveFormat.SampleRate);
Assert.Equal(2, converted.WaveFormat.Channels);
Assert.Same(ProgramOutput.Instance, ProgramOutput.Instance);
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]
public void Play_TwoTracksInARow_RaisesTrackFinishedOnlyForTheSecond()
{
var player = MusicPlayer.Instance;
var finished = 0;
using var done = new ManualResetEventSlim();
EventHandler handler = (_, _) => { Interlocked.Increment(ref finished); done.Set(); };
player.TrackFinished += handler;
try
{
player.Play(CreateWav(TimeSpan.FromSeconds(2)));
Thread.Sleep(200);
player.Play(CreateWav(TimeSpan.FromSeconds(0.5), "second.wav"));
Assert.True(done.Wait(TimeSpan.FromSeconds(5)));
Thread.Sleep(300);
Assert.Equal(1, finished);
}
finally
{
player.TrackFinished -= handler;
}
}
[Fact]
public void Instance_ReturnsSameObjectOnRepeatedAccess()
{
@@ -0,0 +1,117 @@
using NAudio.Wave;
using Radiosender.Services;
namespace Radiosender.Tests;
public class ProgramMixerTests
{
/// <summary>Delivers the same sample value for a given number of samples, then ends.</summary>
private sealed class Constant(float value, int samples = int.MaxValue) : ISampleProvider
{
private int _left = samples;
public WaveFormat WaveFormat => ProgramOutput.Format;
public int Read(Span<float> buffer)
{
var count = Math.Min(buffer.Length, _left);
buffer[..count].Fill(value);
_left -= count;
return count;
}
}
private static (float Broadcast, float Monitor) MixOnce(ProgramMixer mixer)
{
Span<float> broadcast = stackalloc float[8];
Span<float> monitor = stackalloc float[8];
mixer.Mix(broadcast, monitor);
return (broadcast[0], monitor[0]);
}
private static ProgramMixer WithMusicAndMicrophone()
{
var mixer = new ProgramMixer { ListenToBroadcast = false };
mixer.Add(new Constant(0.4f), AudioSource.Music);
mixer.Add(new Constant(0.2f), AudioSource.Microphone);
return mixer;
}
[Fact]
public void Mix_AppliesEachLevelToItsOwnMix()
{
var mixer = WithMusicAndMicrophone();
mixer.MusicForOthers = 0.5f;
mixer.MicrophoneForOthers = 1f;
mixer.MusicForMe = 0.25f;
var (broadcast, monitor) = MixOnce(mixer);
Assert.Equal(0.4f * 0.5f + 0.2f, broadcast, 5);
Assert.Equal(0.4f * 0.25f, monitor, 5); // the monitor never carries the microphone
}
[Fact]
public void Mix_ListeningToTheBroadcastCopiesItExactly()
{
var mixer = WithMusicAndMicrophone();
mixer.MusicForOthers = 0.5f;
mixer.MusicForMe = 0f;
mixer.ListenToBroadcast = true;
var (broadcast, monitor) = MixOnce(mixer);
Assert.Equal(0.4f, broadcast, 5);
Assert.Equal(broadcast, monitor);
}
[Fact]
public void Mix_LimitsTheSumToFullScale()
{
var mixer = new ProgramMixer();
mixer.Add(new Constant(0.8f), AudioSource.Music);
mixer.Add(new Constant(0.8f), AudioSource.Microphone);
Assert.Equal(1f, MixOnce(mixer).Broadcast);
}
[Fact]
public void Mix_DropsAnInputThatEndedAndReportsIt()
{
var mixer = new ProgramMixer();
var track = new Constant(0.5f, samples: 4);
ISampleProvider? ended = null;
mixer.InputEnded += (_, input) => ended = input;
mixer.Add(track, AudioSource.Music);
Span<float> broadcast = stackalloc float[8];
Span<float> monitor = stackalloc float[8];
mixer.Mix(broadcast, monitor);
Assert.Same(track, ended);
Assert.Equal(0.5f, broadcast[3]);
Assert.Equal(0f, broadcast[4]); // silence after the end of the track
Assert.Equal(0f, MixOnce(mixer).Broadcast);
}
[Fact]
public void Remove_TakesTheInputOffBothMixes()
{
var mixer = new ProgramMixer();
var track = new Constant(0.5f);
mixer.Add(track, AudioSource.Music);
mixer.Remove(track);
Assert.Equal((0f, 0f), MixOnce(mixer));
}
[Fact]
public void Levels_OutOfRange_Throw()
{
var mixer = new ProgramMixer();
Assert.Throws<ArgumentOutOfRangeException>(() => mixer.MusicForMe = 1.1f);
Assert.Throws<ArgumentOutOfRangeException>(() => mixer.MicrophoneForOthers = -0.1f);
}
}