🔀 merge(export): AV1 format meets the library-only import
Browse files at this commit9 changed files +1258 -132
- Cargo.lock +1 -0
- crates/app/src/keymap.rs +2 -2
- crates/app/src/main.rs +133 -41
- crates/engine-hw/src/lib.rs +135 -30
- crates/engine/Cargo.toml +8 -0
- crates/engine/src/export.rs +331 -56
- crates/engine/src/hw.rs +52 -1
- crates/engine/src/mux.rs +427 -1
- crates/engine/tests/av1.rs +169 -1
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 button | 110 | /// 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 five | 111 | +/// 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 label | 114 | /// 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` |
| @@ -1999,8 +1999,12 @@ impl Player { | |||
| 1999 | fn set_format(&mut self, format: Format) { | 1999 | fn set_format(&mut self, format: Format) { |
| 2000 | // The one door both the row and its initial go through, so a format the | 2000 | // The one door both the row and its initial go through, so a format the |
| 2001 | // card greys out cannot be picked by keyboard either. | 2001 | // card greys out cannot be picked by keyboard either. |
| 2002 | - if let (Format::Mp4, Some(why)) = (format, self.session.as_ref().and_then(mp4_refusal)) { | 2002 | + if let Some(why) = self |
| 2003 | - self.notice = Some(format!("NOT MP4 — {why}").into()); | 2003 | + .session |
| 2004 | + .as_ref() | ||
| 2005 | + .and_then(|session| format_refusal(session, format)) | ||
| 2006 | + { | ||
| 2007 | + self.notice = Some(format!("NOT {} — {why}", format_label(format)).into()); | ||
| 2004 | return; | 2008 | return; |
| 2005 | } | 2009 | } |
| 2006 | self.format = format; | 2010 | self.format = format; |
| @@ -2072,7 +2076,7 @@ impl Player { | |||
| 2072 | // default and an audio-only timeline (or a second audio lane) is one | 2076 | // default and an audio-only timeline (or a second audio lane) is one |
| 2073 | // edit away -- so the button asks again rather than starting a worker | 2077 | // edit away -- so the button asks again rather than starting a worker |
| 2074 | // that will only settle with the same refusal minutes later. | 2078 | // that will only settle with the same refusal minutes later. |
| 2075 | - if let (Format::Mp4, Some(why)) = (self.format, mp4_refusal(session)) { | 2079 | + if let Some(why) = format_refusal(session, self.format) { |
| 2076 | self.notice = Some(format!("NOT EXPORTED — {why}").into()); | 2080 | self.notice = Some(format!("NOT EXPORTED — {why}").into()); |
| 2077 | cx.notify(); | 2081 | cx.notify(); |
| 2078 | return; | 2082 | return; |
| @@ -3296,15 +3300,20 @@ impl Player { | |||
| 3296 | // An mp4 this timeline cannot be written as reads exactly like the | 3300 | // An mp4 this timeline cannot be written as reads exactly like the |
| 3297 | // formats there is no encoder for: dimmed, unclickable, and carrying its | 3301 | // formats there is no encoder for: dimmed, unclickable, and carrying its |
| 3298 | // own reason instead of the detail line. | 3302 | // own reason instead of the detail line. |
| 3299 | - let refused = self.session.as_ref().and_then(mp4_refusal); | ||
| 3300 | let formats: Vec<_> = FORMATS | 3303 | let formats: Vec<_> = FORMATS |
| 3301 | .into_iter() | 3304 | .into_iter() |
| 3302 | .enumerate() | 3305 | .enumerate() |
| 3303 | .map(|(i, (format, label, detail))| { | 3306 | .map(|(i, (format, label, detail))| { |
| 3304 | - let blocked = format == Some(Format::Mp4) && refused.is_some(); | 3307 | + // Per row, because the two picture formats are refused by |
| 3308 | + // different things: an audio-only timeline greys both, a second | ||
| 3309 | + // audio lane only the mp4. | ||
| 3310 | + let refused = format | ||
| 3311 | + .zip(self.session.as_ref()) | ||
| 3312 | + .and_then(|(f, s)| format_refusal(s, f)); | ||
| 3313 | + let blocked = refused.is_some(); | ||
| 3305 | let detail: SharedString = match &refused { | 3314 | let detail: SharedString = match &refused { |
| 3306 | - Some(why) if blocked => why.clone().into(), | 3315 | + Some(why) => why.clone().into(), |
| 3307 | - _ => detail.into(), | 3316 | + None => detail.into(), |
| 3308 | }; | 3317 | }; |
| 3309 | let picked = format == Some(self.format) && !blocked; | 3318 | let picked = format == Some(self.format) && !blocked; |
| 3310 | let format = format.filter(|_| !blocked); | 3319 | let format = format.filter(|_| !blocked); |
| @@ -3378,11 +3387,11 @@ impl Player { | |||
| 3378 | .text_size(px(11.)) | 3387 | .text_size(px(11.)) |
| 3379 | .text_color(rgb(INK_DIM)) | 3388 | .text_color(rgb(INK_DIM)) |
| 3380 | .child(self.notice.clone().unwrap_or_else(|| { | 3389 | .child(self.notice.clone().unwrap_or_else(|| { |
| 3381 | - "pick a format (m/w/f), then Export — esc closes".into() | 3390 | + "pick a format (m/a/w/f), then Export — esc closes".into() |
| 3382 | })), | 3391 | })), |
| 3383 | ) | 3392 | ) |
| 3384 | // Capped and scrolling like the keybindings list: the | 3393 | // Capped and scrolling like the keybindings list: the |
| 3385 | - // destination, six formats and five qualities are more | 3394 | + // destination, nine formats and five qualities are more |
| 3386 | // rows than a 360 px window has room for, and it is the | 3395 | // rows than a 360 px window has room for, and it is the |
| 3387 | // list that scrolls, never the card that grows. | 3396 | // list that scrolls, never the card that grows. |
| 3388 | .child( | 3397 | .child( |
| @@ -4911,14 +4920,29 @@ impl Quality { | |||
| 4911 | /// `None` is exactly that kind of row. The MP3 reason is a *licence* and not a | 4920 | /// `None` is exactly that kind of row. The MP3 reason is a *licence* and not a |
| 4912 | /// capability: `shine-rs` encodes mp3 in pure Rust under LGPL-2.0, which is a | 4921 | /// capability: `shine-rs` encodes mp3 in pure Rust under LGPL-2.0, which is a |
| 4913 | /// decision about this project rather than about the code, and the row says so | 4922 | /// decision about this project rather than about the code, and the row says so |
| 4914 | -/// instead of pretending the encoder does not exist. | 4923 | +/// instead of pretending the encoder does not exist. HEVC and VP9 are the two |
| 4915 | -const FORMATS: [(Option<Format>, &str, &str); 6] = [ | 4924 | +/// this program *reads* and cannot write -- the plugin decodes both and there is |
| 4925 | +/// no encoder for either here -- so they are rows for the same reason: a codec | ||
| 4926 | +/// that opens but never comes back out is exactly the gap a user would other- | ||
| 4927 | +/// wise go looking for. | ||
| 4928 | +const FORMATS: [(Option<Format>, &str, &str); 9] = [ | ||
| 4916 | (Some(Format::Mp4), "MP4", "H.264 picture + copied AAC"), | 4929 | (Some(Format::Mp4), "MP4", "H.264 picture + copied AAC"), |
| 4930 | + ( | ||
| 4931 | + Some(Format::Av1), | ||
| 4932 | + "AV1", | ||
| 4933 | + "AV1 picture in .mkv — no sound: export WAV or FLAC for that", | ||
| 4934 | + ), | ||
| 4917 | (Some(Format::Wav), "WAV", "16-bit PCM — audio only"), | 4935 | (Some(Format::Wav), "WAV", "16-bit PCM — audio only"), |
| 4918 | (Some(Format::Flac), "FLAC", "lossless — audio only"), | 4936 | (Some(Format::Flac), "FLAC", "lossless — audio only"), |
| 4919 | (None, "MP3", "encoder is LGPL — licence decision pending"), | 4937 | (None, "MP3", "encoder is LGPL — licence decision pending"), |
| 4920 | (None, "OGG", "no pure-Rust Vorbis or Opus encoder"), | 4938 | (None, "OGG", "no pure-Rust Vorbis or Opus encoder"), |
| 4921 | (None, "AAC", "no pure-Rust AAC encoder"), | 4939 | (None, "AAC", "no pure-Rust AAC encoder"), |
| 4940 | + ( | ||
| 4941 | + None, | ||
| 4942 | + "HEVC", | ||
| 4943 | + "no encoder in this stack, and patent-encumbered", | ||
| 4944 | + ), | ||
| 4945 | + (None, "VP9", "superseded by AV1, which is the row above"), | ||
| 4922 | ]; | 4946 | ]; |
| 4923 | 4947 | ||
| 4924 | /// The format a key picks while the export card is up: the row's own initial, | 4948 | /// The format a key picks while the export card is up: the row's own initial, |
| @@ -5030,11 +5054,21 @@ fn export_line(format: Format, session: Option<&PlaybackSession>) -> String { | |||
| 5030 | fn format_line(format: Format) -> &'static str { | 5054 | fn format_line(format: Format) -> &'static str { |
| 5031 | match format { | 5055 | match format { |
| 5032 | Format::Mp4 => "H.264 · MP4 · moov at end", | 5056 | Format::Mp4 => "H.264 · MP4 · moov at end", |
| 5057 | + Format::Av1 => "AV1 · Matroska · picture only, no audio track", | ||
| 5033 | Format::Wav => "16-bit PCM · WAV · timeline audio only", | 5058 | Format::Wav => "16-bit PCM · WAV · timeline audio only", |
| 5034 | Format::Flac => "FLAC · lossless · timeline audio only", | 5059 | Format::Flac => "FLAC · lossless · timeline audio only", |
| 5035 | } | 5060 | } |
| 5036 | } | 5061 | } |
| 5037 | 5062 | ||
| 5063 | +/// The row a format is picked by, which is what a refusal calls it: `MP4`, not | ||
| 5064 | +/// the `mkv` an AV1 file is named with. | ||
| 5065 | +fn format_label(format: Format) -> &'static str { | ||
| 5066 | + FORMATS | ||
| 5067 | + .iter() | ||
| 5068 | + .find(|(row, ..)| *row == Some(format)) | ||
| 5069 | + .map_or("EXPORT", |(_, label, _)| *label) | ||
| 5070 | +} | ||
| 5071 | + | ||
| 5038 | /// The destination under a format: `take.export.mp4` becomes `take.export.wav`. | 5072 | /// The destination under a format: `take.export.mp4` becomes `take.export.wav`. |
| 5039 | /// The stem is untouched, so a name typed into the save dialog survives a | 5073 | /// The stem is untouched, so a name typed into the save dialog survives a |
| 5040 | /// change of mind about the format -- only the extension is the format's to say. | 5074 | /// change of mind about the format -- only the extension is the format's to say. |
| @@ -5101,23 +5135,34 @@ fn is_bare_modifier(key: &str) -> bool { | |||
| 5101 | 5135 | ||
| 5102 | /// A clip's share of the lane. A timeline with no length reads as one full-width | 5136 | /// A clip's share of the lane. A timeline with no length reads as one full-width |
| 5103 | /// box rather than as NaN, which gpui would carry into layout. | 5137 | /// box rather than as NaN, which gpui would carry into layout. |
| 5104 | -/// Why this timeline cannot be written as an mp4, if it cannot: the mp4 path | 5138 | +/// Why this timeline cannot be written in `format`, if it cannot. |
| 5105 | -/// *copies* one AAC track and there is no encoder here to mix several with, so a | ||
| 5106 | -/// timeline whose sound is spread over more than one audio lane is refused by | ||
| 5107 | -/// the engine (`export::run`). Said on the row, before a destination has been | ||
| 5108 | -/// picked, rather than after the write has started. | ||
| 5109 | /// | 5139 | /// |
| 5110 | -/// An audio-only timeline is the other one: every frame of it is a gap, so the | 5140 | +/// An audio-only timeline is the one both picture formats refuse: every frame of |
| 5111 | -/// mp4 would be a black picture over the sound. The engine refuses it too | 5141 | +/// it is a gap, so the file would be a black picture over the sound. The engine |
| 5112 | -/// (`export::start`); this is what greys the row before a destination has been | 5142 | +/// refuses it too (`export::start`); this is what greys the row before a |
| 5113 | -/// picked. | 5143 | +/// destination has been picked. |
| 5114 | -fn mp4_refusal(session: &PlaybackSession) -> Option<String> { | 5144 | +/// |
| 5145 | +/// The second reason is the mp4 path's alone: it *copies* one AAC track and | ||
| 5146 | +/// there is no encoder here to mix several with, so a timeline whose sound is | ||
| 5147 | +/// spread over more than one audio lane is refused by the engine | ||
| 5148 | +/// (`export::run`). An AV1 export carries no sound at all -- said on its row as | ||
| 5149 | +/// its detail, not as a refusal -- so no count of audio lanes stops it. | ||
| 5150 | +fn format_refusal(session: &PlaybackSession, format: Format) -> Option<String> { | ||
| 5151 | + if !format.has_video() { | ||
| 5152 | + return None; | ||
| 5153 | + } | ||
| 5115 | let picture = session | 5154 | let picture = session |
| 5116 | .lanes() | 5155 | .lanes() |
| 5117 | .into_iter() | 5156 | .into_iter() |
| 5118 | .any(|lane| lane.kind == LaneKind::Video && !session.lane_clips(lane).is_empty()); | 5157 | .any(|lane| lane.kind == LaneKind::Video && !session.lane_clips(lane).is_empty()); |
| 5119 | if !picture { | 5158 | if !picture { |
| 5120 | - return Some("no picture — an mp4 would be black; export WAV or FLAC".to_string()); | 5159 | + return Some(format!( |
| 5160 | + "no picture — {} would be black; export WAV or FLAC", | ||
| 5161 | + format.name() | ||
| 5162 | + )); | ||
| 5163 | + } | ||
| 5164 | + if format != Format::Mp4 { | ||
| 5165 | + return None; | ||
| 5121 | } | 5166 | } |
| 5122 | let lanes = session | 5167 | let lanes = session |
| 5123 | .lanes() | 5168 | .lanes() |
| @@ -5624,11 +5669,11 @@ mod tests { | |||
| 5624 | LIBRARY_MAX_W, LIBRARY_MIN_W, Lane, MENU_ITEMS, MENU_W, NO_FILE, PANEL_H, Quality, ROW_H, | 5669 | LIBRARY_MAX_W, LIBRARY_MIN_W, Lane, MENU_ITEMS, MENU_W, NO_FILE, PANEL_H, Quality, ROW_H, |
| 5625 | RULER_HIT_H, SELECTED, SOURCE_TINTS, SURFACE, SWATCH_W, Source, StreamInfo, Volume, | 5670 | RULER_HIT_H, SELECTED, SOURCE_TINTS, SURFACE, SWATCH_W, Source, StreamInfo, Volume, |
| 5626 | WAVE_BPS, WAVE_COL, Wave, applicable, band_label, can_add, cancels_export, color_snap, | 5671 | WAVE_BPS, WAVE_COL, Wave, applicable, band_label, can_add, cancels_export, color_snap, |
| 5627 | - envelope, eq_x, eq_y, export_path, export_settings, format_line, frac_along, frac_down, | 5672 | + envelope, eq_x, eq_y, export_path, export_settings, format_key, format_line, |
| 5628 | - frame_at, histogram, is_bare_modifier, is_project, keymap, lanes_h, marked, menu_at, | 5673 | + format_refusal, frac_along, frac_down, frame_at, histogram, is_bare_modifier, is_project, |
| 5629 | - mp4_refusal, normalise, panel_h, project_path, push_digit, retarget, scrub_due, show_label, | 5674 | + keymap, lanes_h, marked, menu_at, normalise, panel_h, project_path, push_digit, retarget, |
| 5630 | - source_tint, span_partner, start_frac, timecode, unseen_paths, unseen_sources, whole_take, | 5675 | + scrub_due, show_label, source_tint, span_partner, start_frac, timecode, unseen_paths, |
| 5631 | - width_frac, window_title, | 5676 | + unseen_sources, whole_take, width_frac, window_title, |
| 5632 | }; | 5677 | }; |
| 5633 | use super::{file_name, file_uri, library_rows}; | 5678 | use super::{file_name, file_uri, library_rows}; |
| 5634 | 5679 | ||
| @@ -5761,11 +5806,19 @@ mod tests { | |||
| 5761 | assert_eq!(session.lane_clips(Lane::A1).len(), 2); | 5806 | assert_eq!(session.lane_clips(Lane::A1).len(), 2); |
| 5762 | assert!(session.lane_clips(Lane::V1).is_empty(), "still no picture"); | 5807 | assert!(session.lane_clips(Lane::V1).is_empty(), "still no picture"); |
| 5763 | 5808 | ||
| 5764 | - // The mp4 row carries the reason rather than the format's detail line. | 5809 | + // Both picture rows carry the reason rather than the format's detail |
| 5810 | + // line, each naming itself; the audio formats are what this timeline is | ||
| 5811 | + // and are never refused. | ||
| 5765 | assert_eq!( | 5812 | assert_eq!( |
| 5766 | - mp4_refusal(&session).as_deref(), | 5813 | + format_refusal(&session, Format::Mp4).as_deref(), |
| 5767 | Some("no picture — an mp4 would be black; export WAV or FLAC") | 5814 | Some("no picture — an mp4 would be black; export WAV or FLAC") |
| 5768 | ); | 5815 | ); |
| 5816 | + assert_eq!( | ||
| 5817 | + format_refusal(&session, Format::Av1).as_deref(), | ||
| 5818 | + Some("no picture — an AV1 export would be black; export WAV or FLAC") | ||
| 5819 | + ); | ||
| 5820 | + assert_eq!(format_refusal(&session, Format::Wav), None); | ||
| 5821 | + assert_eq!(format_refusal(&session, Format::Flac), None); | ||
| 5769 | } | 5822 | } |
| 5770 | 5823 | ||
| 5771 | fn info( | 5824 | fn info( |
| @@ -6365,19 +6418,26 @@ mod tests { | |||
| 6365 | 6418 | ||
| 6366 | // A second audio lane carrying sound is what an mp4 export cannot | 6419 | // A second audio lane carrying sound is what an mp4 export cannot |
| 6367 | // write, so the card greys that row before a destination is picked. | 6420 | // write, so the card greys that row before a destination is picked. |
| 6368 | - assert_eq!(mp4_refusal(&session), None); | 6421 | + assert_eq!(format_refusal(&session, Format::Mp4), None); |
| 6369 | let a2 = session.add_lane(LaneKind::Audio); | 6422 | let a2 = session.add_lane(LaneKind::Audio); |
| 6370 | assert_eq!(a2.label(), "A2"); | 6423 | assert_eq!(a2.label(), "A2"); |
| 6371 | - assert_eq!(mp4_refusal(&session), None, "an empty lane carries nothing"); | 6424 | + assert_eq!( |
| 6425 | + format_refusal(&session, Format::Mp4), | ||
| 6426 | + None, | ||
| 6427 | + "an empty lane carries nothing" | ||
| 6428 | + ); | ||
| 6372 | assert!( | 6429 | assert!( |
| 6373 | session | 6430 | session |
| 6374 | .place_stream_at(0.0, &path, 0, Some(a2)) | 6431 | .place_stream_at(0.0, &path, 0, Some(a2)) |
| 6375 | .expect("its own file is on this timeline") | 6432 | .expect("its own file is on this timeline") |
| 6376 | ); | 6433 | ); |
| 6377 | assert_eq!( | 6434 | assert_eq!( |
| 6378 | - mp4_refusal(&session).as_deref(), | 6435 | + format_refusal(&session, Format::Mp4).as_deref(), |
| 6379 | Some("2 audio lanes — an mp4 copies one") | 6436 | Some("2 audio lanes — an mp4 copies one") |
| 6380 | ); | 6437 | ); |
| 6438 | + // ...and the one thing that does not stop an AV1 export, which carries | ||
| 6439 | + // no sound to have too much of. | ||
| 6440 | + assert_eq!(format_refusal(&session, Format::Av1), None); | ||
| 6381 | 6441 | ||
| 6382 | // Undo, one edit at a time and backwards: the drop on A2, the lane A2 | 6442 | // Undo, one edit at a time and backwards: the drop on A2, the lane A2 |
| 6383 | // itself, the lift, the drop on V2, and last the lane V2 -- an added | 6443 | // itself, the lift, the drop on V2, and last the lane V2 -- an added |
| @@ -6388,7 +6448,7 @@ mod tests { | |||
| 6388 | } | 6448 | } |
| 6389 | assert_eq!(session.lanes(), vec![Lane::V1, Lane::A1]); | 6449 | assert_eq!(session.lanes(), vec![Lane::V1, Lane::A1]); |
| 6390 | assert_eq!(session.lane_clips(Lane::V1).len(), 1); | 6450 | assert_eq!(session.lane_clips(Lane::V1).len(), 1); |
| 6391 | - assert_eq!(mp4_refusal(&session), None); | 6451 | + assert_eq!(format_refusal(&session, Format::Mp4), None); |
| 6392 | } | 6452 | } |
| 6393 | 6453 | ||
| 6394 | #[test] | 6454 | #[test] |
| @@ -7072,12 +7132,20 @@ mod tests { | |||
| 7072 | 7132 | ||
| 7073 | #[test] | 7133 | #[test] |
| 7074 | fn every_format_row_is_offered_or_says_why_not() { | 7134 | fn every_format_row_is_offered_or_says_why_not() { |
| 7075 | - // The three this program can write are rows that pick, each named after | 7135 | + // The four this program can write are rows that pick. Three are named |
| 7076 | - // its own extension so a destination can never disagree with its bytes. | 7136 | + // after their own extension, so a destination cannot disagree with its |
| 7137 | + // bytes; the fourth is named after its *codec*, because AV1 arrives and | ||
| 7138 | + // leaves in a Matroska file and "MKV" would name the box rather than | ||
| 7139 | + // what is in it. | ||
| 7077 | let offered: Vec<Format> = FORMATS.iter().filter_map(|&(f, ..)| f).collect(); | 7140 | let offered: Vec<Format> = FORMATS.iter().filter_map(|&(f, ..)| f).collect(); |
| 7078 | - assert_eq!(offered, vec![Format::Mp4, Format::Wav, Format::Flac]); | 7141 | + assert_eq!( |
| 7142 | + offered, | ||
| 7143 | + vec![Format::Mp4, Format::Av1, Format::Wav, Format::Flac] | ||
| 7144 | + ); | ||
| 7145 | + assert_eq!(Format::Av1.ext(), "mkv"); | ||
| 7079 | for (format, label, _) in FORMATS { | 7146 | for (format, label, _) in FORMATS { |
| 7080 | match format { | 7147 | match format { |
| 7148 | + Some(Format::Av1) => assert_eq!(label, "AV1"), | ||
| 7081 | Some(format) => assert_eq!(format.ext(), label.to_lowercase()), | 7149 | Some(format) => assert_eq!(format.ext(), label.to_lowercase()), |
| 7082 | // A refused format is a row with a reason, never a hidden one: | 7150 | // A refused format is a row with a reason, never a hidden one: |
| 7083 | // an empty detail column would read as an oversight. | 7151 | // an empty detail column would read as an oversight. |
| @@ -7086,13 +7154,37 @@ mod tests { | |||
| 7086 | } | 7154 | } |
| 7087 | for (format, label, detail) in FORMATS { | 7155 | for (format, label, detail) in FORMATS { |
| 7088 | assert!(!detail.is_empty(), "{label} says nothing"); | 7156 | assert!(!detail.is_empty(), "{label} says nothing"); |
| 7089 | - // Only mp4 carries the picture, so only mp4 leaves the bitrate rows | 7157 | + // Only the two picture formats leave the bitrate rows live -- the |
| 7090 | - // live -- the card dims them off exactly this. | 7158 | + // card dims them off exactly this. |
| 7091 | assert_eq!( | 7159 | assert_eq!( |
| 7092 | format.is_some_and(Format::has_video), | 7160 | format.is_some_and(Format::has_video), |
| 7093 | - format == Some(Format::Mp4) | 7161 | + matches!(format, Some(Format::Mp4 | Format::Av1)) |
| 7094 | ); | 7162 | ); |
| 7095 | } | 7163 | } |
| 7164 | + // The two codecs this program reads and cannot write are rows of their | ||
| 7165 | + // own, refused by name rather than absent -- HEVC for want of an encoder | ||
| 7166 | + // (and for its patents), VP9 because AV1 is the row that replaced it. | ||
| 7167 | + for (label, word) in [("HEVC", "no encoder"), ("VP9", "superseded")] { | ||
| 7168 | + let (format, _, detail) = FORMATS | ||
| 7169 | + .into_iter() | ||
| 7170 | + .find(|(_, row, _)| *row == label) | ||
| 7171 | + .unwrap_or_else(|| panic!("{label} has no row")); | ||
| 7172 | + assert!(format.is_none(), "{label} is not offered"); | ||
| 7173 | + assert!(detail.contains(word), "{label}: {detail}"); | ||
| 7174 | + } | ||
| 7175 | + // The AV1 row says on the row itself that it carries no sound, which is | ||
| 7176 | + // the one thing a user could otherwise only find out by playing the file. | ||
| 7177 | + let (_, _, av1) = FORMATS | ||
| 7178 | + .into_iter() | ||
| 7179 | + .find(|(f, ..)| *f == Some(Format::Av1)) | ||
| 7180 | + .expect("an AV1 row"); | ||
| 7181 | + assert!(av1.contains("no sound"), "{av1}"); | ||
| 7182 | + assert!(format_line(Format::Av1).contains("picture only")); | ||
| 7183 | + assert_eq!( | ||
| 7184 | + format_key("a"), | ||
| 7185 | + Some(Format::Av1), | ||
| 7186 | + "its own initial picks it" | ||
| 7187 | + ); | ||
| 7096 | // The destination follows the format and keeps the stem, mp4 included. | 7188 | // The destination follows the format and keeps the stem, mp4 included. |
| 7097 | assert_eq!( | 7189 | assert_eq!( |
| 7098 | retarget(std::path::Path::new("/a/take.export.mp4"), Format::Wav), | 7190 | 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 a | 1 | +//! 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 on | 3 | //! `dlopen`-able plugin so the main binary never gets a DT_NEEDED on |
| 3 | //! libva/gbm/drm. Every entry point is | 4 | //! libva/gbm/drm. Every entry point is |
| 4 | //! `extern "C"`, catches unwinds and reports failure as a null pointer or a | 5 | //! `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 blocking | 93 | /// 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 only | 94 | /// 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 buffer | 525 | /// 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 = display | 579 | + 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 the | 587 | + 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 smaller | 658 | // 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 one | 818 | /// 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 on | 819 | /// 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 left | 1 | +//! 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 it | 4 | //! 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 no | 5 | //! 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-install | 48 | +/// 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 encoder | 49 | +const AV1_SPEED: u8 = 10; |
| 50 | -/// at all. MP3 has one (`shine-rs`) under LGPL-2.0, which is a licensing | 50 | + |
| 51 | -/// decision this project has not taken; Vorbis, Opus and AAC have none. A | 51 | +/// 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 carries | 60 | /// 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 video | 89 | /// 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-rounding | 259 | // 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 spanning | 260 | // 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 the | 261 | // 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 pixels | 411 | // 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 | shared | 426 | 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 parameter | 655 | /// 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 with | 656 | +/// 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 buffer | 657 | +/// 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 for | 732 | /// 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: a | 766 | // 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 would | 767 | // 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 buffer | 873 | /// 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 = encoder | 922 | *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 = encoder | 960 | *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, so | 503 | /// 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, to | 913 | /// 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 lost | 914 | /// 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 back | 915 | /// 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 | +} | ||