forge
Explore
Log in

Don't you dare go Hollow

🔀 merge(T4): every video format carries sound meets the hw/sw indicator and mixed fps

Browse files at this commit

cf10a7cc78365659cbe785c8c8e83dcf328afb5cAhmet Kaan GümüşParent: 5ebd3ac9728053
Four seams, all kept whole:

- export.rs copy_audio — T4's routing (two lanes, a speeded lane, an equalizer,
  an uncopyable source all fall through to encode_audio) composed with T3's
  conformed-lane comment, which is now the reason a *rate* is NOT one of them:
  a conformed lane still copies, and `tests/mixed_fps.rs
  an_export_of_two_rates_runs_at_the_speed_it_was_shot` is what says so.
- export.rs labels — hw_seat/video_label take both AV1 containers (a container
  is not an encoder), audio_label gained MP3 and stopped calling AV1 soundless.
  It is now a *measurement*: copy_audio hands back an `ExportAudio` that says
  whether the packets were copied, so a progress line naming "AAC copy" is what
  really happened rather than what the edit predicted.
- main.rs — the FORMATS key column meets export_line's seat, and an audio-only
  format now CLEARS the cached video seat instead of showing the last picture
  format's: picking MP3 after AV1 read "SW encode (rav1e) · MP3 · SW
  (rusty_mp3)", which named an encoder that would not run. Same shape for WAV
  and FLAC, which had it before this branch.
- tests/backends.rs — the card==job pin now runs over all three picture formats
  and all three audio-only ones.

Green: engine --lib, --test export/av1/backends/mixed_fps/audio_export/eq_audio
(--test-threads=1), edith --bin, cargo check --workspace. No duplicate keys in
the merged engine manifest.

11 changed files +1665 -155

crates/app/src/main.rsmodified+243 -36
@@ -11,11 +11,12 @@ use std::time::{Duration, Instant};
11 11
12 use engine::audio::StreamInfo;12 use engine::audio::StreamInfo;
13 use engine::color::ColorParams;13 use engine::color::ColorParams;
14+use engine::decode::Backend;
14 use engine::eq::{Band, BandKind, EqParams};15 use engine::eq::{Band, BandKind, EqParams};
15 use engine::export::{ExportSettings, Format};16 use engine::export::{ExportSettings, Format};
16 use engine::project::{Edge, Lane, LaneKind, Source, Speed};17 use engine::project::{Edge, Lane, LaneKind, Source, Speed};
17 use engine::scale::FitPolicy;18 use engine::scale::FitPolicy;
18-use engine::{Clip, ExportHandle, Frame, PlaybackSession};19+use engine::{Clip, Codec, ExportHandle, Frame, PlaybackSession};
19 use gpui::{20 use gpui::{
20 AnyElement, App, Application, Bounds, ClickEvent, Context, CursorStyle, Div, FocusHandle,21 AnyElement, App, Application, Bounds, ClickEvent, Context, CursorStyle, Div, FocusHandle,
21 KeyDownEvent, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, PathBuilder, Pixels,22 KeyDownEvent, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, PathBuilder, Pixels,
@@ -637,6 +638,19 @@ struct Player {
637 /// `None` is a file with no picture to report (every source that is not an638 /// `None` is a file with no picture to report (every source that is not an
638 /// image, and one whose header would not read).639 /// image, and one whose header would not read).
639 sizes: HashMap<PathBuf, Option<(u32, u32)>>,640 sizes: HashMap<PathBuf, Option<(u32, u32)>>,
641+ /// Which decoder each source will run on, probed once at import and kept:
642+ /// the codec (`None` for a still) and the seat the engine picked for it.
643+ /// What a library row says *before* anything plays; the running answer is
644+ /// the session's own (`PlaybackSession::decode_backend`), which follows a
645+ /// fallback this cannot. Filled like `sizes`: presence means "asked", and
646+ /// `None` is a source with no decoder to name -- a song, or one the probe
647+ /// refused -- which must stay in the map or every repaint would ask again.
648+ decoders: HashMap<PathBuf, Option<(Option<Codec>, Backend)>>,
649+ /// Which encoder an export of the picked settings would open, and what it
650+ /// was asked about: the probe opens a real VA-API encoder (~100 ms), so it
651+ /// runs off the render thread and only while the export card is up. The
652+ /// inner `None` is "asked, not answered yet".
653+ export_seat: Option<(ExportSettings, (u32, u32), Option<&'static str>)>,
640 /// The copied clip. Frame ranges only, so it survives the clip it was taken654 /// The copied clip. Frame ranges only, so it survives the clip it was taken
641 /// from being deleted -- and it outlives the selection.655 /// from being deleted -- and it outlives the selection.
642 clipboard: Option<Clip>,656 clipboard: Option<Clip>,
@@ -1997,6 +2011,28 @@ impl Player {
1997 })2011 })
1998 .detach();2012 .detach();
1999 }2013 }
2014+ // Which decoder each file will run on, for the row that says so before
2015+ // a frame of it plays. Off the render thread like the streams above: a
2016+ // stream the plugin takes costs one VA-API init (~90 ms) to answer.
2017+ for path in unseen_paths(session.sources(), &self.decoders) {
2018+ self.decoders.insert(path.clone(), None);
2019+ let probed = cx.background_executor().spawn({
2020+ let path = path.clone();
2021+ // A song and a source no decoder here takes are both `None`:
2022+ // the row says nothing about them rather than guessing, and
2023+ // import refused the second at the door anyway.
2024+ async move { engine::decode::probe(&path).ok() }
2025+ });
2026+ cx.spawn(async move |this, cx| {
2027+ let probed = probed.await;
2028+ this.update(cx, |this, cx| {
2029+ this.decoders.insert(path, probed);
2030+ cx.notify();
2031+ })
2032+ .ok();
2033+ })
2034+ .detach();
2035+ }
2000 for key in unseen_sources(session.sources(), &self.waves) {2036 for key in unseen_sources(session.sources(), &self.waves) {
2001 self.waves.insert(key.clone(), Wave::Loading);2037 self.waves.insert(key.clone(), Wave::Loading);
2002 let decoded = cx.background_executor().spawn({2038 let decoded = cx.background_executor().spawn({
@@ -2029,6 +2065,59 @@ impl Player {
2029 }2065 }
2030 }2066 }
2031 2067
2068+ /// Probes the encoder an export would open, once per (settings,
2069+ /// resolution) and only while the export card is up -- it opens the very
2070+ /// VA-API encoder the export would, which is what makes the card's line a
2071+ /// measurement instead of a promise, and also what makes it too slow for
2072+ /// the render thread. Written before the spawn, like the probes above, so
2073+ /// the repaints during it start no second one.
2074+ fn cache_export_seat(&mut self, cx: &mut Context<Self>) {
2075+ let Some(session) = &self.session else {
2076+ return;
2077+ };
2078+ let settings = export_settings(self.quality, self.custom_mbps, self.format);
2079+ if !self.export_open {
2080+ return;
2081+ }
2082+ // A format with no picture has no seat to probe -- and the *last*
2083+ // format's is not its answer: cleared rather than left standing, or
2084+ // picking MP3 after AV1 would read "SW encode (rav1e) · MP3 · SW
2085+ // (rusty_mp3)", which names an encoder that will not run.
2086+ if !settings.format.has_video() {
2087+ self.export_seat = None;
2088+ return;
2089+ }
2090+ let meta = *session.meta();
2091+ let key = (settings, (meta.width, meta.height));
2092+ if self
2093+ .export_seat
2094+ .is_some_and(|(asked, size, _)| (asked, size) == key)
2095+ {
2096+ return;
2097+ }
2098+ self.export_seat = Some((key.0, key.1, None));
2099+ let probed = cx
2100+ .background_executor()
2101+ .spawn(async move { engine::export::planned_video(&meta, &settings) });
2102+ cx.spawn(async move |this, cx| {
2103+ let probed = probed.await;
2104+ this.update(cx, |this, cx| {
2105+ // Only if the card is still asking the same question: a format
2106+ // changed while the plugin opened has a probe of its own.
2107+ if let Some(seat) = this
2108+ .export_seat
2109+ .as_mut()
2110+ .filter(|(asked, size, _)| (*asked, *size) == key)
2111+ {
2112+ seat.2 = probed;
2113+ }
2114+ cx.notify();
2115+ })
2116+ .ok();
2117+ })
2118+ .detach();
2119+ }
2120+
2032 /// The group id of the clicked clip, which is what marks the other half.2121 /// The group id of the clicked clip, which is what marks the other half.
2033 fn selected_link(&self) -> Option<u32> {2122 fn selected_link(&self) -> Option<u32> {
2034 let (lane, idx) = self.selected?;2123 let (lane, idx) = self.selected?;
@@ -3055,6 +3144,7 @@ impl Render for Player {
3055 // has been through a repaint by the time its clips are drawn, so this3144 // has been through a repaint by the time its clips are drawn, so this
3056 // is the one place that has to notice a new one.3145 // is the one place that has to notice a new one.
3057 self.cache_media(cx);3146 self.cache_media(cx);
3147+ self.cache_export_seat(cx);
3058 // What the compositor calls this window. Pushed only when it changes:3148 // What the compositor calls this window. Pushed only when it changes:
3059 // it is a protocol round trip and this runs at vsync.3149 // it is a protocol round trip and this runs at vsync.
3060 let title = window_title(&self.name);3150 let title = window_title(&self.name);
@@ -3545,11 +3635,17 @@ impl Player {
3545 // Its own length, not one derived from what is on the lanes: a row3635 // Its own length, not one derived from what is on the lanes: a row
3546 // imported and never placed is a row with a length, and it is the3636 // imported and never placed is a row with a length, and it is the
3547 // length a drag would put down.3637 // length a drag would put down.
3548- let rows: Vec<_> = library_rows(sources, &self.streams, self.timeline_audio(), |path| {3638+ let rows: Vec<_> = library_rows(
3549- self.session3639+ sources,
3550- .as_ref()3640+ &self.streams,
3551- .map_or(0, |session| session.file_frames(path))3641+ &self.decoders,
3552- })3642+ self.timeline_audio(),
3643+ |path| {
3644+ self.session
3645+ .as_ref()
3646+ .map_or(0, |session| session.file_frames(path))
3647+ },
3648+ )
3553 .into_iter()3649 .into_iter()
3554 .enumerate()3650 .enumerate()
3555 .map(|(i, row)| {3651 .map(|(i, row)| {
@@ -3580,12 +3676,18 @@ impl Player {
3580 None => String::new(),3676 None => String::new(),
3581 }3677 }
3582 ),3678 ),
3679+ // The file's *own* frame rate, not the timeline's: a clip shot
3680+ // at another rate plays at the speed it was shot at, and the
3681+ // row that says where it came from has to say which rate that
3682+ // was.
3583 (None, Some(meta)) => format!(3683 (None, Some(meta)) => format!(
3584 "{} — {}x{} @ {:.2} fps · drag onto a lane, or Add at playhead",3684 "{} — {}x{} @ {:.2} fps · drag onto a lane, or Add at playhead",
3585 row.path.display(),3685 row.path.display(),
3586 meta.width,3686 meta.width,
3587 meta.height,3687 meta.height,
3588- meta.frame_rate3688+ self.session
3689+ .as_ref()
3690+ .map_or(meta.frame_rate, |session| session.file_fps(&row.path))
3589 ),3691 ),
3590 (None, None) => row.path.display().to_string(),3692 (None, None) => row.path.display().to_string(),
3591 };3693 };
@@ -3780,6 +3882,30 @@ impl Player {
3780 ))3882 ))
3781 }3883 }
3782 3884
3885+ /// What is decoding the picture right now, for the transport line: the
3886+ /// backend is the running worker's own (it is written where a hardware
3887+ /// session falls back to software, so this follows reality), and the codec
3888+ /// comes from the clip under the playhead. Empty when nothing is playing --
3889+ /// the question is about what is happening, not about what would.
3890+ fn live_decode(&self, position: f64, playing: bool) -> String {
3891+ let Some(session) = self.session.as_ref().filter(|_| playing) else {
3892+ return String::new();
3893+ };
3894+ let backend = session.decode_backend();
3895+ let codec = session
3896+ .video_clip_at(position)
3897+ .and_then(|(lane, idx)| session.lane_clips(lane).get(idx).map(|clip| clip.source))
3898+ .and_then(|source| session.sources().get(source))
3899+ .and_then(|source| self.decoders.get(&source.path).copied().flatten())
3900+ .and_then(|(codec, _)| codec);
3901+ match backend {
3902+ // Neither is a decode, and saying "SW" of them would be a lie.
3903+ Backend::Gap => "gap · nothing to decode".to_string(),
3904+ Backend::Still => "still · one decode, held".to_string(),
3905+ _ => format!("{} decode", decode_label(codec, backend)),
3906+ }
3907+ }
3908+
3783 /// Transport, edit and file buttons, timecode, playhead, clips lane.3909 /// Transport, edit and file buttons, timecode, playhead, clips lane.
3784 fn panel(3910 fn panel(
3785 &self,3911 &self,
@@ -3821,8 +3947,16 @@ impl Player {
3821 let progress = export.progress();3947 let progress = export.progress();
3822 (3948 (
3823 format!(3949 format!(
3824- "EXPORTING {}% — {} cancels",3950+ "EXPORTING {}% · {} · {} — {} cancels",
3825 (progress * 100.) as u32,3951 (progress * 100.) as u32,
3952+ // The row that was picked; the engine's line below names the
3953+ // seats alone, since the library is what identifies a codec.
3954+ format_label(self.format),
3955+ // What the worker actually opened, so a fallback to the
3956+ // software encoder shows here rather than being invisible.
3957+ export
3958+ .encoders()
3959+ .unwrap_or_else(|| "opening the encoder".to_string()),
3826 key(ActionId::CancelExport)3960 key(ActionId::CancelExport)
3827 ),3961 ),
3828 progress,3962 progress,
@@ -3832,12 +3966,19 @@ impl Player {
3832 // tooltips. Keys first: at a 640 px window the tail is what a3966 // tooltips. Keys first: at a 640 px window the tail is what a
3833 // truncation eats, and the two hints at the end are also on the3967 // truncation eats, and the two hints at the end are also on the
3834 // ruler's and Import's tooltips.3968 // ruler's and Import's tooltips.
3969+ // While it plays, what is decoding it goes first: it is the
3970+ // answer that changes as the playhead crosses a cut, and the tail
3971+ // of this line is what a narrow window truncates.
3835 (3972 (
3836- format!(3973+ join_detail(
3837- "{} copy · {} paste · {} undo · click the bar to seek · drop a file to import",3974+ &self.live_decode(position, playing),
3838- key(ActionId::Copy),3975+ &format!(
3839- key(ActionId::Paste),3976+ "{} copy · {} paste · {} undo · click the bar to seek · drop a file to \
3840- key(ActionId::Undo)3977+ import",
3978+ key(ActionId::Copy),
3979+ key(ActionId::Paste),
3980+ key(ActionId::Undo)
3981+ ),
3841 ),3982 ),
3842 filled,3983 filled,
3843 )3984 )
@@ -4608,7 +4749,11 @@ impl Player {
4608 .px(px(6.))4749 .px(px(6.))
4609 .text_size(px(11.))4750 .text_size(px(11.))
4610 .text_color(rgb(INK_DIM))4751 .text_color(rgb(INK_DIM))
4611- .child(export_line(self.format, self.session.as_ref())),4752+ .child(export_line(
4753+ self.format,
4754+ self.session.as_ref(),
4755+ self.export_seat.and_then(|(.., seat)| seat),
4756+ )),
4612 )4757 )
4613 .child(4758 .child(
4614 div()4759 div()
@@ -6457,6 +6602,7 @@ struct Row {
6457 fn library_rows(6602 fn library_rows(
6458 sources: &[Source],6603 sources: &[Source],
6459 streams: &HashMap<PathBuf, Vec<StreamInfo>>,6604 streams: &HashMap<PathBuf, Vec<StreamInfo>>,
6605+ decoders: &HashMap<PathBuf, Option<(Option<Codec>, Backend)>>,
6460 timeline_audio: Option<(u32, u16)>,6606 timeline_audio: Option<(u32, u16)>,
6461 frames: impl Fn(&Path) -> u32,6607 frames: impl Fn(&Path) -> u32,
6462 ) -> Vec<Row> {6608 ) -> Vec<Row> {
@@ -6472,12 +6618,22 @@ fn library_rows(
6472 path: source.path.clone(),6618 path: source.path.clone(),
6473 stream: source.audio_stream,6619 stream: source.audio_stream,
6474 name: row_name(&source.path, source.audio_stream, of_file.len() > 1),6620 name: row_name(&source.path, source.audio_stream, of_file.len() > 1),
6475- // Only where there is a choice to describe: a file with one audio6621+ // The decoder first: it is the same for every row of a file and
6476- // track is the row it has always been, name and length, and the6622+ // it is what a person opening the panel is asking about. The
6477- // length is what would be squeezed out at the panel's least width.6623+ // stream half only where there is a choice to describe -- a file
6478- detail: info6624+ // with one audio track is the row it has always been, name and
6479- .filter(|_| of_file.len() > 1)6625+ // length, and the length is what would be squeezed out at the
6480- .map_or_else(String::new, stream_detail),6626+ // panel's least width.
6627+ detail: join_detail(
6628+ &decoders
6629+ .get(&source.path)
6630+ .copied()
6631+ .flatten()
6632+ .map_or_else(String::new, |(codec, backend)| decode_label(codec, backend)),
6633+ &info
6634+ .filter(|_| of_file.len() > 1)
6635+ .map_or_else(String::new, stream_detail),
6636+ ),
6481 // A stream already on the timeline is playing: whatever a probe6637 // A stream already on the timeline is playing: whatever a probe
6482 // would say about it now, it is usable by demonstration.6638 // would say about it now, it is usable by demonstration.
6483 unusable: None,6639 unusable: None,
@@ -6514,9 +6670,20 @@ fn library_rows(
6514 /// why it cannot be used, with the separator only where both halves exist (a6670 /// why it cannot be used, with the separator only where both halves exist (a
6515 /// single-stream file says nothing about its stream).6671 /// single-stream file says nothing about its stream).
6516 fn join_detail(detail: &str, tail: &str) -> String {6672 fn join_detail(detail: &str, tail: &str) -> String {
6517- match detail.is_empty() {6673+ match (detail.is_empty(), tail.is_empty()) {
6518- true => tail.to_string(),6674+ (true, _) => tail.to_string(),
6519- false => format!("{detail} · {tail}"),6675+ (false, true) => detail.to_string(),
6676+ (false, false) => format!("{detail} · {tail}"),
6677+ }
6678+}
6679+
6680+/// How a source's decoder reads: the codec and which seat has it, or the seat
6681+/// alone for a still, which has no coded stream to name. The one place either
6682+/// answer is spelled, so a row, a transport line and a card cannot disagree.
6683+fn decode_label(codec: Option<Codec>, backend: Backend) -> String {
6684+ match codec {
6685+ Some(codec) => format!("{} · {}", codec.name(), backend.label()),
6686+ None => backend.label().to_string(),
6520 }6687 }
6521 }6688 }
6522 6689
@@ -6853,14 +7020,32 @@ fn next_resolution(current: (u32, u32), native: (u32, u32)) -> (u32, u32) {
6853 /// [`format_line`] plus the project's resolution, which is what a video export7020 /// [`format_line`] plus the project's resolution, which is what a video export
6854 /// is written at however many sizes the media on the timeline are. Only for the7021 /// is written at however many sizes the media on the timeline are. Only for the
6855 /// formats that carry a picture -- a WAV has no resolution to state.7022 /// formats that carry a picture -- a WAV has no resolution to state.
6856-fn export_line(format: Format, session: Option<&PlaybackSession>) -> String {7023+fn export_line(
7024+ format: Format,
7025+ session: Option<&PlaybackSession>,
7026+ seat: Option<&'static str>,
7027+) -> String {
6857 let line = format_line(format);7028 let line = format_line(format);
7029+ // What it will really be encoded by, on the same line: the picture's seat
7030+ // as the probe found it (`…` until it lands, never a guess) and the sound's,
7031+ // which is decided without opening anything. Both are what a running export
7032+ // then names on its progress line, from the same two functions.
7033+ let encoders = match session {
7034+ Some(session) => join_detail(
7035+ seat.unwrap_or(match format.has_video() {
7036+ true => "encoder …",
7037+ false => "",
7038+ }),
7039+ session.planned_audio(format),
7040+ ),
7041+ None => String::new(),
7042+ };
6858 match session.filter(|_| format.has_video()) {7043 match session.filter(|_| format.has_video()) {
6859 Some(session) => {7044 Some(session) => {
6860 let (w, h) = session.resolution();7045 let (w, h) = session.resolution();
6861- format!("{line} · project {w}x{h}")7046+ format!("{line} · project {w}x{h} · {encoders}")
6862 }7047 }
6863- None => line.to_string(),7048+ None => join_detail(line, &encoders),
6864 }7049 }
6865 }7050 }
6866 7051
@@ -7913,9 +8098,13 @@ mod tests {
7913 );8098 );
7914 // The rows the panel draws: one per source, each its file's own length8099 // The rows the panel draws: one per source, each its file's own length
7915 // -- source 1 has no clip anywhere and is still 4 s at 30 fps.8100 // -- source 1 has no clip anywhere and is still 4 s at 30 fps.
7916- let rows = library_rows(session.sources(), &HashMap::new(), None, |path| {8101+ let rows = library_rows(
7917- session.file_frames(path)8102+ session.sources(),
7918- });8103+ &HashMap::new(),
8104+ &HashMap::new(),
8105+ None,
8106+ |path| session.file_frames(path),
8107+ );
7919 assert_eq!(rows.len(), 2);8108 assert_eq!(rows.len(), 2);
7920 assert_eq!(rows[0].frames, 150, "5 s at 30 fps");8109 assert_eq!(rows[0].frames, 150, "5 s at 30 fps");
7921 assert_eq!(rows[1].frames, 120, "4 s at 30 fps, never placed");8110 assert_eq!(rows[1].frames, 120, "4 s at 30 fps, never placed");
@@ -7954,7 +8143,9 @@ mod tests {
7954 .find(|s| s.index == session.sources()[0].audio_stream)8143 .find(|s| s.index == session.sources()[0].audio_stream)
7955 .map(|s| (s.sample_rate, s.channels));8144 .map(|s| (s.sample_rate, s.channels));
7956 let frames = session.file_frames(&path);8145 let frames = session.file_frames(&path);
7957- let rows = library_rows(session.sources(), &streams, rate, |_| frames);8146+ let rows = library_rows(session.sources(), &streams, &HashMap::new(), rate, |_| {
8147+ frames
8148+ });
7958 assert_eq!(rows.len(), 1);8149 assert_eq!(rows.len(), 1);
7959 assert_eq!(rows[0].name, "test_tone.mp3");8150 assert_eq!(rows[0].name, "test_tone.mp3");
7960 assert_eq!(rows[0].unusable, None, "the row is placeable");8151 assert_eq!(rows[0].unusable, None, "the row is placeable");
@@ -8026,7 +8217,13 @@ mod tests {
8026 info(3, 0, 0, None, false),8217 info(3, 0, 0, None, false),
8027 ],8218 ],
8028 );8219 );
8029- let rows = library_rows(&sources, &streams, Some((44_100, 2)), |_| 90);8220+ let rows = library_rows(
8221+ &sources,
8222+ &streams,
8223+ &HashMap::new(),
8224+ Some((44_100, 2)),
8225+ |_| 90,
8226+ );
8030 assert_eq!(8227 assert_eq!(
8031 rows.iter().map(|r| r.stream).collect::<Vec<_>>(),8228 rows.iter().map(|r| r.stream).collect::<Vec<_>>(),
8032 [0, 1, 2, 3],8229 [0, 1, 2, 3],
@@ -8064,7 +8261,7 @@ mod tests {
8064 PathBuf::from("/m/plain.mp4"),8261 PathBuf::from("/m/plain.mp4"),
8065 vec![info(0, 44_100, 2, None, true)],8262 vec![info(0, 44_100, 2, None, true)],
8066 );8263 );
8067- let rows = library_rows(&plain, &one, Some((44_100, 2)), |_| 90);8264+ let rows = library_rows(&plain, &one, &HashMap::new(), Some((44_100, 2)), |_| 90);
8068 assert_eq!(rows.len(), 1);8265 assert_eq!(rows.len(), 1);
8069 assert_eq!(rows[0].name, "plain.mp4");8266 assert_eq!(rows[0].name, "plain.mp4");
8070 assert_eq!(8267 assert_eq!(
@@ -8075,7 +8272,7 @@ mod tests {
8075 let mut silent = HashMap::new();8272 let mut silent = HashMap::new();
8076 silent.insert(PathBuf::from("/m/plain.mp4"), Vec::new());8273 silent.insert(PathBuf::from("/m/plain.mp4"), Vec::new());
8077 for probe in [silent, HashMap::new()] {8274 for probe in [silent, HashMap::new()] {
8078- let rows = library_rows(&plain, &probe, None, |_| 90);8275+ let rows = library_rows(&plain, &probe, &HashMap::new(), None, |_| 90);
8079 assert_eq!(rows.len(), 1);8276 assert_eq!(rows.len(), 1);
8080 assert_eq!(rows[0].name, "plain.mp4");8277 assert_eq!(rows[0].name, "plain.mp4");
8081 assert_eq!(rows[0].detail, "");8278 assert_eq!(rows[0].detail, "");
@@ -8093,7 +8290,13 @@ mod tests {
8093 PathBuf::from("/m/other.mp4"),8290 PathBuf::from("/m/other.mp4"),
8094 vec![info(0, 44_100, 2, None, true)],8291 vec![info(0, 44_100, 2, None, true)],
8095 );8292 );
8096- let rows = library_rows(&placed, &streams, Some((44_100, 2)), |_| 90);8293+ let rows = library_rows(
8294+ &placed,
8295+ &streams,
8296+ &HashMap::new(),
8297+ Some((44_100, 2)),
8298+ |_| 90,
8299+ );
8097 assert_eq!(8300 assert_eq!(
8098 rows.iter()8301 rows.iter()
8099 .map(|r| (file_name(&r.path), r.stream))8302 .map(|r| (file_name(&r.path), r.stream))
@@ -8496,7 +8699,7 @@ mod tests {
8496 );8699 );
8497 let streams = HashMap::new();8700 let streams = HashMap::new();
8498 let rows = |session: &PlaybackSession| {8701 let rows = |session: &PlaybackSession| {
8499- library_rows(session.sources(), &streams, None, |_| 0).len()8702+ library_rows(session.sources(), &streams, &HashMap::new(), None, |_| 0).len()
8500 };8703 };
8501 assert_eq!(rows(&session), 2, "a row per source");8704 assert_eq!(rows(&session), 2, "a row per source");
8502 8705
@@ -9813,7 +10016,9 @@ mod tests {
9813 // a title and a status line.10016 // a title and a status line.
9814 let title = 17.;10017 let title = 17.;
9815 let status = 28.;10018 let status = 28.;
9816- let fixed = 17.;10019+ // Two lines of 11 px: the format line carries the encoders an export
10020+ // would open, which is what takes it past one at this width.
10021+ let fixed = 30.;
9817 let gaps = 4. * 2.;10022 let gaps = 4. * 2.;
9818 let padding = 24.;10023 let padding = 24.;
9819 assert!(10024 assert!(
@@ -10379,6 +10584,8 @@ fn main() {
10379 waves: HashMap::new(),10584 waves: HashMap::new(),
10380 streams: HashMap::new(),10585 streams: HashMap::new(),
10381 sizes: HashMap::new(),10586 sizes: HashMap::new(),
10587+ decoders: HashMap::new(),
10588+ export_seat: None,
10382 clipboard: None,10589 clipboard: None,
10383 scrubbing: false,10590 scrubbing: false,
10384 trim: None,10591 trim: None,
crates/engine/src/decode.rsmodified+116 -1
@@ -3,7 +3,7 @@
3 3
4 use std::path::{Path, PathBuf};4 use std::path::{Path, PathBuf};
5 use std::sync::Arc;5 use std::sync::Arc;
6-use std::sync::atomic::{AtomicBool, Ordering};6+use std::sync::atomic::{AtomicBool, AtomicU8, Ordering};
7 use std::sync::mpsc::{Receiver, SyncSender, sync_channel};7 use std::sync::mpsc::{Receiver, SyncSender, sync_channel};
8 use std::thread;8 use std::thread;
9 9
@@ -25,6 +25,106 @@ pub struct Frame {
25 pub bgra: Vec<u8>,25 pub bgra: Vec<u8>,
26 }26 }
27 27
28+/// Which decoder a source is really running on. Read-only introspection: it
29+/// decides nothing, it *reports* what [`DecodeSession::open_worker`] chose --
30+/// a hardware session that opened and then failed before its first picture
31+/// falls back to software and this says so, because it is written where the
32+/// fallback happens rather than where it was hoped for.
33+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
34+pub enum Backend {
35+ /// The worker has not reached its decoder yet: the plugin's VA-API init is
36+ /// ~90 ms, and this is what a caller reads in that window.
37+ #[default]
38+ Opening,
39+ /// The VA-API plugin (`libengine_hw.so`).
40+ Hardware,
41+ /// `rusty_h264`, in this process.
42+ Software,
43+ /// A still image: one `image` decode, no stream and no decoder to pick.
44+ Still,
45+ /// A gap: black frames, nothing decoded at all.
46+ Gap,
47+}
48+
49+impl Backend {
50+ /// Short enough for a library row and a transport line.
51+ pub fn label(self) -> &'static str {
52+ match self {
53+ Self::Opening => "opening",
54+ Self::Hardware => "HW",
55+ Self::Software => "SW",
56+ Self::Still => "still",
57+ Self::Gap => "gap",
58+ }
59+ }
60+
61+ fn code(self) -> u8 {
62+ match self {
63+ Self::Opening => 0,
64+ Self::Hardware => 1,
65+ Self::Software => 2,
66+ Self::Still => 3,
67+ Self::Gap => 4,
68+ }
69+ }
70+
71+ fn from_code(code: u8) -> Self {
72+ match code {
73+ 1 => Self::Hardware,
74+ 2 => Self::Software,
75+ 3 => Self::Still,
76+ 4 => Self::Gap,
77+ _ => Self::Opening,
78+ }
79+ }
80+}
81+
82+/// Where a worker publishes the decoder it opened, for whoever holds the other
83+/// end of its channel. One atomic byte, written once at open (and once more if
84+/// hardware hands the range back to software), read whenever a caller repaints
85+/// -- never per frame on either side.
86+#[derive(Clone, Default)]
87+pub struct BackendCell(Arc<AtomicU8>);
88+
89+impl BackendCell {
90+ fn new(backend: Backend) -> Self {
91+ Self(Arc::new(AtomicU8::new(backend.code())))
92+ }
93+
94+ fn set(&self, backend: Backend) {
95+ self.0.store(backend.code(), Ordering::Relaxed);
96+ }
97+
98+ pub fn get(&self) -> Backend {
99+ Backend::from_code(self.0.load(Ordering::Relaxed))
100+ }
101+}
102+
103+/// Which decoder `path` would open, decided exactly as [`DecodeSession::open_worker`]
104+/// decides it: the same `VE_SW` pin and the same plugin probe against this very
105+/// file. What lets a front-end name the decoder *before* anything plays.
106+///
107+/// The codec is `None` for a still image, which has no coded stream. A stream
108+/// no decoder here can take is an `Err` naming the plugin, exactly as opening
109+/// it would be -- the same refusal, one VA-API init earlier.
110+///
111+/// Costs that one init (~90 ms) for a stream the plugin takes: ask it once per
112+/// file, off a render thread, and keep the answer.
113+pub fn probe(path: &Path) -> crate::Result<(Option<Codec>, Backend)> {
114+ if crate::is_image(path) {
115+ return Ok((None, Backend::Still));
116+ }
117+ let path = path.to_path_buf();
118+ let (meta, _demuxer) = Demuxer::open(&path)?;
119+ if open_hw(&path, 0).is_some() {
120+ return Ok((Some(meta.codec), Backend::Hardware));
121+ }
122+ if meta.codec != Codec::H264 {
123+ return Err(meta.codec.needs_plugin().into());
124+ }
125+ Ok((Some(meta.codec), Backend::Software))
126+}
127+
28 /// A running decode worker: the flag that stops it, and the handle to wait on.128 /// A running decode worker: the flag that stops it, and the handle to wait on.
29 ///129 ///
30 /// Dropping one cancels *and joins*. A worker abandoned mid-`vaInitialize`130 /// Dropping one cancels *and joins*. A worker abandoned mid-`vaInitialize`
@@ -85,6 +185,9 @@ impl Drop for Worker {
85 pub(crate) struct FrameStream {185 pub(crate) struct FrameStream {
86 pub(crate) frames: Receiver<Frame>,186 pub(crate) frames: Receiver<Frame>,
87 pub(crate) worker: Worker,187 pub(crate) worker: Worker,
188+ /// What this stream's pictures are being decoded by. Dropped last and read
189+ /// by the caller, so it outlives nothing and blocks nothing.
190+ pub(crate) backend: BackendCell,
88 }191 }
89 192
90 pub struct DecodeSession;193 pub struct DecodeSession;
@@ -152,6 +255,7 @@ impl DecodeSession {
152 cancel,255 cancel,
153 handle: None,256 handle: None,
154 },257 },
258+ backend: BackendCell::new(Backend::Gap),
155 };259 };
156 }260 }
157 let worker_cancel = Arc::clone(&cancel);261 let worker_cancel = Arc::clone(&cancel);
@@ -180,6 +284,7 @@ impl DecodeSession {
180 FrameStream {284 FrameStream {
181 frames: rx,285 frames: rx,
182 worker: Worker { cancel, handle },286 worker: Worker { cancel, handle },
287+ backend: BackendCell::new(Backend::Gap),
183 }288 }
184 }289 }
185 290
@@ -209,6 +314,7 @@ impl DecodeSession {
209 cancel,314 cancel,
210 handle: None,315 handle: None,
211 },316 },
317+ backend: BackendCell::new(Backend::Still),
212 });318 });
213 }319 }
214 // The one conversion, on this thread: it is a few milliseconds and the320 // The one conversion, on this thread: it is a few milliseconds and the
@@ -245,6 +351,7 @@ impl DecodeSession {
245 Ok(FrameStream {351 Ok(FrameStream {
246 frames: rx,352 frames: rx,
247 worker: Worker { cancel, handle },353 worker: Worker { cancel, handle },
354+ backend: BackendCell::new(Backend::Still),
248 })355 })
249 }356 }
250 357
@@ -285,6 +392,9 @@ impl DecodeSession {
285 // decoder run ahead of the display without limit.392 // decoder run ahead of the display without limit.
286 let (tx, rx) = sync_channel(2);393 let (tx, rx) = sync_channel(2);
287 let cancel = Arc::new(AtomicBool::new(false));394 let cancel = Arc::new(AtomicBool::new(false));
395+ // Written by the worker below the moment it knows, so a caller reading
396+ // it sees what opened rather than what was hoped for.
397+ let backend = BackendCell::default();
288 if end_frame <= start_frame {398 if end_frame <= start_frame {
289 // Nothing to decode: dropping `tx` here closes the channel cleanly,399 // Nothing to decode: dropping `tx` here closes the channel cleanly,
290 // so the caller sees an immediate end of stream rather than an error.400 // so the caller sees an immediate end of stream rather than an error.
@@ -296,10 +406,12 @@ impl DecodeSession {
296 cancel,406 cancel,
297 handle: None,407 handle: None,
298 },408 },
409+ backend,
299 },410 },
300 ));411 ));
301 }412 }
302 let worker_cancel = Arc::clone(&cancel);413 let worker_cancel = Arc::clone(&cancel);
414+ let worker_backend = backend.clone();
303 let handle = thread::Builder::new()415 let handle = thread::Builder::new()
304 .name("decode".into())416 .name("decode".into())
305 .spawn(move || {417 .spawn(move || {
@@ -320,6 +432,7 @@ impl DecodeSession {
320 return;432 return;
321 }433 }
322 eprintln!("decode backend: hardware (VA-API plugin)");434 eprintln!("decode backend: hardware (VA-API plugin)");
435+ worker_backend.set(Backend::Hardware);
323 if run_hw(hw, &tx, start_frame, end_frame, &mut render, &worker_cancel) {436 if run_hw(hw, &tx, start_frame, end_frame, &mut render, &worker_cancel) {
324 return;437 return;
325 }438 }
@@ -334,6 +447,7 @@ impl DecodeSession {
334 return;447 return;
335 }448 }
336 eprintln!("decode backend: software (rusty_h264)");449 eprintln!("decode backend: software (rusty_h264)");
450+ worker_backend.set(Backend::Software);
337 run(451 run(
338 demuxer,452 demuxer,
339 tx,453 tx,
@@ -351,6 +465,7 @@ impl DecodeSession {
351 cancel,465 cancel,
352 handle: Some(handle),466 handle: Some(handle),
353 },467 },
468+ backend,
354 },469 },
355 ))470 ))
356 }471 }
crates/engine/src/export.rsmodified+277 -49
@@ -23,10 +23,14 @@
23 //! picture is re-encoded, so the frame walk honours a rate: it takes the source23 //! picture is re-encoded, so the frame walk honours a rate: it takes the source
24 //! frame each timeline frame shows ([`crate::project::Speed::source_at`], the24 //! frame each timeline frame shows ([`crate::project::Speed::source_at`], the
25 //! very frame preview holds there) and encodes a held one again rather than25 //! very frame preview holds there) and encodes a held one again rather than
26-//! decoding it twice. The sound is *copied* unless something forces a decode,26+//! decoding it twice. A clip whose *file* was shot at another rate than the
27-//! and a packet carries no rate — so a speeded lane is one of the things that27+//! timeline goes through the same walk with one more conversion on the end
28-//! forces one ([`copy_audio`]) rather than being written out at 1.00x under a28+//! ([`crate::project::Rate`]), so it is encoded at the speed it was shot at.
29-//! re-timed picture.29+//! The sound is *copied* unless something forces a decode, and a packet carries
30+//! no rate — so a speeded lane is one of the things that forces one
31+//! ([`copy_audio`]) rather than being written out at 1.00x under a re-timed
32+//! picture. WAV, FLAC and MP3 are decoded and resampled, so they honour a rate
33+//! like the picture does.
30 //!34 //!
31 //! Nothing partial survives a failure: the worker writes to `<out>.part` and35 //! Nothing partial survives a failure: the worker writes to `<out>.part` and
32 //! renames it onto `out` only once the file is closed and complete, so the36 //! renames it onto `out` only once the file is closed and complete, so the
@@ -52,7 +56,7 @@ use crate::audio::{AudioMeta, AudioSession};
52 use crate::demux::{Demuxer, VideoMeta};56 use crate::demux::{Demuxer, VideoMeta};
53 use crate::hw::{HwEncoder, HwSession};57 use crate::hw::{HwEncoder, HwSession};
54 use crate::mux::{AudioParams, Av1Params, MkvMuxer, Mp4Muxer, VideoParams};58 use crate::mux::{AudioParams, Av1Params, MkvMuxer, Mp4Muxer, VideoParams};
55-use crate::project::{LaneKind, Project};59+use crate::project::{LaneKind, Project, Rate};
56 use crate::scale::Composer;60 use crate::scale::Composer;
57 61
58 /// Progress is reported in permille: an atomic integer the render loop can read62 /// Progress is reported in permille: an atomic integer the render loop can read
@@ -167,6 +171,10 @@ struct Shared {
167 cancel: AtomicBool,171 cancel: AtomicBool,
168 finished: AtomicBool,172 finished: AtomicBool,
169 outcome: Mutex<Option<crate::Result<()>>>,173 outcome: Mutex<Option<crate::Result<()>>>,
174+ /// The encoders this job really opened, published the moment they are
175+ /// chosen and never changed after -- one seat for the whole file, which is
176+ /// what [`Enc`] states. `None` until then.
177+ encoders: Mutex<Option<String>>,
170 }178 }
171 179
172 /// A running export. Poll [`is_finished`](ExportHandle::is_finished) once per180 /// A running export. Poll [`is_finished`](ExportHandle::is_finished) once per
@@ -195,6 +203,13 @@ impl ExportHandle {
195 self.shared.finished.load(Ordering::Acquire)203 self.shared.finished.load(Ordering::Acquire)
196 }204 }
197 205
206+ /// What this export is encoding with -- the video seat and what the sound
207+ /// is doing -- as the worker chose them, hardware fallback included.
208+ /// `None` for the first instants of a job, before the encoder is open.
209+ pub fn encoders(&self) -> Option<String> {
210+ self.shared.encoders.lock().unwrap().clone()
211+ }
212+
198 /// The outcome, once — taken out of the handle, so a caller that already213 /// The outcome, once — taken out of the handle, so a caller that already
199 /// reported it sees `None` afterwards. `None` while the export is running.214 /// reported it sees `None` afterwards. `None` while the export is running.
200 pub fn result(&self) -> Option<crate::Result<()>> {215 pub fn result(&self) -> Option<crate::Result<()>> {
@@ -218,6 +233,7 @@ pub fn start(
218 cancel: AtomicBool::new(false),233 cancel: AtomicBool::new(false),
219 finished: AtomicBool::new(false),234 finished: AtomicBool::new(false),
220 outcome: Mutex::new(None),235 outcome: Mutex::new(None),
236+ encoders: Mutex::new(None),
221 });237 });
222 let worker = Arc::clone(&shared);238 let worker = Arc::clone(&shared);
223 let out = out.to_path_buf();239 let out = out.to_path_buf();
@@ -282,12 +298,154 @@ fn has_picture(project: &Project) -> bool {
282 .any(|lane| lane.kind == LaneKind::Video && !project.lane(lane).is_empty())298 .any(|lane| lane.kind == LaneKind::Video && !project.lane(lane).is_empty())
283 }299 }
284 300
301+/// Whether any audio lane holds anything, [`has_picture`]'s pair: what tells a
302+/// timeline whose export will carry sound from one whose file has none.
303+fn has_sound(project: &Project) -> bool {
304+ project
305+ .lanes()
306+ .into_iter()
307+ .any(|lane| lane.kind == LaneKind::Audio && !project.lane(lane).is_empty())
308+}
309+
310+/// Whether any equalizer on the sound is doing something -- the one edit a
311+/// packet copy cannot carry, so an mp4 whose lane has one is decoded and
312+/// re-encoded ([`encode_audio`]) instead of copied. Asked of every audio lane:
313+/// the copy path has exactly one by the time it asks, and [`planned_audio`] is
314+/// asked before that is settled.
315+fn equalized(project: &Project) -> bool {
316+ project.audio_lanes().into_iter().any(|lane| {
317+ (0..project.lane(lane).len())
318+ .any(|idx| project.eq_of(lane, idx).is_some_and(|eq| !eq.is_identity()))
319+ })
320+}
321+
322+/// The bitrate an export codes at: the caller's number through the same clamp
323+/// as the computed one, for the reason [`Enc::open`] states.
324+fn bitrate_of(meta: &VideoMeta, settings: &ExportSettings) -> u64 {
325+ settings
326+ .bitrate
327+ .map_or_else(|| bitrate_for(meta), |b| b.clamp(MIN_BITRATE, MAX_BITRATE))
328+}
329+
330+/// The hardware seat for these settings, opened exactly as the export opens it
331+/// -- the same pins, the same AV1 opt-in, the same dimensions a driver may
332+/// refuse -- or `None` where the software encoder takes the file. The single
333+/// place that choice is made, which is what lets [`planned_video`] *measure* it
334+/// instead of promising it.
335+fn hw_seat(meta: &VideoMeta, settings: &ExportSettings) -> Option<HwEncoder> {
336+ if settings.force_sw || forced("VE_SW_ENC") {
337+ return None;
338+ }
339+ let (fps_num, fps_den) = crate::mux::frame_timing(meta.frame_rate).ok()?;
340+ let bitrate = bitrate_of(meta, settings);
341+ match settings.format {
342+ // Opt-in only, for the reason [`Enc::open_av1`] states in full. Both
343+ // AV1 formats sit on it: the container is not the encoder's business.
344+ format if format.is_av1() && !forced("VE_HW_AV1") => None,
345+ format if format.is_av1() => {
346+ HwEncoder::open_av1(meta.width, meta.height, fps_num, fps_den, bitrate)
347+ }
348+ _ => HwEncoder::open(meta.width, meta.height, fps_num, fps_den, bitrate),
349+ }
350+}
351+
352+/// How a front-end names a video seat: which of the two encoders has the file,
353+/// and which library that is. Not the codec -- a caller shows this beside the
354+/// format it picked, and `rav1e` names AV1 as `rusty_h264` names H.264. One
355+/// place, so what a card says before an export and what its progress line says
356+/// during one cannot drift apart.
357+fn video_label(format: Format, hw: bool) -> &'static str {
358+ match (format.is_av1(), hw) {
359+ (_, true) => "HW encode (VA-API)",
360+ (true, false) => "SW encode (rav1e)",
361+ (false, false) => "SW encode (rusty_h264)",
362+ }
363+}
364+
365+/// The cheap half of "does this timeline's sound have to be re-encoded": what
366+/// the *edit* says, with no file opened. Two lanes are a mix and a mix is not a
367+/// copy; a speeded lane is resampled; an equalizer is sample math. The other
368+/// half -- whether the sources can be copied out of at all -- costs a file open
369+/// each and belongs to [`copy_audio`], which may re-encode where this says copy.
370+fn forces_encode(project: &Project) -> bool {
371+ let lanes: Vec<_> = project
372+ .audio_lanes()
373+ .into_iter()
374+ .filter(|&lane| !project.lane(lane).is_empty())
375+ .collect();
376+ lanes.len() > 1
377+ || lanes
378+ .iter()
379+ .any(|&lane| project.lane(lane).iter().any(|c| !c.speed.is_normal()))
380+ || equalized(project)
381+}
382+
383+/// What the sound is written by. Every audio encoder here is software -- there
384+/// is no hardware AAC, PCM, FLAC or MP3 seat -- so this names *which* one, and
385+/// whether a container escapes encoding altogether by copying the packets it was
386+/// given. Both AV1 formats are in it like the mp4: an AV1 export carries the
387+/// timeline's sound too, so leaving it unnamed would be the old lie.
388+///
389+/// A prediction, and it says so: `copied` is what [`copy_audio`] *did*, which a
390+/// card asking before the export has no way to know (a source that cannot be
391+/// copied out of is only found by opening it). `None` predicts from the edit
392+/// alone.
393+fn audio_label(
394+ project: &Project,
395+ format: Format,
396+ sound: bool,
397+ copied: Option<bool>,
398+) -> &'static str {
399+ if !sound {
400+ return "no sound to write";
401+ }
402+ match format {
403+ Format::Wav => "PCM · SW (hound)",
404+ Format::Flac => "FLAC · SW (flacenc)",
405+ Format::Mp3 => "MP3 · SW (rusty_mp3)",
406+ _ => match copied.unwrap_or(!forces_encode(project)) {
407+ true => "AAC copy",
408+ false => "AAC · SW encode (rusty_aac)",
409+ },
410+ }
411+}
412+
413+/// What [`start`] would write this timeline's sound with, before one is
414+/// started. Pure: no probe and no file opened, so a card may ask it per repaint.
415+pub fn planned_audio(project: &Project, format: Format) -> &'static str {
416+ audio_label(project, format, has_sound(project), None)
417+}
418+
419+/// What [`start`] would encode the picture with, probed the way the export
420+/// probes it -- the very encoder is opened and closed again -- so this is a
421+/// measurement and not a promise. `None` for a format that carries no picture.
422+///
423+/// Costs that open (~100 ms here): ask it off a render thread and keep the
424+/// answer until the format, the resolution or the bitrate changes.
425+pub fn planned_video(meta: &VideoMeta, settings: &ExportSettings) -> Option<&'static str> {
426+ settings
427+ .format
428+ .has_video()
429+ .then(|| video_label(settings.format, hw_seat(meta, settings).is_some()))
430+}
431+
285 fn settle(shared: &Shared, result: crate::Result<()>) {432 fn settle(shared: &Shared, result: crate::Result<()>) {
286 *shared.outcome.lock().unwrap() = Some(result);433 *shared.outcome.lock().unwrap() = Some(result);
287 // Published last: a caller that sees the flag is guaranteed the outcome.434 // Published last: a caller that sees the flag is guaranteed the outcome.
288 shared.finished.store(true, Ordering::Release);435 shared.finished.store(true, Ordering::Release);
289 }436 }
290 437
438+/// The audio track an export writes, and how it was made -- a copy is the
439+/// source's own packets, bit for bit, and anything else is this project's
440+/// encoder over the decoded mix. [`run`] publishes which of the two really
441+/// happened, so the encoder line a user reads is measured and not promised.
442+pub(crate) struct ExportAudio {
443+ pub params: crate::AacTrackParams,
444+ pub packets: Vec<crate::AacPacket>,
445+ /// Whether those packets are the source's, untouched.
446+ pub copied: bool,
447+}
448+
291 /// The timeline's audio track for a file that carries picture: copied packet for449 /// The timeline's audio track for a file that carries picture: copied packet for
292 /// packet where a copy says exactly what the timeline says, and decoded, mixed450 /// packet where a copy says exactly what the timeline says, and decoded, mixed
293 /// and encoded again ([`encode_audio`]) where it cannot -- a second audio lane,451 /// and encoded again ([`encode_audio`]) where it cannot -- a second audio lane,
@@ -302,11 +460,7 @@ fn settle(shared: &Shared, result: crate::Result<()>) {
302 /// ponytail: this holds the whole exported AAC track in memory (~3 kB per460 /// ponytail: this holds the whole exported AAC track in memory (~3 kB per
303 /// 23 ms packet, so ~500 MB for an hour). Upgrade path is a streaming461 /// 23 ms packet, so ~500 MB for an hour). Upgrade path is a streaming
304 /// `copy_segments` that yields packets instead of collecting them.462 /// `copy_segments` that yields packets instead of collecting them.
305-#[allow(clippy::type_complexity)]463+fn copy_audio(project: &Project, meta: &VideoMeta) -> crate::Result<Option<ExportAudio>> {
306-fn copy_audio(
307- project: &Project,
308- meta: &VideoMeta,
309-) -> crate::Result<Option<(crate::AacTrackParams, Vec<crate::AacPacket>)>> {
310 // The segments name their source, and the copy carries its packet-rounding464 // The segments name their source, and the copy carries its packet-rounding
311 // debt across a source join exactly as across a cut, so a timeline spanning465 // debt across a source join exactly as across a cut, so a timeline spanning
312 // files stays in sync. A source whose AAC parameters disagree with the466 // files stays in sync. A source whose AAC parameters disagree with the
@@ -347,13 +501,24 @@ fn copy_audio(
347 // copy never reaches: copying such a lane would write the clip *flat*,501 // copy never reaches: copying such a lane would write the clip *flat*,
348 // silently.502 // silently.
349 //503 //
504+ // A frame *rate* of its own is not one of those, and that is deliberate: do
505+ // not "fix" this into a re-encode. A clip counts the **timeline's** frames
506+ // whatever its file was shot at ([`crate::project::Rate`]), so the window
507+ // this copy trims a source's sound to is `start..end` in whole timeline
508+ // frames -- exactly the seconds the picture covers -- and the file is read
509+ // at the pitch it was recorded at, which is what playing at the rate it was
510+ // shot at means. There is no per-clip stretch to express, so the packets are
511+ // already the right sound in the right place; re-encoding a conformed lane
512+ // would buy nothing and cost a generation of loss on every mixed-rate export
513+ // (`tests/mixed_fps.rs`, `an_export_of_two_rates_runs_at_the_speed_it_was_shot`
514+ // measures the copied sound against the picture). A *speed* is different
515+ // because it resamples, which is why it leaves through the re-encode above.
516+ //
350 // Only these: a timeline nobody has touched still leaves through the copy517 // Only these: a timeline nobody has touched still leaves through the copy
351 // below, packet for packet, so no passthrough quietly becomes a generation518 // below, packet for packet, so no passthrough quietly becomes a generation
352 // of loss.519 // of loss.
353 let speeded = project.lane(lane).iter().any(|c| !c.speed.is_normal());520 let speeded = project.lane(lane).iter().any(|c| !c.speed.is_normal());
354- let equalized = (0..project.lane(lane).len())521+ if speeded || equalized(project) {
355- .any(|idx| project.eq_of(lane, idx).is_some_and(|eq| !eq.is_identity()));
356- if speeded || equalized {
357 return encode_audio(project, meta);522 return encode_audio(project, meta);
358 }523 }
359 // What is left is a copy the *sources* may still not be able to give: AAC524 // What is left is a copy the *sources* may still not be able to give: AAC
@@ -365,7 +530,11 @@ fn copy_audio(
365 // which symphonia has no decoder for at any version -- is the one that comes530 // which symphonia has no decoder for at any version -- is the one that comes
366 // back, by name, from [`encode_audio`].531 // back, by name, from [`encode_audio`].
367 match AudioSession::copy_multi_streams(&project.audio_sources(), segments) {532 match AudioSession::copy_multi_streams(&project.audio_sources(), segments) {
368- Ok(copied) => Ok(copied),533+ Ok(copied) => Ok(copied.map(|(params, packets)| ExportAudio {
534+ params,
535+ packets,
536+ copied: true,
537+ })),
369 Err(_) => encode_audio(project, meta),538 Err(_) => encode_audio(project, meta),
370 }539 }
371 }540 }
@@ -387,11 +556,7 @@ fn copy_audio(
387 /// minute of 48 kHz stereo), for [`run_audio`]'s reason -- `rusty_aac` buffers556 /// minute of 48 kHz stereo), for [`run_audio`]'s reason -- `rusty_aac` buffers
388 /// the whole stream anyway, since it encodes its frames in parallel. Upgrade557 /// the whole stream anyway, since it encodes its frames in parallel. Upgrade
389 /// path is a chunked push once that encoder streams.558 /// path is a chunked push once that encoder streams.
390-#[allow(clippy::type_complexity)]559+fn encode_audio(project: &Project, meta: &VideoMeta) -> crate::Result<Option<ExportAudio>> {
391-fn encode_audio(
392- project: &Project,
393- meta: &VideoMeta,
394-) -> crate::Result<Option<(crate::AacTrackParams, Vec<crate::AacPacket>)>> {
395 let sources = project.audio_sources();560 let sources = project.audio_sources();
396 let segs = project.audio_segments_from(0, meta.frame_rate);561 let segs = project.audio_segments_from(0, meta.frame_rate);
397 let eqs = project.audio_eqs_from(0, meta.frame_rate);562 let eqs = project.audio_eqs_from(0, meta.frame_rate);
@@ -444,8 +609,8 @@ fn encode_audio(
444 samples: packet.duration,609 samples: packet.duration,
445 });610 });
446 }611 }
447- Ok(Some((612+ Ok(Some(ExportAudio {
448- crate::AacTrackParams {613+ params: crate::AacTrackParams {
449 freq_index,614 freq_index,
450 // 1 and 2 are the ISO channel configurations for mono and stereo,615 // 1 and 2 are the ISO channel configurations for mono and stereo,
451 // and the opener refuses anything wider than stereo already.616 // and the opener refuses anything wider than stereo already.
@@ -453,7 +618,8 @@ fn encode_audio(
453 sample_rate: audio.sample_rate,618 sample_rate: audio.sample_rate,
454 },619 },
455 packets,620 packets,
456- )))621+ copied: false,
622+ }))
457 }623 }
458 624
459 fn run(625 fn run(
@@ -471,16 +637,39 @@ fn run(
471 // them into the clusters as it writes. Every video format gets the same637 // them into the clusters as it writes. Every video format gets the same
472 // track: none of them is picture-only any more.638 // track: none of them is picture-only any more.
473 let audio = copy_audio(project, meta)?;639 let audio = copy_audio(project, meta)?;
474- let audio_params = audio.as_ref().map(|(track, _)| AudioParams {640+ let audio_params = audio.as_ref().map(|track| AudioParams {
475- freq_index: track.freq_index,641+ freq_index: track.params.freq_index,
476- chan_conf: track.chan_conf,642+ chan_conf: track.params.chan_conf,
477- sample_rate: track.sample_rate,643+ sample_rate: track.params.sample_rate,
478 });644 });
645+ // What the track *is*, kept before the packets are handed to a muxer: the
646+ // encoder line names a copy or an encode and only `copy_audio` knows which.
647+ let sound = audio.as_ref().map(|track| track.copied);
479 // Taken by the Matroska muxer at creation; the mp4 one writes its track648 // Taken by the Matroska muxer at creation; the mp4 one writes its track
480 // after the picture, so for that path this is still `Some` at the end.649 // after the picture, so for that path this is still `Some` at the end.
481- let mut packets = audio.map(|(_, packets)| packets);650+ let mut packets = audio.map(|track| track.packets);
651+
652+ // One header parse per source, before any of them is decoded: what rate
653+ // each file was shot at against the timeline's ([`Rate`]), which is how the
654+ // clip's timeline frames below become frames of the file. Real time for a
655+ // still, a song and a single-rate project, where every conversion below is
656+ // the identity.
657+ let rates: Vec<Rate> = sources
658+ .iter()
659+ .map(|source| source_rate(&source.path, meta.frame_rate))
660+ .collect();
482 661
483 let mut encoder = Enc::open(meta, settings)?;662 let mut encoder = Enc::open(meta, settings)?;
663+ // What this file is really being written by, for a progress line to name.
664+ // Published *after* the seat is open, so a hardware encoder the driver
665+ // refused reads as the software one that took over rather than as the hope
666+ // it replaced -- and the sound says whether it was copied or encoded, which
667+ // `copy_audio` decided a few lines up.
668+ *shared.encoders.lock().unwrap() = Some(format!(
669+ "{} · {}",
670+ encoder.label(),
671+ audio_label(project, settings.format, sound.is_some(), sound)
672+ ));
484 let mut muxer = None;673 let mut muxer = None;
485 let mut done = 0u32;674 let mut done = 0u32;
486 let black = Black::new(meta);675 let black = Black::new(meta);
@@ -494,14 +683,18 @@ fn run(
494 // encoder is *not* reopened, so the export is one continuous stream683 // encoder is *not* reopened, so the export is one continuous stream
495 // whose GOP boundaries need not line up with the cuts -- nor with the684 // whose GOP boundaries need not line up with the cuts -- nor with the
496 // file boundaries, which are just cuts that change the path.685 // file boundaries, which are just cuts that change the path.
497- let mut pictures = match span.from {686+ let (mut pictures, rate, in_frame) = match span.from {
498 Some((source, in_frame)) => {687 Some((source, in_frame)) => {
499 let entry = sources688 let entry = sources
500 .get(source)689 .get(source)
501 .ok_or_else(|| format!("clip names source {source} of {}", sources.len()))?;690 .ok_or_else(|| format!("clip names source {source} of {}", sources.len()))?;
502- Some(ClipDecoder::open(&entry.path, in_frame)?)691+ let rate = rates[source];
692+ // Opened at the file's own frame, which is the only place the
693+ // file's numbering is used -- the span's are the timeline's.
694+ let pictures = ClipDecoder::open(&entry.path, rate.source_at(in_frame))?;
695+ (Some(pictures), rate, in_frame)
503 }696 }
504- None => None,697+ None => (None, Rate::REAL_TIME, 0),
505 };698 };
506 // What this span is graded by -- the same answer playback's decoder699 // What this span is graded by -- the same answer playback's decoder
507 // carries, so the export is the picture that was watched. `None` for a700 // carries, so the export is the picture that was watched. `None` for a
@@ -532,10 +725,24 @@ fn run(
532 let mut done_here = 0u32;725 let mut done_here = 0u32;
533 // Source frames already taken out of this span's decoder.726 // Source frames already taken out of this span's decoder.
534 let mut taken = 0u32;727 let mut taken = 0u32;
728+ // The whole of the mapping, in the order it composes: the speed says
729+ // which of the clip's (timeline-rate) frames a timeline frame shows,
730+ // and the rate says which frame of the *file* that is -- counted from
731+ // the one the decoder was opened at. At real time and at the timeline's
732+ // own rate this is `Speed::source_at` and nothing else, which is the
733+ // walk a single-rate project has always taken.
734+ let opened_at = rate.source_at(in_frame);
735+ let source_at =
736+ |offset: u32| rate.source_at(in_frame + span.speed.source_at(offset)) - opened_at;
535 while done_here < span.len {737 while done_here < span.len {
536 cancelled(shared)?;738 cancelled(shared)?;
537- let want = span.speed.source_at(done_here);739+ let want = source_at(done_here);
538- let repeats = span.speed.repeats(done_here, span.len);740+ // How many timeline frames from here show that same picture: one at
741+ // real time, more when the clip is slowed or its file is slower
742+ // than the timeline. Encoded again rather than decoded twice.
743+ let repeats = (done_here..span.len)
744+ .take_while(|&offset| source_at(offset) == want)
745+ .count() as u32;
539 let picture = match &mut pictures {746 let picture = match &mut pictures {
540 Some(pictures) => {747 Some(pictures) => {
541 let mut ran_out = false;748 let mut ran_out = false;
@@ -637,6 +844,24 @@ fn run(
637 Ok(())844 Ok(())
638 }845 }
639 846
847+/// What rate `path` was shot at against a timeline at `timeline_fps`
848+/// ([`Rate`]). [`Rate::REAL_TIME`] for the files that have no rate of their own
849+/// -- a still, a song -- and for one that will not open here: the decoder is
850+/// opened a few lines later and fails the export by name, which is a better
851+/// error than this one could raise.
852+fn source_rate(path: &Path, timeline_fps: f64) -> Rate {
853+ if crate::is_image(path) || crate::is_audio(path) {
854+ return Rate::REAL_TIME;
855+ }
856+ match Demuxer::open(path) {
857+ // ...and one whose rate cannot be named against the timeline's, which
858+ // `matches_timeline` refuses at import, so nothing on a timeline is on
859+ // this arm either.
860+ Ok((meta, _)) => Rate::from_fps(meta.frame_rate, timeline_fps).unwrap_or(Rate::REAL_TIME),
861+ Err(_) => Rate::REAL_TIME,
862+ }
863+}
864+
640 /// The audio lanes alone, summed, as a WAV or a FLAC.865 /// The audio lanes alone, summed, as a WAV or a FLAC.
641 ///866 ///
642 /// Nothing here re-derives the edit: the play lists are867 /// Nothing here re-derives the edit: the play lists are
@@ -676,6 +901,9 @@ fn run_audio(
676 else {901 else {
677 return Err("this timeline has no audio to export".into());902 return Err("this timeline has no audio to export".into());
678 };903 };
904+ // The picture path's line, for a file that is sound alone: there is sound
905+ // by the line above, so this names the encoder writing it.
906+ *shared.encoders.lock().unwrap() = Some(audio_label(project, format, true, None).to_string());
679 let channels = usize::from(audio.channels);907 let channels = usize::from(audio.channels);
680 let frames = (f64::from(project.timeline_frames()) / meta.frame_rate908 let frames = (f64::from(project.timeline_frames()) / meta.frame_rate
681 * f64::from(audio.sample_rate))909 * f64::from(audio.sample_rate))
@@ -994,6 +1222,18 @@ enum Enc {
994 }1222 }
995 1223
996 impl Enc {1224 impl Enc {
1225+ /// Which seat this *is*, said the way [`video_label`] says it -- so the
1226+ /// name a running export shows is the name the card showed, or the honest
1227+ /// difference where the probe and the open disagreed.
1228+ fn label(&self) -> &'static str {
1229+ match self {
1230+ Self::Hw(_) => video_label(Format::Mp4, true),
1231+ Self::Sw { .. } => video_label(Format::Mp4, false),
1232+ Self::Av1Hw(_) => video_label(Format::Av1, true),
1233+ Self::Av1Sw { .. } => video_label(Format::Av1, false),
1234+ }
1235+ }
1236+
997 fn open(meta: &VideoMeta, settings: &ExportSettings) -> crate::Result<Self> {1237 fn open(meta: &VideoMeta, settings: &ExportSettings) -> crate::Result<Self> {
998 // Which *codec* the picture is, not which container it goes in: both AV11238 // Which *codec* the picture is, not which container it goes in: both AV1
999 // formats run the same encoder.1239 // formats run the same encoder.
@@ -1003,18 +1243,13 @@ impl Enc {
1003 // A caller's number goes through the same clamp as the computed one: a1243 // A caller's number goes through the same clamp as the computed one: a
1004 // zero bitrate switches the software encoder's lookahead on, which would1244 // zero bitrate switches the software encoder's lookahead on, which would
1005 // break the one-picture-per-call contract `encode` documents below.1245 // break the one-picture-per-call contract `encode` documents below.
1006- let bitrate = settings1246+ let bitrate = bitrate_of(meta, settings);
1007- .bitrate
1008- .map_or_else(|| bitrate_for(meta), |b| b.clamp(MIN_BITRATE, MAX_BITRATE));
1009 // The plugin wants an exact rational, and the muxer already picks one1247 // The plugin wants an exact rational, and the muxer already picks one
1010 // that is exact at every rate we can read -- `fps * 1000 / 1000` would1248 // that is exact at every rate we can read -- `fps * 1000 / 1000` would
1011 // hand 24000/1001 over as a rounded 23.976, which is the same1249 // hand 24000/1001 over as a rounded 23.976, which is the same
1012 // truncation the container timing had.1250 // truncation the container timing had.
1013- let (fps_num, fps_den) = crate::mux::frame_timing(meta.frame_rate)?;1251+ crate::mux::frame_timing(meta.frame_rate)?;
1014- if !settings.force_sw1252+ if let Some(hw) = hw_seat(meta, settings) {
1015- && !forced("VE_SW_ENC")
1016- && let Some(hw) = HwEncoder::open(meta.width, meta.height, fps_num, fps_den, bitrate)
1017- {
1018 eprintln!("export encoder: hardware (VA-API plugin)");1253 eprintln!("export encoder: hardware (VA-API plugin)");
1019 return Ok(Self::Hw(hw));1254 return Ok(Self::Hw(hw));
1020 }1255 }
@@ -1055,19 +1290,12 @@ impl Enc {
1055 /// cros-codecs release that fixes it) plus a probe encode of one frame at1290 /// cros-codecs release that fixes it) plus a probe encode of one frame at
1056 /// open, after which this can prefer hardware the way H.264 does.1291 /// open, after which this can prefer hardware the way H.264 does.
1057 fn open_av1(meta: &VideoMeta, settings: &ExportSettings) -> crate::Result<Self> {1292 fn open_av1(meta: &VideoMeta, settings: &ExportSettings) -> crate::Result<Self> {
1058- let bitrate = settings1293+ let bitrate = bitrate_of(meta, settings);
1059- .bitrate
1060- .map_or_else(|| bitrate_for(meta), |b| b.clamp(MIN_BITRATE, MAX_BITRATE));
1061 let (fps_num, fps_den) = crate::mux::frame_timing(meta.frame_rate)?;1294 let (fps_num, fps_den) = crate::mux::frame_timing(meta.frame_rate)?;
1062 // Two seconds between keyframes, as the H.264 seat does: a seek may only1295 // Two seconds between keyframes, as the H.264 seat does: a seek may only
1063 // land on one, and this is what a cluster of the Matroska file is.1296 // land on one, and this is what a cluster of the Matroska file is.
1064 let gop = (meta.frame_rate * 2.0).round().max(1.0) as u64;1297 let gop = (meta.frame_rate * 2.0).round().max(1.0) as u64;
1065- if forced("VE_HW_AV1")1298+ if let Some(hw) = hw_seat(meta, settings) {
1066- && !settings.force_sw
1067- && !forced("VE_SW_ENC")
1068- && let Some(hw) =
1069- HwEncoder::open_av1(meta.width, meta.height, fps_num, fps_den, bitrate)
1070- {
1071 eprintln!("export encoder: hardware AV1 (VA-API plugin)");1299 eprintln!("export encoder: hardware AV1 (VA-API plugin)");
1072 return Ok(Self::Av1Hw(hw));1300 return Ok(Self::Av1Hw(hw));
1073 }1301 }
crates/engine/src/lib.rsmodified+1 -1
@@ -27,7 +27,7 @@ pub use demux::{Codec, VideoMeta};
27 pub use export::ExportHandle;27 pub use export::ExportHandle;
28 pub use mux::{AudioParams, Mp4Muxer, VideoParams};28 pub use mux::{AudioParams, Mp4Muxer, VideoParams};
29 pub use playback::PlaybackSession;29 pub use playback::PlaybackSession;
30-pub use project::{Clip, Project, Speed};30+pub use project::{Clip, Project, Rate, Speed};
31 31
32 /// Whether a path names a standalone audio file -- a source with no picture,32 /// Whether a path names a standalone audio file -- a source with no picture,
33 /// which belongs on the audio lane and nowhere else. Extension only, lowercased:33 /// which belongs on the audio lane and nowhere else. Extension only, lowercased:
crates/engine/src/playback.rsmodified+181 -50
@@ -22,10 +22,10 @@ use crate::ao::AoSession;
22 use crate::audio::{AudioChunk, AudioSession};22 use crate::audio::{AudioChunk, AudioSession};
23 use crate::clock::{ClockSource, PlaybackClock};23 use crate::clock::{ClockSource, PlaybackClock};
24 use crate::color::ColorParams;24 use crate::color::ColorParams;
25-use crate::decode::{DecodeSession, Frame, Worker};25+use crate::decode::{Backend, BackendCell, DecodeSession, Frame, Worker};
26 use crate::demux::{Codec, Demuxer, VideoMeta};26 use crate::demux::{Codec, Demuxer, VideoMeta};
27 use crate::eq::EqParams;27 use crate::eq::EqParams;
28-use crate::project::{Clip, Edge, Lane, LaneKind, Project, Source, Span, Speed};28+use crate::project::{Clip, Edge, Lane, LaneKind, Project, Rate, Source, Span, Speed};
29 use crate::scale::{Composer, FitPolicy};29 use crate::scale::{Composer, FitPolicy};
30 30
31 /// How long the feeder waits out a full ring. The ring holds a second, so this31 /// 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);
40 /// honest; both are what a video imported onto such a timeline is held to40 /// honest; both are what a video imported onto such a timeline is held to
41 /// ([`matches_timeline`]).41 /// ([`matches_timeline`]).
42 ///42 ///
43-/// ponytail: a 25 fps video refused by an audio-only timeline it could have43+/// ponytail: a 25 fps video imported onto an audio-only timeline it could have
44-/// defined is the ceiling here. Upgrade path is adopting the first *picture's*44+/// defined plays at 25 fps, correctly, but on a 30 fps timeline -- it is read
45-/// rate and codec on import, which means retiming every audio clip already45+/// through [`Rate`] like any other file shot at another rate rather than
46-/// placed in frames.46+/// defining one. Upgrade path is adopting the first *picture's* rate and codec
47+/// on import, which means retiming every audio clip already placed in frames.
47 const AUDIO_ONLY_CANVAS: (u32, u32, f64) = (1920, 1080, 30.0);48 const AUDIO_ONLY_CANVAS: (u32, u32, f64) = (1920, 1080, 30.0);
48 49
49 /// The frame rate a timeline scaffolded from a still image runs at, for50 /// The frame rate a timeline scaffolded from a still image runs at, for
@@ -160,6 +161,11 @@ pub struct PlaybackSession {
160 frames: Receiver<Frame>,161 frames: Receiver<Frame>,
161 /// The current decode worker.162 /// The current decode worker.
162 worker: Worker,163 worker: Worker,
164+ /// What that worker opened -- hardware, software, a still, a gap -- written
165+ /// by the worker itself and read by [`decode_backend`](Self::decode_backend).
166+ /// Replaced with the stream at every seek, so it always describes the
167+ /// pictures currently arriving and never the clip before them.
168+ backend: BackendCell,
163 /// Workers cancelled by a seek or a clip change, waiting to be reaped.169 /// Workers cancelled by a seek or a clip change, waiting to be reaped.
164 /// Joining one inline costs whatever VA-API init it is still inside (98 ms170 /// Joining one inline costs whatever VA-API init it is still inside (98 ms
165 /// measured worst case), which is a visible hitch on the caller's thread;171 /// measured worst case), which is a visible hitch on the caller's thread;
@@ -193,6 +199,20 @@ pub struct PlaybackSession {
193 /// not -- with the single exception `sources` itself has,199 /// not -- with the single exception `sources` itself has,
194 /// [`Self::remove_source`], which takes the same entry out of both.200 /// [`Self::remove_source`], which takes the same entry out of both.
195 counts: Vec<u32>,201 counts: Vec<u32>,
202+ /// What each source's own frame rate is against this timeline's, indexed
203+ /// and grown exactly as [`Self::counts`] is (and shortened with it by
204+ /// [`Self::remove_source`]). [`Rate::REAL_TIME`] for a file shot at the
205+ /// timeline's rate -- and for a still and a song, which have no rate of
206+ /// their own -- so a single-rate project converts nothing anywhere.
207+ ///
208+ /// A clip counts *timeline* frames ([`Rate`]); this is the one thing that
209+ /// knows which frames of the file those are, and only
210+ /// [`start_span`](Self::start_span) and [`try_frame`](Self::try_frame) ask.
211+ rates: Vec<Rate>,
212+ /// The rate of the source the current worker is decoding, kept beside
213+ /// [`Self::span`] because the frames coming back are numbered in *its*
214+ /// file's frames and nothing else can put them back on the timeline.
215+ span_rate: Rate,
196 /// What the current video worker was opened for: where it sits on the216 /// What the current video worker was opened for: where it sits on the
197 /// timeline, how long it runs, and which source frame it started at --217 /// timeline, how long it runs, and which source frame it started at --
198 /// together they rewrite a source frame index into a timeline one. Not a218 /// together they rewrite a source frame index into a timeline one. Not a
@@ -259,12 +279,16 @@ impl PlaybackSession {
259 native: (meta.width, meta.height),279 native: (meta.width, meta.height),
260 frames: stream.frames,280 frames: stream.frames,
261 worker: stream.worker,281 worker: stream.worker,
282+ backend: stream.backend,
262 retired: Vec::new(),283 retired: Vec::new(),
263 clock: PlaybackClock::new(source),284 clock: PlaybackClock::new(source),
264 audio,285 audio,
265 audio_disabled,286 audio_disabled,
266 project,287 project,
267 counts: vec![meta.frame_count],288 counts: vec![meta.frame_count],
289+ // Source 0 *is* the timeline's rate: it defined it.
290+ rates: vec![Rate::REAL_TIME],
291+ span_rate: Rate::REAL_TIME,
268 span,292 span,
269 eos: false,293 eos: false,
270 })294 })
@@ -353,6 +377,7 @@ impl PlaybackSession {
353 native: (width, height),377 native: (width, height),
354 frames: stream.frames,378 frames: stream.frames,
355 worker: stream.worker,379 worker: stream.worker,
380+ backend: stream.backend,
356 retired: Vec::new(),381 retired: Vec::new(),
357 // The song keeps the clock, as a video's own sound does -- and wall382 // The song keeps the clock, as a video's own sound does -- and wall
358 // time keeps it on a machine with no device, where the picture383 // time keeps it on a machine with no device, where the picture
@@ -365,6 +390,9 @@ impl PlaybackSession {
365 audio_disabled,390 audio_disabled,
366 project,391 project,
367 counts: vec![meta.frame_count],392 counts: vec![meta.frame_count],
393+ // Source 0 *is* the timeline's rate: it defined it.
394+ rates: vec![Rate::REAL_TIME],
395+ span_rate: Rate::REAL_TIME,
368 span,396 span,
369 eos: false,397 eos: false,
370 })398 })
@@ -425,12 +453,16 @@ impl PlaybackSession {
425 native: (meta.width, meta.height),453 native: (meta.width, meta.height),
426 frames: stream.frames,454 frames: stream.frames,
427 worker: stream.worker,455 worker: stream.worker,
456+ backend: stream.backend,
428 retired: Vec::new(),457 retired: Vec::new(),
429 clock: PlaybackClock::new(ClockSource::Wall),458 clock: PlaybackClock::new(ClockSource::Wall),
430 audio: None,459 audio: None,
431 audio_disabled: None,460 audio_disabled: None,
432 project,461 project,
433 counts: vec![meta.frame_count],462 counts: vec![meta.frame_count],
463+ // Source 0 *is* the timeline's rate: it defined it.
464+ rates: vec![Rate::REAL_TIME],
465+ span_rate: Rate::REAL_TIME,
434 span,466 span,
435 eos: false,467 eos: false,
436 })468 })
@@ -554,9 +586,16 @@ impl PlaybackSession {
554 // clip check below indexes this list by source, so it must line up with586 // clip check below indexes this list by source, so it must line up with
555 // `doc.sources` whichever entry the scaffolding came from.587 // `doc.sources` whichever entry the scaffolding came from.
556 let mut counts = Vec::with_capacity(doc.sources.len());588 let mut counts = Vec::with_capacity(doc.sources.len());
589+ // Beside it, one entry per source, grown at every `push` below: the
590+ // scaffold defines the rate, so it is read frame for frame; every other
591+ // one is however long it is *in this timeline's frames*, which is the
592+ // length `import` noted for it and the wall the clip check below holds
593+ // it to.
594+ let mut rates = Vec::with_capacity(doc.sources.len());
557 for (i, source) in doc.sources.iter().enumerate() {595 for (i, source) in doc.sources.iter().enumerate() {
558 if i == scaffold {596 if i == scaffold {
559 counts.push(meta.frame_count);597 counts.push(meta.frame_count);
598+ rates.push(Rate::REAL_TIME);
560 continue;599 continue;
561 }600 }
562 // A still has neither a rate to match nor a track to match with:601 // A still has neither a rate to match nor a track to match with:
@@ -567,6 +606,7 @@ impl PlaybackSession {
567 crate::decode::image_size(&source.path)606 crate::decode::image_size(&source.path)
568 .map_err(|e| format!("source {}: {e}", source.path.display()))?;607 .map_err(|e| format!("source {}: {e}", source.path.display()))?;
569 counts.push(image_frames(meta.frame_rate));608 counts.push(image_frames(meta.frame_rate));
609+ rates.push(Rate::REAL_TIME);
570 continue;610 continue;
571 }611 }
572 // A source with no picture is checked on what it does have, and612 // A source with no picture is checked on what it does have, and
@@ -576,13 +616,15 @@ impl PlaybackSession {
576 audio_matches(source, &first_audio)616 audio_matches(source, &first_audio)
577 .map_err(|e| format!("source {}: {e}", source.path.display()))?;617 .map_err(|e| format!("source {}: {e}", source.path.display()))?;
578 counts.push(audio_frames(&source.path, meta.frame_rate)?);618 counts.push(audio_frames(&source.path, meta.frame_rate)?);
619+ rates.push(Rate::REAL_TIME);
579 continue;620 continue;
580 }621 }
581 let (other, _) = Demuxer::open(&source.path)622 let (other, _) = Demuxer::open(&source.path)
582 .map_err(|e| format!("source {}: {e}", source.path.display()))?;623 .map_err(|e| format!("source {}: {e}", source.path.display()))?;
583- matches_timeline(source, &other, &meta, &first_audio)624+ let rate = matches_timeline(source, &other, &meta, &first_audio)
584 .map_err(|e| format!("source {}: {e}", source.path.display()))?;625 .map_err(|e| format!("source {}: {e}", source.path.display()))?;
585- counts.push(other.frame_count);626+ counts.push(rate.timeline_at(other.frame_count));
627+ rates.push(rate);
586 }628 }
587 // The video lane can only play files that have pictures. Hand-written629 // The video lane can only play files that have pictures. Hand-written
588 // (or hand-edited) project files are the one door this can come in630 // (or hand-edited) project files are the one door this can come in
@@ -647,6 +689,7 @@ impl PlaybackSession {
647 native,689 native,
648 frames: stream.frames,690 frames: stream.frames,
649 worker: stream.worker,691 worker: stream.worker,
692+ backend: stream.backend,
650 retired: Vec::new(),693 retired: Vec::new(),
651 clock: PlaybackClock::new(match audio {694 clock: PlaybackClock::new(match audio {
652 Some(_) => ClockSource::Audio,695 Some(_) => ClockSource::Audio,
@@ -656,6 +699,8 @@ impl PlaybackSession {
656 audio_disabled,699 audio_disabled,
657 project,700 project,
658 counts,701 counts,
702+ rates,
703+ span_rate: Rate::REAL_TIME,
659 span,704 span,
660 eos: false,705 eos: false,
661 };706 };
@@ -672,6 +717,24 @@ impl PlaybackSession {
672 &self.meta717 &self.meta
673 }718 }
674 719
720+ /// What the pictures now arriving are being decoded by: the clip under the
721+ /// playhead, since one video worker feeds the composite at a time. An
722+ /// atomic load -- a front-end may ask it every repaint -- and it is what
723+ /// *opened*, so a clip whose hardware session fell back to software reads
724+ /// [`Backend::Software`] from the frame that fallback happened.
725+ pub fn decode_backend(&self) -> Backend {
726+ self.backend.get()
727+ }
728+
729+ /// What an export of this timeline would encode the *sound* with, before
730+ /// one is started: the copy an mp4 normally makes, or the software encoder
731+ /// the format (or an equalized lane) forces. Pure -- no probe, no file
732+ /// opened -- so a card may ask it per repaint; the picture's half costs a
733+ /// plugin open and lives in [`crate::export::planned_video`].
734+ pub fn planned_audio(&self, format: crate::export::Format) -> &'static str {
735+ crate::export::planned_audio(&self.project, format)
736+ }
737+
675 /// Why this session plays silent although the file has sound -- an audio738 /// Why this session plays silent although the file has sound -- an audio
676 /// track in a codec we cannot decode, or one the decoder refused. `None`739 /// track in a codec we cannot decode, or one the decoder refused. `None`
677 /// when there is audio, and for a file that never had any. A front-end740 /// when there is audio, and for a file that never had any. A front-end
@@ -733,9 +796,15 @@ impl PlaybackSession {
733 // (`speed_maps_both_ways`). An empty timeline has no span,796 // (`speed_maps_both_ways`). An empty timeline has no span,
734 // and its one black frame is frame 0. Real time is the797 // and its one black frame is frame 0. Real time is the
735 // arithmetic this always did, frame for frame.798 // arithmetic this always did, frame for frame.
736- frame.index = self799+ // ...through the file's own rate first, which is the ceil
737- .span800+ // half of *that* pair: the picture at source frame `i` is
738- .map_or(frame.index, |s| s.timeline_at(frame.index));801+ // due at the first timeline-rate frame that shows it, and a
802+ // slower file's picture is therefore held for the frames in
803+ // between. Real time for a gap and for a single-rate
804+ // project, where this is the identity.
805+ frame.index = self.span.map_or(frame.index, |s| {
806+ s.timeline_at(self.span_rate.timeline_at(frame.index))
807+ });
739 return Some(frame);808 return Some(frame);
740 }809 }
741 Err(TryRecvError::Empty) => return None,810 Err(TryRecvError::Empty) => return None,
@@ -805,6 +874,14 @@ impl PlaybackSession {
805 /// timeline still moves, there are simply no more pictures, and the874 /// timeline still moves, there are simply no more pictures, and the
806 /// disconnected receiver carries the session on to the next span.875 /// disconnected receiver carries the session on to the next span.
807 fn start_span(&mut self, span: Option<Span>) {876 fn start_span(&mut self, span: Option<Span>) {
877+ // Which file's frames the worker about to be opened will number its
878+ // pictures in: the span's own source, and real time for a gap, whose
879+ // black worker counts timeline frames already. Set before the open,
880+ // because the open is the first thing that converts with it.
881+ self.span_rate = match span.and_then(|s| s.from) {
882+ Some((source, _)) => self.rates.get(source).copied().unwrap_or(Rate::REAL_TIME),
883+ None => Rate::REAL_TIME,
884+ };
808 let opened = match span {885 let opened = match span {
809 // The grade is the composite's at this frame -- the same clip the886 // The grade is the composite's at this frame -- the same clip the
810 // span itself came from -- and it is constant across the span, so887 // span itself came from -- and it is constant across the span, so
@@ -841,10 +918,17 @@ impl PlaybackSession {
841 ..918 ..
842 }) => DecodeSession::open_worker(919 }) => DecodeSession::open_worker(
843 &self.project.sources()[source].path,920 &self.project.sources()[source].path,
844- in_frame,921+ // The file's own frames, which is the only place they exist:
922+ // a clip counts the timeline's ([`Rate`]).
923+ self.span_rate.source_at(in_frame),
845 // Source frames, which a speed makes more (or fewer) than the924 // Source frames, which a speed makes more (or fewer) than the
846- // timeline frames the span covers.925+ // timeline frames the span covers -- and which a file shot at
847- in_frame + span.expect("matched above").source_len(),926+ // another rate makes fewer (or more) again. One past the last
927+ // frame this span shows, not one past its length: at another
928+ // rate those are two different frames.
929+ self.span_rate.source_at(
930+ in_frame + span.expect("matched above").source_len().saturating_sub(1),
931+ ) + 1,
848 self.project932 self.project
849 .composite_color_at(start)933 .composite_color_at(start)
850 .copied()934 .copied()
@@ -875,6 +959,7 @@ impl PlaybackSession {
875 // then can it return and be reaped by a later sweep. Nothing here959 // then can it return and be reaped by a later sweep. Nothing here
876 // joins, so this ordering costs the seek nothing.960 // joins, so this ordering costs the seek nothing.
877 self.frames = stream.frames;961 self.frames = stream.frames;
962+ self.backend = stream.backend;
878 self.retire(stream.worker);963 self.retire(stream.worker);
879 }964 }
880 self.span = span;965 self.span = span;
@@ -1120,13 +1205,36 @@ impl PlaybackSession {
1120 self.project.trim_room(lane, idx, edge, &self.counts)1205 self.project.trim_room(lane, idx, edge, &self.counts)
1121 }1206 }
1122 1207
1123- /// Records how long a source is, for a source index that may be one1208+ /// Records how long a source is and what rate it was shot at, for a source
1124- /// `Project::import` just made or one it handed back. See [`Self::counts`].1209+ /// index that may be one `Project::import` just made or one it handed back.
1125- fn note_frames(&mut self, source: usize, frames: u32) {1210+ /// See [`Self::counts`] and [`Self::rates`], which are one table in two
1211+ /// vectors and grow together.
1212+ fn note_frames(&mut self, source: usize, frames: u32, rate: Rate) {
1126 if source == self.counts.len() {1213 if source == self.counts.len() {
1127 self.counts.push(frames);1214 self.counts.push(frames);
1215+ self.rates.push(rate);
1128 }1216 }
1129 debug_assert_eq!(self.counts.len(), self.project.sources().len());1217 debug_assert_eq!(self.counts.len(), self.project.sources().len());
1218+ debug_assert_eq!(self.rates.len(), self.counts.len());
1219+ }
1220+
1221+ /// The rate noted for whichever source plays `path`, by
1222+ /// [`file_frames`](Self::file_frames)'s rule: one file is one rate however
1223+ /// many audio tracks it carries. [`Rate::REAL_TIME`] for a file this session
1224+ /// has never taken in.
1225+ fn file_rate(&self, path: &Path) -> Rate {
1226+ self.source_of(path)
1227+ .map_or(Rate::REAL_TIME, |i| self.rates[i])
1228+ }
1229+
1230+ /// Which source `path` is, canonicalising only if it has to: a source's own
1231+ /// path is canonical ([`Source::new`]), so a caller handing one back from
1232+ /// [`sources`](Self::sources) -- which is every library row -- hits on the
1233+ /// first walk and never pays for the `canonicalize` syscall the second one
1234+ /// makes. One rule, so a path that names a length names a rate too.
1235+ fn source_of(&self, path: &Path) -> Option<usize> {
1236+ let at = |wanted: &Path| self.project.sources().iter().position(|s| s.path == wanted);
1237+ at(path).or_else(|| at(&Source::new(path, 0).path))
1130 }1238 }
1131 1239
1132 /// How long the whole of `path` is, in timeline frames: the length noted1240 /// How long the whole of `path` is, in timeline frames: the length noted
@@ -1138,14 +1246,20 @@ impl PlaybackSession {
1138 /// audio tracks it carries -- the picture's frame count for an mp4, the1246 /// audio tracks it carries -- the picture's frame count for an mp4, the
1139 /// playing time for a song.1247 /// playing time for a song.
1140 pub fn file_frames(&self, path: &Path) -> u32 {1248 pub fn file_frames(&self, path: &Path) -> u32 {
1141- let at = |wanted: &Path| self.project.sources().iter().position(|s| s.path == wanted);1249+ self.source_of(path).map_or(0, |i| self.counts[i])
1142- // A source's own path is canonical ([`Source::new`]), so a caller1250+ }
1143- // handing one back from [`sources`](Self::sources) -- which is every1251+
1144- // library row -- hits on the first walk and never pays for the1252+ /// What rate the file at `path` was *shot* at, in frames per second -- which
1145- // `canonicalize` syscall the second one makes.1253+ /// is the timeline's own rate for every source that shares it, and is not
1146- at(path)1254+ /// for one placed at another ([`Rate`]). By path like
1147- .or_else(|| at(&Source::new(path, 0).path))1255+ /// [`file_frames`](Self::file_frames), and the timeline's rate for a file
1148- .map_or(0, |i| self.counts[i])1256+ /// this session has never taken in (and for a still and a song, which were
1257+ /// shot at no rate at all).
1258+ ///
1259+ /// What a library row names the file with: the timeline's rate there would
1260+ /// be a lie about a 23.976 fps file the moment one can join.
1261+ pub fn file_fps(&self, path: &Path) -> f64 {
1262+ self.file_rate(path).as_f64() * self.meta.frame_rate
1149 }1263 }
1150 1264
1151 /// The clip the picture is coming from at `timeline_secs`: the lane it sits1265 /// The clip the picture is coming from at `timeline_secs`: the lane it sits
@@ -1304,8 +1418,9 @@ impl PlaybackSession {
1304 let first = self.first_audio()?;1418 let first = self.first_audio()?;
1305 audio_matches(&wanted, &first)?;1419 audio_matches(&wanted, &first)?;
1306 }1420 }
1421+ let rate = self.file_rate(&wanted.path);
1307 let source = self.project.import(path, stream);1422 let source = self.project.import(path, stream);
1308- self.note_frames(source, frames);1423+ self.note_frames(source, frames, rate);
1309 let clip = Clip {1424 let clip = Clip {
1310 start: 0,1425 start: 0,
1311 in_frame: 0,1426 in_frame: 0,
@@ -1387,6 +1502,7 @@ impl PlaybackSession {
1387 // count one index late.1502 // count one index late.
1388 if idx < self.counts.len() {1503 if idx < self.counts.len() {
1389 self.counts.remove(idx);1504 self.counts.remove(idx);
1505+ self.rates.remove(idx);
1390 }1506 }
1391 let now = self.now();1507 let now = self.now();
1392 self.seek(now);1508 self.seek(now);
@@ -1441,11 +1557,14 @@ impl PlaybackSession {
1441 /// nothing playable, so there is nothing for [`undo`](Self::undo) to take1557 /// nothing playable, so there is nothing for [`undo`](Self::undo) to take
1442 /// back, and nothing reseeks.1558 /// back, and nothing reseeks.
1443 ///1559 ///
1444- /// Refused unless it can join the timeline -- same codec, same frame rate,1560+ /// Refused unless it can join the timeline -- same codec, same audio
1445- /// same audio parameters or both silent; the `Err` names the property that1561+ /// parameters or both silent; the `Err` names the property that disagrees,
1446- /// disagrees, for a caller to show. Nothing is changed by a refusal. A1562+ /// for a caller to show. Nothing is changed by a refusal. A *resolution* of
1447- /// *resolution* of its own is not a refusal: the clip is placed on the1563+ /// its own is not a refusal: the clip is placed on the project canvas by its
1448- /// project canvas by its fit policy ([`PlaybackSession::set_fit`]).1564+ /// fit policy ([`PlaybackSession::set_fit`]) -- and neither is a *frame
1565+ /// rate* of its own: the file is placed for the seconds it lasts and read at
1566+ /// [`Rate`] against the timeline's rate, so it plays at the speed it was
1567+ /// shot at.
1449 pub fn import(&mut self, path: &Path) -> crate::Result<usize> {1568 pub fn import(&mut self, path: &Path) -> crate::Result<usize> {
1450 if crate::is_audio(path) {1569 if crate::is_audio(path) {
1451 return self.import_audio(path);1570 return self.import_audio(path);
@@ -1458,9 +1577,15 @@ impl PlaybackSession {
1458 // Stream 0: an import brings a file in on its first audio track, and1577 // Stream 0: an import brings a file in on its first audio track, and
1459 // [`place_stream_at`](Self::place_stream_at) is how any other one of1578 // [`place_stream_at`](Self::place_stream_at) is how any other one of
1460 // its streams reaches the timeline afterwards.1579 // its streams reaches the timeline afterwards.
1461- matches_timeline(&Source::new(path, 0), &meta, &self.meta, &first)?;1580+ // ...and the rate it will be read at comes back from the check that
1581+ // accepted it, so the number the refusal was decided on is the number
1582+ // the file is played by.
1583+ let rate = matches_timeline(&Source::new(path, 0), &meta, &self.meta, &first)?;
1462 let source = self.project.import(path, 0);1584 let source = self.project.import(path, 0);
1463- self.note_frames(source, meta.frame_count);1585+ // Its length *on this timeline*: a file shot slower than the timeline
1586+ // runs covers more frames than it holds, which is the whole of what
1587+ // placing it at another rate means ([`Rate`]).
1588+ self.note_frames(source, rate.timeline_at(meta.frame_count), rate);
1464 Ok(source)1589 Ok(source)
1465 }1590 }
1466 1591
@@ -1480,7 +1605,7 @@ impl PlaybackSession {
1480 audio_matches(&Source::new(path, 0), &first)?;1605 audio_matches(&Source::new(path, 0), &first)?;
1481 let frames = audio_frames(path, self.meta.frame_rate)?;1606 let frames = audio_frames(path, self.meta.frame_rate)?;
1482 let source = self.project.import(path, 0);1607 let source = self.project.import(path, 0);
1483- self.note_frames(source, frames);1608+ self.note_frames(source, frames, Rate::REAL_TIME);
1484 Ok(source)1609 Ok(source)
1485 }1610 }
1486 1611
@@ -1504,7 +1629,7 @@ impl PlaybackSession {
1504 .into());1629 .into());
1505 }1630 }
1506 let source = self.project.import(path, 0);1631 let source = self.project.import(path, 0);
1507- self.note_frames(source, image_frames(self.meta.frame_rate));1632+ self.note_frames(source, image_frames(self.meta.frame_rate), Rate::REAL_TIME);
1508 Ok(source)1633 Ok(source)
1509 }1634 }
1510 1635
@@ -1766,15 +1891,16 @@ impl Drop for PlaybackSession {
1766 1891
1767 /// Whether `path`, already demuxed to `meta`, may join a timeline whose1892 /// Whether `path`, already demuxed to `meta`, may join a timeline whose
1768 /// parameters are `timeline` and whose audio probes as `first`: same codec,1893 /// parameters are `timeline` and whose audio probes as `first`: same codec,
1769-/// same frame rate, same audio parameters or both silent.1894+/// same audio parameters or both silent, and a frame rate that can be named
1895+/// against the timeline's. The [`Rate`] it will be read at comes back with the
1896+/// answer, so the number the check was decided on is the number it plays by.
1770 ///1897 ///
1771 /// *Not* the same size any more. A project has its own resolution1898 /// *Not* the same size any more. A project has its own resolution
1772 /// ([`PlaybackSession::set_resolution`]) and every clip is placed on it by its1899 /// ([`PlaybackSession::set_resolution`]) and every clip is placed on it by its
1773 /// own fit policy, so a 640x360 file joining a 1920x1080 timeline is a1900 /// own fit policy, so a 640x360 file joining a 1920x1080 timeline is a
1774-/// letterboxed clip rather than a refusal. The frame rate stays refused on1901+/// letterboxed clip rather than a refusal, and so is a frame rate of its own:
1775-/// purpose: mixing rates means resampling the *timeline*, which is a different1902+/// the timeline keeps its own rate and the file is read at [`Rate`] against it
1776-/// problem from resampling a picture, and a refusal is the honest answer until1903+/// ([`PlaybackSession::import`] notes how long it is *here*).
1777-/// it is solved.
1778 ///1904 ///
1779 /// The `Err` names the property that disagrees, and those strings are what a1905 /// The `Err` names the property that disagrees, and those strings are what a
1780 /// front-end shows verbatim; [`PlaybackSession::import`] and1906 /// front-end shows verbatim; [`PlaybackSession::import`] and
@@ -1785,7 +1911,7 @@ fn matches_timeline(
1785 meta: &VideoMeta,1911 meta: &VideoMeta,
1786 timeline: &VideoMeta,1912 timeline: &VideoMeta,
1787 first: &Option<crate::AudioProbe>,1913 first: &Option<crate::AudioProbe>,
1788-) -> crate::Result<()> {1914+) -> crate::Result<Rate> {
1789 // Codec first: one timeline is one kind of source. Mixing them would decode1915 // Codec first: one timeline is one kind of source. Mixing them would decode
1790 // (every clip opens its own decoder) but on a machine without the VA-API1916 // (every clip opens its own decoder) but on a machine without the VA-API
1791 // plugin the VP9 half would be black frames with the refusal only on1917 // plugin the VP9 half would be black frames with the refusal only on
@@ -1798,15 +1924,20 @@ fn matches_timeline(
1798 )1924 )
1799 .into());1925 .into());
1800 }1926 }
1801- // Container frame rates are computed from timescales, so never `==`.1927+ // The frame rate is *not* a refusal any more: a file shot at another rate is
1802- if (meta.frame_rate - timeline.frame_rate).abs() > 0.01 {1928+ // placed for the seconds it lasts and read through [`Rate`] at the
1803- return Err(format!(1929+ // decoder's door, so it plays at the speed it was shot at on a timeline
1804- "{:.3} fps does not match the timeline's {:.3} fps",1930+ // that counts frames faster or slower.
1805- meta.frame_rate, timeline.frame_rate1931+ //
1806- )1932+ // A rate that cannot be *named* still is, and this is the one place it is
1807- .into());1933+ // caught: `Rate::from_fps` builds itself out of the muxer's own timescales,
1808- }1934+ // and a file whose rate has none of those (a container that says nothing and
1809- audio_matches(source, first)1935+ // holds one block, so the demuxer measures 0 fps) would otherwise be read
1936+ // 1:1 in silence -- the old rate gate refused those too, by arithmetic
1937+ // accident. The `Err` is `mux::frame_timing`'s own words.
1938+ let rate = Rate::from_fps(meta.frame_rate, timeline.frame_rate)?;
1939+ audio_matches(source, first)?;
1940+ Ok(rate)
1810 }1941 }
1811 1942
1812 /// Whether a candidate's audio may join a timeline whose first source probes as1943 /// Whether a candidate's audio may join a timeline whose first source probes as
crates/engine/src/project.rsmodified+192 -0
@@ -221,9 +221,120 @@ impl std::fmt::Display for Speed {
221 }221 }
222 }222 }
223 223
224+/// What a file's own frame rate is against the timeline's, as an exact
225+/// rational: how many frames of the *file* one frame of the timeline is worth.
226+///
227+/// Every frame number in this module counts **timeline** frames -- a clip's
228+/// `in_frame` and `out_frame` included -- so a 23.976 fps file placed on a 30 fps
229+/// timeline is as many frames long as the seconds it lasts, and every edit
230+/// (trim, split, speed, paste) is the same arithmetic it always was. This is the
231+/// one conversion, and it happens at the decoder's door: [`PlaybackSession`]
232+/// opens a worker with it and [`crate::export`] pulls pictures through it. The
233+/// file's own numbering exists nowhere else.
234+///
235+/// The same floor/ceil pair as [`Speed`], for the same reason: the frame an
236+/// export encodes at a timeline frame has to be the frame playback is holding
237+/// there. Composed *after* a speed rather than folded into it, so a 2x 24 fps
238+/// clip on a 30 fps timeline is exactly both (`rate_composes_with_speed`).
239+///
240+/// Rational and not an `f64`, exactly: 24000/1001 over 30 is `800/1001` and
241+/// stays `800/1001` however far the timeline runs, where a rate rounded to
242+/// (say) milli-fps would leave a fraction of a frame per clip to pile up into a
243+/// visible drift over an hour (`a_23_976_rate_is_exact_and_never_drifts`).
244+///
245+/// [`PlaybackSession`]: crate::PlaybackSession
246+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
247+pub struct Rate {
248+ /// Frames of the file...
249+ source: u32,
250+ /// ...per this many frames of the timeline it plays on. Never zero.
251+ timeline: u32,
252+}
253+
254+impl Rate {
255+ /// A file shot at the timeline's own rate: every conversion below is the
256+ /// identity, which is the path a single-rate project is on.
257+ pub const REAL_TIME: Self = Self {
258+ source: 1,
259+ timeline: 1,
260+ };
261+
262+ /// The rate of a file at `source_fps` on a timeline at `timeline_fps`,
263+ /// exactly.
264+ ///
265+ /// Both rates come out of a container as a division, so neither is ever the
266+ /// number it means (`23.976023976...`); [`crate::mux::frame_timing`] is what
267+ /// already knows how to name one exactly -- it is the same pair the muxer
268+ /// counts an export's frames in -- and this is that pair divided by that
269+ /// pair, reduced. A rate no timescale can name is an `Err` in that
270+ /// function's own words rather than a silent 1:1 -- `matches_timeline` is
271+ /// where a file carrying one is refused by name, beside the codec.
272+ ///
273+ /// Exactly [`REAL_TIME`](Self::REAL_TIME) when the two agree, which is every
274+ /// timeline that had ever opened in this editor before mixed rates.
275+ pub fn from_fps(source_fps: f64, timeline_fps: f64) -> crate::Result<Self> {
276+ let (src_scale, src_ticks) = crate::mux::frame_timing(source_fps)?;
277+ let (tl_scale, tl_ticks) = crate::mux::frame_timing(timeline_fps)?;
278+ // fps is scale/ticks, so the ratio is (src_scale/src_ticks) / (tl_scale/tl_ticks).
279+ let num = u64::from(src_scale) * u64::from(tl_ticks);
280+ let den = u64::from(src_ticks) * u64::from(tl_scale);
281+ let g = gcd(num, den);
282+ let (mut num, mut den) = (num / g, den / g);
283+ // A ratio no pair of real frame rates produces, but the fields are `u32`
284+ // so that every multiplication below fits a `u64` at any frame count.
285+ while num > u64::from(u32::MAX) || den > u64::from(u32::MAX) {
286+ (num, den) = (num.div_ceil(2), den.div_ceil(2));
287+ }
288+ Ok(Self {
289+ source: num.max(1) as u32,
290+ timeline: den.max(1) as u32,
291+ })
292+ }
293+
294+ pub fn is_real_time(self) -> bool {
295+ self.source == self.timeline
296+ }
297+
298+ /// As a multiplier of the timeline's rate: what a *file's* own frame rate
299+ /// is, given the timeline's, for a library row that names it.
300+ pub fn as_f64(self) -> f64 {
301+ f64::from(self.source) / f64::from(self.timeline)
302+ }
303+
304+ /// Which frame of the file the `frame`th timeline-rate frame of it is:
305+ /// floored, [`Speed::source_at`]'s half of the pair.
306+ pub fn source_at(self, frame: u32) -> u32 {
307+ (u64::from(frame) * u64::from(self.source) / u64::from(self.timeline))
308+ .min(u64::from(u32::MAX)) as u32
309+ }
310+
311+ /// Its inverse, ceiled ([`Speed::timeline_at`]'s half): the first
312+ /// timeline-rate frame that shows source frame `source_frame` -- which is
313+ /// the stamp playback puts on a decoded picture, and, applied to a file's
314+ /// frame *count*, how long that file is in timeline frames.
315+ pub fn timeline_at(self, source_frame: u32) -> u32 {
316+ (u64::from(source_frame) * u64::from(self.timeline))
317+ .div_ceil(u64::from(self.source))
318+ .min(u64::from(u32::MAX)) as u32
319+ }
320+}
321+
322+/// Greatest common divisor, for reducing a [`Rate`] to the numbers that fit its
323+/// fields. `a` for `gcd(a, 0)`, and never zero: something divides by it.
324+fn gcd(a: u64, b: u64) -> u64 {
325+ match b {
326+ 0 => a.max(1),
327+ b => gcd(b, a % b),
328+ }
329+}
330+
224 /// A half-open `[in_frame, out_frame)` range of frames of source331 /// A half-open `[in_frame, out_frame)` range of frames of source
225 /// [`source`](Clip::source), placed at timeline frame [`start`](Clip::start).332 /// [`source`](Clip::source), placed at timeline frame [`start`](Clip::start).
226 /// Never empty.333 /// Never empty.
334+///
335+/// Counted at the **timeline's** frame rate, not the file's: a source shot at
336+/// another rate is converted at the decoder's door ([`Rate`]), so every edit
337+/// here is frames of one clock.
227 #[derive(Clone, Copy, PartialEq, Eq, Debug)]338 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
228 pub struct Clip {339 pub struct Clip {
229 /// Timeline frame the clip's first frame is shown at. Meaningless on a340 /// Timeline frame the clip's first frame is shown at. Meaningless on a
@@ -4557,6 +4668,87 @@ mod tests {
4557 assert_eq!(Speed::from_permille(2500).to_string(), "2.50x");4668 assert_eq!(Speed::from_permille(2500).to_string(), "2.50x");
4558 }4669 }
4559 4670
4671+ /// [`Rate`] is [`Speed`]'s pair again, over the *file's* rate: the frame an
4672+ /// export encodes at a timeline frame is the one playback is holding there,
4673+ /// a file is as long in timeline frames as the seconds it lasts, and the two
4674+ /// compose so a speeded clip at another rate is exactly both.
4675+ #[test]
4676+ fn rate_composes_with_speed() {
4677+ // 23.976 into 30 (the ratio that does not terminate), 30 into 23.976,
4678+ // 60 into 30, 25 into 30 -- and the timeline's own rate, which must be
4679+ // the identity map or a single-rate project would move.
4680+ for (source_fps, timeline_fps) in [
4681+ (24000. / 1001., 30.),
4682+ (30., 24000. / 1001.),
4683+ (60., 30.),
4684+ (25., 30.),
4685+ (30., 30.),
4686+ ] {
4687+ let rate = Rate::from_fps(source_fps, timeline_fps).expect("a nameable rate");
4688+ for n in 0..2000u32 {
4689+ let source = rate.source_at(n);
4690+ // The stamp is the *first* timeline-rate frame that shows it, so
4691+ // the picture on screen at `n` is the picture encoded at `n`.
4692+ let held = (0..=source + 4)
4693+ .filter(|&s| rate.timeline_at(s) <= n)
4694+ .next_back();
4695+ assert_eq!(held, Some(source), "{source_fps} on {timeline_fps} at {n}");
4696+ }
4697+ // A file of `count` frames is `timeline_at(count)` frames long here,
4698+ // and its last one still reads a frame the file has.
4699+ for count in 1..500u32 {
4700+ let frames = rate.timeline_at(count);
4701+ assert!(frames >= 1, "a file is never zero frames long");
4702+ assert!(
4703+ rate.source_at(frames - 1) < count,
4704+ "{source_fps} on {timeline_fps}: {count} frames reads past the file"
4705+ );
4706+ }
4707+ // No drift: the mapping is one exact division of the *rate itself*,
4708+ // not an accumulation and not a rounded rate, so an hour in is as
4709+ // true as the first second. (Held to the real ratio of the two rates
4710+ // the caller asked for -- `as_f64` would be true of a wrong rate.)
4711+ for n in [1u32, 100, 10_000, 500_000, 3_000_000] {
4712+ let want = f64::from(n) * source_fps / timeline_fps;
4713+ assert!(
4714+ (f64::from(rate.source_at(n)) - want).abs() < 1.,
4715+ "{source_fps} on {timeline_fps}: frame {n} drifted"
4716+ );
4717+ }
4718+ }
4719+ // The timeline's own rate is the identity, whichever way it is written.
4720+ assert!(Rate::from_fps(30., 30.).expect("30 over 30").is_real_time());
4721+ assert!(
4722+ Rate::from_fps(30.0004, 30.)
4723+ .expect("30.0004 over 30")
4724+ .is_real_time(),
4725+ "a rate is named by the muxer's timescales, and 30.0004 is 30030/1001"
4726+ );
4727+ // ...and a rate no timescale can name is an `Err`, not a silent 1:1: the
4728+ // one thing `matches_timeline` refuses a file for now that the rate gate
4729+ // is gone.
4730+ assert!(Rate::from_fps(0., 30.).is_err(), "not a rate at all");
4731+ assert!(Rate::from_fps(30., f64::NAN).is_err());
4732+ for n in 0..1000 {
4733+ assert_eq!(Rate::REAL_TIME.source_at(n), n);
4734+ assert_eq!(Rate::REAL_TIME.timeline_at(n), n);
4735+ }
4736+ // ...and the composition, in the order the decoder's door applies it:
4737+ // the speed picks the clip's (timeline-rate) frame, the rate picks the
4738+ // file's. A 2x clip of a 23.976 fps file on a 30 fps timeline reads two
4739+ // timeline frames per frame shown, each of them exactly 800/1001 of a
4740+ // file frame.
4741+ let rate = Rate::from_fps(24000. / 1001., 30.).expect("23.976 over 30");
4742+ let speed = Speed::from_permille(2000);
4743+ for d in 0..100u32 {
4744+ assert_eq!(
4745+ rate.source_at(speed.source_at(d)),
4746+ (u64::from(d) * 2 * 800 / 1001) as u32,
4747+ "2x of a 23.976 fps file at timeline frame {d}"
4748+ );
4749+ }
4750+ }
4751+
4560 /// The mapping a speed changes, and the one it does not: a 2x clip reads two4752 /// The mapping a speed changes, and the one it does not: a 2x clip reads two
4561 /// source frames per timeline frame and still starts at its own in-point,4753 /// source frames per timeline frame and still starts at its own in-point,
4562 /// and a half-speed one shows every source frame twice.4754 /// and a half-speed one shows every source frame twice.
crates/engine/tests/audio_files.rsmodified+9 -8
@@ -386,20 +386,21 @@ fn a_video_joins_a_timeline_a_song_started() {
386 import_and_place(&mut session, &asset("test_av.mp4"));386 import_and_place(&mut session, &asset("test_av.mp4"));
387 assert_eq!(session.lane_clips(Lane::V1).len(), 1, "a picture at last");387 assert_eq!(session.lane_clips(Lane::V1).len(), 1, "a picture at last");
388 assert_eq!(session.lane_clips(Lane::A1).len(), 2);388 assert_eq!(session.lane_clips(Lane::A1).len(), 2);
389- // And a file at another rate is refused in the timeline's own words rather389+ // A sample rate the device cannot have two of is still refused in the
390- // than silently retiming the song already on the lane -- the sample rate at390+ // timeline's own words...
391- // one door, the *frame* rate at the other: the canvas a song scaffolds has
392- // a frame rate of its own (30 fps), and a 25 fps picture cannot join it.
393 let e = refusal(session.import(&asset("test_tone_48k.wav")));391 let e = refusal(session.import(&asset("test_tone_48k.wav")));
394 assert_eq!(392 assert_eq!(
395 e,393 e,
396 "audio 48000 Hz 2 ch does not match the timeline's 44100 Hz 2 ch"394 "audio 48000 Hz 2 ch does not match the timeline's 44100 Hz 2 ch"
397 );395 );
398- assert_eq!(
399- refusal(session.import(&asset("test_25fps.mp4"))),
400- "25.000 fps does not match the timeline's 30.000 fps"
401- );
402 assert_eq!(session.sources().len(), 2, "a refusal left a library row");396 assert_eq!(session.sources().len(), 2, "a refusal left a library row");
397+ // ...but a *frame* rate of its own is not a refusal: the canvas a song
398+ // scaffolds runs at 30 fps and a 25 fps picture joins it at the length it
399+ // lasts in seconds (50 frames of file, 60 of timeline).
400+ session
401+ .import(&asset("test_25fps.mp4"))
402+ .expect("25 fps joins the 30 fps canvas a song scaffolded");
403+ assert_eq!(session.file_frames(&asset("test_25fps.mp4")), 60);
403 }404 }
404 405
405 /// Blocks until the export settles, whichever way it settled.406 /// Blocks until the export settles, whichever way it settled.
crates/engine/tests/backends.rsadded+208 -0
@@ -0,0 +1,208 @@
1+//! Which decoder and which encoder a job really runs on -- the introspection a
2+//! front-end shows before an operation and while it runs.
3+//!
4+//! The point of every assertion here is *truthfulness*, not a particular seat:
5+//! this box may or may not have a working plugin, and a test that demanded
6+//! hardware would only be measuring the machine. What must hold is that the
7+//! answer given before an operation is the answer the operation then gives, and
8+//! that neither of them ever names a decoder that could not have run (software
9+//! HEVC, for one, does not exist here).
10+
11+use std::path::PathBuf;
12+use std::time::{Duration, Instant};
13+
14+use engine::Codec;
15+use engine::decode::{Backend, probe};
16+use engine::export::{ExportSettings, Format};
17+use engine::{ExportHandle, PlaybackSession};
18+
19+fn asset(name: &str) -> PathBuf {
20+ PathBuf::from(env!("CARGO_MANIFEST_DIR"))
21+ .join("../../assets")
22+ .join(name)
23+}
24+
25+fn out_path(name: &str, ext: &str) -> PathBuf {
26+ let path = std::env::temp_dir().join(format!("ve_backend_{name}_{}.{ext}", std::process::id()));
27+ let _ = std::fs::remove_file(&path);
28+ let _ = std::fs::remove_file(format!("{}.part", path.display()));
29+ path
30+}
31+
32+/// A still has no coded stream and no decoder to pick, and it must say so
33+/// rather than borrowing the picture path's answer.
34+#[test]
35+fn a_still_probes_as_a_still() {
36+ let (codec, backend) = probe(&asset("test_still.png")).expect("probe the still");
37+ assert_eq!(codec, None, "an image has no coded stream to name");
38+ assert_eq!(backend, Backend::Still);
39+}
40+
41+/// H.264 has both seats, so the probe may legitimately answer either -- but it
42+/// must answer one of them, and it must name the codec.
43+#[test]
44+fn an_h264_source_probes_as_one_of_the_two_seats() {
45+ let (codec, backend) = probe(&asset("test_baseline.mp4")).expect("probe the baseline fixture");
46+ assert_eq!(codec, Some(Codec::H264));
47+ assert!(
48+ matches!(backend, Backend::Hardware | Backend::Software),
49+ "a probe that returned must have picked a seat, got {backend:?}"
50+ );
51+}
52+
53+/// HEVC has no software decoder here at all. A box with the plugin answers
54+/// hardware; a box without it is refused by name -- and *never* told that
55+/// `rusty_h264` will take it, which is the one answer that would be a lie.
56+#[test]
57+fn hevc_probes_as_hardware_or_as_a_refusal() {
58+ match probe(&asset("test_hevc.mkv")) {
59+ Ok((codec, backend)) => {
60+ assert_eq!(codec, Some(Codec::Hevc));
61+ assert_eq!(backend, Backend::Hardware, "there is no software HEVC here");
62+ }
63+ Err(e) => assert!(
64+ e.to_string().contains("plugin"),
65+ "a refusal names the plugin, got {e}"
66+ ),
67+ }
68+}
69+
70+/// The running session reports the decoder its *worker* opened, and it agrees
71+/// with what the probe said before anything played. This is the whole point of
72+/// the cell: the worker writes it where the fallback happens, so a hardware
73+/// session that dropped to software could only be seen here.
74+#[test]
75+fn a_playing_session_reports_the_seat_the_probe_named() {
76+ let path = asset("test_baseline.mp4");
77+ let (_codec, probed) = probe(&path).expect("probe the baseline fixture");
78+ let session = PlaybackSession::open(&path).expect("open the fixture");
79+ let started = Instant::now();
80+ loop {
81+ let live = session.decode_backend();
82+ if live != Backend::Opening {
83+ assert_eq!(live, probed, "the running seat is not the probed one");
84+ break;
85+ }
86+ assert!(
87+ started.elapsed() < Duration::from_secs(20),
88+ "the worker never published a decode backend"
89+ );
90+ std::thread::sleep(Duration::from_millis(10));
91+ }
92+}
93+
94+/// What the export card says before the button and what the progress line says
95+/// during the job are the same two answers, from the same two functions: the
96+/// picture's seat is probed by opening the very encoder the export opens, and
97+/// the sound's is decided outright. A drift between them is a front-end lying
98+/// about the machine, which is exactly what this whole surface is for.
99+///
100+/// Every picture format, because each one is a different pair of seats: H.264
101+/// through `rusty_h264` or the plugin, and AV1 through `rav1e` in either
102+/// container -- a container is not an encoder, and the card must not say it is.
103+#[test]
104+fn the_planned_encoders_are_the_ones_the_job_opens() {
105+ for (format, ext) in [
106+ (Format::Mp4, "mp4"),
107+ (Format::Av1, "mkv"),
108+ (Format::Av1Mp4, "mp4"),
109+ ] {
110+ let settings = ExportSettings {
111+ format,
112+ ..ExportSettings::default()
113+ };
114+ let session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
115+ let planned = format!(
116+ "{} · {}",
117+ engine::export::planned_video(session.meta(), &settings)
118+ .expect("these formats carry picture"),
119+ session.planned_audio(format)
120+ );
121+ let out = out_path("planned", ext);
122+ let handle = session.export_to_with(&out, &settings);
123+ let started = Instant::now();
124+ let opened = loop {
125+ if let Some(line) = handle.encoders() {
126+ break line;
127+ }
128+ assert!(
129+ !handle.is_finished(),
130+ "the export settled before it opened an encoder: {:?}",
131+ handle.result().map(|r| r.err())
132+ );
133+ assert!(
134+ started.elapsed() < Duration::from_secs(60),
135+ "no encoder was published"
136+ );
137+ std::thread::sleep(Duration::from_millis(10));
138+ };
139+ // Nothing here wants the file, only the seat it was going to be written
140+ // with: cancelling deletes the `.part` the worker had started.
141+ handle.cancel();
142+ wind_down(&handle);
143+ assert_eq!(opened, planned, "{ext}");
144+ // ...and the sound is named on both, AV1 included: an AV1 export
145+ // carries the timeline's audio now, so a line that said nothing about
146+ // it would be the old picture-only lie in a new place.
147+ assert!(planned.contains("AAC"), "{ext}: {planned}");
148+ }
149+}
150+
151+/// A WAV job has no picture at all and still names what writes it, so an audio
152+/// export is not a progress line with nothing to say.
153+#[test]
154+fn an_audio_only_job_names_its_encoder() {
155+ for format in [Format::Wav, Format::Flac, Format::Mp3] {
156+ audio_only_job_names_its_encoder(format);
157+ }
158+}
159+
160+fn audio_only_job_names_its_encoder(format: Format) {
161+ let settings = ExportSettings {
162+ format,
163+ ..ExportSettings::default()
164+ };
165+ assert_eq!(
166+ engine::export::planned_video(
167+ &engine::demux::Demuxer::open(&asset("test_av.mp4"))
168+ .expect("open the fixture")
169+ .0,
170+ &settings
171+ ),
172+ None,
173+ "an audio-only format has no video seat to name"
174+ );
175+ let session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
176+ let planned = session.planned_audio(format);
177+ let out = out_path("audio", format.ext());
178+ let handle = session.export_to_with(&out, &settings);
179+ let started = Instant::now();
180+ let opened = loop {
181+ if let Some(line) = handle.encoders() {
182+ break line;
183+ }
184+ assert!(
185+ started.elapsed() < Duration::from_secs(60),
186+ "no encoder was published"
187+ );
188+ std::thread::sleep(Duration::from_millis(10));
189+ };
190+ handle.cancel();
191+ wind_down(&handle);
192+ let _ = std::fs::remove_file(&out);
193+ assert_eq!(opened, planned, "{}", format.ext());
194+}
195+
196+/// Waits for a cancelled job to settle, so its `.part` is gone before the test
197+/// ends -- and so no worker outlives the process holding a VA-API session.
198+fn wind_down(handle: &ExportHandle) {
199+ let started = Instant::now();
200+ while !handle.is_finished() {
201+ assert!(
202+ started.elapsed() < Duration::from_secs(60),
203+ "a cancelled export did not settle"
204+ );
205+ std::thread::sleep(Duration::from_millis(10));
206+ }
207+ let _ = handle.result();
208+}
crates/engine/tests/mixed_fps.rsadded+419 -0
@@ -0,0 +1,419 @@
1+//! Clips shot at other frame rates on one timeline: what a 25 fps and a 23.976
2+//! fps file do on the 30 fps timeline `test_av.mp4` scaffolds.
3+//!
4+//! Everything goes through the front door -- `import`, `place_stream_at`,
5+//! `seek`, `export_to_with`, `open_project` -- because the whole claim is that a
6+//! *user* can put two rates on one timeline and watch both at the speed they
7+//! were shot at. `project.rs`'s own `rate_composes_with_speed` owns the
8+//! arithmetic; what is measured here is that the pictures and the file agree
9+//! with it.
10+//!
11+//! ```text
12+//! cargo test -p engine --test mixed_fps
13+//! ```
14+
15+use std::path::{Path, PathBuf};
16+use std::thread::sleep;
17+use std::time::{Duration, Instant};
18+
19+use engine::export::{ExportSettings, Format};
20+use engine::project::{Edge, Lane, Rate, Speed};
21+use engine::{DecodeSession, Frame, PlaybackSession};
22+
23+/// The timeline's rate, which `test_av.mp4` (30 fps, 5 s) defines.
24+const FPS: f64 = 30.0;
25+
26+fn asset(name: &str) -> PathBuf {
27+ PathBuf::from(env!("CARGO_MANIFEST_DIR"))
28+ .join("../../assets")
29+ .join(name)
30+}
31+
32+/// Silent, for `tests/playback.rs`'s reason: the suite plays real files.
33+fn open(path: impl AsRef<Path>) -> PlaybackSession {
34+ let session = PlaybackSession::open(path).expect("open");
35+ session.set_gain(0.0);
36+ session
37+}
38+
39+fn next_frame(session: &mut PlaybackSession, what: &str) -> Frame {
40+ let deadline = Instant::now() + Duration::from_secs(10);
41+ loop {
42+ if let Some(frame) = session.try_frame() {
43+ return frame;
44+ }
45+ assert!(Instant::now() < deadline, "no frame after {what}");
46+ sleep(Duration::from_millis(4));
47+ }
48+}
49+
50+/// One frame of a file, decoded straight from it: the picture a mapping is
51+/// checked against, in the file's *own* numbering.
52+fn source_frame(path: &Path, index: u32) -> Vec<u8> {
53+ let (_, rx, _cancel) = DecodeSession::open_range(path, index, index + 1).expect("open_range");
54+ let frame = rx
55+ .recv_timeout(Duration::from_secs(10))
56+ .expect("reference frame");
57+ assert_eq!(frame.index, index, "open_range starts where it is told");
58+ frame.bgra
59+}
60+
61+/// Imports `path` and drags it onto the end of the timeline, the way a library
62+/// row reaches a lane.
63+fn import_and_place(session: &mut PlaybackSession, path: &Path) {
64+ session.import(path).expect("the file joins this timeline");
65+ let end = session.timeline_duration();
66+ assert!(
67+ session
68+ .place_stream_at(end, path, 0, None)
69+ .expect("a file just imported is on this timeline"),
70+ "the drag onto the end of the timeline"
71+ );
72+}
73+
74+fn wait(handle: &engine::ExportHandle) -> engine::Result<()> {
75+ let deadline = Instant::now() + Duration::from_secs(180);
76+ while !handle.is_finished() {
77+ assert!(Instant::now() < deadline, "export did not finish");
78+ sleep(Duration::from_millis(20));
79+ }
80+ handle.result().expect("a finished export has an outcome")
81+}
82+
83+/// How different two pictures are, sampled: a re-encode moves every pixel a
84+/// little and a *different* picture of `testsrc2` moves them a lot, so the two
85+/// are never close to the threshold below.
86+fn difference(a: &[u8], b: &[u8]) -> f64 {
87+ assert_eq!(a.len(), b.len(), "two pictures of one size");
88+ let (mut sum, mut n) = (0f64, 0u32);
89+ for i in (0..a.len()).step_by(997) {
90+ sum += f64::from(a[i].abs_diff(b[i]));
91+ n += 1;
92+ }
93+ sum / f64::from(n.max(1))
94+}
95+
96+/// A file's length is the seconds it lasts, in the timeline's frames -- not the
97+/// frames it holds. That is the whole of what placing another rate means: 50
98+/// frames of 25 fps and 48 of 23.976 fps are both two seconds, and two seconds
99+/// of a 30 fps timeline is 60 frames.
100+#[test]
101+fn a_file_at_another_rate_is_placed_for_the_seconds_it_lasts() {
102+ let mut session = open(asset("test_av.mp4"));
103+ assert_eq!(session.file_frames(&asset("test_av.mp4")), 150, "5 s at 30");
104+
105+ let pal = asset("test_25fps.mp4");
106+ session
107+ .import(&pal)
108+ .expect("25 fps joins a 30 fps timeline");
109+ assert_eq!(session.file_frames(&pal), 60, "50 frames at 25 fps is 2 s");
110+
111+ // 24000/1001: 48 frames is 2.002 s, which is 60.06 frames of 30 fps --
112+ // rounded *up*, so the last picture is still reachable by a trim.
113+ let ntsc = asset("test_23976fps.mp4");
114+ session.import(&ntsc).expect("23.976 joins it too");
115+ assert_eq!(session.file_frames(&ntsc), 61);
116+
117+ // ...and placed, both are as long on the timeline as they are in the ear.
118+ let end = session.timeline_duration();
119+ session
120+ .place_stream_at(end, &pal, 0, None)
121+ .expect("the drag");
122+ assert!(
123+ (session.timeline_duration() - (5.0 + 2.0)).abs() < 1e-9,
124+ "a 2 s clip made the timeline {} s",
125+ session.timeline_duration()
126+ );
127+ let end = session.timeline_duration();
128+ session
129+ .place_stream_at(end, &ntsc, 0, None)
130+ .expect("the drag");
131+ assert!(
132+ (session.timeline_duration() - (5.0 + 2.0 + 61. / FPS)).abs() < 1e-9,
133+ "{} s",
134+ session.timeline_duration()
135+ );
136+ // ...and the sound that came down with each take is the same length as its
137+ // picture: a placed take is one linked group, so a rate that stretched only
138+ // the picture would slide the two apart on the very first drag.
139+ let (video, audio) = (session.lane_clips(Lane::V1), session.lane_clips(Lane::A1));
140+ assert_eq!(video.len(), 3, "the 30 fps take and the two others");
141+ assert_eq!(audio.len(), video.len(), "one audio clip per take");
142+ for (v, a) in video.iter().zip(audio) {
143+ assert_eq!((v.start, v.len()), (a.start, a.len()), "{v:?} vs {a:?}");
144+ }
145+}
146+
147+/// The NTSC ratio, which the 23.976 fps fixture is shot at: 24000/1001 over 30
148+/// is exactly 800/1001, and it stays exact however far the timeline runs. A rate
149+/// rounded to a float -- or to milli-fps -- would leave a fraction of a frame
150+/// per clip to pile up into a visible drift over an hour, which is why the
151+/// mapping is built out of the muxer's own timescales and not a division.
152+#[test]
153+fn a_23_976_rate_is_exact_and_never_drifts() {
154+ let ntsc = Rate::from_fps(24_000.0 / 1001.0, FPS).expect("23.976 over 30");
155+ assert!(
156+ (ntsc.as_f64() - 800.0 / 1001.0).abs() < 1e-15,
157+ "{}",
158+ ntsc.as_f64()
159+ );
160+ // Independent integer arithmetic, out to an hour of source and past it: 800
161+ // source frames per 1001 timeline ones, and a file's length is that ceiled
162+ // (the last picture must still be reachable by a trim).
163+ for source in [1u64, 2, 24, 1000, 86_486, 500_000, 1_000_000] {
164+ assert_eq!(
165+ u64::from(ntsc.timeline_at(source as u32)),
166+ (source * 1001).div_ceil(800),
167+ "{source} source frames"
168+ );
169+ }
170+ // ...and the two directions stay each other's inverse at every one of them:
171+ // the frame an export writes at timeline frame `d` is the frame playback is
172+ // holding there, which is what `timeline_at`'s ceil buys.
173+ for d in [0u32, 1, 2, 3, 1000, 100_000, 1_000_000] {
174+ let source = ntsc.source_at(d);
175+ assert!(ntsc.timeline_at(source) <= d, "frame {d} is not yet due");
176+ assert!(
177+ ntsc.timeline_at(source + 1) > d,
178+ "the next frame is due too early at {d}"
179+ );
180+ }
181+ // A timeline's own rate conforms by nothing at all, exactly -- whichever of
182+ // the two rates it is written at.
183+ assert!(Rate::from_fps(FPS, FPS).expect("30 over 30").is_real_time());
184+ assert!(
185+ Rate::from_fps(24_000.0 / 1001.0, 24_000.0 / 1001.0)
186+ .expect("ntsc over ntsc")
187+ .is_real_time()
188+ );
189+ // A rate no timescale can name is refused rather than read 1:1 in silence:
190+ // the one thing `matches_timeline` still turns a file away for.
191+ assert!(Rate::from_fps(0.0, FPS).is_err(), "not a rate at all");
192+}
193+
194+/// The picture on screen at a timeline frame is the picture the *file* holds
195+/// there: frame `floor(offset * 25/30)` of a 25 fps clip, which is what playing
196+/// at the speed it was shot at means, frame for frame.
197+#[test]
198+fn playback_shows_the_frame_the_file_holds_there() {
199+ let pal = asset("test_25fps.mp4");
200+ let mut session = open(asset("test_av.mp4"));
201+ import_and_place(&mut session, &pal);
202+ session.pause();
203+ // The clip starts at timeline frame 150 (5 s) and runs 60 frames.
204+ let start = 150u32;
205+ for offset in [0u32, 1, 5, 6, 29, 30, 47, 59] {
206+ let at = start + offset;
207+ session.seek(f64::from(at) / FPS);
208+ let landed = next_frame(&mut session, "a seek into the 25 fps clip");
209+ assert_eq!(landed.index, at, "a seek lands on the frame it asked for");
210+ let want = (u64::from(offset) * 25_000 / 30_000) as u32;
211+ assert!(
212+ landed.bgra == source_frame(&pal, want),
213+ "timeline frame {at} (offset {offset}) is not source frame {want}"
214+ );
215+ }
216+ // Past the last picture the file holds, the clip is still on the timeline:
217+ // its last frame is shown, not black and not a panic.
218+ session.seek(f64::from(start + 59) / FPS);
219+ let last = next_frame(&mut session, "the last frame of the clip");
220+ assert!(last.bgra == source_frame(&pal, 49), "source frame 49 last");
221+ // ...and the frame in front of it is the 30 fps take, frame for frame: a
222+ // rate belongs to the source that has one, so the clip beside it is read
223+ // exactly as it was before any of this existed.
224+ let av = asset("test_av.mp4");
225+ session.seek(f64::from(start - 1) / FPS);
226+ let before = next_frame(&mut session, "the last frame of the 30 fps take");
227+ assert_eq!(before.index, start - 1);
228+ assert!(
229+ before.bgra == source_frame(&av, start - 1),
230+ "the 30 fps clip is still frame for frame"
231+ );
232+}
233+
234+/// A trim of a clip at another rate is dragged in *timeline* frames and commits
235+/// the source range those frames are worth -- so the box is exactly the room it
236+/// was dragged to, and the picture at its new edge is the file's own frame
237+/// there.
238+#[test]
239+fn a_clip_at_another_rate_trims_to_the_room_it_was_dragged_to() {
240+ let pal = asset("test_25fps.mp4");
241+ let mut session = open(asset("test_av.mp4"));
242+ import_and_place(&mut session, &pal);
243+ session.pause();
244+ let start = 150u32;
245+ // Drag its tail back to 30 timeline frames of room: one second, which at 25
246+ // fps is the file's first 25 pictures.
247+ assert!(
248+ session.trim_clip(Lane::V1, 1, Edge::End, start + 30),
249+ "trim the tail of the 25 fps clip"
250+ );
251+ let clip = session.lane_clips(Lane::V1)[1];
252+ assert_eq!((clip.start, clip.len()), (start, 30), "{clip:?}");
253+ session.seek(f64::from(start + 29) / FPS);
254+ let last = next_frame(&mut session, "the trimmed tail");
255+ assert!(
256+ last.bgra == source_frame(&pal, 24),
257+ "one second of a 25 fps file ends on its frame 24"
258+ );
259+ // ...and its head, dragged forward into source it keeps: 6 timeline frames
260+ // in is 5 source frames in, and the tail did not move.
261+ assert!(session.trim_clip(Lane::V1, 1, Edge::Start, start + 6));
262+ let clip = session.lane_clips(Lane::V1)[1];
263+ assert_eq!((clip.start, clip.len()), (start + 6, 24), "{clip:?}");
264+ session.seek(f64::from(start + 6) / FPS);
265+ let head = next_frame(&mut session, "the trimmed head");
266+ assert!(
267+ head.bgra == source_frame(&pal, 5),
268+ "6 frames of a 30 fps timeline is 5 frames of a 25 fps file"
269+ );
270+}
271+
272+/// A speed and a frame rate compose: a 2x 25 fps clip on a 30 fps timeline is
273+/// half as many timeline frames and reads twice as far into the file for each
274+/// of them.
275+#[test]
276+fn a_speeded_clip_at_another_rate_is_exactly_both() {
277+ let pal = asset("test_25fps.mp4");
278+ let mut session = open(asset("test_av.mp4"));
279+ import_and_place(&mut session, &pal);
280+ session
281+ .set_speed(Lane::V1, 1, Speed::from_permille(2000))
282+ .expect("nothing is in the way of a clip that got shorter");
283+ session.pause();
284+ let start = 150u32;
285+ assert!(
286+ (session.timeline_duration() - (5.0 + 1.0)).abs() < 1e-9,
287+ "2 s at 2x is 1 s: {}",
288+ session.timeline_duration()
289+ );
290+ for offset in [0u32, 3, 14, 29] {
291+ let at = start + offset;
292+ session.seek(f64::from(at) / FPS);
293+ let landed = next_frame(&mut session, "a seek into the speeded clip");
294+ assert_eq!(landed.index, at);
295+ // The speed picks the clip's (timeline-rate) frame, the rate picks the
296+ // file's -- in that order, which is the order the decoder's door
297+ // applies them.
298+ let want = (u64::from(offset) * 2 * 25_000 / 30_000) as u32;
299+ assert!(
300+ landed.bgra == source_frame(&pal, want),
301+ "2x at offset {offset} is not source frame {want}"
302+ );
303+ }
304+}
305+
306+/// A saved project reloads at the same lengths: `open_project` recomputes every
307+/// source's rate from the file, so a mixed-rate timeline is not one that only
308+/// the session that built it could hold.
309+#[test]
310+fn a_mixed_rate_project_reloads_unchanged() {
311+ let pal = asset("test_25fps.mp4");
312+ let mut session = open(asset("test_av.mp4"));
313+ import_and_place(&mut session, &pal);
314+ let duration = session.timeline_duration();
315+ let spans = session.clip_spans();
316+ let path = std::env::temp_dir().join(format!("edith-mixed-{}.edith", std::process::id()));
317+ session.save_project(&path).expect("save");
318+
319+ let reloaded = PlaybackSession::open_project(&path).expect("a mixed-rate project reopens");
320+ assert_eq!(reloaded.clip_spans(), spans, "the same clips, in seconds");
321+ assert!((reloaded.timeline_duration() - duration).abs() < 1e-9);
322+ assert_eq!(reloaded.file_frames(&pal), 60, "the length was recomputed");
323+ std::fs::remove_file(&path).ok();
324+}
325+
326+/// The export is what was watched: as many frames as the timeline has, and the
327+/// 25 fps clip walked through its file at 25 fps -- 25 pictures over 30 frames,
328+/// not 30 of them and not 25 held to the end.
329+#[test]
330+fn an_export_of_two_rates_runs_at_the_speed_it_was_shot() {
331+ let pal = asset("test_25fps.mp4");
332+ let mut session = open(asset("test_av.mp4"));
333+ // A short head of the 30 fps take, then the whole of the 25 fps one --
334+ // enough of each to be a mixed timeline, short enough to encode in a test.
335+ // The sound comes with it: a placed take is one linked group.
336+ assert!(
337+ session.trim_clip(Lane::V1, 0, Edge::End, 15),
338+ "trim the 30 fps take to half a second"
339+ );
340+ import_and_place(&mut session, &pal);
341+ assert!(
342+ session.trim_clip(Lane::V1, 1, Edge::End, 45),
343+ "one second of the 25 fps clip"
344+ );
345+ let total = (session.timeline_duration() * FPS).round() as u32;
346+ assert_eq!(total, 45, "15 frames of 30 fps and 30 of the 25 fps clip");
347+
348+ let out = std::env::temp_dir().join(format!("edith-mixed-{}.mp4", std::process::id()));
349+ wait(&session.export_to_with(
350+ &out,
351+ &ExportSettings {
352+ format: Format::Mp4,
353+ ..ExportSettings::default()
354+ },
355+ ))
356+ .expect("the export");
357+
358+ // Duration first: the file is as long as the timeline, so the mixed rates
359+ // did not stretch or shorten it.
360+ let (meta, rx, _cancel) = DecodeSession::open_range(&out, 0, u32::MAX).expect("reopen");
361+ assert!(
362+ (meta.frame_rate - FPS).abs() < 0.01,
363+ "the export runs at the timeline's rate: {}",
364+ meta.frame_rate
365+ );
366+ assert_eq!(
367+ meta.frame_count, total,
368+ "the export is the timeline's length"
369+ );
370+ let written: Vec<Vec<u8>> = rx.into_iter().map(|frame| frame.bgra).collect();
371+ assert_eq!(written.len() as u32, total, "every frame came back");
372+
373+ // ...and motion: inside the 25 fps clip, 30 exported frames show 25
374+ // pictures, so 5 of them are a picture held from the frame before. A clip
375+ // played at the wrong rate would hold none (too fast, and it would run out
376+ // of file) or hold half of them (too slow).
377+ let held = (16..total as usize)
378+ .filter(|&i| difference(&written[i - 1], &written[i]) < 2.0)
379+ .count();
380+ assert_eq!(
381+ held, 5,
382+ "30 timeline frames of a 25 fps clip hold 5 pictures over"
383+ );
384+
385+ // ...and *which* picture each of those frames is: the very one playback
386+ // holds there, which is the whole reason the two conversions are one
387+ // floor/ceil pair. Nearer its own source frame than either neighbour rather
388+ // than equal to it -- the export is re-encoded, so no pixel survives whole.
389+ for offset in [0u32, 1, 6, 12, 24, 29] {
390+ let want = (u64::from(offset) * 25_000 / 30_000) as u32;
391+ let mine = difference(&written[(15 + offset) as usize], &source_frame(&pal, want));
392+ for other in [want.saturating_sub(1), want + 1] {
393+ if other == want {
394+ continue;
395+ }
396+ assert!(
397+ mine < difference(&written[(15 + offset) as usize], &source_frame(&pal, other)),
398+ "exported frame {offset} of the 25 fps clip is nearer source \
399+ frame {other} than its own {want}"
400+ );
401+ }
402+ }
403+
404+ // The sound came out as long as the picture, from a *packet copy*: a clip
405+ // counts timeline frames whatever its file was shot at, so the window this
406+ // export trimmed the 25 fps file's AAC to is whole timeline frames and the
407+ // copy is in sync. This is the assertion behind the note in
408+ // `export::copy_audio` that says not to turn a conformed lane into a
409+ // re-encode.
410+ let secs = engine::AudioSession::duration_secs(&out)
411+ .expect("probe the export")
412+ .expect("the export has sound");
413+ let want = f64::from(total) / FPS;
414+ assert!(
415+ (secs - want).abs() < 0.05,
416+ "sound is {secs} s under {want} s of picture"
417+ );
418+ std::fs::remove_file(&out).ok();
419+}
crates/engine/tests/playback.rsmodified+8 -7
@@ -813,14 +813,15 @@ fn import_refuses_what_does_not_match() {
813 "a resolution of its own is not a refusal any more: {err}"813 "a resolution of its own is not a refusal any more: {err}"
814 );814 );
815 815
816- // Same codec, same audio, 25 fps: the one property left, named with both816+ // A frame rate of its own is no longer a refusal either: 25 fps joins a
817- // rates. Mixing rates would mean retiming the timeline itself, and there is817+ // 30 fps timeline and is read at `Rate` against it -- see
818- // no resampler for that, so the refusal is the honest answer.818+ // `tests/mixed_fps.rs` for what it then plays like.
819- let err = session819+ session
820 .import(&asset("test_25fps.mp4"))820 .import(&asset("test_25fps.mp4"))
821- .expect_err("25 fps must not join a 30 fps timeline")821+ .expect("25 fps may join a 30 fps timeline");
822- .to_string();822+ session
823- assert_eq!(err, "25.000 fps does not match the timeline's 30.000 fps");823+ .remove_source(&asset("test_25fps.mp4"), 0)
824+ .expect("...and the row it made comes back off");
824 825
825 // Same size and rate, no audio track: the timeline has one.826 // Same size and rate, no audio track: the timeline has one.
826 let err = session827 let err = session
scripts/gen_fixtures.shmodified+11 -3
@@ -161,15 +161,23 @@ enable='between(t,1,1.1)'[v];\
161 ffmpeg -y -f lavfi -i testsrc2=size=640x360:rate=30:duration=2 \161 ffmpeg -y -f lavfi -i testsrc2=size=640x360:rate=30:duration=2 \
162 -an -c:v libx264 -profile:v baseline -pix_fmt yuv420p assets/test_mismatch.mp4162 -an -c:v libx264 -profile:v baseline -pix_fmt yuv420p assets/test_mismatch.mp4
163 # Frame-rate fixture: test_av.mp4 in every respect a timeline is held to -- same163 # Frame-rate fixture: test_av.mp4 in every respect a timeline is held to -- same
164-# codec, same profile, same 44.1k stereo AAC -- except that it runs at 25 fps.164+# codec, same profile, same 44.1k stereo AAC -- except that it runs at 25 fps,
165-# The only thing left for an import to refuse is the rate, which is what makes165+# so a timeline of 30 fps clips has one at another rate to read through `Rate`.
166-# the refusal's wording testable.
167 ffmpeg -y -f lavfi -i testsrc2=size=1280x720:rate=25:duration=2 \166 ffmpeg -y -f lavfi -i testsrc2=size=1280x720:rate=25:duration=2 \
168 -f lavfi -i "sine=frequency=440:duration=2" \167 -f lavfi -i "sine=frequency=440:duration=2" \
169 -f lavfi -i "sine=frequency=880:duration=2" \168 -f lavfi -i "sine=frequency=880:duration=2" \
170 -filter_complex "[1:a][2:a]join=inputs=2:channel_layout=stereo,volume='0.5+0.5*sin(2*PI*t)':eval=frame[a]" \169 -filter_complex "[1:a][2:a]join=inputs=2:channel_layout=stereo,volume='0.5+0.5*sin(2*PI*t)':eval=frame[a]" \
171 -map 0:v -map "[a]" -c:v libx264 -profile:v baseline -pix_fmt yuv420p \170 -map 0:v -map "[a]" -c:v libx264 -profile:v baseline -pix_fmt yuv420p \
172 -c:a aac -b:a 128k assets/test_25fps.mp4171 -c:a aac -b:a 128k assets/test_25fps.mp4
172+# ...and the same again at 23.976 fps (24000/1001), the rate whose ratio to a
173+# 30 fps timeline does not terminate: what the frame mapping's rounding is
174+# actually tested against.
175+ffmpeg -y -f lavfi -i testsrc2=size=1280x720:rate=24000/1001:duration=2 \
176+ -f lavfi -i "sine=frequency=440:duration=2" \
177+ -f lavfi -i "sine=frequency=880:duration=2" \
178+ -filter_complex "[1:a][2:a]join=inputs=2:channel_layout=stereo,volume='0.5+0.5*sin(2*PI*t)':eval=frame[a]" \
179+ -map 0:v -map "[a]" -c:v libx264 -profile:v baseline -pix_fmt yuv420p \
180+ -c:a aac -b:a 128k assets/test_23976fps.mp4
173 # Standalone audio fixtures: the same 440/880 Hz tone with the 1 Hz pulse the181 # Standalone audio fixtures: the same 440/880 Hz tone with the 1 Hz pulse the
174 # A/V fixture carries, at test_av.mp4's own 44.1k stereo -- so an imported song182 # A/V fixture carries, at test_av.mp4's own 44.1k stereo -- so an imported song
175 # can share a timeline with the video clips and the peaks tests can reuse the183 # can share a timeline with the video clips and the peaks tests can reuse the