Files
audio/audio/mixing.sakura
T
2026-11-14 15:37:01 -06:00

401 lines
15 KiB
Plaintext

#! Contains a mixer's voices mixed into frames: each read from its sound at its
#! pitch, by cubic Hermite interpolation between the four frames about where it
#! plays, panned, and its gains ramped from the last frames mixed to these.
#!
#! A mono voice is panned by the constant power law, so at the middle each side
#! has it at -3 dB, as loud in all as it is from one side; a stereo voice's pan
#! turns down the side it moves from, its middle both sides whole.
import std::math;
module malunal::audio;
# How many frames a streamed voice decodes at a time.
const stream_chunk: u64 = 2048;
# Changes the rate the mixer mixes at, as an output's device says.
def mixer::set_rate(&mut this, rate: u32): void {
this.mix_rate = rate;
}
#! Mixes the voices into frames of two channels, replacing what they held, and
#! ends those that played to their end: each voice into its bus, filtered
#! where it says, and into the bus it's sent to; then each bus's effects, and
#! its gain, the master's, and the limiter, where it's on.
#! @param into The frames, a frame's left and right together.
pub def mixer::mix(&mut this, into: slice<f32>): void {
for i in 0..into.length {
into[i] = 0;
}
val frames := into.length / 2;
return if frames == 0;
val width := frames * 2;
if this.mixed.length != bus_count as u64 * width {
this.mixed.resize(bus_count as u64 * width);
}
if this.scratch.length != width {
this.scratch.resize(width);
}
var fed: bool[16];
for v in 0..this.voices.length {
continue if !this.voices[v].live || this.voices[v].how.paused;
val state := address(&mut this.voices[v]);
val held := address(&this.bank[this.voices[v].sound.index as u64]);
val voice := slice::<f32>::over(this.scratch.data, width);
for i in 0..width {
voice[i] = 0;
}
# A voice waiting is heard from where its wait ends; one unheard moves on.
val waits := math::min(through(state).waiting, frames);
through(state).waiting -= waits;
continue if waits == frames;
val heard := slice::<f32>::over(this.scratch.data + waits * 2, width - waits * 2);
val how := through(state).how;
if how.silent && !through(held).streamed {
if pass_silently(&mut through(state), &through(held), this.mix_rate, frames - waits) {
this.end_voice(v);
}
continue;
}
val ended := mix_voice(&mut through(state), &through(held), this.mix_rate, heard, frames - waits);
if how.silent {
through(state).gains = [0, 0];
if ended {
this.end_voice(v);
}
continue;
}
if how.low_pass > 0 || how.high_pass > 0 {
through(state).filtering.run(voice, how.low_pass, how.high_pass, this.mix_rate);
}
this.feed(&mut fed, how.bus, voice, 1);
if how.send > 0 && how.send_bus < bus_count && how.send_bus != how.bus {
this.feed(&mut fed, how.send_bus, voice, how.send);
}
if ended {
this.end_voice(v);
}
}
# Each bus: its effects, then its gain, ramped from what it was given last;
# or, of one silent before, given whole. Reverb goes on as long as its echoes
# do after what feeds it ends.
var any := false;
for b in 0..bus_count as u64 {
val state := &mut this.bus_states[b];
if !fed[b] && state.tail == 0 {
state.live = false;
continue;
}
val part := slice::<f32>::over(this.mixed.data + b * width, width);
if !fed[b] {
for i in 0..width {
part[i] = 0;
}
}
val effects := state.effects;
if effects.low_pass > 0 || effects.high_pass > 0 {
state.filtering.run(part, effects.low_pass, effects.high_pass, this.mix_rate);
}
if effects.reverb.wet > 0 {
if state.echoes is none {
state.echoes = box::new(reverb_state::of(this.mix_rate));
}
if state.echoes is some(&mut echoes) {
echoes.get().run(part, &effects.reverb);
}
state.tail = fed[b] ? reverb_tail(&effects.reverb, this.mix_rate) : (state.tail > frames ? state.tail - frames : 0u);
} else {
state.tail = 0;
}
val target := this.buses[b];
val from := state.live ? state.applied : target;
for i in 0..frames {
val gain := from + (target - from) * (i + 1) as f32 / frames as f32;
into[i * 2] += part[i * 2] * gain;
into[i * 2 + 1] += part[i * 2 + 1] * gain;
}
state.applied = target;
state.live = true;
any = true;
}
# The master's gain, as a bus's is, then the limiter.
val target := this.master_gain;
val from := this.master_live ? this.master_applied : target;
if from != 1 || target != 1 {
for i in 0..frames {
val gain := from + (target - from) * (i + 1) as f32 / frames as f32;
into[i * 2] *= gain;
into[i * 2 + 1] *= gain;
}
}
this.master_applied = target;
this.master_live = any;
if this.limits.on {
if this.limited is none {
this.limited = box::new(limiter_state::of((this.limits.lookahead * this.mix_rate as f32) as u64));
}
if this.limited is some(&mut held) {
held.get().run(into, &this.limits, this.mix_rate);
}
}
}
# Moves a voice of a decoded sound on, unheard, as it would play, its gains
# where they'd be.
# @returns Whether it ended.
def pass_silently(at: &mut voice_state, held: &held_sound, rate: u32, frames: u64): bool {
val step := held.rate as f64 / rate as f64 * math::max(at.how.pitch, 0 as f32) as f64;
at.level = math::clamp(at.level + at.fade * frames as f32, 0 as f32, 1 as f32);
# Heard again, it rises from nothing, as gains ramp.
at.gains = [0, 0];
at.started = true;
at.position += step * frames as f64;
if at.how.looping {
val loop_end := loop_end_of(held);
val loop_start := held.loop_points.start < loop_end ? held.loop_points.start : 0u;
if at.position >= loop_end as f64 {
val length := (loop_end - loop_start) as f64;
val past := at.position - loop_start as f64;
at.position = loop_start as f64 + past - math::floor(past / length) * length;
}
return at.stopping && at.level <= 0;
}
return at.position >= held.frames as f64 || (at.stopping && at.level <= 0);
}
# Adds a voice's frames, by an amount, into a bus's, or, the first this mix,
# sets them.
def mixer::feed(&mut this, fed: &mut bool[16], bus: u32, voice: slice<f32>, amount: f32): void {
val width := voice.length;
val part := slice::<f32>::over(this.mixed.data + bus as u64 * width, width);
if !fed[bus as u64] {
for i in 0..width {
part[i] = voice[i] * amount;
}
fed[bus as u64] = true;
return;
}
for i in 0..width {
part[i] += voice[i] * amount;
}
}
# Mixes one voice into frames, at its own gain.
# @returns Whether it ended.
def mix_voice(at: &mut voice_state, held: &held_sound, rate: u32, into: slice<f32>, frames: u64): bool {
val step := held.rate as f64 / rate as f64 * math::max(at.how.pitch, 0 as f32) as f64;
val gain := at.how.gain;
val pan := math::clamp(at.how.pan, -1 as f32, 1 as f32);
var target: f32[2];
if held.channels == 1 {
val angle := (pan + 1) * math::pi as f32 / 4;
target = [math::cos(angle) * gain, math::sin(angle) * gain];
} else {
target = [math::min(1 - pan, 1 as f32) * gain, math::min(1 + pan, 1 as f32) * gain];
}
val level := math::clamp(at.level + at.fade * frames as f32, 0 as f32, 1 as f32);
var start := at.gains;
if !at.started {
start = [target[0] * at.level, target[1] * at.level];
}
val end: f32[2] = [target[0] * level, target[1] * level];
val channels := held.channels as u64;
val looping := at.how.looping;
var position := at.position;
var finished := false;
# Where a looping decoded voice goes back from, and to.
val loop_end := loop_end_of(held);
val loop_start := held.loop_points.start < loop_end ? held.loop_points.start : 0u;
# The frames read from: the sound's, or those a stream decoded about where
# the voice plays, from `base` on, and where a stream ended, if it did.
var data: *mut f32 = null;
var base: i64 = 0;
var count: i64 = 0;
var ends_at: f64 = held.streamed ? -1 : held.frames as f64;
if held.streamed {
if at.stream is some(&mut s) {
val first := position >= 1 ? (math::floor(position) - 1) as u64 : 0;
val last := math::floor(position + step * frames as f64) as u64 + 3;
val window := &mut s.get();
window.ensure(first, last, channels, looping, held.loop_points);
data = window.window.data;
base = window.base as i64;
count = (window.window.length / channels) as i64;
ends_at = window.ended ? window.end as f64 : -1;
} else {
return true;
}
} else {
data = held.decoded.samples.data;
# Read where they are only short of where a looping voice goes back from.
count = looping ? loop_end as i64 : held.frames as i64;
}
for i in 0..frames {
val sooner := held.streamed ? ends_at >= 0 && position >= ends_at : !looping && position >= ends_at;
if sooner {
finished = true;
break;
}
val index := position as i64;
val t := (position - index as f64) as f32;
val near := index - base;
var left: f32 = 0;
var right: f32 = 0;
if near >= 1 && near + 2 < count {
# Within what's held: the four frames read where they are.
val from := data + (near as u64 - 1) * channels;
if channels == 1 {
val p1: f32 = through(from + 1);
left = t == 0 ? p1 : hermite(through(from), p1, through(from + 2), through(from + 3), t);
right = left;
} else {
val l1: f32 = through(from + 2);
val r1: f32 = through(from + 3);
left = t == 0 ? l1 : hermite(through(from), l1, through(from + 4), through(from + 6), t);
right = t == 0 ? r1 : hermite(through(from + 1), r1, through(from + 5), through(from + 7), t);
}
} else {
# About an end: wrapped around where the voice loops, silent where not.
val p0 := frame_of(at, held, index - 1, looping, loop_start, loop_end);
val p1 := frame_of(at, held, index, looping, loop_start, loop_end);
val p2 := frame_of(at, held, index + 1, looping, loop_start, loop_end);
val p3 := frame_of(at, held, index + 2, looping, loop_start, loop_end);
left = hermite(p0[0], p1[0], p2[0], p3[0], t);
right = channels == 1 ? left : hermite(p0[1], p1[1], p2[1], p3[1], t);
}
val ramp := (i + 1) as f32 / frames as f32;
into[i * 2] += left * (start[0] + (end[0] - start[0]) * ramp);
into[i * 2 + 1] += right * (start[1] + (end[1] - start[1]) * ramp);
position += step;
if looping && !held.streamed && position >= loop_end as f64 {
position -= (loop_end - loop_start) as f64;
}
}
at.position = position;
at.gains = end;
at.level = level;
at.started = true;
return finished || (at.stopping && level <= 0);
}
# Where a looping voice of a decoded sound goes back from: its loop's end, or
# its own.
def loop_end_of(held: &held_sound): u64 {
val end := held.loop_points.end;
return end != 0 && end < held.frames ? end : held.frames;
}
# A frame of a voice's sound, its left and right, a mono one's twice: past
# where a looping voice goes back from, where it goes back to, and before its
# start, a whole sound looping's end; silence outside it where it doesn't loop.
def frame_of(at: &mut voice_state, held: &held_sound, index: i64, looping: bool, loop_start: u64, loop_end: u64): f32[2] {
val channels := held.channels as u64;
if held.streamed {
if at.stream is some(&mut s) {
val window := &s.get();
return [0, 0] if index < window.base as i64;
val k := (index - window.base as i64) as u64;
return [0, 0] if (k + 1) * channels > window.window.length;
val first := window.window[k * channels];
return [first, channels == 1 ? first : window.window[k * channels + 1]];
}
return [0, 0];
}
val count := held.frames as i64;
var k := index;
if looping && k >= loop_end as i64 {
val length := (loop_end - loop_start) as i64;
k = loop_start as i64 + (k - loop_end as i64) % length;
} else if looping && k < 0 && loop_start == 0 {
k = loop_end as i64 + k;
}
if k < 0 || k >= count {
return [0, 0];
}
val at_sample := k as u64 * channels;
val first := held.decoded.samples[at_sample];
return [first, channels == 1 ? first : held.decoded.samples[at_sample + 1]];
}
# The cubic Hermite curve, as Catmull and Rom's spline, through four samples, at
# a place between the middle two.
def hermite(p0: f32, p1: f32, p2: f32, p3: f32, t: f32): f32 {
val c1 := 0.5 * (p2 - p0);
val c2 := p0 - 2.5 * p1 + 2 * p2 - 0.5 * p3;
val c3 := 0.5 * (p3 - p0) + 1.5 * (p1 - p2);
return ((c3 * t + c2) * t + c1) * t + p1;
}
# Decodes until the window holds the frames from one to before another, letting
# go of those before the first, and, where the voice loops, seeking the stream
# back to where its sound loops to as it reaches where it loops from, or its
# end, marking where its frames go on from.
def streaming::ensure(&mut this, first: u64, last: u64, channels: u64, looping: bool, looped: loop_range): void {
val held := this.window.length / channels;
if first > this.base {
val drop := first - this.base < held ? first - this.base : held;
val kept := (held - drop) * channels;
for i in 0..kept {
this.window[i] = this.window[i + drop * channels];
}
this.window.resize(kept);
this.base += drop;
}
# What's marked before the window's first frame is let go of, but the mark
# it goes on from.
while this.marks.length > 1 && this.marks[1].voice <= this.base {
this.marks.remove_at(0);
}
var dry: u32 = 0;
while !this.ended && this.base + this.window.length / channels < last {
var wanted := stream_chunk;
if looping && looped.end > this.at && looped.end - this.at < wanted {
wanted = looped.end - this.at;
}
val reached := looping && looped.end != 0 && this.at >= looped.end;
var got: u64 = 0;
if !reached {
val old := this.window.length;
this.window.resize(old + wanted * channels);
val into := slice::<f32>::over(this.window.data + old, wanted * channels);
if this.decoding.read(into) is value(count) {
got = count;
} else {
this.window.resize(old);
this.ended = true;
this.end = this.base + old / channels;
break;
}
this.window.resize(old + got * channels);
this.at += got;
continue if got == wanted && !(looping && looped.end != 0 && this.at >= looped.end);
}
if looping && dry < 2 {
dry = got == 0 ? dry + 1 : 0;
val back := looped.end != 0 && looped.start >= looped.end ? 0u : looped.start;
val sought := back == 0 ? ok_seeking(&mut this.decoding) : this.decoding.seek(back);
if sought is error(_) {
this.ended = true;
this.end = this.base + this.window.length / channels;
break;
}
this.at = back;
this.marks.append(stream_mark{ voice = this.base + this.window.length / channels, sound = back });
continue;
}
this.ended = true;
this.end = this.base + this.window.length / channels;
}
}
# Reads a stream again from its start, as a seek to it does, without one.
def ok_seeking(decoding: &mut stream): result<void, audio_error> {
decoding.rewind();
return;
}