voelin-media: stream mixer for any number of audio sources

The stream's audio will come from several captures at once (desktop
audio without our own voices, single apps, the microphone), each
delivering at its own pace, rate and channel count. StreamMixer mixes
them on the streamer's clock into 48 kHz stereo:

- every source has a gain, a mute and any number of inputs; an input is
  a lock-free single-producer ring (rtrb) that the capture thread fills,
  mapping channels to stereo as it pushes
- each input is held at a small fixed latency (more for bursty or late
  inputs), starts once that much is buffered, fades out and waits when
  it runs dry, and never holds up the other sources
- rate conversion is per-input cubic interpolation; clock drift is
  absorbed by resampling up to 0.5 % while the buffer is off its
  settled level, otherwise 48 kHz input is copied bit-exact
- a soft limiter on the sum keeps the output within full scale
- peak/RMS meters per source and for the output are atomics that the
  UI reads without locks
- buffers are sized when sources and inputs are created; mixing
  allocates nothing per block (checked by a counting-allocator test)

Includes unit tests and a Criterion bench (benches/mix.rs).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NJvYyRmTjKcb9i8eyYXK5G
This commit is contained in:
Claude committed 2026-09-28 02:50:45 +00:00
1 parent 5efec8c568
commit 49d7e38ab8
5 files changed
+1824

No files matched your search

+6
View File
@@ -36,6 +36,8 @@ dav1d = { version = "0.11.1", optional = true }
libvpx-native-sys = { version = "5.0.17", optional = true }
openh264 = { version = "0.9.8", default-features = false, features = ["libloading"], optional = true }
reqwest = { version = "0.13.5", default-features = false, features = ["rustls"], optional = true }
# Lock-free single-producer rings from capture threads to the stream mixer.
rtrb = "0.4.0"
sha2 = { version = "0.10.9", optional = true }
str0m = { version = "0.23.1", default-features = false, optional = true }
thiserror = "2.0.21"
@@ -68,5 +70,9 @@ tokio = { version = "1", features = ["macros", "rt", "rt-multi-thread", "time"]
name = "convert"
harness = false
[[bench]]
name = "mix"
harness = false
[lints]
workspace = true
+83
View File
@@ -0,0 +1,83 @@
//! The stream mixer: `cargo bench -p voelin-media --bench mix`.
//!
//! One iteration pushes 20 ms into every source and mixes one 20 ms block
//! (960 frames), as the streamer does 50 times a second.
//!
//! - `mix/48k/<n>`: n stereo sources at 48 kHz (copied through)
//! - `mix/44k1/<n>`: n stereo sources at 44.1 kHz (cubic resampling)
//! - `mix/limited/8`: eight loud sources, the limiter working on every frame
use std::hint::black_box;
use std::time::Duration;
use criterion::{BenchmarkId, Criterion, Throughput, criterion_group, criterion_main};
use voelin_media::mix::{MixerConfig, SourceInput, StreamMixer};
const BLOCK: usize = 960;
/// A mixer with `sources` sources at `rate`, each fed a 20 ms stereo block
/// per iteration.
struct Setup {
mixer: StreamMixer,
inputs: Vec<SourceInput>,
/// 20 ms of input at the sources' rate.
block: Vec<f32>,
out: Vec<f32>,
}
impl Setup {
fn new(sources: usize, rate: u32, amplitude: f32) -> Self {
let mixer = StreamMixer::new(MixerConfig::default());
let handle = mixer.handle();
let inputs = (0..sources).map(|i| handle.add_source(format!("s{i}")).input(rate)).collect();
let frames = rate as usize / 50;
let block = (0..frames)
.flat_map(|i| {
let s = amplitude * (i as f32 * 0.05).sin();
[s, -s]
})
.collect();
let mut setup = Self { mixer, inputs, block, out: vec![0.0; BLOCK * 2] };
// Every source past its latency and settled.
for _ in 0..100 {
setup.step();
}
setup
}
fn step(&mut self) {
for input in &mut self.inputs {
input.push(&self.block, 2);
}
self.mixer.mix(&mut self.out);
}
}
fn mixing(c: &mut Criterion) {
let mut group = c.benchmark_group("mix");
group.sample_size(50).measurement_time(Duration::from_secs(3));
for (name, rate) in [("48k", 48_000), ("44k1", 44_100)] {
for sources in [1, 4, 16, 64] {
let mut setup = Setup::new(sources, rate, 0.5 / sources as f32);
group.throughput(Throughput::Elements((BLOCK * sources) as u64));
group.bench_function(BenchmarkId::new(name, sources), |b| {
b.iter(|| {
setup.step();
black_box(&setup.out);
});
});
}
}
let mut setup = Setup::new(8, 48_000, 0.6);
group.throughput(Throughput::Elements((BLOCK * 8) as u64));
group.bench_function(BenchmarkId::new("limited", 8), |b| {
b.iter(|| {
setup.step();
black_box(&setup.out);
});
});
group.finish();
}
criterion_group!(benches, mixing);
criterion_main!(benches);
+4
View File
@@ -13,6 +13,9 @@
//! test source, X11 (feature `x11`), the Wayland ScreenCast portal and
//! PipeWire system audio (feature `pipewire`), and Windows Graphics Capture
//! plus WASAPI loopback on Windows
//! - [`mix`]: the stream's audio mixer ([`mix::StreamMixer`]): any number
//! of sources at their own pace and rate into 48 kHz stereo, with gains,
//! mutes, a soft limiter and lock-free meters
//! - [`queue`]: the bounded, drop-oldest channel capture backends deliver on
//! - the streaming path: [`workers`] (a fork-join pool that allocates
//! nothing per job), [`pool`] (recycled I420 frames), [`handoff`]
@@ -29,6 +32,7 @@ pub mod codec;
pub mod convert;
pub mod frame;
pub mod handoff;
pub mod mix;
pub mod pool;
pub mod queue;
pub mod scale;
File diff suppressed because it is too large. Load diff
+122
View File
@@ -0,0 +1,122 @@
//! The stream mixer allocates nothing per block: pushing into inputs and
//! mixing, with resampling, downmixing, drift correction, gain and mute
//! changes, stalls and restarts, counted with a global allocator that
//! counts only on the thread that asks.
#![allow(unsafe_code)]
use std::alloc::{GlobalAlloc, Layout, System};
use std::cell::Cell;
use voelin_media::mix::{MixerConfig, StreamMixer};
thread_local! {
static COUNTING: Cell<bool> = const { Cell::new(false) };
static COUNT: Cell<u64> = const { Cell::new(0) };
}
fn count() {
// `try_with`: never panics, also while the thread is torn down; const
// thread locals without destructors never allocate.
let _ = COUNTING.try_with(|on| {
if on.get() {
let _ = COUNT.try_with(|n| n.set(n.get() + 1));
}
});
}
struct Counting;
// SAFETY: every method forwards to `System` with the caller's arguments
// unchanged, so `System`'s guarantees hold; counting touches only
// thread-local cells and never allocates.
unsafe impl GlobalAlloc for Counting {
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
count();
// SAFETY: forwarded unchanged (see above).
unsafe { System.alloc(layout) }
}
unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 {
count();
// SAFETY: forwarded unchanged.
unsafe { System.alloc_zeroed(layout) }
}
unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
count();
// SAFETY: forwarded unchanged.
unsafe { System.realloc(ptr, layout, new_size) }
}
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
// SAFETY: forwarded unchanged.
unsafe { System.dealloc(ptr, layout) }
}
}
#[global_allocator]
static ALLOCATOR: Counting = Counting;
/// Allocations `f` makes on this thread.
fn allocations(f: impl FnOnce()) -> u64 {
COUNT.with(|n| n.set(0));
COUNTING.with(|on| on.set(true));
f();
COUNTING.with(|on| on.set(false));
COUNT.with(Cell::get)
}
#[test]
fn mixing_allocates_nothing_per_block() {
const BLOCK: usize = 960;
// The counter works.
assert_eq!(allocations(|| drop(std::hint::black_box(vec![0u8; 16]))), 1);
let mut mixer = StreamMixer::new(MixerConfig::default());
let handle = mixer.handle();
// 48 kHz stereo, 44.1 kHz mono, 6 channels, and one that stalls.
let stereo = handle.add_source("stereo");
let mono = handle.add_source("mono");
let surround = handle.add_source("5.1");
let flaky = handle.add_source("flaky");
let mut inputs = [stereo.input(48_000), mono.input(44_100), surround.input(48_000)];
let mut flaky_input = flaky.input(48_000);
let stereo_block: Vec<f32> = (0..BLOCK * 2).map(|i| (i as f32 * 0.01).sin() * 0.3).collect();
let mono_block: Vec<f32> = (0..882).map(|i| (i as f32 * 0.02).sin() * 0.3).collect();
let six_block: Vec<f32> = (0..BLOCK * 6).map(|i| (i as f32 * 0.03).sin() * 0.3).collect();
let mut out = vec![0.0f32; BLOCK * 2];
// Slightly fast clock on one input so the drift correction runs.
let mut owed = 0.0f64;
let mut step = |block: usize, out: &mut Vec<f32>| {
inputs[0].push(&stereo_block, 2);
inputs[1].push(&mono_block, 1);
owed += BLOCK as f64 * 1.004;
let frames = owed as usize;
owed -= frames as f64;
inputs[2].push(&six_block[..frames.min(BLOCK) * 6], 6);
// On for a second, off for a second.
if (block / 50).is_multiple_of(2) {
flaky_input.push(&stereo_block, 2);
}
match block % 7 {
0 => stereo.set_gain(0.5 + (block % 3) as f32 * 0.25),
3 => mono.set_muted(block.is_multiple_of(2)),
5 => handle.set_gain(0.9),
_ => {}
}
mixer.mix(out);
let _ = (stereo.level(), handle.level(), surround.state(), handle.limiter_gain());
};
// Warm up: sources adopted, inputs playing, latencies settled.
for block in 0..300 {
step(block, &mut out);
}
let count = allocations(|| {
for block in 300..1300 {
step(block, &mut out);
}
});
assert_eq!(count, 0, "allocations in 1000 blocks");
// The flaky source went idle and came back in the measured part.
assert!(flaky.stats().underruns > 0);
assert!(out.iter().any(|s| *s != 0.0));
}