#[allow(dead_code)]
pub(crate) mod text_table {
use crate::text::{Catalog, Seg};
include!(concat!(env!("OUT_DIR"), "/text-mixer.rs"));
}
use std::sync::atomic::{AtomicU32, AtomicU64};
use std::sync::Arc;
use std::time::Duration;
use crate::player::TrackActivity;
use crate::Song;
mod clip;
mod engine;
mod gain;
mod handle;
mod lookahead;
mod tap;
pub use engine::Mixer;
pub use handle::MixerHandle;
use tap::Tap;
pub use tap::{TapRead, SCOPE_LEN, STREAM_LEN};
#[cfg(feature = "cpal")]
mod output;
#[cfg(feature = "cpal")]
pub use output::{buffer_size, Output, OutputError, OutputOptions};
pub const MAX_SOUNDS: usize = 32;
pub const MAX_CLIPS: usize = 64;
pub const MAX_BUSES: usize = 8;
pub const MAX_LOOKAHEAD: Duration = Duration::from_secs(2);
pub const MIN_LOOKAHEAD: Duration = Duration::from_millis(50);
pub const NOTICE_QUEUE: usize = 256;
const QUEUE: usize = 256;
const LOOKAHEAD_BLOCK: usize = 512;
const FADING_CLIPS: usize = 16;
const STEAL_FADE_SECS: f64 = 0.002;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct SoundId(u64);
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct ClipId(u64);
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct BusId(pub u8);
impl BusId {
pub const MAIN: BusId = BusId(0);
fn index(self) -> Result<usize, MixerError> {
let i = self.0 as usize;
if i < MAX_BUSES {
Ok(i)
} else {
Err(MixerError::NoSuchBus)
}
}
}
impl Default for BusId {
fn default() -> Self {
BusId::MAIN
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct PlayOptions {
pub bus: BusId,
pub fade_in: Duration,
pub lookahead: Duration,
}
impl Default for PlayOptions {
fn default() -> Self {
PlayOptions {
bus: BusId::MAIN,
fade_in: Duration::ZERO,
lookahead: Duration::ZERO,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ClipOptions {
pub volume: f32,
pub rate: f32,
pub pan: f32,
pub bus: BusId,
pub looping: bool,
}
impl Default for ClipOptions {
fn default() -> Self {
ClipOptions {
volume: 1.0,
rate: 1.0,
pan: 0.0,
bus: BusId::MAIN,
looping: false,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum SwitchAt {
#[default]
Now,
NextBar,
}
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub struct SwitchOptions {
pub fade: Duration,
pub at: SwitchAt,
pub lookahead: Duration,
}
#[derive(Debug, Clone)]
pub struct Clip {
frames: Arc<[[f32; 2]]>,
sample_rate: u32,
}
impl Clip {
pub fn new(frames: impl Into<Arc<[[f32; 2]]>>, sample_rate: u32) -> Self {
Clip {
frames: frames.into(),
sample_rate: sample_rate.max(1),
}
}
pub fn render(song: &Song, sample_rate: u32) -> Self {
Clip::new(crate::synth::render(song, sample_rate, 0), sample_rate)
}
pub fn len(&self) -> usize {
self.frames.len()
}
pub fn is_empty(&self) -> bool {
self.frames.is_empty()
}
pub fn sample_rate(&self) -> u32 {
self.sample_rate
}
pub fn duration(&self) -> Duration {
Duration::from_secs_f64(self.frames.len() as f64 / self.sample_rate as f64)
}
pub fn frames(&self) -> &[[f32; 2]] {
&self.frames
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MixerError {
QueueFull,
TooManySounds,
NotPlaying,
SampleRateMismatch,
NoSuchBus,
NotLookahead,
}
impl crate::text::Localized for MixerError {
fn text_key(&self) -> &'static str {
match self {
MixerError::QueueFull => "err-mixer-queue-full",
MixerError::TooManySounds => "err-mixer-too-many-sounds",
MixerError::NotPlaying => "err-mixer-not-playing",
MixerError::SampleRateMismatch => "err-mixer-sample-rate-mismatch",
MixerError::NoSuchBus => "err-mixer-no-such-bus",
MixerError::NotLookahead => "err-mixer-not-lookahead",
}
}
fn catalogs(&self) -> &'static [crate::text::Catalog] {
crate::player::mixer::text_table::CATALOGS
}
}
impl core::fmt::Display for MixerError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
crate::text::write_localized(f, self, crate::text::DEFAULT_LANG)
}
}
impl std::error::Error for MixerError {}
struct Playheads {
ids: Vec<AtomicU64>,
ticks: Vec<AtomicU64>,
track_counts: Vec<AtomicU32>,
tracks: Vec<AtomicU64>,
tracks_ext: Vec<AtomicU64>,
latency: AtomicU32,
}
pub const MAX_TRACK_ACTIVITY: usize = 32;
fn pack_activity(a: TrackActivity) -> u64 {
a.note_ons as u64
| (a.key as u64) << 32
| ((a.volume & 0x0f) as u64) << 40
| (a.sounding as u64) << 44
}
fn pack_activity_ext(a: TrackActivity) -> u64 {
a.note_offs as u64 | (a.chord_pcs as u64) << 32 | (a.chord_len as u64) << 48
}
fn unpack_activity(v: u64, ext: u64) -> TrackActivity {
TrackActivity {
sounding: v >> 44 & 1 == 1,
key: (v >> 32) as u8,
volume: (v >> 40) as u8 & 0x0f,
note_ons: v as u32,
chord_len: (ext >> 48) as u8,
chord_pcs: (ext >> 32) as u16,
note_offs: ext as u32,
}
}
pub fn mixer(sample_rate: u32) -> (MixerHandle, Mixer) {
let (tx, rx) = rtrb::RingBuffer::new(QUEUE);
let (gtx, grx) = rtrb::RingBuffer::new(engine::GARBAGE_QUEUE);
let (ntx, nrx) = rtrb::RingBuffer::new(NOTICE_QUEUE);
let heads = Arc::new(Playheads {
ids: (0..MAX_SOUNDS).map(|_| AtomicU64::new(0)).collect(),
ticks: (0..MAX_SOUNDS).map(|_| AtomicU64::new(0)).collect(),
track_counts: (0..MAX_SOUNDS).map(|_| AtomicU32::new(0)).collect(),
tracks: (0..MAX_SOUNDS * MAX_TRACK_ACTIVITY)
.map(|_| AtomicU64::new(0))
.collect(),
tracks_ext: (0..MAX_SOUNDS * MAX_TRACK_ACTIVITY)
.map(|_| AtomicU64::new(0))
.collect(),
latency: AtomicU32::new(0),
});
let tap = Arc::new(Tap::new());
let handle = MixerHandle::new(tx, grx, nrx, heads.clone(), tap.clone(), sample_rate);
let mixer = Mixer::new(rx, gtx, ntx, heads, tap, sample_rate);
(handle, mixer)
}