diff --git a/Cargo.lock b/Cargo.lock index 8f6d6d2..8c2ea8e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1637,6 +1637,7 @@ dependencies = [ "mp4", "oxideav-ac3", "oxideav-core", + "rav1e", "rusty_h264", "symphonia", "symphonia-codec-aac", diff --git a/crates/app/src/keymap.rs b/crates/app/src/keymap.rs index 413905c..ebe7f8b 100644 --- a/crates/app/src/keymap.rs +++ b/crates/app/src/keymap.rs @@ -287,8 +287,8 @@ pub const FIXED: [Fixed; 12] = [ category: Category::File, }, Fixed { - chord: "m / w / f", - label: "Pick the export format: MP4, WAV or FLAC", + chord: "m / a / w / f", + label: "Pick the export format: MP4, AV1, WAV or FLAC", category: Category::File, }, Fixed { diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs index 32c184b..a45c70b 100644 --- a/crates/app/src/main.rs +++ b/crates/app/src/main.rs @@ -108,8 +108,8 @@ const KEYS_ROW_H: f32 = HIT_MIN; /// editor grows -- ten rows fit here, and the eleventh is a scroll away. const KEYS_ROWS_H: f32 = 10. * KEYS_ROW_H; /// The same for the export card, which carries a fixed-format line and a button -/// under its list and so has less room: destination, six formats and five -/// qualities are twelve rows, eight of them on screen. +/// under its list and so has less room: destination, nine formats and five +/// qualities are fifteen rows, eight of them on screen. const EXPORT_ROWS_H: f32 = 8. * KEYS_ROW_H; /// The menu a right-click on a clip opens: wide enough for the longest label /// beside the stroke that does the same thing, with the click targets `HIT_MIN` @@ -2026,8 +2026,12 @@ impl Player { fn set_format(&mut self, format: Format) { // The one door both the row and its initial go through, so a format the // card greys out cannot be picked by keyboard either. - if let (Format::Mp4, Some(why)) = (format, self.session.as_ref().and_then(mp4_refusal)) { - self.notice = Some(format!("NOT MP4 — {why}").into()); + if let Some(why) = self + .session + .as_ref() + .and_then(|session| format_refusal(session, format)) + { + self.notice = Some(format!("NOT {} — {why}", format_label(format)).into()); return; } self.format = format; @@ -2099,7 +2103,7 @@ impl Player { // default and an audio-only timeline (or a second audio lane) is one // edit away -- so the button asks again rather than starting a worker // that will only settle with the same refusal minutes later. - if let (Format::Mp4, Some(why)) = (self.format, mp4_refusal(session)) { + if let Some(why) = format_refusal(session, self.format) { self.notice = Some(format!("NOT EXPORTED — {why}").into()); cx.notify(); return; @@ -3344,15 +3348,20 @@ impl Player { // An mp4 this timeline cannot be written as reads exactly like the // formats there is no encoder for: dimmed, unclickable, and carrying its // own reason instead of the detail line. - let refused = self.session.as_ref().and_then(mp4_refusal); let formats: Vec<_> = FORMATS .into_iter() .enumerate() .map(|(i, (format, label, detail))| { - let blocked = format == Some(Format::Mp4) && refused.is_some(); + // Per row, because the two picture formats are refused by + // different things: an audio-only timeline greys both, a second + // audio lane only the mp4. + let refused = format + .zip(self.session.as_ref()) + .and_then(|(f, s)| format_refusal(s, f)); + let blocked = refused.is_some(); let detail: SharedString = match &refused { - Some(why) if blocked => why.clone().into(), - _ => detail.into(), + Some(why) => why.clone().into(), + None => detail.into(), }; let picked = format == Some(self.format) && !blocked; let format = format.filter(|_| !blocked); @@ -3426,11 +3435,11 @@ impl Player { .text_size(px(11.)) .text_color(rgb(INK_DIM)) .child(self.notice.clone().unwrap_or_else(|| { - "pick a format (m/w/f), then Export — esc closes".into() + "pick a format (m/a/w/f), then Export — esc closes".into() })), ) // Capped and scrolling like the keybindings list: the - // destination, six formats and five qualities are more + // destination, nine formats and five qualities are more // rows than a 360 px window has room for, and it is the // list that scrolls, never the card that grows. .child( @@ -4979,14 +4988,29 @@ impl Quality { /// `None` is exactly that kind of row. The MP3 reason is a *licence* and not a /// capability: `shine-rs` encodes mp3 in pure Rust under LGPL-2.0, which is a /// decision about this project rather than about the code, and the row says so -/// instead of pretending the encoder does not exist. -const FORMATS: [(Option, &str, &str); 6] = [ +/// instead of pretending the encoder does not exist. HEVC and VP9 are the two +/// this program *reads* and cannot write -- the plugin decodes both and there is +/// no encoder for either here -- so they are rows for the same reason: a codec +/// that opens but never comes back out is exactly the gap a user would other- +/// wise go looking for. +const FORMATS: [(Option, &str, &str); 9] = [ (Some(Format::Mp4), "MP4", "H.264 picture + copied AAC"), + ( + Some(Format::Av1), + "AV1", + "AV1 picture in .mkv — no sound: export WAV or FLAC for that", + ), (Some(Format::Wav), "WAV", "16-bit PCM — audio only"), (Some(Format::Flac), "FLAC", "lossless — audio only"), (None, "MP3", "encoder is LGPL — licence decision pending"), (None, "OGG", "no pure-Rust Vorbis or Opus encoder"), (None, "AAC", "no pure-Rust AAC encoder"), + ( + None, + "HEVC", + "no encoder in this stack, and patent-encumbered", + ), + (None, "VP9", "superseded by AV1, which is the row above"), ]; /// The format a key picks while the export card is up: the row's own initial, @@ -5098,11 +5122,21 @@ fn export_line(format: Format, session: Option<&PlaybackSession>) -> String { fn format_line(format: Format) -> &'static str { match format { Format::Mp4 => "H.264 · MP4 · moov at end", + Format::Av1 => "AV1 · Matroska · picture only, no audio track", Format::Wav => "16-bit PCM · WAV · timeline audio only", Format::Flac => "FLAC · lossless · timeline audio only", } } +/// The row a format is picked by, which is what a refusal calls it: `MP4`, not +/// the `mkv` an AV1 file is named with. +fn format_label(format: Format) -> &'static str { + FORMATS + .iter() + .find(|(row, ..)| *row == Some(format)) + .map_or("EXPORT", |(_, label, _)| *label) +} + /// The destination under a format: `take.export.mp4` becomes `take.export.wav`. /// The stem is untouched, so a name typed into the save dialog survives a /// change of mind about the format -- only the extension is the format's to say. @@ -5169,23 +5203,34 @@ fn is_bare_modifier(key: &str) -> bool { /// A clip's share of the lane. A timeline with no length reads as one full-width /// box rather than as NaN, which gpui would carry into layout. -/// Why this timeline cannot be written as an mp4, if it cannot: the mp4 path -/// *copies* one AAC track and there is no encoder here to mix several with, so a -/// timeline whose sound is spread over more than one audio lane is refused by -/// the engine (`export::run`). Said on the row, before a destination has been -/// picked, rather than after the write has started. +/// Why this timeline cannot be written in `format`, if it cannot. /// -/// An audio-only timeline is the other one: every frame of it is a gap, so the -/// mp4 would be a black picture over the sound. The engine refuses it too -/// (`export::start`); this is what greys the row before a destination has been -/// picked. -fn mp4_refusal(session: &PlaybackSession) -> Option { +/// An audio-only timeline is the one both picture formats refuse: every frame of +/// it is a gap, so the file would be a black picture over the sound. The engine +/// refuses it too (`export::start`); this is what greys the row before a +/// destination has been picked. +/// +/// The second reason is the mp4 path's alone: it *copies* one AAC track and +/// there is no encoder here to mix several with, so a timeline whose sound is +/// spread over more than one audio lane is refused by the engine +/// (`export::run`). An AV1 export carries no sound at all -- said on its row as +/// its detail, not as a refusal -- so no count of audio lanes stops it. +fn format_refusal(session: &PlaybackSession, format: Format) -> Option { + if !format.has_video() { + return None; + } let picture = session .lanes() .into_iter() .any(|lane| lane.kind == LaneKind::Video && !session.lane_clips(lane).is_empty()); if !picture { - return Some("no picture — an mp4 would be black; export WAV or FLAC".to_string()); + return Some(format!( + "no picture — {} would be black; export WAV or FLAC", + format.name() + )); + } + if format != Format::Mp4 { + return None; } let lanes = session .lanes() @@ -5692,11 +5737,11 @@ mod tests { LIBRARY_MAX_W, LIBRARY_MIN_W, Lane, MENU_ITEMS, MENU_W, NO_FILE, PANEL_H, Quality, ROW_H, RULER_HIT_H, SELECTED, SOURCE_TINTS, SURFACE, SWATCH_W, Source, StreamInfo, Volume, WAVE_BPS, WAVE_COL, Wave, applicable, band_label, can_add, cancels_export, color_snap, - envelope, eq_x, eq_y, export_path, export_settings, format_line, frac_along, frac_down, - frame_at, histogram, is_bare_modifier, is_project, keymap, lanes_h, marked, menu_at, - mp4_refusal, normalise, panel_h, project_path, push_digit, retarget, scrub_due, show_label, - source_tint, span_partner, start_frac, timecode, unseen_paths, unseen_sources, whole_take, - width_frac, window_title, + envelope, eq_x, eq_y, export_path, export_settings, format_key, format_line, + format_refusal, frac_along, frac_down, frame_at, histogram, is_bare_modifier, is_project, + keymap, lanes_h, marked, menu_at, normalise, panel_h, project_path, push_digit, retarget, + scrub_due, show_label, source_tint, span_partner, start_frac, timecode, unseen_paths, + unseen_sources, whole_take, width_frac, window_title, }; use super::{file_name, file_uri, library_rows}; @@ -5829,11 +5874,19 @@ mod tests { assert_eq!(session.lane_clips(Lane::A1).len(), 2); assert!(session.lane_clips(Lane::V1).is_empty(), "still no picture"); - // The mp4 row carries the reason rather than the format's detail line. + // Both picture rows carry the reason rather than the format's detail + // line, each naming itself; the audio formats are what this timeline is + // and are never refused. assert_eq!( - mp4_refusal(&session).as_deref(), + format_refusal(&session, Format::Mp4).as_deref(), Some("no picture — an mp4 would be black; export WAV or FLAC") ); + assert_eq!( + format_refusal(&session, Format::Av1).as_deref(), + Some("no picture — an AV1 export would be black; export WAV or FLAC") + ); + assert_eq!(format_refusal(&session, Format::Wav), None); + assert_eq!(format_refusal(&session, Format::Flac), None); } fn info( @@ -6433,19 +6486,26 @@ mod tests { // A second audio lane carrying sound is what an mp4 export cannot // write, so the card greys that row before a destination is picked. - assert_eq!(mp4_refusal(&session), None); + assert_eq!(format_refusal(&session, Format::Mp4), None); let a2 = session.add_lane(LaneKind::Audio); assert_eq!(a2.label(), "A2"); - assert_eq!(mp4_refusal(&session), None, "an empty lane carries nothing"); + assert_eq!( + format_refusal(&session, Format::Mp4), + None, + "an empty lane carries nothing" + ); assert!( session .place_stream_at(0.0, &path, 0, Some(a2)) .expect("its own file is on this timeline") ); assert_eq!( - mp4_refusal(&session).as_deref(), + format_refusal(&session, Format::Mp4).as_deref(), Some("2 audio lanes — an mp4 copies one") ); + // ...and the one thing that does not stop an AV1 export, which carries + // no sound to have too much of. + assert_eq!(format_refusal(&session, Format::Av1), None); // Undo, one edit at a time and backwards: the drop on A2, the lane A2 // itself, the lift, the drop on V2, and last the lane V2 -- an added @@ -6456,7 +6516,7 @@ mod tests { } assert_eq!(session.lanes(), vec![Lane::V1, Lane::A1]); assert_eq!(session.lane_clips(Lane::V1).len(), 1); - assert_eq!(mp4_refusal(&session), None); + assert_eq!(format_refusal(&session, Format::Mp4), None); } #[test] @@ -7140,12 +7200,20 @@ mod tests { #[test] fn every_format_row_is_offered_or_says_why_not() { - // The three this program can write are rows that pick, each named after - // its own extension so a destination can never disagree with its bytes. + // The four this program can write are rows that pick. Three are named + // after their own extension, so a destination cannot disagree with its + // bytes; the fourth is named after its *codec*, because AV1 arrives and + // leaves in a Matroska file and "MKV" would name the box rather than + // what is in it. let offered: Vec = FORMATS.iter().filter_map(|&(f, ..)| f).collect(); - assert_eq!(offered, vec![Format::Mp4, Format::Wav, Format::Flac]); + assert_eq!( + offered, + vec![Format::Mp4, Format::Av1, Format::Wav, Format::Flac] + ); + assert_eq!(Format::Av1.ext(), "mkv"); for (format, label, _) in FORMATS { match format { + Some(Format::Av1) => assert_eq!(label, "AV1"), Some(format) => assert_eq!(format.ext(), label.to_lowercase()), // A refused format is a row with a reason, never a hidden one: // an empty detail column would read as an oversight. @@ -7154,13 +7222,37 @@ mod tests { } for (format, label, detail) in FORMATS { assert!(!detail.is_empty(), "{label} says nothing"); - // Only mp4 carries the picture, so only mp4 leaves the bitrate rows - // live -- the card dims them off exactly this. + // Only the two picture formats leave the bitrate rows live -- the + // card dims them off exactly this. assert_eq!( format.is_some_and(Format::has_video), - format == Some(Format::Mp4) + matches!(format, Some(Format::Mp4 | Format::Av1)) ); } + // The two codecs this program reads and cannot write are rows of their + // own, refused by name rather than absent -- HEVC for want of an encoder + // (and for its patents), VP9 because AV1 is the row that replaced it. + for (label, word) in [("HEVC", "no encoder"), ("VP9", "superseded")] { + let (format, _, detail) = FORMATS + .into_iter() + .find(|(_, row, _)| *row == label) + .unwrap_or_else(|| panic!("{label} has no row")); + assert!(format.is_none(), "{label} is not offered"); + assert!(detail.contains(word), "{label}: {detail}"); + } + // The AV1 row says on the row itself that it carries no sound, which is + // the one thing a user could otherwise only find out by playing the file. + let (_, _, av1) = FORMATS + .into_iter() + .find(|(f, ..)| *f == Some(Format::Av1)) + .expect("an AV1 row"); + assert!(av1.contains("no sound"), "{av1}"); + assert!(format_line(Format::Av1).contains("picture only")); + assert_eq!( + format_key("a"), + Some(Format::Av1), + "its own initial picks it" + ); // The destination follows the format and keeps the stem, mp4 included. assert_eq!( retarget(std::path::Path::new("/a/take.export.mp4"), Format::Wav), diff --git a/crates/engine-hw/src/lib.rs b/crates/engine-hw/src/lib.rs index 578154e..c5d2229 100644 --- a/crates/engine-hw/src/lib.rs +++ b/crates/engine-hw/src/lib.rs @@ -1,4 +1,5 @@ -//! VA-API decode (H.264, HEVC, VP9 and AV1) and H.264 encode, shipped as a +//! VA-API decode (H.264, HEVC, VP9 and AV1) and encode (H.264, and AV1 where +//! the GPU has an entrypoint for it), shipped as a //! `dlopen`-able plugin so the main binary never gets a DT_NEEDED on //! libva/gbm/drm. Every entry point is //! `extern "C"`, catches unwinds and reports failure as a null pointer or a @@ -17,6 +18,7 @@ use std::rc::Rc; use cros_codecs::backend::vaapi::decoder::VaapiBackend; use cros_codecs::backend::vaapi::encoder::VaapiBackend as VaapiEncBackend; +use cros_codecs::codec::av1::parser::Profile as Av1Profile; use cros_codecs::codec::h264::parser::{Level, Profile as H264Profile}; use cros_codecs::decoder::stateless::av1::Av1; use cros_codecs::decoder::stateless::h264::H264; @@ -24,7 +26,9 @@ use cros_codecs::decoder::stateless::h265::H265; use cros_codecs::decoder::stateless::vp9::Vp9; use cros_codecs::decoder::stateless::{DecodeError, StatelessDecoder, StatelessVideoDecoder}; use cros_codecs::decoder::{BlockingMode, DecodedHandle, DecoderEvent, StreamInfo}; +use cros_codecs::encoder::av1::EncoderConfig as Av1Config; use cros_codecs::encoder::h264::EncoderConfig as H264Config; +use cros_codecs::encoder::stateless::av1::StatelessEncoder as Av1StatelessEncoder; use cros_codecs::encoder::stateless::h264::StatelessEncoder; use cros_codecs::encoder::{ FrameMetadata, PredictionStructure, RateControl, Tunings, VideoEncoder, @@ -81,6 +85,10 @@ type Encoder = StatelessEncoder< GenericDmaVideoFrame, VaapiEncBackend>, >; +type Av1Encoder = Av1StatelessEncoder< + GenericDmaVideoFrame, + VaapiEncBackend>, +>; /// Ceiling on decode/drain iterations that make no progress. VA-API in blocking /// 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]) { /// point polls it before returning, so the GPU is finished with the buffer /// before the next picture is written into it. struct EncSession { - encoder: Encoder, + /// Boxed because the two codecs are two types and everything past `encode` + /// is the same trait: one session type serves both, which is what keeps the + /// C ABI at one new symbol (the open) instead of four. + encoder: Box>, + /// H.264 only: the byte the driver leaves at zero is a *NAL* header, and an + /// AV1 temporal unit has no such thing. + h264: bool, /// Owns the DRM node the buffer object below was allocated from. _gbm: gbm::Device, frame: GenericDmaVideoFrame, @@ -537,6 +551,17 @@ struct EncSession { impl EncSession { fn open(width: u32, height: u32, fps_num: u32, fps_den: u32, bitrate: u64) -> Option { + Self::open_codec(width, height, fps_num, fps_den, bitrate, false) + } + + fn open_codec( + width: u32, + height: u32, + fps_num: u32, + fps_den: u32, + bitrate: u64, + av1: bool, + ) -> Option { // NV12 chroma is half resolution, so odd dimensions have no packing; // and radeonsi refuses encode contexts below 64x64 (measured). if width < 64 || height < 64 || width % 2 != 0 || height % 2 != 0 { @@ -551,40 +576,92 @@ impl EncSession { height: align16(height), }; let framerate = ((fps_num as f64 / fps_den as f64).round() as i64).clamp(1, 240) as u32; - let low_power = display - .query_config_entrypoints(VAProfile::VAProfileH264Main) - .ok()? - .contains(&VAEntrypoint::VAEntrypointEncSliceLP); - let config = H264Config { - resolution: Resolution { width, height }, - profile: H264Profile::Main, - level: Level::L4, - // No B-frames: coded order stays display order, which is what the - // muxer's duration-only timing assumes. - pred_structure: PredictionStructure::LowDelay { - limit: (framerate * 2) as u16, - }, - initial_tunings: Tunings { - rate_control: RateControl::ConstantBitrate(bitrate), - framerate, - ..Default::default() - }, + let profile = match av1 { + true => VAProfile::VAProfileAV1Profile0, + false => VAProfile::VAProfileH264Main, + }; + // The driver's own answer to "can you encode this at all": a GPU with no + // AV1 encode entrypoint is what makes the caller fall back to `rav1e`, + // and asking here is what turns that into a null rather than a failed + // encode session halfway through an export. + let entrypoints = display.query_config_entrypoints(profile).ok()?; + if !entrypoints.contains(&VAEntrypoint::VAEntrypointEncSlice) + && !entrypoints.contains(&VAEntrypoint::VAEntrypointEncSliceLP) + { + return None; + } + let low_power = entrypoints.contains(&VAEntrypoint::VAEntrypointEncSliceLP); + // No B-frames on either codec: coded order stays display order, which is + // what both muxers' duration-only timing assumes. + let pred_structure = PredictionStructure::LowDelay { + limit: (framerate * 2) as u16, + }; + let encoder: Box> = match av1 { + true => { + // Constant quality, because that is the only rate control the + // vendored AV1 backend takes (`stateless/av1/vaapi.rs` refuses + // anything else outright); 128 of 255 is its own reference + // value. The caller's bitrate therefore does not reach this + // seat -- it reaches `rav1e`, which is the other one. + // + // ponytail: bitrate-driven AV1 on the GPU needs `VA_RC_CBR` + // wired through that backend, which is a change in the vendored + // crate rather than here. + let config = Av1Config { + profile: Av1Profile::Profile0, + resolution: Resolution { width, height }, + pred_structure, + initial_tunings: Tunings { + rate_control: RateControl::ConstantQuality(128), + framerate, + ..Default::default() + }, + ..Default::default() + }; + Box::new( + Av1Encoder::new_vaapi( + display, + config, + Fourcc::from(b"NV12"), + coded, + low_power, + BlockingMode::Blocking, + ) + .ok()?, + ) + } + false => { + let config = H264Config { + resolution: Resolution { width, height }, + profile: H264Profile::Main, + level: Level::L4, + pred_structure, + initial_tunings: Tunings { + rate_control: RateControl::ConstantBitrate(bitrate), + framerate, + ..Default::default() + }, + }; + Box::new( + Encoder::new_vaapi( + display, + config, + Fourcc::from(b"NV12"), + coded, + low_power, + BlockingMode::Blocking, + ) + .ok()?, + ) + } }; - let encoder = Encoder::new_vaapi( - display, - config, - Fourcc::from(b"NV12"), - coded, - low_power, - BlockingMode::Blocking, - ) - .ok()?; // Allocated at the aligned size, so the buffer's pitch is never smaller // than a padded row. let frame = alloc_nv12(&gbm, coded).ok()?; let layout = nv12_layout(coded, frame.get_plane_pitch()[0]); Some(Self { encoder, + h264: !av1, _gbm: gbm, frame, layout, @@ -667,7 +744,9 @@ impl EncSession { fn collect(&mut self) -> Result<(), String> { while let Some(coded) = self.encoder.poll().map_err(|e| e.to_string())? { let mut au = coded.bitstream; - fix_slice_nal_headers(&mut au); + if self.h264 { + fix_slice_nal_headers(&mut au); + } self.ready.push_back(au); } Ok(()) @@ -710,6 +789,32 @@ pub extern "C" fn vh_enc_open( .unwrap_or(std::ptr::null_mut()) } +/// The same, coding AV1 instead of H.264: null unless this GPU has an AV1 +/// encode entrypoint, which is recent hardware -- the caller then encodes AV1 in +/// software instead. `bitrate` is not used by this codec (see `EncSession::open`: +/// the vendored backend is constant-quality only) and is taken all the same, so +/// the two opens stay one signature. +/// +/// The session it returns is fed, drained and closed through `vh_enc_frame`, +/// `vh_enc_drain` and `vh_enc_close` exactly as an H.264 one is; what comes back +/// out of them is AV1 temporal units rather than Annex-B access units. +#[unsafe(no_mangle)] +pub extern "C" fn vh_enc_av1_open( + width: u32, + height: u32, + fps_num: u32, + fps_den: u32, + bitrate: u64, +) -> *mut c_void { + catch_unwind(AssertUnwindSafe(|| { + match EncSession::open_codec(width, height, fps_num, fps_den, bitrate, true) { + Some(session) => Box::into_raw(Box::new(session)) as *mut c_void, + None => std::ptr::null_mut(), + } + })) + .unwrap_or(std::ptr::null_mut()) +} + /// Encodes one tightly-strided I420 picture. 1 when `out`/`out_len` describe one /// Annex-B access unit, 0 when the encoder has nothing coded yet, negative on /// error. The bytes stay valid until the next call on this session. diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index f271111..77dc2ff 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -46,6 +46,14 @@ symphonia = { version = "0.6", default-features = false, features = [ ] } oxideav-ac3 = "=0.0.10" oxideav-core = "0.1.34" +# The software AV1 encoder, and the only new name in this list that was already +# in the lock file: `ravif` pulls the very same rav1e 0.8.1 in through the image +# crate, so this links what the build already compiled. BSD-2 with the AOM +# patent grant, and pure Rust with `asm` *off*: that feature wants `nasm`, which +# this project's build does not have and will not require. `threading` is rayon +# inside rav1e itself and is what keeps an export minutes rather than tens of +# minutes; the cost of no assembly is measured in `export::Enc::open_av1`. +rav1e = { version = "0.8.1", default-features = false, features = ["threading"] } [dev-dependencies] # The still-image suite compares what the timeline shows against the file's own diff --git a/crates/engine/src/export.rs b/crates/engine/src/export.rs index 73c049a..9fe7757 100644 --- a/crates/engine/src/export.rs +++ b/crates/engine/src/export.rs @@ -1,5 +1,5 @@ -//! Export: the edit list rendered back out as one mp4 — or, picture left -//! behind, as one WAV or FLAC of the timeline's audio alone. +//! Export: the edit list rendered back out as one mp4 or one AV1-in-Matroska — +//! or, picture left behind, as one WAV or FLAC of the timeline's audio alone. //! //! Video is fully re-encoded — a cut lands mid-GOP, so stream-copying across it //! is impossible — while audio is copied packet for packet, because there is no @@ -30,7 +30,7 @@ use flacenc::error::Verify; use crate::audio::{AudioMeta, AudioSession}; use crate::demux::{Demuxer, VideoMeta}; use crate::hw::{HwEncoder, HwSession}; -use crate::mux::{AudioParams, Mp4Muxer, VideoParams}; +use crate::mux::{AudioParams, Av1Params, MkvMuxer, Mp4Muxer, VideoParams}; use crate::project::{LaneKind, Project}; use crate::scale::Composer; @@ -44,12 +44,17 @@ const BITS_PER_PIXEL: f64 = 0.1; const MIN_BITRATE: u64 = 1_000_000; const MAX_BITRATE: u64 = 20_000_000; -/// What an export writes. Three, not more: H.264-in-mp4 is the only *video* -/// pair with both an encoder and a decoder under this project's no-install -/// rule, and WAV and FLAC are the only audio formats with a pure-Rust encoder -/// at all. MP3 has one (`shine-rs`) under LGPL-2.0, which is a licensing -/// decision this project has not taken; Vorbis, Opus and AAC have none. A -/// front-end says so rather than hiding the rows. +/// `rav1e`'s fastest preset. Anything slower is minutes per second of timeline +/// on a build with no assembly, which is what this one is. +const AV1_SPEED: u8 = 10; + +/// What an export writes. Four, not more: H.264-in-mp4 and AV1-in-Matroska are +/// the only *video* pairs with both an encoder and a decoder under this +/// project's no-install rule, and WAV and FLAC are the only audio formats with +/// a pure-Rust encoder at all. MP3 has one (`shine-rs`) under LGPL-2.0, which is +/// a licensing decision this project has not taken; Vorbis, Opus and AAC have +/// none. HEVC and VP9 have no encoder here at all (`hevc`/`vp9` import through +/// the plugin and stop there). A front-end says so rather than hiding the rows. #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] pub enum Format { /// Picture and sound: video re-encoded, AAC copied. Copied, so it carries @@ -57,6 +62,12 @@ pub enum Format { /// by name here and mixed by the other two formats, which decode. #[default] Mp4, + /// Picture alone, AV1 in Matroska. Alone because Matroska carries no sound + /// this project can write: there is no AAC or Opus encoder here, and an AAC + /// track copied in would be one *this engine's own reader* leaves silent + /// (`audio::AudioSession::open` refuses Matroska audio). The sound of an AV1 + /// export is a WAV or FLAC beside it, which a front-end says up front. + Av1, /// The audio lane alone, 16-bit PCM. Wav, /// The audio lane alone, losslessly compressed. @@ -69,15 +80,26 @@ impl Format { pub fn ext(self) -> &'static str { match self { Self::Mp4 => "mp4", + Self::Av1 => "mkv", Self::Wav => "wav", Self::Flac => "flac", } } /// Whether this format carries the picture. The bitrate settings are video - /// settings and mean nothing to the other two. + /// settings and mean nothing to the audio two. pub fn has_video(self) -> bool { - matches!(self, Self::Mp4) + matches!(self, Self::Mp4 | Self::Av1) + } + + /// What the format is called where a refusal names it. + pub fn name(self) -> &'static str { + match self { + Self::Mp4 => "an mp4", + Self::Av1 => "an AV1 export", + Self::Wav => "a WAV", + Self::Flac => "a FLAC", + } } } @@ -184,10 +206,13 @@ pub fn start( _ if project.timeline_frames() == 0 => { Err("the timeline is empty: there is nothing to export".into()) } - Format::Mp4 if !has_picture(&project) => Err("the timeline has no picture: \ - an mp4 would be black. Export WAV or FLAC, which are the sound itself" - .into()), - Format::Mp4 => run(&project, &meta, &part, &worker, &settings), + format if format.has_video() && !has_picture(&project) => Err(format!( + "the timeline has no picture: {} would be black. Export WAV or \ + FLAC, which are the sound itself", + format.name() + ) + .into()), + Format::Mp4 | Format::Av1 => run(&project, &meta, &part, &worker, &settings), format => run_audio(&project, &meta, &part, &worker, format), }; 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<()>) { shared.finished.store(true, Ordering::Release); } -fn run( +/// The timeline's one audio lane, copied packet for packet: the mp4 path's +/// sound, and the reason that path carries only one lane of it. +/// +/// ponytail: this holds the whole exported AAC track in memory (~3 kB per +/// 23 ms packet, so ~500 MB for an hour). Upgrade path is a streaming +/// `copy_segments` that yields packets instead of collecting them. +#[allow(clippy::type_complexity)] +fn copy_audio( project: &Project, meta: &VideoMeta, - out: &Path, - shared: &Shared, - settings: &ExportSettings, -) -> crate::Result<()> { - let total = project.timeline_frames(); - let sources = project.sources(); - // Audio first: a track has to be declared when the muxer is created, which - // happens as soon as the first coded picture arrives. - // - // ponytail: this holds the whole exported AAC track in memory (~3 kB per - // 23 ms packet, so ~500 MB for an hour). Upgrade path is a streaming - // `copy_segments` that yields packets instead of collecting them. - // +) -> crate::Result)>> { // The segments name their source, and the copy carries its packet-rounding // debt across a source join exactly as across a cut, so a timeline spanning // files stays in sync. A source whose AAC parameters disagree with the @@ -294,7 +314,28 @@ fn run( ) .into()); } - let audio = AudioSession::copy_multi_streams(&project.audio_sources(), segments)?; + AudioSession::copy_multi_streams(&project.audio_sources(), segments) +} + +fn run( + project: &Project, + meta: &VideoMeta, + out: &Path, + shared: &Shared, + settings: &ExportSettings, +) -> crate::Result<()> { + let total = project.timeline_frames(); + let sources = project.sources(); + // Audio first: a track has to be declared when the muxer is created, which + // happens as soon as the first coded picture arrives. None of it for AV1 -- + // that one is picture only, for the reason [`Format::Av1`] states -- and no + // refusal of it either: a timeline with sound is exported as the video it + // also is, and the front-end says the sound is not in the file *before* the + // export starts rather than failing it here. + let audio = match settings.format { + Format::Av1 => None, + _ => copy_audio(project, meta)?, + }; let audio_params = audio.as_ref().map(|(track, _)| AudioParams { freq_index: track.freq_index, chan_conf: track.chan_conf, @@ -370,8 +411,16 @@ fn run( // Grade first, place second: the grade is the clip's own pixels // and the bars around them are not the clip (see `scale::Composer`). let (y, u, v, width, height) = canvas.place(y, u, v, width, height); - if let Some(au) = encoder.encode(y, u, v, width, height)? { - write_video(&mut muxer, out, meta, audio_params.as_ref(), au)?; + if let Some((au, key)) = encoder.encode(y, u, v, width, height)? { + write_video( + &mut muxer, + out, + meta, + settings, + audio_params.as_ref(), + au, + key, + )?; } done += 1; shared @@ -379,21 +428,33 @@ fn run( .store(done * PROGRESS_SCALE / total.max(1), Ordering::Relaxed); } } - while let Some(au) = encoder.drain()? { - write_video(&mut muxer, out, meta, audio_params.as_ref(), au)?; + while let Some((au, key)) = encoder.drain()? { + write_video( + &mut muxer, + out, + meta, + settings, + audio_params.as_ref(), + au, + key, + )?; } // Progress reads 100% from here on, but nothing is published yet: draining, // the audio pass and `finish` are all still cancellable. cancelled(shared)?; - let Some(mut muxer) = muxer else { + let Some(muxer) = muxer else { return Err("export produced no coded pictures".into()); }; - if let Some((_, packets)) = audio { - for packet in packets { - muxer.write_audio_packet(&packet.bytes)?; + let muxer = match (muxer, audio) { + (Muxer::Mp4(mut mp4), Some((_, packets))) => { + for packet in packets { + mp4.write_audio_packet(&packet.bytes)?; + } + Muxer::Mp4(mp4) } - } + (muxer, _) => muxer, + }; cancelled(shared)?; muxer.finish()?; shared.progress.store(PROGRESS_SCALE, Ordering::Relaxed); @@ -475,7 +536,7 @@ fn run_audio( match format { Format::Wav => write_wav(out, &samples, &audio)?, Format::Flac => write_flac(out, &samples, &audio)?, - Format::Mp4 => unreachable!("the mp4 path is `run`"), + Format::Mp4 | Format::Av1 => unreachable!("the picture formats are `run`"), } shared.progress.store(PROGRESS_SCALE, Ordering::Relaxed); Ok(()) @@ -575,26 +636,72 @@ fn cancelled(shared: &Shared) -> crate::Result<()> { Ok(()) } +/// The two containers an export writes, so the picture loop above is one loop: +/// H.264 goes into mp4, AV1 into Matroska, and nothing else is offered. +enum Muxer { + Mp4(Mp4Muxer), + Mkv(MkvMuxer), +} + +impl Muxer { + fn finish(self) -> crate::Result<()> { + match self { + Self::Mp4(mp4) => mp4.finish(), + Self::Mkv(mkv) => mkv.finish(), + } + } +} + /// Writes one access unit, creating the file on the first one -- the parameter -/// sets for `avcC` only exist once the encoder has coded something. Units with -/// no coded slice are skipped: a software encoder may hand back an empty buffer -/// while it buffers, and the muxer rejects a sample that would carry no picture. +/// sets for `avcC` (and the sequence header for `CodecPrivate`) only exist once +/// the encoder has coded something. Units with no coded slice are skipped: a +/// software encoder may hand back an empty buffer while it buffers, and the +/// muxer rejects a sample that would carry no picture. fn write_video( - muxer: &mut Option, + muxer: &mut Option, out: &Path, meta: &VideoMeta, + settings: &ExportSettings, audio: Option<&AudioParams>, au: &[u8], + key: bool, ) -> crate::Result<()> { + if settings.format == Format::Av1 { + let muxer = match muxer { + Some(Muxer::Mkv(mkv)) => mkv, + Some(Muxer::Mp4(_)) => unreachable!("the format picks the muxer once"), + none => { + // Every AV1 stream opens on a keyframe, and a keyframe carries + // the sequence header the track has to declare: an encoder that + // handed back neither has produced nothing a decoder can start. + let config = crate::mux::av1_sequence_header(au) + .ok_or("the first coded picture carries no AV1 sequence header")?; + let Muxer::Mkv(mkv) = none.insert(Muxer::Mkv(MkvMuxer::create( + out, + &Av1Params { + width: meta.width, + height: meta.height, + frame_rate: meta.frame_rate, + config, + }, + )?)) else { + unreachable!("just inserted a Matroska muxer") + }; + mkv + } + }; + return muxer.write_frame(au, key); + } if !crate::mux::has_coded_slice(au) { return Ok(()); } let muxer = match muxer { - Some(muxer) => muxer, + Some(Muxer::Mp4(mp4)) => mp4, + Some(Muxer::Mkv(_)) => unreachable!("the format picks the muxer once"), none => { let (sps, pps) = crate::mux::parameter_sets(au) .ok_or("the first coded picture carries no SPS/PPS")?; - none.insert(Mp4Muxer::create( + let Muxer::Mp4(mp4) = none.insert(Muxer::Mp4(Mp4Muxer::create( out, &VideoParams { width: meta.width, @@ -604,7 +711,10 @@ fn write_video( pps, }, audio, - )?) + )?)) else { + unreachable!("just inserted an mp4 muxer") + }; + mp4 } }; muxer.write_video_au(au) @@ -620,7 +730,10 @@ fn forced(var: &str) -> bool { } /// Hardware where it is available, software everywhere else -- chosen once for -/// the whole export, so the stream never changes encoder mid-file. +/// the whole export, so the stream never changes encoder mid-file. Both codecs +/// have both seats: an AV1 export runs on the plugin's VA-API encoder where the +/// GPU has one and on `rav1e` where it has not, which is the same pair H.264 has +/// had and the same silent fallback. enum Enc { Hw(HwEncoder), Sw { @@ -630,10 +743,26 @@ enum Enc { au: Vec, flushed: bool, }, + /// AV1 on the GPU, through the same plugin the H.264 seat uses. + Av1Hw(HwEncoder), + Av1Sw { + context: rav1e::Context, + /// Temporal units the encoder has finished but the caller has not + /// collected: `rav1e` reorders and may hand back several at once, while + /// this interface is one picture in, one unit out (the plugin's own + /// `ready` queue exists for the same reason). + ready: std::collections::VecDeque<(Vec, bool)>, + /// The unit currently lent out, for the same reason `Sw` owns one. + au: Vec, + flushed: bool, + }, } impl Enc { fn open(meta: &VideoMeta, settings: &ExportSettings) -> crate::Result { + if settings.format == Format::Av1 { + return Self::open_av1(meta, settings); + } // A caller's number goes through the same clamp as the computed one: a // zero bitrate switches the software encoder's lookahead on, which would // break the one-picture-per-call contract `encode` documents below. @@ -671,7 +800,75 @@ impl Enc { }) } - /// One picture in, at most one access unit out. + /// The AV1 pair. The hardware seat is the plugin's, opened by a symbol of + /// its own (`vh_enc_av1_open`) so a plugin built before AV1 encode existed + /// simply has none and this falls through -- the same "no" a GPU without an + /// AV1 encode entrypoint gives, and the same silent fallback either way. + /// + /// It is **opt-in**, which is the one place this pair does not mirror the + /// H.264 one: the vendored cros-codecs AV1 encoder hung the GPU on this + /// project's own radeonsi box -- `engine_hw: operation failed`, then an + /// amdgpu hard recovery and a lost context, measured 2026-08-10 exporting + /// the 720p fixture. A software encoder that takes half a minute is a worse + /// export than a hardware one; a driver reset is not an export at all. So + /// the plugin's AV1 seat is wired, kept and only entered when `VE_HW_AV1=1` + /// asks for it by name. + /// + /// ponytail: the upgrade path is a driver this was reproduced against (or a + /// cros-codecs release that fixes it) plus a probe encode of one frame at + /// open, after which this can prefer hardware the way H.264 does. + fn open_av1(meta: &VideoMeta, settings: &ExportSettings) -> crate::Result { + let bitrate = settings + .bitrate + .map_or_else(|| bitrate_for(meta), |b| b.clamp(MIN_BITRATE, MAX_BITRATE)); + let (fps_num, fps_den) = crate::mux::frame_timing(meta.frame_rate)?; + // Two seconds between keyframes, as the H.264 seat does: a seek may only + // land on one, and this is what a cluster of the Matroska file is. + let gop = (meta.frame_rate * 2.0).round().max(1.0) as u64; + if forced("VE_HW_AV1") + && !settings.force_sw + && !forced("VE_SW_ENC") + && let Some(hw) = + HwEncoder::open_av1(meta.width, meta.height, fps_num, fps_den, bitrate) + { + eprintln!("export encoder: hardware AV1 (VA-API plugin)"); + return Ok(Self::Av1Hw(hw)); + } + eprintln!("export encoder: software AV1 (rav1e)"); + let mut cfg = rav1e::EncoderConfig::default(); + cfg.width = meta.width as usize; + cfg.height = meta.height as usize; + cfg.bit_depth = 8; + cfg.chroma_sampling = rav1e::prelude::ChromaSampling::Cs420; + // Seconds per frame, which is what `frame_timing` already has as an + // exact rational -- 1001/24000 rather than a rounded 23.976. + cfg.time_base = rav1e::prelude::Rational::new(u64::from(fps_den), u64::from(fps_num)); + cfg.min_key_frame_interval = gop; + cfg.max_key_frame_interval = gop; + cfg.bitrate = bitrate.min(i32::MAX as u64) as i32; + // The fastest preset there is, and it is still slow: `rav1e` is built + // here without its assembly (no `nasm` in this project's build), so an + // export runs at a fraction of realtime. The export worker reports + // progress the whole way, which is what makes that bearable rather than + // hidden. + cfg.speed_settings = rav1e::prelude::SpeedSettings::from_preset(AV1_SPEED); + let config = rav1e::Config::new() + .with_encoder_config(cfg) + .with_threads(std::thread::available_parallelism().map_or(1, |n| n.get())); + let context = config + .new_context::() + .map_err(|e| format!("software AV1 encoder: {e}"))?; + Ok(Self::Av1Sw { + context, + ready: std::collections::VecDeque::new(), + au: Vec::new(), + flushed: false, + }) + } + + /// One picture in, at most one access unit out, and whether that unit is one + /// a decoder may be started from -- which only the Matroska muxer asks, the + /// mp4 one reading its own sync flag off the IDR slice. /// /// ponytail: `rusty_h264` buffers a whole GOP and returns it in one buffer /// when its lookahead is active, which would make this "one access unit" @@ -685,9 +882,35 @@ impl Enc { v: &[u8], width: u32, height: u32, - ) -> crate::Result> { + ) -> crate::Result> { match self { - Self::Hw(hw) => hw.encode(y, u, v, width, height, false), + Self::Av1Hw(hw) => { + let au = hw.encode(y, u, v, width, height, false)?; + // What the *bitstream* says, not what was asked for: an AV1 + // keyframe carries the sequence header, which is the same mark + // `demux` reads a sync point off. A driver that emitted one + // unasked is then still a seek target, and one that skipped a + // requested keyframe cannot be mistaken for a decoder's start. + Ok(au.map(|au| (au, crate::mux::av1_sequence_header(au).is_some()))) + } + Self::Av1Sw { + context, ready, au, .. + } => { + let mut frame = context.new_frame(); + let (w, h) = (width as usize, height as usize); + let (cw, ch) = (w.div_ceil(2), h.div_ceil(2)); + frame.planes[0].copy_from_raw_u8(&y[..w * h], w, 1); + frame.planes[1].copy_from_raw_u8(&u[..cw * ch], cw, 1); + frame.planes[2].copy_from_raw_u8(&v[..cw * ch], cw, 1); + if let Err(e) = context.send_frame(frame) { + return Err(format!("software AV1 encode: {e}").into()); + } + collect_av1(context, ready)?; + Ok(pop_av1(ready, au)) + } + Self::Hw(hw) => Ok(hw + .encode(y, u, v, width, height, false)? + .map(|au| (au, false))), Self::Sw { encoder, au, .. } => { let frame = YuvFrame { width: width as usize, @@ -699,15 +922,32 @@ impl Enc { *au = encoder .try_encode(&frame) .map_err(|e| format!("software encode: {e}"))?; - Ok(Some(&au[..]).filter(|au| !au.is_empty())) + Ok(Some((&au[..], false)).filter(|(au, _)| !au.is_empty())) } } } /// End of stream; call until it returns `None`. - fn drain(&mut self) -> crate::Result> { + fn drain(&mut self) -> crate::Result> { match self { - Self::Hw(hw) => hw.drain(), + Self::Av1Hw(hw) => { + let au = hw.drain()?; + Ok(au.map(|au| (au, crate::mux::av1_sequence_header(au).is_some()))) + } + Self::Av1Sw { + context, + ready, + au, + flushed, + } => { + if !*flushed { + *flushed = true; + context.flush(); + collect_av1(context, ready)?; + } + Ok(pop_av1(ready, au)) + } + Self::Hw(hw) => Ok(hw.drain()?.map(|au| (au, false))), Self::Sw { encoder, au, @@ -720,12 +960,43 @@ impl Enc { *au = encoder .try_flush() .map_err(|e| format!("software encoder flush: {e}"))?; - Ok(Some(&au[..]).filter(|au| !au.is_empty())) + Ok(Some((&au[..], false)).filter(|(au, _)| !au.is_empty())) } } } } +/// Every temporal unit `rav1e` has finished, moved into the queue in display +/// order. `NeedMoreData` (send another picture) and `LimitReached` (the flush is +/// through) are the two ways it says there is nothing more; `Encoded` means a +/// picture was coded but not yet packetised, which is a *keep asking* -- taking +/// it for an end leaves the tail of the export inside the encoder. +fn collect_av1( + context: &mut rav1e::Context, + ready: &mut std::collections::VecDeque<(Vec, bool)>, +) -> crate::Result<()> { + use rav1e::prelude::{EncoderStatus, FrameType}; + loop { + match context.receive_packet() { + Ok(packet) => ready.push_back((packet.data, packet.frame_type == FrameType::KEY)), + Err(EncoderStatus::Encoded) => {} + Err(EncoderStatus::NeedMoreData | EncoderStatus::LimitReached) => return Ok(()), + Err(e) => return Err(format!("software AV1 encode: {e}").into()), + } + } +} + +/// The oldest finished unit, moved into the buffer that is lent out -- the same +/// "valid until the next call" contract the plugin's slice has. +fn pop_av1<'a>( + ready: &mut std::collections::VecDeque<(Vec, bool)>, + au: &'a mut Vec, +) -> Option<(&'a [u8], bool)> { + let (unit, key) = ready.pop_front()?; + *au = unit; + Some((&au[..], key)) +} + /// I420 straight out of the decoder: the export never converts to BGRA and back, /// which would cost two conversions and a generation of colour precision. /// diff --git a/crates/engine/src/hw.rs b/crates/engine/src/hw.rs index 840f8fe..8a68b81 100644 --- a/crates/engine/src/hw.rs +++ b/crates/engine/src/hw.rs @@ -200,6 +200,13 @@ unsafe impl Send for HwSession {} struct EncPlugin { open: extern "C" fn(u32, u32, u32, u32, u64) -> *mut c_void, + /// The AV1 seat, and the one symbol that may be missing: a plugin built + /// before AV1 encode existed exports the four below and not this, which + /// costs an AV1 export its hardware path and nothing else. Every session it + /// opens is fed and closed through the very same three entry points -- the + /// plugin keeps one session type for both codecs, so the codec is decided + /// once, at the open, exactly as the H.264 seat's parameters are. + open_av1: Option *mut c_void>, frame: unsafe extern "C" fn(*mut c_void, *const VhFrame, i32, *mut *const u8, *mut usize) -> i32, drain: unsafe extern "C" fn(*mut c_void, *mut *const u8, *mut usize) -> i32, @@ -225,6 +232,7 @@ fn load_enc() -> Option { (|| { Some(EncPlugin { open: *lib.get(b"vh_enc_open\0").ok()?, + open_av1: lib.get(b"vh_enc_av1_open\0").ok().map(|s| *s), frame: *lib.get(b"vh_enc_frame\0").ok()?, drain: *lib.get(b"vh_enc_drain\0").ok()?, close: *lib.get(b"vh_enc_close\0").ok()?, @@ -253,7 +261,50 @@ impl HwEncoder { /// falls back to the software encoder. pub fn open(width: u32, height: u32, fps_num: u32, fps_den: u32, bitrate: u64) -> Option { let plugin = enc_plugin()?; - let handle = (plugin.open)(width, height, fps_num, fps_den, bitrate); + Self::opened( + plugin, + plugin.open, + width, + height, + fps_num, + fps_den, + bitrate, + ) + } + + /// The same, coding AV1 instead. `None` on everything [`HwEncoder::open`] + /// answers `None` to *and* on a plugin or a GPU with no AV1 encoder -- an + /// AV1 encode entrypoint is recent hardware, so this is the fallback that + /// really fires, and the caller's software AV1 encoder takes the export + /// without saying anything about it. + /// + /// The caller only reaches this behind `VE_HW_AV1=1`: the vendored encoder + /// reset this project's own GPU, which [`crate::export::Enc::open_av1`] + /// states in full. + pub fn open_av1( + width: u32, + height: u32, + fps_num: u32, + fps_den: u32, + bitrate: u64, + ) -> Option { + let plugin = enc_plugin()?; + let open = plugin.open_av1?; + Self::opened(plugin, open, width, height, fps_num, fps_den, bitrate) + } + + /// The null check both opens share, which is the plugin's whole way of + /// saying "no". + fn opened( + plugin: &'static EncPlugin, + open: extern "C" fn(u32, u32, u32, u32, u64) -> *mut c_void, + width: u32, + height: u32, + fps_num: u32, + fps_den: u32, + bitrate: u64, + ) -> Option { + let handle = open(width, height, fps_num, fps_den, bitrate); if handle.is_null() { return None; } diff --git a/crates/engine/src/mux.rs b/crates/engine/src/mux.rs index bc319c4..5344c58 100644 --- a/crates/engine/src/mux.rs +++ b/crates/engine/src/mux.rs @@ -1,8 +1,13 @@ //! Annex-B -> MP4, the mirror of `demux`: encoders emit start-code framed NALs, //! an mp4 sample wants 4-byte length prefixes with SPS/PPS living in `avcC`. +//! +//! ...and AV1 -> Matroska, the mirror of the *other* half of `demux`, for the +//! same reason that half exists: `mp4 0.14` has no `av01` sample entry at all, +//! so an AV1 export is written as EBML by hand exactly as an AV1 import is read +//! as EBML by hand ([`MkvMuxer`]). use std::fs::File; -use std::io::BufWriter; +use std::io::{BufWriter, Seek, SeekFrom, Write}; use std::path::Path; use mp4::{ @@ -177,6 +182,323 @@ impl Mp4Muxer { } } +// Matroska element ids, written with the leading length marker they carry in the +// file -- the same spelling `demux` reads them back with. +const EBML: u32 = 0x1A45_DFA3; +const EBML_VERSION: u32 = 0x4286; +const EBML_READ_VERSION: u32 = 0x42F7; +const EBML_MAX_ID_LENGTH: u32 = 0x42F2; +const EBML_MAX_SIZE_LENGTH: u32 = 0x42F3; +const DOC_TYPE: u32 = 0x4282; +const DOC_TYPE_VERSION: u32 = 0x4287; +const DOC_TYPE_READ_VERSION: u32 = 0x4285; +const SEGMENT: u32 = 0x1853_8067; +const INFO: u32 = 0x1549_A966; +const TIMESTAMP_SCALE: u32 = 0x2AD7B1; +const DURATION: u32 = 0x4489; +const MUXING_APP: u32 = 0x4D80; +const WRITING_APP: u32 = 0x5741; +const TRACKS: u32 = 0x1654_AE6B; +const TRACK_ENTRY: u32 = 0xAE; +const TRACK_NUMBER: u32 = 0xD7; +const TRACK_UID: u32 = 0x73C5; +const TRACK_TYPE: u32 = 0x83; +const FLAG_LACING: u32 = 0x9C; +const CODEC_ID: u32 = 0x86; +const CODEC_PRIVATE: u32 = 0x63A2; +const DEFAULT_DURATION: u32 = 0x23E383; +const VIDEO: u32 = 0xE0; +const PIXEL_WIDTH: u32 = 0xB0; +const PIXEL_HEIGHT: u32 = 0xBA; +const CLUSTER: u32 = 0x1F43_B675; +const CLUSTER_TIMESTAMP: u32 = 0xE7; +const SIMPLE_BLOCK: u32 = 0xA3; + +/// One millisecond, the tick every Matroska muxer writes and this one's block +/// timestamps are in. The *rate* is not derived from these -- `DefaultDuration` +/// is, in exact nanoseconds -- so a millisecond is precise enough for the +/// presentation times and coarse enough to keep a cluster's 16-bit relative +/// timestamp covering half a minute. +const TIMESTAMP_SCALE_NS: u64 = 1_000_000; +/// A cluster is buffered whole (its size is a header field), so it is flushed +/// at the first keyframe past this -- a ceiling on what the muxer holds, not a +/// target. +const CLUSTER_BYTES: usize = 4 << 20; +/// ...and on how far a block's timestamp may sit from its cluster's: the field +/// is a signed 16-bit millisecond count. +const CLUSTER_MS: i64 = 30_000; + +/// The fixed four bytes of an `AV1CodecConfigurationRecord` for what both encode +/// paths here are configured to produce: profile 0, 8-bit, 4:2:0, no operating +/// point delay. `seq_level_idx` is written as 31 -- "maximum parameters", i.e. +/// unstated -- which is what rav1e's own `container_sequence_header` writes and +/// what keeps this record from claiming a level neither encoder promised. The +/// sequence header OBU follows it; that is where a decoder reads the real +/// parameters from, and `demux::parse_av1c` hands exactly those bytes back. +const AV1C_HEAD: [u8; 4] = [ + 0x81, // marker 1, version 1 + 0x1F, // seq_profile 0, seq_level_idx_0 31 + 0x0C, // tier 0, 8-bit, colour, chroma subsampled both ways + 0x00, // no initial presentation delay +]; + +/// What an AV1 Matroska track declares. `config` is the sequence header OBU, +/// which is [`av1_sequence_header`]'s answer for the first coded keyframe. +pub struct Av1Params<'a> { + pub width: u32, + pub height: u32, + pub frame_rate: f64, + pub config: &'a [u8], +} + +/// Writes one AV1 video track as Matroska (`.mkv`). Picture only: this project +/// has no encoder for any sound Matroska carries, and copying the timeline's AAC +/// in would write a track its own reader refuses (`audio::AudioSession::open` +/// leaves a Matroska file silent) -- so the sound is named as left out by the +/// front-end rather than written unplayable. +/// +/// The file is patched twice at [`finish`](MkvMuxer::finish) -- the segment size +/// and the duration -- so a killed process leaves an unfinished file rather than +/// a wrong one; the export's `.part` rename covers that already. +pub struct MkvMuxer { + file: File, + /// Nanoseconds a frame lasts: `DefaultDuration`, which is the *only* exact + /// statement of the frame rate in the file (see `demux::MkvDemuxer::open`). + frame_ns: u64, + segment_size_at: u64, + duration_at: u64, + /// The cluster being built: everything after its id and size, so it can be + /// written once its length is known. + cluster: Vec, + cluster_ts: i64, + frames: u64, +} + +impl MkvMuxer { + pub fn create(path: &Path, video: &Av1Params) -> crate::Result { + if !video.frame_rate.is_finite() || video.frame_rate <= 0.0 { + return Err(format!("bad frame rate {}", video.frame_rate).into()); + } + if video.width == 0 || video.height == 0 { + return Err(format!("bad dimensions {}x{}", video.width, video.height).into()); + } + let frame_ns = (1e9 / video.frame_rate).round() as u64; + if frame_ns == 0 { + return Err(format!("frame rate {} is too fast to time", video.frame_rate).into()); + } + if video.config.is_empty() { + return Err("no AV1 sequence header for the track's CodecPrivate".into()); + } + + let mut head = Vec::new(); + let mut ebml = Vec::new(); + uint(&mut ebml, EBML_VERSION, 1); + uint(&mut ebml, EBML_READ_VERSION, 1); + uint(&mut ebml, EBML_MAX_ID_LENGTH, 4); + uint(&mut ebml, EBML_MAX_SIZE_LENGTH, 8); + elem(&mut ebml, DOC_TYPE, b"matroska"); + uint(&mut ebml, DOC_TYPE_VERSION, 4); + uint(&mut ebml, DOC_TYPE_READ_VERSION, 2); + elem(&mut head, EBML, &ebml); + + // The segment's size is only known at `finish`; it is reserved at the + // widest encoding (8 bytes) so patching it never moves a byte after it. + put_id(&mut head, SEGMENT); + let segment_size_at = head.len() as u64; + head.extend_from_slice(&[0x01, 0, 0, 0, 0, 0, 0, 0]); + + let mut info = Vec::new(); + uint(&mut info, TIMESTAMP_SCALE, TIMESTAMP_SCALE_NS); + elem(&mut info, MUXING_APP, b"edith"); + elem(&mut info, WRITING_APP, b"edith"); + put_id(&mut info, DURATION); + put_size(&mut info, 8); + // Where those eight bytes will land once `Info` is written into `head`, + // which is what `finish` seeks back to. + let duration_at = (head.len() + elem_head_len(INFO, info.len() + 8) + info.len()) as u64; + info.extend_from_slice(&0f64.to_be_bytes()); + elem(&mut head, INFO, &info); + + let mut entry = Vec::new(); + uint(&mut entry, TRACK_NUMBER, 1); + uint(&mut entry, TRACK_UID, 1); + uint(&mut entry, TRACK_TYPE, 1); // video + uint(&mut entry, FLAG_LACING, 0); + elem(&mut entry, CODEC_ID, b"V_AV1"); + let mut av1c = AV1C_HEAD.to_vec(); + av1c.extend_from_slice(video.config); + elem(&mut entry, CODEC_PRIVATE, &av1c); + uint(&mut entry, DEFAULT_DURATION, frame_ns); + let mut dims = Vec::new(); + uint(&mut dims, PIXEL_WIDTH, u64::from(video.width)); + uint(&mut dims, PIXEL_HEIGHT, u64::from(video.height)); + elem(&mut entry, VIDEO, &dims); + let mut tracks = Vec::new(); + elem(&mut tracks, TRACK_ENTRY, &entry); + elem(&mut head, TRACKS, &tracks); + + let mut file = File::create(path)?; + file.write_all(&head)?; + Ok(Self { + file, + frame_ns, + segment_size_at, + duration_at, + cluster: Vec::new(), + cluster_ts: 0, + frames: 0, + }) + } + + /// One coded picture: a whole AV1 temporal unit, in the low-overhead OBU + /// format the demuxer hands back. `key` marks a block a decoder may be + /// started from -- said by the encoder rather than guessed at here, and a + /// keyframe is where a new cluster opens, so every seek target is one. + pub fn write_frame(&mut self, obus: &[u8], key: bool) -> crate::Result<()> { + if obus.is_empty() { + return Err("an empty AV1 temporal unit".into()); + } + let ts = (self.frames * self.frame_ns + TIMESTAMP_SCALE_NS / 2) as i64 + / TIMESTAMP_SCALE_NS as i64; + // A new cluster at every keyframe -- a seek lands on one, so a cluster + // is a whole GOP -- and at the two limits a cluster has whatever the + // encoder keys: what it may weigh, and how far a 16-bit relative + // timestamp reaches. + if self.cluster.is_empty() + || key + || self.cluster.len() >= CLUSTER_BYTES + || ts - self.cluster_ts >= CLUSTER_MS + { + self.flush()?; + self.cluster_ts = ts; + uint(&mut self.cluster, CLUSTER_TIMESTAMP, ts as u64); + } + let mut block = Vec::with_capacity(obus.len() + 4); + block.push(0x81); // track number 1, as a one-byte EBML integer + block.extend_from_slice(&((ts - self.cluster_ts) as i16).to_be_bytes()); + block.push(if key { 0x80 } else { 0 }); + block.extend_from_slice(obus); + elem(&mut self.cluster, SIMPLE_BLOCK, &block); + self.frames += 1; + Ok(()) + } + + fn flush(&mut self) -> crate::Result<()> { + if self.cluster.is_empty() { + return Ok(()); + } + let mut head = Vec::new(); + put_id(&mut head, CLUSTER); + put_size(&mut head, self.cluster.len() as u64); + self.file.write_all(&head)?; + self.file.write_all(&self.cluster)?; + self.cluster.clear(); + Ok(()) + } + + /// Closes the last cluster and patches the two fields that could not be + /// known while writing: the segment's size and the presentation duration. + pub fn finish(mut self) -> crate::Result<()> { + self.flush()?; + if self.frames == 0 { + return Err("no frames were written to the Matroska file".into()); + } + let end = self.file.stream_position()?; + let body = end - (self.segment_size_at + 8); + // The reserved 8-byte size: marker bit in the top byte, value under it. + let size = (1u64 << 56) | body; + self.file.seek(SeekFrom::Start(self.segment_size_at))?; + self.file.write_all(&size.to_be_bytes())?; + let ms = self.frames as f64 * self.frame_ns as f64 / TIMESTAMP_SCALE_NS as f64; + self.file.seek(SeekFrom::Start(self.duration_at))?; + self.file.write_all(&ms.to_be_bytes())?; + self.file.flush()?; + Ok(()) + } +} + +/// The sequence header OBU of a coded temporal unit, for the track's +/// `CodecPrivate`. `None` when the unit carries none, which the first keyframe +/// of a stream never may -- no decoder can start without it. +pub fn av1_sequence_header(obus: &[u8]) -> Option<&[u8]> { + let mut at = 0; + while at < obus.len() { + let header = obus[at]; + // OBU header: type in bits 6..3, then the extension and size flags. + let kind = (header >> 3) & 0xF; + let mut len = 1 + usize::from(header & 0x4 != 0); + // Only the low-overhead format is written or read here: an OBU with no + // size field runs to the end of the unit, which makes the rest of it + // unwalkable, so it is not something to guess at. + if header & 0x2 == 0 { + return None; + } + let (size, size_len) = leb128(obus.get(at + len..)?)?; + len += size_len; + let body = obus.get(at + len..at + len + size)?; + if kind == 1 { + return Some(&obus[at..at + len + body.len()]); + } + at += len + size; + } + None +} + +/// An unsigned LEB128 as AV1 writes its OBU sizes: `(value, bytes read)`. +fn leb128(buf: &[u8]) -> Option<(usize, usize)> { + let mut value = 0usize; + for (i, &byte) in buf.iter().take(8).enumerate() { + value |= usize::from(byte & 0x7F) << (i * 7); + if byte & 0x80 == 0 { + return Some((value, i + 1)); + } + } + None +} + +/// An element id, written as the bytes it is spelled with -- the leading zeros +/// of the constant are not part of it. +fn put_id(out: &mut Vec, id: u32) { + let bytes = id.to_be_bytes(); + let skip = bytes.iter().take_while(|&&b| b == 0).count(); + out.extend_from_slice(&bytes[skip..]); +} + +/// An element size as an EBML variable-length integer, in the fewest bytes that +/// hold it. A value of all ones means *unknown* length, so a size that would +/// land on one takes a byte more. +fn put_size(out: &mut Vec, size: u64) { + let mut len = 1; + while len < 8 && size >= (1u64 << (7 * len)) - 1 { + len += 1; + } + let value = (1u64 << (7 * len)) | size; + out.extend_from_slice(&value.to_be_bytes()[8 - len..]); +} + +fn elem(out: &mut Vec, id: u32, payload: &[u8]) { + put_id(out, id); + put_size(out, payload.len() as u64); + out.extend_from_slice(payload); +} + +/// An unsigned integer element, big-endian in as few bytes as it takes (one at +/// the least: a zero is a byte, not an absence). +fn uint(out: &mut Vec, id: u32, value: u64) { + let bytes = value.to_be_bytes(); + let skip = bytes.iter().take_while(|&&b| b == 0).count().min(7); + elem(out, id, &bytes[skip..]); +} + +/// How many bytes an element's id and size take, which is what an offset inside +/// a payload has to be moved by to become an offset in the file. +fn elem_head_len(id: u32, payload: usize) -> usize { + let (mut head, mut size) = (Vec::new(), Vec::new()); + put_id(&mut head, id); + put_size(&mut size, payload as u64); + head.len() + size.len() +} + /// `(timescale, ticks per frame)` for `fps`, chosen so one frame is a *whole* /// number of ticks: 90 kHz wherever it divides exactly (every integer rate, so /// those exports stay byte for byte what they were), and `round(fps * 1001)` @@ -484,6 +806,110 @@ mod tests { std::fs::remove_file(&out).unwrap(); } + /// One OBU in the low-overhead format: header byte, then a one-byte LEB128 + /// size, which is all a payload this short needs. + fn obu(kind: u8, payload: &[u8]) -> Vec { + let mut out = vec![(kind << 3) | 0x02, payload.len() as u8]; + out.extend_from_slice(payload); + out + } + + /// An EBML size is written in the fewest bytes that hold it -- and never in + /// a length whose value is all ones, which is the *unknown* size the reader + /// would take for "runs to the end of its parent". + #[test] + fn element_sizes_never_spell_an_unknown_length() { + let size = |n| { + let mut out = Vec::new(); + put_size(&mut out, n); + out + }; + assert_eq!(size(0), [0x80]); + assert_eq!(size(126), [0xFE]); + assert_eq!(size(127), [0x40, 0x7F], "127 is all ones in one byte"); + assert_eq!(size(128), [0x40, 0x80]); + assert_eq!(size(0x3FFE), [0x7F, 0xFE]); + assert_eq!(size(0x3FFF), [0x20, 0x3F, 0xFF], "and again at two bytes"); + // Ids are their own bytes, marker and all: that is how `demux` compares + // them, so a one-byte id must not grow leading zeros here. + let mut id = Vec::new(); + put_id(&mut id, SIMPLE_BLOCK); + assert_eq!(id, [0xA3]); + let mut id = Vec::new(); + put_id(&mut id, CLUSTER); + assert_eq!(id, [0x1F, 0x43, 0xB6, 0x75]); + } + + /// The Matroska half of the round trip, with no encoder in it: three coded + /// units out through the muxer and back in through our own demuxer, which is + /// where the hand-written EBML meets the hand-written EBML reader. + #[test] + fn an_av1_track_round_trips_through_our_own_matroska_reader() { + let sequence = obu(1, &[0x11, 0x22, 0x33]); + let mut key = sequence.clone(); + key.extend_from_slice(&obu(6, &[0xAA; 8])); + let inter = obu(6, &[0xBB; 5]); + + let out = std::env::temp_dir().join(format!("ve_mkv_{}.mkv", std::process::id())); + let config = av1_sequence_header(&key).expect("the keyframe carries one"); + assert_eq!(config, &sequence[..], "the sequence header OBU, whole"); + let mut muxer = MkvMuxer::create( + &out, + &Av1Params { + width: 640, + height: 360, + frame_rate: 30.0, + config, + }, + ) + .unwrap(); + muxer.write_frame(&key, true).unwrap(); + muxer.write_frame(&inter, false).unwrap(); + muxer.write_frame(&inter, false).unwrap(); + muxer.finish().unwrap(); + + let (meta, mut demuxer) = crate::demux::Demuxer::open(&out).expect("reopen"); + assert_eq!(meta.codec, crate::demux::Codec::Av1); + assert_eq!((meta.width, meta.height), (640, 360)); + assert!( + (meta.frame_rate - 30.0).abs() < 1e-6, + "DefaultDuration must state the rate exactly: {}", + meta.frame_rate + ); + assert_eq!(meta.frame_count, 3); + + // The keyframe comes back with the `CodecPrivate` sequence header in + // front of it, which is the demuxer's own doing -- so what this checks + // is that the record was written and parsed, not that the block grew. + let first = demuxer.next_access_unit().unwrap().unwrap(); + assert_eq!(&first[..sequence.len()], &sequence[..]); + assert_eq!(&first[sequence.len()..], &key[..]); + assert_eq!(demuxer.next_access_unit().unwrap().unwrap(), inter); + assert_eq!(demuxer.next_access_unit().unwrap().unwrap(), inter); + assert!(demuxer.next_access_unit().unwrap().is_none()); + // One keyframe, so every seek rewinds to it -- and the flag really was + // written, or block 0 would be the answer by default rather than by + // being a sync point. + assert_eq!(demuxer.seek_to_sync_at_or_before(2), 0); + + // A track with no sequence header to declare is refused where the + // message still means something, rather than written unplayable. + assert!( + MkvMuxer::create( + &out, + &Av1Params { + width: 640, + height: 360, + frame_rate: 30.0, + config: &[], + }, + ) + .is_err() + ); + assert!(av1_sequence_header(&inter).is_none(), "no sequence header"); + std::fs::remove_file(&out).unwrap(); + } + /// The whole pipe at an NTSC rate: what we write is what we read back, to /// the ninth decimal. Before this bug was fixed the same round trip lost /// 23.976 on the way out (a rounded frame duration) *and* on the way back diff --git a/crates/engine/tests/av1.rs b/crates/engine/tests/av1.rs index 7b43c77..7faf849 100644 --- a/crates/engine/tests/av1.rs +++ b/crates/engine/tests/av1.rs @@ -224,8 +224,176 @@ fn an_av1_source_exports_as_h264() { handle.result().expect("outcome").expect("export"); let (written, _) = Demuxer::open(&out).expect("reopen the export"); - assert_eq!(written.codec, Codec::H264, "exports are always H.264"); + assert_eq!(written.codec, Codec::H264, "the default format is H.264"); assert_eq!(written.frame_count, FRAMES, "every timeline frame written"); assert_eq!((written.width, written.height), (1280, 720)); let _ = std::fs::remove_file(&out); } + +/// A short timeline out of the H.264 fixture, which is what the AV1 export tests +/// below write: `rav1e` is built here without its assembly, so the length of the +/// timeline is the length of the test. +fn short_timeline(frames: f64) -> PlaybackSession { + let mut session = PlaybackSession::open(asset("test_baseline.mp4")).expect("open the fixture"); + assert!(session.cut_at(frames / 30.0), "cut at frame {frames}"); + assert!( + session.delete_clip(engine::project::Lane::V1, 1), + "drop everything after it" + ); + session +} + +fn av1_settings() -> ExportSettings { + ExportSettings { + format: engine::export::Format::Av1, + // The software encoder, on every machine: the hardware twin below is + // where the plugin's AV1 seat is exercised. + force_sw: true, + ..Default::default() + } +} + +fn exported( + session: &PlaybackSession, + name: &str, + settings: &ExportSettings, + limit: Duration, +) -> PathBuf { + let out = std::env::temp_dir().join(format!("ve_av1_{name}_{}.mkv", std::process::id())); + let _ = std::fs::remove_file(&out); + let started = Instant::now(); + let handle = session.export_to_with(&out, settings); + while !handle.is_finished() { + assert!( + started.elapsed() < limit, + "export did not finish in {limit:?}" + ); + std::thread::sleep(Duration::from_millis(20)); + } + handle.result().expect("outcome").expect("export"); + assert_eq!(handle.progress(), 1.0, "finished at full progress"); + let spent = started.elapsed().as_secs_f64(); + let frames = (session.timeline_duration() * 30.0).round().max(1.0); + eprintln!( + "{name}: {frames} frames in {spent:.2} s = {:.2} ms/frame", + spent * 1000.0 / frames + ); + out +} + +/// The export half of this slice: AV1 out of the software encoder, into a +/// Matroska file this project's own demuxer walks back. Nothing installed is +/// needed -- the file is *read* as a container here, which is where the +/// hand-written EBML either agrees with the hand-written EBML reader or does not. +#[test] +fn an_av1_export_reopens_through_our_own_demuxer() { + let session = short_timeline(30.0); + let out = exported(&session, "sw", &av1_settings(), Duration::from_secs(300)); + + let (meta, mut demuxer) = Demuxer::open(&out).expect("reopen the export"); + assert_eq!(meta.codec, Codec::Av1, "an AV1 export is AV1"); + assert_eq!((meta.width, meta.height), (1280, 720)); + assert!( + (meta.frame_rate - 30.0).abs() < 1e-6, + "DefaultDuration must state the rate exactly: {}", + meta.frame_rate + ); + assert_eq!(meta.frame_count, 30, "every timeline frame is a block"); + + // The first block is a keyframe and leads with the sequence header -- the + // demuxer prepends `CodecPrivate` to every keyframe, so this is also the + // check that the `av1C` record was written and parsed back. + let first = demuxer.next_access_unit().expect("read").expect("a unit"); + assert_eq!( + (first[0] >> 3) & 0xF, + 1, + "the keyframe leads with the sequence header" + ); + assert_eq!(first[0] & 0x2, 2, "obu_has_size_field: low-overhead format"); + let mut count = 1; + while demuxer.next_access_unit().expect("read").is_some() { + count += 1; + } + assert_eq!(count, 30, "every block comes back out"); + assert_eq!( + demuxer.seek_to_sync_at_or_before(29), + 0, + "one GOP, one sync point" + ); + std::fs::remove_file(&out).unwrap(); +} + +/// An audio-only timeline is refused an AV1 export by name, exactly as it is +/// refused an mp4: every frame of it is a gap, so the file would be black. +#[test] +fn an_av1_export_of_an_audio_only_timeline_is_refused_by_name() { + let session = PlaybackSession::open(asset("test_tone.wav")).expect("open the tone"); + let out = std::env::temp_dir().join(format!("ve_av1_refused_{}.mkv", std::process::id())); + let handle = session.export_to_with(&out, &av1_settings()); + while !handle.is_finished() { + std::thread::sleep(Duration::from_millis(10)); + } + let refused = handle + .result() + .expect("outcome") + .expect_err("an audio-only timeline has no picture to code") + .to_string(); + assert!(refused.contains("no picture"), "{refused}"); + assert!(refused.contains("AV1"), "{refused}"); + assert!(!out.exists(), "nothing is written for a refusal"); +} + +/// The whole loop, and the only place it is closed: the file the export wrote is +/// decoded back into pictures, and those pictures are the source's. +#[test] +#[ignore = "needs libengine_hw.so and a VA-API driver with AV1 decode"] +fn an_av1_export_decodes_back_into_the_pictures_that_went_in() { + let session = short_timeline(30.0); + let out = exported( + &session, + "roundtrip", + &av1_settings(), + Duration::from_secs(300), + ); + + let (_, frames) = DecodeSession::open(&out).expect("decode the export"); + let frames: Vec<_> = frames.into_iter().collect(); + assert_eq!(frames.len(), 30, "every written frame decodes back"); + let (_, source, _) = DecodeSession::open_range(asset("test_baseline.mp4"), 0, 30) + .expect("open the source again"); + let source: Vec<_> = source.into_iter().collect(); + for (i, (written, original)) in frames.iter().zip(&source).enumerate() { + let diff: f64 = written + .bgra + .iter() + .zip(&original.bgra) + .map(|(a, b)| f64::from(a.abs_diff(*b))) + .sum::() + / written.bgra.len() as f64; + assert!( + diff < 12.0, + "frame {i} drifted by {diff:.2} from the source" + ); + } + std::fs::remove_file(&out).unwrap(); +} + +/// The hardware seat of the same pair, which is opt-in: `VE_HW_AV1=1` is what +/// enters it, because the vendored encoder reset the GPU of the box this was +/// written on (see `export::Enc::open_av1`). Without that variable this measures +/// the software encoder again, which is the honest outcome rather than a +/// failure, so what it asserts is the file. +#[test] +#[ignore = "needs libengine_hw.so, VE_HW_AV1=1 and a driver whose AV1 encoder survives it"] +fn an_av1_export_runs_on_the_plugin_where_the_gpu_has_one() { + let session = short_timeline(60.0); + let settings = ExportSettings { + format: engine::export::Format::Av1, + ..Default::default() + }; + let out = exported(&session, "hw", &settings, Duration::from_secs(600)); + let (meta, _) = Demuxer::open(&out).expect("reopen the export"); + assert_eq!(meta.codec, Codec::Av1); + assert_eq!(meta.frame_count, 60); + std::fs::remove_file(&out).unwrap(); +}