diff --git a/crates/ec-hw/abi-probe.c b/crates/ec-hw/abi-probe.c deleted file mode 100644 index 43784c30..00000000 --- a/crates/ec-hw/abi-probe.c +++ /dev/null @@ -1,271 +0,0 @@ -/* abi-probe.c — print the layout of every libva codec parameter struct this - * crate transcribes, compiled against the *system* headers. - * - * The numbers it prints are pasted into the `const _: () = assert!(...)` block - * at the end of each `src/params/*.rs`, so a transcription slip is a compile - * error rather than a driver reading garbage. Rerun after a libva upgrade: - * - * cc -o /tmp/abi-probe crates/ec-hw/abi-probe.c $(pkg-config --cflags libva) && /tmp/abi-probe - * - * Same contract as crates/ec-va/abi-probe.c, one level up the stack. - */ -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#define S(t) printf("%-46s size=%-6zu align=%zu\n", #t, sizeof(t), _Alignof(t)) -#define O(t, f) printf(" %-44s %zu\n", #t "." #f, offsetof(t, f)) - -int main(void) -{ - printf("libva %d.%d.%d\n", VA_MAJOR_VERSION, VA_MINOR_VERSION, VA_MICRO_VERSION); - - S(VAPictureH264); - O(VAPictureH264, frame_idx); - O(VAPictureH264, flags); - O(VAPictureH264, TopFieldOrderCnt); - O(VAPictureH264, BottomFieldOrderCnt); - - S(VAPictureParameterBufferH264); - O(VAPictureParameterBufferH264, ReferenceFrames); - O(VAPictureParameterBufferH264, picture_width_in_mbs_minus1); - O(VAPictureParameterBufferH264, bit_depth_luma_minus8); - O(VAPictureParameterBufferH264, num_ref_frames); - O(VAPictureParameterBufferH264, seq_fields); - O(VAPictureParameterBufferH264, pic_init_qp_minus26); - O(VAPictureParameterBufferH264, pic_fields); - O(VAPictureParameterBufferH264, frame_num); - - S(VAIQMatrixBufferH264); - O(VAIQMatrixBufferH264, ScalingList8x8); - - S(VASliceParameterBufferH264); - O(VASliceParameterBufferH264, slice_data_bit_offset); - O(VASliceParameterBufferH264, slice_type); - O(VASliceParameterBufferH264, cabac_init_idc); - O(VASliceParameterBufferH264, RefPicList0); - O(VASliceParameterBufferH264, RefPicList1); - O(VASliceParameterBufferH264, luma_log2_weight_denom); - O(VASliceParameterBufferH264, luma_weight_l0); - O(VASliceParameterBufferH264, chroma_weight_l0); - O(VASliceParameterBufferH264, luma_weight_l1_flag); - O(VASliceParameterBufferH264, chroma_offset_l1); - - S(VAPictureHEVC); - O(VAPictureHEVC, pic_order_cnt); - O(VAPictureHEVC, flags); - - S(VAPictureParameterBufferHEVC); - O(VAPictureParameterBufferHEVC, ReferenceFrames); - O(VAPictureParameterBufferHEVC, pic_width_in_luma_samples); - O(VAPictureParameterBufferHEVC, pic_fields); - O(VAPictureParameterBufferHEVC, sps_max_dec_pic_buffering_minus1); - O(VAPictureParameterBufferHEVC, column_width_minus1); - O(VAPictureParameterBufferHEVC, row_height_minus1); - O(VAPictureParameterBufferHEVC, slice_parsing_fields); - O(VAPictureParameterBufferHEVC, log2_max_pic_order_cnt_lsb_minus4); - O(VAPictureParameterBufferHEVC, st_rps_bits); - - S(VASliceParameterBufferHEVC); - O(VASliceParameterBufferHEVC, slice_segment_address); - O(VASliceParameterBufferHEVC, RefPicList); - O(VASliceParameterBufferHEVC, LongSliceFlags); - O(VASliceParameterBufferHEVC, collocated_ref_idx); - O(VASliceParameterBufferHEVC, luma_log2_weight_denom); - O(VASliceParameterBufferHEVC, delta_luma_weight_l0); - O(VASliceParameterBufferHEVC, delta_luma_weight_l1); - O(VASliceParameterBufferHEVC, five_minus_max_num_merge_cand); - O(VASliceParameterBufferHEVC, num_entry_point_offsets); - O(VASliceParameterBufferHEVC, slice_data_num_emu_prevn_bytes); - - S(VAIQMatrixBufferHEVC); - O(VAIQMatrixBufferHEVC, ScalingList32x32); - O(VAIQMatrixBufferHEVC, ScalingListDC16x16); - - S(VADecPictureParameterBufferVP9); - O(VADecPictureParameterBufferVP9, reference_frames); - O(VADecPictureParameterBufferVP9, pic_fields); - O(VADecPictureParameterBufferVP9, filter_level); - O(VADecPictureParameterBufferVP9, first_partition_size); - O(VADecPictureParameterBufferVP9, mb_segment_tree_probs); - O(VADecPictureParameterBufferVP9, profile); - - S(VASegmentParameterVP9); - O(VASegmentParameterVP9, filter_level); - O(VASegmentParameterVP9, luma_ac_quant_scale); - - S(VASliceParameterBufferVP9); - O(VASliceParameterBufferVP9, seg_param); - - S(VASegmentationStructAV1); - O(VASegmentationStructAV1, feature_data); - O(VASegmentationStructAV1, feature_mask); - S(VAFilmGrainStructAV1); - O(VAFilmGrainStructAV1, grain_seed); - O(VAFilmGrainStructAV1, ar_coeffs_y); - O(VAFilmGrainStructAV1, cr_offset); - S(VAWarpedMotionParamsAV1); - O(VAWarpedMotionParamsAV1, wmmat); - O(VAWarpedMotionParamsAV1, invalid); - - S(VADecPictureParameterBufferAV1); - O(VADecPictureParameterBufferAV1, seq_info_fields); - O(VADecPictureParameterBufferAV1, current_frame); - O(VADecPictureParameterBufferAV1, anchor_frames_num); - O(VADecPictureParameterBufferAV1, anchor_frames_list); - O(VADecPictureParameterBufferAV1, frame_width_minus1); - O(VADecPictureParameterBufferAV1, ref_frame_map); - O(VADecPictureParameterBufferAV1, ref_frame_idx); - O(VADecPictureParameterBufferAV1, seg_info); - O(VADecPictureParameterBufferAV1, film_grain_info); - O(VADecPictureParameterBufferAV1, tile_cols); - O(VADecPictureParameterBufferAV1, width_in_sbs_minus_1); - O(VADecPictureParameterBufferAV1, height_in_sbs_minus_1); - O(VADecPictureParameterBufferAV1, tile_count_minus_1); - O(VADecPictureParameterBufferAV1, pic_info_fields); - O(VADecPictureParameterBufferAV1, superres_scale_denominator); - O(VADecPictureParameterBufferAV1, loop_filter_info_fields); - O(VADecPictureParameterBufferAV1, ref_deltas); - O(VADecPictureParameterBufferAV1, base_qindex); - O(VADecPictureParameterBufferAV1, qmatrix_fields); - O(VADecPictureParameterBufferAV1, mode_control_fields); - O(VADecPictureParameterBufferAV1, cdef_damping_minus_3); - O(VADecPictureParameterBufferAV1, cdef_y_strengths); - O(VADecPictureParameterBufferAV1, loop_restoration_fields); - O(VADecPictureParameterBufferAV1, wm); - - S(VASliceParameterBufferAV1); - O(VASliceParameterBufferAV1, tile_row); - O(VASliceParameterBufferAV1, anchor_frame_idx); - O(VASliceParameterBufferAV1, tile_idx_in_tile_list); - - S(VAEncSequenceParameterBufferH264); - O(VAEncSequenceParameterBufferH264, intra_period); - O(VAEncSequenceParameterBufferH264, picture_width_in_mbs); - O(VAEncSequenceParameterBufferH264, seq_fields); - O(VAEncSequenceParameterBufferH264, bit_depth_luma_minus8); - O(VAEncSequenceParameterBufferH264, offset_for_non_ref_pic); - O(VAEncSequenceParameterBufferH264, offset_for_ref_frame); - O(VAEncSequenceParameterBufferH264, frame_cropping_flag); - O(VAEncSequenceParameterBufferH264, frame_crop_left_offset); - O(VAEncSequenceParameterBufferH264, vui_parameters_present_flag); - O(VAEncSequenceParameterBufferH264, vui_fields); - O(VAEncSequenceParameterBufferH264, aspect_ratio_idc); - O(VAEncSequenceParameterBufferH264, num_units_in_tick); - O(VAEncSequenceParameterBufferH264, time_scale); - - S(VAEncPictureParameterBufferH264); - O(VAEncPictureParameterBufferH264, ReferenceFrames); - O(VAEncPictureParameterBufferH264, coded_buf); - O(VAEncPictureParameterBufferH264, pic_parameter_set_id); - O(VAEncPictureParameterBufferH264, frame_num); - O(VAEncPictureParameterBufferH264, pic_init_qp); - O(VAEncPictureParameterBufferH264, pic_fields); - - S(VAEncSliceParameterBufferH264); - O(VAEncSliceParameterBufferH264, macroblock_info); - O(VAEncSliceParameterBufferH264, slice_type); - O(VAEncSliceParameterBufferH264, idr_pic_id); - O(VAEncSliceParameterBufferH264, delta_pic_order_cnt_bottom); - O(VAEncSliceParameterBufferH264, direct_spatial_mv_pred_flag); - O(VAEncSliceParameterBufferH264, RefPicList0); - O(VAEncSliceParameterBufferH264, RefPicList1); - O(VAEncSliceParameterBufferH264, luma_log2_weight_denom); - O(VAEncSliceParameterBufferH264, cabac_init_idc); - - S(VAEncSequenceParameterBufferHEVC); - O(VAEncSequenceParameterBufferHEVC, intra_period); - O(VAEncSequenceParameterBufferHEVC, pic_width_in_luma_samples); - O(VAEncSequenceParameterBufferHEVC, seq_fields); - O(VAEncSequenceParameterBufferHEVC, log2_min_luma_coding_block_size_minus3); - O(VAEncSequenceParameterBufferHEVC, pcm_sample_bit_depth_luma_minus1); - O(VAEncSequenceParameterBufferHEVC, vui_parameters_present_flag); - O(VAEncSequenceParameterBufferHEVC, vui_fields); - O(VAEncSequenceParameterBufferHEVC, aspect_ratio_idc); - O(VAEncSequenceParameterBufferHEVC, vui_num_units_in_tick); - O(VAEncSequenceParameterBufferHEVC, min_spatial_segmentation_idc); - O(VAEncSequenceParameterBufferHEVC, scc_fields); - - S(VAEncPictureParameterBufferHEVC); - O(VAEncPictureParameterBufferHEVC, reference_frames); - O(VAEncPictureParameterBufferHEVC, coded_buf); - O(VAEncPictureParameterBufferHEVC, collocated_ref_pic_index); - O(VAEncPictureParameterBufferHEVC, column_width_minus1); - O(VAEncPictureParameterBufferHEVC, row_height_minus1); - O(VAEncPictureParameterBufferHEVC, log2_parallel_merge_level_minus2); - O(VAEncPictureParameterBufferHEVC, nal_unit_type); - O(VAEncPictureParameterBufferHEVC, pic_fields); - O(VAEncPictureParameterBufferHEVC, hierarchical_level_plus1); - O(VAEncPictureParameterBufferHEVC, scc_fields); - - S(VAEncSliceParameterBufferHEVC); - O(VAEncSliceParameterBufferHEVC, num_ctu_in_slice); - O(VAEncSliceParameterBufferHEVC, slice_type); - O(VAEncSliceParameterBufferHEVC, ref_pic_list0); - O(VAEncSliceParameterBufferHEVC, ref_pic_list1); - O(VAEncSliceParameterBufferHEVC, luma_log2_weight_denom); - O(VAEncSliceParameterBufferHEVC, max_num_merge_cand); - O(VAEncSliceParameterBufferHEVC, slice_fields); - O(VAEncSliceParameterBufferHEVC, pred_weight_table_bit_offset); - - S(VAEncSequenceParameterBufferAV1); - O(VAEncSequenceParameterBufferAV1, intra_period); - O(VAEncSequenceParameterBufferAV1, seq_fields); - O(VAEncSequenceParameterBufferAV1, order_hint_bits_minus_1); - S(VAEncSegParamAV1); - O(VAEncSegParamAV1, feature_data); - O(VAEncSegParamAV1, feature_mask); - S(VAEncWarpedMotionParamsAV1); - S(VAEncPictureParameterBufferAV1); - O(VAEncPictureParameterBufferAV1, reconstructed_frame); - O(VAEncPictureParameterBufferAV1, coded_buf); - O(VAEncPictureParameterBufferAV1, reference_frames); - O(VAEncPictureParameterBufferAV1, ref_frame_idx); - O(VAEncPictureParameterBufferAV1, ref_frame_ctrl_l0); - O(VAEncPictureParameterBufferAV1, picture_flags); - O(VAEncPictureParameterBufferAV1, seg_id_block_size); - O(VAEncPictureParameterBufferAV1, filter_level); - O(VAEncPictureParameterBufferAV1, loop_filter_flags); - O(VAEncPictureParameterBufferAV1, ref_deltas); - O(VAEncPictureParameterBufferAV1, base_qindex); - O(VAEncPictureParameterBufferAV1, min_base_qindex); - O(VAEncPictureParameterBufferAV1, qmatrix_flags); - O(VAEncPictureParameterBufferAV1, mode_control_flags); - O(VAEncPictureParameterBufferAV1, segments); - O(VAEncPictureParameterBufferAV1, tile_cols); - O(VAEncPictureParameterBufferAV1, width_in_sbs_minus_1); - O(VAEncPictureParameterBufferAV1, context_update_tile_id); - O(VAEncPictureParameterBufferAV1, cdef_damping_minus_3); - O(VAEncPictureParameterBufferAV1, loop_restoration_flags); - O(VAEncPictureParameterBufferAV1, wm); - O(VAEncPictureParameterBufferAV1, bit_offset_qindex); - O(VAEncPictureParameterBufferAV1, tile_group_obu_hdr_info); - O(VAEncPictureParameterBufferAV1, number_skip_frames); - O(VAEncPictureParameterBufferAV1, skip_frames_reduced_size); - S(VAEncTileGroupBufferAV1); - - S(VAEncMiscParameterRateControl); - O(VAEncMiscParameterRateControl, rc_flags); - O(VAEncMiscParameterRateControl, ICQ_quality_factor); - O(VAEncMiscParameterRateControl, max_qp); - S(VAEncMiscParameterFrameRate); - O(VAEncMiscParameterFrameRate, framerate_flags); - S(VAEncMiscParameterHRD); - O(VAEncMiscParameterHRD, buffer_size); - S(VAEncMiscParameterBufferQualityLevel); - S(VAEncPackedHeaderParameterBuffer); - O(VAEncPackedHeaderParameterBuffer, bit_length); - O(VAEncPackedHeaderParameterBuffer, has_emulation_bytes); - S(VACodedBufferSegment); - O(VACodedBufferSegment, bit_offset); - O(VACodedBufferSegment, status); - O(VACodedBufferSegment, buf); - O(VACodedBufferSegment, next); - return 0; -} diff --git a/crates/ec-hw/examples/hw_caps.rs b/crates/ec-hw/examples/hw_caps.rs deleted file mode 100644 index 555255bb..00000000 --- a/crates/ec-hw/examples/hw_caps.rs +++ /dev/null @@ -1,102 +0,0 @@ -//! Lists hardware capabilities, then encodes a gradient with each codec and decodes the Vulkan streams back. -//! -//! ```text -//! cargo run -p ec-hw --example hw_caps -//! ``` - -use ec_hw::{ - Backend, Codec, EncCodec, EncoderConfig, FrameMetadata, HwDecoder, HwEncoder, I420, - RateControlMode, capabilities, -}; - -const FRAMES: u32 = 30; -const WIDTH: u32 = 1280; -const HEIGHT: u32 = 720; - -fn main() { - for cap in capabilities() { - println!( - "{:?} {:?} {:?} {:?} max {}x{}", - cap.backend, cap.direction, cap.codec, cap.profile, cap.max_width, cap.max_height - ); - } - for codec in [EncCodec::H264, EncCodec::H265, EncCodec::Av1] { - if let Err(e) = run(codec) { - println!("{codec:?}: error: {e}"); - } - } -} - -fn run(codec: EncCodec) -> ec_hw::Result<()> { - let config = EncoderConfig { - bitrate: 2_000_000, - rate_control: RateControlMode::ConstantBitrate, - ..EncoderConfig::new(codec, WIDTH, HEIGHT) - }; - let mut encoder = match HwEncoder::open(config, None) { - Ok(encoder) => encoder, - Err(e) => { - println!("{codec:?}: no encoder: {e}"); - return Ok(()); - } - }; - let backend = encoder.backend(); - let mut coded = Vec::with_capacity(FRAMES as usize); - for index in 0..FRAMES { - let meta = FrameMetadata { - timestamp: index as i64, - force_keyframe: index == 0, - }; - coded.push(encoder.encode(&gray_gradient(index), meta)?); - } - let bytes: usize = coded.iter().map(|c| c.data.len()).sum(); - println!("{codec:?} {backend:?} {FRAMES} frames {bytes} bytes"); - - if backend != Backend::Vk { - return Ok(()); - } - let mut decoder = match HwDecoder::open(decode_codec(codec)) { - Ok(decoder) => decoder, - Err(e) => { - println!(" decode unavailable: {e}"); - return Ok(()); - } - }; - let mut frames = 0; - for c in &coded { - decoder.decode(&c.data, c.timestamp)?; - while decoder.next_frame()?.is_some() { - frames += 1; - } - } - decoder.flush()?; - while decoder.next_frame()?.is_some() { - frames += 1; - } - println!(" decoded {frames} frames"); - Ok(()) -} - -fn decode_codec(codec: EncCodec) -> Codec { - match codec { - EncCodec::H264 => Codec::H264, - EncCodec::H265 => Codec::H265, - EncCodec::Av1 => Codec::Av1, - } -} - -fn gray_gradient(index: u32) -> I420 { - let (w, h) = (WIDTH as usize, HEIGHT as usize); - let shift = 4 * index as usize; - let y = (0..h) - .flat_map(|row| (0..w).map(move |col| ((col + row + shift) & 0xff) as u8)) - .collect(); - let chroma = w.div_ceil(2) * h.div_ceil(2); - I420 { - y, - u: vec![128; chroma], - v: vec![128; chroma], - width: WIDTH, - height: HEIGHT, - } -} diff --git a/crates/ec-hw/examples/hw_config.rs b/crates/ec-hw/examples/hw_config.rs deleted file mode 100644 index 1bdb28c1..00000000 --- a/crates/ec-hw/examples/hw_config.rs +++ /dev/null @@ -1,144 +0,0 @@ -use std::fs; -use std::path::{Path, PathBuf}; - -use ec_hw::{ - Backend, EncCodec, EncoderConfig, FrameMetadata, H264Profile, HwEncoder, I420, RateControlMode, -}; - -const WIDTH: u32 = 640; -const HEIGHT: u32 = 360; -const FRAMES: usize = 30; -const FPS: u32 = 30; -const GOP: u32 = 15; -const FORCE_AT: usize = 7; -const BITRATE: u32 = 2_000_000; -const FIELDS: [&str; 7] = [ - "profile", - "width", - "height", - "color_space", - "color_transfer", - "color_primaries", - "color_range", -]; - -fn config(profile: H264Profile) -> EncoderConfig { - EncoderConfig { - bitrate: BITRATE, - framerate: (FPS, 1), - gop_size: GOP, - rate_control: RateControlMode::ConstantBitrate, - ..EncoderConfig::new(EncCodec::H264, WIDTH, HEIGHT) - } - .h264_profile(profile) - .colour(6, 6, 6, true) -} - -fn frame(t: usize) -> I420 { - let (w, h) = (WIDTH as usize, HEIGHT as usize); - let y = (0..w * h) - .map(|i| ((i % w + i / w + 3 * t) & 0xff) as u8) - .collect(); - let chroma = w / 2 * h / 2; - I420 { - y, - u: vec![(96 + t % 64) as u8; chroma], - v: vec![160; chroma], - width: WIDTH, - height: HEIGHT, - } -} - -fn encode(dir: &Path, name: &str, profile: H264Profile, backend: Backend) -> Option { - let mut encoder = match HwEncoder::open(config(profile), Some(backend)) { - Ok(encoder) => encoder, - Err(e) => { - println!("{name}: {e}"); - return None; - } - }; - let mut stream = Vec::new(); - for t in 0..FRAMES { - let meta = FrameMetadata { - timestamp: t as i64, - force_keyframe: t == FORCE_AT, - }; - let coded = encoder.encode(&frame(t), meta).expect("encode frame"); - stream.extend_from_slice(&coded.data); - } - let path = dir.join(format!("{name}.h264")); - fs::write(&path, stream).expect("write stream"); - Some(path) -} - -fn probe(path: &Path) -> Vec<(String, String)> { - let out = ec_testkit::ffprobe() - .args(["-v", "error", "-select_streams", "v:0", "-show_entries"]) - .arg(format!("stream={}", FIELDS.join(","))) - .args(["-of", "default=nw=1"]) - .arg(path) - .output() - .expect("run ffprobe"); - String::from_utf8_lossy(&out.stdout) - .lines() - .filter_map(|l| l.split_once('=')) - .map(|(k, v)| (k.to_string(), v.to_string())) - .collect() -} - -fn keyframes(path: &Path) -> Vec { - let out = ec_testkit::ffprobe() - .args([ - "-v", - "error", - "-select_streams", - "v:0", - "-show_entries", - "frame=key_frame", - ]) - .args(["-of", "csv=p=0"]) - .arg(path) - .output() - .expect("run ffprobe"); - String::from_utf8_lossy(&out.stdout) - .lines() - .enumerate() - .filter(|(_, l)| l.trim() == "1") - .map(|(i, _)| i) - .collect() -} - -fn value(info: &[(String, String)], key: &str) -> String { - info.iter() - .find(|(k, _)| k == key) - .map_or("-".to_string(), |(_, v)| v.clone()) -} - -fn main() { - let dir = std::env::temp_dir(); - for (label, profile) in [("main", H264Profile::Main), ("cb", H264Profile::ConstrainedBaseline)] { - compare(&dir, label, profile); - } -} - -fn compare(dir: &Path, label: &str, profile: H264Profile) { - let Some(vk) = encode(dir, &format!("vk_{label}"), profile, Backend::Vk) else { - return; - }; - let Some(va) = encode(dir, &format!("va_{label}"), profile, Backend::Va) else { - return; - }; - let (vk_info, va_info) = (probe(&vk), probe(&va)); - let mut same = true; - println!("{:<16}{:<16}{:<16}", "field", "vk", "va"); - for key in FIELDS { - let (a, b) = (value(&vk_info, key), value(&va_info, key)); - same &= a == b; - println!("{key:<16}{a:<16}{b:<16}"); - } - let (kv, ka) = (keyframes(&vk), keyframes(&va)); - same &= kv == ka; - let list = |k: &[usize]| k.iter().map(usize::to_string).collect::>().join(","); - println!("{:<16}{:<16}{:<16}", "keyframes", list(&kv), list(&ka)); - println!("{label} match: {same}"); -} diff --git a/crates/ec-hw/examples/hw_decode.rs b/crates/ec-hw/examples/hw_decode.rs index 1a69046d..99ca62bc 100644 --- a/crates/ec-hw/examples/hw_decode.rs +++ b/crates/ec-hw/examples/hw_decode.rs @@ -130,12 +130,7 @@ fn mixed_cases(dir: &Path) { } fn mixed_case(label: &str, codec: Codec, units: &[&[u8]], ten: bool, gpu: &ec_vk::Gpu) { - let mut reference = if ten { - HwDecoder::open_16(codec) - } else { - HwDecoder::open(codec) - } - .expect("open decoder"); + let mut reference = HwDecoder::open(codec).expect("open decoder"); let expected = decoded_planes(&mut reference, units, ten); let mut decoder = HwDecoder::open(codec).expect("open mixed decoder"); @@ -187,17 +182,12 @@ fn dmabuf_cases(dir: &Path) { } fn dmabuf_case(label: &str, codec: Codec, units: &[&[u8]], ten: bool) { - let mut reference = if ten { - HwDecoder::open_16(codec) - } else { - HwDecoder::open(codec) - } - .expect("open decoder"); + let mut reference = HwDecoder::open(codec).expect("open decoder"); assert_eq!(reference.backend(), Backend::Vk, "{label}: must decode on Vulkan"); let expected = decoded_planes(&mut reference, units, ten); let gpu = ec_vk::Gpu::open().expect("Vulkan device"); - let mut decoder = HwDecoder::open_dmabuf(codec).expect("open DMA-BUF decoder"); + let mut decoder = HwDecoder::open(codec).expect("open DMA-BUF decoder"); assert_eq!(decoder.backend(), Backend::Vk, "{label}: DMA-BUF must decode on Vulkan"); let mut got = Vec::new(); for (pts, unit) in units.iter().enumerate() { @@ -222,7 +212,8 @@ fn decoded_planes(decoder: &mut HwDecoder, units: &[&[u8]], ten: bool) -> Vec<(V fn take_planes(decoder: &mut HwDecoder, ten: bool, out: &mut Vec<(Vec, Vec)>) { if ten { - while let Some((_, frame)) = decoder.next_frame_16().expect("next frame") { + while let Some(picture) = decoder.next_picture().expect("next picture") { + let frame = picture.to_i420_16().expect("to_i420_16"); out.push(p010_planes(&frame)); } } else { @@ -250,8 +241,9 @@ fn p010_planes(frame: &I420_16) -> (Vec, Vec) { } fn collect_dmabuf(decoder: &mut HwDecoder, gpu: &ec_vk::Gpu, out: &mut Vec<(Vec, Vec)>) { - while let Some((_, picture)) = decoder.next_dmabuf().expect("next DMA-BUF") { - out.push(read_back(gpu, picture)); + while let Some(picture) = decoder.next_picture().expect("next picture") { + let dmabuf = picture.export_dmabuf().expect("export DMA-BUF"); + out.push(read_back(gpu, dmabuf)); } } diff --git a/crates/ec-hw/examples/hw_pipeline.rs b/crates/ec-hw/examples/hw_pipeline.rs deleted file mode 100644 index 0afbaec2..00000000 --- a/crates/ec-hw/examples/hw_pipeline.rs +++ /dev/null @@ -1,165 +0,0 @@ -use std::time::Instant; - -use ec_hw::{ - Backend, EncCodec, EncodeInput, EncoderConfig, FrameMetadata, HwEncoder, I420, I420_16, - RateControlMode, -}; - -const FRAMES: usize = 120; -const PATTERN: usize = 6; - -struct Case { - codec: EncCodec, - width: u32, - height: u32, - ten: bool, -} - -enum Source { - Eight(Vec), - Ten(Vec), -} - -fn main() { - let cases = [ - Case { - codec: EncCodec::H265, - width: 3840, - height: 2160, - ten: true, - }, - Case { - codec: EncCodec::H264, - width: 1920, - height: 1080, - ten: false, - }, - Case { - codec: EncCodec::H265, - width: 1920, - height: 1080, - ten: false, - }, - Case { - codec: EncCodec::Av1, - width: 1920, - height: 1080, - ten: false, - }, - ]; - for case in &cases { - let source = if case.ten { - Source::Ten(pattern_16(case)) - } else { - Source::Eight(pattern(case)) - }; - for backend in [Backend::Vk, Backend::Va] { - if let Err(e) = run(case, &source, backend) { - println!( - "{:?} {}x{} {backend:?}: error: {e}", - case.codec, case.width, case.height - ); - } - } - } -} - -fn config(case: &Case) -> EncoderConfig { - let base = EncoderConfig { - rate_control: RateControlMode::ConstantQp { qp: 30 }, - ..EncoderConfig::new(case.codec, case.width, case.height) - }; - if case.ten { - base.ten_bit() - } else { - base - } -} - -fn meta(index: usize) -> FrameMetadata { - FrameMetadata { - timestamp: index as i64, - force_keyframe: index == 0, - } -} - -fn run(case: &Case, source: &Source, backend: Backend) -> ec_hw::Result<()> { - let mut encoder = HwEncoder::open(config(case), Some(backend))?; - let start = Instant::now(); - let mut sync = Vec::with_capacity(FRAMES); - for index in 0..FRAMES { - let coded = match source { - Source::Eight(frames) => encoder.encode(&frames[index % PATTERN], meta(index))?, - Source::Ten(frames) => encoder.encode_16(&frames[index % PATTERN], meta(index))?, - }; - sync.push(coded); - } - let sync_ms = start.elapsed().as_secs_f64() * 1000.0 / FRAMES as f64; - - let mut encoder = HwEncoder::open(config(case), Some(backend))?; - let start = Instant::now(); - let mut piped = Vec::with_capacity(FRAMES); - for index in 0..FRAMES { - let input = match source { - Source::Eight(frames) => EncodeInput::I420(&frames[index % PATTERN]), - Source::Ten(frames) => EncodeInput::I420_16(&frames[index % PATTERN]), - }; - piped.extend(encoder.submit(input, meta(index))?); - } - piped.extend(encoder.flush()?); - let piped_ms = start.elapsed().as_secs_f64() * 1000.0 / FRAMES as f64; - - if matches!(backend, Backend::Vk) { - assert_eq!(sync, piped, "{:?} sync and pipelined bitstreams differ", case.codec); - } - println!( - "{:?} {}x{} {}-bit {backend:?}: sync {sync_ms:.2} ms/frame, pipelined {piped_ms:.2} ms/frame, {} frames", - case.codec, - case.width, - case.height, - if case.ten { 10 } else { 8 }, - piped.len() - ); - Ok(()) -} - -fn pattern(case: &Case) -> Vec { - let (w, h) = (case.width as usize, case.height as usize); - let (cw, ch) = (w / 2, h / 2); - (0..PATTERN) - .map(|k| I420 { - y: (0..h) - .flat_map(move |row| (0..w).map(move |x| ((x + row + 3 * k) & 0xff) as u8)) - .collect(), - u: (0..ch) - .flat_map(move |row| (0..cw).map(move |x| ((x + 2 * row + 5 * k) & 0xff) as u8)) - .collect(), - v: (0..ch) - .flat_map(move |row| (0..cw).map(move |x| ((2 * x + row + 7 * k) & 0xff) as u8)) - .collect(), - width: case.width, - height: case.height, - }) - .collect() -} - -fn pattern_16(case: &Case) -> Vec { - let (w, h) = (case.width as usize, case.height as usize); - let (cw, ch) = (w / 2, h / 2); - (0..PATTERN) - .map(|k| I420_16 { - y: (0..h) - .flat_map(move |row| (0..w).map(move |x| ((x + row + 3 * k) & 0x3ff) as u16)) - .collect(), - u: (0..ch) - .flat_map(move |row| (0..cw).map(move |x| ((x + 2 * row + 5 * k) & 0x3ff) as u16)) - .collect(), - v: (0..ch) - .flat_map(move |row| (0..cw).map(move |x| ((2 * x + row + 7 * k) & 0x3ff) as u16)) - .collect(), - width: case.width, - height: case.height, - bit_depth: 10, - }) - .collect() -} diff --git a/crates/ec-hw/examples/hw_rgb.rs b/crates/ec-hw/examples/hw_rgb.rs deleted file mode 100644 index cab3262e..00000000 --- a/crates/ec-hw/examples/hw_rgb.rs +++ /dev/null @@ -1,148 +0,0 @@ -use ec_hw::{ - Backend, Codec, EncCodec, EncoderConfig, FrameMetadata, HwDecoder, HwEncoder, I420, - RateControlMode, RgbFrame, RgbOrder, -}; - -const FRAMES: u32 = 30; - -fn main() { - for codec in [EncCodec::H264, EncCodec::H265, EncCodec::Av1] { - if let Err(e) = run(codec, (1280, 720), (1280, 720)) { - println!("{codec:?} 1280x720: error: {e}"); - } - } - for target in [(1280, 720), (640, 360)] { - if let Err(e) = run(EncCodec::H264, (1920, 1080), target) { - println!("H264 1920x1080 -> {}x{}: error: {e}", target.0, target.1); - } - } -} - -fn run(codec: EncCodec, source: (u32, u32), target: (u32, u32)) -> ec_hw::Result<()> { - let config = EncoderConfig { - bitrate: 4_000_000, - rate_control: RateControlMode::ConstantBitrate, - ..EncoderConfig::new(codec, target.0, target.1) - }; - let mut encoder = match HwEncoder::open(config, std::env::args().nth(1).map(|_| Backend::Va)) { - Ok(encoder) => encoder, - Err(e) => { - println!("{codec:?}: no encoder: {e}"); - return Ok(()); - } - }; - let backend = encoder.backend(); - let mut coded = Vec::with_capacity(FRAMES as usize); - for index in 0..FRAMES { - let pixels = bgra_gradient(index, source); - let frame = RgbFrame { - data: &pixels, - width: source.0, - height: source.1, - stride: source.0 * 4, - order: RgbOrder::Bgra, - }; - let meta = FrameMetadata { - timestamp: index as i64, - force_keyframe: index == 0, - }; - coded.push(encoder.encode_rgb(&frame, meta)?); - } - let bytes: usize = coded.iter().map(|c| c.data.len()).sum(); - println!( - "{codec:?} {backend:?} {}x{} -> {}x{} {FRAMES} frames {bytes} bytes", - source.0, source.1, target.0, target.1 - ); - - let mut decoder = match HwDecoder::open(decode_codec(codec)) { - Ok(decoder) => decoder, - Err(e) => { - println!(" decode unavailable: {e}"); - return Ok(()); - } - }; - let mut decoded = Vec::new(); - for c in &coded { - decoder.decode(&c.data, c.timestamp)?; - while let Some(frame) = decoder.next_frame()? { - decoded.push(frame); - } - } - decoder.flush()?; - while let Some(frame) = decoder.next_frame()? { - decoded.push(frame); - } - - let total: f64 = decoded - .iter() - .map(|(ts, frame)| { - mean_abs_luma(&frame.y, &luma_reference(*ts as u32, source, target)) - }) - .sum(); - let mean = if decoded.is_empty() { - 0.0 - } else { - total / decoded.len() as f64 - }; - println!( - " decoded {} frames, mean |Y diff| {mean:.2}", - decoded.len() - ); - Ok(()) -} - -fn decode_codec(codec: EncCodec) -> Codec { - match codec { - EncCodec::H264 => Codec::H264, - EncCodec::H265 => Codec::H265, - EncCodec::Av1 => Codec::Av1, - } -} - -fn bgra_gradient(index: u32, (w, h): (u32, u32)) -> Vec { - let shift = index as usize * 4; - let mut out = Vec::with_capacity(w as usize * h as usize * 4); - for y in 0..h as usize { - for x in 0..w as usize { - let r = (x + shift) & 0xff; - let g = (y + 2 * shift) & 0xff; - let b = ((x + y) / 2 + 3 * shift) & 0xff; - out.extend_from_slice(&[b as u8, g as u8, r as u8, 0xff]); - } - } - out -} - -fn luma_reference(index: u32, source: (u32, u32), target: (u32, u32)) -> Vec { - let (sw, sh) = (source.0 as usize, source.1 as usize); - let (w, h) = (target.0 as usize, target.1 as usize); - let mut scaled = vec![0; w * h * 4]; - ec_dsp::rgb::rgb_box_downscale( - &bgra_gradient(index, source), - sw, - sh, - sw * 4, - &mut scaled, - w, - h, - ); - let chroma = (w / 2) * (h / 2); - let mut frame = I420 { - y: vec![0; w * h], - u: vec![0; chroma], - v: vec![0; chroma], - width: target.0, - height: target.1, - }; - ec_dsp::rgb::bgra_to_i420_709(&scaled, w, h, &mut frame.y, &mut frame.u, &mut frame.v); - frame.y -} - -fn mean_abs_luma(decoded: &[u8], reference: &[u8]) -> f64 { - let sum: u64 = decoded - .iter() - .zip(reference) - .map(|(&a, &b)| u64::from(a.abs_diff(b))) - .sum(); - sum as f64 / reference.len() as f64 -} diff --git a/crates/ec-hw/examples/hw_smoke.rs b/crates/ec-hw/examples/hw_smoke.rs new file mode 100644 index 00000000..8000180b --- /dev/null +++ b/crates/ec-hw/examples/hw_smoke.rs @@ -0,0 +1,164 @@ +use ec_hw::{ + Backend, Codec, CodedFrame, EncCodec, EncoderConfig, FrameMetadata, HwDecoder, HwEncoder, HwPicture, I420_16, + RateControlMode, RgbFrame, RgbOrder, Tunings, capabilities, +}; + +const W: u32 = 1280; +const H: u32 = 720; +const FPS: u32 = 30; +const SEGMENT: u32 = 30; +const PEAK: f64 = 1023.0; + +fn main() { + for cap in capabilities() { + println!( + "{:?} {:?} {:?} {:?} max {}x{}", + cap.backend, cap.direction, cap.codec, cap.profile, cap.max_width, cap.max_height + ); + } + for codec in [EncCodec::H264, EncCodec::H265, EncCodec::Av1] { + if let Err(e) = eight_bit(codec) { + println!("{codec:?}: error: {e}"); + } + } + for codec in [EncCodec::H265, EncCodec::Av1] { + for backend in [Backend::Vk, Backend::Va] { + if let Err(e) = ten_bit(codec, backend) { + println!("{codec:?} 10-bit {backend:?}: error: {e}"); + } + } + } +} + +fn eight_bit(codec: EncCodec) -> ec_hw::Result<()> { + let config = EncoderConfig { + bitrate: 4_000_000, + framerate: (FPS, 1), + gop_size: 1000, + rate_control: RateControlMode::ConstantBitrate, + ..EncoderConfig::new(codec, W, H) + }; + let mut encoder = HwEncoder::open(config, None)?; + let mut coded = Vec::new(); + for index in 0..3 * SEGMENT { + if index == SEGMENT { + encoder.tune(Tunings { bitrate: 1_000_000, framerate: (FPS, 1) })?; + } + if index == 2 * SEGMENT { + encoder.tune(Tunings { bitrate: 3_000_000, framerate: (FPS, 1) })?; + } + let pixels = bgra_gradient(index); + let frame = RgbFrame { data: &pixels, width: W, height: H, stride: W * 4, order: RgbOrder::Bgra }; + let meta = FrameMetadata { timestamp: index as i64, force_keyframe: index == 0 }; + coded.push(encoder.encode_rgb(&frame, meta)?); + } + let kbps: Vec = coded + .chunks(SEGMENT as usize) + .map(|chunk| { + let bytes: usize = chunk.iter().map(|c| c.data.len()).sum(); + format!("{:.0}", bytes as f64 * 8.0 * FPS as f64 / SEGMENT as f64 / 1000.0) + }) + .collect(); + let keyframes = coded.iter().filter(|c| c.is_keyframe).count(); + println!("{codec:?} {:?} kb/s per segment: {} keyframes {keyframes}", encoder.backend(), kbps.join(" ")); + let decoded = decode(codec, &coded)?; + println!(" decoded {} of {}", decoded.len(), coded.len()); + Ok(()) +} + +fn ten_bit(codec: EncCodec, backend: Backend) -> ec_hw::Result<()> { + let config = EncoderConfig { + bitrate: 4_000_000, + rate_control: RateControlMode::ConstantQp { qp: 30 }, + ..EncoderConfig::new(codec, W, H).ten_bit() + }; + let mut encoder = HwEncoder::open(config, Some(backend))?; + let mut coded = Vec::new(); + let mut sources = Vec::new(); + for index in 0..SEGMENT { + let frame = pattern(index); + let meta = FrameMetadata { timestamp: index as i64, force_keyframe: index == 0 }; + coded.push(encoder.encode_16(&frame, meta)?); + sources.push(frame); + } + let decoded = decode(codec, &coded)?; + let mut sum = 0.0; + for picture in &decoded { + sum += psnr(&sources[picture.timestamp as usize], &picture.to_i420_16()?); + } + let psnr = sum / decoded.len().max(1) as f64; + println!("{codec:?} 10-bit {backend:?}: decoded {} of {}, PSNR {psnr:.2} dB", decoded.len(), coded.len()); + Ok(()) +} + +fn decode(codec: EncCodec, coded: &[CodedFrame]) -> ec_hw::Result> { + let mut decoder = HwDecoder::open(decode_codec(codec))?; + let mut pictures = Vec::new(); + for c in coded { + decoder.decode(&c.data, c.timestamp)?; + while let Some(picture) = decoder.next_picture()? { + pictures.push(picture); + } + } + decoder.flush()?; + while let Some(picture) = decoder.next_picture()? { + pictures.push(picture); + } + Ok(pictures) +} + +fn decode_codec(codec: EncCodec) -> Codec { + match codec { + EncCodec::H264 => Codec::H264, + EncCodec::H265 => Codec::H265, + EncCodec::Av1 => Codec::Av1, + } +} + +fn bgra_gradient(index: u32) -> Vec { + let shift = index as usize * 4; + let mut out = Vec::with_capacity(W as usize * H as usize * 4); + for y in 0..H as usize { + for x in 0..W as usize { + let r = (x + shift) & 0xff; + let g = (y + 2 * shift) & 0xff; + let b = ((x + y) / 2 + 3 * shift) & 0xff; + out.extend_from_slice(&[b as u8, g as u8, r as u8, 0xff]); + } + } + out +} + +fn pattern(index: u32) -> I420_16 { + let t = index as usize; + let (w, h) = (W as usize, H as usize); + I420_16 { + y: plane(w, h, |x, y| x * 3 + y * 5 + t * 16), + u: plane(w / 2, h / 2, |x, y| x * 7 + y * 2 + t * 9), + v: plane(w / 2, h / 2, |x, y| x * 2 + y * 11 + t * 5 + 512), + width: W, + height: H, + bit_depth: 10, + } +} + +fn plane(w: usize, h: usize, value: impl Fn(usize, usize) -> usize) -> Vec { + let mut out = Vec::with_capacity(w * h); + for row in 0..h { + for col in 0..w { + out.push((value(col, row) & 0x3ff) as u16); + } + } + out +} + +fn psnr(a: &I420_16, b: &I420_16) -> f64 { + let mut sse = 0f64; + let mut n = 0usize; + for (x, y) in a.y.iter().chain(&a.u).chain(&a.v).zip(b.y.iter().chain(&b.u).chain(&b.v)) { + let d = f64::from(*x) - f64::from(*y); + sse += d * d; + n += 1; + } + 10.0 * (PEAK * PEAK * n as f64 / sse).log10() +} diff --git a/crates/ec-hw/examples/hw_speed.rs b/crates/ec-hw/examples/hw_speed.rs deleted file mode 100644 index 184e8d5e..00000000 --- a/crates/ec-hw/examples/hw_speed.rs +++ /dev/null @@ -1,26 +0,0 @@ -use ec_hw::{EncCodec, EncoderConfig, FrameMetadata, HwEncoder, RateControlMode, RgbFrame, RgbOrder}; -use std::time::Instant; - -fn main() { - let (w, h) = (1920u32, 1080u32); - let frames: Vec> = (0..8) - .map(|t| (0..w * h).flat_map(|i| [(i % w + t * 9) as u8, (i / w) as u8, t as u8 * 20, 255]).collect()) - .collect(); - for codec in [EncCodec::H264, EncCodec::H265, EncCodec::Av1] { - for (ow, oh) in [(1920, 1080), (640, 360)] { - let mut cfg = EncoderConfig::new(codec, ow, oh); - cfg.bitrate = 8_000_000; - cfg.framerate = (60, 1); - cfg.rate_control = RateControlMode::ConstantBitrate; - let Ok(mut enc) = HwEncoder::open(cfg, None) else { continue }; - let n = 120; - let start = Instant::now(); - for i in 0..n { - let frame = RgbFrame { data: &frames[i % 8], width: w, height: h, stride: w * 4, order: RgbOrder::Bgra }; - enc.encode_rgb(&frame, FrameMetadata { timestamp: i as i64, force_keyframe: false }).unwrap(); - } - let ms = start.elapsed().as_secs_f64() * 1000.0 / n as f64; - println!("{codec:?} {:?} 1080p->{ow}x{oh}: {ms:.2} ms/frame ({:.0} fps)", enc.backend(), 1000.0 / ms); - } - } -} diff --git a/crates/ec-hw/examples/hw_ten.rs b/crates/ec-hw/examples/hw_ten.rs deleted file mode 100644 index d7f5fb0e..00000000 --- a/crates/ec-hw/examples/hw_ten.rs +++ /dev/null @@ -1,141 +0,0 @@ -use ec_hw::{ - Backend, Codec, EncCodec, EncoderConfig, FrameMetadata, HwDecoder, HwEncoder, I420_16, - RateControlMode, -}; - -const WIDTH: u32 = 1280; -const HEIGHT: u32 = 720; -const FRAMES: u32 = 30; -const PEAK: f64 = 1023.0; - -fn main() { - let dir = std::env::temp_dir().display().to_string(); - let rates = [ - ("cqp", RateControlMode::ConstantQp { qp: 30 }), - ("cbr", RateControlMode::ConstantBitrate), - ]; - for codec in [EncCodec::H265, EncCodec::Av1] { - for (name, rate) in rates { - for backend in [Backend::Vk, Backend::Va] { - if let Err(e) = run(&dir, codec, name, rate, backend) { - println!("{codec:?} {name} {backend:?}: error: {e}"); - } - } - } - } -} - -fn run( - dir: &str, - codec: EncCodec, - name: &str, - rate: RateControlMode, - backend: Backend, -) -> ec_hw::Result<()> { - let config = EncoderConfig { - bitrate: 4_000_000, - rate_control: rate, - ..EncoderConfig::new(codec, WIDTH, HEIGHT).ten_bit() - }; - let mut encoder = match HwEncoder::open(config, Some(backend)) { - Ok(encoder) => encoder, - Err(e) => { - println!("{codec:?} {name} {backend:?}: no encoder: {e}"); - return Ok(()); - } - }; - let mut coded = Vec::with_capacity(FRAMES as usize); - let mut sources = Vec::with_capacity(FRAMES as usize); - for index in 0..FRAMES { - let frame = pattern(index); - let meta = FrameMetadata { - timestamp: index as i64, - force_keyframe: index == 0, - }; - coded.push(encoder.encode_16(&frame, meta)?); - sources.push(frame); - } - let stream: Vec = coded.iter().flat_map(|c| c.data.iter().copied()).collect(); - let stem = format!("{dir}/ten_{codec:?}_{name}_{backend:?}"); - std::fs::write(format!("{stem}.bin"), &stream).expect("write bitstream"); - - let mut decoder = HwDecoder::open_16(decode_codec(codec))?; - let mut decoded = Vec::new(); - for c in &coded { - decoder.decode(&c.data, c.timestamp)?; - while let Some(frame) = decoder.next_frame_16()? { - decoded.push(frame); - } - } - decoder.flush()?; - while let Some(frame) = decoder.next_frame_16()? { - decoded.push(frame); - } - - let mut yuv = Vec::new(); - for (_, frame) in &decoded { - for sample in frame.y.iter().chain(&frame.u).chain(&frame.v) { - yuv.extend_from_slice(&sample.to_le_bytes()); - } - } - std::fs::write(format!("{stem}_ours.yuv"), &yuv).expect("write decoded yuv"); - - let psnr: f64 = decoded - .iter() - .map(|(ts, frame)| psnr(&sources[*ts as usize], frame)) - .sum::() - / decoded.len().max(1) as f64; - println!( - "{codec:?} {name} {backend:?}: {} bytes, decoded {} frames, PSNR {psnr:.2} dB", - stream.len(), - decoded.len() - ); - Ok(()) -} - -fn decode_codec(codec: EncCodec) -> Codec { - match codec { - EncCodec::H264 => Codec::H264, - EncCodec::H265 => Codec::H265, - EncCodec::Av1 => Codec::Av1, - } -} - -fn pattern(index: u32) -> I420_16 { - let t = index as usize; - let (w, h) = (WIDTH as usize, HEIGHT as usize); - I420_16 { - y: plane(w, h, |x, y| x * 3 + y * 5 + t * 16), - u: plane(w / 2, h / 2, |x, y| x * 7 + y * 2 + t * 9), - v: plane(w / 2, h / 2, |x, y| x * 2 + y * 11 + t * 5 + 512), - width: WIDTH, - height: HEIGHT, - bit_depth: 10, - } -} - -fn plane(w: usize, h: usize, value: impl Fn(usize, usize) -> usize) -> Vec { - let mut out = Vec::with_capacity(w * h); - for row in 0..h { - for col in 0..w { - out.push((value(col, row) & 0x3ff) as u16); - } - } - out -} - -fn psnr(a: &I420_16, b: &I420_16) -> f64 { - let mut sse = 0f64; - let mut n = 0usize; - for (x, y) in - a.y.iter() - .chain(&a.u) - .chain(&a.v) - .zip(b.y.iter().chain(&b.u).chain(&b.v)) - { - let d = f64::from(*x) - f64::from(*y); - sse += d * d; - n += 1; - } - 10.0 * (PEAK * PEAK * n as f64 / sse).log10() -} diff --git a/crates/ec-hw/examples/hw_tune.rs b/crates/ec-hw/examples/hw_tune.rs deleted file mode 100644 index f5743bc4..00000000 --- a/crates/ec-hw/examples/hw_tune.rs +++ /dev/null @@ -1,102 +0,0 @@ -use ec_hw::{ - Codec, EncCodec, EncoderConfig, FrameMetadata, HwDecoder, HwEncoder, RateControlMode, RgbFrame, - RgbOrder, Tunings, -}; - -const W: u32 = 1280; -const H: u32 = 720; -const FPS: u32 = 30; -const SEGMENT: u32 = 90; - -fn main() { - for codec in [EncCodec::H264, EncCodec::H265, EncCodec::Av1] { - if let Err(e) = run(codec) { - println!("{codec:?}: error: {e}"); - } - } -} - -fn run(codec: EncCodec) -> ec_hw::Result<()> { - let config = EncoderConfig { - bitrate: 4_000_000, - rate_control: RateControlMode::ConstantBitrate, - framerate: (FPS, 1), - gop_size: 1000, - ..EncoderConfig::new(codec, W, H) - }; - let mut encoder = HwEncoder::open(config, None)?; - let mut coded = Vec::new(); - for index in 0..3 * SEGMENT { - if index == SEGMENT { - encoder.tune(Tunings { - bitrate: 1_000_000, - framerate: (FPS, 1), - })?; - } - if index == 2 * SEGMENT { - encoder.tune(Tunings { - bitrate: 3_000_000, - framerate: (FPS, 1), - })?; - } - let pixels = bgra_gradient(index); - let frame = RgbFrame { - data: &pixels, - width: W, - height: H, - stride: W * 4, - order: RgbOrder::Bgra, - }; - let meta = FrameMetadata { - timestamp: index as i64, - force_keyframe: index == 0, - }; - coded.push(encoder.encode_rgb(&frame, meta)?); - } - - let mut line = format!("{codec:?} {:?} kb/s per segment:", encoder.backend()); - for chunk in coded.chunks(SEGMENT as usize) { - let bytes: usize = chunk.iter().map(|c| c.data.len()).sum(); - let kbps = bytes as f64 * 8.0 * FPS as f64 / SEGMENT as f64 / 1000.0; - line += &format!(" {kbps:.0}"); - } - let keyframes = coded.iter().filter(|c| c.is_keyframe).count(); - println!("{line}, keyframes {keyframes}"); - - let mut decoder = HwDecoder::open(decode_codec(codec))?; - let mut decoded = 0; - for c in &coded { - decoder.decode(&c.data, c.timestamp)?; - while decoder.next_frame()?.is_some() { - decoded += 1; - } - } - decoder.flush()?; - while decoder.next_frame()?.is_some() { - decoded += 1; - } - println!(" decoded {decoded} of {}", coded.len()); - Ok(()) -} - -fn decode_codec(codec: EncCodec) -> Codec { - match codec { - EncCodec::H264 => Codec::H264, - EncCodec::H265 => Codec::H265, - EncCodec::Av1 => Codec::Av1, - } -} - -fn bgra_gradient(index: u32) -> Vec { - let shift = index as usize * 4; - let mut out = Vec::with_capacity(W as usize * H as usize * 4); - for y in 0..H as usize { - for x in 0..W as usize { - let r = (x + shift) & 0xff; - let g = (y + 2 * shift) & 0xff; - let b = ((x + y) / 2 + 3 * shift) & 0xff; - out.extend_from_slice(&[b as u8, g as u8, r as u8, 0xff]); - } - } - out -} diff --git a/crates/ec-hw/src/enc/headers.rs b/crates/ec-hw/src/enc/headers.rs index 7fd0e64a..a9023700 100644 --- a/crates/ec-hw/src/enc/headers.rs +++ b/crates/ec-hw/src/enc/headers.rs @@ -9,7 +9,6 @@ //! field below therefore has to agree with the `VAEnc*ParameterBuffer` the //! driver was given, or the header describes a picture other than the one the //! hardware coded. -#![allow(dead_code)] // parked with the encoder: the writers return when it is ported /// `VAEncPackedHeaderSequence`: packed sequence-level header bits. pub const PACKED_HEADER_SEQUENCE: u32 = 1; diff --git a/crates/ec-hw/src/enc/mod.rs b/crates/ec-hw/src/enc/mod.rs index 4c8c0730..eb2e9aa2 100644 --- a/crates/ec-hw/src/enc/mod.rs +++ b/crates/ec-hw/src/enc/mod.rs @@ -34,7 +34,6 @@ //! are all measured by `gpu.rs`'s `av1_encode_rate_control_lands`, which //! prints what each mode delivered against what it was asked for. -#![allow(dead_code)] // the header writers wait for the encoder port use std::collections::VecDeque; use std::rc::Rc; @@ -49,10 +48,10 @@ use ec_va::va::{ VA_FOURCC_NV12, VA_FOURCC_P010, VA_RT_FORMAT_YUV420, VA_RT_FORMAT_YUV420_10, VA_SURFACE_ATTRIB_USAGE_HINT_ENCODER, VAConfigAttribType, VAImage, }; -use ec_va::{CapReport, Config, ConfigAttrib, Context, Display, Surface, SurfaceSpec, Vpp}; +use ec_va::{CapReport, Config, ConfigAttrib, Context, Display, Surface, SurfaceSpec}; use crate::error::{Error, Result}; -use crate::frame::{Frame, I420, I420_16}; +use crate::frame::{I420, I420_16}; use crate::pool::{PooledSurface, SurfacePool}; use crate::rate::{RATE_WINDOW_MS, RateFeedback, hrd_buffer_ms}; @@ -129,17 +128,6 @@ pub struct Encoder { /// Set when the rate control parameters have to be resent. tunings_dirty: bool, rc: RateFeedback, - profile: Profile, - /// P010 -> NV12 GPU-resident conversion pipeline for [`Encoder::encode_frame`] - /// on a source that is not the encoder's own format or size; built lazily, - /// since most encoders never see one. - vpp: Option, - /// The small pool [`Encoder::vpp`] converts into, round-robined rather - /// than pool-acquired: each conversion is fully synced before this - /// encoder's own picture submission returns, so two surfaces are enough - /// to never hand out one still in flight. - vpp_surfaces: Vec>, - vpp_next: usize, /// Pictures submitted by [`Encoder::submit`], oldest first, not yet read back. pending: VecDeque>, } @@ -264,10 +252,6 @@ impl Encoder { idr_count: 0, tunings_dirty: true, rc: RateFeedback::default(), - profile, - vpp: None, - vpp_surfaces: Vec::new(), - vpp_next: 0, pending: VecDeque::new(), }) } @@ -369,36 +353,6 @@ impl Encoder { } } - /// Pipelined encode of an imported surface: a GPU copy into a pool surface - /// whose padding is then zeroed, matching the CPU upload path. A surface of - /// the coded size is copied whole; any other size is scaled to the - /// configured width x height, so one capture can feed several layers. - pub fn submit_prime( - &mut self, - surface: Rc>, - meta: FrameMetadata, - ) -> Result> { - let input = self - .pool - .acquire() - .ok_or_else(|| Error::config("submit_prime: every surface is still in use"))?; - let dest = if surface.size() == self.coded_size { - (0, 0, 0, 0) - } else { - (0, 0, self.config.width, self.config.height) - }; - self.vpp()? - .convert_region(&surface, (0, 0, 0, 0), Rc::clone(input.surface()), dest)?; - zero_padding( - self.context.display(), - input.surface(), - self.config.bit_depth, - (self.config.width, self.config.height), - self.coded_size, - )?; - self.push_pipelined(input, meta) - } - fn retire_oldest(&mut self) -> Result> { match self.pending.pop_front() { Some(f) => self.finish(f).map(Some), @@ -431,72 +385,6 @@ impl Encoder { self.encode_settled(Rc::clone(input.surface()), meta) } - /// Encode a decoded frame's GPU surface directly: no `to_i420` read-back, - /// no re-upload, just the decoder's picture handed straight to the - /// encoder as its source. This is the path a decode-then-encode pipeline - /// (e.g. a transcode) wants — the alternative is a full frame through - /// system memory and back for no reason. - /// - /// A source whose size differs from the encoder's coded size, or whose - /// depth differs from the encoder's, goes through the GPU video-processing - /// pipeline into an NV12 surface of the encoder's size first. - /// - /// Refused, rather than silently working around, when: - /// - `frame` was decoded on a different [`ec_va::Display`]: a surface id - /// only means anything on the display that created it. - /// - `frame`'s bit depth is neither 8 nor 10. - pub fn encode_frame(&mut self, frame: &Frame, meta: FrameMetadata) -> Result { - if !self.pending.is_empty() { - return Err(Error::config( - "encode_frame: pipelined frames pending; call flush first", - )); - } - if frame.bit_depth != 8 && frame.bit_depth != 10 { - return Err(Error::unsupported( - format!("encode_frame of a {}-bit source", frame.bit_depth), - "the VPP conversion this crate builds reads 8-bit NV12 and 10-bit P010 only", - )); - } - if !Rc::ptr_eq(frame.display(), self.context.display()) { - return Err(Error::config( - "encode_frame: the frame was decoded on a different Display than this encoder", - )); - } - let source = - if frame.bit_depth != self.config.bit_depth || frame.coded_size != self.coded_size { - self.vpp_into_pool(frame.surface(), frame.display_size)? - } else { - Rc::clone(frame.surface()) - }; - self.encode_settled(source, meta) - } - - /// Encode a surface imported with [`ec_va::Surface::import_prime`] or - /// decoded elsewhere on this encoder's display: read by the GPU in place. - /// - /// The surface must be NV12, since H.264 is 8-bit only. A surface of another - /// size goes through the same GPU conversion as [`Encoder::encode_frame`]; - /// `display_size` is the picture's visible size (its cropped size, when the - /// surface is padded to the codec's block size). - pub fn encode_surface( - &mut self, - surface: &Rc>, - display_size: (u32, u32), - meta: FrameMetadata, - ) -> Result { - if !self.pending.is_empty() { - return Err(Error::config( - "encode_surface: pipelined frames pending; call flush first", - )); - } - if surface.size() != self.coded_size { - let converted = self.vpp_into_pool(surface, display_size)?; - self.encode_settled(converted, meta) - } else { - self.encode_settled(Rc::clone(surface), meta) - } - } - fn check_size(&self, width: u32, height: u32) -> Result<()> { if width != self.config.width || height != self.config.height { return Err(Error::config(format!( @@ -507,50 +395,6 @@ impl Encoder { Ok(()) } - /// Place a source surface's visible rect into this encoder's coded size, - /// in NV12, on the GPU: a whole-surface convert when the source is - /// already the encoder's coded size, a region copy/convert otherwise. - /// Builds the VPP pipeline and its two-surface pool on first use, painting - /// the pool black so any padding beyond `display_size` a region copy never - /// touches is deterministic. - fn vpp(&mut self) -> Result<&Vpp> { - if self.vpp.is_none() { - let spec = surface_spec(self.config.bit_depth, self.coded_size); - let display = Rc::clone(self.context.display()); - let surfaces = ec_va::create_pool(&display, &spec, 2)?; - for s in &surfaces { - fill_black(&display, s, self.coded_size, self.config.bit_depth)?; - } - let vpp = Vpp::new( - &display, - VA_RT_FORMAT_YUV420 | VA_RT_FORMAT_YUV420_10, - self.coded_size.0, - self.coded_size.1, - )?; - self.vpp_surfaces = surfaces.into_iter().map(Rc::new).collect(); - self.vpp = Some(vpp); - } - Ok(self.vpp.as_ref().expect("just built above if it was None")) - } - - fn vpp_into_pool( - &mut self, - source: &ec_va::va::Surface, - display_size: (u32, u32), - ) -> Result> { - self.vpp()?; - let dest = Rc::clone(&self.vpp_surfaces[self.vpp_next]); - self.vpp_next = (self.vpp_next + 1) % self.vpp_surfaces.len(); - let whole = display_size == self.coded_size; - let vpp = self.vpp()?; - if whole { - Ok(vpp.convert(source, dest)?) - } else { - let rect = (0, 0, display_size.0, display_size.1); - Ok(vpp.convert_region(source, rect, dest, rect)?) - } - } - /// Shared synchronous path for [`Encoder::encode`], [`Encoder::encode_frame`] /// and [`Encoder::encode_surface`]: submit, then read back at once. fn encode_settled( @@ -763,10 +607,6 @@ impl Encoder { Ok(()) } - pub(crate) fn context(&self) -> &Rc { - &self.context - } - pub(crate) fn config(&self) -> &EncoderConfig { &self.config } @@ -785,10 +625,6 @@ impl Encoder { self.idr_count } - /// The VA profile this encoder was configured with. - pub fn profile(&self) -> Profile { - self.profile - } } /// The surface format an encoder of `bit_depth` works in. @@ -869,86 +705,12 @@ fn upload(context: &Rc, frame: &I420, surface: &Surface, coded: (u32, u }) } -/// Paint an NV12 surface black (Y=16, chroma=128, TV-range neutral): the -/// one-time initialisation [`Encoder::vpp_into_pool`] gives its pool so a -/// region copy's untouched padding reads the same deterministic value on -/// every driver instead of whatever the fresh allocation contained. -fn fill_black(display: &Display, surface: &Surface, size: (u32, u32), bit_depth: u8) -> Result<()> { - write_surface(display, surface, fourcc(bit_depth), size, |layout, data| { - // P010 carries the sample in the top ten bits, so black is the 8-bit - // value shifted up by six, little endian. - let samples = |eight: u8| -> Vec { - if bit_depth == 8 { - vec![eight] - } else { - (u16::from(eight) << 6).to_le_bytes().to_vec() - } - }; - for (plane, value, rows) in [ - (0usize, 16u8, size.1 as usize), - (1, 128, size.1 as usize / 2), - ] { - let pitch = layout.pitches[plane] as usize; - let base = layout.offsets[plane] as usize; - let unit = samples(value); - let width = size.0 as usize * unit.len(); - for row in 0..rows { - let start = base + row * pitch; - if let Some(line) = data.get_mut(start..start + width) { - for px in line.chunks_exact_mut(unit.len()) { - px.copy_from_slice(&unit); - } - } - } - } - }) -} - fn fill_zero(display: &Display, surface: &Surface, size: (u32, u32), bit_depth: u8) -> Result<()> { write_surface(display, surface, fourcc(bit_depth), size, |_, data| { data.fill(0) }) } -fn zero_padding( - display: &Display, - surface: &ec_va::va::Surface, - bit_depth: u8, - (w, h): (u32, u32), - coded: (u32, u32), -) -> Result<()> { - if (w, h) == coded { - return Ok(()); - } - let (fourcc, px) = if bit_depth > 8 { - (VA_FOURCC_P010, 2) - } else { - (VA_FOURCC_NV12, 1) - }; - let (w, h, cw, ch) = ( - w as usize * px, - h as usize, - coded.0 as usize * px, - coded.1 as usize, - ); - write_surface(display, surface, fourcc, coded, |layout, data| { - for (plane, rows, last, start) in [ - (0, h, ch, w), - (1, h.div_ceil(2), ch / 2, w.next_multiple_of(2 * px)), - ] { - let pitch = layout.pitches[plane] as usize; - let base = layout.offsets[plane] as usize; - for row in 0..last { - let from = if row < rows { start } else { 0 }; - if let Some(dst) = data.get_mut(base + row * pitch + from..base + row * pitch + cw) - { - dst.fill(0); - } - } - } - }) -} - /// Upload one 10-bit frame into a surface as P010: samples move from the low /// ten bits of the caller's `u16` into P010's top ten. fn upload_16( @@ -989,13 +751,3 @@ fn upload_16( } }) } - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn default_profile_is_high() { - assert_eq!(H264Profile::default(), H264Profile::High); - } -} diff --git a/crates/ec-hw/src/frame.rs b/crates/ec-hw/src/frame.rs index 94f173b2..d2ba392b 100644 --- a/crates/ec-hw/src/frame.rs +++ b/crates/ec-hw/src/frame.rs @@ -72,11 +72,6 @@ impl Frame { &self.surface } - /// The display the surface was created on. - pub(crate) fn display(&self) -> &Rc { - &self.display - } - /// This frame's colour metadata, when the codec's decoder resolves one. pub fn colour(&self) -> Option { self.colour diff --git a/crates/ec-hw/src/hw.rs b/crates/ec-hw/src/hw.rs index e13e53a6..42966ef4 100644 --- a/crates/ec-hw/src/hw.rs +++ b/crates/ec-hw/src/hw.rs @@ -12,8 +12,6 @@ use std::collections::VecDeque; use crate::error::{Error, Result}; use crate::output::HwPicture; use crate::picture::{I420, I420_16, RgbPicture}; -#[cfg(target_os = "linux")] -use crate::picture::DmaBufPicture; use crate::rate::{RateFeedback, hrd_buffer_ms}; use crate::types::{ Codec, CodedFrame, EncCodec, EncoderConfig, FrameMetadata, H264Profile, RateControlMode, @@ -129,14 +127,7 @@ fn vk_grace() -> Result<()> { pub fn capabilities() -> Vec { let mut out = Vec::new(); if let Some(gpu) = vk_gpu() { - for caps in gpu.caps().into_iter().filter(|c| { - c.direction == ec_vk::Direction::Encode - || (c.direction == ec_vk::Direction::Decode - && matches!( - c.codec, - ec_vk::Codec::H264 | ec_vk::Codec::H265 | ec_vk::Codec::Av1 | ec_vk::Codec::Vp9 - )) - }) { + for caps in gpu.caps() { let codec = match caps.codec { ec_vk::Codec::H264 => Codec::H264, ec_vk::Codec::H265 => Codec::H265, @@ -1207,17 +1198,6 @@ impl HwDecoder { HwDecoder::open_with(codec, Some(output)) } - /// Same as [`HwDecoder::open`]: every picture can be asked for 10-bit I420 with [`HwPicture::to_i420_16`]. - pub fn open_16(codec: Codec) -> Result { - HwDecoder::open(codec) - } - - /// Same as [`HwDecoder::open`]: every picture can be asked for DMA-BUF file descriptors with [`HwPicture::export_dmabuf`]. Linux only. - #[cfg(target_os = "linux")] - pub fn open_dmabuf(codec: Codec) -> Result { - HwDecoder::open(codec) - } - fn open_with(codec: Codec, rgb: Option) -> Result { let mut reasons = Vec::new(); let born_epoch = crate::reset::gpu_reset_epoch(); @@ -1310,23 +1290,6 @@ impl HwDecoder { } } - /// The next picture in display order, as 10-bit I420 with its timestamp. - pub fn next_frame_16(&mut self) -> Result> { - match self.pull()? { - None => Ok(None), - Some(picture) => Ok(Some((picture.timestamp, picture.to_i420_16()?))), - } - } - - /// The next picture in display order, as DMA-BUF file descriptors with its timestamp. Linux only. - #[cfg(target_os = "linux")] - pub fn next_dmabuf(&mut self) -> Result> { - match self.pull()? { - None => Ok(None), - Some(picture) => Ok(Some((picture.timestamp, picture.export_dmabuf()?))), - } - } - /// The next picture in display order, as packed RGB with its timestamp. An error on a decoder not opened with [`HwDecoder::open_rgb`]. pub fn next_rgb(&mut self) -> Result> { let mut dst = RgbPicture::default(); diff --git a/crates/ec-hw/tests/common/mod.rs b/crates/ec-hw/tests/common/mod.rs new file mode 100644 index 00000000..75cad5f3 --- /dev/null +++ b/crates/ec-hw/tests/common/mod.rs @@ -0,0 +1,13 @@ +use std::rc::Rc; + +use ec_va::Display; + +pub fn display() -> Option> { + match ec_va::open() { + Ok(display) => Some(display), + Err(e) => { + eprintln!("skipped: no VA display ({e})"); + None + } + } +} diff --git a/crates/ec-hw/tests/film_grain.rs b/crates/ec-hw/tests/film_grain.rs index 9621042c..89f7713a 100644 --- a/crates/ec-hw/tests/film_grain.rs +++ b/crates/ec-hw/tests/film_grain.rs @@ -14,18 +14,12 @@ use std::rc::Rc; use ec_hw::{Codec, Decoder, I420}; use ec_va::Display; +mod common; +use common::display; + /// Frames in the grain fixture (every one of them is shown). const FRAMES: usize = 90; -fn display() -> Option> { - match ec_va::open() { - Ok(display) => Some(display), - Err(e) => { - eprintln!("skipped: no VA display ({e})"); - None - } - } -} /// Split an IVF container into its frames (temporal units). fn split_ivf(data: &[u8]) -> Vec<&[u8]> { diff --git a/crates/ec-hw/tests/gpu.rs b/crates/ec-hw/tests/gpu.rs index 63ae3da1..f1605654 100644 --- a/crates/ec-hw/tests/gpu.rs +++ b/crates/ec-hw/tests/gpu.rs @@ -8,29 +8,22 @@ use std::io::Read; use std::path::{Path, PathBuf}; -use std::process::{Command, Stdio}; +use std::process::Stdio; use std::rc::Rc; -use std::time::Instant; use ec_hw::{ - Codec, Decoder, EncCodec, Encoder, EncoderConfig, Frame, FrameMetadata, H264Profile, I420, + Codec, Decoder, EncCodec, Encoder, EncoderConfig, Frame, FrameMetadata, I420, I420_16, RateControlMode, }; use ec_va::Display; +mod common; +use common::display; + /// Frames compared per fixture: enough to cover several GOPs and any /// reordering, few enough to keep the suite under a minute. const FRAMES: usize = 24; -fn display() -> Option> { - match ec_va::open() { - Ok(display) => Some(display), - Err(e) => { - eprintln!("skipped: no VA display ({e})"); - None - } - } -} /// The software reference: ffmpeg decoding the same file to raw planes. struct Reference { @@ -378,25 +371,6 @@ fn ten_bit(pattern: &str, codec: &str) -> Vec { .collect() } -/// The selection must not depend on where the repository is checked out. -#[test] -fn fixture_selection_ignores_the_checkout_path() { - for p in eight_bit("ivf", "av1") { - let name = name_of(&p); - assert!( - name.starts_with("av1") && !name.contains("10bit"), - "{name} is not an 8-bit AV1 fixture" - ); - } - for p in ten_bit("ivf", "vp9") { - let name = name_of(&p); - assert!( - name.starts_with("vp9") && name.contains("10bit"), - "{name} is not a 10-bit VP9 fixture" - ); - } -} - #[test] fn h264_matches_ffmpeg() { compare_against_ffmpeg(&ec_testkit::fixtures("bitstreams", "264"), Codec::H264, false); @@ -430,68 +404,11 @@ fn hevc_10bit_decodes_to_p010() { compare_against_ffmpeg(&files, Codec::H265, true); } -#[test] -fn vp9_matches_ffmpeg() { - compare_against_ffmpeg(&eight_bit("ivf", "vp9"), Codec::Vp9, false); -} - -#[test] -fn vp9_10bit_matches_ffmpeg() { - compare_against_ffmpeg(&ten_bit("ivf", "vp9"), Codec::Vp9, true); -} - #[test] fn av1_matches_ffmpeg() { compare_against_ffmpeg(&eight_bit("ivf", "av1"), Codec::Av1, false); } -#[test] -fn av1_10bit_matches_ffmpeg() { - compare_against_ffmpeg(&ten_bit("ivf", "av1"), Codec::Av1, true); -} - -/// Every "not supported" this crate says has to be a fact about the driver, not -/// a string. This GPU decodes VP9 profiles 0 and 2 and AV1 profiles 0 and 2 — -/// so the 4:4:4 fixtures must come back as a typed refusal naming the profile, -/// and the capability report must agree that the profile is absent. -#[test] -fn unsupported_profiles_are_refused_with_a_reason() { - let Some(display) = display() else { return }; - let caps = ec_va::CapReport::probe(&display).expect("caps probe"); - for (file, codec, absent) in [ - ( - "vp9-profile1-444.ivf", - Codec::Vp9, - ec_va::caps::Profile::VP9Profile1, - ), - ( - "av1-profile1-444.ivf", - Codec::Av1, - ec_va::caps::Profile::AV1Profile1, - ), - ] { - let path = ec_testkit::fixture(&format!("bitstreams/{file}")); - assert!( - !caps.supports(absent, ec_va::caps::Entrypoint::VLD), - "{absent:?} is in fact supported — the refusal below would be a bug" - ); - let data = std::fs::read(&path).expect("fixture is readable"); - let mut decoder = Decoder::new(&display, codec).expect("decoder opens"); - let err = decode_stream(&mut decoder, codec, &data, 1, |_| {}) - .expect_err("a 4:4:4 stream must be refused"); - let message = err.to_string(); - assert!( - matches!(err, ec_hw::Error::Unsupported { .. }), - "{file}: expected a typed refusal, got {message}" - ); - println!("{file}: {message}"); - } -} - -// --------------------------------------------------------------------------- -// Encoding -// --------------------------------------------------------------------------- - /// A moving synthetic frame: a gradient with a box that travels, so motion /// compensation has something to find and a static-image encoder cannot cheat. fn source_frame(width: u32, height: u32, t: u32) -> I420 { @@ -629,383 +546,11 @@ fn h264_encode_round_trips_through_ffmpeg() { round_trip(EncCodec::H264, 640, 480, 30.0); } -/// Each selectable H.264 profile: the driver encodes it, ffprobe reports the -/// profile the SPS signals, and ffmpeg decodes the stream with no error output -/// and the picture matches the source. -fn h264_profile_round_trip(profile: H264Profile, ffprobe_name: &str) { - let Some(display) = display() else { return }; - let (width, height, frames) = (640u32, 480u32, 12u32); - let mut config = EncoderConfig::new(EncCodec::H264, width, height).h264_profile(profile); - config.gop_size = 30; - config.rate_control = RateControlMode::ConstantQp { qp: 26 }; - let mut encoder = Encoder::new(&display, config).expect("encoder"); - let mut stream = Vec::new(); - for t in 0..frames { - let coded = encoder - .encode( - &source_frame(width, height, t), - FrameMetadata { - timestamp: i64::from(t), - force_keyframe: false, - }, - ) - .expect("encode"); - stream.extend_from_slice(&coded.data); - } - - let dir = std::env::temp_dir().join(format!("ec-hw-h264-{profile:?}")); - std::fs::create_dir_all(&dir).expect("temp dir"); - let path = dir.join("out.264"); - std::fs::write(&path, &stream).expect("write bitstream"); - - let probe = ec_testkit::ffprobe() - .args([ - "-v", - "error", - "-select_streams", - "v:0", - "-show_entries", - "stream=profile", - "-of", - "csv=p=0", - ]) - .arg(&path) - .output() - .expect("ffprobe runs"); - let got = String::from_utf8_lossy(&probe.stdout).trim().to_string(); - assert_eq!( - got, ffprobe_name, - "{profile:?}: ffprobe reads the SPS profile" - ); - - // Strict decode: any warning or error on stderr fails the test. - let decode = ec_testkit::ffmpeg() - .args(["-nostdin", "-v", "warning", "-i"]) - .arg(&path) - .args(["-f", "null", "-"]) - .output() - .expect("ffmpeg runs"); - assert!( - decode.status.success() && decode.stderr.is_empty(), - "{profile:?}: ffmpeg reports {}", - String::from_utf8_lossy(&decode.stderr) - ); - - let mut reference = Reference::open(&path, width, height, false).expect("ffmpeg runs"); - let mut worst = f64::INFINITY; - for t in 0..frames { - let got = reference.next(width, height).expect("decoded picture"); - worst = worst.min(psnr( - &got, - &Planes::from_8bit(&source_frame(width, height, t)), - )); - } - println!("{profile:?}: {} bytes, worst {worst:.1} dB", stream.len()); - assert!(worst >= 30.0, "{profile:?}: worst frame {worst:.1} dB"); -} - -#[test] -fn h264_constrained_baseline_encodes_and_decodes() { - h264_profile_round_trip(H264Profile::ConstrainedBaseline, "Constrained Baseline"); -} - -#[test] -fn h264_main_profile_has_no_high_syntax_and_decodes() { - h264_profile_round_trip(H264Profile::Main, "Main"); -} - -#[test] -fn h264_high_profile_still_decodes() { - h264_profile_round_trip(H264Profile::High, "High"); -} - #[test] fn hevc_encode_round_trips_through_ffmpeg() { round_trip(EncCodec::H265, 640, 480, 30.0); } -/// 1916x1080 is the shape that broke the incumbent HEVC encoder: the coded size -/// is 1920x1088, and only the conformance window brings it back. -#[test] -fn hevc_encode_honours_the_conformance_window() { - round_trip(EncCodec::H265, 1916, 1080, 30.0); -} - -/// What this crate encodes, its own hardware decoder must decode. -#[test] -fn our_encoder_and_our_decoder_agree() { - let Some(display) = display() else { return }; - for (enc, dec) in [(EncCodec::H264, Codec::H264), (EncCodec::H265, Codec::H265)] { - let stream = encode_stream(&display, enc, 640, 480, 12).expect("encode"); - let mut decoder = Decoder::new(&display, dec).expect("decoder opens"); - let mut worst = f64::INFINITY; - let mut count = 0u32; - decode_stream(&mut decoder, dec, &stream, 12, |frame| { - let got = Planes::from_8bit(&frame.to_i420().expect("readback")); - let want = Planes::from_8bit(&source_frame(640, 480, count)); - worst = worst.min(psnr(&got, &want)); - count += 1; - }) - .expect("decode"); - assert_eq!(count, 12, "{enc:?}: decoded {count} of 12 frames"); - println!("{enc:?} -> our decoder: {count} frames, worst {worst:.1} dB vs source"); - assert!(worst >= 30.0, "{enc:?}: worst {worst:.1} dB"); - } -} - -/// A decoded surface goes straight into an encoder with no `to_i420` -/// read-back, and what comes out is not measurably different from the -/// CPU-path baseline (decode -> `to_i420` -> `encode`) of the same frames. -/// -/// 1920x1080 is the size on purpose: H.264's 16-block and HEVC's 32-block -/// rounding both land on the same 1920x1088 coded size for it, so the -/// decoder's surfaces satisfy `encode_frame`'s coded-size check against -/// either target codec without a second fixture. -#[test] -fn encode_frame_zero_copy_matches_the_cpu_path() { - let Some(display) = display() else { return }; - let (width, height) = (1920u32, 1080u32); - let path = ec_testkit::fixture("bitstreams/h264-1080p-23.976-8bit.264"); - let data = std::fs::read(&path).expect("fixture is readable"); - let frames = 10usize; - - for (target, dec_codec) in [(EncCodec::H264, Codec::H264), (EncCodec::H265, Codec::H265)] { - let mut cfg = EncoderConfig::new(target, width, height); - cfg.gop_size = 30; - cfg.rate_control = RateControlMode::ConstantQp { qp: 22 }; - let mut zero_copy = Encoder::new(&display, cfg).expect("zero-copy encoder opens"); - let mut cpu_path = Encoder::new(&display, cfg).expect("cpu-path encoder opens"); - let mut zc_stream = Vec::new(); - let mut cpu_stream = Vec::new(); - let mut count = 0i64; - - let mut decoder = Decoder::new(&display, Codec::H264).expect("decoder opens"); - decode_stream(&mut decoder, Codec::H264, &data, frames, |frame| { - let meta = FrameMetadata { - timestamp: count, - force_keyframe: false, - }; - // The zero-copy path never reads the surface back to the CPU: the - // only `to_i420` call in this loop is the CPU-path baseline's. - let zc = zero_copy - .encode_frame(&frame, meta) - .expect("encode_frame (zero copy)"); - zc_stream.extend_from_slice(&zc.data); - let i420 = frame.to_i420().expect("readback for the CPU-path baseline"); - let cpu = cpu_path.encode(&i420, meta).expect("encode (CPU path)"); - cpu_stream.extend_from_slice(&cpu.data); - count += 1; - }) - .expect("decode"); - assert_eq!( - count as usize, frames, - "{target:?}: decoded {count} of {frames}" - ); - - let ext = match target { - EncCodec::H264 => "264", - EncCodec::H265 => "265", - EncCodec::Av1 => unreachable!("AV1 is not in this test's target list"), - }; - let dir = std::env::temp_dir().join("ec-hw-encode-frame-zero-copy"); - std::fs::create_dir_all(&dir).expect("temp dir"); - for (name, bytes) in [("zc", &zc_stream), ("cpu", &cpu_stream)] { - std::fs::write(dir.join(format!("{name}.{ext}")), bytes).expect("write bitstream"); - } - - let mut zc_decoder = Decoder::new(&display, dec_codec).expect("zc decoder opens"); - let mut cpu_decoder = Decoder::new(&display, dec_codec).expect("cpu decoder opens"); - let mut zc_frames = Vec::new(); - let mut cpu_frames = Vec::new(); - decode_stream(&mut zc_decoder, dec_codec, &zc_stream, frames, |f| { - zc_frames.push(Planes::from_8bit(&f.to_i420().expect("readback"))) - }) - .expect("decode zero-copy stream"); - decode_stream(&mut cpu_decoder, dec_codec, &cpu_stream, frames, |f| { - cpu_frames.push(Planes::from_8bit(&f.to_i420().expect("readback"))) - }) - .expect("decode CPU-path stream"); - assert_eq!( - zc_frames.len(), - frames, - "{target:?}: zero-copy stream frame count" - ); - assert_eq!( - cpu_frames.len(), - frames, - "{target:?}: CPU-path stream frame count" - ); - - let worst = zc_frames - .iter() - .zip(&cpu_frames) - .map(|(a, b)| psnr(a, b)) - .fold(f64::INFINITY, f64::min); - println!("{target:?} encode_frame vs CPU path: worst {worst:.1} dB"); - assert!( - worst >= 35.0, - "{target:?}: worst {worst:.1} dB vs the CPU path" - ); - } -} - -/// `EncoderConfig::colour` reaches the VUI of both codecs' packed SPS: an -/// export with a colour description survives ffprobe reading it back, and -/// leaving it unset keeps today's behaviour (no `video_signal_type`, -/// deterministically — two encodes of the same picture with no colour set -/// come back byte for byte identical). -#[test] -fn colour_description_reaches_the_vui() { - let Some(display) = display() else { return }; - let (width, height) = (640u32, 480u32); - let dir = std::env::temp_dir().join("ec-hw-colour-vui"); - std::fs::create_dir_all(&dir).expect("temp dir"); - - let encode_one = |colour: Option<(u8, u8, u8, bool)>, name: &str| -> (PathBuf, Vec) { - let mut cfg = EncoderConfig::new(EncCodec::H265, width, height); - cfg.rate_control = RateControlMode::ConstantQp { qp: 26 }; - if let Some((primaries, transfer, matrix, full_range)) = colour { - cfg = cfg.colour(primaries, transfer, matrix, full_range); - } - let mut enc = Encoder::new(&display, cfg).expect("encoder opens"); - let coded = enc - .encode( - &source_frame(width, height, 0), - FrameMetadata { - timestamp: 0, - force_keyframe: true, - }, - ) - .expect("encode"); - let path = dir.join(name); - std::fs::write(&path, &coded.data).expect("write bitstream"); - (path, coded.data) - }; - let probe = |path: &Path| -> String { - let out = ec_testkit::ffprobe() - .args([ - "-v", - "error", - "-select_streams", - "v:0", - "-show_entries", - "stream=color_primaries,color_transfer,color_space", - "-of", - "csv=p=0", - ]) - .arg(path) - .output() - .expect("ffprobe runs"); - String::from_utf8_lossy(&out.stdout).trim().to_string() - }; - - // Pinned default case: no colour set, twice, must match exactly. - let (default_path, default_bytes) = encode_one(None, "default-a.265"); - let (_, default_bytes2) = encode_one(None, "default-b.265"); - assert_eq!( - default_bytes, default_bytes2, - "no colour set: two encodes of the same picture must be byte-identical" - ); - let default_probe = probe(&default_path); - println!("no colour set: ffprobe sees `{default_probe}`"); - assert!( - !default_probe.contains("bt2020"), - "no colour set should not read back as BT.2020: `{default_probe}`" - ); - - // BT.2020 / PQ / BT.2020 non-constant luminance (H.273 9/16/9). - let (bt2020_path, _) = encode_one(Some((9, 16, 9, false)), "bt2020.265"); - // ffprobe's csv reorders these as color_space,color_transfer,color_primaries - // regardless of the -show_entries order given above. - let got = probe(&bt2020_path); - assert_eq!( - got, "bt2020nc,smpte2084,bt2020", - "ffprobe on the BT.2020 stream" - ); -} - -/// AV1 hardware encode, proved by two independent decoders. -/// -/// The reconstruction inside the GPU is not observable from here, so what is -/// asserted is that the coded stream means the same thing to two decoders that -/// share no code: ffmpeg's libdav1d and this family's own `ec-av1`. Every -/// shown frame is compared sample for sample — a header field that disagrees -/// with what the hardware coded shows up as a mismatch in one of them long -/// before it shows up as a quality number. -/// -/// The path was refused in-tree until 2026-09-07: a probe on 2026-08-14 took -/// the GPU down ("the CS has cancelled because the context is lost"). That -/// refusal is retired by measurement, not by opinion — ffmpeg's own -/// `av1_vaapi` encodes on this driver (mesa 26.1.8, gfx1200), and the -/// parameters below are the recipe it uses. -#[test] -fn av1_encode_agrees_between_two_decoders() { - let Some(display) = display() else { return }; - let dir = std::env::temp_dir().join("ec-hw-av1-encode"); - let _ = std::fs::create_dir_all(&dir); - for (width, height, frames) in [(640u32, 384u32, 10u32), (1920, 1080, 10)] { - let data = match encode_stream(&display, EncCodec::Av1, width, height, frames) { - Ok(data) => data, - Err(e) => { - eprintln!("skipped: AV1 encode unavailable ({e})"); - return; - } - }; - let path = dir.join(format!("hw-{width}x{height}.obu")); - std::fs::write(&path, &data).expect("write the coded stream"); - - // Decoder one: this family's software AV1 decoder, on the raw OBUs. - let ours = ec_av1::stream::decode_stream(&data) - .unwrap_or_else(|e| panic!("ec-av1 decodes the {width}x{height} hardware stream: {e}")); - assert_eq!( - ours.len(), - frames as usize, - "{width}x{height}: ec-av1 decoded {} of {frames} shown frames", - ours.len() - ); - - // Decoder two: ffmpeg (libdav1d) on the same bytes. - let mut reference = - Reference::open(&path, width, height, false).expect("ffmpeg opens the stream"); - let mut worst = f64::INFINITY; - for (i, picture) in ours.iter().enumerate() { - let theirs = reference - .next(width, height) - .unwrap_or_else(|| panic!("{width}x{height}: ffmpeg has no frame {i}")); - let mine = Planes { - y: picture.y.clone(), - u: picture.u.clone(), - v: picture.v.clone(), - peak: 255.0, - }; - let db = psnr(&mine, &theirs); - assert!( - db.is_infinite(), - "{width}x{height} frame {i}: the two decoders disagree ({db:.2} dB)" - ); - // Agreement alone would also be satisfied by ten grey frames: the - // coded picture has to be the picture that was submitted. - let source = Planes::from_8bit(&source_frame(width, height, i as u32)); - let fidelity = psnr(&mine, &source); - assert!( - fidelity > 30.0, - "{width}x{height} frame {i}: coded {fidelity:.2} dB from the source" - ); - worst = worst.min(fidelity); - } - println!( - "AV1 encode {width}x{height}: {frames} frames, {} bytes, ec-av1 and libdav1d agree \ - sample for sample, worst frame {worst:.2} dB from the source", - data.len() - ); - } -} - -// --------------------------------------------------------------------------- -// 10-bit hardware AV1: his whole AV1 library is yuv420p10le, so an 8-bit-only -// encoder does not serve his files. -// --------------------------------------------------------------------------- - /// stream is neither flat nor 8-bit content dressed up as 10. fn source_frame_16(width: u32, height: u32, t: u32) -> I420_16 { let (w, h) = (width as usize, height as usize); @@ -1175,107 +720,6 @@ fn hevc_main10_encode_round_trips() { ); } -/// 10-bit AV1 hardware encode, proved by two decoders and by two readings of -/// the stream's bit depth. -/// -/// The bit depth is not taken on trust: ffprobe (libdav1d) must call the -/// stream `yuv420p10le`, which is it reading the `high_bitdepth` bit this -/// crate packs into the sequence header, and `ec-av1`'s own decode must -/// produce samples above 255 — an 8-bit stream dressed as 10 fails both. -#[test] -fn av1_10bit_encode_agrees_between_two_decoders() { - let Some(display) = display() else { return }; - let dir = std::env::temp_dir().join("ec-hw-av1-10bit"); - let _ = std::fs::create_dir_all(&dir); - let frames = 10u32; - let (label, _, planes) = ten_bit_source(&dir, frames); - let (width, height) = (planes[0].width, planes[0].height); - let data = match encode_stream_16( - &display, - EncCodec::Av1, - &planes, - 90, - RateControlMode::ConstantQp { qp: 90 }, - ) { - Ok(data) => data, - Err(e) => { - eprintln!("skipped: 10-bit AV1 encode unavailable ({e})"); - return; - } - }; - let path = dir.join("hw-10bit.obu"); - std::fs::write(&path, &data).expect("write the coded stream"); - - assert_eq!( - ffprobe_pix_fmt(&path, "obu").as_deref(), - Some("yuv420p10le"), - "the coded stream's sequence header does not say 10-bit" - ); - - let ten_bit_h264 = EncoderConfig::new(EncCodec::H264, width, height).ten_bit(); - assert!(Encoder::new(&display, ten_bit_h264).is_err()); - let mut config = EncoderConfig::new(EncCodec::Av1, width, height).ten_bit(); - config.rate_control = RateControlMode::ConstantQp { qp: 90 }; - let mut ten = Encoder::new(&display, config).expect("a 10-bit AV1 encoder"); - assert!( - ten.encode(&source_frame(width, height, 0), FrameMetadata::default()) - .is_err(), - "8-bit pixels went into a 10-bit encoder" - ); - - let ours = ec_av1::stream::decode_stream(&data) - .unwrap_or_else(|e| panic!("ec-av1 decodes the 10-bit hardware stream: {e}")); - assert_eq!( - ours.len(), - planes.len(), - "ec-av1 decoded {} of {frames} frames", - ours.len() - ); - let peak = ours - .iter() - .flat_map(|p| p.y.iter()) - .copied() - .max() - .unwrap_or(0); - assert!( - peak > 255, - "every decoded luma sample fits in 8 bits (peak {peak})" - ); - - let mut reference = - Reference::open(&path, width, height, true).expect("ffmpeg opens the stream"); - let mut worst = f64::INFINITY; - for (i, picture) in ours.iter().enumerate() { - let theirs = reference - .next(width, height) - .unwrap_or_else(|| panic!("ffmpeg has no frame {i}")); - let mine = Planes { - y: picture.y.clone(), - u: picture.u.clone(), - v: picture.v.clone(), - peak: 1023.0, - }; - let db = psnr(&mine, &theirs); - assert!( - db.is_infinite(), - "frame {i}: the two decoders disagree ({db:.2} dB)" - ); - let source = Planes::from_16bit(&planes[i]); - let fidelity = psnr(&mine, &source); - assert!( - fidelity > 30.0, - "frame {i}: coded {fidelity:.2} dB from the 10-bit source" - ); - worst = worst.min(fidelity); - } - println!( - "AV1 10-bit encode {width}x{height} ({label}): {frames} frames, {} bytes, pix_fmt \ - yuv420p10le, CQP 90, decoded peak luma {peak}, ec-av1 and libdav1d agree sample for \ - sample, worst frame {worst:.2} dB from the source (10-bit domain)", - data.len() - ); -} - /// Rate control: does an asked-for bitrate come back? /// /// CQP was the only mode the AV1 path had ever measured, because the config @@ -1416,199 +860,12 @@ fn ffmpeg_psnr_at(coded: &Path, source: &Path, fps: u32) -> Option { .filter(|v| v.is_finite()) } -/// What the GPU's AV1 costs against software, on his own content. -/// -/// Four quantisers per encoder on a 1920x1080 crop of a film and of a screen -/// capture, PSNR from ffmpeg, BD-rate over the overlapping quality range -/// against librav1e speed 6 and libaom cpu-used 6. Nothing is asserted about -/// the number — a fixed-function encoder is not a search — but it is measured -/// and printed rather than assumed, and the ladder itself is asserted to be -/// monotone, which is the part a broken parameter set would break. -#[test] -fn av1_encode_bd_row_vs_software() { - let Some(display) = display() else { return }; - // A ladder compared with itself saves nothing: the check on the metric. - let same = [(100.0, 30.0), (200.0, 35.0), (400.0, 40.0)]; - assert!( - bd_rate(&same, &same).abs() < 1e-9, - "bd_rate is not self-zero" - ); - - let dir = std::env::temp_dir().join("ec-hw-av1-bd"); - let _ = std::fs::create_dir_all(&dir); - for (label, source) in real_clips() { - let y4m = dir.join(format!("{label}.y4m")); - let (width, height, frames) = (1920u32, 1080u32, 12u32); - assert!( - extract_y4m(&source, &y4m, width, height, frames), - "{label}: extraction failed" - ); - let planes = raw_frames(&y4m, width, height, frames).expect("frames of the trailer"); - - let mut ours = Vec::new(); - // Descending quantiser: every ladder here is ordered by rising rate. - for qp in [180u32, 140, 100, 60] { - let mut config = EncoderConfig::new(EncCodec::Av1, width, height); - config.framerate = (24, 1); - config.gop_size = 60; - config.rate_control = RateControlMode::ConstantQp { qp }; - let mut encoder = match Encoder::new(&display, config) { - Ok(encoder) => encoder, - Err(e) => { - eprintln!("skipped: AV1 encode unavailable ({e})"); - return; - } - }; - let mut bytes = Vec::new(); - for (i, frame) in planes.iter().enumerate() { - let coded = encoder - .encode( - frame, - FrameMetadata { - timestamp: i as i64, - force_keyframe: false, - }, - ) - .expect("hardware AV1 encode"); - bytes.extend_from_slice(&coded.data); - } - let path = dir.join(format!("{label}-hw-{qp}.obu")); - std::fs::write(&path, &bytes).expect("write"); - if let Some(db) = ffmpeg_psnr(&path, &y4m, true) { - ours.push((bytes.len() as f64 * 8.0 / f64::from(frames), db)); - } - } - let rav1e: Vec<(f64, f64)> = [180u32, 140, 100, 60] - .iter() - .filter_map(|q| { - software_point( - &dir, - &y4m, - label, - "librav1e", - &[ - "-rav1e-params", - &format!("speed=6:quantizer={q}"), - "-g", - "60", - ], - *q, - frames, - ) - }) - .collect(); - let libaom: Vec<(f64, f64)> = [56u32, 44, 32, 20] - .iter() - .filter_map(|crf| { - software_point( - &dir, - &y4m, - label, - "libaom-av1", - &[ - "-cpu-used", - "6", - "-crf", - &crf.to_string(), - "-b:v", - "0", - "-g", - "60", - ], - *crf, - frames, - ) - }) - .collect(); - - for (name, ladder) in [("hw AV1", &ours), ("librav1e", &rav1e), ("libaom", &libaom)] { - println!("{label} {name}: {ladder:?}"); - for pair in ladder.windows(2) { - assert!( - pair[1].0 > pair[0].0 && pair[1].1 > pair[0].1, - "{label} {name}: ladder is not monotone at {pair:?}" - ); - } - } - if ours.len() >= 3 && rav1e.len() >= 3 { - println!( - "BD-rate row: {label}, hw AV1 vs librav1e speed 6: {:+.1}%", - bd_rate(&rav1e, &ours) * 100.0 - ); - } - if ours.len() >= 3 && libaom.len() >= 3 { - println!( - "BD-rate row: {label}, hw AV1 vs libaom cpu-used 6: {:+.1}%", - bd_rate(&libaom, &ours) * 100.0 - ); - } - } -} - -/// One software encoder's rate/PSNR point, or `None` when that encoder is not -/// built into this ffmpeg. -fn software_point( - dir: &Path, - y4m: &Path, - label: &str, - encoder: &str, - args: &[&str], - point: u32, - frames: u32, -) -> Option<(f64, f64)> { - let out = dir.join(format!("{label}-{encoder}-{point}.ivf")); - let _ = std::fs::remove_file(&out); - let status = ec_testkit::ffmpeg() - .args(["-nostdin", "-v", "error", "-y", "-i"]) - .arg(y4m) - .args(["-c:v", encoder]) - .args(args) - .arg(&out) - .status() - .ok()?; - if !status.success() { - return None; - } - let bytes = std::fs::metadata(&out).ok()?.len() as f64; - let db = ffmpeg_psnr(&out, y4m, false)?; - Some((bytes * 8.0 / f64::from(frames), db)) -} - /// PSNR of a coded stream against the source, from ffmpeg's own filter. -fn ffmpeg_psnr(coded: &Path, source: &Path, raw_obu: bool) -> Option { - let mut cmd = ec_testkit::ffmpeg(); - cmd.args(["-nostdin", "-v", "info"]); - if raw_obu { - cmd.args(["-f", "obu"]); - } - // Both inputs are pinned to the same rate: a raw OBU stream carries no - // timing, so ffmpeg would otherwise call it 25 fps against a 24 fps - // source and the filter would compare frame i with frame i+k. - let out = cmd - .args(["-r", "24"]) - .arg("-i") - .arg(coded) - .args(["-r", "24"]) - .arg("-i") - .arg(source) - .args(["-lavfi", "psnr", "-f", "null", "-"]) - .output() - .ok()?; - let text = String::from_utf8_lossy(&out.stderr); - let field = text.split("average:").nth(1)?; - field - .split_whitespace() - .next()? - .parse::() - .ok() - .filter(|v| v.is_finite()) -} - -/// A 1920x1080 crop of `frames` pictures, as a y4m file the encoders share. -fn extract_y4m(source: &Path, out: &Path, width: u32, height: u32, frames: u32) -> bool { - let _ = std::fs::remove_file(out); - ec_testkit::ffmpeg() - .args(["-nostdin", "-v", "error", "-y", "-ss", "20", "-i"]) +/// A 1920x1080 crop of `frames` pictures, as a y4m file the encoders share. +fn extract_y4m(source: &Path, out: &Path, width: u32, height: u32, frames: u32) -> bool { + let _ = std::fs::remove_file(out); + ec_testkit::ffmpeg() + .args(["-nostdin", "-v", "error", "-y", "-ss", "20", "-i"]) .arg(source) .args([ "-frames:v", @@ -1656,1299 +913,3 @@ fn real_clips() -> Vec<(&'static str, PathBuf)> { ("sintel 720p", ec_testkit::fixture("open/sintel_trailer-720p.mp4")), ] } - -/// BD-rate of `test` against `reference`, as a fraction (negative = fewer -/// bits for the same quality), integrated piecewise-linearly in -/// `log10(bits per frame)` over the PSNR range the two ladders share. -/// -/// The cubic fit of the original method needs four well-spread points and -/// misbehaves outside them; a trapezoid over the overlap is the honest -/// version of the same integral for ladders this short. -fn bd_rate(reference: &[(f64, f64)], test: &[(f64, f64)]) -> f64 { - let low = reference[0].1.max(test[0].1); - let high = reference[reference.len() - 1].1.min(test[test.len() - 1].1); - if high <= low { - return f64::NAN; - } - // log-rate at a PSNR, linearly interpolated inside the ladder. - let at = |ladder: &[(f64, f64)], db: f64| -> f64 { - for pair in ladder.windows(2) { - let ((r0, d0), (r1, d1)) = (pair[0], pair[1]); - if db >= d0 && db <= d1 { - let t = if (d1 - d0).abs() < f64::EPSILON { - 0.0 - } else { - (db - d0) / (d1 - d0) - }; - return r0.log10() + t * (r1.log10() - r0.log10()); - } - } - if db < ladder[0].1 { - ladder[0].0.log10() - } else { - ladder[ladder.len() - 1].0.log10() - } - }; - let steps = 100; - let mut integral = 0.0; - for i in 0..steps { - let a = low + (high - low) * f64::from(i) / f64::from(steps); - let b = low + (high - low) * f64::from(i + 1) / f64::from(steps); - let da = at(test, a) - at(reference, a); - let db = at(test, b) - at(reference, b); - integral += (da + db) / 2.0 * (b - a); - } - 10f64.powf(integral / (high - low)) - 1.0 -} - -/// Hardware AV1 encode speed at the two sizes his library is in, in frames per -/// second. Real time is 24 fps; the number is printed rather than asserted, -/// since a busy GPU is not a failing encoder. -#[test] -fn av1_encode_speed() { - let Some(display) = display() else { return }; - for (width, height) in [(1920u32, 1080u32), (3840, 1608)] { - let frames = 30u32; - let start = Instant::now(); - match encode_stream(&display, EncCodec::Av1, width, height, frames) { - Ok(data) => { - let secs = start.elapsed().as_secs_f64(); - println!( - "AV1 encode {width}x{height}: {:.1} fps ({frames} frames in {secs:.2} s), {} kbit/frame", - f64::from(frames) / secs, - data.len() * 8 / frames as usize / 1000 - ); - } - Err(e) => { - eprintln!("skipped: AV1 encode unavailable ({e})"); - return; - } - } - } - // 10-bit at the size his own films are in: the depth his library is - // actually stored at, so the fps that matters for a real export. - let planes: Vec = (0..30).map(|t| source_frame_16(3840, 1608, t)).collect(); - let start = Instant::now(); - match encode_stream_16( - &display, - EncCodec::Av1, - &planes, - 90, - RateControlMode::ConstantQp { qp: 90 }, - ) { - Ok(data) => { - let secs = start.elapsed().as_secs_f64(); - println!( - "AV1 encode 3840x1608 10-bit: {:.1} fps ({} frames in {secs:.2} s), {} kbit/frame", - planes.len() as f64 / secs, - planes.len(), - data.len() * 8 / planes.len() / 1000 - ); - } - Err(e) => eprintln!("skipped: 10-bit AV1 encode unavailable ({e})"), - } -} - -// --------------------------------------------------------------------------- -// The four incumbent defects, as tests -// --------------------------------------------------------------------------- - -/// A `frame_num` gap is normal, not corruption. -/// -/// Dropping a reference picture from the middle of a GOP is what a seek, a lost -/// packet or an encoder that skipped a picture all look like. The incumbent -/// stack treated it as an error and fell back to software for the rest of the -/// timeline; here the missing pictures are inferred (8.2.5.2) and decoding -/// carries on in hardware. -#[test] -fn h264_frame_num_gaps_are_synthesised() { - let Some(display) = display() else { return }; - let path = ec_testkit::fixture("bitstreams/h264-1080p-23.976-8bit.264"); - let data = std::fs::read(&path).expect("fixture is readable"); - let units = split_access_units(&data, Codec::H264); - assert!( - units.len() > 8, - "fixture is too short to drop a picture from" - ); - - // Drop two reference pictures from the middle of the first GOP. - let mut kept: Vec<&[u8]> = Vec::new(); - for (i, unit) in units.iter().enumerate() { - if (3..=5).contains(&i) { - continue; - } - kept.push(unit); - } - - let mut decoder = Decoder::new(&display, Codec::H264).expect("decoder opens"); - let mut frames = 0usize; - for (i, unit) in kept.iter().enumerate().take(20) { - if let Err(e) = decoder.decode(unit, i as i64) { - panic!( - "unit {i} failed after {} gap frames: {e}", - decoder.gap_frames_synthesized() - ); - } - while let Some(frame) = decoder.next_frame() { - // The frame is real: reading it back must work, not just arrive. - let planes = frame.to_i420().expect("readback"); - assert_eq!(planes.y.len(), 1920 * 1080); - frames += 1; - } - } - decoder.flush().expect("flush"); - while decoder.next_frame().is_some() { - frames += 1; - } - let synthesised = decoder.gap_frames_synthesized(); - println!("frame_num gap: {frames} frames decoded, {synthesised} pictures inferred"); - assert!(synthesised > 0, "the gap was not detected"); - assert!(frames >= 10, "only {frames} frames survived the gap"); -} - -/// VmRSS in kilobytes, from `/proc/self/status`. -fn rss_kb() -> u64 { - let status = std::fs::read_to_string("/proc/self/status").unwrap_or_default(); - status - .lines() - .find_map(|line| line.strip_prefix("VmRSS:")) - .and_then(|v| v.split_whitespace().next().map(|n| n.to_string())) - .and_then(|n| n.parse().ok()) - .unwrap_or(0) -} - -/// Decode and read back for longer than any export, and watch the resident set. -/// -/// The incumbent leaked ~3 MB per frame by mapping a VA image and never -/// unmapping it: a 719-frame export lost 2 GB. Every mapping here is a guard -/// that unmaps on drop, and this is the test that says so out loud. -#[test] -fn long_decode_does_not_grow_the_resident_set() { - // VmRSS is a process-wide number and the harness runs every test in this - // binary as a thread of one process: a sibling allocating between the - // baseline and the end reading shows up here as a 200 MB "leak". The - // measurement therefore runs in a child process holding only this test. - if std::env::var_os("EC_HW_RSS_CHILD").is_none() { - let status = Command::new(std::env::current_exe().expect("test binary path")) - .args(["--exact", "long_decode_does_not_grow_the_resident_set"]) - .env("EC_HW_RSS_CHILD", "1") - .status() - .expect("re-run this test in its own process"); - assert!(status.success(), "isolated RSS run failed"); - return; - } - let Some(display) = display() else { return }; - let path = ec_testkit::fixture("bitstreams/h264-1080p-23.976-8bit.264"); - let data = std::fs::read(&path).expect("fixture is readable"); - let units = split_access_units(&data, Codec::H264); - let mut decoder = Decoder::new(&display, Codec::H264).expect("decoder opens"); - - // Warm up first: the first pictures allocate the surface pool and the - // readback image, and that growth is not a leak. - let mut decoded = 0usize; - let mut baseline = 0u64; - let mut readback_ms = 0f64; - let mut pending: Vec = Vec::new(); - let target = 719usize; - 'outer: for pass in 0..16 { - if pass > 0 { - decoder.reset(); - } - for (i, unit) in units.iter().enumerate() { - decoder.decode(unit, i as i64).expect("decode"); - while let Some(frame) = decoder.next_frame() { - // Hold a few frames before reading any back: a decoder that is - // read one frame per submission spends its time waiting for the - // GPU, which measures latency rather than throughput. - pending.push(frame); - if pending.len() < 4 { - continue; - } - let start = std::time::Instant::now(); - for frame in pending.drain(..) { - let planes = frame.to_i420().expect("readback"); - std::hint::black_box(&planes); - decoded += 1; - } - readback_ms += start.elapsed().as_secs_f64() * 1000.0; - if decoded == 60 { - baseline = rss_kb(); - } - if decoded >= target { - break 'outer; - } - } - } - } - decoder.flush().expect("flush"); - let end = rss_kb(); - let delta_mb = (end.saturating_sub(baseline)) as f64 / 1024.0; - println!( - "{decoded} frames decoded and read back: RSS {baseline} -> {end} kB (delta {delta_mb:.1} MB), \ - decode and read back {:.2} ms/frame at 1920x1080", - readback_ms / decoded as f64 - ); - assert!(decoded >= target, "only {decoded} frames decoded"); - assert!( - delta_mb < 50.0, - "resident set grew {delta_mb:.1} MB over {decoded} frames" - ); -} - -/// The zero-copy path: a decoded surface exports as DRM PRIME file descriptors. -/// -/// This is what edith's `engine-hw` imports into gbm, so the fds and the plane -/// layout matter as much as the pixels do. -#[test] -fn frames_export_as_dma_buf() { - let Some(display) = display() else { return }; - let path = ec_testkit::fixture("bitstreams/h264-1080p-23.976-8bit.264"); - let data = std::fs::read(&path).expect("fixture is readable"); - let mut decoder = Decoder::new(&display, Codec::H264).expect("decoder opens"); - let mut exported = 0usize; - decode_stream(&mut decoder, Codec::H264, &data, 2, |frame| { - let prime = frame.export_prime().expect("export"); - assert_eq!(prime.fourcc, ec_va::va::VA_FOURCC_NV12); - assert_eq!((prime.width, prime.height), frame.coded_size); - assert!(!prime.objects.is_empty(), "no DRM objects exported"); - assert!(!prime.layers.is_empty(), "no layers exported"); - let planes: usize = prime.layers.iter().map(|l| l.planes.len()).sum(); - assert!( - planes >= 2, - "NV12 needs a luma and a chroma plane, got {planes}" - ); - exported += 1; - }) - .expect("decode"); - assert!(exported >= 1, "nothing was exported"); - println!("DRM PRIME export: {exported} frames"); -} - -// --------------------------------------------------------------------------- -// His library -// --------------------------------------------------------------------------- - -/// Turn any container into an elementary stream ffmpeg and this crate agree on. -/// -/// `frames` bounds the extraction: piping a two-hour 4K film through memory to -/// compare its first five hundred pictures is several gigabytes of nothing. -fn elementary(path: &Path, codec: Codec, frames: usize) -> Option> { - let args: &[&str] = match codec { - Codec::H264 => &["-bsf:v", "h264_mp4toannexb", "-f", "h264"], - Codec::H265 => &["-bsf:v", "hevc_mp4toannexb", "-f", "hevc"], - Codec::Vp9 | Codec::Av1 => &["-f", "ivf"], - }; - let out = ec_testkit::ffmpeg() - .args(["-nostdin", "-v", "error", "-i"]) - .arg(path) - .args(["-map", "0:v:0", "-c:v", "copy"]) - // A few more coded pictures than frames wanted: reordering means the - // last few packets have not been shown yet. - .args(["-frames:v", &(frames + 16).to_string()]) - .args(args) - .arg("-") - .stderr(Stdio::null()) - .output() - .ok()?; - (!out.stdout.is_empty()).then_some(out.stdout) -} - -#[test] -fn real_library_spot_check() { - let Some(display) = display() else { return }; - let wanted: Vec<(PathBuf, Codec, bool)> = [ - ("open/sintel_trailer-480p.mp4", Codec::H264, false), - ("open/sintel_trailer-1080p.mp4", Codec::H264, false), - ("derived/sintel720-x265-main10.mp4", Codec::H265, true), - ] - .into_iter() - .map(|(rel, codec, ten_bit)| (ec_testkit::fixture(rel), codec, ten_bit)) - .collect(); - - // 500 frames per file by default; a diagnostic run can ask for fewer. - let limit: usize = std::env::var("EC_HW_SWEEP_FRAMES") - .ok() - .and_then(|v| v.parse().ok()) - .unwrap_or(500); - let mut table = Vec::new(); - for (path, codec, ten_bit) in &wanted { - let path = Path::new(path); - let data = elementary(path, *codec, limit).expect("elementary stream"); - let mut decoder = Decoder::new(&display, *codec).expect("decoder opens"); - let mut reference: Option = None; - let mut worst = f64::INFINITY; - let mut compared = 0usize; - let mut failed: Option = None; - let result = decode_stream(&mut decoder, *codec, &data, limit, |frame| { - let (w, h) = frame.display_size; - let reference = reference - .get_or_insert_with(|| Reference::open(path, w, h, *ten_bit).expect("ffmpeg runs")); - let Some(want) = reference.next(w, h) else { - return; - }; - let got = if *ten_bit { - Planes::from_16bit(&frame.to_i420_16().expect("readback")) - } else { - Planes::from_8bit(&frame.to_i420().expect("readback")) - }; - if got.y.len() != want.y.len() { - failed = Some("frame size disagrees with ffmpeg".to_string()); - return; - } - let db = psnr(&got, &want); - if std::env::var_os("EC_HW_DEBUG").is_some() { - eprintln!(" {} frame {compared}: {db:.1} dB", short(path)); - } - worst = worst.min(db); - compared += 1; - }); - match result { - Ok(decoded) => table.push(format!( - "{:<52} {decoded:>4} frames, {compared} compared, worst {}", - short(path), - if worst.is_infinite() { - "exact".to_string() - } else { - format!("{worst:.1} dB") - } - )), - Err(e) => failed = Some(e.to_string()), - } - if let Some(reason) = failed { - table.push(format!("{:<52} FAIL {reason}", short(path))); - } - assert!(compared > 0, "{}: nothing decoded", short(path)); - assert!( - worst >= 40.0, - "{}: worst frame {worst:.1} dB against ffmpeg", - short(path) - ); - } - for row in table { - println!("{row}"); - } -} - -/// A library path without the directory tree, so a report can carry it. -fn short(path: &Path) -> String { - path.file_name() - .map(|n| n.to_string_lossy().to_string()) - .unwrap_or_default() -} - -/// PSNR of one plane, in dB (`f64::INFINITY` for an exact match). -fn plane_psnr(a: &[u16], b: &[u16], peak: f64) -> f64 { - let n = a.len().min(b.len()); - let mse: f64 = a[..n] - .iter() - .zip(&b[..n]) - .map(|(&p, &q)| { - let d = f64::from(p) - f64::from(q); - d * d - }) - .sum::() - / n as f64; - if mse == 0.0 { - f64::INFINITY - } else { - 10.0 * (peak * peak / mse).log10() - } -} - -/// -/// `real_library_spot_check` already pins the whole-frame PSNR at >= 40 dB -/// for a mix of files; this isolates Y from U/V on this specific 10-bit film, -/// against both `yuv420p10le` (the lossless comparison) and `yuv420p` (the -/// truncating `to_i420` path, which rounds ffmpeg's dithered 8-bit output -/// against this crate's un-dithered right-shift -- a real but small gap, not -/// a bug). A collapsed U/V PSNR here (a grey frame) would mean the chroma -/// plane is being read at the wrong stride/offset; it is not, on this file. -#[test] -fn ten_bit_chroma_is_not_grey() { - let Some(display) = display() else { return }; - let path = &ec_testkit::fixture("derived/sintel720-x265-main10.mp4"); - let frames = 3usize; - let data = elementary(path, Codec::H265, frames).expect("elementary stream"); - let mut decoder = Decoder::new(&display, Codec::H265).expect("decoder opens"); - let mut ref10: Option = None; - let mut ref8: Option = None; - let mut compared = 0usize; - decode_stream(&mut decoder, Codec::H265, &data, frames, |frame| { - let (w, h) = frame.display_size; - let ref10 = - ref10.get_or_insert_with(|| Reference::open(path, w, h, true).expect("ffmpeg runs")); - let want10 = ref10.next(w, h).expect("ffmpeg has a frame"); - let got16 = Planes::from_16bit(&frame.to_i420_16().expect("readback")); - let y_db = plane_psnr(&got16.y, &want10.y, 1023.0); - let uv_db = plane_psnr( - &[got16.u.as_slice(), got16.v.as_slice()].concat(), - &[want10.u.as_slice(), want10.v.as_slice()].concat(), - 1023.0, - ); - println!("frame {compared} to_i420_16 vs yuv420p10le: Y {y_db:.1} dB, UV {uv_db:.1} dB"); - assert!( - y_db >= 50.0, - "frame {compared}: Y PSNR collapsed to {y_db:.1} dB" - ); - assert!( - uv_db >= 50.0, - "frame {compared}: chroma PSNR collapsed to {uv_db:.1} dB (grey frame)" - ); - - let ref8 = - ref8.get_or_insert_with(|| Reference::open(path, w, h, false).expect("ffmpeg runs")); - let want8 = ref8.next(w, h).expect("ffmpeg has a frame"); - let got8 = Planes::from_8bit(&frame.to_i420().expect("readback")); - let y_db8 = plane_psnr(&got8.y, &want8.y, 255.0); - let uv_db8 = plane_psnr( - &[got8.u.as_slice(), got8.v.as_slice()].concat(), - &[want8.u.as_slice(), want8.v.as_slice()].concat(), - 255.0, - ); - println!("frame {compared} to_i420 vs yuv420p: Y {y_db8:.1} dB, UV {uv_db8:.1} dB"); - // ffmpeg dithers its 8-bit downconversion; this crate truncates. Both - // are legitimate 10-to-8 roundings, so the floor here is the - // dithering noise floor, not the lossless bound above. - assert!( - y_db8 >= 30.0, - "frame {compared}: 8-bit Y PSNR {y_db8:.1} dB" - ); - assert!( - uv_db8 >= 30.0, - "frame {compared}: 8-bit chroma PSNR collapsed to {uv_db8:.1} dB (grey frame)" - ); - compared += 1; - }) - .expect("decode"); - assert_eq!(compared, frames, "not all frames were compared"); -} - -/// An SDR H.264 stream, which carries no HDR SEI at all: `Frame::colour` -/// either resolves from the VUI or answers [`None`], but never panics. -#[test] -fn sdr_h264_colour_never_panics() { - let Some(display) = display() else { return }; - let paths = ec_testkit::fixtures("bitstreams", "264"); - let path = &paths[0]; - let data = std::fs::read(path).expect("fixture is readable"); - let mut decoder = Decoder::new(&display, Codec::H264).expect("decoder opens"); - let mut seen = 0usize; - decode_stream(&mut decoder, Codec::H264, &data, 2, |frame| { - seen += 1; - // No SEI parsing on this codec: content light is always absent. - if let Some(colour) = frame.colour() { - assert_eq!(colour.light.max_cll, None); - } - }) - .expect("decode"); - assert!(seen > 0, "{}: nothing decoded", short(path)); -} - -/// A CRA GOP boundary stores its RASL leading pictures *after* the CRA in -/// decode order, even though they display before it (they predict from -/// pictures the CRA's own random-access point does not have). A decoder -/// started fresh at that CRA — what a seek does — must therefore drop those -/// RASL pictures per H.265 8.1.3's `NoRaslOutputFlag`, or its output shifts by -/// however many RASL pictures the GOP has, handing back the wrong picture for -/// every display index at or after the seek target. -#[test] -fn hevc_seek_matches_linear_mkv() { - let Some(display) = display() else { return }; - let path = ec_testkit::fixture("video/hevc-open-gop.mkv"); - let data = elementary(&path, Codec::H265, 45).expect("elementary stream"); - let units = split_access_units(&data, Codec::H265); - - // Linear decode: every picture from the start, frame 30 kept for - // comparison (the file's second CRA, per `test_hevc.mkv`'s 30-picture - // GOPs). - const TARGET: usize = 30; - let mut decoder = Decoder::new(&display, Codec::H265).expect("decoder opens"); - let mut linear_frame_30 = None; - let mut index = 0usize; - decode_stream(&mut decoder, Codec::H265, &data, 45, |frame| { - if index == TARGET { - linear_frame_30 = Some(frame.to_i420().expect("readback")); - } - index += 1; - }) - .expect("linear decode"); - let linear_frame_30 = linear_frame_30.expect("linear decode reached frame 30"); - - // Find the access unit whose first VCL NAL is the CRA at this GOP - // boundary, and feed the decoder from there on, exactly as a seek would: - // nothing from before it goes in. - let cra_at = units - .iter() - .position(|au| starts_with_cra(au)) - .expect("a CRA access unit exists"); - - // A seek reuses the parameter sets a decoder already learned; a fresh one - // has none, so it is primed the same way `ec_hw::Decoder::reset` expects a - // caller to: decode the leading VPS/SPS/PPS (their IDR picture is thrown - // away) and reset picture state before feeding the seek target. - let mut seek_decoder = Decoder::new(&display, Codec::H265).expect("decoder opens"); - seek_decoder - .decode(units[0], 0) - .expect("prime parameter sets"); - seek_decoder.reset(); - let mut seeked_frame = None; - for (i, unit) in units[cra_at..].iter().enumerate() { - seek_decoder.decode(unit, i as i64).expect("seek decode"); - if let Some(frame) = seek_decoder.next_frame() { - seeked_frame = Some(frame.to_i420().expect("readback")); - break; - } - } - if seeked_frame.is_none() { - seek_decoder.flush().expect("flush"); - seeked_frame = seek_decoder - .next_frame() - .map(|f| f.to_i420().expect("readback")); - } - let seeked_frame = seeked_frame.expect("a frame came out after the seek"); - - assert_eq!( - seeked_frame, linear_frame_30, - "seeking to the CRA before frame 30 handed back a different picture \ - than a linear decode of frame 30 — RASL pictures were not dropped" - ); -} - -/// An H.264 open-GOP I picture is not an IDR: it is a plain I slice -/// (`nal_unit_type` 1) whose predecessors in decode order can still hold -/// references from before it, so leading pictures between it and the next -/// IDR may predict from a picture never decoded since a fresh start there — -/// exactly what a seek does. A decoder started at that I must drop those -/// leading pictures per D.2.8's recovery point default, or its output shifts -/// by however many leading pictures the GOP has. -#[test] -fn h264_seek_matches_linear_open_gop() { - let Some(display) = display() else { return }; - let path = ec_testkit::fixture("video/h264-open-gop.mp4"); - let data = elementary(&path, Codec::H264, 60).expect("elementary stream"); - let units = split_access_units(&data, Codec::H264); - - // Linear decode: every picture from the start, frame 30 kept for - // comparison (the fixture's second I picture, `keyint=30`). - const TARGET: usize = 30; - let mut decoder = Decoder::new(&display, Codec::H264).expect("decoder opens"); - let mut linear_frame_30 = None; - let mut index = 0usize; - decode_stream(&mut decoder, Codec::H264, &data, 60, |frame| { - if index == TARGET { - linear_frame_30 = Some(frame.to_i420().expect("readback")); - } - index += 1; - }) - .expect("linear decode"); - let linear_frame_30 = linear_frame_30.expect("linear decode reached frame 30"); - - // Find the access unit whose first VCL NAL is the open-GOP I picture at - // this GOP boundary, and feed the decoder from there on, exactly as a - // seek would: nothing from before it goes in. - let open_gop_at = units - .iter() - .position(|au| is_open_gop_i(au)) - .expect("an open-GOP I access unit exists"); - - // A seek reuses the parameter sets a decoder already learned; a fresh one - // has none, so it is primed the same way `ec_hw::Decoder::reset` expects a - // caller to: decode the leading IDR (its picture is thrown away) and - // reset picture state before feeding the seek target. - let mut seek_decoder = Decoder::new(&display, Codec::H264).expect("decoder opens"); - seek_decoder - .decode(units[0], 0) - .expect("prime parameter sets"); - seek_decoder.reset(); - let mut seeked_frame = None; - for (i, unit) in units[open_gop_at..].iter().enumerate() { - seek_decoder.decode(unit, i as i64).expect("seek decode"); - if let Some(frame) = seek_decoder.next_frame() { - seeked_frame = Some(frame.to_i420().expect("readback")); - break; - } - } - if seeked_frame.is_none() { - seek_decoder.flush().expect("flush"); - seeked_frame = seek_decoder - .next_frame() - .map(|f| f.to_i420().expect("readback")); - } - let seeked_frame = seeked_frame.expect("a frame came out after the seek"); - - assert_eq!( - seeked_frame, linear_frame_30, - "seeking to the open-GOP I before frame 30 handed back a different \ - picture than a linear decode of frame 30 — leading pictures with \ - missing references were not dropped" - ); -} - -/// True when an access unit's first VCL NAL is an H.264 open-GOP I slice -/// (`nal_unit_type` 1, `slice_type % 5 == 2`), found by scanning for the -/// access unit's first start code rather than assuming a fixed prefix length. -fn is_open_gop_i(au: &[u8]) -> bool { - let mut i = 0usize; - while i + 3 < au.len() { - if au[i] != 0 || au[i + 1] != 0 || au[i + 2] != 1 { - i += 1; - continue; - } - let header = au[i + 3]; - if header & 0x1f != 1 { - return false; - } - let mut r = ec_core::BitReader::new(&au[i + 4..]); - if r.read_ue().is_err() { - return false; - } - return matches!(r.read_ue(), Ok(code) if code % 5 == 2); - } - false -} - -/// True when an access unit's first VCL NAL is an HEVC CRA (`nal_type` 21). -/// A CRA's access unit may open with its own VPS/SPS/PPS, so this skips past -/// non-VCL NALs to the first one that carries a slice. -fn starts_with_cra(au: &[u8]) -> bool { - let mut i = 0usize; - while i + 3 < au.len() { - if au[i] == 0 && au[i + 1] == 0 && au[i + 2] == 1 { - let t = (au[i + 3] >> 1) & 0x3f; - if t <= 31 { - return t == 21; - } - i += 3; - continue; - } - i += 1; - } - false -} - -/// `ffmpeg -bsf:v trace_headers` over a bitstream, returning every -/// `name = value` line it prints — the slice header fields the driver wrote. -fn trace_headers(path: &Path, codec: &str) -> Vec<(String, i64)> { - let out = ec_testkit::ffmpeg() - .args(["-v", "trace", "-hide_banner", "-nostats", "-f", codec, "-i"]) - .arg(path) - .args(["-c:v", "copy", "-bsf:v", "trace_headers", "-f", "null", "-"]) - .output() - .expect("ffmpeg runs"); - let text = String::from_utf8_lossy(&out.stderr); - text.lines() - .filter_map(|line| { - // "[trace_headers @ 0x...] 16 frame_num 0000 = 0" - let (lhs, value) = line.rsplit_once(" = ")?; - let mut words = lhs.split_whitespace().rev(); - let _bits = words.next()?; - let name = words.next()?; - Some((name.to_string(), value.trim().parse().ok()?)) - }) - .collect() -} - -/// Phone-class stateful decoders order output from `frame_num` and the POC -/// fields, so a stream whose every slice says 0/0 judders there even though -/// desktop decoders (which re-derive from decode order) play it cleanly. -/// Encode a long P-run and read the fields back the way such a decoder does. -fn slice_counters( - codec: EncCodec, - width: u32, - height: u32, - frames: u32, -) -> (PathBuf, Vec<(String, i64)>) { - let Some(display) = display() else { - return (PathBuf::new(), Vec::new()); - }; - let mut config = EncoderConfig::new(codec, width, height); - config.gop_size = frames * 2; - config.framerate = (30, 1); - config.rate_control = RateControlMode::ConstantQp { qp: 30 }; - let mut encoder = Encoder::new(&display, config).expect("encoder"); - let mut out = Vec::new(); - for t in 0..frames { - let coded = encoder - .encode( - &source_frame(width, height, t), - FrameMetadata { - timestamp: i64::from(t), - force_keyframe: false, - }, - ) - .expect("encode"); - assert_eq!(coded.is_keyframe, t == 0, "one IDR then P-frames at {t}"); - out.extend_from_slice(&coded.data); - } - let dir = std::env::temp_dir().join(format!("ec-hw-counters-{codec:?}")); - std::fs::create_dir_all(&dir).expect("temp dir"); - let (name, fmt) = match codec { - EncCodec::H264 => ("out.264", "h264"), - EncCodec::H265 => ("out.265", "hevc"), - EncCodec::Av1 => unreachable!(), - }; - let path = dir.join(name); - std::fs::write(&path, &out).expect("write"); - let fields = trace_headers(&path, fmt); - (path, fields) -} - -fn values(fields: &[(String, i64)], name: &str) -> Vec { - fields - .iter() - .filter(|(n, _)| n == name) - .map(|(_, v)| *v) - .collect() -} - -#[test] -fn h264_slice_headers_count_frames_for_stateful_decoders() { - let frames = 64u32; - let (path, fields) = slice_counters(EncCodec::H264, 640, 360, frames); - if fields.is_empty() { - return; - } - let frame_num = values(&fields, "frame_num"); - assert_eq!( - frame_num.len(), - frames as usize, - "one slice per picture in {}", - path.display() - ); - let log2_max = values(&fields, "log2_max_frame_num_minus4")[0] + 4; - let max_frame_num = 1i64 << log2_max; - let expected: Vec = (0..frames as i64).map(|n| n % max_frame_num).collect(); - assert_eq!( - frame_num, expected, - "frame_num steps +1 mod {max_frame_num}" - ); - // pic_order_cnt_type 2: POC = 2 * FrameNumOffset-adjusted frame_num, no lsb is - // written — the decoder's output order is the decode order by construction. - let poc_type = values(&fields, "pic_order_cnt_type"); - assert!( - !poc_type.is_empty() && poc_type.iter().all(|&t| t == 2), - "POC type 2 in the SPS: {poc_type:?}" - ); - assert!( - values(&fields, "pic_order_cnt_lsb").is_empty(), - "no POC lsb under type 2" - ); - assert!( - values(&fields, "level_idc").iter().all(|&l| l == 30), - "640x360@30 is level 3.0" - ); -} - -#[test] -fn hevc_slice_headers_count_pocs_for_stateful_decoders() { - let frames = 64u32; - let (path, fields) = slice_counters(EncCodec::H265, 640, 360, frames); - if fields.is_empty() { - return; - } - let lsb = values(&fields, "slice_pic_order_cnt_lsb"); - assert_eq!( - lsb.len(), - frames as usize - 1, - "every non-IDR slice carries a POC lsb in {}", - path.display() - ); - let log2_max = values(&fields, "log2_max_pic_order_cnt_lsb_minus4")[0] + 4; - let max_lsb = 1i64 << log2_max; - let expected: Vec = (1..frames as i64).map(|n| n % max_lsb).collect(); - assert_eq!(lsb, expected, "POC lsb steps +1 mod {max_lsb}"); -} - -// --------------------------------------------------------------------------- -// Rate control: achieved bitrate against the request, and PSNR at that rate -// --------------------------------------------------------------------------- - -/// Write 8-bit 4:2:0 frames as a y4m file, the reference ffmpeg compares with. -fn write_y4m_8(path: &Path, frames: &[I420], fps: u32) -> bool { - use std::io::Write; - let Some(first) = frames.first() else { - return false; - }; - let Ok(file) = std::fs::File::create(path) else { - return false; - }; - let mut out = std::io::BufWriter::new(file); - let header = format!( - "YUV4MPEG2 W{} H{} F{fps}:1 Ip A1:1 C420jpeg\n", - first.width, first.height - ); - if out.write_all(header.as_bytes()).is_err() { - return false; - } - for f in frames { - if out.write_all(b"FRAME\n").is_err() - || out.write_all(&f.y).is_err() - || out.write_all(&f.u).is_err() - || out.write_all(&f.v).is_err() - { - return false; - } - } - out.flush().is_ok() -} - -/// Average PSNR (dB) of a raw elementary stream against its source y4m. -fn psnr_of_elementary(coded: &Path, format: &str, source: &Path, fps: u32) -> Option { - let rate = fps.to_string(); - let out = ec_testkit::ffmpeg() - .args(["-nostdin", "-v", "info", "-f", format, "-r", &rate, "-i"]) - .arg(coded) - .args(["-r", &rate, "-i"]) - .arg(source) - .args(["-lavfi", "psnr", "-f", "null", "-"]) - .output() - .ok()?; - let text = String::from_utf8_lossy(&out.stderr); - let field = text.split("average:").nth(1)?; - field - .split_whitespace() - .next()? - .parse::() - .ok() - .filter(|v| v.is_finite()) -} - -/// One CBR encode of `frames` at `bitrate`: the stream, and the bits per second -/// it actually spent over the clip. -fn cbr_encode( - display: &Rc, - codec: EncCodec, - (width, height, fps): (u32, u32, u32), - bitrate: u32, - frames: &[I420], -) -> Result<(Vec, f64), ec_hw::Error> { - let mut config = EncoderConfig::new(codec, width, height); - config.framerate = (fps, 1); - config.gop_size = 30; - config.bitrate = bitrate; - config.rate_control = RateControlMode::ConstantBitrate; - let mut encoder = Encoder::new(display, config)?; - let mut out = Vec::new(); - for (t, frame) in frames.iter().enumerate() { - let coded = encoder.encode( - frame, - FrameMetadata { - timestamp: t as i64, - force_keyframe: false, - }, - )?; - out.extend_from_slice(&coded.data); - } - let delivered = out.len() as f64 * 8.0 * f64::from(fps) / frames.len() as f64; - Ok((out, delivered)) -} - -/// CBR must land within +/-5% of the request on every codec, clip and rate, -/// and the PSNR it reaches at that rate is printed for the report. -#[test] -fn cbr_lands_within_five_percent_of_the_request() { - let Some(display) = display() else { return }; - // 8 s: a 2 s clip also carries the start-up of the rate controller, which - // is measured apart from the steady-state rate the request is about. - let (width, height, fps, frames) = (1280u32, 720u32, 30u32, 240u32); - let dir = std::env::temp_dir().join("ec-hw-rc-measure"); - std::fs::create_dir_all(&dir).expect("temp dir"); - - // Two clips: a synthetic moving box, and ffmpeg's testsrc2 (the content the - // edith measurements used), both generated here so nothing depends on a - // personal library. - let synthetic: Vec = (0..frames) - .map(|t| source_frame(width, height, t)) - .collect(); - let synthetic_y4m = dir.join("cbr-synthetic.y4m"); - assert!(write_y4m_8(&synthetic_y4m, &synthetic, fps), "write source"); - let testsrc_y4m = dir.join("cbr-testsrc2.y4m"); - let generated = ec_testkit::ffmpeg() - .args(["-nostdin", "-v", "error", "-y", "-f", "lavfi", "-i"]) - .arg(format!("testsrc2=size={width}x{height}:rate={fps}")) - .args(["-frames:v", &frames.to_string(), "-pix_fmt", "yuv420p"]) - .arg(&testsrc_y4m) - .status() - .is_ok_and(|s| s.success()); - let testsrc = generated - .then(|| raw_frames(&testsrc_y4m, width, height, frames)) - .flatten() - .expect("ffmpeg generates testsrc2"); - let clips: [(&str, Vec, PathBuf); 2] = [ - ("moving box", synthetic, synthetic_y4m), - ("testsrc2", testsrc, testsrc_y4m), - ]; - let mut failures = Vec::new(); - println!("CBR, {width}x{height} {fps} fps, {frames} frames:"); - for (codec, name, format) in [ - (EncCodec::H264, "H.264", "h264"), - (EncCodec::H265, "HEVC", "hevc"), - (EncCodec::Av1, "AV1", "obu"), - ] { - for (clip_name, pictures, source) in &clips { - for target in [1_000_000u32, 3_000_000, 8_000_000] { - let (stream, delivered) = - match cbr_encode(&display, codec, (width, height, fps), target, pictures) { - Ok(encoded) => encoded, - Err(e) => panic!("{name} {clip_name} at {target} bps: encode failed ({e})"), - }; - let coded = dir.join(format!( - "{name}-{}-{target}.{format}", - clip_name.replace(' ', "-") - )); - std::fs::write(&coded, &stream).expect("write stream"); - let db = psnr_of_elementary(&coded, format, source, fps).unwrap_or(f64::NAN); - let error = delivered / f64::from(target) - 1.0; - println!( - " {name:<6} {clip_name:<12} target {:>5} kbps -> {:>6.0} kbps ({:+5.1}%), {db:.2} dB", - target / 1000, - delivered / 1000.0, - error * 100.0 - ); - if error.abs() > 0.05 { - failures.push(format!( - "{name} {clip_name} at {target} bps: {:+.1}%", - error * 100.0 - )); - } - } - } - } - assert!(failures.is_empty(), "outside +/-5%: {failures:?}"); -} - -fn imported_nv12( - display: &Rc, - frame: &I420, -) -> Rc> { - use ec_va::SurfaceExt; - - let (w, h) = (frame.width, frame.height); - let mut pool = - ec_va::create_pool(display, &ec_va::SurfaceSpec::nv12(w, h), 1).expect("surface"); - let surface = pool.pop().expect("one surface"); - { - let format = - ec_va::surface::image_format(display, ec_va::va::VA_FOURCC_NV12).expect("format"); - let mut image = - ec_va::surface::create_image(&surface, format, (w, h), (w, h)).expect("image"); - let layout = *image.image(); - let data = AsMut::<[u8]>::as_mut(&mut image); - let (wu, hu) = (w as usize, h as usize); - let (cw, ch) = (wu.div_ceil(2), hu.div_ceil(2)); - for row in 0..hu { - let d = layout.offsets[0] as usize + row * layout.pitches[0] as usize; - data[d..d + wu].copy_from_slice(&frame.y[row * wu..row * wu + wu]); - } - for row in 0..ch { - let d = layout.offsets[1] as usize + row * layout.pitches[1] as usize; - for col in 0..cw { - data[d + col * 2] = frame.u[row * cw + col]; - data[d + col * 2 + 1] = frame.v[row * cw + col]; - } - } - } - let prime = surface.export().expect("export"); - let objects: Vec = prime - .objects - .iter() - .map(|o| ec_va::RawPrimeObject { - fd: std::os::fd::AsRawFd::as_raw_fd(&o.fd), - size: o.size, - modifier: o.modifier, - }) - .collect(); - let imported = ec_va::import_prime_raw( - display, - prime.fourcc, - (prime.width, prime.height), - &objects, - &prime.layers, - ) - .expect("import"); - drop(prime); - Rc::new(imported) -} - -/// Encoding an imported DMA-BUF must give the bytes the CPU path gives for the -/// same pixels: the import is only a different way of handing over the source. -#[test] -fn encode_surface_of_an_imported_dma_buf_matches_the_cpu_path() { - let Some(display) = display() else { return }; - let (w, h) = (640u32, 480u32); - for codec in [EncCodec::H264, EncCodec::H265] { - let mut config = EncoderConfig::new(codec, w, h); - config.gop_size = 3; - config.rate_control = RateControlMode::ConstantQp { qp: 30 }; - let mut cpu = Encoder::new(&display, config).expect("cpu encoder"); - let mut dma = Encoder::new(&display, config).expect("dma encoder"); - for t in 0..4u32 { - let frame = source_frame(w, h, t); - let meta = FrameMetadata { - timestamp: i64::from(t), - force_keyframe: false, - }; - let want = cpu.encode(&frame, meta).expect("cpu encode"); - let surface = imported_nv12(&display, &frame); - let got = dma - .encode_surface(&surface, (w, h), meta) - .expect("encode_surface"); - assert_eq!(got.is_keyframe, want.is_keyframe, "{codec:?} frame {t}"); - assert_eq!( - got.data.len(), - want.data.len(), - "{codec:?} frame {t}: imported source coded to a different size" - ); - assert!(got.data == want.data, "{codec:?} frame {t}: bytes differ"); - } - } -} - -// --------------------------------------------------------------------------- -// Broken streams: an inter picture whose references were never decoded -// --------------------------------------------------------------------------- - -/// The OBUs of an AV1 temporal unit, as whole byte slices (each with its header). -fn av1_obus(tu: &[u8]) -> Vec<&[u8]> { - let mut out = Vec::new(); - let mut i = 0usize; - while i < tu.len() { - let header = tu[i]; - let ext = usize::from((header >> 2) & 1); - if (header >> 1) & 1 == 0 { - break; // no obu_size: the rest of the unit is one OBU - } - let mut size = 0usize; - let mut pos = i + 1 + ext; - for shift in (0..64).step_by(7) { - let Some(&byte) = tu.get(pos) else { return out }; - pos += 1; - size |= usize::from(byte & 0x7f) << shift; - if byte & 0x80 == 0 { - break; - } - } - let end = (pos + size).min(tu.len()); - out.push(&tu[i..end]); - i = end; - } - out -} - -/// The Annex B NAL units of an access unit, without their start codes. -fn annexb_nals(au: &[u8]) -> Vec<&[u8]> { - let mut starts = Vec::new(); - let mut i = 0usize; - while i + 3 <= au.len() { - if au[i] == 0 && au[i + 1] == 0 && au[i + 2] == 1 { - starts.push(i + 3); - i += 3; - } else { - i += 1; - } - } - starts - .iter() - .enumerate() - .map(|(n, &start)| { - let end = starts.get(n + 1).map_or(au.len(), |&next| next - 3); - let mut nal = &au[start..end]; - while let [rest @ .., 0] = nal { - nal = rest; // trailing zeros belong to the next start code - } - nal - }) - .collect() -} - -/// A stream that starts at an inter picture: the parameter sets of the first -/// access unit, then the access unit that follows it, with the picture that -/// would have filled its references (the first access unit) left out. -fn broken_gop(codec: Codec, data: &[u8]) -> Option> { - let mut stream = Vec::new(); - match codec { - Codec::Av1 => { - let units = split_ivf(data); - // The sequence header OBU, which the first temporal unit carries. - let seq = av1_obus(units.first()?) - .into_iter() - .find(|obu| (obu[0] >> 3) & 0xf == 1)?; - stream.extend_from_slice(seq); - stream.extend_from_slice(units.get(1)?); - } - Codec::Vp9 => { - // VP9 carries its parameters in the frame header: the inter frame - // alone is the broken stream. - stream.extend_from_slice(split_ivf(data).get(1)?); - } - Codec::H264 | Codec::H265 => { - let units = split_access_units(data, codec); - let is_parameter_set = |nal: &[u8]| { - let t = match codec { - Codec::H264 => nal[0] & 0x1f, - _ => (nal[0] >> 1) & 0x3f, - }; - match codec { - Codec::H264 => t == 7 || t == 8, - _ => (32..=34).contains(&t), - } - }; - for nal in annexb_nals(units.first()?) { - if is_parameter_set(nal) { - stream.extend_from_slice(&[0, 0, 0, 1]); - stream.extend_from_slice(nal); - } - } - stream.extend_from_slice(units.get(1)?); - } - } - Some(stream) -} - -/// Each codec's broken GOP is refused with an error at the first access unit -/// that needs the missing picture, and never produces a picture. Refusing an -/// inter frame whose references were never filled is what the software -/// decoders do (ec-av1: "no saved CDF state"). -#[test] -fn a_broken_gop_is_refused_on_every_codec() { - let Some(display) = display() else { return }; - let cases = [ - (Codec::Av1, "av1-1080p-23.976-8bit.ivf"), - (Codec::Vp9, "vp9-1080p-23.976-8bit.ivf"), - (Codec::H264, "h264-bframes-320.264"), - (Codec::H265, "hevc-bframes-320.265"), - ]; - for (codec, name) in cases { - let path = ec_testkit::fixture(&format!("bitstreams/{name}")); - let data = std::fs::read(&path).expect("fixture is readable"); - let stream = broken_gop(codec, &data).expect("the fixture has a second access unit"); - let mut decoder = Decoder::new(&display, codec).expect("decoder"); - let refusal = decoder.decode(&stream, 0).err().map(|e| e.to_string()); - let mut pictures = 0usize; - while decoder.next_frame().is_some() { - pictures += 1; - } - assert!( - refusal.is_some(), - "{codec:?} {name}: the broken GOP decoded without an error ({pictures} pictures)" - ); - assert_eq!( - pictures, 0, - "{codec:?} {name}: a picture came out of a broken GOP" - ); - println!("{codec:?} {name}: refused: {}", refusal.unwrap_or_default()); - } -} - -#[test] -fn ten_bit_prime_submit_matches_the_cpu_path() { - let file = ec_testkit::fixture("derived/sintel720-x265-main10.mp4"); - let Some(display) = display() else { return }; - let data = elementary(&file, Codec::H265, 1).expect("elementary stream"); - let mut decoder = Decoder::new(&display, Codec::H265).expect("decoder opens"); - let mut size = (0, 0); - decode_stream(&mut decoder, Codec::H265, &data, 1, |f| { - size = f.display_size - }) - .expect("decode"); - let mut cfg = EncoderConfig::new(EncCodec::H265, size.0, size.1).ten_bit(); - cfg.rate_control = RateControlMode::ConstantQp { qp: 22 }; - let mut zc = Encoder::new(&display, cfg).expect("encoder"); - let mut cpu = Encoder::new(&display, cfg).expect("encoder"); - let (mut a, mut b) = (Vec::new(), Vec::new()); - let mut t = 0; - let mut decoder = Decoder::new(&display, Codec::H265).expect("decoder opens"); - decode_stream(&mut decoder, Codec::H265, &data, 8, |frame| { - let meta = FrameMetadata { - timestamp: t, - force_keyframe: false, - }; - t += 1; - let prime = frame.export_prime().expect("export"); - let imported = Rc::new(ec_va::import_prime(&display, &prime).expect("import")); - if let Some(c) = zc.submit_prime(imported, meta).expect("submit_prime") { - a.extend(c.data); - } - if let Some(c) = cpu - .submit_16(&frame.to_i420_16().expect("readback"), meta) - .expect("submit_16") - { - b.extend(c.data); - } - }) - .expect("decode"); - a.extend(zc.flush().expect("flush").into_iter().flat_map(|c| c.data)); - b.extend(cpu.flush().expect("flush").into_iter().flat_map(|c| c.data)); - assert!(!a.is_empty()); - assert!( - a == b, - "zero-copy and CPU 10-bit streams differ ({} vs {} bytes)", - a.len(), - b.len() - ); -} - -#[test] -fn h264_encode_decodes_with_no_reorder_delay() { - let Some(display) = display() else { return }; - let mut config = EncoderConfig::new(EncCodec::H264, 1280, 720); - config.framerate = (30, 1); - config.gop_size = 30; - config.rate_control = RateControlMode::ConstantQp { qp: 30 }; - let mut encoder = Encoder::new(&display, config).expect("encoder"); - let mut decoder = Decoder::new(&display, Codec::H264).expect("decoder"); - for t in 0..10 { - let meta = FrameMetadata { - timestamp: i64::from(t), - force_keyframe: false, - }; - let unit = encoder - .encode(&source_frame(1280, 720, t), meta) - .expect("encode"); - decoder.decode(&unit.data, i64::from(t)).expect("decode"); - assert!(decoder.next_frame().is_some(), "frame {t} held back"); - } -} - -#[test] -fn imported_dma_buf_scales_and_crops_through_vpp() { - let Some(display) = display() else { return }; - let mean = |y: &[u8]| y.iter().map(|&v| f64::from(v)).sum::() / y.len() as f64; - let meta = FrameMetadata { - timestamp: 0, - force_keyframe: false, - }; - for (source_w, source_h, scale) in [(1280, 720, true), (640, 360, false)] { - let source = source_frame(source_w, source_h, 0); - let mut config = EncoderConfig::new(EncCodec::H264, 640, 360); - config.rate_control = RateControlMode::ConstantQp { qp: 22 }; - let mut encoder = Encoder::new(&display, config).expect("encoder"); - let surface = imported_nv12(&display, &source); - let data = if scale { - let mut data = Vec::new(); - if let Some(c) = encoder.submit_prime(surface, meta).expect("submit_prime") { - data.extend(c.data); - } - data.extend( - encoder - .flush() - .expect("flush") - .into_iter() - .flat_map(|c| c.data), - ); - data - } else { - encoder - .encode_surface(&surface, (640, 360), meta) - .expect("encode_surface") - .data - }; - let mut decoder = Decoder::new(&display, Codec::H264).expect("decoder"); - decoder.decode(&data, 0).expect("decode"); - decoder.flush().expect("flush"); - let frame = decoder.next_frame().expect("a picture"); - assert_eq!(frame.display_size, (640, 360)); - let got = frame.to_i420().expect("readback"); - assert!((mean(&got.y) - mean(&source.y)).abs() < 3.0); - } -} diff --git a/crates/ec-hw/tests/idr_counting.rs b/crates/ec-hw/tests/idr_counting.rs index 1f36bd41..adaf6770 100644 --- a/crates/ec-hw/tests/idr_counting.rs +++ b/crates/ec-hw/tests/idr_counting.rs @@ -10,24 +10,16 @@ use std::path::{Path, PathBuf}; use std::process::Stdio; -use std::rc::Rc; use ec_hw::{EncCodec, Encoder, EncoderConfig, FrameMetadata, I420, RateControlMode}; -use ec_va::Display; + +mod common; +use common::display; const WIDTH: u32 = 384; const HEIGHT: u32 = 256; const FPS: u32 = 30; -fn display() -> Option> { - match ec_va::open() { - Ok(display) => Some(display), - Err(e) => { - eprintln!("skipped: no VA display ({e})"); - None - } - } -} fn scratch(name: &str) -> PathBuf { let dir = std::env::temp_dir().join(format!("ec-hw-idr-{name}")); diff --git a/crates/ec-vk/examples/av1_encode.rs b/crates/ec-vk/examples/av1_encode.rs deleted file mode 100644 index 7f8da7b6..00000000 --- a/crates/ec-vk/examples/av1_encode.rs +++ /dev/null @@ -1,77 +0,0 @@ -use ec_vk::{Av1Encoder, Av1EncoderConfig, Gpu, RateControl}; - -const W: u32 = 1280; -const H: u32 = 720; -const FPS: u32 = 30; -const FRAMES: u32 = 60; - -fn frame(n: u32) -> (Vec, Vec, Vec) { - let y = (0..H) - .flat_map(|row| (0..W).map(move |col| ((col + row + 4 * n) % 256) as u8)) - .collect(); - let u = (0..H / 2) - .flat_map(|_| (0..W / 2).map(move |col| ((col * 2 + n) % 256) as u8)) - .collect(); - let v = (0..H / 2) - .flat_map(|row| (0..W / 2).map(move |_| ((row * 2 + 2 * n) % 256) as u8)) - .collect(); - (y, u, v) -} - -fn main() { - let path = std::env::args() - .nth(1) - .expect("usage: av1_encode [cbr_bitrate]"); - let gpu = Gpu::open().expect("open Vulkan Video device"); - let cfg = Av1EncoderConfig { - width: W, - height: H, - fps: (FPS, 1), - level: 23, - gop_size: 30, - rate: match std::env::args().nth(2) { - Some(b) => RateControl::Cbr { - bitrate: b.parse().expect("bitrate"), - buffer_ms: 1000, - }, - None => RateControl::ConstantQp { qp: 26 }, - }, - bit_depth: 8, - colour: None, - quality: 0, - }; - let mut encoder = Av1Encoder::new(&gpu, cfg).expect("create encoder"); - - let mut out = Vec::new(); - out.extend_from_slice(b"DKIF"); - out.extend_from_slice(&0u16.to_le_bytes()); - out.extend_from_slice(&32u16.to_le_bytes()); - out.extend_from_slice(b"AV01"); - out.extend_from_slice(&(W as u16).to_le_bytes()); - out.extend_from_slice(&(H as u16).to_le_bytes()); - out.extend_from_slice(&FPS.to_le_bytes()); - out.extend_from_slice(&1u32.to_le_bytes()); - out.extend_from_slice(&FRAMES.to_le_bytes()); - out.extend_from_slice(&0u32.to_le_bytes()); - - let mut total = 0usize; - for n in 0..FRAMES { - let (y, u, v) = frame(n); - let coded = encoder.encode(&y, &u, &v, false).expect("encode frame"); - println!( - "frame {n}: {} bytes keyframe {}", - coded.data.len(), - coded.keyframe - ); - out.extend_from_slice(&(coded.data.len() as u32).to_le_bytes()); - out.extend_from_slice(&(n as u64).to_le_bytes()); - out.extend_from_slice(&coded.data); - total += coded.data.len(); - } - let seconds = FRAMES as f64 / FPS as f64; - println!( - "total {total} bytes, {:.1} kb/s", - total as f64 * 8.0 / seconds / 1000.0 - ); - std::fs::write(&path, out).expect("write output"); -} diff --git a/crates/ec-vk/examples/h264_encode.rs b/crates/ec-vk/examples/h264_encode.rs deleted file mode 100644 index cecff9dc..00000000 --- a/crates/ec-vk/examples/h264_encode.rs +++ /dev/null @@ -1,55 +0,0 @@ -use ec_vk::{Gpu, H264Encoder, H264EncoderConfig, H264Profile, RateControl}; - -const W: u32 = 1280; -const H: u32 = 720; -const FRAMES: u32 = 60; - -fn frame(n: u32) -> (Vec, Vec, Vec) { - let y = (0..H) - .flat_map(|row| (0..W).map(move |col| ((col + row + 4 * n) % 256) as u8)) - .collect(); - let u = (0..H / 2) - .flat_map(|_| (0..W / 2).map(move |col| ((col * 2 + n) % 256) as u8)) - .collect(); - let v = (0..H / 2) - .flat_map(|row| (0..W / 2).map(move |_| ((row * 2 + 2 * n) % 256) as u8)) - .collect(); - (y, u, v) -} - -fn main() { - let path = std::env::args() - .nth(1) - .expect("usage: h264_encode "); - let gpu = Gpu::open().expect("open Vulkan Video device"); - let cfg = H264EncoderConfig { - width: W, - height: H, - fps: (30, 1), - level: 62, - gop_size: 30, - profile: H264Profile::High, - colour: None, - quality: 0, - rate: match std::env::args().nth(2) { - Some(b) => RateControl::Cbr { - bitrate: b.parse().expect("bitrate"), - buffer_ms: 1000, - }, - None => RateControl::ConstantQp { qp: 26 }, - }, - }; - let mut encoder = H264Encoder::new(&gpu, cfg).expect("create encoder"); - let mut out = Vec::new(); - for n in 0..FRAMES { - let (y, u, v) = frame(n); - let coded = encoder.encode(&y, &u, &v, false).expect("encode frame"); - println!( - "frame {n}: {} bytes keyframe {}", - coded.data.len(), - coded.keyframe - ); - out.extend_from_slice(&coded.data); - } - std::fs::write(&path, out).expect("write output"); -} diff --git a/crates/ec-vk/examples/h265_encode.rs b/crates/ec-vk/examples/h265_encode.rs deleted file mode 100644 index fd83622f..00000000 --- a/crates/ec-vk/examples/h265_encode.rs +++ /dev/null @@ -1,55 +0,0 @@ -use ec_vk::{Gpu, H265Encoder, H265EncoderConfig, RateControl}; - -const W: u32 = 1280; -const H: u32 = 720; -const FRAMES: u32 = 60; - -fn frame(n: u32) -> (Vec, Vec, Vec) { - let y = (0..H) - .flat_map(|row| (0..W).map(move |col| ((col + row + 4 * n) % 256) as u8)) - .collect(); - let u = (0..H / 2) - .flat_map(|_| (0..W / 2).map(move |col| ((col * 2 + n) % 256) as u8)) - .collect(); - let v = (0..H / 2) - .flat_map(|row| (0..W / 2).map(move |_| ((row * 2 + 2 * n) % 256) as u8)) - .collect(); - (y, u, v) -} - -fn main() { - let path = std::env::args() - .nth(1) - .expect("usage: h265_encode [cbr_bitrate]"); - let gpu = Gpu::open().expect("open Vulkan Video device"); - let cfg = H265EncoderConfig { - width: W, - height: H, - fps: (30, 1), - level: 186, - gop_size: 30, - rate: match std::env::args().nth(2) { - Some(b) => RateControl::Cbr { - bitrate: b.parse().expect("bitrate"), - buffer_ms: 1000, - }, - None => RateControl::ConstantQp { qp: 26 }, - }, - bit_depth: 8, - colour: None, - quality: 0, - }; - let mut encoder = H265Encoder::new(&gpu, cfg).expect("create encoder"); - let mut out = Vec::new(); - for n in 0..FRAMES { - let (y, u, v) = frame(n); - let coded = encoder.encode(&y, &u, &v, false).expect("encode frame"); - println!( - "frame {n}: {} bytes keyframe {}", - coded.data.len(), - coded.keyframe - ); - out.extend_from_slice(&coded.data); - } - std::fs::write(&path, out).expect("write output"); -} diff --git a/crates/ec-vk/src/h265.rs b/crates/ec-vk/src/h265.rs index 21aeb9e2..fd42a644 100644 --- a/crates/ec-vk/src/h265.rs +++ b/crates/ec-vk/src/h265.rs @@ -244,7 +244,12 @@ impl H265Encoder { .history .next(force_keyframe || self.position >= self.gop_size); self.poc = if step.key { 0 } else { self.poc + 1 }; - let keep = self.history.kept(&step); + let reference = step.reference.map(|(slot, _)| slot as usize); + let keep = std::array::from_fn(|i| { + self.history.slots[i] + .filter(|_| i != step.slot as usize && Some(i) != reference) + .map(|h| h.data) + }); self.history.store(&step, self.poc); self.position = if step.key { 1 } else { self.position + 1 }; self.flight.push(Meta { diff --git a/crates/ec-vk/src/history.rs b/crates/ec-vk/src/history.rs index 65e13eae..343d2908 100644 --- a/crates/ec-vk/src/history.rs +++ b/crates/ec-vk/src/history.rs @@ -5,10 +5,10 @@ const ANCHOR_EVERY: u64 = 16; const MAX_AGE: u64 = 120; #[derive(Debug, Clone, Copy)] -struct Held { +pub(crate) struct Held { id: u64, acked: bool, - data: T, + pub(crate) data: T, } /// Where the next picture goes and what it references. @@ -26,7 +26,7 @@ pub(crate) struct Step { /// acknowledged them, the last two chain each picture to the previous one. pub(crate) struct History { next_id: u64, - slots: [Option>; DPB_SLOTS], + pub(crate) slots: [Option>; DPB_SLOTS], last: Option<(usize, T)>, next_anchor: usize, armed: bool, @@ -107,15 +107,6 @@ impl History { self.last = Some((slot, data)); } - pub(crate) fn kept(&self, step: &Step) -> [Option; DPB_SLOTS] { - let reference = step.reference.map(|(slot, _)| slot as usize); - std::array::from_fn(|i| { - self.slots[i] - .filter(|_| i != step.slot as usize && Some(i) != reference) - .map(|h| h.data) - }) - } - fn newest_acked(&self, id: u64) -> Option<(usize, T)> { (0..DPB_SLOTS) .filter_map(|i| self.slots[i].map(|h| (i, h)))