diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs index dc053d9..5fa1fa7 100644 --- a/crates/app/src/main.rs +++ b/crates/app/src/main.rs @@ -430,6 +430,7 @@ struct Picker { #[derive(Clone, Copy, PartialEq, Eq, Debug)] enum Pick { Resolution, + Fps, Fit(Lane, usize), /// What the export's *sound* is coded at. Opened from the card's Sound row, /// which is the only place it means anything. @@ -439,9 +440,13 @@ enum Pick { /// One value a list offers, carrying everything picking it needs -- so a click /// goes straight to the value rather than to a position in a list that was /// built somewhere else. -#[derive(Clone, Copy, PartialEq, Eq, Debug)] +/// `Eq` is off it for the rate: a frame rate is the `f64` the engine is told, +/// bit for bit (23.976023976... is not 23.976), and nothing here keys a map on a +/// choice -- comparing two is all a list row ever does. +#[derive(Clone, Copy, PartialEq, Debug)] enum Choice { Size(u32, u32), + Fps(f64), Fit(Lane, usize, FitPolicy), AudioRate(u32), } @@ -622,6 +627,23 @@ fn typed(key: &str) -> Option { /// them, which is what makes the trip round come back to where it started. const RESOLUTIONS: [(u32, u32); 4] = [(3840, 2160), (1920, 1080), (1280, 720), (854, 480)]; +/// The project frame rates the list offers, slowest first: the rates footage is +/// actually shot and delivered at, the NTSC ones written as the ratios they are +/// (`24000/1001`, not `23.976`) -- the engine conforms the timeline to the very +/// number it is handed, so a rate rounded here would be a rate no timescale can +/// name. The media's own is cycled in beside them +/// ([`frame_rate_ladder`]), which is what keeps the way back on the list. +const FRAME_RATES: [f64; 8] = [ + 24_000. / 1001., + 24., + 25., + 30_000. / 1001., + 30., + 50., + 60_000. / 1001., + 60., +]; + /// How far a band may be pushed either way, in dB. The engine clamps nothing /// here -- it will filter whatever it is given -- so this is a UI decision: /// past about this a peaking band stops sounding like tone and starts sounding @@ -1696,6 +1718,23 @@ impl Player { cx.notify(); } + /// The project cut at another rate: the list names one and this is where it + /// happens, the way [`apply_resolution`](Self::apply_resolution) is for a + /// size. The whole timeline is conformed to it by the engine + /// ([`PlaybackSession::set_frame_rate`]) -- same seconds, same footage -- + /// and the rate the app itself counts frames in follows, since every + /// timecode, ruler mark and step key here is measured in it. + fn apply_frame_rate(&mut self, fps: f64, cx: &mut Context) { + if let Some(session) = &mut self.session + && session.set_frame_rate(fps) + { + self.fps = session.meta().frame_rate; + self.notice = Some(format!("PROJECT: {} fps", fps_label(fps)).into()); + self.reset_after_reseek(); + } + cx.notify(); + } + /// Opens a choice list on a setting, where it was asked for. One floating /// thing at a time: the click that opens it is the click that closes /// whatever menu it was opened from. @@ -1713,6 +1752,7 @@ impl Player { self.picker = None; match choice { Choice::Size(w, h) => self.apply_resolution(w, h, cx), + Choice::Fps(fps) => self.apply_frame_rate(fps, cx), Choice::Fit(lane, idx, fit) => self.apply_fit(lane, idx, fit, cx), // The same field the row's key steps, set outright: a list picks a // value, it does not step to one. @@ -1734,6 +1774,7 @@ impl Player { Pick::Resolution => { resolution_choices(session.resolution(), session.native_resolution()) } + Pick::Fps => fps_choices(session.meta().frame_rate, session.native_frame_rate()), Pick::Fit(lane, idx) => { fit_choices(lane, idx, session.fit_of(lane, idx), session.resolution()) } @@ -2043,8 +2084,11 @@ impl Player { /// ceiling by the same, and the switch either way (a ring of two, like the /// silence card's unit row). /// - /// Every one of them goes through the session, so it reseeks: what the ear - /// hears while the arrow is held is the mix that is being set. + /// Every one of them goes through the session, which hands it straight to + /// the running mixer: what the ear hears while the arrow is held is the mix + /// that is being set, and nothing is rebuilt to make that true -- no reseek, + /// so no `reset_after_reseek` and no blink in the picture behind the card + /// ([`engine::PlaybackSession::set_lane_gain_db`]). fn nudge_mix(&mut self, steps: i32, cx: &mut Context) { let lanes = self.mix_lanes(); let Some(session) = self.session.as_mut() else { @@ -4165,8 +4209,13 @@ impl Player { if self.export.is_some() { return; } - let settings = + let mut settings = export_settings(self.quality, self.custom_mbps, self.format, self.audio_kbps); + // The track the library has picked is the one that travels -- the same + // row the overlay draws, so the file carries what was watched. Set here + // rather than inside `export_settings`, which the card also calls for + // the *estimate* and which nothing else needs a subtitle for. + settings.subtitles = Some(self.sub_track); let Some(session) = &mut self.session else { self.notice = Some("NOTHING TO EXPORT — open a file first".into()); cx.notify(); @@ -5279,11 +5328,17 @@ impl Player { /// `None` -- no element at all -- while the toggle is off, with no track /// picked, and between cues: the picture is what this window is for, and a /// permanent empty band across it would be in the way of exactly that. + /// + /// The cues are the *timeline's* ([`PlaybackSession::timeline_cues`]) and + /// not the track's own: on a cut timeline an embedded track's cues ride the + /// pictures they belong to, and this is the same map the export writes the + /// file with -- so what is read here is what the file says. fn subtitle_overlay(&self, at: f64) -> Option> { if !self.subs_on { return None; } - let cues = cues_at(&self.subtitle_track()?.cues, at); + let mapped = self.session.as_ref()?.timeline_cues(self.sub_track); + let cues = cues_at(&mapped, at); if cues.is_empty() { return None; } @@ -5599,6 +5654,30 @@ impl Player { this.open_picker(Pick::Resolution, event.position(), cx) }), )) + // The rate every clip is counted in, which is also the rate + // the export is written at -- the other half of "the project + // is not the media", and the one the panel could only ever + // read out before. A click opens the rates with this one + // marked; picking one conforms the whole timeline to it. + .child(control( + "fps", + None, + match self.session.is_some() { + true => format!("{} fps", fps_label(self.fps)), + false => "Rate".to_string(), + }, + match self.session.is_some() { + true => format!( + "click to pick a frame rate — the project is cut at {} fps", + fps_label(self.fps) + ), + false => "the project's frame rate — open a file first".to_string(), + }, + live, + cx.listener(|this, event: &ClickEvent, _, cx| { + this.open_picker(Pick::Fps, event.position(), cx) + }), + )) // How much of the timeline the panel below is showing -- // beside the resolution, since neither of them edits // anything: they are both what is being looked at. The @@ -6453,6 +6532,27 @@ impl Player { })); } list.push(r.into_any_element()); + // What happens to the picked subtitle track, in one line: it is written + // into the file, or the reason it is not. Nothing to pick here -- which + // track is the library's row and the container is the format row above + // -- so the row says and does not answer, like the machine lines below. + list.push( + entry( + ("subtitles", 0), + "", + "Subtitles".into(), + self.session + .as_ref() + .map_or_else( + || "none".into(), + |s| s.planned_subtitles(self.format, Some(self.sub_track)), + ) + .into(), + false, + false, + ) + .into_any_element(), + ); let destination = entry( ("destination", 0), "d", @@ -8298,7 +8398,17 @@ impl Player { ), } .into(); - let cues: Vec<(f32, f32)> = track.cues.iter().map(|cue| cue_box(scale, cue)).collect(); + // Where the cues are on *this* timeline and not in the file they came + // from ([`PlaybackSession::timeline_cues`]) -- the same map the plate + // over the picture and the export both go through, which is what keeps + // a mark under the take it is spoken over after a cut. + let cues: Vec<(f32, f32)> = self + .session + .as_ref()? + .timeline_cues(self.sub_track) + .iter() + .map(|cue| cue_box(scale, cue)) + .collect(); Some( div() .flex_none() @@ -10035,6 +10145,53 @@ fn resolution_choices(current: (u32, u32), native: (u32, u32)) -> Vec .collect() } +/// Every project frame rate on offer, slowest first: [`FRAME_RATES`] with the +/// media's own cycled in at its place by speed, so a project already cut at a +/// listed rate does not see it twice and the media's own rate -- the one a +/// project moved off it has no other way back to -- is always there. +/// [`resolution_ladder`]'s rule, for the other setting the project has of its +/// own. +fn frame_rate_ladder(native: f64) -> Vec { + let mut rates = FRAME_RATES.to_vec(); + // Bit for bit: 23.976023976... is not 23.976, and a rate that read as + // "already listed" when it is not would take the media's own off the list. + if !rates.contains(&native) { + let at = rates + .iter() + .position(|&fps| fps > native) + .unwrap_or(rates.len()); + rates.insert(at, native); + } + rates +} + +/// The rate list's rows: every rung of the ladder, the media's own said so, and +/// the one in force marked. Named as a person writes a rate ([`fps_label`]), +/// with what it is for beside it -- short, or the row loses its tail to the +/// truncation the resolution list already met. +fn fps_choices(current: f64, native: f64) -> Vec { + frame_rate_ladder(native) + .into_iter() + .map(|fps| { + ( + Choice::Fps(fps), + format!("{} fps", fps_label(fps)).into(), + match fps == native { + true => "the media's own".to_string(), + // The rates that are a ratio are the ones nobody can tell + // from their neighbour by the label alone. + false => match (fps - fps.round()).abs() < 0.001 { + true => String::new(), + false => "NTSC".to_string(), + }, + } + .into(), + fps == current, + ) + }) + .collect() +} + /// The fit list's rows: all four policies against the canvas they place a /// picture on, since the word alone ("fill") says nothing about the size it is /// filling -- which is the very thing the notice says after a stroke. @@ -10212,6 +10369,10 @@ fn export_settings( // badly, which is a thing about the machine and not about the output -- // `VE_SW_ENC` already says it, and to the whole run rather than once. force_sw: false, + // The picked track is put on by `start_export`, which is the only + // caller that writes a file; the rest of them are asking about the + // bitrate and the format. + subtitles: None, } } @@ -11638,7 +11799,8 @@ mod tests { containers, enable, envelope, eq_card_w, eq_freq, eq_freq_label, eq_spectrum, eq_x, eq_y, estimated_mb, export_path, export_settings, format_key, - format_line, format_refusal, fps_label, frac_along, frac_down, frame_at, histogram, + format_line, format_refusal, fps_choices, fps_label, frac_along, frac_down, frame_at, + frame_rate_ladder, histogram, inserted_band, is_bare_modifier, is_project, keymap, keys_filter, keys_rows, lanes_h, marked, menu_at, next_audio_kbps, next_container, normalise, nothing_to_play, panel_h, project_path, retarget, scrub_due, show_label, silence_rate, snap_cue, snap_marks, snapped, @@ -11647,7 +11809,8 @@ mod tests { whole_take, window_title, }; use super::{ - Choice, ETA_SPAN, Edge, FITS, LaneKind, PPS_DEFAULT, RESOLUTIONS, Repeat, Scale, View, + Choice, ETA_SPAN, Edge, FITS, FRAME_RATES, LaneKind, PPS_DEFAULT, RESOLUTIONS, Repeat, + Scale, View, ZOOM_MAX_SECONDS, ZOOM_MIN_FRAMES, ZOOM_STEP, audio_rate_choices, clock, eta_secs, file_name, file_uri, fit_choices, landing, lane_refuses, library_rows, live_idx, next_fit, next_resolution, note_progress, px_along, @@ -14584,10 +14747,35 @@ mod tests { assert!(fits[2].3, "the clip's own policy is not marked"); assert!(fits[0].2.contains("1920x1080"), "{}", fits[0].2); + // The rate list, the other setting the project has of its own: every + // rate on offer, the media's own cycled in at its place by speed and + // said so, and the one the timeline is cut at marked. The value carried + // is the `f64` the engine conforms to, not the rounded label -- 23.976 + // is not 24000/1001, and a rate the timescales cannot name is refused. + let ntsc = 24_000. / 1001.; + let rates = frame_rate_ladder(25.); + assert_eq!(rates.len(), FRAME_RATES.len(), "25 is already on the list"); + let odd = frame_rate_ladder(48.); + assert_eq!(odd[5], 48., "the media's own, in its place by speed"); + assert_eq!(odd.len(), FRAME_RATES.len() + 1); + let fps = fps_choices(ntsc, 48.); + assert_eq!(fps.len(), odd.len()); + assert_eq!(fps.iter().filter(|(.., picked)| *picked).count(), 1); + assert_eq!(fps[0].0, Choice::Fps(ntsc), "the ratio, not 23.976"); + assert_eq!(fps[0].1.as_ref(), "23.976 fps"); + assert!(fps[0].3, "the rate in force is not marked"); + assert!(fps[5].2.contains("the media's own"), "{}", fps[5].2); + for (.., detail, _) in &fps { + assert!(detail.chars().count() < 26, "{detail} loses its tail"); + } + // The open list fits the floor the menus are measured against: the - // longest of them is the resolution ladder, and it hangs at the pointer - // with every row on screen. Rows are click targets (WCAG 2.5.8). + // longest of them is the rate ladder with an odd rate cycled in, and it + // hangs at the pointer with every row on screen. Rows are click targets + // (WCAG 2.5.8). assert!(MENU_ROW_H >= HIT_MIN); + assert!(odd.len() > ladder.len(), "the longest list moved"); + assert!(MENU_PAD * 2. + odd.len() as f32 * MENU_ROW_H <= 360.); let tall = MENU_PAD * 2. + ladder.len() as f32 * MENU_ROW_H; assert!(tall <= 360., "the list is taller than the floor"); assert_eq!( @@ -15171,6 +15359,45 @@ mod tests { }; assert!(subtitle_detail(&refused).contains("pictures")); assert!(cues_at(&refused.cues, 1.).is_empty()); + + // ...and what the plate and the strip draw after a *cut*: the timeline's + // own clock, asked of the engine through the very map an export writes + // the file with (`PlaybackSession::timeline_cues`), so the preview and + // the file cannot drift apart. The numbers are the export's own + // (`export::a_subtitle_file_beside_the_media_keeps_the_timelines_own_ + // clock`): 0.5s..2.5s rippled out of a five-second timeline leaves + // three seconds, which clips the second cue and takes the third away + // altogether -- while the track itself still holds all three, which is + // exactly why the drawing may not read them straight. + let lanes = session.lanes(); + session + .cut_regions(&[(15, 60)], &lanes) + .expect("cut 0.5s..2.5s out"); + assert_eq!(session.timeline_duration(), 3.0); + assert_eq!(session.subtitles()[0].cues.len(), 3, "the track is untouched"); + let mapped = session.timeline_cues(0); + assert_eq!( + mapped + .iter() + .map(|c| (c.start_us, c.end_us)) + .collect::>(), + vec![(500_000, 1_500_000), (2_000_000, 3_000_000)] + ); + // The overlay's own two lines, at the same moments as above. + let drawn = |t: f64| -> Vec { + cues_at(&mapped, t) + .into_iter() + .map(|c| c.text.clone()) + .collect() + }; + assert_eq!(drawn(0.7), ["first line"]); + assert_eq!(drawn(2.5), ["second line\nwith a break"]); + assert!( + drawn(4.2).is_empty(), + "a cue past the cut end is drawn where the file writes none" + ); + // ...and the strip's: the second cue is one second wide now, not 1.25. + assert_eq!(cue_box(scale, &mapped[1]), (80., 40.)); } #[test] diff --git a/crates/engine/src/audio.rs b/crates/engine/src/audio.rs index 80a317e..d424d9b 100644 --- a/crates/engine/src/audio.rs +++ b/crates/engine/src/audio.rs @@ -28,7 +28,9 @@ use std::fs::File; use std::io::BufReader; use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use std::sync::mpsc::{Receiver, SyncSender, sync_channel}; +use std::sync::{Arc, Mutex}; use std::thread; use mp4::{AudioObjectType, ChannelConfig, MediaType, Mp4Reader, Mp4Track, TrackType}; @@ -152,6 +154,67 @@ pub struct StreamInfo { pub decodable: bool, } +/// The mix settings a *running* mixer reads: what each lane is turned by on its +/// way into the sum and the ceiling the sum comes out through, both swappable +/// while the stream plays. +/// +/// This is what keeps a fader off the reseek path. Everything else a timeline +/// says lives inside a decode worker -- a segment's window, its curve, its rate +/// -- and can only be changed by rebuilding it, which is a flush, a re-open and +/// a hole in the sound. These two live at the sum, where nothing is decoded, so +/// the mixer can pick them up between one block and the next: an arrow key held +/// down on a fader moves the level and nothing else moves at all. +/// +/// One of these belongs to one mixer thread. [`is_live`](MixControls::is_live) +/// is what says whether a mixer is actually reading it -- a single lane at +/// unity with the limiter off is not mixed at all +/// ([`AudioSession::open_mixed_streams_master`]), and a caller that finds this +/// dead has to reopen the stream to be heard. +pub struct MixControls { + /// Bumped by every change; the mixer reloads when the number it last saw + /// is not this one, so an unchanged mix costs one relaxed load per block. + version: AtomicU64, + /// The lane amplitudes and the limiter, together: they are set together and + /// a mixer that read half of one change and half of the next would be + /// mixing a state nobody asked for. + state: Mutex<(Vec, Limiter)>, + /// A mixer thread has these; see the type docs. + live: AtomicBool, +} + +impl MixControls { + pub fn new(gains: Vec, limiter: Limiter) -> Arc { + Arc::new(Self { + version: AtomicU64::new(0), + state: Mutex::new((gains, limiter)), + live: AtomicBool::new(false), + }) + } + + /// Hands the running mixer a new mix. Cheap enough for a key repeat: a lock + /// held for a `Vec` swap and an atomic. + pub fn set(&self, gains: Vec, limiter: Limiter) { + *self.state.lock().unwrap() = (gains, limiter); + self.version.fetch_add(1, Ordering::Release); + } + + /// Whether a mixer thread is reading this at all. + pub fn is_live(&self) -> bool { + self.live.load(Ordering::Acquire) + } + + /// The mix, if it has moved since `seen`. `None` -- the every-block case -- + /// takes no lock. + fn changed(&self, seen: &mut u64) -> Option<(Vec, Limiter)> { + let now = self.version.load(Ordering::Acquire); + if now == *seen { + return None; + } + *seen = now; + Some(self.state.lock().unwrap().clone()) + } +} + pub struct AudioSession; impl AudioSession { @@ -497,6 +560,26 @@ impl AudioSession { speeds: &[Vec>], gains: &[f32], limiter: Limiter, + ) -> crate::Result)>> { + Self::open_mixed_streams_live(sources, lanes, eqs, speeds, gains, limiter, None) + } + + /// [`open_mixed_streams_master`](Self::open_mixed_streams_master) with the + /// mix left *reachable*: `live` is the handle the mixer picks its gains and + /// its limiter off between blocks, so a fader moved while the stream plays + /// is heard without the stream being rebuilt ([`MixControls`]). + /// + /// `gains`/`limiter` still say what it starts as -- they are what decides + /// whether there is a mixer at all -- and the handle is marked live only + /// when there is one. An export passes `None`: nothing can move under it. + pub fn open_mixed_streams_live( + sources: &[(PathBuf, usize)], + lanes: &[Vec<(Option, f64, f64)>], + eqs: &[Vec>], + speeds: &[Vec>], + gains: &[f32], + limiter: Limiter, + live: Option<&Arc>, ) -> crate::Result)>> { let [first, rest @ ..] = lanes else { return Ok(None); @@ -540,12 +623,20 @@ impl AudioSession { let mut gains = gains.to_vec(); gains.resize(lanes.len(), 1.0); // Built here, off the thread that will run it, where the rate is known. - let limiter = limiter + let state = limiter .is_active() .then(|| LimiterState::new(&limiter, meta.sample_rate, channels)); + // Marked before the spawn rather than inside it: a caller asks this the + // moment the open returns, and a flag set on the far thread would still + // read dead. + let live = live.map(|live| { + live.live.store(true, Ordering::Release); + live.clone() + }); + let rate = meta.sample_rate; thread::Builder::new() .name("audio-mix".into()) - .spawn(move || mix(&rxs, channels, &gains, limiter, &tx))?; + .spawn(move || mix(&rxs, channels, gains, state, rate, live.as_deref(), &tx))?; Ok(Some((meta, rx))) } @@ -2124,10 +2215,15 @@ struct Worker { fn mix( rxs: &[Receiver], channels: usize, - gains: &[f32], + mut gains: Vec, mut limiter: Option, + rate: u32, + controls: Option<&MixControls>, tx: &SyncSender, ) { + // The version of the mix these gains and this limiter came from; see the + // reload at the head of the loop. + let mut seen = 0; let mut pending: Vec> = rxs.iter().map(|_| Vec::new()).collect(); let mut live: Vec = rxs.iter().map(|_| true).collect(); // Numbering follows lane 0, whose first chunk says where it starts. @@ -2135,6 +2231,24 @@ fn mix( let mut emitted = 0; let mut out: Vec = Vec::new(); loop { + // A mix moved while the stream plays, picked up between two blocks: + // the levels change at a block boundary and nothing else changes at + // all -- no flush, no re-open, no hole. The limiter is *retuned* rather + // than rebuilt, so its delay line keeps running and the sample count + // the master clock is made of does not move ([`LimiterState::retune`]). + if let Some((next, params)) = controls.and_then(|c| c.changed(&mut seen)) { + gains = next; + gains.resize(rxs.len(), 1.0); + match limiter.as_mut() { + Some(state) => state.retune(¶ms), + // First time it has ever been switched in on this stream: the + // one that swallows nothing, for the count's sake. + None if params.is_active() => { + limiter = Some(LimiterState::engaged(¶ms, rate, channels)); + } + None => {} + } + } for (i, rx) in rxs.iter().enumerate() { while live[i] && pending[i].is_empty() { match rx.recv() { diff --git a/crates/engine/src/decode.rs b/crates/engine/src/decode.rs index c26256e..98edef9 100644 --- a/crates/engine/src/decode.rs +++ b/crates/engine/src/decode.rs @@ -87,7 +87,7 @@ impl Backend { pub struct BackendCell(Arc); impl BackendCell { - fn new(backend: Backend) -> Self { + pub(crate) fn new(backend: Backend) -> Self { Self(Arc::new(AtomicU8::new(backend.code()))) } diff --git a/crates/engine/src/edith.rs b/crates/engine/src/edith.rs index 0a8890c..9b3927a 100644 --- a/crates/engine/src/edith.rs +++ b/crates/engine/src/edith.rs @@ -19,10 +19,13 @@ //! gain audio 1 -3.0 //! ``` //! -//! The `fps` line is the rate the timeline was cut at, printed so it reads back -//! bit-exactly. A file without one (every dialect before v9) means "whatever -//! the scaffolding source runs at", which is what such a project always was and -//! is an answer only a project holding a video has +//! The `fps` line is the rate the timeline was cut at -- the scaffolding +//! source's own unless a rate was picked +//! ([`crate::PlaybackSession::set_frame_rate`]), and the *only* thing that says +//! so once one was, since every clip number in the file is counted in it. +//! Printed so it reads back bit-exactly. A file without one (every dialect +//! before v9) means "whatever the scaffolding source runs at", which is what +//! such a project always was and is an answer only a project holding a video has //! ([`crate::PlaybackSession::open_project`]). //! //! A `subtitle` line is `subtitle `: which track of that file the diff --git a/crates/engine/src/export.rs b/crates/engine/src/export.rs index 467261b..94aac2a 100644 --- a/crates/engine/src/export.rs +++ b/crates/engine/src/export.rs @@ -66,9 +66,10 @@ use oxideav_core::Muxer as _; use crate::audio::{AudioMeta, AudioSession}; use crate::demux::{Demuxer, VideoMeta}; use crate::hw::{HwEncoder, HwSession}; -use crate::mux::{AudioParams, Av1Params, HevcParams, MkvMuxer, Mp4Muxer, VideoParams}; +use crate::mux::{AudioParams, Av1Params, HevcParams, MkvMuxer, Mp4Muxer, SubParams, VideoParams}; use crate::project::{LaneKind, Project, Rate}; use crate::scale::Composer; +use crate::subtitle::{Cue, SubtitleTrack}; /// Progress is reported in permille: an atomic integer the render loop can read /// without a lock, fine enough for any progress bar. @@ -241,6 +242,16 @@ pub struct ExportSettings { /// it used to. Means nothing to WAV and FLAC, which code no rate, and /// nothing to a *copied* AAC track, which carries its source's. pub audio_kbps: Option, + /// Which of the project's subtitle tracks travels with the file: an index + /// into [`Project::subtitles`], which is the same list a front-end picks a + /// row of. `None` writes none -- what every caller wrote before there was a + /// choice, so an export of a timeline without subtitles is the file it + /// always was, byte for byte. + /// + /// Only a Matroska container carries it: an mp4's `tx3g` is a different + /// beast and nothing here writes one, so an mp4 export says so + /// ([`planned_subtitles`]) rather than dropping the track in silence. + pub subtitles: Option, } struct Shared { @@ -546,6 +557,139 @@ pub fn audio_rate_refusal(project: &Project, format: Format) -> Option<&'static } } +/// The track a Matroska export carries, or `None`: no pick, a pick nothing +/// answers, a track that could not be read, one with no cue left on the +/// exported timeline -- and every mp4, whose refusal [`planned_subtitles`] says +/// out loud before the button is pressed. +fn export_subtitles( + project: &Project, + meta: &VideoMeta, + settings: &ExportSettings, +) -> Option { + if !matches!(settings.format, Format::Av1 | Format::Hevc) { + return None; + } + let track = project.subtitles().get(settings.subtitles?)?; + if track.refused.is_some() { + return None; + } + let cues = timeline_cues(project, track, meta.frame_rate); + (!cues.is_empty()).then(|| SubParams { + label: track.label.clone(), + cues, + }) +} + +/// The track's cues where the *exported* timeline puts them, which is the only +/// clock the file has: the export writes timeline frame 0 onwards and nothing +/// else, exactly as the sound is mixed from frame 0 and resized to the +/// timeline's own length ([`encode_audio`]). +/// +/// Which clock the cues arrive in is what the track itself says: +/// +/// * a track out of a *file* (`SubtitleTrack::track`) is timed against that +/// file, so each cue is carried through the spans that play it -- a cue over +/// a stretch that was cut out is gone, one straddling a cut keeps the half +/// that is still there, and one after a rippled delete moves back with the +/// picture it belongs to. The *edges* a cut clips to are frames -- that is +/// what a cut is -- but a cue nothing clipped keeps its own microseconds, so +/// an untouched timeline exports the times the source states. +/// * a *standalone* file (`subs.srt`) is timed against nothing else -- there is +/// no clip to hang it on and no offset in the project to shift it by -- so it +/// is the timeline's own clock, which is where it was drawn while editing +/// (`Player::subtitle_overlay`). Clipped to the exported length and no more. +/// +/// This is also what the *preview* draws: the plate over the picture and the +/// timeline strip both ask it through +/// [`PlaybackSession::timeline_cues`](crate::PlaybackSession::timeline_cues), so +/// what a rippled timeline shows and what its export writes are one answer by +/// construction rather than two maps kept in step by hand. +/// +/// Pure and cheap enough to ask per repaint (a walk of the spans and of the +/// cues, no file opened), which is how a front-end asks it. +pub fn timeline_cues(project: &Project, track: &SubtitleTrack, fps: f64) -> Vec { + let frames = project.timeline_frames(); + let us = |frame: u32| (f64::from(frame) / fps * 1e6).round() as i64; + let end = us(frames); + // The file the cues are timed against, when there is one on this timeline. + // A track whose media has since been dropped from the project has no span + // to be carried through and falls back to the timeline's clock, which is + // what it was drawn on. + // + // Through the same `canonical` a source is indexed by, or the two spellings + // of one file (an argv `../assets/film.mkv`, a symlinked folder) would read + // as two files and the cues would quietly fall back to the timeline's clock. + let source = track.track.and_then(|_| { + let path = crate::project::canonical(&track.path); + project.sources().iter().position(|s| s.path == path) + }); + let Some(source) = source else { + return track + .cues + .iter() + .filter_map(|cue| { + let (start_us, end_us) = (cue.start_us.max(0), cue.end_us.min(end)); + (end_us > start_us).then(|| Cue { + start_us, + end_us, + text: cue.text.clone(), + }) + }) + .collect(); + }; + let mut out = Vec::new(); + for span in project.composite_spans_from(0) { + let Some((_, in_frame)) = span.from.filter(|&(from, _)| from == source) else { + continue; + }; + // What of the file this span plays, as *time in the file*: a clip counts + // the timeline's frames whatever its file was shot at ([`Rate`]), which + // is what makes those frames the same seconds a cue is timed in. + let (first, last) = (us(in_frame), us(in_frame + span.source_len())); + // Where that lands, and how fast: a cue is carried by the same factor + // the pictures under it are, so a slowed clip stretches its subtitles + // with it instead of leaving them behind. + let start = us(span.start); + let onto = |t: i64| start + ((t - first) as f64 / span.speed.as_f64()).round() as i64; + for cue in &track.cues { + let (a, b) = (cue.start_us.max(first), cue.end_us.min(last)); + if b <= a { + continue; // wholly outside what this span kept + } + out.push(Cue { + start_us: onto(a), + end_us: onto(b).min(end), + text: cue.text.clone(), + }); + } + } + // The spans come in timeline order but a cue's *own* order across them does + // not: a Matroska muxer writes blocks as they come up. + out.sort_by_key(|cue| cue.start_us); + out +} + +/// What [`start`] would do about the subtitles, in the words a card shows. +/// Pure, like [`planned_audio`]: no file is opened, so it may be asked per +/// repaint. +pub fn planned_subtitles(project: &Project, format: Format, pick: Option) -> String { + let Some(track) = pick.and_then(|i| project.subtitles().get(i)) else { + return "none".into(); + }; + if let Some(why) = &track.refused { + return format!("{} — {why}", track.label); + } + match format { + _ if track.cues.is_empty() => "none".into(), + Format::Av1 | Format::Hevc => format!("{} → embedded", track.label), + // Said before the export rather than after it: an mp4 carries text in + // `tx3g` and nothing here writes one, so the honest answer is the + // container that does. + format if format.has_video() => "mkv only — an mp4 carries none".into(), + _ => "none — this format is the sound alone".into(), + } +} + /// What [`start`] would encode the picture with, probed the way the export /// probes it -- the very encoder is opened and closed again -- so this is a /// measurement and not a promise. `None` for a format that carries no picture. @@ -791,6 +935,10 @@ fn run( // Taken by the Matroska muxer at creation; the mp4 one writes its track // after the picture, so for that path this is still `Some` at the end. let mut packets = audio.map(|track| track.packets); + // ...and the cues with them, for the same reason: the subtitle track is + // declared in the header and its blocks are interleaved into the clusters, + // so the muxer needs the lot before the first picture is written. + let mut subs = export_subtitles(project, meta, settings); // One header parse per source, before any of them is decoded: what rate // each file was shot at against the timeline's ([`Rate`]), which is how the @@ -939,6 +1087,7 @@ fn run( settings, audio_params.as_ref(), &mut packets, + &mut subs, au, key, )?; @@ -959,6 +1108,7 @@ fn run( settings, audio_params.as_ref(), &mut packets, + &mut subs, au, key, )?; @@ -1419,6 +1569,7 @@ fn write_video( settings: &ExportSettings, audio: Option<&AudioParams>, packets: &mut Option>, + subs: &mut Option, au: &[u8], key: bool, ) -> crate::Result<()> { @@ -1446,6 +1597,7 @@ fn write_video( hvcc: &hvcc, }, sound, + subs.take(), )?)) else { unreachable!("just inserted a Matroska muxer") }; @@ -1502,6 +1654,7 @@ fn write_video( out, ¶ms(meta, au)?, sound, + subs.take(), )?)) else { unreachable!("just inserted a Matroska muxer") }; @@ -2156,6 +2309,102 @@ impl SwDecoder { mod tests { use super::*; + /// A track of three cues, in whichever clock `track` says: `Some(n)` is a + /// track of the media file, `None` a `.srt` beside it. + fn subtitles(path: &str, track: Option) -> SubtitleTrack { + SubtitleTrack { + path: path.into(), + track, + label: "eng".into(), + cues: vec![ + Cue { + start_us: 500_000, + end_us: 1_500_000, + text: "first".into(), + }, + Cue { + start_us: 2_000_000, + end_us: 3_250_000, + text: "second".into(), + }, + Cue { + start_us: 4_000_000, + end_us: 4_750_000, + text: "third".into(), + }, + ], + refused: None, + } + } + + /// A standalone subtitle file is timed against the timeline itself -- there + /// is no clip to hang it on -- so a cut moves the pictures and not it. What + /// it does get is the exported length: a cue past the end of the file would + /// otherwise be a block after the last picture. + /// + /// The pair of this, the embedded clock, is measured against a real exported + /// file in `tests/export_subs.rs`; both live in one function and this is the + /// half that needs no encoder. + #[test] + fn a_subtitle_file_beside_the_media_keeps_the_timelines_own_clock() { + // 5 seconds at 30, with `[0.5s, 2.5s)` cut out of it: 3 seconds left. + let mut project = Project::single("/nonexistent/film.mp4", 150); + let track = subtitles("/nonexistent/film.srt", None); + assert!(project.ripple_delete(15, 60)); + assert_eq!(project.timeline_frames(), 90); + let cues = timeline_cues(&project, &track, 30.0); + assert_eq!( + cues, + vec![ + Cue { + start_us: 500_000, + end_us: 1_500_000, + text: "first".into() + }, + // Clipped to the three seconds the export writes... + Cue { + start_us: 2_000_000, + end_us: 3_000_000, + text: "second".into() + }, + // ...and the one wholly past the end is not written at all. + ] + ); + // A track *of a file* the project no longer plays has no span to be + // carried through either, so it falls back to the same clock rather + // than exporting nothing. + let orphan = subtitles("/nonexistent/other.mkv", Some(2)); + assert_eq!(timeline_cues(&project, &orphan, 30.0).len(), 2); + } + + /// The embedded clock, without an encoder in it: the cut moves the cues with + /// the pictures, and a cue nothing clipped keeps its own microseconds. + #[test] + fn a_track_of_the_media_is_carried_through_the_cut() { + let mut project = Project::single("/nonexistent/film.mkv", 150); + let track = subtitles("/nonexistent/film.mkv", Some(2)); + assert!(project.ripple_delete(15, 60), "cut 0.5s..2.5s out"); + let cues = timeline_cues(&project, &track, 30.0); + assert_eq!( + cues, + vec![ + // The first cue was wholly inside the cut. The second straddled + // its far edge and kept the 0.75s that is still there... + Cue { + start_us: 500_000, + end_us: 1_250_000, + text: "second".into() + }, + // ...and the third simply moves back the two seconds that went. + Cue { + start_us: 2_000_000, + end_us: 2_750_000, + text: "third".into() + }, + ] + ); + } + #[test] fn bitrate_clamps_at_both_ends() { let meta = |width, height, frame_rate| VideoMeta { diff --git a/crates/engine/src/limiter.rs b/crates/engine/src/limiter.rs index 61c5765..75b4107 100644 --- a/crates/engine/src/limiter.rs +++ b/crates/engine/src/limiter.rs @@ -106,6 +106,11 @@ pub struct LimiterState { /// delay line, which is how the latency is paid back (module docs). warm: usize, gain: f32, + /// Switched out while the mix runs ([`LimiterState::retune`]): the line + /// still delays and still emits a frame per frame, only nothing is held + /// down. Dropping the state instead would drop the frames still inside the + /// line, and those frames are what the master clock counts. + bypass: bool, ceiling: f32, /// Where the knee starts, as an amplitude: under this the fast path runs /// and no logarithm is taken. @@ -125,6 +130,7 @@ impl LimiterState { at: 0, warm: frames - 1, gain: 1.0, + bypass: !params.on, ceiling: db_to_linear(ceiling_db), knee_floor: db_to_linear(ceiling_db - KNEE_DB / 2.0), // One time constant per sample: the gain covers 63% of the way back @@ -133,6 +139,34 @@ impl LimiterState { } } + /// One switched in **while the mix is already running**: the same limiter, + /// except that it swallows nothing to fill its delay line -- what comes out + /// first is the line's own [`LOOKAHEAD_MS`] of silence and the mix behind + /// it, where a fresh state would have eaten that much of the mix instead. + /// + /// Which matters because the count *is* the clock: a mixer that emitted + /// fewer samples than the timeline asked for would slide the picture off + /// the sound by the lookahead, once per switch-on. A hair of silence at the + /// moment somebody engages a limiter is the honest price. + pub fn engaged(params: &Limiter, sample_rate: u32, channels: usize) -> Self { + Self { + warm: 0, + ..Self::new(params, sample_rate, channels) + } + } + + /// Points a running limiter at another setting -- a ceiling dragged, the + /// switch flipped -- without touching the delay line, the peak window or + /// the gain it is holding. That is what makes the ceiling a live control: + /// rebuilding the state would restart the window (a pump) and lose the + /// frames inside the line (a slip against the picture). + pub fn retune(&mut self, params: &Limiter) { + let ceiling_db = params.with_ceiling(params.ceiling_db).ceiling_db; + self.bypass = !params.on; + self.ceiling = db_to_linear(ceiling_db); + self.knee_floor = db_to_linear(ceiling_db - KNEE_DB / 2.0); + } + /// Rewrites `buf` -- interleaved frames -- as the limited mix. Shorter than /// what came in by the delay line's length, once, at the first call. pub fn process(&mut self, buf: &mut Vec) { @@ -163,8 +197,14 @@ impl LimiterState { self.warm -= 1; continue; } + // Bypassed, the line is a delay and nothing else: the frames come + // out as they went in, one for one. + let gain = match self.bypass { + true => 1.0, + false => self.gain, + }; for c in 0..channels { - out.push(self.line[self.at * channels + c] * self.gain); + out.push(self.line[self.at * channels + c] * gain); } } *buf = out; @@ -240,6 +280,56 @@ mod tests { assert_eq!(buf.len(), rate as usize * 2 - (state.peaks.len() - 1) * 2); } + /// A ceiling dragged while the mix runs: the new one is honoured from the + /// next block, the delay line keeps running -- so the block is as long as + /// it would have been, which is what the master clock counts -- and + /// switching the limiter out leaves the samples alone rather than dropping + /// the ones still inside the line. + #[test] + fn a_retune_moves_the_ceiling_and_costs_no_samples() { + let rate = 48_000; + let mut state = LimiterState::engaged( + &Limiter { + ceiling_db: -3.0, + on: true, + }, + rate, + 2, + ); + let block: Vec = (0..2_000).map(|i| 2.0 * ((i % 7) as f32 - 3.0)).collect(); + + // Engaged mid-stream: nothing is swallowed, so the count is the count. + let mut buf = block.clone(); + state.process(&mut buf); + assert_eq!(buf.len(), block.len(), "an engaged limiter ate samples"); + let hot = buf.iter().fold(0.0f32, |m, s| m.max(s.abs())); + assert!(hot <= db_to_linear(-3.0) + 1e-6, "peak {hot} passed -3 dB"); + + // Down to -12: the same length again, and quieter. + state.retune(&Limiter { + ceiling_db: -12.0, + on: true, + }); + let mut buf = block.clone(); + state.process(&mut buf); + assert_eq!(buf.len(), block.len(), "a retune ate samples"); + let quiet = buf.iter().fold(0.0f32, |m, s| m.max(s.abs())); + assert!(quiet <= db_to_linear(-12.0) + 1e-6, "peak {quiet} passed -12 dB"); + assert!(quiet < hot, "the ceiling did not move: {hot} -> {quiet}"); + + // Switched out: the line still delays, so the count still holds, and + // what comes out is the mix as it was written. + state.retune(&Limiter { + ceiling_db: -12.0, + on: false, + }); + let mut buf = block.clone(); + state.process(&mut buf); + assert_eq!(buf.len(), block.len(), "a bypass ate samples"); + let raw = buf.iter().fold(0.0f32, |m, s| m.max(s.abs())); + assert!(raw > 1.0, "bypassed, the mix is untouched: peak {raw}"); + } + /// Flat settings are a passthrough, which is what the export invariant /// rests on: 0 dB is exactly 1.0, never 0.9999999. #[test] diff --git a/crates/engine/src/mux.rs b/crates/engine/src/mux.rs index 6d6db49..e6539c0 100644 --- a/crates/engine/src/mux.rs +++ b/crates/engine/src/mux.rs @@ -482,6 +482,11 @@ const CODEC_DELAY: u32 = 0x56AA; const CLUSTER: u32 = 0x1F43_B675; const CLUSTER_TIMESTAMP: u32 = 0xE7; const SIMPLE_BLOCK: u32 = 0xA3; +const TRACK_NAME: u32 = 0x536E; +const TRACK_LANGUAGE: u32 = 0x22B59C; +const BLOCK_GROUP: u32 = 0xA0; +const BLOCK: u32 = 0xA1; +const BLOCK_DURATION: u32 = 0x9B; /// One millisecond, the tick every Matroska muxer writes and this one's block /// timestamps are in. The *rate* is not derived from these -- `DefaultDuration` @@ -532,6 +537,34 @@ pub struct HevcParams<'a> { pub hvcc: &'a [u8], } +/// The soft subtitle track a Matroska file carries beside the picture: text, +/// timed, still text in the file -- a player draws it and a user can turn it +/// off, which is what "soft" means and what burning it into the pixels is not. +/// +/// The cues are the *exported timeline's* (`export::timeline_cues` puts them +/// there), because the file's clock is the timeline's; nothing here shifts +/// anything. +pub struct SubParams { + /// What the track is called in the file. A three-letter code goes in as + /// `Language`, which is what a player's subtitle menu reads; anything else + /// is a `Name`, which is what it shows when there is no language to show. + /// + /// ponytail: one string for both because a [`crate::subtitle::SubtitleTrack`] + /// carries one label and not a (language, name) pair. The upgrade path is to + /// keep the two apart from the demuxer down -- `MkvSubtitle` already has + /// them -- and it belongs to whoever needs a per-language export list. + pub label: String, + /// In start order, which is the order they are written in. + pub cues: Vec, +} + +/// The cues waiting to be interleaved into the clusters, [`MkvAudio`]'s twin. +struct MkvSubs { + cues: Vec, + /// Cues already written. + next: usize, +} + /// Writes one AV1 video track as Matroska (`.mkv`), and the timeline's AAC /// beside it where there is any: an `A_AAC` track whose `CodecPrivate` is the /// two-byte `AudioSpecificConfig` an mp4's `esds` carries, which is what @@ -562,6 +595,9 @@ pub struct MkvMuxer { /// The AAC track, if the timeline has sound, and how far it has been /// written. audio: Option, + /// The subtitle track, if one travels with the file, and how far it has + /// been written. + subs: Option, } /// The sound waiting to be interleaved into the clusters. @@ -588,6 +624,7 @@ impl MkvMuxer { path: &Path, video: &Av1Params, audio: Option<(&AudioParams, Vec)>, + subs: Option, ) -> crate::Result { if video.config.is_empty() { return Err("no AV1 sequence header for the track's CodecPrivate".into()); @@ -602,6 +639,7 @@ impl MkvMuxer { b"V_AV1", &av1c, audio, + subs, ) } @@ -616,6 +654,7 @@ impl MkvMuxer { path: &Path, video: &HevcParams, audio: Option<(&AudioParams, Vec)>, + subs: Option, ) -> crate::Result { if video.hvcc.is_empty() { return Err("no hvcC record for the track's CodecPrivate".into()); @@ -628,9 +667,11 @@ impl MkvMuxer { b"V_MPEGH/ISO/HEVC", video.hvcc, audio, + subs, ) } + #[allow(clippy::too_many_arguments)] fn open( path: &Path, width: u32, @@ -639,6 +680,7 @@ impl MkvMuxer { codec_id: &[u8], codec_private: &[u8], audio: Option<(&AudioParams, Vec)>, + subs: Option, ) -> crate::Result { if !frame_rate.is_finite() || frame_rate <= 0.0 { return Err(format!("bad frame rate {frame_rate}").into()); @@ -697,6 +739,12 @@ impl MkvMuxer { if let Some((audio, _)) = &audio { elem(&mut tracks, TRACK_ENTRY, &aac_track_entry(audio)?); } + // Declared even where the audio track is not: the numbers are fixed + // (1 picture, 2 sound, 3 text) rather than counted, so a file with + // subtitles and no sound still says track 3 in its blocks. + if let Some(subs) = &subs { + elem(&mut tracks, TRACK_ENTRY, &subtitle_track_entry(&subs.label)); + } elem(&mut head, TRACKS, &tracks); let mut file = File::create(path)?; @@ -715,6 +763,10 @@ impl MkvMuxer { samples: 0, sample_rate: params.sample_rate.max(1), }), + subs: subs.map(|subs| MkvSubs { + cues: subs.cues, + next: 0, + }), }) } @@ -742,8 +794,10 @@ impl MkvMuxer { uint(&mut self.cluster, CLUSTER_TIMESTAMP, ts as u64); } // The sound this picture plays under goes in first, into the cluster the - // picture opened: a player reads the two together. + // picture opened: a player reads the two together. The cue over it with + // them, for the same reason. self.drain_audio(ts)?; + self.drain_subs(ts)?; self.block(1, ts, key, obus); self.frames += 1; Ok(()) @@ -784,6 +838,41 @@ impl MkvMuxer { } } + /// Every cue that has come up by `until`, into the current cluster -- + /// [`drain_audio`](MkvMuxer::drain_audio)'s twin, and `i64::MAX` at + /// [`finish`](MkvMuxer::finish) writes what is left: a cue may still be on + /// screen over the last picture, and one written nowhere is one a player + /// never shows. + fn drain_subs(&mut self, until: i64) -> crate::Result<()> { + loop { + let Some(subs) = &mut self.subs else { + return Ok(()); + }; + let Some(cue) = subs.cues.get_mut(subs.next) else { + return Ok(()); + }; + // Milliseconds, the tick this file is written in: a cue is read for + // a second or more and no eye finds the half a tick it rounds by. + let ts = (cue.start_us + 500) / 1_000; + if ts > until { + return Ok(()); + } + // A cue that says it ends before it starts stays up for one tick + // rather than for a duration a reader would take as unsigned. + let ms = ((cue.end_us - cue.start_us + 500) / 1_000).max(1) as u64; + let text = std::mem::take(&mut cue.text); + subs.next += 1; + // A cluster of its own where the text has run past what a 16-bit + // relative timestamp reaches, exactly as the sound's drain does. + if self.cluster.is_empty() || ts - self.cluster_ts >= CLUSTER_MS { + self.flush()?; + self.cluster_ts = ts; + uint(&mut self.cluster, CLUSTER_TIMESTAMP, ts as u64); + } + self.block_group(SUB_TRACK, ts, ms, text.as_bytes()); + } + } + /// One `SimpleBlock` of `track`, timed against the open cluster. Every AAC /// packet is a keyframe; a picture is one when the encoder said so. fn block(&mut self, track: u8, ts: i64, key: bool, payload: &[u8]) { @@ -795,6 +884,24 @@ impl MkvMuxer { elem(&mut self.cluster, SIMPLE_BLOCK, &block); } + /// One `BlockGroup`: a `Block` and the `BlockDuration` beside it. That pair + /// is how a cue says when it goes away -- a `SimpleBlock` has nowhere to put + /// a duration, and a subtitle without one stays up until whatever a player + /// decides, which is what a subtitle must never do. + fn block_group(&mut self, track: u8, ts: i64, duration_ms: u64, payload: &[u8]) { + let mut block = Vec::with_capacity(payload.len() + 4); + block.push(0x80 | track); // the track number as a one-byte EBML integer + block.extend_from_slice(&((ts - self.cluster_ts) as i16).to_be_bytes()); + // No flags a text block can carry: not lacing, and "keyframe" is a + // `SimpleBlock` field that a plain `Block` does not have at all. + block.push(0); + block.extend_from_slice(payload); + let mut group = Vec::new(); + elem(&mut group, BLOCK, &block); + uint(&mut group, BLOCK_DURATION, duration_ms); + elem(&mut self.cluster, BLOCK_GROUP, &group); + } + fn flush(&mut self) -> crate::Result<()> { if self.cluster.is_empty() { return Ok(()); @@ -814,6 +921,7 @@ impl MkvMuxer { // Whatever sound outlasts the last picture, before the last cluster is // closed: a track cut short here is a file that goes silent at the end. self.drain_audio(i64::MAX)?; + self.drain_subs(i64::MAX)?; self.flush()?; if self.frames == 0 { return Err("no frames were written to the Matroska file".into()); @@ -878,6 +986,36 @@ fn aac_track_entry(audio: &AudioParams) -> crate::Result> { Ok(entry) } +/// Which track a subtitle block names. Fixed, like the picture's 1 and the +/// sound's 2: a file with no audio track still writes its text on 3, so nothing +/// has to count tracks to read a block. +const SUB_TRACK: u8 = 3; + +/// The `TrackEntry` of the subtitle track: type 0x11 (subtitles) and +/// `S_TEXT/UTF8`, whose blocks are the cue's own UTF-8 text and whose timing is +/// the block's -- the codec every player draws and the one this project's own +/// reader parses back (`subtitle::cues_of`). +/// +/// The label is a `Language` where it is one (`eng`, `tur`: three letters is +/// what ISO-639-2 is) and a `Name` otherwise, which is exactly what +/// [`crate::subtitle::of_matroska`] reads back out, so a track exported and +/// re-imported keeps the name it had. +fn subtitle_track_entry(label: &str) -> Vec { + let mut entry = Vec::new(); + uint(&mut entry, TRACK_NUMBER, u64::from(SUB_TRACK)); + uint(&mut entry, TRACK_UID, u64::from(SUB_TRACK)); + uint(&mut entry, TRACK_TYPE, 0x11); + uint(&mut entry, FLAG_LACING, 0); + elem(&mut entry, CODEC_ID, b"S_TEXT/UTF8"); + let code = label.len() == 3 && label.bytes().all(|b| b.is_ascii_lowercase()); + match (code, label.is_empty()) { + (true, _) => elem(&mut entry, TRACK_LANGUAGE, label.as_bytes()), + (false, false) => elem(&mut entry, TRACK_NAME, label.as_bytes()), + (false, true) => {} + } + entry +} + /// The sequence header OBU of a coded temporal unit, for the track's /// `CodecPrivate`. `None` when the unit carries none, which the first keyframe /// of a stream never may -- no decoder can start without it. @@ -1444,6 +1582,7 @@ mod tests { }, packets, )), + None, ) .unwrap(); // Half a second of picture under a second of sound: the tail of the @@ -1571,6 +1710,7 @@ mod tests { config, }, None, + None, ) .unwrap(); muxer.write_frame(&key, true).unwrap(); @@ -1614,6 +1754,7 @@ mod tests { config: &[], }, None, + None, ) .is_err() ); diff --git a/crates/engine/src/playback.rs b/crates/engine/src/playback.rs index 1f6154e..002f3d2 100644 --- a/crates/engine/src/playback.rs +++ b/crates/engine/src/playback.rs @@ -12,7 +12,7 @@ //! the renderer decides which frame that means. use std::path::Path; -use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicI64, AtomicU64, Ordering}; use std::sync::mpsc::{Receiver, TryRecvError}; use std::sync::{Arc, Mutex}; use std::thread; @@ -32,6 +32,13 @@ use crate::scale::{Composer, FitPolicy}; /// only has to be short next to that; it costs one wakeup per 10 ms of audio. const RING_FULL_WAIT: Duration = Duration::from_millis(10); +/// How long the feeder waits out a ring that took *nothing*: the flush of a +/// restart, which only the device's own callback can clear (`engine-audio` +/// refuses a write queued behind one). Short, because this is the gap at the +/// head of every restart and the ear is in it -- one wakeup per millisecond, +/// for the millisecond or two it lasts. +const FLUSH_WAIT: Duration = Duration::from_millis(1); + /// The timeline a file with no picture scaffolds: 1080p at 30 fps, H.264 -- /// nothing was shot on it, so it is the canvas a *later* import meets rather /// than a description of the song. H.264 because it is the one codec that @@ -91,6 +98,18 @@ struct Audio { /// Bumped by every seek. A feeder only owns the device while this still /// matches the value it started with; see [`feed`]. epoch: Arc, + /// The device position the *current* stream's first real sample was queued + /// at, `-1` until the feeder has queued one. Written by the feeder under the + /// device lock, read by [`tick`](PlaybackSession::tick). + /// + /// This is what keeps a restart out of the timeline. Between a flush and the + /// first sample of the new stream the device plays silence -- a decoder open + /// is tens of milliseconds -- and that silence is elapsed *device* time + /// ([`crate::ao`] counts it, as it must: it really was played). It is not + /// elapsed *timeline* time, and a clock anchored on the first poll after a + /// seek counts it as such, which is a permanent offset between the picture + /// and the sound, re-rolled by every edit made while playing. + content_at: Arc, /// The last [`TAP_SAMPLES`] mono samples handed to the device, oldest /// first: what a meter or an analyser draws. Written by the feeder, which /// is not the device's own callback -- the plugin's RT thread never sees @@ -158,6 +177,11 @@ pub struct PlaybackSession { /// starts here, and a caller offering sizes to pick from needs the media's /// own among them or a project moved off it could never come back. native: (u32, u32), + /// ...and the scaffolding source's own frame rate, kept for exactly that + /// reason: the project rate starts here, and the list a caller offers rates + /// from needs the media's own on it or a project moved off it has no way + /// back ([`PlaybackSession::set_frame_rate`] is not an undo step either). + native_fps: f64, frames: Receiver, /// The current decode worker. worker: Worker, @@ -228,6 +252,39 @@ pub struct PlaybackSession { span: Option, /// The last clip has been played out; see [`PlaybackSession::is_eos`]. eos: bool, + /// The mix the running mixer is reading, when there is one: what lets a + /// fader and the master ceiling move without rebuilding the audio pipeline + /// at all ([`crate::audio::MixControls`]). `None` for a timeline that is + /// not mixed -- one audio lane at unity with the limiter off, which is the + /// bit-exact single-stream path -- and the first move off that reopens the + /// stream once, mixed, and lives from there. + mix: Option>, + /// An audio stream has been started and has not yet played a sample: the + /// window [`tick`](Self::tick) holds the clock still through, so the silence + /// of a restart is never counted as timeline time. See + /// [`Audio::content_at`]. + priming: bool, +} + +/// What an edit dirtied -- which half of the pipeline has to be rebuilt for the +/// change to be seen or heard, and, far more to the point, which half must not +/// be. +/// +/// Rebuilding a half is expensive and *audible*: the video worker costs a +/// decoder open (98 ms of VA-API init, worst case, measured) and the audio one +/// costs a flush, a re-open and a hole in the sound. A grade changes no sample +/// and a fader changes no picture, so neither may pay the other's price -- that +/// is the whole of this type. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +enum Dirty { + /// The picture only: a grade, a fit policy, the project resolution. The + /// sound keeps playing, untouched, and the clock never moves. + Picture, + /// The sound only: a clip's equalizer. The picture keeps playing. + Sound, + /// The timeline itself -- what is where, how long, how fast. Both halves + /// are rebuilt, because both are decoding the wrong thing. + Both, } impl PlaybackSession { @@ -277,6 +334,7 @@ impl PlaybackSession { Ok(Self { meta, native: (meta.width, meta.height), + native_fps: meta.frame_rate, frames: stream.frames, worker: stream.worker, backend: stream.backend, @@ -291,6 +349,8 @@ impl PlaybackSession { span_rate: Rate::REAL_TIME, span, eos: false, + mix: None, + priming: false, }) } @@ -375,6 +435,7 @@ impl PlaybackSession { Ok(Self { meta, native: (width, height), + native_fps: frame_rate, frames: stream.frames, worker: stream.worker, backend: stream.backend, @@ -395,6 +456,8 @@ impl PlaybackSession { span_rate: Rate::REAL_TIME, span, eos: false, + mix: None, + priming: false, }) } @@ -451,6 +514,7 @@ impl PlaybackSession { Ok(Self { meta, native: (meta.width, meta.height), + native_fps: IMAGE_ONLY_RATE, frames: stream.frames, worker: stream.worker, backend: stream.backend, @@ -465,6 +529,8 @@ impl PlaybackSession { span_rate: Rate::REAL_TIME, span, eos: false, + mix: None, + priming: false, }) } @@ -585,6 +651,32 @@ impl PlaybackSession { meta.width = width; meta.height = height; } + // ...and the project's own *rate*, which is the scaffold's unless the + // file says otherwise. The two made-up rates above already took the + // saved one (their counts are computed from it); a scaffold with a + // picture keeps its own here, so a project cut at a rate nobody picked + // is the file it always was -- and one where a rate *was* picked + // ([`set_frame_rate`](Self::set_frame_rate)) comes back at it rather + // than at the media's, which would leave every clip number counted in + // frames the timeline no longer has. + let native_fps = match crate::is_audio(&first.path) { + true => AUDIO_ONLY_CANVAS.2, + false if crate::is_image(&first.path) => IMAGE_ONLY_RATE, + false => meta.frame_rate, + }; + if let Some(fps) = saved_fps { + meta.frame_rate = fps; + } + // A song and a still have no rate of their own to be conformed from: + // their length above was counted in the timeline's frames already, + // whatever those are. A file with pictures is read through [`Rate`] like + // any other source when the project is cut at another rate. + let made_up = crate::is_audio(&first.path) || crate::is_image(&first.path); + let scaffold_rate = match made_up || native_fps == meta.frame_rate { + true => Rate::REAL_TIME, + false => Rate::from_fps(native_fps, meta.frame_rate) + .map_err(|e| format!("source {}: {e}", first.path.display()))?, + }; let first_audio = first_audio_of(&doc.sources)?; // In source order, with the scaffold's own count in its own slot: the @@ -599,8 +691,8 @@ impl PlaybackSession { let mut rates = Vec::with_capacity(doc.sources.len()); for (i, source) in doc.sources.iter().enumerate() { if i == scaffold { - counts.push(meta.frame_count); - rates.push(Rate::REAL_TIME); + counts.push(scaffold_rate.timeline_at(meta.frame_count)); + rates.push(scaffold_rate); continue; } // A still has neither a rate to match nor a track to match with: @@ -704,6 +796,7 @@ impl PlaybackSession { let mut session = Self { meta, native, + native_fps, frames: stream.frames, worker: stream.worker, backend: stream.backend, @@ -720,6 +813,8 @@ impl PlaybackSession { span_rate: Rate::REAL_TIME, span, eos: false, + mix: None, + priming: false, }; // The scaffolding above opened source 0 from its first frame and the // whole of its audio; this puts both onto the clip the playhead is @@ -752,6 +847,33 @@ impl PlaybackSession { crate::export::planned_audio(&self.project, format) } + /// What an export would do about the subtitle track at `pick` -- + /// [`crate::export::planned_subtitles`], asked of the project a front-end is + /// holding, and pure for the same reason. `pick` is a row of + /// [`subtitles`](Self::subtitles). + pub fn planned_subtitles(&self, format: crate::export::Format, pick: Option) -> String { + crate::export::planned_subtitles(&self.project, format, pick) + } + + /// Where the cues of the track at `pick` land on *this* timeline -- + /// [`crate::export::timeline_cues`], the very map an export writes the file + /// with, so a front-end that draws these draws what the file will say. On a + /// rippled or cut timeline that is the whole point: an embedded track rides + /// the spans that still play it, and a standalone `.srt` keeps the + /// timeline's own clock, clipped to its length. + /// + /// Empty for a row that is not there and for a track that could not be read. + /// Pure and file-free, so it may be asked per repaint; the cost is a walk of + /// the spans and of the cues. + pub fn timeline_cues(&self, pick: usize) -> Vec { + self.project + .subtitles() + .get(pick) + .map_or_else(Vec::new, |t| { + crate::export::timeline_cues(&self.project, t, self.meta.frame_rate) + }) + } + /// Why the sound's rate is not a choice for this timeline in this format -- /// [`crate::export::audio_rate_refusal`], asked of the project a front-end /// is holding, and pure for the same reason. @@ -899,8 +1021,20 @@ impl PlaybackSession { } } - /// Whether the timeline has been played out. Any seek clears it, so an edit - /// after the end (which reseeks) revives the session. + /// Whether the timeline has been played out: the picture worker ran to the + /// end and there was no next clip. It is exactly that and nothing more, + /// which is what decides who clears it -- **starting a picture does** + /// (`start_picture`), so a seek clears it and so does every edit that + /// rebuilds the picture (`Dirty::Picture`, `Dirty::Both` -- a paste or a + /// placement past the end revives the session, and it has a new picture to + /// show for it). + /// + /// A **sound-only** edit does not (`Dirty::Sound`: an equalizer, a fader): + /// it rebuilds the sound where the playhead stands and starts no picture + /// worker, so the last frame is still the last frame and this is still the + /// end. A front-end's `Ended` therefore survives an EQ tweak made after the + /// timeline ran out -- the parameters are on the project either way, and the + /// next press restarts from the top with them, which is what `Ended` means. pub fn is_eos(&self) -> bool { self.eos } @@ -1031,15 +1165,29 @@ impl PlaybackSession { gap.map_or(1, |s| s.len), )), }; - if let Ok(stream) = opened { - // Receiver first, worker second: the drop of the *old* receiver is - // what wakes the outgoing worker if it is parked in `send`, and only - // then can it return and be reaped by a later sweep. Nothing here - // joins, so this ordering costs the seek nothing. - self.frames = stream.frames; - self.backend = stream.backend; - self.retire(stream.worker); - } + let Ok(stream) = opened else { + // The file would not open. The span still goes in -- the timeline + // moves on, there are simply no more pictures -- but the *frames* + // must not: the old channel's pictures are numbered in the old + // source's frames, and presenting them under the new mapping would + // put the wrong picture at the wrong time (and leave + // [`decode_backend`](Self::decode_backend) describing a worker that + // is no longer feeding anything). A dead receiver instead, which is + // what carries the session on to the next span. The old worker stays + // parked in `self.worker` where the caller already cancelled it; the + // next span retires it. + self.frames = std::sync::mpsc::channel().1; + self.backend = BackendCell::new(Backend::Gap); + self.span = span; + return; + }; + // Receiver first, worker second: the drop of the *old* receiver is + // what wakes the outgoing worker if it is parked in `send`, and only + // then can it return and be reaped by a later sweep. Nothing here + // joins, so this ordering costs the seek nothing. + self.frames = stream.frames; + self.backend = stream.backend; + self.retire(stream.worker); self.span = span; } @@ -1158,18 +1306,20 @@ impl PlaybackSession { } /// Gives that clip an equalizer, or takes it off with `None`. One undo step, - /// like every other edit -- and, like every other edit, it *reseeks*: the - /// audio workers are rebuilt from the new curves right where the playhead + /// like every other edit -- and it rebuilds the **sound** where the playhead /// is, so a band changed during playback is heard from the next chunk on - /// rather than at the next play. `false` for a bad index or a non-finite - /// band, and nothing changes. + /// rather than at the next play. The picture is not touched: the video + /// worker keeps decoding through it ([`Dirty`]). `false` for a bad index or + /// a non-finite band, and nothing changes. /// - /// ponytail: the reseek is what makes it live, so the cost of a change is a - /// decoder restart -- inaudible at a drag's end, but too much to call once - /// per pointer sample (a caller commits one change per gesture). Upgrade - /// path is an `Arc` swap the running worker polls per chunk. + /// ponytail: the audio rebuild is what makes it live, so the cost of a + /// change is a decoder restart -- inaudible at a drag's end, but too much to + /// call once per pointer sample (a caller commits one change per gesture). + /// Upgrade path is the per-segment twin of [`crate::audio::MixControls`], + /// which the lane worker would poll per chunk the way the mixer polls the + /// gains. pub fn set_eq(&mut self, lane: Lane, idx: usize, params: Option) -> bool { - self.edit(|p| p.set_eq(lane, idx, params)) + self.edit(Dirty::Sound, |p| p.set_eq(lane, idx, params)) } /// How loud that lane plays, in dB -- everything on it, every frequency of @@ -1178,12 +1328,36 @@ impl PlaybackSession { self.project.lane_gain_db(lane) } - /// Sets it. One undo step and a reseek, the equalizer's rule for the - /// equalizer's reason: the mixer is rebuilt from the new volumes right - /// where the playhead is, so a track turned down during playback is heard - /// turned down from the next chunk on. + /// Sets it. One undo step -- and **nothing is rebuilt**: a lane's volume + /// lives at the sum, so the running mixer is handed the new number and + /// picks it up at its next block ([`crate::audio::MixControls`]). A fader + /// held down under an arrow key therefore moves the level and nothing else: + /// no flush, no decoder restart, no hole in the sound and no blink in the + /// picture. + /// + /// The one exception is the timeline that is not mixed at all -- a single + /// audio lane at unity with the limiter off, which plays through the + /// bit-exact single-stream path and has no mixer to talk to. Moving *that* + /// off unity opens one, once; every move after it is live. pub fn set_lane_gain_db(&mut self, lane: Lane, db: f32) -> bool { - self.edit(|p| p.set_lane_gain_db(lane, db)) + if !self.project.set_lane_gain_db(lane, db) { + return false; + } + self.push_mix(); + true + } + + /// Hands the mix the running mixer is reading its new settings -- the whole + /// of what a fader and a ceiling cost. With no mixer listening (the + /// single-lane flat path, and a session with no sound at all) the sound is + /// rebuilt instead, which is what opens one. + fn push_mix(&mut self) { + let gains = self.project.audio_gains(); + let limiter = self.project.limiter(); + match &self.mix { + Some(mix) => mix.set(gains, limiter), + None => self.reseek_audio(), + } } /// The master limiter the whole mix is summed through. @@ -1192,9 +1366,25 @@ impl PlaybackSession { } /// Sets it, live like a lane volume and for the same reason -- the ceiling - /// a person is dragging has to be the ceiling they are hearing. + /// a person is dragging has to be the ceiling they are hearing. Nothing is + /// rebuilt: the running limiter is *retuned* between two blocks + /// ([`crate::limiter::LimiterState::retune`]), so its delay line keeps + /// running and the sample count the master clock is made of does not move. + /// + /// ponytail: not an undo step, and deliberately -- [`Project::undo`] + /// restores the lane list, and the limiter is not in it, so snapshotting + /// here would push a step whose undo changes nothing a person can see or + /// hear (the twin [`set_lane_gain_db`](Self::set_lane_gain_db) *is* + /// undoable only because a lane volume lives in that list). The project + /// resolution is outside undo for the same reason and says so. Upgrade path + /// is a history that carries the mix beside the lanes, which every existing + /// snapshot site would then have to fill in. pub fn set_limiter(&mut self, limiter: crate::limiter::Limiter) -> bool { - self.edit(|p| p.set_limiter(limiter)) + if !self.project.set_limiter(limiter) { + return false; + } + self.push_mix(); + true } /// Lifts one lane's clip out, leaving a gap: black frames on the video lane, @@ -1203,7 +1393,7 @@ impl PlaybackSession { /// the last placement there is empties the timeline, which is a state /// ([`is_empty`](Self::is_empty)) and one undo away. pub fn lift_clip(&mut self, lane: Lane, idx: usize) -> bool { - self.edit(|p| p.lift(lane, idx)) + self.edit(Dirty::Both, |p| p.lift(lane, idx)) } /// Moves that clip onto lane `to` with its head at timeline frame `start` -- @@ -1219,7 +1409,7 @@ impl PlaybackSession { /// pointer on a frame, and converting it back through seconds would be a /// rounding step between the box let go of and the box committed. pub fn move_clip_to(&mut self, from: Lane, idx: usize, to: Lane, start: u32) -> bool { - self.edit(|p| p.move_clip(from, idx, to, start)) + self.edit(Dirty::Both, |p| p.move_clip(from, idx, to, start)) } /// Drags one end of that clip to timeline frame `to`, changing how much of @@ -1401,7 +1591,7 @@ impl PlaybackSession { /// without the caller having to nudge the playhead itself. `false` for an /// index that is not there and for a value that is not finite. pub fn set_color(&mut self, lane: Lane, idx: usize, params: Option) -> bool { - self.edit(|p| p.set_color(lane, idx, params)) + self.edit(Dirty::Picture, |p| p.set_color(lane, idx, params)) } /// The same grade and the same reseek without the undo step @@ -1409,7 +1599,7 @@ impl PlaybackSession { /// through, so the frame regrades under the hand and the whole gesture is /// still a single `z`. pub fn set_color_live(&mut self, lane: Lane, idx: usize, params: Option) -> bool { - self.edit(|p| p.set_color_live(lane, idx, params)) + self.edit(Dirty::Picture, |p| p.set_color_live(lane, idx, params)) } /// The project's resolution: what every clip is composed onto, what the @@ -1426,10 +1616,13 @@ impl PlaybackSession { self.native } - /// Sets it. Reseeks like an edit, so the frame on screen is recomposed at - /// the new size at once, paused or playing. `false` for a size that is not a - /// picture -- zero either way, or past 8K, which is where the per-frame - /// buffers stop being a sane thing to allocate from a keystroke. + /// Sets it. Rebuilds the **picture** where the playhead is, so the frame on + /// screen is recomposed at the new size at once, paused or playing -- and + /// the sound is not touched at all: the size of the canvas is not something + /// a sample can carry, so resizing a 4K film mid-play costs neither a hole + /// in the audio nor an offset against it ([`Dirty`]). `false` for a size + /// that is not a picture -- zero either way, or past 8K, which is where the + /// per-frame buffers stop being a sane thing to allocate from a keystroke. /// /// ponytail: not an undo step. The project resolution is not in the lane /// snapshots [`Project::undo`] restores, so cycling it back is one more @@ -1444,6 +1637,61 @@ impl PlaybackSession { } self.meta.width = width; self.meta.height = height; + self.invalidate(Dirty::Picture); + true + } + + /// The scaffolding source's own frame rate -- what the project rate started + /// as, and the one rate a caller offering a list of them must not leave out + /// ([`native_resolution`](Self::native_resolution)'s reason). + pub fn native_frame_rate(&self) -> f64 { + self.native_fps + } + + /// Cuts this timeline at `fps` from here on: every clip is *conformed* to + /// the new rate ([`Project::retime`]), every source is read through a + /// [`Rate`] against it, and an export written from this session comes out at + /// it. The edit survives as the same seconds of the same footage on a finer + /// or coarser grid -- a 30 fps take on a timeline moved to 24 keeps its + /// length and its sync, it is simply counted in 24ths now. + /// + /// Reseeks like [`set_resolution`](Self::set_resolution), so the picture and + /// the sound under the playhead are already the new rate's when this + /// returns. `false` -- changing nothing -- for a rate that is not a rate, for + /// the one already in force, and for one no timescale can name + /// ([`crate::mux::frame_timing`], the same wall a file of an unnameable rate + /// is refused at). + /// + /// ponytail: not an undo step, exactly as the project resolution is not -- + /// and this one *moves the frame numbers*, so the way back is picking the + /// old rate (or the media's, [`native_frame_rate`](Self::native_frame_rate)) + /// rather than a `z`, and it lands within a frame of where it started rather + /// than on it (see [`Project::retime`]). Upgrade path is the same one: the + /// project's settings snapshotted beside the lanes. + pub fn set_frame_rate(&mut self, fps: f64) -> bool { + if !fps.is_finite() || fps <= 0.0 || fps == self.meta.frame_rate { + return false; + } + // Old timeline frames per new one, exactly -- the one map every frame + // number on every lane goes through. Built before anything is touched, + // since a rate no timescale can name is a refusal and not a half-retimed + // project. + let Ok(k) = Rate::from_fps(self.meta.frame_rate, fps) else { + return false; + }; + // Lengths first: the retime holds every clip inside its source's *new* + // length, so a clip that played to the last frame of its file still + // does rather than naming one past the end. + for count in &mut self.counts { + *count = k.timeline_at(*count).max(1); + } + self.project.retime(k, &self.counts); + // A file's own rate has not changed; what it is *against* has. + for rate in &mut self.rates { + *rate = rate.then(k); + } + self.meta.frame_rate = fps; + self.meta.frame_count = k.timeline_at(self.meta.frame_count).max(1); let now = self.now(); self.seek(now); true @@ -1458,7 +1706,7 @@ impl PlaybackSession { /// grade: the picture on screen is recomposed through the new policy without /// the caller nudging the playhead. `false` for an index that is not there. pub fn set_fit(&mut self, lane: Lane, idx: usize, fit: FitPolicy) -> bool { - self.edit(|p| p.set_fit(lane, idx, fit)) + self.edit(Dirty::Picture, |p| p.set_fit(lane, idx, fit)) } /// The clip at `idx` -- what a caller copies. It is a pair of source frame @@ -1473,7 +1721,7 @@ impl PlaybackSession { /// the end of the timeline the clip is appended. One undo step. pub fn paste_at(&mut self, timeline_secs: f64, clip: Clip) -> bool { let at = secs_to_frame(timeline_secs, self.meta.frame_rate); - self.edit(|p| p.paste(at, clip)) + self.edit(Dirty::Both, |p| p.paste(at, clip)) } /// Places the whole of `path` played on its audio `stream` at @@ -1632,7 +1880,7 @@ impl PlaybackSession { /// and it reseeks like every other edit. pub fn place_at(&mut self, lane: Lane, timeline_secs: f64, clip: Clip) -> bool { let at = secs_to_frame(timeline_secs, self.meta.frame_rate); - self.edit(|p| p.place(lane, at, clip)) + self.edit(Dirty::Both, |p| p.place(lane, at, clip)) } /// Removes `lane`'s clip at `idx` and everything under it, closing the gap @@ -1646,12 +1894,12 @@ impl PlaybackSession { /// not `V1`'s, and a front-end that could only say "the third clip" would /// delete the wrong one the moment a second lane exists. pub fn delete_clip(&mut self, lane: Lane, idx: usize) -> bool { - self.edit(|p| p.delete_in(lane, idx)) + self.edit(Dirty::Both, |p| p.delete_in(lane, idx)) } /// Undoes the last successful edit, and reseeks like a delete. pub fn undo(&mut self) -> bool { - self.edit(Project::undo) + self.edit(Dirty::Both, Project::undo) } /// Takes `path` into the **library**: it becomes a source of this session, @@ -1743,18 +1991,36 @@ impl PlaybackSession { Ok(source) } - /// Applies an edit and, if it took, reseeks onto the new mapping. `seek` - /// clamps to the new duration and keeps playing playing, so a delete that - /// shortens the timeline past the playhead lands on the last frame. - fn edit(&mut self, f: impl FnOnce(&mut Project) -> bool) -> bool { + /// Applies an edit and, if it took, rebuilds **what it dirtied** and nothing + /// else ([`Dirty`]). A structural edit reseeks: `seek` clamps to the new + /// duration and keeps playing playing, so a delete that shortens the + /// timeline past the playhead lands on the last frame. A grade or a fit + /// policy rebuilds the picture where it stands, with the sound running + /// through it untouched -- no flush, no re-open, no hole -- and an + /// equalizer the other way round. + fn edit(&mut self, dirty: Dirty, f: impl FnOnce(&mut Project) -> bool) -> bool { if !f(&mut self.project) { return false; } - let now = self.now(); - self.seek(now); + self.invalidate(dirty); true } + /// Rebuilds the dirtied half (or both) at the playhead. + fn invalidate(&mut self, dirty: Dirty) { + match dirty { + Dirty::Picture => { + let (_, target) = self.landing(self.now()); + self.start_picture(target); + } + Dirty::Sound => self.reseek_audio(), + Dirty::Both => { + let now = self.now(); + self.seek(now); + } + } + } + /// Current timeline position in seconds. pub fn now(&self) -> f64 { self.clock.now() @@ -1856,12 +2122,51 @@ impl PlaybackSession { /// Playing stays playing and paused stays paused -- but a paused seek still /// decodes, so the caller can show the frame it landed on. pub fn seek(&mut self, secs: f64) { + let (t, target) = self.landing(secs); + let was_playing = self.clock.is_playing(); + self.stop_audio(); + self.start_picture(target); + let audio_running = self.start_audio(target); + // Same invariant as `play`: position the clock before audio restarts. + if audio_running && self.clock.source() != ClockSource::Audio { + self.clock.switch_to_audio(); + } + self.clock.seek_to(t); + self.resume(was_playing); + } + + /// Where a seek to `secs` lands: the clamped timeline position and the + /// timeline frame it means. The one place the clamp lives, so every + /// invalidation below lands on the same frame a seek would. + fn landing(&self, secs: f64) -> (f64, u32) { let fps = self.meta.frame_rate; let total = self.project.timeline_frames(); let t = secs.clamp(0.0, f64::from(total) / fps); - let target = secs_to_frame(t, fps).min(total.saturating_sub(1)); - let was_playing = self.clock.is_playing(); + (t, secs_to_frame(t, fps).min(total.saturating_sub(1))) + } + + /// Rebuilds the **picture** at `target` and touches nothing else: the sound + /// keeps playing out of the same stream, the clock keeps running, and a + /// grade dragged during playback is therefore silent. + fn start_picture(&mut self, target: u32) { + // Cancel first, drop second: the old worker may be parked in `send` on + // the bounded channel, where only the disconnect wakes it -- and it + // then finds the flag already set. It is then parked, not joined; see + // [`retire`](Self::retire), which is what keeps a scrub off the price + // of a VA-API init. + self.worker.cancel(); + // The span runs from `target` to the end of whatever it landed in -- a + // clip, or a gap, which starts a black-frame worker instead. `None` is + // the emptied timeline, black too, and `start_span` says so. + self.start_span(self.project.composite_span_at(target)); + self.eos = false; + } + /// Silences the device and supersedes whatever is feeding it: the first half + /// of every audio restart, and the only thing that ever discards queued + /// sound. + fn stop_audio(&mut self) { + self.mix = None; if let Some(audio) = &self.audio { let ao = audio.ao.lock().unwrap(); ao.set_active(false); @@ -1869,25 +2174,31 @@ impl PlaybackSession { // feeder re-checks the epoch inside that same lock: whatever it is // carrying can no longer reach the ring after this point. audio.epoch.fetch_add(1, Ordering::Release); + // Nothing of the new stream has been played yet, by definition. + audio.content_at.store(-1, Ordering::Release); ao.flush(); // The flushed samples are not being played any more, so nothing may // still be drawn from them. audio.tap.lock().unwrap().clear(); } + } - // Cancel first, drop second: the old worker may be parked in `send` on - // the bounded channel, where only the disconnect wakes it -- and it - // then finds the flag already set. It is then parked, not joined; see - // [`retire`](Self::retire), which is what keeps a scrub off the price - // of a VA-API init. - self.worker.cancel(); - // The span runs from `target` to the end of whatever it landed in -- a - // clip, or a gap, which starts a black-frame worker instead. `None` is - // the emptied timeline, black too, and `start_span` says so. - self.start_span(self.project.composite_span_at(target)); - self.eos = false; + /// Puts the device back where it was: playing if it was playing, and with + /// the clock held until the new stream is really audible (see + /// [`Audio::content_at`]). + fn resume(&mut self, was_playing: bool) { + self.priming = true; + if was_playing && let Some(audio) = &self.audio { + audio.ao.lock().unwrap().set_active(true); + } + } + /// Rebuilds the **sound** from `target` -- the second half of a restart -- + /// and says whether anything will be fed. + fn start_audio(&mut self, target: u32) -> bool { + let fps = self.meta.frame_rate; let mut audio_running = false; + let mut live = None; if let Some(audio) = &self.audio && !audio.died.load(Ordering::Acquire) { @@ -1921,32 +2232,58 @@ impl PlaybackSession { // the library row said, and what an export copies (`export::run`). let sources = self.project.audio_sources(); // ...and the mix settings over the lot: each lane's own volume on - // its way into the sum and the master limiter over the sum, both - // rebuilt here like the curves above, which is what makes a lane - // fader and a ceiling audible while the timeline runs. + // its way into the sum and the master limiter over the sum. These + // two are handed over *live* as well as at the open: they sit at + // the sum, where nothing is decoded, so a fader moved later is a + // number the running mixer picks up rather than a stream rebuilt + // under the ear ([`crate::audio::MixControls`]). let gains = self.project.audio_gains(); let limiter = self.project.limiter(); - audio_running = match AudioSession::open_mixed_streams_master( - &sources, &segs, &eqs, &speeds, &gains, limiter, + let controls = crate::audio::MixControls::new(gains.clone(), limiter); + audio_running = match AudioSession::open_mixed_streams_live( + &sources, + &segs, + &eqs, + &speeds, + &gains, + limiter, + Some(&controls), ) { Ok(Some((_, rx))) => audio.spawn_feeder(rx), _ => false, }; + // Only a mixed timeline has a mixer to talk to; the single-lane + // flat path is the bit-exact one and has none. + live = (audio_running && controls.is_live()).then_some(controls); if !audio_running { // Nothing will ever be fed again; let `tick` fall to wall time // instead of waiting on a device that has no more work coming. audio.fed_all.store(true, Ordering::Release); } } + self.mix = live; + audio_running + } - // Same invariant as `play`: position the clock before audio restarts. + /// Rebuilds the sound alone, from where the playhead is: what a change that + /// no picture can show goes through. The video worker is left decoding, so + /// the picture does not blink -- and the clock, held still by + /// [`resume`](Self::resume) until the new stream is audible, puts the sound + /// back exactly where the picture already is. + /// + /// End of stream is deliberately left alone -- no picture worker is started + /// here, so a timeline that was played out still is; see + /// [`is_eos`](Self::is_eos). + fn reseek_audio(&mut self) { + let (t, target) = self.landing(self.now()); + let was_playing = self.clock.is_playing(); + self.stop_audio(); + let audio_running = self.start_audio(target); if audio_running && self.clock.source() != ClockSource::Audio { self.clock.switch_to_audio(); } self.clock.seek_to(t); - if was_playing && let Some(audio) = &self.audio { - audio.ao.lock().unwrap().set_active(true); - } + self.resume(was_playing); } /// Renders the edited timeline to `out` on a worker thread. The session is @@ -2000,10 +2337,35 @@ impl PlaybackSession { // Audio EOF. Wall time carries the same timeline on from here, with // no jump, and this branch cannot be reached again. self.clock.switch_to_wall(); - } else { + return; + } + if self.priming { + // A stream that has been started and has not been heard yet: the + // device is playing the silence of its own restart, and none of it + // is timeline time ([`Audio::content_at`]). The clock holds where + // the seek left it -- so the picture holds too, on the frame it + // landed on, rather than sliding ahead of a sound that has not + // started. + let started = audio.content_at.load(Ordering::Acquire); + if started < 0 { + return; + } + // ...and then the *first sample of the stream* becomes the + // reference, not whatever position this poll happened to catch: the + // clock's own anchor is its first report ([`PlaybackClock`]), and + // anchoring it here is what makes a mid-play edit cost no offset. + // + // ponytail: `started` is the position when the sample was queued, + // and it is heard at the next callback -- up to one quantum (5-21 + // ms) later, so that much of the restart is still counted. Upgrade + // path is the position at the first *pop* of real audio, which only + // the plugin's RT thread can see. self.clock - .set_audio_position(position as u64, audio.sample_rate); + .set_audio_position(started as u64, audio.sample_rate); + self.priming = false; } + self.clock + .set_audio_position(position as u64, audio.sample_rate); } } @@ -2232,6 +2594,7 @@ fn open_audio(path: &Path, stream: usize) -> (Option