use std::sync::atomic::Ordering;
use std::sync::Arc;
use super::clip::ClipVoice;
use super::gain::Gain;
use super::lookahead::LaStream;
use super::tap::Tap;
use super::{
pack_activity, pack_activity_ext, ClipId, Playheads, SoundId, FADING_CLIPS, MAX_BUSES,
MAX_CLIPS, MAX_SOUNDS, MAX_TRACK_ACTIVITY, STEAL_FADE_SECS,
};
use crate::{Command, Notice, Player};
use pikopiko_runtime::output::{EqSettings, OutputEq};
pub(super) const GARBAGE_QUEUE: usize = 2 * PENDING;
const PENDING: usize = MAX_SOUNDS + MAX_CLIPS + FADING_CLIPS;
const CHUNK: usize = 1024;
pub(super) enum Source {
Player(Box<Player>),
Stream(Box<LaStream>),
}
impl Source {
fn position(&self) -> u64 {
match self {
Source::Player(p) => p.position(),
Source::Stream(s) => s.tick(),
}
}
fn is_finished(&self) -> bool {
match self {
Source::Player(p) => p.is_finished(),
Source::Stream(s) => s.is_finished(),
}
}
fn mark_removed(&self) {
if let Source::Stream(s) = self {
s.shared.removed.store(true, Ordering::Release);
}
}
}
pub(super) enum Garbage {
Sound(SoundId, Source),
Clip(Arc<[[f32; 2]]>),
}
#[derive(Clone, Copy, Debug)]
pub(super) enum BusOp {
Volume { target: f32, frames: u32 },
Pause { frames: u32 },
Resume { frames: u32 },
Stop { frames: u32 },
}
pub(super) enum Msg {
Add {
id: SoundId,
source: Source,
fade_in: u32,
bus: u8,
bar_ticks: u64,
length: u64,
after: Option<SoundId>,
},
Cmd(SoundId, Command),
Fade {
id: SoundId,
target: f32,
frames: u32,
stop: bool,
},
Remove(SoundId),
RemoveAll,
MasterVolume(f32),
OutputEq(EqSettings),
PlayClip {
id: ClipId,
data: Arc<[[f32; 2]]>,
step: f64,
pan: f32,
volume: f32,
bus: u8,
looping: bool,
},
ClipFade {
id: ClipId,
target: f32,
frames: u32,
stop: bool,
},
Bus(u8, BusOp),
}
struct Slot {
id: SoundId,
source: Source,
gain: Gain,
bus: u8,
bar_ticks: u64,
length: u64,
tpf: f64,
after: Option<SoundId>,
start_fade: u32,
}
struct Bus {
volume: Gain,
pause: Gain,
pausing: bool,
paused: bool,
}
impl Bus {
const NEW: Bus = Bus {
volume: Gain::UNITY,
pause: Gain::UNITY,
pausing: false,
paused: false,
};
fn settle(&mut self) {
if self.pausing && self.pause.is_still() && self.pause.value() == 0.0 {
self.paused = true;
}
}
}
pub struct Mixer {
rx: rtrb::Consumer<Msg>,
garbage: rtrb::Producer<Garbage>,
notices: rtrb::Producer<(SoundId, Notice)>,
slots: Vec<Option<Slot>>,
clips: Vec<Option<ClipVoice>>,
fading: Vec<Option<ClipVoice>>,
buses: [Bus; MAX_BUSES],
pending_garbage: Vec<Option<Garbage>>,
scratch: Vec<[f32; 2]>,
busbuf: Vec<[f32; 2]>,
crossed: Vec<Option<usize>>,
ended: Vec<bool>,
master: f32,
eq: OutputEq,
sample_rate: u32,
clip_order: u64,
heads: Arc<Playheads>,
tap: Arc<Tap>,
}
fn crossing(before: u64, after: u64, bar: u64, length: u64, tpf: f64, n: usize) -> Option<usize> {
if bar == 0 {
return None;
}
let next = (before / bar + 1) * bar;
let wrapped = after < before;
let at_end = length > 0 && after >= length;
if !wrapped && !at_end {
if after >= next && after > before {
let k = (u128::from(next - before) * n as u128 / u128::from(after - before)) as usize;
return Some(k.min(n));
}
return None;
}
let bound = if length > 0 { next.min(length) } else { next };
if tpf > 0.0 {
let k = (bound.saturating_sub(before) as f64 / tpf).round();
Some((k as usize).min(n))
} else {
Some(0)
}
}
impl Mixer {
pub(super) fn new(
rx: rtrb::Consumer<Msg>,
garbage: rtrb::Producer<Garbage>,
notices: rtrb::Producer<(SoundId, Notice)>,
heads: Arc<Playheads>,
tap: Arc<Tap>,
sample_rate: u32,
) -> Mixer {
Mixer {
rx,
garbage,
notices,
slots: (0..MAX_SOUNDS).map(|_| None).collect(),
clips: (0..MAX_CLIPS).map(|_| None).collect(),
fading: (0..FADING_CLIPS).map(|_| None).collect(),
buses: [const { Bus::NEW }; MAX_BUSES],
pending_garbage: (0..PENDING).map(|_| None).collect(),
scratch: vec![[0.0; 2]; CHUNK],
busbuf: vec![[0.0; 2]; CHUNK],
crossed: vec![None; MAX_SOUNDS],
ended: vec![false; MAX_SOUNDS],
master: 1.0,
eq: OutputEq::flat(sample_rate),
sample_rate,
clip_order: 0,
heads,
tap,
}
}
pub fn report_output_latency(&self, latency: std::time::Duration) {
let rate = self.sample_rate as f64;
let frames = (latency.as_secs_f64() * rate).round().clamp(0.0, rate) as u32;
self.heads.latency.store(frames, Ordering::Relaxed);
}
pub fn sample_rate(&self) -> u32 {
self.sample_rate
}
fn handle_messages(&mut self) {
while let Ok(msg) = self.rx.pop() {
match msg {
Msg::Add {
id,
source,
fade_in,
bus,
bar_ticks,
length,
after,
} => {
let (gain, start_fade) = if after.is_some() {
(Gain::SILENT, fade_in)
} else if fade_in > 0 {
let mut g = Gain::SILENT;
g.start(1.0, fade_in, false);
(g, 0)
} else {
(Gain::UNITY, 0)
};
let slot = Slot {
id,
source,
gain,
bus,
bar_ticks,
length,
tpf: 0.0,
after,
start_fade,
};
if let Some(free) = self.slots.iter_mut().find(|s| s.is_none()) {
*free = Some(slot);
} else {
slot.source.mark_removed();
self.retire(Garbage::Sound(slot.id, slot.source));
}
}
Msg::Cmd(id, cmd) => {
if let Some(s) = self.slots.iter_mut().flatten().find(|s| s.id == id) {
if let Source::Player(p) = &mut s.source {
p.handle(cmd);
}
}
}
Msg::Fade {
id,
target,
frames,
stop,
} => {
if let Some(s) = self.slots.iter_mut().flatten().find(|s| s.id == id) {
s.gain.start(target, frames, stop);
}
}
Msg::Remove(id) => {
if let Some(i) = self.slot_index(id) {
self.remove_slot(i);
}
}
Msg::RemoveAll => {
for i in 0..self.slots.len() {
self.remove_slot(i);
}
for i in 0..self.clips.len() {
if let Some(c) = self.clips[i].take() {
self.retire(Garbage::Clip(c.data));
}
}
for i in 0..self.fading.len() {
if let Some(c) = self.fading[i].take() {
self.retire(Garbage::Clip(c.data));
}
}
}
Msg::MasterVolume(v) => {
self.master = if v.is_finite() { v.max(0.0) } else { 0.0 };
}
Msg::OutputEq(settings) => self.eq.set(settings),
Msg::PlayClip {
id,
data,
step,
pan,
volume,
bus,
looping,
} => {
self.clip_order += 1;
let voice =
ClipVoice::new(id, data, step, pan, volume, bus, looping, self.clip_order);
self.add_clip(voice);
}
Msg::ClipFade {
id,
target,
frames,
stop,
} => {
if let Some(c) = self
.clips
.iter_mut()
.chain(self.fading.iter_mut())
.flatten()
.find(|c| c.id == id)
{
c.gain.start(target, frames, stop);
}
}
Msg::Bus(b, op) => self.bus_op(b as usize, op),
}
}
}
fn slot_index(&self, id: SoundId) -> Option<usize> {
self.slots
.iter()
.position(|s| s.as_ref().is_some_and(|s| s.id == id))
}
fn remove_slot(&mut self, i: usize) {
if let Some(s) = self.slots[i].take() {
s.source.mark_removed();
self.retire(Garbage::Sound(s.id, s.source));
}
}
fn add_clip(&mut self, voice: ClipVoice) {
if let Some(free) = self.clips.iter_mut().find(|c| c.is_none()) {
*free = Some(voice);
return;
}
let oldest = |same_bus: bool| {
self.clips
.iter()
.enumerate()
.filter_map(|(i, c)| c.as_ref().map(|c| (i, c)))
.filter(|(_, c)| !same_bus || c.bus == voice.bus)
.min_by_key(|(_, c)| c.order)
.map(|(i, _)| i)
};
let Some(i) = oldest(true).or_else(|| oldest(false)) else {
self.retire(Garbage::Clip(voice.data));
return;
};
let Some(mut victim) = self.clips[i].replace(voice) else {
return;
};
let frames = (STEAL_FADE_SECS * self.sample_rate as f64).round().max(1.0) as u32;
victim.gain.start(0.0, frames, true);
if let Some(free) = self.fading.iter_mut().find(|c| c.is_none()) {
*free = Some(victim);
} else {
self.retire(Garbage::Clip(victim.data));
}
}
fn bus_op(&mut self, b: usize, op: BusOp) {
let Some(bus) = self.buses.get_mut(b) else {
return;
};
match op {
BusOp::Volume { target, frames } => bus.volume.start(target, frames, false),
BusOp::Pause { frames } => {
bus.pausing = true;
bus.pause.start(0.0, frames, false);
bus.settle();
}
BusOp::Resume { frames } => {
bus.pausing = false;
bus.paused = false;
bus.pause.start(1.0, frames, false);
}
BusOp::Stop { frames } => {
let paused = bus.paused;
for i in 0..self.slots.len() {
if self.slots[i].as_ref().is_some_and(|s| s.bus as usize == b) {
if paused || frames == 0 {
self.remove_slot(i);
} else if let Some(s) = &mut self.slots[i] {
s.gain.start(0.0, frames, true);
}
}
}
for i in 0..self.clips.len() {
if self.clips[i].as_ref().is_some_and(|c| c.bus as usize == b) {
if paused || frames == 0 {
if let Some(c) = self.clips[i].take() {
self.retire(Garbage::Clip(c.data));
}
} else if let Some(c) = &mut self.clips[i] {
c.gain.start(0.0, frames, true);
}
}
}
for i in 0..self.fading.len() {
if paused && self.fading[i].as_ref().is_some_and(|c| c.bus as usize == b) {
if let Some(c) = self.fading[i].take() {
self.retire(Garbage::Clip(c.data));
}
}
}
}
}
}
fn retire(&mut self, g: Garbage) {
if let Err(rtrb::PushError::Full(g)) = self.garbage.push(g) {
if let Some(slot) = self.pending_garbage.iter_mut().find(|s| s.is_none()) {
*slot = Some(g);
} else {
std::mem::forget(g);
}
}
}
fn flush_pending_garbage(&mut self) {
for i in 0..self.pending_garbage.len() {
if let Some(item) = self.pending_garbage[i].take() {
if let Err(rtrb::PushError::Full(item)) = self.garbage.push(item) {
self.pending_garbage[i] = Some(item);
return;
}
}
}
}
pub fn process_stereo(&mut self, out: &mut [[f32; 2]]) {
self.handle_messages();
self.flush_pending_garbage();
out.fill([0.0, 0.0]);
let mut done = 0;
while done < out.len() {
let n = (out.len() - done).min(CHUNK);
for b in 0..MAX_BUSES {
self.mix_bus(b, &mut out[done..done + n]);
}
done += n;
}
self.publish_heads();
self.eq.process_block(out);
for o in out.iter_mut() {
o[0] = (o[0] * self.master).clamp(-1.0, 1.0);
o[1] = (o[1] * self.master).clamp(-1.0, 1.0);
}
self.tap.record(out);
}
fn mix_bus(&mut self, b: usize, out: &mut [[f32; 2]]) {
let n = out.len();
let bu8 = b as u8;
let occupied = self.slots.iter().flatten().any(|s| s.bus == bu8)
|| self.clips.iter().flatten().any(|c| c.bus == bu8)
|| self.fading.iter().flatten().any(|c| c.bus == bu8);
let bus = &mut self.buses[b];
if !occupied {
bus.volume.advance(n as u32);
bus.pause.advance(n as u32);
bus.settle();
return;
}
if bus.paused {
return;
}
let mut busbuf = std::mem::take(&mut self.busbuf);
let acc = &mut busbuf[..n];
acc.fill([0.0, 0.0]);
for i in 0..self.slots.len() {
self.crossed[i] = None;
self.ended[i] = false;
let Some(slot) = &mut self.slots[i] else {
continue;
};
if slot.bus != bu8 || slot.after.is_some() {
continue;
}
let before = slot.source.position();
render(
&mut slot.source,
slot.id,
&mut self.scratch[..n],
&mut self.notices,
);
add_with_gain(acc, &self.scratch[..n], &mut slot.gain);
let after = slot.source.position();
self.crossed[i] = crossing(before, after, slot.bar_ticks, slot.length, slot.tpf, n);
if after > before && (slot.length == 0 || after < slot.length) {
slot.tpf = (after - before) as f64 / n as f64;
}
self.ended[i] = slot.source.is_finished() || slot.gain.is_done();
}
for i in 0..self.slots.len() {
let Some(slot) = &self.slots[i] else {
continue;
};
let Some(from) = slot.after else {
continue;
};
if slot.bus != bu8 {
continue;
}
let from_index = self.slot_index(from);
let start = match from_index {
Some(j) => self.crossed[j].or(self.ended[j].then_some(n)),
None => Some(0),
};
let Some(k) = start else {
continue;
};
let fade = slot.start_fade;
if let Some(j) = from_index {
if let Some(f) = &mut self.slots[j] {
f.gain.start(0.0, fade, true);
if fade == 0 {
self.ended[j] = true;
}
}
}
let Some(slot) = &mut self.slots[i] else {
continue;
};
slot.after = None;
slot.gain.start(1.0, fade, false);
let m = n - k;
if m > 0 {
render(
&mut slot.source,
slot.id,
&mut self.scratch[..m],
&mut self.notices,
);
add_with_gain(&mut acc[k..], &self.scratch[..m], &mut slot.gain);
self.ended[i] = slot.source.is_finished() || slot.gain.is_done();
}
}
for i in 0..self.slots.len() {
if self.ended[i] {
self.ended[i] = false;
self.remove_slot(i);
}
}
for i in 0..self.clips.len() {
let finished = match &mut self.clips[i] {
Some(c) if c.bus == bu8 => c.mix(acc),
_ => false,
};
if finished {
if let Some(c) = self.clips[i].take() {
self.retire(Garbage::Clip(c.data));
}
}
}
for i in 0..self.fading.len() {
let finished = match &mut self.fading[i] {
Some(c) if c.bus == bu8 => c.mix(acc),
_ => false,
};
if finished {
if let Some(c) = self.fading[i].take() {
self.retire(Garbage::Clip(c.data));
}
}
}
let bus = &mut self.buses[b];
if bus.volume.is_unity() && bus.pause.is_unity() {
for (o, a) in out.iter_mut().zip(acc.iter()) {
o[0] += a[0];
o[1] += a[1];
}
} else {
for (o, a) in out.iter_mut().zip(acc.iter()) {
let g = bus.volume.next() * bus.pause.next();
o[0] += a[0] * g;
o[1] += a[1] * g;
}
}
bus.settle();
self.busbuf = busbuf;
}
fn publish_heads(&self) {
for (i, slot) in self.slots.iter().enumerate() {
match slot {
Some(s) => {
self.heads.ticks[i].store(s.source.position(), Ordering::Relaxed);
let n = match &s.source {
Source::Player(p) => {
let n = p.track_count().min(MAX_TRACK_ACTIVITY);
for t in 0..n {
let a = p.track_activity(t);
let k = i * MAX_TRACK_ACTIVITY + t;
self.heads.tracks[k].store(pack_activity(a), Ordering::Relaxed);
self.heads.tracks_ext[k]
.store(pack_activity_ext(a), Ordering::Relaxed);
}
n
}
Source::Stream(_) => 0,
};
self.heads.track_counts[i].store(n as u32, Ordering::Relaxed);
self.heads.ids[i].store(s.id.0, Ordering::Relaxed);
}
None => self.heads.ids[i].store(0, Ordering::Relaxed),
}
}
}
pub fn process_interleaved(&mut self, out: &mut [f32], channels: usize) {
let channels = channels.max(1);
let mut buf = [[0.0f32; 2]; 256];
for chunk in out.chunks_mut(channels * buf.len()) {
let frames = chunk.len() / channels;
self.process_stereo(&mut buf[..frames]);
for (f, s) in chunk.chunks_mut(channels).zip(&buf[..frames]) {
match f.len() {
1 => f[0] = (s[0] + s[1]) * 0.5,
_ => {
f[0] = s[0];
f[1] = s[1];
for x in &mut f[2..] {
*x = 0.0;
}
}
}
}
}
}
pub fn sounding(&self) -> usize {
self.slots.iter().flatten().count()
}
pub fn sounding_clips(&self) -> usize {
self.clips.iter().flatten().count() + self.fading.iter().flatten().count()
}
}
fn render(
source: &mut Source,
id: SoundId,
buf: &mut [[f32; 2]],
notices: &mut rtrb::Producer<(SoundId, Notice)>,
) {
match source {
Source::Player(p) => {
p.render(buf);
while let Some(n) = p.poll_notice() {
let _ = notices.push((id, n));
}
}
Source::Stream(s) => s.read(buf, |n| {
let _ = notices.push((id, n));
}),
}
}
fn add_with_gain(acc: &mut [[f32; 2]], src: &[[f32; 2]], gain: &mut Gain) {
let dst = acc.iter_mut().zip(src);
if gain.is_unity() {
for (o, s) in dst {
o[0] += s[0];
o[1] += s[1];
}
} else {
for (o, s) in dst {
let g = gain.next();
o[0] += s[0] * g;
o[1] += s[1] * g;
}
}
}
#[cfg(test)]
mod tests {
use super::crossing;
#[test]
fn crossing_finds_the_bar_inside_the_block() {
assert_eq!(crossing(50, 150, 100, 1000, 1.0, 100), Some(50));
assert_eq!(crossing(10, 90, 100, 1000, 0.8, 100), None);
assert_eq!(crossing(50, 100, 100, 1000, 0.5, 100), Some(100));
assert_eq!(crossing(0, 50, 100, 1000, 0.0, 100), None);
assert_eq!(crossing(350, 20, 100, 400, 1.0, 100), Some(50));
assert_eq!(crossing(380, 400, 1000, 400, 2.0, 100), Some(10));
assert_eq!(crossing(0, 1000, 0, 2000, 1.0, 100), None);
}
}