forge
Explore
Log in

Don't you dare go Hollow

Create a waveform visualizer as a video clip

Browse files at this commit

735b90e538d6281fd382405bc5aa3e57780553c5Ahmet Kaan GümüşParent: 5cd971b
  • feat
    • create a waveform visualizer as a video clip
Show full message
✨ feat(audio): create a waveform visualizer as a video clip

Select an audio clip and press h (or the clip menu). The sound's envelope
is painted as a sliding mirrored waveform onto a video lane, so preview
and export both show it. Paste still never drops a song on V1.
crates/app/src/keymap.rsmodified+15 -3
@@ -159,6 +159,9 @@ actions! {
159 Equalizer,159 Equalizer,
160 Speed,160 Speed,
161 Silence,161 Silence,
162+ /// Paints a sliding waveform of this audio clip onto a video lane, so the
163+ /// sound is a picture on the same timeline — preview and export both.
164+ Visualizer,
162 /// Crossfades the selected audio clip into its neighbour ([`Project::crossfade`]):165 /// Crossfades the selected audio clip into its neighbour ([`Project::crossfade`]):
163 /// two adjacent clips picked on one lane, or a single pick faded into the166 /// two adjacent clips picked on one lane, or a single pick faded into the
164 /// clip right after it.167 /// clip right after it.
@@ -302,6 +305,7 @@ impl ActionId {
302 ActionId::Equalizer => "Equalizer",305 ActionId::Equalizer => "Equalizer",
303 ActionId::Speed => "Speed…",306 ActionId::Speed => "Speed…",
304 ActionId::Silence => "Silences…",307 ActionId::Silence => "Silences…",
308+ ActionId::Visualizer => "Create visualizer",
305 ActionId::Crossfade => "Crossfade to next",309 ActionId::Crossfade => "Crossfade to next",
306 ActionId::TrimIn => "Trim in",310 ActionId::TrimIn => "Trim in",
307 ActionId::TrimOut => "Trim out",311 ActionId::TrimOut => "Trim out",
@@ -385,6 +389,7 @@ impl ActionId {
385 ActionId::Equalizer => "equalizer",389 ActionId::Equalizer => "equalizer",
386 ActionId::Speed => "speed",390 ActionId::Speed => "speed",
387 ActionId::Silence => "silence",391 ActionId::Silence => "silence",
392+ ActionId::Visualizer => "visualizer",
388 ActionId::Crossfade => "crossfade",393 ActionId::Crossfade => "crossfade",
389 ActionId::TrimIn => "trim-in",394 ActionId::TrimIn => "trim-in",
390 ActionId::TrimOut => "trim-out",395 ActionId::TrimOut => "trim-out",
@@ -454,6 +459,7 @@ impl ActionId {
454 // timeline the clip is on -- it is a clip card like the three459 // timeline the clip is on -- it is a clip card like the three
455 // above it, opened on whichever half was picked.460 // above it, opened on whichever half was picked.
456 | ActionId::Silence461 | ActionId::Silence
462+ | ActionId::Visualizer
457 | ActionId::Crossfade463 | ActionId::Crossfade
458 | ActionId::TrimIn464 | ActionId::TrimIn
459 | ActionId::TrimOut465 | ActionId::TrimOut
@@ -1112,6 +1118,8 @@ impl Keymap {
1112 // delete (x and delete) -- what it opens is a card that can cut1118 // delete (x and delete) -- what it opens is a card that can cut
1113 // forty places at once.1119 // forty places at once.
1114 b(ActionId::Silence, "u", false),1120 b(ActionId::Silence, "u", false),
1121+ // Waveform-as-video: `h` was free (Theme is ctrl+h, Screenshot is w).
1122+ b(ActionId::Visualizer, "h", false),
1115 // Crossfade takes ctrl+f: the mnemonic letter for "fade", with1123 // Crossfade takes ctrl+f: the mnemonic letter for "fade", with
1116 // ctrl its own room now that plain "f" is the mix card's own1124 // ctrl its own room now that plain "f" is the mix card's own
1117 // (below) -- the same letter, the modifier telling them apart.1125 // (below) -- the same letter, the modifier telling them apart.
@@ -1425,7 +1433,7 @@ fn parse(text: &str) -> Result<(Keymap, Vec<String>), String> {
1425 mod tests {1433 mod tests {
1426 use engine::scratch::Scratch;1434 use engine::scratch::Scratch;
1427 1435
1428- use super::{ActionId, Chord, Keymap, config_path_in, emit, parse};1436+ use super::{config_path_in, emit, parse, ActionId, Chord, Keymap};
1429 1437
1430 fn chord(key: &str, ctrl: bool) -> Chord {1438 fn chord(key: &str, ctrl: bool) -> Chord {
1431 Chord {1439 Chord {
@@ -1445,7 +1453,7 @@ mod tests {
1445 #[test]1453 #[test]
1446 fn every_default_stroke_reaches_its_action() {1454 fn every_default_stroke_reaches_its_action() {
1447 let k = Keymap::defaults();1455 let k = Keymap::defaults();
1448- assert_eq!(k.entries().len(), 78);1456+ assert_eq!(k.entries().len(), 79);
1449 // The cut odometer: bare walks one, `<`/`>` (what shift+,/shift+.1457 // The cut odometer: bare walks one, `<`/`>` (what shift+,/shift+.
1450 // actually type) strides ten.1458 // actually type) strides ten.
1451 assert_eq!(k.lookup(".", false), Some(ActionId::WalkCutNext));1459 assert_eq!(k.lookup(".", false), Some(ActionId::WalkCutNext));
@@ -1468,6 +1476,7 @@ mod tests {
1468 assert_eq!(k.lookup("l", true), Some(ActionId::PasteFilePath));1476 assert_eq!(k.lookup("l", true), Some(ActionId::PasteFilePath));
1469 assert_eq!(k.lookup("?", false), Some(ActionId::ShowActions));1477 assert_eq!(k.lookup("?", false), Some(ActionId::ShowActions));
1470 assert_eq!(k.lookup("h", true), Some(ActionId::Theme));1478 assert_eq!(k.lookup("h", true), Some(ActionId::Theme));
1479+ assert_eq!(k.lookup("h", false), Some(ActionId::Visualizer));
1471 assert_eq!(k.lookup("space", false), Some(ActionId::Play));1480 assert_eq!(k.lookup("space", false), Some(ActionId::Play));
1472 // The seek keys: bare arrows a frame, ctrl arrows a second, and the two1481 // The seek keys: bare arrows a frame, ctrl arrows a second, and the two
1473 // ends of the timeline.1482 // ends of the timeline.
@@ -1699,7 +1708,10 @@ mod tests {
1699 let label = action.label();1708 let label = action.label();
1700 let words = label.split_whitespace().count();1709 let words = label.split_whitespace().count();
1701 assert!(words <= 4, "{action:?}: {words} words -- {label:?}");1710 assert!(words <= 4, "{action:?}: {words} words -- {label:?}");
1702- assert!(!label.contains('('), "{action:?}: a parenthesis -- {label:?}");1711+ assert!(
1712+ !label.contains('('),
1713+ "{action:?}: a parenthesis -- {label:?}"
1714+ );
1703 assert!(1715 assert!(
1704 !label.to_lowercase().starts_with("the "),1716 !label.to_lowercase().starts_with("the "),
1705 "{action:?}: leads with an article -- {label:?}"1717 "{action:?}: leads with an article -- {label:?}"
crates/app/src/menus.rsmodified+2 -2
@@ -211,7 +211,7 @@ impl RowItem {
211 /// action a stroke already reaches -- the menu is a second way *to* the actions211 /// action a stroke already reaches -- the menu is a second way *to* the actions
212 /// and never a second version of them -- so both the label and the hint come212 /// and never a second version of them -- so both the label and the hint come
213 /// out of the keymap registry and the two can never disagree.213 /// out of the keymap registry and the two can never disagree.
214-pub(crate) const MENU_ITEMS: [ActionId; 16] = [214+pub(crate) const MENU_ITEMS: [ActionId; 17] = [
215 ActionId::Cut,215 ActionId::Cut,
216 // The cut machinery (DESIGN.md §6) on the very clip it is about: the216 // The cut machinery (DESIGN.md §6) on the very clip it is about: the
217 // trims and the loop-trim were strokes the spine rail listed and nothing217 // trims and the loop-trim were strokes the spine rail listed and nothing
@@ -239,6 +239,7 @@ pub(crate) const MENU_ITEMS: [ActionId; 16] = [
239 // ...and the sound ones, the same class refusal the other way round.239 // ...and the sound ones, the same class refusal the other way round.
240 ActionId::Equalizer,240 ActionId::Equalizer,
241 ActionId::Silence,241 ActionId::Silence,
242+ ActionId::Visualizer,
242 ActionId::Speed,243 ActionId::Speed,
243 ActionId::Fit,244 ActionId::Fit,
244 // Last, under the rule line the render draws before the first of them245 // Last, under the rule line the render draws before the first of them
@@ -311,7 +312,6 @@ pub(crate) fn destructive(action: ActionId) -> bool {
311 )312 )
312 }313 }
313 314
314-
315 /// One row of the actions card, in the order it lists them: a heading, then315 /// One row of the actions card, in the order it lists them: a heading, then
316 /// every action the registry files under it, then the strokes the modal cards316 /// every action the registry files under it, then the strokes the modal cards
317 /// answer themselves.317 /// answer themselves.
crates/app/src/oracle.rsmodified+16 -8
@@ -222,11 +222,14 @@ pub(crate) fn enable(action: ActionId, ctx: Ctx) -> Enable {
222 // policy is a picture setting for the same reason.222 // policy is a picture setting for the same reason.
223 // The dissolve is the picture join and the crossfade's mirror: two223 // The dissolve is the picture join and the crossfade's mirror: two
224 // pictures cross, and there is no picture on a waveform to cross.224 // pictures cross, and there is no picture on a waveform to cross.
225- ActionId::Color | ActionId::Fit | ActionId::Transform | ActionId::Dissolve => match ctx.clip225+ ActionId::Color | ActionId::Fit | ActionId::Transform | ActionId::Dissolve => {
226- {226+ match ctx.clip {
227- Some((_, lane)) if lane.kind != LaneKind::Video => Enable::Hidden("this clip is sound"),227+ Some((_, lane)) if lane.kind != LaneKind::Video => {
228- _ => Enable::Yes,228+ Enable::Hidden("this clip is sound")
229- },229+ }
230+ _ => Enable::Yes,
231+ }
232+ }
230 // The scan reads samples, and a still has none -- ever, unlike a video233 // The scan reads samples, and a still has none -- ever, unlike a video
231 // clip whose sound may be one lane down or simply silent. Exactly what234 // clip whose sound may be one lane down or simply silent. Exactly what
232 // `unscannable` says after the fact, said before the row is drawn so235 // `unscannable` says after the fact, said before the row is drawn so
@@ -234,6 +237,13 @@ pub(crate) fn enable(action: ActionId, ctx: Ctx) -> Enable {
234 // same class refusal over the same clip: nothing to mix for a picture237 // same class refusal over the same clip: nothing to mix for a picture
235 // with no sound at all.238 // with no sound at all.
236 ActionId::Silence | ActionId::Mix if ctx.image => Enable::Hidden("this clip is a still"),239 ActionId::Silence | ActionId::Mix if ctx.image => Enable::Hidden("this clip is a still"),
240+ ActionId::Visualizer if ctx.image => Enable::Hidden("this clip is a still"),
241+ ActionId::Visualizer if ctx.no_sound => Enable::Hidden("this clip has no sound"),
242+ ActionId::Visualizer => match ctx.clip {
243+ Some((_, lane)) if lane.kind == LaneKind::Audio => Enable::Yes,
244+ Some(_) => Enable::Hidden("this clip is picture"),
245+ None => Enable::No("select an audio clip"),
246+ },
237 ActionId::Silence | ActionId::Mix if ctx.no_sound => {247 ActionId::Silence | ActionId::Mix if ctx.no_sound => {
238 Enable::Hidden("this clip has no sound")248 Enable::Hidden("this clip has no sound")
239 }249 }
@@ -339,9 +349,7 @@ pub(crate) fn enable(action: ActionId, ctx: Ctx) -> Enable {
339 // A clock started against an empty timeline is a clock counting349 // A clock started against an empty timeline is a clock counting
340 // nothing: the transport says so by being dim, which is what its own350 // nothing: the transport says so by being dim, which is what its own
341 // ad-hoc boolean used to say before the oracle knew the question.351 // ad-hoc boolean used to say before the oracle knew the question.
342- ActionId::Play | ActionId::Loop if !ctx.playable => {352+ ActionId::Play | ActionId::Loop if !ctx.playable => Enable::No("the timeline is empty"),
343- Enable::No("the timeline is empty")
344- }
345 // A rate applies to a clip of either kind and to its whole group, so353 // A rate applies to a clip of either kind and to its whole group, so
346 // there is no lane it means nothing on, and the engine words the one354 // there is no lane it means nothing on, and the engine words the one
347 // refusal there is (no room). Everything else is the editor's own and355 // refusal there is (no room). Everything else is the editor's own and
crates/app/src/player/actions.rsmodified+2 -0
@@ -55,6 +55,7 @@ impl Player {
55 | ActionId::ImportSubtitles55 | ActionId::ImportSubtitles
56 | ActionId::Crossfade56 | ActionId::Crossfade
57 | ActionId::Dissolve57 | ActionId::Dissolve
58+ | ActionId::Visualizer
58 ) {59 ) {
59 self.mark_dirty();60 self.mark_dirty();
60 }61 }
@@ -144,6 +145,7 @@ impl Player {
144 ActionId::Equalizer => self.open_eq(cx),145 ActionId::Equalizer => self.open_eq(cx),
145 ActionId::Speed => self.open_speed(cx),146 ActionId::Speed => self.open_speed(cx),
146 ActionId::Silence => self.open_silence(cx),147 ActionId::Silence => self.open_silence(cx),
148+ ActionId::Visualizer => self.create_visualizer(cx),
147 ActionId::Mix => self.open_mix(None, cx),149 ActionId::Mix => self.open_mix(None, cx),
148 ActionId::SubtitleStyle => self.open_subtitle_style(cx),150 ActionId::SubtitleStyle => self.open_subtitle_style(cx),
149 ActionId::ToggleSnap => self.toggle_snap(cx),151 ActionId::ToggleSnap => self.toggle_snap(cx),
crates/app/src/player/library.rsmodified+61 -0
@@ -133,6 +133,67 @@ impl Player {
133 cx.notify();133 cx.notify();
134 }134 }
135 135
136+ /// Paints a sliding waveform of the marked audio clip onto a video lane.
137+ /// Same implementation the clip menu and the `h` stroke both reach.
138+ pub(crate) fn create_visualizer(&mut self, cx: &mut Context<Self>) {
139+ if self.exporting().is_some() {
140+ return;
141+ }
142+ let Some((lane, idx)) = self.selected.anchor() else {
143+ self.notify_user("NO VISUALIZER — select an audio clip".into());
144+ cx.notify();
145+ return;
146+ };
147+ let placed = match &mut self.session {
148+ None => {
149+ self.notify_user("NO VISUALIZER — no file open".into());
150+ cx.notify();
151+ return;
152+ }
153+ Some(session) => {
154+ if lane.kind != LaneKind::Audio {
155+ self.notify_user("NO VISUALIZER — select an audio clip".into());
156+ cx.notify();
157+ return;
158+ }
159+ let Some(clip) = session.lane_clips(lane).get(idx).copied() else {
160+ self.notify_user("NO VISUALIZER — select an audio clip".into());
161+ cx.notify();
162+ return;
163+ };
164+ let Some(src) = session.sources().get(clip.source).cloned() else {
165+ self.notify_user("NO VISUALIZER — that clip has no source".into());
166+ cx.notify();
167+ return;
168+ };
169+ if !engine::is_audio(&src.path) {
170+ self.notify_user("NO VISUALIZER — this clip is not a sound file".into());
171+ cx.notify();
172+ return;
173+ }
174+ session.place_visualizer(
175+ clip.start,
176+ &src.path,
177+ src.audio_stream,
178+ clip.in_frame,
179+ clip.out_frame,
180+ None,
181+ )
182+ }
183+ };
184+ match placed {
185+ Ok(true) => {
186+ self.notify_user("VISUALIZER ADDED".into());
187+ self.reset_after_reseek();
188+ }
189+ Err(e) => self.notify_user(format!("NO VISUALIZER — {e}").into()),
190+ Ok(false) => {
191+ self.notify_user("NO VISUALIZER — that clip could not be placed".into())
192+ }
193+ }
194+ cx.notify();
195+ }
196+
136 /// Takes a library row's file out of the list, which is the one thing a row197 /// Takes a library row's file out of the list, which is the one thing a row
137 /// can lose. Refused in the engine's own words while clips still play from198 /// can lose. Refused in the engine's own words while clips still play from
138 /// it -- and those words name the lanes holding them, so the refusal says199 /// it -- and those words name the lanes holding them, so the refusal says
crates/app/src/tests/editing.rsmodified+3 -0
@@ -753,11 +753,13 @@ fn the_clip_menu_dims_what_the_playhead_is_not_on_and_stays_in_the_window() {
753 assert!(!sound.contains(&ActionId::Fit), "{sound:?}");753 assert!(!sound.contains(&ActionId::Fit), "{sound:?}");
754 assert!(sound.contains(&ActionId::Equalizer));754 assert!(sound.contains(&ActionId::Equalizer));
755 assert!(sound.contains(&ActionId::Silence));755 assert!(sound.contains(&ActionId::Silence));
756+ assert!(sound.contains(&ActionId::Visualizer));
756 // Picture: the mirror of it. The sound of a take is the audio lane's,757 // Picture: the mirror of it. The sound of a take is the audio lane's,
757 // clip for clip, so the equalizer is not this clip's business -- but the758 // clip for clip, so the equalizer is not this clip's business -- but the
758 // silence scan is, because it opens on the half it is grouped with.759 // silence scan is, because it opens on the half it is grouped with.
759 let picture = menu(v1, false, 60);760 let picture = menu(v1, false, 60);
760 assert!(!picture.contains(&ActionId::Equalizer), "{picture:?}");761 assert!(!picture.contains(&ActionId::Equalizer), "{picture:?}");
762+ assert!(!picture.contains(&ActionId::Visualizer), "{picture:?}");
761 assert!(picture.contains(&ActionId::Color));763 assert!(picture.contains(&ActionId::Color));
762 assert!(picture.contains(&ActionId::Fit));764 assert!(picture.contains(&ActionId::Fit));
763 assert!(picture.contains(&ActionId::Silence));765 assert!(picture.contains(&ActionId::Silence));
@@ -766,6 +768,7 @@ fn the_clip_menu_dims_what_the_playhead_is_not_on_and_stays_in_the_window() {
766 // rewrite), scanned like none.768 // rewrite), scanned like none.
767 let still = menu(v1, true, 60);769 let still = menu(v1, true, 60);
768 assert!(!still.contains(&ActionId::Silence), "{still:?}");770 assert!(!still.contains(&ActionId::Silence), "{still:?}");
771+ assert!(!still.contains(&ActionId::Visualizer), "{still:?}");
769 assert!(!still.contains(&ActionId::Equalizer), "{still:?}");772 assert!(!still.contains(&ActionId::Equalizer), "{still:?}");
770 assert!(still.contains(&ActionId::Color));773 assert!(still.contains(&ActionId::Color));
771 assert!(still.contains(&ActionId::Fit));774 assert!(still.contains(&ActionId::Fit));
crates/engine/src/decode.rsmodified+176 -0
@@ -55,6 +55,9 @@ pub enum Backend {
55 Still,55 Still,
56 /// A gap: black frames, nothing decoded at all.56 /// A gap: black frames, nothing decoded at all.
57 Gap,57 Gap,
58+ /// A waveform visualizer: the picture is painted from the audio's peaks
59+ /// ([`visualizer_i420`]), no decoder seat and no stream of pictures at all.
60+ Visualizer,
58 }61 }
59 62
60 impl Backend {63 impl Backend {
@@ -66,6 +69,7 @@ impl Backend {
66 Self::Software => "SW",69 Self::Software => "SW",
67 Self::Still => "still",70 Self::Still => "still",
68 Self::Gap => "gap",71 Self::Gap => "gap",
72+ Self::Visualizer => "viz",
69 }73 }
70 }74 }
71 75
@@ -76,6 +80,7 @@ impl Backend {
76 Self::Software => 2,80 Self::Software => 2,
77 Self::Still => 3,81 Self::Still => 3,
78 Self::Gap => 4,82 Self::Gap => 4,
83+ Self::Visualizer => 5,
79 }84 }
80 }85 }
81 86
@@ -85,6 +90,7 @@ impl Backend {
85 2 => Self::Software,90 2 => Self::Software,
86 3 => Self::Still,91 3 => Self::Still,
87 4 => Self::Gap,92 4 => Self::Gap,
93+ 5 => Self::Visualizer,
88 _ => Self::Opening,94 _ => Self::Opening,
89 }95 }
90 }96 }
@@ -601,6 +607,96 @@ impl DecodeSession {
601 })607 })
602 }608 }
603 609
610+ /// A worker for an audio file played as a *picture* ([`crate::is_audio`]):
611+ /// the file's peaks are decoded **once** on the worker, and every picture
612+ /// after that is painted -- a sliding mirrored waveform
613+ /// ([`visualizer_i420`]) at the canvas's own size, then graded, placed and
614+ /// converted exactly like a decoded picture, so a grade, a transform and a
615+ /// fit policy reach it the way they reach anything else on the timeline.
616+ ///
617+ /// `start_frame` and `len` are the file's own frames at `fps` -- which for
618+ /// an audio source are also the timeline's
619+ /// ([`crate::project::Rate::REAL_TIME`]) -- so `Frame::index` runs
620+ /// `start_frame ..` like a decoder's output and a speed reaches it through
621+ /// the same rewrite as any other clip.
622+ pub(crate) fn open_visualizer(
623+ path: &Path,
624+ stream: usize,
625+ start_frame: u32,
626+ len: u32,
627+ fps: f64,
628+ color: ColorParams,
629+ transform: TransformParams,
630+ canvas: Composer,
631+ ) -> crate::Result<FrameStream> {
632+ let (tx, rx) = sync_channel(2);
633+ let cancel = Arc::new(AtomicBool::new(false));
634+ if len == 0 {
635+ return Ok(FrameStream {
636+ frames: rx,
637+ worker: Worker {
638+ cancel,
639+ handle: None,
640+ reuse: None,
641+ },
642+ backend: BackendCell::new(Backend::Visualizer),
643+ });
644+ }
645+ // Painted at the canvas's own size, so the composite places nothing:
646+ // the picture *is* the canvas, and whatever transform the clip
647+ // carries still reaches it through the render below.
648+ let (width, height) = canvas.dims();
649+ let worker_cancel = Arc::clone(&cancel);
650+ let path = path.to_path_buf();
651+ let handle = thread::Builder::new()
652+ .name("viz".into())
653+ .spawn(move || {
654+ // The one decode this seat ever does: the whole envelope,
655+ // off the render thread, and abandoned at once if the caller
656+ // is already gone. A file that will not open -- and one with
657+ // no track at all -- paints the flat line, which is what its
658+ // silence looks like anyway: a visualizer frame always
659+ // exists, and is never worth failing a span over.
660+ let peaks = crate::waveform::peaks(&path, stream, VIZ_BUCKETS_PER_SEC)
661+ .ok()
662+ .flatten()
663+ .unwrap_or_default();
664+ if worker_cancel.load(Ordering::Relaxed) {
665+ return;
666+ }
667+ let fps = if fps.is_finite() && fps > 0.0 { fps } else { 30.0 };
668+ let mut render = Render::new(
669+ color,
670+ transform,
671+ ColorDescription::default(),
672+ canvas,
673+ tonemap::Preset::default(),
674+ None,
675+ );
676+ for index in 0..len {
677+ if worker_cancel.load(Ordering::Relaxed) {
678+ return;
679+ }
680+ let t = f64::from(start_frame + index) / fps;
681+ let (y, u, v) = visualizer_i420(&peaks, t, width, height);
682+ let frame = render.frame(start_frame + index, &y, &u, &v, width, height);
683+ if tx.send(frame).is_err() {
684+ return; // caller moved on
685+ }
686+ }
687+ })
688+ .ok();
689+ Ok(FrameStream {
690+ frames: rx,
691+ worker: Worker {
692+ cancel,
693+ handle,
694+ reuse: None,
695+ },
696+ backend: BackendCell::new(Backend::Visualizer),
697+ })
698+ }
699+
604 /// As [`DecodeSession::open_range`], but the caller gets the whole700 /// As [`DecodeSession::open_range`], but the caller gets the whole
605 /// [`Worker`] and can therefore *wait* for it, and the range is graded by701 /// [`Worker`] and can therefore *wait* for it, and the range is graded by
606 /// `color` -- the clip's own setting, folded into the conversion the frames702 /// `color` -- the clip's own setting, folded into the conversion the frames
@@ -1308,6 +1404,86 @@ fn rgb_to_i420(rgb: &[u8], width: usize, height: usize) -> (Vec<u8>, Vec<u8>, Ve
1308 (y, u, v)1404 (y, u, v)
1309 }1405 }
1310 1406
1407+/// Peak buckets per second the visualizer paints from, shared by the one
1408+/// caller that decodes them ([`DecodeSession::open_visualizer`], preview and
1409+/// export both) and the painter that reads them.
1410+pub(crate) const VIZ_BUCKETS_PER_SEC: u32 = 60;
1411+
1412+/// How much sound one visualizer frame shows, centered on the frame's own
1413+/// time: two seconds, so a glance reads the shape of the around-now rather
1414+/// than the whole file squeezed into one picture.
1415+const VIZ_WINDOW_SECS: f64 = 2.0;
1416+
1417+/// One visualizer picture, painted straight into tightly packed I420 in the
1418+/// BT.601 limited range [`rgb_to_i420`] writes: dark (`16`, neutral chroma)
1419+/// with the waveform bright (`220`), so what turns it into pixels on a screen
1420+/// is the same conversion a still goes through.
1421+///
1422+/// The columns are a **sliding** window of [`VIZ_WINDOW_SECS`] centered on
1423+/// `t_secs`, mirrored around the vertical middle: the buckets' maxima reach
1424+/// up from the center line and their minima down, the standard symmetric
1425+/// envelope. `t_secs` outside the peaks -- and an empty envelope, silence
1426+/// included, whose buckets are `(0.0, 0.0)` -- paints the one-pixel center
1427+/// line: a visualizer frame always exists, whatever the sound did.
1428+pub(crate) fn visualizer_i420(
1429+ peaks: &[(f32, f32)],
1430+ t_secs: f64,
1431+ width: u32,
1432+ height: u32,
1433+) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
1434+ // Even dims, like every canvas this engine composes at: an odd caller is
1435+ // shaved rather than handed chroma math it did not ask about.
1436+ let width = width & !1;
1437+ let height = height & !1;
1438+ let (w, h) = (width as usize, height as usize);
1439+ let (cw, ch) = crate::scale::chroma_dims(w, h);
1440+ let mut y = vec![16u8; w * h];
1441+ let u = vec![128u8; cw * ch];
1442+ let v = vec![128u8; cw * ch];
1443+ let center = h / 2;
1444+ let duration = peaks.len() as f64 / f64::from(VIZ_BUCKETS_PER_SEC);
1445+ if peaks.is_empty() || !t_secs.is_finite() || !(0.0..=duration).contains(&t_secs) {
1446+ for col in 0..w {
1447+ y[center * w + col] = 220;
1448+ }
1449+ return (y, u, v);
1450+ }
1451+ let per_sec = f64::from(VIZ_BUCKETS_PER_SEC);
1452+ // The window, clamped to the peaks that exist: a frame near either end
1453+ // looks past the file's edge, and draws the part of the window that is
1454+ // real rather than padding it out.
1455+ let first = (((t_secs - VIZ_WINDOW_SECS / 2.0).max(0.0) * per_sec).floor() as usize)
1456+ .min(peaks.len() - 1);
1457+ let last = ((((t_secs + VIZ_WINDOW_SECS / 2.0).min(duration) * per_sec).ceil() as usize)
1458+ .clamp(first + 1, peaks.len()))
1459+ .min(peaks.len());
1460+ let span = (last - first) as f64;
1461+ let scale = center as f32;
1462+ for col in 0..w {
1463+ // The buckets this column draws: at least one, whatever the window's
1464+ // width is against the picture's -- a short clip stretches, a long
1465+ // one condenses, and neither leaves a column with nothing.
1466+ let b0 = first + (col as f64 * span / w as f64).floor() as usize;
1467+ let b1 = first
1468+ + (((col + 1) as f64 * span / w as f64).ceil() as usize)
1469+ .clamp(b0 - first + 1, last - first);
1470+ let (mut lo, mut hi) = (f32::INFINITY, f32::NEG_INFINITY);
1471+ for &(min, max) in &peaks[b0..b1] {
1472+ lo = lo.min(min);
1473+ hi = hi.max(max);
1474+ }
1475+ // Mirrored around the center: maxima up, minima down, silence a line.
1476+ let top = (scale - hi * scale).round();
1477+ let bottom = (scale - lo * scale).round();
1478+ let top = (top as isize).clamp(0, h as isize - 1) as usize;
1479+ let bottom = (bottom as isize).clamp(top as isize, h as isize - 1) as usize;
1480+ for row in top..=bottom {
1481+ y[row * w + col] = 220;
1482+ }
1483+ }
1484+ (y, u, v)
1485+}
1486+
1311 /// `None` when the software path must be used: forced by `VE_SW=1`, or the1487 /// `None` when the software path must be used: forced by `VE_SW=1`, or the
1312 /// plugin is absent/broken/unable to open this particular file.1488 /// plugin is absent/broken/unable to open this particular file.
1313 fn open_hw(path: &Path, start_frame: u32) -> Option<HwSession> {1489 fn open_hw(path: &Path, start_frame: u32) -> Option<HwSession> {
crates/engine/src/export.rsmodified+79 -11
@@ -2760,7 +2760,18 @@ fn run(
2760 let want = untouched.then(|| encoder.dma_want(meta)).flatten();2760 let want = untouched.then(|| encoder.dma_want(meta)).flatten();
2761 // Opened at the file's own frame, which is the only place the2761 // Opened at the file's own frame, which is the only place the
2762 // file's numbering is used -- the span's are the timeline's.2762 // file's numbering is used -- the span's are the timeline's.
2763- let pictures = ClipDecoder::open(&entry.path, rate.source_at(in_frame), want)?;2763+ let pictures = if crate::is_audio(&entry.path) {
2764+ ClipDecoder::visualizer(
2765+ &entry.path,
2766+ entry.audio_stream,
2767+ rate.source_at(in_frame),
2768+ meta.width,
2769+ meta.height,
2770+ meta.frame_rate,
2771+ )?
2772+ } else {
2773+ ClipDecoder::open(&entry.path, rate.source_at(in_frame), want)?
2774+ };
2764 (Some(pictures), rate, in_frame, Some(color), mapper)2775 (Some(pictures), rate, in_frame, Some(color), mapper)
2765 }2776 }
2766 // A gap's black is 16/128/128, which is black in every matrix here2777 // A gap's black is 16/128/128, which is black in every matrix here
@@ -2815,7 +2826,18 @@ fn run(
2815 Ok(Dissolve {2826 Ok(Dissolve {
2816 window,2827 window,
2817 tail_start: span.len - window,2828 tail_start: span.len - window,
2818- decoder: ClipDecoder::open(&entry.path, b_rate.source_at(b_in_frame), None)?,2829+ decoder: if crate::is_audio(&entry.path) {
2830+ ClipDecoder::visualizer(
2831+ &entry.path,
2832+ entry.audio_stream,
2833+ b_rate.source_at(b_in_frame),
2834+ meta.width,
2835+ meta.height,
2836+ meta.frame_rate,
2837+ )?
2838+ } else {
2839+ ClipDecoder::open(&entry.path, b_rate.source_at(b_in_frame), None)?
2840+ },
2819 mapper: b_mapper,2841 mapper: b_mapper,
2820 remap: b_remap,2842 remap: b_remap,
2821 grade: project.composite_color_at(b_start).copied(),2843 grade: project.composite_color_at(b_start).copied(),
@@ -4388,6 +4410,18 @@ enum ClipDecoder {
4388 /// other two are opened there -- the span's pictures come from one place,4410 /// other two are opened there -- the span's pictures come from one place,
4389 /// and no thread can make one picture arrive sooner.4411 /// and no thread can make one picture arrive sooner.
4390 Still(crate::decode::Still),4412 Still(crate::decode::Still),
4413+ /// An audio file playing as a picture: each `next` paints one visualizer
4414+ /// frame from peaks already decoded ([`crate::decode::visualizer_i420`]).
4415+ Visualizer {
4416+ peaks: Vec<(f32, f32)>,
4417+ width: u32,
4418+ height: u32,
4419+ fps: f64,
4420+ next: u32,
4421+ y: Vec<u8>,
4422+ u: Vec<u8>,
4423+ v: Vec<u8>,
4424+ },
4391 }4425 }
4392 4426
4393 /// The receiving half of a decode thread, plus the picture it last handed out4427 /// The receiving half of a decode thread, plus the picture it last handed out
@@ -4489,6 +4523,31 @@ impl ClipDecoder {
4489 }))4523 }))
4490 }4524 }
4491 4525
4526+ fn visualizer(
4527+ path: &Path,
4528+ stream: usize,
4529+ start_frame: u32,
4530+ width: u32,
4531+ height: u32,
4532+ fps: f64,
4533+ ) -> crate::Result<Self> {
4534+ let peaks = crate::waveform::peaks(path, stream, crate::decode::VIZ_BUCKETS_PER_SEC)
4535+ .ok()
4536+ .flatten()
4537+ .unwrap_or_default();
4538+ let fps = if fps.is_finite() && fps > 0.0 { fps } else { 30.0 };
4539+ Ok(Self::Visualizer {
4540+ peaks,
4541+ width,
4542+ height,
4543+ fps,
4544+ next: start_frame,
4545+ y: Vec::new(),
4546+ u: Vec::new(),
4547+ v: Vec::new(),
4548+ })
4549+ }
4550+
4492 /// The next picture, borrowed until the call after -- as tightly packed4551 /// The next picture, borrowed until the call after -- as tightly packed
4493 /// I420, or as the GPU buffer the decoder wrote it into.4552 /// I420, or as the GPU buffer the decoder wrote it into.
4494 fn next(&mut self) -> crate::Result<Option<Frame<'_>>> {4553 fn next(&mut self) -> crate::Result<Option<Frame<'_>>> {
@@ -4497,6 +4556,24 @@ impl ClipDecoder {
4497 let (y, u, v, width, height) = still.picture();4556 let (y, u, v, width, height) = still.picture();
4498 Ok(Some(Frame::Pixels(y, u, v, width, height)))4557 Ok(Some(Frame::Pixels(y, u, v, width, height)))
4499 }4558 }
4559+ Self::Visualizer {
4560+ peaks,
4561+ width,
4562+ height,
4563+ fps,
4564+ next,
4565+ y,
4566+ u,
4567+ v,
4568+ } => {
4569+ let (yy, uu, vv) =
4570+ crate::decode::visualizer_i420(peaks, f64::from(*next) / *fps, *width, *height);
4571+ *y = yy;
4572+ *u = uu;
4573+ *v = vv;
4574+ *next += 1;
4575+ Ok(Some(Frame::Pixels(y, u, v, *width & !1, *height & !1)))
4576+ }
4500 Self::Streamed(stream) if stream.ended => Ok(None),4577 Self::Streamed(stream) if stream.ended => Ok(None),
4501 Self::Streamed(stream) => match stream.frames.recv() {4578 Self::Streamed(stream) => match stream.frames.recv() {
4502 Ok(Ok(Some(frame))) => Ok(Some(match stream.current.insert(frame) {4579 Ok(Ok(Some(frame))) => Ok(Some(match stream.current.insert(frame) {
@@ -4509,20 +4586,11 @@ impl ClipDecoder {
4509 } => Frame::Pixels(y, u, v, *width, *height),4586 } => Frame::Pixels(y, u, v, *width, *height),
4510 Yuv::Dma(dma) => Frame::Dma(dma),4587 Yuv::Dma(dma) => Frame::Dma(dma),
4511 })),4588 })),
4512- // The decoder said end of stream in as many words -- a source
4513- // shorter than the clip that names it, which the span loop ends
4514- // gracefully on.
4515 Ok(Ok(None)) => {4589 Ok(Ok(None)) => {
4516 stream.ended = true;4590 stream.ended = true;
4517 Ok(None)4591 Ok(None)
4518 }4592 }
4519 Ok(Err(e)) => Err(e),4593 Ok(Err(e)) => Err(e),
4520- // The channel went quiet without either: the thread panicked.
4521- // Read as end of stream that would truncate the export at this
4522- // frame and *report success*, which is the one outcome an
4523- // export must never have -- before the decode moved onto a
4524- // thread the same panic took the whole export down, and it
4525- // still does.
4526 Err(_) => Err("the decoder stopped without a picture or a reason".into()),4594 Err(_) => Err("the decoder stopped without a picture or a reason".into()),
4527 },4595 },
4528 }4596 }
crates/engine/src/playback.rsmodified+113 -15
@@ -1096,27 +1096,18 @@ impl PlaybackSession {
1096 counts.push(rate.timeline_at(other.frame_count));1096 counts.push(rate.timeline_at(other.frame_count));
1097 rates.push(rate);1097 rates.push(rate);
1098 }1098 }
1099- // The video lane can only play files that have pictures. Hand-written1099+ // A still is silent, so a clip playing one on an audio lane is a
1100- // (or hand-edited) project files are the one door this can come in1100+ // segment the audio worker would open a PNG for. Refused by name
1101- // through, so it is refused by name here rather than becoming a clip1101+ // here, which is the one door it can arrive through
1102- // that decodes to nothing.1102+ // (`place_stream_at` never puts one there). An audio file on a
1103+ // *video* lane used to be refused the same way; it plays as a
1104+ // waveform visualizer now ([`DecodeSession::open_visualizer`]).
1103 for (kind, clip) in doc1105 for (kind, clip) in doc
1104 .lanes1106 .lanes
1105 .iter()1107 .iter()
1106 .flat_map(|(kind, clips)| clips.iter().map(move |clip| (*kind, clip)))1108 .flat_map(|(kind, clips)| clips.iter().map(move |clip| (*kind, clip)))
1107 {1109 {
1108 let path = &doc.sources[clip.source].path;1110 let path = &doc.sources[clip.source].path;
1109- if kind == LaneKind::Video && crate::is_audio(path) {
1110- return Err(format!(
1111- "{} has no picture: it can only play on an audio lane",
1112- path.display()
1113- )
1114- .into());
1115- }
1116- // ...and the mirror of it: a still is silent, so a clip playing one
1117- // on an audio lane is a segment the audio worker would open a PNG
1118- // for. Refused by name here, which is the one door it can arrive
1119- // through (`place_stream_at` never puts one there).
1120 if kind == LaneKind::Audio && crate::is_image(path) {1111 if kind == LaneKind::Audio && crate::is_image(path) {
1121 return Err(format!(1112 return Err(format!(
1122 "{} is a still image: it can only play on a video lane",1113 "{} is a still image: it can only play on a video lane",
@@ -1840,6 +1831,39 @@ impl PlaybackSession {
1840 )1831 )
1841 .inspect_err(|e| eprintln!("timeline frame {start}: image open failed: {e}"))1832 .inspect_err(|e| eprintln!("timeline frame {start}: image open failed: {e}"))
1842 }1833 }
1834+ Some(Span {
1835+ start,
1836+ from: Some((source, in_frame)),
1837+ ..
1838+ }) if crate::is_audio(&self.project.sources()[source].path) => {
1839+ let (path, stream) = {
1840+ let src = &self.project.sources()[source];
1841+ (src.path.clone(), src.audio_stream)
1842+ };
1843+ DecodeSession::open_visualizer(
1844+ &path,
1845+ stream,
1846+ in_frame,
1847+ span.expect("matched above").source_len(),
1848+ self.meta.frame_rate,
1849+ self.project
1850+ .composite_color_at(start)
1851+ .copied()
1852+ .unwrap_or_default(),
1853+ self.project
1854+ .composite_transform_at(start)
1855+ .copied()
1856+ .unwrap_or_default(),
1857+ Composer::new(
1858+ self.meta.width,
1859+ self.meta.height,
1860+ self.project.composite_fit_at(start),
1861+ ),
1862+ )
1863+ .inspect_err(|e| {
1864+ eprintln!("timeline frame {start}: visualizer open failed: {e}")
1865+ })
1866+ }
1843 Some(Span {1867 Some(Span {
1844 start,1868 start,
1845 from: Some((source, in_frame)),1869 from: Some((source, in_frame)),
@@ -3234,6 +3258,80 @@ impl PlaybackSession {
3234 self.edit(Dirty::Both, |p| p.place(lane, at, clip))3258 self.edit(Dirty::Both, |p| p.place(lane, at, clip))
3235 }3259 }
3236 3260
3261+ /// Places a waveform-visualizer clip of `path`'s audio on a video lane.
3262+ /// The picture is painted from the sound ([`DecodeSession::open_visualizer`]);
3263+ /// this does not also put a copy on an audio lane.
3264+ pub fn place_visualizer(
3265+ &mut self,
3266+ start: u32,
3267+ path: &Path,
3268+ stream: usize,
3269+ in_frame: u32,
3270+ out_frame: u32,
3271+ onto: Option<Lane>,
3272+ ) -> crate::Result<bool> {
3273+ if !crate::is_audio(path) {
3274+ return Err(format!(
3275+ "{} is not audio: a visualizer needs a sound file",
3276+ path.display()
3277+ )
3278+ .into());
3279+ }
3280+ if out_frame <= in_frame {
3281+ return Err("visualizer clip is empty".into());
3282+ }
3283+ let wanted = Source::new(path, stream);
3284+ let first = self.first_audio()?;
3285+ self.audio_matches_cached(&wanted, &first)?;
3286+ let frames = match self.file_frames(&wanted.path) {
3287+ 0 => {
3288+ let n = audio_frames(path, self.meta.frame_rate)?;
3289+ let source = self.project.import(path, stream);
3290+ self.note_frames(source, n, Rate::REAL_TIME);
3291+ n
3292+ }
3293+ n => n,
3294+ };
3295+ let out_frame = out_frame.min(frames);
3296+ if out_frame <= in_frame {
3297+ return Err("visualizer clip is empty".into());
3298+ }
3299+ let source = self.project.import(path, stream);
3300+ let clip = Clip {
3301+ fade_in: 0,
3302+ fade_out: 0,
3303+ transition_out: 0,
3304+ start: 0,
3305+ in_frame,
3306+ out_frame,
3307+ source,
3308+ link: None,
3309+ eq: None,
3310+ color: None,
3311+ transform: None,
3312+ fit: FitPolicy::default(),
3313+ speed: Speed::NORMAL,
3314+ };
3315+ let end = start + clip.frames();
3316+ let overlaps = |lane: Lane| {
3317+ self.project
3318+ .lane(lane)
3319+ .iter()
3320+ .any(|c| c.start < end && start < c.end())
3321+ };
3322+ let lane = match onto {
3323+ Some(lane) if lane.kind == LaneKind::Video && !overlaps(lane) => lane,
3324+ _ => self
3325+ .project
3326+ .lanes()
3327+ .into_iter()
3328+ .filter(|l| l.kind == LaneKind::Video)
3329+ .find(|&l| !overlaps(l))
3330+ .unwrap_or_else(|| self.add_lane(LaneKind::Video)),
3331+ };
3332+ Ok(self.edit(Dirty::Both, |p| p.place(lane, start, clip)))
3333+ }
3334+
3237 /// Removes `lane`'s clip at `idx` and everything under it, closing the gap3335 /// Removes `lane`'s clip at `idx` and everything under it, closing the gap
3238 /// on every lane. Unlike a split this *does* move every following frame, so3336 /// on every lane. Unlike a split this *does* move every following frame, so
3239 /// the session reseeks to wherever the playhead now points.3337 /// the session reseeks to wherever the playhead now points.
crates/engine/src/scale.rsmodified+8 -0
@@ -588,6 +588,14 @@ impl Composer {
588 self.width == 0 || self.height == 0588 self.width == 0 || self.height == 0
589 }589 }
590 590
591+ /// The canvas this composer places onto, for the painter that fills it
592+ /// directly at this size -- a picture authored at the canvas's own
593+ /// dimensions takes the pass-through path [`is_passthrough`](Self::is_passthrough)
594+ /// answers for, and it needs the numbers before there is a picture.
595+ pub(crate) fn dims(&self) -> (u32, u32) {
596+ (self.width, self.height)
597+ }
598+
591 /// How many decoded pictures a worker over this canvas may keep ahead of599 /// How many decoded pictures a worker over this canvas may keep ahead of
592 /// its consumer: a budget in *bytes*, so a 4K project runs a shallower queue600 /// its consumer: a budget in *bytes*, so a 4K project runs a shallower queue
593 /// than a 1080p one instead of the same number of far bigger frames.601 /// than a 1080p one instead of the same number of far bigger frames.
crates/engine/tests/audio_files.rsmodified+86 -36
@@ -1,8 +1,8 @@
1 //! Standalone audio files as sources: every container we claim to read decodes1 //! 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 song2 //! 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)3 //! *is* a timeline on its own (canvas scaffolded, picture black, sound exported)
4-//! and the two things it cannot do -- play on the video lane, be copied into an4+//! and a visualizer clip is how that song gets a picture on a video lane.
5-//! mp4 -- are refusals that say so.5+//! Paste still never lands a song on V1 by accident.
6 //!6 //!
7 //! ```text7 //! ```text
8 //! cargo test -p engine --release --test audio_files8 //! cargo test -p engine --release --test audio_files
@@ -125,7 +125,10 @@ fn an_ac3_track_with_no_picture_opens_out_of_an_mka() {
125 let (rate, channels, samples) = decode(&asset("test_ac3.mka"));125 let (rate, channels, samples) = decode(&asset("test_ac3.mka"));
126 assert_eq!((rate, channels), (44100, 2), "test_ac3.mka");126 assert_eq!((rate, channels), (44100, 2), "test_ac3.mka");
127 let secs = samples.len() as f64 / f64::from(rate) / f64::from(channels);127 let secs = samples.len() as f64 / f64::from(rate) / f64::from(channels);
128- assert!((secs - 2.0).abs() < 0.2, "test_ac3.mka: {secs:.3} s, want 2.0");128+ assert!(
129+ (secs - 2.0).abs() < 0.2,
130+ "test_ac3.mka: {secs:.3} s, want 2.0"
131+ );
129 let mid = samples.len() / 2;132 let mid = samples.len() / 2;
130 let peak = samples[mid..][..channels as usize * 64]133 let peak = samples[mid..][..channels as usize * 64]
131 .iter()134 .iter()
@@ -167,11 +170,9 @@ fn a_song_joins_a_video_timeline_on_the_audio_lane() {
167 assert_eq!(session.timeline_duration(), before);170 assert_eq!(session.timeline_duration(), before);
168 assert_eq!(session.file_frames(&asset("test_tone.mp3")), 90);171 assert_eq!(session.file_frames(&asset("test_tone.mp3")), 90);
169 let end = session.timeline_duration();172 let end = session.timeline_duration();
170- assert!(173+ assert!(session
171- session174+ .place_stream_at(end, &asset("test_tone.mp3"), 0, None)
172- .place_stream_at(end, &asset("test_tone.mp3"), 0, None)175+ .expect("a song just imported is on this timeline"));
173- .expect("a song just imported is on this timeline")
174- );
175 176
176 // 3 s at 30 fps, placed at the end: the audio lane runs 90 frames past the177 // 3 s at 30 fps, placed at the end: the audio lane runs 90 frames past the
177 // video.178 // video.
@@ -220,8 +221,9 @@ fn a_rate_the_device_cannot_mix_is_converted_at_the_door() {
220 // ...and the samples themselves, straight out of the worker the session221 // ...and the samples themselves, straight out of the worker the session
221 // feeds from: one second of the 48k file, resampled onto a 44.1k timeline.222 // feeds from: one second of the 48k file, resampled onto a 44.1k timeline.
222 let sources = [(asset("test_av.mp4"), 0), (asset("test_tone_48k.wav"), 0)];223 let sources = [(asset("test_av.mp4"), 0), (asset("test_tone_48k.wav"), 0)];
223- let (meta, rx) =224+ let (meta, rx) = AudioSession::open_multi_streams(&sources, &[(Some(1), 0.25, 1.25)])
224- AudioSession::open_multi_streams(&sources, &[(Some(1), 0.25, 1.25)]).expect("open").expect("the timeline has sound");225+ .expect("open")
226+ .expect("the timeline has sound");
225 assert_eq!(227 assert_eq!(
226 (meta.sample_rate, meta.channels),228 (meta.sample_rate, meta.channels),
227 (44100, 2),229 (44100, 2),
@@ -239,7 +241,10 @@ fn a_rate_the_device_cannot_mix_is_converted_at_the_door() {
239 for (name, channel, hz) in [("left", 0, 440.0), ("right", 1, 880.0)] {241 for (name, channel, hz) in [("left", 0, 440.0), ("right", 1, 880.0)] {
240 let side: Vec<f32> = samples[channel..].iter().step_by(2).copied().collect();242 let side: Vec<f32> = samples[channel..].iter().step_by(2).copied().collect();
241 let secs = side.len() as f64 / 44100.0;243 let secs = side.len() as f64 / 44100.0;
242- let crossings = side.windows(2).filter(|p| (p[0] < 0.0) != (p[1] < 0.0)).count() as f64;244+ let crossings = side
245+ .windows(2)
246+ .filter(|p| (p[0] < 0.0) != (p[1] < 0.0))
247+ .count() as f64;
243 let got = crossings / 2.0 / secs;248 let got = crossings / 2.0 / secs;
244 assert!(249 assert!(
245 (got - hz).abs() <= 0.02 * hz,250 (got - hz).abs() <= 0.02 * hz,
@@ -497,11 +502,9 @@ fn the_first_import_of_a_song_opens_a_library_over_an_empty_timeline() {
497 );502 );
498 503
499 // The drag: onto the audio lane and nowhere else, at the song's own length.504 // The drag: onto the audio lane and nowhere else, at the song's own length.
500- assert!(505+ assert!(session
501- session506+ .place_stream_at(0.0, &mp3, 0, None)
502- .place_stream_at(0.0, &mp3, 0, None)507+ .expect("its own file is on this timeline"));
503- .expect("its own file is on this timeline")
504- );
505 assert!(!session.is_empty());508 assert!(!session.is_empty());
506 assert!((session.timeline_duration() - 3.0).abs() < 0.05);509 assert!((session.timeline_duration() - 3.0).abs() < 0.05);
507 assert_eq!(session.lane_clips(Lane::A1).len(), 1);510 assert_eq!(session.lane_clips(Lane::A1).len(), 1);
@@ -571,11 +574,9 @@ fn an_export_refuses_audio_it_cannot_copy() {
571 );574 );
572 // A timeline of nothing but mp4 still exports, which is the invariant this575 // A timeline of nothing but mp4 still exports, which is the invariant this
573 // refusal must not have cost.576 // refusal must not have cost.
574- assert!(577+ assert!(AudioSession::copy_multi_segments(&sources[..1], &segs[..1])
575- AudioSession::copy_multi_segments(&sources[..1], &segs[..1])578+ .expect("mp4 audio still copies")
576- .expect("mp4 audio still copies")579+ .is_some());
577- .is_some()
578- );
579 }580 }
580 581
581 #[test]582 #[test]
@@ -623,21 +624,67 @@ fn a_song_survives_a_save_and_a_reload() {
623 before624 before
624 );625 );
625 626
626- // The one thing only a hand-edited project can ask for: a file with no627+ let _ = std::fs::remove_dir_all(&dir);
627- // picture on the video lane. Written by hand, because no door in the engine628+}
628- // will produce it.629+
629- let broken = dir.join("broken.edith");630+#[test]
630- std::fs::write(631+fn place_visualizer_puts_a_waveform_on_a_video_lane() {
631- &broken,632+ let dir = Scratch::dir("ve_audio_viz");
632- "edith 2\nplayhead 0\nsource test_av.mp4\nsource test_tone.flac\n\633+ let song = {
633- video 0 0 90 1 -\naudio 0 0 90 1 -\n",634+ let to = dir.join("test_tone.mp3");
634- )635+ std::fs::copy(asset("test_tone.mp3"), &to).expect("copy");
635- .expect("write");636+ to
636- let e = refusal(PlaybackSession::open_project(&broken));637+ };
638+ let mut session = open(&song);
639+ let audio = session.lane_clips(Lane::A1)[0];
640+ assert!(session.lane_clips(Lane::V1).is_empty());
637 assert!(641 assert!(
638- e.ends_with("has no picture: it can only play on an audio lane"),642+ session
639- "{e}"643+ .place_visualizer(0, &song, 0, audio.in_frame, audio.out_frame, None)
644+ .expect("place visualizer"),
645+ "placed"
646+ );
647+ assert_eq!(
648+ session.lane_clips(Lane::A1).len(),
649+ 1,
650+ "audio lane unchanged"
651+ );
652+ let video = session.lane_clips(Lane::V1);
653+ assert_eq!(video.len(), 1);
654+ assert_eq!(video[0].source, audio.source);
655+ assert_eq!(
656+ (video[0].in_frame, video[0].out_frame),
657+ (audio.in_frame, audio.out_frame)
640 );658 );
659+
660+ session.seek(1.0);
661+ let deadline = std::time::Instant::now() + std::time::Duration::from_secs(15);
662+ let mut saw = false;
663+ let mut frames = 0u32;
664+ while std::time::Instant::now() < deadline && frames < 45 {
665+ if let Some(frame) = session.try_frame() {
666+ frames += 1;
667+ if frame
668+ .bgra
669+ .chunks_exact(4)
670+ .any(|p| p[0] > 32 || p[1] > 32 || p[2] > 32)
671+ {
672+ saw = true;
673+ break;
674+ }
675+ } else {
676+ std::thread::sleep(std::time::Duration::from_millis(10));
677+ }
678+ }
679+ assert!(saw, "visualizer frame stayed black after {frames} pictures");
680+
681+ let project = dir.join("viz.edith");
682+ session.save_project(&project).expect("save");
683+ drop(session);
684+ let reloaded = PlaybackSession::open_project(&project).expect("reload visualizer project");
685+ assert_eq!(reloaded.lane_clips(Lane::V1).len(), 1);
686+ assert_eq!(reloaded.lane_clips(Lane::A1).len(), 1);
687+ drop(reloaded);
641 let _ = std::fs::remove_dir_all(&dir);688 let _ = std::fs::remove_dir_all(&dir);
642 }689 }
643 690
@@ -691,7 +738,10 @@ fn a_pasted_song_never_lands_on_the_video_lane() {
691 #[test]738 #[test]
692 fn an_audio_only_file_wearing_an_mp4_extension_still_opens() {739 fn an_audio_only_file_wearing_an_mp4_extension_still_opens() {
693 let session = open(asset("test_audio_only.mp4"));740 let session = open(asset("test_audio_only.mp4"));
694- assert!(session.lane_clips(Lane::V1).is_empty(), "no picture anywhere");741+ assert!(
742+ session.lane_clips(Lane::V1).is_empty(),
743+ "no picture anywhere"
744+ );
695 assert_eq!(session.lane_clips(Lane::A1).len(), 1);745 assert_eq!(session.lane_clips(Lane::A1).len(), 1);
696 assert!((session.timeline_duration() - 3.0).abs() < 0.1);746 assert!((session.timeline_duration() - 3.0).abs() < 0.1);
697 }747 }
@@ -731,7 +781,7 @@ fn a_project_scaffolded_from_an_audio_only_mp4_reloads() {
731 fn a_mono_source_up_mixes_onto_a_stereo_timeline() {781 fn a_mono_source_up_mixes_onto_a_stereo_timeline() {
732 let dir = Scratch::dir("ve_audio_upmix");782 let dir = Scratch::dir("ve_audio_upmix");
733 let mut session = open(asset("test_tone.mp3")); // a 3 s stereo timeline783 let mut session = open(asset("test_tone.mp3")); // a 3 s stereo timeline
734- // 44100 Hz, 1 ch AAC -- no rate to resample, only the layout in question.784+ // 44100 Hz, 1 ch AAC -- no rate to resample, only the layout in question.
735 import_and_place(&mut session, &asset("test_audio_only.mp4"));785 import_and_place(&mut session, &asset("test_audio_only.mp4"));
736 assert_eq!(session.lane_clips(Lane::A1).len(), 2);786 assert_eq!(session.lane_clips(Lane::A1).len(), 2);
737 assert!((session.timeline_duration() - 6.0).abs() < 0.1);787 assert!((session.timeline_duration() - 6.0).abs() < 0.1);