forge
Explore
Log in

Don't you dare go Hollow

AV1 comes back out, in a Matroska file this editor reopens

Browse files at this commit

dd3a2a84d4ac1c4831854d14faf1be20db7a8ffdAhmet Kaan GümüşParent: 5f60e19
  • feat
    • AV1 comes back out, in a Matroska file this editor reopens
Show full message
✨ feat(export): AV1 comes back out, in a Matroska file this editor reopens

The export card's second picture format. AV1 already *arrives* here as
Matroska (`mp4 0.14` has no `av01` sample entry at all, so `demux` walks
the EBML by hand); it now leaves the same way, through an `MkvMuxer`
written beside the mp4 one -- EBML header, `Info`, one `V_AV1` track whose
`CodecPrivate` is a real `av1C` record built from the first keyframe's
sequence header OBU, then clusters that open on every keyframe. The
segment size and the duration are the only two fields patched at `finish`.
Matroska rather than AV1-in-mp4 because the reader for it already exists:
the round trip closes against this project's own `Demuxer`.

Picture only, and said so on the row before a destination is picked ("AV1
picture in .mkv — no sound: export WAV or FLAC for that"). Matroska
carries no sound this project can *write* -- no AAC or Opus encoder here
-- and an AAC track copied in would be one this engine's own reader leaves
silent (`AudioSession::open` refuses Matroska audio). A silent track
written anyway is the one failure a user would not notice.

The encoder pair mirrors H.264's: `rav1e` in software, the plugin's new
`vh_enc_av1_open` on the GPU. The hardware seat is wired, tested and
**opt-in** (`VE_HW_AV1=1`): the vendored cros-codecs AV1 encoder took the
radeonsi box this was written on into an amdgpu hard recovery, and a
driver reset is not an export. `rav1e` is not a new dependency at all --
`ravif` already locks the same 0.8.1 -- and is built with `asm` off (no
`nasm` in this build) and `threading` on: 39 s for the 5 s 720p fixture,
progress reported the whole way.

HEVC and VP9 are rows too, refused by name: no encoder in this stack and
patent-encumbered, and superseded by the AV1 row above.
Cargo.lockmodified+1 -0
@@ -1636,6 +1636,7 @@ dependencies = [
1636 "mp4",1636 "mp4",
1637 "oxideav-ac3",1637 "oxideav-ac3",
1638 "oxideav-core",1638 "oxideav-core",
1639+ "rav1e",
1639 "rusty_h264",1640 "rusty_h264",
1640 "symphonia",1641 "symphonia",
1641 "symphonia-codec-aac",1642 "symphonia-codec-aac",
crates/app/src/keymap.rsmodified+2 -2
@@ -287,8 +287,8 @@ pub const FIXED: [Fixed; 12] = [
287 category: Category::File,287 category: Category::File,
288 },288 },
289 Fixed {289 Fixed {
290- chord: "m / w / f",290+ chord: "m / a / w / f",
291- label: "Pick the export format: MP4, WAV or FLAC",291+ label: "Pick the export format: MP4, AV1, WAV or FLAC",
292 category: Category::File,292 category: Category::File,
293 },293 },
294 Fixed {294 Fixed {
crates/app/src/main.rsmodified+133 -41
@@ -108,8 +108,8 @@ const KEYS_ROW_H: f32 = HIT_MIN;
108 /// editor grows -- ten rows fit here, and the eleventh is a scroll away.108 /// editor grows -- ten rows fit here, and the eleventh is a scroll away.
109 const KEYS_ROWS_H: f32 = 10. * KEYS_ROW_H;109 const KEYS_ROWS_H: f32 = 10. * KEYS_ROW_H;
110 /// The same for the export card, which carries a fixed-format line and a button110 /// The same for the export card, which carries a fixed-format line and a button
111-/// under its list and so has less room: destination, six formats and five111+/// under its list and so has less room: destination, nine formats and five
112-/// qualities are twelve rows, eight of them on screen.112+/// qualities are fifteen rows, eight of them on screen.
113 const EXPORT_ROWS_H: f32 = 8. * KEYS_ROW_H;113 const EXPORT_ROWS_H: f32 = 8. * KEYS_ROW_H;
114 /// The menu a right-click on a clip opens: wide enough for the longest label114 /// The menu a right-click on a clip opens: wide enough for the longest label
115 /// beside the stroke that does the same thing, with the click targets `HIT_MIN`115 /// beside the stroke that does the same thing, with the click targets `HIT_MIN`
@@ -1982,8 +1982,12 @@ impl Player {
1982 fn set_format(&mut self, format: Format) {1982 fn set_format(&mut self, format: Format) {
1983 // The one door both the row and its initial go through, so a format the1983 // The one door both the row and its initial go through, so a format the
1984 // card greys out cannot be picked by keyboard either.1984 // card greys out cannot be picked by keyboard either.
1985- if let (Format::Mp4, Some(why)) = (format, self.session.as_ref().and_then(mp4_refusal)) {1985+ if let Some(why) = self
1986- self.notice = Some(format!("NOT MP4 — {why}").into());1986+ .session
1987+ .as_ref()
1988+ .and_then(|session| format_refusal(session, format))
1989+ {
1990+ self.notice = Some(format!("NOT {} — {why}", format_label(format)).into());
1987 return;1991 return;
1988 }1992 }
1989 self.format = format;1993 self.format = format;
@@ -2055,7 +2059,7 @@ impl Player {
2055 // default and an audio-only timeline (or a second audio lane) is one2059 // default and an audio-only timeline (or a second audio lane) is one
2056 // edit away -- so the button asks again rather than starting a worker2060 // edit away -- so the button asks again rather than starting a worker
2057 // that will only settle with the same refusal minutes later.2061 // that will only settle with the same refusal minutes later.
2058- if let (Format::Mp4, Some(why)) = (self.format, mp4_refusal(session)) {2062+ if let Some(why) = format_refusal(session, self.format) {
2059 self.notice = Some(format!("NOT EXPORTED — {why}").into());2063 self.notice = Some(format!("NOT EXPORTED — {why}").into());
2060 cx.notify();2064 cx.notify();
2061 return;2065 return;
@@ -3276,15 +3280,20 @@ impl Player {
3276 // An mp4 this timeline cannot be written as reads exactly like the3280 // An mp4 this timeline cannot be written as reads exactly like the
3277 // formats there is no encoder for: dimmed, unclickable, and carrying its3281 // formats there is no encoder for: dimmed, unclickable, and carrying its
3278 // own reason instead of the detail line.3282 // own reason instead of the detail line.
3279- let refused = self.session.as_ref().and_then(mp4_refusal);
3280 let formats: Vec<_> = FORMATS3283 let formats: Vec<_> = FORMATS
3281 .into_iter()3284 .into_iter()
3282 .enumerate()3285 .enumerate()
3283 .map(|(i, (format, label, detail))| {3286 .map(|(i, (format, label, detail))| {
3284- let blocked = format == Some(Format::Mp4) && refused.is_some();3287+ // Per row, because the two picture formats are refused by
3288+ // different things: an audio-only timeline greys both, a second
3289+ // audio lane only the mp4.
3290+ let refused = format
3291+ .zip(self.session.as_ref())
3292+ .and_then(|(f, s)| format_refusal(s, f));
3293+ let blocked = refused.is_some();
3285 let detail: SharedString = match &refused {3294 let detail: SharedString = match &refused {
3286- Some(why) if blocked => why.clone().into(),3295+ Some(why) => why.clone().into(),
3287- _ => detail.into(),3296+ None => detail.into(),
3288 };3297 };
3289 let picked = format == Some(self.format) && !blocked;3298 let picked = format == Some(self.format) && !blocked;
3290 let format = format.filter(|_| !blocked);3299 let format = format.filter(|_| !blocked);
@@ -3358,11 +3367,11 @@ impl Player {
3358 .text_size(px(11.))3367 .text_size(px(11.))
3359 .text_color(rgb(INK_DIM))3368 .text_color(rgb(INK_DIM))
3360 .child(self.notice.clone().unwrap_or_else(|| {3369 .child(self.notice.clone().unwrap_or_else(|| {
3361- "pick a format (m/w/f), then Export — esc closes".into()3370+ "pick a format (m/a/w/f), then Export — esc closes".into()
3362 })),3371 })),
3363 )3372 )
3364 // Capped and scrolling like the keybindings list: the3373 // Capped and scrolling like the keybindings list: the
3365- // destination, six formats and five qualities are more3374+ // destination, nine formats and five qualities are more
3366 // rows than a 360 px window has room for, and it is the3375 // rows than a 360 px window has room for, and it is the
3367 // list that scrolls, never the card that grows.3376 // list that scrolls, never the card that grows.
3368 .child(3377 .child(
@@ -4927,14 +4936,29 @@ impl Quality {
4927 /// `None` is exactly that kind of row. The MP3 reason is a *licence* and not a4936 /// `None` is exactly that kind of row. The MP3 reason is a *licence* and not a
4928 /// capability: `shine-rs` encodes mp3 in pure Rust under LGPL-2.0, which is a4937 /// capability: `shine-rs` encodes mp3 in pure Rust under LGPL-2.0, which is a
4929 /// decision about this project rather than about the code, and the row says so4938 /// decision about this project rather than about the code, and the row says so
4930-/// instead of pretending the encoder does not exist.4939+/// instead of pretending the encoder does not exist. HEVC and VP9 are the two
4931-const FORMATS: [(Option<Format>, &str, &str); 6] = [4940+/// this program *reads* and cannot write -- the plugin decodes both and there is
4941+/// no encoder for either here -- so they are rows for the same reason: a codec
4942+/// that opens but never comes back out is exactly the gap a user would other-
4943+/// wise go looking for.
4944+const FORMATS: [(Option<Format>, &str, &str); 9] = [
4932 (Some(Format::Mp4), "MP4", "H.264 picture + copied AAC"),4945 (Some(Format::Mp4), "MP4", "H.264 picture + copied AAC"),
4946+ (
4947+ Some(Format::Av1),
4948+ "AV1",
4949+ "AV1 picture in .mkv — no sound: export WAV or FLAC for that",
4950+ ),
4933 (Some(Format::Wav), "WAV", "16-bit PCM — audio only"),4951 (Some(Format::Wav), "WAV", "16-bit PCM — audio only"),
4934 (Some(Format::Flac), "FLAC", "lossless — audio only"),4952 (Some(Format::Flac), "FLAC", "lossless — audio only"),
4935 (None, "MP3", "encoder is LGPL — licence decision pending"),4953 (None, "MP3", "encoder is LGPL — licence decision pending"),
4936 (None, "OGG", "no pure-Rust Vorbis or Opus encoder"),4954 (None, "OGG", "no pure-Rust Vorbis or Opus encoder"),
4937 (None, "AAC", "no pure-Rust AAC encoder"),4955 (None, "AAC", "no pure-Rust AAC encoder"),
4956+ (
4957+ None,
4958+ "HEVC",
4959+ "no encoder in this stack, and patent-encumbered",
4960+ ),
4961+ (None, "VP9", "superseded by AV1, which is the row above"),
4938 ];4962 ];
4939 4963
4940 /// The format a key picks while the export card is up: the row's own initial,4964 /// The format a key picks while the export card is up: the row's own initial,
@@ -5046,11 +5070,21 @@ fn export_line(format: Format, session: Option<&PlaybackSession>) -> String {
5046 fn format_line(format: Format) -> &'static str {5070 fn format_line(format: Format) -> &'static str {
5047 match format {5071 match format {
5048 Format::Mp4 => "H.264 · MP4 · moov at end",5072 Format::Mp4 => "H.264 · MP4 · moov at end",
5073+ Format::Av1 => "AV1 · Matroska · picture only, no audio track",
5049 Format::Wav => "16-bit PCM · WAV · timeline audio only",5074 Format::Wav => "16-bit PCM · WAV · timeline audio only",
5050 Format::Flac => "FLAC · lossless · timeline audio only",5075 Format::Flac => "FLAC · lossless · timeline audio only",
5051 }5076 }
5052 }5077 }
5053 5078
5079+/// The row a format is picked by, which is what a refusal calls it: `MP4`, not
5080+/// the `mkv` an AV1 file is named with.
5081+fn format_label(format: Format) -> &'static str {
5082+ FORMATS
5083+ .iter()
5084+ .find(|(row, ..)| *row == Some(format))
5085+ .map_or("EXPORT", |(_, label, _)| *label)
5086+}
5087+
5054 /// The destination under a format: `take.export.mp4` becomes `take.export.wav`.5088 /// The destination under a format: `take.export.mp4` becomes `take.export.wav`.
5055 /// The stem is untouched, so a name typed into the save dialog survives a5089 /// The stem is untouched, so a name typed into the save dialog survives a
5056 /// change of mind about the format -- only the extension is the format's to say.5090 /// change of mind about the format -- only the extension is the format's to say.
@@ -5117,23 +5151,34 @@ fn is_bare_modifier(key: &str) -> bool {
5117 5151
5118 /// A clip's share of the lane. A timeline with no length reads as one full-width5152 /// A clip's share of the lane. A timeline with no length reads as one full-width
5119 /// box rather than as NaN, which gpui would carry into layout.5153 /// box rather than as NaN, which gpui would carry into layout.
5120-/// Why this timeline cannot be written as an mp4, if it cannot: the mp4 path5154+/// Why this timeline cannot be written in `format`, if it cannot.
5121-/// *copies* one AAC track and there is no encoder here to mix several with, so a
5122-/// timeline whose sound is spread over more than one audio lane is refused by
5123-/// the engine (`export::run`). Said on the row, before a destination has been
5124-/// picked, rather than after the write has started.
5125 ///5155 ///
5126-/// An audio-only timeline is the other one: every frame of it is a gap, so the5156+/// An audio-only timeline is the one both picture formats refuse: every frame of
5127-/// mp4 would be a black picture over the sound. The engine refuses it too5157+/// it is a gap, so the file would be a black picture over the sound. The engine
5128-/// (`export::start`); this is what greys the row before a destination has been5158+/// refuses it too (`export::start`); this is what greys the row before a
5129-/// picked.5159+/// destination has been picked.
5130-fn mp4_refusal(session: &PlaybackSession) -> Option<String> {5160+///
5161+/// The second reason is the mp4 path's alone: it *copies* one AAC track and
5162+/// there is no encoder here to mix several with, so a timeline whose sound is
5163+/// spread over more than one audio lane is refused by the engine
5164+/// (`export::run`). An AV1 export carries no sound at all -- said on its row as
5165+/// its detail, not as a refusal -- so no count of audio lanes stops it.
5166+fn format_refusal(session: &PlaybackSession, format: Format) -> Option<String> {
5167+ if !format.has_video() {
5168+ return None;
5169+ }
5131 let picture = session5170 let picture = session
5132 .lanes()5171 .lanes()
5133 .into_iter()5172 .into_iter()
5134 .any(|lane| lane.kind == LaneKind::Video && !session.lane_clips(lane).is_empty());5173 .any(|lane| lane.kind == LaneKind::Video && !session.lane_clips(lane).is_empty());
5135 if !picture {5174 if !picture {
5136- return Some("no picture — an mp4 would be black; export WAV or FLAC".to_string());5175+ return Some(format!(
5176+ "no picture — {} would be black; export WAV or FLAC",
5177+ format.name()
5178+ ));
5179+ }
5180+ if format != Format::Mp4 {
5181+ return None;
5137 }5182 }
5138 let lanes = session5183 let lanes = session
5139 .lanes()5184 .lanes()
@@ -5640,11 +5685,11 @@ mod tests {
5640 LIBRARY_MAX_W, LIBRARY_MIN_W, Lane, MENU_ITEMS, MENU_W, NO_FILE, PANEL_H, Quality, ROW_H,5685 LIBRARY_MAX_W, LIBRARY_MIN_W, Lane, MENU_ITEMS, MENU_W, NO_FILE, PANEL_H, Quality, ROW_H,
5641 RULER_HIT_H, SELECTED, SOURCE_TINTS, SURFACE, SWATCH_W, Source, StreamInfo, Volume,5686 RULER_HIT_H, SELECTED, SOURCE_TINTS, SURFACE, SWATCH_W, Source, StreamInfo, Volume,
5642 WAVE_BPS, WAVE_COL, Wave, applicable, band_label, can_add, cancels_export, color_snap,5687 WAVE_BPS, WAVE_COL, Wave, applicable, band_label, can_add, cancels_export, color_snap,
5643- envelope, eq_x, eq_y, export_path, export_settings, format_line, frac_along, frac_down,5688+ envelope, eq_x, eq_y, export_path, export_settings, format_key, format_line,
5644- frame_at, histogram, is_bare_modifier, is_project, keymap, lane_clips, lanes_h, marked,5689+ format_refusal, frac_along, frac_down, frame_at, histogram, is_bare_modifier, is_project,
5645- menu_at, mp4_refusal, normalise, panel_h, project_path, push_digit, retarget, scrub_due,5690+ keymap, lane_clips, lanes_h, marked, menu_at, normalise, panel_h, project_path, push_digit,
5646- show_label, source_frames, source_tint, span_partner, start_frac, timecode, unseen_paths,5691+ retarget, scrub_due, show_label, source_frames, source_tint, span_partner, start_frac,
5647- unseen_sources, whole_take, width_frac, window_title,5692+ timecode, unseen_paths, unseen_sources, whole_take, width_frac, window_title,
5648 };5693 };
5649 use super::{file_name, file_uri, library_rows};5694 use super::{file_name, file_uri, library_rows};
5650 5695
@@ -5784,11 +5829,19 @@ mod tests {
5784 assert_eq!(session.lane_clips(Lane::A1).len(), 2);5829 assert_eq!(session.lane_clips(Lane::A1).len(), 2);
5785 assert!(session.lane_clips(Lane::V1).is_empty(), "still no picture");5830 assert!(session.lane_clips(Lane::V1).is_empty(), "still no picture");
5786 5831
5787- // The mp4 row carries the reason rather than the format's detail line.5832+ // Both picture rows carry the reason rather than the format's detail
5833+ // line, each naming itself; the audio formats are what this timeline is
5834+ // and are never refused.
5788 assert_eq!(5835 assert_eq!(
5789- mp4_refusal(&session).as_deref(),5836+ format_refusal(&session, Format::Mp4).as_deref(),
5790 Some("no picture — an mp4 would be black; export WAV or FLAC")5837 Some("no picture — an mp4 would be black; export WAV or FLAC")
5791 );5838 );
5839+ assert_eq!(
5840+ format_refusal(&session, Format::Av1).as_deref(),
5841+ Some("no picture — an AV1 export would be black; export WAV or FLAC")
5842+ );
5843+ assert_eq!(format_refusal(&session, Format::Wav), None);
5844+ assert_eq!(format_refusal(&session, Format::Flac), None);
5792 }5845 }
5793 5846
5794 fn info(5847 fn info(
@@ -6382,19 +6435,26 @@ mod tests {
6382 6435
6383 // A second audio lane carrying sound is what an mp4 export cannot6436 // A second audio lane carrying sound is what an mp4 export cannot
6384 // write, so the card greys that row before a destination is picked.6437 // write, so the card greys that row before a destination is picked.
6385- assert_eq!(mp4_refusal(&session), None);6438+ assert_eq!(format_refusal(&session, Format::Mp4), None);
6386 let a2 = session.add_lane(LaneKind::Audio);6439 let a2 = session.add_lane(LaneKind::Audio);
6387 assert_eq!(a2.label(), "A2");6440 assert_eq!(a2.label(), "A2");
6388- assert_eq!(mp4_refusal(&session), None, "an empty lane carries nothing");6441+ assert_eq!(
6442+ format_refusal(&session, Format::Mp4),
6443+ None,
6444+ "an empty lane carries nothing"
6445+ );
6389 assert!(6446 assert!(
6390 session6447 session
6391 .place_stream_at(0.0, &path, 0, frames, Some(a2))6448 .place_stream_at(0.0, &path, 0, frames, Some(a2))
6392 .expect("its own file is on this timeline")6449 .expect("its own file is on this timeline")
6393 );6450 );
6394 assert_eq!(6451 assert_eq!(
6395- mp4_refusal(&session).as_deref(),6452+ format_refusal(&session, Format::Mp4).as_deref(),
6396 Some("2 audio lanes — an mp4 copies one")6453 Some("2 audio lanes — an mp4 copies one")
6397 );6454 );
6455+ // ...and the one thing that does not stop an AV1 export, which carries
6456+ // no sound to have too much of.
6457+ assert_eq!(format_refusal(&session, Format::Av1), None);
6398 6458
6399 // Undo, one edit at a time and backwards: the drop on A2, the lane A26459 // Undo, one edit at a time and backwards: the drop on A2, the lane A2
6400 // itself, the lift, the drop on V2, and last the lane V2 -- an added6460 // itself, the lift, the drop on V2, and last the lane V2 -- an added
@@ -6405,7 +6465,7 @@ mod tests {
6405 }6465 }
6406 assert_eq!(session.lanes(), vec![Lane::V1, Lane::A1]);6466 assert_eq!(session.lanes(), vec![Lane::V1, Lane::A1]);
6407 assert_eq!(session.lane_clips(Lane::V1).len(), 1);6467 assert_eq!(session.lane_clips(Lane::V1).len(), 1);
6408- assert_eq!(mp4_refusal(&session), None);6468+ assert_eq!(format_refusal(&session, Format::Mp4), None);
6409 }6469 }
6410 6470
6411 #[test]6471 #[test]
@@ -7089,12 +7149,20 @@ mod tests {
7089 7149
7090 #[test]7150 #[test]
7091 fn every_format_row_is_offered_or_says_why_not() {7151 fn every_format_row_is_offered_or_says_why_not() {
7092- // The three this program can write are rows that pick, each named after7152+ // The four this program can write are rows that pick. Three are named
7093- // its own extension so a destination can never disagree with its bytes.7153+ // after their own extension, so a destination cannot disagree with its
7154+ // bytes; the fourth is named after its *codec*, because AV1 arrives and
7155+ // leaves in a Matroska file and "MKV" would name the box rather than
7156+ // what is in it.
7094 let offered: Vec<Format> = FORMATS.iter().filter_map(|&(f, ..)| f).collect();7157 let offered: Vec<Format> = FORMATS.iter().filter_map(|&(f, ..)| f).collect();
7095- assert_eq!(offered, vec![Format::Mp4, Format::Wav, Format::Flac]);7158+ assert_eq!(
7159+ offered,
7160+ vec![Format::Mp4, Format::Av1, Format::Wav, Format::Flac]
7161+ );
7162+ assert_eq!(Format::Av1.ext(), "mkv");
7096 for (format, label, _) in FORMATS {7163 for (format, label, _) in FORMATS {
7097 match format {7164 match format {
7165+ Some(Format::Av1) => assert_eq!(label, "AV1"),
7098 Some(format) => assert_eq!(format.ext(), label.to_lowercase()),7166 Some(format) => assert_eq!(format.ext(), label.to_lowercase()),
7099 // A refused format is a row with a reason, never a hidden one:7167 // A refused format is a row with a reason, never a hidden one:
7100 // an empty detail column would read as an oversight.7168 // an empty detail column would read as an oversight.
@@ -7103,13 +7171,37 @@ mod tests {
7103 }7171 }
7104 for (format, label, detail) in FORMATS {7172 for (format, label, detail) in FORMATS {
7105 assert!(!detail.is_empty(), "{label} says nothing");7173 assert!(!detail.is_empty(), "{label} says nothing");
7106- // Only mp4 carries the picture, so only mp4 leaves the bitrate rows7174+ // Only the two picture formats leave the bitrate rows live -- the
7107- // live -- the card dims them off exactly this.7175+ // card dims them off exactly this.
7108 assert_eq!(7176 assert_eq!(
7109 format.is_some_and(Format::has_video),7177 format.is_some_and(Format::has_video),
7110- format == Some(Format::Mp4)7178+ matches!(format, Some(Format::Mp4 | Format::Av1))
7111 );7179 );
7112 }7180 }
7181+ // The two codecs this program reads and cannot write are rows of their
7182+ // own, refused by name rather than absent -- HEVC for want of an encoder
7183+ // (and for its patents), VP9 because AV1 is the row that replaced it.
7184+ for (label, word) in [("HEVC", "no encoder"), ("VP9", "superseded")] {
7185+ let (format, _, detail) = FORMATS
7186+ .into_iter()
7187+ .find(|(_, row, _)| *row == label)
7188+ .unwrap_or_else(|| panic!("{label} has no row"));
7189+ assert!(format.is_none(), "{label} is not offered");
7190+ assert!(detail.contains(word), "{label}: {detail}");
7191+ }
7192+ // The AV1 row says on the row itself that it carries no sound, which is
7193+ // the one thing a user could otherwise only find out by playing the file.
7194+ let (_, _, av1) = FORMATS
7195+ .into_iter()
7196+ .find(|(f, ..)| *f == Some(Format::Av1))
7197+ .expect("an AV1 row");
7198+ assert!(av1.contains("no sound"), "{av1}");
7199+ assert!(format_line(Format::Av1).contains("picture only"));
7200+ assert_eq!(
7201+ format_key("a"),
7202+ Some(Format::Av1),
7203+ "its own initial picks it"
7204+ );
7113 // The destination follows the format and keeps the stem, mp4 included.7205 // The destination follows the format and keeps the stem, mp4 included.
7114 assert_eq!(7206 assert_eq!(
7115 retarget(std::path::Path::new("/a/take.export.mp4"), Format::Wav),7207 retarget(std::path::Path::new("/a/take.export.mp4"), Format::Wav),
crates/engine-hw/src/lib.rsmodified+135 -30
@@ -1,4 +1,5 @@
1-//! VA-API decode (H.264, HEVC, VP9 and AV1) and H.264 encode, shipped as a1+//! VA-API decode (H.264, HEVC, VP9 and AV1) and encode (H.264, and AV1 where
2+//! the GPU has an entrypoint for it), shipped as a
2 //! `dlopen`-able plugin so the main binary never gets a DT_NEEDED on3 //! `dlopen`-able plugin so the main binary never gets a DT_NEEDED on
3 //! libva/gbm/drm. Every entry point is4 //! libva/gbm/drm. Every entry point is
4 //! `extern "C"`, catches unwinds and reports failure as a null pointer or a5 //! `extern "C"`, catches unwinds and reports failure as a null pointer or a
@@ -17,6 +18,7 @@ use std::rc::Rc;
17 18
18 use cros_codecs::backend::vaapi::decoder::VaapiBackend;19 use cros_codecs::backend::vaapi::decoder::VaapiBackend;
19 use cros_codecs::backend::vaapi::encoder::VaapiBackend as VaapiEncBackend;20 use cros_codecs::backend::vaapi::encoder::VaapiBackend as VaapiEncBackend;
21+use cros_codecs::codec::av1::parser::Profile as Av1Profile;
20 use cros_codecs::codec::h264::parser::{Level, Profile as H264Profile};22 use cros_codecs::codec::h264::parser::{Level, Profile as H264Profile};
21 use cros_codecs::decoder::stateless::av1::Av1;23 use cros_codecs::decoder::stateless::av1::Av1;
22 use cros_codecs::decoder::stateless::h264::H264;24 use cros_codecs::decoder::stateless::h264::H264;
@@ -24,7 +26,9 @@ use cros_codecs::decoder::stateless::h265::H265;
24 use cros_codecs::decoder::stateless::vp9::Vp9;26 use cros_codecs::decoder::stateless::vp9::Vp9;
25 use cros_codecs::decoder::stateless::{DecodeError, StatelessDecoder, StatelessVideoDecoder};27 use cros_codecs::decoder::stateless::{DecodeError, StatelessDecoder, StatelessVideoDecoder};
26 use cros_codecs::decoder::{BlockingMode, DecodedHandle, DecoderEvent, StreamInfo};28 use cros_codecs::decoder::{BlockingMode, DecodedHandle, DecoderEvent, StreamInfo};
29+use cros_codecs::encoder::av1::EncoderConfig as Av1Config;
27 use cros_codecs::encoder::h264::EncoderConfig as H264Config;30 use cros_codecs::encoder::h264::EncoderConfig as H264Config;
31+use cros_codecs::encoder::stateless::av1::StatelessEncoder as Av1StatelessEncoder;
28 use cros_codecs::encoder::stateless::h264::StatelessEncoder;32 use cros_codecs::encoder::stateless::h264::StatelessEncoder;
29 use cros_codecs::encoder::{33 use cros_codecs::encoder::{
30 FrameMetadata, PredictionStructure, RateControl, Tunings, VideoEncoder,34 FrameMetadata, PredictionStructure, RateControl, Tunings, VideoEncoder,
@@ -81,6 +85,10 @@ type Encoder = StatelessEncoder<
81 GenericDmaVideoFrame,85 GenericDmaVideoFrame,
82 VaapiEncBackend<GenericDmaVideoFrame, Surface<GenericDmaVideoFrame>>,86 VaapiEncBackend<GenericDmaVideoFrame, Surface<GenericDmaVideoFrame>>,
83 >;87 >;
88+type Av1Encoder = Av1StatelessEncoder<
89+ GenericDmaVideoFrame,
90+ VaapiEncBackend<GenericDmaVideoFrame, Surface<GenericDmaVideoFrame>>,
91+>;
84 92
85 /// Ceiling on decode/drain iterations that make no progress. VA-API in blocking93 /// Ceiling on decode/drain iterations that make no progress. VA-API in blocking
86 /// mode should always either hand back an event or accept input; this only94 /// mode should always either hand back an event or accept input; this only
@@ -517,7 +525,13 @@ fn fix_slice_nal_headers(au: &mut [u8]) {
517 /// point polls it before returning, so the GPU is finished with the buffer525 /// point polls it before returning, so the GPU is finished with the buffer
518 /// before the next picture is written into it.526 /// before the next picture is written into it.
519 struct EncSession {527 struct EncSession {
520- encoder: Encoder,528+ /// Boxed because the two codecs are two types and everything past `encode`
529+ /// is the same trait: one session type serves both, which is what keeps the
530+ /// C ABI at one new symbol (the open) instead of four.
531+ encoder: Box<dyn VideoEncoder<GenericDmaVideoFrame>>,
532+ /// H.264 only: the byte the driver leaves at zero is a *NAL* header, and an
533+ /// AV1 temporal unit has no such thing.
534+ h264: bool,
521 /// Owns the DRM node the buffer object below was allocated from.535 /// Owns the DRM node the buffer object below was allocated from.
522 _gbm: gbm::Device<std::fs::File>,536 _gbm: gbm::Device<std::fs::File>,
523 frame: GenericDmaVideoFrame,537 frame: GenericDmaVideoFrame,
@@ -537,6 +551,17 @@ struct EncSession {
537 551
538 impl EncSession {552 impl EncSession {
539 fn open(width: u32, height: u32, fps_num: u32, fps_den: u32, bitrate: u64) -> Option<Self> {553 fn open(width: u32, height: u32, fps_num: u32, fps_den: u32, bitrate: u64) -> Option<Self> {
554+ Self::open_codec(width, height, fps_num, fps_den, bitrate, false)
555+ }
556+
557+ fn open_codec(
558+ width: u32,
559+ height: u32,
560+ fps_num: u32,
561+ fps_den: u32,
562+ bitrate: u64,
563+ av1: bool,
564+ ) -> Option<Self> {
540 // NV12 chroma is half resolution, so odd dimensions have no packing;565 // NV12 chroma is half resolution, so odd dimensions have no packing;
541 // and radeonsi refuses encode contexts below 64x64 (measured).566 // and radeonsi refuses encode contexts below 64x64 (measured).
542 if width < 64 || height < 64 || width % 2 != 0 || height % 2 != 0 {567 if width < 64 || height < 64 || width % 2 != 0 || height % 2 != 0 {
@@ -551,40 +576,92 @@ impl EncSession {
551 height: align16(height),576 height: align16(height),
552 };577 };
553 let framerate = ((fps_num as f64 / fps_den as f64).round() as i64).clamp(1, 240) as u32;578 let framerate = ((fps_num as f64 / fps_den as f64).round() as i64).clamp(1, 240) as u32;
554- let low_power = display579+ let profile = match av1 {
555- .query_config_entrypoints(VAProfile::VAProfileH264Main)580+ true => VAProfile::VAProfileAV1Profile0,
556- .ok()?581+ false => VAProfile::VAProfileH264Main,
557- .contains(&VAEntrypoint::VAEntrypointEncSliceLP);582+ };
558- let config = H264Config {583+ // The driver's own answer to "can you encode this at all": a GPU with no
559- resolution: Resolution { width, height },584+ // AV1 encode entrypoint is what makes the caller fall back to `rav1e`,
560- profile: H264Profile::Main,585+ // and asking here is what turns that into a null rather than a failed
561- level: Level::L4,586+ // encode session halfway through an export.
562- // No B-frames: coded order stays display order, which is what the587+ let entrypoints = display.query_config_entrypoints(profile).ok()?;
563- // muxer's duration-only timing assumes.588+ if !entrypoints.contains(&VAEntrypoint::VAEntrypointEncSlice)
564- pred_structure: PredictionStructure::LowDelay {589+ && !entrypoints.contains(&VAEntrypoint::VAEntrypointEncSliceLP)
565- limit: (framerate * 2) as u16,590+ {
566- },591+ return None;
567- initial_tunings: Tunings {592+ }
568- rate_control: RateControl::ConstantBitrate(bitrate),593+ let low_power = entrypoints.contains(&VAEntrypoint::VAEntrypointEncSliceLP);
569- framerate,594+ // No B-frames on either codec: coded order stays display order, which is
570- ..Default::default()595+ // what both muxers' duration-only timing assumes.
571- },596+ let pred_structure = PredictionStructure::LowDelay {
597+ limit: (framerate * 2) as u16,
598+ };
599+ let encoder: Box<dyn VideoEncoder<GenericDmaVideoFrame>> = match av1 {
600+ true => {
601+ // Constant quality, because that is the only rate control the
602+ // vendored AV1 backend takes (`stateless/av1/vaapi.rs` refuses
603+ // anything else outright); 128 of 255 is its own reference
604+ // value. The caller's bitrate therefore does not reach this
605+ // seat -- it reaches `rav1e`, which is the other one.
606+ //
607+ // ponytail: bitrate-driven AV1 on the GPU needs `VA_RC_CBR`
608+ // wired through that backend, which is a change in the vendored
609+ // crate rather than here.
610+ let config = Av1Config {
611+ profile: Av1Profile::Profile0,
612+ resolution: Resolution { width, height },
613+ pred_structure,
614+ initial_tunings: Tunings {
615+ rate_control: RateControl::ConstantQuality(128),
616+ framerate,
617+ ..Default::default()
618+ },
619+ ..Default::default()
620+ };
621+ Box::new(
622+ Av1Encoder::new_vaapi(
623+ display,
624+ config,
625+ Fourcc::from(b"NV12"),
626+ coded,
627+ low_power,
628+ BlockingMode::Blocking,
629+ )
630+ .ok()?,
631+ )
632+ }
633+ false => {
634+ let config = H264Config {
635+ resolution: Resolution { width, height },
636+ profile: H264Profile::Main,
637+ level: Level::L4,
638+ pred_structure,
639+ initial_tunings: Tunings {
640+ rate_control: RateControl::ConstantBitrate(bitrate),
641+ framerate,
642+ ..Default::default()
643+ },
644+ };
645+ Box::new(
646+ Encoder::new_vaapi(
647+ display,
648+ config,
649+ Fourcc::from(b"NV12"),
650+ coded,
651+ low_power,
652+ BlockingMode::Blocking,
653+ )
654+ .ok()?,
655+ )
656+ }
572 };657 };
573- let encoder = Encoder::new_vaapi(
574- display,
575- config,
576- Fourcc::from(b"NV12"),
577- coded,
578- low_power,
579- BlockingMode::Blocking,
580- )
581- .ok()?;
582 // Allocated at the aligned size, so the buffer's pitch is never smaller658 // Allocated at the aligned size, so the buffer's pitch is never smaller
583 // than a padded row.659 // than a padded row.
584 let frame = alloc_nv12(&gbm, coded).ok()?;660 let frame = alloc_nv12(&gbm, coded).ok()?;
585 let layout = nv12_layout(coded, frame.get_plane_pitch()[0]);661 let layout = nv12_layout(coded, frame.get_plane_pitch()[0]);
586 Some(Self {662 Some(Self {
587 encoder,663 encoder,
664+ h264: !av1,
588 _gbm: gbm,665 _gbm: gbm,
589 frame,666 frame,
590 layout,667 layout,
@@ -667,7 +744,9 @@ impl EncSession {
667 fn collect(&mut self) -> Result<(), String> {744 fn collect(&mut self) -> Result<(), String> {
668 while let Some(coded) = self.encoder.poll().map_err(|e| e.to_string())? {745 while let Some(coded) = self.encoder.poll().map_err(|e| e.to_string())? {
669 let mut au = coded.bitstream;746 let mut au = coded.bitstream;
670- fix_slice_nal_headers(&mut au);747+ if self.h264 {
748+ fix_slice_nal_headers(&mut au);
749+ }
671 self.ready.push_back(au);750 self.ready.push_back(au);
672 }751 }
673 Ok(())752 Ok(())
@@ -710,6 +789,32 @@ pub extern "C" fn vh_enc_open(
710 .unwrap_or(std::ptr::null_mut())789 .unwrap_or(std::ptr::null_mut())
711 }790 }
712 791
792+/// The same, coding AV1 instead of H.264: null unless this GPU has an AV1
793+/// encode entrypoint, which is recent hardware -- the caller then encodes AV1 in
794+/// software instead. `bitrate` is not used by this codec (see `EncSession::open`:
795+/// the vendored backend is constant-quality only) and is taken all the same, so
796+/// the two opens stay one signature.
797+///
798+/// The session it returns is fed, drained and closed through `vh_enc_frame`,
799+/// `vh_enc_drain` and `vh_enc_close` exactly as an H.264 one is; what comes back
800+/// out of them is AV1 temporal units rather than Annex-B access units.
801+#[unsafe(no_mangle)]
802+pub extern "C" fn vh_enc_av1_open(
803+ width: u32,
804+ height: u32,
805+ fps_num: u32,
806+ fps_den: u32,
807+ bitrate: u64,
808+) -> *mut c_void {
809+ catch_unwind(AssertUnwindSafe(|| {
810+ match EncSession::open_codec(width, height, fps_num, fps_den, bitrate, true) {
811+ Some(session) => Box::into_raw(Box::new(session)) as *mut c_void,
812+ None => std::ptr::null_mut(),
813+ }
814+ }))
815+ .unwrap_or(std::ptr::null_mut())
816+}
817+
713 /// Encodes one tightly-strided I420 picture. 1 when `out`/`out_len` describe one818 /// Encodes one tightly-strided I420 picture. 1 when `out`/`out_len` describe one
714 /// Annex-B access unit, 0 when the encoder has nothing coded yet, negative on819 /// Annex-B access unit, 0 when the encoder has nothing coded yet, negative on
715 /// error. The bytes stay valid until the next call on this session.820 /// error. The bytes stay valid until the next call on this session.
crates/engine/Cargo.tomlmodified+8 -0
@@ -37,3 +37,11 @@ symphonia = { version = "0.6", default-features = false, features = [
37 ] }37 ] }
38 oxideav-ac3 = "=0.0.10"38 oxideav-ac3 = "=0.0.10"
39 oxideav-core = "0.1.34"39 oxideav-core = "0.1.34"
40+# The software AV1 encoder, and the only new name in this list that was already
41+# in the lock file: `ravif` pulls the very same rav1e 0.8.1 in through the image
42+# crate, so this links what the build already compiled. BSD-2 with the AOM
43+# patent grant, and pure Rust with `asm` *off*: that feature wants `nasm`, which
44+# this project's build does not have and will not require. `threading` is rayon
45+# inside rav1e itself and is what keeps an export minutes rather than tens of
46+# minutes; the cost of no assembly is measured in `export::Enc::open_av1`.
47+rav1e = { version = "0.8.1", default-features = false, features = ["threading"] }
crates/engine/src/export.rsmodified+331 -56
@@ -1,5 +1,5 @@
1-//! Export: the edit list rendered back out as one mp4 — or, picture left1+//! Export: the edit list rendered back out as one mp4 or one AV1-in-Matroska —
2-//! behind, as one WAV or FLAC of the timeline's audio alone.2+//! or, picture left behind, as one WAV or FLAC of the timeline's audio alone.
3 //!3 //!
4 //! Video is fully re-encoded — a cut lands mid-GOP, so stream-copying across it4 //! Video is fully re-encoded — a cut lands mid-GOP, so stream-copying across it
5 //! is impossible — while audio is copied packet for packet, because there is no5 //! is impossible — while audio is copied packet for packet, because there is no
@@ -30,7 +30,7 @@ use flacenc::error::Verify;
30 use crate::audio::{AudioMeta, AudioSession};30 use crate::audio::{AudioMeta, AudioSession};
31 use crate::demux::{Demuxer, VideoMeta};31 use crate::demux::{Demuxer, VideoMeta};
32 use crate::hw::{HwEncoder, HwSession};32 use crate::hw::{HwEncoder, HwSession};
33-use crate::mux::{AudioParams, Mp4Muxer, VideoParams};33+use crate::mux::{AudioParams, Av1Params, MkvMuxer, Mp4Muxer, VideoParams};
34 use crate::project::{LaneKind, Project};34 use crate::project::{LaneKind, Project};
35 use crate::scale::Composer;35 use crate::scale::Composer;
36 36
@@ -44,12 +44,17 @@ const BITS_PER_PIXEL: f64 = 0.1;
44 const MIN_BITRATE: u64 = 1_000_000;44 const MIN_BITRATE: u64 = 1_000_000;
45 const MAX_BITRATE: u64 = 20_000_000;45 const MAX_BITRATE: u64 = 20_000_000;
46 46
47-/// What an export writes. Three, not more: H.264-in-mp4 is the only *video*47+/// `rav1e`'s fastest preset. Anything slower is minutes per second of timeline
48-/// pair with both an encoder and a decoder under this project's no-install48+/// on a build with no assembly, which is what this one is.
49-/// rule, and WAV and FLAC are the only audio formats with a pure-Rust encoder49+const AV1_SPEED: u8 = 10;
50-/// at all. MP3 has one (`shine-rs`) under LGPL-2.0, which is a licensing50+
51-/// decision this project has not taken; Vorbis, Opus and AAC have none. A51+/// What an export writes. Four, not more: H.264-in-mp4 and AV1-in-Matroska are
52-/// front-end says so rather than hiding the rows.52+/// the only *video* pairs with both an encoder and a decoder under this
53+/// project's no-install rule, and WAV and FLAC are the only audio formats with
54+/// a pure-Rust encoder at all. MP3 has one (`shine-rs`) under LGPL-2.0, which is
55+/// a licensing decision this project has not taken; Vorbis, Opus and AAC have
56+/// none. HEVC and VP9 have no encoder here at all (`hevc`/`vp9` import through
57+/// the plugin and stop there). A front-end says so rather than hiding the rows.
53 #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]58 #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
54 pub enum Format {59 pub enum Format {
55 /// Picture and sound: video re-encoded, AAC copied. Copied, so it carries60 /// Picture and sound: video re-encoded, AAC copied. Copied, so it carries
@@ -57,6 +62,12 @@ pub enum Format {
57 /// by name here and mixed by the other two formats, which decode.62 /// by name here and mixed by the other two formats, which decode.
58 #[default]63 #[default]
59 Mp4,64 Mp4,
65+ /// Picture alone, AV1 in Matroska. Alone because Matroska carries no sound
66+ /// this project can write: there is no AAC or Opus encoder here, and an AAC
67+ /// track copied in would be one *this engine's own reader* leaves silent
68+ /// (`audio::AudioSession::open` refuses Matroska audio). The sound of an AV1
69+ /// export is a WAV or FLAC beside it, which a front-end says up front.
70+ Av1,
60 /// The audio lane alone, 16-bit PCM.71 /// The audio lane alone, 16-bit PCM.
61 Wav,72 Wav,
62 /// The audio lane alone, losslessly compressed.73 /// The audio lane alone, losslessly compressed.
@@ -69,15 +80,26 @@ impl Format {
69 pub fn ext(self) -> &'static str {80 pub fn ext(self) -> &'static str {
70 match self {81 match self {
71 Self::Mp4 => "mp4",82 Self::Mp4 => "mp4",
83+ Self::Av1 => "mkv",
72 Self::Wav => "wav",84 Self::Wav => "wav",
73 Self::Flac => "flac",85 Self::Flac => "flac",
74 }86 }
75 }87 }
76 88
77 /// Whether this format carries the picture. The bitrate settings are video89 /// Whether this format carries the picture. The bitrate settings are video
78- /// settings and mean nothing to the other two.90+ /// settings and mean nothing to the audio two.
79 pub fn has_video(self) -> bool {91 pub fn has_video(self) -> bool {
80- matches!(self, Self::Mp4)92+ matches!(self, Self::Mp4 | Self::Av1)
93+ }
94+
95+ /// What the format is called where a refusal names it.
96+ pub fn name(self) -> &'static str {
97+ match self {
98+ Self::Mp4 => "an mp4",
99+ Self::Av1 => "an AV1 export",
100+ Self::Wav => "a WAV",
101+ Self::Flac => "a FLAC",
102+ }
81 }103 }
82 }104 }
83 105
@@ -184,10 +206,13 @@ pub fn start(
184 _ if project.timeline_frames() == 0 => {206 _ if project.timeline_frames() == 0 => {
185 Err("the timeline is empty: there is nothing to export".into())207 Err("the timeline is empty: there is nothing to export".into())
186 }208 }
187- Format::Mp4 if !has_picture(&project) => Err("the timeline has no picture: \209+ format if format.has_video() && !has_picture(&project) => Err(format!(
188- an mp4 would be black. Export WAV or FLAC, which are the sound itself"210+ "the timeline has no picture: {} would be black. Export WAV or \
189- .into()),211+ FLAC, which are the sound itself",
190- Format::Mp4 => run(&project, &meta, &part, &worker, &settings),212+ format.name()
213+ )
214+ .into()),
215+ Format::Mp4 | Format::Av1 => run(&project, &meta, &part, &worker, &settings),
191 format => run_audio(&project, &meta, &part, &worker, format),216 format => run_audio(&project, &meta, &part, &worker, format),
192 };217 };
193 let result = written.and_then(|()| std::fs::rename(&part, &out).map_err(Into::into));218 let result = written.and_then(|()| std::fs::rename(&part, &out).map_err(Into::into));
@@ -220,22 +245,17 @@ fn settle(shared: &Shared, result: crate::Result<()>) {
220 shared.finished.store(true, Ordering::Release);245 shared.finished.store(true, Ordering::Release);
221 }246 }
222 247
223-fn run(248+/// The timeline's one audio lane, copied packet for packet: the mp4 path's
249+/// sound, and the reason that path carries only one lane of it.
250+///
251+/// ponytail: this holds the whole exported AAC track in memory (~3 kB per
252+/// 23 ms packet, so ~500 MB for an hour). Upgrade path is a streaming
253+/// `copy_segments` that yields packets instead of collecting them.
254+#[allow(clippy::type_complexity)]
255+fn copy_audio(
224 project: &Project,256 project: &Project,
225 meta: &VideoMeta,257 meta: &VideoMeta,
226- out: &Path,258+) -> crate::Result<Option<(crate::AacTrackParams, Vec<crate::AacPacket>)>> {
227- shared: &Shared,
228- settings: &ExportSettings,
229-) -> crate::Result<()> {
230- let total = project.timeline_frames();
231- let sources = project.sources();
232- // Audio first: a track has to be declared when the muxer is created, which
233- // happens as soon as the first coded picture arrives.
234- //
235- // ponytail: this holds the whole exported AAC track in memory (~3 kB per
236- // 23 ms packet, so ~500 MB for an hour). Upgrade path is a streaming
237- // `copy_segments` that yields packets instead of collecting them.
238- //
239 // The segments name their source, and the copy carries its packet-rounding259 // The segments name their source, and the copy carries its packet-rounding
240 // debt across a source join exactly as across a cut, so a timeline spanning260 // debt across a source join exactly as across a cut, so a timeline spanning
241 // files stays in sync. A source whose AAC parameters disagree with the261 // files stays in sync. A source whose AAC parameters disagree with the
@@ -279,7 +299,11 @@ fn run(
279 .lane(lane)299 .lane(lane)
280 .iter()300 .iter()
281 .enumerate()301 .enumerate()
282- .find(|(idx, _)| project.eq_of(lane, *idx).is_some_and(|eq| !eq.is_identity()))302+ .find(|(idx, _)| {
303+ project
304+ .eq_of(lane, *idx)
305+ .is_some_and(|eq| !eq.is_identity())
306+ })
283 .map(|(idx, clip)| (clip.start, idx))307 .map(|(idx, clip)| (clip.start, idx))
284 {308 {
285 return Err(format!(309 return Err(format!(
@@ -290,7 +314,28 @@ fn run(
290 )314 )
291 .into());315 .into());
292 }316 }
293- let audio = AudioSession::copy_multi_streams(&project.audio_sources(), segments)?;317+ AudioSession::copy_multi_streams(&project.audio_sources(), segments)
318+}
319+
320+fn run(
321+ project: &Project,
322+ meta: &VideoMeta,
323+ out: &Path,
324+ shared: &Shared,
325+ settings: &ExportSettings,
326+) -> crate::Result<()> {
327+ let total = project.timeline_frames();
328+ let sources = project.sources();
329+ // Audio first: a track has to be declared when the muxer is created, which
330+ // happens as soon as the first coded picture arrives. None of it for AV1 --
331+ // that one is picture only, for the reason [`Format::Av1`] states -- and no
332+ // refusal of it either: a timeline with sound is exported as the video it
333+ // also is, and the front-end says the sound is not in the file *before* the
334+ // export starts rather than failing it here.
335+ let audio = match settings.format {
336+ Format::Av1 => None,
337+ _ => copy_audio(project, meta)?,
338+ };
294 let audio_params = audio.as_ref().map(|(track, _)| AudioParams {339 let audio_params = audio.as_ref().map(|(track, _)| AudioParams {
295 freq_index: track.freq_index,340 freq_index: track.freq_index,
296 chan_conf: track.chan_conf,341 chan_conf: track.chan_conf,
@@ -366,8 +411,16 @@ fn run(
366 // Grade first, place second: the grade is the clip's own pixels411 // Grade first, place second: the grade is the clip's own pixels
367 // and the bars around them are not the clip (see `scale::Composer`).412 // and the bars around them are not the clip (see `scale::Composer`).
368 let (y, u, v, width, height) = canvas.place(y, u, v, width, height);413 let (y, u, v, width, height) = canvas.place(y, u, v, width, height);
369- if let Some(au) = encoder.encode(y, u, v, width, height)? {414+ if let Some((au, key)) = encoder.encode(y, u, v, width, height)? {
370- write_video(&mut muxer, out, meta, audio_params.as_ref(), au)?;415+ write_video(
416+ &mut muxer,
417+ out,
418+ meta,
419+ settings,
420+ audio_params.as_ref(),
421+ au,
422+ key,
423+ )?;
371 }424 }
372 done += 1;425 done += 1;
373 shared426 shared
@@ -375,21 +428,33 @@ fn run(
375 .store(done * PROGRESS_SCALE / total.max(1), Ordering::Relaxed);428 .store(done * PROGRESS_SCALE / total.max(1), Ordering::Relaxed);
376 }429 }
377 }430 }
378- while let Some(au) = encoder.drain()? {431+ while let Some((au, key)) = encoder.drain()? {
379- write_video(&mut muxer, out, meta, audio_params.as_ref(), au)?;432+ write_video(
433+ &mut muxer,
434+ out,
435+ meta,
436+ settings,
437+ audio_params.as_ref(),
438+ au,
439+ key,
440+ )?;
380 }441 }
381 // Progress reads 100% from here on, but nothing is published yet: draining,442 // Progress reads 100% from here on, but nothing is published yet: draining,
382 // the audio pass and `finish` are all still cancellable.443 // the audio pass and `finish` are all still cancellable.
383 cancelled(shared)?;444 cancelled(shared)?;
384 445
385- let Some(mut muxer) = muxer else {446+ let Some(muxer) = muxer else {
386 return Err("export produced no coded pictures".into());447 return Err("export produced no coded pictures".into());
387 };448 };
388- if let Some((_, packets)) = audio {449+ let muxer = match (muxer, audio) {
389- for packet in packets {450+ (Muxer::Mp4(mut mp4), Some((_, packets))) => {
390- muxer.write_audio_packet(&packet.bytes)?;451+ for packet in packets {
452+ mp4.write_audio_packet(&packet.bytes)?;
453+ }
454+ Muxer::Mp4(mp4)
391 }455 }
392- }456+ (muxer, _) => muxer,
457+ };
393 cancelled(shared)?;458 cancelled(shared)?;
394 muxer.finish()?;459 muxer.finish()?;
395 shared.progress.store(PROGRESS_SCALE, Ordering::Relaxed);460 shared.progress.store(PROGRESS_SCALE, Ordering::Relaxed);
@@ -471,7 +536,7 @@ fn run_audio(
471 match format {536 match format {
472 Format::Wav => write_wav(out, &samples, &audio)?,537 Format::Wav => write_wav(out, &samples, &audio)?,
473 Format::Flac => write_flac(out, &samples, &audio)?,538 Format::Flac => write_flac(out, &samples, &audio)?,
474- Format::Mp4 => unreachable!("the mp4 path is `run`"),539+ Format::Mp4 | Format::Av1 => unreachable!("the picture formats are `run`"),
475 }540 }
476 shared.progress.store(PROGRESS_SCALE, Ordering::Relaxed);541 shared.progress.store(PROGRESS_SCALE, Ordering::Relaxed);
477 Ok(())542 Ok(())
@@ -571,26 +636,72 @@ fn cancelled(shared: &Shared) -> crate::Result<()> {
571 Ok(())636 Ok(())
572 }637 }
573 638
639+/// The two containers an export writes, so the picture loop above is one loop:
640+/// H.264 goes into mp4, AV1 into Matroska, and nothing else is offered.
641+enum Muxer {
642+ Mp4(Mp4Muxer),
643+ Mkv(MkvMuxer),
644+}
645+
646+impl Muxer {
647+ fn finish(self) -> crate::Result<()> {
648+ match self {
649+ Self::Mp4(mp4) => mp4.finish(),
650+ Self::Mkv(mkv) => mkv.finish(),
651+ }
652+ }
653+}
654+
574 /// Writes one access unit, creating the file on the first one -- the parameter655 /// Writes one access unit, creating the file on the first one -- the parameter
575-/// sets for `avcC` only exist once the encoder has coded something. Units with656+/// sets for `avcC` (and the sequence header for `CodecPrivate`) only exist once
576-/// no coded slice are skipped: a software encoder may hand back an empty buffer657+/// the encoder has coded something. Units with no coded slice are skipped: a
577-/// while it buffers, and the muxer rejects a sample that would carry no picture.658+/// software encoder may hand back an empty buffer while it buffers, and the
659+/// muxer rejects a sample that would carry no picture.
578 fn write_video(660 fn write_video(
579- muxer: &mut Option<Mp4Muxer>,661+ muxer: &mut Option<Muxer>,
580 out: &Path,662 out: &Path,
581 meta: &VideoMeta,663 meta: &VideoMeta,
664+ settings: &ExportSettings,
582 audio: Option<&AudioParams>,665 audio: Option<&AudioParams>,
583 au: &[u8],666 au: &[u8],
667+ key: bool,
584 ) -> crate::Result<()> {668 ) -> crate::Result<()> {
669+ if settings.format == Format::Av1 {
670+ let muxer = match muxer {
671+ Some(Muxer::Mkv(mkv)) => mkv,
672+ Some(Muxer::Mp4(_)) => unreachable!("the format picks the muxer once"),
673+ none => {
674+ // Every AV1 stream opens on a keyframe, and a keyframe carries
675+ // the sequence header the track has to declare: an encoder that
676+ // handed back neither has produced nothing a decoder can start.
677+ let config = crate::mux::av1_sequence_header(au)
678+ .ok_or("the first coded picture carries no AV1 sequence header")?;
679+ let Muxer::Mkv(mkv) = none.insert(Muxer::Mkv(MkvMuxer::create(
680+ out,
681+ &Av1Params {
682+ width: meta.width,
683+ height: meta.height,
684+ frame_rate: meta.frame_rate,
685+ config,
686+ },
687+ )?)) else {
688+ unreachable!("just inserted a Matroska muxer")
689+ };
690+ mkv
691+ }
692+ };
693+ return muxer.write_frame(au, key);
694+ }
585 if !crate::mux::has_coded_slice(au) {695 if !crate::mux::has_coded_slice(au) {
586 return Ok(());696 return Ok(());
587 }697 }
588 let muxer = match muxer {698 let muxer = match muxer {
589- Some(muxer) => muxer,699+ Some(Muxer::Mp4(mp4)) => mp4,
700+ Some(Muxer::Mkv(_)) => unreachable!("the format picks the muxer once"),
590 none => {701 none => {
591 let (sps, pps) = crate::mux::parameter_sets(au)702 let (sps, pps) = crate::mux::parameter_sets(au)
592 .ok_or("the first coded picture carries no SPS/PPS")?;703 .ok_or("the first coded picture carries no SPS/PPS")?;
593- none.insert(Mp4Muxer::create(704+ let Muxer::Mp4(mp4) = none.insert(Muxer::Mp4(Mp4Muxer::create(
594 out,705 out,
595 &VideoParams {706 &VideoParams {
596 width: meta.width,707 width: meta.width,
@@ -600,7 +711,10 @@ fn write_video(
600 pps,711 pps,
601 },712 },
602 audio,713 audio,
603- )?)714+ )?)) else {
715+ unreachable!("just inserted an mp4 muxer")
716+ };
717+ mp4
604 }718 }
605 };719 };
606 muxer.write_video_au(au)720 muxer.write_video_au(au)
@@ -616,7 +730,10 @@ fn forced(var: &str) -> bool {
616 }730 }
617 731
618 /// Hardware where it is available, software everywhere else -- chosen once for732 /// Hardware where it is available, software everywhere else -- chosen once for
619-/// the whole export, so the stream never changes encoder mid-file.733+/// the whole export, so the stream never changes encoder mid-file. Both codecs
734+/// have both seats: an AV1 export runs on the plugin's VA-API encoder where the
735+/// GPU has one and on `rav1e` where it has not, which is the same pair H.264 has
736+/// had and the same silent fallback.
620 enum Enc {737 enum Enc {
621 Hw(HwEncoder),738 Hw(HwEncoder),
622 Sw {739 Sw {
@@ -626,10 +743,26 @@ enum Enc {
626 au: Vec<u8>,743 au: Vec<u8>,
627 flushed: bool,744 flushed: bool,
628 },745 },
746+ /// AV1 on the GPU, through the same plugin the H.264 seat uses.
747+ Av1Hw(HwEncoder),
748+ Av1Sw {
749+ context: rav1e::Context<u8>,
750+ /// Temporal units the encoder has finished but the caller has not
751+ /// collected: `rav1e` reorders and may hand back several at once, while
752+ /// this interface is one picture in, one unit out (the plugin's own
753+ /// `ready` queue exists for the same reason).
754+ ready: std::collections::VecDeque<(Vec<u8>, bool)>,
755+ /// The unit currently lent out, for the same reason `Sw` owns one.
756+ au: Vec<u8>,
757+ flushed: bool,
758+ },
629 }759 }
630 760
631 impl Enc {761 impl Enc {
632 fn open(meta: &VideoMeta, settings: &ExportSettings) -> crate::Result<Self> {762 fn open(meta: &VideoMeta, settings: &ExportSettings) -> crate::Result<Self> {
763+ if settings.format == Format::Av1 {
764+ return Self::open_av1(meta, settings);
765+ }
633 // A caller's number goes through the same clamp as the computed one: a766 // A caller's number goes through the same clamp as the computed one: a
634 // zero bitrate switches the software encoder's lookahead on, which would767 // zero bitrate switches the software encoder's lookahead on, which would
635 // break the one-picture-per-call contract `encode` documents below.768 // break the one-picture-per-call contract `encode` documents below.
@@ -667,7 +800,75 @@ impl Enc {
667 })800 })
668 }801 }
669 802
670- /// One picture in, at most one access unit out.803+ /// The AV1 pair. The hardware seat is the plugin's, opened by a symbol of
804+ /// its own (`vh_enc_av1_open`) so a plugin built before AV1 encode existed
805+ /// simply has none and this falls through -- the same "no" a GPU without an
806+ /// AV1 encode entrypoint gives, and the same silent fallback either way.
807+ ///
808+ /// It is **opt-in**, which is the one place this pair does not mirror the
809+ /// H.264 one: the vendored cros-codecs AV1 encoder hung the GPU on this
810+ /// project's own radeonsi box -- `engine_hw: operation failed`, then an
811+ /// amdgpu hard recovery and a lost context, measured 2026-08-10 exporting
812+ /// the 720p fixture. A software encoder that takes half a minute is a worse
813+ /// export than a hardware one; a driver reset is not an export at all. So
814+ /// the plugin's AV1 seat is wired, kept and only entered when `VE_HW_AV1=1`
815+ /// asks for it by name.
816+ ///
817+ /// ponytail: the upgrade path is a driver this was reproduced against (or a
818+ /// cros-codecs release that fixes it) plus a probe encode of one frame at
819+ /// open, after which this can prefer hardware the way H.264 does.
820+ fn open_av1(meta: &VideoMeta, settings: &ExportSettings) -> crate::Result<Self> {
821+ let bitrate = settings
822+ .bitrate
823+ .map_or_else(|| bitrate_for(meta), |b| b.clamp(MIN_BITRATE, MAX_BITRATE));
824+ let (fps_num, fps_den) = crate::mux::frame_timing(meta.frame_rate)?;
825+ // Two seconds between keyframes, as the H.264 seat does: a seek may only
826+ // land on one, and this is what a cluster of the Matroska file is.
827+ let gop = (meta.frame_rate * 2.0).round().max(1.0) as u64;
828+ if forced("VE_HW_AV1")
829+ && !settings.force_sw
830+ && !forced("VE_SW_ENC")
831+ && let Some(hw) =
832+ HwEncoder::open_av1(meta.width, meta.height, fps_num, fps_den, bitrate)
833+ {
834+ eprintln!("export encoder: hardware AV1 (VA-API plugin)");
835+ return Ok(Self::Av1Hw(hw));
836+ }
837+ eprintln!("export encoder: software AV1 (rav1e)");
838+ let mut cfg = rav1e::EncoderConfig::default();
839+ cfg.width = meta.width as usize;
840+ cfg.height = meta.height as usize;
841+ cfg.bit_depth = 8;
842+ cfg.chroma_sampling = rav1e::prelude::ChromaSampling::Cs420;
843+ // Seconds per frame, which is what `frame_timing` already has as an
844+ // exact rational -- 1001/24000 rather than a rounded 23.976.
845+ cfg.time_base = rav1e::prelude::Rational::new(u64::from(fps_den), u64::from(fps_num));
846+ cfg.min_key_frame_interval = gop;
847+ cfg.max_key_frame_interval = gop;
848+ cfg.bitrate = bitrate.min(i32::MAX as u64) as i32;
849+ // The fastest preset there is, and it is still slow: `rav1e` is built
850+ // here without its assembly (no `nasm` in this project's build), so an
851+ // export runs at a fraction of realtime. The export worker reports
852+ // progress the whole way, which is what makes that bearable rather than
853+ // hidden.
854+ cfg.speed_settings = rav1e::prelude::SpeedSettings::from_preset(AV1_SPEED);
855+ let config = rav1e::Config::new()
856+ .with_encoder_config(cfg)
857+ .with_threads(std::thread::available_parallelism().map_or(1, |n| n.get()));
858+ let context = config
859+ .new_context::<u8>()
860+ .map_err(|e| format!("software AV1 encoder: {e}"))?;
861+ Ok(Self::Av1Sw {
862+ context,
863+ ready: std::collections::VecDeque::new(),
864+ au: Vec::new(),
865+ flushed: false,
866+ })
867+ }
868+
869+ /// One picture in, at most one access unit out, and whether that unit is one
870+ /// a decoder may be started from -- which only the Matroska muxer asks, the
871+ /// mp4 one reading its own sync flag off the IDR slice.
671 ///872 ///
672 /// ponytail: `rusty_h264` buffers a whole GOP and returns it in one buffer873 /// ponytail: `rusty_h264` buffers a whole GOP and returns it in one buffer
673 /// when its lookahead is active, which would make this "one access unit"874 /// when its lookahead is active, which would make this "one access unit"
@@ -681,9 +882,35 @@ impl Enc {
681 v: &[u8],882 v: &[u8],
682 width: u32,883 width: u32,
683 height: u32,884 height: u32,
684- ) -> crate::Result<Option<&[u8]>> {885+ ) -> crate::Result<Option<(&[u8], bool)>> {
685 match self {886 match self {
686- Self::Hw(hw) => hw.encode(y, u, v, width, height, false),887+ Self::Av1Hw(hw) => {
888+ let au = hw.encode(y, u, v, width, height, false)?;
889+ // What the *bitstream* says, not what was asked for: an AV1
890+ // keyframe carries the sequence header, which is the same mark
891+ // `demux` reads a sync point off. A driver that emitted one
892+ // unasked is then still a seek target, and one that skipped a
893+ // requested keyframe cannot be mistaken for a decoder's start.
894+ Ok(au.map(|au| (au, crate::mux::av1_sequence_header(au).is_some())))
895+ }
896+ Self::Av1Sw {
897+ context, ready, au, ..
898+ } => {
899+ let mut frame = context.new_frame();
900+ let (w, h) = (width as usize, height as usize);
901+ let (cw, ch) = (w.div_ceil(2), h.div_ceil(2));
902+ frame.planes[0].copy_from_raw_u8(&y[..w * h], w, 1);
903+ frame.planes[1].copy_from_raw_u8(&u[..cw * ch], cw, 1);
904+ frame.planes[2].copy_from_raw_u8(&v[..cw * ch], cw, 1);
905+ if let Err(e) = context.send_frame(frame) {
906+ return Err(format!("software AV1 encode: {e}").into());
907+ }
908+ collect_av1(context, ready)?;
909+ Ok(pop_av1(ready, au))
910+ }
911+ Self::Hw(hw) => Ok(hw
912+ .encode(y, u, v, width, height, false)?
913+ .map(|au| (au, false))),
687 Self::Sw { encoder, au, .. } => {914 Self::Sw { encoder, au, .. } => {
688 let frame = YuvFrame {915 let frame = YuvFrame {
689 width: width as usize,916 width: width as usize,
@@ -695,15 +922,32 @@ impl Enc {
695 *au = encoder922 *au = encoder
696 .try_encode(&frame)923 .try_encode(&frame)
697 .map_err(|e| format!("software encode: {e}"))?;924 .map_err(|e| format!("software encode: {e}"))?;
698- Ok(Some(&au[..]).filter(|au| !au.is_empty()))925+ Ok(Some((&au[..], false)).filter(|(au, _)| !au.is_empty()))
699 }926 }
700 }927 }
701 }928 }
702 929
703 /// End of stream; call until it returns `None`.930 /// End of stream; call until it returns `None`.
704- fn drain(&mut self) -> crate::Result<Option<&[u8]>> {931+ fn drain(&mut self) -> crate::Result<Option<(&[u8], bool)>> {
705 match self {932 match self {
706- Self::Hw(hw) => hw.drain(),933+ Self::Av1Hw(hw) => {
934+ let au = hw.drain()?;
935+ Ok(au.map(|au| (au, crate::mux::av1_sequence_header(au).is_some())))
936+ }
937+ Self::Av1Sw {
938+ context,
939+ ready,
940+ au,
941+ flushed,
942+ } => {
943+ if !*flushed {
944+ *flushed = true;
945+ context.flush();
946+ collect_av1(context, ready)?;
947+ }
948+ Ok(pop_av1(ready, au))
949+ }
950+ Self::Hw(hw) => Ok(hw.drain()?.map(|au| (au, false))),
707 Self::Sw {951 Self::Sw {
708 encoder,952 encoder,
709 au,953 au,
@@ -716,12 +960,43 @@ impl Enc {
716 *au = encoder960 *au = encoder
717 .try_flush()961 .try_flush()
718 .map_err(|e| format!("software encoder flush: {e}"))?;962 .map_err(|e| format!("software encoder flush: {e}"))?;
719- Ok(Some(&au[..]).filter(|au| !au.is_empty()))963+ Ok(Some((&au[..], false)).filter(|(au, _)| !au.is_empty()))
720 }964 }
721 }965 }
722 }966 }
723 }967 }
724 968
969+/// Every temporal unit `rav1e` has finished, moved into the queue in display
970+/// order. `NeedMoreData` (send another picture) and `LimitReached` (the flush is
971+/// through) are the two ways it says there is nothing more; `Encoded` means a
972+/// picture was coded but not yet packetised, which is a *keep asking* -- taking
973+/// it for an end leaves the tail of the export inside the encoder.
974+fn collect_av1(
975+ context: &mut rav1e::Context<u8>,
976+ ready: &mut std::collections::VecDeque<(Vec<u8>, bool)>,
977+) -> crate::Result<()> {
978+ use rav1e::prelude::{EncoderStatus, FrameType};
979+ loop {
980+ match context.receive_packet() {
981+ Ok(packet) => ready.push_back((packet.data, packet.frame_type == FrameType::KEY)),
982+ Err(EncoderStatus::Encoded) => {}
983+ Err(EncoderStatus::NeedMoreData | EncoderStatus::LimitReached) => return Ok(()),
984+ Err(e) => return Err(format!("software AV1 encode: {e}").into()),
985+ }
986+ }
987+}
988+
989+/// The oldest finished unit, moved into the buffer that is lent out -- the same
990+/// "valid until the next call" contract the plugin's slice has.
991+fn pop_av1<'a>(
992+ ready: &mut std::collections::VecDeque<(Vec<u8>, bool)>,
993+ au: &'a mut Vec<u8>,
994+) -> Option<(&'a [u8], bool)> {
995+ let (unit, key) = ready.pop_front()?;
996+ *au = unit;
997+ Some((&au[..], key))
998+}
999+
725 /// I420 straight out of the decoder: the export never converts to BGRA and back,1000 /// I420 straight out of the decoder: the export never converts to BGRA and back,
726 /// which would cost two conversions and a generation of colour precision.1001 /// which would cost two conversions and a generation of colour precision.
727 ///1002 ///
crates/engine/src/hw.rsmodified+52 -1
@@ -200,6 +200,13 @@ unsafe impl Send for HwSession {}
200 200
201 struct EncPlugin {201 struct EncPlugin {
202 open: extern "C" fn(u32, u32, u32, u32, u64) -> *mut c_void,202 open: extern "C" fn(u32, u32, u32, u32, u64) -> *mut c_void,
203+ /// The AV1 seat, and the one symbol that may be missing: a plugin built
204+ /// before AV1 encode existed exports the four below and not this, which
205+ /// costs an AV1 export its hardware path and nothing else. Every session it
206+ /// opens is fed and closed through the very same three entry points -- the
207+ /// plugin keeps one session type for both codecs, so the codec is decided
208+ /// once, at the open, exactly as the H.264 seat's parameters are.
209+ open_av1: Option<extern "C" fn(u32, u32, u32, u32, u64) -> *mut c_void>,
203 frame:210 frame:
204 unsafe extern "C" fn(*mut c_void, *const VhFrame, i32, *mut *const u8, *mut usize) -> i32,211 unsafe extern "C" fn(*mut c_void, *const VhFrame, i32, *mut *const u8, *mut usize) -> i32,
205 drain: unsafe extern "C" fn(*mut c_void, *mut *const u8, *mut usize) -> i32,212 drain: unsafe extern "C" fn(*mut c_void, *mut *const u8, *mut usize) -> i32,
@@ -225,6 +232,7 @@ fn load_enc() -> Option<EncPlugin> {
225 (|| {232 (|| {
226 Some(EncPlugin {233 Some(EncPlugin {
227 open: *lib.get(b"vh_enc_open\0").ok()?,234 open: *lib.get(b"vh_enc_open\0").ok()?,
235+ open_av1: lib.get(b"vh_enc_av1_open\0").ok().map(|s| *s),
228 frame: *lib.get(b"vh_enc_frame\0").ok()?,236 frame: *lib.get(b"vh_enc_frame\0").ok()?,
229 drain: *lib.get(b"vh_enc_drain\0").ok()?,237 drain: *lib.get(b"vh_enc_drain\0").ok()?,
230 close: *lib.get(b"vh_enc_close\0").ok()?,238 close: *lib.get(b"vh_enc_close\0").ok()?,
@@ -253,7 +261,50 @@ impl HwEncoder {
253 /// falls back to the software encoder.261 /// falls back to the software encoder.
254 pub fn open(width: u32, height: u32, fps_num: u32, fps_den: u32, bitrate: u64) -> Option<Self> {262 pub fn open(width: u32, height: u32, fps_num: u32, fps_den: u32, bitrate: u64) -> Option<Self> {
255 let plugin = enc_plugin()?;263 let plugin = enc_plugin()?;
256- let handle = (plugin.open)(width, height, fps_num, fps_den, bitrate);264+ Self::opened(
265+ plugin,
266+ plugin.open,
267+ width,
268+ height,
269+ fps_num,
270+ fps_den,
271+ bitrate,
272+ )
273+ }
274+
275+ /// The same, coding AV1 instead. `None` on everything [`HwEncoder::open`]
276+ /// answers `None` to *and* on a plugin or a GPU with no AV1 encoder -- an
277+ /// AV1 encode entrypoint is recent hardware, so this is the fallback that
278+ /// really fires, and the caller's software AV1 encoder takes the export
279+ /// without saying anything about it.
280+ ///
281+ /// The caller only reaches this behind `VE_HW_AV1=1`: the vendored encoder
282+ /// reset this project's own GPU, which [`crate::export::Enc::open_av1`]
283+ /// states in full.
284+ pub fn open_av1(
285+ width: u32,
286+ height: u32,
287+ fps_num: u32,
288+ fps_den: u32,
289+ bitrate: u64,
290+ ) -> Option<Self> {
291+ let plugin = enc_plugin()?;
292+ let open = plugin.open_av1?;
293+ Self::opened(plugin, open, width, height, fps_num, fps_den, bitrate)
294+ }
295+
296+ /// The null check both opens share, which is the plugin's whole way of
297+ /// saying "no".
298+ fn opened(
299+ plugin: &'static EncPlugin,
300+ open: extern "C" fn(u32, u32, u32, u32, u64) -> *mut c_void,
301+ width: u32,
302+ height: u32,
303+ fps_num: u32,
304+ fps_den: u32,
305+ bitrate: u64,
306+ ) -> Option<Self> {
307+ let handle = open(width, height, fps_num, fps_den, bitrate);
257 if handle.is_null() {308 if handle.is_null() {
258 return None;309 return None;
259 }310 }
crates/engine/src/mux.rsmodified+427 -1
@@ -1,8 +1,13 @@
1 //! Annex-B -> MP4, the mirror of `demux`: encoders emit start-code framed NALs,1 //! Annex-B -> MP4, the mirror of `demux`: encoders emit start-code framed NALs,
2 //! an mp4 sample wants 4-byte length prefixes with SPS/PPS living in `avcC`.2 //! an mp4 sample wants 4-byte length prefixes with SPS/PPS living in `avcC`.
3+//!
4+//! ...and AV1 -> Matroska, the mirror of the *other* half of `demux`, for the
5+//! same reason that half exists: `mp4 0.14` has no `av01` sample entry at all,
6+//! so an AV1 export is written as EBML by hand exactly as an AV1 import is read
7+//! as EBML by hand ([`MkvMuxer`]).
3 8
4 use std::fs::File;9 use std::fs::File;
5-use std::io::BufWriter;10+use std::io::{BufWriter, Seek, SeekFrom, Write};
6 use std::path::Path;11 use std::path::Path;
7 12
8 use mp4::{13 use mp4::{
@@ -177,6 +182,323 @@ impl Mp4Muxer {
177 }182 }
178 }183 }
179 184
185+// Matroska element ids, written with the leading length marker they carry in the
186+// file -- the same spelling `demux` reads them back with.
187+const EBML: u32 = 0x1A45_DFA3;
188+const EBML_VERSION: u32 = 0x4286;
189+const EBML_READ_VERSION: u32 = 0x42F7;
190+const EBML_MAX_ID_LENGTH: u32 = 0x42F2;
191+const EBML_MAX_SIZE_LENGTH: u32 = 0x42F3;
192+const DOC_TYPE: u32 = 0x4282;
193+const DOC_TYPE_VERSION: u32 = 0x4287;
194+const DOC_TYPE_READ_VERSION: u32 = 0x4285;
195+const SEGMENT: u32 = 0x1853_8067;
196+const INFO: u32 = 0x1549_A966;
197+const TIMESTAMP_SCALE: u32 = 0x2AD7B1;
198+const DURATION: u32 = 0x4489;
199+const MUXING_APP: u32 = 0x4D80;
200+const WRITING_APP: u32 = 0x5741;
201+const TRACKS: u32 = 0x1654_AE6B;
202+const TRACK_ENTRY: u32 = 0xAE;
203+const TRACK_NUMBER: u32 = 0xD7;
204+const TRACK_UID: u32 = 0x73C5;
205+const TRACK_TYPE: u32 = 0x83;
206+const FLAG_LACING: u32 = 0x9C;
207+const CODEC_ID: u32 = 0x86;
208+const CODEC_PRIVATE: u32 = 0x63A2;
209+const DEFAULT_DURATION: u32 = 0x23E383;
210+const VIDEO: u32 = 0xE0;
211+const PIXEL_WIDTH: u32 = 0xB0;
212+const PIXEL_HEIGHT: u32 = 0xBA;
213+const CLUSTER: u32 = 0x1F43_B675;
214+const CLUSTER_TIMESTAMP: u32 = 0xE7;
215+const SIMPLE_BLOCK: u32 = 0xA3;
216+
217+/// One millisecond, the tick every Matroska muxer writes and this one's block
218+/// timestamps are in. The *rate* is not derived from these -- `DefaultDuration`
219+/// is, in exact nanoseconds -- so a millisecond is precise enough for the
220+/// presentation times and coarse enough to keep a cluster's 16-bit relative
221+/// timestamp covering half a minute.
222+const TIMESTAMP_SCALE_NS: u64 = 1_000_000;
223+/// A cluster is buffered whole (its size is a header field), so it is flushed
224+/// at the first keyframe past this -- a ceiling on what the muxer holds, not a
225+/// target.
226+const CLUSTER_BYTES: usize = 4 << 20;
227+/// ...and on how far a block's timestamp may sit from its cluster's: the field
228+/// is a signed 16-bit millisecond count.
229+const CLUSTER_MS: i64 = 30_000;
230+
231+/// The fixed four bytes of an `AV1CodecConfigurationRecord` for what both encode
232+/// paths here are configured to produce: profile 0, 8-bit, 4:2:0, no operating
233+/// point delay. `seq_level_idx` is written as 31 -- "maximum parameters", i.e.
234+/// unstated -- which is what rav1e's own `container_sequence_header` writes and
235+/// what keeps this record from claiming a level neither encoder promised. The
236+/// sequence header OBU follows it; that is where a decoder reads the real
237+/// parameters from, and `demux::parse_av1c` hands exactly those bytes back.
238+const AV1C_HEAD: [u8; 4] = [
239+ 0x81, // marker 1, version 1
240+ 0x1F, // seq_profile 0, seq_level_idx_0 31
241+ 0x0C, // tier 0, 8-bit, colour, chroma subsampled both ways
242+ 0x00, // no initial presentation delay
243+];
244+
245+/// What an AV1 Matroska track declares. `config` is the sequence header OBU,
246+/// which is [`av1_sequence_header`]'s answer for the first coded keyframe.
247+pub struct Av1Params<'a> {
248+ pub width: u32,
249+ pub height: u32,
250+ pub frame_rate: f64,
251+ pub config: &'a [u8],
252+}
253+
254+/// Writes one AV1 video track as Matroska (`.mkv`). Picture only: this project
255+/// has no encoder for any sound Matroska carries, and copying the timeline's AAC
256+/// in would write a track its own reader refuses (`audio::AudioSession::open`
257+/// leaves a Matroska file silent) -- so the sound is named as left out by the
258+/// front-end rather than written unplayable.
259+///
260+/// The file is patched twice at [`finish`](MkvMuxer::finish) -- the segment size
261+/// and the duration -- so a killed process leaves an unfinished file rather than
262+/// a wrong one; the export's `.part` rename covers that already.
263+pub struct MkvMuxer {
264+ file: File,
265+ /// Nanoseconds a frame lasts: `DefaultDuration`, which is the *only* exact
266+ /// statement of the frame rate in the file (see `demux::MkvDemuxer::open`).
267+ frame_ns: u64,
268+ segment_size_at: u64,
269+ duration_at: u64,
270+ /// The cluster being built: everything after its id and size, so it can be
271+ /// written once its length is known.
272+ cluster: Vec<u8>,
273+ cluster_ts: i64,
274+ frames: u64,
275+}
276+
277+impl MkvMuxer {
278+ pub fn create(path: &Path, video: &Av1Params) -> crate::Result<Self> {
279+ if !video.frame_rate.is_finite() || video.frame_rate <= 0.0 {
280+ return Err(format!("bad frame rate {}", video.frame_rate).into());
281+ }
282+ if video.width == 0 || video.height == 0 {
283+ return Err(format!("bad dimensions {}x{}", video.width, video.height).into());
284+ }
285+ let frame_ns = (1e9 / video.frame_rate).round() as u64;
286+ if frame_ns == 0 {
287+ return Err(format!("frame rate {} is too fast to time", video.frame_rate).into());
288+ }
289+ if video.config.is_empty() {
290+ return Err("no AV1 sequence header for the track's CodecPrivate".into());
291+ }
292+
293+ let mut head = Vec::new();
294+ let mut ebml = Vec::new();
295+ uint(&mut ebml, EBML_VERSION, 1);
296+ uint(&mut ebml, EBML_READ_VERSION, 1);
297+ uint(&mut ebml, EBML_MAX_ID_LENGTH, 4);
298+ uint(&mut ebml, EBML_MAX_SIZE_LENGTH, 8);
299+ elem(&mut ebml, DOC_TYPE, b"matroska");
300+ uint(&mut ebml, DOC_TYPE_VERSION, 4);
301+ uint(&mut ebml, DOC_TYPE_READ_VERSION, 2);
302+ elem(&mut head, EBML, &ebml);
303+
304+ // The segment's size is only known at `finish`; it is reserved at the
305+ // widest encoding (8 bytes) so patching it never moves a byte after it.
306+ put_id(&mut head, SEGMENT);
307+ let segment_size_at = head.len() as u64;
308+ head.extend_from_slice(&[0x01, 0, 0, 0, 0, 0, 0, 0]);
309+
310+ let mut info = Vec::new();
311+ uint(&mut info, TIMESTAMP_SCALE, TIMESTAMP_SCALE_NS);
312+ elem(&mut info, MUXING_APP, b"edith");
313+ elem(&mut info, WRITING_APP, b"edith");
314+ put_id(&mut info, DURATION);
315+ put_size(&mut info, 8);
316+ // Where those eight bytes will land once `Info` is written into `head`,
317+ // which is what `finish` seeks back to.
318+ let duration_at = (head.len() + elem_head_len(INFO, info.len() + 8) + info.len()) as u64;
319+ info.extend_from_slice(&0f64.to_be_bytes());
320+ elem(&mut head, INFO, &info);
321+
322+ let mut entry = Vec::new();
323+ uint(&mut entry, TRACK_NUMBER, 1);
324+ uint(&mut entry, TRACK_UID, 1);
325+ uint(&mut entry, TRACK_TYPE, 1); // video
326+ uint(&mut entry, FLAG_LACING, 0);
327+ elem(&mut entry, CODEC_ID, b"V_AV1");
328+ let mut av1c = AV1C_HEAD.to_vec();
329+ av1c.extend_from_slice(video.config);
330+ elem(&mut entry, CODEC_PRIVATE, &av1c);
331+ uint(&mut entry, DEFAULT_DURATION, frame_ns);
332+ let mut dims = Vec::new();
333+ uint(&mut dims, PIXEL_WIDTH, u64::from(video.width));
334+ uint(&mut dims, PIXEL_HEIGHT, u64::from(video.height));
335+ elem(&mut entry, VIDEO, &dims);
336+ let mut tracks = Vec::new();
337+ elem(&mut tracks, TRACK_ENTRY, &entry);
338+ elem(&mut head, TRACKS, &tracks);
339+
340+ let mut file = File::create(path)?;
341+ file.write_all(&head)?;
342+ Ok(Self {
343+ file,
344+ frame_ns,
345+ segment_size_at,
346+ duration_at,
347+ cluster: Vec::new(),
348+ cluster_ts: 0,
349+ frames: 0,
350+ })
351+ }
352+
353+ /// One coded picture: a whole AV1 temporal unit, in the low-overhead OBU
354+ /// format the demuxer hands back. `key` marks a block a decoder may be
355+ /// started from -- said by the encoder rather than guessed at here, and a
356+ /// keyframe is where a new cluster opens, so every seek target is one.
357+ pub fn write_frame(&mut self, obus: &[u8], key: bool) -> crate::Result<()> {
358+ if obus.is_empty() {
359+ return Err("an empty AV1 temporal unit".into());
360+ }
361+ let ts = (self.frames * self.frame_ns + TIMESTAMP_SCALE_NS / 2) as i64
362+ / TIMESTAMP_SCALE_NS as i64;
363+ // A new cluster at every keyframe -- a seek lands on one, so a cluster
364+ // is a whole GOP -- and at the two limits a cluster has whatever the
365+ // encoder keys: what it may weigh, and how far a 16-bit relative
366+ // timestamp reaches.
367+ if self.cluster.is_empty()
368+ || key
369+ || self.cluster.len() >= CLUSTER_BYTES
370+ || ts - self.cluster_ts >= CLUSTER_MS
371+ {
372+ self.flush()?;
373+ self.cluster_ts = ts;
374+ uint(&mut self.cluster, CLUSTER_TIMESTAMP, ts as u64);
375+ }
376+ let mut block = Vec::with_capacity(obus.len() + 4);
377+ block.push(0x81); // track number 1, as a one-byte EBML integer
378+ block.extend_from_slice(&((ts - self.cluster_ts) as i16).to_be_bytes());
379+ block.push(if key { 0x80 } else { 0 });
380+ block.extend_from_slice(obus);
381+ elem(&mut self.cluster, SIMPLE_BLOCK, &block);
382+ self.frames += 1;
383+ Ok(())
384+ }
385+
386+ fn flush(&mut self) -> crate::Result<()> {
387+ if self.cluster.is_empty() {
388+ return Ok(());
389+ }
390+ let mut head = Vec::new();
391+ put_id(&mut head, CLUSTER);
392+ put_size(&mut head, self.cluster.len() as u64);
393+ self.file.write_all(&head)?;
394+ self.file.write_all(&self.cluster)?;
395+ self.cluster.clear();
396+ Ok(())
397+ }
398+
399+ /// Closes the last cluster and patches the two fields that could not be
400+ /// known while writing: the segment's size and the presentation duration.
401+ pub fn finish(mut self) -> crate::Result<()> {
402+ self.flush()?;
403+ if self.frames == 0 {
404+ return Err("no frames were written to the Matroska file".into());
405+ }
406+ let end = self.file.stream_position()?;
407+ let body = end - (self.segment_size_at + 8);
408+ // The reserved 8-byte size: marker bit in the top byte, value under it.
409+ let size = (1u64 << 56) | body;
410+ self.file.seek(SeekFrom::Start(self.segment_size_at))?;
411+ self.file.write_all(&size.to_be_bytes())?;
412+ let ms = self.frames as f64 * self.frame_ns as f64 / TIMESTAMP_SCALE_NS as f64;
413+ self.file.seek(SeekFrom::Start(self.duration_at))?;
414+ self.file.write_all(&ms.to_be_bytes())?;
415+ self.file.flush()?;
416+ Ok(())
417+ }
418+}
419+
420+/// The sequence header OBU of a coded temporal unit, for the track's
421+/// `CodecPrivate`. `None` when the unit carries none, which the first keyframe
422+/// of a stream never may -- no decoder can start without it.
423+pub fn av1_sequence_header(obus: &[u8]) -> Option<&[u8]> {
424+ let mut at = 0;
425+ while at < obus.len() {
426+ let header = obus[at];
427+ // OBU header: type in bits 6..3, then the extension and size flags.
428+ let kind = (header >> 3) & 0xF;
429+ let mut len = 1 + usize::from(header & 0x4 != 0);
430+ // Only the low-overhead format is written or read here: an OBU with no
431+ // size field runs to the end of the unit, which makes the rest of it
432+ // unwalkable, so it is not something to guess at.
433+ if header & 0x2 == 0 {
434+ return None;
435+ }
436+ let (size, size_len) = leb128(obus.get(at + len..)?)?;
437+ len += size_len;
438+ let body = obus.get(at + len..at + len + size)?;
439+ if kind == 1 {
440+ return Some(&obus[at..at + len + body.len()]);
441+ }
442+ at += len + size;
443+ }
444+ None
445+}
446+
447+/// An unsigned LEB128 as AV1 writes its OBU sizes: `(value, bytes read)`.
448+fn leb128(buf: &[u8]) -> Option<(usize, usize)> {
449+ let mut value = 0usize;
450+ for (i, &byte) in buf.iter().take(8).enumerate() {
451+ value |= usize::from(byte & 0x7F) << (i * 7);
452+ if byte & 0x80 == 0 {
453+ return Some((value, i + 1));
454+ }
455+ }
456+ None
457+}
458+
459+/// An element id, written as the bytes it is spelled with -- the leading zeros
460+/// of the constant are not part of it.
461+fn put_id(out: &mut Vec<u8>, id: u32) {
462+ let bytes = id.to_be_bytes();
463+ let skip = bytes.iter().take_while(|&&b| b == 0).count();
464+ out.extend_from_slice(&bytes[skip..]);
465+}
466+
467+/// An element size as an EBML variable-length integer, in the fewest bytes that
468+/// hold it. A value of all ones means *unknown* length, so a size that would
469+/// land on one takes a byte more.
470+fn put_size(out: &mut Vec<u8>, size: u64) {
471+ let mut len = 1;
472+ while len < 8 && size >= (1u64 << (7 * len)) - 1 {
473+ len += 1;
474+ }
475+ let value = (1u64 << (7 * len)) | size;
476+ out.extend_from_slice(&value.to_be_bytes()[8 - len..]);
477+}
478+
479+fn elem(out: &mut Vec<u8>, id: u32, payload: &[u8]) {
480+ put_id(out, id);
481+ put_size(out, payload.len() as u64);
482+ out.extend_from_slice(payload);
483+}
484+
485+/// An unsigned integer element, big-endian in as few bytes as it takes (one at
486+/// the least: a zero is a byte, not an absence).
487+fn uint(out: &mut Vec<u8>, id: u32, value: u64) {
488+ let bytes = value.to_be_bytes();
489+ let skip = bytes.iter().take_while(|&&b| b == 0).count().min(7);
490+ elem(out, id, &bytes[skip..]);
491+}
492+
493+/// How many bytes an element's id and size take, which is what an offset inside
494+/// a payload has to be moved by to become an offset in the file.
495+fn elem_head_len(id: u32, payload: usize) -> usize {
496+ let (mut head, mut size) = (Vec::new(), Vec::new());
497+ put_id(&mut head, id);
498+ put_size(&mut size, payload as u64);
499+ head.len() + size.len()
500+}
501+
180 /// `(timescale, ticks per frame)` for `fps`, chosen so one frame is a *whole*502 /// `(timescale, ticks per frame)` for `fps`, chosen so one frame is a *whole*
181 /// number of ticks: 90 kHz wherever it divides exactly (every integer rate, so503 /// number of ticks: 90 kHz wherever it divides exactly (every integer rate, so
182 /// those exports stay byte for byte what they were), and `round(fps * 1001)`504 /// those exports stay byte for byte what they were), and `round(fps * 1001)`
@@ -484,6 +806,110 @@ mod tests {
484 std::fs::remove_file(&out).unwrap();806 std::fs::remove_file(&out).unwrap();
485 }807 }
486 808
809+ /// One OBU in the low-overhead format: header byte, then a one-byte LEB128
810+ /// size, which is all a payload this short needs.
811+ fn obu(kind: u8, payload: &[u8]) -> Vec<u8> {
812+ let mut out = vec![(kind << 3) | 0x02, payload.len() as u8];
813+ out.extend_from_slice(payload);
814+ out
815+ }
816+
817+ /// An EBML size is written in the fewest bytes that hold it -- and never in
818+ /// a length whose value is all ones, which is the *unknown* size the reader
819+ /// would take for "runs to the end of its parent".
820+ #[test]
821+ fn element_sizes_never_spell_an_unknown_length() {
822+ let size = |n| {
823+ let mut out = Vec::new();
824+ put_size(&mut out, n);
825+ out
826+ };
827+ assert_eq!(size(0), [0x80]);
828+ assert_eq!(size(126), [0xFE]);
829+ assert_eq!(size(127), [0x40, 0x7F], "127 is all ones in one byte");
830+ assert_eq!(size(128), [0x40, 0x80]);
831+ assert_eq!(size(0x3FFE), [0x7F, 0xFE]);
832+ assert_eq!(size(0x3FFF), [0x20, 0x3F, 0xFF], "and again at two bytes");
833+ // Ids are their own bytes, marker and all: that is how `demux` compares
834+ // them, so a one-byte id must not grow leading zeros here.
835+ let mut id = Vec::new();
836+ put_id(&mut id, SIMPLE_BLOCK);
837+ assert_eq!(id, [0xA3]);
838+ let mut id = Vec::new();
839+ put_id(&mut id, CLUSTER);
840+ assert_eq!(id, [0x1F, 0x43, 0xB6, 0x75]);
841+ }
842+
843+ /// The Matroska half of the round trip, with no encoder in it: three coded
844+ /// units out through the muxer and back in through our own demuxer, which is
845+ /// where the hand-written EBML meets the hand-written EBML reader.
846+ #[test]
847+ fn an_av1_track_round_trips_through_our_own_matroska_reader() {
848+ let sequence = obu(1, &[0x11, 0x22, 0x33]);
849+ let mut key = sequence.clone();
850+ key.extend_from_slice(&obu(6, &[0xAA; 8]));
851+ let inter = obu(6, &[0xBB; 5]);
852+
853+ let out = std::env::temp_dir().join(format!("ve_mkv_{}.mkv", std::process::id()));
854+ let config = av1_sequence_header(&key).expect("the keyframe carries one");
855+ assert_eq!(config, &sequence[..], "the sequence header OBU, whole");
856+ let mut muxer = MkvMuxer::create(
857+ &out,
858+ &Av1Params {
859+ width: 640,
860+ height: 360,
861+ frame_rate: 30.0,
862+ config,
863+ },
864+ )
865+ .unwrap();
866+ muxer.write_frame(&key, true).unwrap();
867+ muxer.write_frame(&inter, false).unwrap();
868+ muxer.write_frame(&inter, false).unwrap();
869+ muxer.finish().unwrap();
870+
871+ let (meta, mut demuxer) = crate::demux::Demuxer::open(&out).expect("reopen");
872+ assert_eq!(meta.codec, crate::demux::Codec::Av1);
873+ assert_eq!((meta.width, meta.height), (640, 360));
874+ assert!(
875+ (meta.frame_rate - 30.0).abs() < 1e-6,
876+ "DefaultDuration must state the rate exactly: {}",
877+ meta.frame_rate
878+ );
879+ assert_eq!(meta.frame_count, 3);
880+
881+ // The keyframe comes back with the `CodecPrivate` sequence header in
882+ // front of it, which is the demuxer's own doing -- so what this checks
883+ // is that the record was written and parsed, not that the block grew.
884+ let first = demuxer.next_access_unit().unwrap().unwrap();
885+ assert_eq!(&first[..sequence.len()], &sequence[..]);
886+ assert_eq!(&first[sequence.len()..], &key[..]);
887+ assert_eq!(demuxer.next_access_unit().unwrap().unwrap(), inter);
888+ assert_eq!(demuxer.next_access_unit().unwrap().unwrap(), inter);
889+ assert!(demuxer.next_access_unit().unwrap().is_none());
890+ // One keyframe, so every seek rewinds to it -- and the flag really was
891+ // written, or block 0 would be the answer by default rather than by
892+ // being a sync point.
893+ assert_eq!(demuxer.seek_to_sync_at_or_before(2), 0);
894+
895+ // A track with no sequence header to declare is refused where the
896+ // message still means something, rather than written unplayable.
897+ assert!(
898+ MkvMuxer::create(
899+ &out,
900+ &Av1Params {
901+ width: 640,
902+ height: 360,
903+ frame_rate: 30.0,
904+ config: &[],
905+ },
906+ )
907+ .is_err()
908+ );
909+ assert!(av1_sequence_header(&inter).is_none(), "no sequence header");
910+ std::fs::remove_file(&out).unwrap();
911+ }
912+
487 /// The whole pipe at an NTSC rate: what we write is what we read back, to913 /// The whole pipe at an NTSC rate: what we write is what we read back, to
488 /// the ninth decimal. Before this bug was fixed the same round trip lost914 /// the ninth decimal. Before this bug was fixed the same round trip lost
489 /// 23.976 on the way out (a rounded frame duration) *and* on the way back915 /// 23.976 on the way out (a rounded frame duration) *and* on the way back
crates/engine/tests/av1.rsmodified+169 -1
@@ -224,8 +224,176 @@ fn an_av1_source_exports_as_h264() {
224 handle.result().expect("outcome").expect("export");224 handle.result().expect("outcome").expect("export");
225 225
226 let (written, _) = Demuxer::open(&out).expect("reopen the export");226 let (written, _) = Demuxer::open(&out).expect("reopen the export");
227- assert_eq!(written.codec, Codec::H264, "exports are always H.264");227+ assert_eq!(written.codec, Codec::H264, "the default format is H.264");
228 assert_eq!(written.frame_count, FRAMES, "every timeline frame written");228 assert_eq!(written.frame_count, FRAMES, "every timeline frame written");
229 assert_eq!((written.width, written.height), (1280, 720));229 assert_eq!((written.width, written.height), (1280, 720));
230 let _ = std::fs::remove_file(&out);230 let _ = std::fs::remove_file(&out);
231 }231 }
232+
233+/// A short timeline out of the H.264 fixture, which is what the AV1 export tests
234+/// below write: `rav1e` is built here without its assembly, so the length of the
235+/// timeline is the length of the test.
236+fn short_timeline(frames: f64) -> PlaybackSession {
237+ let mut session = PlaybackSession::open(asset("test_baseline.mp4")).expect("open the fixture");
238+ assert!(session.cut_at(frames / 30.0), "cut at frame {frames}");
239+ assert!(
240+ session.delete_clip(engine::project::Lane::V1, 1),
241+ "drop everything after it"
242+ );
243+ session
244+}
245+
246+fn av1_settings() -> ExportSettings {
247+ ExportSettings {
248+ format: engine::export::Format::Av1,
249+ // The software encoder, on every machine: the hardware twin below is
250+ // where the plugin's AV1 seat is exercised.
251+ force_sw: true,
252+ ..Default::default()
253+ }
254+}
255+
256+fn exported(
257+ session: &PlaybackSession,
258+ name: &str,
259+ settings: &ExportSettings,
260+ limit: Duration,
261+) -> PathBuf {
262+ let out = std::env::temp_dir().join(format!("ve_av1_{name}_{}.mkv", std::process::id()));
263+ let _ = std::fs::remove_file(&out);
264+ let started = Instant::now();
265+ let handle = session.export_to_with(&out, settings);
266+ while !handle.is_finished() {
267+ assert!(
268+ started.elapsed() < limit,
269+ "export did not finish in {limit:?}"
270+ );
271+ std::thread::sleep(Duration::from_millis(20));
272+ }
273+ handle.result().expect("outcome").expect("export");
274+ assert_eq!(handle.progress(), 1.0, "finished at full progress");
275+ let spent = started.elapsed().as_secs_f64();
276+ let frames = (session.timeline_duration() * 30.0).round().max(1.0);
277+ eprintln!(
278+ "{name}: {frames} frames in {spent:.2} s = {:.2} ms/frame",
279+ spent * 1000.0 / frames
280+ );
281+ out
282+}
283+
284+/// The export half of this slice: AV1 out of the software encoder, into a
285+/// Matroska file this project's own demuxer walks back. Nothing installed is
286+/// needed -- the file is *read* as a container here, which is where the
287+/// hand-written EBML either agrees with the hand-written EBML reader or does not.
288+#[test]
289+fn an_av1_export_reopens_through_our_own_demuxer() {
290+ let session = short_timeline(30.0);
291+ let out = exported(&session, "sw", &av1_settings(), Duration::from_secs(300));
292+
293+ let (meta, mut demuxer) = Demuxer::open(&out).expect("reopen the export");
294+ assert_eq!(meta.codec, Codec::Av1, "an AV1 export is AV1");
295+ assert_eq!((meta.width, meta.height), (1280, 720));
296+ assert!(
297+ (meta.frame_rate - 30.0).abs() < 1e-6,
298+ "DefaultDuration must state the rate exactly: {}",
299+ meta.frame_rate
300+ );
301+ assert_eq!(meta.frame_count, 30, "every timeline frame is a block");
302+
303+ // The first block is a keyframe and leads with the sequence header -- the
304+ // demuxer prepends `CodecPrivate` to every keyframe, so this is also the
305+ // check that the `av1C` record was written and parsed back.
306+ let first = demuxer.next_access_unit().expect("read").expect("a unit");
307+ assert_eq!(
308+ (first[0] >> 3) & 0xF,
309+ 1,
310+ "the keyframe leads with the sequence header"
311+ );
312+ assert_eq!(first[0] & 0x2, 2, "obu_has_size_field: low-overhead format");
313+ let mut count = 1;
314+ while demuxer.next_access_unit().expect("read").is_some() {
315+ count += 1;
316+ }
317+ assert_eq!(count, 30, "every block comes back out");
318+ assert_eq!(
319+ demuxer.seek_to_sync_at_or_before(29),
320+ 0,
321+ "one GOP, one sync point"
322+ );
323+ std::fs::remove_file(&out).unwrap();
324+}
325+
326+/// An audio-only timeline is refused an AV1 export by name, exactly as it is
327+/// refused an mp4: every frame of it is a gap, so the file would be black.
328+#[test]
329+fn an_av1_export_of_an_audio_only_timeline_is_refused_by_name() {
330+ let session = PlaybackSession::open(asset("test_tone.wav")).expect("open the tone");
331+ let out = std::env::temp_dir().join(format!("ve_av1_refused_{}.mkv", std::process::id()));
332+ let handle = session.export_to_with(&out, &av1_settings());
333+ while !handle.is_finished() {
334+ std::thread::sleep(Duration::from_millis(10));
335+ }
336+ let refused = handle
337+ .result()
338+ .expect("outcome")
339+ .expect_err("an audio-only timeline has no picture to code")
340+ .to_string();
341+ assert!(refused.contains("no picture"), "{refused}");
342+ assert!(refused.contains("AV1"), "{refused}");
343+ assert!(!out.exists(), "nothing is written for a refusal");
344+}
345+
346+/// The whole loop, and the only place it is closed: the file the export wrote is
347+/// decoded back into pictures, and those pictures are the source's.
348+#[test]
349+#[ignore = "needs libengine_hw.so and a VA-API driver with AV1 decode"]
350+fn an_av1_export_decodes_back_into_the_pictures_that_went_in() {
351+ let session = short_timeline(30.0);
352+ let out = exported(
353+ &session,
354+ "roundtrip",
355+ &av1_settings(),
356+ Duration::from_secs(300),
357+ );
358+
359+ let (_, frames) = DecodeSession::open(&out).expect("decode the export");
360+ let frames: Vec<_> = frames.into_iter().collect();
361+ assert_eq!(frames.len(), 30, "every written frame decodes back");
362+ let (_, source, _) = DecodeSession::open_range(asset("test_baseline.mp4"), 0, 30)
363+ .expect("open the source again");
364+ let source: Vec<_> = source.into_iter().collect();
365+ for (i, (written, original)) in frames.iter().zip(&source).enumerate() {
366+ let diff: f64 = written
367+ .bgra
368+ .iter()
369+ .zip(&original.bgra)
370+ .map(|(a, b)| f64::from(a.abs_diff(*b)))
371+ .sum::<f64>()
372+ / written.bgra.len() as f64;
373+ assert!(
374+ diff < 12.0,
375+ "frame {i} drifted by {diff:.2} from the source"
376+ );
377+ }
378+ std::fs::remove_file(&out).unwrap();
379+}
380+
381+/// The hardware seat of the same pair, which is opt-in: `VE_HW_AV1=1` is what
382+/// enters it, because the vendored encoder reset the GPU of the box this was
383+/// written on (see `export::Enc::open_av1`). Without that variable this measures
384+/// the software encoder again, which is the honest outcome rather than a
385+/// failure, so what it asserts is the file.
386+#[test]
387+#[ignore = "needs libengine_hw.so, VE_HW_AV1=1 and a driver whose AV1 encoder survives it"]
388+fn an_av1_export_runs_on_the_plugin_where_the_gpu_has_one() {
389+ let session = short_timeline(60.0);
390+ let settings = ExportSettings {
391+ format: engine::export::Format::Av1,
392+ ..Default::default()
393+ };
394+ let out = exported(&session, "hw", &settings, Duration::from_secs(600));
395+ let (meta, _) = Demuxer::open(&out).expect("reopen the export");
396+ assert_eq!(meta.codec, Codec::Av1);
397+ assert_eq!(meta.frame_count, 60);
398+ std::fs::remove_file(&out).unwrap();
399+}