forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

audio_files.rs996 lines, 40.2 KiBHistoryRawDownload
1//! Standalone audio files as sources: every container we claim to read decodes
2//! to the same tone, a song joins a timeline of video on the audio lane, a song
3//! *is* a timeline on its own (canvas scaffolded, picture black, sound exported)
4//! and a visualizer clip is how that song gets a picture on a video lane.
5//! Paste still never lands a song on V1 by accident.
6//!
7//! ```text
8//! cargo test -p engine --release --test audio_files
9//! ```
10
11use std::path::{Path, PathBuf};
12
13use engine::export::{ExportSettings, Format};
14use engine::project::{Lane, LaneKind};
15use engine::scratch::Scratch;
16use engine::{AudioSession, Clip, PlaybackSession, Project};
17
18/// The fixtures `scripts/gen_fixtures.sh` writes: 3 s of 440 Hz left / 880 Hz
19/// right at 44.1k stereo, under a 1 Hz volume pulse -- the same tone
20/// `test_av.mp4` carries, so a song and a video clip share one timeline.
21/// `test_tone.mpg` is the same MPEG audio stream under the standard's spelling
22/// rather than the codec's; the cover-carrying `.mpeg` has its own test below.
23const CONTAINERS: [&str; 7] = [
24 "test_tone.mp3",
25 "test_tone.mpg",
26 "test_tone.wav",
27 "test_tone.flac",
28 "test_tone.ogg",
29 "test_tone.m4a",
30 "test_tone.aac",
31];
32
33fn asset(name: &str) -> PathBuf {
34 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
35 .join("../../assets")
36 .join(name)
37}
38
39/// The two acts a file on the timeline now takes, in the order a user does
40/// them: taken into the library (`PlaybackSession::import` places nothing),
41/// then dragged onto the end of the timeline.
42fn import_and_place(session: &mut PlaybackSession, path: &Path) {
43 session.import(path).expect("the file joins this timeline");
44 let end = session.timeline_duration();
45 assert!(
46 session
47 .place_stream_at(end, path, 0, None)
48 .expect("a file just imported is on this timeline"),
49 "the drag onto the end of the timeline"
50 );
51}
52
53/// The message of a call that had to be refused. Not `expect_err`: that wants
54/// `Debug` on the success side, and neither a session nor a packet has it.
55fn refusal<T>(result: engine::Result<T>) -> String {
56 match result {
57 Ok(_) => panic!("expected a refusal"),
58 Err(e) => e.to_string(),
59 }
60}
61
62fn open(path: impl AsRef<Path>) -> PlaybackSession {
63 let session = PlaybackSession::open(path).expect("open");
64 session.set_gain(0.0);
65 session
66}
67
68/// Every frame the file decodes to, interleaved, plus the meta it declares.
69fn decode(path: &Path) -> (u32, u16, Vec<f32>) {
70 let (meta, rx) = AudioSession::open(path)
71 .expect("open")
72 .expect("the fixture has audio");
73 let mut samples = Vec::new();
74 for chunk in rx {
75 samples.extend(chunk.samples);
76 }
77 (meta.sample_rate, meta.channels, samples)
78}
79
80#[test]
81fn every_container_decodes_the_same_three_second_tone() {
82 for name in CONTAINERS {
83 let (rate, channels, samples) = decode(&asset(name));
84 assert_eq!((rate, channels), (44100, 2), "{name}");
85 let secs = samples.len() as f64 / f64::from(rate) / f64::from(channels);
86 // Lossy formats pad: a codec frame is 1152 (mp3) or 1024 (aac) samples,
87 // so a tenth of a second is generous and still catches a decoder that
88 // stops early or doubles the stream.
89 assert!(
90 (secs - 3.0).abs() < 0.1,
91 "{name}: {secs:.3} s of audio, want 3.0"
92 );
93 // The fixture's envelope is 0.5 + 0.5*sin(2*PI*t): full scale at t=0.25
94 // of every second, silence at t=0.75. Sample it there rather than
95 // trusting a length -- a channel-swapped or mis-scaled decode still has
96 // the right number of samples.
97 for second in 0..3 {
98 let at = |t: f64| {
99 let frame = ((f64::from(second) + t) * f64::from(rate)) as usize;
100 let block = &samples[frame * usize::from(channels)..][..usize::from(channels) * 64];
101 block.iter().fold(0.0f32, |peak, s| peak.max(s.abs()))
102 };
103 // Depth as a ratio, not an absolute: the fixture's sines sit around
104 // an eighth of full scale and that is the encoder's business
105 // (ledger:873), while a dip 20x below the peak is the pulse.
106 let (loud, quiet) = (at(0.25), at(0.75));
107 assert!(loud > 0.05, "{name} second {second}: peak only {loud}");
108 assert!(
109 quiet < 0.05 * loud,
110 "{name} second {second}: dip {quiet} against peak {loud}"
111 );
112 }
113 }
114}
115
116/// DEBT #64: an AC-3 soundtrack ripped to its own `.mka`, with no video track
117/// at all. `crate::demux::is_matroska` already admits `.mka` (it has since
118/// 810ded2, 2026-08-12), so `Track::open` already takes this file down the
119/// same [`MkvAc3Track`] door `test_ac3.mkv` uses -- the debt's routing gap was
120/// already closed, this was just never proven by a fixture. If `is_matroska`
121/// ever lost `.mka` again, this file would fall through to `SymTrack`, whose
122/// `mkv` reader has no AC-3 decoder, and `decode` below would panic on "the
123/// fixture has audio". 2 s of 440 Hz at 44.1k stereo, unpulsed (a plain sine,
124/// not the CONTAINERS envelope), so a non-silent sample anywhere in the
125/// middle is enough.
126#[test]
127fn an_ac3_track_with_no_picture_opens_out_of_an_mka() {
128 let (rate, channels, samples) = decode(&asset("test_ac3.mka"));
129 assert_eq!((rate, channels), (44100, 2), "test_ac3.mka");
130 let secs = samples.len() as f64 / f64::from(rate) / f64::from(channels);
131 assert!(
132 (secs - 2.0).abs() < 0.2,
133 "test_ac3.mka: {secs:.3} s, want 2.0"
134 );
135 let mid = samples.len() / 2;
136 let peak = samples[mid..][..channels as usize * 64]
137 .iter()
138 .fold(0.0f32, |peak, s| peak.max(s.abs()));
139 assert!(peak > 0.01, "test_ac3.mka: decoded to silence, peak {peak}");
140}
141
142/// The length a placement is built from, which is the only frame count a file
143/// with no picture has.
144#[test]
145fn duration_comes_from_the_header_or_the_decode() {
146 for name in CONTAINERS {
147 let secs = AudioSession::duration_secs(asset(name))
148 .expect("probe")
149 .expect("the fixture has audio");
150 assert!(
151 (secs - 3.0).abs() < 0.1,
152 "{name}: duration reads {secs:.3} s"
153 );
154 }
155 assert_eq!(
156 AudioSession::duration_secs(asset("test_baseline.mp4")).expect("probe"),
157 None,
158 "a silent video has no audio duration"
159 );
160}
161
162#[test]
163fn a_song_joins_a_video_timeline_on_the_audio_lane() {
164 let mut session = open(asset("test_av.mp4"));
165 let before = session.timeline_duration();
166 // The import alone is a library row: the lanes are untouched until it is
167 // dragged onto one.
168 session
169 .import(&asset("test_tone.mp3"))
170 .expect("import the song");
171 assert_eq!(session.sources().len(), 2, "the library grew");
172 assert_eq!(session.lane_clips(Lane::A1).len(), 1, "an import placed it");
173 assert_eq!(session.timeline_duration(), before);
174 assert_eq!(session.file_frames(&asset("test_tone.mp3")), 90);
175 let end = session.timeline_duration();
176 assert!(session
177 .place_stream_at(end, &asset("test_tone.mp3"), 0, None)
178 .expect("a song just imported is on this timeline"));
179
180 // 3 s at 30 fps, placed at the end: the audio lane runs 90 frames past the
181 // video.
182 assert!(
183 (session.timeline_duration() - (before + 3.0)).abs() < 0.05,
184 "{} s of timeline, want {}",
185 session.timeline_duration(),
186 before + 3.0
187 );
188 assert_eq!(session.sources().len(), 2);
189 // The video lane never hears about it: one clip, the one the file opened
190 // with. The audio lane has two.
191 assert_eq!(session.lane_clips(Lane::V1).len(), 1, "video lane");
192 assert_eq!(session.lane_clips(Lane::A1).len(), 2, "audio lane");
193 let song = session.lane_clips(Lane::A1)[1].clone();
194 assert_eq!((song.source, song.in_frame, song.len()), (1, 0, 90));
195
196 // And it plays: the segment list past the join names the song, so the
197 // worker opens it rather than running silent.
198 session.seek(before + 1.0);
199 assert!(session.lane_spans_by_source(Lane::A1).len() >= 2);
200}
201
202/// A rate one output device cannot have two of is **converted**, not refused:
203/// the 48 kHz tone joins a 44.1 kHz timeline, is placed for the seconds it
204/// lasts, and comes out at the pitch it was recorded at. The mix runs at the
205/// highest source rate (48 kHz), so the 44.1 kHz video sound is the one
206/// converted there.
207///
208/// The pitch is the whole claim. Reading a 44.1 kHz file's frames one for one
209/// onto a 48 kHz timeline plays it 8.1% fast and 440 Hz becomes 476 -- which is
210/// what "it imported" would look like from a length check alone.
211#[test]
212fn a_rate_the_device_cannot_mix_is_converted_at_the_door() {
213 let mut session = open(asset("test_av.mp4"));
214 let before = session.timeline_duration();
215 import_and_place(&mut session, &asset("test_tone_48k.wav"));
216 assert_eq!(session.sources().len(), 2, "the 48k file is in the library");
217 assert_eq!(session.lane_clips(Lane::A1).len(), 2, "and on the lane");
218 // 3 s of tone placed after the video, at the timeline's own rate.
219 assert!(
220 (session.timeline_duration() - (before + 3.0)).abs() < 0.05,
221 "{} s of timeline, want {}",
222 session.timeline_duration(),
223 before + 3.0
224 );
225
226 // ...and the samples themselves, straight out of the worker the session
227 // feeds from: one second of the 48k file, on the 48k timeline it sets.
228 let sources = [(asset("test_av.mp4"), 0), (asset("test_tone_48k.wav"), 0)];
229 let (meta, rx) = AudioSession::open_multi_streams(&sources, &[(Some(1), 0.25, 1.25)])
230 .expect("open")
231 .expect("the timeline has sound");
232 assert_eq!(
233 (meta.sample_rate, meta.channels),
234 (48_000, 2),
235 "the highest source rate, not the first source's 44.1 kHz"
236 );
237 let samples: Vec<f32> = rx.into_iter().flat_map(|c| c.samples).collect();
238 let frames = samples.len() / 2;
239 assert!(
240 (frames as i64 - 48000).abs() < 64,
241 "one second of timeline is {frames} frames of 48000"
242 );
243 // 440 Hz left, 880 Hz right -- the fixture's own tones, unmoved. Zero
244 // crossings date them without an FFT: the 48k tone read at 1:1 is exact here,
245 // and a 44.1k source read 1:1 would come out 8% high, which this 2% band rejects.
246 for (name, channel, hz) in [("left", 0, 440.0), ("right", 1, 880.0)] {
247 let side: Vec<f32> = samples[channel..].iter().step_by(2).copied().collect();
248 let secs = side.len() as f64 / 48000.0;
249 let crossings = side
250 .windows(2)
251 .filter(|p| (p[0] < 0.0) != (p[1] < 0.0))
252 .count() as f64;
253 let got = crossings / 2.0 / secs;
254 assert!(
255 (got - hz).abs() <= 0.02 * hz,
256 "{name}: {got:.1} Hz out of a {hz} Hz tone -- the resample moved the pitch"
257 );
258 }
259}
260
261/// A song *is* a timeline: it scaffolds the canvas a video would have defined,
262/// its own length is the timeline's, the video lane starts empty and the picture
263/// is the black of an uncovered canvas.
264#[test]
265fn a_song_is_a_timeline_of_its_own() {
266 let mut session = open(asset("test_tone.mp3"));
267 let meta = *session.meta();
268 assert_eq!(
269 (meta.width, meta.height),
270 (1920, 1080),
271 "the default canvas"
272 );
273 assert_eq!(meta.frame_rate, 30.0);
274 // 3 s of tone at 30 fps, rounded up: the only frame count a file with no
275 // picture has, and it is the timeline's length too.
276 assert_eq!(meta.frame_count, 90);
277 assert!((session.timeline_duration() - 3.0).abs() < 0.05);
278 assert!(!session.is_empty(), "a song is not an empty timeline");
279 assert!(
280 session.lane_clips(Lane::V1).is_empty(),
281 "no picture anywhere"
282 );
283 assert_eq!(session.lane_clips(Lane::A1).len(), 1);
284 let clip = session.lane_clips(Lane::A1)[0].clone();
285 assert_eq!((clip.source, clip.in_frame, clip.len()), (0, 0, 90));
286 assert_eq!(session.sources().len(), 1);
287
288 // And it shows black rather than nothing: the whole timeline is a gap, so
289 // the black worker feeds it at the canvas size.
290 session.seek(1.0);
291 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
292 let frame = loop {
293 if let Some(frame) = session.try_frame() {
294 break frame;
295 }
296 assert!(std::time::Instant::now() < deadline, "no frame at 1 s");
297 std::thread::sleep(std::time::Duration::from_millis(10));
298 };
299 assert_eq!((frame.width, frame.height), (1920, 1080));
300 assert_eq!(frame.index, 30, "the gap is indexed in timeline frames");
301 assert!(
302 frame.bgra.as_chunks::<4>().0.iter().all(|p| p[..3] == [0, 0, 0]),
303 "the picture over a song is black"
304 );
305}
306
307/// A file that is neither a picture nor a sound this engine can play is not a
308/// timeline: refused at the door, in the words of whatever refused it.
309#[test]
310fn a_file_with_no_picture_and_no_sound_is_still_refused() {
311 let dir = Scratch::dir("ve_audio_bad");
312 let fake = dir.join("not_really.mp3");
313 std::fs::write(&fake, b"this is not an mp3").expect("write");
314 let e = refusal(PlaybackSession::open(&fake));
315 assert!(e.starts_with(&fake.display().to_string()), "{e}");
316}
317
318/// The whole audio-only round trip a user makes: open a song, place a second
319/// one, save, reopen, export the sound -- as an mp4 of the sound alone, and as
320/// WAV.
321#[test]
322fn an_audio_only_project_saves_reloads_and_exports_its_sound() {
323 let dir = Scratch::dir("ve_audio_only");
324
325 let mut session = open(asset("test_tone.mp3"));
326 // A second song joins it, the same way one joins a timeline of video: no
327 // picture is needed for the import to have something to hold it to.
328 import_and_place(&mut session, &asset("test_tone.flac"));
329 assert_eq!(session.lane_clips(Lane::A1).len(), 2);
330 assert!(session.lane_clips(Lane::V1).is_empty());
331 assert!((session.timeline_duration() - 6.0).abs() < 0.1);
332
333 // An mp4 of it is the sound alone, in an mp4 with no picture; WAV writes the
334 // sound too.
335 let mp4 = dir.join("song.mp4");
336 wait(&session.export_to_with(
337 &mp4,
338 &ExportSettings {
339 format: Format::Mp4,
340 ..ExportSettings::default()
341 },
342 ))
343 .expect("an audio-only timeline exports as the sound alone in an mp4");
344 assert!(mp4.exists(), "the mp4 export wrote nothing");
345
346 let wav = dir.join("song.wav");
347 wait(&session.export_to_with(
348 &wav,
349 &ExportSettings {
350 format: Format::Wav,
351 ..ExportSettings::default()
352 },
353 ))
354 .expect("wav export of an audio-only timeline");
355 let (rate, channels, samples) = decode(&wav);
356 assert_eq!((rate, channels), (44100, 2));
357 let secs = samples.len() as f64 / f64::from(rate) / f64::from(channels);
358 assert!((secs - 6.0).abs() < 0.1, "{secs:.3} s of exported audio");
359 let peak = samples.iter().fold(0.0f32, |peak, s| peak.max(s.abs()));
360 assert!(peak > 0.05, "the export is silent: peak {peak}");
361
362 // Saved and reopened: an .edith naming nothing but songs loads.
363 let project = dir.join("songs.edith");
364 let before = (
365 session.lane_spans_by_source(Lane::A1),
366 session.sources().to_vec(),
367 session.timeline_duration(),
368 );
369 session.save_project(&project).expect("save");
370 drop(session);
371 let reloaded = PlaybackSession::open_project(&project).expect("reload an audio-only project");
372 reloaded.set_gain(0.0);
373 assert_eq!(
374 (
375 reloaded.lane_spans_by_source(Lane::A1),
376 reloaded.sources().to_vec(),
377 reloaded.timeline_duration()
378 ),
379 before
380 );
381 assert_eq!(reloaded.meta().frame_rate, 30.0, "the canvas came back");
382 assert_eq!(
383 (reloaded.meta().width, reloaded.meta().height),
384 (1920, 1080)
385 );
386 assert!(reloaded.lane_clips(Lane::V1).is_empty());
387 drop(reloaded);
388 let _ = std::fs::remove_dir_all(&dir);
389}
390
391/// DEBT #45: the device the timeline plays through used to be opened once, on
392/// the first non-image source ([`audio_source_of`] in `playback.rs`) -- with
393/// no check that the source it landed on has a usable audio track at all. A
394/// timeline whose *first* source is silent (`test_baseline.mp4` has no audio
395/// track) therefore never reopened on a later source that does, and stayed
396/// silent for the whole session however many other sources had sound.
397///
398/// No PipeWire daemon lives in this sandbox (`AoSession::probe()` is false
399/// here), so the device itself cannot be tapped for samples -- this reaches
400/// past it instead, onto the one signal `open_audio` still hands back with no
401/// device at all: [`PlaybackSession::audio_disabled_reason`]. `test_dts.mkv`'s
402/// track has a header (so it is chosen over a source with none) but no
403/// decoder (so opening it, unlike the silent baseline, is a reason worth
404/// giving) -- the old code never got there, and reports nothing.
405#[test]
406fn a_silent_first_source_does_not_stop_the_scan_for_one_with_sound() {
407 let dir = Scratch::dir("ve_silent_first_source");
408 let path0 = asset("test_baseline.mp4");
409 let path1 = asset("test_dts.mkv");
410 let (meta0, _) = engine::demux::Demuxer::open(&path0).expect("open the baseline fixture");
411 let (meta1, _) = engine::demux::Demuxer::open(&path1).expect("open the dts fixture");
412
413 // `Project`, not `PlaybackSession::import`: the session-level import gate
414 // would itself refuse a real track landing on a silent timeline
415 // (`audio_matches_probed`, a different corner of the same debt) before
416 // this test ever reaches `open_project`.
417 let mut project = Project::single(&path0, meta0.frame_count);
418 let source1 = project.import(&path1, 0);
419 let lane2 = project.add_lane(LaneKind::Video);
420 let clip = Clip {
421 speed_keys: Vec::new(),
422 reversed: false,
423 stabilise: None, deinterlace: Default::default(), mark: Default::default(),
424 angle: Default::default(),
425 fade_in: 0,
426 fade_out: 0,
427 transition_out: 0,
428 transition_kind: Default::default(),
429 visualizer: 0,
430 viz_paint: 0,
431 gain_db: 0.0,
432 gain_keys: Vec::new(),
433 pan: 0,
434 pitch: 0.0,
435 transform_keys: Vec::new(),
436 opacity_keys: Vec::new(),
437 color_keys: Vec::new(),
438 effects: Vec::new(),
439 start: 0,
440 in_frame: 0,
441 out_frame: meta1.frame_count,
442 source: source1,
443 link: None,
444 eq: None,
445 color: None,
446 fit: Default::default(),
447 speed: engine::Speed::NORMAL,
448 transform: None,
449 };
450 assert!(project.place(lane2, 0, clip), "the second source lands");
451
452 let (sources, lanes, eq, color, transform) = project.without_orphan_sources();
453 let file = dir.join("silent_first.edith");
454 engine::edith::save(
455 &file,
456 &sources,
457 &lanes,
458 &project.lane_gains(),
459 &project.lane_subs(),
460 project.subtitles(),
461 &eq,
462 &color,
463 &transform,
464 (meta0.width, meta0.height),
465 None,
466 project.tone(),
467 false,
468 true,
469 engine::export::EncoderSeat::default(),
470 project.limiter(),
471 None,
472 0,
473 )
474 .expect("save");
475
476 let reloaded = PlaybackSession::open_project(&file).expect("reopen");
477 assert!(
478 reloaded.audio_disabled_reason().is_none(),
479 "the scan for a source with sound never reached test_dts.mkv, which decodes: {:?}",
480 reloaded.audio_disabled_reason()
481 );
482 drop(reloaded);
483 let _ = std::fs::remove_dir_all(&dir);
484}
485
486/// A *song* as the first import into an empty window: `open_library` takes the
487/// audio-only fork of `open` (there is no picture to scaffold a canvas from) and
488/// still leaves the timeline empty. The row is there at the song's own length,
489/// the canvas and the clock a song would have set are set, and the drag that
490/// follows is what makes it play.
491#[test]
492fn the_first_import_of_a_song_opens_a_library_over_an_empty_timeline() {
493 let mp3 = asset("test_tone.mp3");
494 let mut session = PlaybackSession::open_library(&mp3).expect("open into the library");
495 session.set_gain(0.0);
496 assert!(session.is_empty(), "the timeline must start empty");
497 assert_eq!(session.timeline_duration(), 0.0);
498 assert!(session.lane_clips(Lane::A1).is_empty(), "nothing placed");
499 assert!(session.lane_clips(Lane::V1).is_empty(), "no picture either");
500 // The canvas a song scaffolds, and the clock that goes with it -- a session
501 // with an empty timeline is still this file's session.
502 let meta = *session.meta();
503 assert_eq!((meta.width, meta.height), (1920, 1080), "the song canvas");
504 assert_eq!(meta.frame_rate, 30.0);
505 assert_eq!(session.sources().len(), 1, "the library row");
506 assert_eq!(session.file_frames(&mp3), 90, "3 s at 30 fps, never placed");
507 assert!(!session.undo(), "opening a library is not an undo step");
508 // A file this session never took in has no length and cannot be placed.
509 assert_eq!(session.file_frames(&asset("test_tone.flac")), 0);
510 assert_eq!(
511 refusal(session.place_stream_at(0.0, &asset("test_tone.flac"), 0, None)),
512 format!(
513 "{} is not on this timeline",
514 asset("test_tone.flac").display()
515 )
516 );
517
518 // The drag: onto the audio lane and nowhere else, at the song's own length.
519 assert!(session
520 .place_stream_at(0.0, &mp3, 0, None)
521 .expect("its own file is on this timeline"));
522 assert!(!session.is_empty());
523 assert!((session.timeline_duration() - 3.0).abs() < 0.05);
524 assert_eq!(session.lane_clips(Lane::A1).len(), 1);
525 assert!(session.lane_clips(Lane::V1).is_empty(), "still no picture");
526 let clip = session.lane_clips(Lane::A1)[0].clone();
527 assert_eq!((clip.source, clip.in_frame, clip.len()), (0, 0, 90));
528 // And it plays: the segment list names the song, so the worker opens it
529 // rather than running silent.
530 session.seek(1.0);
531 assert!(!session.lane_spans_by_source(Lane::A1).is_empty());
532 // One `z` takes the drag back to the empty timeline, row and all.
533 assert!(session.undo(), "undo the drag");
534 assert!(session.is_empty());
535 assert_eq!(session.sources().len(), 1, "the row survives the undo");
536}
537
538/// The other half of the door: a *video* joining a timeline a song scaffolded.
539/// It is held to the canvas the song set (H.264, 30 fps), so a matching file
540/// brings its picture in -- and the timeline stops being audio-only, mp4 export
541/// included.
542#[test]
543fn a_video_joins_a_timeline_a_song_started() {
544 let mut session = open(asset("test_tone.mp3"));
545 import_and_place(&mut session, &asset("test_av.mp4"));
546 assert_eq!(session.lane_clips(Lane::V1).len(), 1, "a picture at last");
547 assert_eq!(session.lane_clips(Lane::A1).len(), 2);
548 // A sample rate the device cannot have two of is no refusal either: it is
549 // resampled onto the timeline's, as a frame rate is conformed to the canvas.
550 session
551 .import(&asset("test_tone_48k.wav"))
552 .expect("48 kHz joins a 44.1 kHz timeline");
553 assert_eq!(session.sources().len(), 3);
554 // ...and a *frame* rate of its own is not a refusal either: the canvas a song
555 // scaffolds runs at 30 fps and a 25 fps picture joins it at the length it
556 // lasts in seconds (50 frames of file, 60 of timeline).
557 session
558 .import(&asset("test_25fps.mp4"))
559 .expect("25 fps joins the 30 fps canvas a song scaffolded");
560 assert_eq!(session.file_frames(&asset("test_25fps.mp4")), 60);
561}
562
563/// Blocks until the export settles, whichever way it settled.
564fn wait(handle: &engine::ExportHandle) -> engine::Result<()> {
565 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(120);
566 loop {
567 if let Some(result) = handle.result() {
568 return result;
569 }
570 assert!(std::time::Instant::now() < deadline, "export never settled");
571 std::thread::sleep(std::time::Duration::from_millis(20));
572 }
573}
574
575/// The *copy* path names what it cannot copy, by file and by format. That is a
576/// fallback's reason rather than a user's refusal now -- `export::copy_audio`
577/// takes this `Err` as "not copyable" and decodes and re-encodes the timeline
578/// instead (`tests/audio_export.rs` exports exactly this shape as an mp4 with
579/// sound in it) -- but the words are what a caller with no encoder shows, so
580/// they are still asserted here.
581#[test]
582fn an_export_refuses_audio_it_cannot_copy() {
583 let sources = vec![asset("test_av.mp4"), asset("test_tone.mp3")];
584 let segs = [(Some(0), 0.0, 1.0), (Some(1), 0.0, 1.0)];
585 assert_eq!(
586 refusal(AudioSession::copy_multi_segments(&sources, &segs)),
587 "a packet copy needs AAC in an mp4; test_tone.mp3 is mp3"
588 );
589 // A timeline of nothing but mp4 still exports, which is the invariant this
590 // refusal must not have cost.
591 assert!(AudioSession::copy_multi_segments(&sources[..1], &segs[..1])
592 .expect("mp4 audio still copies")
593 .is_some());
594}
595
596#[test]
597fn a_song_survives_a_save_and_a_reload() {
598 let dir = Scratch::dir("ve_audio_files");
599 let copy = |name: &str| {
600 let to = dir.join(name);
601 std::fs::copy(asset(name), &to).expect("copy the fixture");
602 to
603 };
604
605 let mut session = open(copy("test_av.mp4"));
606 import_and_place(&mut session, &copy("test_tone.flac"));
607 // And one placed at the playhead, the way a library row dropped on the
608 // audio lane arrives -- so the reload has both doors to restore.
609 let song = session.lane_clips(Lane::A1)[1].clone();
610 assert!(session.place_at(
611 Lane::A1,
612 1.0,
613 Clip {
614 fade_in: 0,
615 fade_out: 0,
616 in_frame: 0,
617 out_frame: 30,
618 ..song
619 }
620 ));
621 let before = (
622 session.lane_spans_by_source(Lane::A1),
623 session.sources().to_vec(),
624 session.timeline_duration(),
625 );
626
627 let project = dir.join("song.edith");
628 session.save_project(&project).expect("save");
629 drop(session);
630 let reloaded = PlaybackSession::open_project(&project).expect("reload");
631 reloaded.set_gain(0.0);
632 assert_eq!(
633 (
634 reloaded.lane_spans_by_source(Lane::A1),
635 reloaded.sources().to_vec(),
636 reloaded.timeline_duration()
637 ),
638 before
639 );
640
641 let _ = std::fs::remove_dir_all(&dir);
642}
643
644#[test]
645fn place_visualizer_puts_a_waveform_on_a_video_lane() {
646 let dir = Scratch::dir("ve_audio_viz");
647 let song = {
648 let to = dir.join("test_tone.mp3");
649 std::fs::copy(asset("test_tone.mp3"), &to).expect("copy");
650 to
651 };
652 let mut session = open(&song);
653 let audio = session.lane_clips(Lane::A1)[0].clone();
654 assert!(session.lane_clips(Lane::V1).is_empty());
655 assert!(
656 session
657 .place_visualizer(0, &song, 0, audio.in_frame, audio.out_frame, None)
658 .expect("place visualizer"),
659 "placed"
660 );
661 assert_eq!(
662 session.lane_clips(Lane::A1).len(),
663 1,
664 "audio lane unchanged"
665 );
666 let video = session.lane_clips(Lane::V1);
667 assert_eq!(video.len(), 1);
668 assert_eq!(video[0].visualizer & 1, 1, "the clip is marked a waveform");
669 assert_eq!(video[0].source, audio.source);
670 assert_eq!(
671 (video[0].in_frame, video[0].out_frame),
672 (audio.in_frame, audio.out_frame)
673 );
674
675 session.seek(1.0);
676 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(15);
677 let mut saw = false;
678 let mut frames = 0u32;
679 while std::time::Instant::now() < deadline && frames < 45 {
680 if let Some(frame) = session.try_frame() {
681 frames += 1;
682 if frame
683 .bgra
684 .as_chunks::<4>().0.iter()
685 .any(|p| p[0] > 32 || p[1] > 32 || p[2] > 32)
686 {
687 saw = true;
688 break;
689 }
690 } else {
691 std::thread::sleep(std::time::Duration::from_millis(10));
692 }
693 }
694 assert!(saw, "visualizer frame stayed black after {frames} pictures");
695
696 let project = dir.join("viz.edith");
697 session.save_project(&project).expect("save");
698 drop(session);
699 let reloaded = PlaybackSession::open_project(&project).expect("reload visualizer project");
700 assert_eq!(reloaded.lane_clips(Lane::V1).len(), 1);
701 assert_eq!(reloaded.lane_clips(Lane::V1)[0].visualizer & 1, 1);
702 assert_eq!(reloaded.lane_clips(Lane::A1).len(), 1);
703 drop(reloaded);
704 let _ = std::fs::remove_dir_all(&dir);
705}
706
707#[test]
708fn place_visualizer_paints_a_video_file_soundtrack() {
709 let dir = Scratch::dir("ve_av_viz");
710 let film = {
711 let to = dir.join("test_av.mp4");
712 std::fs::copy(asset("test_av.mp4"), &to).expect("copy");
713 to
714 };
715 let mut session = open(&film);
716 let picture = session.lane_clips(Lane::V1)[0].clone();
717 let before = session.lane_clips(Lane::V1).len();
718 assert!(
719 session
720 .place_visualizer(picture.end(), &film, 0, picture.in_frame, picture.out_frame, None)
721 .expect("place visualizer of a film"),
722 "placed"
723 );
724 let video = session.lane_clips(Lane::V1);
725 assert_eq!(video.len(), before + 1);
726 let viz = video.last().unwrap().clone();
727 assert_eq!(viz.visualizer & 1, 1);
728 assert_eq!((viz.in_frame, viz.out_frame), (picture.in_frame, picture.out_frame));
729 session.seek(f64::from(viz.start) / 30.0 + 0.5);
730 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(15);
731 let mut saw = false;
732 let mut frames = 0u32;
733 while std::time::Instant::now() < deadline && frames < 45 {
734 if let Some(frame) = session.try_frame() {
735 frames += 1;
736 if frame.bgra.as_chunks::<4>().0.iter().any(|p| p[0] > 32 || p[1] > 32 || p[2] > 32) {
737 saw = true;
738 break;
739 }
740 } else {
741 std::thread::sleep(std::time::Duration::from_millis(10));
742 }
743 }
744 assert!(saw, "film soundtrack visualizer stayed black after {frames} pictures");
745 let _ = std::fs::remove_dir_all(&dir);
746}
747
748/// ...and the door the editor itself had onto that same broken project: a copy
749/// of the song pasted from the clipboard used to land on `V1` as well as `A1`,
750/// where it decodes to nothing -- and the save it wrote was refused on the way
751/// back in. The paste is the plain UI path, so this is data loss with no
752/// hand-editing anywhere in it.
753#[test]
754fn a_pasted_song_never_lands_on_the_video_lane() {
755 let dir = Scratch::dir("ve_audio_paste");
756 let copy = |name: &str| {
757 let to = dir.join(name);
758 std::fs::copy(asset(name), &to).expect("copy the fixture");
759 to
760 };
761
762 let mut session = open(copy("test_av.mp4"));
763 import_and_place(&mut session, &copy("test_tone.flac"));
764 let song = session.lane_clips(Lane::A1)[1].clone();
765 let video_before = session.lane_clips(Lane::V1).to_vec();
766 assert!(session.paste_at(0.0, song.clone()), "paste the copied song");
767
768 // The video lane got room and nothing else: the same clips, pushed along.
769 let video_after = session.lane_clips(Lane::V1).to_vec();
770 assert_eq!(video_after.len(), video_before.len(), "no clip on V1");
771 for (after, before) in video_after.iter().zip(&video_before) {
772 assert_eq!(after.source, before.source);
773 assert_eq!(after.start, before.start + song.len());
774 }
775 // The audio lane is the one that gained it, at the playhead.
776 assert_eq!(session.lane_clips(Lane::A1).len(), 3);
777 assert_eq!(session.lane_clips(Lane::A1)[0].source, song.source);
778
779 // And the save that follows reopens -- which is what the video-lane clip
780 // used to cost ("file contains a box with a larger size than it").
781 let project = dir.join("pasted.edith");
782 session.save_project(&project).expect("save");
783 drop(session);
784 let reloaded = PlaybackSession::open_project(&project).expect("the save reopens");
785 reloaded.set_gain(0.0);
786 assert_eq!(reloaded.lane_clips(Lane::A1).len(), 3);
787 assert_eq!(reloaded.lane_clips(Lane::V1).len(), video_after.len());
788 let _ = std::fs::remove_dir_all(&dir);
789}
790
791/// A song muxed into an `.mp4` -- the extension names a film, the header names
792/// no picture. `open` falls to the audio-only door on the demuxer's own
793/// `NoVideoTrack` rather than refusing "no H.264, HEVC, VP9 or AV1 video track
794/// in file", exactly as it would have if the file had been named `.mp3`.
795#[test]
796fn an_audio_only_file_wearing_an_mp4_extension_still_opens() {
797 let session = open(asset("test_audio_only.mp4"));
798 assert!(
799 session.lane_clips(Lane::V1).is_empty(),
800 "no picture anywhere"
801 );
802 assert_eq!(session.lane_clips(Lane::A1).len(), 1);
803 assert!((session.timeline_duration() - 3.0).abs() < 0.1);
804}
805
806/// An MPEG audio stream wearing the *standard's* spelling -- `.mpeg`, what a
807/// voice note or a tagged download off the web is called -- with a JPEG cover
808/// muxed into its ID3v2 tag beside the sound. Two claims, and the first is the
809/// bug: the spelling has to reach the audio door at all (`is_audio`, and with
810/// it every lane decision and the import itself). While the extension list did
811/// not admit it the file fell through to the mp4 demuxer and the library door
812/// answered `IMPORT FAILED: <name> — file contains a box with a larger size
813/// than it`, this test's `import`/`open` failing in exactly those words. The
814/// second is that the cover is not mistaken for a picture: symphonia skips the
815/// ID3v2 tag, the file opens audio-only, and the tone decodes non-silent.
816#[test]
817fn an_mpeg_audio_file_with_a_cover_stream_opens_and_imports() {
818 let name = "test_tone_cover.mpeg";
819 let path = asset(name);
820 assert!(engine::is_audio(&path), "{name} is sound");
821
822 // The open door: a song *is* a timeline, and no cover stream puts a clip on
823 // the video lane.
824 let session = open(&path);
825 assert!(
826 session.lane_clips(Lane::V1).is_empty(),
827 "{name}: the cover is not a picture source"
828 );
829 assert_eq!(session.lane_clips(Lane::A1).len(), 1);
830 assert!((session.timeline_duration() - 3.0).abs() < 0.1, "{name}");
831 drop(session);
832
833 // The library door the message came from: an import into a session that
834 // already has a timeline.
835 let mut session = open(asset("test_tone.mp3"));
836 import_and_place(&mut session, &path);
837 drop(session);
838
839 let (rate, channels, samples) = decode(&path);
840 assert_eq!((rate, channels), (44100, 2), "{name}");
841 let secs = samples.len() as f64 / f64::from(rate) / f64::from(channels);
842 assert!((secs - 3.0).abs() < 0.1, "{name}: {secs:.3} s of audio");
843 let peak = samples.iter().fold(0.0f32, |m, s| m.max(s.abs()));
844 assert!(peak > 0.05, "{name}: decoded everything silent (peak {peak})");
845}
846
847/// The same fallback in [`PlaybackSession::open_project`]'s scaffold branch: a
848/// project whose first source is one of these files reloads instead of failing
849/// the open a save never had trouble with the first time.
850#[test]
851fn a_project_scaffolded_from_an_audio_only_mp4_reloads() {
852 let dir = Scratch::dir("ve_audio_only_mp4");
853 let mp4 = asset("test_audio_only.mp4");
854 let session = open(&mp4);
855 let project = dir.join("song_mp4.edith");
856 session.save_project(&project).expect("save");
857 drop(session);
858 let reloaded =
859 PlaybackSession::open_project(&project).expect("reload a project scaffolded from it");
860 reloaded.set_gain(0.0);
861 assert!(reloaded.lane_clips(Lane::V1).is_empty());
862 assert_eq!(reloaded.lane_clips(Lane::A1).len(), 1);
863 assert!((reloaded.timeline_duration() - 3.0).abs() < 0.1);
864 drop(reloaded);
865 let _ = std::fs::remove_dir_all(&dir);
866}
867
868/// DEBT #46: a mono source used to be refused outright by a stereo timeline
869/// ("audio 1 ch does not match the timeline's 2 ch") -- the only layout gate
870/// left after the 2026-08-12 convert-at-import work. It now up-mixes,
871/// [`engine::audio::widen`] duplicating the one channel into both of a stereo
872/// timeline's, mirroring the [`engine::audio::downmix`] a wider source already
873/// folds through at the decoder's door. Reverted to before that fix, this test
874/// fails at `import_and_place` itself: `place_stream_at` returns
875/// `Err("audio 1 ch does not match the timeline's 2 ch")` instead of landing
876/// the clip, because `widen` and the `audio_matches_probed` mono exception
877/// did not exist.
878#[test]
879fn a_mono_source_up_mixes_onto_a_stereo_timeline() {
880 let dir = Scratch::dir("ve_audio_upmix");
881 let mut session = open(asset("test_tone.mp3")); // a 3 s stereo timeline
882 // 44100 Hz, 1 ch AAC -- no rate to resample, only the layout in question.
883 import_and_place(&mut session, &asset("test_audio_only.mp4"));
884 assert_eq!(session.lane_clips(Lane::A1).len(), 2);
885 assert!((session.timeline_duration() - 6.0).abs() < 0.1);
886
887 let wav = dir.join("upmix.wav");
888 wait(&session.export_to_with(
889 &wav,
890 &ExportSettings {
891 format: Format::Wav,
892 ..ExportSettings::default()
893 },
894 ))
895 .expect("wav export of the up-mixed timeline");
896 let (rate, channels, samples) = decode(&wav);
897 assert_eq!((rate, channels), (44100, 2));
898
899 // Inside the mono clip's own span (the second half of the timeline): left
900 // and right must carry the identical signal `widen` duplicated, and it
901 // must not be silence -- a bug in `widen` could zero the buffer instead of
902 // filling it.
903 let start = (3.5 * f64::from(rate)) as usize;
904 let end = (5.5 * f64::from(rate)) as usize;
905 let mut peak = 0.0f32;
906 for frame in start..end {
907 let (l, r) = (samples[frame * 2], samples[frame * 2 + 1]);
908 assert!(
909 (l - r).abs() < 1e-6,
910 "frame {frame}: left {l} and right {r} must carry the up-mixed mono signal"
911 );
912 peak = peak.max(l.abs());
913 }
914 assert!(peak > 0.01, "the up-mixed span is silent: peak {peak}");
915 let _ = std::fs::remove_dir_all(&dir);
916}
917
918/// The major brand of `path`, read off its `ftyp` box: what a player picks a
919/// parser by, and the one thing an `.m4a` and an `.mp4` of the same sound differ in.
920fn major_brand(path: &Path) -> String {
921 let bytes = std::fs::read(path).expect("read the export");
922 assert_eq!(&bytes[4..8], b"ftyp", "{} opens with no ftyp box", path.display());
923 String::from_utf8_lossy(&bytes[8..12]).into_owned()
924}
925
926/// ffprobe's `entries` for every stream of `path`, one line per stream, fields
927/// comma-separated.
928fn probe_lines(path: &Path, entries: &str) -> Vec<String> {
929 let output = std::process::Command::new("ffprobe")
930 .args(["-v", "error", "-show_entries", entries, "-of", "csv=p=0"])
931 .arg(path)
932 .output()
933 .expect("run ffprobe");
934 assert!(output.status.success(), "ffprobe failed on {}", path.display());
935 String::from_utf8_lossy(&output.stdout)
936 .lines()
937 .filter(|line| !line.is_empty())
938 .map(str::to_owned)
939 .collect()
940}
941
942/// The sound-alone mp4 and the `.m4a` are the same file in every way but the
943/// brand: one AAC stream, the length of the tone, and no picture.
944fn assert_sound_alone_aac(path: &Path, brand: &str) {
945 assert_eq!(major_brand(path), brand, "{}: the major brand", path.display());
946 assert_eq!(
947 probe_lines(path, "stream=codec_name,codec_type"),
948 vec!["aac,audio".to_string()],
949 "{}: one AAC stream and no picture",
950 path.display()
951 );
952 let secs: f64 = probe_lines(path, "format=duration")[0]
953 .parse()
954 .expect("a duration in seconds");
955 assert!(
956 (secs - 3.0).abs() < 0.05,
957 "{}: {secs:.4} s of sound for a 3 s tone",
958 path.display()
959 );
960}
961
962/// An `.m4a` export of a song is one AAC track under the `M4A ` brand, as long as
963/// the song.
964#[test]
965fn an_m4a_export_is_one_aac_stream_under_the_m4a_brand() {
966 let dir = Scratch::dir("ve_m4a_export");
967 let session = open(asset("test_tone.mp3"));
968 let out = dir.join("tone.m4a");
969 wait(&session.export_to_with(
970 &out,
971 &ExportSettings {
972 format: Format::M4a,
973 ..ExportSettings::default()
974 },
975 ))
976 .expect("m4a export of an audio-only timeline");
977 assert_sound_alone_aac(&out, "M4A ");
978}
979
980/// The same timeline as an `.mp4` is the same AAC track under the plain `isom`
981/// brand: the sound alone, where a picture-less timeline used to be refused.
982#[test]
983fn an_audio_only_mp4_is_the_same_aac_under_an_mp4_brand() {
984 let dir = Scratch::dir("ve_mp4_audio_only");
985 let session = open(asset("test_tone.mp3"));
986 let out = dir.join("tone.mp4");
987 wait(&session.export_to_with(
988 &out,
989 &ExportSettings {
990 format: Format::Mp4,
991 ..ExportSettings::default()
992 },
993 ))
994 .expect("mp4 export of an audio-only timeline");
995 assert_sound_alone_aac(&out, "isom");
996}