forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

hear.rs6244 lines, 280.1 KiBHistoryRawDownload
1//! Hear tools: `levels` (how loud the sound is over time), `silence` (where it is
2//! quiet, in timeline frames) and `cut_silence` (cut those stretches out of the
3//! timeline as one undo step).
4//!
5//! Silence is found per clip, the way the GUI's silence card does it
6//! (`player/cards.rs::scan_silences`): each clip's own in..out range is read with
7//! `silence::levels`, the quiet runs become timeline frames through
8//! `silence::timeline_regions` (which applies the clip's in point and speed), and
9//! the cut goes to `cut_regions` on every lane, or the lanes named, as one edit.
10//! A lane, and the mix, are read along the timeline instead: gaps between clips
11//! are silence there, so they are found and cut too.
12
13use std::time::Instant;
14
15pub(crate) use engine::normalize::{offline_refusal, offline_refusal_for};
16use engine::limiter::Limiter;
17use engine::loudness::{self, Loudness, gain_to_target};
18use engine::normalize::{Plan, duck_offsets, measure_lane, measure_mix, plan_of, render_mix, set_plans, shifted};
19use engine::project::{
20 GainKey, Lane, LaneKind, MAX_CLIP_GAIN_DB, MAX_GAIN_DB, MIN_GAIN_DB, RedoCheckpoint, gain_keys_db_at,
21};
22use engine::silence::{self, SILENT_DB, Settings, WINDOWS_PER_SEC};
23use engine::{Clip, PlaybackSession, Speed};
24use serde_json::{Value, json};
25
26use crate::parse;
27use crate::server::{Entry, Reply, Server, Tool, opt_bool, opt_f64, opt_str, tri};
28
29const NO_PROJECT: &str = "no project open — call project_open or project_new first";
30
31/// Reply text stays under this, per MCP.md 3.3.
32const CAP: usize = 4096;
33/// Silence lines listed before the rest are counted.
34const MAX_LINES: usize = 60;
35/// Values kept in the structured `levels` output.
36const MAX_VALUES: usize = 6000;
37
38const LEVELS_DOC: &str = r#"Loudness over time: RMS dBFS per 20 ms window, grouped into per_sec values (power mean of each group), as text rows plus a summary.
39target: a clip (A1@0) reads its own sound over its in..out span; a lane (A1) reads its clips in timeline time, with gaps as -120; src:N reads the whole source file, and range is then in source time; mix reads the timeline as exported (every unmuted lane at its gain), rendered to a temporary WAV first.
40Clip gain, its volume envelope and lane gain are added to the levels of an audio clip or lane (so they read as played), and a lane under a duck includes the duck's dips, as the mix plays it; fades and the equalizer are not, use loudness for those.
41range {from,to}: narrows the span. Timeline frames for a clip, lane or mix, source time for src:N. Defaults to the whole span.
42per_sec: a number, the buckets per second (how many values each second of sound gets), e.g. 10; default 2, max 50. The text is capped near 4 KB; a coarser per_sec shows the rest.
43target is required. Read only; changes nothing."#;
44
45const SILENCE_DOC: &str = r#"Find the quiet stretches (silence) in the sound, per clip, and list them as timeline frames. Read only.
46target: a clip (A1@0), a lane (A1, the default), src:N, or mix. A lane is judged inside its clips only: the timeline gaps between clips are structure, not silence, so they are never listed (the reply names how many were left alone). src:N scans the source file's own sound from its start, so its times are source time (frames at the timeline fps), not timeline time. mix scans the timeline as exported, every unmuted lane together, in timeline time (rendered to a temporary WAV first).
47Clip gain, its volume envelope and lane gain are applied to the sound before it is judged, so a quiet clip reads quiet as it plays, and a lane under a duck is judged with the duck (fades and the equalizer are not).
48threshold_db: at or below this is quiet. Default: measured from the target, 30 dB under its median speech level (windows above -60 dBFS), kept between -90 and -10; the reply names the threshold used. min_silence: a quiet run shorter than this is ignored, judged before the padding is taken off (default 0.5 s). padding: kept at both ends of each quiet run, so a cut never touches speech (default 0.15 s). min_keep: a kept sliver shorter than this joins the silences either side of it (default 0: no joins).
49Structured regions are [from, to] pairs of frame strings such as "450f", exactly what edit's cut_regions op takes (a JSON number there would be seconds, so these are strings on purpose)."#;
50
51const CUT_SILENCE_DOC: &str = r#"Tighten the silences that silence finds on the timeline, as one undo step. The regions are exactly those silence reports for the same target and settings (the target defaults to lane A1). Each silence is cut back so the pause left in it is keep seconds, a natural pause surviving as a short beat instead of being removed; a silence at or under keep is left alone. Only the sound inside clips is judged: the timeline gaps between a lane's clips (a lead-in, the space between takes) are structure, never cut, and the reply names how many were left alone. src:N is refused: a source is not on the timeline, so silence it for its times and cut the lane or clip that plays it. Caption lanes ripple with the cut; locked caption lanes stay.
52keep: the TOTAL pause left in each silence, in seconds, padding included (0.05 to 10, default 0.4; to delete pauses entirely use cut_regions). The padding at each end of a silence is never cut and counts toward keep: a 0.4 s keep with 0.15 s padding leaves 0.15 s at each end and 0.10 s of quiet between them, 0.40 s in all. When keep is under twice the padding, the pause left is 2 × padding, the least a cut can leave. A silence that runs to the end of its clip keeps keep in all after the last speech (its end padding is part of that), so a tail never shrinks under keep. The reply measures it.
53force: a cut that would remove more than half the target's sound is refused, with its spans named, so a threshold that is too loose cannot wipe a take. force:true cuts anyway.
54lanes: the lanes to cut. With a target, lanes is the RIPPLE SCOPE: the silence is judged on the target alone, and the same spans are cut on every listed lane (the target's own lane is added when it is not listed). Default with no lanes: the target's lane and the lanes of clips linked (grouped) to it, so linked video follows the sound while picture-only B-roll stays put; a mix target cuts every lane. A take must stay whole, or the engine refuses and says why; a lane not named never moves, and the reply names it as left in place (a music bed: name it in lanes to move it too).
55JOINT CUT: lanes:["A1","A2"] (two speakers in a conversation, say) with no target. The silence is where EVERY listed audio lane is quiet at once: each lane is judged on its own clips at its own threshold (or threshold_db for all when given), and a timeline gap on a lane counts as quiet for it, so the joint silence is a stretch where the other listed lanes are quiet too, and a stretch where no listed lane has a clip is never cut. The cut is made on the listed lanes together, so their turns stay in step. A video lane in a joint list is cut with the spans but not judged, and a joint cut needs two or more audio lanes in its list. A target with lanes is never a joint cut: there lanes is the ripple scope, judged on the target alone. Locks follow the ripple rule: a locked target, or a locked lane named in lanes, refuses the cut with the lane_flags way out; a mix's default scope (every lane) refuses the same way, naming each locked lane, and changes nothing.
56dry_run: report what would be cut, then roll back. Nothing changed and no undo step is added.
57The reply names the pause each cut left as "pauses now X s", measured back from the sound after the cut: the lane's for a lane or clip, the mix as exported for a mix, the joint quiet for a joint cut (frames are 1/fps, so a keep that is not a whole frame reads a frame over at most).
58mode: cut (default, as above) · speed_up: each silence plays at rate (1.05–4, default 4) instead of being cut, the room it no longer needs closed, as the GUI's speed silences do; keep and force do not apply, and titles keep their times · keep_silence: the speech is cut and the silence kept, the GUI's keep-only silence; one target only (no joint cut), its share guard does not apply since the speech is the point. Both take dry_run and undo as cut does."#;
59
60/// The pause cut_silence leaves at each cut when neither `keep` nor `padding` is given.
61const DEFAULT_KEEP: f64 = 0.4;
62
63const LOUDNESS_DOC: &str = r#"EBU R128 loudness of the sound (integrated LUFS, loudness range, true peak, max momentary and short-term). Read only.
64target: a clip (A1@0), a lane (A1), src:N (a whole source file), or "mix" (the timeline as exported, every unmuted lane at its gain).
65A clip or lane reads as it plays: clip speed, clip gain and envelope, clip fades, equalizer, lane gain and the lane's duck all included (a lane reads its clips with their gains; a clip reads its own span). A video clip reads its source's sound through its in point and speed, with no gain of its own.
66range {from,to}: narrows the span. Timeline frames for a clip, lane or mix; source frames for src:N.
67target is required: a clip (A1@0), a lane (A1), src:N, or mix.
68"mix" renders the whole timeline to a temporary WAV first, so it takes about as long as an export of the sound. Figures show "silent" where there is no energy."#;
69
70const NORMALIZE_DOC: &str = r#"Set the volume so the sound measures a target loudness. Changes lane gain; a boost past the lane's +12 dB cap goes on that lane's clips as clip gain (each up to +24 dB, added to what the clip has), in the same undo step. One undo step. dry_run:true measures and reports the planned gain per lane (predicted from the measurement) and changes nothing.
71target: a lane (A1: its gain moves), or "mix" (every unmuted audio lane with clips moves by the same dB, so the mix as a whole lands on the target).
72lufs: integrated target, default -14. true_peak: ceiling in dBTP, default -1; the gain is cut back if the peak would pass it.
73allow_limiter (target mix only): when the true peak is what holds the gain back, or the mix already sits over the true_peak ceiling (a clipped mix), switch the master limiter on with its true-peak ceiling at the true_peak value and re-gain with it in circuit, all in the same undo step. When the master limiter is already on, a mix normalize counts on it without the flag, at the lower of the limiter's ceiling and true_peak. The limiter's detector is the same 8x true-peak meter the reply reads, so it holds the mix at or under true_peak; a measured overshoot still lowers its ceiling. The limiter is a mix-wide setting, so it is left on afterwards, at the true-peak ceiling reported in the reply.
74The figures in the reply are measured after the change, not predicted; when the level misses the target by more than 0.1 LU or the peaks pass the ceiling, the gain is corrected up to eight times; with the limiter on, a true-peak overshoot lowers the limiter's ceiling (down to -12 dBFS) instead of the gain.
75Structured output: target, lufs (asked), achieved_lufs, reached (within 0.1 LU and under the ceiling), short_by_lu, capped_by (true_peak, limiter, clip_gain_limit, lane_gain_limit or null), clip_gain (the clips that took a boost: clip, change_db), limiter (the setting it switched on, or null), measured_true_peak_dbtp, refinements.
76Common targets: YouTube and Spotify -14 LUFS, Apple Music -16, EBU R128 broadcast -23.
77Lane gain stays within -60..+12 dB: the rest of a boost goes on the lane's clips, each within +24 dB; the reply names the split (lane gain, then clip gain per clip). A lane held at both limits is reported with what it wanted and what it reached."#;
78
79/// What a `target` names: one clip, a whole lane, every clip of one source, or the
80/// whole timeline as exported.
81#[derive(Clone)]
82#[allow(clippy::large_enum_variant)] // Clip grew with its effects stack; these are short-lived
83enum Target {
84 Clip(Lane, Clip),
85 Lane(Lane),
86 Source(usize),
87 Mix,
88}
89
90// ---- schemas --------------------------------------------------------------
91
92fn settings_props() -> serde_json::Map<String, Value> {
93 match json!({
94 "threshold_db": {
95 "type": "number", "minimum": -120, "maximum": 0,
96 "description": "At or below this level (dBFS) a window is quiet. Default: 30 dB under the target's median speech level, between -90 and -10; the reply names the value used."
97 },
98 "min_silence": {
99 "type": "number", "minimum": 0, "maximum": 60,
100 "description": "A quiet run shorter than this many seconds is ignored (judged before the padding). Default 0.5."
101 },
102 "padding": {
103 "type": "number", "minimum": 0, "maximum": 10,
104 "description": "Seconds kept at each end of a silence so a cut never touches speech. Default 0.15."
105 },
106 "min_keep": {
107 "type": "number", "minimum": 0, "maximum": 10,
108 "description": "Kept sound shorter than this many seconds joins the silences around it. Default 0 (no joins)."
109 }
110 }) {
111 Value::Object(m) => m,
112 _ => serde_json::Map::new(),
113 }
114}
115
116fn target_prop(default: &str) -> Value {
117 json!({
118 "type": "string",
119 "description": format!("A clip address (A1@0), a lane (A1), src:N for a whole source file, or \"mix\" for the timeline as exported. Default {default}.")
120 })
121}
122
123fn levels_schema() -> Value {
124 json!({
125 "type": "object",
126 "properties": {
127 "target": {
128 "type": "string",
129 "description": "A clip address (A1@0), a lane (A1), src:N for a whole source file, or \"mix\" for the timeline as exported."
130 },
131 "range": {
132 "type": "object",
133 "description": "Optional span. Timeline times for a clip, lane or mix, source times for src:N.",
134 "properties": {
135 "from": { "description": "Start, e.g. 450f, 15.0s or 15." },
136 "to": { "description": "End, e.g. 900f, 30.0s or end." }
137 }
138 },
139 "per_sec": {
140 "type": "number", "exclusiveMinimum": 0, "maximum": 50, "examples": [10],
141 "description": "Buckets per second: a number, how many values each second of sound gets (e.g. 10 for ten per second). Default 2, max 50. Higher is finer and longer."
142 }
143 },
144 "required": ["target"]
145 })
146}
147
148fn silence_schema() -> Value {
149 let mut props = settings_props();
150 props.insert("target".into(), target_prop("A1"));
151 json!({ "type": "object", "properties": props })
152}
153
154fn cut_silence_schema() -> Value {
155 let mut props = settings_props();
156 props.insert("target".into(), target_prop("A1"));
157 props.insert(
158 "keep".into(),
159 json!({
160 "type": "number", "minimum": 0.05, "maximum": 10,
161 "description": "The total pause left in each silence, in seconds, padding included (cut back to this, not removed; 0.05 to 10). Default 0.4. The padding at each end is never cut and counts toward it."
162 }),
163 );
164 props.insert(
165 "force".into(),
166 json!({ "type": "boolean", "description": "Cut even when it would remove more than half the target's sound (refused otherwise)." }),
167 );
168 props.insert(
169 "lanes".into(),
170 json!({
171 "type": "array",
172 "items": { "type": "string" },
173 "description": "Lanes to cut, e.g. [\"V1\", \"A1\"]. With a target, these are the ripple scope: the silence is judged on the target alone and the same spans are cut on each listed lane (the target's lane is added if not listed). With no target, two or more audio lanes make a JOINT cut: the silence is where every listed audio lane is quiet at once (a gap on a lane counts as quiet; a stretch with no listed clip is never cut), cut from the listed lanes together, so their turns stay in step; a video lane in that list is cut with the spans but not judged. Default with no lanes: the target's lane and the lanes of clips linked to it; a mix target defaults to every lane. A lane not listed never moves and is reported. A locked lane named here refuses the cut (unlock it with lane_flags); a locked lane the default scope reaches through a link refuses too, and a mix's default scope (every lane) refuses the same way."
174 }),
175 );
176 props.insert(
177 "dry_run".into(),
178 json!({ "type": "boolean", "description": "Report what would be cut, then roll back." }),
179 );
180 props.insert(
181 "mode".into(),
182 json!({
183 "type": "string",
184 "enum": ["cut", "speed_up", "keep_silence"],
185 "description": "cut (default): shorten each silence to keep. speed_up: play each silence at rate instead of cutting it (the GUI's speed-silences). keep_silence: cut the speech and keep the silence (the GUI's keep-only silence); one target only."
186 }),
187 );
188 props.insert(
189 "rate".into(),
190 json!({
191 "type": "number", "minimum": 1.05, "maximum": 4,
192 "description": "mode speed_up only: the speed each silence plays at, 1.05 to 4. Default 4 (the GUI's default)."
193 }),
194 );
195 json!({ "type": "object", "properties": props })
196}
197
198fn loudness_schema() -> Value {
199 json!({
200 "type": "object",
201 "properties": {
202 "target": {
203 "type": "string",
204 "description": "Required. A clip address (A1@0), a lane (A1), src:N for a whole source file, or \"mix\" for the timeline as exported."
205 },
206 "range": {
207 "type": "object",
208 "description": "Optional span. Timeline times for a clip, lane or mix; source times for src:N.",
209 "properties": {
210 "from": { "description": "Start, e.g. 450f, 15.0s or 15." },
211 "to": { "description": "End, e.g. 900f, 30.0s or end." }
212 }
213 }
214 },
215 "required": ["target"]
216 })
217}
218
219fn normalize_schema() -> Value {
220 json!({
221 "type": "object",
222 "properties": {
223 "dry_run": {
224 "type": "boolean",
225 "description": "Measure and report the gain each lane would move by, then change nothing (no undo step)."
226 },
227 "target": {
228 "type": "string",
229 "description": "A lane (A1) whose gain moves, or \"mix\" for every unmuted audio lane together."
230 },
231 "allow_limiter": {
232 "type": "boolean",
233 "description": "Target mix only. If the true peak holds the gain back, turn the master limiter on with its true-peak ceiling at the true_peak value and re-gain, in one undo step. Default false. Not needed when the master limiter is already on: a mix normalize counts on it."
234 },
235 "lufs": {
236 "type": "number", "minimum": -70, "maximum": 0,
237 "description": "Integrated loudness to reach, LUFS. Default -14 (YouTube, Spotify). Apple Music -16, EBU R128 broadcast -23."
238 },
239 "true_peak": {
240 "type": "number", "minimum": -20, "maximum": 0,
241 "description": "True-peak ceiling in dBTP. Default -1."
242 },
243 "each": {
244 "type": "boolean",
245 "description": "With lanes: set each listed lane on its own, so each one alone measures lufs over its clips (its own gain moves, one undo step). Needs lanes; not with target or allow_limiter."
246 },
247 "lanes": {
248 "type": "array", "items": { "type": "string" },
249 "description": "With each:true: the audio lanes to set, such as [\"A1\",\"A2\"]."
250 }
251 }
252 })
253}
254
255pub fn tools() -> Vec<Tool> {
256 vec![
257 Tool {
258 name: "levels",
259 description: LEVELS_DOC,
260 schema: levels_schema,
261 run: run_levels,
262 },
263 Tool {
264 name: "silence",
265 description: SILENCE_DOC,
266 schema: silence_schema,
267 run: run_silence,
268 },
269 Tool {
270 name: "cut_silence",
271 description: CUT_SILENCE_DOC,
272 schema: cut_silence_schema,
273 run: run_cut_silence,
274 },
275 Tool {
276 name: "loudness",
277 description: LOUDNESS_DOC,
278 schema: loudness_schema,
279 run: run_loudness,
280 },
281 Tool {
282 name: "normalize",
283 description: NORMALIZE_DOC,
284 schema: normalize_schema,
285 run: run_normalize,
286 },
287 ]
288}
289
290// ---- targets --------------------------------------------------------------
291
292fn fail(e: String) -> Reply {
293 Reply::err(e)
294}
295
296fn source_name(s: &PlaybackSession, n: usize) -> String {
297 s.sources()
298 .get(n)
299 .and_then(|src| src.path.file_name())
300 .map(|f| f.to_string_lossy().into_owned())
301 .unwrap_or_default()
302}
303
304/// What `src:N` is missing from: how many sources the project has, and which they are.
305fn source_hint(s: &PlaybackSession) -> String {
306 source_count_note(s.sources().len())
307}
308
309fn source_count_note(count: usize) -> String {
310 match count {
311 0 => "this project has no sources".into(),
312 1 => "this project has 1 source (src:0)".into(),
313 _ => format!("this project has {count} sources (src:0..src:{})", count - 1),
314 }
315}
316
317/// The refusal for a `src:N` past the project's sources, worded like listen's.
318fn no_source(s: &PlaybackSession, n: usize) -> String {
319 format!("no source src:{n}: {}", source_hint(s))
320}
321
322fn lane_ok(s: &PlaybackSession, lane: Lane, name: &str) -> Result<(), String> {
323 if !s.lanes().contains(&lane) {
324 return Err(format!("no lane {name} on this timeline"));
325 }
326 if lane.kind == LaneKind::Subtitle {
327 return Err(format!("{name} is a caption lane; scan a media lane"));
328 }
329 Ok(())
330}
331
332/// The one parser of `target` for every hear tool: `mix`, `src:N`, a clip address
333/// (A1@0 or A1#0), or a lane (A1).
334fn resolve(s: &PlaybackSession, raw: &str) -> Result<Target, String> {
335 let t = raw.trim();
336 if is_mix(t) {
337 return Ok(Target::Mix);
338 }
339 if let Some(rest) = t.strip_prefix("src:") {
340 let digits: String = rest
341 .trim()
342 .chars()
343 .take_while(char::is_ascii_digit)
344 .collect();
345 let n = digits
346 .parse::<usize>()
347 .map_err(|_| format!("`{t}` is not a source: write src:N"))?;
348 if n >= s.sources().len() {
349 return Err(no_source(s, n));
350 }
351 return Ok(Target::Source(n));
352 }
353 if t.contains(['@', '#']) {
354 let (lane, idx) = parse::clip(s, t)?;
355 if lane.kind == LaneKind::Subtitle {
356 return Err(format!("{t} is a caption; scan a media clip"));
357 }
358 let clip = s
359 .lane_clips(lane)
360 .get(idx)
361 .cloned()
362 .ok_or_else(|| format!("no media clip at {t}"))?;
363 return Ok(Target::Clip(lane, clip));
364 }
365 let lane = parse::lane(t)?;
366 lane_ok(s, lane, t)?;
367 Ok(Target::Lane(lane))
368}
369
370/// The `target` argument, or A1 when it is left out (the silence default).
371fn target_arg(s: &PlaybackSession, args: &Value) -> Result<Target, String> {
372 match args.get("target") {
373 None | Some(Value::Null) => {
374 lane_ok(s, Lane::A1, "A1")?;
375 Ok(Target::Lane(Lane::A1))
376 }
377 Some(Value::String(t)) => resolve(s, t),
378 Some(_) => Err("`target` must be a clip address (A1@0), a lane (A1), src:N or mix".into()),
379 }
380}
381
382fn label(s: &PlaybackSession, t: &Target) -> String {
383 match t {
384 Target::Clip(l, c) => parse::addr(*l, c.start),
385 Target::Lane(l) => parse::lane_name(*l),
386 Target::Source(n) => format!("src:{n} {}", source_name(s, *n)),
387 Target::Mix => "mix".into(),
388 }
389}
390
391/// The clips a clip or lane target covers. A source or the mix is read as a file,
392/// not clip by clip, so it has none here.
393fn clips_of(s: &PlaybackSession, t: Target) -> Vec<(Lane, Clip)> {
394 match t {
395 Target::Clip(l, c) => vec![(l, c)],
396 Target::Lane(l) => s.lane_clips(l).iter().map(|c| (l, c.clone())).collect(),
397 Target::Source(_) | Target::Mix => Vec::new(),
398 }
399}
400
401/// The dB a clip's sound moves by on its way out: its clip gain plus its lane
402/// gain, on an audio lane. Video has neither, so it is 0. Fades and the
403/// equalizer are not in it; `loudness` reads those.
404fn played_offset(s: &PlaybackSession, lane: Lane, clip: &Clip) -> f32 {
405 if lane.kind != LaneKind::Audio {
406 return 0.0;
407 }
408 let idx = s
409 .lane_clips(lane)
410 .iter()
411 .position(|c| c.start == clip.start);
412 let clip_db = idx.and_then(|i| s.clip_gain_of(lane, i)).unwrap_or(0.0);
413 clip_db + s.lane_gain_db(lane)
414}
415
416/// The loudness of one clip's own source range, one value per 20 ms window from
417/// its in point, with the clip's gain and its lane's gain applied (see
418/// `played_offset`). `None` for a file with no audio track.
419fn read(
420 s: &PlaybackSession,
421 lane: Lane,
422 clip: &Clip,
423 fps: f64,
424) -> Result<Option<Vec<f32>>, String> {
425 if let Some(why) = offline_refusal_for(s, parse::addr(lane, clip.start), &[clip.source]) {
426 return Err(why);
427 }
428 let src = s.sources().get(clip.source).ok_or_else(|| {
429 format!(
430 "a clip uses src:{}, which is not on the timeline",
431 clip.source
432 )
433 })?;
434 let range = (
435 f64::from(clip.in_frame) / fps,
436 f64::from(clip.out_frame) / fps,
437 );
438 let levels = silence::levels(&src.path, src.audio_stream, range).map_err(|e| {
439 format!(
440 "reading the sound of src:{} {}: {e}",
441 clip.source,
442 source_name(s, clip.source)
443 )
444 })?;
445 let off = played_offset(s, lane, clip);
446 // The volume envelope varies over the clip, so each window reads it at its own
447 // source time: window i starts i windows past the in point.
448 let keys = clip_keys(s, lane, clip);
449 let window = 1.0 / f64::from(WINDOWS_PER_SEC);
450 Ok(levels.map(|v| {
451 if off == 0.0 && keys.is_empty() {
452 return v;
453 }
454 v.into_iter()
455 .enumerate()
456 .map(|(i, x)| {
457 if x > SILENT_DB {
458 let env = if keys.is_empty() {
459 0.0
460 } else {
461 gain_keys_db_at(keys, f64::from(clip.in_frame) + i as f64 * window * fps)
462 };
463 (x + off + env).max(SILENT_DB)
464 } else {
465 x
466 }
467 })
468 .collect()
469 }))
470}
471
472/// The clip's own volume envelope, or none for a video clip or one with no points.
473fn clip_keys<'a>(s: &'a PlaybackSession, lane: Lane, clip: &Clip) -> &'a [GainKey] {
474 if lane.kind != LaneKind::Audio {
475 return &[];
476 }
477 s.lane_clips(lane)
478 .iter()
479 .position(|c| c.start == clip.start)
480 .map_or(&[][..], |i| s.gain_keys_of(lane, i))
481}
482
483// ---- silence --------------------------------------------------------------
484
485fn settings_arg(args: &Value) -> Result<Settings, String> {
486 let d = Settings::default();
487 let get = |k: &str, dv: f64, lo: f64, hi: f64| -> Result<f64, String> {
488 match args.get(k) {
489 None | Some(Value::Null) => Ok(dv),
490 Some(v) => {
491 let x = v
492 .as_f64()
493 .ok_or_else(|| format!("`{k}` must be a number"))?;
494 if !x.is_finite() || x < lo || x > hi {
495 Err(format!("`{k}` {x} is out of range; it must be {lo} to {hi}"))
496 } else {
497 Ok(x)
498 }
499 }
500 }
501 };
502 Ok(Settings {
503 threshold_db: get("threshold_db", f64::from(d.threshold_db), -120.0, 0.0)? as f32,
504 min_silence: get("min_silence", d.min_silence, 0.0, 60.0)?,
505 padding: get("padding", d.padding, 0.0, 10.0)?,
506 min_keep: get("min_keep", 0.0, 0.0, 10.0)?,
507 })
508}
509
510/// The silent stretches silence reports. `min_silence` is judged on the quiet run itself, before
511/// the padding is taken off its ends (the engine does that): a 0.4 s pause is a pause at a 0.3 s
512/// minimum even though 0.1 s of it is padding. Counting the padding first dropped every short
513/// narration pause.
514fn regions_of(levels: &[f32], cfg: Settings) -> Vec<(f64, f64)> {
515 silence::regions(levels, cfg)
516}
517
518/// Sorts and joins overlapping or touching `(from, to)` frame spans.
519fn merge(mut v: Vec<(u32, u32)>) -> Vec<(u32, u32)> {
520 v.sort_unstable();
521 let mut out: Vec<(u32, u32)> = Vec::with_capacity(v.len());
522 for (a, b) in v {
523 match out.last_mut() {
524 Some(last) if a <= last.1 => last.1 = last.1.max(b),
525 _ => out.push((a, b)),
526 }
527 }
528 out
529}
530
531struct Found {
532 /// Timeline `(from, to)` frames, merged and in order.
533 regions: Vec<(u32, u32)>,
534 /// Clips whose sound was read.
535 scanned: usize,
536 /// Clips skipped because their file has no audio track.
537 no_audio: Vec<String>,
538}
539
540/// The silence of the given clips, as timeline frames. A lane's clips that touch (one ends where
541/// the next begins) are one stretch of sound: a quiet run that reaches the seam continues into the
542/// next clip, so a pause a cut has split across two clips is judged as the one pause it is. The
543/// gap between two clips that do not touch is never sound to judge, so a run never crosses it.
544/// The settings then apply to each joined run as `silence::regions` applies them to a clip's run.
545fn find(s: &PlaybackSession, clips: &[(Lane, Clip)], cfg: Settings) -> Result<Found, String> {
546 let fps = parse::session_fps(s);
547 let quiet_cfg = Settings {
548 min_silence: 0.0,
549 padding: 0.0,
550 min_keep: 0.0,
551 ..cfg
552 };
553 let mut regions: Vec<(u32, u32)> = Vec::new();
554 let mut scanned = 0;
555 let mut no_audio = Vec::new();
556 let mut lanes: Vec<Lane> = Vec::new();
557 for (lane, _) in clips {
558 if !lanes.contains(lane) {
559 lanes.push(*lane);
560 }
561 }
562 for lane in lanes {
563 let mut lane_clips: Vec<&Clip> = clips
564 .iter()
565 .filter(|(l, _)| *l == lane)
566 .map(|(_, c)| c)
567 .collect();
568 lane_clips.sort_by_key(|c| c.start);
569 // The duck of an audio lane, as windows of timeline time.
570 let duck = if lane.kind == LaneKind::Audio {
571 let to = lane_clips.iter().map(|c| c.end()).max().unwrap_or(0);
572 Some(duck_offsets(s, lane, to, fps)?)
573 } else {
574 None
575 };
576 // Unpadded quiet runs in timeline frames, joined across touching clips.
577 let mut quiet: Vec<(u32, u32)> = Vec::new();
578 // Whether the last run read reaches the end of the clip before this one, and where that clip ends.
579 let mut open_at_end = false;
580 let mut prev_end: Option<u32> = None;
581 for clip in lane_clips {
582 let mut levels = match read(s, lane, clip, fps)? {
583 None => {
584 no_audio.push(format!(
585 "{} (src:{} {} has no audio track)",
586 parse::addr(lane, clip.start),
587 clip.source,
588 source_name(s, clip.source)
589 ));
590 open_at_end = false;
591 prev_end = None;
592 continue;
593 }
594 Some(levels) => levels,
595 };
596 scanned += 1;
597 if let Some(offsets) = &duck {
598 apply_duck(&mut levels, clip, fps, offsets);
599 }
600 let runs = silence::timeline_regions(clip, fps, &regions_of(&levels, quiet_cfg));
601 let touching = open_at_end && prev_end == Some(clip.start);
602 for (i, &(a, len)) in runs.iter().enumerate() {
603 match quiet.last_mut() {
604 Some(last) if i == 0 && touching && a <= clip.start + 1 => last.1 = a + len,
605 _ => quiet.push((a, a + len)),
606 }
607 }
608 open_at_end = runs.last().is_some_and(|&(a, len)| a + len + 1 >= clip.end());
609 prev_end = Some(clip.end());
610 }
611 regions.extend(padded_runs(&quiet, cfg, fps));
612 }
613 Ok(Found {
614 regions: merge(regions),
615 scanned,
616 no_audio,
617 })
618}
619
620/// The silence `find` settles from unpadded quiet runs: a run must be long enough (judged before
621/// the padding), its ends are padded, and a sliver of speech shorter than min_keep between two runs
622/// is swallowed. `silence::regions` applies the same rules to a clip's run.
623fn padded_runs(quiet: &[(u32, u32)], cfg: Settings, fps: f64) -> Vec<(u32, u32)> {
624 let pad = (cfg.padding * fps).ceil() as u32;
625 let mut padded: Vec<(u32, u32)> = Vec::new();
626 for &(a, b) in quiet {
627 if f64::from(b - a) / fps < cfg.min_silence {
628 continue;
629 }
630 let (from, to) = (a + pad, b.saturating_sub(pad));
631 if to <= from {
632 continue;
633 }
634 match padded.last_mut() {
635 Some(last) if f64::from(from.saturating_sub(last.1)) / fps < cfg.min_keep => last.1 = to,
636 _ => padded.push((from, to)),
637 }
638 }
639 padded
640}
641
642/// The frames both lists of sorted, disjoint `(from, to)` spans share.
643fn intersect(a: &[(u32, u32)], b: &[(u32, u32)]) -> Vec<(u32, u32)> {
644 let (mut i, mut j) = (0, 0);
645 let mut out = Vec::new();
646 while i < a.len() && j < b.len() {
647 let (lo, hi) = (a[i].0.max(b[j].0), a[i].1.min(b[j].1));
648 if lo < hi {
649 out.push((lo, hi));
650 }
651 if a[i].1 < b[j].1 {
652 i += 1;
653 } else {
654 j += 1;
655 }
656 }
657 out
658}
659
660/// The silence of several lanes judged together: a stretch is silent where every judged lane is
661/// quiet at once. A lane is quiet inside its clips at its own threshold (as `find` judges it), and
662/// in its timeline gaps and past its last clip (a lane with no clip at a time is silent there). A
663/// stretch where no judged lane has a clip is structure, not silence, so it is never listed. The
664/// settings then apply to the joint runs as they do to one lane's.
665fn find_joint(s: &PlaybackSession, judged: &[(Lane, f32)], cfg: Settings) -> Result<Found, String> {
666 let fps = parse::session_fps(s);
667 let lane_quiet = Settings {
668 min_silence: 0.0,
669 padding: 0.0,
670 min_keep: 0.0,
671 ..cfg
672 };
673 let mut quiet: Option<Vec<(u32, u32)>> = None;
674 let mut sound: Vec<(u32, u32)> = Vec::new();
675 let mut scanned = 0;
676 let mut no_audio = Vec::new();
677 for &(lane, threshold_db) in judged {
678 let clips = lane_clips(s, lane);
679 let own = if clips.is_empty() {
680 vec![(0, u32::MAX)]
681 } else {
682 let f = find(s, &clips, Settings { threshold_db, ..lane_quiet })?;
683 scanned += f.scanned;
684 no_audio.extend(f.no_audio);
685 let mut v = f.regions;
686 v.extend(lane_gaps(s, lane));
687 // Past the lane's last clip there is no sound on it either, so it is quiet there too.
688 let lane_end = clips.iter().map(|(_, c)| c.end()).max().unwrap_or(0);
689 v.push((lane_end, u32::MAX));
690 merge(v)
691 };
692 quiet = Some(match quiet {
693 None => own,
694 Some(q) => intersect(&q, &own),
695 });
696 sound.extend(clips.iter().map(|(_, c)| (c.start, c.end())));
697 }
698 let Some(quiet) = quiet else {
699 return Ok(Found {
700 regions: Vec::new(),
701 scanned,
702 no_audio,
703 });
704 };
705 let joint = intersect(&quiet, &merge(sound));
706 Ok(Found {
707 regions: merge(padded_runs(&joint, cfg, fps)),
708 scanned,
709 no_audio,
710 })
711}
712
713/// A cut that would remove more than this share of the target's sound is refused unless forced.
714const CUT_SHARE_LIMIT: f64 = 0.5;
715
716/// The first few spans as `start–end s` pairs, the rest counted. Spans are `(start, len)` frames
717/// (what `cut_spans_for` returns), so the end is start plus len.
718fn span_list(spans: &[(u32, u32)], fps: f64) -> String {
719 const SHOWN: usize = 6;
720 let mut parts: Vec<String> = spans
721 .iter()
722 .take(SHOWN)
723 .map(|&(at, len)| format!("{:.3}–{:.3}s", parse::secs(at, fps), parse::secs(at + len, fps)))
724 .collect();
725 if spans.len() > SHOWN {
726 parts.push(format!("… {} more", spans.len() - SHOWN));
727 }
728 parts.join(", ")
729}
730
731/// The numbered region lines of the text reply, capped at `MAX_LINES`.
732fn region_lines(regions: &[(u32, u32)], fps: f64) -> Vec<String> {
733 let mut lines: Vec<String> = regions
734 .iter()
735 .take(MAX_LINES)
736 .enumerate()
737 .map(|(i, &(a, b))| {
738 format!(
739 "{}. {:.3}–{:.3}s ({}f)",
740 i + 1,
741 parse::secs(a, fps),
742 parse::secs(b, fps),
743 b - a
744 )
745 })
746 .collect();
747 if regions.len() > MAX_LINES {
748 lines.push(format!("… {} more", regions.len() - MAX_LINES));
749 }
750 lines
751}
752
753fn region_json(regions: &[(u32, u32)]) -> Value {
754 Value::Array(
755 regions
756 .iter()
757 .map(|&(a, b)| json!([format!("{a}f"), format!("{b}f")]))
758 .collect(),
759 )
760}
761
762/// The silence of one target, found where its sound is: a source's own file (in
763/// source time), the timeline as exported (the mix), a lane along its timeline, or
764/// the clips a clip covers (in timeline time).
765fn scan(s: &PlaybackSession, t: Target, cfg: Settings) -> Result<Found, String> {
766 match t {
767 Target::Source(n) => find_source(s, n, cfg),
768 Target::Mix => find_mix(s, cfg),
769 Target::Lane(lane) => scan_lane(s, lane, cfg),
770 Target::Clip(lane, clip) => find(s, &[(lane, clip)], cfg),
771 }
772}
773
774/// Seconds regions as frames at `fps`, rounded inward like `timeline_regions` does.
775fn frame_regions(regions: &[(f64, f64)], fps: f64) -> Vec<(u32, u32)> {
776 regions
777 .iter()
778 .filter_map(|&(from, to)| {
779 let a = (from * fps).ceil().max(0.0) as u32;
780 let b = (to * fps).floor().max(0.0) as u32;
781 (b > a).then_some((a, b))
782 })
783 .collect()
784}
785
786/// Silence of a whole source file, read from its start. Its regions are source
787/// frames at the timeline fps, rounded inward like `timeline_regions` does.
788fn find_source(s: &PlaybackSession, n: usize, cfg: Settings) -> Result<Found, String> {
789 let fps = parse::session_fps(s);
790 let src = s
791 .sources()
792 .get(n)
793 .ok_or_else(|| no_source(s, n))?;
794 let name = format!("src:{n} {}", source_name(s, n));
795 if let Some(why) = offline_refusal_for(s, &name, &[n]) {
796 return Err(why);
797 }
798 let Some(levels) = silence::levels(&src.path, src.audio_stream, (0.0, f64::INFINITY))
799 .map_err(|e| format!("reading the sound of {name}: {e}"))?
800 else {
801 return Ok(Found {
802 regions: Vec::new(),
803 scanned: 0,
804 no_audio: vec![format!("{name} has no audio track")],
805 });
806 };
807 Ok(Found {
808 regions: merge(frame_regions(&regions_of(&levels, cfg), fps)),
809 scanned: 1,
810 no_audio: Vec::new(),
811 })
812}
813
814/// Silence of the timeline as exported: the mix rendered to a temporary WAV, which
815/// starts at timeline frame 0, so its regions are timeline frames.
816fn find_mix(s: &PlaybackSession, cfg: Settings) -> Result<Found, String> {
817 let fps = parse::session_fps(s);
818 let wav = render_mix(s)?;
819 let Some(levels) = silence::levels(&wav.0, 0, (0.0, f64::INFINITY))
820 .map_err(|e| format!("reading the mix: {e}"))?
821 else {
822 return Ok(Found {
823 regions: Vec::new(),
824 scanned: 0,
825 no_audio: vec!["the mix has no sound track".into()],
826 });
827 };
828 Ok(Found {
829 regions: merge(frame_regions(&regions_of(&levels, cfg), fps)),
830 scanned: 1,
831 no_audio: Vec::new(),
832 })
833}
834
835/// Silence of a lane: the quiet inside its clips, read where each clip sits, with the lane's duck.
836/// Only the sound INSIDE clips is judged. The timeline gaps between clips (a title's lead-in, the
837/// space between two takes) are structure, not silence, so they are never listed or cut; see
838/// [`lane_gaps`] for the count the reply names.
839fn scan_lane(s: &PlaybackSession, lane: Lane, cfg: Settings) -> Result<Found, String> {
840 if s.lane_clips(lane).is_empty() {
841 return Err(format!("{} has no clips to scan", parse::lane_name(lane)));
842 }
843 let clips: Vec<(Lane, Clip)> = s.lane_clips(lane).iter().map(|c| (lane, c.clone())).collect();
844 find(s, &clips, cfg)
845}
846
847/// The timeline spans of a lane that no clip covers, as `(from, to)` frames, in order: the lead-in
848/// before the first clip and every gap between two clips. Structure, not silence, so they are
849/// reported and left alone.
850pub(crate) fn lane_gaps(s: &PlaybackSession, lane: Lane) -> Vec<(u32, u32)> {
851 let mut clips: Vec<&Clip> = s.lane_clips(lane).iter().collect();
852 clips.sort_by_key(|c| c.start);
853 let mut gaps = Vec::new();
854 let mut cursor = 0u32;
855 for c in clips {
856 if c.start > cursor {
857 gaps.push((cursor, c.start));
858 }
859 cursor = cursor.max(c.end());
860 }
861 gaps
862}
863
864/// The reply's note on the gaps a lane-level scan or cut leaves alone, or empty when there are none.
865fn gap_note(s: &PlaybackSession, lanes: &[Lane], fps: f64) -> String {
866 let mut parts = Vec::new();
867 for &l in lanes {
868 let gaps = lane_gaps(s, l);
869 if gaps.is_empty() {
870 continue;
871 }
872 let total: u32 = gaps.iter().map(|&(a, b)| b - a).sum();
873 parts.push(format!(
874 "{} timeline gap{} on {} left alone ({:.3} s, not silence)",
875 gaps.len(),
876 if gaps.len() == 1 { "" } else { "s" },
877 parse::lane_name(l),
878 parse::secs(total, fps)
879 ));
880 }
881 if parts.is_empty() {
882 String::new()
883 } else {
884 format!(" · {}", parts.join("; "))
885 }
886}
887
888/// A lane's sound along its timeline, one value per window from timeline 0 to the lane's end:
889/// the clips read where they sit, the gaps silent, the lane's duck applied. Also the clips read
890/// and the clips with no audio track, by name.
891fn lane_windows(s: &PlaybackSession, lane: Lane) -> Result<(Vec<f32>, usize, Vec<String>), String> {
892 if s.lane_clips(lane).is_empty() {
893 return Err(format!("{} has no clips to scan", parse::lane_name(lane)));
894 }
895 let fps = parse::session_fps(s);
896 let end = lane_end(s, lane);
897 let mut reads = Vec::new();
898 let mut no_audio = Vec::new();
899 for clip in s.lane_clips(lane) {
900 match read(s, lane, clip, fps)? {
901 None => no_audio.push(format!(
902 "{} (src:{} {} has no audio track)",
903 parse::addr(lane, clip.start),
904 clip.source,
905 source_name(s, clip.source)
906 )),
907 Some(levels) => reads.push((clip.clone(), Some(levels))),
908 }
909 }
910 let scanned = reads.len();
911 // Windows from timeline 0 to the lane's end; a gap has no clip, so it reads silent.
912 let (_, mut windows) = span_windows(&reads, fps, (0, end));
913 let offsets = duck_offsets(s, lane, end, fps)?;
914 apply_offsets_to_windows(&mut windows, 0, &offsets);
915 Ok((windows, scanned, no_audio))
916}
917
918/// The pause each cut joint now sits in, measured back from the sound after the cut: the quiet
919/// run around the joint, in seconds, one per span in order. `quiet` is the silence of that sound
920/// judged at the same threshold with no padding and no forgiveness, in seconds. Read on the
921/// result, so it is what is there, not the plan.
922fn measured_pauses(quiet: &[(f64, f64)], spans: &[(u32, u32)], fps: f64) -> Vec<f64> {
923 let mut removed = 0u32;
924 let mut out = Vec::with_capacity(spans.len());
925 for &(at, len) in spans {
926 // Each span's joint, on the timeline as it stands after the spans before it are gone.
927 let joint = f64::from(at.saturating_sub(removed)) / fps;
928 removed = removed.saturating_add(len);
929 let pause = quiet
930 .iter()
931 .find(|&&(a, b)| a - 1e-6 <= joint && joint <= b + 1e-6)
932 .map_or(0.0, |&(a, b)| b - a);
933 out.push(pause);
934 }
935 out
936}
937
938/// The pauses after a cut, judged the way `silence` judges them: only the sound INSIDE clips, so
939/// the timeline gaps between clips are never part of a pause. Quiet runs that touch across a cut
940/// seam are one pause, as the sound is. A lane or clip target is read on its own clips (its duck
941/// included), a mix as exported, which has no one lane to read and may be cut on lanes that are
942/// empty.
943fn measured_cut_pauses(
944 s: &PlaybackSession,
945 target: &Target,
946 spans: &[(u32, u32)],
947 cfg: Settings,
948 fps: f64,
949) -> Result<Vec<f64>, String> {
950 let quiet_cfg = Settings {
951 min_silence: 0.0,
952 padding: 0.0,
953 min_keep: 0.0,
954 ..cfg
955 };
956 let quiet: Vec<(f64, f64)> = match target {
957 Target::Lane(lane) => find(s, &lane_clips(s, *lane), quiet_cfg)?
958 .regions
959 .iter()
960 .map(|&(a, b)| (f64::from(a) / fps, f64::from(b) / fps))
961 .collect(),
962 Target::Clip(lane, clip) => find(s, &[(*lane, clip.clone())], quiet_cfg)?
963 .regions
964 .iter()
965 .map(|&(a, b)| (f64::from(a) / fps, f64::from(b) / fps))
966 .collect(),
967 Target::Mix | Target::Source(_) => {
968 let wav = render_mix(s)?;
969 let levels = silence::levels(&wav.0, 0, (0.0, f64::INFINITY))
970 .map_err(|e| format!("reading the mix: {e}"))?
971 .unwrap_or_default();
972 regions_of(&levels, quiet_cfg)
973 }
974 };
975 Ok(measured_pauses(&quiet, spans, fps))
976}
977
978/// The clips of a lane, paired with their lane, as `find` takes them.
979fn lane_clips(s: &PlaybackSession, lane: Lane) -> Vec<(Lane, Clip)> {
980 s.lane_clips(lane).iter().map(|c| (lane, c.clone())).collect()
981}
982
983/// Why cut_silence will not cut a bare source, and what to run instead.
984fn source_cut_refusal(s: &PlaybackSession, n: usize) -> String {
985 let name = format!("src:{n} {}", source_name(s, n));
986 let playing = s
987 .lanes()
988 .into_iter()
989 .filter(|l| l.kind == LaneKind::Audio)
990 .find_map(|l| {
991 s.lane_clips(l)
992 .iter()
993 .find(|c| c.source == n)
994 .map(|c| (l, parse::addr(l, c.start)))
995 });
996 match playing {
997 Some((lane, addr)) => format!(
998 "cut_silence needs the timeline: {name} is a source file, not a clip or lane. \
999Run silence on src:{n} for its quiet stretches in source time, then cut_silence on the lane that plays it ({}), or on the clip {addr}.",
1000 parse::lane_name(lane)
1001 ),
1002 None => format!(
1003 "cut_silence needs the timeline: {name} is a source file, and no audio lane plays it. Put it on an audio lane, then cut_silence on that lane or clip."
1004 ),
1005 }
1006}
1007
1008/// Median speech level (the windows above this) is the reference for an automatic threshold.
1009const AUTO_ACTIVE_DB: f32 = -60.0;
1010/// An automatic threshold sits this far under the median speech level.
1011const AUTO_OFFSET_DB: f32 = 30.0;
1012
1013/// Whether the caller gave `threshold_db`. When not, the threshold is measured from the target.
1014fn threshold_given(args: &Value) -> bool {
1015 matches!(args.get("threshold_db"), Some(v) if !v.is_null())
1016}
1017
1018/// The levels of a target as one track, for measuring its speech: a lane's windows (its duck
1019/// included), a clip's read, a source file, or the mix as exported.
1020fn speech_levels(s: &PlaybackSession, target: &Target) -> Result<Option<Vec<f32>>, String> {
1021 let fps = parse::session_fps(s);
1022 match target {
1023 Target::Lane(l) => Ok(Some(lane_windows(s, *l)?.0)),
1024 Target::Clip(l, c) => read(s, *l, c, fps),
1025 Target::Source(n) => {
1026 let src = s
1027 .sources()
1028 .get(*n)
1029 .ok_or_else(|| no_source(s, *n))?;
1030 silence::levels(&src.path, src.audio_stream, (0.0, f64::INFINITY))
1031 .map_err(|e| format!("reading the sound of src:{n}: {e}"))
1032 }
1033 Target::Mix => {
1034 let wav = render_mix(s)?;
1035 silence::levels(&wav.0, 0, (0.0, f64::INFINITY))
1036 .map_err(|e| format!("reading the mix: {e}"))
1037 }
1038 }
1039}
1040
1041/// The threshold to use when none is given: 30 dB under the median level of the target's speech
1042/// (its windows above -60 dBFS), kept between -90 and -10 dBFS. Returns it with a note saying how it
1043/// was measured, so the reply can name the threshold it used. With no speech to measure, the
1044/// default stands and the note says so.
1045fn auto_threshold(s: &PlaybackSession, target: &Target) -> Result<(f32, String), String> {
1046 let default = Settings::default().threshold_db;
1047 let mut active: Vec<f32> = speech_levels(s, target)?
1048 .unwrap_or_default()
1049 .into_iter()
1050 .filter(|&x| x > AUTO_ACTIVE_DB)
1051 .collect();
1052 if active.is_empty() {
1053 return Ok((
1054 default,
1055 format!("no speech above {AUTO_ACTIVE_DB} dBFS to measure, so the default {default} dBFS"),
1056 ));
1057 }
1058 active.sort_by(f32::total_cmp);
1059 let median = active[active.len() / 2];
1060 let thr = (median - AUTO_OFFSET_DB).clamp(-90.0, -10.0);
1061 Ok((
1062 thr,
1063 format!(
1064 "threshold {thr:.1} dBFS, {AUTO_OFFSET_DB} dB under the median speech level {median:.1} dBFS (set threshold_db to override)"
1065 ),
1066 ))
1067}
1068
1069fn run_silence(srv: &mut Server, args: &Value) -> Reply {
1070 let cfg = match settings_arg(args) {
1071 Ok(c) => c,
1072 Err(e) => return fail(e),
1073 };
1074 let s = tri!(srv.session_ref());
1075 let target = match target_arg(s, args) {
1076 Ok(t) => t,
1077 Err(e) => return fail(e),
1078 };
1079 let (cfg, thr_note) = if threshold_given(args) {
1080 (cfg, None)
1081 } else {
1082 match auto_threshold(s, &target) {
1083 Ok((t, note)) => (Settings { threshold_db: t, ..cfg }, Some(note)),
1084 Err(e) => return fail(e),
1085 }
1086 };
1087 let name = label(s, &target);
1088 let found = match scan(s, target.clone(), cfg) {
1089 Ok(f) => f,
1090 Err(e) => return fail(e),
1091 };
1092 if found.scanned == 0 {
1093 return fail(format!(
1094 "nothing to scan on {name}: {}",
1095 found.no_audio.join("; ")
1096 ));
1097 }
1098 let fps = parse::session_fps(s);
1099 let total: u32 = found.regions.iter().map(|&(a, b)| b - a).sum();
1100 let scope = match target {
1101 Target::Source(_) => "the source file, in source time".to_string(),
1102 Target::Mix => "the mix as exported, in timeline time".to_string(),
1103 Target::Lane(_) => format!("{} clip(s) on the lane, judged inside the clips", found.scanned),
1104 Target::Clip(..) => format!("scanned {} clip(s)", found.scanned),
1105 };
1106 let mut text = format!(
1107 "silence on {name}: {} region(s), {:.3} s ({total}f) at or below {:.1} dBFS for {:.2} s or more · {scope}",
1108 found.regions.len(),
1109 parse::secs(total, fps),
1110 cfg.threshold_db,
1111 cfg.min_silence,
1112 );
1113 if let Some(note) = &thr_note {
1114 text.push_str(&format!("\nthreshold: {note}"));
1115 }
1116 if let Target::Lane(l) = &target {
1117 text.push_str(&gap_note(s, &[*l], fps));
1118 }
1119 for line in region_lines(&found.regions, fps) {
1120 text.push('\n');
1121 text.push_str(&line);
1122 }
1123 if !found.no_audio.is_empty() {
1124 text.push_str(&format!(
1125 "\nskipped, no audio track: {}",
1126 found.no_audio.join("; ")
1127 ));
1128 }
1129 let structured = json!({
1130 "regions": region_json(&found.regions),
1131 "count": found.regions.len(),
1132 "total_frames": total,
1133 "scanned": found.scanned,
1134 "threshold_db": cfg.threshold_db,
1135 "threshold_auto": thr_note.is_some(),
1136 });
1137 Reply::ok(text).with(structured)
1138}
1139
1140// ---- cut_silence ----------------------------------------------------------
1141
1142/// The `lanes` argument: `None` for every lane, or the named ones.
1143fn lanes_arg(s: &PlaybackSession, args: &Value) -> Result<Option<Vec<Lane>>, String> {
1144 match args.get("lanes") {
1145 None | Some(Value::Null) => Ok(None),
1146 Some(Value::Array(a)) if !a.is_empty() => a
1147 .iter()
1148 .map(|x| {
1149 let name = x
1150 .as_str()
1151 .ok_or_else(|| "`lanes` lists lane names such as V1".to_string())?;
1152 let lane = parse::lane(name)?;
1153 // A caption lane is a valid scope: captions follow a cut on their own.
1154 if lane.kind == LaneKind::Subtitle {
1155 if !s.lanes().contains(&lane) {
1156 return Err(format!("no lane {name} on this timeline"));
1157 }
1158 } else {
1159 lane_ok(s, lane, name)?;
1160 }
1161 Ok(lane)
1162 })
1163 .collect::<Result<Vec<_>, String>>()
1164 .map(Some),
1165 Some(_) => {
1166 Err("`lanes` must be a non-empty list of lane names such as [\"V1\", \"A1\"]".into())
1167 }
1168 }
1169}
1170
1171/// The lanes of a joint cut: `lanes` naming two or more distinct lanes with no target. None
1172/// otherwise: with a target, `lanes` is the target's ripple scope (the silence is judged on the
1173/// target alone), and one lane is the target's own cut. A joint cut has no target, since the
1174/// silence is judged across the lanes it names.
1175fn joint_lanes(s: &PlaybackSession, args: &Value) -> Result<Option<Vec<Lane>>, String> {
1176 let Some(lanes) = lanes_arg(s, args)? else {
1177 return Ok(None);
1178 };
1179 let mut uniq: Vec<Lane> = Vec::new();
1180 for l in lanes {
1181 if !uniq.contains(&l) {
1182 uniq.push(l);
1183 }
1184 }
1185 if uniq.len() < 2 || arg_given(args, "target") {
1186 return Ok(None);
1187 }
1188 Ok(Some(uniq))
1189}
1190
1191/// The lane a target sits on, if it is one lane's (a lane or a clip). A mix or a source has none.
1192fn target_lane(t: &Target) -> Option<Lane> {
1193 match t {
1194 Target::Lane(l) | Target::Clip(l, _) => Some(*l),
1195 Target::Source(_) | Target::Mix => None,
1196 }
1197}
1198
1199/// The note a cut owes when it took the default target (A1, the doc's default) and other audio
1200/// lanes with clips hold sound it did not scan: they are named, with the target to cut them.
1201/// Empty when the target was given, for a joint cut, or when no other audio lane has clips.
1202fn default_target_note(s: &PlaybackSession, args: &Value, target: Option<&Target>) -> String {
1203 let Some(target) = target else {
1204 return String::new();
1205 };
1206 if arg_given(args, "target") {
1207 return String::new();
1208 }
1209 let scanned = target_lane(target);
1210 let mut others: Vec<String> = Vec::new();
1211 for l in s.lanes() {
1212 if l.kind == LaneKind::Audio && Some(l) != scanned && !s.lane_clips(l).is_empty() {
1213 others.push(parse::lane_name(l));
1214 }
1215 }
1216 let Some(first) = others.first() else {
1217 return String::new();
1218 };
1219 let scanned_name = label(s, target);
1220 if others.len() == 1 {
1221 format!(" · scanned {scanned_name} only, the default target; {first} also holds sound: target {first} to cut its pauses")
1222 } else {
1223 format!(
1224 " · scanned {scanned_name} only, the default target; {} also hold sound: target {first} (or another of them) to cut their pauses",
1225 others.join(", ")
1226 )
1227 }
1228}
1229
1230/// The reply of a cut that finds no pause to cut. It names the rule that kept each quiet stretch out
1231/// and the longest quiet there was, so the setting to lower is the one named. `thr` is the threshold
1232/// as the reply words it; `longest` is in seconds, unpadded.
1233fn no_pause_note(name: &str, thr: &str, min_silence: f64, padding: f64, longest: f64) -> String {
1234 if longest <= 0.0 {
1235 format!("no quiet under {thr} on {name}; nothing cut")
1236 } else if longest < min_silence {
1237 format!(
1238 "no pause of {min_silence:.2} s or longer (min_silence) under {thr} on {name}; the longest quiet was {longest:.2} s — lower min_silence to cut shorter pauses; nothing cut"
1239 )
1240 } else {
1241 format!(
1242 "the longest quiet under {thr} on {name} was {longest:.2} s, not longer than the {padding:.2} s padding kept at each end; lower padding to cut it; nothing cut"
1243 )
1244 }
1245}
1246
1247/// Whether an optional argument other than null was given.
1248pub(crate) fn arg_given(args: &Value, key: &str) -> bool {
1249 matches!(args.get(key), Some(v) if !v.is_null())
1250}
1251
1252/// The refusal for a cut on a locked lane, with the way out (the same words edit's lock check gives).
1253pub(crate) fn lock_refusal(l: Lane) -> String {
1254 let n = parse::lane_name(l);
1255 format!("lane {n} is locked: unlock it first with lane_flags {{lane:\"{n}\", locked:false}}")
1256}
1257
1258/// The name of a joint cut in the reply: its lanes joined, marked as joint.
1259fn joint_label(lanes: &[Lane]) -> String {
1260 let names: Vec<String> = lanes.iter().map(|&l| parse::lane_name(l)).collect();
1261 format!("{} (joint)", names.join("+"))
1262}
1263
1264/// The lanes' judged gains and the note, if any, that goes with them.
1265type Judgement = (Vec<(Lane, f32)>, Option<String>);
1266
1267/// Each judged lane with the threshold it is judged at, and the note that says how they were
1268/// set. A threshold given applies to every lane; otherwise each lane measures its own (the same
1269/// rule as a single lane's). A lane with no clips has no speech to measure, so it takes the
1270/// default and is silent throughout.
1271fn joint_thresholds(
1272 s: &PlaybackSession,
1273 lanes: &[Lane],
1274 cfg: Settings,
1275 given: bool,
1276) -> Result<Judgement, String> {
1277 let mut judged = Vec::new();
1278 let mut notes = Vec::new();
1279 for &l in lanes {
1280 if given {
1281 judged.push((l, cfg.threshold_db));
1282 } else if s.lane_clips(l).is_empty() {
1283 judged.push((l, Settings::default().threshold_db));
1284 notes.push(format!("{} has no clips, so it is quiet throughout", parse::lane_name(l)));
1285 } else {
1286 let (thr, note) = auto_threshold(s, &Target::Lane(l))?;
1287 judged.push((l, thr));
1288 notes.push(format!("{}: {note}", parse::lane_name(l)));
1289 }
1290 }
1291 let note = (!given).then(|| notes.join("; "));
1292 Ok((judged, note))
1293}
1294
1295/// The pauses a joint cut leaves, measured on the joint silence after the cut, as
1296/// `measured_cut_pauses` measures a single lane's.
1297fn measured_joint_pauses(
1298 s: &PlaybackSession,
1299 judged: &[(Lane, f32)],
1300 spans: &[(u32, u32)],
1301 fps: f64,
1302) -> Result<Vec<f64>, String> {
1303 let quiet_cfg = Settings {
1304 min_silence: 0.0,
1305 padding: 0.0,
1306 min_keep: 0.0,
1307 ..Settings::default()
1308 };
1309 let quiet: Vec<(f64, f64)> = find_joint(s, judged, quiet_cfg)?
1310 .regions
1311 .iter()
1312 .map(|&(a, b)| (f64::from(a) / fps, f64::from(b) / fps))
1313 .collect();
1314 Ok(measured_pauses(&quiet, spans, fps))
1315}
1316
1317/// Snapshots the engine pushed since `start` (a `history_pushes` reading). Exact
1318/// at the undo cap, where the undo depth stops growing.
1319fn pushed_since(s: &PlaybackSession, start: u64) -> usize {
1320 s.history_pushes().saturating_sub(start) as usize
1321}
1322
1323/// Takes `n` engine undo steps back. False if the engine would not take one.
1324fn undo_n(s: &mut PlaybackSession, n: usize) -> bool {
1325 (0..n).all(|_| s.undo())
1326}
1327
1328/// Records the snapshots pushed since `start` as one ledger entry named `label`.
1329pub(super) fn record_pushes(srv: &mut Server, start: u64, label: String) {
1330 let Some(s) = srv.session.as_ref() else {
1331 return;
1332 };
1333 let n = pushed_since(s, start);
1334 if n > 0 {
1335 srv.ledger.push(Entry::new(n, label));
1336 srv.history_lost_on_open = false;
1337 srv.redo_ledger.clear();
1338 srv.trim_ledger();
1339 }
1340}
1341
1342/// The shortest pause a cut may leave: below it the pause is not a pause a person can hear.
1343const MIN_KEEP_SECS: f64 = 0.05;
1344
1345/// The slowest a speed_up plays a silence at: the GUI's silence rate starts one step above real time.
1346const MIN_SILENCE_RATE: f64 = 1.05;
1347
1348/// What cut_silence does to each silence it finds: cut it back to `keep` (the default), play it at a
1349/// speed, or cut the speech and keep the silence (the GUI's keep-only silence).
1350#[derive(Clone, Copy, PartialEq, Eq, Debug)]
1351enum CutMode {
1352 Cut,
1353 SpeedUp,
1354 KeepSilence,
1355}
1356
1357impl CutMode {
1358 /// The word the `mode` argument takes for this mode.
1359 fn name(self) -> &'static str {
1360 match self {
1361 CutMode::Cut => "cut",
1362 CutMode::SpeedUp => "speed_up",
1363 CutMode::KeepSilence => "keep_silence",
1364 }
1365 }
1366}
1367
1368/// `mode`, or cut when it is absent.
1369fn cut_mode(args: &Value) -> Result<CutMode, String> {
1370 match args.get("mode") {
1371 None | Some(Value::Null) => Ok(CutMode::Cut),
1372 Some(Value::String(t)) => match t.as_str() {
1373 "cut" => Ok(CutMode::Cut),
1374 "speed_up" => Ok(CutMode::SpeedUp),
1375 "keep_silence" => Ok(CutMode::KeepSilence),
1376 other => Err(format!("`mode` {other} is not one of cut, speed_up, keep_silence")),
1377 },
1378 Some(_) => Err("`mode` is a word: cut, speed_up or keep_silence".into()),
1379 }
1380}
1381
1382/// `rate`, the speed a speed_up plays each silence at: 1.05 to 4 (the GUI's silence rate), or None when
1383/// it is absent. The GUI's default is the top rate, 4, which the caller applies.
1384fn speed_rate(args: &Value) -> Result<Option<Speed>, String> {
1385 match args.get("rate") {
1386 None | Some(Value::Null) => Ok(None),
1387 Some(v) => match v.as_f64() {
1388 Some(x) if x.is_finite() && (MIN_SILENCE_RATE..=4.0).contains(&x) => {
1389 Ok(Some(Speed::from_permille((x * 1000.0).round() as u16)))
1390 }
1391 _ => Err(format!("`rate` is the speed a silence plays at, from {MIN_SILENCE_RATE} to 4")),
1392 },
1393 }
1394}
1395
1396/// The timeline spans a target's sound covers, as `(from, to)` frames: a clip's own span, a lane's
1397/// clips, or the whole mix. Empty for a source file, which has no place on the timeline.
1398fn target_windows(s: &PlaybackSession, t: &Target) -> Vec<(u32, u32)> {
1399 match t {
1400 Target::Clip(_, c) => vec![(c.start, c.end())],
1401 Target::Lane(l) => s.lane_clips(*l).iter().map(|c| (c.start, c.end())).collect(),
1402 Target::Mix => vec![(0, parse::session_end(s))],
1403 Target::Source(_) => Vec::new(),
1404 }
1405}
1406
1407/// The speech a keep_silence cut takes out: the stretches of each window that the quiet `quiet`
1408/// does not cover, as `(start, len)` timeline frames. The complement is taken with
1409/// `silence::invert` inside each window, as the GUI's keep-only silence does per clip.
1410fn speech_within(windows: &[(u32, u32)], quiet: &[(u32, u32)], fps: f64) -> Vec<(u32, u32)> {
1411 let mut out = Vec::new();
1412 for &(a, b) in windows {
1413 if b <= a {
1414 continue;
1415 }
1416 let duration = f64::from(b - a) / fps;
1417 let inside: Vec<(f64, f64)> = quiet
1418 .iter()
1419 .filter(|&&(qa, qb)| qb > a && qa < b)
1420 .map(|&(qa, qb)| (f64::from(qa.max(a) - a) / fps, f64::from(qb.min(b) - a) / fps))
1421 .collect();
1422 for (from, to) in silence::invert(duration, &inside) {
1423 let start = a + (from * fps).round() as u32;
1424 let end = (a + (to * fps).round() as u32).min(b);
1425 if end > start {
1426 out.push((start, end - start));
1427 }
1428 }
1429 }
1430 out
1431}
1432
1433/// `keep` in seconds, 0.05 to 10, or absent.
1434fn keep_secs(args: &Value) -> Result<Option<f64>, String> {
1435 match args.get("keep") {
1436 None | Some(Value::Null) => Ok(None),
1437 Some(v) => match v.as_f64() {
1438 Some(x) if x.is_finite() && (MIN_KEEP_SECS..=10.0).contains(&x) => Ok(Some(x)),
1439 Some(x) if x.is_finite() && (0.0..MIN_KEEP_SECS).contains(&x) => Err(format!(
1440 "`keep` {x} would leave less than {MIN_KEEP_SECS} s of pause; use keep ≥ {MIN_KEEP_SECS}. To delete pauses entirely use cut_regions"
1441 )),
1442 _ => Err("`keep` is a time in seconds, 0.05 to 10".into()),
1443 },
1444 }
1445}
1446
1447/// The settings silence and cut_silence both scan with. They are the same, so a cut is made on
1448/// exactly the regions silence reports for the same args. min_keep is 0 unless given: a kept
1449/// sliver of speech joined into two silences would be cut with them.
1450fn cut_settings(args: &Value) -> Result<Settings, String> {
1451 settings_arg(args)
1452}
1453
1454/// The lanes a cut takes when `lanes` is absent: the target's lane and the lanes of clips linked
1455/// to it. A mix has no one lane, so it takes every lane.
1456fn default_cut_scope(s: &PlaybackSession, t: &Target) -> Vec<Lane> {
1457 match t {
1458 Target::Lane(l) => super::listen::linked_lanes(s, *l, s.lane_clips(*l)),
1459 Target::Clip(l, c) => super::listen::linked_lanes(s, *l, std::slice::from_ref(c)),
1460 Target::Source(_) | Target::Mix => s.lanes(),
1461 }
1462}
1463
1464/// The frames of sound the cut lanes hold: the lengths of their audio clips, gaps and
1465/// picture-only lanes left out. A scope with no audio lane counts every clip on it.
1466fn sound_frames(s: &PlaybackSession, scope: &[Lane]) -> u32 {
1467 let audio: Vec<Lane> = scope.iter().copied().filter(|l| l.kind == LaneKind::Audio).collect();
1468 let pick = if audio.is_empty() { scope.to_vec() } else { audio };
1469 let mut total = 0u32;
1470 for l in pick {
1471 for c in s.lane_clips(l) {
1472 total = total.saturating_add(c.end().saturating_sub(c.start));
1473 }
1474 }
1475 total
1476}
1477
1478/// The spans a cut takes out of each silence region, so the pause left in it is `keep` seconds
1479/// in all, padding included. `regions` are the silence as `find` reports it: the padding at each
1480/// end is already outside them, and it is what stays there, so the frames of quiet left are the
1481/// two paddings plus the part of the region kept, which is keep less the two paddings. The
1482/// padding is rounded up to whole frames as `find` rounds it, and keep to the nearest frame. A
1483/// silence whose quiet is at or under keep is left alone; a keep under twice the padding leaves
1484/// 2 × padding (the region is cut whole). A silence that runs to its clip's end keeps keep after
1485/// the speech before it, its end padding included, so the tail is never shorter than keep.
1486/// Returns `(start, len)` timeline frames.
1487fn cut_spans_for(
1488 regions: &[(u32, u32)],
1489 keep: f64,
1490 padding: f64,
1491 fps: f64,
1492 clip_ends: &[u32],
1493) -> Vec<(u32, u32)> {
1494 let pad = (padding * fps).ceil() as u32;
1495 let total = (keep * fps).round() as u32;
1496 // The frames of the region left in place.
1497 let inner = total.saturating_sub(2 * pad);
1498 regions
1499 .iter()
1500 .filter_map(|&(a, b)| {
1501 let f = b.saturating_sub(a);
1502 if f == 0 {
1503 return None;
1504 }
1505 // The region ends `pad` before the clip's end (give or take the frame rounding) when the
1506 // silence runs to it: the padding at the clip's end stays, and the kept part sits after
1507 // the speech before it.
1508 let at_clip_end = clip_ends.iter().any(|&e| e >= b && e - b <= pad + 3);
1509 if at_clip_end {
1510 let start = a.saturating_add(inner);
1511 return (b > start).then_some((start, b - start));
1512 }
1513 // The kept part is split half at each end; the cut takes the rest of the region.
1514 let len = f.checked_sub(inner).filter(|&n| n > 0)?;
1515 Some((a + inner / 2, len))
1516 })
1517 .collect()
1518}
1519
1520/// The audio clips on lanes a cut does not name that the cut runs through. They keep their place
1521/// while the cut lanes shorten, so they fall out of step with them (a music bed under two speakers,
1522/// say). Their addresses, so the reply can name them.
1523fn unlisted_spanning(s: &PlaybackSession, scope: &[Lane], spans: &[(u32, u32)]) -> Vec<String> {
1524 let mut out = Vec::new();
1525 for l in s.lanes() {
1526 if scope.contains(&l) || l.kind != LaneKind::Audio {
1527 continue;
1528 }
1529 for c in s.lane_clips(l) {
1530 if spans.iter().any(|&(a, len)| c.start < a + len && c.end() > a) {
1531 out.push(parse::addr(l, c.start));
1532 }
1533 }
1534 }
1535 out
1536}
1537
1538/// The note a cut owes when a lane it did not cut now runs past the end of the cut lanes: a music bed
1539/// under two speakers that the cut shortened, say. Each such lane is named, with how far past it runs
1540/// and the trim that brings it back to the new end. Empty when no lane outside the cut runs past.
1541fn overrun_note(s: &PlaybackSession, scope: &[Lane], fps: f64) -> String {
1542 let cut_end = super::listen::lanes_end(s, scope);
1543 if cut_end == 0 {
1544 return String::new();
1545 }
1546 let mut parts: Vec<String> = Vec::new();
1547 for l in s.lanes() {
1548 let end = super::listen::lanes_end(s, &[l]);
1549 if scope.contains(&l) || end <= cut_end {
1550 continue;
1551 }
1552 let name = parse::lane_name(l);
1553 // The clip that crosses the new end is trimmed; when the lane has none there, the clips past it go.
1554 let fix = match s.lane_clips(l).iter().find(|c| c.start < cut_end && c.end() > cut_end) {
1555 Some(c) => format!(
1556 "trim {{clip:\"{}\", edge:\"out\", to:\"{:.3}s\"}}",
1557 parse::addr(l, c.start),
1558 parse::secs(cut_end, fps)
1559 ),
1560 None => "delete the clips past the cut lanes' end".to_string(),
1561 };
1562 parts.push(format!(
1563 "{name} runs {:.3} s past the cut lanes (they end at {:.3} s, {name} at {:.3} s): trim it with the edit op {fix}",
1564 parse::secs(end - cut_end, fps),
1565 parse::secs(cut_end, fps),
1566 parse::secs(end, fps),
1567 ));
1568 }
1569 if parts.is_empty() {
1570 return String::new();
1571 }
1572 format!(" · {}", parts.join("; "))
1573}
1574
1575/// A cut rolled back from a clean project leaves it clean: its save marks move past the rolled-back
1576/// pushes, as `edit`'s dry run and batch rollback do. A project that was dirty keeps its marks.
1577fn keep_clean_marks(srv: &mut Server, was_clean: bool) {
1578 if !was_clean {
1579 return;
1580 }
1581 if let Some(s) = srv.session.as_ref() {
1582 srv.saved_depth = Some(s.undo_depth());
1583 srv.saved_pushes = Some(s.history_pushes());
1584 srv.saved_sources = Some(s.sources().len());
1585 }
1586}
1587
1588fn run_cut_silence(srv: &mut Server, args: &Value) -> Reply {
1589 let cfg = match cut_settings(args) {
1590 Ok(c) => c,
1591 Err(e) => return fail(e),
1592 };
1593 let keep = match keep_secs(args) {
1594 Ok(k) => k.unwrap_or(DEFAULT_KEEP),
1595 Err(e) => return fail(e),
1596 };
1597 let mode = match cut_mode(args) {
1598 Ok(m) => m,
1599 Err(e) => return fail(e),
1600 };
1601 let rate = match speed_rate(args) {
1602 Ok(r) => r,
1603 Err(e) => return fail(e),
1604 };
1605 if mode != CutMode::Cut && args.get("keep").is_some_and(|v| !v.is_null()) {
1606 return fail(format!("`keep` is the pause mode cut leaves; {} takes no keep", mode.name()));
1607 }
1608 if mode != CutMode::SpeedUp && rate.is_some() {
1609 return fail(format!("`rate` is the speed of mode speed_up; {} takes no rate", mode.name()));
1610 }
1611 // The GUI's silence rate defaults to its top speed.
1612 let speed = rate.unwrap_or(Speed::MAX);
1613 let dry = opt_bool(args, "dry_run").unwrap_or(false);
1614 // A cut that is rolled back (a dry run, or a refused cut) leaves the project as it was.
1615 let was_clean = !super::project::dirty(srv);
1616 let Some(s) = srv.session.as_mut() else {
1617 return Reply::err(NO_PROJECT);
1618 };
1619 // A joint cut names two or more lanes and has no target; any other cut has one.
1620 let joint = match joint_lanes(s, args) {
1621 Ok(j) => j,
1622 Err(e) => return fail(e),
1623 };
1624 if mode == CutMode::KeepSilence && joint.is_some() {
1625 return fail("mode keep_silence takes one target, not a joint cut: name the target and drop lanes".into());
1626 }
1627 let target = match &joint {
1628 Some(_) => None,
1629 None => match target_arg(s, args) {
1630 Ok(t) => Some(t),
1631 Err(e) => return fail(e),
1632 },
1633 };
1634 if let Some(Target::Source(n)) = target {
1635 return fail(source_cut_refusal(s, n));
1636 }
1637 // The name, the scope a cut takes by default, the thresholds used and the regions found. A
1638 // joint cut judges each listed lane at its own threshold; a single cut as it always has.
1639 let (name, linked, judged, thr_note, found, cfg) = match (&joint, &target) {
1640 (Some(lanes), _) => {
1641 // Only audio lanes are judged; a video lane in the list is cut with the spans, not judged.
1642 let judged_lanes: Vec<Lane> = lanes.iter().copied().filter(|l| l.kind == LaneKind::Audio).collect();
1643 if judged_lanes.len() < 2 {
1644 return fail(format!(
1645 "a joint cut judges two or more audio lanes, and lanes has {}: give target with the one audio lane, and lanes for the lanes to cut with it",
1646 judged_lanes.len()
1647 ));
1648 }
1649 let (judged, thr_note) = match joint_thresholds(s, &judged_lanes, cfg, threshold_given(args)) {
1650 Ok(j) => j,
1651 Err(e) => return fail(e),
1652 };
1653 // The same regions the joint silence reports for these args: the cut is made on those.
1654 let found = match find_joint(s, &judged, cfg) {
1655 Ok(f) => f,
1656 Err(e) => return fail(e),
1657 };
1658 (joint_label(lanes), Vec::new(), judged, thr_note, found, cfg)
1659 }
1660 (None, Some(target)) => {
1661 let name = label(s, target);
1662 let linked = default_cut_scope(s, target);
1663 let (cfg, thr_note) = if threshold_given(args) {
1664 (cfg, None)
1665 } else {
1666 match auto_threshold(s, target) {
1667 Ok((t, note)) => (Settings { threshold_db: t, ..cfg }, Some(note)),
1668 Err(e) => return fail(e),
1669 }
1670 };
1671 // The same regions `silence` reports for these args: the cut is made on exactly those.
1672 let found = match scan(s, target.clone(), cfg) {
1673 Ok(f) => f,
1674 Err(e) => return fail(e),
1675 };
1676 (name, linked, Vec::new(), thr_note, found, cfg)
1677 }
1678 _ => return fail("cut_silence needs a target, or two or more lanes to cut together".into()),
1679 };
1680 if found.scanned == 0 {
1681 return fail(format!(
1682 "nothing to scan on {name}: {}",
1683 found.no_audio.join("; ")
1684 ));
1685 }
1686 // With a target, `lanes` is the ripple scope: the same spans are cut on each. The target's own
1687 // lane joins them when it is not listed, so the silence is always cut on the lane it was found on.
1688 let mut added_target = None;
1689 let mut scope = match (&joint, lanes_arg(s, args)) {
1690 (Some(lanes), _) => lanes.clone(),
1691 (None, Ok(Some(mut v))) => {
1692 if let Some(l) = target.as_ref().and_then(target_lane).filter(|l| !v.contains(l)) {
1693 v.insert(0, l);
1694 added_target = Some(l);
1695 }
1696 v
1697 }
1698 (None, Ok(None)) => linked,
1699 (None, Err(e)) => return fail(e),
1700 };
1701 // Locks, as the ripple rule has them. A locked lane the cut would move refuses, with the way
1702 // out: the target's own lane, a lane named in `lanes`, a lane a take reaches through its link.
1703 // A mix's default scope (every lane) refuses too, naming each locked lane, and changes nothing.
1704 // Captions ride the cut: every caption lane the scope does not name joins it, and a locked one stays put.
1705 let locked_captions = super::listen::ride_captions(s, &mut scope);
1706 let locked: Vec<Lane> = scope.iter().copied().filter(|&l| s.lane_locked(l)).collect();
1707 if let Some((&first, rest)) = locked.split_first() {
1708 let mut why = lock_refusal(first);
1709 if !rest.is_empty() {
1710 let names: Vec<String> = rest.iter().map(|&l| parse::lane_name(l)).collect();
1711 why.push_str(&format!("; lanes {} are locked too", names.join(", ")));
1712 }
1713 return fail(format!("cut_silence refused: {why}; nothing changed"));
1714 }
1715 if scope.is_empty() {
1716 return fail(format!("cut_silence refused: every lane on {name} is locked; unlock one with lane_flags"));
1717 }
1718 let scope_names: Vec<String> = scope.iter().map(|&l| parse::lane_name(l)).collect();
1719 // Both the dry run and the real run name the lanes the cut takes, the same way.
1720 let lanes_named = format!("{} lane(s) ({})", scope_names.len(), scope_names.join("+"));
1721 let fps = parse::session_fps(s);
1722 let other_lanes = default_target_note(s, args, target.as_ref());
1723 if found.regions.is_empty() {
1724 // Judged without the min_silence and padding, so the reply can name the longest quiet.
1725 let quiet_cfg = Settings { min_silence: 0.0, padding: 0.0, min_keep: 0.0, ..cfg };
1726 let quiet = match (&target, &joint) {
1727 (Some(t), _) => scan(s, t.clone(), quiet_cfg).map(|f| f.regions),
1728 (None, Some(_)) => find_joint(s, &judged, quiet_cfg).map(|f| f.regions),
1729 (None, None) => Ok(Vec::new()),
1730 };
1731 let quiet = match quiet {
1732 Ok(q) => q,
1733 Err(e) => return fail(e),
1734 };
1735 let longest = quiet.iter().map(|&(a, b)| f64::from(b - a)).fold(0.0, f64::max) / fps;
1736 let thr = if joint.is_some() {
1737 "each lane's threshold".to_string()
1738 } else {
1739 format!("{:.1} dBFS", cfg.threshold_db)
1740 };
1741 let text = no_pause_note(&name, &thr, cfg.min_silence, cfg.padding, longest) + &other_lanes;
1742 return Reply::ok(text).with(json!({
1743 "regions": [], "count": 0, "removed_frames": 0, "dry_run": dry,
1744 "longest_quiet_s": (longest * 1000.0).round() / 1000.0,
1745 }));
1746 }
1747 // Where the cut lanes' clips end: a silence running to one of those ends is the tail.
1748 let clip_ends: Vec<u32> = scope
1749 .iter()
1750 .flat_map(|&l| s.lane_clips(l).iter().map(|c| c.end()))
1751 .collect();
1752 // What each mode acts on: the silence cut back to keep, the silence itself (played fast), or the
1753 // speech inside the target (kept silence). All are (start, len) timeline frames.
1754 let spans = match mode {
1755 CutMode::Cut => cut_spans_for(&found.regions, keep, cfg.padding, fps, &clip_ends),
1756 CutMode::SpeedUp => found.regions.iter().map(|&(a, b)| (a, b - a)).collect(),
1757 CutMode::KeepSilence => match &target {
1758 Some(t) => speech_within(&target_windows(s, t), &found.regions, fps),
1759 None => Vec::new(),
1760 },
1761 };
1762 let gaps = match (&joint, &target) {
1763 (Some(lanes), _) => gap_note(s, lanes, fps),
1764 (None, Some(Target::Lane(l))) => gap_note(s, &[*l], fps),
1765 _ => String::new(),
1766 };
1767 if spans.is_empty() {
1768 let why = match mode {
1769 CutMode::KeepSilence => format!("the silence covers all of {name}, so there is no speech to cut"),
1770 _ => format!("all ≤ keep ({keep} s)"),
1771 };
1772 return Reply::ok(format!(
1773 "{} silence(s) found on {name}, {why}; nothing cut{other_lanes}",
1774 found.regions.len()
1775 ))
1776 .with(json!({
1777 "regions": region_json(&found.regions),
1778 "count": found.regions.len(),
1779 "removed_frames": 0,
1780 "dry_run": dry,
1781 }));
1782 }
1783
1784 // Read before the cut: the audio on unlisted lanes that the cut runs through.
1785 let spanning = unlisted_spanning(s, &scope, &spans);
1786 let start = s.history_pushes();
1787 // A dry run is a trial: its redo history and redo ledger are put back once it is undone.
1788 let trial = start_trial(s, dry).map(|redo| Trial { redo, ledger: std::mem::take(&mut srv.redo_ledger) });
1789 let end_before = parse::session_end(s);
1790 let lanes_before = super::listen::media_end(s, &scope);
1791 let sound_before = sound_frames(s, &scope);
1792 let cues_before = super::listen::scope_cues(s, &scope);
1793 // Each span is cut as found: its edges are inside the silence, so no kept sliver of speech
1794 // lies between two spans for the edit's sliver join to delete.
1795 let shape0 = super::edit::shape(s);
1796 let applied = match mode {
1797 CutMode::SpeedUp => s.speed_regions(&spans, speed, &scope),
1798 _ => s.cut_regions(&spans, &scope),
1799 };
1800 if let Err(e) = applied {
1801 let rolled = roll_back_cut(srv, start, trial);
1802 srv.trim_ledger();
1803 keep_clean_marks(srv, was_clean);
1804 let note = if rolled {
1805 ""
1806 } else {
1807 " (could not roll every step back; check the project)"
1808 };
1809 let verb = if mode == CutMode::SpeedUp { "speed refused" } else { "cut refused" };
1810 return fail(format!("{verb}: {e}; nothing changed{note}"));
1811 }
1812 // Titles move with a cut as they do for cut_regions. A speed-up closes only part of each silence's
1813 // room, which moves the later titles by an amount move_titles_for_cuts does not model, so they keep
1814 // their times there.
1815 let moved = if mode != CutMode::SpeedUp && super::edit::has_picture(&scope) {
1816 match super::edit::move_titles_for_cuts(s, &spans, fps) {
1817 Ok(m) => m,
1818 Err(e) => {
1819 roll_back_cut(srv, start, trial);
1820 keep_clean_marks(srv, was_clean);
1821 return fail(format!("cut refused: {e}; nothing changed"));
1822 }
1823 }
1824 } else {
1825 Vec::new()
1826 };
1827 let from = spans.first().map_or(0, |sp| sp.0);
1828 let effects = super::edit::side_effects(&shape0, &super::edit::shape(s), "cut_regions");
1829 let ripple = format!(
1830 "{}{}{}{}{}",
1831 super::edit::titles_note(&moved),
1832 super::edit::left_behind(s, &scope, from),
1833 super::edit::caption_drift(s, args, &scope, from),
1834 super::listen::caption_changes(&cues_before, &super::listen::scope_cues(s, &scope)),
1835 super::listen::caption_tail_note(s, fps)
1836 );
1837 let end_after = parse::session_end(s);
1838 // Read now, while the cut is in place: a dry run rolls it back below.
1839 let overrun = overrun_note(s, &scope, fps);
1840 let lanes_after = super::listen::media_end(s, &scope);
1841 let sound_after = sound_frames(s, &scope);
1842 // The pause actually left, read back from the sound after the cut and before any undo below.
1843 // A pause is what a cut leaves; a speed-up or a kept silence leaves none to measure.
1844 let pauses = match (mode, &target) {
1845 (CutMode::Cut, Some(t)) => measured_cut_pauses(s, t, &spans, cfg, fps),
1846 (CutMode::Cut, None) => measured_joint_pauses(s, &judged, &spans, fps),
1847 _ => Ok(Vec::new()),
1848 };
1849 // Measured on the cut lanes: a cut on A1 alone shortens A1 even when a longer lane sets the timeline end.
1850 let removed = lanes_before.saturating_sub(lanes_after);
1851 let removed_secs = parse::secs(removed, fps);
1852 // The share is of the sound: the clips' own frames, so a lead-in gap is not counted as sound.
1853 let removed_sound = sound_before.saturating_sub(sound_after);
1854
1855 // The same decision for a dry run and a real cut: a cut over the share limit is undone here.
1856 let force = opt_bool(args, "force").unwrap_or(false);
1857 let share = if sound_before > 0 {
1858 f64::from(removed_sound) / f64::from(sound_before)
1859 } else {
1860 0.0
1861 };
1862 // The guard is for a cut that takes sound away by accident. A speed-up removes none, and keep_silence
1863 // removes the speech on purpose, so neither is limited by it.
1864 if mode == CutMode::Cut && !force && share > CUT_SHARE_LIMIT {
1865 let rolled = roll_back_cut(srv, start, trial);
1866 srv.trim_ledger();
1867 keep_clean_marks(srv, was_clean);
1868 let note = if rolled {
1869 ""
1870 } else {
1871 " (could not roll every step back; check the project)"
1872 };
1873 return fail(format!(
1874 "cut refused: it would remove {:.3} s of {:.3} s of sound on {name} ({:.0}%), more than half. Cut spans: {}. Nothing changed{note}. Raise keep or lower threshold_db, or pass force:true to cut anyway.",
1875 parse::secs(removed_sound, fps),
1876 parse::secs(sound_before, fps),
1877 share * 100.0,
1878 span_list(&spans, fps),
1879 ));
1880 }
1881
1882 let mut note = String::new();
1883 if dry {
1884 if !roll_back_cut(srv, start, trial) {
1885 note = " (could not roll every step back; check the project)".into();
1886 }
1887 keep_clean_marks(srv, was_clean);
1888 }
1889 // `s` is not used past this point, so the ledger can be written.
1890 // The count phrase and the verbs for this mode: a kept silence counts the speech it cuts.
1891 let counted = match mode {
1892 CutMode::KeepSilence => format!("{} speech stretch(es) between {} silence(s)", spans.len(), found.regions.len()),
1893 _ => format!("{} of {} silence(s)", spans.len(), found.regions.len()),
1894 };
1895 let rate_txt = format!("{:.2}x", f64::from(speed.permille()) / 1000.0);
1896 let (dry_verb, done_verb) = match mode {
1897 CutMode::Cut => ("would cut".to_string(), "cut".to_string()),
1898 CutMode::SpeedUp => (format!("would speed up to {rate_txt}"), format!("sped up to {rate_txt}")),
1899 CutMode::KeepSilence => ("would cut the speech out".to_string(), "cut the speech out".to_string()),
1900 };
1901 let head = if dry {
1902 format!(
1903 "dry run — {dry_verb} {counted} from {lanes_named}, and would remove {removed_secs:.3} s (the timeline's loss, not the silence found); timeline {:.3} s → {:.3} s; nothing changed{note}",
1904 parse::secs(end_before, fps),
1905 parse::secs(end_after, fps),
1906 )
1907 } else {
1908 record_pushes(
1909 srv,
1910 start,
1911 format!("cut_silence {name} ({} regions)", spans.len()),
1912 );
1913 format!(
1914 "{done_verb} {counted} from {lanes_named}, {removed_secs:.3} s removed; timeline {:.3} s → {:.3} s ({end_after}f) · undo step {}",
1915 parse::secs(end_before, fps),
1916 parse::secs(end_after, fps),
1917 srv.ledger.len(),
1918 )
1919 };
1920 let mut text = head;
1921 text.push_str(&overrun);
1922 text.push_str(&ripple);
1923 if let Some(l) = added_target {
1924 text.push_str(&format!(" · {} is the target, so it is cut with the listed lanes", parse::lane_name(l)));
1925 }
1926 if !locked_captions.is_empty() {
1927 let names: Vec<String> = locked_captions.iter().map(|&l| parse::lane_name(l)).collect();
1928 text.push_str(&format!("; locked captions {} stay put, so they are not cut (unlock them with lane_flags to ride the cut)", names.join(", ")));
1929 }
1930 if !spanning.is_empty() {
1931 text.push_str(&format!(
1932 "; out of step, not cut: {} (audio left in place across the cut; pass its lane in lanes to cut it too)",
1933 spanning.join(", ")
1934 ));
1935 }
1936 let pause_note = match &pauses {
1937 Ok(p) if !p.is_empty() => {
1938 let lo = p.iter().copied().fold(f64::INFINITY, f64::min);
1939 let hi = p.iter().copied().fold(f64::NEG_INFINITY, f64::max);
1940 if hi - lo < 0.005 {
1941 format!("{lo:.2} s")
1942 } else {
1943 format!("{lo:.2}–{hi:.2} s")
1944 }
1945 }
1946 Ok(_) => "none (no cut joints)".to_string(),
1947 Err(e) => format!("not measured ({e})"),
1948 };
1949 if mode == CutMode::Cut {
1950 text.push_str(&format!(" · pauses now {pause_note} (measured after the cut on {name})"));
1951 }
1952 if let Some(note) = &thr_note {
1953 text.push_str(&format!("\nthreshold: {note}"));
1954 }
1955 text.push_str(&gaps);
1956 if !effects.is_empty() {
1957 text.push_str(&format!("\neffects: {}", effects.join("; ")));
1958 }
1959 // The lines are the spans cut, as the timeline loses them: the silence's frames less what is kept.
1960 let cut_regions: Vec<(u32, u32)> = spans.iter().map(|&(a, len)| (a, a + len)).collect();
1961 for line in region_lines(&cut_regions, fps) {
1962 text.push('\n');
1963 text.push_str(&line);
1964 }
1965 if !found.no_audio.is_empty() {
1966 text.push_str(&format!(
1967 "\nskipped, no audio track: {}",
1968 found.no_audio.join("; ")
1969 ));
1970 }
1971 let structured = json!({
1972 "regions": region_json(&cut_regions),
1973 "count": found.regions.len(),
1974 "cut_count": spans.len(),
1975 "lanes": scope_names,
1976 "joint": joint.is_some(),
1977 "out_of_step": spanning,
1978 "removed_frames": removed,
1979 "removed_sound_frames": removed_sound,
1980 "timeline_frames_before": end_before,
1981 "timeline_frames": if dry { end_before } else { end_after },
1982 "pauses_measured_s": pauses.as_ref().ok().map(|p| p.iter().map(|x| (x * 1000.0).round() / 1000.0).collect::<Vec<f64>>()),
1983 "dry_run": dry,
1984 "undo_steps": srv.ledger.len(),
1985 });
1986 Reply::ok(text).with(structured)
1987}
1988
1989// ---- levels ---------------------------------------------------------------
1990
1991/// `[from, to)` from `range`, clamped to `[lo, hi)`. Frames for a timeline span,
1992/// source frames for a source. A time past the end of the span is refused by name,
1993/// in seconds, rather than clamped into an empty range.
1994fn range_arg(args: &Value, fps: f64, lo: u32, hi: u32, name: &str) -> Result<(u32, u32), String> {
1995 let Some(r) = args.get("range").filter(|v| !v.is_null()) else {
1996 return Ok((lo, hi));
1997 };
1998 let obj = r
1999 .as_object()
2000 .ok_or("`range` must be {from, to}, each a time such as 450f or 15.0s")?;
2001 let pick = |k: &str, dv: u32| -> Result<u32, String> {
2002 match obj.get(k) {
2003 None | Some(Value::Null) => Ok(dv),
2004 Some(v) => parse::frame(v, fps, hi),
2005 }
2006 };
2007 let (raw_from, raw_to) = (pick("from", lo)?, pick("to", hi)?);
2008 // The timeline shows times to the millisecond, and a `to` one frame past the end is the end.
2009 let secs = |f: u32| format!("{:.3}s", parse::secs(f, fps));
2010 let raw_to = if hi < u32::MAX && raw_to > hi && raw_to - hi <= 1 { hi } else { raw_to };
2011 if hi < u32::MAX && (raw_from > hi || raw_to > hi) {
2012 return Err(format!(
2013 "range {}–{} is past the end of {name} ({})",
2014 secs(raw_from),
2015 secs(raw_to),
2016 secs(hi)
2017 ));
2018 }
2019 let (from, to) = (raw_from.clamp(lo, hi), raw_to.clamp(lo, hi));
2020 if to <= from {
2021 return Err(format!(
2022 "range is empty: it runs from {} to {} in {name}",
2023 secs(from),
2024 secs(to)
2025 ));
2026 }
2027 Ok((from, to))
2028}
2029
2030/// One value per window across a timeline span, with gaps and silent files read as
2031/// `SILENT_DB`. Returns the time of the first window in seconds and the values.
2032fn span_windows(reads: &[(Clip, Option<Vec<f32>>)], fps: f64, span: (u32, u32)) -> (f64, Vec<f32>) {
2033 let w = f64::from(WINDOWS_PER_SEC);
2034 let first = (f64::from(span.0) / fps * w).floor() as usize;
2035 let last = (f64::from(span.1) / fps * w).ceil() as usize;
2036 let values = (first..last)
2037 .map(|i| {
2038 let t = i as f64 / w;
2039 reads
2040 .iter()
2041 .find(|(c, _)| t >= f64::from(c.start) / fps && t < f64::from(c.end()) / fps)
2042 .and_then(|(c, levels)| {
2043 let levels = levels.as_ref()?;
2044 let src_secs = c.source_offset_f((t - f64::from(c.start) / fps) * fps) / fps;
2045 let j = (src_secs * w).floor() as usize;
2046 levels.get(j).copied()
2047 })
2048 .unwrap_or(SILENT_DB)
2049 })
2050 .collect();
2051 (first as f64 / w, values)
2052}
2053
2054/// Groups windows into `per_sec` values each: the power mean, in dB, floored at
2055/// `SILENT_DB`, so a loud window and a quiet one average as sound does.
2056fn bucket(windows: &[f32], per_sec: f64) -> Vec<f32> {
2057 if windows.is_empty() {
2058 return Vec::new();
2059 }
2060 let w = f64::from(WINDOWS_PER_SEC);
2061 let n = ((windows.len() as f64) * per_sec / w).ceil().max(1.0) as usize;
2062 let mut sum = vec![0f64; n];
2063 let mut count = vec![0u32; n];
2064 for (k, &v) in windows.iter().enumerate() {
2065 let b = (((k as f64) * per_sec / w).floor() as usize).min(n - 1);
2066 sum[b] += 10f64.powf(f64::from(v) / 10.0);
2067 count[b] += 1;
2068 }
2069 (0..n)
2070 .map(|b| {
2071 if count[b] == 0 {
2072 SILENT_DB
2073 } else {
2074 let db = 10.0 * (sum[b] / f64::from(count[b])).log10();
2075 db.max(f64::from(SILENT_DB)) as f32
2076 }
2077 })
2078 .collect()
2079}
2080
2081fn lane_end(s: &PlaybackSession, l: Lane) -> u32 {
2082 s.lane_clips(l).last().map_or(0, |c| c.end())
2083}
2084
2085fn run_levels(srv: &mut Server, args: &Value) -> Reply {
2086 let s = tri!(srv.session_ref());
2087 let Some(raw) = opt_str(args, "target") else {
2088 return fail(
2089 "missing `target`: give a clip address such as A1@0, a lane such as A1, src:N, or mix"
2090 .into(),
2091 );
2092 };
2093 let per_sec = match opt_f64(args, "per_sec") {
2094 None => 2.0,
2095 Some(p) if p.is_finite() && p > 0.0 && p <= 50.0 => p,
2096 Some(p) => {
2097 return fail(format!(
2098 "per_sec {p} is out of range: per_sec is buckets per second, a number above 0 up to 50, e.g. 10"
2099 ));
2100 }
2101 };
2102 let target = match resolve(s, raw) {
2103 Ok(t) => t,
2104 Err(e) => return fail(e),
2105 };
2106 let fps = parse::session_fps(s);
2107 let (lo, hi) = match &target {
2108 Target::Source(_) => (0, u32::MAX),
2109 Target::Clip(_, c) => (c.start, c.end()),
2110 Target::Lane(l) => (0, lane_end(s, *l)),
2111 Target::Mix => (0, parse::session_end(s)),
2112 };
2113 if hi == 0 {
2114 return fail(format!("{} has no clips to measure", label(s, &target)));
2115 }
2116 let (from, to) = match range_arg(args, fps, lo, hi, &label(s, &target)) {
2117 Ok(r) => r,
2118 Err(e) => return fail(e),
2119 };
2120 let name = label(s, &target);
2121
2122 let mut notes: Vec<String> = Vec::new();
2123 let lane_of_target = audio_lane_of(&target);
2124 let (base, mut windows) = match target {
2125 Target::Source(n) => {
2126 if let Some(why) = offline_refusal_for(s, &name, &[n]) {
2127 return fail(why);
2128 }
2129 let src = &s.sources()[n];
2130 let from_s = f64::from(from) / fps;
2131 let to_s = if to == u32::MAX {
2132 f64::INFINITY
2133 } else {
2134 f64::from(to) / fps
2135 };
2136 match silence::levels(&src.path, src.audio_stream, (from_s, to_s)) {
2137 Ok(Some(v)) => (from_s, v),
2138 Ok(None) => {
2139 return fail(format!("{name} has no audio track: nothing to measure"));
2140 }
2141 Err(e) => return fail(format!("reading the sound of {name}: {e}")),
2142 }
2143 }
2144 Target::Mix => {
2145 let wav = match render_mix(s) {
2146 Ok(w) => w,
2147 Err(e) => return fail(e),
2148 };
2149 let from_s = f64::from(from) / fps;
2150 let to_s = if to >= hi {
2151 f64::INFINITY
2152 } else {
2153 f64::from(to) / fps
2154 };
2155 match silence::levels(&wav.0, 0, (from_s, to_s)) {
2156 Ok(Some(v)) => (from_s, v),
2157 Ok(None) => {
2158 return fail(format!("{name} has no sound track: nothing to measure"));
2159 }
2160 Err(e) => return fail(format!("reading the mix: {e}")),
2161 }
2162 }
2163 _ => {
2164 let mut reads = Vec::new();
2165 let mut silent = Vec::new();
2166 for (lane, clip) in clips_of(s, target) {
2167 match read(s, lane, &clip, fps) {
2168 Ok(levels) => {
2169 if levels.is_none() {
2170 silent.push(format!(
2171 "src:{} {}",
2172 clip.source,
2173 source_name(s, clip.source)
2174 ));
2175 }
2176 reads.push((clip, levels));
2177 }
2178 Err(e) => return fail(e),
2179 }
2180 }
2181 if !silent.is_empty() {
2182 notes.push(format!(
2183 "no audio track, read as silence: {}",
2184 silent.join(", ")
2185 ));
2186 }
2187 span_windows(&reads, fps, (from, to))
2188 }
2189 };
2190 if windows.is_empty() {
2191 return fail(format!("{name}: the span is empty"));
2192 }
2193 // A lane under a duck reads as it plays: the duck comes off its windows too.
2194 if let Some(lane) = lane_of_target {
2195 let offsets = match duck_offsets(s, lane, to, fps) {
2196 Ok(v) => v,
2197 Err(e) => return fail(e),
2198 };
2199 if let Some(note) = duck_note(s, lane) {
2200 let first = (f64::from(from) / fps * f64::from(WINDOWS_PER_SEC)).floor() as usize;
2201 apply_offsets_to_windows(&mut windows, first, &offsets);
2202 notes.push(note);
2203 }
2204 // A muted lane is left out of the mix and export, so its own sound is all this reads.
2205 if s.lane_muted(lane) {
2206 notes.push(muted_note(lane));
2207 }
2208 }
2209
2210 // Summary over the 20 ms windows themselves, not over the grouped values.
2211 let w = f64::from(WINDOWS_PER_SEC);
2212 let (mut loud, mut loud_at, mut quiet, mut quiet_at) = (f32::MIN, 0usize, f32::MAX, 0usize);
2213 let (mut power, mut below) = (0f64, 0usize);
2214 for (i, &v) in windows.iter().enumerate() {
2215 if v > loud {
2216 loud = v;
2217 loud_at = i;
2218 }
2219 if v < quiet {
2220 quiet = v;
2221 quiet_at = i;
2222 }
2223 // The mean is taken over power, not over the dB values, as bucket does.
2224 power += 10f64.powf(f64::from(v) / 10.0);
2225 if v <= -40.0 {
2226 below += 1;
2227 }
2228 }
2229 let n = windows.len() as f64;
2230 let mean = (10.0 * (power / n).log10()).max(f64::from(SILENT_DB));
2231 let at = |i: usize| base + i as f64 / w;
2232 // Every figure says the window it measures: the extremes are single 20 ms windows, the
2233 // rows below are per-second groups of them.
2234 let summary = format!(
2235 "loudest 20 ms window {:.0} dBFS at {:.2}s · quietest 20 ms window {:.0} dBFS at {:.2}s · mean {mean:.1} dBFS (power mean of the 20 ms windows) · {:.0}% of windows at or below -40 dBFS",
2236 loud,
2237 at(loud_at),
2238 quiet,
2239 at(quiet_at),
2240 below as f64 / n * 100.0,
2241 );
2242
2243 let values = bucket(&windows, per_sec);
2244 let header = format!(
2245 "{name} levels dBFS, {per_sec}/s (power mean of each group of 20 ms windows), {:.1}–{:.1}s",
2246 base,
2247 base + n / w
2248 );
2249 let rows: Vec<String> = values
2250 .chunks(10)
2251 .enumerate()
2252 .map(|(r, chunk)| {
2253 let t = base + (r * 10) as f64 / per_sec;
2254 let mut line = format!("{t:>6.1}s ");
2255 for v in chunk {
2256 // Five wide: "-120" is four characters, and a column must keep a gap after it.
2257 line.push_str(&format!("{:>5}", v.round() as i32));
2258 }
2259 line
2260 })
2261 .collect();
2262
2263 // Fixed parts first, then as many rows as the cap leaves room for.
2264 let fixed = header.len() + summary.len() + notes.iter().map(|x| x.len() + 1).sum::<usize>();
2265 let budget = CAP.saturating_sub(fixed + 120);
2266 let mut used = 0usize;
2267 let mut shown = 0usize;
2268 for row in &rows {
2269 if used + row.len() + 1 > budget {
2270 break;
2271 }
2272 used += row.len() + 1;
2273 shown += 1;
2274 }
2275 let mut text = String::new();
2276 text.push_str(&header);
2277 text.push('\n');
2278 text.push_str(&summary);
2279 for note in &notes {
2280 text.push('\n');
2281 text.push_str(note);
2282 }
2283 for row in rows.iter().take(shown) {
2284 text.push('\n');
2285 text.push_str(row);
2286 }
2287 if shown < rows.len() {
2288 let suggest = ((per_sec * shown as f64 / rows.len() as f64) * 10.0).floor() / 10.0;
2289 text.push_str(&format!(
2290 "\n… {} more row(s) cut to stay under 4 KB; per_sec {:.1} or a narrower range shows the rest",
2291 rows.len() - shown,
2292 suggest.max(0.1),
2293 ));
2294 }
2295
2296 let kept: Vec<f64> = values
2297 .iter()
2298 .take(MAX_VALUES)
2299 .map(|&v| (f64::from(v) * 10.0).round() / 10.0)
2300 .collect();
2301 // Levels are RMS; the peak that clips is the true peak, so a target whose true peak is above
2302 // the -1 dBTP ceiling is warned here too, as loudness warns.
2303 if let Ok(r) = measure_target(s, args, raw)
2304 && let Some(w) = peak_warning(r.loud.true_peak_dbtp, r.loud.integrated_lufs, &r.span, r.name == "mix")
2305 {
2306 text.push('\n');
2307 text.push_str(&w);
2308 }
2309 let structured = json!({
2310 "per_sec": per_sec,
2311 "start_secs": base,
2312 "values": kept,
2313 "truncated": values.len() > MAX_VALUES,
2314 });
2315 Reply::ok(text).with(structured)
2316}
2317
2318/// The true-peak ceiling the loudness tools hold the mix to, in dBTP.
2319const PEAK_CEILING_DBTP: f64 = -1.0;
2320
2321/// The warning for a true peak above the -1 dBTP ceiling, judged on the value as it is shown (one
2322/// decimal): a peak that reads -1.0 is within spec, so -0.96 does not warn. Headroom gone, so a
2323/// gain up is held or clips.
2324fn peak_warning(true_peak_dbtp: f64, integrated_lufs: f64, span: &str, mix: bool) -> Option<String> {
2325 if !true_peak_dbtp.is_finite() || shown_peak(true_peak_dbtp) <= PEAK_CEILING_DBTP {
2326 return None;
2327 }
2328 let base = format!(
2329 "WARNING: true peak {} dBTP over {span} is above the -1 dBTP ceiling (clips on some players)",
2330 signed_figure(true_peak_dbtp)
2331 );
2332 if !integrated_lufs.is_finite() {
2333 return Some(base);
2334 }
2335 // The headroom only matters when the target needs a gain up: a louder mix comes down under a
2336 // normalize, and its peaks come down with it.
2337 let to_normalize = NORMALIZE_TARGET_LUFS - integrated_lufs;
2338 // The cut the peak needs to come down to the ceiling. A normalize makes the larger of the two
2339 // cuts, so when the peak needs more, the level it lands on is the one the peak allows.
2340 let peak_cut = (true_peak_dbtp - PEAK_CEILING_DBTP).max(0.0);
2341 Some(if to_normalize > 0.05 {
2342 format!("{base}; no headroom, so a normalize to {NORMALIZE_TARGET_LUFS:.0} or a gain up is held by the ceiling or clips")
2343 } else if to_normalize < -0.05 && peak_cut > -to_normalize + 0.05 {
2344 let held = integrated_lufs - peak_cut;
2345 let way = if mix {
2346 "allow_limiter:true".to_string()
2347 } else {
2348 "a normalize of the mix with allow_limiter:true".to_string()
2349 };
2350 format!(
2351 "{base}; a normalize to {NORMALIZE_TARGET_LUFS:.0} would turn it down {:.1} dB, but the {PEAK_CEILING_DBTP:.0} dBTP ceiling holds it at {} LUFS unless {way}",
2352 -to_normalize,
2353 figure(held),
2354 )
2355 } else if to_normalize < -0.05 {
2356 format!(
2357 "{base}; a normalize to {NORMALIZE_TARGET_LUFS:.0} would turn it down {:.1} dB",
2358 -to_normalize
2359 )
2360 } else {
2361 base
2362 })
2363}
2364
2365/// The integrated target `normalize` aims for by default: YouTube and Spotify.
2366const NORMALIZE_TARGET_LUFS: f64 = -14.0;
2367
2368// ---- loudness -------------------------------------------------------------
2369
2370/// Whether `target` names the whole mix rather than an address.
2371fn is_mix(raw: &str) -> bool {
2372 raw.trim().eq_ignore_ascii_case("mix")
2373}
2374
2375/// The lane an audio target plays on; `None` for a source or a video lane.
2376fn audio_lane_of(t: &Target) -> Option<Lane> {
2377 match t {
2378 Target::Lane(l) | Target::Clip(l, _) if l.kind == LaneKind::Audio => Some(*l),
2379 _ => None,
2380 }
2381}
2382
2383/// Takes the duck's dB off the windows from timeline window `first` on. Silent
2384/// windows stay silent.
2385fn apply_offsets_to_windows(windows: &mut [f32], first: usize, offsets: &[f32]) {
2386 if offsets.is_empty() {
2387 return;
2388 }
2389 for (i, v) in windows.iter_mut().enumerate() {
2390 if *v > SILENT_DB {
2391 let off = offsets.get(first + i).copied().unwrap_or(0.0);
2392 *v = (*v + off).max(SILENT_DB);
2393 }
2394 }
2395}
2396
2397/// Takes the duck's dB off one clip's windows. Window j of a clip is at timeline
2398/// time `start + j / (speed * WINDOWS_PER_SEC)`, which is where the duck's windows
2399/// are read.
2400fn apply_duck(levels: &mut [f32], clip: &Clip, fps: f64, offsets: &[f32]) {
2401 if offsets.is_empty() {
2402 return;
2403 }
2404 let w = f64::from(WINDOWS_PER_SEC);
2405 for (j, v) in levels.iter_mut().enumerate() {
2406 if *v > SILENT_DB {
2407 let t = f64::from(clip.start) / fps + clip.timeline_offset_f(j as f64 / w * fps) / fps;
2408 let off = offsets
2409 .get((t * w).floor() as usize)
2410 .copied()
2411 .unwrap_or(0.0);
2412 *v = (*v + off).max(SILENT_DB);
2413 }
2414 }
2415}
2416
2417/// Measures a source file's own sound, `range` in seconds.
2418fn source_loudness(
2419 s: &PlaybackSession,
2420 n: usize,
2421 range: Option<(f64, f64)>,
2422) -> Result<Loudness, String> {
2423 let src = &s.sources()[n];
2424 loudness::measure_file(&src.path, src.audio_stream, range)
2425 .map_err(|e| format!("reading the sound of src:{n} {}: {e}", source_name(s, n)))?
2426 .ok_or_else(|| format!("src:{n} {} has no audio track", source_name(s, n)))
2427}
2428
2429
2430/// One measurement, as the engine plays it.
2431struct Read {
2432 name: String,
2433 /// The span measured, in seconds and the target's name: "0.000–11.633s of A2".
2434 span: String,
2435 /// The lane gain (dB) the figures include, for an audio lane or clip.
2436 lane_gain: Option<f64>,
2437 /// "includes the duck under A3 (...)" (or "the ducks under A2 and A3") when the measured lane is under a duck.
2438 duck: Option<String>,
2439 loud: Loudness,
2440 seconds: f64,
2441}
2442
2443/// The note that a lane's figures include its ducks, the same words `levels` uses.
2444fn duck_note(s: &PlaybackSession, lane: Lane) -> Option<String> {
2445 let ducks = s.lane_duck_list(lane);
2446 if ducks.is_empty() {
2447 return None;
2448 }
2449 let each: Vec<String> = ducks
2450 .iter()
2451 .map(|d| {
2452 format!(
2453 "{} ({:+.1} dB at most)",
2454 parse::lane_name(Lane::new(LaneKind::Audio, d.under)),
2455 f64::from(d.depth_db)
2456 )
2457 })
2458 .collect();
2459 let word = if each.len() == 1 { "duck" } else { "ducks" };
2460 Some(format!("includes the {word} under {}", join_and(&each)))
2461}
2462
2463/// The note on a muted lane's levels: the figures are its own sound, which the mix does not play.
2464fn muted_note(lane: Lane) -> String {
2465 format!(
2466 "{} is muted: it is silent in the mix and export; the level shown is the lane's own sound",
2467 parse::lane_name(lane)
2468 )
2469}
2470
2471/// `a`, `a and b`, `a, b and c`.
2472fn join_and(items: &[String]) -> String {
2473 match items.split_last() {
2474 None => String::new(),
2475 Some((last, [])) => last.clone(),
2476 Some((last, rest)) => format!("{} and {last}", rest.join(", ")),
2477 }
2478}
2479
2480/// The span a measurement covers, named in seconds with the target.
2481fn span_label(from: u32, to: u32, fps: f64, name: &str) -> String {
2482 if to == u32::MAX {
2483 format!("{:.3}s to the end of {name}", parse::secs(from, fps))
2484 } else {
2485 format!("{:.3}–{:.3}s of {name}", parse::secs(from, fps), parse::secs(to, fps))
2486 }
2487}
2488
2489fn measure_target(s: &PlaybackSession, args: &Value, raw: &str) -> Result<Read, String> {
2490 let started = Instant::now();
2491 let fps = parse::session_fps(s);
2492 let end = parse::session_end(s);
2493 let target = resolve(s, raw)?;
2494 let name = label(s, &target);
2495 // Each arm names the span it measured.
2496 let span: String;
2497 let (loud, lane_gain, duck) = match target {
2498 Target::Mix => {
2499 let (from, to) = range_arg(args, fps, 0, end, &name)?;
2500 span = span_label(from, to, fps, &name);
2501 (measure_mix(s, from, to, fps, end)?, None, None)
2502 }
2503 Target::Lane(lane) => {
2504 if lane.kind != LaneKind::Audio {
2505 return Err(format!(
2506 "{name} is a video lane with no sound of its own; measure an audio lane (A1) or mix"
2507 ));
2508 }
2509 let lane_end_frame = lane_end(s, lane);
2510 if lane_end_frame == 0 {
2511 return Err(format!("{name} has no clips to measure"));
2512 }
2513 let (from, to) = range_arg(args, fps, 0, lane_end_frame, &name)?;
2514 span = span_label(from, to, fps, &name);
2515 let g = f64::from(s.lane_gain_db(lane));
2516 let l = measure_lane(s, lane, from, to, fps)?
2517 .ok_or_else(|| format!("{name} has no sound to measure"))?;
2518 (shifted(l, g), Some(g), duck_note(s, lane))
2519 }
2520 Target::Clip(lane, clip) if lane.kind == LaneKind::Audio => {
2521 let (from, to) = range_arg(args, fps, clip.start, clip.end(), &name)?;
2522 span = span_label(from, to, fps, &name);
2523 let g = f64::from(s.lane_gain_db(lane));
2524 let l = measure_lane(s, lane, from, to, fps)?
2525 .ok_or_else(|| format!("{name} has no sound to measure"))?;
2526 (shifted(l, g), Some(g), duck_note(s, lane))
2527 }
2528 Target::Clip(_, clip) => {
2529 // A video clip's sound is its source's, read through the clip's in
2530 // point and speed.
2531 let (from, to) = range_arg(args, fps, clip.start, clip.end(), &name)?;
2532 span = span_label(from, to, fps, &name);
2533 let src_at = |t: u32| f64::from(clip.in_frame) + clip.source_offset_f(f64::from(t - clip.start));
2534 let range = (src_at(from) / fps, src_at(to) / fps);
2535 (source_loudness(s, clip.source, Some(range))?, None, None)
2536 }
2537 Target::Source(n) => {
2538 if let Some(why) = offline_refusal_for(s, &name, &[n]) {
2539 return Err(why);
2540 }
2541 // The file's own length bounds the range, so a range past its end is refused by name.
2542 let src = s.sources().get(n).ok_or_else(|| no_source(s, n))?;
2543 let secs = engine::probe_media(&src.path).duration_secs.filter(|d| *d > 0.0);
2544 let end = secs.map_or(u32::MAX, |d| (d * fps).ceil() as u32);
2545 let (from, to) = range_arg(args, fps, 0, end, &name)?;
2546 span = span_label(from, to, fps, &name);
2547 let range = (from != 0 || to != end).then(|| {
2548 let end_s = if end == u32::MAX { f64::INFINITY } else { f64::from(to) / fps };
2549 (f64::from(from) / fps, end_s)
2550 });
2551 (source_loudness(s, n, range)?, None, None)
2552 }
2553 };
2554 Ok(Read {
2555 name,
2556 span,
2557 lane_gain,
2558 duck,
2559 loud,
2560 seconds: started.elapsed().as_secs_f64(),
2561 })
2562}
2563
2564/// A figure for text: one decimal, or `silent` for no energy.
2565fn figure(x: f64) -> String {
2566 if x.is_finite() {
2567 format!("{x:.1}")
2568 } else {
2569 "silent".into()
2570 }
2571}
2572
2573/// A true peak as the text shows it: one decimal, rounded half away from zero.
2574fn shown_peak(x: f64) -> f64 {
2575 (x * 10.0).round() / 10.0
2576}
2577
2578/// A true peak for text: one decimal with its sign, so a level over zero reads `+0.3`.
2579fn signed_figure(x: f64) -> String {
2580 if x.is_finite() {
2581 format!("{x:+.1}")
2582 } else {
2583 "silent".into()
2584 }
2585}
2586
2587fn loudness_text(r: &Read) -> String {
2588 let l = &r.loud;
2589 let gain = match r.lane_gain {
2590 Some(g) => format!(", as played at lane gain {g:+.1} dB"),
2591 None => String::new(),
2592 };
2593 let duck = r.duck.as_ref().map_or_else(String::new, |d| format!(" · {d}"));
2594 let lra = if l.lra_samples >= 2 {
2595 format!("LRA {:.1} LU", l.range_lu)
2596 } else {
2597 "LRA n/a (needs 3.5 s or more of audio: two 3 s short-term values)".into()
2598 };
2599 let short = if l.analysed_secs >= SHORT_TERM_SECS {
2600 figure(l.short_term_max_lufs)
2601 } else {
2602 format!("n/a (under {SHORT_TERM_SECS} s of audio)")
2603 };
2604 format!(
2605 "{} loudness (EBU R128{gain}): integrated {} LUFS · {lra} · true peak {} dBTP · max momentary {} · max short-term {short}{duck} · analysed {:.2} s of audio in {:.2} s{warn}",
2606 r.name,
2607 figure(l.integrated_lufs),
2608 signed_figure(l.true_peak_dbtp),
2609 figure(l.momentary_max_lufs),
2610 l.analysed_secs,
2611 r.seconds,
2612 warn = peak_warning(l.true_peak_dbtp, l.integrated_lufs, &r.span, r.name == "mix").map_or_else(String::new, |w| format!(" · {w}")),
2613 )
2614}
2615
2616/// The EBU R128 short-term window: no short-term value exists for less audio than this.
2617const SHORT_TERM_SECS: f64 = 3.0;
2618
2619fn run_loudness(srv: &mut Server, args: &Value) -> Reply {
2620 let Some(raw) = opt_str(args, "target") else {
2621 return fail(
2622 "missing `target`: give a clip address such as A1@0, a lane such as A1, src:N, or mix"
2623 .into(),
2624 );
2625 };
2626 let s = tri!(srv.session_ref());
2627 let r = match measure_target(s, args, raw) {
2628 Ok(r) => r,
2629 Err(e) => return fail(e),
2630 };
2631 let text = loudness_text(&r);
2632 let l = r.loud;
2633 let structured = json!({
2634 "target": r.name,
2635 "integrated_lufs": l.integrated_lufs,
2636 // Null where the figure is undefined, not a 0.0 that reads as a measurement.
2637 "range_lu": if l.lra_samples >= 2 { json!(l.range_lu) } else { Value::Null },
2638 "true_peak_dbtp": l.true_peak_dbtp,
2639 "sample_peak_dbfs": l.sample_peak_dbfs,
2640 "momentary_max_lufs": l.momentary_max_lufs,
2641 "short_term_max_lufs": if l.analysed_secs >= SHORT_TERM_SECS { json!(l.short_term_max_lufs) } else { Value::Null },
2642 "analysed_secs": l.analysed_secs,
2643 "lane_gain_db": r.lane_gain,
2644 "seconds": r.seconds,
2645 });
2646 Reply::ok(text).with(structured)
2647}
2648
2649/// The clip gain a boost past the lane cap put on a lane's clips, read after the change: each
2650/// clip that moved, by its address (`A1@450`) and the dB it gained, with the lane's gain.
2651struct Spill {
2652 lane: String,
2653 lane_db: f64,
2654 clips: Vec<(String, f64)>,
2655}
2656
2657/// How many clip addresses a split names before it says "and N more".
2658const SPLIT_CLIPS_NAMED: usize = 8;
2659
2660impl Spill {
2661 /// "lane A1 +12.0 dB, clips A1@0 A1@450 +6.0 dB clip gain", or the clips' own figures when they differ.
2662 fn text(&self) -> String {
2663 let lane = format!("lane {} {:+.1} dB", self.lane, self.lane_db);
2664 let same = self.clips.windows(2).all(|w| (w[0].1 - w[1].1).abs() <= 0.05);
2665 if same {
2666 let named: Vec<&str> = self.clips.iter().take(SPLIT_CLIPS_NAMED).map(|(a, _)| a.as_str()).collect();
2667 let more = self.clips.len().saturating_sub(SPLIT_CLIPS_NAMED);
2668 let and = if more > 0 { format!(" and {more} more") } else { String::new() };
2669 format!("{lane}, clips {}{and} {:+.1} dB clip gain", named.join(" "), self.clips[0].1)
2670 } else {
2671 let parts: Vec<String> = self.clips.iter().map(|(a, d)| format!("{a} {d:+.1} dB")).collect();
2672 format!("{lane}, clip gain {}", parts.join(", "))
2673 }
2674 }
2675}
2676
2677/// The clip gain a plan's lane holds now beyond its old clip gains, or `None` when no clip moved.
2678fn spill_of(s: &PlaybackSession, p: &Plan) -> Option<Spill> {
2679 let clips: Vec<(String, f64)> = p
2680 .clips
2681 .iter()
2682 .filter_map(|&(i, old)| {
2683 let moved = f64::from(s.clip_gain_of(p.lane, i)?) - old;
2684 let start = s.lane_clips(p.lane).get(i)?.start;
2685 (moved.abs() > 0.05).then(|| (format!("{}@{start}", parse::lane_name(p.lane)), moved))
2686 })
2687 .collect();
2688 (!clips.is_empty()).then(|| Spill {
2689 lane: parse::lane_name(p.lane),
2690 lane_db: f64::from(s.lane_gain_db(p.lane)),
2691 clips,
2692 })
2693}
2694
2695/// The gain a plan's lane really moved by in total: its lane gain, and the mean clip gain on top.
2696fn total_moved(s: &PlaybackSession, p: &Plan) -> f64 {
2697 let lane = f64::from(s.lane_gain_db(p.lane)) - p.old;
2698 if p.clips.is_empty() {
2699 return lane;
2700 }
2701 let clip: f64 = p
2702 .clips
2703 .iter()
2704 .map(|&(i, old)| f64::from(s.clip_gain_of(p.lane, i).unwrap_or(0.0)) - old)
2705 .sum::<f64>()
2706 / p.clips.len() as f64;
2707 lane + clip
2708}
2709
2710/// The clips a boost put clip gain on, as the reply's structured output lists them: address and dB.
2711fn clip_gain_json<'a>(spills: impl Iterator<Item = &'a Spill>) -> Vec<Value> {
2712 spills
2713 .flat_map(|sp| sp.clips.iter().map(|(clip, db)| json!({ "clip": clip, "change_db": db })))
2714 .collect()
2715}
2716
2717/// The cap a held normalize names: the clip gain when a lane's boost ran past the lane cap into its clips,
2718/// otherwise the lane gain (below the range).
2719fn cap_kind(clamped: &[(String, f64, f64)]) -> &'static str {
2720 if clamped.iter().any(|(_, wanted, _)| *wanted > f64::from(MAX_GAIN_DB)) {
2721 "clip_gain_limit"
2722 } else {
2723 "lane_gain_limit"
2724 }
2725}
2726
2727/// How close a normalize has to land, in LU, before it stops refining.
2728const NORMALIZE_LUFS_TOLERANCE: f64 = 0.1;
2729/// Float slack on the tolerance, so a level exactly 0.1 LU off (after the arithmetic) still counts.
2730const LUFS_EPSILON: f64 = 1e-6;
2731
2732/// Whether a measured integrated level lands on the target: within the tolerance, on the unrounded
2733/// values. The reply shows one decimal, so a level that reads -14.1 can still be within 0.1 of -14.0.
2734fn lufs_reached(lufs: f64, achieved: f64) -> bool {
2735 achieved.is_finite() && (lufs - achieved).abs() <= NORMALIZE_LUFS_TOLERANCE + LUFS_EPSILON
2736}
2737/// How far over the true-peak ceiling the measured sound may sit, in dB.
2738const NORMALIZE_PEAK_TOLERANCE: f64 = 0.05;
2739/// Corrections made after the first change, at most. With the master limiter in circuit each one
2740/// may also lower the limiter's ceiling by the true-peak overshoot the limiter lets through,
2741/// which takes several.
2742const NORMALIZE_PASSES: usize = 8;
2743/// Corrections allowed with the master limiter in circuit. Each one walks the limiter's ceiling down
2744/// by the overshoot, and the inter-sample peaks take several walks to clear, so this is more than the
2745/// plain cap: at 8 a walk could run out one step short of the ceiling.
2746const LIMITED_PASSES: usize = 24;
2747
2748/// The corrections a normalize may make: `LIMITED_PASSES` with the limiter, `NORMALIZE_PASSES` without.
2749fn pass_cap(limited: bool) -> usize {
2750 if limited {
2751 LIMITED_PASSES
2752 } else {
2753 NORMALIZE_PASSES
2754 }
2755}
2756
2757/// How far over the true-peak ceiling a measured result may sit and still count as held. With the
2758/// limiter in circuit the peak must be at or under the ceiling: the walk steps past it by a margin,
2759/// so a result that reads -0.96 against a -1.0 ceiling is not held.
2760fn peak_tolerance(limited: bool) -> f64 {
2761 if limited {
2762 0.0
2763 } else {
2764 NORMALIZE_PEAK_TOLERANCE
2765 }
2766}
2767/// How close under the limiter's ceiling a measured peak must sit to count as held at it, in dB.
2768const LIMITER_AT_CEILING_DB: f64 = 0.25;
2769/// How far (dB) the limiter's ceiling may be walked down from the target's, before the peaks are
2770/// called held. Measured from the target, not a fixed level: a target of -15 dBTP must walk too.
2771const LIMITER_WALK_DB: f64 = 11.0;
2772
2773/// The lowest ceiling the limiter may be walked down to for a true-peak target `tp` (dBTP): the
2774/// walk allowance below it, never past the engine's own limit.
2775fn limiter_floor(tp: f64) -> f64 {
2776 (tp - LIMITER_WALK_DB).max(f64::from(Limiter::MIN_DB))
2777}
2778
2779/// How far the measured true peak sits over the ceiling, in dB (negative when
2780/// under); 0 for silence.
2781fn peak_over(l: &Loudness, ceiling: f64) -> f64 {
2782 if l.true_peak_dbtp.is_finite() {
2783 l.true_peak_dbtp - ceiling
2784 } else {
2785 0.0
2786 }
2787}
2788
2789/// Where a normalize's gain settles: the ceiling the limiter ends at, the
2790/// lanes the lane gain limit held back, the measured result, and the corrections made.
2791struct Settled {
2792 ceiling: f64,
2793 clamped: Vec<(String, f64, f64)>,
2794 after: Loudness,
2795 passes: usize,
2796 stuck: bool,
2797 /// The peaks were cut to the ceiling and the level was left short of it: the ceiling holds it.
2798 cut: bool,
2799}
2800
2801/// Sets `lanes` to their old gains plus `gain` and refines until the level lands on `lufs` and the
2802/// peaks sit under `tp`, measuring after each change. Shared by the mix, one lane and `each`.
2803#[allow(clippy::too_many_arguments)]
2804fn settle(
2805 s: &mut PlaybackSession,
2806 raw: &str,
2807 plans: &[Plan],
2808 lufs: f64,
2809 tp: f64,
2810 limited: bool,
2811 mut ceiling: f64,
2812 mut gain: f64,
2813 unmoved: Option<Loudness>,
2814) -> Result<Settled, String> {
2815 let (mut clamped, mut after) = match unmoved.filter(|_| gain.abs() < 0.01) {
2816 Some(l) => (Vec::new(), l),
2817 None => (set_plans(s, plans, gain), measure_target(s, &json!({}), raw)?.loud),
2818 };
2819 let max_passes = pass_cap(limited);
2820 let tol = peak_tolerance(limited);
2821 let mut passes = 0;
2822 // Set once the peaks have been cut to the ceiling: a louder step after that
2823 // would only breach it again, so the level is left where the ceiling holds it.
2824 let mut cut = false;
2825 // Set when a cut left the measured true peak where it was: the peaks are held by
2826 // something gain does not move (the limiter's inter-sample overshoot), so more cuts are wasted.
2827 let mut stuck = false;
2828 let mut prev_over = f64::INFINITY;
2829 // The level a gain step moves: learned from the last two measurements, since a limiter in
2830 // circuit moves the level by less than the gain it is given.
2831 let mut slope = 1.0_f64;
2832 let mut last: Option<(f64, f64)> = None;
2833 while passes < max_passes && after.integrated_lufs.is_finite() {
2834 let miss = lufs - after.integrated_lufs;
2835 let over = peak_over(&after, tp);
2836 // Every lane held at its gain limit ends the search, unless the limiter still has its peak to
2837 // walk down: a clamp moves no more level, but the ceiling can still come down under the peak.
2838 if (clamped.len() == plans.len() && (!limited || over <= tol))
2839 || (lufs_reached(lufs, after.integrated_lufs) && over <= tol)
2840 {
2841 break;
2842 }
2843 if let Some((g0, l0)) = last {
2844 let (dg, dl) = (gain - g0, after.integrated_lufs - l0);
2845 if dg.abs() > 0.05 && (dl / dg).is_finite() {
2846 slope = (dl / dg).clamp(0.2, 2.0);
2847 }
2848 }
2849 last = Some((gain, after.integrated_lufs));
2850 let level_step = miss / slope;
2851 if limited && over > tol {
2852 // The limiter holds its true-peak ceiling, so a measured overshoot is rare. When one
2853 // comes, the ceiling comes down by the overshoot, and the level is taken again with it.
2854 let next = ceiling - over - NORMALIZE_PEAK_TOLERANCE;
2855 if next < limiter_floor(tp) {
2856 stuck = true;
2857 break;
2858 }
2859 ceiling = next;
2860 if !s.set_limiter(Limiter { on: true, ceiling_db: ceiling as f32 }) {
2861 stuck = true;
2862 break;
2863 }
2864 gain += level_step;
2865 } else {
2866 if cut && over > tol && over >= prev_over - 0.02 {
2867 stuck = true;
2868 break;
2869 }
2870 prev_over = over;
2871 let step = if over > tol {
2872 cut = true;
2873 level_step.min(-over)
2874 } else if cut && miss > 0.0 {
2875 break;
2876 } else if !limited && over < NORMALIZE_PEAK_TOLERANCE && level_step > -over {
2877 // The peaks have less headroom under the ceiling than the level step needs. Gain
2878 // moves the peaks about as far as it moves the level, so the step stops at the
2879 // ceiling; a step past it would be found only after a lane clamp had ended the search.
2880 cut = true;
2881 -over
2882 } else {
2883 level_step
2884 };
2885 if step.abs() < 0.01 {
2886 break;
2887 }
2888 gain += step;
2889 }
2890 clamped = set_plans(s, plans, gain);
2891 passes += 1;
2892 after = measure_target(s, &json!({}), raw)?.loud;
2893 }
2894
2895 Ok(Settled { ceiling, clamped, after, passes, stuck, cut })
2896}
2897
2898/// The loudness `normalize` aims for (`lufs`, default -14) and the true-peak ceiling (`true_peak`,
2899/// default -1), checked.
2900fn normalize_levels(args: &Value) -> Result<(f64, f64), String> {
2901 let lufs = match opt_f64(args, "lufs") {
2902 None => -14.0,
2903 Some(x) if x.is_finite() && (-70.0..=0.0).contains(&x) => x,
2904 Some(x) => return Err(format!("lufs {x} is out of range; it must be -70 to 0")),
2905 };
2906 let tp = match opt_f64(args, "true_peak") {
2907 None => -1.0,
2908 Some(x) if x.is_finite() && (-20.0..=0.0).contains(&x) => x,
2909 Some(x) => return Err(format!("true_peak {x} is out of range; it must be -20 to 0")),
2910 };
2911 Ok((lufs, tp))
2912}
2913
2914/// One lane of `normalize` with `each`, as measured before any change.
2915struct EachLane {
2916 name: String,
2917 played: Loudness,
2918 delta: f64,
2919 tp_binds: bool,
2920 plan: Plan,
2921}
2922
2923/// What a lossy export can add to the true peak: an AAC or Opus encode may land above the timeline's
2924/// peaks, so a ceiling right at 0 dBTP leaves nothing for it.
2925const LOSSY_HEADROOM_NOTE: &str = "AAC/Opus encoding can add up to about 1 dB of true peak; for a lossy export aim the ceiling at -2 dBTP";
2926
2927/// The words a normalize reply leads with: whether the target was reached, before anything else.
2928fn verdict(reached: bool) -> &'static str {
2929 if reached {
2930 "target reached: "
2931 } else {
2932 "short of the target: "
2933 }
2934}
2935
2936/// How far a measured level sits from the target, as a reply words it: "0.90 LU short" or "0.20 LU over".
2937fn short_text(lufs: f64, achieved: f64) -> String {
2938 if achieved <= lufs {
2939 format!("{:.2} LU short", lufs - achieved)
2940 } else {
2941 format!("{:.2} LU over", achieved - lufs)
2942 }
2943}
2944
2945/// The note a rollback that could not take every step back adds; empty when it did.
2946fn rollback_note(rolled: bool) -> &'static str {
2947 if rolled {
2948 ""
2949 } else {
2950 " (could not roll every step back; check the project)"
2951 }
2952}
2953
2954/// Opens a trial for a dry run: the change is made as a real run makes it, then `finish_trial` takes
2955/// it back. The redo history is set aside, since the trial's own steps would clear it, and the undo
2956/// cap holds, so a rolled-back trial leaves the history as it found it (as a rolled-back batch does).
2957fn start_trial(s: &mut PlaybackSession, dry: bool) -> Option<RedoCheckpoint> {
2958 dry.then(|| {
2959 s.hold_history(true);
2960 s.take_redo()
2961 })
2962}
2963
2964/// Takes a trial's steps back, since `start`, and puts its redo history back. True if every step came back.
2965fn finish_trial(s: &mut PlaybackSession, start: u64, redo: RedoCheckpoint) -> bool {
2966 let rolled = undo_n(s, pushed_since(s, start));
2967 s.restore_redo(redo);
2968 s.hold_history(false);
2969 rolled
2970}
2971
2972/// A dry run's set-aside history: its redo stack, and the ledger's redo entries.
2973struct Trial {
2974 redo: RedoCheckpoint,
2975 ledger: Vec<Entry>,
2976}
2977
2978/// Undoes a cut since `start`. A dry run (`trial`) puts back the redo history it set aside. A cut
2979/// rolled back for real leaves no branch to redo, as edit.rs's batch rollback did before it kept
2980/// redo. True if every step came back.
2981fn roll_back_cut(srv: &mut Server, start: u64, trial: Option<Trial>) -> bool {
2982 let Some(s) = srv.session.as_mut() else {
2983 return false;
2984 };
2985 match trial {
2986 Some(t) => {
2987 srv.redo_ledger = t.ledger;
2988 finish_trial(s, start, t.redo)
2989 }
2990 None => {
2991 let n = pushed_since(s, start);
2992 let rolled = undo_n(s, n);
2993 if n > 0 {
2994 s.clear_redo();
2995 srv.redo_ledger.clear();
2996 }
2997 rolled
2998 }
2999 }
3000}
3001
3002/// Whether `allow_limiter` puts the master limiter in the way of a normalize. The linear prediction
3003/// (`tp_binds`: gain would carry the peaks over `tp`) is one reason; the other is a mix that already
3004/// sits over `tp`, because a clipped mix does not fall linearly with gain (the clip moves with it).
3005fn limiter_in_the_way(allow_limiter: bool, tp_binds: bool, played_tp: f64, tp: f64) -> bool {
3006 allow_limiter && (tp_binds || played_tp > tp)
3007}
3008
3009/// The change a normalize makes, measured as it goes. With `limited` the master limiter goes on at
3010/// the ceiling and the gain is taken again from the mix as it then measures; the limiter holds the
3011/// peaks down so the rest of the gain can land. A real run and a dry run both make this change.
3012#[allow(clippy::too_many_arguments)]
3013fn normalize_trial(
3014 s: &mut PlaybackSession,
3015 raw: &str,
3016 plans: &[Plan],
3017 lufs: f64,
3018 hold: f64,
3019 limited: bool,
3020 delta: f64,
3021 played: Loudness,
3022) -> Result<Settled, String> {
3023 let mut gain = delta;
3024 // The limiter's detector is the meter's own true-peak method, so its ceiling is the target: the
3025 // walk aims at the true_peak value (or the lower limiter ceiling) with or without the limiter.
3026 if limited {
3027 // A limiter already on at this ceiling is no change to make, not a refusal.
3028 let want = Limiter { on: true, ceiling_db: hold as f32 };
3029 if s.limiter() != want && !s.set_limiter(want) {
3030 return Err("the engine refused the limiter change".into());
3031 }
3032 let r = measure_target(s, &json!({}), raw)?;
3033 if r.loud.integrated_lufs.is_finite() {
3034 gain = lufs - r.loud.integrated_lufs;
3035 }
3036 }
3037 settle(s, raw, plans, lufs, hold, limited, hold, gain, (!limited).then_some(played))
3038}
3039
3040/// The past tense a reply uses for a change that was made, or the conditional for a dry run, which
3041/// makes the change only to measure it and says so.
3042fn mood(dry: bool, done: &'static str, would: &'static str) -> &'static str {
3043 if dry {
3044 would
3045 } else {
3046 done
3047 }
3048}
3049
3050/// `normalize` with `each`: every audio lane in `lanes` is set on its own, so that each lane alone
3051/// measures `lufs` over its clips and its peaks stay under `true_peak`. One undo step for all of
3052/// them. Nothing changes if any listed lane cannot be measured.
3053fn run_normalize_each(srv: &mut Server, args: &Value) -> Reply {
3054 let (lufs, tp) = match normalize_levels(args) {
3055 Ok(v) => v,
3056 Err(e) => return fail(e),
3057 };
3058 if arg_given(args, "target") {
3059 return fail("each takes `lanes`, not `target`: list the audio lanes to set, such as [\"A1\",\"A2\"]".into());
3060 }
3061 if opt_bool(args, "allow_limiter").unwrap_or(false) {
3062 return fail("allow_limiter goes with target mix: the master limiter is mix-wide, so it cannot be set for each lane".into());
3063 }
3064 let Some(list) = args.get("lanes").and_then(Value::as_array) else {
3065 return fail("each needs `lanes`: the audio lanes to set, such as [\"A1\",\"A2\"]".into());
3066 };
3067 let s = tri!(srv.session_ref());
3068 // A master limiter already on is mix-wide and already in the mix: the flag would change nothing.
3069 let limiter_on = s.limiter().on;
3070 let mut lanes: Vec<(Lane, String)> = Vec::new();
3071 for raw in list {
3072 let Some(raw) = raw.as_str() else {
3073 return fail("lanes takes lane names, such as [\"A1\",\"A2\"]".into());
3074 };
3075 match resolve(s, raw) {
3076 Ok(Target::Lane(l)) if l.kind == LaneKind::Audio => {
3077 if lanes.iter().any(|(k, _)| *k == l) {
3078 return fail(format!("{raw} is listed twice in lanes"));
3079 }
3080 lanes.push((l, raw.to_string()));
3081 }
3082 Ok(_) => return fail(format!("normalize takes audio lanes (A1) in lanes; `{raw}` is not one")),
3083 Err(e) => return fail(e),
3084 }
3085 }
3086 if lanes.is_empty() {
3087 return fail("lanes is empty: list the audio lanes to set, such as [\"A1\",\"A2\"]".into());
3088 }
3089 let picked: Vec<Lane> = lanes.iter().map(|(l, _)| *l).collect();
3090 if let Err(e) = super::edit::check_unlocked(s, &picked) {
3091 return fail(e);
3092 }
3093
3094 // Every lane is measured alone before anything moves, so a silent lane refuses the whole call.
3095 let mut each: Vec<EachLane> = Vec::new();
3096 for (lane, raw) in &lanes {
3097 let before = match measure_target(s, &json!({}), raw) {
3098 Ok(r) => r,
3099 Err(e) => return fail(e),
3100 };
3101 let played = before.loud;
3102 if !played.integrated_lufs.is_finite() {
3103 return fail(format!("{} is silent: nothing to normalize", before.name));
3104 }
3105 let delta = gain_to_target(&played, lufs, tp);
3106 let tp_binds = played.true_peak_dbtp.is_finite()
3107 && tp - played.true_peak_dbtp < lufs - played.integrated_lufs;
3108 each.push(EachLane {
3109 name: before.name,
3110 played,
3111 delta,
3112 tp_binds,
3113 plan: plan_of(s, *lane),
3114 });
3115 }
3116
3117 let dry = opt_bool(args, "dry_run").unwrap_or(false);
3118 let was_clean = !super::project::dirty(srv);
3119 let Some(s) = srv.session.as_mut() else {
3120 return Reply::err(NO_PROJECT);
3121 };
3122 let start = s.history_pushes();
3123 let redo = start_trial(s, dry);
3124 // Each lane is set and settled in turn. The gain each lane really moved by is read before a dry
3125 // run takes the change back, so the dry run reports what the real run does.
3126 let settled: Result<Vec<(Settled, f64, Option<Spill>)>, String> = each
3127 .iter()
3128 .map(|e| -> Result<(Settled, f64, Option<Spill>), String> {
3129 let st = settle(s, &e.name, std::slice::from_ref(&e.plan), lufs, tp, false, tp, e.delta, Some(e.played))?;
3130 let applied = total_moved(s, &e.plan);
3131 Ok((st, applied, spill_of(s, &e.plan)))
3132 })
3133 .collect();
3134 let changed = s.history_pushes() > start;
3135 let rolled = redo.is_none_or(|r| finish_trial(s, start, r));
3136 if dry {
3137 keep_clean_marks(srv, was_clean);
3138 }
3139 let rows = match settled {
3140 Ok(v) => v,
3141 Err(e) => return fail(e),
3142 };
3143 let changed_kept = changed && !dry;
3144 if changed_kept {
3145 let names: Vec<&str> = each.iter().map(|e| e.name.as_str()).collect();
3146 record_pushes(srv, start, format!("normalize each {} {lufs:.1} LUFS", names.join(" ")));
3147 }
3148
3149 let mut parts = Vec::new();
3150 let mut lane_json = Vec::new();
3151 let mut all_reached = true;
3152 let mut held_by_peak = false;
3153 // The headline's clauses, one per lane: what the lane moved by and the level it reached.
3154 let mut clauses: Vec<String> = Vec::new();
3155 // Each lane the true peak held back, with the peak it measured before the change.
3156 let mut peak_names: Vec<String> = Vec::new();
3157 for (e, (st, applied, spill)) in each.iter().zip(&rows) {
3158 let achieved = st.after.integrated_lufs;
3159 let over = peak_over(&st.after, tp);
3160 let level_ok = lufs_reached(lufs, achieved);
3161 let reached = level_ok && over <= NORMALIZE_PEAK_TOLERANCE;
3162 all_reached &= reached;
3163 let capped_by: Option<&str> = if reached {
3164 None
3165 } else if !st.clamped.is_empty() {
3166 Some(cap_kind(&st.clamped))
3167 } else if e.tp_binds || over > NORMALIZE_PEAK_TOLERANCE {
3168 Some("true_peak")
3169 } else {
3170 None
3171 };
3172 held_by_peak |= capped_by == Some("true_peak");
3173 let moved = if *applied > 0.05 {
3174 format!("{} {} {:.1} dB to {achieved:.1} LUFS", e.name, mood(dry, "raised", "would raise"), applied)
3175 } else if *applied < -0.05 {
3176 format!("{} {} {:.1} dB to {achieved:.1} LUFS", e.name, mood(dry, "lowered", "would lower"), -applied)
3177 } else {
3178 format!("{} {} {achieved:.1} LUFS", e.name, mood(dry, "left at", "would be left at"))
3179 };
3180 let clause_status = match capped_by {
3181 _ if reached => String::new(),
3182 Some("clip_gain_limit") => ", held by the clip gain limit".to_string(),
3183 Some("lane_gain_limit") => ", held by the lane gain limit".to_string(),
3184 Some("true_peak") => String::new(),
3185 _ => format!(", {} {lufs:.1}", mood(dry, "did not reach", "would not reach")),
3186 };
3187 clauses.push(format!("{moved}{clause_status}"));
3188 if !reached && capped_by == Some("true_peak") {
3189 peak_names.push(format!("{} peaked at {} dBTP before", e.name, signed_figure(e.played.true_peak_dbtp)));
3190 }
3191 let status = match capped_by {
3192 _ if reached => String::new(),
3193 Some("clip_gain_limit") => format!(
3194 " — held by the clip gain limit: lane {:+.0} dB and each clip {:+.0} dB",
3195 f64::from(MAX_GAIN_DB),
3196 f64::from(MAX_CLIP_GAIN_DB)
3197 ),
3198 Some("lane_gain_limit") => format!(
3199 " — held by the lane gain limit {:+.0}..{:+.0} dB",
3200 f64::from(MIN_GAIN_DB),
3201 f64::from(MAX_GAIN_DB)
3202 ),
3203 Some(_) if !level_ok => format!(
3204 " — {}, held by the true-peak ceiling {tp:.1} dBTP",
3205 short_text(lufs, achieved)
3206 ),
3207 Some(_) => format!(" — held by the true-peak ceiling {tp:.1} dBTP"),
3208 None => format!(" — {} {lufs:.1}: got {achieved:.2} LUFS", mood(dry, "did not reach", "would not reach")),
3209 };
3210 let stuck = if st.stuck {
3211 " · stopped refining: the last cut did not move the true peak"
3212 } else {
3213 ""
3214 };
3215 let split = spill.as_ref().map_or(String::new(), |sp| format!(" · {}", sp.text()));
3216 parts.push(format!(
3217 "{} {} → {} LUFS (gain {applied:+.2} dB, true peak {} → {} dBTP){status}{stuck}{split}",
3218 e.name,
3219 figure(e.played.integrated_lufs),
3220 figure(achieved),
3221 signed_figure(e.played.true_peak_dbtp),
3222 signed_figure(st.after.true_peak_dbtp),
3223 ));
3224 lane_json.push(json!({
3225 "lane": e.name,
3226 "before_integrated_lufs": e.played.integrated_lufs,
3227 "after_integrated_lufs": achieved,
3228 "applied_db": applied,
3229 "reached": reached,
3230 "capped_by": capped_by,
3231 "measured_true_peak_dbtp": st.after.true_peak_dbtp,
3232 "refinements": st.passes,
3233 "clamped": st.clamped.iter().map(|(n, _, _)| n.clone()).collect::<Vec<_>>(),
3234 "clip_gain": clip_gain_json(spill.iter()),
3235 }));
3236 }
3237 // The headline says what the lanes reached, not only what was asked: a lane held by the peak
3238 // ceiling does not reach the target, and the parts below give each lane's level.
3239 // A lane that missed the target names what it applied and reached; lanes held by the true-peak
3240 // ceiling say so once, with the way to reach the target on the mix.
3241 let lossy = if held_by_peak || each.iter().any(|e| e.tp_binds) {
3242 format!(" · {LOSSY_HEADROOM_NOTE}")
3243 } else {
3244 String::new()
3245 };
3246 let (lead, undo) = if dry {
3247 ("dry run — ", format!(" · nothing changed: measured, then taken back{}", rollback_note(rolled)))
3248 } else if changed_kept {
3249 ("", format!(" · undo step {}", srv.ledger.len()))
3250 } else {
3251 ("", String::from(" · no change"))
3252 };
3253 let text = if all_reached {
3254 format!("{}{lead}{} each lane to {lufs:.1} LUFS: {}{undo}", verdict(true), mood(dry, "normalized", "would normalize"), parts.join("; "))
3255 } else {
3256 let mut head = clauses.join("; ");
3257 if !peak_names.is_empty() {
3258 let who = match peak_names.len() {
3259 1 => "held".to_string(),
3260 2 => "both held".to_string(),
3261 n => format!("all {n} held"),
3262 };
3263 head.push_str(&format!(
3264 " — {who} by the {tp:.1} dBTP ceiling ({}); no lane alone reaches {lufs:.1} past it{}",
3265 peak_names.join(", "),
3266 if limiter_on {
3267 "; the master limiter is already on, so normalize target mix can reach it on the mix"
3268 } else {
3269 "; normalize target mix with allow_limiter:true to reach it on the mix"
3270 }
3271 ));
3272 }
3273 format!("{}{lead}{head}{lossy}{undo} · {}", verdict(false), parts.join("; "))
3274 };
3275 Reply::ok(text).with(json!({
3276 "each": true,
3277 "lufs": lufs,
3278 "true_peak_dbtp": tp,
3279 "reached": all_reached,
3280 "lanes": lane_json,
3281 "dry_run": dry,
3282 "changed": changed_kept,
3283 "undo_steps": srv.ledger.len(),
3284 }))
3285}
3286
3287
3288fn run_normalize(srv: &mut Server, args: &Value) -> Reply {
3289 if opt_bool(args, "each").unwrap_or(false) {
3290 return run_normalize_each(srv, args);
3291 }
3292 if arg_given(args, "lanes") {
3293 return fail("lanes goes with each:true: each lane is set on its own. Add each:true, or use target for one lane".into());
3294 }
3295 let Some(raw) = opt_str(args, "target") else {
3296 return fail("missing `target`: give a lane such as A1, or mix".into());
3297 };
3298 let (lufs, tp) = match normalize_levels(args) {
3299 Ok(v) => v,
3300 Err(e) => return fail(e),
3301 };
3302 let allow_limiter = opt_bool(args, "allow_limiter").unwrap_or(false);
3303 let mix = is_mix(raw);
3304 if allow_limiter && !mix {
3305 return fail(format!(
3306 "allow_limiter goes with target mix, not with {raw}: the master limiter is mix-wide, it acts on every lane at once and cannot be set for one lane. To do both, normalize {raw} without it (that moves its lane gain only), then run normalize with target mix and allow_limiter:true to limit the mix"
3307 ));
3308 }
3309
3310 let s = tri!(srv.session_ref());
3311 if !mix {
3312 match resolve(s, raw) {
3313 Ok(Target::Lane(l)) if l.kind == LaneKind::Audio => {}
3314 Ok(_) => {
3315 return fail(format!(
3316 "normalize takes an audio lane (A1) or mix; `{raw}` is not one"
3317 ));
3318 }
3319 Err(e) => return fail(e),
3320 }
3321 }
3322 let before = match measure_target(s, &json!({}), raw) {
3323 Ok(r) => r,
3324 Err(e) => return fail(e),
3325 };
3326 let played = before.loud;
3327 if !played.integrated_lufs.is_finite() {
3328 return fail(format!("{} is silent: nothing to normalize", before.name));
3329 }
3330 // The limiter as it stood before the trial: a dry run reads its wording from this. A master
3331 // limiter already on below true_peak is the ceiling the peaks are held to, so the gain is
3332 // predicted against it, not against true_peak.
3333 let was_limiter = s.limiter();
3334 let counted_on = mix && was_limiter.on;
3335 let hold = if counted_on { tp.min(f64::from(was_limiter.ceiling_db)) } else { tp };
3336 let delta = gain_to_target(&played, lufs, hold);
3337 // The true peak holds the gain back when it is the tighter of the two limits.
3338 let tp_binds = played.true_peak_dbtp.is_finite()
3339 && hold - played.true_peak_dbtp < lufs - played.integrated_lufs;
3340
3341 // Each lane that moves, with its gain now.
3342 let lanes: Vec<Lane> = if mix {
3343 s.lanes()
3344 .into_iter()
3345 .filter(|l| {
3346 l.kind == LaneKind::Audio && !s.lane_clips(*l).is_empty() && !s.lane_muted(*l)
3347 })
3348 .collect()
3349 } else {
3350 match resolve(s, raw) {
3351 Ok(Target::Lane(l)) => vec![l],
3352 _ => Vec::new(),
3353 }
3354 };
3355 if lanes.is_empty() {
3356 return fail("the mix has no unmuted audio lane with clips to move".into());
3357 }
3358 // A locked lane is one a normalize would move, so the whole call refuses before anything changes.
3359 if let Err(e) = super::edit::check_unlocked(s, &lanes) {
3360 return fail(e);
3361 }
3362 // Each lane as it stands: its lane gain, and its clips' gains for a boost past the lane cap.
3363 let plans: Vec<Plan> = lanes.iter().map(|&l| plan_of(s, l)).collect();
3364 let olds: Vec<f64> = plans.iter().map(|p| p.old).collect();
3365
3366 let dry = opt_bool(args, "dry_run").unwrap_or(false);
3367 let was_clean = !super::project::dirty(srv);
3368 let Some(s) = srv.session.as_mut() else {
3369 return Reply::err(NO_PROJECT);
3370 };
3371 let start = s.history_pushes();
3372 let was_on = was_limiter.on;
3373 // A mix with the master limiter already on counts on it, as allow_limiter would: the flag then
3374 // changes nothing, so it is never advised for this case.
3375 let limiter_asked = allow_limiter || counted_on;
3376 let redo = start_trial(s, dry);
3377 // allow_limiter with the true peak in the way: the master limiter goes on at the ceiling, and
3378 // the gain is taken again from the mix as it then measures. A dry run makes the same change and
3379 // takes it back, so its numbers are the real run's. The peak is in the way when the linear
3380 // prediction says so (`tp_binds`), or when the mix already sits over the ceiling: a clipped mix
3381 // does not fall with gain the way the prediction assumes (the clip is what the peak is made of),
3382 // so a linear walk down chases it, while the limiter, ahead of the clip, holds it linearly.
3383 let limited = limiter_in_the_way(limiter_asked, tp_binds, played.true_peak_dbtp, hold);
3384 let trial = normalize_trial(s, raw, &plans, lufs, hold, limited, delta, played);
3385 let changed = s.history_pushes() > start;
3386 let lim = s.limiter();
3387 // The lane gain each lane really holds after the change: the clamp can hold a lane back.
3388 let news: Vec<f64> = lanes.iter().map(|&l| f64::from(s.lane_gain_db(l))).collect();
3389 // The gain each lane really moved by in total (lane gain and clip gain), and the clip gain a boost
3390 // past the lane cap put on its clips: read here, before a dry run takes the change back.
3391 let totals: Vec<f64> = plans.iter().map(|p| total_moved(s, p)).collect();
3392 let spills: Vec<Option<Spill>> = plans.iter().map(|p| spill_of(s, p)).collect();
3393 let rolled = redo.is_none_or(|r| finish_trial(s, start, r));
3394 if dry {
3395 keep_clean_marks(srv, was_clean);
3396 }
3397 let st = match trial {
3398 Ok(v) => v,
3399 Err(e) => return fail(e),
3400 };
3401 let changed_kept = changed && !dry;
3402 if changed_kept {
3403 let what = if mix { "mix".to_string() } else { raw.to_string() };
3404 let with = if limited { " with the limiter" } else { "" };
3405 record_pushes(srv, start, format!("normalize {what} {lufs:.1} LUFS{with}"));
3406 }
3407
3408 let Settled { ceiling, clamped, after, passes, stuck, cut, .. } = st;
3409 let max_passes = pass_cap(limited);
3410 let tol = peak_tolerance(limited);
3411 // The lane gain each lane really moved by, and the mean of those (the one change for a lane).
3412 let moved: Vec<f64> = news.iter().zip(&olds).map(|(n, o)| n - o).collect();
3413 let applied = totals.iter().sum::<f64>() / totals.len() as f64;
3414 // Each lane's change: the split where a boost went on its clips, else its lane gain.
3415 let lane_moves: Vec<String> = lanes
3416 .iter()
3417 .zip(&moved)
3418 .zip(&spills)
3419 .map(|((&l, m), sp)| match sp {
3420 Some(sp) => sp.text(),
3421 None => format!("lane gain {} {m:+.2} dB", parse::lane_name(l)),
3422 })
3423 .collect();
3424 // The split of every lane the boost reached into its clips, for a reply that is not reached.
3425 let split_note: Vec<String> = spills.iter().flatten().map(Spill::text).collect();
3426
3427 let achieved = after.integrated_lufs;
3428 let over = peak_over(&after, hold);
3429 let level_ok = lufs_reached(lufs, achieved);
3430 let reached = level_ok && over <= tol;
3431 let short = if achieved.is_finite() {
3432 (lufs - achieved).max(0.0)
3433 } else {
3434 0.0
3435 };
3436 let limiter_holds = over > tol && (limited || lim.on);
3437 // A limiter on below the true_peak target holds the peaks at its own ceiling: a level short of
3438 // the target there is the limiter's doing, whatever the lane gains say, since the gain it takes back is
3439 // what the walk asked for.
3440 let limiter_at_ceiling = lim.on
3441 && f64::from(lim.ceiling_db) < tp
3442 && over <= tol
3443 && after.true_peak_dbtp.is_finite()
3444 && after.true_peak_dbtp >= f64::from(lim.ceiling_db) - LIMITER_AT_CEILING_DB;
3445 let capped_by: Option<&str> = if reached {
3446 None
3447 } else if limiter_at_ceiling {
3448 Some("limiter")
3449 } else if !clamped.is_empty() {
3450 Some(cap_kind(&clamped))
3451 } else if limiter_holds {
3452 Some("limiter")
3453 } else if tp_binds || over > tol || cut {
3454 Some("true_peak")
3455 } else {
3456 None
3457 };
3458
3459 let head = if reached {
3460 if mix && limited {
3461 format!(
3462 "{} the mix to {lufs:.1} LUFS with the master limiter on at {ceiling:.1} dBTP: {} {} audio lane(s): {}",
3463 mood(dry, "normalized", "would normalize"),
3464 mood(dry, "moved", "would move"),
3465 lanes.len(),
3466 lane_moves.join("; ")
3467 )
3468 } else if mix {
3469 format!(
3470 "{} the mix to {lufs:.1} LUFS: {} {} audio lane(s): {}",
3471 mood(dry, "normalized", "would normalize"),
3472 mood(dry, "moved", "would move"),
3473 lanes.len(),
3474 lane_moves.join("; ")
3475 )
3476 } else {
3477 match &spills[0] {
3478 Some(sp) => format!("{} {} to {lufs:.1} LUFS: {}", mood(dry, "normalized", "would normalize"), before.name, sp.text()),
3479 None => format!(
3480 "{} {} to {lufs:.1} LUFS: lane gain {:+.1} → {:+.1} dB",
3481 mood(dry, "normalized", "would normalize"), before.name, olds[0], news[0]
3482 ),
3483 }
3484 }
3485 } else {
3486 let what = if mix { "mix" } else { before.name.as_str() };
3487 // The outcome first, then what held it. A level within the tolerance reads as reached, and
3488 // the peak that kept it from the target is named: "mix reached -14.1 LUFS (true peak held
3489 // at ceiling)". Otherwise "did not reach" says what was asked, what came out and how far off.
3490 let peak_held = matches!(capped_by, Some("true_peak") | Some("limiter"));
3491 let gap = if level_ok {
3492 let held = if peak_held { " (true peak held at ceiling)" } else { "" };
3493 format!("{what} {} {} LUFS{held}", mood(dry, "reached", "would reach"), figure(achieved))
3494 } else if changed_kept && applied.abs() >= 0.05 && achieved.is_finite() {
3495 // The gain went on, so the reply leads with what it did; "did not reach" alone reads as if
3496 // nothing moved. The reason that held it follows, as below.
3497 let verb = if applied > 0.0 { mood(dry, "raised", "would raise") } else { mood(dry, "lowered", "would lower") };
3498 format!(
3499 "{what} {verb} {:.1} dB to {} LUFS, {}",
3500 applied.abs(),
3501 figure(achieved),
3502 short_text(lufs, achieved)
3503 )
3504 } else {
3505 // Two decimals here: a level that reads -14.1 may still be 0.14 off, and that is why it missed.
3506 let how_far = if achieved > lufs {
3507 " (above it)".to_string()
3508 } else {
3509 format!(" ({})", short_text(lufs, achieved))
3510 };
3511 format!("{what} {} {lufs:.1}: got {achieved:.2} LUFS{how_far}", mood(dry, "did not reach", "would not reach"))
3512 };
3513 match capped_by {
3514 // The lane is at its +12 dB cap and every clip at its +24 dB: nothing more can be added.
3515 Some("clip_gain_limit") => {
3516 let needs: Vec<String> = clamped
3517 .iter()
3518 .map(|(name, wanted, got)| format!("{name} needs {wanted:+.1} dB, reaches {got:+.1}"))
3519 .collect();
3520 format!(
3521 "{gap}: {} — lane gain +{:.0} dB and clip gain +{:.0} dB on each clip is the most; aim lower or lower the target",
3522 needs.join("; "),
3523 f64::from(MAX_GAIN_DB),
3524 f64::from(MAX_CLIP_GAIN_DB)
3525 )
3526 }
3527 Some("lane_gain_limit") => {
3528 let needs: Vec<String> = clamped
3529 .iter()
3530 .map(|(name, wanted, _)| {
3531 format!("{name} needs {wanted:+.1} dB but lane gain is held at {:+.0}..{:+.0} dB", f64::from(MIN_GAIN_DB), f64::from(MAX_GAIN_DB))
3532 })
3533 .collect();
3534 format!("{gap}: {}", needs.join("; "))
3535 }
3536 Some("limiter") if f64::from(lim.ceiling_db) < tp && over <= tol => format!(
3537 "{gap}, held by the master limiter at {:.1} dBTP (the mix peaks at {} dBTP); project_settings limiter {{\"on\": true, \"ceiling_db\": {tp:.1}}} raises that ceiling to true_peak",
3538 lim.ceiling_db,
3539 signed_figure(after.true_peak_dbtp),
3540 ),
3541 Some("limiter") => format!(
3542 "{gap}: the master limiter (on at {:.1} dBTP) is already at its floor {:.0} dBTP and the true peak {} dBTP is still {over:.1} dB over {tp:.1}; lower the target or true_peak",
3543 lim.ceiling_db,
3544 limiter_floor(tp),
3545 signed_figure(after.true_peak_dbtp),
3546 ),
3547 // The level is on the target and the peak alone holds it back: the fix is the same
3548 // advice without the "did not reach" that the level no longer has.
3549 // The master limiter already on below true_peak is the ceiling: the fix is the limiter's own.
3550 Some("true_peak") if counted_on && hold < tp => format!(
3551 "{gap}, held by the master limiter at {hold:.1} dBTP (already on; the mix peaks at {} dBTP); project_settings limiter {{\"on\": true, \"ceiling_db\": {tp:.1}}} raises that ceiling to true_peak",
3552 signed_figure(after.true_peak_dbtp),
3553 ),
3554 Some("true_peak") if level_ok && mix && limiter_asked => format!("{gap}; lower the target or true_peak"),
3555 Some("true_peak") if level_ok && mix => format!("{gap}; allow_limiter:true (or lower the target)"),
3556 // A lane under a limiter already on: the flag is not the fix, and the limiter is mix-wide.
3557 Some("true_peak") if level_ok && was_on => format!("{gap}; lower the target or true_peak"),
3558 Some("true_peak") if level_ok => format!(
3559 "{gap}; the master limiter is mix-wide: normalize target mix with allow_limiter:true (or lower the target)"
3560 ),
3561 // With the limiter already allowed, the fix it could offer is the one just tried.
3562 Some("true_peak") if mix && limiter_asked => format!(
3563 "{gap}, held by the true-peak ceiling {hold:.1} dBTP; lower the target or true_peak"
3564 ),
3565 Some("true_peak") if was_on => format!(
3566 "{gap}, held by the true-peak ceiling {hold:.1} dBTP; lower the target or true_peak"
3567 ),
3568 Some("true_peak") if mix => format!(
3569 "{gap}, held by the true-peak ceiling {hold:.1} dBTP — allow_limiter:true (or lower the target)"
3570 ),
3571 Some("true_peak") => format!(
3572 "{gap}, held by the true-peak ceiling {hold:.1} dBTP — the master limiter is mix-wide: normalize target mix with allow_limiter:true (or lower the target)"
3573 ),
3574 _ => gap,
3575 }
3576 };
3577 let clamp_note = if clamped.is_empty() {
3578 String::new()
3579 } else {
3580 let list: Vec<String> = clamped
3581 .iter()
3582 .map(|(name, wanted, got)| format!("{name} wanted {wanted:+.1} dB, held at {got:+.1}"))
3583 .collect();
3584 if cap_kind(&clamped) == "clip_gain_limit" {
3585 format!(
3586 " · held at lane {:+.0} dB and each clip {:+.0} dB: {}",
3587 f64::from(MAX_GAIN_DB),
3588 f64::from(MAX_CLIP_GAIN_DB),
3589 list.join("; ")
3590 )
3591 } else {
3592 format!(
3593 " · held at the limit {:+.0}..{:+.0} dB: {}",
3594 f64::from(MIN_GAIN_DB),
3595 f64::from(MAX_GAIN_DB),
3596 list.join("; ")
3597 )
3598 }
3599 };
3600 let refined = if passes > 0 {
3601 format!(" · {passes} refinement pass(es)")
3602 } else {
3603 String::new()
3604 };
3605 let mut tail = String::new();
3606 // A reached reply names the split in its head; one that fell short names it here.
3607 if !reached && !split_note.is_empty() {
3608 tail.push_str(&format!(" · {}", split_note.join("; ")));
3609 }
3610 if !reached && capped_by.is_none() && passes >= max_passes {
3611 tail.push_str(&format!(" · stopped after {max_passes} corrections, the most tried"));
3612 }
3613 if stuck {
3614 tail.push_str(" · stopped refining: the last cut did not move the true peak");
3615 }
3616 if limited && achieved.is_finite() && played.integrated_lufs.is_finite() {
3617 // The lane gain is what the mix's loudness gets; the limiter takes back the rest of it.
3618 let took = applied - (achieved - played.integrated_lufs);
3619 if took.abs() >= 0.05 {
3620 tail.push_str(&format!(" · the limiter took back {took:.2} dB of that lane gain"));
3621 }
3622 }
3623 if allow_limiter && lim.on && dry {
3624 // Nothing is kept: the reply says what the real run would do to the limiter.
3625 let verb = if was_on { "leave" } else { "turn" };
3626 tail.push_str(&format!(" · would {verb} the limiter on at {:.1} dBTP", lim.ceiling_db));
3627 } else if allow_limiter && lim.on {
3628 tail.push_str(&format!(
3629 " · limiter left on at {:.1} dBTP (limiter off to remove: project_settings limiter {{\"on\": false}})",
3630 lim.ceiling_db
3631 ));
3632 }
3633 if counted_on && limited {
3634 tail.push_str(&format!(
3635 " · the master limiter was already on at {:.1} dBTP and is counted on in the gain",
3636 was_limiter.ceiling_db
3637 ));
3638 }
3639 let ceiling_involved = limited || lim.on || tp_binds || capped_by.is_some();
3640 let lossy = if ceiling_involved {
3641 format!(" · {LOSSY_HEADROOM_NOTE}")
3642 } else {
3643 String::new()
3644 };
3645 let (lead, undo) = if dry {
3646 ("dry run — ", format!(" · nothing changed: measured, then taken back{}", rollback_note(rolled)))
3647 } else if changed_kept {
3648 // The entry recorded above is the last one, so its number is the ledger's length.
3649 ("", format!(" · undo step {}", srv.ledger.len()))
3650 } else {
3651 ("", String::from(" · no change"))
3652 };
3653 let text = format!(
3654 "{}{lead}{head}; integrated {} → {} LUFS, true peak {} → {} dBTP (measured){refined}{clamp_note}{tail}{lossy}{undo}",
3655 verdict(reached),
3656 figure(played.integrated_lufs),
3657 figure(achieved),
3658 signed_figure(played.true_peak_dbtp),
3659 signed_figure(after.true_peak_dbtp),
3660 );
3661 let limiter = if limited {
3662 json!({ "on": true, "ceiling_db": ceiling })
3663 } else {
3664 Value::Null
3665 };
3666 let lane_moves_json: Vec<Value> = lanes
3667 .iter()
3668 .zip(olds.iter().zip(&news))
3669 .map(|(&l, (&from, &to))| {
3670 json!({ "lane": parse::lane_name(l), "from_db": from, "to_db": to, "change_db": to - from })
3671 })
3672 .collect();
3673 Reply::ok(text).with(json!({
3674 "target": before.name,
3675 "lufs": lufs,
3676 "achieved_lufs": achieved,
3677 "reached": reached,
3678 "short_by_lu": short,
3679 "capped_by": capped_by,
3680 "true_peak_dbtp": tp,
3681 "measured_true_peak_dbtp": after.true_peak_dbtp,
3682 "allow_limiter": allow_limiter,
3683 "limiter_counted_on": counted_on,
3684 "limiter": limiter,
3685 "applied_db": applied,
3686 "lane_moves": lane_moves_json,
3687 "before_integrated_lufs": played.integrated_lufs,
3688 "after_integrated_lufs": achieved,
3689 "after_measured": true,
3690 "refinements": passes,
3691 "clamped": clamped.iter().map(|(n, _, _)| n.clone()).collect::<Vec<_>>(),
3692 "clip_gain": clip_gain_json(spills.iter().flatten()),
3693 "dry_run": dry,
3694 "changed": changed_kept,
3695 "undo_steps": srv.ledger.len(),
3696 }))
3697}
3698
3699#[cfg(test)]
3700mod tests {
3701 use super::*;
3702 use std::path::PathBuf;
3703 use std::path::Path;
3704
3705 /// A 48 kHz mono WAV: 1 s of 440 Hz tone, 1 s of digital silence, 1 s of tone.
3706 fn write_wav(path: &Path) {
3707 write_wav_with(path, 3, |t| {
3708 if (1.0..2.0).contains(&t) {
3709 0.0
3710 } else {
3711 0.5 * (2.0 * std::f64::consts::PI * 440.0 * t).sin()
3712 }
3713 });
3714 }
3715
3716 /// A 48 kHz mono WAV of `secs` seconds whose sample at time `t` is `f(t)`.
3717 fn write_wav_with(path: &Path, secs: u32, f: impl Fn(f64) -> f64) {
3718 let rate: u32 = 48_000;
3719 let mut data: Vec<u8> = Vec::new();
3720 for i in 0..(secs * rate) {
3721 let v = f(f64::from(i) / f64::from(rate));
3722 data.extend_from_slice(&((v * 32767.0) as i16).to_le_bytes());
3723 }
3724 let mut out = Vec::new();
3725 out.extend_from_slice(b"RIFF");
3726 out.extend_from_slice(&(36 + data.len() as u32).to_le_bytes());
3727 out.extend_from_slice(b"WAVEfmt ");
3728 out.extend_from_slice(&16u32.to_le_bytes());
3729 out.extend_from_slice(&1u16.to_le_bytes());
3730 out.extend_from_slice(&1u16.to_le_bytes());
3731 out.extend_from_slice(&rate.to_le_bytes());
3732 out.extend_from_slice(&(rate * 2).to_le_bytes());
3733 out.extend_from_slice(&2u16.to_le_bytes());
3734 out.extend_from_slice(&16u16.to_le_bytes());
3735 out.extend_from_slice(b"data");
3736 out.extend_from_slice(&(data.len() as u32).to_le_bytes());
3737 out.extend_from_slice(&data);
3738 std::fs::write(path, out).expect("write test wav");
3739 }
3740
3741 fn server_on(path: &Path) -> Server {
3742 engine::ao::set_silent_output();
3743 let sess = PlaybackSession::open(path).expect("open test media");
3744 Server {
3745 session: Some(sess),
3746 ..Server::default()
3747 }
3748 }
3749
3750 /// The generated WAV, and its directory removed when the test ends.
3751 struct TestWav {
3752 dir: PathBuf,
3753 path: PathBuf,
3754 }
3755
3756 impl Drop for TestWav {
3757 fn drop(&mut self) {
3758 let _ = std::fs::remove_dir_all(&self.dir);
3759 }
3760 }
3761
3762 fn tone_wav() -> TestWav {
3763 // One directory per call: the tests run in parallel and each removes its own.
3764 static NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
3765 let n = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3766 let dir = std::env::temp_dir().join(format!("edith-hear-test-{}-{n}", std::process::id()));
3767 std::fs::create_dir_all(&dir).expect("temp dir");
3768 let path = dir.join("tone_gap.wav");
3769 write_wav(&path);
3770 TestWav { dir, path }
3771 }
3772
3773 fn server_for(wav: &TestWav) -> Server {
3774 server_on(&wav.path)
3775 }
3776
3777 fn fps_of(srv: &Server) -> f64 {
3778 parse::session_fps(srv.session.as_ref().unwrap())
3779 }
3780
3781 fn frames_of(v: &Value) -> (u32, u32) {
3782 let f = |x: &Value| {
3783 x.as_str()
3784 .unwrap()
3785 .trim_end_matches('f')
3786 .parse::<u32>()
3787 .unwrap()
3788 };
3789 let pair = &v.as_array().unwrap()[0];
3790 (f(&pair[0]), f(&pair[1]))
3791 }
3792
3793 #[test]
3794 fn silence_finds_the_gap() {
3795 let wav = tone_wav();
3796 let mut srv = server_for(&wav);
3797 let fps = fps_of(&srv);
3798 let r = run_silence(&mut srv, &json!({ "target": "A1" }));
3799 assert!(!r.is_error, "{}", r.text);
3800 let st = r.structured.expect("structured");
3801 assert_eq!(st["count"], 1, "{}", r.text);
3802 let (a, b) = frames_of(&st["regions"]);
3803 let (a, b) = (parse::secs(a, fps), parse::secs(b, fps));
3804 assert!((1.0..=1.3).contains(&a), "from {a}s");
3805 assert!((1.7..=2.0).contains(&b), "to {b}s");
3806 }
3807
3808 #[test]
3809 fn silence_on_a_source_scans_the_file_in_source_time() {
3810 let wav = tone_wav();
3811 let mut srv = server_for(&wav);
3812 let fps = fps_of(&srv);
3813 let r = run_silence(&mut srv, &json!({ "target": "src:0" }));
3814 assert!(!r.is_error, "{}", r.text);
3815 assert!(r.text.contains("source time"), "{}", r.text);
3816 let st = r.structured.expect("structured");
3817 assert_eq!(st["count"], 1, "{}", r.text);
3818 let (a, b) = frames_of(&st["regions"]);
3819 let (a, b) = (parse::secs(a, fps), parse::secs(b, fps));
3820 assert!((1.0..=1.3).contains(&a), "from {a}s");
3821 assert!((1.7..=2.0).contains(&b), "to {b}s");
3822 }
3823
3824 #[test]
3825 fn cut_silence_refuses_a_bare_source_and_names_the_lane() {
3826 let wav = tone_wav();
3827 let mut srv = server_for(&wav);
3828 let before = srv.session.as_ref().unwrap().undo_depth();
3829 let r = run_cut_silence(&mut srv, &json!({ "target": "src:0" }));
3830 assert!(r.is_error, "{}", r.text);
3831 assert!(
3832 r.text.contains("cut_silence needs the timeline"),
3833 "{}",
3834 r.text
3835 );
3836 assert!(r.text.contains("A1"), "{}", r.text);
3837 assert_eq!(srv.session.as_ref().unwrap().undo_depth(), before);
3838 }
3839
3840 #[test]
3841 fn cut_silence_shortens_the_timeline() {
3842 let wav = tone_wav();
3843 let mut srv = server_for(&wav);
3844 let fps = fps_of(&srv);
3845 let before = parse::session_end(srv.session.as_ref().unwrap());
3846 let r = run_cut_silence(&mut srv, &json!({ "target": "A1" }));
3847 assert!(!r.is_error, "{}", r.text);
3848 let after = parse::session_end(srv.session.as_ref().unwrap());
3849 let removed = parse::secs(before - after, fps);
3850 // The 1 s of silence keeps the default 0.4 s pause, the padding 0.15 s each side is never
3851 // cut, so about 0.53 s goes (the kept piece inside the silence rounds in to whole frames).
3852 assert!(
3853 (0.5..=0.6).contains(&removed),
3854 "removed {removed}s: {}",
3855 r.text
3856 );
3857 assert_eq!(srv.ledger.len(), 1);
3858 }
3859
3860 #[test]
3861 fn cut_silence_dry_run_changes_nothing() {
3862 let wav = tone_wav();
3863 let mut srv = server_for(&wav);
3864 let before = parse::session_end(srv.session.as_ref().unwrap());
3865 let depth = srv.session.as_ref().unwrap().undo_depth();
3866 let r = run_cut_silence(&mut srv, &json!({ "target": "A1", "dry_run": true }));
3867 assert!(!r.is_error, "{}", r.text);
3868 // A dry run says it would cut and that nothing changed; it never says the cut was kept.
3869 assert!(r.text.starts_with("dry run — would cut ") && r.text.contains("; nothing changed"), "{}", r.text);
3870 assert!(!r.text.contains("nothing kept"), "{}", r.text);
3871 assert_eq!(parse::session_end(srv.session.as_ref().unwrap()), before);
3872 assert_eq!(srv.session.as_ref().unwrap().undo_depth(), depth);
3873 assert!(srv.ledger.is_empty());
3874 }
3875
3876 /// At the undo cap the depth stops growing, so a depth delta would count
3877 /// nothing: the cut must still land one ledger step, and undo must restore
3878 /// the state from before it.
3879 #[test]
3880 fn cut_silence_at_the_cap_is_counted_and_undo_restores_it() {
3881 use crate::tools::edit::run_undo;
3882 let wav = tone_wav();
3883 let mut srv = server_for(&wav);
3884 // Each gain flip moves the lane gain, so each pushes one snapshot and one ledger step.
3885 for i in 0..105 {
3886 let db = if i % 2 == 0 { -3 } else { -6 };
3887 let ops = json!([{ "op": "lane_gain", "lane": "A1", "db": db }]);
3888 let r = crate::tools::edit::run_edit(&mut srv, &json!({ "ops": ops }));
3889 assert!(!r.is_error, "lane_gain {i}: {}", r.text);
3890 }
3891 let lane = parse::lane("A1").unwrap();
3892 let s = srv.session.as_ref().unwrap();
3893 assert_eq!(s.undo_depth(), 100, "the cap holds the depth at 100");
3894 assert_eq!(srv.ledger.len(), 100);
3895 let end_before = parse::session_end(s);
3896 let gain_before = s.lane_gain_db(lane);
3897 let pushes_before = s.history_pushes();
3898
3899 let r = run_cut_silence(&mut srv, &json!({ "target": "A1" }));
3900 assert!(!r.is_error, "{}", r.text);
3901 let s = srv.session.as_ref().unwrap();
3902 let pushed = (s.history_pushes() - pushes_before) as usize;
3903 assert!(pushed >= 1, "the cut pushed a snapshot");
3904 let last = srv.ledger.last().unwrap();
3905 assert_eq!(
3906 last.steps, pushed,
3907 "the ledger counts the pushes, not the depth"
3908 );
3909 assert!(last.label.starts_with("cut_silence A1"), "{}", last.label);
3910 assert_ne!(
3911 parse::session_end(s),
3912 end_before,
3913 "the cut shortened the timeline"
3914 );
3915
3916 let u = run_undo(&mut srv, &json!({}));
3917 assert!(!u.is_error, "{}", u.text);
3918 let s = srv.session.as_ref().unwrap();
3919 assert_eq!(
3920 parse::session_end(s),
3921 end_before,
3922 "undo restores the timeline"
3923 );
3924 assert_eq!(
3925 s.lane_gain_db(lane),
3926 gain_before,
3927 "undo restores the lane gain"
3928 );
3929 assert_eq!(
3930 srv.ledger.iter().map(|e| e.steps).sum::<usize>(),
3931 s.undo_depth()
3932 );
3933 }
3934
3935 #[test]
3936 fn levels_rows_keep_every_value_apart() {
3937 // The tone has a second of digital silence, so its rows carry -120: a value four
3938 // characters wide must still stand apart from the next one.
3939 let wav = tone_wav();
3940 let mut srv = server_for(&wav);
3941 let r = run_levels(&mut srv, &json!({ "target": "A1", "per_sec": 2 }));
3942 assert!(!r.is_error, "{}", r.text);
3943 assert!(r.text.contains("-120"), "no -120 value to test with: {}", r.text);
3944 let mut rows = 0;
3945 for line in r.text.lines() {
3946 // A row is "{time:>6.1}s " then 5-wide values; the header and summary lines do not parse.
3947 let Some((time, rest)) = line.split_once("s ") else { continue };
3948 if time.trim().parse::<f64>().is_err() {
3949 continue;
3950 }
3951 rows += 1;
3952 let chars: Vec<char> = rest.chars().collect();
3953 assert_eq!(chars.len() % 5, 0, "row not in 5-wide columns: {line:?}");
3954 for cell in chars.chunks(5) {
3955 let cell: String = cell.iter().collect();
3956 assert!(cell.starts_with(' ') || cell.starts_with('-'), "{line:?}");
3957 assert!(cell.trim().parse::<i32>().is_ok(), "bad cell {cell:?} in {line:?}");
3958 }
3959 }
3960 assert!(rows > 0, "no rows read: {}", r.text);
3961 }
3962
3963 #[test]
3964 fn levels_reads_loud_and_silent() {
3965 let wav = tone_wav();
3966 let mut srv = server_for(&wav);
3967 let r = run_levels(&mut srv, &json!({ "target": "A1", "per_sec": 2 }));
3968 assert!(!r.is_error, "{}", r.text);
3969 assert!(r.text.contains("levels dBFS, 2/s"), "{}", r.text);
3970 let vals: Vec<f64> = r.structured.unwrap()["values"]
3971 .as_array()
3972 .unwrap()
3973 .iter()
3974 .map(|v| v.as_f64().unwrap())
3975 .collect();
3976 assert!(vals.iter().any(|&v| v > -20.0), "no loud bucket: {vals:?}");
3977 assert!(
3978 vals.iter().any(|&v| v <= -100.0),
3979 "no silent bucket: {vals:?}"
3980 );
3981 }
3982
3983 /// The loudest bucket of a `levels` reply.
3984 fn loudest(r: &Reply) -> f64 {
3985 r.structured.as_ref().unwrap()["values"]
3986 .as_array()
3987 .unwrap()
3988 .iter()
3989 .map(|v| v.as_f64().unwrap())
3990 .fold(f64::MIN, f64::max)
3991 }
3992
3993 #[test]
3994 fn levels_summary_names_its_window_and_takes_the_power_mean() {
3995 // Half a second of digital silence, then a 0.3 sine (about -13.5 dBFS RMS). The extremes are
3996 // single 20 ms windows and say so; the mean is the power mean, near -14.7 dBFS, not the
3997 // average of the dB values (about -43).
3998 let wav = wav_of(2, |t| if t < 0.5 { 0.0 } else { 0.3 * (2.0 * std::f64::consts::PI * 440.0 * t).sin() });
3999 let mut srv = server_for(&wav);
4000 let r = run_levels(&mut srv, &json!({ "target": "A1", "per_sec": 2 }));
4001 assert!(!r.is_error, "{}", r.text);
4002 assert!(r.text.contains("quietest 20 ms window -120 dBFS at 0.00s"), "{}", r.text);
4003 assert!(r.text.contains("loudest 20 ms window -13 dBFS") || r.text.contains("loudest 20 ms window -14 dBFS"), "{}", r.text);
4004 assert!(r.text.contains("(power mean of the 20 ms windows)"), "{}", r.text);
4005 assert!(r.text.contains("(power mean of each group of 20 ms windows)"), "{}", r.text);
4006 let mean: f64 = r
4007 .text
4008 .split(" · mean ")
4009 .nth(1)
4010 .and_then(|t| t.split_whitespace().next())
4011 .and_then(|t| t.parse().ok())
4012 .unwrap_or_else(|| panic!("no mean figure: {}", r.text));
4013 assert!((-16.0..-13.0).contains(&mean), "power mean of the windows, got {mean}: {}", r.text);
4014 }
4015
4016 #[test]
4017 fn levels_read_the_volume_envelope() {
4018 let wav = tone_wav();
4019 let mut srv = server_for(&wav);
4020 let before = run_levels(&mut srv, &json!({ "target": "A1", "per_sec": 2 }));
4021 assert!(!before.is_error, "{}", before.text);
4022 let set = crate::tools::edit::run_edit(
4023 &mut srv,
4024 &json!({"ops": [{"op": "gain_keys", "clip": "A1#0", "keys": [["0s", -20]]}]}),
4025 );
4026 assert!(!set.is_error, "{}", set.text);
4027 // A constant -20 dB envelope lowers every window of the tone by 20 dB.
4028 let after = run_levels(&mut srv, &json!({ "target": "A1", "per_sec": 2 }));
4029 assert!(!after.is_error, "{}", after.text);
4030 let drop = loudest(&before) - loudest(&after);
4031 assert!((drop - 20.0).abs() < 0.5, "drop {drop} dB, expected 20");
4032 }
4033
4034 #[test]
4035 fn levels_refuses_a_bad_target() {
4036 let wav = tone_wav();
4037 let mut srv = server_for(&wav);
4038 let r = run_levels(&mut srv, &json!({ "target": "V9" }));
4039 assert!(r.is_error);
4040 let r = run_levels(&mut srv, &json!({}));
4041 assert!(r.is_error);
4042 }
4043
4044 #[test]
4045 fn levels_says_a_muted_lane_is_silent_in_the_mix() {
4046 let wav = tone_wav();
4047 let mut srv = server_for(&wav);
4048 let set = crate::tools::edit::run_edit(
4049 &mut srv,
4050 &json!({"ops": [{"op": "lane_flags", "lane": "A1", "muted": true}]}),
4051 );
4052 assert!(!set.is_error, "{}", set.text);
4053 let r = run_levels(&mut srv, &json!({ "target": "A1", "per_sec": 2 }));
4054 assert!(!r.is_error, "{}", r.text);
4055 assert!(
4056 r.text.contains(
4057 "A1 is muted: it is silent in the mix and export; the level shown is the lane's own sound"
4058 ),
4059 "{}",
4060 r.text
4061 );
4062 assert!(loudest(&r) > -20.0, "the lane's own sound is still read");
4063 // Unmuted, the same lane says nothing of the kind.
4064 let set = crate::tools::edit::run_edit(
4065 &mut srv,
4066 &json!({"ops": [{"op": "lane_flags", "lane": "A1", "muted": false}]}),
4067 );
4068 assert!(!set.is_error, "{}", set.text);
4069 let r = run_levels(&mut srv, &json!({ "target": "A1", "per_sec": 2 }));
4070 assert!(!r.text.contains("is muted"), "{}", r.text);
4071 }
4072
4073 /// The test WAV on A1 at 0 s (the session's own clip), and again at 5 s: a 2 s
4074 /// gap between the two clips.
4075 fn gapped_lane(wav: &TestWav) -> Server {
4076 let mut srv = server_for(wav);
4077 let placed = crate::tools::edit::run_edit(
4078 &mut srv,
4079 &json!({"ops": [{"op": "place", "source": 0, "at": "5s"}]}),
4080 );
4081 assert!(!placed.is_error, "{}", placed.text);
4082 srv
4083 }
4084
4085 #[test]
4086 fn silence_on_a_lane_leaves_the_gap_between_clips_alone() {
4087 let wav = tone_wav();
4088 let mut srv = gapped_lane(&wav);
4089 let fps = fps_of(&srv);
4090 let r = run_silence(&mut srv, &json!({ "target": "A1" }));
4091 assert!(!r.is_error, "{}", r.text);
4092 let st = r.structured.expect("structured");
4093 // The quiet second inside the first clip and the quiet inside the second. The 2 s gap
4094 // (3 s to 5 s) is structure, not silence: it is listed nowhere and named in the reply.
4095 assert_eq!(st["count"], 2, "{}", r.text);
4096 for region in st["regions"].as_array().unwrap() {
4097 let (a, b) = frames_of(&json!([region.clone()]));
4098 let (a, b) = (parse::secs(a, fps), parse::secs(b, fps));
4099 assert!(b <= 3.0 || a >= 5.0, "region {a}–{b}s lies in the gap: {}", r.text);
4100 }
4101 assert!(r.text.contains("1 timeline gap on A1 left alone"), "{}", r.text);
4102 }
4103
4104 #[test]
4105 fn a_lead_in_before_the_first_clip_is_never_silence_to_cut() {
4106 // A 3 s lead-in (a title's time) before the only clip on A1: silence reports the clip's
4107 // quiet and no lead-in, and cut_silence leaves the lead-in where it is.
4108 let wav = tone_wav();
4109 let mut srv = server_for(&wav);
4110 let made = crate::tools::edit::run_edit(
4111 &mut srv,
4112 &json!({"ops": [
4113 {"op": "delete", "clip": "A1#0"},
4114 {"op": "place", "source": 0, "at": "3s"},
4115 ]}),
4116 );
4117 assert!(!made.is_error, "{}", made.text);
4118 let fps = fps_of(&srv);
4119 let lane = parse::lane("A1").unwrap();
4120 let r = run_silence(&mut srv, &json!({ "target": "A1" }));
4121 assert!(!r.is_error, "{}", r.text);
4122 let st = r.structured.expect("structured");
4123 assert_eq!(st["count"], 1, "{}", r.text);
4124 let (a, _) = frames_of(&st["regions"]);
4125 assert!(parse::secs(a, fps) >= 4.0, "region starts in the lead-in: {}", r.text);
4126 assert!(r.text.contains("1 timeline gap on A1 left alone"), "{}", r.text);
4127 let cut = run_cut_silence(&mut srv, &json!({ "target": "A1" }));
4128 assert!(!cut.is_error, "{}", cut.text);
4129 let first = srv.session.as_ref().unwrap().lane_clips(lane)[0].start;
4130 assert_eq!(first, (3.0 * fps).round() as u32, "the lead-in moved: {}", cut.text);
4131 }
4132
4133 #[test]
4134 fn cut_silence_tightens_the_quiet_in_clips_and_leaves_the_gap() {
4135 let wav = tone_wav();
4136 let mut srv = gapped_lane(&wav);
4137 let fps = fps_of(&srv);
4138 let r = run_cut_silence(
4139 &mut srv,
4140 &json!({ "target": "A1", "min_silence": 0.5, "padding": 0.2 }),
4141 );
4142 assert!(!r.is_error, "{}", r.text);
4143 // Each 1 s quiet inside a clip keeps 0.4 s and loses 0.6 s, 1.2 s in all. The 2 s gap is
4144 // not silence, so it is not cut.
4145 let removed = r.structured.as_ref().unwrap()["removed_frames"]
4146 .as_u64()
4147 .unwrap() as u32;
4148 let removed = parse::secs(removed, fps);
4149 assert!(
4150 (removed - 1.2).abs() < 0.05,
4151 "removed {removed} s: {}",
4152 r.text
4153 );
4154 assert!(r.text.contains("1 timeline gap on A1 left alone"), "{}", r.text);
4155 }
4156
4157 /// 440 Hz bursts: 1 s of tone, then 1.2 s of digital silence, repeated, 13 s in all. The
4158 /// last silence is 1 s, and ends the file.
4159 fn bursts_wav() -> TestWav {
4160 static NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
4161 let n = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4162 let dir = std::env::temp_dir().join(format!("edith-hear-bursts-{}-{n}", std::process::id()));
4163 std::fs::create_dir_all(&dir).expect("temp dir");
4164 let path = dir.join("bursts.wav");
4165 write_wav_with(&path, 13, |t| {
4166 if t % 2.2 < 1.0 {
4167 0.5 * (2.0 * std::f64::consts::PI * 440.0 * t).sin()
4168 } else {
4169 0.0
4170 }
4171 });
4172 TestWav { dir, path }
4173 }
4174
4175 /// The bursts on A2 and A3, A1 emptied: the mix is silent only where both lanes are.
4176 fn bursts_on_two_lanes(wav: &TestWav) -> Server {
4177 let mut srv = server_for(wav);
4178 let made = crate::tools::edit::run_edit(
4179 &mut srv,
4180 &json!({"ops": [
4181 {"op": "delete", "clip": "A1#0"},
4182 {"op": "lane_add", "kind": "audio"},
4183 {"op": "lane_add", "kind": "audio"},
4184 ]}),
4185 );
4186 assert!(!made.is_error, "{}", made.text);
4187 let placed = crate::tools::edit::run_edit(
4188 &mut srv,
4189 &json!({"ops": [
4190 {"op": "place", "source": 0, "lane": "A2", "at": "0s"},
4191 {"op": "place", "source": 0, "lane": "A3", "at": "0s"},
4192 ]}),
4193 );
4194 assert!(!placed.is_error, "{}", placed.text);
4195 srv
4196 }
4197
4198 #[test]
4199 fn cut_silence_on_the_mix_keeps_each_pause_and_measures_it() {
4200 let wav = bursts_wav();
4201 let mut srv = bursts_on_two_lanes(&wav);
4202 let fps = fps_of(&srv);
4203 let end_before = parse::session_end(srv.session.as_ref().unwrap());
4204 let dry = run_cut_silence(
4205 &mut srv,
4206 &json!({ "target": "mix", "keep": 0.25, "dry_run": true }),
4207 );
4208 assert!(!dry.is_error, "{}", dry.text);
4209 assert_eq!(
4210 parse::session_end(srv.session.as_ref().unwrap()),
4211 end_before,
4212 "a dry run keeps nothing"
4213 );
4214 let r = run_cut_silence(&mut srv, &json!({ "target": "mix", "keep": 0.25 }));
4215 assert!(!r.is_error, "{}", r.text);
4216 assert!(!r.text.contains("not measured"), "{}", r.text);
4217 let st = r.structured.clone().expect("structured");
4218 let pauses: Vec<f64> = st["pauses_measured_s"]
4219 .as_array()
4220 .expect("measured pauses")
4221 .iter()
4222 .map(|p| p.as_f64().unwrap())
4223 .collect();
4224 assert_eq!(pauses.len(), 6, "{}", r.text);
4225 for p in &pauses {
4226 assert!(*p >= 0.25 - 1e-9, "pause {p} s is under keep: {}", r.text);
4227 }
4228 // The timeline loses exactly what each silence gave up: 5 gaps of 1.2 s and a last one of 1 s.
4229 let removed = parse::secs(st["removed_frames"].as_u64().unwrap() as u32, fps);
4230 let gaps = 5.0 * 1.2 + 1.0;
4231 let expected: f64 = gaps - pauses.iter().sum::<f64>();
4232 assert!(
4233 (removed - expected).abs() < 0.25,
4234 "removed {removed} s, expected {expected} s from pauses {pauses:?}: {}",
4235 r.text
4236 );
4237 // The dry run reported the same amount the real cut removed.
4238 let d = dry.structured.as_ref().unwrap();
4239 assert_eq!(d["removed_frames"], st["removed_frames"], "{}", dry.text);
4240 let removed_dry = parse::secs(d["removed_frames"].as_u64().unwrap() as u32, fps);
4241 assert!(
4242 dry.text.contains(&format!("would remove {removed_dry:.3} s")),
4243 "{}",
4244 dry.text
4245 );
4246 }
4247
4248 #[test]
4249 fn cut_silence_leaves_the_pause_it_names_measured_from_the_result() {
4250 let wav = tone_wav();
4251 let mut srv = gapped_lane(&wav);
4252 let r = run_cut_silence(
4253 &mut srv,
4254 &json!({ "target": "A1", "min_silence": 0.5, "keep": 0.4 }),
4255 );
4256 assert!(!r.is_error, "{}", r.text);
4257 assert!(r.text.contains("measured after the cut"), "{}", r.text);
4258 // Each measured joint sits in a quiet run of keep seconds, to the window's 20 ms.
4259 let pauses = r.structured.as_ref().unwrap()["pauses_measured_s"]
4260 .as_array()
4261 .expect("measured pauses")
4262 .clone();
4263 assert!(!pauses.is_empty(), "{}", r.text);
4264 for p in pauses {
4265 let p = p.as_f64().unwrap();
4266 // keep 0.4 with the rounding inward of two frames and the 20 ms windows that read it.
4267 assert!((p - 0.4).abs() < 0.1, "pause {p} s, want 0.4: {}", r.text);
4268 }
4269 }
4270
4271 #[test]
4272 fn joint_cut_counts_a_lane_past_its_last_clip_as_quiet() {
4273 // A3 ends at 3 s, so after that A3 has no clip: its time there is silent, as a gap is. Under
4274 // A2's bursts (sound 0-1, 2.2-3.2, 4.4-5.4 s ...) the pauses after 3 s are joint silence too.
4275 let wav = bursts_wav();
4276 let mut srv = bursts_on_two_lanes(&wav);
4277 let trimmed = crate::tools::edit::run_edit(&mut srv, &json!({"ops": [{"op": "trim", "clip": "A3#0", "edge": "out", "to": "3s"}]}));
4278 assert!(!trimmed.is_error, "{}", trimmed.text);
4279 let r = run_cut_silence(&mut srv, &json!({"lanes": ["A2", "A3"], "dry_run": true}));
4280 assert!(!r.is_error, "{}", r.text);
4281 let count = r.structured.as_ref().unwrap()["count"].as_u64().unwrap();
4282 assert!(count >= 3, "pauses past A3's last clip are silent on both lanes: {} ({count})", r.text);
4283 }
4284
4285 /// 1 s of tone, then 2 s of digital silence to the end: the clip's quiet runs to its edge.
4286 fn tail_wav() -> TestWav {
4287 static NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
4288 let n = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4289 let dir = std::env::temp_dir().join(format!("edith-hear-tail-{}-{n}", std::process::id()));
4290 std::fs::create_dir_all(&dir).expect("temp dir");
4291 let path = dir.join("tail.wav");
4292 write_wav_with(&path, 3, |t| if t < 1.0 { 0.5 * (2.0 * std::f64::consts::PI * 440.0 * t).sin() } else { 0.0 });
4293 TestWav { dir, path }
4294 }
4295
4296 #[test]
4297 fn cut_silence_measures_the_kept_pause_inside_its_clip_not_the_gap_after_it() {
4298 // The tail on A1 at 0, and a 1 s tone copy at 6 s: the 3 s gap between the clips is not
4299 // silence, so the pause the cut leaves is the 0.4 s kept inside the first clip.
4300 // The session opens with the source on A1 at 0; the second copy goes at 6 s.
4301 let wav = tail_wav();
4302 let mut srv = server_for(&wav);
4303 let placed = crate::tools::edit::run_edit(
4304 &mut srv,
4305 &json!({"ops": [{"op": "place", "source": 0, "at": "6s", "in": "0s", "out": "1s"}]}),
4306 );
4307 assert!(!placed.is_error, "{}", placed.text);
4308 let r = run_cut_silence(&mut srv, &json!({ "target": "A1" }));
4309 assert!(!r.is_error, "{}", r.text);
4310 let pauses = r.structured.as_ref().unwrap()["pauses_measured_s"]
4311 .as_array()
4312 .expect("measured pauses")
4313 .clone();
4314 assert_eq!(pauses.len(), 1, "{}", r.text);
4315 let p = pauses[0].as_f64().unwrap();
4316 // The keep (0.4 s, padding included) is the whole pause left after the speech, the 0.15 s
4317 // padding at the clip's end among it. The 2 s gap after the clip is not in it.
4318 assert!((p - 0.4).abs() < 0.05, "pause {p} s, want 0.40 s: {}", r.text);
4319 assert!(p < 1.0, "the gap after the clip is counted: {}", r.text);
4320 }
4321
4322 #[test]
4323 fn cut_silence_dry_run_leaves_a_saved_project_saved() {
4324 let wav = tail_wav();
4325 let mut srv = server_for(&wav);
4326 let s = srv.session.as_ref().unwrap();
4327 srv.saved_depth = Some(s.undo_depth());
4328 srv.saved_pushes = Some(s.history_pushes());
4329 srv.saved_sources = Some(s.sources().len());
4330 assert!(!crate::tools::project::dirty(&srv));
4331 // The tail is 2 s of the 3 s clip, over half the sound, so both the dry run and the real cut are forced.
4332 let dry = run_cut_silence(&mut srv, &json!({ "target": "A1", "dry_run": true, "force": true }));
4333 assert!(!dry.is_error, "{}", dry.text);
4334 assert!(dry.text.starts_with("dry run"), "{}", dry.text);
4335 assert!(!crate::tools::project::dirty(&srv), "a dry run leaves the saved project saved");
4336 assert!(srv.ledger.is_empty(), "and keeps no undo step");
4337 // A real cut is a change, so the project is unsaved after it.
4338 let cut = run_cut_silence(&mut srv, &json!({ "target": "A1", "force": true }));
4339 assert!(!cut.is_error, "{}", cut.text);
4340 assert!(crate::tools::project::dirty(&srv), "a real cut is unsaved");
4341 }
4342
4343 #[test]
4344 fn silence_judges_a_pause_across_touching_clips_as_one() {
4345 // The tail cut to keep 0.4 s, which leaves its pause split across two clips that touch.
4346 let wav = tail_wav();
4347 let mut srv = server_for(&wav);
4348 let placed = crate::tools::edit::run_edit(
4349 &mut srv,
4350 &json!({"ops": [{"op": "place", "source": 0, "at": "6s", "in": "0s", "out": "1s"}]}),
4351 );
4352 assert!(!placed.is_error, "{}", placed.text);
4353 let fps = fps_of(&srv);
4354 let cut = run_cut_silence(&mut srv, &json!({ "target": "A1" }));
4355 assert!(!cut.is_error, "{}", cut.text);
4356 // The silence now reads the pause as one run: the seam is no gap.
4357 // The pause left is keep, 0.4 s, under the default 0.5 s minimum, so it is listed at 0.3 s.
4358 let r = run_silence(&mut srv, &json!({ "target": "A1", "min_silence": 0.3 }));
4359 assert!(!r.is_error, "{}", r.text);
4360 let st = r.structured.expect("structured");
4361 assert_eq!(st["count"], 1, "the seam split the pause: {}", r.text);
4362 let (a, b) = frames_of(&st["regions"]);
4363 assert!(parse::secs(a, fps) >= 1.0 && parse::secs(b, fps) <= 1.7, "region {a}–{b}f: {}", r.text);
4364 // And the cut leaves that pause where it is: a second cut finds nothing to take.
4365 let again = run_cut_silence(&mut srv, &json!({ "target": "A1" }));
4366 assert!(!again.is_error, "{}", again.text);
4367 assert_eq!(again.structured.as_ref().unwrap()["removed_frames"], 0, "{}", again.text);
4368 }
4369
4370 #[test]
4371 fn silence_never_joins_quiet_across_a_gap_between_clips() {
4372 // Two copies of the tail, 1 s apart: each clip's own quiet ends at its edge, and the gap
4373 // between them is not sound, so the two pauses stay two.
4374 let wav = tail_wav();
4375 let mut srv = server_for(&wav);
4376 let placed = crate::tools::edit::run_edit(
4377 &mut srv,
4378 &json!({"ops": [{"op": "place", "source": 0, "at": "4s"}]}),
4379 );
4380 assert!(!placed.is_error, "{}", placed.text);
4381 let r = run_silence(&mut srv, &json!({ "target": "A1" }));
4382 assert!(!r.is_error, "{}", r.text);
4383 assert_eq!(r.structured.as_ref().unwrap()["count"], 2, "{}", r.text);
4384 assert!(r.text.contains("1 timeline gap on A1 left alone"), "{}", r.text);
4385 }
4386
4387 #[test]
4388 fn levels_and_silence_accept_the_mix() {
4389 let wav = tone_wav();
4390 let mut srv = gapped_lane(&wav);
4391 let r = run_levels(&mut srv, &json!({ "target": "mix", "per_sec": 2 }));
4392 assert!(!r.is_error, "{}", r.text);
4393 assert!(r.text.starts_with("mix levels dBFS"), "{}", r.text);
4394 let r = run_silence(&mut srv, &json!({ "target": "MIX" }));
4395 assert!(!r.is_error, "{}", r.text);
4396 assert_eq!(r.structured.as_ref().unwrap()["count"], 3, "{}", r.text);
4397 }
4398
4399 fn tone_asset() -> PathBuf {
4400 PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../assets/test_tone.wav")
4401 }
4402
4403 fn integrated_of(r: &Reply) -> f64 {
4404 r.structured.as_ref().expect("structured")["integrated_lufs"]
4405 .as_f64()
4406 .unwrap_or(f64::NAN)
4407 }
4408
4409 #[test]
4410 fn loudness_reads_the_tone_on_a_lane() {
4411 let mut srv = server_on(&tone_asset());
4412 let r = run_loudness(&mut srv, &json!({ "target": "A1" }));
4413 assert!(!r.is_error, "{}", r.text);
4414 assert!(integrated_of(&r).is_finite(), "{}", r.text);
4415 assert!(r.text.contains("integrated"), "{}", r.text);
4416 }
4417
4418 #[test]
4419 fn loudness_says_when_a_lane_includes_its_duck() {
4420 let tone = tone_asset();
4421 let mut srv = server_on(&tone);
4422 let s = srv.session.as_mut().expect("session");
4423 let a2 = s.add_lane(LaneKind::Audio);
4424 s.place_stream_at(0.0, Path::new(&tone), 0, Some(a2)).expect("place the tone on A2");
4425 let plain = run_loudness(&mut srv, &json!({ "target": "A2" }));
4426 assert!(!plain.is_error && !plain.text.contains("duck"), "{}", plain.text);
4427 let s = srv.session.as_mut().expect("session");
4428 let duck = engine::duck::Duck {
4429 under: 0,
4430 depth_db: -12.0,
4431 threshold_db: -40.0,
4432 attack_ms: 80.0,
4433 release_ms: 400.0,
4434 };
4435 assert!(s.set_lane_duck(a2, Some(duck)), "the duck is set");
4436 let ducked = run_loudness(&mut srv, &json!({ "target": "A2" }));
4437 assert!(
4438 !ducked.is_error && ducked.text.contains("includes the duck under A1 (-12.0 dB at most)"),
4439 "{}",
4440 ducked.text
4441 );
4442 }
4443
4444 #[test]
4445 fn a_lane_gain_moves_the_mix_by_its_power_share() {
4446 // Two mono lanes at about equal loudness: their powers add, so the mix sits 3 LU above
4447 // either lane alone. At -40 dB A2 keeps a ten-thousandth of its power, so the mix falls to
4448 // A1's share: about 3 LU lower than at 0 dB.
4449 let tau = std::f64::consts::PI * 2.0;
4450 let mut wav = tone_wav();
4451 wav.path = wav.dir.join("low.wav");
4452 write_wav_with(&wav.path, 3, |t| 0.5 * (tau * 440.0 * t).sin());
4453 let high = wav.dir.join("high.wav");
4454 write_wav_with(&high, 3, |t| 0.5 * (tau * 1000.0 * t).sin());
4455 let mut srv = server_on(&wav.path);
4456 let import = crate::server::tools().into_iter().find(|t| t.name == "media_import").expect("tool");
4457 let made = (import.run)(&mut srv, &json!({ "paths": [high.display().to_string()] }));
4458 assert!(!made.is_error, "{}", made.text);
4459 let placed = crate::tools::edit::run_edit(
4460 &mut srv,
4461 &json!({"ops": [
4462 {"op": "lane_add", "kind": "audio"},
4463 {"op": "place", "source": 1, "lane": "A2", "at": "0s"},
4464 ]}),
4465 );
4466 assert!(!placed.is_error, "{}", placed.text);
4467 let a2 = Lane::new(LaneKind::Audio, 1);
4468 let lane_db = |srv: &mut Server, lane: &str| {
4469 integrated_of(&run_loudness(srv, &json!({ "target": lane })))
4470 };
4471 let (one, other) = (lane_db(&mut srv, "A1"), lane_db(&mut srv, "A2"));
4472 // Both lanes are mono, so the mix is mono too: it is the two powers added.
4473 let power_sum = |a: f64, b: f64| 10.0 * (10f64.powf(a / 10.0) + 10f64.powf(b / 10.0)).log10();
4474 let both = integrated_of(&run_loudness(&mut srv, &json!({ "target": "mix" })));
4475 assert!((both - power_sum(one, other)).abs() < 0.2, "mix {both}, lanes {one} and {other}");
4476 let s = srv.session.as_mut().expect("session");
4477 assert!(s.set_lane_gain_db(a2, -40.0), "the gain is set");
4478 let quiet = integrated_of(&run_loudness(&mut srv, &json!({ "target": "mix" })));
4479 let expected = power_sum(one, other - 40.0);
4480 assert!((quiet - expected).abs() < 0.2, "mix {quiet} at -40 dB, expected {expected}");
4481 // The 440 Hz and 1 kHz tones are near enough in loudness that the drop is about 3 LU.
4482 let drop = both - quiet;
4483 assert!((drop - 3.0).abs() < 0.5, "drop {drop} LU");
4484 }
4485
4486 #[test]
4487 fn cut_silence_dry_run_keeps_the_undo_and_redo_history() {
4488 let wav = tone_wav();
4489 let mut srv = server_for(&wav);
4490 let cut = run_cut_silence(&mut srv, &json!({ "target": "A1" }));
4491 assert!(!cut.is_error, "{}", cut.text);
4492 let undone = crate::tools::edit::run_undo(&mut srv, &json!({}));
4493 assert!(!undone.is_error, "{}", undone.text);
4494 let s = srv.session.as_ref().unwrap();
4495 let (undo, redo) = (s.undo_depth(), s.redo_depth());
4496 assert!(redo > 0, "the undone cut is on the redo stack");
4497 let ledger = srv.redo_ledger.len();
4498 assert_eq!(ledger, 1);
4499 let dirty = crate::tools::project::dirty(&srv);
4500
4501 let dry = run_cut_silence(&mut srv, &json!({ "target": "A1", "dry_run": true }));
4502 assert!(!dry.is_error, "{}", dry.text);
4503 let s = srv.session.as_ref().unwrap();
4504 assert_eq!((s.undo_depth(), s.redo_depth()), (undo, redo), "{}", dry.text);
4505 assert_eq!(srv.redo_ledger.len(), ledger, "{}", dry.text);
4506 assert_eq!(crate::tools::project::dirty(&srv), dirty, "{}", dry.text);
4507 }
4508
4509 /// The limiter is in the way with allow_limiter when the linear prediction says the peaks bind, or
4510 /// when the mix already sits over the ceiling (the clipped case the prediction gets wrong). Without
4511 /// allow_limiter it is never in the way, and a quiet mix the peaks do not touch leaves it out.
4512 #[test]
4513 fn allow_limiter_engages_for_a_clipped_mix_the_prediction_misses() {
4514 // Clipped: +1.6 dBTP against a -1 ceiling, the linear gain says the peaks are fine.
4515 assert!(limiter_in_the_way(true, false, 1.6, -1.0));
4516 // The linear prediction binds.
4517 assert!(limiter_in_the_way(true, true, -6.1, -1.0));
4518 // Quiet, and the peaks do not bind: no limiter.
4519 assert!(!limiter_in_the_way(true, false, -6.1, -1.0));
4520 // Not allowed: never.
4521 assert!(!limiter_in_the_way(false, true, 1.6, -1.0));
4522 }
4523
4524 #[test]
4525 fn normalize_mix_lands_on_the_target() {
4526 let mut srv = server_on(&tone_asset());
4527 let r = run_normalize(&mut srv, &json!({ "target": "mix", "lufs": -20 }));
4528 assert!(!r.is_error, "{}", r.text);
4529 assert_eq!(srv.ledger.len(), 1, "one undo step: {}", r.text);
4530 assert!(r.text.ends_with("undo step 1"), "{}", r.text);
4531 let m = run_loudness(&mut srv, &json!({ "target": "mix" }));
4532 assert!(!m.is_error, "{}", m.text);
4533 assert!(
4534 (integrated_of(&m) - -20.0).abs() <= 1.0,
4535 "mix at {} LUFS: {}",
4536 integrated_of(&m),
4537 m.text
4538 );
4539 }
4540
4541 #[test]
4542 fn normalize_lane_lands_on_the_target() {
4543 let mut srv = server_on(&tone_asset());
4544 let r = run_normalize(&mut srv, &json!({ "target": "A1", "lufs": -20 }));
4545 assert!(!r.is_error, "{}", r.text);
4546 let m = run_loudness(&mut srv, &json!({ "target": "A1" }));
4547 assert!(!m.is_error, "{}", m.text);
4548 assert!(
4549 (integrated_of(&m) - -20.0).abs() <= 1.0,
4550 "A1 at {} LUFS: {}",
4551 integrated_of(&m),
4552 m.text
4553 );
4554 }
4555
4556 /// The tone on A1 and on A2 (a lane of its own at -6 dB), two speakers at different levels.
4557 fn two_lanes_apart() -> Server {
4558 let tone = tone_asset();
4559 let mut srv = server_on(&tone);
4560 let s = srv.session.as_mut().expect("session");
4561 let a2 = s.add_lane(LaneKind::Audio);
4562 s.place_stream_at(0.0, Path::new(&tone), 0, Some(a2)).expect("place the tone on A2");
4563 assert!(s.set_lane_gain_db(a2, -6.0));
4564 srv
4565 }
4566
4567 #[test]
4568 fn normalize_each_sets_every_lane_alone_to_the_target() {
4569 let mut srv = two_lanes_apart();
4570 let r = run_normalize(&mut srv, &json!({ "each": true, "lanes": ["A1", "A2"], "lufs": -20 }));
4571 assert!(!r.is_error, "{}", r.text);
4572 assert_eq!(srv.ledger.len(), 1, "one undo step: {}", r.text);
4573 assert!(r.text.ends_with("undo step 1"), "{}", r.text);
4574 assert!(r.text.contains("A1 ") && r.text.contains("A2 "), "{}", r.text);
4575 let a1 = lufs_at(&mut srv, "A1");
4576 let a2 = lufs_at(&mut srv, "A2");
4577 assert!((a1 - -20.0).abs() <= 1.0, "A1 at {a1} LUFS: {}", r.text);
4578 assert!((a2 - -20.0).abs() <= 1.0, "A2 at {a2} LUFS: {}", r.text);
4579 // The same tone on both lanes: A2 started 6 dB under A1 (-6 against 0), but each lane is set
4580 // by its own measurement, so both land on the same gain.
4581 let s = srv.session.as_ref().expect("session");
4582 let g1 = f64::from(s.lane_gain_db(parse::lane("A1").unwrap()));
4583 let g2 = f64::from(s.lane_gain_db(parse::lane("A2").unwrap()));
4584 assert!((g2 - g1).abs() <= 0.5, "gains {g1} and {g2}: {}", r.text);
4585 let st = r.structured.as_ref().expect("structured");
4586 assert_eq!(st["lanes"].as_array().expect("lanes").len(), 2);
4587 assert_eq!(st["reached"], true, "{}", r.text);
4588 }
4589
4590 #[test]
4591 fn normalize_each_undo_restores_both_lanes_in_one_step() {
4592 let mut srv = two_lanes_apart();
4593 let s = srv.session.as_ref().expect("session");
4594 let (before1, before2) = (
4595 s.lane_gain_db(parse::lane("A1").unwrap()),
4596 s.lane_gain_db(parse::lane("A2").unwrap()),
4597 );
4598 let depth = srv.session.as_ref().unwrap().undo_depth();
4599 let r = run_normalize(&mut srv, &json!({ "each": true, "lanes": ["A1", "A2"], "lufs": -20 }));
4600 assert!(!r.is_error, "{}", r.text);
4601 // One normalize records several engine snapshots; the one ledger entry covers all of them.
4602 assert_eq!(srv.ledger.len(), 1, "{}", r.text);
4603 let s = srv.session.as_mut().expect("session");
4604 while s.undo_depth() > depth && s.undo() {}
4605 let s = srv.session.as_ref().expect("session");
4606 assert_eq!(s.lane_gain_db(parse::lane("A1").unwrap()), before1);
4607 assert_eq!(s.lane_gain_db(parse::lane("A2").unwrap()), before2);
4608 }
4609
4610 #[test]
4611 fn normalize_each_dry_run_predicts_each_lane_and_changes_nothing() {
4612 let mut srv = two_lanes_apart();
4613 let g2 = srv.session.as_ref().unwrap().lane_gain_db(parse::lane("A2").unwrap());
4614 let r = run_normalize(&mut srv, &json!({ "each": true, "lanes": ["A1", "A2"], "lufs": -20, "dry_run": true }));
4615 assert!(!r.is_error, "{}", r.text);
4616 assert!(r.text.starts_with("target reached: dry run — would "), "{}", r.text);
4617 assert!(r.text.contains("· nothing changed"), "{}", r.text);
4618 let st = r.structured.as_ref().expect("structured");
4619 assert_eq!(st["changed"], false);
4620 assert_eq!(st["lanes"].as_array().expect("lanes").len(), 2);
4621 assert_eq!(srv.session.as_ref().unwrap().lane_gain_db(parse::lane("A2").unwrap()), g2);
4622 assert_eq!(srv.ledger.len(), 0);
4623 }
4624
4625 #[test]
4626 fn normalize_each_refuses_bad_arguments_before_changing_anything() {
4627 let mut srv = two_lanes_apart();
4628 let g1 = srv.session.as_ref().unwrap().lane_gain_db(parse::lane("A1").unwrap());
4629 for (args, want) in [
4630 (json!({ "each": true, "lufs": -20 }), "each needs `lanes`"),
4631 (json!({ "each": true, "lanes": ["A1"], "target": "A2" }), "each takes `lanes`, not `target`"),
4632 (json!({ "each": true, "lanes": ["A1", "A1"] }), "listed twice"),
4633 (json!({ "each": true, "lanes": ["V1"] }), "audio lanes"),
4634 (json!({ "each": true, "lanes": ["A1"], "allow_limiter": true }), "allow_limiter goes with target mix"),
4635 (json!({ "lanes": ["A1", "A2"] }), "lanes goes with each:true"),
4636 ] {
4637 let r = run_normalize(&mut srv, &args);
4638 assert!(r.is_error, "{args}: {}", r.text);
4639 assert!(r.text.contains(want), "wanted {want:?} in {}", r.text);
4640 }
4641 assert_eq!(srv.session.as_ref().unwrap().lane_gain_db(parse::lane("A1").unwrap()), g1);
4642 assert_eq!(srv.ledger.len(), 0);
4643 }
4644
4645 fn lufs_at(srv: &mut Server, target: &str) -> f64 {
4646 let r = run_loudness(srv, &json!({ "target": target }));
4647 assert!(!r.is_error, "{}", r.text);
4648 integrated_of(&r)
4649 }
4650
4651 #[test]
4652 fn clip_gain_lowers_the_clip_loudness_by_the_same_amount() {
4653 let mut srv = server_on(&tone_asset());
4654 let before = lufs_at(&mut srv, "A1@0");
4655 assert!(before.is_finite(), "tone clip is silent");
4656 let set = srv
4657 .session
4658 .as_mut()
4659 .unwrap()
4660 .set_clip_gain(Lane::A1, 0, -6.0);
4661 assert!(set, "the clip gain was not set");
4662 let after = lufs_at(&mut srv, "A1@0");
4663 assert!(
4664 (before - after - 6.0).abs() <= 0.3,
4665 "clip at -6 dB read {before} -> {after}"
4666 );
4667 // The lane reading moves with it, since the lane is that clip.
4668 let lane_after = lufs_at(&mut srv, "A1");
4669 assert!(
4670 (lane_after - after).abs() <= 0.3,
4671 "lane {lane_after} vs clip {after}"
4672 );
4673 }
4674
4675 #[test]
4676 fn clip_gain_reaches_levels_and_silence_on_a_clip() {
4677 let mut srv = server_on(&tone_asset());
4678 let peak = |srv: &mut Server| {
4679 let r = run_levels(srv, &json!({ "target": "A1@0", "per_sec": 2 }));
4680 assert!(!r.is_error, "{}", r.text);
4681 r.structured.expect("structured")["values"]
4682 .as_array()
4683 .unwrap()
4684 .iter()
4685 .filter_map(|v| v.as_f64())
4686 .fold(f64::MIN, f64::max)
4687 };
4688 let before = peak(&mut srv);
4689 srv.session
4690 .as_mut()
4691 .unwrap()
4692 .set_clip_gain(Lane::A1, 0, -6.0);
4693 let after = peak(&mut srv);
4694 assert!(
4695 (before - after - 6.0).abs() <= 0.5,
4696 "levels peak {before} -> {after}"
4697 );
4698 // Silence at a threshold the tone sits below only once the gain is on.
4699 let r = run_silence(&mut srv, &json!({ "target": "A1@0", "threshold_db": -20 }));
4700 assert!(!r.is_error, "{}", r.text);
4701 }
4702
4703 #[test]
4704 fn normalize_names_the_true_peak_cap_and_the_limiter_fixes_it() {
4705 let mut srv = server_on(&tone_asset());
4706 // The test tone peaks at -18 dBTP, so a -15 ceiling is the one that holds.
4707 let args = json!({ "target": "mix", "lufs": -14, "true_peak": -15 });
4708 let r = run_normalize(&mut srv, &args);
4709 assert!(!r.is_error, "{}", r.text);
4710 let st = r.structured.expect("structured");
4711 assert_eq!(st["capped_by"], "true_peak", "{}", r.text);
4712 assert!(r.text.starts_with("short of the target: mix raised "), "{}", r.text);
4713 assert!(r.text.contains("held by the true-peak ceiling -15.0 dBTP — allow_limiter:true"), "{}", r.text);
4714 let plain = st["achieved_lufs"].as_f64().unwrap();
4715 assert!(plain < -14.0, "the cap should hold it short: {plain}");
4716 assert!(st["limiter"].is_null());
4717
4718 let mut srv = server_on(&tone_asset());
4719 let r = run_normalize(
4720 &mut srv,
4721 &json!({ "target": "mix", "lufs": -14, "true_peak": -15, "allow_limiter": true }),
4722 );
4723 assert!(!r.is_error, "{}", r.text);
4724 assert_eq!(srv.ledger.len(), 1, "one undo step: {}", r.text);
4725 let st = r.structured.expect("structured");
4726 assert_eq!(st["limiter"]["on"], true, "{}", r.text);
4727 assert!(r.text.contains("dBTP"), "the limiter is named by its true-peak ceiling: {}", r.text);
4728 let reached = st["achieved_lufs"].as_f64().unwrap();
4729 // The lane gain cap binds here, so the limiter adds no level; its walk to the ceiling costs
4730 // a few hundredths of a LU at most.
4731 assert!(reached > plain - 0.1, "limiter lost level {plain} -> {reached}");
4732 assert_eq!(st["after_measured"], true, "{}", r.text);
4733 assert!(srv.session.as_ref().unwrap().limiter().on);
4734 }
4735
4736 /// The mix is held at or under the true_peak target with the limiter in circuit. The limiter's
4737 /// detector is the meter's own true-peak method, but on this tone at this gain the limiter can
4738 /// read a little over its ceiling (gain moves within the filter's support), so the walk may
4739 /// lower the ceiling below the target; the held mix is what is checked.
4740 #[test]
4741 fn the_mix_with_the_limiter_is_held_at_the_true_peak_target() {
4742 let mut srv = server_on(&tone_asset());
4743 let r = run_normalize(
4744 &mut srv,
4745 &json!({ "target": "mix", "lufs": -14, "true_peak": -15, "allow_limiter": true }),
4746 );
4747 assert!(!r.is_error, "{}", r.text);
4748 let st = r.structured.expect("structured");
4749 assert_eq!(st["limiter"]["on"], true, "{}", r.text);
4750 let measured = st["measured_true_peak_dbtp"].as_f64().unwrap();
4751 assert!(measured <= -15.0, "the mix reads {measured} dBTP past the -15 ceiling: {}", r.text);
4752 }
4753
4754 /// Three sources for three audio lanes, as the report's project had them: quiet speech-like pulses
4755 /// on A1, a quiet tone on A2 and clicks on A3. The mix is peaky, so its true peak, not its level, is what
4756 /// a gain runs into first.
4757 fn three_lanes_of_sound() -> (TestWav, Server) {
4758 static NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
4759 let n = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4760 let dir = std::env::temp_dir().join(format!("edith-hear-three-{}-{n}", std::process::id()));
4761 std::fs::create_dir_all(&dir).expect("temp dir");
4762 let pulses = dir.join("pulses.wav");
4763 write_wav_with(&pulses, 13, |t| {
4764 if t % 2.2 < 1.0 {
4765 0.05 * (2.0 * std::f64::consts::PI * 300.0 * t).sin()
4766 } else {
4767 0.0
4768 }
4769 });
4770 let tone = dir.join("tone.wav");
4771 write_wav_with(&tone, 13, |t| 0.003 * (2.0 * std::f64::consts::PI * 300.0 * t).sin());
4772 let clicks = dir.join("clicks.wav");
4773 write_wav_with(&clicks, 13, |t| {
4774 if t % 1.0 < 0.02 {
4775 0.7 * (2.0 * std::f64::consts::PI * 1000.0 * t).sin()
4776 } else {
4777 0.0
4778 }
4779 });
4780 let wav = TestWav { dir, path: pulses.clone() };
4781 let mut srv = server_on(&pulses);
4782 let import = crate::server::tools().into_iter().find(|t| t.name == "media_import").expect("tool");
4783 let paths = json!({ "paths": [tone.to_string_lossy(), clicks.to_string_lossy()] });
4784 let imported = (import.run)(&mut srv, &paths);
4785 assert!(!imported.is_error, "{}", imported.text);
4786 let made = crate::tools::edit::run_edit(
4787 &mut srv,
4788 &json!({"ops": [
4789 {"op": "lane_add", "kind": "audio"},
4790 {"op": "lane_add", "kind": "audio"},
4791 {"op": "place", "source": 1, "lane": "A2", "at": "0s"},
4792 {"op": "place", "source": 2, "lane": "A3", "at": "0s"},
4793 ]}),
4794 );
4795 assert!(!made.is_error, "{}", made.text);
4796 (wav, srv)
4797 }
4798
4799 /// A master limiter already on at -6 dBTP, below the -1 true_peak target, is the ceiling the peaks
4800 /// are held to: a normalize counts on it. The gain used to be predicted against -1 dBTP and the walk
4801 /// stopped at the limiter's ceiling short of the target, with the reply naming no cause.
4802 #[test]
4803 fn normalize_counts_on_a_limiter_already_on_below_the_true_peak_target() {
4804 let (_wav, mut srv) = three_lanes_of_sound();
4805 let set = srv.session.as_mut().unwrap().set_limiter(Limiter { on: true, ceiling_db: -6.0 });
4806 assert!(set, "the limiter was not set");
4807 let r = run_normalize(&mut srv, &json!({ "target": "mix", "lufs": -19 }));
4808 assert!(!r.is_error, "{}", r.text);
4809 let st = r.structured.expect("structured");
4810 assert_eq!(st["reached"], true, "{}", r.text);
4811 assert_eq!(st["capped_by"], Value::Null, "{}", r.text);
4812 let achieved = st["achieved_lufs"].as_f64().unwrap();
4813 assert!((achieved + 19.0).abs() <= 0.1, "reached {achieved}: {}", r.text);
4814 let measured = st["measured_true_peak_dbtp"].as_f64().unwrap();
4815 assert!(measured <= -6.0 + 0.05, "the limiter holds the peaks at -6: {measured}: {}", r.text);
4816 }
4817
4818 /// A level short of the target that the master limiter's ceiling holds names that limiter.
4819 #[test]
4820 fn a_short_normalize_held_by_the_limiter_names_the_limiter() {
4821 let (_wav, mut srv) = three_lanes_of_sound();
4822 srv.session.as_mut().unwrap().set_limiter(Limiter { on: true, ceiling_db: -6.0 });
4823 let r = run_normalize(&mut srv, &json!({ "target": "mix", "lufs": -9, "dry_run": true }));
4824 assert!(!r.is_error, "{}", r.text);
4825 let st = r.structured.expect("structured");
4826 assert_eq!(st["reached"], false, "{}", r.text);
4827 assert_eq!(st["capped_by"], "limiter", "{}", r.text);
4828 assert!(r.text.contains("held by the master limiter at -6.0 dBTP"), "{}", r.text);
4829 }
4830
4831 #[test]
4832 fn range_past_the_end_of_a_lane_is_named_in_seconds() {
4833 // A2 of a 3 s timeline: 5 s to 6 s is past its end, and says so.
4834 let err = range_arg(&json!({ "range": { "from": "5.0s", "to": "6.0s" } }), 30.0, 0, 90, "A2")
4835 .unwrap_err();
4836 assert!(err.contains("5.000s–6.000s is past the end of A2 (3.000s)"), "{err}");
4837 let err = range_arg(&json!({ "range": { "from": "1.0s", "to": "1.0s" } }), 30.0, 0, 90, "A2")
4838 .unwrap_err();
4839 assert!(err.starts_with("range is empty"), "{err}");
4840 assert_eq!(range_arg(&json!({ "range": { "from": "1.0s" } }), 30.0, 0, 90, "A2").unwrap(), (30, 90));
4841 }
4842
4843 #[test]
4844 fn missing_source_names_how_many_the_project_has() {
4845 assert_eq!(source_count_note(0), "this project has no sources");
4846 assert_eq!(source_count_note(1), "this project has 1 source (src:0)");
4847 assert_eq!(source_count_note(3), "this project has 3 sources (src:0..src:2)");
4848 }
4849
4850 #[test]
4851 fn loudness_of_a_missing_source_names_the_project_sources() {
4852 let mut srv = server_on(&tone_asset());
4853 let r = run_loudness(&mut srv, &json!({ "target": "src:1" }));
4854 assert!(r.is_error, "{}", r.text);
4855 assert_eq!(r.text, "no source src:1: this project has 1 source (src:0)");
4856 }
4857
4858 #[test]
4859 fn loudness_of_a_three_second_file_says_lra_needs_more_audio() {
4860 let mut srv = server_on(&tone_asset());
4861 let r = run_loudness(&mut srv, &json!({ "target": "src:0" }));
4862 assert!(!r.is_error, "{}", r.text);
4863 assert!(r.text.contains("LRA n/a"), "{}", r.text);
4864 assert!(r.text.contains("analysed 3.00 s of audio in "), "{}", r.text);
4865 let st = r.structured.expect("structured");
4866 assert!(st["range_lu"].is_null(), "{}", r.text);
4867 }
4868
4869 /// A 440 Hz tone at 0.0153 for 3 s, about -40 LUFS: a recording too quiet for the lane's +12 dB cap.
4870 fn quiet_tone() -> TestWav {
4871 static NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
4872 let n = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4873 let dir = std::env::temp_dir().join(format!("edith-hear-quiet-{}-{n}", std::process::id()));
4874 std::fs::create_dir_all(&dir).expect("temp dir");
4875 let path = dir.join("quiet_tone.wav");
4876 write_wav_with(&path, 3, |t| 0.0153 * (2.0 * std::f64::consts::PI * 440.0 * t).sin());
4877 TestWav { dir, path }
4878 }
4879
4880 fn clip_gain_of(srv: &Server, idx: usize) -> f32 {
4881 srv.session.as_ref().unwrap().clip_gain_of(Lane::A1, idx).expect("clip")
4882 }
4883
4884 #[test]
4885 fn normalize_takes_a_quiet_tone_past_the_lane_cap_onto_its_clip() {
4886 let wav = quiet_tone();
4887 let mut srv = server_for(&wav);
4888 let before = lufs_at(&mut srv, "A1");
4889 assert!((before - -40.0).abs() <= 1.0, "quiet tone at {before} LUFS");
4890 let r = run_normalize(&mut srv, &json!({ "target": "A1", "lufs": -16 }));
4891 assert!(!r.is_error, "{}", r.text);
4892 assert!(r.text.starts_with("target reached: "), "{}", r.text);
4893 assert!(r.text.contains("lane A1 +12.0 dB, clips A1@0 +12.0 dB clip gain"), "{}", r.text);
4894 assert_eq!(srv.session.as_ref().unwrap().lane_gain_db(Lane::A1), 12.0, "{}", r.text);
4895 assert!((clip_gain_of(&srv, 0) - 12.0).abs() <= 0.05, "clip gain {}: {}", clip_gain_of(&srv, 0), r.text);
4896 let st = r.structured.expect("structured");
4897 assert_eq!(st["reached"], true, "{}", r.text);
4898 assert!(st["capped_by"].is_null(), "{}", r.text);
4899 assert_eq!(st["clip_gain"][0]["clip"], "A1@0", "{}", r.text);
4900 let after = lufs_at(&mut srv, "A1");
4901 assert!((after - -16.0).abs() <= 0.2, "A1 at {after} LUFS: {}", r.text);
4902 }
4903
4904 #[test]
4905 fn clip_gain_boost_adds_to_the_gain_a_clip_already_has() {
4906 let wav = quiet_tone();
4907 let mut srv = server_for(&wav);
4908 assert!(srv.session.as_mut().unwrap().set_clip_gain(Lane::A1, 0, 3.0));
4909 // At +3 dB the tone is about -37 LUFS: the lane takes +12, the clip the other +9 on its +3.
4910 let r = run_normalize(&mut srv, &json!({ "target": "A1", "lufs": -16 }));
4911 assert!(!r.is_error, "{}", r.text);
4912 assert!(r.text.contains("lane A1 +12.0 dB, clips A1@0 +9.0 dB clip gain"), "{}", r.text);
4913 assert!((clip_gain_of(&srv, 0) - 12.0).abs() <= 0.05, "clip gain {}: {}", clip_gain_of(&srv, 0), r.text);
4914 }
4915
4916 #[test]
4917 fn clip_gain_boost_undo_restores_the_lane_and_clip_gains_exactly() {
4918 let wav = quiet_tone();
4919 let mut srv = server_for(&wav);
4920 assert!(srv.session.as_mut().unwrap().set_clip_gain(Lane::A1, 0, 3.0));
4921 let (lane0, clip0) = (srv.session.as_ref().unwrap().lane_gain_db(Lane::A1), clip_gain_of(&srv, 0));
4922 let depth = srv.session.as_ref().unwrap().undo_depth();
4923 let r = run_normalize(&mut srv, &json!({ "target": "A1", "lufs": -16 }));
4924 assert!(!r.is_error, "{}", r.text);
4925 assert_eq!(srv.ledger.len(), 1, "one undo step: {}", r.text);
4926 assert!(clip_gain_of(&srv, 0) > clip0, "{}", r.text);
4927 let s = srv.session.as_mut().expect("session");
4928 while s.undo_depth() > depth && s.undo() {}
4929 let s = srv.session.as_ref().expect("session");
4930 assert_eq!(s.lane_gain_db(Lane::A1), lane0);
4931 assert_eq!(s.clip_gain_of(Lane::A1, 0), Some(clip0));
4932 }
4933
4934 #[test]
4935 fn clip_gain_boost_dry_run_predicts_the_split_and_changes_nothing() {
4936 let wav = quiet_tone();
4937 let mut srv = server_for(&wav);
4938 let r = run_normalize(&mut srv, &json!({ "target": "A1", "lufs": -16, "dry_run": true }));
4939 assert!(!r.is_error, "{}", r.text);
4940 assert!(
4941 r.text.starts_with("target reached: dry run — would normalize A1 to -16.0 LUFS: lane A1 +12.0 dB, clips A1@0 +12.0 dB clip gain"),
4942 "{}",
4943 r.text
4944 );
4945 assert_eq!(r.structured.as_ref().unwrap()["changed"], false);
4946 assert_eq!(srv.ledger.len(), 0);
4947 assert_eq!(srv.session.as_ref().unwrap().lane_gain_db(Lane::A1), 0.0);
4948 assert_eq!(clip_gain_of(&srv, 0), 0.0, "{}", r.text);
4949 }
4950
4951 #[test]
4952 fn normalize_each_puts_the_boost_past_the_lane_cap_on_the_clips() {
4953 let wav = quiet_tone();
4954 let mut srv = server_for(&wav);
4955 let r = run_normalize(&mut srv, &json!({ "each": true, "lanes": ["A1"], "lufs": -16 }));
4956 assert!(!r.is_error, "{}", r.text);
4957 assert!(r.text.starts_with("target reached: normalized each lane"), "{}", r.text);
4958 assert!(r.text.contains("lane A1 +12.0 dB, clips A1@0 +12.0 dB clip gain"), "{}", r.text);
4959 assert_eq!(srv.ledger.len(), 1, "{}", r.text);
4960 }
4961
4962 #[test]
4963 fn a_boost_past_both_caps_says_so_and_names_the_shortfall() {
4964 // -40 LUFS plus +36 dB (lane +12, clip +24) reaches -4; -3 is one LU past that.
4965 let wav = quiet_tone();
4966 let mut srv = server_for(&wav);
4967 let r = run_normalize(&mut srv, &json!({ "target": "mix", "lufs": -3, "true_peak": 0 }));
4968 assert!(!r.is_error, "{}", r.text);
4969 assert!(r.text.starts_with("short of the target: mix raised "), "{}", r.text);
4970 assert!(r.text.contains("lane gain +12 dB and clip gain +24 dB on each clip is the most"), "{}", r.text);
4971 assert!(r.text.contains("LU short"), "{}", r.text);
4972 let st = r.structured.expect("structured");
4973 assert_eq!(st["capped_by"], "clip_gain_limit", "{}", r.text);
4974 assert_eq!(st["reached"], false, "{}", r.text);
4975 assert_eq!(srv.session.as_ref().unwrap().lane_gain_db(Lane::A1), 12.0);
4976 assert!((clip_gain_of(&srv, 0) - 24.0).abs() <= 0.05, "clip gain {}", clip_gain_of(&srv, 0));
4977 }
4978
4979 #[test]
4980 fn normalize_leads_with_the_outcome_and_names_the_lane_gain_cap() {
4981 // A loud target the lanes cannot reach: the reply says where it landed and why.
4982 let mut srv = server_on(&tone_asset());
4983 let r = run_normalize(&mut srv, &json!({ "target": "mix", "lufs": -2 }));
4984 assert!(!r.is_error, "{}", r.text);
4985 assert!(r.text.starts_with("short of the target: mix raised "), "{}", r.text);
4986 assert_eq!(r.structured.as_ref().unwrap()["capped_by"], "true_peak", "{}", r.text);
4987 }
4988
4989 fn levels_max(r: &Reply) -> f64 {
4990 r.structured.as_ref().expect("structured")["values"]
4991 .as_array()
4992 .expect("values")
4993 .iter()
4994 .filter_map(Value::as_f64)
4995 .fold(f64::MIN, f64::max)
4996 }
4997
4998 #[test]
4999 fn normalize_mix_reports_the_measured_peak() {
5000 let mut srv = server_on(&tone_asset());
5001 let r = run_normalize(
5002 &mut srv,
5003 &json!({ "target": "mix", "lufs": -14, "true_peak": -15 }),
5004 );
5005 assert!(!r.is_error, "{}", r.text);
5006 assert!(!r.text.contains("expected"), "{}", r.text);
5007 assert!(r.text.contains("(measured)"), "{}", r.text);
5008 let st = r.structured.expect("structured");
5009 assert_eq!(st["after_measured"], true, "{}", r.text);
5010 // The figure the reply gives is the one a fresh reading of the mix finds.
5011 let m = run_loudness(&mut srv, &json!({ "target": "mix" }));
5012 let peak = m.structured.expect("structured")["true_peak_dbtp"]
5013 .as_f64()
5014 .unwrap();
5015 let said = st["measured_true_peak_dbtp"].as_f64().unwrap();
5016 assert!((peak - said).abs() < 0.1, "reply {said} vs reading {peak}");
5017 assert!(peak <= -15.0 + 0.1, "the ceiling holds: {peak}");
5018 }
5019
5020 #[test]
5021 fn normalize_mix_keeps_the_true_peak_under_the_default_ceiling() {
5022 let mut srv = server_on(&tone_asset());
5023 let r = run_normalize(&mut srv, &json!({ "target": "mix", "lufs": -8 }));
5024 assert!(!r.is_error, "{}", r.text);
5025 let m = run_loudness(&mut srv, &json!({ "target": "mix" }));
5026 let peak = m.structured.expect("structured")["true_peak_dbtp"]
5027 .as_f64()
5028 .unwrap();
5029 assert!(
5030 peak <= -1.0 + 0.1,
5031 "-1 dBTP ceiling, mix reads {peak}: {}",
5032 r.text
5033 );
5034 }
5035
5036 fn run_edit_flags(srv: &mut Server, lane: &str, locked: bool) -> Reply {
5037 crate::tools::edit::run_edit(srv, &json!({"ops": [{"op": "lane_flags", "lane": lane, "locked": locked}]}))
5038 }
5039
5040 #[test]
5041 fn normalize_refuses_when_a_lane_it_would_change_is_locked() {
5042 // Single lane, each, and the mix: a locked lane among those a normalize would move refuses
5043 // the whole call, and nothing changes.
5044 for args in [
5045 json!({ "target": "A2", "lufs": -20 }),
5046 json!({ "each": true, "lanes": ["A1", "A2"], "lufs": -20 }),
5047 json!({ "target": "mix", "lufs": -20 }),
5048 ] {
5049 let mut srv = two_lanes_apart();
5050 let r = run_edit_flags(&mut srv, "A2", true);
5051 assert!(!r.is_error, "{}", r.text);
5052 let gain_before = srv.session.as_ref().unwrap().lane_gain_db(parse::lane("A2").unwrap());
5053 let ledger = srv.ledger.len();
5054 let r = run_normalize(&mut srv, &args);
5055 assert!(r.is_error, "{args}: {}", r.text);
5056 assert!(r.text.contains("A2 is locked"), "{args}: {}", r.text);
5057 assert_eq!(srv.ledger.len(), ledger, "{args}: nothing changed");
5058 assert_eq!(srv.session.as_ref().unwrap().lane_gain_db(parse::lane("A2").unwrap()), gain_before, "{args}");
5059 }
5060 }
5061
5062 #[test]
5063 fn normalize_limiter_path_ends_under_the_true_peak_ceiling() {
5064 let mut srv = server_on(&tone_asset());
5065 let r = run_normalize(
5066 &mut srv,
5067 &json!({ "target": "mix", "lufs": -14, "true_peak": -15, "allow_limiter": true }),
5068 );
5069 assert!(!r.is_error, "{}", r.text);
5070 let st = r.structured.expect("structured");
5071 // The walk aims under the target: the measured peak is at or under the ceiling, not 0.1 over it.
5072 let peak = st["measured_true_peak_dbtp"].as_f64().unwrap();
5073 assert!(peak <= -15.0, "true peak {peak} over the -15 ceiling: {}", r.text);
5074 assert!(r.text.contains("limiter left on at") && r.text.contains("dBTP"), "{}", r.text);
5075 }
5076
5077 #[test]
5078 fn normalize_counts_on_a_limiter_already_on_and_never_advises_the_flag() {
5079 // The true peak holds the linear gain at -15 dBTP (the tone reaches -14 LUFS only past it), so
5080 // without a limiter the mix stops short. With the limiter already on at the same ceiling, the
5081 // flag would change nothing: the mix is normalized with the limiter in circuit, and says so.
5082 let args = json!({ "target": "mix", "lufs": -14, "true_peak": -15, "dry_run": true });
5083 let mut plain = server_on(&tone_asset());
5084 let plain_r = run_normalize(&mut plain, &args);
5085 let plain_lufs = plain_r.structured.expect("structured")["achieved_lufs"].as_f64().unwrap();
5086
5087 let mut srv = server_on(&tone_asset());
5088 srv.session
5089 .as_mut()
5090 .unwrap()
5091 .set_limiter(engine::limiter::Limiter { on: true, ceiling_db: -15.0 });
5092 let r = run_normalize(&mut srv, &args);
5093 assert!(!r.is_error, "{}", r.text);
5094 assert!(!r.text.contains("allow_limiter"), "the flag changes nothing here: {}", r.text);
5095 assert!(r.text.contains("counted on"), "{}", r.text);
5096 let st = r.structured.expect("structured");
5097 assert_eq!(st["limiter_counted_on"], true, "{}", r.text);
5098 let achieved = st["achieved_lufs"].as_f64().unwrap();
5099 assert!(achieved > plain_lufs + 0.5, "the limiter lets the gain on: {achieved} vs {plain_lufs}: {}", r.text);
5100 // A dry run takes its change back: the limiter is still on at the ceiling it was at.
5101 assert!(srv.session.as_ref().unwrap().limiter().on);
5102 assert!((srv.session.as_ref().unwrap().limiter().ceiling_db + 15.0).abs() < 1e-3);
5103 }
5104
5105 #[test]
5106 fn levels_per_sec_error_says_what_the_number_is() {
5107 let mut srv = server_on(&tone_asset());
5108 let r = run_levels(&mut srv, &json!({ "target": "A1", "per_sec": 60 }));
5109 assert!(r.is_error, "{}", r.text);
5110 assert!(r.text.contains("per_sec is buckets per second"), "{}", r.text);
5111 assert!(r.text.contains("e.g. 10"), "{}", r.text);
5112 }
5113
5114 #[test]
5115 fn hear_schemas_show_per_sec_type_and_loudness_target_required() {
5116 let levels = levels_schema();
5117 assert_eq!(levels["properties"]["per_sec"]["type"], "number");
5118 assert!(levels["properties"]["per_sec"]["description"].as_str().unwrap().contains("Buckets per second"));
5119 let loudness = loudness_schema();
5120 assert_eq!(loudness["required"], json!(["target"]));
5121 assert!(loudness["properties"]["target"]["description"].as_str().unwrap().starts_with("Required."));
5122 assert!(LOUDNESS_DOC.contains("target is required"));
5123 }
5124
5125 #[test]
5126 fn allow_limiter_on_a_lane_says_why_and_what_to_run() {
5127 let mut srv = server_on(&tone_asset());
5128 let r = run_normalize(
5129 &mut srv,
5130 &json!({ "target": "A1", "lufs": -14, "allow_limiter": true }),
5131 );
5132 assert!(r.is_error, "{}", r.text);
5133 assert!(r.text.contains("mix-wide"), "{}", r.text);
5134 assert!(r.text.contains("normalize A1 without it"), "{}", r.text);
5135 assert!(r.text.contains("allow_limiter:true"), "{}", r.text);
5136 assert_eq!(srv.ledger.len(), 0);
5137 }
5138
5139 #[test]
5140 fn a_ducked_lane_reads_with_its_duck() {
5141 let mut srv = server_on(&tone_asset());
5142 let a2 = {
5143 let s = srv.session.as_mut().expect("session");
5144 let a2 = s.add_lane(LaneKind::Audio);
5145 let clip = s.lane_clips(Lane::A1)[0].clone();
5146 assert!(s.place_at(a2, 0.0, clip), "place a copy of the tone on A2");
5147 a2
5148 };
5149 let plain = run_loudness(&mut srv, &json!({ "target": "A2" }));
5150 let plain_levels = run_levels(&mut srv, &json!({ "target": "A2", "per_sec": 10 }));
5151 assert!(!plain.is_error && !plain_levels.is_error, "{}", plain.text);
5152
5153 // A1 is the key: the tone is well above -60 dBFS, so A2 drops by 20 dB.
5154 let duck = engine::duck::Duck {
5155 threshold_db: -60.0,
5156 ..engine::duck::Duck::new(0, -20.0)
5157 };
5158 assert!(srv.session.as_mut().unwrap().set_lane_duck(a2, Some(duck)));
5159 let ducked = run_loudness(&mut srv, &json!({ "target": "A2" }));
5160 assert!(!ducked.is_error, "{}", ducked.text);
5161 assert!(
5162 integrated_of(&ducked) <= integrated_of(&plain) - 10.0,
5163 "ducked {} vs plain {}",
5164 integrated_of(&ducked),
5165 integrated_of(&plain)
5166 );
5167 let ducked_levels = run_levels(&mut srv, &json!({ "target": "A2", "per_sec": 10 }));
5168 assert!(!ducked_levels.is_error, "{}", ducked_levels.text);
5169 assert!(
5170 levels_max(&ducked_levels) <= levels_max(&plain_levels) - 10.0,
5171 "levels {} vs {}",
5172 levels_max(&ducked_levels),
5173 levels_max(&plain_levels)
5174 );
5175 assert!(
5176 ducked_levels.text.contains("duck under A1"),
5177 "{}",
5178 ducked_levels.text
5179 );
5180
5181 // Taken off again, the lane reads as it did.
5182 assert!(srv.session.as_mut().unwrap().set_lane_duck(a2, None));
5183 let off = run_loudness(&mut srv, &json!({ "target": "A2" }));
5184 assert!((integrated_of(&off) - integrated_of(&plain)).abs() < 0.1);
5185 }
5186
5187 #[test]
5188 fn a_lane_ducked_under_two_keys_reads_with_both_ducks() {
5189 let mut srv = server_on(&tone_asset());
5190 let a2 = {
5191 let s = srv.session.as_mut().expect("session");
5192 let a2 = s.add_lane(LaneKind::Audio);
5193 let a3 = s.add_lane(LaneKind::Audio);
5194 let clip = s.lane_clips(Lane::A1)[0].clone();
5195 assert!(s.place_at(a2, 0.0, clip.clone()), "the ducked tone on A2");
5196 assert!(s.place_at(a3, 0.0, clip), "a second key on A3");
5197 a2
5198 };
5199 let plain_levels = run_levels(&mut srv, &json!({ "target": "A2", "per_sec": 10 }));
5200 assert!(!plain_levels.is_error, "{}", plain_levels.text);
5201 let plain_levels_lufs = run_loudness(&mut srv, &json!({ "target": "A2" }));
5202 let s = srv.session.as_mut().unwrap();
5203 // A1 and A3 are both loud tones: A2 drops by 20 dB under A1 and 6 dB under A3.
5204 let under_a1 = engine::duck::Duck {
5205 threshold_db: -60.0,
5206 ..engine::duck::Duck::new(0, -20.0)
5207 };
5208 let under_a3 = engine::duck::Duck {
5209 threshold_db: -60.0,
5210 ..engine::duck::Duck::new(2, -6.0)
5211 };
5212 assert!(s.set_lane_duck(a2, Some(under_a1)));
5213 assert!(s.set_lane_duck(a2, Some(under_a3)));
5214 assert_eq!(s.lane_duck_list(a2).len(), 2, "both ducks stand");
5215
5216 let both = run_loudness(&mut srv, &json!({ "target": "A2" }));
5217 assert!(!both.is_error, "{}", both.text);
5218 assert!(
5219 both.text.contains("ducks under A1 (-20.0 dB at most) and A3 (-6.0 dB at most)"),
5220 "{}",
5221 both.text
5222 );
5223 assert!(
5224 integrated_of(&both) <= integrated_of(&plain_levels_lufs) - 20.0,
5225 "both ducks: {} vs plain {}",
5226 integrated_of(&both),
5227 integrated_of(&plain_levels_lufs)
5228 );
5229
5230 // Off for A3 alone leaves A1's duck, and the reading comes back up to it.
5231 assert!(srv.session.as_mut().unwrap().clear_lane_duck(a2, 2));
5232 let one = run_loudness(&mut srv, &json!({ "target": "A2" }));
5233 assert!(!one.is_error, "{}", one.text);
5234 assert!(one.text.contains("duck under A1 (-20.0 dB at most)"), "{}", one.text);
5235 let gap = integrated_of(&one) - integrated_of(&plain_levels_lufs);
5236 assert!((-22.0..=-18.0).contains(&gap), "only A1's duck: {gap} dB");
5237 }
5238
5239 /// The 1 s silence between two tones, cut with the given settings; returns the seconds removed.
5240 fn removed_by_cut(args: Value) -> f64 {
5241 let wav = tone_wav();
5242 let mut srv = server_for(&wav);
5243 let fps = fps_of(&srv);
5244 let before = parse::session_end(srv.session.as_ref().unwrap());
5245 let r = run_cut_silence(&mut srv, &args);
5246 assert!(!r.is_error, "{}", r.text);
5247 let after = parse::session_end(srv.session.as_ref().unwrap());
5248 parse::secs(before - after, fps)
5249 }
5250
5251 #[test]
5252 fn cut_silence_keeps_a_beat_of_each_pause_by_default() {
5253 // A 1 s pause keeps 0.4 s by default, so about 0.53 s goes.
5254 let default = removed_by_cut(json!({ "target": "A1" }));
5255 assert!((0.5..=0.6).contains(&default), "default removed {default}s");
5256 let kept = removed_by_cut(json!({ "target": "A1", "keep": 0.7 }));
5257 assert!((0.25..=0.35).contains(&kept), "keep 0.7 removed {kept}s");
5258 }
5259
5260 #[test]
5261 fn cut_silence_refuses_keep_under_a_twentieth_of_a_second() {
5262 let mut srv = server_for(&tone_wav());
5263 let before = parse::session_end(srv.session.as_ref().unwrap());
5264 let r = run_cut_silence(&mut srv, &json!({ "target": "A1", "keep": 0 }));
5265 assert!(r.is_error && r.text.contains("cut_regions"), "{}", r.text);
5266 assert_eq!(parse::session_end(srv.session.as_ref().unwrap()), before);
5267 }
5268
5269 /// The refusal names each span as start to end, never end before start: spans are start and
5270 /// length frames, so the end is their sum.
5271 #[test]
5272 fn cut_spans_are_named_start_to_end() {
5273 assert_eq!(super::span_list(&[(10, 5), (40, 12)], 25.0), "0.400–0.600s, 1.600–2.080s");
5274 }
5275
5276 /// Every span a refused cut names runs forward: its start comes before its end.
5277 #[test]
5278 fn a_refused_cut_names_each_span_start_to_end() {
5279 let wav = beeps_wav();
5280 let mut srv = server_for(&wav);
5281 let r = run_cut_silence(&mut srv, &json!({ "target": "A1", "keep": 0.05 }));
5282 assert!(r.is_error, "{}", r.text);
5283 let list = r.text.split("Cut spans: ").nth(1).and_then(|t| t.split(". Nothing changed").next()).unwrap();
5284 let spans: Vec<&str> = list.split(", ").collect();
5285 assert!(spans.len() >= 2, "{}", r.text);
5286 for span in spans {
5287 let (a, b) = span.trim_end_matches('s').split_once('–').unwrap();
5288 let (a, b): (f64, f64) = (a.parse().unwrap(), b.parse().unwrap());
5289 assert!(a < b, "span {span} runs backwards: {}", r.text);
5290 }
5291 }
5292
5293 /// Four 50 ms tone bursts, one per second: the quiet between them is 0.95 s.
5294 fn beeps_wav() -> TestWav {
5295 let wav = tone_wav();
5296 write_wav_with(&wav.path, 4, |t| {
5297 if t % 1.0 < 0.05 {
5298 0.5 * (2.0 * std::f64::consts::PI * 440.0 * t).sin()
5299 } else {
5300 0.0
5301 }
5302 });
5303 wav
5304 }
5305
5306 #[test]
5307 fn cut_silence_over_half_the_sound_is_refused_and_changes_nothing() {
5308 let wav = beeps_wav();
5309 let mut srv = server_for(&wav);
5310 let before = parse::session_end(srv.session.as_ref().unwrap());
5311 // Keep 0.05 cuts 4 x 0.6 s of a 4 s take: 60 %, over the half a cut may take.
5312 for dry in [true, false] {
5313 let r = run_cut_silence(&mut srv, &json!({ "target": "A1", "keep": 0.05, "dry_run": dry }));
5314 assert!(r.is_error && r.text.contains("force:true"), "dry {dry}: {}", r.text);
5315 assert!(r.text.contains("Cut spans"), "{}", r.text);
5316 assert_eq!(parse::session_end(srv.session.as_ref().unwrap()), before, "dry {dry}");
5317 }
5318 let r = run_cut_silence(&mut srv, &json!({ "target": "A1", "keep": 0.05, "force": true }));
5319 assert!(!r.is_error, "{}", r.text);
5320 }
5321
5322 #[test]
5323 fn cut_silence_keeps_every_burst_of_speech_at_a_short_keep() {
5324 let wav = beeps_wav();
5325 let mut srv = server_for(&wav);
5326 let bursts = loud_windows(&srv);
5327 // min_keep would join each 50 ms burst to the silences either side and cut it too; a cut
5328 // keeps every burst whole.
5329 let r = run_cut_silence(&mut srv, &json!({ "target": "A1", "keep": 0.05, "force": true }));
5330 assert!(!r.is_error, "{}", r.text);
5331 let loud_after = loud_windows(&srv);
5332 assert!(loud_after.abs_diff(bursts) <= 3, "burst windows {bursts} before, {loud_after} after: {}", r.text);
5333 }
5334
5335 #[test]
5336 fn cut_silence_takes_keep_and_padding_together_and_refuses_keep_over_ten() {
5337 let wav = tone_wav();
5338 let mut srv = server_for(&wav);
5339 let r = run_cut_silence(&mut srv, &json!({ "target": "A1", "keep": 0.4, "padding": 0.2 }));
5340 assert!(!r.is_error, "{}", r.text);
5341 let r = run_cut_silence(&mut srv, &json!({ "target": "A1", "keep": 11 }));
5342 assert!(r.is_error, "{}", r.text);
5343 }
5344
5345 /// The loud (above -40 dBFS) 20 ms windows of A1, as the silence scan reads them.
5346 fn loud_windows(srv: &Server) -> usize {
5347 let s = srv.session.as_ref().unwrap();
5348 let (w, _, _) = lane_windows(s, parse::lane("A1").unwrap()).expect("lane windows");
5349 w.iter().filter(|&&v| v > -40.0).count()
5350 }
5351
5352 #[test]
5353 fn cut_silence_cuts_exactly_the_regions_silence_reports_and_no_tone_sample() {
5354 // Tone, 1 s of silence, tone: the silence is 1.0 to 2.0 s, and its padding is kept.
5355 let wav = tone_wav();
5356 let mut srv = server_for(&wav);
5357 let fps = fps_of(&srv);
5358 let loud_before = loud_windows(&srv);
5359 assert!(loud_before >= 99, "tone windows before: {loud_before}");
5360 let sil = run_silence(&mut srv, &json!({ "target": "A1", "min_silence": 0.05 }));
5361 assert!(!sil.is_error, "{}", sil.text);
5362 let cut = run_cut_silence(&mut srv, &json!({ "target": "A1", "min_silence": 0.05, "keep": 0.1 }));
5363 assert!(!cut.is_error, "{}", cut.text);
5364 // Same regions, to the frame, for the same settings.
5365 assert_eq!(
5366 sil.structured.as_ref().unwrap()["regions"],
5367 cut.structured.as_ref().unwrap()["regions"],
5368 "silence {} / cut {}",
5369 sil.text,
5370 cut.text
5371 );
5372 // The cut removed interior silence only: every tone window is still there (a window
5373 // either side of the joint may read differently, by a window or two).
5374 let loud_after = loud_windows(&srv);
5375 assert!(loud_after.abs_diff(loud_before) <= 3, "tone windows {loud_before} before, {loud_after} after: {}", cut.text);
5376 // keep 0.1 is under the 0.3 s of padding either side, so the whole 0.67 s between paddings goes,
5377 // and the 0.15 s of padding each side is what is left: a 0.36 s pause, as measured.
5378 let removed = parse::secs(cut.structured.as_ref().unwrap()["removed_frames"].as_u64().unwrap() as u32, fps);
5379 assert!((0.6..=0.7).contains(&removed), "removed {removed} s: {}", cut.text);
5380 }
5381
5382 #[test]
5383 fn silence_default_min_lists_only_regions_as_long_as_the_minimum() {
5384 // The 1 s quiet run is judged before its padding: the default 0.5 s minimum keeps it, and
5385 // a 1.2 s minimum, which it does not reach, lists nothing.
5386 let wav = tone_wav();
5387 let mut srv = server_for(&wav);
5388 let r = run_silence(&mut srv, &json!({ "target": "A1" }));
5389 assert_eq!(r.structured.as_ref().unwrap()["count"], 1, "{}", r.text);
5390 let r = run_silence(&mut srv, &json!({ "target": "A1", "min_silence": 1.2 }));
5391 assert_eq!(r.structured.as_ref().unwrap()["count"], 0, "{}", r.text);
5392 }
5393
5394 /// A WAV of `secs` seconds whose sample at `t` is `f(t)`, removed when the test ends.
5395 fn wav_of(secs: u32, f: impl Fn(f64) -> f64) -> TestWav {
5396 static NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
5397 let n = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
5398 let dir = std::env::temp_dir().join(format!("edith-hear-wav-{}-{n}", std::process::id()));
5399 std::fs::create_dir_all(&dir).expect("temp dir");
5400 let path = dir.join("wav.wav");
5401 write_wav_with(&path, secs, f);
5402 TestWav { dir, path }
5403 }
5404
5405 #[test]
5406 fn a_pause_of_0_4_s_is_found_at_a_0_3_s_minimum() {
5407 // Tone, a 0.4 s pause of digital silence, tone. The pause is judged before the 0.15 s of
5408 // padding comes off its ends, so it is a region at a 0.3 s minimum (0.1 s after padding).
5409 let wav = wav_of(3, |t| {
5410 if (1.0..1.4).contains(&t) {
5411 0.0
5412 } else {
5413 0.3 * (2.0 * std::f64::consts::PI * 440.0 * t).sin()
5414 }
5415 });
5416 let mut srv = server_for(&wav);
5417 let r = run_silence(&mut srv, &json!({ "target": "A1", "threshold_db": -40, "min_silence": 0.3 }));
5418 assert!(!r.is_error, "{}", r.text);
5419 assert_eq!(r.structured.as_ref().unwrap()["count"], 1, "{}", r.text);
5420 }
5421
5422 #[test]
5423 fn the_threshold_is_measured_from_quiet_speech_when_none_is_given() {
5424 // Speech at about -48 dBFS, pauses of about -80 dBFS. The default -40 dBFS calls the speech
5425 // quiet too, so the pauses are lost in it; the measured threshold (30 dB under the speech) finds
5426 // the pauses, and the reply names the threshold it used.
5427 let speech = |t: f64| 0.00563 * (2.0 * std::f64::consts::PI * 220.0 * t).sin();
5428 let wav = wav_of(4, |t| {
5429 if (1.0..1.4).contains(&t) || (2.4..2.8).contains(&t) {
5430 1.4e-4 * (2.0 * std::f64::consts::PI * 300.0 * t).sin()
5431 } else {
5432 speech(t)
5433 }
5434 });
5435 let mut srv = server_for(&wav);
5436 let fixed = run_silence(&mut srv, &json!({ "target": "A1", "threshold_db": -40, "min_silence": 0.3 }));
5437 // At -40 the speech is quiet too, so the pauses are not separate silences.
5438 assert_ne!(fixed.structured.as_ref().unwrap()["count"], 2, "{}", fixed.text);
5439 let auto = run_silence(&mut srv, &json!({ "target": "A1", "min_silence": 0.3 }));
5440 assert!(!auto.is_error, "{}", auto.text);
5441 assert_eq!(auto.structured.as_ref().unwrap()["count"], 2, "{}", auto.text);
5442 assert_eq!(auto.structured.as_ref().unwrap()["threshold_auto"], true);
5443 assert!(auto.text.contains("threshold") && auto.text.contains("median speech level"), "{}", auto.text);
5444 }
5445
5446 #[test]
5447 fn a_silence_running_to_the_clip_end_keeps_keep_after_the_speech() {
5448 // 1 s of tone, then 1 s of digital silence that ends the clip. The tail's pause is kept at
5449 // 0.4 s after the last speech (its 0.15 s end padding stays too), not cut to ~0.2 s.
5450 let wav = wav_of(2, |t| if t < 1.0 { 0.5 * (2.0 * std::f64::consts::PI * 440.0 * t).sin() } else { 0.0 });
5451 let mut srv = server_for(&wav);
5452 let fps = fps_of(&srv);
5453 let r = run_cut_silence(&mut srv, &json!({ "target": "A1" }));
5454 assert!(!r.is_error, "{}", r.text);
5455 let st = r.structured.as_ref().unwrap();
5456 let measured = st["pauses_measured_s"][0].as_f64().expect("a measured pause");
5457 assert!(measured >= 0.4 - 0.03, "tail pause {measured} s: {}", r.text);
5458 // The silence was 1 s: 0.4 s is the whole pause left after the speech, its 0.15 s end
5459 // padding among it, and 0.6 s goes.
5460 let removed = parse::secs(st["removed_frames"].as_u64().unwrap() as u32, fps);
5461 assert!((removed - 0.6).abs() < 0.05, "removed {removed} s: {}", r.text);
5462 }
5463
5464 #[test]
5465 fn cut_silence_says_every_silence_is_at_or_under_keep_and_cuts_nothing() {
5466 let wav = tone_wav();
5467 let mut srv = server_for(&wav);
5468 let before = parse::session_end(srv.session.as_ref().unwrap());
5469 // The 1 s gap is 0.7 s after padding, so a 1.5 s keep is more than every silence.
5470 let r = run_cut_silence(&mut srv, &json!({ "target": "A1", "keep": 1.5 }));
5471 assert!(!r.is_error, "{}", r.text);
5472 assert!(r.text.contains("1 silence(s) found") && r.text.contains("all ≤ keep") && r.text.contains("nothing cut"), "{}", r.text);
5473 assert!(!r.text.contains("no silence found"), "{}", r.text);
5474 assert_eq!(parse::session_end(srv.session.as_ref().unwrap()), before);
5475 assert_eq!(srv.ledger.len(), 0);
5476 }
5477
5478 #[test]
5479 fn cut_silence_guard_counts_the_clips_sound_not_the_lead_in_gap() {
5480 // Two 3 s clips with a 2 s gap between them: the gap is not sound, so the 2 x 0.57 s of quiet
5481 // inside the clips is about a sixth of the 6 s of sound and is not refused.
5482 let wav = tone_wav();
5483 let mut srv = gapped_lane(&wav);
5484 let fps = fps_of(&srv);
5485 let r = run_cut_silence(&mut srv, &json!({ "target": "A1" }));
5486 assert!(!r.is_error, "{}", r.text);
5487 assert!(!r.text.contains("more than half"), "{}", r.text);
5488 let st = r.structured.as_ref().unwrap();
5489 let sound = parse::secs(st["removed_sound_frames"].as_u64().unwrap() as u32, fps);
5490 assert!((0.9..=1.3).contains(&sound), "sound removed {sound} s: {}", r.text);
5491 }
5492
5493 #[test]
5494 fn cut_silence_over_half_the_sound_counts_the_sound_it_removes() {
5495 // Over half of the sound is refused with the sound's own figures, not the timeline's.
5496 let wav = beeps_wav();
5497 let mut srv = server_for(&wav);
5498 let r = run_cut_silence(&mut srv, &json!({ "target": "A1", "keep": 0.05, "dry_run": true }));
5499 assert!(r.is_error, "{}", r.text);
5500 assert!(r.text.contains("of 4.000 s of sound"), "{}", r.text);
5501 }
5502
5503 #[test]
5504 fn levels_clamps_a_to_one_frame_past_the_end_and_refuses_more() {
5505 // A lane of 90 frames at 30 fps: 91 is one frame past its end, which is the end.
5506 let r = range_arg(&json!({ "range": { "from": "0f", "to": "91f" } }), 30.0, 0, 90, "A2").unwrap();
5507 assert_eq!(r, (0, 90));
5508 let err = range_arg(&json!({ "range": { "from": "0f", "to": "92f" } }), 30.0, 0, 90, "A2").unwrap_err();
5509 assert!(err.contains("3.067s") && err.contains("3.000s"), "{err}");
5510 }
5511
5512 #[test]
5513 fn levels_warns_about_the_range_it_measured_and_says_which() {
5514 // One second of full-scale tone, then silence: the peak is only in the first second.
5515 let wav = tone_wav();
5516 write_wav_with(&wav.path, 3, |t| if t < 1.0 { 0.99 * (2.0 * std::f64::consts::PI * 440.0 * t).sin() } else { 0.0 });
5517 let mut srv = server_for(&wav);
5518 let quiet = run_levels(&mut srv, &json!({ "target": "A1", "range": { "from": "1.5s", "to": "2.5s" } }));
5519 assert!(!quiet.is_error, "{}", quiet.text);
5520 assert!(!quiet.text.contains("WARNING"), "{}", quiet.text);
5521 let loud = run_levels(&mut srv, &json!({ "target": "A1", "range": { "from": "0s", "to": "1s" } }));
5522 assert!(loud.text.contains("WARNING: true peak") && loud.text.contains("over 0.000–1.000s of A1"), "{}", loud.text);
5523 }
5524
5525 #[test]
5526 fn peak_warning_names_the_span_it_measured() {
5527 assert!(peak_warning(-0.3, -20.0, "0.000–1.000s of A1", false).unwrap().contains("over 0.000–1.000s of A1"));
5528 assert!(peak_warning(-1.5, -20.0, "the whole A1", false).is_none());
5529 }
5530
5531 #[test]
5532 fn peak_warning_is_strictly_above_the_ceiling() {
5533 // Exactly -1 dBTP is within spec: no warning. Just over it warns, with the ceiling named.
5534 assert!(peak_warning(-1.0, -20.0, "the mix", true).is_none());
5535 let over = peak_warning(-0.94, -20.0, "the mix", true).expect("-0.94 is above the ceiling");
5536 assert!(over.contains("true peak -0.9 dBTP over the mix is above the -1 dBTP ceiling (clips on some players)"), "{over}");
5537 assert!(!over.contains("at or above"), "{over}");
5538 }
5539
5540 #[test]
5541 fn peak_warning_is_judged_on_the_shown_value() {
5542 // -0.96 and -0.95 read -1.0 at one decimal, the ceiling itself: no warning, and no
5543 // "-1.0 dBTP ... above the -1 dBTP ceiling" line. -0.94 reads -0.9 and warns.
5544 assert!(peak_warning(-0.96, -20.0, "the mix", true).is_none());
5545 assert!(peak_warning(-0.951, -20.0, "the mix", true).is_none());
5546 assert!(peak_warning(-0.95, -20.0, "the mix", true).is_none());
5547 assert!(peak_warning(-0.949, -20.0, "the mix", true).unwrap().contains("true peak -0.9 dBTP"));
5548 }
5549
5550 #[test]
5551 fn headroom_is_named_only_when_the_target_needs_a_gain_up() {
5552 // Louder than -14: the normalize turns the mix down, so there is no headroom claim.
5553 let loud = peak_warning(-0.3, -12.6, "the mix", true).unwrap();
5554 assert!(loud.contains("a normalize to -14 would turn it down 1.4 dB"), "{loud}");
5555 assert!(!loud.contains("held by the ceiling"), "{loud}");
5556 // Quieter than -14: the gain up is held by the peaks, and that is said.
5557 let quiet = peak_warning(-0.3, -16.0, "the mix", true).unwrap();
5558 assert!(quiet.contains("no headroom") && quiet.contains("gain up is held"), "{quiet}");
5559 }
5560
5561 /// A mix a normalize would turn down 0.6 dB, but whose peak needs 2.2 dB more: the ceiling holds
5562 /// the level at -15.6 LUFS, and the note says so. A lane names the limiter by its mix instead.
5563 #[test]
5564 fn loudness_prediction_counts_the_true_peak_ceiling() {
5565 let mix = peak_warning(1.2, -13.4, "the mix", true).unwrap();
5566 assert!(
5567 mix.contains("a normalize to -14 would turn it down 0.6 dB, but the -1 dBTP ceiling holds it at -15.6 LUFS unless allow_limiter:true"),
5568 "{mix}"
5569 );
5570 let lane = peak_warning(1.2, -13.4, "0.000–4.000s of A1", false).unwrap();
5571 assert!(lane.contains("holds it at -15.6 LUFS unless a normalize of the mix with allow_limiter:true"), "{lane}");
5572 // A peak that needs less than the level's own turn-down leaves the prediction as it was.
5573 let small = peak_warning(-0.4, -13.4, "the mix", true).unwrap();
5574 assert!(small.contains("would turn it down 0.6 dB") && !small.contains("holds it"), "{small}");
5575 }
5576
5577 #[test]
5578 fn normalize_dry_run_reports_the_planned_gain_and_changes_nothing() {
5579 let wav = tone_wav();
5580 let mut srv = server_for(&wav);
5581 let gain_before = srv.session.as_ref().unwrap().lane_gain_db(parse::lane("A1").unwrap());
5582 let depth = srv.session.as_ref().unwrap().undo_depth();
5583 let r = run_normalize(&mut srv, &json!({"target": "A1", "lufs": -14, "dry_run": true}));
5584 assert!(!r.is_error, "{}", r.text);
5585 assert!(r.text.starts_with("target reached: dry run — would "), "{}", r.text);
5586 assert!(r.text.contains("· nothing changed"), "{}", r.text);
5587 assert!(r.text.contains("A1 ") && r.text.contains("dB"), "{}", r.text);
5588 let st = r.structured.as_ref().unwrap();
5589 assert_eq!(st["changed"], false);
5590 assert_eq!(st["lane_moves"].as_array().unwrap().len(), 1);
5591 let gain_after = srv.session.as_ref().unwrap().lane_gain_db(parse::lane("A1").unwrap());
5592 assert_eq!(gain_before, gain_after);
5593 assert_eq!(srv.session.as_ref().unwrap().undo_depth(), depth);
5594 assert_eq!(srv.ledger.len(), 0);
5595 }
5596
5597 #[test]
5598 fn normalize_dry_run_with_the_limiter_predicts_the_real_run() {
5599 // The tone peaks at -18 dBTP, so the -15 ceiling binds and allow_limiter gives the gain back
5600 // through the limiter. The dry run makes that same change, then takes it back.
5601 let args = json!({ "target": "mix", "lufs": -19, "true_peak": -15, "allow_limiter": true });
5602 let mut dry_srv = server_on(&tone_asset());
5603 let depth = dry_srv.session.as_ref().unwrap().undo_depth();
5604 let dry = run_normalize(&mut dry_srv, &json!({ "target": "mix", "lufs": -19, "true_peak": -15, "allow_limiter": true, "dry_run": true }));
5605 assert!(!dry.is_error, "{}", dry.text);
5606 assert!(dry.text.starts_with("target reached: dry run — would normalize "), "{}", dry.text);
5607 assert!(dry.text.contains("· nothing changed"), "{}", dry.text);
5608 assert_eq!(dry_srv.ledger.len(), 0);
5609 // A dry run changes nothing, so it says what the real run would do to the limiter.
5610 assert!(dry.text.contains("would turn the limiter on at -15."), "{}", dry.text);
5611 assert!(!dry.text.contains("left on"), "{}", dry.text);
5612 let s = dry_srv.session.as_ref().unwrap();
5613 assert!(!s.limiter().on, "the trial's limiter is taken back");
5614 assert_eq!(s.undo_depth(), depth);
5615
5616 let mut real_srv = server_on(&tone_asset());
5617 let real = run_normalize(&mut real_srv, &args);
5618 assert!(!real.is_error, "{}", real.text);
5619 assert!(real.text.contains("limiter left on at -15."), "{}", real.text);
5620 let d = dry.structured.expect("structured");
5621 let r = real.structured.expect("structured");
5622 let (dl, rl) = (d["achieved_lufs"].as_f64().unwrap(), r["achieved_lufs"].as_f64().unwrap());
5623 assert!((dl - rl).abs() < 1e-9, "dry run {dl} vs real {rl}: {} / {}", dry.text, real.text);
5624 assert_eq!(d["lane_moves"], r["lane_moves"], "{} / {}", dry.text, real.text);
5625 assert_eq!(d["measured_true_peak_dbtp"], r["measured_true_peak_dbtp"]);
5626 assert_eq!(d["capped_by"], r["capped_by"]);
5627 // A boost, not a cut: the lanes go up, and the limiter takes back part of that gain.
5628 let applied = r["applied_db"].as_f64().unwrap();
5629 assert!(applied > 0.0, "{}", real.text);
5630 assert!(real.text.contains("the limiter took back"), "{}", real.text);
5631 assert!(real.text.contains("lane gain A"), "{}", real.text);
5632 assert!(real.text.contains("AAC/Opus encoding can add up to about 1 dB of true peak"), "{}", real.text);
5633 }
5634
5635 #[test]
5636 fn normalize_each_headline_says_what_the_lanes_reached() {
5637 let mut srv = two_lanes_apart();
5638 // -8 LUFS is past what a -15 dBTP ceiling lets the tone reach on either lane.
5639 let r = run_normalize(&mut srv, &json!({ "each": true, "lanes": ["A1", "A2"], "lufs": -8, "true_peak": -15 }));
5640 assert!(!r.is_error, "{}", r.text);
5641 // Each lane names what it moved by and reached; the peak ceiling holds them both, said once.
5642 assert!(r.text.starts_with("short of the target: A1 "), "{}", r.text);
5643 assert!(r.text.contains(" LUFS; A2 "), "{}", r.text);
5644 assert!(r.text.contains(" — both held by the -15.0 dBTP ceiling (A1 peaked at -18.1 dBTP before, A2 peaked at -24.1 dBTP before); no lane alone reaches -8.0 past it; normalize target mix with allow_limiter:true to reach it on the mix"), "{}", r.text);
5645 assert!(!r.text.contains("speech"), "{}", r.text);
5646 assert!(!r.text.contains("normalized each lane to -8.0"), "{}", r.text);
5647 assert!(!r.text.contains("did not all reach"), "{}", r.text);
5648 assert_eq!(r.structured.as_ref().unwrap()["reached"], false);
5649 }
5650
5651 #[test]
5652 fn normalize_lane_names_the_level_it_reached_and_how_far_short() {
5653 let mut srv = server_on(&tone_asset());
5654 let r = run_normalize(&mut srv, &json!({ "target": "A1", "lufs": -8, "true_peak": -15 }));
5655 assert!(!r.is_error, "{}", r.text);
5656 // The gain went on, so the headline says what it did, not "did not reach" as if nothing moved.
5657 assert!(r.text.starts_with("short of the target: A1 raised "), "{}", r.text);
5658 assert!(!r.text.contains("did not reach"), "{}", r.text);
5659 assert!(r.text.contains(" dB to -") && r.text.contains(" LUFS, "), "{}", r.text);
5660 assert!(r.text.contains(" LU short, held by the true-peak ceiling -15.0 dBTP"), "{}", r.text);
5661 assert_eq!(srv.ledger.len(), 1, "a lane that is held still changes: {}", r.text);
5662 assert!(r.text.contains("· undo step 1"), "{}", r.text);
5663
5664 // A dry run changes nothing, so it keeps the "did not reach" headline.
5665 let mut dry_srv = server_on(&tone_asset());
5666 let dry = run_normalize(&mut dry_srv, &json!({ "target": "A1", "lufs": -8, "true_peak": -15, "dry_run": true }));
5667 assert!(dry.text.starts_with("short of the target: dry run — A1 would not reach -8.0: got "), "{}", dry.text);
5668 assert!(dry.text.contains("· nothing changed"), "{}", dry.text);
5669 assert_eq!(dry_srv.ledger.len(), 0, "{}", dry.text);
5670 }
5671
5672 #[test]
5673 fn cut_spans_keep_the_total_pause_at_keep_or_twice_the_padding() {
5674 // A quiet run of 31 frames at 30 fps with 0.15 s (5 frames) of padding each side: the
5675 // region is 21 frames inside. Keep 0.4 s (12 frames) is the whole pause, padding included,
5676 // so 2 frames of the region stay and 19 go: 5 + 1 + 1 + 5 = 12 frames of quiet left.
5677 let spans = cut_spans_for(&[(100, 121)], 0.4, 0.15, 30.0, &[]);
5678 assert_eq!(spans, vec![(101, 19)], "{spans:?}");
5679 // Keep under twice the padding: the paddings are all that can stay, so the region goes whole.
5680 assert_eq!(cut_spans_for(&[(100, 121)], 0.1, 0.15, 30.0, &[]), vec![(100, 21)]);
5681 // A silence whose quiet is at or under keep is left alone (the quiet is 31 frames).
5682 assert!(cut_spans_for(&[(100, 121)], 1.1, 0.15, 30.0, &[]).is_empty());
5683 assert!(cut_spans_for(&[(100, 121)], 1.5, 0.15, 30.0, &[]).is_empty());
5684 }
5685
5686 #[test]
5687 fn cut_spans_keep_the_tail_at_keep_in_all() {
5688 // The region runs to the clip's end at 126: the 5 frames of padding after it stay, and the
5689 // kept part follows the speech before it. 5 + 7 + 5 = 12 frames, which is keep 0.4 s.
5690 let spans = cut_spans_for(&[(100, 121)], 0.4, 0.15, 30.0, &[126]);
5691 assert_eq!(spans, vec![(102, 19)], "{spans:?}");
5692 let left = 5 + (102 - 100) + (126 - 121);
5693 assert_eq!(left, 12);
5694 }
5695
5696 #[test]
5697 fn a_cut_never_reaches_speech_on_either_side() {
5698 // Speech is loud at both sides of each silence: the padding never cut means no frame of it is.
5699 let wav = tone_wav();
5700 let mut srv = server_for(&wav);
5701 let loud_before = loud_windows(&srv);
5702 let r = run_cut_silence(&mut srv, &json!({ "target": "A1", "keep": 0.05, "force": true }));
5703 assert!(!r.is_error, "{}", r.text);
5704 let loud_after = loud_windows(&srv);
5705 assert!(loud_after.abs_diff(loud_before) <= 3, "tone windows {loud_before} before, {loud_after} after: {}", r.text);
5706 }
5707
5708 /// A timeline with V1+A1 as one linked take (test_av.mp4) and picture-only B-roll on V2.
5709 fn linked_av_with_broll() -> Server {
5710 engine::ao::set_silent_output();
5711 let p = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets/test_av.mp4");
5712 let sess = PlaybackSession::open(p).expect("open test asset");
5713 let mut srv = Server { session: Some(sess), ..Server::default() };
5714 let tool = crate::server::tools().into_iter().find(|t| t.name == "edit").expect("edit");
5715 let r = (tool.run)(
5716 &mut srv,
5717 &json!({"ops": [{"op": "lane_add", "kind": "video"}, {"op": "place", "source": 0, "at": "0f", "lane": "V2", "audio": false}]}),
5718 );
5719 assert!(!r.is_error, "{}", r.text);
5720 srv
5721 }
5722
5723 #[test]
5724 fn cut_silence_defaults_to_the_voice_and_its_linked_picture() {
5725 let srv = linked_av_with_broll();
5726 let s = srv.session.as_ref().unwrap();
5727 let voice = default_cut_scope(s, &Target::Lane(Lane::A1));
5728 assert!(voice.contains(&Lane::V1) && voice.contains(&Lane::A1), "{voice:?}");
5729 assert!(!voice.contains(&parse::lane("V2").unwrap()), "B-roll is not linked to the voice: {voice:?}");
5730 assert_eq!(default_cut_scope(s, &Target::Lane(parse::lane("V2").unwrap())), vec![parse::lane("V2").unwrap()]);
5731 assert_eq!(default_cut_scope(s, &Target::Mix), s.lanes());
5732 }
5733
5734 #[test]
5735 fn cut_silence_on_the_default_lane_names_the_other_sound_lanes() {
5736 // A1 (the default target) holds a steady tone with no pause; A2 holds bursts with pauses.
5737 // The reply says what it scanned, and points at A2 where the pauses are.
5738 let steady = wav_of(3, |t| 0.3 * (2.0 * std::f64::consts::PI * 440.0 * t).sin());
5739 let bursts = bursts_wav();
5740 let mut srv = server_for(&steady);
5741 {
5742 let s = srv.session.as_mut().expect("session");
5743 let a2 = s.add_lane(LaneKind::Audio);
5744 s.import(&bursts.path).expect("import the bursts");
5745 s.place_stream_at(0.0, &bursts.path, 0, Some(a2)).expect("place the bursts on A2");
5746 }
5747 let r = run_cut_silence(&mut srv, &json!({}));
5748 assert!(!r.is_error, "{}", r.text);
5749 assert!(r.text.contains("scanned A1 only, the default target; A2 also holds sound: target A2 to cut its pauses"), "{}", r.text);
5750 // Given a target, the reply does not second-guess the choice.
5751 let explicit = run_cut_silence(&mut srv, &json!({ "target": "A1" }));
5752 assert!(!explicit.text.contains("also holds sound"), "{}", explicit.text);
5753 }
5754
5755 /// A mix with an offline source is refused by name, with the fix, before any render.
5756 #[test]
5757 fn a_mix_with_an_offline_source_is_refused_by_name() {
5758 let td = crate::testutil::TestDir::new("hear-offline-mix");
5759 let gone = td.path().join("gone.mp4");
5760 std::fs::copy(Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets/test_25fps.mp4"), &gone).expect("copy");
5761 let project = td.path().join("offline.edith");
5762 let call = |server: &mut Server, name: &str, args: Value| {
5763 let t = crate::server::tools().into_iter().find(|t| t.name == name).expect("tool");
5764 (t.run)(server, &args)
5765 };
5766 let mut server = Server::new();
5767 assert!(!call(&mut server, "project_new", json!({"path": project, "resolution": "1280x720"})).is_error);
5768 assert!(!call(&mut server, "media_import", json!({"paths": [gone]})).is_error);
5769 assert!(!call(&mut server, "edit", json!({"ops": [{"op": "place", "source": "src:0", "lane": "V1", "at": "0s"}]})).is_error);
5770 assert!(!call(&mut server, "project_save", json!({})).is_error);
5771 std::fs::remove_file(&gone).expect("remove");
5772
5773 let mut opened = Server::new();
5774 assert!(!call(&mut opened, "project_open", json!({"path": project})).is_error);
5775 let r = call(&mut opened, "levels", json!({"target": "mix"}));
5776 assert!(r.is_error, "{}", r.text);
5777 assert!(r.text.starts_with("rendering the mix refused: 1 source(s) offline"), "{}", r.text);
5778 assert!(r.text.contains("src:0") && r.text.contains("media_relink"), "{}", r.text);
5779 assert!(!r.text.contains("No such file"), "{}", r.text);
5780 }
5781
5782 /// The bursts on A1 and A2, each the first 3 s only, and the whole bursts on A3, which the
5783 /// joint cuts do not list. A1 and A2 end at 3 s; A3 runs to 13 s.
5784 fn short_joint_server(wav: &TestWav) -> Server {
5785 let mut srv = server_for(wav);
5786 let made = crate::tools::edit::run_edit(
5787 &mut srv,
5788 &json!({"ops": [
5789 {"op": "delete", "clip": "A1#0"},
5790 {"op": "lane_add", "kind": "audio"},
5791 {"op": "lane_add", "kind": "audio"},
5792 {"op": "place", "source": 0, "lane": "A1", "at": "0s", "in": "0s", "out": "3s"},
5793 {"op": "place", "source": 0, "lane": "A2", "at": "0s", "in": "0s", "out": "3s"},
5794 {"op": "place", "source": 0, "lane": "A3", "at": "0s"},
5795 ]}),
5796 );
5797 assert!(!made.is_error, "{}", made.text);
5798 srv
5799 }
5800
5801 #[test]
5802 fn a_joint_silence_is_where_every_listed_lane_is_quiet_and_no_stretch_without_a_clip() {
5803 let wav = bursts_wav();
5804 let srv = short_joint_server(&wav);
5805 let s = srv.session.as_ref().unwrap();
5806 let fps = parse::session_fps(s);
5807 let (a1, a2) = (parse::lane("A1").unwrap(), parse::lane("A2").unwrap());
5808 let cfg = Settings { threshold_db: -40.0, min_silence: 0.0, padding: 0.0, min_keep: 0.0 };
5809 let found = find_joint(s, &[(a1, -40.0), (a2, -40.0)], cfg).expect("joint silence");
5810 // Both lanes play the tone 0..1 s and go quiet 1..2.2 s, so the joint silence is that
5811 // stretch. Past 3 s no listed lane has a clip, so nothing there is silence to cut.
5812 assert_eq!(found.regions.len(), 1, "{:?}", found.regions);
5813 let (a, b) = found.regions[0];
5814 assert!((parse::secs(a, fps) - 1.0).abs() < 0.05, "starts at {:.3} s", parse::secs(a, fps));
5815 assert!((parse::secs(b, fps) - 2.2).abs() < 0.05, "ends at {:.3} s", parse::secs(b, fps));
5816 }
5817
5818 #[test]
5819 fn a_joint_cut_moves_the_listed_lanes_together_and_leaves_the_unlisted_lane() {
5820 let wav = bursts_wav();
5821 let mut srv = short_joint_server(&wav);
5822 let (a1, a2, a3) = (
5823 parse::lane("A1").unwrap(),
5824 parse::lane("A2").unwrap(),
5825 parse::lane("A3").unwrap(),
5826 );
5827 let before_a3 = lane_end(srv.session.as_ref().unwrap(), a3);
5828 let before_a1 = lane_end(srv.session.as_ref().unwrap(), a1);
5829 let r = run_cut_silence(&mut srv, &json!({ "lanes": ["A1", "A2"], "keep": 0.4 }));
5830 assert!(!r.is_error, "{}", r.text);
5831 assert!(r.text.contains("(joint)"), "{}", r.text);
5832 let s = srv.session.as_ref().unwrap();
5833 // The cut is the same on both listed lanes, so their ends agree and both shrink.
5834 assert_eq!(lane_end(s, a1), lane_end(s, a2), "the listed lanes stay in step: {}", r.text);
5835 assert!(lane_end(s, a1) < before_a1, "the joint silence is cut: {}", r.text);
5836 // A3 is not listed, so it never moves: its clip is whole and it keeps its end.
5837 assert_eq!(lane_end(s, a3), before_a3, "an unlisted lane moved: {}", r.text);
5838 // Its clip runs through the cut, so the reply names it as out of step.
5839 assert!(r.text.contains("out of step, not cut: A3@0"), "{}", r.text);
5840 assert_eq!(r.structured.as_ref().unwrap()["out_of_step"], json!(["A3@0"]));
5841 let pauses = r.structured.as_ref().unwrap()["pauses_measured_s"].as_array().expect("pauses").clone();
5842 assert_eq!(pauses.len(), 1, "{}", r.text);
5843 let p = pauses[0].as_f64().unwrap();
5844 assert!((p - 0.4).abs() < 0.05, "joint pause {p} s, want 0.40 s: {}", r.text);
5845 }
5846
5847 /// A cut that leaves the timeline as long as it was, or shorter, says which lane holds its end:
5848 /// the bed on A3, which the cut does not list, still runs to the end. Dry run and real cut say
5849 /// the same.
5850 #[test]
5851 fn a_cut_that_leaves_the_timeline_long_names_the_lane_holding_it() {
5852 let wav = bursts_wav();
5853 for dry in [true, false] {
5854 let mut srv = short_joint_server(&wav);
5855 let r = run_cut_silence(&mut srv, &json!({ "lanes": ["A1", "A2"], "keep": 0.4, "dry_run": dry }));
5856 assert!(!r.is_error, "{}", r.text);
5857 assert!(
5858 r.text.contains("A3 runs ") && r.text.contains(" past the cut lanes (they end at "),
5859 "dry {dry}: {}",
5860 r.text
5861 );
5862 }
5863 }
5864
5865 /// A cut that shortens the timeline with no uncut lane holding its end gets no such note.
5866 #[test]
5867 fn a_cut_that_shortens_the_timeline_has_no_timeline_stays_note() {
5868 let wav = tone_wav();
5869 let mut srv = server_for(&wav);
5870 let r = run_cut_silence(&mut srv, &json!({ "target": "A1" }));
5871 assert!(!r.is_error, "{}", r.text);
5872 assert!(!r.text.contains("timeline stays"), "{}", r.text);
5873 }
5874
5875 #[test]
5876 fn a_joint_cut_with_a_video_lane_judges_only_the_audio_lanes() {
5877 let mut srv = linked_av_with_broll();
5878 // One audio lane and a video lane is no joint cut: the reply says what it needs.
5879 for lanes in [json!(["A1", "V1"]), json!(["V1", "V2"])] {
5880 let r = run_cut_silence(&mut srv, &json!({ "lanes": lanes, "dry_run": true }));
5881 assert!(r.is_error && r.text.contains("two or more audio lanes"), "{}", r.text);
5882 }
5883 }
5884
5885 #[test]
5886 fn a_target_with_lanes_is_the_ripple_scope_and_judges_the_target_alone() {
5887 let wav = bursts_wav();
5888 for dry in [true, false] {
5889 let mut srv = short_joint_server(&wav);
5890 let a1 = parse::lane("A1").unwrap();
5891 let a2 = parse::lane("A2").unwrap();
5892 let before = lane_end(srv.session.as_ref().unwrap(), a1);
5893 let r = run_cut_silence(&mut srv, &json!({ "target": "A1", "lanes": ["A1", "A2"], "keep": 0.4, "dry_run": dry }));
5894 assert!(!r.is_error, "dry {dry}: {}", r.text);
5895 assert!(!r.text.contains("(joint)"), "{}", r.text);
5896 assert_eq!(r.structured.as_ref().unwrap()["lanes"], json!(["A1", "A2"]), "{}", r.text);
5897 let s = srv.session.as_ref().unwrap();
5898 if dry {
5899 assert_eq!(lane_end(s, a1), before, "a dry run cut");
5900 } else {
5901 // The spans found on A1 are cut on A2 too, so both lanes shrink and stay in step.
5902 assert!(lane_end(s, a1) < before, "{}", r.text);
5903 assert_eq!(lane_end(s, a1), lane_end(s, a2), "the lanes stay in step: {}", r.text);
5904 }
5905 }
5906 }
5907
5908 #[test]
5909 fn a_target_with_lanes_adds_the_target_lane_when_it_is_not_listed() {
5910 let wav = bursts_wav();
5911 let mut srv = short_joint_server(&wav);
5912 let r = run_cut_silence(&mut srv, &json!({ "target": "A1", "lanes": ["A2"], "keep": 0.4, "dry_run": true }));
5913 assert!(!r.is_error, "{}", r.text);
5914 assert_eq!(r.structured.as_ref().unwrap()["lanes"], json!(["A1", "A2"]), "{}", r.text);
5915 assert!(r.text.contains("A1 is the target, so it is cut with the listed lanes"), "{}", r.text);
5916 }
5917
5918 #[test]
5919 fn a_target_with_lanes_cuts_the_video_lanes_at_the_same_spans() {
5920 // test_av has 0.16 to 0.19 s pauses on A1, which a 0.1 s minimum finds. V1 is the linked
5921 // picture, V2 the B-roll: both shrink by exactly what A1 loses, so they stay in step.
5922 let mut srv = linked_av_with_broll();
5923 let (a1, v1, v2) = (parse::lane("A1").unwrap(), parse::lane("V1").unwrap(), parse::lane("V2").unwrap());
5924 let before = [a1, v1, v2].map(|l| lane_end(srv.session.as_ref().unwrap(), l));
5925 let r = run_cut_silence(
5926 &mut srv,
5927 &json!({ "target": "A1", "lanes": ["A1", "V1", "V2"], "threshold_db": -40, "min_silence": 0.1, "padding": 0.02, "keep": 0.1 }),
5928 );
5929 assert!(!r.is_error, "{}", r.text);
5930 assert!(r.structured.as_ref().unwrap()["cut_count"].as_u64().unwrap_or(0) >= 1, "{}", r.text);
5931 let s = srv.session.as_ref().unwrap();
5932 let after = [a1, v1, v2].map(|l| lane_end(s, l));
5933 let cut = before[0] - after[0];
5934 assert!(cut > 0, "A1 was not cut: {}", r.text);
5935 assert_eq!(before[1] - after[1], cut, "V1 cut at other spans: {}", r.text);
5936 assert_eq!(before[2] - after[2], cut, "V2 cut at other spans: {}", r.text);
5937 assert_eq!(after[0], after[1], "V1 and A1 stay in step: {}", r.text);
5938 }
5939
5940 #[test]
5941 fn a_pause_shorter_than_min_silence_says_so_and_names_the_longest_quiet() {
5942 // Tone, a 0.4 s pause of digital silence, tone: the default min_silence (0.5 s) keeps it out.
5943 let wav = wav_of(3, |t| {
5944 if (1.0..1.4).contains(&t) {
5945 0.0
5946 } else {
5947 0.3 * (2.0 * std::f64::consts::PI * 440.0 * t).sin()
5948 }
5949 });
5950 let mut srv = server_for(&wav);
5951 let r = run_cut_silence(&mut srv, &json!({ "target": "A1" }));
5952 assert!(!r.is_error, "{}", r.text);
5953 assert!(r.text.starts_with("no pause of 0.50 s or longer (min_silence) under "), "{}", r.text);
5954 assert!(r.text.contains(" dBFS on A1; the longest quiet was 0.4"), "{}", r.text);
5955 assert!(r.text.contains("lower min_silence to cut shorter pauses"), "{}", r.text);
5956 assert_eq!(r.structured.as_ref().unwrap()["count"], 0, "{}", r.text);
5957 }
5958
5959 #[test]
5960 fn no_pause_note_names_the_rule_that_kept_the_quiet_out() {
5961 let short = no_pause_note("A1", "-40.0 dBFS", 0.5, 0.15, 0.42);
5962 assert_eq!(
5963 short,
5964 "no pause of 0.50 s or longer (min_silence) under -40.0 dBFS on A1; the longest quiet was 0.42 s — lower min_silence to cut shorter pauses; nothing cut"
5965 );
5966 let padded = no_pause_note("A1", "-40.0 dBFS", 0.5, 0.3, 0.6);
5967 assert!(padded.contains("the longest quiet under -40.0 dBFS on A1 was 0.60 s") && padded.contains("lower padding"), "{padded}");
5968 assert_eq!(no_pause_note("A1", "-40.0 dBFS", 0.5, 0.15, 0.0), "no quiet under -40.0 dBFS on A1; nothing cut");
5969 }
5970
5971 #[test]
5972 fn cut_silence_keep_is_the_total_pause_and_the_reply_says_what_is_left() {
5973 let wav = bursts_wav();
5974 let mut srv = server_for(&wav);
5975 let fps = fps_of(&srv);
5976 let r = run_cut_silence(&mut srv, &json!({ "target": "A1", "keep": 0.4 }));
5977 assert!(!r.is_error, "{}", r.text);
5978 // Padding is inside keep, so the pauses measure keep, not keep plus the padding. The
5979 // measure is read in 20 ms windows, so each may run a frame over keep at most.
5980 assert!(r.text.contains("pauses now 0.4"), "{}", r.text);
5981 let pauses = r.structured.as_ref().unwrap()["pauses_measured_s"].as_array().expect("pauses").clone();
5982 assert!(pauses.len() >= 4, "{}", r.text);
5983 for p in pauses {
5984 let p = p.as_f64().unwrap();
5985 assert!((0.4 - 0.01..=0.4 + 1.0 / fps + 0.01).contains(&p), "pause {p} s, want 0.40 s: {}", r.text);
5986 }
5987 }
5988
5989 #[test]
5990 fn a_level_within_a_tenth_of_a_lu_is_reached_on_the_unrounded_value() {
5991 // -14.1 reads one decimal; the check is on the value, so 0.1 LU off is reached.
5992 assert!(lufs_reached(-14.0, -14.1));
5993 assert!(lufs_reached(-14.0, -13.9));
5994 assert!(!lufs_reached(-14.0, -14.11));
5995 assert!(!lufs_reached(-14.0, f64::NAN));
5996 assert!(!lufs_reached(-14.0, f64::NEG_INFINITY));
5997 }
5998
5999 /// Locks the lane `name` (or unlocks it) through edit, as a person would with lane_flags.
6000 fn set_locked(srv: &mut Server, name: &str, locked: bool) {
6001 let made = crate::tools::edit::run_edit(
6002 srv,
6003 &json!({"ops": [{"op": "lane_flags", "lane": name, "locked": locked}]}),
6004 );
6005 assert!(!made.is_error, "{}", made.text);
6006 }
6007
6008 #[test]
6009 fn cut_silence_refuses_a_locked_target_with_the_way_out() {
6010 let wav = tone_wav();
6011 let mut srv = gapped_lane(&wav);
6012 set_locked(&mut srv, "A1", true);
6013 let before = parse::session_end(srv.session.as_ref().unwrap());
6014 for dry in [false, true] {
6015 let r = run_cut_silence(&mut srv, &json!({ "target": "A1", "dry_run": dry }));
6016 assert!(r.is_error, "a locked target cut: {}", r.text);
6017 assert!(r.text.contains("lane A1 is locked") && r.text.contains("lane_flags"), "{}", r.text);
6018 }
6019 assert_eq!(parse::session_end(srv.session.as_ref().unwrap()), before, "a refused cut changes nothing");
6020 // Unlocked, the same cut goes through.
6021 set_locked(&mut srv, "A1", false);
6022 let r = run_cut_silence(&mut srv, &json!({ "target": "A1" }));
6023 assert!(!r.is_error, "{}", r.text);
6024 }
6025
6026 #[test]
6027 fn cut_silence_refuses_a_locked_lane_named_in_lanes() {
6028 let wav = bursts_wav();
6029 let mut srv = bursts_on_two_lanes(&wav);
6030 set_locked(&mut srv, "A3", true);
6031 let r = run_cut_silence(&mut srv, &json!({ "target": "A2", "lanes": ["A2", "A3"], "dry_run": true }));
6032 assert!(r.is_error, "a named locked lane was cut: {}", r.text);
6033 assert!(r.text.contains("lane A3 is locked") && r.text.contains("lane_flags"), "{}", r.text);
6034 // A joint cut names its lanes too, so a locked one refuses it the same way.
6035 let j = run_cut_silence(&mut srv, &json!({ "lanes": ["A2", "A3"], "keep": 0.25 }));
6036 assert!(j.is_error && j.text.contains("lane A3 is locked"), "{}", j.text);
6037 }
6038
6039 #[test]
6040 fn cut_silence_mix_refuses_over_a_locked_lane_and_changes_nothing() {
6041 let wav = bursts_wav();
6042 let mut srv = bursts_on_two_lanes(&wav);
6043 set_locked(&mut srv, "A3", true);
6044 let a2 = parse::lane("A2").unwrap();
6045 let a3 = parse::lane("A3").unwrap();
6046 let a2_before = srv.session.as_ref().unwrap().lane_clips(a2).to_vec();
6047 let a3_before = srv.session.as_ref().unwrap().lane_clips(a3).to_vec();
6048 let end_before = parse::session_end(srv.session.as_ref().unwrap());
6049 let ledger_before = srv.ledger.len();
6050 let r = run_cut_silence(&mut srv, &json!({ "target": "mix", "keep": 0.25 }));
6051 assert!(r.is_error, "a mix cut over a locked lane ran: {}", r.text);
6052 assert!(r.text.contains("lane A3 is locked") && r.text.contains("lane_flags"), "{}", r.text);
6053 assert!(r.text.contains("nothing changed"), "{}", r.text);
6054 let s = srv.session.as_ref().unwrap();
6055 assert_eq!(s.lane_clips(a2), a2_before.as_slice(), "the unlocked lane moved");
6056 assert_eq!(s.lane_clips(a3), a3_before.as_slice(), "the locked lane moved");
6057 assert_eq!(parse::session_end(s), end_before, "the timeline changed");
6058 assert_eq!(srv.ledger.len(), ledger_before, "a refused cut left an undo step");
6059 }
6060
6061 /// The dry run and the real run name the same lanes, in the same words.
6062 #[test]
6063 fn cut_silence_dry_run_and_real_run_name_the_same_lanes() {
6064 let wav = bursts_wav();
6065 let mut srv = bursts_on_two_lanes(&wav);
6066 let dry = run_cut_silence(&mut srv, &json!({ "target": "mix", "keep": 0.25, "dry_run": true }));
6067 assert!(!dry.is_error, "{}", dry.text);
6068 let names: Vec<String> = dry.structured.as_ref().unwrap()["lanes"]
6069 .as_array()
6070 .unwrap()
6071 .iter()
6072 .map(|v| v.as_str().unwrap().to_string())
6073 .collect();
6074 let named = format!("({})", names.join("+"));
6075 assert!(dry.text.contains(&named), "the dry run hides its lanes: {}", dry.text);
6076 let real = run_cut_silence(&mut srv, &json!({ "target": "mix", "keep": 0.25 }));
6077 assert!(!real.is_error, "{}", real.text);
6078 assert!(real.text.contains(&named), "the real run hides its lanes: {}", real.text);
6079 }
6080
6081 /// The listed spans are the ones removed: their lengths sum to what the timeline lost.
6082 #[test]
6083 fn cut_silence_lists_the_spans_it_removes() {
6084 let wav = bursts_wav();
6085 let mut srv = server_for(&wav);
6086 let r = run_cut_silence(&mut srv, &json!({ "target": "A1", "keep": 0.25 }));
6087 assert!(!r.is_error, "{}", r.text);
6088 let st = r.structured.as_ref().unwrap();
6089 let listed: u32 = st["regions"]
6090 .as_array()
6091 .unwrap()
6092 .iter()
6093 .map(|p| {
6094 let (a, b) = frames_of(&json!([p]));
6095 b - a
6096 })
6097 .sum();
6098 assert!(listed > 0, "nothing was cut: {}", r.text);
6099 assert_eq!(listed, st["removed_frames"].as_u64().unwrap() as u32, "the listed spans differ from the removal: {}", r.text);
6100 }
6101
6102 /// A cut on A2 alone leaves A3, which runs past the new end of A2: the reply names A3, how far
6103 /// past it runs, and the trim that brings it to the end.
6104 #[test]
6105 fn cut_silence_names_an_unlisted_lane_that_runs_past_the_cut_lanes() {
6106 let wav = bursts_wav();
6107 let mut srv = bursts_on_two_lanes(&wav);
6108 let r = run_cut_silence(&mut srv, &json!({ "target": "A2", "lanes": ["A2"], "keep": 0.25 }));
6109 assert!(!r.is_error, "{}", r.text);
6110 assert!(r.text.contains("A3 runs ") && r.text.contains(" s past the cut lanes"), "{}", r.text);
6111 assert!(r.text.contains("trim {clip:\"A3@") && r.text.contains("edge:\"out\""), "{}", r.text);
6112 }
6113
6114 /// A cut that leaves no lane outside it past its end says nothing about the lanes it skipped.
6115 #[test]
6116 fn cut_silence_with_no_lane_past_the_cut_names_none() {
6117 let wav = bursts_wav();
6118 let mut srv = bursts_on_two_lanes(&wav);
6119 let r = run_cut_silence(&mut srv, &json!({ "target": "mix", "keep": 0.25 }));
6120 assert!(!r.is_error, "{}", r.text);
6121 assert!(!r.text.contains("past the cut lanes"), "{}", r.text);
6122 }
6123
6124 #[test]
6125 fn cut_silence_joint_cut_runs_once_the_locked_lane_is_unlocked() {
6126 let wav = bursts_wav();
6127 let mut srv = bursts_on_two_lanes(&wav);
6128 set_locked(&mut srv, "A3", true);
6129 set_locked(&mut srv, "A3", false);
6130 let r = run_cut_silence(&mut srv, &json!({ "lanes": ["A2", "A3"], "keep": 0.25 }));
6131 assert!(!r.is_error, "{}", r.text);
6132 assert!(!r.text.contains("skipped locked"), "{}", r.text);
6133 }
6134
6135 /// The tone with a silence from 1 s to 2 s, and captions placed on S1 over it: "first line"
6136 /// 0.5 s to 1.5 s, "second line" 2 s to 3.25 s, "third line" 4 s to 4.75 s.
6137 fn captioned_tone(wav: &TestWav) -> Server {
6138 let mut srv = server_for(wav);
6139 let srt = Path::new(env!("CARGO_MANIFEST_DIR")).join("../engine/tests/data/test_subs.srt");
6140 let made = crate::tools::edit::run_edit(
6141 &mut srv,
6142 &json!({"ops": [
6143 {"op": "subtitles_import", "path": srt.display().to_string()},
6144 {"op": "captions_place", "track": 0}
6145 ]}),
6146 );
6147 assert!(!made.is_error, "{}", made.text);
6148 srv
6149 }
6150
6151 /// The caption cues on S1 as (text, start in microseconds).
6152 fn cue_starts(srv: &Server) -> Vec<(String, i64)> {
6153 let s = srv.session.as_ref().unwrap();
6154 s.sub_lane_cues(parse::lane("S1").unwrap()).into_iter().map(|c| (c.text, c.start_us)).collect()
6155 }
6156
6157 fn start_of(cues: &[(String, i64)], text: &str) -> i64 {
6158 cues.iter().find(|c| c.0 == text).unwrap_or_else(|| panic!("no cue {text:?} in {cues:?}")).1
6159 }
6160
6161 /// Captions ride a silence cut as cut_regions moves them: the cue after the cut moves back by
6162 /// the time the cut removed, and the reply names the moved cues. The picture is cut too.
6163 #[test]
6164 fn cut_silence_moves_the_captions_with_the_cut() {
6165 let wav = tone_wav();
6166 let mut srv = captioned_tone(&wav);
6167 let a1 = parse::lane("A1").unwrap();
6168 let fps = fps_of(&srv);
6169 let media = |srv: &Server| super::super::listen::media_end(srv.session.as_ref().unwrap(), &[a1]);
6170 let (m0, c0) = (media(&srv), cue_starts(&srv));
6171 let r = run_cut_silence(&mut srv, &json!({ "target": "A1" }));
6172 assert!(!r.is_error, "{}", r.text);
6173 let removed = m0 - media(&srv);
6174 assert!(removed > 0, "the silence is cut: {}", r.text);
6175 let c1 = cue_starts(&srv);
6176 let shift = f64::from(removed) / fps * 1e6;
6177 let frame_us = 1e6 / fps;
6178 let moved = (start_of(&c0, "third line") - start_of(&c1, "third line")) as f64;
6179 assert!((moved - shift).abs() <= frame_us, "third line moved {moved} us, the cut removed {shift} us: {}", r.text);
6180 assert!(r.text.contains("captions followed the cut"), "{}", r.text);
6181 // The timeline is as long as its captions here: the picture is shorter than "third line" runs.
6182 assert!(r.text.contains("captions run to"), "{}", r.text);
6183 // A dry run predicts the same captions and keeps them.
6184 let mut dry = captioned_tone(&wav);
6185 let d = run_cut_silence(&mut dry, &json!({ "target": "A1", "dry_run": true }));
6186 assert!(d.text.contains("captions followed the cut"), "{}", d.text);
6187 assert_eq!(cue_starts(&dry), c0, "a dry run keeps the captions");
6188 }
6189
6190 /// A caption lane named in `lanes` is a valid ripple scope: the cut is made with it, and its
6191 /// cues move the same as they do on their own.
6192 #[test]
6193 fn cut_silence_accepts_a_caption_lane_in_lanes() {
6194 let wav = tone_wav();
6195 let mut named = captioned_tone(&wav);
6196 let mut own = captioned_tone(&wav);
6197 let r = run_cut_silence(&mut named, &json!({ "target": "A1", "lanes": ["A1", "S1"] }));
6198 assert!(!r.is_error, "{}", r.text);
6199 assert!(!r.text.contains("caption lane"), "{}", r.text);
6200 let o = run_cut_silence(&mut own, &json!({ "target": "A1" }));
6201 assert!(!o.is_error, "{}", o.text);
6202 assert_eq!(cue_starts(&named), cue_starts(&own));
6203 }
6204
6205 /// A locked caption lane is left alone and named; the cut still runs on the rest.
6206 #[test]
6207 fn cut_silence_leaves_a_locked_caption_lane_and_names_it() {
6208 let wav = tone_wav();
6209 let mut srv = captioned_tone(&wav);
6210 let before = cue_starts(&srv);
6211 set_locked(&mut srv, "S1", true);
6212 let r = run_cut_silence(&mut srv, &json!({ "target": "A1" }));
6213 assert!(!r.is_error, "{}", r.text);
6214 assert!(r.text.contains("locked captions S1 stay put"), "{}", r.text);
6215 assert_eq!(cue_starts(&srv), before, "the locked captions do not move");
6216 // Named in lanes, a lock refuses the cut with the way out, as any locked lane does.
6217 let named = run_cut_silence(&mut srv, &json!({ "target": "A1", "lanes": ["A1", "S1"] }));
6218 assert!(named.is_error && named.text.contains("lane_flags"), "{}", named.text);
6219 }
6220
6221 /// A caption wholly inside the silence is removed with it, and the reply names it.
6222 #[test]
6223 fn cut_silence_drops_a_caption_wholly_inside_the_cut() {
6224 let wav = tone_wav();
6225 let td = crate::testutil::TestDir::new("hear-caption-inside");
6226 let srt = td.path().join("inside.srt");
6227 std::fs::write(&srt, "1\n00:00:01.250,000 --> 00:00:01.350,000\ngone words\n\n2\n00:00:02.500,000 --> 00:00:02.900,000\nafter words\n").expect("write srt");
6228 let mut srv = server_for(&wav);
6229 let made = crate::tools::edit::run_edit(
6230 &mut srv,
6231 &json!({"ops": [
6232 {"op": "subtitles_import", "path": srt.display().to_string()},
6233 {"op": "captions_place", "track": 0}
6234 ]}),
6235 );
6236 assert!(!made.is_error, "{}", made.text);
6237 let r = run_cut_silence(&mut srv, &json!({ "target": "A1" }));
6238 assert!(!r.is_error, "{}", r.text);
6239 let texts: Vec<String> = cue_starts(&srv).into_iter().map(|c| c.0).collect();
6240 assert!(!texts.iter().any(|t| t == "gone words"), "{texts:?}");
6241 assert!(texts.iter().any(|t| t == "after words"), "{texts:?}");
6242 assert!(r.text.contains("removed cue 'gone words'"), "{}", r.text);
6243 }
6244}