forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

voice.rs452 lines, 20.9 KiBHistoryRawDownload
1//! Voice cleanup: the `clean_voice` tool (one click: gate, noise reduction, compressor and
2//! de-esser at settings for speech, as one undo step) and the `dynamics` edit op (each
3//! processor on its own). The DSP is `engine::voice`; this is the argument handling, the
4//! noise learning and the replies.
5
6use engine::PlaybackSession;
7use engine::project::{Lane, LaneKind};
8use engine::voice::{Compressor, DeEsser, Gate, Learned, Strength, VoiceFx};
9use serde_json::{Map, Value, json};
10
11use super::edit_fx::Applied;
12use super::hear::record_pushes;
13use crate::parse;
14use crate::server::{Reply, Server, Tool, opt_str};
15
16const NO_PROJECT: &str = "no project open — call project_open or project_new first";
17
18const CLEAN_VOICE_DOC: &str = r#"One-click voice cleanup for an audio lane, as one undo step: a noise gate, spectral noise reduction, a compressor and a de-esser, set for speech. The noise is learned from the lane itself: by default its quietest half second (a pause between words, found automatically), or the noise_from range you name. Replaces the lane's gate, nr, compressor and deesser settings with the preset; fine-tune each afterwards with edit {ops:[{op:"dynamics", lane, ...}]}, take it all off with edit {ops:[{op:"dynamics", lane, reset:true}]} or undo.
19strength: light (gentle: nr 35%, 2:1), medium (default: nr 60%, 3:1) or strong (nr 85%, 4:1, deeper gate). The gate opens a few dB over the learned noise level.
20noise_from {from,to}: a stretch of the lane that holds only the noise (room tone, breath-free pause), in the usual times (450f, 15.0s). Give it when the automatic pick lands on something that is not noise.
21Order of the processors: the clips' equalizer, gate, noise reduction, compressor, de-esser, then the lane's volume, its duck and the master limiter. They run in playback and in every export, and the sound of an export is the sound you hear."#;
22
23pub fn tools() -> Vec<Tool> {
24 vec![Tool { name: "clean_voice", description: CLEAN_VOICE_DOC, schema: clean_voice_schema, run: run_clean_voice }]
25}
26
27fn clean_voice_schema() -> Value {
28 json!({
29 "type": "object",
30 "properties": {
31 "lane": {
32 "type": "string",
33 "description": "The audio lane to clean, such as A1. Default A1."
34 },
35 "strength": {
36 "type": "string", "enum": ["light", "medium", "strong"],
37 "description": "How hard it works. Default medium."
38 },
39 "noise_from": {
40 "type": "object",
41 "description": "A stretch of the lane that holds only noise, from `from` up to but not including `to`. Times take the usual forms: 450f, 15.0s, 00:00:15:00. Default: the quietest half second of the lane, found automatically.",
42 "properties": {
43 "from": { "description": "Start of the stretch." },
44 "to": { "description": "End of the stretch (exclusive)." }
45 },
46 "required": ["from", "to"]
47 }
48 }
49 })
50}
51
52/// `{from, to}` as lane seconds.
53fn range_secs(v: &Value, what: &str, fps: f64, end: u32) -> Result<(f64, f64), String> {
54 let (Some(from), Some(to)) = (v.get("from"), v.get("to")) else {
55 return Err(format!("{what} needs both `from` and `to`, e.g. {{\"from\": \"2s\", \"to\": \"2.6s\"}}"));
56 };
57 let from = parse::frame(from, fps, end).map_err(|e| format!("{what}.from: {e}"))?;
58 let to = parse::frame(to, fps, end).map_err(|e| format!("{what}.to: {e}"))?;
59 if from >= to {
60 return Err(format!("{what}.from must come before {what}.to"));
61 }
62 Ok((f64::from(from) / fps, f64::from(to) / fps))
63}
64
65fn lane_checks(s: &PlaybackSession, lane: Lane, raw: &str, who: &str) -> Result<(), String> {
66 if !s.lanes().contains(&lane) {
67 let names: Vec<String> = s.lanes().into_iter().map(parse::lane_name).collect();
68 return Err(format!("{raw} is not a lane on this timeline; the lanes are {}", names.join(", ")));
69 }
70 if lane.kind != LaneKind::Audio {
71 return Err(format!("{who}: voice cleanup is for audio lanes, and {raw} is not one"));
72 }
73 if s.lane_clips(lane).is_empty() {
74 return Err(format!("{who}: {raw} has no clips to clean"));
75 }
76 super::edit::check_unlocked(s, &[lane])
77}
78
79fn learned_note(l: &Learned, explicit: bool) -> String {
80 let at = if explicit {
81 format!("{:.2}-{:.2} s", l.from.0, l.from.1)
82 } else {
83 format!("the quietest stretch, {:.2}-{:.2} s", l.from.0, l.from.1)
84 };
85 format!("noise learned from {at} ({:.1} dBFS)", l.noise_db)
86}
87
88fn run_clean_voice(srv: &mut Server, args: &Value) -> Reply {
89 let raw = opt_str(args, "lane").unwrap_or("A1");
90 let strength = match opt_str(args, "strength") {
91 None => Strength::Medium,
92 Some(name) => match Strength::from_name(name) {
93 Some(s) => s,
94 None => return Reply::err(format!("strength `{name}` is not one of light, medium, strong")),
95 },
96 };
97 let lane = match parse::lane(raw) {
98 Ok(l) => l,
99 Err(e) => return Reply::err(e),
100 };
101 let Some(s) = srv.session.as_mut() else {
102 return Reply::err(NO_PROJECT);
103 };
104 let who = format!("clean_voice {raw}");
105 if let Err(e) = lane_checks(s, lane, raw, &who) {
106 return Reply::err(e);
107 }
108 let fps = parse::session_fps(s);
109 let end = parse::session_end(s);
110 let explicit = match args.get("noise_from") {
111 None | Some(Value::Null) => None,
112 Some(v) => match range_secs(v, "noise_from", fps, end) {
113 Ok(r) => Some(r),
114 Err(e) => return Reply::err(format!("{who}: {e}")),
115 },
116 };
117 let (learned, nr_note) = match s.learn_noise(lane, explicit) {
118 Ok(l) => {
119 let note = learned_note(&l, explicit.is_some());
120 (Some(l), note)
121 }
122 // Naming a stretch that cannot be learned from is a mistake to report; the automatic pick
123 // finding nothing just means there is no noise to subtract, and the rest still applies.
124 Err(e) if explicit.is_some() => return Reply::err(format!("{who}: {e}")),
125 Err(e) => (None, format!("noise reduction left off: {e}")),
126 };
127 let fx = VoiceFx::clean_voice(
128 strength,
129 learned.as_ref().map(|l| l.profile.clone()).unwrap_or_default(),
130 learned.as_ref().map(|l| l.noise_db),
131 );
132 if s.lane_voice(lane) == fx {
133 return Reply::ok(format!("{who} {}: already set · {}", strength.name(), fx.summary()));
134 }
135 let start = s.history_pushes();
136 if !s.set_lane_voice(lane, fx.clone()) {
137 return Reply::err(format!("{who}: the engine refused it"));
138 }
139 record_pushes(srv, start, format!("clean_voice {raw} {}", strength.name()));
140 let undo = srv.ledger.len();
141 Reply::ok(format!(
142 "cleaned {raw} ({}): {} · {nr_note} · undo step {undo}",
143 strength.name(),
144 fx.summary()
145 ))
146 .with(json!({
147 "lane": raw,
148 "strength": strength.name(),
149 "voice": voice_json(&fx),
150 "noise_db": learned.as_ref().map(|l| l.noise_db),
151 "noise_from": learned.as_ref().map(|l| json!([l.from.0, l.from.1])),
152 "undo_steps": undo,
153 }))
154}
155
156/// The processors as JSON, the profile left out (it is 256 numbers nobody reads).
157pub fn voice_json(fx: &VoiceFx) -> Value {
158 json!({
159 "gate": { "on": fx.gate.on, "threshold_db": fx.gate.threshold_db, "attack_ms": fx.gate.attack_ms,
160 "release_ms": fx.gate.release_ms, "hold_ms": fx.gate.hold_ms, "range_db": fx.gate.range_db },
161 "nr": { "on": fx.nr.on, "strength": fx.nr.strength, "floor_db": fx.nr.floor_db,
162 "profile": !fx.nr.profile.is_empty() },
163 "compressor": { "on": fx.comp.on, "threshold_db": fx.comp.threshold_db, "ratio": fx.comp.ratio,
164 "attack_ms": fx.comp.attack_ms, "release_ms": fx.comp.release_ms,
165 "knee_db": fx.comp.knee_db, "makeup_db": fx.comp.makeup(),
166 "auto_makeup": fx.comp.auto_makeup },
167 "deesser": { "on": fx.deess.on, "threshold_db": fx.deess.threshold_db, "amount": fx.deess.amount,
168 "lo_hz": fx.deess.lo_hz, "hi_hz": fx.deess.hi_hz },
169 })
170}
171
172// ---- the dynamics op ---------------------------------------------------------------
173
174/// How one processor was addressed: `false` bypasses it, `true` switches it on as it is, an
175/// object sets numbers (and switches it on unless it says `on:false`).
176struct Addressed<'a> {
177 on: bool,
178 nums: Option<&'a Map<String, Value>>,
179}
180
181fn addressed<'a>(op: &'a Value, key: &str) -> Result<Option<Addressed<'a>>, String> {
182 match op.get(key) {
183 None | Some(Value::Null) => Ok(None),
184 Some(Value::Bool(b)) => Ok(Some(Addressed { on: *b, nums: None })),
185 Some(Value::Object(m)) => {
186 let on = match m.get("on") {
187 None | Some(Value::Null) => true,
188 Some(Value::Bool(b)) => *b,
189 Some(_) => return Err(format!("dynamics: {key}.on must be true or false")),
190 };
191 Ok(Some(Addressed { on, nums: Some(m) }))
192 }
193 Some(_) => Err(format!("dynamics: {key} must be true, false or an object of settings")),
194 }
195}
196
197fn check_keys(key: &str, m: &Map<String, Value>, allowed: &[&str]) -> Result<(), String> {
198 match m.keys().find(|k| *k != "on" && !allowed.contains(&k.as_str())) {
199 Some(k) => Err(format!("dynamics: {key} has no `{k}`; it takes on, {}", allowed.join(", "))),
200 None => Ok(()),
201 }
202}
203
204fn number(who: &str, m: Option<&Map<String, Value>>, k: &str, cur: f32, lo: f32, hi: f32) -> Result<f32, String> {
205 let Some(v) = m.and_then(|m| m.get(k)).filter(|v| !v.is_null()) else {
206 return Ok(cur);
207 };
208 let x = v.as_f64().filter(|x| x.is_finite()).ok_or_else(|| format!("{who}: {k} must be a number"))?;
209 if x < f64::from(lo) || x > f64::from(hi) {
210 return Err(format!("{who}: {k} {x} out of range {lo}–{hi}"));
211 }
212 Ok(x as f32)
213}
214
215fn boolean(who: &str, m: Option<&Map<String, Value>>, k: &str) -> Result<Option<bool>, String> {
216 match m.and_then(|m| m.get(k)) {
217 None | Some(Value::Null) => Ok(None),
218 Some(Value::Bool(b)) => Ok(Some(*b)),
219 Some(_) => Err(format!("{who}: {k} must be true or false")),
220 }
221}
222
223/// `dynamics {lane, gate?, nr?, compressor?, deesser?, reset?}`: sets the voice processors of an
224/// audio lane one by one; what an op does not name stays as it was. Each processor takes `false`
225/// (bypass, keeping its settings), `true` (on as it is) or an object of numbers (on, unless it
226/// says `on:false`):
227///
228/// * `gate {threshold_db -90..0, attack_ms, release_ms, hold_ms, range_db -90..0}`
229/// * `nr {strength 0..1, floor_db -60..0, from?: {from,to}, learn?}` -- switching it on learns the
230/// noise profile from the quietest half second of the lane, or from `from`; `learn:true` learns
231/// it again; a profile already there is kept otherwise
232/// * `compressor {threshold_db -60..0, ratio 1..20, attack_ms, release_ms, knee_db 0..30, makeup_db
233/// -12..24, auto_makeup}` -- a makeup_db without auto_makeup switches automatic makeup off
234/// * `deesser {threshold_db -60..0, amount 0..1, lo_hz, hi_hz}`
235///
236/// `reset:true` takes every processor off and back to its defaults.
237pub fn dynamics(s: &mut PlaybackSession, op: &Value, fps: f64) -> Result<Applied, String> {
238 let raw = op.get("lane").and_then(Value::as_str).ok_or("dynamics: missing `lane`, an audio lane such as \"A1\"")?;
239 let lane = parse::lane(raw)?;
240 let who = format!("dynamics {raw}");
241 lane_checks(s, lane, raw, &who)?;
242 let before = s.lane_voice(lane);
243 let mut fx = before.clone();
244 let reset = matches!(op.get("reset"), Some(Value::Bool(true)));
245 if reset {
246 fx = VoiceFx::default();
247 }
248 let mut notes = Vec::new();
249
250 if let Some(a) = addressed(op, "gate")? {
251 if let Some(m) = a.nums {
252 check_keys("gate", m, &["threshold_db", "attack_ms", "release_ms", "hold_ms", "range_db"])?;
253 }
254 let who = format!("{who} gate");
255 let g = fx.gate;
256 let n = a.nums;
257 fx.gate = Gate {
258 on: a.on,
259 threshold_db: number(&who, n, "threshold_db", g.threshold_db, -90.0, 0.0)?,
260 attack_ms: number(&who, n, "attack_ms", g.attack_ms, 0.1, 100.0)?,
261 release_ms: number(&who, n, "release_ms", g.release_ms, 1.0, 3000.0)?,
262 hold_ms: number(&who, n, "hold_ms", g.hold_ms, 0.0, 2000.0)?,
263 range_db: number(&who, n, "range_db", g.range_db, -90.0, 0.0)?,
264 };
265 }
266 if let Some(a) = addressed(op, "compressor")? {
267 if let Some(m) = a.nums {
268 check_keys(
269 "compressor",
270 m,
271 &["threshold_db", "ratio", "attack_ms", "release_ms", "knee_db", "makeup_db", "auto_makeup"],
272 )?;
273 }
274 let who = format!("{who} compressor");
275 let c = fx.comp;
276 let n = a.nums;
277 let makeup_given = n.is_some_and(|m| m.get("makeup_db").is_some_and(|v| !v.is_null()));
278 fx.comp = Compressor {
279 on: a.on,
280 threshold_db: number(&who, n, "threshold_db", c.threshold_db, -60.0, 0.0)?,
281 ratio: number(&who, n, "ratio", c.ratio, 1.0, 20.0)?,
282 attack_ms: number(&who, n, "attack_ms", c.attack_ms, 0.1, 500.0)?,
283 release_ms: number(&who, n, "release_ms", c.release_ms, 5.0, 5000.0)?,
284 knee_db: number(&who, n, "knee_db", c.knee_db, 0.0, 30.0)?,
285 makeup_db: number(&who, n, "makeup_db", c.makeup_db, -12.0, 24.0)?,
286 auto_makeup: boolean(&who, n, "auto_makeup")?.unwrap_or(c.auto_makeup && !makeup_given),
287 };
288 }
289 if let Some(a) = addressed(op, "deesser")? {
290 if let Some(m) = a.nums {
291 check_keys("deesser", m, &["threshold_db", "amount", "lo_hz", "hi_hz"])?;
292 }
293 let who = format!("{who} deesser");
294 let d = fx.deess;
295 let n = a.nums;
296 fx.deess = DeEsser {
297 on: a.on,
298 threshold_db: number(&who, n, "threshold_db", d.threshold_db, -60.0, 0.0)?,
299 amount: number(&who, n, "amount", d.amount, 0.0, 1.0)?,
300 lo_hz: number(&who, n, "lo_hz", d.lo_hz, 1000.0, 12000.0)?,
301 hi_hz: number(&who, n, "hi_hz", d.hi_hz, 2000.0, 16000.0)?,
302 };
303 if fx.deess.clamped() != Some(fx.deess) {
304 return Err(format!("{who}: hi_hz must be above lo_hz (by more than 10%)"));
305 }
306 }
307 if let Some(a) = addressed(op, "nr")? {
308 let mut explicit = None;
309 let mut relearn = false;
310 if let Some(m) = a.nums {
311 check_keys("nr", m, &["strength", "floor_db", "from", "learn"])?;
312 if let Some(r) = m.get("from").filter(|v| !v.is_null()) {
313 explicit = Some(range_secs(r, "nr.from", fps, parse::session_end(s)).map_err(|e| format!("{who}: {e}"))?);
314 }
315 relearn = boolean(&who, Some(m), "learn")?.unwrap_or(false);
316 }
317 let who = format!("{who} nr");
318 let n = a.nums;
319 fx.nr.on = a.on;
320 fx.nr.strength = number(&who, n, "strength", fx.nr.strength, 0.0, 1.0)?;
321 fx.nr.floor_db = number(&who, n, "floor_db", fx.nr.floor_db, -60.0, 0.0)?;
322 if a.on && (fx.nr.profile.is_empty() || explicit.is_some() || relearn) {
323 let l = s.learn_noise(lane, explicit).map_err(|e| format!("{who}: {e}"))?;
324 notes.push(learned_note(&l, explicit.is_some()));
325 fx.nr.profile = l.profile;
326 }
327 }
328 if op.get("gate").is_none()
329 && op.get("nr").is_none()
330 && op.get("compressor").is_none()
331 && op.get("deesser").is_none()
332 && !reset
333 {
334 return Err(format!(
335 "{who}: name at least one of gate, nr, compressor, deesser (each true, false or an object of settings), or reset:true"
336 ));
337 }
338 if fx == before {
339 return Ok(Applied { text: format!("{who} → already set ({})", summary_or_off(&fx)), touched: Vec::new() });
340 }
341 if !s.set_lane_voice(lane, fx.clone()) {
342 return Err(format!("{who}: the engine refused it (is the lane an audio lane with a profile for the noise reduction?)"));
343 }
344 let mut text = format!("{who} → {}", summary_or_off(&fx));
345 for n in notes {
346 text.push_str(" · ");
347 text.push_str(&n);
348 }
349 Ok(Applied { text, touched: Vec::new() })
350}
351
352fn summary_or_off(fx: &VoiceFx) -> String {
353 match fx.summary() {
354 s if s.is_empty() => "no processors on".to_string(),
355 s => s,
356 }
357}
358
359#[cfg(test)]
360mod tests {
361 use super::*;
362
363 #[test]
364 fn a_processor_is_addressed_by_bool_or_object() {
365 let op = json!({"gate": false, "compressor": true, "deesser": {"amount": 0.5, "on": false}});
366 let g = addressed(&op, "gate").unwrap().unwrap();
367 assert!(!g.on && g.nums.is_none());
368 assert!(addressed(&op, "compressor").unwrap().unwrap().on);
369 let d = addressed(&op, "deesser").unwrap().unwrap();
370 assert!(!d.on && d.nums.is_some());
371 assert!(addressed(&op, "nr").unwrap().is_none());
372 assert!(addressed(&json!({"gate": 3}), "gate").is_err());
373 assert!(addressed(&json!({"gate": {"on": "yes"}}), "gate").is_err());
374 let m = json!({"threshold": 1});
375 assert!(check_keys("gate", m.as_object().unwrap(), &["threshold_db"]).unwrap_err().contains("no `threshold`"));
376 }
377
378 #[test]
379 fn numbers_are_range_checked_by_name() {
380 let m = json!({"ratio": 40});
381 let e = number("dynamics A1 compressor", m.as_object(), "ratio", 3.0, 1.0, 20.0).unwrap_err();
382 assert_eq!(e, "dynamics A1 compressor: ratio 40 out of range 1–20");
383 assert_eq!(number("x", m.as_object(), "knee_db", 6.0, 0.0, 30.0), Ok(6.0), "unnamed keeps its value");
384 let s = json!({"ratio": "x"});
385 assert!(number("x", s.as_object(), "ratio", 3.0, 1.0, 20.0).unwrap_err().contains("must be a number"));
386 }
387
388 fn session() -> PlaybackSession {
389 engine::ao::set_silent_output();
390 let p = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets/test_av.mp4");
391 PlaybackSession::open(p).expect("open test asset")
392 }
393
394 #[test]
395 fn dynamics_sets_processors_one_by_one_and_undoes_per_op() {
396 let mut s = session();
397 let a1 = Lane::new(LaneKind::Audio, 0);
398 let a = dynamics(&mut s, &json!({"lane": "A1", "compressor": {"ratio": 4, "threshold_db": -24}, "gate": true}), 30.0)
399 .unwrap();
400 assert!(a.text.contains("comp") && a.text.contains("gate"), "{}", a.text);
401 let fx = s.lane_voice(a1);
402 assert!(fx.comp.on && fx.gate.on && !fx.nr.on && !fx.deess.on);
403 assert_eq!(fx.comp.ratio, 4.0);
404 // Bypass keeps the settings.
405 dynamics(&mut s, &json!({"lane": "A1", "compressor": false}), 30.0).unwrap();
406 let fx = s.lane_voice(a1);
407 assert!(!fx.comp.on && fx.comp.ratio == 4.0 && fx.gate.on);
408 assert!(s.undo());
409 assert!(s.lane_voice(a1).comp.on, "undo brings the compressor back");
410 assert!(s.undo());
411 assert!(!s.lane_voice(a1).is_active(), "second undo leaves everything off");
412 // Reset.
413 dynamics(&mut s, &json!({"lane": "A1", "deesser": true}), 30.0).unwrap();
414 dynamics(&mut s, &json!({"lane": "A1", "reset": true}), 30.0).unwrap();
415 assert!(s.lane_voice(a1).is_default());
416 }
417
418 #[test]
419 fn dynamics_refuses_bad_input_by_name() {
420 let mut s = session();
421 let e = dynamics(&mut s, &json!({"lane": "A1", "compressor": {"ratio": 99}}), 30.0).unwrap_err();
422 assert!(e.contains("ratio 99 out of range"), "{e}");
423 let e = dynamics(&mut s, &json!({"lane": "A1", "gate": {"thresh": 1}}), 30.0).unwrap_err();
424 assert!(e.contains("no `thresh`"), "{e}");
425 let e = dynamics(&mut s, &json!({"lane": "V1", "gate": true}), 30.0).unwrap_err();
426 assert!(e.contains("not one"), "{e}");
427 assert!(dynamics(&mut s, &json!({"gate": true}), 30.0).unwrap_err().contains("missing `lane`"));
428 s.set_lane_locked(Lane::new(LaneKind::Audio, 0), true);
429 let e = dynamics(&mut s, &json!({"lane": "A1", "gate": true}), 30.0).unwrap_err();
430 assert!(e.contains("locked"), "{e}");
431 assert!(!s.lane_voice(Lane::new(LaneKind::Audio, 0)).is_active());
432 }
433
434 #[test]
435 fn clean_voice_is_one_undo_step_and_the_lane_view_names_the_processors() {
436 let mut srv = crate::server::Server::new();
437 srv.session = Some(session());
438 let r = run_clean_voice(&mut srv, &json!({"lane": "A1", "strength": "medium"}));
439 assert!(!r.is_error, "{}", r.text);
440 assert!(r.text.contains("cleaned A1 (medium)") && r.text.contains("undo step 1"), "{}", r.text);
441 let s = srv.session.as_mut().unwrap();
442 let a1 = Lane::new(LaneKind::Audio, 0);
443 let fx = s.lane_voice(a1);
444 assert!(fx.gate.on && fx.comp.on && fx.deess.on);
445 assert!(s.undo(), "one undo step");
446 assert!(s.lane_voice(a1).is_default());
447 let bad = run_clean_voice(&mut srv, &json!({"lane": "A1", "strength": "loud"}));
448 assert!(bad.is_error && bad.text.contains("light, medium, strong"), "{}", bad.text);
449 let video = run_clean_voice(&mut srv, &json!({"lane": "V1"}));
450 assert!(video.is_error, "{}", video.text);
451 }
452}