diff --git a/crates/app/src/keymap.rs b/crates/app/src/keymap.rs index be18822..511f8c1 100644 --- a/crates/app/src/keymap.rs +++ b/crates/app/src/keymap.rs @@ -159,6 +159,9 @@ actions! { Equalizer, Speed, Silence, + /// Paints a sliding waveform of this audio clip onto a video lane, so the + /// sound is a picture on the same timeline — preview and export both. + Visualizer, /// Crossfades the selected audio clip into its neighbour ([`Project::crossfade`]): /// two adjacent clips picked on one lane, or a single pick faded into the /// clip right after it. @@ -302,6 +305,7 @@ impl ActionId { ActionId::Equalizer => "Equalizer", ActionId::Speed => "Speed…", ActionId::Silence => "Silences…", + ActionId::Visualizer => "Create visualizer", ActionId::Crossfade => "Crossfade to next", ActionId::TrimIn => "Trim in", ActionId::TrimOut => "Trim out", @@ -385,6 +389,7 @@ impl ActionId { ActionId::Equalizer => "equalizer", ActionId::Speed => "speed", ActionId::Silence => "silence", + ActionId::Visualizer => "visualizer", ActionId::Crossfade => "crossfade", ActionId::TrimIn => "trim-in", ActionId::TrimOut => "trim-out", @@ -454,6 +459,7 @@ impl ActionId { // timeline the clip is on -- it is a clip card like the three // above it, opened on whichever half was picked. | ActionId::Silence + | ActionId::Visualizer | ActionId::Crossfade | ActionId::TrimIn | ActionId::TrimOut @@ -1112,6 +1118,8 @@ impl Keymap { // delete (x and delete) -- what it opens is a card that can cut // forty places at once. b(ActionId::Silence, "u", false), + // Waveform-as-video: `h` was free (Theme is ctrl+h, Screenshot is w). + b(ActionId::Visualizer, "h", false), // Crossfade takes ctrl+f: the mnemonic letter for "fade", with // ctrl its own room now that plain "f" is the mix card's own // (below) -- the same letter, the modifier telling them apart. @@ -1425,7 +1433,7 @@ fn parse(text: &str) -> Result<(Keymap, Vec), String> { mod tests { use engine::scratch::Scratch; - use super::{ActionId, Chord, Keymap, config_path_in, emit, parse}; + use super::{config_path_in, emit, parse, ActionId, Chord, Keymap}; fn chord(key: &str, ctrl: bool) -> Chord { Chord { @@ -1445,7 +1453,7 @@ mod tests { #[test] fn every_default_stroke_reaches_its_action() { let k = Keymap::defaults(); - assert_eq!(k.entries().len(), 78); + assert_eq!(k.entries().len(), 79); // The cut odometer: bare walks one, `<`/`>` (what shift+,/shift+. // actually type) strides ten. assert_eq!(k.lookup(".", false), Some(ActionId::WalkCutNext)); @@ -1468,6 +1476,7 @@ mod tests { assert_eq!(k.lookup("l", true), Some(ActionId::PasteFilePath)); assert_eq!(k.lookup("?", false), Some(ActionId::ShowActions)); assert_eq!(k.lookup("h", true), Some(ActionId::Theme)); + assert_eq!(k.lookup("h", false), Some(ActionId::Visualizer)); assert_eq!(k.lookup("space", false), Some(ActionId::Play)); // The seek keys: bare arrows a frame, ctrl arrows a second, and the two // ends of the timeline. @@ -1699,7 +1708,10 @@ mod tests { let label = action.label(); let words = label.split_whitespace().count(); assert!(words <= 4, "{action:?}: {words} words -- {label:?}"); - assert!(!label.contains('('), "{action:?}: a parenthesis -- {label:?}"); + assert!( + !label.contains('('), + "{action:?}: a parenthesis -- {label:?}" + ); assert!( !label.to_lowercase().starts_with("the "), "{action:?}: leads with an article -- {label:?}" diff --git a/crates/app/src/menus.rs b/crates/app/src/menus.rs index 29924e2..49997bc 100644 --- a/crates/app/src/menus.rs +++ b/crates/app/src/menus.rs @@ -211,7 +211,7 @@ impl RowItem { /// action a stroke already reaches -- the menu is a second way *to* the actions /// and never a second version of them -- so both the label and the hint come /// out of the keymap registry and the two can never disagree. -pub(crate) const MENU_ITEMS: [ActionId; 16] = [ +pub(crate) const MENU_ITEMS: [ActionId; 17] = [ ActionId::Cut, // The cut machinery (DESIGN.md §6) on the very clip it is about: the // trims and the loop-trim were strokes the spine rail listed and nothing @@ -239,6 +239,7 @@ pub(crate) const MENU_ITEMS: [ActionId; 16] = [ // ...and the sound ones, the same class refusal the other way round. ActionId::Equalizer, ActionId::Silence, + ActionId::Visualizer, ActionId::Speed, ActionId::Fit, // Last, under the rule line the render draws before the first of them @@ -311,7 +312,6 @@ pub(crate) fn destructive(action: ActionId) -> bool { ) } - /// One row of the actions card, in the order it lists them: a heading, then /// every action the registry files under it, then the strokes the modal cards /// answer themselves. diff --git a/crates/app/src/oracle.rs b/crates/app/src/oracle.rs index 1518ebe..c5195b2 100644 --- a/crates/app/src/oracle.rs +++ b/crates/app/src/oracle.rs @@ -222,11 +222,14 @@ pub(crate) fn enable(action: ActionId, ctx: Ctx) -> Enable { // policy is a picture setting for the same reason. // The dissolve is the picture join and the crossfade's mirror: two // pictures cross, and there is no picture on a waveform to cross. - ActionId::Color | ActionId::Fit | ActionId::Transform | ActionId::Dissolve => match ctx.clip - { - Some((_, lane)) if lane.kind != LaneKind::Video => Enable::Hidden("this clip is sound"), - _ => Enable::Yes, - }, + ActionId::Color | ActionId::Fit | ActionId::Transform | ActionId::Dissolve => { + match ctx.clip { + Some((_, lane)) if lane.kind != LaneKind::Video => { + Enable::Hidden("this clip is sound") + } + _ => Enable::Yes, + } + } // The scan reads samples, and a still has none -- ever, unlike a video // clip whose sound may be one lane down or simply silent. Exactly what // `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 { // same class refusal over the same clip: nothing to mix for a picture // with no sound at all. ActionId::Silence | ActionId::Mix if ctx.image => Enable::Hidden("this clip is a still"), + ActionId::Visualizer if ctx.image => Enable::Hidden("this clip is a still"), + ActionId::Visualizer if ctx.no_sound => Enable::Hidden("this clip has no sound"), + ActionId::Visualizer => match ctx.clip { + Some((_, lane)) if lane.kind == LaneKind::Audio => Enable::Yes, + Some(_) => Enable::Hidden("this clip is picture"), + None => Enable::No("select an audio clip"), + }, ActionId::Silence | ActionId::Mix if ctx.no_sound => { Enable::Hidden("this clip has no sound") } @@ -339,9 +349,7 @@ pub(crate) fn enable(action: ActionId, ctx: Ctx) -> Enable { // A clock started against an empty timeline is a clock counting // nothing: the transport says so by being dim, which is what its own // ad-hoc boolean used to say before the oracle knew the question. - ActionId::Play | ActionId::Loop if !ctx.playable => { - Enable::No("the timeline is empty") - } + ActionId::Play | ActionId::Loop if !ctx.playable => Enable::No("the timeline is empty"), // A rate applies to a clip of either kind and to its whole group, so // there is no lane it means nothing on, and the engine words the one // refusal there is (no room). Everything else is the editor's own and diff --git a/crates/app/src/player/actions.rs b/crates/app/src/player/actions.rs index 22e9915..3d645eb 100644 --- a/crates/app/src/player/actions.rs +++ b/crates/app/src/player/actions.rs @@ -55,6 +55,7 @@ impl Player { | ActionId::ImportSubtitles | ActionId::Crossfade | ActionId::Dissolve + | ActionId::Visualizer ) { self.mark_dirty(); } @@ -144,6 +145,7 @@ impl Player { ActionId::Equalizer => self.open_eq(cx), ActionId::Speed => self.open_speed(cx), ActionId::Silence => self.open_silence(cx), + ActionId::Visualizer => self.create_visualizer(cx), ActionId::Mix => self.open_mix(None, cx), ActionId::SubtitleStyle => self.open_subtitle_style(cx), ActionId::ToggleSnap => self.toggle_snap(cx), diff --git a/crates/app/src/player/library.rs b/crates/app/src/player/library.rs index 55e26d5..98f8f6e 100644 --- a/crates/app/src/player/library.rs +++ b/crates/app/src/player/library.rs @@ -133,6 +133,67 @@ impl Player { cx.notify(); } + /// Paints a sliding waveform of the marked audio clip onto a video lane. + /// Same implementation the clip menu and the `h` stroke both reach. + pub(crate) fn create_visualizer(&mut self, cx: &mut Context) { + if self.exporting().is_some() { + return; + } + let Some((lane, idx)) = self.selected.anchor() else { + self.notify_user("NO VISUALIZER — select an audio clip".into()); + cx.notify(); + return; + }; + let placed = match &mut self.session { + None => { + self.notify_user("NO VISUALIZER — no file open".into()); + cx.notify(); + return; + } + Some(session) => { + if lane.kind != LaneKind::Audio { + self.notify_user("NO VISUALIZER — select an audio clip".into()); + cx.notify(); + return; + } + let Some(clip) = session.lane_clips(lane).get(idx).copied() else { + self.notify_user("NO VISUALIZER — select an audio clip".into()); + cx.notify(); + return; + }; + let Some(src) = session.sources().get(clip.source).cloned() else { + self.notify_user("NO VISUALIZER — that clip has no source".into()); + cx.notify(); + return; + }; + if !engine::is_audio(&src.path) { + self.notify_user("NO VISUALIZER — this clip is not a sound file".into()); + cx.notify(); + return; + } + session.place_visualizer( + clip.start, + &src.path, + src.audio_stream, + clip.in_frame, + clip.out_frame, + None, + ) + } + }; + match placed { + Ok(true) => { + self.notify_user("VISUALIZER ADDED".into()); + self.reset_after_reseek(); + } + Err(e) => self.notify_user(format!("NO VISUALIZER — {e}").into()), + Ok(false) => { + self.notify_user("NO VISUALIZER — that clip could not be placed".into()) + } + } + cx.notify(); + } + /// Takes a library row's file out of the list, which is the one thing a row /// can lose. Refused in the engine's own words while clips still play from /// it -- and those words name the lanes holding them, so the refusal says diff --git a/crates/app/src/tests/editing.rs b/crates/app/src/tests/editing.rs index 977b6bb..797f8bf 100644 --- a/crates/app/src/tests/editing.rs +++ b/crates/app/src/tests/editing.rs @@ -753,11 +753,13 @@ fn the_clip_menu_dims_what_the_playhead_is_not_on_and_stays_in_the_window() { assert!(!sound.contains(&ActionId::Fit), "{sound:?}"); assert!(sound.contains(&ActionId::Equalizer)); assert!(sound.contains(&ActionId::Silence)); + assert!(sound.contains(&ActionId::Visualizer)); // Picture: the mirror of it. The sound of a take is the audio lane's, // clip for clip, so the equalizer is not this clip's business -- but the // silence scan is, because it opens on the half it is grouped with. let picture = menu(v1, false, 60); assert!(!picture.contains(&ActionId::Equalizer), "{picture:?}"); + assert!(!picture.contains(&ActionId::Visualizer), "{picture:?}"); assert!(picture.contains(&ActionId::Color)); assert!(picture.contains(&ActionId::Fit)); 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() { // rewrite), scanned like none. let still = menu(v1, true, 60); assert!(!still.contains(&ActionId::Silence), "{still:?}"); + assert!(!still.contains(&ActionId::Visualizer), "{still:?}"); assert!(!still.contains(&ActionId::Equalizer), "{still:?}"); assert!(still.contains(&ActionId::Color)); assert!(still.contains(&ActionId::Fit)); diff --git a/crates/engine/src/decode.rs b/crates/engine/src/decode.rs index 53d455e..a6abe0b 100644 --- a/crates/engine/src/decode.rs +++ b/crates/engine/src/decode.rs @@ -55,6 +55,9 @@ pub enum Backend { Still, /// A gap: black frames, nothing decoded at all. Gap, + /// A waveform visualizer: the picture is painted from the audio's peaks + /// ([`visualizer_i420`]), no decoder seat and no stream of pictures at all. + Visualizer, } impl Backend { @@ -66,6 +69,7 @@ impl Backend { Self::Software => "SW", Self::Still => "still", Self::Gap => "gap", + Self::Visualizer => "viz", } } @@ -76,6 +80,7 @@ impl Backend { Self::Software => 2, Self::Still => 3, Self::Gap => 4, + Self::Visualizer => 5, } } @@ -85,6 +90,7 @@ impl Backend { 2 => Self::Software, 3 => Self::Still, 4 => Self::Gap, + 5 => Self::Visualizer, _ => Self::Opening, } } @@ -601,6 +607,96 @@ impl DecodeSession { }) } + /// A worker for an audio file played as a *picture* ([`crate::is_audio`]): + /// the file's peaks are decoded **once** on the worker, and every picture + /// after that is painted -- a sliding mirrored waveform + /// ([`visualizer_i420`]) at the canvas's own size, then graded, placed and + /// converted exactly like a decoded picture, so a grade, a transform and a + /// fit policy reach it the way they reach anything else on the timeline. + /// + /// `start_frame` and `len` are the file's own frames at `fps` -- which for + /// an audio source are also the timeline's + /// ([`crate::project::Rate::REAL_TIME`]) -- so `Frame::index` runs + /// `start_frame ..` like a decoder's output and a speed reaches it through + /// the same rewrite as any other clip. + pub(crate) fn open_visualizer( + path: &Path, + stream: usize, + start_frame: u32, + len: u32, + fps: f64, + color: ColorParams, + transform: TransformParams, + canvas: Composer, + ) -> crate::Result { + let (tx, rx) = sync_channel(2); + let cancel = Arc::new(AtomicBool::new(false)); + if len == 0 { + return Ok(FrameStream { + frames: rx, + worker: Worker { + cancel, + handle: None, + reuse: None, + }, + backend: BackendCell::new(Backend::Visualizer), + }); + } + // Painted at the canvas's own size, so the composite places nothing: + // the picture *is* the canvas, and whatever transform the clip + // carries still reaches it through the render below. + let (width, height) = canvas.dims(); + let worker_cancel = Arc::clone(&cancel); + let path = path.to_path_buf(); + let handle = thread::Builder::new() + .name("viz".into()) + .spawn(move || { + // The one decode this seat ever does: the whole envelope, + // off the render thread, and abandoned at once if the caller + // is already gone. A file that will not open -- and one with + // no track at all -- paints the flat line, which is what its + // silence looks like anyway: a visualizer frame always + // exists, and is never worth failing a span over. + let peaks = crate::waveform::peaks(&path, stream, VIZ_BUCKETS_PER_SEC) + .ok() + .flatten() + .unwrap_or_default(); + if worker_cancel.load(Ordering::Relaxed) { + return; + } + let fps = if fps.is_finite() && fps > 0.0 { fps } else { 30.0 }; + let mut render = Render::new( + color, + transform, + ColorDescription::default(), + canvas, + tonemap::Preset::default(), + None, + ); + for index in 0..len { + if worker_cancel.load(Ordering::Relaxed) { + return; + } + let t = f64::from(start_frame + index) / fps; + let (y, u, v) = visualizer_i420(&peaks, t, width, height); + let frame = render.frame(start_frame + index, &y, &u, &v, width, height); + if tx.send(frame).is_err() { + return; // caller moved on + } + } + }) + .ok(); + Ok(FrameStream { + frames: rx, + worker: Worker { + cancel, + handle, + reuse: None, + }, + backend: BackendCell::new(Backend::Visualizer), + }) + } + /// As [`DecodeSession::open_range`], but the caller gets the whole /// [`Worker`] and can therefore *wait* for it, and the range is graded by /// `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, Vec, Ve (y, u, v) } +/// Peak buckets per second the visualizer paints from, shared by the one +/// caller that decodes them ([`DecodeSession::open_visualizer`], preview and +/// export both) and the painter that reads them. +pub(crate) const VIZ_BUCKETS_PER_SEC: u32 = 60; + +/// How much sound one visualizer frame shows, centered on the frame's own +/// time: two seconds, so a glance reads the shape of the around-now rather +/// than the whole file squeezed into one picture. +const VIZ_WINDOW_SECS: f64 = 2.0; + +/// One visualizer picture, painted straight into tightly packed I420 in the +/// BT.601 limited range [`rgb_to_i420`] writes: dark (`16`, neutral chroma) +/// with the waveform bright (`220`), so what turns it into pixels on a screen +/// is the same conversion a still goes through. +/// +/// The columns are a **sliding** window of [`VIZ_WINDOW_SECS`] centered on +/// `t_secs`, mirrored around the vertical middle: the buckets' maxima reach +/// up from the center line and their minima down, the standard symmetric +/// envelope. `t_secs` outside the peaks -- and an empty envelope, silence +/// included, whose buckets are `(0.0, 0.0)` -- paints the one-pixel center +/// line: a visualizer frame always exists, whatever the sound did. +pub(crate) fn visualizer_i420( + peaks: &[(f32, f32)], + t_secs: f64, + width: u32, + height: u32, +) -> (Vec, Vec, Vec) { + // Even dims, like every canvas this engine composes at: an odd caller is + // shaved rather than handed chroma math it did not ask about. + let width = width & !1; + let height = height & !1; + let (w, h) = (width as usize, height as usize); + let (cw, ch) = crate::scale::chroma_dims(w, h); + let mut y = vec![16u8; w * h]; + let u = vec![128u8; cw * ch]; + let v = vec![128u8; cw * ch]; + let center = h / 2; + let duration = peaks.len() as f64 / f64::from(VIZ_BUCKETS_PER_SEC); + if peaks.is_empty() || !t_secs.is_finite() || !(0.0..=duration).contains(&t_secs) { + for col in 0..w { + y[center * w + col] = 220; + } + return (y, u, v); + } + let per_sec = f64::from(VIZ_BUCKETS_PER_SEC); + // The window, clamped to the peaks that exist: a frame near either end + // looks past the file's edge, and draws the part of the window that is + // real rather than padding it out. + let first = (((t_secs - VIZ_WINDOW_SECS / 2.0).max(0.0) * per_sec).floor() as usize) + .min(peaks.len() - 1); + let last = ((((t_secs + VIZ_WINDOW_SECS / 2.0).min(duration) * per_sec).ceil() as usize) + .clamp(first + 1, peaks.len())) + .min(peaks.len()); + let span = (last - first) as f64; + let scale = center as f32; + for col in 0..w { + // The buckets this column draws: at least one, whatever the window's + // width is against the picture's -- a short clip stretches, a long + // one condenses, and neither leaves a column with nothing. + let b0 = first + (col as f64 * span / w as f64).floor() as usize; + let b1 = first + + (((col + 1) as f64 * span / w as f64).ceil() as usize) + .clamp(b0 - first + 1, last - first); + let (mut lo, mut hi) = (f32::INFINITY, f32::NEG_INFINITY); + for &(min, max) in &peaks[b0..b1] { + lo = lo.min(min); + hi = hi.max(max); + } + // Mirrored around the center: maxima up, minima down, silence a line. + let top = (scale - hi * scale).round(); + let bottom = (scale - lo * scale).round(); + let top = (top as isize).clamp(0, h as isize - 1) as usize; + let bottom = (bottom as isize).clamp(top as isize, h as isize - 1) as usize; + for row in top..=bottom { + y[row * w + col] = 220; + } + } + (y, u, v) +} + /// `None` when the software path must be used: forced by `VE_SW=1`, or the /// plugin is absent/broken/unable to open this particular file. fn open_hw(path: &Path, start_frame: u32) -> Option { diff --git a/crates/engine/src/export.rs b/crates/engine/src/export.rs index ac46eaf..cf6fc2f 100644 --- a/crates/engine/src/export.rs +++ b/crates/engine/src/export.rs @@ -2760,7 +2760,18 @@ fn run( let want = untouched.then(|| encoder.dma_want(meta)).flatten(); // Opened at the file's own frame, which is the only place the // file's numbering is used -- the span's are the timeline's. - let pictures = ClipDecoder::open(&entry.path, rate.source_at(in_frame), want)?; + let pictures = if crate::is_audio(&entry.path) { + ClipDecoder::visualizer( + &entry.path, + entry.audio_stream, + rate.source_at(in_frame), + meta.width, + meta.height, + meta.frame_rate, + )? + } else { + ClipDecoder::open(&entry.path, rate.source_at(in_frame), want)? + }; (Some(pictures), rate, in_frame, Some(color), mapper) } // A gap's black is 16/128/128, which is black in every matrix here @@ -2815,7 +2826,18 @@ fn run( Ok(Dissolve { window, tail_start: span.len - window, - decoder: ClipDecoder::open(&entry.path, b_rate.source_at(b_in_frame), None)?, + decoder: if crate::is_audio(&entry.path) { + ClipDecoder::visualizer( + &entry.path, + entry.audio_stream, + b_rate.source_at(b_in_frame), + meta.width, + meta.height, + meta.frame_rate, + )? + } else { + ClipDecoder::open(&entry.path, b_rate.source_at(b_in_frame), None)? + }, mapper: b_mapper, remap: b_remap, grade: project.composite_color_at(b_start).copied(), @@ -4388,6 +4410,18 @@ enum ClipDecoder { /// other two are opened there -- the span's pictures come from one place, /// and no thread can make one picture arrive sooner. Still(crate::decode::Still), + /// An audio file playing as a picture: each `next` paints one visualizer + /// frame from peaks already decoded ([`crate::decode::visualizer_i420`]). + Visualizer { + peaks: Vec<(f32, f32)>, + width: u32, + height: u32, + fps: f64, + next: u32, + y: Vec, + u: Vec, + v: Vec, + }, } /// The receiving half of a decode thread, plus the picture it last handed out @@ -4489,6 +4523,31 @@ impl ClipDecoder { })) } + fn visualizer( + path: &Path, + stream: usize, + start_frame: u32, + width: u32, + height: u32, + fps: f64, + ) -> crate::Result { + let peaks = crate::waveform::peaks(path, stream, crate::decode::VIZ_BUCKETS_PER_SEC) + .ok() + .flatten() + .unwrap_or_default(); + let fps = if fps.is_finite() && fps > 0.0 { fps } else { 30.0 }; + Ok(Self::Visualizer { + peaks, + width, + height, + fps, + next: start_frame, + y: Vec::new(), + u: Vec::new(), + v: Vec::new(), + }) + } + /// The next picture, borrowed until the call after -- as tightly packed /// I420, or as the GPU buffer the decoder wrote it into. fn next(&mut self) -> crate::Result>> { @@ -4497,6 +4556,24 @@ impl ClipDecoder { let (y, u, v, width, height) = still.picture(); Ok(Some(Frame::Pixels(y, u, v, width, height))) } + Self::Visualizer { + peaks, + width, + height, + fps, + next, + y, + u, + v, + } => { + let (yy, uu, vv) = + crate::decode::visualizer_i420(peaks, f64::from(*next) / *fps, *width, *height); + *y = yy; + *u = uu; + *v = vv; + *next += 1; + Ok(Some(Frame::Pixels(y, u, v, *width & !1, *height & !1))) + } Self::Streamed(stream) if stream.ended => Ok(None), Self::Streamed(stream) => match stream.frames.recv() { Ok(Ok(Some(frame))) => Ok(Some(match stream.current.insert(frame) { @@ -4509,20 +4586,11 @@ impl ClipDecoder { } => Frame::Pixels(y, u, v, *width, *height), Yuv::Dma(dma) => Frame::Dma(dma), })), - // The decoder said end of stream in as many words -- a source - // shorter than the clip that names it, which the span loop ends - // gracefully on. Ok(Ok(None)) => { stream.ended = true; Ok(None) } Ok(Err(e)) => Err(e), - // The channel went quiet without either: the thread panicked. - // Read as end of stream that would truncate the export at this - // frame and *report success*, which is the one outcome an - // export must never have -- before the decode moved onto a - // thread the same panic took the whole export down, and it - // still does. Err(_) => Err("the decoder stopped without a picture or a reason".into()), }, } diff --git a/crates/engine/src/playback.rs b/crates/engine/src/playback.rs index 423d9bc..687679e 100644 --- a/crates/engine/src/playback.rs +++ b/crates/engine/src/playback.rs @@ -1096,27 +1096,18 @@ impl PlaybackSession { counts.push(rate.timeline_at(other.frame_count)); rates.push(rate); } - // The video lane can only play files that have pictures. Hand-written - // (or hand-edited) project files are the one door this can come in - // through, so it is refused by name here rather than becoming a clip - // that decodes to nothing. + // A still is silent, so a clip playing one on an audio lane is a + // segment the audio worker would open a PNG for. Refused by name + // here, which is the one door it can arrive through + // (`place_stream_at` never puts one there). An audio file on a + // *video* lane used to be refused the same way; it plays as a + // waveform visualizer now ([`DecodeSession::open_visualizer`]). for (kind, clip) in doc .lanes .iter() .flat_map(|(kind, clips)| clips.iter().map(move |clip| (*kind, clip))) { let path = &doc.sources[clip.source].path; - if kind == LaneKind::Video && crate::is_audio(path) { - return Err(format!( - "{} has no picture: it can only play on an audio lane", - path.display() - ) - .into()); - } - // ...and the mirror of it: a still is silent, so a clip playing one - // on an audio lane is a segment the audio worker would open a PNG - // for. Refused by name here, which is the one door it can arrive - // through (`place_stream_at` never puts one there). if kind == LaneKind::Audio && crate::is_image(path) { return Err(format!( "{} is a still image: it can only play on a video lane", @@ -1840,6 +1831,39 @@ impl PlaybackSession { ) .inspect_err(|e| eprintln!("timeline frame {start}: image open failed: {e}")) } + Some(Span { + start, + from: Some((source, in_frame)), + .. + }) if crate::is_audio(&self.project.sources()[source].path) => { + let (path, stream) = { + let src = &self.project.sources()[source]; + (src.path.clone(), src.audio_stream) + }; + DecodeSession::open_visualizer( + &path, + stream, + in_frame, + span.expect("matched above").source_len(), + self.meta.frame_rate, + self.project + .composite_color_at(start) + .copied() + .unwrap_or_default(), + self.project + .composite_transform_at(start) + .copied() + .unwrap_or_default(), + Composer::new( + self.meta.width, + self.meta.height, + self.project.composite_fit_at(start), + ), + ) + .inspect_err(|e| { + eprintln!("timeline frame {start}: visualizer open failed: {e}") + }) + } Some(Span { start, from: Some((source, in_frame)), @@ -3234,6 +3258,80 @@ impl PlaybackSession { self.edit(Dirty::Both, |p| p.place(lane, at, clip)) } + /// Places a waveform-visualizer clip of `path`'s audio on a video lane. + /// The picture is painted from the sound ([`DecodeSession::open_visualizer`]); + /// this does not also put a copy on an audio lane. + pub fn place_visualizer( + &mut self, + start: u32, + path: &Path, + stream: usize, + in_frame: u32, + out_frame: u32, + onto: Option, + ) -> crate::Result { + if !crate::is_audio(path) { + return Err(format!( + "{} is not audio: a visualizer needs a sound file", + path.display() + ) + .into()); + } + if out_frame <= in_frame { + return Err("visualizer clip is empty".into()); + } + let wanted = Source::new(path, stream); + let first = self.first_audio()?; + self.audio_matches_cached(&wanted, &first)?; + let frames = match self.file_frames(&wanted.path) { + 0 => { + let n = audio_frames(path, self.meta.frame_rate)?; + let source = self.project.import(path, stream); + self.note_frames(source, n, Rate::REAL_TIME); + n + } + n => n, + }; + let out_frame = out_frame.min(frames); + if out_frame <= in_frame { + return Err("visualizer clip is empty".into()); + } + let source = self.project.import(path, stream); + let clip = Clip { + fade_in: 0, + fade_out: 0, + transition_out: 0, + start: 0, + in_frame, + out_frame, + source, + link: None, + eq: None, + color: None, + transform: None, + fit: FitPolicy::default(), + speed: Speed::NORMAL, + }; + let end = start + clip.frames(); + let overlaps = |lane: Lane| { + self.project + .lane(lane) + .iter() + .any(|c| c.start < end && start < c.end()) + }; + let lane = match onto { + Some(lane) if lane.kind == LaneKind::Video && !overlaps(lane) => lane, + _ => self + .project + .lanes() + .into_iter() + .filter(|l| l.kind == LaneKind::Video) + .find(|&l| !overlaps(l)) + .unwrap_or_else(|| self.add_lane(LaneKind::Video)), + }; + Ok(self.edit(Dirty::Both, |p| p.place(lane, start, clip))) + } + /// Removes `lane`'s clip at `idx` and everything under it, closing the gap /// on every lane. Unlike a split this *does* move every following frame, so /// the session reseeks to wherever the playhead now points. diff --git a/crates/engine/src/scale.rs b/crates/engine/src/scale.rs index f5de2b5..fad3afc 100644 --- a/crates/engine/src/scale.rs +++ b/crates/engine/src/scale.rs @@ -588,6 +588,14 @@ impl Composer { self.width == 0 || self.height == 0 } + /// The canvas this composer places onto, for the painter that fills it + /// directly at this size -- a picture authored at the canvas's own + /// dimensions takes the pass-through path [`is_passthrough`](Self::is_passthrough) + /// answers for, and it needs the numbers before there is a picture. + pub(crate) fn dims(&self) -> (u32, u32) { + (self.width, self.height) + } + /// How many decoded pictures a worker over this canvas may keep ahead of /// its consumer: a budget in *bytes*, so a 4K project runs a shallower queue /// than a 1080p one instead of the same number of far bigger frames. diff --git a/crates/engine/tests/audio_files.rs b/crates/engine/tests/audio_files.rs index d470e5a..6f3d58d 100644 --- a/crates/engine/tests/audio_files.rs +++ b/crates/engine/tests/audio_files.rs @@ -1,8 +1,8 @@ //! Standalone audio files as sources: every container we claim to read decodes //! to the same tone, a song joins a timeline of video on the audio lane, a song //! *is* a timeline on its own (canvas scaffolded, picture black, sound exported) -//! and the two things it cannot do -- play on the video lane, be copied into an -//! mp4 -- are refusals that say so. +//! and a visualizer clip is how that song gets a picture on a video lane. +//! Paste still never lands a song on V1 by accident. //! //! ```text //! cargo test -p engine --release --test audio_files @@ -125,7 +125,10 @@ fn an_ac3_track_with_no_picture_opens_out_of_an_mka() { let (rate, channels, samples) = decode(&asset("test_ac3.mka")); assert_eq!((rate, channels), (44100, 2), "test_ac3.mka"); let secs = samples.len() as f64 / f64::from(rate) / f64::from(channels); - assert!((secs - 2.0).abs() < 0.2, "test_ac3.mka: {secs:.3} s, want 2.0"); + assert!( + (secs - 2.0).abs() < 0.2, + "test_ac3.mka: {secs:.3} s, want 2.0" + ); let mid = samples.len() / 2; let peak = samples[mid..][..channels as usize * 64] .iter() @@ -167,11 +170,9 @@ fn a_song_joins_a_video_timeline_on_the_audio_lane() { assert_eq!(session.timeline_duration(), before); assert_eq!(session.file_frames(&asset("test_tone.mp3")), 90); let end = session.timeline_duration(); - assert!( - session - .place_stream_at(end, &asset("test_tone.mp3"), 0, None) - .expect("a song just imported is on this timeline") - ); + assert!(session + .place_stream_at(end, &asset("test_tone.mp3"), 0, None) + .expect("a song just imported is on this timeline")); // 3 s at 30 fps, placed at the end: the audio lane runs 90 frames past the // video. @@ -220,8 +221,9 @@ fn a_rate_the_device_cannot_mix_is_converted_at_the_door() { // ...and the samples themselves, straight out of the worker the session // feeds from: one second of the 48k file, resampled onto a 44.1k timeline. let sources = [(asset("test_av.mp4"), 0), (asset("test_tone_48k.wav"), 0)]; - let (meta, rx) = - AudioSession::open_multi_streams(&sources, &[(Some(1), 0.25, 1.25)]).expect("open").expect("the timeline has sound"); + let (meta, rx) = AudioSession::open_multi_streams(&sources, &[(Some(1), 0.25, 1.25)]) + .expect("open") + .expect("the timeline has sound"); assert_eq!( (meta.sample_rate, meta.channels), (44100, 2), @@ -239,7 +241,10 @@ fn a_rate_the_device_cannot_mix_is_converted_at_the_door() { for (name, channel, hz) in [("left", 0, 440.0), ("right", 1, 880.0)] { let side: Vec = samples[channel..].iter().step_by(2).copied().collect(); let secs = side.len() as f64 / 44100.0; - let crossings = side.windows(2).filter(|p| (p[0] < 0.0) != (p[1] < 0.0)).count() as f64; + let crossings = side + .windows(2) + .filter(|p| (p[0] < 0.0) != (p[1] < 0.0)) + .count() as f64; let got = crossings / 2.0 / secs; assert!( (got - hz).abs() <= 0.02 * hz, @@ -497,11 +502,9 @@ fn the_first_import_of_a_song_opens_a_library_over_an_empty_timeline() { ); // The drag: onto the audio lane and nowhere else, at the song's own length. - assert!( - session - .place_stream_at(0.0, &mp3, 0, None) - .expect("its own file is on this timeline") - ); + assert!(session + .place_stream_at(0.0, &mp3, 0, None) + .expect("its own file is on this timeline")); assert!(!session.is_empty()); assert!((session.timeline_duration() - 3.0).abs() < 0.05); assert_eq!(session.lane_clips(Lane::A1).len(), 1); @@ -571,11 +574,9 @@ fn an_export_refuses_audio_it_cannot_copy() { ); // A timeline of nothing but mp4 still exports, which is the invariant this // refusal must not have cost. - assert!( - AudioSession::copy_multi_segments(&sources[..1], &segs[..1]) - .expect("mp4 audio still copies") - .is_some() - ); + assert!(AudioSession::copy_multi_segments(&sources[..1], &segs[..1]) + .expect("mp4 audio still copies") + .is_some()); } #[test] @@ -623,21 +624,67 @@ fn a_song_survives_a_save_and_a_reload() { before ); - // The one thing only a hand-edited project can ask for: a file with no - // picture on the video lane. Written by hand, because no door in the engine - // will produce it. - let broken = dir.join("broken.edith"); - std::fs::write( - &broken, - "edith 2\nplayhead 0\nsource test_av.mp4\nsource test_tone.flac\n\ - video 0 0 90 1 -\naudio 0 0 90 1 -\n", - ) - .expect("write"); - let e = refusal(PlaybackSession::open_project(&broken)); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn place_visualizer_puts_a_waveform_on_a_video_lane() { + let dir = Scratch::dir("ve_audio_viz"); + let song = { + let to = dir.join("test_tone.mp3"); + std::fs::copy(asset("test_tone.mp3"), &to).expect("copy"); + to + }; + let mut session = open(&song); + let audio = session.lane_clips(Lane::A1)[0]; + assert!(session.lane_clips(Lane::V1).is_empty()); assert!( - e.ends_with("has no picture: it can only play on an audio lane"), - "{e}" + session + .place_visualizer(0, &song, 0, audio.in_frame, audio.out_frame, None) + .expect("place visualizer"), + "placed" + ); + assert_eq!( + session.lane_clips(Lane::A1).len(), + 1, + "audio lane unchanged" + ); + let video = session.lane_clips(Lane::V1); + assert_eq!(video.len(), 1); + assert_eq!(video[0].source, audio.source); + assert_eq!( + (video[0].in_frame, video[0].out_frame), + (audio.in_frame, audio.out_frame) ); + + session.seek(1.0); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(15); + let mut saw = false; + let mut frames = 0u32; + while std::time::Instant::now() < deadline && frames < 45 { + if let Some(frame) = session.try_frame() { + frames += 1; + if frame + .bgra + .chunks_exact(4) + .any(|p| p[0] > 32 || p[1] > 32 || p[2] > 32) + { + saw = true; + break; + } + } else { + std::thread::sleep(std::time::Duration::from_millis(10)); + } + } + assert!(saw, "visualizer frame stayed black after {frames} pictures"); + + let project = dir.join("viz.edith"); + session.save_project(&project).expect("save"); + drop(session); + let reloaded = PlaybackSession::open_project(&project).expect("reload visualizer project"); + assert_eq!(reloaded.lane_clips(Lane::V1).len(), 1); + assert_eq!(reloaded.lane_clips(Lane::A1).len(), 1); + drop(reloaded); let _ = std::fs::remove_dir_all(&dir); } @@ -691,7 +738,10 @@ fn a_pasted_song_never_lands_on_the_video_lane() { #[test] fn an_audio_only_file_wearing_an_mp4_extension_still_opens() { let session = open(asset("test_audio_only.mp4")); - assert!(session.lane_clips(Lane::V1).is_empty(), "no picture anywhere"); + assert!( + session.lane_clips(Lane::V1).is_empty(), + "no picture anywhere" + ); assert_eq!(session.lane_clips(Lane::A1).len(), 1); assert!((session.timeline_duration() - 3.0).abs() < 0.1); } @@ -731,7 +781,7 @@ fn a_project_scaffolded_from_an_audio_only_mp4_reloads() { fn a_mono_source_up_mixes_onto_a_stereo_timeline() { let dir = Scratch::dir("ve_audio_upmix"); let mut session = open(asset("test_tone.mp3")); // a 3 s stereo timeline - // 44100 Hz, 1 ch AAC -- no rate to resample, only the layout in question. + // 44100 Hz, 1 ch AAC -- no rate to resample, only the layout in question. import_and_place(&mut session, &asset("test_audio_only.mp4")); assert_eq!(session.lane_clips(Lane::A1).len(), 2); assert!((session.timeline_duration() - 6.0).abs() < 0.1);