forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

voice_early_stop.rs173 lines, 6.5 KiBHistoryRawDownload
1//! A ranged export stops mixing once its range is in: it drops the mix's receiver while the
2//! mixer, the voice stage and the lane decoders are still producing. Each of them has to end
3//! on its next send into the closed channel -- quietly, with no thread left behind -- and an
4//! export cancelled mid-mix, and one started after it, must be unaffected.
5//!
6//! Its own test binary, alone in it: the check counts the process's audio threads by name,
7//! which a test running beside it would disturb.
8
9use std::path::Path;
10use std::time::{Duration, Instant};
11
12use engine::export::{ExportHandle, ExportSettings, Format};
13use engine::project::{Clip, Lane, LaneKind, Source, Speed};
14use engine::scale::FitPolicy;
15use engine::scratch::Scratch;
16use engine::voice::{self, Strength, VoiceFx};
17use engine::Project;
18
19const RATE: u32 = 44_100;
20const FPS: f64 = 30.0;
21const SECONDS: u32 = 60;
22
23fn clip(frames: u32) -> Clip {
24 Clip {
25 speed_keys: Vec::new(),
26 fade_in: 0,
27 fade_out: 0,
28 transition_out: 0,
29 visualizer: 0,
30 viz_paint: 0,
31 gain_db: 0.0,
32 gain_keys: Vec::new(),
33 pan: 0,
34 pitch: 0.0,
35 transform_keys: Vec::new(),
36 start: 0,
37 in_frame: 0,
38 out_frame: frames,
39 source: 0,
40 link: None,
41 eq: None,
42 color: None,
43 fit: FitPolicy::default(),
44 speed: Speed::NORMAL,
45 transform: None,
46 opacity_keys: Vec::new(),
47 color_keys: Vec::new(),
48 effects: Vec::new(),
49 transition_kind: Default::default(),
50 reversed: false,
51 stabilise: None, deinterlace: Default::default(), mark: Default::default(),
52 angle: Default::default(),
53 }
54}
55
56/// A mono 16-bit wav of `SECONDS` of noise at about -30 dBFS with a 1 kHz tone over it.
57fn write_wav(path: &Path) {
58 let frames = SECONDS * RATE;
59 let mut state = 1u64;
60 let mut data = Vec::with_capacity(frames as usize * 2);
61 for i in 0..frames {
62 state = state.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1_442_695_040_888_963_407);
63 let noise = ((state >> 40) as f32 / (1u64 << 24) as f32 - 0.5) * 0.11;
64 let tone = 0.25 * (std::f32::consts::TAU * 1000.0 * i as f32 / RATE as f32).sin();
65 data.extend_from_slice(&(((noise + tone) * 32767.0).round() as i16).to_le_bytes());
66 }
67 let mut out = Vec::new();
68 out.extend_from_slice(b"RIFF");
69 out.extend_from_slice(&(36 + data.len() as u32).to_le_bytes());
70 out.extend_from_slice(b"WAVEfmt ");
71 out.extend_from_slice(&16u32.to_le_bytes());
72 out.extend_from_slice(&1u16.to_le_bytes());
73 out.extend_from_slice(&1u16.to_le_bytes());
74 out.extend_from_slice(&RATE.to_le_bytes());
75 out.extend_from_slice(&(RATE * 2).to_le_bytes());
76 out.extend_from_slice(&2u16.to_le_bytes());
77 out.extend_from_slice(&16u16.to_le_bytes());
78 out.extend_from_slice(b"data");
79 out.extend_from_slice(&(data.len() as u32).to_le_bytes());
80 out.extend_from_slice(&data);
81 std::fs::write(path, out).expect("write the generated wav");
82}
83
84/// The process's threads that belong to a mix: lane decoders, voice stages, mixers.
85fn audio_threads() -> usize {
86 std::fs::read_dir("/proc/self/task")
87 .expect("the thread list")
88 .filter_map(|t| std::fs::read_to_string(t.ok()?.path().join("comm")).ok())
89 .filter(|name| matches!(name.trim(), "audio-decode" | "voice-fx" | "audio-mix"))
90 .count()
91}
92
93/// Waits up to two seconds for every mix thread to end, then says how many are left.
94fn threads_left() -> usize {
95 let started = Instant::now();
96 while audio_threads() > 0 && started.elapsed() < Duration::from_secs(2) {
97 std::thread::sleep(Duration::from_millis(5));
98 }
99 audio_threads()
100}
101
102fn wait(handle: &ExportHandle) -> Duration {
103 let started = Instant::now();
104 while !handle.is_finished() {
105 assert!(started.elapsed() < Duration::from_secs(120), "export hung");
106 std::thread::sleep(Duration::from_millis(2));
107 }
108 started.elapsed()
109}
110
111#[test]
112fn a_short_range_stops_the_mix_early_and_leaves_no_thread_behind() {
113 let dir = Scratch::dir("ve_voice_early_stop");
114 let wav = dir.join("voice.wav");
115 write_wav(&wav);
116 let mut project = Project::from_parts(
117 vec![Source::new(&wav, 0)],
118 vec![(LaneKind::Audio, vec![clip(SECONDS * FPS as u32)])],
119 Vec::new(),
120 Vec::new(),
121 Vec::new(),
122 )
123 .expect("one audio lane over a generated file");
124 let learned = voice::learn_noise(&project, Lane::A1, FPS, None, Some((0.1, 0.9))).unwrap();
125 assert!(project.set_lane_voice(
126 Lane::A1,
127 VoiceFx::clean_voice(Strength::Strong, learned.profile, Some(learned.noise_db))
128 ));
129 let mut meta = engine::demux::Demuxer::open(
130 &std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../assets/test_av.mp4"),
131 )
132 .expect("open test_av")
133 .0;
134 meta.frame_rate = FPS;
135 let export = |range: Option<(u32, u32)>, name: &str| {
136 engine::export::start(
137 project.clone(),
138 meta,
139 &dir.join(name),
140 &ExportSettings { format: Format::Wav, range, ..Default::default() },
141 None,
142 )
143 };
144 assert_eq!(threads_left(), 0, "the noise learn leaves no thread behind either");
145
146 let full = export(None, "full.wav");
147 let full_took = wait(&full);
148 full.result().expect("an outcome").expect("the full export");
149 assert_eq!(threads_left(), 0, "a finished mix leaves no thread behind");
150
151 // One second from the start: no pre-roll, and the mix of the other 59 is never read.
152 let short = export(Some((0, FPS as u32)), "short.wav");
153 let short_took = wait(&short);
154 short.result().expect("an outcome").expect("the ranged export");
155 assert!(
156 short_took * 4 < full_took,
157 "one second took {short_took:?}, the whole minute {full_took:?}"
158 );
159 assert_eq!(threads_left(), 0, "the early stop leaves no mix thread behind");
160
161 let cancelled = export(None, "cancelled.wav");
162 cancelled.cancel();
163 wait(&cancelled);
164 assert!(cancelled.result().expect("an outcome").is_err(), "a cancel reports as one");
165 assert_eq!(threads_left(), 0, "a cancel leaves no mix thread behind");
166
167 let again = export(Some((0, FPS as u32)), "again.wav");
168 wait(&again);
169 again.result().expect("an outcome").expect("an export after the cancel");
170 let bytes = std::fs::metadata(dir.join("again.wav")).unwrap().len();
171 assert_eq!(bytes, std::fs::metadata(dir.join("short.wav")).unwrap().len(), "the same second again");
172 assert_eq!(threads_left(), 0);
173}