Skip to content

armgit / raea

Public Imported from GitHub
0

Render Anything Engine: tell your AI what to make. Videos, motion graphics, 3D and games as React and TypeScript, rendered on your own GPU. Rust + Bevy, macOS, Linux and Windows.

CI's size and dupes gates on 0.1.11: the mixer's output device (the stream and following the system's output) in its own crate, raea-sys-mix-device, so raea-sys-mix is under 2000 lines and live.rs under 500; one make::Gate in raea-core-brief for a cut's and a goal's gates (cut-plan and goal-plan had the same struct, and status.rs the same closure twice); the CTA's best line found without a copy of hands-audit's fold

shinyobjectzf4db12c1d026
diff --git a/Cargo.lock b/Cargo.lock
index 7435963c..5726baec 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -16436,11 +16436,22 @@ dependencies = [
"raea-io-home",
"raea-io-media",
"raea-io-trace",
+ "raea-sys-mix-device",
"raea-sys-mix-level",
"raea-sys-tone",
"serde_json",
]
+[[package]]
+name = "raea-sys-mix-device"
+version = "0.1.0"
+dependencies = [
+ "audioadapter-buffers",
+ "cpal 0.15.3",
+ "firewheel",
+ "raea-io-trace",
+]
+
[[package]]
name = "raea-sys-mix-level"
version = "0.1.0"
diff --git a/Cargo.toml b/Cargo.toml
index 6f882cd8..dd0e241c 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -86,6 +86,7 @@ members = [
"systems/tone",
"systems/mix",
"systems/mix/level",
+ "systems/mix/device",
"systems/ml",
"systems/mlx",
"systems/kimodo",
diff --git a/apps/make/src/status.rs b/apps/make/src/status.rs
index 2ccce8b5..53ebee67 100644
--- a/apps/make/src/status.rs
+++ b/apps/make/src/status.rs
@@ -1,8 +1,7 @@
//! Whether a job is done (docs/make.feature MK1), from what's on disk and nothing the agent says: the deliverables, the
//! notes, the record of renders and checks, and the judge's rounds. Pure over a `Job` so it is tested on fixtures.
-use std::path::{Path, PathBuf};
-use std::time::SystemTime;
+use std::{path::{Path, PathBuf}, time::SystemTime};
use raea_core_brief::make::{self, Make};
use raea_core_facts::{Level, record::Entry};
@@ -188,10 +187,11 @@ pub fn status(job: &Job) -> Value {
}
let mut gates = checks(job);
gates.extend(lods(job, &notes));
+ // a cut job: its brief's rules over every delivered file (MK25-MK27), and the person's review its critic; a goal's
+ let plan = |g: make::Gate| gate(g.name, g.of.as_deref(), g.clear, g.says);
match (&job.make.cut, job.make.kind) {
- // a cut job: its brief's rules over every delivered file (MK25-MK27), and the person's review its critic
- (Some(c), make::Kind::Cut) => gates.extend(raea_runtime_cut_plan::gates(c, job.dir).into_iter().map(|g| gate(g.name, g.of.as_deref(), g.clear, g.says))),
- (_, make::Kind::Goal) => gates.extend(job.make.goal.iter().flat_map(|g| raea_runtime_goal_plan::gates(g, job.dir)).map(|g| gate(g.name, g.of.as_deref(), g.clear, g.says))),
+ (Some(c), make::Kind::Cut) => gates.extend(raea_runtime_cut_plan::gates(c, job.dir).into_iter().map(plan)),
+ (_, make::Kind::Goal) => gates.extend(job.make.goal.iter().flat_map(|g| raea_runtime_goal_plan::gates(g, job.dir)).map(plan)),
_ => gates.extend(critic(job, newest, &notes)),
}
let (asks, said) = crate::asked::gates(&sheets(job), job.ledger, &notes);
diff --git a/core/brief/src/make.rs b/core/brief/src/make.rs
index 2b39d268..b13f9b69 100644
--- a/core/brief/src/make.rs
+++ b/core/brief/src/make.rs
@@ -318,3 +318,13 @@ pub fn doctor(m: &Make) -> Vec<String> {
}
out
}
+
+/// One gate as `raea make status` lists it: its name, the file, item or rule it's about, whether it's clear, and what
+/// it says. A cut's gates come from raea-runtime-cut-plan, a goal's from raea-runtime-goal-plan.
+#[derive(Debug, Clone, PartialEq)]
+pub struct Gate {
+ pub name: &'static str,
+ pub of: Option<String>,
+ pub clear: bool,
+ pub says: String,
+}
diff --git a/runtime/cut-plan/src/lib.rs b/runtime/cut-plan/src/lib.rs
index 617e9bcc..d347d681 100644
--- a/runtime/cut-plan/src/lib.rs
+++ b/runtime/cut-plan/src/lib.rs
@@ -10,14 +10,8 @@ use std::path::Path;
use raea_core_brief::cut::{self, Cut, norm};
use serde_json::Value;
-/// One gate as `raea make status` lists it: its name, the file or item it's about, whether it's clear, what it says.
-#[derive(Debug, Clone, PartialEq)]
-pub struct Gate {
- pub name: &'static str,
- pub of: Option<String>,
- pub clear: bool,
- pub says: String,
-}
+/// One gate as `raea make status` lists it (a goal's are the same kind)
+pub use raea_core_brief::make::Gate;
fn gate(name: &'static str, of: Option<&str>, clear: bool, says: String) -> Gate {
Gate { name, of: of.map(str::to_string), clear, says }
@@ -192,7 +186,10 @@ fn file_gates(c: &Cut, plan: &cut::CutPlan, format: &str, f: &Path, rel: &str, s
in_order(&want, &j.iter().map(|(w, _)| w.as_str()).collect::<Vec<_>>())
};
let lines: Vec<&str> = std::iter::once(cta.text.as_str()).chain(cta.also.iter().map(String::as_str)).collect();
- let (best, heard_share) = lines.iter().map(|l| (*l, share(l, &last))).fold(("", 0.0), |a, b| if b.1 > a.1 { b } else { a });
+ // the line heard most, the first of equals (none when no line's words were heard)
+ let heard: Vec<_> = lines.iter().map(|l| share(l, &last)).collect();
+ let heard_share = heard.iter().copied().fold(0.0, f64::max);
+ let best = lines.iter().zip(&heard).find(|(_, h)| heard_share > 0.0 && **h == heard_share).map_or("", |(l, _)| *l);
let on_screen = screen.iter().any(|(s, at)| *at >= end - within && lines.iter().any(|l| share(l, &s.split(' ').collect::<Vec<_>>()) >= CTA_SHARE));
let ok = heard_share >= CTA_SHARE || on_screen;
let says = match (ok, on_screen) {
diff --git a/runtime/goal-plan/src/lib.rs b/runtime/goal-plan/src/lib.rs
index 06c75576..6a948d3b 100644
--- a/runtime/goal-plan/src/lib.rs
+++ b/runtime/goal-plan/src/lib.rs
@@ -12,14 +12,8 @@ use std::time::{Duration, Instant, SystemTime};
use raea_core_brief::goal::Goal;
use serde_json::{Value, json};
-/// One gate as `raea make status` lists it: its name, the rule it's about, whether it's clear, what it says.
-#[derive(Debug, Clone, PartialEq)]
-pub struct Gate {
- pub name: &'static str,
- pub of: Option<String>,
- pub clear: bool,
- pub says: String,
-}
+/// One gate as `raea make status` lists it (a cut's are the same kind): `of` is the rule it's about
+pub use raea_core_brief::make::Gate;
fn gate(name: &'static str, of: &str, clear: bool, says: String) -> Gate {
Gate { name, of: Some(of.to_string()), clear, says }
diff --git a/systems/mix/Cargo.toml b/systems/mix/Cargo.toml
index cd498069..727e36c7 100644
--- a/systems/mix/Cargo.toml
+++ b/systems/mix/Cargo.toml
@@ -9,6 +9,8 @@ description = "raea's one mixer core: the same Firewheel graph plays live in the
[dependencies]
# the mix before the master: dialogue at one level, room tone at the joins
raea-sys-mix-level = { path = "level" }
+# the system's output: the stream live play runs in, moved onto the device in use
+raea-sys-mix-device = { path = "device" }
raea-io-trace = { path = "../../io/trace" }
# the bounce's scratch file, as the frames come (SG4a)
raea-io-home = { path = "../../io/home" }
diff --git a/systems/mix/device/Cargo.toml b/systems/mix/device/Cargo.toml
new file mode 100644
index 00000000..f25cc4f6
--- /dev/null
+++ b/systems/mix/device/Cargo.toml
@@ -0,0 +1,16 @@
+[package]
+name = "raea-sys-mix-device"
+version = "0.1.0"
+edition = "2024"
+license = "FSL-1.1-ALv2"
+publish = false
+description = "raea's mixer on the system's output: Firewheel's processor driven from cpal's callback, and moved onto the device in use when the output changes or the stream breaks"
+
+[dependencies]
+raea-io-trace = { path = "../../../io/trace" }
+# the mixer's graph, as raea-sys-mix pins it
+firewheel = { version = "=0.12.1", default-features = false, features = ["std", "scheduled_events"] }
+# the cpal react and the legacy app use (0.15): Firewheel's own CPAL backend needs 0.18, which can't link beside 0.15
+cpal = "0.15"
+# the processor's output, pulled into a stereo buffer
+audioadapter-buffers = { version = "4.0.0", default-features = false, features = ["std"] }
diff --git a/systems/mix/device/src/lib.rs b/systems/mix/device/src/lib.rs
new file mode 100644
index 00000000..f25f8ae8
--- /dev/null
+++ b/systems/mix/device/src/lib.rs
@@ -0,0 +1,130 @@
+//! The mixer's output: the system's default device, with Firewheel's processor pulled from cpal's callback, followed
+//! when the system's output changes (headphones in, AirPods away, a display's speakers) or cpal says the stream broke
+//! (11-26, Shane: "sometimes i dont hear any sound": the stream stayed on the device it opened on, gone or not the one
+//! being listened to).
+
+use std::sync::Arc;
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::time::{Duration, Instant};
+
+use audioadapter_buffers::direct::InterleavedSlice;
+use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
+pub use cpal::Stream;
+use firewheel::backend::BackendProcessInfo;
+use firewheel::node::StreamStatus;
+use firewheel::{ActivateInfo, FirewheelContext};
+
+/// The output a mixer plays on: the device's name (empty while there's none), the rate and block size it asks for,
+/// and whether cpal said the stream broke.
+pub struct Output {
+ pub name: String,
+ rate: u32,
+ block: u32,
+ lost: Arc<AtomicBool>,
+ looked: Instant,
+}
+
+impl Output {
+ /// The default device's stream, and the rate it runs at (`rate` when the device takes it).
+ pub fn open(cx: &mut FirewheelContext, rate: u32, block: u32) -> Result<(Output, Stream, u32), String> {
+ let lost = Arc::new(AtomicBool::new(false));
+ let (stream, got, name) = start(cx, rate, block, lost.clone())?;
+ Ok((Output { name, rate, block, lost, looked: Instant::now() }, stream, got))
+ }
+
+ /// Whether the stream should move: at once after cpal said it broke, else when the system's default output, looked
+ /// at once a second, is another device.
+ pub fn moved(&mut self) -> bool {
+ let lost = self.lost.load(Ordering::Relaxed);
+ if !lost && self.looked.elapsed() < Duration::from_secs(1) {
+ return false;
+ }
+ self.looked = Instant::now();
+ let now = cpal::default_host().default_output_device().and_then(|d| d.name().ok()).unwrap_or_default();
+ lost || (!now.is_empty() && now != self.name)
+ }
+
+ /// The stream started again on the default device: `old` is let go first, which hands the graph back (its
+ /// processor dropped). The new stream and its rate, or no device to play on (looked for again in a second).
+ pub fn reopen(&mut self, cx: &mut FirewheelContext, old: Option<Stream>) -> Result<(Stream, u32), String> {
+ drop(old);
+ let t0 = Instant::now();
+ while cx.is_active() && t0.elapsed() < Duration::from_millis(500) {
+ let _ = cx.update();
+ std::thread::sleep(Duration::from_millis(1));
+ }
+ self.lost.store(false, Ordering::Relaxed);
+ match start(cx, self.rate, self.block, self.lost.clone()) {
+ Ok((stream, rate, name)) => {
+ eprintln!("raea mixer: sound now on {name} (was {})", if self.name.is_empty() { "nothing" } else { &self.name });
+ self.name = name;
+ Ok((stream, rate))
+ }
+ Err(e) => {
+ if !self.name.is_empty() {
+ eprintln!("raea mixer: no sound: {e}");
+ }
+ self.name.clear();
+ Err(e)
+ }
+ }
+ }
+}
+
+/// The default output device, at `want` Hz when it takes it, `block` frames a callback when it takes that: Firewheel's
+/// processor pulled from cpal's callback, as the bounce pulls it into a buffer (stereo, spread over the device's
+/// channels).
+fn start(cx: &mut FirewheelContext, want: u32, block: u32, lost: Arc<AtomicBool>) -> Result<(Stream, u32, String), String> {
+ let host = cpal::default_host();
+ let dev = host.default_output_device().ok_or("no audio output device")?;
+ let name = dev.name().unwrap_or_default();
+ let def = dev.default_output_config().map_err(|e| format!("audio output: {e}"))?;
+ let channels = def.channels();
+ let takes_48k = dev.supported_output_configs().map(|mut c| c.any(|r| r.channels() == channels && r.sample_format() == cpal::SampleFormat::F32 && r.min_sample_rate().0 <= want && r.max_sample_rate().0 >= want)).unwrap_or(false);
+ let rate = if takes_48k { want } else { def.sample_rate().0 };
+ let max_block = 8192usize;
+ let mut proc = cx
+ .activate(ActivateInfo { sample_rate: std::num::NonZeroU32::new(rate).unwrap(), max_block_frames: std::num::NonZeroU32::new(max_block as u32).unwrap(), num_stream_in_channels: 0, num_stream_out_channels: 2, input_to_output_latency_seconds: 0.0 })
+ .map_err(|e| format!("the mixer's graph: {e:?}"))?;
+ let ch = channels as usize;
+ let began = std::time::Instant::now();
+ let mut stereo = vec![0f32; max_block * 2];
+ let empty: [f32; 0] = [];
+ let mut callback = move |out: &mut [f32], info: &cpal::OutputCallbackInfo| {
+ let ts = info.timestamp();
+ let delay = ts.playback.duration_since(&ts.callback);
+ let frames = out.len() / ch.max(1);
+ let mut done = 0;
+ while done < frames {
+ let k = (frames - done).min(max_block);
+ let pi = BackendProcessInfo { frames: k, process_timestamp: Some(std::time::Instant::now()), duration_since_stream_start: began.elapsed(), input_stream_status: StreamStatus::empty(), output_stream_status: StreamStatus::empty(), dropped_frames: 0, process_to_playback_delay: delay };
+ if let (Ok(input), Ok(mut output)) = (InterleavedSlice::new(&empty[..], 0, 0), InterleavedSlice::new_mut(&mut stereo[..k * 2], 2, k)) {
+ proc.process(&input, &mut output, pi);
+ }
+ for i in 0..k {
+ let (l, r) = (stereo[2 * i], stereo[2 * i + 1]);
+ let o = &mut out[(done + i) * ch..(done + i + 1) * ch];
+ match ch {
+ 1 => o[0] = 0.5 * (l + r),
+ _ => {
+ o[0] = l;
+ o[1] = r;
+ o[2..].fill(0.0);
+ }
+ }
+ }
+ done += k;
+ }
+ };
+ // the block size when the device's range takes it, else its own
+ let fits = dev.supported_output_configs().map(|mut c| c.any(|r| r.channels() == channels && matches!(r.buffer_size(), cpal::SupportedBufferSize::Range { min, max } if *min <= block && block <= *max))).unwrap_or(false);
+ let config = cpal::StreamConfig { channels, sample_rate: cpal::SampleRate(rate), buffer_size: if fits { cpal::BufferSize::Fixed(block) } else { cpal::BufferSize::Default } };
+ let mut said = raea_io_trace::once::said_once::<cpal::StreamError>("raea mixer");
+ let broke = move |e: cpal::StreamError| {
+ lost.store(true, Ordering::Relaxed);
+ said(e)
+ };
+ let stream = dev.build_output_stream(&config, move |o: &mut [f32], i: &cpal::OutputCallbackInfo| callback(o, i), broke, None).map_err(|e| format!("audio stream: {e}"))?;
+ stream.play().map_err(|e| format!("audio stream: {e}"))?;
+ Ok((stream, rate, name))
+}
diff --git a/systems/mix/src/live.rs b/systems/mix/src/live.rs
index dc833330..fe42c053 100644
--- a/systems/mix/src/live.rs
+++ b/systems/mix/src/live.rs
@@ -7,16 +7,15 @@
use std::collections::HashMap;
use std::path::{Path, PathBuf};
-use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::atomic::Ordering;
use std::sync::mpsc::{Receiver, Sender, channel};
use std::sync::{Arc, Mutex};
-use audioadapter_buffers::direct::InterleavedSlice;
-use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
-use firewheel::backend::BackendProcessInfo;
+use cpal::traits::StreamTrait;
use firewheel::clock::{EventInstant, InstantSamples};
-use firewheel::node::{NodeID, StreamStatus};
-use firewheel::{ActivateInfo, FirewheelConfig, FirewheelContext};
+use firewheel::node::NodeID;
+use firewheel::{FirewheelConfig, FirewheelContext};
+use raea_sys_mix_device::Output;
use crate::nodes::{Stats, event};
use raea_io_media::pcm::Pcm;
@@ -36,13 +35,8 @@ pub struct Live {
cx: FirewheelContext,
/// the device's stream: None for the moment it's reopened on another device (follow_device)
_stream: Option<cpal::Stream>,
- /// the output it plays on (its name), the block size it was asked for, and whether cpal said the stream broke
- /// (the device unplugged, its AirPods put away): the stage follows the system's output (11-26, Shane: "sometimes i
- /// dont hear any sound": the stream stayed on the device it opened on, gone or not the one being listened to)
- device: String,
- block: u32,
- lost: Arc<AtomicBool>,
- looked: std::time::Instant,
+ /// the output it plays on, followed when the system's output changes (raea-sys-mix-device)
+ out: Output,
voices: NodeID,
master: NodeID,
score: Option<Score>,
@@ -93,8 +87,7 @@ impl Live {
let mut cx = FirewheelContext::new(FirewheelConfig::default());
let (voices, master) = crate::graph(&mut cx, stats.clone(), tap.as_ref().map(|t| t.1.clone()), mute)?;
let block = std::env::var("RAEA_AUDIO_BLOCK").ok().and_then(|v| v.parse().ok()).unwrap_or(256u32);
- let lost = Arc::new(AtomicBool::new(false));
- let (stream, rate, device) = start(&mut cx, block, lost.clone())?;
+ let (out, stream, rate) = Output::open(&mut cx, RATE, block)?;
if rate != RATE {
eprintln!("raea mixer: the device runs at {rate} Hz, not {RATE}: live play can't be the bounce sample for sample");
}
@@ -106,7 +99,7 @@ impl Live {
// a device opened beside the edit's open waits for nothing by then
Ok(Live {
opened: std::time::Instant::now(),
- settled: false, cx, _stream: Some(stream), device, block, lost, looked: std::time::Instant::now(), voices, master, score: None, pcm: HashMap::new(), opening: HashMap::new(), loader: raea_io_media::pcm::loader(), rate, head, head_base: head, origin: None, drift_ms: Vec::new(), anchors: Vec::new(), slews: 0, load_ms: Vec::new(), load_wait: std::time::Duration::from_millis(std::env::var("RAEA_AUDIO_LOAD_WAIT_MS").ok().and_then(|v| v.parse().ok()).unwrap_or(80)), used: HashMap::new(), items: Vec::new(), keep: HashMap::new(), blocks: Vec::new(), master_set: (0.0, 20.0 * (crate::nodes::CEILING as f64).log10()), bypass: false, resting: false, built: Default::default(), stats, tap })
+ settled: false, cx, _stream: Some(stream), out, voices, master, score: None, pcm: HashMap::new(), opening: HashMap::new(), loader: raea_io_media::pcm::loader(), rate, head, head_base: head, origin: None, drift_ms: Vec::new(), anchors: Vec::new(), slews: 0, load_ms: Vec::new(), load_wait: std::time::Duration::from_millis(std::env::var("RAEA_AUDIO_LOAD_WAIT_MS").ok().and_then(|v| v.parse().ok()).unwrap_or(80)), used: HashMap::new(), items: Vec::new(), keep: HashMap::new(), blocks: Vec::new(), master_set: (0.0, 20.0 * (crate::nodes::CEILING as f64).log10()), bypass: false, resting: false, built: Default::default(), stats, tap })
}
/// The master: `gain_db` on the sum, then the limiter at `ceiling_db` (dBTP).
@@ -359,48 +352,22 @@ impl Live {
/// old one is let go, which hands the graph back (its processor dropped), and it starts again on the new device. The
/// timeline is placed again on the next frame, as after a rest.
fn follow_device(&mut self) {
- let lost = self.lost.load(Ordering::Relaxed);
- if !lost && self.looked.elapsed() < std::time::Duration::from_secs(1) {
+ if !self.out.moved() {
return;
}
- self.looked = std::time::Instant::now();
- let now = cpal::default_host().default_output_device().and_then(|d| d.name().ok()).unwrap_or_default();
- if !lost && (now.is_empty() || now == self.device) {
- return;
- }
- // the old stream and its callback go, and the processor in it: the context is free to start again
- self._stream = None;
- let t0 = std::time::Instant::now();
- while self.cx.is_active() && t0.elapsed() < std::time::Duration::from_millis(500) {
- let _ = self.cx.update();
- std::thread::sleep(std::time::Duration::from_millis(1));
- }
- self.lost.store(false, Ordering::Relaxed);
- match start(&mut self.cx, self.block, self.lost.clone()) {
- Ok((stream, rate, device)) => {
- eprintln!("raea mixer: sound now on {device} (was {})", if self.device.is_empty() { "nothing" } else { &self.device });
- if rate != self.rate {
- // the head and the score count samples: both at the new device's rate
- self.head_base = (self.head_base as f64 * rate as f64 / self.rate as f64).round() as i64;
- self.rate = rate;
- self.score = None;
- }
- self._stream = Some(stream);
- self.device = device;
- self.resting = false;
- self.origin = None;
- self.settled = false;
- self.opened = std::time::Instant::now();
- let _ = self.cx.update();
- }
- // no device to play on (none plugged in): looked for again in a second
- Err(e) => {
- if !self.device.is_empty() {
- eprintln!("raea mixer: no sound: {e}");
- }
- self.device.clear();
- }
+ let Ok((stream, rate)) = self.out.reopen(&mut self.cx, self._stream.take()) else { return };
+ if rate != self.rate {
+ // the head and the score count samples: both at the new device's rate
+ self.head_base = (self.head_base as f64 * rate as f64 / self.rate as f64).round() as i64;
+ self.rate = rate;
+ self.score = None;
}
+ self._stream = Some(stream);
+ self.resting = false;
+ self.origin = None;
+ self.settled = false;
+ self.opened = std::time::Instant::now();
+ let _ = self.cx.update();
}
/// The device stream stopped (after stop_all and its fade-outs: nothing is heard): no callback runs, so neither the
@@ -465,64 +432,6 @@ impl Live {
}
}
-/// The default output device, at 48 kHz when it takes it, `block` frames a callback when it takes that: Firewheel's
-/// processor pulled from cpal's callback, as the bounce pulls it into a buffer (stereo, spread over the device's
-/// channels).
-fn start(cx: &mut FirewheelContext, block: u32, lost: Arc<AtomicBool>) -> Result<(cpal::Stream, u32, String), String> {
- let host = cpal::default_host();
- let dev = host.default_output_device().ok_or("no audio output device")?;
- let name = dev.name().unwrap_or_default();
- let def = dev.default_output_config().map_err(|e| format!("audio output: {e}"))?;
- let channels = def.channels();
- let takes_48k = dev.supported_output_configs().map(|mut c| c.any(|r| r.channels() == channels && r.sample_format() == cpal::SampleFormat::F32 && r.min_sample_rate().0 <= RATE && r.max_sample_rate().0 >= RATE)).unwrap_or(false);
- let rate = if takes_48k { RATE } else { def.sample_rate().0 };
- let max_block = 8192usize;
- let mut proc = cx
- .activate(ActivateInfo { sample_rate: std::num::NonZeroU32::new(rate).unwrap(), max_block_frames: std::num::NonZeroU32::new(max_block as u32).unwrap(), num_stream_in_channels: 0, num_stream_out_channels: 2, input_to_output_latency_seconds: 0.0 })
- .map_err(|e| format!("the mixer's graph: {e:?}"))?;
- let ch = channels as usize;
- let began = std::time::Instant::now();
- let mut stereo = vec![0f32; max_block * 2];
- let empty: [f32; 0] = [];
- let mut callback = move |out: &mut [f32], info: &cpal::OutputCallbackInfo| {
- let ts = info.timestamp();
- let delay = ts.playback.duration_since(&ts.callback);
- let frames = out.len() / ch.max(1);
- let mut done = 0;
- while done < frames {
- let k = (frames - done).min(max_block);
- let pi = BackendProcessInfo { frames: k, process_timestamp: Some(std::time::Instant::now()), duration_since_stream_start: began.elapsed(), input_stream_status: StreamStatus::empty(), output_stream_status: StreamStatus::empty(), dropped_frames: 0, process_to_playback_delay: delay };
- if let (Ok(input), Ok(mut output)) = (InterleavedSlice::new(&empty[..], 0, 0), InterleavedSlice::new_mut(&mut stereo[..k * 2], 2, k)) {
- proc.process(&input, &mut output, pi);
- }
- for i in 0..k {
- let (l, r) = (stereo[2 * i], stereo[2 * i + 1]);
- let o = &mut out[(done + i) * ch..(done + i + 1) * ch];
- match ch {
- 1 => o[0] = 0.5 * (l + r),
- _ => {
- o[0] = l;
- o[1] = r;
- o[2..].fill(0.0);
- }
- }
- }
- done += k;
- }
- };
- // the block size when the device's range takes it, else its own
- let fits = dev.supported_output_configs().map(|mut c| c.any(|r| r.channels() == channels && matches!(r.buffer_size(), cpal::SupportedBufferSize::Range { min, max } if *min <= block && block <= *max))).unwrap_or(false);
- let config = cpal::StreamConfig { channels, sample_rate: cpal::SampleRate(rate), buffer_size: if fits { cpal::BufferSize::Fixed(block) } else { cpal::BufferSize::Default } };
- let mut said = raea_io_trace::once::said_once::<cpal::StreamError>("raea mixer");
- let broke = move |e: cpal::StreamError| {
- lost.store(true, Ordering::Relaxed);
- said(e)
- };
- let stream = dev.build_output_stream(&config, move |o: &mut [f32], i: &cpal::OutputCallbackInfo| callback(o, i), broke, None).map_err(|e| format!("audio stream: {e}"))?;
- stream.play().map_err(|e| format!("audio stream: {e}"))?;
- Ok((stream, rate, name))
-}
-
impl Drop for Live {
fn drop(&mut self) {
let Some((path, buf)) = self.tap.take() else { return };
diff --git a/tools/layers.toml b/tools/layers.toml
index 61c9bbf9..82b941d8 100644
--- a/tools/layers.toml
+++ b/tools/layers.toml
@@ -55,6 +55,7 @@ raea-core-ask = "core"
raea-sys-k = "systems"
raea-sys-mix = "systems"
raea-sys-mix-level = "systems"
+raea-sys-mix-device = "systems"
raea-sys-tone = "systems"
raea-seedling = "systems"
raea-sys-ml = "systems"
@@ -295,6 +296,8 @@ raea-sys-rt = true
raea-sys-mix = true
# the mix before the master: dialogue at one level, room tone at the joins (the mix masters what it gives)
raea-sys-mix-level = true
+# the mixer's output: the device stream live play runs in, followed when the system's output changes
+raea-sys-mix-device = true
raea-sys-tone = true
raea-sys-ml = true
raea-sys-mlx = true