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.

raea mixes and masters every render's sound: dialogue at one level, a leveller before the limiter, room tone at the joins

Zachary Guglin4c3a3ba799c0
diff --git a/Cargo.lock b/Cargo.lock
index df473078..7cdaf928 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -16101,10 +16101,18 @@ dependencies = [
"cpal 0.15.3",
"firewheel",
"raea-io-media",
+ "raea-sys-mix-level",
"raea-sys-tone",
"serde_json",
]
+[[package]]
+name = "raea-sys-mix-level"
+version = "0.1.0"
+dependencies = [
+ "raea-io-media",
+]
+
[[package]]
name = "raea-sys-ml"
version = "0.1.0"
diff --git a/Cargo.toml b/Cargo.toml
index fb321c6e..9207068c 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -80,6 +80,7 @@ members = [
"systems/k",
"systems/tone",
"systems/mix",
+ "systems/mix/level",
"systems/ml",
"systems/mlx",
"systems/kimodo",
diff --git a/docs/manual/concepts/rendering.md b/docs/manual/concepts/rendering.md
index 91d57d37..0de285ab 100644
--- a/docs/manual/concepts/rendering.md
+++ b/docs/manual/concepts/rendering.md
@@ -109,8 +109,14 @@ out of order, a phrase `word()` can't find, or a missing prop.
## Loudness
-When the composition has a `<Mix>`, the export comes out at -14 LUFS integrated (within 1) with true peak at or below
--1 dBTP, which is what the major platforms play back at.
+raea mixes and masters every render's sound. First the mix: each line of dialogue (a clip on the `voice` bus, or
+footage's own sound on no bus) is measured over the part of its take it plays and brought to the same level, so no line
+is louder or quieter than the next. Room tone and silent takes keep their level, and so do music, effects and anything
+on another bus, which sit under the dialogue as their buses set them. A clip's `gainDb` is an offset on top of the
+level. Then the master: a leveller rounds the loud passages, the whole piece comes up to its loudness, and a true-peak
+limiter holds it at the ceiling. A join that drops into dead silence gets the room's own tone. The export comes out at
+-14 LUFS integrated (within 1) with true peak at or below -1 dBTP, which is what the major platforms play back at;
+`<Mix lufs={…} ceiling={…}>` sets another target.
## Mistakes to avoid
diff --git a/runtime/export/src/lib.rs b/runtime/export/src/lib.rs
index 1ab310d0..beae4033 100644
--- a/runtime/export/src/lib.rs
+++ b/runtime/export/src/lib.rs
@@ -188,6 +188,8 @@ fn push_sound(cx: &mut Ctx, props: &Map<String, Value>, skey: &str) {
// a sound track with samples: a short window says so (decoding the whole take for it held a long take whole)
let audible = *cx.audible.entry(file.clone()).or_insert_with(|| raea_io_media::decode_audio_window(&file, 0.0, 0.05).is_ok_and(|a| a.len() > 0));
if !muted && volume > 0.0 && audible {
+ // raea's mix: dialogue at one level, gainDb an offset on it (raea-sys-mix level.rs), as live play has it
+ let volume = volume * raea_sys_mix::level::gain(&file, num(props, "data-clip-from").unwrap_or(0.0), num(props, "data-clip-to"), props.get("data-bus").and_then(|v| v.as_str())) as f64;
cx.sounds.push(Sound { src: file.display().to_string(), at, volume, rate: num(props, "data-playback-rate").unwrap_or(1.0), key: skey.to_string(), fade_in: num(props, "data-fade-in"), fade_out: num(props, "data-fade-out"), bus: props.get("data-bus").and_then(|v| v.as_str()).map(str::to_string) });
}
}
diff --git a/runtime/sound/src/names.rs b/runtime/sound/src/names.rs
index 4dce90bf..7de7aa98 100644
--- a/runtime/sound/src/names.rs
+++ b/runtime/sound/src/names.rs
@@ -84,11 +84,13 @@ pub fn sounds_into<'a>(items: impl IntoIterator<Item = (&'a str, Option<&'a Map<
continue;
}
let (key, bus) = SOUND_NAMES.with_borrow_mut(|n| (n.key(node, &file), props.get("data-bus").and_then(|v| v.as_str()).map(|b| n.bus(b))));
+ // raea's mix: dialogue at one level, gainDb an offset on it (raea-sys-mix level.rs)
+ let level = raea_sys_mix::level::gain(&file, num(props, "data-clip-from").unwrap_or(0.0), num(props, "data-clip-to"), props.get("data-bus").and_then(|v| v.as_str()));
out.push(Sound {
key,
file,
at,
- volume: volume as f32,
+ volume: volume as f32 * level,
rate: num(props, "data-playback-rate").unwrap_or(1.0),
fade_in: num(props, "data-fade-in").unwrap_or(0.0),
fade_out: num(props, "data-fade-out").unwrap_or(0.0),
diff --git a/sdk/guides/craft/motion/delivery.md b/sdk/guides/craft/motion/delivery.md
index 3b935bf8..54e5295a 100644
--- a/sdk/guides/craft/motion/delivery.md
+++ b/sdk/guides/craft/motion/delivery.md
@@ -18,8 +18,8 @@
`raea check out/launch-9x16.mp4 --manifest out/render.json --shape 9:16 --platform tiktok`.
- Captions: burn them in for feeds that play without sound, unless the delivery controller says captions off; then
burn none, and leave the words file beside the export for the platform's own captions.
-- Sound to -14 LUFS integrated with true peak at or below -1 dBTP: one `<Mix lufs={-14} ceiling={-1.5} />` per
- composition does it (`motion/sound`). A spec that names another number wins.
+- Sound to -14 LUFS integrated with true peak at or below -1 dBTP: raea's mix and master do it on every render
+ (`motion/sound`). A spec that names another number wins: `<Mix lufs={…} ceiling={…} />` sets it.
- Render the export at `--quality master` (motion graphics and type) or `--quality high` (a film), and versions made
for notes with no `--quality` flag; name it in lowercase letters, digits and hyphens, with its shape and length:
`spring-launch-9x16-15s.mp4`. Each version is a new file beside the last, never written over it.
diff --git a/sdk/guides/craft/motion/rendering.md b/sdk/guides/craft/motion/rendering.md
index 67d03113..99fda4b8 100644
--- a/sdk/guides/craft/motion/rendering.md
+++ b/sdk/guides/craft/motion/rendering.md
@@ -24,7 +24,10 @@
- **Without `--manifest`**, `raea render` writes the export alone, without the measurements `raea check` reads. Render
another deliverable from its own file the same way (`raea render NAME.tsx -o NAME.mp4 --manifest NAME.json`) and
check it.
-- **Loudness** comes out at -14 LUFS integrated (±1) with true peak at or below -1 dBTP when `<Mix>` is in the tree.
+- **Loudness** comes out at -14 LUFS integrated (±1) with true peak at or below -1 dBTP: raea levels each line of
+ dialogue (the `voice` bus, or footage on no bus) to the same loudness and masters the piece, so don't measure lines
+ or set `gainDb` to level them, and don't master the voice outside raea. `gainDb` is for a deliberate change, on top
+ of raea's level. `<Mix lufs={…} ceiling={…}>` sets another target.
## Why
diff --git a/sdk/guides/craft/motion/sound.md b/sdk/guides/craft/motion/sound.md
index 2a6fd6fb..c5a9efff 100644
--- a/sdk/guides/craft/motion/sound.md
+++ b/sdk/guides/craft/motion/sound.md
@@ -36,11 +36,14 @@
- Narration over the picture, when the footage has no voice for it, is
`<Speech text="the words" start={frame} />` from `raea/speech` (Pocket TTS, on this computer; `voice` picks a
Pocket voice or a WAV of one).
-- Master the sum with one `<Mix lufs={-14} ceiling={-1.5} />` per composition. It brings the whole mix to -14 LUFS
- integrated and limits true peaks under the ceiling, which is what the floor's loudness defect asks for.
+- raea mixes and masters every render: each line of dialogue (the `voice` bus, or footage on no bus) comes to the same
+ loudness, a join into dead silence gets the room's tone, and the whole mix comes to -14 LUFS integrated with true
+ peaks under -1 dBTP, which is what the floor's loudness defect asks for. Don't level lines with `gainDb` or master
+ the voice outside raea. One `<Mix lufs={…} ceiling={…} />` per composition sets another target.
- Put the sounds in the tree in time order. The engine keys a sound's stretch by its place in the tree, so adding a
sound in the middle of the list can split the ones after it.
-- Balance relative to the voice. The approved pieces, mastered by `<Mix>` to -14 LUFS, sit like this:
+- Balance relative to the voice. The approved pieces, mastered to -14 LUFS, sit like this (each a `gainDb` on top of
+ raea's level for the voice, or on the sound's own level for the rest):
| sound | with a voice | without one (promo, deck, game) |
|---|---|---|
@@ -110,7 +113,6 @@ ends up shouting over the narrator while another is inaudible.
- `loop` on an `<Audio>` without `endAt` to stretch a short ambience: nothing loops, it plays once and stops dead
(the render warns). With `endAt` it repeats with a hard jump at each loop; tile copies with crossfades instead.
- Two `<Mix>` in one composition: it throws.
-- No `<Mix>`: the sum plays as it is, at whatever loudness it adds up to.
- Rewording a `sao()` prompt on every pass. Each new prompt makes a new sound.
- `style` on an `<Audio>`: Audio has no picture and takes no style.
- Hand-placing dozens of game sounds from a log. Cue them from `useGameEvents` (`motion/games`).
diff --git a/sdk/video/src/media.tsx b/sdk/video/src/media.tsx
index 64702492..54432866 100644
--- a/sdk/video/src/media.tsx
+++ b/sdk/video/src/media.tsx
@@ -224,6 +224,9 @@ function useMediaAttrs(owner: string, props: MediaProps, src = props.src as stri
"data-playback-rate": rate,
"data-start-from": props.startFrom ?? props.trimBefore ?? 0,
"data-end-at": props.endAt ?? props.trimAfter,
+ // the clip's span of its source in seconds, where raea's mix measures it to level dialogue (raea-sys-mix level.rs)
+ "data-clip-from": (props.startFrom ?? props.trimBefore ?? 0) / fps,
+ "data-clip-to": endAt === undefined ? undefined : endAt / fps,
"data-loop": props.loop ? "true" : undefined,
"data-muted": props.muted ? "true" : undefined,
"data-ended": t.ended ? "true" : undefined,
diff --git a/systems/mix/Cargo.toml b/systems/mix/Cargo.toml
index 14fb528e..311fa499 100644
--- a/systems/mix/Cargo.toml
+++ b/systems/mix/Cargo.toml
@@ -7,6 +7,8 @@ license = "FSL-1.1-ALv2"
description = "raea's one mixer core: the same Firewheel graph plays live in the device callback and renders offline as the bounce, so a render and a play sound the same, sample for sample (sdk/react/docs/audio-stack.md)"
[dependencies]
+# the mix before the master: dialogue at one level, room tone at the joins
+raea-sys-mix-level = { path = "level" }
# the audio graph: sample-accurate scheduled events, custom nodes, a CPAL stream live and a processor pulled by hand
# offline. 0.12 because bevy_seedling 0.8 pins it: one Firewheel for raea and Bevy. On Bevy 0.20 both are vendored and
# ported (vendor/firewheel*, vendor/bevy_seedling) until their releases catch up.
diff --git a/systems/mix/level/Cargo.toml b/systems/mix/level/Cargo.toml
new file mode 100644
index 00000000..9b7d25ef
--- /dev/null
+++ b/systems/mix/level/Cargo.toml
@@ -0,0 +1,10 @@
+[package]
+name = "raea-sys-mix-level"
+version = "0.1.0"
+edition = "2024"
+license = "FSL-1.1-ALv2"
+publish = false
+description = "raea's mix before its master: dialogue at one level, and the room's tone at a join into dead silence"
+
+[dependencies]
+raea-io-media = { path = "../../../io/media", default-features = false, features = ["soft-audio"] }
diff --git a/systems/mix/level/src/joins.rs b/systems/mix/level/src/joins.rs
new file mode 100644
index 00000000..c30a72f8
--- /dev/null
+++ b/systems/mix/level/src/joins.rs
@@ -0,0 +1,157 @@
+//! Room tone at the joins: a gap the mix drops into digital silence and comes straight back from (two lines of a
+//! take joined with a gap between them) is filled with the room's own tone, the quietest stretch of sound before it.
+//! A dead-silent gap reads as a dropout (11-14: the walkaround's v1; raea check called it one, and the agent rebuilt
+//! the voice outside raea to fill its gaps). The tone is the quietest stretch of sound within LOOK of the gap, before
+//! it or, where the line before runs on without a pause, after it. The gap is the check's dropout exactly (raea check's defects.rs): from
+//! HAD dBFS or more to under SILENT in one 10 ms step, back within two to within 10 dB, 50 ms to 3 s later. A pause that
+//! fades out or in is the edit's own and is left as it is. The render's master fills them (it has the whole bounce);
+//! live play hears the gap.
+use raea_io_media::Audio;
+
+/// The check's dropout: from this level (dBFS, a 10 ms step's RMS) ...
+pub const HAD: f64 = -45.0;
+/// ... to under this
+pub const SILENT: f64 = -80.0;
+/// How far back the room tone is looked for (s), and how long a stretch of it is taken (s)
+const LOOK: f64 = 3.0;
+const TONE: f64 = 0.3;
+/// How far under HAD a gap's edge may be and still be a hard join (dB)
+const EDGE: f64 = 5.0;
+/// A stretch quieter than this is silence, not tone (dBFS)
+const QUIETEST: f64 = -75.0;
+
+fn db(sq: f64) -> f64 {
+ 10.0 * sq.max(1e-20).log10()
+}
+
+/// Each 10 ms step's level (dBFS RMS over the channels)
+fn steps(a: &Audio, hop: usize) -> Vec<f64> {
+ let n = a.len() / hop;
+ let mut out = Vec::with_capacity(n);
+ for k in 0..n {
+ let mut s = 0f64;
+ for c in &a.channels {
+ for v in &c[k * hop..(k + 1) * hop] {
+ s += (*v as f64) * (*v as f64);
+ }
+ }
+ out.push(db(s / (hop * a.channels.len().max(1)) as f64));
+ }
+ out
+}
+
+/// The gaps (first and last step, end exclusive) the check would call dropouts, on steps measured as the master will
+/// play them: a run of dead silence, 50 ms to 3 s, with sound (within EDGE dB of HAD) inside the three steps either
+/// side of it. The check's own grid of steps can split a 12 ms fade where this one doesn't, so the edge is looked for
+/// over 30 ms; a fade that takes longer than that is a pause, and stays.
+pub fn gaps(rms: &[f64]) -> Vec<(usize, usize)> {
+ let loud = |s: &[f64]| s.iter().any(|l| *l >= HAD - EDGE);
+ let mut out = Vec::new();
+ let mut i = 1;
+ while i < rms.len() {
+ if rms[i] >= SILENT || rms[i - 1] < SILENT {
+ i += 1;
+ continue;
+ }
+ let mut j = i + 1;
+ while j < rms.len() && rms[j] < SILENT {
+ j += 1;
+ }
+ if (5..=300).contains(&(j - i)) && loud(&rms[i.saturating_sub(3)..i]) && loud(&rms[j..(j + 3).min(rms.len())]) {
+ out.push((i, j));
+ }
+ i = j.max(i + 1);
+ }
+ out
+}
+
+/// `a` with each dropout filled by the room's tone: the quietest TONE of sound (not silence) in the LOOK before it,
+/// looped with 10 ms crossfades and faded in and out at the gap's edges. Its gaps are found as the master will play
+/// it, `gain` dB up, where the check hears them. Unchanged where there's none.
+pub fn filled(a: &Audio, gain: f64) -> Audio {
+ let hop = (a.rate as usize / 100).max(1);
+ let rms: Vec<f64> = steps(a, hop).into_iter().map(|l| l + gain).collect();
+ let found = gaps(&rms);
+ if found.is_empty() {
+ return a.clone();
+ }
+ let mut out = a.clone();
+ let longest = (TONE * 100.0) as usize;
+ let xf = hop;
+ for (i, j) in found {
+ // the quietest stretch of sound near the gap, before it or after it: the room between words, the longest of
+ // them up to TONE (a line that runs on leaves only short pauses: 120 ms loops well enough under a short gap)
+ let quietest = |tone: usize| {
+ let near = (i.saturating_sub((LOOK * 100.0) as usize)..i.saturating_sub(tone)).chain(j..(j + (LOOK * 100.0) as usize).min(rms.len().saturating_sub(tone)));
+ near.filter(|&s| rms[s..s + tone].iter().all(|l| *l >= QUIETEST && *l < HAD + 15.0)).min_by(|&x, &y| {
+ let m = |s: usize| rms[s..s + tone].iter().sum::<f64>();
+ m(x).total_cmp(&m(y))
+ }).map(|t| (t, tone))
+ };
+ let Some((t, tone)) = [longest, longest * 2 / 3, longest * 2 / 5].into_iter().find_map(quietest) else {
+ continue;
+ };
+ let (src, len) = (t * hop, tone * hop);
+ let (start, end) = (i * hop, (j * hop).min(a.len()));
+ for c in 0..out.channels.len() {
+ for (k, s) in (start..end).enumerate() {
+ // looped, each pass crossfaded into the next; in and out over 10 ms at the gap's edges
+ let (pass, at) = (k / (len - xf), k % (len - xf));
+ let mut v = a.channels[c][src + at];
+ if pass > 0 && at < xf {
+ let w = at as f32 / xf as f32;
+ v = v * w + a.channels[c][src + len - xf + at] * (1.0 - w);
+ }
+ let edge = (k.min(end - s) as f32 / xf as f32).min(1.0);
+ out.channels[c][s] += v * edge;
+ }
+ }
+ }
+ out
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn noise(n: usize, level: f32, seed: &mut u32) -> Vec<f32> {
+ (0..n).map(|_| {
+ *seed = seed.wrapping_mul(1664525).wrapping_add(1013904223);
+ ((*seed >> 8) as f32 / (1u32 << 24) as f32 * 2.0 - 1.0) * level
+ }).collect()
+ }
+
+ /// Two lines with room tone under them and a dead gap between: the gap is filled, and the check's dropout is gone;
+ /// a pause that fades is left alone
+ #[test]
+ fn a_dead_gap_gets_the_room_s_tone() {
+ let rate = 48_000u32;
+ let mut seed = 7;
+ // 1 s of a line (-20 dBFS) with a pause of room tone in it (-65), 0.2 s dead, 1 s more
+ let mut x = noise(rate as usize, 0.1, &mut seed);
+ for v in x[rate as usize / 4..].iter_mut().take(rate as usize / 2) {
+ *v *= 0.01;
+ }
+ x.extend(vec![0.0; rate as usize / 5]);
+ x.extend(noise(rate as usize, 0.1, &mut seed));
+ let a = Audio { rate, channels: vec![x.clone(), x] };
+ let hop = rate as usize / 100;
+ assert_eq!(gaps(&steps(&a, hop)).len(), 1);
+ let f = filled(&a, 0.0);
+ // a gap under the line before the master's gain is still one once it's played: found at the level heard
+ let quiet = Audio { rate, channels: a.channels.iter().map(|c| c.iter().map(|v| v * 0.03).collect()).collect() };
+ assert!(gaps(&steps(&quiet, hop)).is_empty());
+ assert!(!gaps(&steps(&quiet, hop).into_iter().map(|l| l + 30.0).collect::<Vec<_>>()).is_empty());
+ assert!(gaps(&steps(&filled(&quiet, 30.0), hop).into_iter().map(|l| l + 30.0).collect::<Vec<_>>()).is_empty());
+ assert!(gaps(&steps(&f, hop)).is_empty());
+ let gap = &f.channels[0][rate as usize + rate as usize / 20..rate as usize + rate as usize / 10];
+ assert!(gap.iter().any(|v| v.abs() > 1e-4), "the gap holds tone");
+ // a fade to silence and back over 0.3 s is a pause, not a dropout
+ let fade: Vec<f32> = (0..rate as usize * 2).map(|i| {
+ let t = i as f32 / rate as f32;
+ let g = ((t - 1.0).abs() / 0.15).min(1.0);
+ ((i % 97) as f32 / 97.0 - 0.5) * 0.2 * g
+ }).collect();
+ assert!(gaps(&steps(&Audio { rate, channels: vec![fade] }, hop)).is_empty());
+ }
+}
diff --git a/systems/mix/level/src/level.rs b/systems/mix/level/src/level.rs
new file mode 100644
index 00000000..3380d1cd
--- /dev/null
+++ b/systems/mix/level/src/level.rs
@@ -0,0 +1,113 @@
+//! raea's mix, before its master: every line of dialogue at one loudness, so the master brings the whole piece to its
+//! target without a line louder or quieter than the next (11-14: a phone walkaround's lines ran from -13.8 to -26.9
+//! LUFS; the agent measured each and set its gainDb, and the limiter still flattened the loud ones).
+//!
+//! Dialogue is a clip on the voice bus, or footage (a video file's sound) on no bus. It's measured over the span of its
+//! source it plays (BS.1770 integrated loudness, gated, so its pauses don't count) and brought to DIALOGUE, by at most
+//! REACH either way. A clip quieter than ROOM is room tone or a silent take: it keeps its level. Everything else (music,
+//! effects, ambience, anything on another bus) keeps its own level and its bus's settings, which now sit under dialogue
+//! that's always at the same place. A clip's gainDb is an offset on top of the level, never undone by it.
+//!
+//! Live play and the render call the same function on the same span, so they hear the same mix; each span is measured
+//! once a process.
+use std::collections::HashMap;
+use std::path::{Path, PathBuf};
+use std::sync::{Mutex, PoisonError};
+
+/// Where dialogue sits before the master: EBU R128's programme level, the master brings it up to the delivery's
+pub const DIALOGUE: f64 = -23.0;
+/// The most a clip is moved, up or down (dB)
+pub const REACH: f64 = 12.0;
+/// Under this a clip is room tone or silence, not a line (LUFS)
+pub const ROOM: f64 = -45.0;
+/// A span with no end is measured this far
+const OPEN: f64 = 30.0;
+
+/// Each file's measured spans, (from ms, to ms or -1, gain): looked up by the path as it is, without making a key,
+/// since live play asks every frame
+static LEVELS: Mutex<Option<HashMap<PathBuf, Vec<(i64, i64, f32)>>>> = Mutex::new(None);
+
+/// A video file's extension (its sound is the footage's own)
+fn footage(ext: &str) -> bool {
+ for v in ["mov", "mp4", "m4v", "webm", "mkv"] {
+ if ext.eq_ignore_ascii_case(v) {
+ return true;
+ }
+ }
+ false
+}
+
+/// Whether a clip is dialogue: on the voice bus, or a video file's sound on no bus
+pub fn is_dialogue(file: &Path, bus: Option<&str>) -> bool {
+ match bus {
+ Some(b) => b == "voice",
+ None => file.extension().and_then(|x| x.to_str()).is_some_and(footage),
+ }
+}
+
+/// The gain (dB) that brings a clip of `loudness` LUFS to DIALOGUE: 0 for room tone or an unmeasurable span
+pub fn to_dialogue(loudness: f64) -> f64 {
+ if !loudness.is_finite() || loudness < ROOM { 0.0 } else { (DIALOGUE - loudness).clamp(-REACH, REACH) }
+}
+
+fn millis(s: f64) -> i64 {
+ (s * 1000.0).round() as i64
+}
+
+/// A span of `file` measured before: its gain
+fn known(file: &Path, a: i64, b: i64) -> Option<f32> {
+ let levels = LEVELS.lock().unwrap_or_else(PoisonError::into_inner);
+ for s in levels.as_ref()?.get(file)? {
+ if s.0 == a && s.1 == b {
+ return Some(s.2);
+ }
+ }
+ None
+}
+
+/// The linear gain raea's mix puts on a clip playing `file` from `from` to `to` seconds of it (None: to its end, or
+/// OPEN on), on `bus`: dialogue's level, else 1
+pub fn gain(file: &Path, from: f64, to: Option<f64>, bus: Option<&str>) -> f32 {
+ if !is_dialogue(file, bus) {
+ return 1.0;
+ }
+ let (a, b) = (millis(from), to.map_or(-1, millis));
+ if let Some(g) = known(file, a, b) {
+ return g;
+ }
+ let secs = to.map_or(OPEN, |t| (t - from).max(0.4));
+ let loud = raea_io_media::decode_audio_window(file, from.max(0.0), secs).map_or(f64::NAN, |a| raea_io_media::audio::lufs(&a));
+ let g = 10f64.powf(to_dialogue(loud) / 20.0) as f32;
+ LEVELS.lock().unwrap_or_else(PoisonError::into_inner).get_or_insert_with(HashMap::new).entry(file.to_path_buf()).or_default().push((a, b, g));
+ g
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ /// The walkaround's lines, measured 11-14, all come to -23; room tone and silence keep their level; nothing moves
+ /// further than REACH
+ #[test]
+ fn dialogue_comes_to_one_level() {
+ for (line, loud) in [("intro", -22.1), ("ext5", -26.9), ("rear2", -16.4), ("trunk1", -13.8)] {
+ let g = to_dialogue(loud);
+ assert!((loud + g - DIALOGUE).abs() < 1e-9, "{line}: {loud} + {g}");
+ }
+ assert_eq!(to_dialogue(-50.0), 0.0);
+ assert_eq!(to_dialogue(f64::NEG_INFINITY), 0.0);
+ assert_eq!(to_dialogue(-40.0), REACH);
+ assert_eq!(to_dialogue(0.0), -REACH);
+ }
+
+ /// Dialogue is the voice bus, or footage on no bus; music, effects and ambience keep their own level
+ #[test]
+ fn what_is_dialogue() {
+ assert!(is_dialogue(Path::new("take.MOV"), None));
+ assert!(is_dialogue(Path::new("vo.wav"), Some("voice")));
+ assert!(!is_dialogue(Path::new("song.mp3"), None));
+ assert!(!is_dialogue(Path::new("take.mov"), Some("music")));
+ assert!(!is_dialogue(Path::new("hit.wav"), Some("sfx")));
+ assert_eq!(gain(Path::new("song.mp3"), 0.0, None, None), 1.0);
+ }
+}
diff --git a/systems/mix/level/src/lib.rs b/systems/mix/level/src/lib.rs
new file mode 100644
index 00000000..4dbd1db1
--- /dev/null
+++ b/systems/mix/level/src/lib.rs
@@ -0,0 +1,5 @@
+//! raea's mix before its master (raea-sys-mix masters it): every line of dialogue at one level (level.rs) and the
+//! room's tone at a join the mix drops into dead silence (joins.rs). Live play and the render level clips the same way;
+//! the render's master fills the joins.
+pub mod joins;
+pub mod level;
diff --git a/systems/mix/src/lib.rs b/systems/mix/src/lib.rs
index 4cc29f4c..4b4ff354 100644
--- a/systems/mix/src/lib.rs
+++ b/systems/mix/src/lib.rs
@@ -7,6 +7,7 @@
//! Neural models never sit here: generated sound is rendered once, cached as PCM keyed by its inputs, and comes in as a
//! plain source like any file (sdk/react/docs/audio-stack.md).
+pub use raea_sys_mix_level::{joins, level};
pub mod live;
pub mod nodes;
pub mod offline;
@@ -17,7 +18,7 @@ use std::sync::Arc;
/// The version of the core's mastering (a raw bounce, its gain, the limiter): caches of a master or a mastered track
/// carry it, so one an earlier core made isn't taken for this one's.
-pub const MASTER_VERSION: u32 = 3;
+pub const MASTER_VERSION: u32 = 4;
/// The core's rate: a render's bounce, and live play when the device takes it.
pub const RATE: u32 = 48_000;
diff --git a/systems/mix/src/nodes/limiter.rs b/systems/mix/src/nodes/limiter.rs
index b7044533..41e7a5fb 100644
--- a/systems/mix/src/nodes/limiter.rs
+++ b/systems/mix/src/nodes/limiter.rs
@@ -18,8 +18,19 @@ pub struct Limiter {
/// each channel's last TAPS samples in
hist: [[f32; TAPS]; 2],
taps: [[f32; TAPS]; 3],
+ /// the leveller's mean square of the mix, followed
+ env: f32,
}
+/// The leveller ahead of the limiter (raea's master, 11-19): from LEVEL dB under the ceiling, RATIO to 1 on the mix's
+/// RMS (ATTACK in, RELEASE out), so phone speech brought up to a delivery's loudness rounds its peaks instead of the
+/// limiter flattening them (the walkaround's lines peaked 15-19 dB over their loudness: the limiter alone flat-topped
+/// them, and raea check found the sound clipping). Under it, nothing changes.
+pub const LEVEL: f32 = 9.0;
+pub const RATIO: f32 = 3.0;
+pub const ATTACK: f64 = 0.010;
+pub const RELEASE: f64 = 0.150;
+
const TAPS: usize = 12;
impl Default for Limiter {
@@ -41,7 +52,7 @@ impl Limiter {
*t = (sinc * w) as f32;
}
}
- Limiter { delay: Vec::new(), need: Vec::new(), at: 0, gain: 1.0, pre: 1.0, ceiling: CEILING, hist: [[0.0; TAPS]; 2], taps }
+ Limiter { delay: Vec::new(), need: Vec::new(), at: 0, gain: 1.0, pre: 1.0, ceiling: CEILING, hist: [[0.0; TAPS]; 2], taps, env: 0.0 }
}
pub fn run(&mut self, l: &mut [f32], r: &mut [f32], rate: f64) {
@@ -56,8 +67,16 @@ impl Limiter {
// aimed 0.26 dB under: the 12-tap meter reads a peak between samples up to ~1% low
let (pre, ceiling) = (self.pre, self.ceiling * 0.97);
let need = |v: f32| if v > ceiling { ceiling / v } else { 1.0 };
+ let (up, down) = ((1.0 - (-1.0 / (ATTACK * rate)).exp()) as f32, (1.0 - (-1.0 / (RELEASE * rate)).exp()) as f32);
+ let floor = (self.ceiling * 10f32.powf(-LEVEL / 20.0)).powi(2);
for i in 0..l.len() {
- let frame = [l[i] * pre, r[i] * pre];
+ let mut frame = [l[i] * pre, r[i] * pre];
+ let p = 0.5 * (frame[0] * frame[0] + frame[1] * frame[1]);
+ self.env += if p > self.env { up } else { down } * (p - self.env);
+ if self.env > floor {
+ let lg = (floor / self.env).powf(0.5 * (1.0 - 1.0 / RATIO));
+ frame = [frame[0] * lg, frame[1] * lg];
+ }
// the sample leaving the window: its own need, settled
let own = self.need[self.at];
let late = std::mem::replace(&mut self.delay[self.at], frame);
diff --git a/systems/mix/src/offline.rs b/systems/mix/src/offline.rs
index 469f52ff..e777c0d5 100644
--- a/systems/mix/src/offline.rs
+++ b/systems/mix/src/offline.rs
@@ -181,15 +181,31 @@ pub fn master_raw(raw: &raea_io_media::Audio, master: Option<(f64, f64)>) -> rae
raea_io_media::Audio { rate: raw.rate, channels: vec![l, r] }
}
+/// What raea masters a piece to when it has no <Mix>: the major platforms' loudness (LUFS) and a -1 dBTP ceiling
+pub const MIX: (f64, f64) = (-14.0, -1.0);
+
/// The master over a raw bounce, the one function every render uses (react's fed and page renders, raea-render's SQL renders, a
/// play's master-gain): with a <Mix> (`mix`: target LUFS, ceiling dBTP), the gain from the raw sound to the target, then
/// the limiter at the ceiling, the ceiling lowered by any overshoot `encode` (an AAC round trip) puts back (twice at most);
-/// without one, the live default. Returns the master it used and the mastered sound.
+/// without one, MIX; the leveller (nodes::LEVEL) rounds the loud passages first, and the gain is made up for what it
+/// took. Returns the master it used and the mastered sound.
pub fn master_mix(raw: &raea_io_media::Audio, mix: Option<(f64, f64)>, encode: Option<&dyn Fn(&raea_io_media::Audio) -> Result<raea_io_media::Audio, String>>) -> (Option<(f64, f64)>, raea_io_media::Audio) {
- let Some((lufs, ceiling)) = mix.filter(|_| raea_io_media::audio::lufs(raw).is_finite()) else { return (None, master_raw(raw, None)) };
- let gain = raea_io_media::audio::master_gained(raw, lufs, ceiling).1;
+ // raea masters whatever it renders (11-19): without a <Mix>, to MIX's loudness and ceiling
+ let Some((lufs, ceiling)) = mix.or(Some(MIX)).filter(|_| raea_io_media::audio::lufs(raw).is_finite()) else { return (None, master_raw(raw, None)) };
+ let mut gain = raea_io_media::audio::master_gained(raw, lufs, ceiling).1;
+ // a join the mix drops into dead silence gets the room's tone, found at the level the master plays it (joins.rs)
+ let raw = &crate::joins::filled(raw, gain);
+ let mut a = master_raw(raw, Some((gain, ceiling)));
+ // the leveller takes a little loudness with the peaks: made up, twice at most
+ for _ in 0..2 {
+ let got = raea_io_media::audio::lufs(&a);
+ if !got.is_finite() || (got - lufs).abs() <= 0.2 {
+ break;
+ }
+ gain += lufs - got;
+ a = master_raw(raw, Some((gain, ceiling)));
+ }
let mut master = Some((gain, ceiling));
- let mut a = master_raw(raw, master);
if let Some(enc) = encode {
let mut c = ceiling;
for _ in 0..2 {
diff --git a/tools/layers.toml b/tools/layers.toml
index bc4ca261..5f98496a 100644
--- a/tools/layers.toml
+++ b/tools/layers.toml
@@ -50,6 +50,7 @@ raea-core-calls = "core"
raea-core-brief = "core"
raea-sys-k = "systems"
raea-sys-mix = "systems"
+raea-sys-mix-level = "systems"
raea-sys-tone = "systems"
raea-seedling = "systems"
raea-sys-ml = "systems"
@@ -263,6 +264,8 @@ raea-sys-volume = true
# the scene's ray tracing (the traced-light pass reads its scene)
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
raea-sys-tone = true
raea-sys-ml = true
raea-sys-mlx = true