diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs index 90cca3f..77b458b 100644 --- a/crates/app/src/main.rs +++ b/crates/app/src/main.rs @@ -11,11 +11,12 @@ use std::time::{Duration, Instant}; use engine::audio::StreamInfo; use engine::color::ColorParams; +use engine::decode::Backend; use engine::eq::{Band, BandKind, EqParams}; use engine::export::{ExportSettings, Format}; use engine::project::{Edge, Lane, LaneKind, Source, Speed}; use engine::scale::FitPolicy; -use engine::{Clip, ExportHandle, Frame, PlaybackSession}; +use engine::{Clip, Codec, ExportHandle, Frame, PlaybackSession}; use gpui::{ AnyElement, App, Application, Bounds, ClickEvent, Context, CursorStyle, Div, FocusHandle, KeyDownEvent, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, PathBuilder, Pixels, @@ -637,6 +638,19 @@ struct Player { /// `None` is a file with no picture to report (every source that is not an /// image, and one whose header would not read). sizes: HashMap>, + /// Which decoder each source will run on, probed once at import and kept: + /// the codec (`None` for a still) and the seat the engine picked for it. + /// What a library row says *before* anything plays; the running answer is + /// the session's own (`PlaybackSession::decode_backend`), which follows a + /// fallback this cannot. Filled like `sizes`: presence means "asked", and + /// `None` is a source with no decoder to name -- a song, or one the probe + /// refused -- which must stay in the map or every repaint would ask again. + decoders: HashMap, Backend)>>, + /// Which encoder an export of the picked settings would open, and what it + /// was asked about: the probe opens a real VA-API encoder (~100 ms), so it + /// runs off the render thread and only while the export card is up. The + /// inner `None` is "asked, not answered yet". + export_seat: Option<(ExportSettings, (u32, u32), Option<&'static str>)>, /// The copied clip. Frame ranges only, so it survives the clip it was taken /// from being deleted -- and it outlives the selection. clipboard: Option, @@ -1997,6 +2011,28 @@ impl Player { }) .detach(); } + // Which decoder each file will run on, for the row that says so before + // a frame of it plays. Off the render thread like the streams above: a + // stream the plugin takes costs one VA-API init (~90 ms) to answer. + for path in unseen_paths(session.sources(), &self.decoders) { + self.decoders.insert(path.clone(), None); + let probed = cx.background_executor().spawn({ + let path = path.clone(); + // A song and a source no decoder here takes are both `None`: + // the row says nothing about them rather than guessing, and + // import refused the second at the door anyway. + async move { engine::decode::probe(&path).ok() } + }); + cx.spawn(async move |this, cx| { + let probed = probed.await; + this.update(cx, |this, cx| { + this.decoders.insert(path, probed); + cx.notify(); + }) + .ok(); + }) + .detach(); + } for key in unseen_sources(session.sources(), &self.waves) { self.waves.insert(key.clone(), Wave::Loading); let decoded = cx.background_executor().spawn({ @@ -2029,6 +2065,59 @@ impl Player { } } + /// Probes the encoder an export would open, once per (settings, + /// resolution) and only while the export card is up -- it opens the very + /// VA-API encoder the export would, which is what makes the card's line a + /// measurement instead of a promise, and also what makes it too slow for + /// the render thread. Written before the spawn, like the probes above, so + /// the repaints during it start no second one. + fn cache_export_seat(&mut self, cx: &mut Context) { + let Some(session) = &self.session else { + return; + }; + let settings = export_settings(self.quality, self.custom_mbps, self.format); + if !self.export_open { + return; + } + // A format with no picture has no seat to probe -- and the *last* + // format's is not its answer: cleared rather than left standing, or + // picking MP3 after AV1 would read "SW encode (rav1e) · MP3 · SW + // (rusty_mp3)", which names an encoder that will not run. + if !settings.format.has_video() { + self.export_seat = None; + return; + } + let meta = *session.meta(); + let key = (settings, (meta.width, meta.height)); + if self + .export_seat + .is_some_and(|(asked, size, _)| (asked, size) == key) + { + return; + } + self.export_seat = Some((key.0, key.1, None)); + let probed = cx + .background_executor() + .spawn(async move { engine::export::planned_video(&meta, &settings) }); + cx.spawn(async move |this, cx| { + let probed = probed.await; + this.update(cx, |this, cx| { + // Only if the card is still asking the same question: a format + // changed while the plugin opened has a probe of its own. + if let Some(seat) = this + .export_seat + .as_mut() + .filter(|(asked, size, _)| (*asked, *size) == key) + { + seat.2 = probed; + } + cx.notify(); + }) + .ok(); + }) + .detach(); + } + /// The group id of the clicked clip, which is what marks the other half. fn selected_link(&self) -> Option { let (lane, idx) = self.selected?; @@ -3055,6 +3144,7 @@ impl Render for Player { // has been through a repaint by the time its clips are drawn, so this // is the one place that has to notice a new one. self.cache_media(cx); + self.cache_export_seat(cx); // What the compositor calls this window. Pushed only when it changes: // it is a protocol round trip and this runs at vsync. let title = window_title(&self.name); @@ -3545,11 +3635,17 @@ impl Player { // Its own length, not one derived from what is on the lanes: a row // imported and never placed is a row with a length, and it is the // length a drag would put down. - let rows: Vec<_> = library_rows(sources, &self.streams, self.timeline_audio(), |path| { - self.session - .as_ref() - .map_or(0, |session| session.file_frames(path)) - }) + let rows: Vec<_> = library_rows( + sources, + &self.streams, + &self.decoders, + self.timeline_audio(), + |path| { + self.session + .as_ref() + .map_or(0, |session| session.file_frames(path)) + }, + ) .into_iter() .enumerate() .map(|(i, row)| { @@ -3580,12 +3676,18 @@ impl Player { None => String::new(), } ), + // The file's *own* frame rate, not the timeline's: a clip shot + // at another rate plays at the speed it was shot at, and the + // row that says where it came from has to say which rate that + // was. (None, Some(meta)) => format!( "{} — {}x{} @ {:.2} fps · drag onto a lane, or Add at playhead", row.path.display(), meta.width, meta.height, - meta.frame_rate + self.session + .as_ref() + .map_or(meta.frame_rate, |session| session.file_fps(&row.path)) ), (None, None) => row.path.display().to_string(), }; @@ -3780,6 +3882,30 @@ impl Player { )) } + /// What is decoding the picture right now, for the transport line: the + /// backend is the running worker's own (it is written where a hardware + /// session falls back to software, so this follows reality), and the codec + /// comes from the clip under the playhead. Empty when nothing is playing -- + /// the question is about what is happening, not about what would. + fn live_decode(&self, position: f64, playing: bool) -> String { + let Some(session) = self.session.as_ref().filter(|_| playing) else { + return String::new(); + }; + let backend = session.decode_backend(); + let codec = session + .video_clip_at(position) + .and_then(|(lane, idx)| session.lane_clips(lane).get(idx).map(|clip| clip.source)) + .and_then(|source| session.sources().get(source)) + .and_then(|source| self.decoders.get(&source.path).copied().flatten()) + .and_then(|(codec, _)| codec); + match backend { + // Neither is a decode, and saying "SW" of them would be a lie. + Backend::Gap => "gap · nothing to decode".to_string(), + Backend::Still => "still · one decode, held".to_string(), + _ => format!("{} decode", decode_label(codec, backend)), + } + } + /// Transport, edit and file buttons, timecode, playhead, clips lane. fn panel( &self, @@ -3821,8 +3947,16 @@ impl Player { let progress = export.progress(); ( format!( - "EXPORTING {}% — {} cancels", + "EXPORTING {}% · {} · {} — {} cancels", (progress * 100.) as u32, + // The row that was picked; the engine's line below names the + // seats alone, since the library is what identifies a codec. + format_label(self.format), + // What the worker actually opened, so a fallback to the + // software encoder shows here rather than being invisible. + export + .encoders() + .unwrap_or_else(|| "opening the encoder".to_string()), key(ActionId::CancelExport) ), progress, @@ -3832,12 +3966,19 @@ impl Player { // tooltips. Keys first: at a 640 px window the tail is what a // truncation eats, and the two hints at the end are also on the // ruler's and Import's tooltips. + // While it plays, what is decoding it goes first: it is the + // answer that changes as the playhead crosses a cut, and the tail + // of this line is what a narrow window truncates. ( - format!( - "{} copy · {} paste · {} undo · click the bar to seek · drop a file to import", - key(ActionId::Copy), - key(ActionId::Paste), - key(ActionId::Undo) + join_detail( + &self.live_decode(position, playing), + &format!( + "{} copy · {} paste · {} undo · click the bar to seek · drop a file to \ + import", + key(ActionId::Copy), + key(ActionId::Paste), + key(ActionId::Undo) + ), ), filled, ) @@ -4608,7 +4749,11 @@ impl Player { .px(px(6.)) .text_size(px(11.)) .text_color(rgb(INK_DIM)) - .child(export_line(self.format, self.session.as_ref())), + .child(export_line( + self.format, + self.session.as_ref(), + self.export_seat.and_then(|(.., seat)| seat), + )), ) .child( div() @@ -6457,6 +6602,7 @@ struct Row { fn library_rows( sources: &[Source], streams: &HashMap>, + decoders: &HashMap, Backend)>>, timeline_audio: Option<(u32, u16)>, frames: impl Fn(&Path) -> u32, ) -> Vec { @@ -6472,12 +6618,22 @@ fn library_rows( path: source.path.clone(), stream: source.audio_stream, name: row_name(&source.path, source.audio_stream, of_file.len() > 1), - // Only where there is a choice to describe: a file with one audio - // track is the row it has always been, name and length, and the - // length is what would be squeezed out at the panel's least width. - detail: info - .filter(|_| of_file.len() > 1) - .map_or_else(String::new, stream_detail), + // The decoder first: it is the same for every row of a file and + // it is what a person opening the panel is asking about. The + // stream half only where there is a choice to describe -- a file + // with one audio track is the row it has always been, name and + // length, and the length is what would be squeezed out at the + // panel's least width. + detail: join_detail( + &decoders + .get(&source.path) + .copied() + .flatten() + .map_or_else(String::new, |(codec, backend)| decode_label(codec, backend)), + &info + .filter(|_| of_file.len() > 1) + .map_or_else(String::new, stream_detail), + ), // A stream already on the timeline is playing: whatever a probe // would say about it now, it is usable by demonstration. unusable: None, @@ -6514,9 +6670,20 @@ fn library_rows( /// why it cannot be used, with the separator only where both halves exist (a /// single-stream file says nothing about its stream). fn join_detail(detail: &str, tail: &str) -> String { - match detail.is_empty() { - true => tail.to_string(), - false => format!("{detail} · {tail}"), + match (detail.is_empty(), tail.is_empty()) { + (true, _) => tail.to_string(), + (false, true) => detail.to_string(), + (false, false) => format!("{detail} · {tail}"), + } +} + +/// How a source's decoder reads: the codec and which seat has it, or the seat +/// alone for a still, which has no coded stream to name. The one place either +/// answer is spelled, so a row, a transport line and a card cannot disagree. +fn decode_label(codec: Option, backend: Backend) -> String { + match codec { + Some(codec) => format!("{} · {}", codec.name(), backend.label()), + None => backend.label().to_string(), } } @@ -6853,14 +7020,32 @@ fn next_resolution(current: (u32, u32), native: (u32, u32)) -> (u32, u32) { /// [`format_line`] plus the project's resolution, which is what a video export /// is written at however many sizes the media on the timeline are. Only for the /// formats that carry a picture -- a WAV has no resolution to state. -fn export_line(format: Format, session: Option<&PlaybackSession>) -> String { +fn export_line( + format: Format, + session: Option<&PlaybackSession>, + seat: Option<&'static str>, +) -> String { let line = format_line(format); + // What it will really be encoded by, on the same line: the picture's seat + // as the probe found it (`…` until it lands, never a guess) and the sound's, + // which is decided without opening anything. Both are what a running export + // then names on its progress line, from the same two functions. + let encoders = match session { + Some(session) => join_detail( + seat.unwrap_or(match format.has_video() { + true => "encoder …", + false => "", + }), + session.planned_audio(format), + ), + None => String::new(), + }; match session.filter(|_| format.has_video()) { Some(session) => { let (w, h) = session.resolution(); - format!("{line} · project {w}x{h}") + format!("{line} · project {w}x{h} · {encoders}") } - None => line.to_string(), + None => join_detail(line, &encoders), } } @@ -7913,9 +8098,13 @@ mod tests { ); // The rows the panel draws: one per source, each its file's own length // -- source 1 has no clip anywhere and is still 4 s at 30 fps. - let rows = library_rows(session.sources(), &HashMap::new(), None, |path| { - session.file_frames(path) - }); + let rows = library_rows( + session.sources(), + &HashMap::new(), + &HashMap::new(), + None, + |path| session.file_frames(path), + ); assert_eq!(rows.len(), 2); assert_eq!(rows[0].frames, 150, "5 s at 30 fps"); assert_eq!(rows[1].frames, 120, "4 s at 30 fps, never placed"); @@ -7954,7 +8143,9 @@ mod tests { .find(|s| s.index == session.sources()[0].audio_stream) .map(|s| (s.sample_rate, s.channels)); let frames = session.file_frames(&path); - let rows = library_rows(session.sources(), &streams, rate, |_| frames); + let rows = library_rows(session.sources(), &streams, &HashMap::new(), rate, |_| { + frames + }); assert_eq!(rows.len(), 1); assert_eq!(rows[0].name, "test_tone.mp3"); assert_eq!(rows[0].unusable, None, "the row is placeable"); @@ -8026,7 +8217,13 @@ mod tests { info(3, 0, 0, None, false), ], ); - let rows = library_rows(&sources, &streams, Some((44_100, 2)), |_| 90); + let rows = library_rows( + &sources, + &streams, + &HashMap::new(), + Some((44_100, 2)), + |_| 90, + ); assert_eq!( rows.iter().map(|r| r.stream).collect::>(), [0, 1, 2, 3], @@ -8064,7 +8261,7 @@ mod tests { PathBuf::from("/m/plain.mp4"), vec![info(0, 44_100, 2, None, true)], ); - let rows = library_rows(&plain, &one, Some((44_100, 2)), |_| 90); + let rows = library_rows(&plain, &one, &HashMap::new(), Some((44_100, 2)), |_| 90); assert_eq!(rows.len(), 1); assert_eq!(rows[0].name, "plain.mp4"); assert_eq!( @@ -8075,7 +8272,7 @@ mod tests { let mut silent = HashMap::new(); silent.insert(PathBuf::from("/m/plain.mp4"), Vec::new()); for probe in [silent, HashMap::new()] { - let rows = library_rows(&plain, &probe, None, |_| 90); + let rows = library_rows(&plain, &probe, &HashMap::new(), None, |_| 90); assert_eq!(rows.len(), 1); assert_eq!(rows[0].name, "plain.mp4"); assert_eq!(rows[0].detail, ""); @@ -8093,7 +8290,13 @@ mod tests { PathBuf::from("/m/other.mp4"), vec![info(0, 44_100, 2, None, true)], ); - let rows = library_rows(&placed, &streams, Some((44_100, 2)), |_| 90); + let rows = library_rows( + &placed, + &streams, + &HashMap::new(), + Some((44_100, 2)), + |_| 90, + ); assert_eq!( rows.iter() .map(|r| (file_name(&r.path), r.stream)) @@ -8496,7 +8699,7 @@ mod tests { ); let streams = HashMap::new(); let rows = |session: &PlaybackSession| { - library_rows(session.sources(), &streams, None, |_| 0).len() + library_rows(session.sources(), &streams, &HashMap::new(), None, |_| 0).len() }; assert_eq!(rows(&session), 2, "a row per source"); @@ -9813,7 +10016,9 @@ mod tests { // a title and a status line. let title = 17.; let status = 28.; - let fixed = 17.; + // Two lines of 11 px: the format line carries the encoders an export + // would open, which is what takes it past one at this width. + let fixed = 30.; let gaps = 4. * 2.; let padding = 24.; assert!( @@ -10379,6 +10584,8 @@ fn main() { waves: HashMap::new(), streams: HashMap::new(), sizes: HashMap::new(), + decoders: HashMap::new(), + export_seat: None, clipboard: None, scrubbing: false, trim: None, diff --git a/crates/engine/src/decode.rs b/crates/engine/src/decode.rs index 5a8b170..c26256e 100644 --- a/crates/engine/src/decode.rs +++ b/crates/engine/src/decode.rs @@ -3,7 +3,7 @@ use std::path::{Path, PathBuf}; use std::sync::Arc; -use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicU8, Ordering}; use std::sync::mpsc::{Receiver, SyncSender, sync_channel}; use std::thread; @@ -25,6 +25,106 @@ pub struct Frame { pub bgra: Vec, } +/// Which decoder a source is really running on. Read-only introspection: it +/// decides nothing, it *reports* what [`DecodeSession::open_worker`] chose -- +/// a hardware session that opened and then failed before its first picture +/// falls back to software and this says so, because it is written where the +/// fallback happens rather than where it was hoped for. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum Backend { + /// The worker has not reached its decoder yet: the plugin's VA-API init is + /// ~90 ms, and this is what a caller reads in that window. + #[default] + Opening, + /// The VA-API plugin (`libengine_hw.so`). + Hardware, + /// `rusty_h264`, in this process. + Software, + /// A still image: one `image` decode, no stream and no decoder to pick. + Still, + /// A gap: black frames, nothing decoded at all. + Gap, +} + +impl Backend { + /// Short enough for a library row and a transport line. + pub fn label(self) -> &'static str { + match self { + Self::Opening => "opening", + Self::Hardware => "HW", + Self::Software => "SW", + Self::Still => "still", + Self::Gap => "gap", + } + } + + fn code(self) -> u8 { + match self { + Self::Opening => 0, + Self::Hardware => 1, + Self::Software => 2, + Self::Still => 3, + Self::Gap => 4, + } + } + + fn from_code(code: u8) -> Self { + match code { + 1 => Self::Hardware, + 2 => Self::Software, + 3 => Self::Still, + 4 => Self::Gap, + _ => Self::Opening, + } + } +} + +/// Where a worker publishes the decoder it opened, for whoever holds the other +/// end of its channel. One atomic byte, written once at open (and once more if +/// hardware hands the range back to software), read whenever a caller repaints +/// -- never per frame on either side. +#[derive(Clone, Default)] +pub struct BackendCell(Arc); + +impl BackendCell { + fn new(backend: Backend) -> Self { + Self(Arc::new(AtomicU8::new(backend.code()))) + } + + fn set(&self, backend: Backend) { + self.0.store(backend.code(), Ordering::Relaxed); + } + + pub fn get(&self) -> Backend { + Backend::from_code(self.0.load(Ordering::Relaxed)) + } +} + +/// Which decoder `path` would open, decided exactly as [`DecodeSession::open_worker`] +/// decides it: the same `VE_SW` pin and the same plugin probe against this very +/// file. What lets a front-end name the decoder *before* anything plays. +/// +/// The codec is `None` for a still image, which has no coded stream. A stream +/// no decoder here can take is an `Err` naming the plugin, exactly as opening +/// it would be -- the same refusal, one VA-API init earlier. +/// +/// Costs that one init (~90 ms) for a stream the plugin takes: ask it once per +/// file, off a render thread, and keep the answer. +pub fn probe(path: &Path) -> crate::Result<(Option, Backend)> { + if crate::is_image(path) { + return Ok((None, Backend::Still)); + } + let path = path.to_path_buf(); + let (meta, _demuxer) = Demuxer::open(&path)?; + if open_hw(&path, 0).is_some() { + return Ok((Some(meta.codec), Backend::Hardware)); + } + if meta.codec != Codec::H264 { + return Err(meta.codec.needs_plugin().into()); + } + Ok((Some(meta.codec), Backend::Software)) +} + /// A running decode worker: the flag that stops it, and the handle to wait on. /// /// Dropping one cancels *and joins*. A worker abandoned mid-`vaInitialize` @@ -85,6 +185,9 @@ impl Drop for Worker { pub(crate) struct FrameStream { pub(crate) frames: Receiver, pub(crate) worker: Worker, + /// What this stream's pictures are being decoded by. Dropped last and read + /// by the caller, so it outlives nothing and blocks nothing. + pub(crate) backend: BackendCell, } pub struct DecodeSession; @@ -152,6 +255,7 @@ impl DecodeSession { cancel, handle: None, }, + backend: BackendCell::new(Backend::Gap), }; } let worker_cancel = Arc::clone(&cancel); @@ -180,6 +284,7 @@ impl DecodeSession { FrameStream { frames: rx, worker: Worker { cancel, handle }, + backend: BackendCell::new(Backend::Gap), } } @@ -209,6 +314,7 @@ impl DecodeSession { cancel, handle: None, }, + backend: BackendCell::new(Backend::Still), }); } // The one conversion, on this thread: it is a few milliseconds and the @@ -245,6 +351,7 @@ impl DecodeSession { Ok(FrameStream { frames: rx, worker: Worker { cancel, handle }, + backend: BackendCell::new(Backend::Still), }) } @@ -285,6 +392,9 @@ impl DecodeSession { // decoder run ahead of the display without limit. let (tx, rx) = sync_channel(2); let cancel = Arc::new(AtomicBool::new(false)); + // Written by the worker below the moment it knows, so a caller reading + // it sees what opened rather than what was hoped for. + let backend = BackendCell::default(); if end_frame <= start_frame { // Nothing to decode: dropping `tx` here closes the channel cleanly, // so the caller sees an immediate end of stream rather than an error. @@ -296,10 +406,12 @@ impl DecodeSession { cancel, handle: None, }, + backend, }, )); } let worker_cancel = Arc::clone(&cancel); + let worker_backend = backend.clone(); let handle = thread::Builder::new() .name("decode".into()) .spawn(move || { @@ -320,6 +432,7 @@ impl DecodeSession { return; } eprintln!("decode backend: hardware (VA-API plugin)"); + worker_backend.set(Backend::Hardware); if run_hw(hw, &tx, start_frame, end_frame, &mut render, &worker_cancel) { return; } @@ -334,6 +447,7 @@ impl DecodeSession { return; } eprintln!("decode backend: software (rusty_h264)"); + worker_backend.set(Backend::Software); run( demuxer, tx, @@ -351,6 +465,7 @@ impl DecodeSession { cancel, handle: Some(handle), }, + backend, }, )) } diff --git a/crates/engine/src/export.rs b/crates/engine/src/export.rs index 30e0809..bbf26a6 100644 --- a/crates/engine/src/export.rs +++ b/crates/engine/src/export.rs @@ -23,10 +23,14 @@ //! picture is re-encoded, so the frame walk honours a rate: it takes the source //! frame each timeline frame shows ([`crate::project::Speed::source_at`], the //! very frame preview holds there) and encodes a held one again rather than -//! decoding it twice. The sound is *copied* unless something forces a decode, -//! and a packet carries no rate — so a speeded lane is one of the things that -//! forces one ([`copy_audio`]) rather than being written out at 1.00x under a -//! re-timed picture. +//! decoding it twice. A clip whose *file* was shot at another rate than the +//! timeline goes through the same walk with one more conversion on the end +//! ([`crate::project::Rate`]), so it is encoded at the speed it was shot at. +//! The sound is *copied* unless something forces a decode, and a packet carries +//! no rate — so a speeded lane is one of the things that forces one +//! ([`copy_audio`]) rather than being written out at 1.00x under a re-timed +//! picture. WAV, FLAC and MP3 are decoded and resampled, so they honour a rate +//! like the picture does. //! //! Nothing partial survives a failure: the worker writes to `.part` and //! renames it onto `out` only once the file is closed and complete, so the @@ -52,7 +56,7 @@ use crate::audio::{AudioMeta, AudioSession}; use crate::demux::{Demuxer, VideoMeta}; use crate::hw::{HwEncoder, HwSession}; use crate::mux::{AudioParams, Av1Params, MkvMuxer, Mp4Muxer, VideoParams}; -use crate::project::{LaneKind, Project}; +use crate::project::{LaneKind, Project, Rate}; use crate::scale::Composer; /// Progress is reported in permille: an atomic integer the render loop can read @@ -167,6 +171,10 @@ struct Shared { cancel: AtomicBool, finished: AtomicBool, outcome: Mutex>>, + /// The encoders this job really opened, published the moment they are + /// chosen and never changed after -- one seat for the whole file, which is + /// what [`Enc`] states. `None` until then. + encoders: Mutex>, } /// A running export. Poll [`is_finished`](ExportHandle::is_finished) once per @@ -195,6 +203,13 @@ impl ExportHandle { self.shared.finished.load(Ordering::Acquire) } + /// What this export is encoding with -- the video seat and what the sound + /// is doing -- as the worker chose them, hardware fallback included. + /// `None` for the first instants of a job, before the encoder is open. + pub fn encoders(&self) -> Option { + self.shared.encoders.lock().unwrap().clone() + } + /// The outcome, once — taken out of the handle, so a caller that already /// reported it sees `None` afterwards. `None` while the export is running. pub fn result(&self) -> Option> { @@ -218,6 +233,7 @@ pub fn start( cancel: AtomicBool::new(false), finished: AtomicBool::new(false), outcome: Mutex::new(None), + encoders: Mutex::new(None), }); let worker = Arc::clone(&shared); let out = out.to_path_buf(); @@ -282,12 +298,154 @@ fn has_picture(project: &Project) -> bool { .any(|lane| lane.kind == LaneKind::Video && !project.lane(lane).is_empty()) } +/// Whether any audio lane holds anything, [`has_picture`]'s pair: what tells a +/// timeline whose export will carry sound from one whose file has none. +fn has_sound(project: &Project) -> bool { + project + .lanes() + .into_iter() + .any(|lane| lane.kind == LaneKind::Audio && !project.lane(lane).is_empty()) +} + +/// Whether any equalizer on the sound is doing something -- the one edit a +/// packet copy cannot carry, so an mp4 whose lane has one is decoded and +/// re-encoded ([`encode_audio`]) instead of copied. Asked of every audio lane: +/// the copy path has exactly one by the time it asks, and [`planned_audio`] is +/// asked before that is settled. +fn equalized(project: &Project) -> bool { + project.audio_lanes().into_iter().any(|lane| { + (0..project.lane(lane).len()) + .any(|idx| project.eq_of(lane, idx).is_some_and(|eq| !eq.is_identity())) + }) +} + +/// The bitrate an export codes at: the caller's number through the same clamp +/// as the computed one, for the reason [`Enc::open`] states. +fn bitrate_of(meta: &VideoMeta, settings: &ExportSettings) -> u64 { + settings + .bitrate + .map_or_else(|| bitrate_for(meta), |b| b.clamp(MIN_BITRATE, MAX_BITRATE)) +} + +/// The hardware seat for these settings, opened exactly as the export opens it +/// -- the same pins, the same AV1 opt-in, the same dimensions a driver may +/// refuse -- or `None` where the software encoder takes the file. The single +/// place that choice is made, which is what lets [`planned_video`] *measure* it +/// instead of promising it. +fn hw_seat(meta: &VideoMeta, settings: &ExportSettings) -> Option { + if settings.force_sw || forced("VE_SW_ENC") { + return None; + } + let (fps_num, fps_den) = crate::mux::frame_timing(meta.frame_rate).ok()?; + let bitrate = bitrate_of(meta, settings); + match settings.format { + // Opt-in only, for the reason [`Enc::open_av1`] states in full. Both + // AV1 formats sit on it: the container is not the encoder's business. + format if format.is_av1() && !forced("VE_HW_AV1") => None, + format if format.is_av1() => { + HwEncoder::open_av1(meta.width, meta.height, fps_num, fps_den, bitrate) + } + _ => HwEncoder::open(meta.width, meta.height, fps_num, fps_den, bitrate), + } +} + +/// How a front-end names a video seat: which of the two encoders has the file, +/// and which library that is. Not the codec -- a caller shows this beside the +/// format it picked, and `rav1e` names AV1 as `rusty_h264` names H.264. One +/// place, so what a card says before an export and what its progress line says +/// during one cannot drift apart. +fn video_label(format: Format, hw: bool) -> &'static str { + match (format.is_av1(), hw) { + (_, true) => "HW encode (VA-API)", + (true, false) => "SW encode (rav1e)", + (false, false) => "SW encode (rusty_h264)", + } +} + +/// The cheap half of "does this timeline's sound have to be re-encoded": what +/// the *edit* says, with no file opened. Two lanes are a mix and a mix is not a +/// copy; a speeded lane is resampled; an equalizer is sample math. The other +/// half -- whether the sources can be copied out of at all -- costs a file open +/// each and belongs to [`copy_audio`], which may re-encode where this says copy. +fn forces_encode(project: &Project) -> bool { + let lanes: Vec<_> = project + .audio_lanes() + .into_iter() + .filter(|&lane| !project.lane(lane).is_empty()) + .collect(); + lanes.len() > 1 + || lanes + .iter() + .any(|&lane| project.lane(lane).iter().any(|c| !c.speed.is_normal())) + || equalized(project) +} + +/// What the sound is written by. Every audio encoder here is software -- there +/// is no hardware AAC, PCM, FLAC or MP3 seat -- so this names *which* one, and +/// whether a container escapes encoding altogether by copying the packets it was +/// given. Both AV1 formats are in it like the mp4: an AV1 export carries the +/// timeline's sound too, so leaving it unnamed would be the old lie. +/// +/// A prediction, and it says so: `copied` is what [`copy_audio`] *did*, which a +/// card asking before the export has no way to know (a source that cannot be +/// copied out of is only found by opening it). `None` predicts from the edit +/// alone. +fn audio_label( + project: &Project, + format: Format, + sound: bool, + copied: Option, +) -> &'static str { + if !sound { + return "no sound to write"; + } + match format { + Format::Wav => "PCM · SW (hound)", + Format::Flac => "FLAC · SW (flacenc)", + Format::Mp3 => "MP3 · SW (rusty_mp3)", + _ => match copied.unwrap_or(!forces_encode(project)) { + true => "AAC copy", + false => "AAC · SW encode (rusty_aac)", + }, + } +} + +/// What [`start`] would write this timeline's sound with, before one is +/// started. Pure: no probe and no file opened, so a card may ask it per repaint. +pub fn planned_audio(project: &Project, format: Format) -> &'static str { + audio_label(project, format, has_sound(project), None) +} + +/// 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. +/// +/// Costs that open (~100 ms here): ask it off a render thread and keep the +/// answer until the format, the resolution or the bitrate changes. +pub fn planned_video(meta: &VideoMeta, settings: &ExportSettings) -> Option<&'static str> { + settings + .format + .has_video() + .then(|| video_label(settings.format, hw_seat(meta, settings).is_some())) +} + fn settle(shared: &Shared, result: crate::Result<()>) { *shared.outcome.lock().unwrap() = Some(result); // Published last: a caller that sees the flag is guaranteed the outcome. shared.finished.store(true, Ordering::Release); } +/// The audio track an export writes, and how it was made -- a copy is the +/// source's own packets, bit for bit, and anything else is this project's +/// encoder over the decoded mix. [`run`] publishes which of the two really +/// happened, so the encoder line a user reads is measured and not promised. +pub(crate) struct ExportAudio { + pub params: crate::AacTrackParams, + pub packets: Vec, + /// Whether those packets are the source's, untouched. + pub copied: bool, +} + /// The timeline's audio track for a file that carries picture: copied packet for /// packet where a copy says exactly what the timeline says, and decoded, mixed /// and encoded again ([`encode_audio`]) where it cannot -- a second audio lane, @@ -302,11 +460,7 @@ fn settle(shared: &Shared, result: crate::Result<()>) { /// ponytail: this holds the whole exported AAC track in memory (~3 kB per /// 23 ms packet, so ~500 MB for an hour). Upgrade path is a streaming /// `copy_segments` that yields packets instead of collecting them. -#[allow(clippy::type_complexity)] -fn copy_audio( - project: &Project, - meta: &VideoMeta, -) -> crate::Result)>> { +fn copy_audio(project: &Project, meta: &VideoMeta) -> crate::Result> { // The segments name their source, and the copy carries its packet-rounding // debt across a source join exactly as across a cut, so a timeline spanning // files stays in sync. A source whose AAC parameters disagree with the @@ -347,13 +501,24 @@ fn copy_audio( // copy never reaches: copying such a lane would write the clip *flat*, // silently. // + // A frame *rate* of its own is not one of those, and that is deliberate: do + // not "fix" this into a re-encode. A clip counts the **timeline's** frames + // whatever its file was shot at ([`crate::project::Rate`]), so the window + // this copy trims a source's sound to is `start..end` in whole timeline + // frames -- exactly the seconds the picture covers -- and the file is read + // at the pitch it was recorded at, which is what playing at the rate it was + // shot at means. There is no per-clip stretch to express, so the packets are + // already the right sound in the right place; re-encoding a conformed lane + // would buy nothing and cost a generation of loss on every mixed-rate export + // (`tests/mixed_fps.rs`, `an_export_of_two_rates_runs_at_the_speed_it_was_shot` + // measures the copied sound against the picture). A *speed* is different + // because it resamples, which is why it leaves through the re-encode above. + // // Only these: a timeline nobody has touched still leaves through the copy // below, packet for packet, so no passthrough quietly becomes a generation // of loss. let speeded = project.lane(lane).iter().any(|c| !c.speed.is_normal()); - let equalized = (0..project.lane(lane).len()) - .any(|idx| project.eq_of(lane, idx).is_some_and(|eq| !eq.is_identity())); - if speeded || equalized { + if speeded || equalized(project) { return encode_audio(project, meta); } // What is left is a copy the *sources* may still not be able to give: AAC @@ -365,7 +530,11 @@ fn copy_audio( // which symphonia has no decoder for at any version -- is the one that comes // back, by name, from [`encode_audio`]. match AudioSession::copy_multi_streams(&project.audio_sources(), segments) { - Ok(copied) => Ok(copied), + Ok(copied) => Ok(copied.map(|(params, packets)| ExportAudio { + params, + packets, + copied: true, + })), Err(_) => encode_audio(project, meta), } } @@ -387,11 +556,7 @@ fn copy_audio( /// minute of 48 kHz stereo), for [`run_audio`]'s reason -- `rusty_aac` buffers /// the whole stream anyway, since it encodes its frames in parallel. Upgrade /// path is a chunked push once that encoder streams. -#[allow(clippy::type_complexity)] -fn encode_audio( - project: &Project, - meta: &VideoMeta, -) -> crate::Result)>> { +fn encode_audio(project: &Project, meta: &VideoMeta) -> crate::Result> { let sources = project.audio_sources(); let segs = project.audio_segments_from(0, meta.frame_rate); let eqs = project.audio_eqs_from(0, meta.frame_rate); @@ -444,8 +609,8 @@ fn encode_audio( samples: packet.duration, }); } - Ok(Some(( - crate::AacTrackParams { + Ok(Some(ExportAudio { + params: crate::AacTrackParams { freq_index, // 1 and 2 are the ISO channel configurations for mono and stereo, // and the opener refuses anything wider than stereo already. @@ -453,7 +618,8 @@ fn encode_audio( sample_rate: audio.sample_rate, }, packets, - ))) + copied: false, + })) } fn run( @@ -471,16 +637,39 @@ fn run( // them into the clusters as it writes. Every video format gets the same // track: none of them is picture-only any more. let audio = copy_audio(project, meta)?; - let audio_params = audio.as_ref().map(|(track, _)| AudioParams { - freq_index: track.freq_index, - chan_conf: track.chan_conf, - sample_rate: track.sample_rate, + let audio_params = audio.as_ref().map(|track| AudioParams { + freq_index: track.params.freq_index, + chan_conf: track.params.chan_conf, + sample_rate: track.params.sample_rate, }); + // What the track *is*, kept before the packets are handed to a muxer: the + // encoder line names a copy or an encode and only `copy_audio` knows which. + let sound = audio.as_ref().map(|track| track.copied); // 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(|(_, packets)| packets); + let mut packets = audio.map(|track| track.packets); + + // 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 + // clip's timeline frames below become frames of the file. Real time for a + // still, a song and a single-rate project, where every conversion below is + // the identity. + let rates: Vec = sources + .iter() + .map(|source| source_rate(&source.path, meta.frame_rate)) + .collect(); let mut encoder = Enc::open(meta, settings)?; + // What this file is really being written by, for a progress line to name. + // Published *after* the seat is open, so a hardware encoder the driver + // refused reads as the software one that took over rather than as the hope + // it replaced -- and the sound says whether it was copied or encoded, which + // `copy_audio` decided a few lines up. + *shared.encoders.lock().unwrap() = Some(format!( + "{} · {}", + encoder.label(), + audio_label(project, settings.format, sound.is_some(), sound) + )); let mut muxer = None; let mut done = 0u32; let black = Black::new(meta); @@ -494,14 +683,18 @@ fn run( // encoder is *not* reopened, so the export is one continuous stream // whose GOP boundaries need not line up with the cuts -- nor with the // file boundaries, which are just cuts that change the path. - let mut pictures = match span.from { + let (mut pictures, rate, in_frame) = match span.from { Some((source, in_frame)) => { let entry = sources .get(source) .ok_or_else(|| format!("clip names source {source} of {}", sources.len()))?; - Some(ClipDecoder::open(&entry.path, in_frame)?) + let rate = rates[source]; + // 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))?; + (Some(pictures), rate, in_frame) } - None => None, + None => (None, Rate::REAL_TIME, 0), }; // What this span is graded by -- the same answer playback's decoder // carries, so the export is the picture that was watched. `None` for a @@ -532,10 +725,24 @@ fn run( let mut done_here = 0u32; // Source frames already taken out of this span's decoder. let mut taken = 0u32; + // The whole of the mapping, in the order it composes: the speed says + // which of the clip's (timeline-rate) frames a timeline frame shows, + // and the rate says which frame of the *file* that is -- counted from + // the one the decoder was opened at. At real time and at the timeline's + // own rate this is `Speed::source_at` and nothing else, which is the + // walk a single-rate project has always taken. + let opened_at = rate.source_at(in_frame); + let source_at = + |offset: u32| rate.source_at(in_frame + span.speed.source_at(offset)) - opened_at; while done_here < span.len { cancelled(shared)?; - let want = span.speed.source_at(done_here); - let repeats = span.speed.repeats(done_here, span.len); + let want = source_at(done_here); + // How many timeline frames from here show that same picture: one at + // real time, more when the clip is slowed or its file is slower + // than the timeline. Encoded again rather than decoded twice. + let repeats = (done_here..span.len) + .take_while(|&offset| source_at(offset) == want) + .count() as u32; let picture = match &mut pictures { Some(pictures) => { let mut ran_out = false; @@ -637,6 +844,24 @@ fn run( Ok(()) } +/// What rate `path` was shot at against a timeline at `timeline_fps` +/// ([`Rate`]). [`Rate::REAL_TIME`] for the files that have no rate of their own +/// -- a still, a song -- and for one that will not open here: the decoder is +/// opened a few lines later and fails the export by name, which is a better +/// error than this one could raise. +fn source_rate(path: &Path, timeline_fps: f64) -> Rate { + if crate::is_image(path) || crate::is_audio(path) { + return Rate::REAL_TIME; + } + match Demuxer::open(path) { + // ...and one whose rate cannot be named against the timeline's, which + // `matches_timeline` refuses at import, so nothing on a timeline is on + // this arm either. + Ok((meta, _)) => Rate::from_fps(meta.frame_rate, timeline_fps).unwrap_or(Rate::REAL_TIME), + Err(_) => Rate::REAL_TIME, + } +} + /// The audio lanes alone, summed, as a WAV or a FLAC. /// /// Nothing here re-derives the edit: the play lists are @@ -676,6 +901,9 @@ fn run_audio( else { return Err("this timeline has no audio to export".into()); }; + // The picture path's line, for a file that is sound alone: there is sound + // by the line above, so this names the encoder writing it. + *shared.encoders.lock().unwrap() = Some(audio_label(project, format, true, None).to_string()); let channels = usize::from(audio.channels); let frames = (f64::from(project.timeline_frames()) / meta.frame_rate * f64::from(audio.sample_rate)) @@ -994,6 +1222,18 @@ enum Enc { } impl Enc { + /// Which seat this *is*, said the way [`video_label`] says it -- so the + /// name a running export shows is the name the card showed, or the honest + /// difference where the probe and the open disagreed. + fn label(&self) -> &'static str { + match self { + Self::Hw(_) => video_label(Format::Mp4, true), + Self::Sw { .. } => video_label(Format::Mp4, false), + Self::Av1Hw(_) => video_label(Format::Av1, true), + Self::Av1Sw { .. } => video_label(Format::Av1, false), + } + } + fn open(meta: &VideoMeta, settings: &ExportSettings) -> crate::Result { // Which *codec* the picture is, not which container it goes in: both AV1 // formats run the same encoder. @@ -1003,18 +1243,13 @@ impl Enc { // A caller's number goes through the same clamp as the computed one: a // zero bitrate switches the software encoder's lookahead on, which would // break the one-picture-per-call contract `encode` documents below. - let bitrate = settings - .bitrate - .map_or_else(|| bitrate_for(meta), |b| b.clamp(MIN_BITRATE, MAX_BITRATE)); + let bitrate = bitrate_of(meta, settings); // The plugin wants an exact rational, and the muxer already picks one // that is exact at every rate we can read -- `fps * 1000 / 1000` would // hand 24000/1001 over as a rounded 23.976, which is the same // truncation the container timing had. - let (fps_num, fps_den) = crate::mux::frame_timing(meta.frame_rate)?; - if !settings.force_sw - && !forced("VE_SW_ENC") - && let Some(hw) = HwEncoder::open(meta.width, meta.height, fps_num, fps_den, bitrate) - { + crate::mux::frame_timing(meta.frame_rate)?; + if let Some(hw) = hw_seat(meta, settings) { eprintln!("export encoder: hardware (VA-API plugin)"); return Ok(Self::Hw(hw)); } @@ -1055,19 +1290,12 @@ impl Enc { /// cros-codecs release that fixes it) plus a probe encode of one frame at /// open, after which this can prefer hardware the way H.264 does. fn open_av1(meta: &VideoMeta, settings: &ExportSettings) -> crate::Result { - let bitrate = settings - .bitrate - .map_or_else(|| bitrate_for(meta), |b| b.clamp(MIN_BITRATE, MAX_BITRATE)); + let bitrate = bitrate_of(meta, settings); let (fps_num, fps_den) = crate::mux::frame_timing(meta.frame_rate)?; // Two seconds between keyframes, as the H.264 seat does: a seek may only // land on one, and this is what a cluster of the Matroska file is. let gop = (meta.frame_rate * 2.0).round().max(1.0) as u64; - if forced("VE_HW_AV1") - && !settings.force_sw - && !forced("VE_SW_ENC") - && let Some(hw) = - HwEncoder::open_av1(meta.width, meta.height, fps_num, fps_den, bitrate) - { + if let Some(hw) = hw_seat(meta, settings) { eprintln!("export encoder: hardware AV1 (VA-API plugin)"); return Ok(Self::Av1Hw(hw)); } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 246839b..015bbd7 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -27,7 +27,7 @@ pub use demux::{Codec, VideoMeta}; pub use export::ExportHandle; pub use mux::{AudioParams, Mp4Muxer, VideoParams}; pub use playback::PlaybackSession; -pub use project::{Clip, Project, Speed}; +pub use project::{Clip, Project, Rate, Speed}; /// Whether a path names a standalone audio file -- a source with no picture, /// which belongs on the audio lane and nowhere else. Extension only, lowercased: diff --git a/crates/engine/src/playback.rs b/crates/engine/src/playback.rs index cc58c39..d423fa4 100644 --- a/crates/engine/src/playback.rs +++ b/crates/engine/src/playback.rs @@ -22,10 +22,10 @@ use crate::ao::AoSession; use crate::audio::{AudioChunk, AudioSession}; use crate::clock::{ClockSource, PlaybackClock}; use crate::color::ColorParams; -use crate::decode::{DecodeSession, Frame, Worker}; +use crate::decode::{Backend, BackendCell, DecodeSession, Frame, Worker}; use crate::demux::{Codec, Demuxer, VideoMeta}; use crate::eq::EqParams; -use crate::project::{Clip, Edge, Lane, LaneKind, Project, Source, Span, Speed}; +use crate::project::{Clip, Edge, Lane, LaneKind, Project, Rate, Source, Span, Speed}; use crate::scale::{Composer, FitPolicy}; /// How long the feeder waits out a full ring. The ring holds a second, so this @@ -40,10 +40,11 @@ const RING_FULL_WAIT: Duration = Duration::from_millis(10); /// honest; both are what a video imported onto such a timeline is held to /// ([`matches_timeline`]). /// -/// ponytail: a 25 fps video refused by an audio-only timeline it could have -/// defined is the ceiling here. Upgrade path is adopting the first *picture's* -/// rate and codec on import, which means retiming every audio clip already -/// placed in frames. +/// ponytail: a 25 fps video imported onto an audio-only timeline it could have +/// defined plays at 25 fps, correctly, but on a 30 fps timeline -- it is read +/// through [`Rate`] like any other file shot at another rate rather than +/// defining one. Upgrade path is adopting the first *picture's* rate and codec +/// on import, which means retiming every audio clip already placed in frames. const AUDIO_ONLY_CANVAS: (u32, u32, f64) = (1920, 1080, 30.0); /// The frame rate a timeline scaffolded from a still image runs at, for @@ -160,6 +161,11 @@ pub struct PlaybackSession { frames: Receiver, /// The current decode worker. worker: Worker, + /// What that worker opened -- hardware, software, a still, a gap -- written + /// by the worker itself and read by [`decode_backend`](Self::decode_backend). + /// Replaced with the stream at every seek, so it always describes the + /// pictures currently arriving and never the clip before them. + backend: BackendCell, /// Workers cancelled by a seek or a clip change, waiting to be reaped. /// Joining one inline costs whatever VA-API init it is still inside (98 ms /// measured worst case), which is a visible hitch on the caller's thread; @@ -193,6 +199,20 @@ pub struct PlaybackSession { /// not -- with the single exception `sources` itself has, /// [`Self::remove_source`], which takes the same entry out of both. counts: Vec, + /// What each source's own frame rate is against this timeline's, indexed + /// and grown exactly as [`Self::counts`] is (and shortened with it by + /// [`Self::remove_source`]). [`Rate::REAL_TIME`] for a file shot at the + /// timeline's rate -- and for a still and a song, which have no rate of + /// their own -- so a single-rate project converts nothing anywhere. + /// + /// A clip counts *timeline* frames ([`Rate`]); this is the one thing that + /// knows which frames of the file those are, and only + /// [`start_span`](Self::start_span) and [`try_frame`](Self::try_frame) ask. + rates: Vec, + /// The rate of the source the current worker is decoding, kept beside + /// [`Self::span`] because the frames coming back are numbered in *its* + /// file's frames and nothing else can put them back on the timeline. + span_rate: Rate, /// What the current video worker was opened for: where it sits on the /// timeline, how long it runs, and which source frame it started at -- /// together they rewrite a source frame index into a timeline one. Not a @@ -259,12 +279,16 @@ impl PlaybackSession { native: (meta.width, meta.height), frames: stream.frames, worker: stream.worker, + backend: stream.backend, retired: Vec::new(), clock: PlaybackClock::new(source), audio, audio_disabled, project, counts: vec![meta.frame_count], + // Source 0 *is* the timeline's rate: it defined it. + rates: vec![Rate::REAL_TIME], + span_rate: Rate::REAL_TIME, span, eos: false, }) @@ -353,6 +377,7 @@ impl PlaybackSession { native: (width, height), frames: stream.frames, worker: stream.worker, + backend: stream.backend, retired: Vec::new(), // The song keeps the clock, as a video's own sound does -- and wall // time keeps it on a machine with no device, where the picture @@ -365,6 +390,9 @@ impl PlaybackSession { audio_disabled, project, counts: vec![meta.frame_count], + // Source 0 *is* the timeline's rate: it defined it. + rates: vec![Rate::REAL_TIME], + span_rate: Rate::REAL_TIME, span, eos: false, }) @@ -425,12 +453,16 @@ impl PlaybackSession { native: (meta.width, meta.height), frames: stream.frames, worker: stream.worker, + backend: stream.backend, retired: Vec::new(), clock: PlaybackClock::new(ClockSource::Wall), audio: None, audio_disabled: None, project, counts: vec![meta.frame_count], + // Source 0 *is* the timeline's rate: it defined it. + rates: vec![Rate::REAL_TIME], + span_rate: Rate::REAL_TIME, span, eos: false, }) @@ -554,9 +586,16 @@ impl PlaybackSession { // clip check below indexes this list by source, so it must line up with // `doc.sources` whichever entry the scaffolding came from. let mut counts = Vec::with_capacity(doc.sources.len()); + // Beside it, one entry per source, grown at every `push` below: the + // scaffold defines the rate, so it is read frame for frame; every other + // one is however long it is *in this timeline's frames*, which is the + // length `import` noted for it and the wall the clip check below holds + // it to. + 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); continue; } // A still has neither a rate to match nor a track to match with: @@ -567,6 +606,7 @@ impl PlaybackSession { crate::decode::image_size(&source.path) .map_err(|e| format!("source {}: {e}", source.path.display()))?; counts.push(image_frames(meta.frame_rate)); + rates.push(Rate::REAL_TIME); continue; } // A source with no picture is checked on what it does have, and @@ -576,13 +616,15 @@ impl PlaybackSession { audio_matches(source, &first_audio) .map_err(|e| format!("source {}: {e}", source.path.display()))?; counts.push(audio_frames(&source.path, meta.frame_rate)?); + rates.push(Rate::REAL_TIME); continue; } let (other, _) = Demuxer::open(&source.path) .map_err(|e| format!("source {}: {e}", source.path.display()))?; - matches_timeline(source, &other, &meta, &first_audio) + let rate = matches_timeline(source, &other, &meta, &first_audio) .map_err(|e| format!("source {}: {e}", source.path.display()))?; - counts.push(other.frame_count); + 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 @@ -647,6 +689,7 @@ impl PlaybackSession { native, frames: stream.frames, worker: stream.worker, + backend: stream.backend, retired: Vec::new(), clock: PlaybackClock::new(match audio { Some(_) => ClockSource::Audio, @@ -656,6 +699,8 @@ impl PlaybackSession { audio_disabled, project, counts, + rates, + span_rate: Rate::REAL_TIME, span, eos: false, }; @@ -672,6 +717,24 @@ impl PlaybackSession { &self.meta } + /// What the pictures now arriving are being decoded by: the clip under the + /// playhead, since one video worker feeds the composite at a time. An + /// atomic load -- a front-end may ask it every repaint -- and it is what + /// *opened*, so a clip whose hardware session fell back to software reads + /// [`Backend::Software`] from the frame that fallback happened. + pub fn decode_backend(&self) -> Backend { + self.backend.get() + } + + /// What an export of this timeline would encode the *sound* with, before + /// one is started: the copy an mp4 normally makes, or the software encoder + /// the format (or an equalized lane) forces. Pure -- no probe, no file + /// opened -- so a card may ask it per repaint; the picture's half costs a + /// plugin open and lives in [`crate::export::planned_video`]. + pub fn planned_audio(&self, format: crate::export::Format) -> &'static str { + crate::export::planned_audio(&self.project, format) + } + /// Why this session plays silent although the file has sound -- an audio /// track in a codec we cannot decode, or one the decoder refused. `None` /// when there is audio, and for a file that never had any. A front-end @@ -733,9 +796,15 @@ impl PlaybackSession { // (`speed_maps_both_ways`). An empty timeline has no span, // and its one black frame is frame 0. Real time is the // arithmetic this always did, frame for frame. - frame.index = self - .span - .map_or(frame.index, |s| s.timeline_at(frame.index)); + // ...through the file's own rate first, which is the ceil + // half of *that* pair: the picture at source frame `i` is + // due at the first timeline-rate frame that shows it, and a + // slower file's picture is therefore held for the frames in + // between. Real time for a gap and for a single-rate + // project, where this is the identity. + frame.index = self.span.map_or(frame.index, |s| { + s.timeline_at(self.span_rate.timeline_at(frame.index)) + }); return Some(frame); } Err(TryRecvError::Empty) => return None, @@ -805,6 +874,14 @@ impl PlaybackSession { /// timeline still moves, there are simply no more pictures, and the /// disconnected receiver carries the session on to the next span. fn start_span(&mut self, span: Option) { + // Which file's frames the worker about to be opened will number its + // pictures in: the span's own source, and real time for a gap, whose + // black worker counts timeline frames already. Set before the open, + // because the open is the first thing that converts with it. + self.span_rate = match span.and_then(|s| s.from) { + Some((source, _)) => self.rates.get(source).copied().unwrap_or(Rate::REAL_TIME), + None => Rate::REAL_TIME, + }; let opened = match span { // The grade is the composite's at this frame -- the same clip the // span itself came from -- and it is constant across the span, so @@ -841,10 +918,17 @@ impl PlaybackSession { .. }) => DecodeSession::open_worker( &self.project.sources()[source].path, - in_frame, + // The file's own frames, which is the only place they exist: + // a clip counts the timeline's ([`Rate`]). + self.span_rate.source_at(in_frame), // Source frames, which a speed makes more (or fewer) than the - // timeline frames the span covers. - in_frame + span.expect("matched above").source_len(), + // timeline frames the span covers -- and which a file shot at + // another rate makes fewer (or more) again. One past the last + // frame this span shows, not one past its length: at another + // rate those are two different frames. + self.span_rate.source_at( + in_frame + span.expect("matched above").source_len().saturating_sub(1), + ) + 1, self.project .composite_color_at(start) .copied() @@ -875,6 +959,7 @@ impl PlaybackSession { // 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; @@ -1120,13 +1205,36 @@ impl PlaybackSession { self.project.trim_room(lane, idx, edge, &self.counts) } - /// Records how long a source is, for a source index that may be one - /// `Project::import` just made or one it handed back. See [`Self::counts`]. - fn note_frames(&mut self, source: usize, frames: u32) { + /// Records how long a source is and what rate it was shot at, for a source + /// index that may be one `Project::import` just made or one it handed back. + /// See [`Self::counts`] and [`Self::rates`], which are one table in two + /// vectors and grow together. + fn note_frames(&mut self, source: usize, frames: u32, rate: Rate) { if source == self.counts.len() { self.counts.push(frames); + self.rates.push(rate); } debug_assert_eq!(self.counts.len(), self.project.sources().len()); + debug_assert_eq!(self.rates.len(), self.counts.len()); + } + + /// The rate noted for whichever source plays `path`, by + /// [`file_frames`](Self::file_frames)'s rule: one file is one rate however + /// many audio tracks it carries. [`Rate::REAL_TIME`] for a file this session + /// has never taken in. + fn file_rate(&self, path: &Path) -> Rate { + self.source_of(path) + .map_or(Rate::REAL_TIME, |i| self.rates[i]) + } + + /// Which source `path` is, canonicalising only if it has to: a source's own + /// path is canonical ([`Source::new`]), so a caller handing one back from + /// [`sources`](Self::sources) -- which is every library row -- hits on the + /// first walk and never pays for the `canonicalize` syscall the second one + /// makes. One rule, so a path that names a length names a rate too. + fn source_of(&self, path: &Path) -> Option { + let at = |wanted: &Path| self.project.sources().iter().position(|s| s.path == wanted); + at(path).or_else(|| at(&Source::new(path, 0).path)) } /// How long the whole of `path` is, in timeline frames: the length noted @@ -1138,14 +1246,20 @@ impl PlaybackSession { /// audio tracks it carries -- the picture's frame count for an mp4, the /// playing time for a song. pub fn file_frames(&self, path: &Path) -> u32 { - let at = |wanted: &Path| self.project.sources().iter().position(|s| s.path == wanted); - // A source's own path is canonical ([`Source::new`]), so a caller - // handing one back from [`sources`](Self::sources) -- which is every - // library row -- hits on the first walk and never pays for the - // `canonicalize` syscall the second one makes. - at(path) - .or_else(|| at(&Source::new(path, 0).path)) - .map_or(0, |i| self.counts[i]) + self.source_of(path).map_or(0, |i| self.counts[i]) + } + + /// What rate the file at `path` was *shot* at, in frames per second -- which + /// is the timeline's own rate for every source that shares it, and is not + /// for one placed at another ([`Rate`]). By path like + /// [`file_frames`](Self::file_frames), and the timeline's rate for a file + /// this session has never taken in (and for a still and a song, which were + /// shot at no rate at all). + /// + /// What a library row names the file with: the timeline's rate there would + /// be a lie about a 23.976 fps file the moment one can join. + pub fn file_fps(&self, path: &Path) -> f64 { + self.file_rate(path).as_f64() * self.meta.frame_rate } /// The clip the picture is coming from at `timeline_secs`: the lane it sits @@ -1304,8 +1418,9 @@ impl PlaybackSession { let first = self.first_audio()?; audio_matches(&wanted, &first)?; } + let rate = self.file_rate(&wanted.path); let source = self.project.import(path, stream); - self.note_frames(source, frames); + self.note_frames(source, frames, rate); let clip = Clip { start: 0, in_frame: 0, @@ -1387,6 +1502,7 @@ impl PlaybackSession { // count one index late. if idx < self.counts.len() { self.counts.remove(idx); + self.rates.remove(idx); } let now = self.now(); self.seek(now); @@ -1441,11 +1557,14 @@ impl PlaybackSession { /// nothing playable, so there is nothing for [`undo`](Self::undo) to take /// back, and nothing reseeks. /// - /// Refused unless it can join the timeline -- same codec, same frame rate, - /// same audio parameters or both silent; the `Err` names the property that - /// disagrees, for a caller to show. Nothing is changed by a refusal. A - /// *resolution* of its own is not a refusal: the clip is placed on the - /// project canvas by its fit policy ([`PlaybackSession::set_fit`]). + /// Refused unless it can join the timeline -- same codec, same audio + /// parameters or both silent; the `Err` names the property that disagrees, + /// for a caller to show. Nothing is changed by a refusal. A *resolution* of + /// its own is not a refusal: the clip is placed on the project canvas by its + /// fit policy ([`PlaybackSession::set_fit`]) -- and neither is a *frame + /// rate* of its own: the file is placed for the seconds it lasts and read at + /// [`Rate`] against the timeline's rate, so it plays at the speed it was + /// shot at. pub fn import(&mut self, path: &Path) -> crate::Result { if crate::is_audio(path) { return self.import_audio(path); @@ -1458,9 +1577,15 @@ impl PlaybackSession { // Stream 0: an import brings a file in on its first audio track, and // [`place_stream_at`](Self::place_stream_at) is how any other one of // its streams reaches the timeline afterwards. - matches_timeline(&Source::new(path, 0), &meta, &self.meta, &first)?; + // ...and the rate it will be read at comes back from the check that + // accepted it, so the number the refusal was decided on is the number + // the file is played by. + let rate = matches_timeline(&Source::new(path, 0), &meta, &self.meta, &first)?; let source = self.project.import(path, 0); - self.note_frames(source, meta.frame_count); + // Its length *on this timeline*: a file shot slower than the timeline + // runs covers more frames than it holds, which is the whole of what + // placing it at another rate means ([`Rate`]). + self.note_frames(source, rate.timeline_at(meta.frame_count), rate); Ok(source) } @@ -1480,7 +1605,7 @@ impl PlaybackSession { audio_matches(&Source::new(path, 0), &first)?; let frames = audio_frames(path, self.meta.frame_rate)?; let source = self.project.import(path, 0); - self.note_frames(source, frames); + self.note_frames(source, frames, Rate::REAL_TIME); Ok(source) } @@ -1504,7 +1629,7 @@ impl PlaybackSession { .into()); } let source = self.project.import(path, 0); - self.note_frames(source, image_frames(self.meta.frame_rate)); + self.note_frames(source, image_frames(self.meta.frame_rate), Rate::REAL_TIME); Ok(source) } @@ -1766,15 +1891,16 @@ impl Drop for PlaybackSession { /// Whether `path`, already demuxed to `meta`, may join a timeline whose /// parameters are `timeline` and whose audio probes as `first`: same codec, -/// same frame rate, same audio parameters or both silent. +/// same audio parameters or both silent, and a frame rate that can be named +/// against the timeline's. The [`Rate`] it will be read at comes back with the +/// answer, so the number the check was decided on is the number it plays by. /// /// *Not* the same size any more. A project has its own resolution /// ([`PlaybackSession::set_resolution`]) and every clip is placed on it by its /// own fit policy, so a 640x360 file joining a 1920x1080 timeline is a -/// letterboxed clip rather than a refusal. The frame rate stays refused on -/// purpose: mixing rates means resampling the *timeline*, which is a different -/// problem from resampling a picture, and a refusal is the honest answer until -/// it is solved. +/// letterboxed clip rather than a refusal, and so is a frame rate of its own: +/// the timeline keeps its own rate and the file is read at [`Rate`] against it +/// ([`PlaybackSession::import`] notes how long it is *here*). /// /// The `Err` names the property that disagrees, and those strings are what a /// front-end shows verbatim; [`PlaybackSession::import`] and @@ -1785,7 +1911,7 @@ fn matches_timeline( meta: &VideoMeta, timeline: &VideoMeta, first: &Option, -) -> crate::Result<()> { +) -> crate::Result { // Codec first: one timeline is one kind of source. Mixing them would decode // (every clip opens its own decoder) but on a machine without the VA-API // plugin the VP9 half would be black frames with the refusal only on @@ -1798,15 +1924,20 @@ fn matches_timeline( ) .into()); } - // Container frame rates are computed from timescales, so never `==`. - if (meta.frame_rate - timeline.frame_rate).abs() > 0.01 { - return Err(format!( - "{:.3} fps does not match the timeline's {:.3} fps", - meta.frame_rate, timeline.frame_rate - ) - .into()); - } - audio_matches(source, first) + // The frame rate is *not* a refusal any more: a file shot at another rate is + // placed for the seconds it lasts and read through [`Rate`] at the + // decoder's door, so it plays at the speed it was shot at on a timeline + // that counts frames faster or slower. + // + // A rate that cannot be *named* still is, and this is the one place it is + // caught: `Rate::from_fps` builds itself out of the muxer's own timescales, + // and a file whose rate has none of those (a container that says nothing and + // holds one block, so the demuxer measures 0 fps) would otherwise be read + // 1:1 in silence -- the old rate gate refused those too, by arithmetic + // accident. The `Err` is `mux::frame_timing`'s own words. + let rate = Rate::from_fps(meta.frame_rate, timeline.frame_rate)?; + audio_matches(source, first)?; + Ok(rate) } /// Whether a candidate's audio may join a timeline whose first source probes as diff --git a/crates/engine/src/project.rs b/crates/engine/src/project.rs index 7c7fe1e..5ae102b 100644 --- a/crates/engine/src/project.rs +++ b/crates/engine/src/project.rs @@ -221,9 +221,120 @@ impl std::fmt::Display for Speed { } } +/// What a file's own frame rate is against the timeline's, as an exact +/// rational: how many frames of the *file* one frame of the timeline is worth. +/// +/// Every frame number in this module counts **timeline** frames -- a clip's +/// `in_frame` and `out_frame` included -- so a 23.976 fps file placed on a 30 fps +/// timeline is as many frames long as the seconds it lasts, and every edit +/// (trim, split, speed, paste) is the same arithmetic it always was. This is the +/// one conversion, and it happens at the decoder's door: [`PlaybackSession`] +/// opens a worker with it and [`crate::export`] pulls pictures through it. The +/// file's own numbering exists nowhere else. +/// +/// The same floor/ceil pair as [`Speed`], for the same reason: the frame an +/// export encodes at a timeline frame has to be the frame playback is holding +/// there. Composed *after* a speed rather than folded into it, so a 2x 24 fps +/// clip on a 30 fps timeline is exactly both (`rate_composes_with_speed`). +/// +/// Rational and not an `f64`, exactly: 24000/1001 over 30 is `800/1001` and +/// stays `800/1001` however far the timeline runs, where a rate rounded to +/// (say) milli-fps would leave a fraction of a frame per clip to pile up into a +/// visible drift over an hour (`a_23_976_rate_is_exact_and_never_drifts`). +/// +/// [`PlaybackSession`]: crate::PlaybackSession +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub struct Rate { + /// Frames of the file... + source: u32, + /// ...per this many frames of the timeline it plays on. Never zero. + timeline: u32, +} + +impl Rate { + /// A file shot at the timeline's own rate: every conversion below is the + /// identity, which is the path a single-rate project is on. + pub const REAL_TIME: Self = Self { + source: 1, + timeline: 1, + }; + + /// The rate of a file at `source_fps` on a timeline at `timeline_fps`, + /// exactly. + /// + /// Both rates come out of a container as a division, so neither is ever the + /// number it means (`23.976023976...`); [`crate::mux::frame_timing`] is what + /// already knows how to name one exactly -- it is the same pair the muxer + /// counts an export's frames in -- and this is that pair divided by that + /// pair, reduced. A rate no timescale can name is an `Err` in that + /// function's own words rather than a silent 1:1 -- `matches_timeline` is + /// where a file carrying one is refused by name, beside the codec. + /// + /// Exactly [`REAL_TIME`](Self::REAL_TIME) when the two agree, which is every + /// timeline that had ever opened in this editor before mixed rates. + pub fn from_fps(source_fps: f64, timeline_fps: f64) -> crate::Result { + let (src_scale, src_ticks) = crate::mux::frame_timing(source_fps)?; + let (tl_scale, tl_ticks) = crate::mux::frame_timing(timeline_fps)?; + // fps is scale/ticks, so the ratio is (src_scale/src_ticks) / (tl_scale/tl_ticks). + let num = u64::from(src_scale) * u64::from(tl_ticks); + let den = u64::from(src_ticks) * u64::from(tl_scale); + let g = gcd(num, den); + let (mut num, mut den) = (num / g, den / g); + // A ratio no pair of real frame rates produces, but the fields are `u32` + // so that every multiplication below fits a `u64` at any frame count. + while num > u64::from(u32::MAX) || den > u64::from(u32::MAX) { + (num, den) = (num.div_ceil(2), den.div_ceil(2)); + } + Ok(Self { + source: num.max(1) as u32, + timeline: den.max(1) as u32, + }) + } + + pub fn is_real_time(self) -> bool { + self.source == self.timeline + } + + /// As a multiplier of the timeline's rate: what a *file's* own frame rate + /// is, given the timeline's, for a library row that names it. + pub fn as_f64(self) -> f64 { + f64::from(self.source) / f64::from(self.timeline) + } + + /// Which frame of the file the `frame`th timeline-rate frame of it is: + /// floored, [`Speed::source_at`]'s half of the pair. + pub fn source_at(self, frame: u32) -> u32 { + (u64::from(frame) * u64::from(self.source) / u64::from(self.timeline)) + .min(u64::from(u32::MAX)) as u32 + } + + /// Its inverse, ceiled ([`Speed::timeline_at`]'s half): the first + /// timeline-rate frame that shows source frame `source_frame` -- which is + /// the stamp playback puts on a decoded picture, and, applied to a file's + /// frame *count*, how long that file is in timeline frames. + pub fn timeline_at(self, source_frame: u32) -> u32 { + (u64::from(source_frame) * u64::from(self.timeline)) + .div_ceil(u64::from(self.source)) + .min(u64::from(u32::MAX)) as u32 + } +} + +/// Greatest common divisor, for reducing a [`Rate`] to the numbers that fit its +/// fields. `a` for `gcd(a, 0)`, and never zero: something divides by it. +fn gcd(a: u64, b: u64) -> u64 { + match b { + 0 => a.max(1), + b => gcd(b, a % b), + } +} + /// A half-open `[in_frame, out_frame)` range of frames of source /// [`source`](Clip::source), placed at timeline frame [`start`](Clip::start). /// Never empty. +/// +/// Counted at the **timeline's** frame rate, not the file's: a source shot at +/// another rate is converted at the decoder's door ([`Rate`]), so every edit +/// here is frames of one clock. #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub struct Clip { /// Timeline frame the clip's first frame is shown at. Meaningless on a @@ -4557,6 +4668,87 @@ mod tests { assert_eq!(Speed::from_permille(2500).to_string(), "2.50x"); } + /// [`Rate`] is [`Speed`]'s pair again, over the *file's* rate: the frame an + /// export encodes at a timeline frame is the one playback is holding there, + /// a file is as long in timeline frames as the seconds it lasts, and the two + /// compose so a speeded clip at another rate is exactly both. + #[test] + fn rate_composes_with_speed() { + // 23.976 into 30 (the ratio that does not terminate), 30 into 23.976, + // 60 into 30, 25 into 30 -- and the timeline's own rate, which must be + // the identity map or a single-rate project would move. + for (source_fps, timeline_fps) in [ + (24000. / 1001., 30.), + (30., 24000. / 1001.), + (60., 30.), + (25., 30.), + (30., 30.), + ] { + let rate = Rate::from_fps(source_fps, timeline_fps).expect("a nameable rate"); + for n in 0..2000u32 { + let source = rate.source_at(n); + // The stamp is the *first* timeline-rate frame that shows it, so + // the picture on screen at `n` is the picture encoded at `n`. + let held = (0..=source + 4) + .filter(|&s| rate.timeline_at(s) <= n) + .next_back(); + assert_eq!(held, Some(source), "{source_fps} on {timeline_fps} at {n}"); + } + // A file of `count` frames is `timeline_at(count)` frames long here, + // and its last one still reads a frame the file has. + for count in 1..500u32 { + let frames = rate.timeline_at(count); + assert!(frames >= 1, "a file is never zero frames long"); + assert!( + rate.source_at(frames - 1) < count, + "{source_fps} on {timeline_fps}: {count} frames reads past the file" + ); + } + // No drift: the mapping is one exact division of the *rate itself*, + // not an accumulation and not a rounded rate, so an hour in is as + // true as the first second. (Held to the real ratio of the two rates + // the caller asked for -- `as_f64` would be true of a wrong rate.) + for n in [1u32, 100, 10_000, 500_000, 3_000_000] { + let want = f64::from(n) * source_fps / timeline_fps; + assert!( + (f64::from(rate.source_at(n)) - want).abs() < 1., + "{source_fps} on {timeline_fps}: frame {n} drifted" + ); + } + } + // The timeline's own rate is the identity, whichever way it is written. + assert!(Rate::from_fps(30., 30.).expect("30 over 30").is_real_time()); + assert!( + Rate::from_fps(30.0004, 30.) + .expect("30.0004 over 30") + .is_real_time(), + "a rate is named by the muxer's timescales, and 30.0004 is 30030/1001" + ); + // ...and a rate no timescale can name is an `Err`, not a silent 1:1: the + // one thing `matches_timeline` refuses a file for now that the rate gate + // is gone. + assert!(Rate::from_fps(0., 30.).is_err(), "not a rate at all"); + assert!(Rate::from_fps(30., f64::NAN).is_err()); + for n in 0..1000 { + assert_eq!(Rate::REAL_TIME.source_at(n), n); + assert_eq!(Rate::REAL_TIME.timeline_at(n), n); + } + // ...and the composition, in the order the decoder's door applies it: + // the speed picks the clip's (timeline-rate) frame, the rate picks the + // file's. A 2x clip of a 23.976 fps file on a 30 fps timeline reads two + // timeline frames per frame shown, each of them exactly 800/1001 of a + // file frame. + let rate = Rate::from_fps(24000. / 1001., 30.).expect("23.976 over 30"); + let speed = Speed::from_permille(2000); + for d in 0..100u32 { + assert_eq!( + rate.source_at(speed.source_at(d)), + (u64::from(d) * 2 * 800 / 1001) as u32, + "2x of a 23.976 fps file at timeline frame {d}" + ); + } + } + /// The mapping a speed changes, and the one it does not: a 2x clip reads two /// source frames per timeline frame and still starts at its own in-point, /// and a half-speed one shows every source frame twice. diff --git a/crates/engine/tests/audio_files.rs b/crates/engine/tests/audio_files.rs index f0e43ad..d1d018f 100644 --- a/crates/engine/tests/audio_files.rs +++ b/crates/engine/tests/audio_files.rs @@ -386,20 +386,21 @@ fn a_video_joins_a_timeline_a_song_started() { import_and_place(&mut session, &asset("test_av.mp4")); assert_eq!(session.lane_clips(Lane::V1).len(), 1, "a picture at last"); assert_eq!(session.lane_clips(Lane::A1).len(), 2); - // And a file at another rate is refused in the timeline's own words rather - // than silently retiming the song already on the lane -- the sample rate at - // one door, the *frame* rate at the other: the canvas a song scaffolds has - // a frame rate of its own (30 fps), and a 25 fps picture cannot join it. + // A sample rate the device cannot have two of is still refused in the + // timeline's own words... let e = refusal(session.import(&asset("test_tone_48k.wav"))); assert_eq!( e, "audio 48000 Hz 2 ch does not match the timeline's 44100 Hz 2 ch" ); - assert_eq!( - refusal(session.import(&asset("test_25fps.mp4"))), - "25.000 fps does not match the timeline's 30.000 fps" - ); assert_eq!(session.sources().len(), 2, "a refusal left a library row"); + // ...but a *frame* rate of its own is not a refusal: the canvas a song + // scaffolds runs at 30 fps and a 25 fps picture joins it at the length it + // lasts in seconds (50 frames of file, 60 of timeline). + session + .import(&asset("test_25fps.mp4")) + .expect("25 fps joins the 30 fps canvas a song scaffolded"); + assert_eq!(session.file_frames(&asset("test_25fps.mp4")), 60); } /// Blocks until the export settles, whichever way it settled. diff --git a/crates/engine/tests/backends.rs b/crates/engine/tests/backends.rs new file mode 100644 index 0000000..0a995e0 --- /dev/null +++ b/crates/engine/tests/backends.rs @@ -0,0 +1,208 @@ +//! Which decoder and which encoder a job really runs on -- the introspection a +//! front-end shows before an operation and while it runs. +//! +//! The point of every assertion here is *truthfulness*, not a particular seat: +//! this box may or may not have a working plugin, and a test that demanded +//! hardware would only be measuring the machine. What must hold is that the +//! answer given before an operation is the answer the operation then gives, and +//! that neither of them ever names a decoder that could not have run (software +//! HEVC, for one, does not exist here). + +use std::path::PathBuf; +use std::time::{Duration, Instant}; + +use engine::Codec; +use engine::decode::{Backend, probe}; +use engine::export::{ExportSettings, Format}; +use engine::{ExportHandle, PlaybackSession}; + +fn asset(name: &str) -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("../../assets") + .join(name) +} + +fn out_path(name: &str, ext: &str) -> PathBuf { + let path = std::env::temp_dir().join(format!("ve_backend_{name}_{}.{ext}", std::process::id())); + let _ = std::fs::remove_file(&path); + let _ = std::fs::remove_file(format!("{}.part", path.display())); + path +} + +/// A still has no coded stream and no decoder to pick, and it must say so +/// rather than borrowing the picture path's answer. +#[test] +fn a_still_probes_as_a_still() { + let (codec, backend) = probe(&asset("test_still.png")).expect("probe the still"); + assert_eq!(codec, None, "an image has no coded stream to name"); + assert_eq!(backend, Backend::Still); +} + +/// H.264 has both seats, so the probe may legitimately answer either -- but it +/// must answer one of them, and it must name the codec. +#[test] +fn an_h264_source_probes_as_one_of_the_two_seats() { + let (codec, backend) = probe(&asset("test_baseline.mp4")).expect("probe the baseline fixture"); + assert_eq!(codec, Some(Codec::H264)); + assert!( + matches!(backend, Backend::Hardware | Backend::Software), + "a probe that returned must have picked a seat, got {backend:?}" + ); +} + +/// HEVC has no software decoder here at all. A box with the plugin answers +/// hardware; a box without it is refused by name -- and *never* told that +/// `rusty_h264` will take it, which is the one answer that would be a lie. +#[test] +fn hevc_probes_as_hardware_or_as_a_refusal() { + match probe(&asset("test_hevc.mkv")) { + Ok((codec, backend)) => { + assert_eq!(codec, Some(Codec::Hevc)); + assert_eq!(backend, Backend::Hardware, "there is no software HEVC here"); + } + Err(e) => assert!( + e.to_string().contains("plugin"), + "a refusal names the plugin, got {e}" + ), + } +} + +/// The running session reports the decoder its *worker* opened, and it agrees +/// with what the probe said before anything played. This is the whole point of +/// the cell: the worker writes it where the fallback happens, so a hardware +/// session that dropped to software could only be seen here. +#[test] +fn a_playing_session_reports_the_seat_the_probe_named() { + let path = asset("test_baseline.mp4"); + let (_codec, probed) = probe(&path).expect("probe the baseline fixture"); + let session = PlaybackSession::open(&path).expect("open the fixture"); + let started = Instant::now(); + loop { + let live = session.decode_backend(); + if live != Backend::Opening { + assert_eq!(live, probed, "the running seat is not the probed one"); + break; + } + assert!( + started.elapsed() < Duration::from_secs(20), + "the worker never published a decode backend" + ); + std::thread::sleep(Duration::from_millis(10)); + } +} + +/// What the export card says before the button and what the progress line says +/// during the job are the same two answers, from the same two functions: the +/// picture's seat is probed by opening the very encoder the export opens, and +/// the sound's is decided outright. A drift between them is a front-end lying +/// about the machine, which is exactly what this whole surface is for. +/// +/// Every picture format, because each one is a different pair of seats: H.264 +/// through `rusty_h264` or the plugin, and AV1 through `rav1e` in either +/// container -- a container is not an encoder, and the card must not say it is. +#[test] +fn the_planned_encoders_are_the_ones_the_job_opens() { + for (format, ext) in [ + (Format::Mp4, "mp4"), + (Format::Av1, "mkv"), + (Format::Av1Mp4, "mp4"), + ] { + let settings = ExportSettings { + format, + ..ExportSettings::default() + }; + let session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture"); + let planned = format!( + "{} · {}", + engine::export::planned_video(session.meta(), &settings) + .expect("these formats carry picture"), + session.planned_audio(format) + ); + let out = out_path("planned", ext); + let handle = session.export_to_with(&out, &settings); + let started = Instant::now(); + let opened = loop { + if let Some(line) = handle.encoders() { + break line; + } + assert!( + !handle.is_finished(), + "the export settled before it opened an encoder: {:?}", + handle.result().map(|r| r.err()) + ); + assert!( + started.elapsed() < Duration::from_secs(60), + "no encoder was published" + ); + std::thread::sleep(Duration::from_millis(10)); + }; + // Nothing here wants the file, only the seat it was going to be written + // with: cancelling deletes the `.part` the worker had started. + handle.cancel(); + wind_down(&handle); + assert_eq!(opened, planned, "{ext}"); + // ...and the sound is named on both, AV1 included: an AV1 export + // carries the timeline's audio now, so a line that said nothing about + // it would be the old picture-only lie in a new place. + assert!(planned.contains("AAC"), "{ext}: {planned}"); + } +} + +/// A WAV job has no picture at all and still names what writes it, so an audio +/// export is not a progress line with nothing to say. +#[test] +fn an_audio_only_job_names_its_encoder() { + for format in [Format::Wav, Format::Flac, Format::Mp3] { + audio_only_job_names_its_encoder(format); + } +} + +fn audio_only_job_names_its_encoder(format: Format) { + let settings = ExportSettings { + format, + ..ExportSettings::default() + }; + assert_eq!( + engine::export::planned_video( + &engine::demux::Demuxer::open(&asset("test_av.mp4")) + .expect("open the fixture") + .0, + &settings + ), + None, + "an audio-only format has no video seat to name" + ); + let session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture"); + let planned = session.planned_audio(format); + let out = out_path("audio", format.ext()); + let handle = session.export_to_with(&out, &settings); + let started = Instant::now(); + let opened = loop { + if let Some(line) = handle.encoders() { + break line; + } + assert!( + started.elapsed() < Duration::from_secs(60), + "no encoder was published" + ); + std::thread::sleep(Duration::from_millis(10)); + }; + handle.cancel(); + wind_down(&handle); + let _ = std::fs::remove_file(&out); + assert_eq!(opened, planned, "{}", format.ext()); +} + +/// Waits for a cancelled job to settle, so its `.part` is gone before the test +/// ends -- and so no worker outlives the process holding a VA-API session. +fn wind_down(handle: &ExportHandle) { + let started = Instant::now(); + while !handle.is_finished() { + assert!( + started.elapsed() < Duration::from_secs(60), + "a cancelled export did not settle" + ); + std::thread::sleep(Duration::from_millis(10)); + } + let _ = handle.result(); +} diff --git a/crates/engine/tests/mixed_fps.rs b/crates/engine/tests/mixed_fps.rs new file mode 100644 index 0000000..68d8156 --- /dev/null +++ b/crates/engine/tests/mixed_fps.rs @@ -0,0 +1,419 @@ +//! Clips shot at other frame rates on one timeline: what a 25 fps and a 23.976 +//! fps file do on the 30 fps timeline `test_av.mp4` scaffolds. +//! +//! Everything goes through the front door -- `import`, `place_stream_at`, +//! `seek`, `export_to_with`, `open_project` -- because the whole claim is that a +//! *user* can put two rates on one timeline and watch both at the speed they +//! were shot at. `project.rs`'s own `rate_composes_with_speed` owns the +//! arithmetic; what is measured here is that the pictures and the file agree +//! with it. +//! +//! ```text +//! cargo test -p engine --test mixed_fps +//! ``` + +use std::path::{Path, PathBuf}; +use std::thread::sleep; +use std::time::{Duration, Instant}; + +use engine::export::{ExportSettings, Format}; +use engine::project::{Edge, Lane, Rate, Speed}; +use engine::{DecodeSession, Frame, PlaybackSession}; + +/// The timeline's rate, which `test_av.mp4` (30 fps, 5 s) defines. +const FPS: f64 = 30.0; + +fn asset(name: &str) -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("../../assets") + .join(name) +} + +/// Silent, for `tests/playback.rs`'s reason: the suite plays real files. +fn open(path: impl AsRef) -> PlaybackSession { + let session = PlaybackSession::open(path).expect("open"); + session.set_gain(0.0); + session +} + +fn next_frame(session: &mut PlaybackSession, what: &str) -> Frame { + let deadline = Instant::now() + Duration::from_secs(10); + loop { + if let Some(frame) = session.try_frame() { + return frame; + } + assert!(Instant::now() < deadline, "no frame after {what}"); + sleep(Duration::from_millis(4)); + } +} + +/// One frame of a file, decoded straight from it: the picture a mapping is +/// checked against, in the file's *own* numbering. +fn source_frame(path: &Path, index: u32) -> Vec { + let (_, rx, _cancel) = DecodeSession::open_range(path, index, index + 1).expect("open_range"); + let frame = rx + .recv_timeout(Duration::from_secs(10)) + .expect("reference frame"); + assert_eq!(frame.index, index, "open_range starts where it is told"); + frame.bgra +} + +/// Imports `path` and drags it onto the end of the timeline, the way a library +/// row reaches a lane. +fn import_and_place(session: &mut PlaybackSession, path: &Path) { + session.import(path).expect("the file joins this timeline"); + let end = session.timeline_duration(); + assert!( + session + .place_stream_at(end, path, 0, None) + .expect("a file just imported is on this timeline"), + "the drag onto the end of the timeline" + ); +} + +fn wait(handle: &engine::ExportHandle) -> engine::Result<()> { + let deadline = Instant::now() + Duration::from_secs(180); + while !handle.is_finished() { + assert!(Instant::now() < deadline, "export did not finish"); + sleep(Duration::from_millis(20)); + } + handle.result().expect("a finished export has an outcome") +} + +/// How different two pictures are, sampled: a re-encode moves every pixel a +/// little and a *different* picture of `testsrc2` moves them a lot, so the two +/// are never close to the threshold below. +fn difference(a: &[u8], b: &[u8]) -> f64 { + assert_eq!(a.len(), b.len(), "two pictures of one size"); + let (mut sum, mut n) = (0f64, 0u32); + for i in (0..a.len()).step_by(997) { + sum += f64::from(a[i].abs_diff(b[i])); + n += 1; + } + sum / f64::from(n.max(1)) +} + +/// A file's length is the seconds it lasts, in the timeline's frames -- not the +/// frames it holds. That is the whole of what placing another rate means: 50 +/// frames of 25 fps and 48 of 23.976 fps are both two seconds, and two seconds +/// of a 30 fps timeline is 60 frames. +#[test] +fn a_file_at_another_rate_is_placed_for_the_seconds_it_lasts() { + let mut session = open(asset("test_av.mp4")); + assert_eq!(session.file_frames(&asset("test_av.mp4")), 150, "5 s at 30"); + + let pal = asset("test_25fps.mp4"); + session + .import(&pal) + .expect("25 fps joins a 30 fps timeline"); + assert_eq!(session.file_frames(&pal), 60, "50 frames at 25 fps is 2 s"); + + // 24000/1001: 48 frames is 2.002 s, which is 60.06 frames of 30 fps -- + // rounded *up*, so the last picture is still reachable by a trim. + let ntsc = asset("test_23976fps.mp4"); + session.import(&ntsc).expect("23.976 joins it too"); + assert_eq!(session.file_frames(&ntsc), 61); + + // ...and placed, both are as long on the timeline as they are in the ear. + let end = session.timeline_duration(); + session + .place_stream_at(end, &pal, 0, None) + .expect("the drag"); + assert!( + (session.timeline_duration() - (5.0 + 2.0)).abs() < 1e-9, + "a 2 s clip made the timeline {} s", + session.timeline_duration() + ); + let end = session.timeline_duration(); + session + .place_stream_at(end, &ntsc, 0, None) + .expect("the drag"); + assert!( + (session.timeline_duration() - (5.0 + 2.0 + 61. / FPS)).abs() < 1e-9, + "{} s", + session.timeline_duration() + ); + // ...and the sound that came down with each take is the same length as its + // picture: a placed take is one linked group, so a rate that stretched only + // the picture would slide the two apart on the very first drag. + let (video, audio) = (session.lane_clips(Lane::V1), session.lane_clips(Lane::A1)); + assert_eq!(video.len(), 3, "the 30 fps take and the two others"); + assert_eq!(audio.len(), video.len(), "one audio clip per take"); + for (v, a) in video.iter().zip(audio) { + assert_eq!((v.start, v.len()), (a.start, a.len()), "{v:?} vs {a:?}"); + } +} + +/// The NTSC ratio, which the 23.976 fps fixture is shot at: 24000/1001 over 30 +/// is exactly 800/1001, and it stays exact however far the timeline runs. A rate +/// rounded to a float -- or to milli-fps -- would leave a fraction of a frame +/// per clip to pile up into a visible drift over an hour, which is why the +/// mapping is built out of the muxer's own timescales and not a division. +#[test] +fn a_23_976_rate_is_exact_and_never_drifts() { + let ntsc = Rate::from_fps(24_000.0 / 1001.0, FPS).expect("23.976 over 30"); + assert!( + (ntsc.as_f64() - 800.0 / 1001.0).abs() < 1e-15, + "{}", + ntsc.as_f64() + ); + // Independent integer arithmetic, out to an hour of source and past it: 800 + // source frames per 1001 timeline ones, and a file's length is that ceiled + // (the last picture must still be reachable by a trim). + for source in [1u64, 2, 24, 1000, 86_486, 500_000, 1_000_000] { + assert_eq!( + u64::from(ntsc.timeline_at(source as u32)), + (source * 1001).div_ceil(800), + "{source} source frames" + ); + } + // ...and the two directions stay each other's inverse at every one of them: + // the frame an export writes at timeline frame `d` is the frame playback is + // holding there, which is what `timeline_at`'s ceil buys. + for d in [0u32, 1, 2, 3, 1000, 100_000, 1_000_000] { + let source = ntsc.source_at(d); + assert!(ntsc.timeline_at(source) <= d, "frame {d} is not yet due"); + assert!( + ntsc.timeline_at(source + 1) > d, + "the next frame is due too early at {d}" + ); + } + // A timeline's own rate conforms by nothing at all, exactly -- whichever of + // the two rates it is written at. + assert!(Rate::from_fps(FPS, FPS).expect("30 over 30").is_real_time()); + assert!( + Rate::from_fps(24_000.0 / 1001.0, 24_000.0 / 1001.0) + .expect("ntsc over ntsc") + .is_real_time() + ); + // A rate no timescale can name is refused rather than read 1:1 in silence: + // the one thing `matches_timeline` still turns a file away for. + assert!(Rate::from_fps(0.0, FPS).is_err(), "not a rate at all"); +} + +/// The picture on screen at a timeline frame is the picture the *file* holds +/// there: frame `floor(offset * 25/30)` of a 25 fps clip, which is what playing +/// at the speed it was shot at means, frame for frame. +#[test] +fn playback_shows_the_frame_the_file_holds_there() { + let pal = asset("test_25fps.mp4"); + let mut session = open(asset("test_av.mp4")); + import_and_place(&mut session, &pal); + session.pause(); + // The clip starts at timeline frame 150 (5 s) and runs 60 frames. + let start = 150u32; + for offset in [0u32, 1, 5, 6, 29, 30, 47, 59] { + let at = start + offset; + session.seek(f64::from(at) / FPS); + let landed = next_frame(&mut session, "a seek into the 25 fps clip"); + assert_eq!(landed.index, at, "a seek lands on the frame it asked for"); + let want = (u64::from(offset) * 25_000 / 30_000) as u32; + assert!( + landed.bgra == source_frame(&pal, want), + "timeline frame {at} (offset {offset}) is not source frame {want}" + ); + } + // Past the last picture the file holds, the clip is still on the timeline: + // its last frame is shown, not black and not a panic. + session.seek(f64::from(start + 59) / FPS); + let last = next_frame(&mut session, "the last frame of the clip"); + assert!(last.bgra == source_frame(&pal, 49), "source frame 49 last"); + // ...and the frame in front of it is the 30 fps take, frame for frame: a + // rate belongs to the source that has one, so the clip beside it is read + // exactly as it was before any of this existed. + let av = asset("test_av.mp4"); + session.seek(f64::from(start - 1) / FPS); + let before = next_frame(&mut session, "the last frame of the 30 fps take"); + assert_eq!(before.index, start - 1); + assert!( + before.bgra == source_frame(&av, start - 1), + "the 30 fps clip is still frame for frame" + ); +} + +/// A trim of a clip at another rate is dragged in *timeline* frames and commits +/// the source range those frames are worth -- so the box is exactly the room it +/// was dragged to, and the picture at its new edge is the file's own frame +/// there. +#[test] +fn a_clip_at_another_rate_trims_to_the_room_it_was_dragged_to() { + let pal = asset("test_25fps.mp4"); + let mut session = open(asset("test_av.mp4")); + import_and_place(&mut session, &pal); + session.pause(); + let start = 150u32; + // Drag its tail back to 30 timeline frames of room: one second, which at 25 + // fps is the file's first 25 pictures. + assert!( + session.trim_clip(Lane::V1, 1, Edge::End, start + 30), + "trim the tail of the 25 fps clip" + ); + let clip = session.lane_clips(Lane::V1)[1]; + assert_eq!((clip.start, clip.len()), (start, 30), "{clip:?}"); + session.seek(f64::from(start + 29) / FPS); + let last = next_frame(&mut session, "the trimmed tail"); + assert!( + last.bgra == source_frame(&pal, 24), + "one second of a 25 fps file ends on its frame 24" + ); + // ...and its head, dragged forward into source it keeps: 6 timeline frames + // in is 5 source frames in, and the tail did not move. + assert!(session.trim_clip(Lane::V1, 1, Edge::Start, start + 6)); + let clip = session.lane_clips(Lane::V1)[1]; + assert_eq!((clip.start, clip.len()), (start + 6, 24), "{clip:?}"); + session.seek(f64::from(start + 6) / FPS); + let head = next_frame(&mut session, "the trimmed head"); + assert!( + head.bgra == source_frame(&pal, 5), + "6 frames of a 30 fps timeline is 5 frames of a 25 fps file" + ); +} + +/// A speed and a frame rate compose: a 2x 25 fps clip on a 30 fps timeline is +/// half as many timeline frames and reads twice as far into the file for each +/// of them. +#[test] +fn a_speeded_clip_at_another_rate_is_exactly_both() { + let pal = asset("test_25fps.mp4"); + let mut session = open(asset("test_av.mp4")); + import_and_place(&mut session, &pal); + session + .set_speed(Lane::V1, 1, Speed::from_permille(2000)) + .expect("nothing is in the way of a clip that got shorter"); + session.pause(); + let start = 150u32; + assert!( + (session.timeline_duration() - (5.0 + 1.0)).abs() < 1e-9, + "2 s at 2x is 1 s: {}", + session.timeline_duration() + ); + for offset in [0u32, 3, 14, 29] { + let at = start + offset; + session.seek(f64::from(at) / FPS); + let landed = next_frame(&mut session, "a seek into the speeded clip"); + assert_eq!(landed.index, at); + // The speed picks the clip's (timeline-rate) frame, the rate picks the + // file's -- in that order, which is the order the decoder's door + // applies them. + let want = (u64::from(offset) * 2 * 25_000 / 30_000) as u32; + assert!( + landed.bgra == source_frame(&pal, want), + "2x at offset {offset} is not source frame {want}" + ); + } +} + +/// A saved project reloads at the same lengths: `open_project` recomputes every +/// source's rate from the file, so a mixed-rate timeline is not one that only +/// the session that built it could hold. +#[test] +fn a_mixed_rate_project_reloads_unchanged() { + let pal = asset("test_25fps.mp4"); + let mut session = open(asset("test_av.mp4")); + import_and_place(&mut session, &pal); + let duration = session.timeline_duration(); + let spans = session.clip_spans(); + let path = std::env::temp_dir().join(format!("edith-mixed-{}.edith", std::process::id())); + session.save_project(&path).expect("save"); + + let reloaded = PlaybackSession::open_project(&path).expect("a mixed-rate project reopens"); + assert_eq!(reloaded.clip_spans(), spans, "the same clips, in seconds"); + assert!((reloaded.timeline_duration() - duration).abs() < 1e-9); + assert_eq!(reloaded.file_frames(&pal), 60, "the length was recomputed"); + std::fs::remove_file(&path).ok(); +} + +/// The export is what was watched: as many frames as the timeline has, and the +/// 25 fps clip walked through its file at 25 fps -- 25 pictures over 30 frames, +/// not 30 of them and not 25 held to the end. +#[test] +fn an_export_of_two_rates_runs_at_the_speed_it_was_shot() { + let pal = asset("test_25fps.mp4"); + let mut session = open(asset("test_av.mp4")); + // A short head of the 30 fps take, then the whole of the 25 fps one -- + // enough of each to be a mixed timeline, short enough to encode in a test. + // The sound comes with it: a placed take is one linked group. + assert!( + session.trim_clip(Lane::V1, 0, Edge::End, 15), + "trim the 30 fps take to half a second" + ); + import_and_place(&mut session, &pal); + assert!( + session.trim_clip(Lane::V1, 1, Edge::End, 45), + "one second of the 25 fps clip" + ); + let total = (session.timeline_duration() * FPS).round() as u32; + assert_eq!(total, 45, "15 frames of 30 fps and 30 of the 25 fps clip"); + + let out = std::env::temp_dir().join(format!("edith-mixed-{}.mp4", std::process::id())); + wait(&session.export_to_with( + &out, + &ExportSettings { + format: Format::Mp4, + ..ExportSettings::default() + }, + )) + .expect("the export"); + + // Duration first: the file is as long as the timeline, so the mixed rates + // did not stretch or shorten it. + let (meta, rx, _cancel) = DecodeSession::open_range(&out, 0, u32::MAX).expect("reopen"); + assert!( + (meta.frame_rate - FPS).abs() < 0.01, + "the export runs at the timeline's rate: {}", + meta.frame_rate + ); + assert_eq!( + meta.frame_count, total, + "the export is the timeline's length" + ); + let written: Vec> = rx.into_iter().map(|frame| frame.bgra).collect(); + assert_eq!(written.len() as u32, total, "every frame came back"); + + // ...and motion: inside the 25 fps clip, 30 exported frames show 25 + // pictures, so 5 of them are a picture held from the frame before. A clip + // played at the wrong rate would hold none (too fast, and it would run out + // of file) or hold half of them (too slow). + let held = (16..total as usize) + .filter(|&i| difference(&written[i - 1], &written[i]) < 2.0) + .count(); + assert_eq!( + held, 5, + "30 timeline frames of a 25 fps clip hold 5 pictures over" + ); + + // ...and *which* picture each of those frames is: the very one playback + // holds there, which is the whole reason the two conversions are one + // floor/ceil pair. Nearer its own source frame than either neighbour rather + // than equal to it -- the export is re-encoded, so no pixel survives whole. + for offset in [0u32, 1, 6, 12, 24, 29] { + let want = (u64::from(offset) * 25_000 / 30_000) as u32; + let mine = difference(&written[(15 + offset) as usize], &source_frame(&pal, want)); + for other in [want.saturating_sub(1), want + 1] { + if other == want { + continue; + } + assert!( + mine < difference(&written[(15 + offset) as usize], &source_frame(&pal, other)), + "exported frame {offset} of the 25 fps clip is nearer source \ + frame {other} than its own {want}" + ); + } + } + + // The sound came out as long as the picture, from a *packet copy*: a clip + // counts timeline frames whatever its file was shot at, so the window this + // export trimmed the 25 fps file's AAC to is whole timeline frames and the + // copy is in sync. This is the assertion behind the note in + // `export::copy_audio` that says not to turn a conformed lane into a + // re-encode. + let secs = engine::AudioSession::duration_secs(&out) + .expect("probe the export") + .expect("the export has sound"); + let want = f64::from(total) / FPS; + assert!( + (secs - want).abs() < 0.05, + "sound is {secs} s under {want} s of picture" + ); + std::fs::remove_file(&out).ok(); +} diff --git a/crates/engine/tests/playback.rs b/crates/engine/tests/playback.rs index ea97884..5268282 100644 --- a/crates/engine/tests/playback.rs +++ b/crates/engine/tests/playback.rs @@ -813,14 +813,15 @@ fn import_refuses_what_does_not_match() { "a resolution of its own is not a refusal any more: {err}" ); - // Same codec, same audio, 25 fps: the one property left, named with both - // rates. Mixing rates would mean retiming the timeline itself, and there is - // no resampler for that, so the refusal is the honest answer. - let err = session + // A frame rate of its own is no longer a refusal either: 25 fps joins a + // 30 fps timeline and is read at `Rate` against it -- see + // `tests/mixed_fps.rs` for what it then plays like. + session .import(&asset("test_25fps.mp4")) - .expect_err("25 fps must not join a 30 fps timeline") - .to_string(); - assert_eq!(err, "25.000 fps does not match the timeline's 30.000 fps"); + .expect("25 fps may join a 30 fps timeline"); + session + .remove_source(&asset("test_25fps.mp4"), 0) + .expect("...and the row it made comes back off"); // Same size and rate, no audio track: the timeline has one. let err = session diff --git a/scripts/gen_fixtures.sh b/scripts/gen_fixtures.sh index 1de0018..b121be0 100755 --- a/scripts/gen_fixtures.sh +++ b/scripts/gen_fixtures.sh @@ -161,15 +161,23 @@ enable='between(t,1,1.1)'[v];\ ffmpeg -y -f lavfi -i testsrc2=size=640x360:rate=30:duration=2 \ -an -c:v libx264 -profile:v baseline -pix_fmt yuv420p assets/test_mismatch.mp4 # Frame-rate fixture: test_av.mp4 in every respect a timeline is held to -- same -# codec, same profile, same 44.1k stereo AAC -- except that it runs at 25 fps. -# The only thing left for an import to refuse is the rate, which is what makes -# the refusal's wording testable. +# codec, same profile, same 44.1k stereo AAC -- except that it runs at 25 fps, +# so a timeline of 30 fps clips has one at another rate to read through `Rate`. ffmpeg -y -f lavfi -i testsrc2=size=1280x720:rate=25:duration=2 \ -f lavfi -i "sine=frequency=440:duration=2" \ -f lavfi -i "sine=frequency=880:duration=2" \ -filter_complex "[1:a][2:a]join=inputs=2:channel_layout=stereo,volume='0.5+0.5*sin(2*PI*t)':eval=frame[a]" \ -map 0:v -map "[a]" -c:v libx264 -profile:v baseline -pix_fmt yuv420p \ -c:a aac -b:a 128k assets/test_25fps.mp4 +# ...and the same again at 23.976 fps (24000/1001), the rate whose ratio to a +# 30 fps timeline does not terminate: what the frame mapping's rounding is +# actually tested against. +ffmpeg -y -f lavfi -i testsrc2=size=1280x720:rate=24000/1001:duration=2 \ + -f lavfi -i "sine=frequency=440:duration=2" \ + -f lavfi -i "sine=frequency=880:duration=2" \ + -filter_complex "[1:a][2:a]join=inputs=2:channel_layout=stereo,volume='0.5+0.5*sin(2*PI*t)':eval=frame[a]" \ + -map 0:v -map "[a]" -c:v libx264 -profile:v baseline -pix_fmt yuv420p \ + -c:a aac -b:a 128k assets/test_23976fps.mp4 # Standalone audio fixtures: the same 440/880 Hz tone with the 1 Hz pulse the # A/V fixture carries, at test_av.mp4's own 44.1k stereo -- so an imported song # can share a timeline with the video clips and the peaks tests can reuse the