Merge branch 'simplify/u16' into simplify/w1b
Browse files at this commit23 changed files +213 -3678
- crates/ec-hw/abi-probe.c +0 -271
- crates/ec-hw/examples/hw_caps.rs +0 -102
- crates/ec-hw/examples/hw_config.rs +0 -144
- crates/ec-hw/examples/hw_decode.rs +8 -16
- crates/ec-hw/examples/hw_pipeline.rs +0 -165
- crates/ec-hw/examples/hw_rgb.rs +0 -148
- crates/ec-hw/examples/hw_smoke.rs +164 -0
- crates/ec-hw/examples/hw_speed.rs +0 -26
- crates/ec-hw/examples/hw_ten.rs +0 -141
- crates/ec-hw/examples/hw_tune.rs +0 -102
- crates/ec-hw/src/enc/headers.rs +0 -1
- crates/ec-hw/src/enc/mod.rs +2 -250
- crates/ec-hw/src/frame.rs +0 -5
- crates/ec-hw/src/hw.rs +1 -38
- crates/ec-hw/tests/common/mod.rs +13 -0
- crates/ec-hw/tests/film_grain.rs +3 -9
- crates/ec-hw/tests/gpu.rs +10 -2049
- crates/ec-hw/tests/idr_counting.rs +3 -11
- crates/ec-vk/examples/av1_encode.rs +0 -77
- crates/ec-vk/examples/h264_encode.rs +0 -55
- crates/ec-vk/examples/h265_encode.rs +0 -55
- crates/ec-vk/src/h265.rs +6 -1
- crates/ec-vk/src/history.rs +3 -12
crates/ec-hw/abi-probe.cdeleted+0 -271
| @@ -1,271 +0,0 @@ | ||
| 1 | -/* abi-probe.c — print the layout of every libva codec parameter struct this | |
| 2 | - * crate transcribes, compiled against the *system* headers. | |
| 3 | - * | |
| 4 | - * The numbers it prints are pasted into the `const _: () = assert!(...)` block | |
| 5 | - * at the end of each `src/params/*.rs`, so a transcription slip is a compile | |
| 6 | - * error rather than a driver reading garbage. Rerun after a libva upgrade: | |
| 7 | - * | |
| 8 | - * cc -o /tmp/abi-probe crates/ec-hw/abi-probe.c $(pkg-config --cflags libva) && /tmp/abi-probe | |
| 9 | - * | |
| 10 | - * Same contract as crates/ec-va/abi-probe.c, one level up the stack. | |
| 11 | - */ | |
| 12 | -#include <stdio.h> | |
| 13 | -#include <stddef.h> | |
| 14 | -#include <va/va.h> | |
| 15 | -#include <va/va_dec_hevc.h> | |
| 16 | -#include <va/va_dec_vp9.h> | |
| 17 | -#include <va/va_dec_av1.h> | |
| 18 | -#include <va/va_enc_h264.h> | |
| 19 | -#include <va/va_enc_hevc.h> | |
| 20 | -#include <va/va_enc_av1.h> | |
| 21 | - | |
| 22 | -#define S(t) printf("%-46s size=%-6zu align=%zu\n", #t, sizeof(t), _Alignof(t)) | |
| 23 | -#define O(t, f) printf(" %-44s %zu\n", #t "." #f, offsetof(t, f)) | |
| 24 | - | |
| 25 | -int main(void) | |
| 26 | -{ | |
| 27 | - printf("libva %d.%d.%d\n", VA_MAJOR_VERSION, VA_MINOR_VERSION, VA_MICRO_VERSION); | |
| 28 | - | |
| 29 | - S(VAPictureH264); | |
| 30 | - O(VAPictureH264, frame_idx); | |
| 31 | - O(VAPictureH264, flags); | |
| 32 | - O(VAPictureH264, TopFieldOrderCnt); | |
| 33 | - O(VAPictureH264, BottomFieldOrderCnt); | |
| 34 | - | |
| 35 | - S(VAPictureParameterBufferH264); | |
| 36 | - O(VAPictureParameterBufferH264, ReferenceFrames); | |
| 37 | - O(VAPictureParameterBufferH264, picture_width_in_mbs_minus1); | |
| 38 | - O(VAPictureParameterBufferH264, bit_depth_luma_minus8); | |
| 39 | - O(VAPictureParameterBufferH264, num_ref_frames); | |
| 40 | - O(VAPictureParameterBufferH264, seq_fields); | |
| 41 | - O(VAPictureParameterBufferH264, pic_init_qp_minus26); | |
| 42 | - O(VAPictureParameterBufferH264, pic_fields); | |
| 43 | - O(VAPictureParameterBufferH264, frame_num); | |
| 44 | - | |
| 45 | - S(VAIQMatrixBufferH264); | |
| 46 | - O(VAIQMatrixBufferH264, ScalingList8x8); | |
| 47 | - | |
| 48 | - S(VASliceParameterBufferH264); | |
| 49 | - O(VASliceParameterBufferH264, slice_data_bit_offset); | |
| 50 | - O(VASliceParameterBufferH264, slice_type); | |
| 51 | - O(VASliceParameterBufferH264, cabac_init_idc); | |
| 52 | - O(VASliceParameterBufferH264, RefPicList0); | |
| 53 | - O(VASliceParameterBufferH264, RefPicList1); | |
| 54 | - O(VASliceParameterBufferH264, luma_log2_weight_denom); | |
| 55 | - O(VASliceParameterBufferH264, luma_weight_l0); | |
| 56 | - O(VASliceParameterBufferH264, chroma_weight_l0); | |
| 57 | - O(VASliceParameterBufferH264, luma_weight_l1_flag); | |
| 58 | - O(VASliceParameterBufferH264, chroma_offset_l1); | |
| 59 | - | |
| 60 | - S(VAPictureHEVC); | |
| 61 | - O(VAPictureHEVC, pic_order_cnt); | |
| 62 | - O(VAPictureHEVC, flags); | |
| 63 | - | |
| 64 | - S(VAPictureParameterBufferHEVC); | |
| 65 | - O(VAPictureParameterBufferHEVC, ReferenceFrames); | |
| 66 | - O(VAPictureParameterBufferHEVC, pic_width_in_luma_samples); | |
| 67 | - O(VAPictureParameterBufferHEVC, pic_fields); | |
| 68 | - O(VAPictureParameterBufferHEVC, sps_max_dec_pic_buffering_minus1); | |
| 69 | - O(VAPictureParameterBufferHEVC, column_width_minus1); | |
| 70 | - O(VAPictureParameterBufferHEVC, row_height_minus1); | |
| 71 | - O(VAPictureParameterBufferHEVC, slice_parsing_fields); | |
| 72 | - O(VAPictureParameterBufferHEVC, log2_max_pic_order_cnt_lsb_minus4); | |
| 73 | - O(VAPictureParameterBufferHEVC, st_rps_bits); | |
| 74 | - | |
| 75 | - S(VASliceParameterBufferHEVC); | |
| 76 | - O(VASliceParameterBufferHEVC, slice_segment_address); | |
| 77 | - O(VASliceParameterBufferHEVC, RefPicList); | |
| 78 | - O(VASliceParameterBufferHEVC, LongSliceFlags); | |
| 79 | - O(VASliceParameterBufferHEVC, collocated_ref_idx); | |
| 80 | - O(VASliceParameterBufferHEVC, luma_log2_weight_denom); | |
| 81 | - O(VASliceParameterBufferHEVC, delta_luma_weight_l0); | |
| 82 | - O(VASliceParameterBufferHEVC, delta_luma_weight_l1); | |
| 83 | - O(VASliceParameterBufferHEVC, five_minus_max_num_merge_cand); | |
| 84 | - O(VASliceParameterBufferHEVC, num_entry_point_offsets); | |
| 85 | - O(VASliceParameterBufferHEVC, slice_data_num_emu_prevn_bytes); | |
| 86 | - | |
| 87 | - S(VAIQMatrixBufferHEVC); | |
| 88 | - O(VAIQMatrixBufferHEVC, ScalingList32x32); | |
| 89 | - O(VAIQMatrixBufferHEVC, ScalingListDC16x16); | |
| 90 | - | |
| 91 | - S(VADecPictureParameterBufferVP9); | |
| 92 | - O(VADecPictureParameterBufferVP9, reference_frames); | |
| 93 | - O(VADecPictureParameterBufferVP9, pic_fields); | |
| 94 | - O(VADecPictureParameterBufferVP9, filter_level); | |
| 95 | - O(VADecPictureParameterBufferVP9, first_partition_size); | |
| 96 | - O(VADecPictureParameterBufferVP9, mb_segment_tree_probs); | |
| 97 | - O(VADecPictureParameterBufferVP9, profile); | |
| 98 | - | |
| 99 | - S(VASegmentParameterVP9); | |
| 100 | - O(VASegmentParameterVP9, filter_level); | |
| 101 | - O(VASegmentParameterVP9, luma_ac_quant_scale); | |
| 102 | - | |
| 103 | - S(VASliceParameterBufferVP9); | |
| 104 | - O(VASliceParameterBufferVP9, seg_param); | |
| 105 | - | |
| 106 | - S(VASegmentationStructAV1); | |
| 107 | - O(VASegmentationStructAV1, feature_data); | |
| 108 | - O(VASegmentationStructAV1, feature_mask); | |
| 109 | - S(VAFilmGrainStructAV1); | |
| 110 | - O(VAFilmGrainStructAV1, grain_seed); | |
| 111 | - O(VAFilmGrainStructAV1, ar_coeffs_y); | |
| 112 | - O(VAFilmGrainStructAV1, cr_offset); | |
| 113 | - S(VAWarpedMotionParamsAV1); | |
| 114 | - O(VAWarpedMotionParamsAV1, wmmat); | |
| 115 | - O(VAWarpedMotionParamsAV1, invalid); | |
| 116 | - | |
| 117 | - S(VADecPictureParameterBufferAV1); | |
| 118 | - O(VADecPictureParameterBufferAV1, seq_info_fields); | |
| 119 | - O(VADecPictureParameterBufferAV1, current_frame); | |
| 120 | - O(VADecPictureParameterBufferAV1, anchor_frames_num); | |
| 121 | - O(VADecPictureParameterBufferAV1, anchor_frames_list); | |
| 122 | - O(VADecPictureParameterBufferAV1, frame_width_minus1); | |
| 123 | - O(VADecPictureParameterBufferAV1, ref_frame_map); | |
| 124 | - O(VADecPictureParameterBufferAV1, ref_frame_idx); | |
| 125 | - O(VADecPictureParameterBufferAV1, seg_info); | |
| 126 | - O(VADecPictureParameterBufferAV1, film_grain_info); | |
| 127 | - O(VADecPictureParameterBufferAV1, tile_cols); | |
| 128 | - O(VADecPictureParameterBufferAV1, width_in_sbs_minus_1); | |
| 129 | - O(VADecPictureParameterBufferAV1, height_in_sbs_minus_1); | |
| 130 | - O(VADecPictureParameterBufferAV1, tile_count_minus_1); | |
| 131 | - O(VADecPictureParameterBufferAV1, pic_info_fields); | |
| 132 | - O(VADecPictureParameterBufferAV1, superres_scale_denominator); | |
| 133 | - O(VADecPictureParameterBufferAV1, loop_filter_info_fields); | |
| 134 | - O(VADecPictureParameterBufferAV1, ref_deltas); | |
| 135 | - O(VADecPictureParameterBufferAV1, base_qindex); | |
| 136 | - O(VADecPictureParameterBufferAV1, qmatrix_fields); | |
| 137 | - O(VADecPictureParameterBufferAV1, mode_control_fields); | |
| 138 | - O(VADecPictureParameterBufferAV1, cdef_damping_minus_3); | |
| 139 | - O(VADecPictureParameterBufferAV1, cdef_y_strengths); | |
| 140 | - O(VADecPictureParameterBufferAV1, loop_restoration_fields); | |
| 141 | - O(VADecPictureParameterBufferAV1, wm); | |
| 142 | - | |
| 143 | - S(VASliceParameterBufferAV1); | |
| 144 | - O(VASliceParameterBufferAV1, tile_row); | |
| 145 | - O(VASliceParameterBufferAV1, anchor_frame_idx); | |
| 146 | - O(VASliceParameterBufferAV1, tile_idx_in_tile_list); | |
| 147 | - | |
| 148 | - S(VAEncSequenceParameterBufferH264); | |
| 149 | - O(VAEncSequenceParameterBufferH264, intra_period); | |
| 150 | - O(VAEncSequenceParameterBufferH264, picture_width_in_mbs); | |
| 151 | - O(VAEncSequenceParameterBufferH264, seq_fields); | |
| 152 | - O(VAEncSequenceParameterBufferH264, bit_depth_luma_minus8); | |
| 153 | - O(VAEncSequenceParameterBufferH264, offset_for_non_ref_pic); | |
| 154 | - O(VAEncSequenceParameterBufferH264, offset_for_ref_frame); | |
| 155 | - O(VAEncSequenceParameterBufferH264, frame_cropping_flag); | |
| 156 | - O(VAEncSequenceParameterBufferH264, frame_crop_left_offset); | |
| 157 | - O(VAEncSequenceParameterBufferH264, vui_parameters_present_flag); | |
| 158 | - O(VAEncSequenceParameterBufferH264, vui_fields); | |
| 159 | - O(VAEncSequenceParameterBufferH264, aspect_ratio_idc); | |
| 160 | - O(VAEncSequenceParameterBufferH264, num_units_in_tick); | |
| 161 | - O(VAEncSequenceParameterBufferH264, time_scale); | |
| 162 | - | |
| 163 | - S(VAEncPictureParameterBufferH264); | |
| 164 | - O(VAEncPictureParameterBufferH264, ReferenceFrames); | |
| 165 | - O(VAEncPictureParameterBufferH264, coded_buf); | |
| 166 | - O(VAEncPictureParameterBufferH264, pic_parameter_set_id); | |
| 167 | - O(VAEncPictureParameterBufferH264, frame_num); | |
| 168 | - O(VAEncPictureParameterBufferH264, pic_init_qp); | |
| 169 | - O(VAEncPictureParameterBufferH264, pic_fields); | |
| 170 | - | |
| 171 | - S(VAEncSliceParameterBufferH264); | |
| 172 | - O(VAEncSliceParameterBufferH264, macroblock_info); | |
| 173 | - O(VAEncSliceParameterBufferH264, slice_type); | |
| 174 | - O(VAEncSliceParameterBufferH264, idr_pic_id); | |
| 175 | - O(VAEncSliceParameterBufferH264, delta_pic_order_cnt_bottom); | |
| 176 | - O(VAEncSliceParameterBufferH264, direct_spatial_mv_pred_flag); | |
| 177 | - O(VAEncSliceParameterBufferH264, RefPicList0); | |
| 178 | - O(VAEncSliceParameterBufferH264, RefPicList1); | |
| 179 | - O(VAEncSliceParameterBufferH264, luma_log2_weight_denom); | |
| 180 | - O(VAEncSliceParameterBufferH264, cabac_init_idc); | |
| 181 | - | |
| 182 | - S(VAEncSequenceParameterBufferHEVC); | |
| 183 | - O(VAEncSequenceParameterBufferHEVC, intra_period); | |
| 184 | - O(VAEncSequenceParameterBufferHEVC, pic_width_in_luma_samples); | |
| 185 | - O(VAEncSequenceParameterBufferHEVC, seq_fields); | |
| 186 | - O(VAEncSequenceParameterBufferHEVC, log2_min_luma_coding_block_size_minus3); | |
| 187 | - O(VAEncSequenceParameterBufferHEVC, pcm_sample_bit_depth_luma_minus1); | |
| 188 | - O(VAEncSequenceParameterBufferHEVC, vui_parameters_present_flag); | |
| 189 | - O(VAEncSequenceParameterBufferHEVC, vui_fields); | |
| 190 | - O(VAEncSequenceParameterBufferHEVC, aspect_ratio_idc); | |
| 191 | - O(VAEncSequenceParameterBufferHEVC, vui_num_units_in_tick); | |
| 192 | - O(VAEncSequenceParameterBufferHEVC, min_spatial_segmentation_idc); | |
| 193 | - O(VAEncSequenceParameterBufferHEVC, scc_fields); | |
| 194 | - | |
| 195 | - S(VAEncPictureParameterBufferHEVC); | |
| 196 | - O(VAEncPictureParameterBufferHEVC, reference_frames); | |
| 197 | - O(VAEncPictureParameterBufferHEVC, coded_buf); | |
| 198 | - O(VAEncPictureParameterBufferHEVC, collocated_ref_pic_index); | |
| 199 | - O(VAEncPictureParameterBufferHEVC, column_width_minus1); | |
| 200 | - O(VAEncPictureParameterBufferHEVC, row_height_minus1); | |
| 201 | - O(VAEncPictureParameterBufferHEVC, log2_parallel_merge_level_minus2); | |
| 202 | - O(VAEncPictureParameterBufferHEVC, nal_unit_type); | |
| 203 | - O(VAEncPictureParameterBufferHEVC, pic_fields); | |
| 204 | - O(VAEncPictureParameterBufferHEVC, hierarchical_level_plus1); | |
| 205 | - O(VAEncPictureParameterBufferHEVC, scc_fields); | |
| 206 | - | |
| 207 | - S(VAEncSliceParameterBufferHEVC); | |
| 208 | - O(VAEncSliceParameterBufferHEVC, num_ctu_in_slice); | |
| 209 | - O(VAEncSliceParameterBufferHEVC, slice_type); | |
| 210 | - O(VAEncSliceParameterBufferHEVC, ref_pic_list0); | |
| 211 | - O(VAEncSliceParameterBufferHEVC, ref_pic_list1); | |
| 212 | - O(VAEncSliceParameterBufferHEVC, luma_log2_weight_denom); | |
| 213 | - O(VAEncSliceParameterBufferHEVC, max_num_merge_cand); | |
| 214 | - O(VAEncSliceParameterBufferHEVC, slice_fields); | |
| 215 | - O(VAEncSliceParameterBufferHEVC, pred_weight_table_bit_offset); | |
| 216 | - | |
| 217 | - S(VAEncSequenceParameterBufferAV1); | |
| 218 | - O(VAEncSequenceParameterBufferAV1, intra_period); | |
| 219 | - O(VAEncSequenceParameterBufferAV1, seq_fields); | |
| 220 | - O(VAEncSequenceParameterBufferAV1, order_hint_bits_minus_1); | |
| 221 | - S(VAEncSegParamAV1); | |
| 222 | - O(VAEncSegParamAV1, feature_data); | |
| 223 | - O(VAEncSegParamAV1, feature_mask); | |
| 224 | - S(VAEncWarpedMotionParamsAV1); | |
| 225 | - S(VAEncPictureParameterBufferAV1); | |
| 226 | - O(VAEncPictureParameterBufferAV1, reconstructed_frame); | |
| 227 | - O(VAEncPictureParameterBufferAV1, coded_buf); | |
| 228 | - O(VAEncPictureParameterBufferAV1, reference_frames); | |
| 229 | - O(VAEncPictureParameterBufferAV1, ref_frame_idx); | |
| 230 | - O(VAEncPictureParameterBufferAV1, ref_frame_ctrl_l0); | |
| 231 | - O(VAEncPictureParameterBufferAV1, picture_flags); | |
| 232 | - O(VAEncPictureParameterBufferAV1, seg_id_block_size); | |
| 233 | - O(VAEncPictureParameterBufferAV1, filter_level); | |
| 234 | - O(VAEncPictureParameterBufferAV1, loop_filter_flags); | |
| 235 | - O(VAEncPictureParameterBufferAV1, ref_deltas); | |
| 236 | - O(VAEncPictureParameterBufferAV1, base_qindex); | |
| 237 | - O(VAEncPictureParameterBufferAV1, min_base_qindex); | |
| 238 | - O(VAEncPictureParameterBufferAV1, qmatrix_flags); | |
| 239 | - O(VAEncPictureParameterBufferAV1, mode_control_flags); | |
| 240 | - O(VAEncPictureParameterBufferAV1, segments); | |
| 241 | - O(VAEncPictureParameterBufferAV1, tile_cols); | |
| 242 | - O(VAEncPictureParameterBufferAV1, width_in_sbs_minus_1); | |
| 243 | - O(VAEncPictureParameterBufferAV1, context_update_tile_id); | |
| 244 | - O(VAEncPictureParameterBufferAV1, cdef_damping_minus_3); | |
| 245 | - O(VAEncPictureParameterBufferAV1, loop_restoration_flags); | |
| 246 | - O(VAEncPictureParameterBufferAV1, wm); | |
| 247 | - O(VAEncPictureParameterBufferAV1, bit_offset_qindex); | |
| 248 | - O(VAEncPictureParameterBufferAV1, tile_group_obu_hdr_info); | |
| 249 | - O(VAEncPictureParameterBufferAV1, number_skip_frames); | |
| 250 | - O(VAEncPictureParameterBufferAV1, skip_frames_reduced_size); | |
| 251 | - S(VAEncTileGroupBufferAV1); | |
| 252 | - | |
| 253 | - S(VAEncMiscParameterRateControl); | |
| 254 | - O(VAEncMiscParameterRateControl, rc_flags); | |
| 255 | - O(VAEncMiscParameterRateControl, ICQ_quality_factor); | |
| 256 | - O(VAEncMiscParameterRateControl, max_qp); | |
| 257 | - S(VAEncMiscParameterFrameRate); | |
| 258 | - O(VAEncMiscParameterFrameRate, framerate_flags); | |
| 259 | - S(VAEncMiscParameterHRD); | |
| 260 | - O(VAEncMiscParameterHRD, buffer_size); | |
| 261 | - S(VAEncMiscParameterBufferQualityLevel); | |
| 262 | - S(VAEncPackedHeaderParameterBuffer); | |
| 263 | - O(VAEncPackedHeaderParameterBuffer, bit_length); | |
| 264 | - O(VAEncPackedHeaderParameterBuffer, has_emulation_bytes); | |
| 265 | - S(VACodedBufferSegment); | |
| 266 | - O(VACodedBufferSegment, bit_offset); | |
| 267 | - O(VACodedBufferSegment, status); | |
| 268 | - O(VACodedBufferSegment, buf); | |
| 269 | - O(VACodedBufferSegment, next); | |
| 270 | - return 0; | |
| 271 | -} |
crates/ec-hw/examples/hw_caps.rsdeleted+0 -102
| @@ -1,102 +0,0 @@ | ||
| 1 | -//! Lists hardware capabilities, then encodes a gradient with each codec and decodes the Vulkan streams back. | |
| 2 | -//! | |
| 3 | -//! ```text | |
| 4 | -//! cargo run -p ec-hw --example hw_caps | |
| 5 | -//! ``` | |
| 6 | - | |
| 7 | -use ec_hw::{ | |
| 8 | - Backend, Codec, EncCodec, EncoderConfig, FrameMetadata, HwDecoder, HwEncoder, I420, | |
| 9 | - RateControlMode, capabilities, | |
| 10 | -}; | |
| 11 | - | |
| 12 | -const FRAMES: u32 = 30; | |
| 13 | -const WIDTH: u32 = 1280; | |
| 14 | -const HEIGHT: u32 = 720; | |
| 15 | - | |
| 16 | -fn main() { | |
| 17 | - for cap in capabilities() { | |
| 18 | - println!( | |
| 19 | - "{:?} {:?} {:?} {:?} max {}x{}", | |
| 20 | - cap.backend, cap.direction, cap.codec, cap.profile, cap.max_width, cap.max_height | |
| 21 | - ); | |
| 22 | - } | |
| 23 | - for codec in [EncCodec::H264, EncCodec::H265, EncCodec::Av1] { | |
| 24 | - if let Err(e) = run(codec) { | |
| 25 | - println!("{codec:?}: error: {e}"); | |
| 26 | - } | |
| 27 | - } | |
| 28 | -} | |
| 29 | - | |
| 30 | -fn run(codec: EncCodec) -> ec_hw::Result<()> { | |
| 31 | - let config = EncoderConfig { | |
| 32 | - bitrate: 2_000_000, | |
| 33 | - rate_control: RateControlMode::ConstantBitrate, | |
| 34 | - ..EncoderConfig::new(codec, WIDTH, HEIGHT) | |
| 35 | - }; | |
| 36 | - let mut encoder = match HwEncoder::open(config, None) { | |
| 37 | - Ok(encoder) => encoder, | |
| 38 | - Err(e) => { | |
| 39 | - println!("{codec:?}: no encoder: {e}"); | |
| 40 | - return Ok(()); | |
| 41 | - } | |
| 42 | - }; | |
| 43 | - let backend = encoder.backend(); | |
| 44 | - let mut coded = Vec::with_capacity(FRAMES as usize); | |
| 45 | - for index in 0..FRAMES { | |
| 46 | - let meta = FrameMetadata { | |
| 47 | - timestamp: index as i64, | |
| 48 | - force_keyframe: index == 0, | |
| 49 | - }; | |
| 50 | - coded.push(encoder.encode(&gray_gradient(index), meta)?); | |
| 51 | - } | |
| 52 | - let bytes: usize = coded.iter().map(|c| c.data.len()).sum(); | |
| 53 | - println!("{codec:?} {backend:?} {FRAMES} frames {bytes} bytes"); | |
| 54 | - | |
| 55 | - if backend != Backend::Vk { | |
| 56 | - return Ok(()); | |
| 57 | - } | |
| 58 | - let mut decoder = match HwDecoder::open(decode_codec(codec)) { | |
| 59 | - Ok(decoder) => decoder, | |
| 60 | - Err(e) => { | |
| 61 | - println!(" decode unavailable: {e}"); | |
| 62 | - return Ok(()); | |
| 63 | - } | |
| 64 | - }; | |
| 65 | - let mut frames = 0; | |
| 66 | - for c in &coded { | |
| 67 | - decoder.decode(&c.data, c.timestamp)?; | |
| 68 | - while decoder.next_frame()?.is_some() { | |
| 69 | - frames += 1; | |
| 70 | - } | |
| 71 | - } | |
| 72 | - decoder.flush()?; | |
| 73 | - while decoder.next_frame()?.is_some() { | |
| 74 | - frames += 1; | |
| 75 | - } | |
| 76 | - println!(" decoded {frames} frames"); | |
| 77 | - Ok(()) | |
| 78 | -} | |
| 79 | - | |
| 80 | -fn decode_codec(codec: EncCodec) -> Codec { | |
| 81 | - match codec { | |
| 82 | - EncCodec::H264 => Codec::H264, | |
| 83 | - EncCodec::H265 => Codec::H265, | |
| 84 | - EncCodec::Av1 => Codec::Av1, | |
| 85 | - } | |
| 86 | -} | |
| 87 | - | |
| 88 | -fn gray_gradient(index: u32) -> I420 { | |
| 89 | - let (w, h) = (WIDTH as usize, HEIGHT as usize); | |
| 90 | - let shift = 4 * index as usize; | |
| 91 | - let y = (0..h) | |
| 92 | - .flat_map(|row| (0..w).map(move |col| ((col + row + shift) & 0xff) as u8)) | |
| 93 | - .collect(); | |
| 94 | - let chroma = w.div_ceil(2) * h.div_ceil(2); | |
| 95 | - I420 { | |
| 96 | - y, | |
| 97 | - u: vec![128; chroma], | |
| 98 | - v: vec![128; chroma], | |
| 99 | - width: WIDTH, | |
| 100 | - height: HEIGHT, | |
| 101 | - } | |
| 102 | -} |
crates/ec-hw/examples/hw_config.rsdeleted+0 -144
| @@ -1,144 +0,0 @@ | ||
| 1 | -use std::fs; | |
| 2 | -use std::path::{Path, PathBuf}; | |
| 3 | - | |
| 4 | -use ec_hw::{ | |
| 5 | - Backend, EncCodec, EncoderConfig, FrameMetadata, H264Profile, HwEncoder, I420, RateControlMode, | |
| 6 | -}; | |
| 7 | - | |
| 8 | -const WIDTH: u32 = 640; | |
| 9 | -const HEIGHT: u32 = 360; | |
| 10 | -const FRAMES: usize = 30; | |
| 11 | -const FPS: u32 = 30; | |
| 12 | -const GOP: u32 = 15; | |
| 13 | -const FORCE_AT: usize = 7; | |
| 14 | -const BITRATE: u32 = 2_000_000; | |
| 15 | -const FIELDS: [&str; 7] = [ | |
| 16 | - "profile", | |
| 17 | - "width", | |
| 18 | - "height", | |
| 19 | - "color_space", | |
| 20 | - "color_transfer", | |
| 21 | - "color_primaries", | |
| 22 | - "color_range", | |
| 23 | -]; | |
| 24 | - | |
| 25 | -fn config(profile: H264Profile) -> EncoderConfig { | |
| 26 | - EncoderConfig { | |
| 27 | - bitrate: BITRATE, | |
| 28 | - framerate: (FPS, 1), | |
| 29 | - gop_size: GOP, | |
| 30 | - rate_control: RateControlMode::ConstantBitrate, | |
| 31 | - ..EncoderConfig::new(EncCodec::H264, WIDTH, HEIGHT) | |
| 32 | - } | |
| 33 | - .h264_profile(profile) | |
| 34 | - .colour(6, 6, 6, true) | |
| 35 | -} | |
| 36 | - | |
| 37 | -fn frame(t: usize) -> I420 { | |
| 38 | - let (w, h) = (WIDTH as usize, HEIGHT as usize); | |
| 39 | - let y = (0..w * h) | |
| 40 | - .map(|i| ((i % w + i / w + 3 * t) & 0xff) as u8) | |
| 41 | - .collect(); | |
| 42 | - let chroma = w / 2 * h / 2; | |
| 43 | - I420 { | |
| 44 | - y, | |
| 45 | - u: vec![(96 + t % 64) as u8; chroma], | |
| 46 | - v: vec![160; chroma], | |
| 47 | - width: WIDTH, | |
| 48 | - height: HEIGHT, | |
| 49 | - } | |
| 50 | -} | |
| 51 | - | |
| 52 | -fn encode(dir: &Path, name: &str, profile: H264Profile, backend: Backend) -> Option<PathBuf> { | |
| 53 | - let mut encoder = match HwEncoder::open(config(profile), Some(backend)) { | |
| 54 | - Ok(encoder) => encoder, | |
| 55 | - Err(e) => { | |
| 56 | - println!("{name}: {e}"); | |
| 57 | - return None; | |
| 58 | - } | |
| 59 | - }; | |
| 60 | - let mut stream = Vec::new(); | |
| 61 | - for t in 0..FRAMES { | |
| 62 | - let meta = FrameMetadata { | |
| 63 | - timestamp: t as i64, | |
| 64 | - force_keyframe: t == FORCE_AT, | |
| 65 | - }; | |
| 66 | - let coded = encoder.encode(&frame(t), meta).expect("encode frame"); | |
| 67 | - stream.extend_from_slice(&coded.data); | |
| 68 | - } | |
| 69 | - let path = dir.join(format!("{name}.h264")); | |
| 70 | - fs::write(&path, stream).expect("write stream"); | |
| 71 | - Some(path) | |
| 72 | -} | |
| 73 | - | |
| 74 | -fn probe(path: &Path) -> Vec<(String, String)> { | |
| 75 | - let out = ec_testkit::ffprobe() | |
| 76 | - .args(["-v", "error", "-select_streams", "v:0", "-show_entries"]) | |
| 77 | - .arg(format!("stream={}", FIELDS.join(","))) | |
| 78 | - .args(["-of", "default=nw=1"]) | |
| 79 | - .arg(path) | |
| 80 | - .output() | |
| 81 | - .expect("run ffprobe"); | |
| 82 | - String::from_utf8_lossy(&out.stdout) | |
| 83 | - .lines() | |
| 84 | - .filter_map(|l| l.split_once('=')) | |
| 85 | - .map(|(k, v)| (k.to_string(), v.to_string())) | |
| 86 | - .collect() | |
| 87 | -} | |
| 88 | - | |
| 89 | -fn keyframes(path: &Path) -> Vec<usize> { | |
| 90 | - let out = ec_testkit::ffprobe() | |
| 91 | - .args([ | |
| 92 | - "-v", | |
| 93 | - "error", | |
| 94 | - "-select_streams", | |
| 95 | - "v:0", | |
| 96 | - "-show_entries", | |
| 97 | - "frame=key_frame", | |
| 98 | - ]) | |
| 99 | - .args(["-of", "csv=p=0"]) | |
| 100 | - .arg(path) | |
| 101 | - .output() | |
| 102 | - .expect("run ffprobe"); | |
| 103 | - String::from_utf8_lossy(&out.stdout) | |
| 104 | - .lines() | |
| 105 | - .enumerate() | |
| 106 | - .filter(|(_, l)| l.trim() == "1") | |
| 107 | - .map(|(i, _)| i) | |
| 108 | - .collect() | |
| 109 | -} | |
| 110 | - | |
| 111 | -fn value(info: &[(String, String)], key: &str) -> String { | |
| 112 | - info.iter() | |
| 113 | - .find(|(k, _)| k == key) | |
| 114 | - .map_or("-".to_string(), |(_, v)| v.clone()) | |
| 115 | -} | |
| 116 | - | |
| 117 | -fn main() { | |
| 118 | - let dir = std::env::temp_dir(); | |
| 119 | - for (label, profile) in [("main", H264Profile::Main), ("cb", H264Profile::ConstrainedBaseline)] { | |
| 120 | - compare(&dir, label, profile); | |
| 121 | - } | |
| 122 | -} | |
| 123 | - | |
| 124 | -fn compare(dir: &Path, label: &str, profile: H264Profile) { | |
| 125 | - let Some(vk) = encode(dir, &format!("vk_{label}"), profile, Backend::Vk) else { | |
| 126 | - return; | |
| 127 | - }; | |
| 128 | - let Some(va) = encode(dir, &format!("va_{label}"), profile, Backend::Va) else { | |
| 129 | - return; | |
| 130 | - }; | |
| 131 | - let (vk_info, va_info) = (probe(&vk), probe(&va)); | |
| 132 | - let mut same = true; | |
| 133 | - println!("{:<16}{:<16}{:<16}", "field", "vk", "va"); | |
| 134 | - for key in FIELDS { | |
| 135 | - let (a, b) = (value(&vk_info, key), value(&va_info, key)); | |
| 136 | - same &= a == b; | |
| 137 | - println!("{key:<16}{a:<16}{b:<16}"); | |
| 138 | - } | |
| 139 | - let (kv, ka) = (keyframes(&vk), keyframes(&va)); | |
| 140 | - same &= kv == ka; | |
| 141 | - let list = |k: &[usize]| k.iter().map(usize::to_string).collect::<Vec<_>>().join(","); | |
| 142 | - println!("{:<16}{:<16}{:<16}", "keyframes", list(&kv), list(&ka)); | |
| 143 | - println!("{label} match: {same}"); | |
| 144 | -} |
crates/ec-hw/examples/hw_decode.rsmodified+8 -16
| @@ -130,12 +130,7 @@ fn mixed_cases(dir: &Path) { | ||
| 130 | 130 | } |
| 131 | 131 | |
| 132 | 132 | fn mixed_case(label: &str, codec: Codec, units: &[&[u8]], ten: bool, gpu: &ec_vk::Gpu) { |
| 133 | - let mut reference = if ten { | |
| 134 | - HwDecoder::open_16(codec) | |
| 135 | - } else { | |
| 136 | - HwDecoder::open(codec) | |
| 137 | - } | |
| 138 | - .expect("open decoder"); | |
| 133 | + let mut reference = HwDecoder::open(codec).expect("open decoder"); | |
| 139 | 134 | let expected = decoded_planes(&mut reference, units, ten); |
| 140 | 135 | |
| 141 | 136 | let mut decoder = HwDecoder::open(codec).expect("open mixed decoder"); |
| @@ -187,17 +182,12 @@ fn dmabuf_cases(dir: &Path) { | ||
| 187 | 182 | } |
| 188 | 183 | |
| 189 | 184 | fn dmabuf_case(label: &str, codec: Codec, units: &[&[u8]], ten: bool) { |
| 190 | - let mut reference = if ten { | |
| 191 | - HwDecoder::open_16(codec) | |
| 192 | - } else { | |
| 193 | - HwDecoder::open(codec) | |
| 194 | - } | |
| 195 | - .expect("open decoder"); | |
| 185 | + let mut reference = HwDecoder::open(codec).expect("open decoder"); | |
| 196 | 186 | assert_eq!(reference.backend(), Backend::Vk, "{label}: must decode on Vulkan"); |
| 197 | 187 | let expected = decoded_planes(&mut reference, units, ten); |
| 198 | 188 | |
| 199 | 189 | let gpu = ec_vk::Gpu::open().expect("Vulkan device"); |
| 200 | - let mut decoder = HwDecoder::open_dmabuf(codec).expect("open DMA-BUF decoder"); | |
| 190 | + let mut decoder = HwDecoder::open(codec).expect("open DMA-BUF decoder"); | |
| 201 | 191 | assert_eq!(decoder.backend(), Backend::Vk, "{label}: DMA-BUF must decode on Vulkan"); |
| 202 | 192 | let mut got = Vec::new(); |
| 203 | 193 | for (pts, unit) in units.iter().enumerate() { |
| @@ -222,7 +212,8 @@ fn decoded_planes(decoder: &mut HwDecoder, units: &[&[u8]], ten: bool) -> Vec<(V | ||
| 222 | 212 | |
| 223 | 213 | fn take_planes(decoder: &mut HwDecoder, ten: bool, out: &mut Vec<(Vec<u8>, Vec<u8>)>) { |
| 224 | 214 | if ten { |
| 225 | - while let Some((_, frame)) = decoder.next_frame_16().expect("next frame") { | |
| 215 | + while let Some(picture) = decoder.next_picture().expect("next picture") { | |
| 216 | + let frame = picture.to_i420_16().expect("to_i420_16"); | |
| 226 | 217 | out.push(p010_planes(&frame)); |
| 227 | 218 | } |
| 228 | 219 | } else { |
| @@ -250,8 +241,9 @@ fn p010_planes(frame: &I420_16) -> (Vec<u8>, Vec<u8>) { | ||
| 250 | 241 | } |
| 251 | 242 | |
| 252 | 243 | fn collect_dmabuf(decoder: &mut HwDecoder, gpu: &ec_vk::Gpu, out: &mut Vec<(Vec<u8>, Vec<u8>)>) { |
| 253 | - while let Some((_, picture)) = decoder.next_dmabuf().expect("next DMA-BUF") { | |
| 254 | - out.push(read_back(gpu, picture)); | |
| 244 | + while let Some(picture) = decoder.next_picture().expect("next picture") { | |
| 245 | + let dmabuf = picture.export_dmabuf().expect("export DMA-BUF"); | |
| 246 | + out.push(read_back(gpu, dmabuf)); | |
| 255 | 247 | } |
| 256 | 248 | } |
| 257 | 249 |
crates/ec-hw/examples/hw_pipeline.rsdeleted+0 -165
| @@ -1,165 +0,0 @@ | ||
| 1 | -use std::time::Instant; | |
| 2 | - | |
| 3 | -use ec_hw::{ | |
| 4 | - Backend, EncCodec, EncodeInput, EncoderConfig, FrameMetadata, HwEncoder, I420, I420_16, | |
| 5 | - RateControlMode, | |
| 6 | -}; | |
| 7 | - | |
| 8 | -const FRAMES: usize = 120; | |
| 9 | -const PATTERN: usize = 6; | |
| 10 | - | |
| 11 | -struct Case { | |
| 12 | - codec: EncCodec, | |
| 13 | - width: u32, | |
| 14 | - height: u32, | |
| 15 | - ten: bool, | |
| 16 | -} | |
| 17 | - | |
| 18 | -enum Source { | |
| 19 | - Eight(Vec<I420>), | |
| 20 | - Ten(Vec<I420_16>), | |
| 21 | -} | |
| 22 | - | |
| 23 | -fn main() { | |
| 24 | - let cases = [ | |
| 25 | - Case { | |
| 26 | - codec: EncCodec::H265, | |
| 27 | - width: 3840, | |
| 28 | - height: 2160, | |
| 29 | - ten: true, | |
| 30 | - }, | |
| 31 | - Case { | |
| 32 | - codec: EncCodec::H264, | |
| 33 | - width: 1920, | |
| 34 | - height: 1080, | |
| 35 | - ten: false, | |
| 36 | - }, | |
| 37 | - Case { | |
| 38 | - codec: EncCodec::H265, | |
| 39 | - width: 1920, | |
| 40 | - height: 1080, | |
| 41 | - ten: false, | |
| 42 | - }, | |
| 43 | - Case { | |
| 44 | - codec: EncCodec::Av1, | |
| 45 | - width: 1920, | |
| 46 | - height: 1080, | |
| 47 | - ten: false, | |
| 48 | - }, | |
| 49 | - ]; | |
| 50 | - for case in &cases { | |
| 51 | - let source = if case.ten { | |
| 52 | - Source::Ten(pattern_16(case)) | |
| 53 | - } else { | |
| 54 | - Source::Eight(pattern(case)) | |
| 55 | - }; | |
| 56 | - for backend in [Backend::Vk, Backend::Va] { | |
| 57 | - if let Err(e) = run(case, &source, backend) { | |
| 58 | - println!( | |
| 59 | - "{:?} {}x{} {backend:?}: error: {e}", | |
| 60 | - case.codec, case.width, case.height | |
| 61 | - ); | |
| 62 | - } | |
| 63 | - } | |
| 64 | - } | |
| 65 | -} | |
| 66 | - | |
| 67 | -fn config(case: &Case) -> EncoderConfig { | |
| 68 | - let base = EncoderConfig { | |
| 69 | - rate_control: RateControlMode::ConstantQp { qp: 30 }, | |
| 70 | - ..EncoderConfig::new(case.codec, case.width, case.height) | |
| 71 | - }; | |
| 72 | - if case.ten { | |
| 73 | - base.ten_bit() | |
| 74 | - } else { | |
| 75 | - base | |
| 76 | - } | |
| 77 | -} | |
| 78 | - | |
| 79 | -fn meta(index: usize) -> FrameMetadata { | |
| 80 | - FrameMetadata { | |
| 81 | - timestamp: index as i64, | |
| 82 | - force_keyframe: index == 0, | |
| 83 | - } | |
| 84 | -} | |
| 85 | - | |
| 86 | -fn run(case: &Case, source: &Source, backend: Backend) -> ec_hw::Result<()> { | |
| 87 | - let mut encoder = HwEncoder::open(config(case), Some(backend))?; | |
| 88 | - let start = Instant::now(); | |
| 89 | - let mut sync = Vec::with_capacity(FRAMES); | |
| 90 | - for index in 0..FRAMES { | |
| 91 | - let coded = match source { | |
| 92 | - Source::Eight(frames) => encoder.encode(&frames[index % PATTERN], meta(index))?, | |
| 93 | - Source::Ten(frames) => encoder.encode_16(&frames[index % PATTERN], meta(index))?, | |
| 94 | - }; | |
| 95 | - sync.push(coded); | |
| 96 | - } | |
| 97 | - let sync_ms = start.elapsed().as_secs_f64() * 1000.0 / FRAMES as f64; | |
| 98 | - | |
| 99 | - let mut encoder = HwEncoder::open(config(case), Some(backend))?; | |
| 100 | - let start = Instant::now(); | |
| 101 | - let mut piped = Vec::with_capacity(FRAMES); | |
| 102 | - for index in 0..FRAMES { | |
| 103 | - let input = match source { | |
| 104 | - Source::Eight(frames) => EncodeInput::I420(&frames[index % PATTERN]), | |
| 105 | - Source::Ten(frames) => EncodeInput::I420_16(&frames[index % PATTERN]), | |
| 106 | - }; | |
| 107 | - piped.extend(encoder.submit(input, meta(index))?); | |
| 108 | - } | |
| 109 | - piped.extend(encoder.flush()?); | |
| 110 | - let piped_ms = start.elapsed().as_secs_f64() * 1000.0 / FRAMES as f64; | |
| 111 | - | |
| 112 | - if matches!(backend, Backend::Vk) { | |
| 113 | - assert_eq!(sync, piped, "{:?} sync and pipelined bitstreams differ", case.codec); | |
| 114 | - } | |
| 115 | - println!( | |
| 116 | - "{:?} {}x{} {}-bit {backend:?}: sync {sync_ms:.2} ms/frame, pipelined {piped_ms:.2} ms/frame, {} frames", | |
| 117 | - case.codec, | |
| 118 | - case.width, | |
| 119 | - case.height, | |
| 120 | - if case.ten { 10 } else { 8 }, | |
| 121 | - piped.len() | |
| 122 | - ); | |
| 123 | - Ok(()) | |
| 124 | -} | |
| 125 | - | |
| 126 | -fn pattern(case: &Case) -> Vec<I420> { | |
| 127 | - let (w, h) = (case.width as usize, case.height as usize); | |
| 128 | - let (cw, ch) = (w / 2, h / 2); | |
| 129 | - (0..PATTERN) | |
| 130 | - .map(|k| I420 { | |
| 131 | - y: (0..h) | |
| 132 | - .flat_map(move |row| (0..w).map(move |x| ((x + row + 3 * k) & 0xff) as u8)) | |
| 133 | - .collect(), | |
| 134 | - u: (0..ch) | |
| 135 | - .flat_map(move |row| (0..cw).map(move |x| ((x + 2 * row + 5 * k) & 0xff) as u8)) | |
| 136 | - .collect(), | |
| 137 | - v: (0..ch) | |
| 138 | - .flat_map(move |row| (0..cw).map(move |x| ((2 * x + row + 7 * k) & 0xff) as u8)) | |
| 139 | - .collect(), | |
| 140 | - width: case.width, | |
| 141 | - height: case.height, | |
| 142 | - }) | |
| 143 | - .collect() | |
| 144 | -} | |
| 145 | - | |
| 146 | -fn pattern_16(case: &Case) -> Vec<I420_16> { | |
| 147 | - let (w, h) = (case.width as usize, case.height as usize); | |
| 148 | - let (cw, ch) = (w / 2, h / 2); | |
| 149 | - (0..PATTERN) | |
| 150 | - .map(|k| I420_16 { | |
| 151 | - y: (0..h) | |
| 152 | - .flat_map(move |row| (0..w).map(move |x| ((x + row + 3 * k) & 0x3ff) as u16)) | |
| 153 | - .collect(), | |
| 154 | - u: (0..ch) | |
| 155 | - .flat_map(move |row| (0..cw).map(move |x| ((x + 2 * row + 5 * k) & 0x3ff) as u16)) | |
| 156 | - .collect(), | |
| 157 | - v: (0..ch) | |
| 158 | - .flat_map(move |row| (0..cw).map(move |x| ((2 * x + row + 7 * k) & 0x3ff) as u16)) | |
| 159 | - .collect(), | |
| 160 | - width: case.width, | |
| 161 | - height: case.height, | |
| 162 | - bit_depth: 10, | |
| 163 | - }) | |
| 164 | - .collect() | |
| 165 | -} |
crates/ec-hw/examples/hw_rgb.rsdeleted+0 -148
| @@ -1,148 +0,0 @@ | ||
| 1 | -use ec_hw::{ | |
| 2 | - Backend, Codec, EncCodec, EncoderConfig, FrameMetadata, HwDecoder, HwEncoder, I420, | |
| 3 | - RateControlMode, RgbFrame, RgbOrder, | |
| 4 | -}; | |
| 5 | - | |
| 6 | -const FRAMES: u32 = 30; | |
| 7 | - | |
| 8 | -fn main() { | |
| 9 | - for codec in [EncCodec::H264, EncCodec::H265, EncCodec::Av1] { | |
| 10 | - if let Err(e) = run(codec, (1280, 720), (1280, 720)) { | |
| 11 | - println!("{codec:?} 1280x720: error: {e}"); | |
| 12 | - } | |
| 13 | - } | |
| 14 | - for target in [(1280, 720), (640, 360)] { | |
| 15 | - if let Err(e) = run(EncCodec::H264, (1920, 1080), target) { | |
| 16 | - println!("H264 1920x1080 -> {}x{}: error: {e}", target.0, target.1); | |
| 17 | - } | |
| 18 | - } | |
| 19 | -} | |
| 20 | - | |
| 21 | -fn run(codec: EncCodec, source: (u32, u32), target: (u32, u32)) -> ec_hw::Result<()> { | |
| 22 | - let config = EncoderConfig { | |
| 23 | - bitrate: 4_000_000, | |
| 24 | - rate_control: RateControlMode::ConstantBitrate, | |
| 25 | - ..EncoderConfig::new(codec, target.0, target.1) | |
| 26 | - }; | |
| 27 | - let mut encoder = match HwEncoder::open(config, std::env::args().nth(1).map(|_| Backend::Va)) { | |
| 28 | - Ok(encoder) => encoder, | |
| 29 | - Err(e) => { | |
| 30 | - println!("{codec:?}: no encoder: {e}"); | |
| 31 | - return Ok(()); | |
| 32 | - } | |
| 33 | - }; | |
| 34 | - let backend = encoder.backend(); | |
| 35 | - let mut coded = Vec::with_capacity(FRAMES as usize); | |
| 36 | - for index in 0..FRAMES { | |
| 37 | - let pixels = bgra_gradient(index, source); | |
| 38 | - let frame = RgbFrame { | |
| 39 | - data: &pixels, | |
| 40 | - width: source.0, | |
| 41 | - height: source.1, | |
| 42 | - stride: source.0 * 4, | |
| 43 | - order: RgbOrder::Bgra, | |
| 44 | - }; | |
| 45 | - let meta = FrameMetadata { | |
| 46 | - timestamp: index as i64, | |
| 47 | - force_keyframe: index == 0, | |
| 48 | - }; | |
| 49 | - coded.push(encoder.encode_rgb(&frame, meta)?); | |
| 50 | - } | |
| 51 | - let bytes: usize = coded.iter().map(|c| c.data.len()).sum(); | |
| 52 | - println!( | |
| 53 | - "{codec:?} {backend:?} {}x{} -> {}x{} {FRAMES} frames {bytes} bytes", | |
| 54 | - source.0, source.1, target.0, target.1 | |
| 55 | - ); | |
| 56 | - | |
| 57 | - let mut decoder = match HwDecoder::open(decode_codec(codec)) { | |
| 58 | - Ok(decoder) => decoder, | |
| 59 | - Err(e) => { | |
| 60 | - println!(" decode unavailable: {e}"); | |
| 61 | - return Ok(()); | |
| 62 | - } | |
| 63 | - }; | |
| 64 | - let mut decoded = Vec::new(); | |
| 65 | - for c in &coded { | |
| 66 | - decoder.decode(&c.data, c.timestamp)?; | |
| 67 | - while let Some(frame) = decoder.next_frame()? { | |
| 68 | - decoded.push(frame); | |
| 69 | - } | |
| 70 | - } | |
| 71 | - decoder.flush()?; | |
| 72 | - while let Some(frame) = decoder.next_frame()? { | |
| 73 | - decoded.push(frame); | |
| 74 | - } | |
| 75 | - | |
| 76 | - let total: f64 = decoded | |
| 77 | - .iter() | |
| 78 | - .map(|(ts, frame)| { | |
| 79 | - mean_abs_luma(&frame.y, &luma_reference(*ts as u32, source, target)) | |
| 80 | - }) | |
| 81 | - .sum(); | |
| 82 | - let mean = if decoded.is_empty() { | |
| 83 | - 0.0 | |
| 84 | - } else { | |
| 85 | - total / decoded.len() as f64 | |
| 86 | - }; | |
| 87 | - println!( | |
| 88 | - " decoded {} frames, mean |Y diff| {mean:.2}", | |
| 89 | - decoded.len() | |
| 90 | - ); | |
| 91 | - Ok(()) | |
| 92 | -} | |
| 93 | - | |
| 94 | -fn decode_codec(codec: EncCodec) -> Codec { | |
| 95 | - match codec { | |
| 96 | - EncCodec::H264 => Codec::H264, | |
| 97 | - EncCodec::H265 => Codec::H265, | |
| 98 | - EncCodec::Av1 => Codec::Av1, | |
| 99 | - } | |
| 100 | -} | |
| 101 | - | |
| 102 | -fn bgra_gradient(index: u32, (w, h): (u32, u32)) -> Vec<u8> { | |
| 103 | - let shift = index as usize * 4; | |
| 104 | - let mut out = Vec::with_capacity(w as usize * h as usize * 4); | |
| 105 | - for y in 0..h as usize { | |
| 106 | - for x in 0..w as usize { | |
| 107 | - let r = (x + shift) & 0xff; | |
| 108 | - let g = (y + 2 * shift) & 0xff; | |
| 109 | - let b = ((x + y) / 2 + 3 * shift) & 0xff; | |
| 110 | - out.extend_from_slice(&[b as u8, g as u8, r as u8, 0xff]); | |
| 111 | - } | |
| 112 | - } | |
| 113 | - out | |
| 114 | -} | |
| 115 | - | |
| 116 | -fn luma_reference(index: u32, source: (u32, u32), target: (u32, u32)) -> Vec<u8> { | |
| 117 | - let (sw, sh) = (source.0 as usize, source.1 as usize); | |
| 118 | - let (w, h) = (target.0 as usize, target.1 as usize); | |
| 119 | - let mut scaled = vec![0; w * h * 4]; | |
| 120 | - ec_dsp::rgb::rgb_box_downscale( | |
| 121 | - &bgra_gradient(index, source), | |
| 122 | - sw, | |
| 123 | - sh, | |
| 124 | - sw * 4, | |
| 125 | - &mut scaled, | |
| 126 | - w, | |
| 127 | - h, | |
| 128 | - ); | |
| 129 | - let chroma = (w / 2) * (h / 2); | |
| 130 | - let mut frame = I420 { | |
| 131 | - y: vec![0; w * h], | |
| 132 | - u: vec![0; chroma], | |
| 133 | - v: vec![0; chroma], | |
| 134 | - width: target.0, | |
| 135 | - height: target.1, | |
| 136 | - }; | |
| 137 | - ec_dsp::rgb::bgra_to_i420_709(&scaled, w, h, &mut frame.y, &mut frame.u, &mut frame.v); | |
| 138 | - frame.y | |
| 139 | -} | |
| 140 | - | |
| 141 | -fn mean_abs_luma(decoded: &[u8], reference: &[u8]) -> f64 { | |
| 142 | - let sum: u64 = decoded | |
| 143 | - .iter() | |
| 144 | - .zip(reference) | |
| 145 | - .map(|(&a, &b)| u64::from(a.abs_diff(b))) | |
| 146 | - .sum(); | |
| 147 | - sum as f64 / reference.len() as f64 | |
| 148 | -} |
crates/ec-hw/examples/hw_smoke.rsadded+164 -0
| @@ -0,0 +1,164 @@ | ||
| 1 | +use ec_hw::{ | |
| 2 | + Backend, Codec, CodedFrame, EncCodec, EncoderConfig, FrameMetadata, HwDecoder, HwEncoder, HwPicture, I420_16, | |
| 3 | + RateControlMode, RgbFrame, RgbOrder, Tunings, capabilities, | |
| 4 | +}; | |
| 5 | + | |
| 6 | +const W: u32 = 1280; | |
| 7 | +const H: u32 = 720; | |
| 8 | +const FPS: u32 = 30; | |
| 9 | +const SEGMENT: u32 = 30; | |
| 10 | +const PEAK: f64 = 1023.0; | |
| 11 | + | |
| 12 | +fn main() { | |
| 13 | + for cap in capabilities() { | |
| 14 | + println!( | |
| 15 | + "{:?} {:?} {:?} {:?} max {}x{}", | |
| 16 | + cap.backend, cap.direction, cap.codec, cap.profile, cap.max_width, cap.max_height | |
| 17 | + ); | |
| 18 | + } | |
| 19 | + for codec in [EncCodec::H264, EncCodec::H265, EncCodec::Av1] { | |
| 20 | + if let Err(e) = eight_bit(codec) { | |
| 21 | + println!("{codec:?}: error: {e}"); | |
| 22 | + } | |
| 23 | + } | |
| 24 | + for codec in [EncCodec::H265, EncCodec::Av1] { | |
| 25 | + for backend in [Backend::Vk, Backend::Va] { | |
| 26 | + if let Err(e) = ten_bit(codec, backend) { | |
| 27 | + println!("{codec:?} 10-bit {backend:?}: error: {e}"); | |
| 28 | + } | |
| 29 | + } | |
| 30 | + } | |
| 31 | +} | |
| 32 | + | |
| 33 | +fn eight_bit(codec: EncCodec) -> ec_hw::Result<()> { | |
| 34 | + let config = EncoderConfig { | |
| 35 | + bitrate: 4_000_000, | |
| 36 | + framerate: (FPS, 1), | |
| 37 | + gop_size: 1000, | |
| 38 | + rate_control: RateControlMode::ConstantBitrate, | |
| 39 | + ..EncoderConfig::new(codec, W, H) | |
| 40 | + }; | |
| 41 | + let mut encoder = HwEncoder::open(config, None)?; | |
| 42 | + let mut coded = Vec::new(); | |
| 43 | + for index in 0..3 * SEGMENT { | |
| 44 | + if index == SEGMENT { | |
| 45 | + encoder.tune(Tunings { bitrate: 1_000_000, framerate: (FPS, 1) })?; | |
| 46 | + } | |
| 47 | + if index == 2 * SEGMENT { | |
| 48 | + encoder.tune(Tunings { bitrate: 3_000_000, framerate: (FPS, 1) })?; | |
| 49 | + } | |
| 50 | + let pixels = bgra_gradient(index); | |
| 51 | + let frame = RgbFrame { data: &pixels, width: W, height: H, stride: W * 4, order: RgbOrder::Bgra }; | |
| 52 | + let meta = FrameMetadata { timestamp: index as i64, force_keyframe: index == 0 }; | |
| 53 | + coded.push(encoder.encode_rgb(&frame, meta)?); | |
| 54 | + } | |
| 55 | + let kbps: Vec<String> = coded | |
| 56 | + .chunks(SEGMENT as usize) | |
| 57 | + .map(|chunk| { | |
| 58 | + let bytes: usize = chunk.iter().map(|c| c.data.len()).sum(); | |
| 59 | + format!("{:.0}", bytes as f64 * 8.0 * FPS as f64 / SEGMENT as f64 / 1000.0) | |
| 60 | + }) | |
| 61 | + .collect(); | |
| 62 | + let keyframes = coded.iter().filter(|c| c.is_keyframe).count(); | |
| 63 | + println!("{codec:?} {:?} kb/s per segment: {} keyframes {keyframes}", encoder.backend(), kbps.join(" ")); | |
| 64 | + let decoded = decode(codec, &coded)?; | |
| 65 | + println!(" decoded {} of {}", decoded.len(), coded.len()); | |
| 66 | + Ok(()) | |
| 67 | +} | |
| 68 | + | |
| 69 | +fn ten_bit(codec: EncCodec, backend: Backend) -> ec_hw::Result<()> { | |
| 70 | + let config = EncoderConfig { | |
| 71 | + bitrate: 4_000_000, | |
| 72 | + rate_control: RateControlMode::ConstantQp { qp: 30 }, | |
| 73 | + ..EncoderConfig::new(codec, W, H).ten_bit() | |
| 74 | + }; | |
| 75 | + let mut encoder = HwEncoder::open(config, Some(backend))?; | |
| 76 | + let mut coded = Vec::new(); | |
| 77 | + let mut sources = Vec::new(); | |
| 78 | + for index in 0..SEGMENT { | |
| 79 | + let frame = pattern(index); | |
| 80 | + let meta = FrameMetadata { timestamp: index as i64, force_keyframe: index == 0 }; | |
| 81 | + coded.push(encoder.encode_16(&frame, meta)?); | |
| 82 | + sources.push(frame); | |
| 83 | + } | |
| 84 | + let decoded = decode(codec, &coded)?; | |
| 85 | + let mut sum = 0.0; | |
| 86 | + for picture in &decoded { | |
| 87 | + sum += psnr(&sources[picture.timestamp as usize], &picture.to_i420_16()?); | |
| 88 | + } | |
| 89 | + let psnr = sum / decoded.len().max(1) as f64; | |
| 90 | + println!("{codec:?} 10-bit {backend:?}: decoded {} of {}, PSNR {psnr:.2} dB", decoded.len(), coded.len()); | |
| 91 | + Ok(()) | |
| 92 | +} | |
| 93 | + | |
| 94 | +fn decode(codec: EncCodec, coded: &[CodedFrame]) -> ec_hw::Result<Vec<HwPicture>> { | |
| 95 | + let mut decoder = HwDecoder::open(decode_codec(codec))?; | |
| 96 | + let mut pictures = Vec::new(); | |
| 97 | + for c in coded { | |
| 98 | + decoder.decode(&c.data, c.timestamp)?; | |
| 99 | + while let Some(picture) = decoder.next_picture()? { | |
| 100 | + pictures.push(picture); | |
| 101 | + } | |
| 102 | + } | |
| 103 | + decoder.flush()?; | |
| 104 | + while let Some(picture) = decoder.next_picture()? { | |
| 105 | + pictures.push(picture); | |
| 106 | + } | |
| 107 | + Ok(pictures) | |
| 108 | +} | |
| 109 | + | |
| 110 | +fn decode_codec(codec: EncCodec) -> Codec { | |
| 111 | + match codec { | |
| 112 | + EncCodec::H264 => Codec::H264, | |
| 113 | + EncCodec::H265 => Codec::H265, | |
| 114 | + EncCodec::Av1 => Codec::Av1, | |
| 115 | + } | |
| 116 | +} | |
| 117 | + | |
| 118 | +fn bgra_gradient(index: u32) -> Vec<u8> { | |
| 119 | + let shift = index as usize * 4; | |
| 120 | + let mut out = Vec::with_capacity(W as usize * H as usize * 4); | |
| 121 | + for y in 0..H as usize { | |
| 122 | + for x in 0..W as usize { | |
| 123 | + let r = (x + shift) & 0xff; | |
| 124 | + let g = (y + 2 * shift) & 0xff; | |
| 125 | + let b = ((x + y) / 2 + 3 * shift) & 0xff; | |
| 126 | + out.extend_from_slice(&[b as u8, g as u8, r as u8, 0xff]); | |
| 127 | + } | |
| 128 | + } | |
| 129 | + out | |
| 130 | +} | |
| 131 | + | |
| 132 | +fn pattern(index: u32) -> I420_16 { | |
| 133 | + let t = index as usize; | |
| 134 | + let (w, h) = (W as usize, H as usize); | |
| 135 | + I420_16 { | |
| 136 | + y: plane(w, h, |x, y| x * 3 + y * 5 + t * 16), | |
| 137 | + u: plane(w / 2, h / 2, |x, y| x * 7 + y * 2 + t * 9), | |
| 138 | + v: plane(w / 2, h / 2, |x, y| x * 2 + y * 11 + t * 5 + 512), | |
| 139 | + width: W, | |
| 140 | + height: H, | |
| 141 | + bit_depth: 10, | |
| 142 | + } | |
| 143 | +} | |
| 144 | + | |
| 145 | +fn plane(w: usize, h: usize, value: impl Fn(usize, usize) -> usize) -> Vec<u16> { | |
| 146 | + let mut out = Vec::with_capacity(w * h); | |
| 147 | + for row in 0..h { | |
| 148 | + for col in 0..w { | |
| 149 | + out.push((value(col, row) & 0x3ff) as u16); | |
| 150 | + } | |
| 151 | + } | |
| 152 | + out | |
| 153 | +} | |
| 154 | + | |
| 155 | +fn psnr(a: &I420_16, b: &I420_16) -> f64 { | |
| 156 | + let mut sse = 0f64; | |
| 157 | + let mut n = 0usize; | |
| 158 | + for (x, y) in a.y.iter().chain(&a.u).chain(&a.v).zip(b.y.iter().chain(&b.u).chain(&b.v)) { | |
| 159 | + let d = f64::from(*x) - f64::from(*y); | |
| 160 | + sse += d * d; | |
| 161 | + n += 1; | |
| 162 | + } | |
| 163 | + 10.0 * (PEAK * PEAK * n as f64 / sse).log10() | |
| 164 | +} |
crates/ec-hw/examples/hw_speed.rsdeleted+0 -26
| @@ -1,26 +0,0 @@ | ||
| 1 | -use ec_hw::{EncCodec, EncoderConfig, FrameMetadata, HwEncoder, RateControlMode, RgbFrame, RgbOrder}; | |
| 2 | -use std::time::Instant; | |
| 3 | - | |
| 4 | -fn main() { | |
| 5 | - let (w, h) = (1920u32, 1080u32); | |
| 6 | - let frames: Vec<Vec<u8>> = (0..8) | |
| 7 | - .map(|t| (0..w * h).flat_map(|i| [(i % w + t * 9) as u8, (i / w) as u8, t as u8 * 20, 255]).collect()) | |
| 8 | - .collect(); | |
| 9 | - for codec in [EncCodec::H264, EncCodec::H265, EncCodec::Av1] { | |
| 10 | - for (ow, oh) in [(1920, 1080), (640, 360)] { | |
| 11 | - let mut cfg = EncoderConfig::new(codec, ow, oh); | |
| 12 | - cfg.bitrate = 8_000_000; | |
| 13 | - cfg.framerate = (60, 1); | |
| 14 | - cfg.rate_control = RateControlMode::ConstantBitrate; | |
| 15 | - let Ok(mut enc) = HwEncoder::open(cfg, None) else { continue }; | |
| 16 | - let n = 120; | |
| 17 | - let start = Instant::now(); | |
| 18 | - for i in 0..n { | |
| 19 | - let frame = RgbFrame { data: &frames[i % 8], width: w, height: h, stride: w * 4, order: RgbOrder::Bgra }; | |
| 20 | - enc.encode_rgb(&frame, FrameMetadata { timestamp: i as i64, force_keyframe: false }).unwrap(); | |
| 21 | - } | |
| 22 | - let ms = start.elapsed().as_secs_f64() * 1000.0 / n as f64; | |
| 23 | - println!("{codec:?} {:?} 1080p->{ow}x{oh}: {ms:.2} ms/frame ({:.0} fps)", enc.backend(), 1000.0 / ms); | |
| 24 | - } | |
| 25 | - } | |
| 26 | -} |
crates/ec-hw/examples/hw_ten.rsdeleted+0 -141
| @@ -1,141 +0,0 @@ | ||
| 1 | -use ec_hw::{ | |
| 2 | - Backend, Codec, EncCodec, EncoderConfig, FrameMetadata, HwDecoder, HwEncoder, I420_16, | |
| 3 | - RateControlMode, | |
| 4 | -}; | |
| 5 | - | |
| 6 | -const WIDTH: u32 = 1280; | |
| 7 | -const HEIGHT: u32 = 720; | |
| 8 | -const FRAMES: u32 = 30; | |
| 9 | -const PEAK: f64 = 1023.0; | |
| 10 | - | |
| 11 | -fn main() { | |
| 12 | - let dir = std::env::temp_dir().display().to_string(); | |
| 13 | - let rates = [ | |
| 14 | - ("cqp", RateControlMode::ConstantQp { qp: 30 }), | |
| 15 | - ("cbr", RateControlMode::ConstantBitrate), | |
| 16 | - ]; | |
| 17 | - for codec in [EncCodec::H265, EncCodec::Av1] { | |
| 18 | - for (name, rate) in rates { | |
| 19 | - for backend in [Backend::Vk, Backend::Va] { | |
| 20 | - if let Err(e) = run(&dir, codec, name, rate, backend) { | |
| 21 | - println!("{codec:?} {name} {backend:?}: error: {e}"); | |
| 22 | - } | |
| 23 | - } | |
| 24 | - } | |
| 25 | - } | |
| 26 | -} | |
| 27 | - | |
| 28 | -fn run( | |
| 29 | - dir: &str, | |
| 30 | - codec: EncCodec, | |
| 31 | - name: &str, | |
| 32 | - rate: RateControlMode, | |
| 33 | - backend: Backend, | |
| 34 | -) -> ec_hw::Result<()> { | |
| 35 | - let config = EncoderConfig { | |
| 36 | - bitrate: 4_000_000, | |
| 37 | - rate_control: rate, | |
| 38 | - ..EncoderConfig::new(codec, WIDTH, HEIGHT).ten_bit() | |
| 39 | - }; | |
| 40 | - let mut encoder = match HwEncoder::open(config, Some(backend)) { | |
| 41 | - Ok(encoder) => encoder, | |
| 42 | - Err(e) => { | |
| 43 | - println!("{codec:?} {name} {backend:?}: no encoder: {e}"); | |
| 44 | - return Ok(()); | |
| 45 | - } | |
| 46 | - }; | |
| 47 | - let mut coded = Vec::with_capacity(FRAMES as usize); | |
| 48 | - let mut sources = Vec::with_capacity(FRAMES as usize); | |
| 49 | - for index in 0..FRAMES { | |
| 50 | - let frame = pattern(index); | |
| 51 | - let meta = FrameMetadata { | |
| 52 | - timestamp: index as i64, | |
| 53 | - force_keyframe: index == 0, | |
| 54 | - }; | |
| 55 | - coded.push(encoder.encode_16(&frame, meta)?); | |
| 56 | - sources.push(frame); | |
| 57 | - } | |
| 58 | - let stream: Vec<u8> = coded.iter().flat_map(|c| c.data.iter().copied()).collect(); | |
| 59 | - let stem = format!("{dir}/ten_{codec:?}_{name}_{backend:?}"); | |
| 60 | - std::fs::write(format!("{stem}.bin"), &stream).expect("write bitstream"); | |
| 61 | - | |
| 62 | - let mut decoder = HwDecoder::open_16(decode_codec(codec))?; | |
| 63 | - let mut decoded = Vec::new(); | |
| 64 | - for c in &coded { | |
| 65 | - decoder.decode(&c.data, c.timestamp)?; | |
| 66 | - while let Some(frame) = decoder.next_frame_16()? { | |
| 67 | - decoded.push(frame); | |
| 68 | - } | |
| 69 | - } | |
| 70 | - decoder.flush()?; | |
| 71 | - while let Some(frame) = decoder.next_frame_16()? { | |
| 72 | - decoded.push(frame); | |
| 73 | - } | |
| 74 | - | |
| 75 | - let mut yuv = Vec::new(); | |
| 76 | - for (_, frame) in &decoded { | |
| 77 | - for sample in frame.y.iter().chain(&frame.u).chain(&frame.v) { | |
| 78 | - yuv.extend_from_slice(&sample.to_le_bytes()); | |
| 79 | - } | |
| 80 | - } | |
| 81 | - std::fs::write(format!("{stem}_ours.yuv"), &yuv).expect("write decoded yuv"); | |
| 82 | - | |
| 83 | - let psnr: f64 = decoded | |
| 84 | - .iter() | |
| 85 | - .map(|(ts, frame)| psnr(&sources[*ts as usize], frame)) | |
| 86 | - .sum::<f64>() | |
| 87 | - / decoded.len().max(1) as f64; | |
| 88 | - println!( | |
| 89 | - "{codec:?} {name} {backend:?}: {} bytes, decoded {} frames, PSNR {psnr:.2} dB", | |
| 90 | - stream.len(), | |
| 91 | - decoded.len() | |
| 92 | - ); | |
| 93 | - Ok(()) | |
| 94 | -} | |
| 95 | - | |
| 96 | -fn decode_codec(codec: EncCodec) -> Codec { | |
| 97 | - match codec { | |
| 98 | - EncCodec::H264 => Codec::H264, | |
| 99 | - EncCodec::H265 => Codec::H265, | |
| 100 | - EncCodec::Av1 => Codec::Av1, | |
| 101 | - } | |
| 102 | -} | |
| 103 | - | |
| 104 | -fn pattern(index: u32) -> I420_16 { | |
| 105 | - let t = index as usize; | |
| 106 | - let (w, h) = (WIDTH as usize, HEIGHT as usize); | |
| 107 | - I420_16 { | |
| 108 | - y: plane(w, h, |x, y| x * 3 + y * 5 + t * 16), | |
| 109 | - u: plane(w / 2, h / 2, |x, y| x * 7 + y * 2 + t * 9), | |
| 110 | - v: plane(w / 2, h / 2, |x, y| x * 2 + y * 11 + t * 5 + 512), | |
| 111 | - width: WIDTH, | |
| 112 | - height: HEIGHT, | |
| 113 | - bit_depth: 10, | |
| 114 | - } | |
| 115 | -} | |
| 116 | - | |
| 117 | -fn plane(w: usize, h: usize, value: impl Fn(usize, usize) -> usize) -> Vec<u16> { | |
| 118 | - let mut out = Vec::with_capacity(w * h); | |
| 119 | - for row in 0..h { | |
| 120 | - for col in 0..w { | |
| 121 | - out.push((value(col, row) & 0x3ff) as u16); | |
| 122 | - } | |
| 123 | - } | |
| 124 | - out | |
| 125 | -} | |
| 126 | - | |
| 127 | -fn psnr(a: &I420_16, b: &I420_16) -> f64 { | |
| 128 | - let mut sse = 0f64; | |
| 129 | - let mut n = 0usize; | |
| 130 | - for (x, y) in | |
| 131 | - a.y.iter() | |
| 132 | - .chain(&a.u) | |
| 133 | - .chain(&a.v) | |
| 134 | - .zip(b.y.iter().chain(&b.u).chain(&b.v)) | |
| 135 | - { | |
| 136 | - let d = f64::from(*x) - f64::from(*y); | |
| 137 | - sse += d * d; | |
| 138 | - n += 1; | |
| 139 | - } | |
| 140 | - 10.0 * (PEAK * PEAK * n as f64 / sse).log10() | |
| 141 | -} |
crates/ec-hw/examples/hw_tune.rsdeleted+0 -102
| @@ -1,102 +0,0 @@ | ||
| 1 | -use ec_hw::{ | |
| 2 | - Codec, EncCodec, EncoderConfig, FrameMetadata, HwDecoder, HwEncoder, RateControlMode, RgbFrame, | |
| 3 | - RgbOrder, Tunings, | |
| 4 | -}; | |
| 5 | - | |
| 6 | -const W: u32 = 1280; | |
| 7 | -const H: u32 = 720; | |
| 8 | -const FPS: u32 = 30; | |
| 9 | -const SEGMENT: u32 = 90; | |
| 10 | - | |
| 11 | -fn main() { | |
| 12 | - for codec in [EncCodec::H264, EncCodec::H265, EncCodec::Av1] { | |
| 13 | - if let Err(e) = run(codec) { | |
| 14 | - println!("{codec:?}: error: {e}"); | |
| 15 | - } | |
| 16 | - } | |
| 17 | -} | |
| 18 | - | |
| 19 | -fn run(codec: EncCodec) -> ec_hw::Result<()> { | |
| 20 | - let config = EncoderConfig { | |
| 21 | - bitrate: 4_000_000, | |
| 22 | - rate_control: RateControlMode::ConstantBitrate, | |
| 23 | - framerate: (FPS, 1), | |
| 24 | - gop_size: 1000, | |
| 25 | - ..EncoderConfig::new(codec, W, H) | |
| 26 | - }; | |
| 27 | - let mut encoder = HwEncoder::open(config, None)?; | |
| 28 | - let mut coded = Vec::new(); | |
| 29 | - for index in 0..3 * SEGMENT { | |
| 30 | - if index == SEGMENT { | |
| 31 | - encoder.tune(Tunings { | |
| 32 | - bitrate: 1_000_000, | |
| 33 | - framerate: (FPS, 1), | |
| 34 | - })?; | |
| 35 | - } | |
| 36 | - if index == 2 * SEGMENT { | |
| 37 | - encoder.tune(Tunings { | |
| 38 | - bitrate: 3_000_000, | |
| 39 | - framerate: (FPS, 1), | |
| 40 | - })?; | |
| 41 | - } | |
| 42 | - let pixels = bgra_gradient(index); | |
| 43 | - let frame = RgbFrame { | |
| 44 | - data: &pixels, | |
| 45 | - width: W, | |
| 46 | - height: H, | |
| 47 | - stride: W * 4, | |
| 48 | - order: RgbOrder::Bgra, | |
| 49 | - }; | |
| 50 | - let meta = FrameMetadata { | |
| 51 | - timestamp: index as i64, | |
| 52 | - force_keyframe: index == 0, | |
| 53 | - }; | |
| 54 | - coded.push(encoder.encode_rgb(&frame, meta)?); | |
| 55 | - } | |
| 56 | - | |
| 57 | - let mut line = format!("{codec:?} {:?} kb/s per segment:", encoder.backend()); | |
| 58 | - for chunk in coded.chunks(SEGMENT as usize) { | |
| 59 | - let bytes: usize = chunk.iter().map(|c| c.data.len()).sum(); | |
| 60 | - let kbps = bytes as f64 * 8.0 * FPS as f64 / SEGMENT as f64 / 1000.0; | |
| 61 | - line += &format!(" {kbps:.0}"); | |
| 62 | - } | |
| 63 | - let keyframes = coded.iter().filter(|c| c.is_keyframe).count(); | |
| 64 | - println!("{line}, keyframes {keyframes}"); | |
| 65 | - | |
| 66 | - let mut decoder = HwDecoder::open(decode_codec(codec))?; | |
| 67 | - let mut decoded = 0; | |
| 68 | - for c in &coded { | |
| 69 | - decoder.decode(&c.data, c.timestamp)?; | |
| 70 | - while decoder.next_frame()?.is_some() { | |
| 71 | - decoded += 1; | |
| 72 | - } | |
| 73 | - } | |
| 74 | - decoder.flush()?; | |
| 75 | - while decoder.next_frame()?.is_some() { | |
| 76 | - decoded += 1; | |
| 77 | - } | |
| 78 | - println!(" decoded {decoded} of {}", coded.len()); | |
| 79 | - Ok(()) | |
| 80 | -} | |
| 81 | - | |
| 82 | -fn decode_codec(codec: EncCodec) -> Codec { | |
| 83 | - match codec { | |
| 84 | - EncCodec::H264 => Codec::H264, | |
| 85 | - EncCodec::H265 => Codec::H265, | |
| 86 | - EncCodec::Av1 => Codec::Av1, | |
| 87 | - } | |
| 88 | -} | |
| 89 | - | |
| 90 | -fn bgra_gradient(index: u32) -> Vec<u8> { | |
| 91 | - let shift = index as usize * 4; | |
| 92 | - let mut out = Vec::with_capacity(W as usize * H as usize * 4); | |
| 93 | - for y in 0..H as usize { | |
| 94 | - for x in 0..W as usize { | |
| 95 | - let r = (x + shift) & 0xff; | |
| 96 | - let g = (y + 2 * shift) & 0xff; | |
| 97 | - let b = ((x + y) / 2 + 3 * shift) & 0xff; | |
| 98 | - out.extend_from_slice(&[b as u8, g as u8, r as u8, 0xff]); | |
| 99 | - } | |
| 100 | - } | |
| 101 | - out | |
| 102 | -} |
crates/ec-hw/src/enc/headers.rsmodified+0 -1
| @@ -9,7 +9,6 @@ | ||
| 9 | 9 | //! field below therefore has to agree with the `VAEnc*ParameterBuffer` the |
| 10 | 10 | //! driver was given, or the header describes a picture other than the one the |
| 11 | 11 | //! hardware coded. |
| 12 | -#![allow(dead_code)] // parked with the encoder: the writers return when it is ported | |
| 13 | 12 | |
| 14 | 13 | /// `VAEncPackedHeaderSequence`: packed sequence-level header bits. |
| 15 | 14 | pub const PACKED_HEADER_SEQUENCE: u32 = 1; |
crates/ec-hw/src/enc/mod.rsmodified+2 -250
| @@ -34,7 +34,6 @@ | ||
| 34 | 34 | //! are all measured by `gpu.rs`'s `av1_encode_rate_control_lands`, which |
| 35 | 35 | //! prints what each mode delivered against what it was asked for. |
| 36 | 36 | |
| 37 | -#![allow(dead_code)] // the header writers wait for the encoder port | |
| 38 | 37 | |
| 39 | 38 | use std::collections::VecDeque; |
| 40 | 39 | use std::rc::Rc; |
| @@ -49,10 +48,10 @@ use ec_va::va::{ | ||
| 49 | 48 | VA_FOURCC_NV12, VA_FOURCC_P010, VA_RT_FORMAT_YUV420, VA_RT_FORMAT_YUV420_10, |
| 50 | 49 | VA_SURFACE_ATTRIB_USAGE_HINT_ENCODER, VAConfigAttribType, VAImage, |
| 51 | 50 | }; |
| 52 | -use ec_va::{CapReport, Config, ConfigAttrib, Context, Display, Surface, SurfaceSpec, Vpp}; | |
| 51 | +use ec_va::{CapReport, Config, ConfigAttrib, Context, Display, Surface, SurfaceSpec}; | |
| 53 | 52 | |
| 54 | 53 | use crate::error::{Error, Result}; |
| 55 | -use crate::frame::{Frame, I420, I420_16}; | |
| 54 | +use crate::frame::{I420, I420_16}; | |
| 56 | 55 | use crate::pool::{PooledSurface, SurfacePool}; |
| 57 | 56 | use crate::rate::{RATE_WINDOW_MS, RateFeedback, hrd_buffer_ms}; |
| 58 | 57 | |
| @@ -129,17 +128,6 @@ pub struct Encoder { | ||
| 129 | 128 | /// Set when the rate control parameters have to be resent. |
| 130 | 129 | tunings_dirty: bool, |
| 131 | 130 | rc: RateFeedback, |
| 132 | - profile: Profile, | |
| 133 | - /// P010 -> NV12 GPU-resident conversion pipeline for [`Encoder::encode_frame`] | |
| 134 | - /// on a source that is not the encoder's own format or size; built lazily, | |
| 135 | - /// since most encoders never see one. | |
| 136 | - vpp: Option<Vpp>, | |
| 137 | - /// The small pool [`Encoder::vpp`] converts into, round-robined rather | |
| 138 | - /// than pool-acquired: each conversion is fully synced before this | |
| 139 | - /// encoder's own picture submission returns, so two surfaces are enough | |
| 140 | - /// to never hand out one still in flight. | |
| 141 | - vpp_surfaces: Vec<Rc<Surface>>, | |
| 142 | - vpp_next: usize, | |
| 143 | 131 | /// Pictures submitted by [`Encoder::submit`], oldest first, not yet read back. |
| 144 | 132 | pending: VecDeque<InFlight<()>>, |
| 145 | 133 | } |
| @@ -264,10 +252,6 @@ impl Encoder { | ||
| 264 | 252 | idr_count: 0, |
| 265 | 253 | tunings_dirty: true, |
| 266 | 254 | rc: RateFeedback::default(), |
| 267 | - profile, | |
| 268 | - vpp: None, | |
| 269 | - vpp_surfaces: Vec::new(), | |
| 270 | - vpp_next: 0, | |
| 271 | 255 | pending: VecDeque::new(), |
| 272 | 256 | }) |
| 273 | 257 | } |
| @@ -369,36 +353,6 @@ impl Encoder { | ||
| 369 | 353 | } |
| 370 | 354 | } |
| 371 | 355 | |
| 372 | - /// Pipelined encode of an imported surface: a GPU copy into a pool surface | |
| 373 | - /// whose padding is then zeroed, matching the CPU upload path. A surface of | |
| 374 | - /// the coded size is copied whole; any other size is scaled to the | |
| 375 | - /// configured width x height, so one capture can feed several layers. | |
| 376 | - pub fn submit_prime( | |
| 377 | - &mut self, | |
| 378 | - surface: Rc<ec_va::va::Surface<ec_va::surface::PrimeImport>>, | |
| 379 | - meta: FrameMetadata, | |
| 380 | - ) -> Result<Option<CodedFrame>> { | |
| 381 | - let input = self | |
| 382 | - .pool | |
| 383 | - .acquire() | |
| 384 | - .ok_or_else(|| Error::config("submit_prime: every surface is still in use"))?; | |
| 385 | - let dest = if surface.size() == self.coded_size { | |
| 386 | - (0, 0, 0, 0) | |
| 387 | - } else { | |
| 388 | - (0, 0, self.config.width, self.config.height) | |
| 389 | - }; | |
| 390 | - self.vpp()? | |
| 391 | - .convert_region(&surface, (0, 0, 0, 0), Rc::clone(input.surface()), dest)?; | |
| 392 | - zero_padding( | |
| 393 | - self.context.display(), | |
| 394 | - input.surface(), | |
| 395 | - self.config.bit_depth, | |
| 396 | - (self.config.width, self.config.height), | |
| 397 | - self.coded_size, | |
| 398 | - )?; | |
| 399 | - self.push_pipelined(input, meta) | |
| 400 | - } | |
| 401 | - | |
| 402 | 356 | fn retire_oldest(&mut self) -> Result<Option<CodedFrame>> { |
| 403 | 357 | match self.pending.pop_front() { |
| 404 | 358 | Some(f) => self.finish(f).map(Some), |
| @@ -431,72 +385,6 @@ impl Encoder { | ||
| 431 | 385 | self.encode_settled(Rc::clone(input.surface()), meta) |
| 432 | 386 | } |
| 433 | 387 | |
| 434 | - /// Encode a decoded frame's GPU surface directly: no `to_i420` read-back, | |
| 435 | - /// no re-upload, just the decoder's picture handed straight to the | |
| 436 | - /// encoder as its source. This is the path a decode-then-encode pipeline | |
| 437 | - /// (e.g. a transcode) wants — the alternative is a full frame through | |
| 438 | - /// system memory and back for no reason. | |
| 439 | - /// | |
| 440 | - /// A source whose size differs from the encoder's coded size, or whose | |
| 441 | - /// depth differs from the encoder's, goes through the GPU video-processing | |
| 442 | - /// pipeline into an NV12 surface of the encoder's size first. | |
| 443 | - /// | |
| 444 | - /// Refused, rather than silently working around, when: | |
| 445 | - /// - `frame` was decoded on a different [`ec_va::Display`]: a surface id | |
| 446 | - /// only means anything on the display that created it. | |
| 447 | - /// - `frame`'s bit depth is neither 8 nor 10. | |
| 448 | - pub fn encode_frame(&mut self, frame: &Frame, meta: FrameMetadata) -> Result<CodedFrame> { | |
| 449 | - if !self.pending.is_empty() { | |
| 450 | - return Err(Error::config( | |
| 451 | - "encode_frame: pipelined frames pending; call flush first", | |
| 452 | - )); | |
| 453 | - } | |
| 454 | - if frame.bit_depth != 8 && frame.bit_depth != 10 { | |
| 455 | - return Err(Error::unsupported( | |
| 456 | - format!("encode_frame of a {}-bit source", frame.bit_depth), | |
| 457 | - "the VPP conversion this crate builds reads 8-bit NV12 and 10-bit P010 only", | |
| 458 | - )); | |
| 459 | - } | |
| 460 | - if !Rc::ptr_eq(frame.display(), self.context.display()) { | |
| 461 | - return Err(Error::config( | |
| 462 | - "encode_frame: the frame was decoded on a different Display than this encoder", | |
| 463 | - )); | |
| 464 | - } | |
| 465 | - let source = | |
| 466 | - if frame.bit_depth != self.config.bit_depth || frame.coded_size != self.coded_size { | |
| 467 | - self.vpp_into_pool(frame.surface(), frame.display_size)? | |
| 468 | - } else { | |
| 469 | - Rc::clone(frame.surface()) | |
| 470 | - }; | |
| 471 | - self.encode_settled(source, meta) | |
| 472 | - } | |
| 473 | - | |
| 474 | - /// Encode a surface imported with [`ec_va::Surface::import_prime`] or | |
| 475 | - /// decoded elsewhere on this encoder's display: read by the GPU in place. | |
| 476 | - /// | |
| 477 | - /// The surface must be NV12, since H.264 is 8-bit only. A surface of another | |
| 478 | - /// size goes through the same GPU conversion as [`Encoder::encode_frame`]; | |
| 479 | - /// `display_size` is the picture's visible size (its cropped size, when the | |
| 480 | - /// surface is padded to the codec's block size). | |
| 481 | - pub fn encode_surface<D: SurfaceMemoryDescriptor>( | |
| 482 | - &mut self, | |
| 483 | - surface: &Rc<ec_va::va::Surface<D>>, | |
| 484 | - display_size: (u32, u32), | |
| 485 | - meta: FrameMetadata, | |
| 486 | - ) -> Result<CodedFrame> { | |
| 487 | - if !self.pending.is_empty() { | |
| 488 | - return Err(Error::config( | |
| 489 | - "encode_surface: pipelined frames pending; call flush first", | |
| 490 | - )); | |
| 491 | - } | |
| 492 | - if surface.size() != self.coded_size { | |
| 493 | - let converted = self.vpp_into_pool(surface, display_size)?; | |
| 494 | - self.encode_settled(converted, meta) | |
| 495 | - } else { | |
| 496 | - self.encode_settled(Rc::clone(surface), meta) | |
| 497 | - } | |
| 498 | - } | |
| 499 | - | |
| 500 | 388 | fn check_size(&self, width: u32, height: u32) -> Result<()> { |
| 501 | 389 | if width != self.config.width || height != self.config.height { |
| 502 | 390 | return Err(Error::config(format!( |
| @@ -507,50 +395,6 @@ impl Encoder { | ||
| 507 | 395 | Ok(()) |
| 508 | 396 | } |
| 509 | 397 | |
| 510 | - /// Place a source surface's visible rect into this encoder's coded size, | |
| 511 | - /// in NV12, on the GPU: a whole-surface convert when the source is | |
| 512 | - /// already the encoder's coded size, a region copy/convert otherwise. | |
| 513 | - /// Builds the VPP pipeline and its two-surface pool on first use, painting | |
| 514 | - /// the pool black so any padding beyond `display_size` a region copy never | |
| 515 | - /// touches is deterministic. | |
| 516 | - fn vpp(&mut self) -> Result<&Vpp> { | |
| 517 | - if self.vpp.is_none() { | |
| 518 | - let spec = surface_spec(self.config.bit_depth, self.coded_size); | |
| 519 | - let display = Rc::clone(self.context.display()); | |
| 520 | - let surfaces = ec_va::create_pool(&display, &spec, 2)?; | |
| 521 | - for s in &surfaces { | |
| 522 | - fill_black(&display, s, self.coded_size, self.config.bit_depth)?; | |
| 523 | - } | |
| 524 | - let vpp = Vpp::new( | |
| 525 | - &display, | |
| 526 | - VA_RT_FORMAT_YUV420 | VA_RT_FORMAT_YUV420_10, | |
| 527 | - self.coded_size.0, | |
| 528 | - self.coded_size.1, | |
| 529 | - )?; | |
| 530 | - self.vpp_surfaces = surfaces.into_iter().map(Rc::new).collect(); | |
| 531 | - self.vpp = Some(vpp); | |
| 532 | - } | |
| 533 | - Ok(self.vpp.as_ref().expect("just built above if it was None")) | |
| 534 | - } | |
| 535 | - | |
| 536 | - fn vpp_into_pool<D: SurfaceMemoryDescriptor>( | |
| 537 | - &mut self, | |
| 538 | - source: &ec_va::va::Surface<D>, | |
| 539 | - display_size: (u32, u32), | |
| 540 | - ) -> Result<Rc<Surface>> { | |
| 541 | - self.vpp()?; | |
| 542 | - let dest = Rc::clone(&self.vpp_surfaces[self.vpp_next]); | |
| 543 | - self.vpp_next = (self.vpp_next + 1) % self.vpp_surfaces.len(); | |
| 544 | - let whole = display_size == self.coded_size; | |
| 545 | - let vpp = self.vpp()?; | |
| 546 | - if whole { | |
| 547 | - Ok(vpp.convert(source, dest)?) | |
| 548 | - } else { | |
| 549 | - let rect = (0, 0, display_size.0, display_size.1); | |
| 550 | - Ok(vpp.convert_region(source, rect, dest, rect)?) | |
| 551 | - } | |
| 552 | - } | |
| 553 | - | |
| 554 | 398 | /// Shared synchronous path for [`Encoder::encode`], [`Encoder::encode_frame`] |
| 555 | 399 | /// and [`Encoder::encode_surface`]: submit, then read back at once. |
| 556 | 400 | fn encode_settled<D: SurfaceMemoryDescriptor>( |
| @@ -763,10 +607,6 @@ impl Encoder { | ||
| 763 | 607 | Ok(()) |
| 764 | 608 | } |
| 765 | 609 | |
| 766 | - pub(crate) fn context(&self) -> &Rc<Context> { | |
| 767 | - &self.context | |
| 768 | - } | |
| 769 | - | |
| 770 | 610 | pub(crate) fn config(&self) -> &EncoderConfig { |
| 771 | 611 | &self.config |
| 772 | 612 | } |
| @@ -785,10 +625,6 @@ impl Encoder { | ||
| 785 | 625 | self.idr_count |
| 786 | 626 | } |
| 787 | 627 | |
| 788 | - /// The VA profile this encoder was configured with. | |
| 789 | - pub fn profile(&self) -> Profile { | |
| 790 | - self.profile | |
| 791 | - } | |
| 792 | 628 | } |
| 793 | 629 | |
| 794 | 630 | /// The surface format an encoder of `bit_depth` works in. |
| @@ -869,86 +705,12 @@ fn upload(context: &Rc<Context>, frame: &I420, surface: &Surface, coded: (u32, u | ||
| 869 | 705 | }) |
| 870 | 706 | } |
| 871 | 707 | |
| 872 | -/// Paint an NV12 surface black (Y=16, chroma=128, TV-range neutral): the | |
| 873 | -/// one-time initialisation [`Encoder::vpp_into_pool`] gives its pool so a | |
| 874 | -/// region copy's untouched padding reads the same deterministic value on | |
| 875 | -/// every driver instead of whatever the fresh allocation contained. | |
| 876 | -fn fill_black(display: &Display, surface: &Surface, size: (u32, u32), bit_depth: u8) -> Result<()> { | |
| 877 | - write_surface(display, surface, fourcc(bit_depth), size, |layout, data| { | |
| 878 | - // P010 carries the sample in the top ten bits, so black is the 8-bit | |
| 879 | - // value shifted up by six, little endian. | |
| 880 | - let samples = |eight: u8| -> Vec<u8> { | |
| 881 | - if bit_depth == 8 { | |
| 882 | - vec![eight] | |
| 883 | - } else { | |
| 884 | - (u16::from(eight) << 6).to_le_bytes().to_vec() | |
| 885 | - } | |
| 886 | - }; | |
| 887 | - for (plane, value, rows) in [ | |
| 888 | - (0usize, 16u8, size.1 as usize), | |
| 889 | - (1, 128, size.1 as usize / 2), | |
| 890 | - ] { | |
| 891 | - let pitch = layout.pitches[plane] as usize; | |
| 892 | - let base = layout.offsets[plane] as usize; | |
| 893 | - let unit = samples(value); | |
| 894 | - let width = size.0 as usize * unit.len(); | |
| 895 | - for row in 0..rows { | |
| 896 | - let start = base + row * pitch; | |
| 897 | - if let Some(line) = data.get_mut(start..start + width) { | |
| 898 | - for px in line.chunks_exact_mut(unit.len()) { | |
| 899 | - px.copy_from_slice(&unit); | |
| 900 | - } | |
| 901 | - } | |
| 902 | - } | |
| 903 | - } | |
| 904 | - }) | |
| 905 | -} | |
| 906 | - | |
| 907 | 708 | fn fill_zero(display: &Display, surface: &Surface, size: (u32, u32), bit_depth: u8) -> Result<()> { |
| 908 | 709 | write_surface(display, surface, fourcc(bit_depth), size, |_, data| { |
| 909 | 710 | data.fill(0) |
| 910 | 711 | }) |
| 911 | 712 | } |
| 912 | 713 | |
| 913 | -fn zero_padding<D: SurfaceMemoryDescriptor>( | |
| 914 | - display: &Display, | |
| 915 | - surface: &ec_va::va::Surface<D>, | |
| 916 | - bit_depth: u8, | |
| 917 | - (w, h): (u32, u32), | |
| 918 | - coded: (u32, u32), | |
| 919 | -) -> Result<()> { | |
| 920 | - if (w, h) == coded { | |
| 921 | - return Ok(()); | |
| 922 | - } | |
| 923 | - let (fourcc, px) = if bit_depth > 8 { | |
| 924 | - (VA_FOURCC_P010, 2) | |
| 925 | - } else { | |
| 926 | - (VA_FOURCC_NV12, 1) | |
| 927 | - }; | |
| 928 | - let (w, h, cw, ch) = ( | |
| 929 | - w as usize * px, | |
| 930 | - h as usize, | |
| 931 | - coded.0 as usize * px, | |
| 932 | - coded.1 as usize, | |
| 933 | - ); | |
| 934 | - write_surface(display, surface, fourcc, coded, |layout, data| { | |
| 935 | - for (plane, rows, last, start) in [ | |
| 936 | - (0, h, ch, w), | |
| 937 | - (1, h.div_ceil(2), ch / 2, w.next_multiple_of(2 * px)), | |
| 938 | - ] { | |
| 939 | - let pitch = layout.pitches[plane] as usize; | |
| 940 | - let base = layout.offsets[plane] as usize; | |
| 941 | - for row in 0..last { | |
| 942 | - let from = if row < rows { start } else { 0 }; | |
| 943 | - if let Some(dst) = data.get_mut(base + row * pitch + from..base + row * pitch + cw) | |
| 944 | - { | |
| 945 | - dst.fill(0); | |
| 946 | - } | |
| 947 | - } | |
| 948 | - } | |
| 949 | - }) | |
| 950 | -} | |
| 951 | - | |
| 952 | 714 | /// Upload one 10-bit frame into a surface as P010: samples move from the low |
| 953 | 715 | /// ten bits of the caller's `u16` into P010's top ten. |
| 954 | 716 | fn upload_16( |
| @@ -989,13 +751,3 @@ fn upload_16( | ||
| 989 | 751 | } |
| 990 | 752 | }) |
| 991 | 753 | } |
| 992 | - | |
| 993 | -#[cfg(test)] | |
| 994 | -mod tests { | |
| 995 | - use super::*; | |
| 996 | - | |
| 997 | - #[test] | |
| 998 | - fn default_profile_is_high() { | |
| 999 | - assert_eq!(H264Profile::default(), H264Profile::High); | |
| 1000 | - } | |
| 1001 | -} |
crates/ec-hw/src/frame.rsmodified+0 -5
| @@ -72,11 +72,6 @@ impl Frame { | ||
| 72 | 72 | &self.surface |
| 73 | 73 | } |
| 74 | 74 | |
| 75 | - /// The display the surface was created on. | |
| 76 | - pub(crate) fn display(&self) -> &Rc<Display> { | |
| 77 | - &self.display | |
| 78 | - } | |
| 79 | - | |
| 80 | 75 | /// This frame's colour metadata, when the codec's decoder resolves one. |
| 81 | 76 | pub fn colour(&self) -> Option<Colour> { |
| 82 | 77 | self.colour |
crates/ec-hw/src/hw.rsmodified+1 -38
| @@ -12,8 +12,6 @@ use std::collections::VecDeque; | ||
| 12 | 12 | use crate::error::{Error, Result}; |
| 13 | 13 | use crate::output::HwPicture; |
| 14 | 14 | use crate::picture::{I420, I420_16, RgbPicture}; |
| 15 | -#[cfg(target_os = "linux")] | |
| 16 | -use crate::picture::DmaBufPicture; | |
| 17 | 15 | use crate::rate::{RateFeedback, hrd_buffer_ms}; |
| 18 | 16 | use crate::types::{ |
| 19 | 17 | Codec, CodedFrame, EncCodec, EncoderConfig, FrameMetadata, H264Profile, RateControlMode, |
| @@ -129,14 +127,7 @@ fn vk_grace() -> Result<()> { | ||
| 129 | 127 | pub fn capabilities() -> Vec<Capability> { |
| 130 | 128 | let mut out = Vec::new(); |
| 131 | 129 | if let Some(gpu) = vk_gpu() { |
| 132 | - for caps in gpu.caps().into_iter().filter(|c| { | |
| 133 | - c.direction == ec_vk::Direction::Encode | |
| 134 | - || (c.direction == ec_vk::Direction::Decode | |
| 135 | - && matches!( | |
| 136 | - c.codec, | |
| 137 | - ec_vk::Codec::H264 | ec_vk::Codec::H265 | ec_vk::Codec::Av1 | ec_vk::Codec::Vp9 | |
| 138 | - )) | |
| 139 | - }) { | |
| 130 | + for caps in gpu.caps() { | |
| 140 | 131 | let codec = match caps.codec { |
| 141 | 132 | ec_vk::Codec::H264 => Codec::H264, |
| 142 | 133 | ec_vk::Codec::H265 => Codec::H265, |
| @@ -1207,17 +1198,6 @@ impl HwDecoder { | ||
| 1207 | 1198 | HwDecoder::open_with(codec, Some(output)) |
| 1208 | 1199 | } |
| 1209 | 1200 | |
| 1210 | - /// Same as [`HwDecoder::open`]: every picture can be asked for 10-bit I420 with [`HwPicture::to_i420_16`]. | |
| 1211 | - pub fn open_16(codec: Codec) -> Result<HwDecoder> { | |
| 1212 | - HwDecoder::open(codec) | |
| 1213 | - } | |
| 1214 | - | |
| 1215 | - /// Same as [`HwDecoder::open`]: every picture can be asked for DMA-BUF file descriptors with [`HwPicture::export_dmabuf`]. Linux only. | |
| 1216 | - #[cfg(target_os = "linux")] | |
| 1217 | - pub fn open_dmabuf(codec: Codec) -> Result<HwDecoder> { | |
| 1218 | - HwDecoder::open(codec) | |
| 1219 | - } | |
| 1220 | - | |
| 1221 | 1201 | fn open_with(codec: Codec, rgb: Option<RgbOutput>) -> Result<HwDecoder> { |
| 1222 | 1202 | let mut reasons = Vec::new(); |
| 1223 | 1203 | let born_epoch = crate::reset::gpu_reset_epoch(); |
| @@ -1310,23 +1290,6 @@ impl HwDecoder { | ||
| 1310 | 1290 | } |
| 1311 | 1291 | } |
| 1312 | 1292 | |
| 1313 | - /// The next picture in display order, as 10-bit I420 with its timestamp. | |
| 1314 | - pub fn next_frame_16(&mut self) -> Result<Option<(i64, I420_16)>> { | |
| 1315 | - match self.pull()? { | |
| 1316 | - None => Ok(None), | |
| 1317 | - Some(picture) => Ok(Some((picture.timestamp, picture.to_i420_16()?))), | |
| 1318 | - } | |
| 1319 | - } | |
| 1320 | - | |
| 1321 | - /// The next picture in display order, as DMA-BUF file descriptors with its timestamp. Linux only. | |
| 1322 | - #[cfg(target_os = "linux")] | |
| 1323 | - pub fn next_dmabuf(&mut self) -> Result<Option<(i64, DmaBufPicture)>> { | |
| 1324 | - match self.pull()? { | |
| 1325 | - None => Ok(None), | |
| 1326 | - Some(picture) => Ok(Some((picture.timestamp, picture.export_dmabuf()?))), | |
| 1327 | - } | |
| 1328 | - } | |
| 1329 | - | |
| 1330 | 1293 | /// The next picture in display order, as packed RGB with its timestamp. An error on a decoder not opened with [`HwDecoder::open_rgb`]. |
| 1331 | 1294 | pub fn next_rgb(&mut self) -> Result<Option<(i64, RgbPicture)>> { |
| 1332 | 1295 | let mut dst = RgbPicture::default(); |
crates/ec-hw/tests/common/mod.rsadded+13 -0
| @@ -0,0 +1,13 @@ | ||
| 1 | +use std::rc::Rc; | |
| 2 | + | |
| 3 | +use ec_va::Display; | |
| 4 | + | |
| 5 | +pub fn display() -> Option<Rc<Display>> { | |
| 6 | + match ec_va::open() { | |
| 7 | + Ok(display) => Some(display), | |
| 8 | + Err(e) => { | |
| 9 | + eprintln!("skipped: no VA display ({e})"); | |
| 10 | + None | |
| 11 | + } | |
| 12 | + } | |
| 13 | +} |
crates/ec-hw/tests/film_grain.rsmodified+3 -9
| @@ -14,18 +14,12 @@ use std::rc::Rc; | ||
| 14 | 14 | use ec_hw::{Codec, Decoder, I420}; |
| 15 | 15 | use ec_va::Display; |
| 16 | 16 | |
| 17 | +mod common; | |
| 18 | +use common::display; | |
| 19 | + | |
| 17 | 20 | /// Frames in the grain fixture (every one of them is shown). |
| 18 | 21 | const FRAMES: usize = 90; |
| 19 | 22 | |
| 20 | -fn display() -> Option<Rc<Display>> { | |
| 21 | - match ec_va::open() { | |
| 22 | - Ok(display) => Some(display), | |
| 23 | - Err(e) => { | |
| 24 | - eprintln!("skipped: no VA display ({e})"); | |
| 25 | - None | |
| 26 | - } | |
| 27 | - } | |
| 28 | -} | |
| 29 | 23 | |
| 30 | 24 | /// Split an IVF container into its frames (temporal units). |
| 31 | 25 | fn split_ivf(data: &[u8]) -> Vec<&[u8]> { |
crates/ec-hw/tests/gpu.rsmodified+10 -2049
Diff too large; view file
| @@ -8,29 +8,22 @@ | ||
| 8 | 8 | |
| 9 | 9 | use std::io::Read; |
| 10 | 10 | use std::path::{Path, PathBuf}; |
| 11 | -use std::process::{Command, Stdio}; | |
| 11 | +use std::process::Stdio; | |
| 12 | 12 | use std::rc::Rc; |
| 13 | -use std::time::Instant; | |
| 14 | 13 | |
| 15 | 14 | use ec_hw::{ |
| 16 | - Codec, Decoder, EncCodec, Encoder, EncoderConfig, Frame, FrameMetadata, H264Profile, I420, | |
| 15 | + Codec, Decoder, EncCodec, Encoder, EncoderConfig, Frame, FrameMetadata, I420, | |
| 17 | 16 | I420_16, RateControlMode, |
| 18 | 17 | }; |
| 19 | 18 | use ec_va::Display; |
| 20 | 19 | |
| 20 | +mod common; | |
| 21 | +use common::display; | |
| 22 | + | |
| 21 | 23 | /// Frames compared per fixture: enough to cover several GOPs and any |
| 22 | 24 | /// reordering, few enough to keep the suite under a minute. |
| 23 | 25 | const FRAMES: usize = 24; |
| 24 | 26 | |
| 25 | -fn display() -> Option<Rc<Display>> { | |
| 26 | - match ec_va::open() { | |
| 27 | - Ok(display) => Some(display), | |
| 28 | - Err(e) => { | |
| 29 | - eprintln!("skipped: no VA display ({e})"); | |
| 30 | - None | |
| 31 | - } | |
| 32 | - } | |
| 33 | -} | |
| 34 | 27 | |
| 35 | 28 | /// The software reference: ffmpeg decoding the same file to raw planes. |
| 36 | 29 | struct Reference { |
| @@ -378,25 +371,6 @@ fn ten_bit(pattern: &str, codec: &str) -> Vec<PathBuf> { | ||
| 378 | 371 | .collect() |
| 379 | 372 | } |
| 380 | 373 | |
| 381 | -/// The selection must not depend on where the repository is checked out. | |
| 382 | -#[test] | |
| 383 | -fn fixture_selection_ignores_the_checkout_path() { | |
| 384 | - for p in eight_bit("ivf", "av1") { | |
| 385 | - let name = name_of(&p); | |
| 386 | - assert!( | |
| 387 | - name.starts_with("av1") && !name.contains("10bit"), | |
| 388 | - "{name} is not an 8-bit AV1 fixture" | |
| 389 | - ); | |
| 390 | - } | |
| 391 | - for p in ten_bit("ivf", "vp9") { | |
| 392 | - let name = name_of(&p); | |
| 393 | - assert!( | |
| 394 | - name.starts_with("vp9") && name.contains("10bit"), | |
| 395 | - "{name} is not a 10-bit VP9 fixture" | |
| 396 | - ); | |
| 397 | - } | |
| 398 | -} | |
| 399 | - | |
| 400 | 374 | #[test] |
| 401 | 375 | fn h264_matches_ffmpeg() { |
| 402 | 376 | compare_against_ffmpeg(&ec_testkit::fixtures("bitstreams", "264"), Codec::H264, false); |
| @@ -430,68 +404,11 @@ fn hevc_10bit_decodes_to_p010() { | ||
| 430 | 404 | compare_against_ffmpeg(&files, Codec::H265, true); |
| 431 | 405 | } |
| 432 | 406 | |
| 433 | -#[test] | |
| 434 | -fn vp9_matches_ffmpeg() { | |
| 435 | - compare_against_ffmpeg(&eight_bit("ivf", "vp9"), Codec::Vp9, false); | |
| 436 | -} | |
| 437 | - | |
| 438 | -#[test] | |
| 439 | -fn vp9_10bit_matches_ffmpeg() { | |
| 440 | - compare_against_ffmpeg(&ten_bit("ivf", "vp9"), Codec::Vp9, true); | |
| 441 | -} | |
| 442 | - | |
| 443 | 407 | #[test] |
| 444 | 408 | fn av1_matches_ffmpeg() { |
| 445 | 409 | compare_against_ffmpeg(&eight_bit("ivf", "av1"), Codec::Av1, false); |
| 446 | 410 | } |
| 447 | 411 | |
| 448 | -#[test] | |
| 449 | -fn av1_10bit_matches_ffmpeg() { | |
| 450 | - compare_against_ffmpeg(&ten_bit("ivf", "av1"), Codec::Av1, true); | |
| 451 | -} | |
| 452 | - | |
| 453 | -/// Every "not supported" this crate says has to be a fact about the driver, not | |
| 454 | -/// a string. This GPU decodes VP9 profiles 0 and 2 and AV1 profiles 0 and 2 — | |
| 455 | -/// so the 4:4:4 fixtures must come back as a typed refusal naming the profile, | |
| 456 | -/// and the capability report must agree that the profile is absent. | |
| 457 | -#[test] | |
| 458 | -fn unsupported_profiles_are_refused_with_a_reason() { | |
| 459 | - let Some(display) = display() else { return }; | |
| 460 | - let caps = ec_va::CapReport::probe(&display).expect("caps probe"); | |
| 461 | - for (file, codec, absent) in [ | |
| 462 | - ( | |
| 463 | - "vp9-profile1-444.ivf", | |
| 464 | - Codec::Vp9, | |
| 465 | - ec_va::caps::Profile::VP9Profile1, | |
| 466 | - ), | |
| 467 | - ( | |
| 468 | - "av1-profile1-444.ivf", | |
| 469 | - Codec::Av1, | |
| 470 | - ec_va::caps::Profile::AV1Profile1, | |
| 471 | - ), | |
| 472 | - ] { | |
| 473 | - let path = ec_testkit::fixture(&format!("bitstreams/{file}")); | |
| 474 | - assert!( | |
| 475 | - !caps.supports(absent, ec_va::caps::Entrypoint::VLD), | |
| 476 | - "{absent:?} is in fact supported — the refusal below would be a bug" | |
| 477 | - ); | |
| 478 | - let data = std::fs::read(&path).expect("fixture is readable"); | |
| 479 | - let mut decoder = Decoder::new(&display, codec).expect("decoder opens"); | |
| 480 | - let err = decode_stream(&mut decoder, codec, &data, 1, |_| {}) | |
| 481 | - .expect_err("a 4:4:4 stream must be refused"); | |
| 482 | - let message = err.to_string(); | |
| 483 | - assert!( | |
| 484 | - matches!(err, ec_hw::Error::Unsupported { .. }), | |
| 485 | - "{file}: expected a typed refusal, got {message}" | |
| 486 | - ); | |
| 487 | - println!("{file}: {message}"); | |
| 488 | - } | |
| 489 | -} | |
| 490 | - | |
| 491 | -// --------------------------------------------------------------------------- | |
| 492 | -// Encoding | |
| 493 | -// --------------------------------------------------------------------------- | |
| 494 | - | |
| 495 | 412 | /// A moving synthetic frame: a gradient with a box that travels, so motion |
| 496 | 413 | /// compensation has something to find and a static-image encoder cannot cheat. |
| 497 | 414 | fn source_frame(width: u32, height: u32, t: u32) -> I420 { |
| @@ -629,383 +546,11 @@ fn h264_encode_round_trips_through_ffmpeg() { | ||
| 629 | 546 | round_trip(EncCodec::H264, 640, 480, 30.0); |
| 630 | 547 | } |
| 631 | 548 | |
| 632 | -/// Each selectable H.264 profile: the driver encodes it, ffprobe reports the | |
| 633 | -/// profile the SPS signals, and ffmpeg decodes the stream with no error output | |
| 634 | -/// and the picture matches the source. | |
| 635 | -fn h264_profile_round_trip(profile: H264Profile, ffprobe_name: &str) { | |
| 636 | - let Some(display) = display() else { return }; | |
| 637 | - let (width, height, frames) = (640u32, 480u32, 12u32); | |
| 638 | - let mut config = EncoderConfig::new(EncCodec::H264, width, height).h264_profile(profile); | |
| 639 | - config.gop_size = 30; | |
| 640 | - config.rate_control = RateControlMode::ConstantQp { qp: 26 }; | |
| 641 | - let mut encoder = Encoder::new(&display, config).expect("encoder"); | |
| 642 | - let mut stream = Vec::new(); | |
| 643 | - for t in 0..frames { | |
| 644 | - let coded = encoder | |
| 645 | - .encode( | |
| 646 | - &source_frame(width, height, t), | |
| 647 | - FrameMetadata { | |
| 648 | - timestamp: i64::from(t), | |
| 649 | - force_keyframe: false, | |
| 650 | - }, | |
| 651 | - ) | |
| 652 | - .expect("encode"); | |
| 653 | - stream.extend_from_slice(&coded.data); | |
| 654 | - } | |
| 655 | - | |
| 656 | - let dir = std::env::temp_dir().join(format!("ec-hw-h264-{profile:?}")); | |
| 657 | - std::fs::create_dir_all(&dir).expect("temp dir"); | |
| 658 | - let path = dir.join("out.264"); | |
| 659 | - std::fs::write(&path, &stream).expect("write bitstream"); | |
| 660 | - | |
| 661 | - let probe = ec_testkit::ffprobe() | |
| 662 | - .args([ | |
| 663 | - "-v", | |
| 664 | - "error", | |
| 665 | - "-select_streams", | |
| 666 | - "v:0", | |
| 667 | - "-show_entries", | |
| 668 | - "stream=profile", | |
| 669 | - "-of", | |
| 670 | - "csv=p=0", | |
| 671 | - ]) | |
| 672 | - .arg(&path) | |
| 673 | - .output() | |
| 674 | - .expect("ffprobe runs"); | |
| 675 | - let got = String::from_utf8_lossy(&probe.stdout).trim().to_string(); | |
| 676 | - assert_eq!( | |
| 677 | - got, ffprobe_name, | |
| 678 | - "{profile:?}: ffprobe reads the SPS profile" | |
| 679 | - ); | |
| 680 | - | |
| 681 | - // Strict decode: any warning or error on stderr fails the test. | |
| 682 | - let decode = ec_testkit::ffmpeg() | |
| 683 | - .args(["-nostdin", "-v", "warning", "-i"]) | |
| 684 | - .arg(&path) | |
| 685 | - .args(["-f", "null", "-"]) | |
| 686 | - .output() | |
| 687 | - .expect("ffmpeg runs"); | |
| 688 | - assert!( | |
| 689 | - decode.status.success() && decode.stderr.is_empty(), | |
| 690 | - "{profile:?}: ffmpeg reports {}", | |
| 691 | - String::from_utf8_lossy(&decode.stderr) | |
| 692 | - ); | |
| 693 | - | |
| 694 | - let mut reference = Reference::open(&path, width, height, false).expect("ffmpeg runs"); | |
| 695 | - let mut worst = f64::INFINITY; | |
| 696 | - for t in 0..frames { | |
| 697 | - let got = reference.next(width, height).expect("decoded picture"); | |
| 698 | - worst = worst.min(psnr( | |
| 699 | - &got, | |
| 700 | - &Planes::from_8bit(&source_frame(width, height, t)), | |
| 701 | - )); | |
| 702 | - } | |
| 703 | - println!("{profile:?}: {} bytes, worst {worst:.1} dB", stream.len()); | |
| 704 | - assert!(worst >= 30.0, "{profile:?}: worst frame {worst:.1} dB"); | |
| 705 | -} | |
| 706 | - | |
| 707 | -#[test] | |
| 708 | -fn h264_constrained_baseline_encodes_and_decodes() { | |
| 709 | - h264_profile_round_trip(H264Profile::ConstrainedBaseline, "Constrained Baseline"); | |
| 710 | -} | |
| 711 | - | |
| 712 | -#[test] | |
| 713 | -fn h264_main_profile_has_no_high_syntax_and_decodes() { | |
| 714 | - h264_profile_round_trip(H264Profile::Main, "Main"); | |
| 715 | -} | |
| 716 | - | |
| 717 | -#[test] | |
| 718 | -fn h264_high_profile_still_decodes() { | |
| 719 | - h264_profile_round_trip(H264Profile::High, "High"); | |
| 720 | -} | |
| 721 | - | |
| 722 | 549 | #[test] |
| 723 | 550 | fn hevc_encode_round_trips_through_ffmpeg() { |
| 724 | 551 | round_trip(EncCodec::H265, 640, 480, 30.0); |
| 725 | 552 | } |
| 726 | 553 | |
| 727 | -/// 1916x1080 is the shape that broke the incumbent HEVC encoder: the coded size | |
| 728 | -/// is 1920x1088, and only the conformance window brings it back. | |
| 729 | -#[test] | |
| 730 | -fn hevc_encode_honours_the_conformance_window() { | |
| 731 | - round_trip(EncCodec::H265, 1916, 1080, 30.0); | |
| 732 | -} | |
| 733 | - | |
| 734 | -/// What this crate encodes, its own hardware decoder must decode. | |
| 735 | -#[test] | |
| 736 | -fn our_encoder_and_our_decoder_agree() { | |
| 737 | - let Some(display) = display() else { return }; | |
| 738 | - for (enc, dec) in [(EncCodec::H264, Codec::H264), (EncCodec::H265, Codec::H265)] { | |
| 739 | - let stream = encode_stream(&display, enc, 640, 480, 12).expect("encode"); | |
| 740 | - let mut decoder = Decoder::new(&display, dec).expect("decoder opens"); | |
| 741 | - let mut worst = f64::INFINITY; | |
| 742 | - let mut count = 0u32; | |
| 743 | - decode_stream(&mut decoder, dec, &stream, 12, |frame| { | |
| 744 | - let got = Planes::from_8bit(&frame.to_i420().expect("readback")); | |
| 745 | - let want = Planes::from_8bit(&source_frame(640, 480, count)); | |
| 746 | - worst = worst.min(psnr(&got, &want)); | |
| 747 | - count += 1; | |
| 748 | - }) | |
| 749 | - .expect("decode"); | |
| 750 | - assert_eq!(count, 12, "{enc:?}: decoded {count} of 12 frames"); | |
| 751 | - println!("{enc:?} -> our decoder: {count} frames, worst {worst:.1} dB vs source"); | |
| 752 | - assert!(worst >= 30.0, "{enc:?}: worst {worst:.1} dB"); | |
| 753 | - } | |
| 754 | -} | |
| 755 | - | |
| 756 | -/// A decoded surface goes straight into an encoder with no `to_i420` | |
| 757 | -/// read-back, and what comes out is not measurably different from the | |
| 758 | -/// CPU-path baseline (decode -> `to_i420` -> `encode`) of the same frames. | |
| 759 | -/// | |
| 760 | -/// 1920x1080 is the size on purpose: H.264's 16-block and HEVC's 32-block | |
| 761 | -/// rounding both land on the same 1920x1088 coded size for it, so the | |
| 762 | -/// decoder's surfaces satisfy `encode_frame`'s coded-size check against | |
| 763 | -/// either target codec without a second fixture. | |
| 764 | -#[test] | |
| 765 | -fn encode_frame_zero_copy_matches_the_cpu_path() { | |
| 766 | - let Some(display) = display() else { return }; | |
| 767 | - let (width, height) = (1920u32, 1080u32); | |
| 768 | - let path = ec_testkit::fixture("bitstreams/h264-1080p-23.976-8bit.264"); | |
| 769 | - let data = std::fs::read(&path).expect("fixture is readable"); | |
| 770 | - let frames = 10usize; | |
| 771 | - | |
| 772 | - for (target, dec_codec) in [(EncCodec::H264, Codec::H264), (EncCodec::H265, Codec::H265)] { | |
| 773 | - let mut cfg = EncoderConfig::new(target, width, height); | |
| 774 | - cfg.gop_size = 30; | |
| 775 | - cfg.rate_control = RateControlMode::ConstantQp { qp: 22 }; | |
| 776 | - let mut zero_copy = Encoder::new(&display, cfg).expect("zero-copy encoder opens"); | |
| 777 | - let mut cpu_path = Encoder::new(&display, cfg).expect("cpu-path encoder opens"); | |
| 778 | - let mut zc_stream = Vec::new(); | |
| 779 | - let mut cpu_stream = Vec::new(); | |
| 780 | - let mut count = 0i64; | |
| 781 | - | |
| 782 | - let mut decoder = Decoder::new(&display, Codec::H264).expect("decoder opens"); | |
| 783 | - decode_stream(&mut decoder, Codec::H264, &data, frames, |frame| { | |
| 784 | - let meta = FrameMetadata { | |
| 785 | - timestamp: count, | |
| 786 | - force_keyframe: false, | |
| 787 | - }; | |
| 788 | - // The zero-copy path never reads the surface back to the CPU: the | |
| 789 | - // only `to_i420` call in this loop is the CPU-path baseline's. | |
| 790 | - let zc = zero_copy | |
| 791 | - .encode_frame(&frame, meta) | |
| 792 | - .expect("encode_frame (zero copy)"); | |
| 793 | - zc_stream.extend_from_slice(&zc.data); | |
| 794 | - let i420 = frame.to_i420().expect("readback for the CPU-path baseline"); | |
| 795 | - let cpu = cpu_path.encode(&i420, meta).expect("encode (CPU path)"); | |
| 796 | - cpu_stream.extend_from_slice(&cpu.data); | |
| 797 | - count += 1; | |
| 798 | - }) | |
| 799 | - .expect("decode"); | |
| 800 | - assert_eq!( | |
| 801 | - count as usize, frames, | |
| 802 | - "{target:?}: decoded {count} of {frames}" | |
| 803 | - ); | |
| 804 | - | |
| 805 | - let ext = match target { | |
| 806 | - EncCodec::H264 => "264", | |
| 807 | - EncCodec::H265 => "265", | |
| 808 | - EncCodec::Av1 => unreachable!("AV1 is not in this test's target list"), | |
| 809 | - }; | |
| 810 | - let dir = std::env::temp_dir().join("ec-hw-encode-frame-zero-copy"); | |
| 811 | - std::fs::create_dir_all(&dir).expect("temp dir"); | |
| 812 | - for (name, bytes) in [("zc", &zc_stream), ("cpu", &cpu_stream)] { | |
| 813 | - std::fs::write(dir.join(format!("{name}.{ext}")), bytes).expect("write bitstream"); | |
| 814 | - } | |
| 815 | - | |
| 816 | - let mut zc_decoder = Decoder::new(&display, dec_codec).expect("zc decoder opens"); | |
| 817 | - let mut cpu_decoder = Decoder::new(&display, dec_codec).expect("cpu decoder opens"); | |
| 818 | - let mut zc_frames = Vec::new(); | |
| 819 | - let mut cpu_frames = Vec::new(); | |
| 820 | - decode_stream(&mut zc_decoder, dec_codec, &zc_stream, frames, |f| { | |
| 821 | - zc_frames.push(Planes::from_8bit(&f.to_i420().expect("readback"))) | |
| 822 | - }) | |
| 823 | - .expect("decode zero-copy stream"); | |
| 824 | - decode_stream(&mut cpu_decoder, dec_codec, &cpu_stream, frames, |f| { | |
| 825 | - cpu_frames.push(Planes::from_8bit(&f.to_i420().expect("readback"))) | |
| 826 | - }) | |
| 827 | - .expect("decode CPU-path stream"); | |
| 828 | - assert_eq!( | |
| 829 | - zc_frames.len(), | |
| 830 | - frames, | |
| 831 | - "{target:?}: zero-copy stream frame count" | |
| 832 | - ); | |
| 833 | - assert_eq!( | |
| 834 | - cpu_frames.len(), | |
| 835 | - frames, | |
| 836 | - "{target:?}: CPU-path stream frame count" | |
| 837 | - ); | |
| 838 | - | |
| 839 | - let worst = zc_frames | |
| 840 | - .iter() | |
| 841 | - .zip(&cpu_frames) | |
| 842 | - .map(|(a, b)| psnr(a, b)) | |
| 843 | - .fold(f64::INFINITY, f64::min); | |
| 844 | - println!("{target:?} encode_frame vs CPU path: worst {worst:.1} dB"); | |
| 845 | - assert!( | |
| 846 | - worst >= 35.0, | |
| 847 | - "{target:?}: worst {worst:.1} dB vs the CPU path" | |
| 848 | - ); | |
| 849 | - } | |
| 850 | -} | |
| 851 | - | |
| 852 | -/// `EncoderConfig::colour` reaches the VUI of both codecs' packed SPS: an | |
| 853 | -/// export with a colour description survives ffprobe reading it back, and | |
| 854 | -/// leaving it unset keeps today's behaviour (no `video_signal_type`, | |
| 855 | -/// deterministically — two encodes of the same picture with no colour set | |
| 856 | -/// come back byte for byte identical). | |
| 857 | -#[test] | |
| 858 | -fn colour_description_reaches_the_vui() { | |
| 859 | - let Some(display) = display() else { return }; | |
| 860 | - let (width, height) = (640u32, 480u32); | |
| 861 | - let dir = std::env::temp_dir().join("ec-hw-colour-vui"); | |
| 862 | - std::fs::create_dir_all(&dir).expect("temp dir"); | |
| 863 | - | |
| 864 | - let encode_one = |colour: Option<(u8, u8, u8, bool)>, name: &str| -> (PathBuf, Vec<u8>) { | |
| 865 | - let mut cfg = EncoderConfig::new(EncCodec::H265, width, height); | |
| 866 | - cfg.rate_control = RateControlMode::ConstantQp { qp: 26 }; | |
| 867 | - if let Some((primaries, transfer, matrix, full_range)) = colour { | |
| 868 | - cfg = cfg.colour(primaries, transfer, matrix, full_range); | |
| 869 | - } | |
| 870 | - let mut enc = Encoder::new(&display, cfg).expect("encoder opens"); | |
| 871 | - let coded = enc | |
| 872 | - .encode( | |
| 873 | - &source_frame(width, height, 0), | |
| 874 | - FrameMetadata { | |
| 875 | - timestamp: 0, | |
| 876 | - force_keyframe: true, | |
| 877 | - }, | |
| 878 | - ) | |
| 879 | - .expect("encode"); | |
| 880 | - let path = dir.join(name); | |
| 881 | - std::fs::write(&path, &coded.data).expect("write bitstream"); | |
| 882 | - (path, coded.data) | |
| 883 | - }; | |
| 884 | - let probe = |path: &Path| -> String { | |
| 885 | - let out = ec_testkit::ffprobe() | |
| 886 | - .args([ | |
| 887 | - "-v", | |
| 888 | - "error", | |
| 889 | - "-select_streams", | |
| 890 | - "v:0", | |
| 891 | - "-show_entries", | |
| 892 | - "stream=color_primaries,color_transfer,color_space", | |
| 893 | - "-of", | |
| 894 | - "csv=p=0", | |
| 895 | - ]) | |
| 896 | - .arg(path) | |
| 897 | - .output() | |
| 898 | - .expect("ffprobe runs"); | |
| 899 | - String::from_utf8_lossy(&out.stdout).trim().to_string() | |
| 900 | - }; | |
| 901 | - | |
| 902 | - // Pinned default case: no colour set, twice, must match exactly. | |
| 903 | - let (default_path, default_bytes) = encode_one(None, "default-a.265"); | |
| 904 | - let (_, default_bytes2) = encode_one(None, "default-b.265"); | |
| 905 | - assert_eq!( | |
| 906 | - default_bytes, default_bytes2, | |
| 907 | - "no colour set: two encodes of the same picture must be byte-identical" | |
| 908 | - ); | |
| 909 | - let default_probe = probe(&default_path); | |
| 910 | - println!("no colour set: ffprobe sees `{default_probe}`"); | |
| 911 | - assert!( | |
| 912 | - !default_probe.contains("bt2020"), | |
| 913 | - "no colour set should not read back as BT.2020: `{default_probe}`" | |
| 914 | - ); | |
| 915 | - | |
| 916 | - // BT.2020 / PQ / BT.2020 non-constant luminance (H.273 9/16/9). | |
| 917 | - let (bt2020_path, _) = encode_one(Some((9, 16, 9, false)), "bt2020.265"); | |
| 918 | - // ffprobe's csv reorders these as color_space,color_transfer,color_primaries | |
| 919 | - // regardless of the -show_entries order given above. | |
| 920 | - let got = probe(&bt2020_path); | |
| 921 | - assert_eq!( | |
| 922 | - got, "bt2020nc,smpte2084,bt2020", | |
| 923 | - "ffprobe on the BT.2020 stream" | |
| 924 | - ); | |
| 925 | -} | |
| 926 | - | |
| 927 | -/// AV1 hardware encode, proved by two independent decoders. | |
| 928 | -/// | |
| 929 | -/// The reconstruction inside the GPU is not observable from here, so what is | |
| 930 | -/// asserted is that the coded stream means the same thing to two decoders that | |
| 931 | -/// share no code: ffmpeg's libdav1d and this family's own `ec-av1`. Every | |
| 932 | -/// shown frame is compared sample for sample — a header field that disagrees | |
| 933 | -/// with what the hardware coded shows up as a mismatch in one of them long | |
| 934 | -/// before it shows up as a quality number. | |
| 935 | -/// | |
| 936 | -/// The path was refused in-tree until 2026-09-07: a probe on 2026-08-14 took | |
| 937 | -/// the GPU down ("the CS has cancelled because the context is lost"). That | |
| 938 | -/// refusal is retired by measurement, not by opinion — ffmpeg's own | |
| 939 | -/// `av1_vaapi` encodes on this driver (mesa 26.1.8, gfx1200), and the | |
| 940 | -/// parameters below are the recipe it uses. | |
| 941 | -#[test] | |
| 942 | -fn av1_encode_agrees_between_two_decoders() { | |
| 943 | - let Some(display) = display() else { return }; | |
| 944 | - let dir = std::env::temp_dir().join("ec-hw-av1-encode"); | |
| 945 | - let _ = std::fs::create_dir_all(&dir); | |
| 946 | - for (width, height, frames) in [(640u32, 384u32, 10u32), (1920, 1080, 10)] { | |
| 947 | - let data = match encode_stream(&display, EncCodec::Av1, width, height, frames) { | |
| 948 | - Ok(data) => data, | |
| 949 | - Err(e) => { | |
| 950 | - eprintln!("skipped: AV1 encode unavailable ({e})"); | |
| 951 | - return; | |
| 952 | - } | |
| 953 | - }; | |
| 954 | - let path = dir.join(format!("hw-{width}x{height}.obu")); | |
| 955 | - std::fs::write(&path, &data).expect("write the coded stream"); | |
| 956 | - | |
| 957 | - // Decoder one: this family's software AV1 decoder, on the raw OBUs. | |
| 958 | - let ours = ec_av1::stream::decode_stream(&data) | |
| 959 | - .unwrap_or_else(|e| panic!("ec-av1 decodes the {width}x{height} hardware stream: {e}")); | |
| 960 | - assert_eq!( | |
| 961 | - ours.len(), | |
| 962 | - frames as usize, | |
| 963 | - "{width}x{height}: ec-av1 decoded {} of {frames} shown frames", | |
| 964 | - ours.len() | |
| 965 | - ); | |
| 966 | - | |
| 967 | - // Decoder two: ffmpeg (libdav1d) on the same bytes. | |
| 968 | - let mut reference = | |
| 969 | - Reference::open(&path, width, height, false).expect("ffmpeg opens the stream"); | |
| 970 | - let mut worst = f64::INFINITY; | |
| 971 | - for (i, picture) in ours.iter().enumerate() { | |
| 972 | - let theirs = reference | |
| 973 | - .next(width, height) | |
| 974 | - .unwrap_or_else(|| panic!("{width}x{height}: ffmpeg has no frame {i}")); | |
| 975 | - let mine = Planes { | |
| 976 | - y: picture.y.clone(), | |
| 977 | - u: picture.u.clone(), | |
| 978 | - v: picture.v.clone(), | |
| 979 | - peak: 255.0, | |
| 980 | - }; | |
| 981 | - let db = psnr(&mine, &theirs); | |
| 982 | - assert!( | |
| 983 | - db.is_infinite(), | |
| 984 | - "{width}x{height} frame {i}: the two decoders disagree ({db:.2} dB)" | |
| 985 | - ); | |
| 986 | - // Agreement alone would also be satisfied by ten grey frames: the | |
| 987 | - // coded picture has to be the picture that was submitted. | |
| 988 | - let source = Planes::from_8bit(&source_frame(width, height, i as u32)); | |
| 989 | - let fidelity = psnr(&mine, &source); | |
| 990 | - assert!( | |
| 991 | - fidelity > 30.0, | |
| 992 | - "{width}x{height} frame {i}: coded {fidelity:.2} dB from the source" | |
| 993 | - ); | |
| 994 | - worst = worst.min(fidelity); | |
| 995 | - } | |
| 996 | - println!( | |
| 997 | - "AV1 encode {width}x{height}: {frames} frames, {} bytes, ec-av1 and libdav1d agree \ | |
| 998 | - sample for sample, worst frame {worst:.2} dB from the source", | |
| 999 | - data.len() | |
| 1000 | - ); | |
| 1001 | - } | |
| 1002 | -} | |
| 1003 | - | |
| 1004 | -// --------------------------------------------------------------------------- | |
| 1005 | -// 10-bit hardware AV1: his whole AV1 library is yuv420p10le, so an 8-bit-only | |
| 1006 | -// encoder does not serve his files. | |
| 1007 | -// --------------------------------------------------------------------------- | |
| 1008 | - | |
| 1009 | 554 | /// stream is neither flat nor 8-bit content dressed up as 10. |
| 1010 | 555 | fn source_frame_16(width: u32, height: u32, t: u32) -> I420_16 { |
| 1011 | 556 | let (w, h) = (width as usize, height as usize); |
| @@ -1175,107 +720,6 @@ fn hevc_main10_encode_round_trips() { | ||
| 1175 | 720 | ); |
| 1176 | 721 | } |
| 1177 | 722 | |
| 1178 | -/// 10-bit AV1 hardware encode, proved by two decoders and by two readings of | |
| 1179 | -/// the stream's bit depth. | |
| 1180 | -/// | |
| 1181 | -/// The bit depth is not taken on trust: ffprobe (libdav1d) must call the | |
| 1182 | -/// stream `yuv420p10le`, which is it reading the `high_bitdepth` bit this | |
| 1183 | -/// crate packs into the sequence header, and `ec-av1`'s own decode must | |
| 1184 | -/// produce samples above 255 — an 8-bit stream dressed as 10 fails both. | |
| 1185 | -#[test] | |
| 1186 | -fn av1_10bit_encode_agrees_between_two_decoders() { | |
| 1187 | - let Some(display) = display() else { return }; | |
| 1188 | - let dir = std::env::temp_dir().join("ec-hw-av1-10bit"); | |
| 1189 | - let _ = std::fs::create_dir_all(&dir); | |
| 1190 | - let frames = 10u32; | |
| 1191 | - let (label, _, planes) = ten_bit_source(&dir, frames); | |
| 1192 | - let (width, height) = (planes[0].width, planes[0].height); | |
| 1193 | - let data = match encode_stream_16( | |
| 1194 | - &display, | |
| 1195 | - EncCodec::Av1, | |
| 1196 | - &planes, | |
| 1197 | - 90, | |
| 1198 | - RateControlMode::ConstantQp { qp: 90 }, | |
| 1199 | - ) { | |
| 1200 | - Ok(data) => data, | |
| 1201 | - Err(e) => { | |
| 1202 | - eprintln!("skipped: 10-bit AV1 encode unavailable ({e})"); | |
| 1203 | - return; | |
| 1204 | - } | |
| 1205 | - }; | |
| 1206 | - let path = dir.join("hw-10bit.obu"); | |
| 1207 | - std::fs::write(&path, &data).expect("write the coded stream"); | |
| 1208 | - | |
| 1209 | - assert_eq!( | |
| 1210 | - ffprobe_pix_fmt(&path, "obu").as_deref(), | |
| 1211 | - Some("yuv420p10le"), | |
| 1212 | - "the coded stream's sequence header does not say 10-bit" | |
| 1213 | - ); | |
| 1214 | - | |
| 1215 | - let ten_bit_h264 = EncoderConfig::new(EncCodec::H264, width, height).ten_bit(); | |
| 1216 | - assert!(Encoder::new(&display, ten_bit_h264).is_err()); | |
| 1217 | - let mut config = EncoderConfig::new(EncCodec::Av1, width, height).ten_bit(); | |
| 1218 | - config.rate_control = RateControlMode::ConstantQp { qp: 90 }; | |
| 1219 | - let mut ten = Encoder::new(&display, config).expect("a 10-bit AV1 encoder"); | |
| 1220 | - assert!( | |
| 1221 | - ten.encode(&source_frame(width, height, 0), FrameMetadata::default()) | |
| 1222 | - .is_err(), | |
| 1223 | - "8-bit pixels went into a 10-bit encoder" | |
| 1224 | - ); | |
| 1225 | - | |
| 1226 | - let ours = ec_av1::stream::decode_stream(&data) | |
| 1227 | - .unwrap_or_else(|e| panic!("ec-av1 decodes the 10-bit hardware stream: {e}")); | |
| 1228 | - assert_eq!( | |
| 1229 | - ours.len(), | |
| 1230 | - planes.len(), | |
| 1231 | - "ec-av1 decoded {} of {frames} frames", | |
| 1232 | - ours.len() | |
| 1233 | - ); | |
| 1234 | - let peak = ours | |
| 1235 | - .iter() | |
| 1236 | - .flat_map(|p| p.y.iter()) | |
| 1237 | - .copied() | |
| 1238 | - .max() | |
| 1239 | - .unwrap_or(0); | |
| 1240 | - assert!( | |
| 1241 | - peak > 255, | |
| 1242 | - "every decoded luma sample fits in 8 bits (peak {peak})" | |
| 1243 | - ); | |
| 1244 | - | |
| 1245 | - let mut reference = | |
| 1246 | - Reference::open(&path, width, height, true).expect("ffmpeg opens the stream"); | |
| 1247 | - let mut worst = f64::INFINITY; | |
| 1248 | - for (i, picture) in ours.iter().enumerate() { | |
| 1249 | - let theirs = reference | |
| 1250 | - .next(width, height) | |
| 1251 | - .unwrap_or_else(|| panic!("ffmpeg has no frame {i}")); | |
| 1252 | - let mine = Planes { | |
| 1253 | - y: picture.y.clone(), | |
| 1254 | - u: picture.u.clone(), | |
| 1255 | - v: picture.v.clone(), | |
| 1256 | - peak: 1023.0, | |
| 1257 | - }; | |
| 1258 | - let db = psnr(&mine, &theirs); | |
| 1259 | - assert!( | |
| 1260 | - db.is_infinite(), | |
| 1261 | - "frame {i}: the two decoders disagree ({db:.2} dB)" | |
| 1262 | - ); | |
| 1263 | - let source = Planes::from_16bit(&planes[i]); | |
| 1264 | - let fidelity = psnr(&mine, &source); | |
| 1265 | - assert!( | |
| 1266 | - fidelity > 30.0, | |
| 1267 | - "frame {i}: coded {fidelity:.2} dB from the 10-bit source" | |
| 1268 | - ); | |
| 1269 | - worst = worst.min(fidelity); | |
| 1270 | - } | |
| 1271 | - println!( | |
| 1272 | - "AV1 10-bit encode {width}x{height} ({label}): {frames} frames, {} bytes, pix_fmt \ | |
| 1273 | - yuv420p10le, CQP 90, decoded peak luma {peak}, ec-av1 and libdav1d agree sample for \ | |
| 1274 | - sample, worst frame {worst:.2} dB from the source (10-bit domain)", | |
| 1275 | - data.len() | |
| 1276 | - ); | |
| 1277 | -} | |
| 1278 | - | |
| 1279 | 723 | /// Rate control: does an asked-for bitrate come back? |
| 1280 | 724 | /// |
| 1281 | 725 | /// 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<f64> { | ||
| 1416 | 860 | .filter(|v| v.is_finite()) |
| 1417 | 861 | } |
| 1418 | 862 | |
| 1419 | -/// What the GPU's AV1 costs against software, on his own content. | |
| 1420 | -/// | |
| 1421 | -/// Four quantisers per encoder on a 1920x1080 crop of a film and of a screen | |
| 1422 | -/// capture, PSNR from ffmpeg, BD-rate over the overlapping quality range | |
| 1423 | -/// against librav1e speed 6 and libaom cpu-used 6. Nothing is asserted about | |
| 1424 | -/// the number — a fixed-function encoder is not a search — but it is measured | |
| 1425 | -/// and printed rather than assumed, and the ladder itself is asserted to be | |
| 1426 | -/// monotone, which is the part a broken parameter set would break. | |
| 1427 | -#[test] | |
| 1428 | -fn av1_encode_bd_row_vs_software() { | |
| 1429 | - let Some(display) = display() else { return }; | |
| 1430 | - // A ladder compared with itself saves nothing: the check on the metric. | |
| 1431 | - let same = [(100.0, 30.0), (200.0, 35.0), (400.0, 40.0)]; | |
| 1432 | - assert!( | |
| 1433 | - bd_rate(&same, &same).abs() < 1e-9, | |
| 1434 | - "bd_rate is not self-zero" | |
| 1435 | - ); | |
| 1436 | - | |
| 1437 | - let dir = std::env::temp_dir().join("ec-hw-av1-bd"); | |
| 1438 | - let _ = std::fs::create_dir_all(&dir); | |
| 1439 | - for (label, source) in real_clips() { | |
| 1440 | - let y4m = dir.join(format!("{label}.y4m")); | |
| 1441 | - let (width, height, frames) = (1920u32, 1080u32, 12u32); | |
| 1442 | - assert!( | |
| 1443 | - extract_y4m(&source, &y4m, width, height, frames), | |
| 1444 | - "{label}: extraction failed" | |
| 1445 | - ); | |
| 1446 | - let planes = raw_frames(&y4m, width, height, frames).expect("frames of the trailer"); | |
| 1447 | - | |
| 1448 | - let mut ours = Vec::new(); | |
| 1449 | - // Descending quantiser: every ladder here is ordered by rising rate. | |
| 1450 | - for qp in [180u32, 140, 100, 60] { | |
| 1451 | - let mut config = EncoderConfig::new(EncCodec::Av1, width, height); | |
| 1452 | - config.framerate = (24, 1); | |
| 1453 | - config.gop_size = 60; | |
| 1454 | - config.rate_control = RateControlMode::ConstantQp { qp }; | |
| 1455 | - let mut encoder = match Encoder::new(&display, config) { | |
| 1456 | - Ok(encoder) => encoder, | |
| 1457 | - Err(e) => { | |
| 1458 | - eprintln!("skipped: AV1 encode unavailable ({e})"); | |
| 1459 | - return; | |
| 1460 | - } | |
| 1461 | - }; | |
| 1462 | - let mut bytes = Vec::new(); | |
| 1463 | - for (i, frame) in planes.iter().enumerate() { | |
| 1464 | - let coded = encoder | |
| 1465 | - .encode( | |
| 1466 | - frame, | |
| 1467 | - FrameMetadata { | |
| 1468 | - timestamp: i as i64, | |
| 1469 | - force_keyframe: false, | |
| 1470 | - }, | |
| 1471 | - ) | |
| 1472 | - .expect("hardware AV1 encode"); | |
| 1473 | - bytes.extend_from_slice(&coded.data); | |
| 1474 | - } | |
| 1475 | - let path = dir.join(format!("{label}-hw-{qp}.obu")); | |
| 1476 | - std::fs::write(&path, &bytes).expect("write"); | |
| 1477 | - if let Some(db) = ffmpeg_psnr(&path, &y4m, true) { | |
| 1478 | - ours.push((bytes.len() as f64 * 8.0 / f64::from(frames), db)); | |
| 1479 | - } | |
| 1480 | - } | |
| 1481 | - let rav1e: Vec<(f64, f64)> = [180u32, 140, 100, 60] | |
| 1482 | - .iter() | |
| 1483 | - .filter_map(|q| { | |
| 1484 | - software_point( | |
| 1485 | - &dir, | |
| 1486 | - &y4m, | |
| 1487 | - label, | |
| 1488 | - "librav1e", | |
| 1489 | - &[ | |
| 1490 | - "-rav1e-params", | |
| 1491 | - &format!("speed=6:quantizer={q}"), | |
| 1492 | - "-g", | |
| 1493 | - "60", | |
| 1494 | - ], | |
| 1495 | - *q, | |
| 1496 | - frames, | |
| 1497 | - ) | |
| 1498 | - }) | |
| 1499 | - .collect(); | |
| 1500 | - let libaom: Vec<(f64, f64)> = [56u32, 44, 32, 20] | |
| 1501 | - .iter() | |
| 1502 | - .filter_map(|crf| { | |
| 1503 | - software_point( | |
| 1504 | - &dir, | |
| 1505 | - &y4m, | |
| 1506 | - label, | |
| 1507 | - "libaom-av1", | |
| 1508 | - &[ | |
| 1509 | - "-cpu-used", | |
| 1510 | - "6", | |
| 1511 | - "-crf", | |
| 1512 | - &crf.to_string(), | |
| 1513 | - "-b:v", | |
| 1514 | - "0", | |
| 1515 | - "-g", | |
| 1516 | - "60", | |
| 1517 | - ], | |
| 1518 | - *crf, | |
| 1519 | - frames, | |
| 1520 | - ) | |
| 1521 | - }) | |
| 1522 | - .collect(); | |
| 1523 | - | |
| 1524 | - for (name, ladder) in [("hw AV1", &ours), ("librav1e", &rav1e), ("libaom", &libaom)] { | |
| 1525 | - println!("{label} {name}: {ladder:?}"); | |
| 1526 | - for pair in ladder.windows(2) { | |
| 1527 | - assert!( | |
| 1528 | - pair[1].0 > pair[0].0 && pair[1].1 > pair[0].1, | |
| 1529 | - "{label} {name}: ladder is not monotone at {pair:?}" | |
| 1530 | - ); | |
| 1531 | - } | |
| 1532 | - } | |
| 1533 | - if ours.len() >= 3 && rav1e.len() >= 3 { | |
| 1534 | - println!( | |
| 1535 | - "BD-rate row: {label}, hw AV1 vs librav1e speed 6: {:+.1}%", | |
| 1536 | - bd_rate(&rav1e, &ours) * 100.0 | |
| 1537 | - ); | |
| 1538 | - } | |
| 1539 | - if ours.len() >= 3 && libaom.len() >= 3 { | |
| 1540 | - println!( | |
| 1541 | - "BD-rate row: {label}, hw AV1 vs libaom cpu-used 6: {:+.1}%", | |
| 1542 | - bd_rate(&libaom, &ours) * 100.0 | |
| 1543 | - ); | |
| 1544 | - } | |
| 1545 | - } | |
| 1546 | -} | |
| 1547 | - | |
| 1548 | -/// One software encoder's rate/PSNR point, or `None` when that encoder is not | |
| 1549 | -/// built into this ffmpeg. | |
| 1550 | -fn software_point( | |
| 1551 | - dir: &Path, | |
| 1552 | - y4m: &Path, | |
| 1553 | - label: &str, | |
| 1554 | - encoder: &str, | |
| 1555 | - args: &[&str], | |
| 1556 | - point: u32, | |
| 1557 | - frames: u32, | |
| 1558 | -) -> Option<(f64, f64)> { | |
| 1559 | - let out = dir.join(format!("{label}-{encoder}-{point}.ivf")); | |
| 1560 | - let _ = std::fs::remove_file(&out); | |
| 1561 | - let status = ec_testkit::ffmpeg() | |
| 1562 | - .args(["-nostdin", "-v", "error", "-y", "-i"]) | |
| 1563 | - .arg(y4m) | |
| 1564 | - .args(["-c:v", encoder]) | |
| 1565 | - .args(args) | |
| 1566 | - .arg(&out) | |
| 1567 | - .status() | |
| 1568 | - .ok()?; | |
| 1569 | - if !status.success() { | |
| 1570 | - return None; | |
| 1571 | - } | |
| 1572 | - let bytes = std::fs::metadata(&out).ok()?.len() as f64; | |
| 1573 | - let db = ffmpeg_psnr(&out, y4m, false)?; | |
| 1574 | - Some((bytes * 8.0 / f64::from(frames), db)) | |
| 1575 | -} | |
| 1576 | - | |
| 1577 | 863 | /// PSNR of a coded stream against the source, from ffmpeg's own filter. |
| 1578 | -fn ffmpeg_psnr(coded: &Path, source: &Path, raw_obu: bool) -> Option<f64> { | |
| 1579 | - let mut cmd = ec_testkit::ffmpeg(); | |
| 1580 | - cmd.args(["-nostdin", "-v", "info"]); | |
| 1581 | - if raw_obu { | |
| 1582 | - cmd.args(["-f", "obu"]); | |
| 1583 | - } | |
| 1584 | - // Both inputs are pinned to the same rate: a raw OBU stream carries no | |
| 1585 | - // timing, so ffmpeg would otherwise call it 25 fps against a 24 fps | |
| 1586 | - // source and the filter would compare frame i with frame i+k. | |
| 1587 | - let out = cmd | |
| 1588 | - .args(["-r", "24"]) | |
| 1589 | - .arg("-i") | |
| 1590 | - .arg(coded) | |
| 1591 | - .args(["-r", "24"]) | |
| 1592 | - .arg("-i") | |
| 1593 | - .arg(source) | |
| 1594 | - .args(["-lavfi", "psnr", "-f", "null", "-"]) | |
| 1595 | - .output() | |
| 1596 | - .ok()?; | |
| 1597 | - let text = String::from_utf8_lossy(&out.stderr); | |
| 1598 | - let field = text.split("average:").nth(1)?; | |
| 1599 | - field | |
| 1600 | - .split_whitespace() | |
| 1601 | - .next()? | |
| 1602 | - .parse::<f64>() | |
| 1603 | - .ok() | |
| 1604 | - .filter(|v| v.is_finite()) | |
| 1605 | -} | |
| 1606 | - | |
| 1607 | -/// A 1920x1080 crop of `frames` pictures, as a y4m file the encoders share. | |
| 1608 | -fn extract_y4m(source: &Path, out: &Path, width: u32, height: u32, frames: u32) -> bool { | |
| 1609 | - let _ = std::fs::remove_file(out); | |
| 1610 | - ec_testkit::ffmpeg() | |
| 1611 | - .args(["-nostdin", "-v", "error", "-y", "-ss", "20", "-i"]) | |
| 864 | +/// A 1920x1080 crop of `frames` pictures, as a y4m file the encoders share. | |
| 865 | +fn extract_y4m(source: &Path, out: &Path, width: u32, height: u32, frames: u32) -> bool { | |
| 866 | + let _ = std::fs::remove_file(out); | |
| 867 | + ec_testkit::ffmpeg() | |
| 868 | + .args(["-nostdin", "-v", "error", "-y", "-ss", "20", "-i"]) | |
| 1612 | 869 | .arg(source) |
| 1613 | 870 | .args([ |
| 1614 | 871 | "-frames:v", |
| @@ -1656,1299 +913,3 @@ fn real_clips() -> Vec<(&'static str, PathBuf)> { | ||
| 1656 | 913 | ("sintel 720p", ec_testkit::fixture("open/sintel_trailer-720p.mp4")), |
| 1657 | 914 | ] |
| 1658 | 915 | } |
| 1659 | - | |
| 1660 | -/// BD-rate of `test` against `reference`, as a fraction (negative = fewer | |
| 1661 | -/// bits for the same quality), integrated piecewise-linearly in | |
| 1662 | -/// `log10(bits per frame)` over the PSNR range the two ladders share. | |
| 1663 | -/// | |
| 1664 | -/// The cubic fit of the original method needs four well-spread points and | |
| 1665 | -/// misbehaves outside them; a trapezoid over the overlap is the honest | |
| 1666 | -/// version of the same integral for ladders this short. | |
| 1667 | -fn bd_rate(reference: &[(f64, f64)], test: &[(f64, f64)]) -> f64 { | |
| 1668 | - let low = reference[0].1.max(test[0].1); | |
| 1669 | - let high = reference[reference.len() - 1].1.min(test[test.len() - 1].1); | |
| 1670 | - if high <= low { | |
| 1671 | - return f64::NAN; | |
| 1672 | - } | |
| 1673 | - // log-rate at a PSNR, linearly interpolated inside the ladder. | |
| 1674 | - let at = |ladder: &[(f64, f64)], db: f64| -> f64 { | |
| 1675 | - for pair in ladder.windows(2) { | |
| 1676 | - let ((r0, d0), (r1, d1)) = (pair[0], pair[1]); | |
| 1677 | - if db >= d0 && db <= d1 { | |
| 1678 | - let t = if (d1 - d0).abs() < f64::EPSILON { | |
| 1679 | - 0.0 | |
| 1680 | - } else { | |
| 1681 | - (db - d0) / (d1 - d0) | |
| 1682 | - }; | |
| 1683 | - return r0.log10() + t * (r1.log10() - r0.log10()); | |
| 1684 | - } | |
| 1685 | - } | |
| 1686 | - if db < ladder[0].1 { | |
| 1687 | - ladder[0].0.log10() | |
| 1688 | - } else { | |
| 1689 | - ladder[ladder.len() - 1].0.log10() | |
| 1690 | - } | |
| 1691 | - }; | |
| 1692 | - let steps = 100; | |
| 1693 | - let mut integral = 0.0; | |
| 1694 | - for i in 0..steps { | |
| 1695 | - let a = low + (high - low) * f64::from(i) / f64::from(steps); | |
| 1696 | - let b = low + (high - low) * f64::from(i + 1) / f64::from(steps); | |
| 1697 | - let da = at(test, a) - at(reference, a); | |
| 1698 | - let db = at(test, b) - at(reference, b); | |
| 1699 | - integral += (da + db) / 2.0 * (b - a); | |
| 1700 | - } | |
| 1701 | - 10f64.powf(integral / (high - low)) - 1.0 | |
| 1702 | -} | |
| 1703 | - | |
| 1704 | -/// Hardware AV1 encode speed at the two sizes his library is in, in frames per | |
| 1705 | -/// second. Real time is 24 fps; the number is printed rather than asserted, | |
| 1706 | -/// since a busy GPU is not a failing encoder. | |
| 1707 | -#[test] | |
| 1708 | -fn av1_encode_speed() { | |
| 1709 | - let Some(display) = display() else { return }; | |
| 1710 | - for (width, height) in [(1920u32, 1080u32), (3840, 1608)] { | |
| 1711 | - let frames = 30u32; | |
| 1712 | - let start = Instant::now(); | |
| 1713 | - match encode_stream(&display, EncCodec::Av1, width, height, frames) { | |
| 1714 | - Ok(data) => { | |
| 1715 | - let secs = start.elapsed().as_secs_f64(); | |
| 1716 | - println!( | |
| 1717 | - "AV1 encode {width}x{height}: {:.1} fps ({frames} frames in {secs:.2} s), {} kbit/frame", | |
| 1718 | - f64::from(frames) / secs, | |
| 1719 | - data.len() * 8 / frames as usize / 1000 | |
| 1720 | - ); | |
| 1721 | - } | |
| 1722 | - Err(e) => { | |
| 1723 | - eprintln!("skipped: AV1 encode unavailable ({e})"); | |
| 1724 | - return; | |
| 1725 | - } | |
| 1726 | - } | |
| 1727 | - } | |
| 1728 | - // 10-bit at the size his own films are in: the depth his library is | |
| 1729 | - // actually stored at, so the fps that matters for a real export. | |
| 1730 | - let planes: Vec<I420_16> = (0..30).map(|t| source_frame_16(3840, 1608, t)).collect(); | |
| 1731 | - let start = Instant::now(); | |
| 1732 | - match encode_stream_16( | |
| 1733 | - &display, | |
| 1734 | - EncCodec::Av1, | |
| 1735 | - &planes, | |
| 1736 | - 90, | |
| 1737 | - RateControlMode::ConstantQp { qp: 90 }, | |
| 1738 | - ) { | |
| 1739 | - Ok(data) => { | |
| 1740 | - let secs = start.elapsed().as_secs_f64(); | |
| 1741 | - println!( | |
| 1742 | - "AV1 encode 3840x1608 10-bit: {:.1} fps ({} frames in {secs:.2} s), {} kbit/frame", | |
| 1743 | - planes.len() as f64 / secs, | |
| 1744 | - planes.len(), | |
| 1745 | - data.len() * 8 / planes.len() / 1000 | |
| 1746 | - ); | |
| 1747 | - } | |
| 1748 | - Err(e) => eprintln!("skipped: 10-bit AV1 encode unavailable ({e})"), | |
| 1749 | - } | |
| 1750 | -} | |
| 1751 | - | |
| 1752 | -// --------------------------------------------------------------------------- | |
| 1753 | -// The four incumbent defects, as tests | |
| 1754 | -// --------------------------------------------------------------------------- | |
| 1755 | - | |
| 1756 | -/// A `frame_num` gap is normal, not corruption. | |
| 1757 | -/// | |
| 1758 | -/// Dropping a reference picture from the middle of a GOP is what a seek, a lost | |
| 1759 | -/// packet or an encoder that skipped a picture all look like. The incumbent | |
| 1760 | -/// stack treated it as an error and fell back to software for the rest of the | |
| 1761 | -/// timeline; here the missing pictures are inferred (8.2.5.2) and decoding | |
| 1762 | -/// carries on in hardware. | |
| 1763 | -#[test] | |
| 1764 | -fn h264_frame_num_gaps_are_synthesised() { | |
| 1765 | - let Some(display) = display() else { return }; | |
| 1766 | - let path = ec_testkit::fixture("bitstreams/h264-1080p-23.976-8bit.264"); | |
| 1767 | - let data = std::fs::read(&path).expect("fixture is readable"); | |
| 1768 | - let units = split_access_units(&data, Codec::H264); | |
| 1769 | - assert!( | |
| 1770 | - units.len() > 8, | |
| 1771 | - "fixture is too short to drop a picture from" | |
| 1772 | - ); | |
| 1773 | - | |
| 1774 | - // Drop two reference pictures from the middle of the first GOP. | |
| 1775 | - let mut kept: Vec<&[u8]> = Vec::new(); | |
| 1776 | - for (i, unit) in units.iter().enumerate() { | |
| 1777 | - if (3..=5).contains(&i) { | |
| 1778 | - continue; | |
| 1779 | - } | |
| 1780 | - kept.push(unit); | |
| 1781 | - } | |
| 1782 | - | |
| 1783 | - let mut decoder = Decoder::new(&display, Codec::H264).expect("decoder opens"); | |
| 1784 | - let mut frames = 0usize; | |
| 1785 | - for (i, unit) in kept.iter().enumerate().take(20) { | |
| 1786 | - if let Err(e) = decoder.decode(unit, i as i64) { | |
| 1787 | - panic!( | |
| 1788 | - "unit {i} failed after {} gap frames: {e}", | |
| 1789 | - decoder.gap_frames_synthesized() | |
| 1790 | - ); | |
| 1791 | - } | |
| 1792 | - while let Some(frame) = decoder.next_frame() { | |
| 1793 | - // The frame is real: reading it back must work, not just arrive. | |
| 1794 | - let planes = frame.to_i420().expect("readback"); | |
| 1795 | - assert_eq!(planes.y.len(), 1920 * 1080); | |
| 1796 | - frames += 1; | |
| 1797 | - } | |
| 1798 | - } | |
| 1799 | - decoder.flush().expect("flush"); | |
| 1800 | - while decoder.next_frame().is_some() { | |
| 1801 | - frames += 1; | |
| 1802 | - } | |
| 1803 | - let synthesised = decoder.gap_frames_synthesized(); | |
| 1804 | - println!("frame_num gap: {frames} frames decoded, {synthesised} pictures inferred"); | |
| 1805 | - assert!(synthesised > 0, "the gap was not detected"); | |
| 1806 | - assert!(frames >= 10, "only {frames} frames survived the gap"); | |
| 1807 | -} | |
| 1808 | - | |
| 1809 | -/// VmRSS in kilobytes, from `/proc/self/status`. | |
| 1810 | -fn rss_kb() -> u64 { | |
| 1811 | - let status = std::fs::read_to_string("/proc/self/status").unwrap_or_default(); | |
| 1812 | - status | |
| 1813 | - .lines() | |
| 1814 | - .find_map(|line| line.strip_prefix("VmRSS:")) | |
| 1815 | - .and_then(|v| v.split_whitespace().next().map(|n| n.to_string())) | |
| 1816 | - .and_then(|n| n.parse().ok()) | |
| 1817 | - .unwrap_or(0) | |
| 1818 | -} | |
| 1819 | - | |
| 1820 | -/// Decode and read back for longer than any export, and watch the resident set. | |
| 1821 | -/// | |
| 1822 | -/// The incumbent leaked ~3 MB per frame by mapping a VA image and never | |
| 1823 | -/// unmapping it: a 719-frame export lost 2 GB. Every mapping here is a guard | |
| 1824 | -/// that unmaps on drop, and this is the test that says so out loud. | |
| 1825 | -#[test] | |
| 1826 | -fn long_decode_does_not_grow_the_resident_set() { | |
| 1827 | - // VmRSS is a process-wide number and the harness runs every test in this | |
| 1828 | - // binary as a thread of one process: a sibling allocating between the | |
| 1829 | - // baseline and the end reading shows up here as a 200 MB "leak". The | |
| 1830 | - // measurement therefore runs in a child process holding only this test. | |
| 1831 | - if std::env::var_os("EC_HW_RSS_CHILD").is_none() { | |
| 1832 | - let status = Command::new(std::env::current_exe().expect("test binary path")) | |
| 1833 | - .args(["--exact", "long_decode_does_not_grow_the_resident_set"]) | |
| 1834 | - .env("EC_HW_RSS_CHILD", "1") | |
| 1835 | - .status() | |
| 1836 | - .expect("re-run this test in its own process"); | |
| 1837 | - assert!(status.success(), "isolated RSS run failed"); | |
| 1838 | - return; | |
| 1839 | - } | |
| 1840 | - let Some(display) = display() else { return }; | |
| 1841 | - let path = ec_testkit::fixture("bitstreams/h264-1080p-23.976-8bit.264"); | |
| 1842 | - let data = std::fs::read(&path).expect("fixture is readable"); | |
| 1843 | - let units = split_access_units(&data, Codec::H264); | |
| 1844 | - let mut decoder = Decoder::new(&display, Codec::H264).expect("decoder opens"); | |
| 1845 | - | |
| 1846 | - // Warm up first: the first pictures allocate the surface pool and the | |
| 1847 | - // readback image, and that growth is not a leak. | |
| 1848 | - let mut decoded = 0usize; | |
| 1849 | - let mut baseline = 0u64; | |
| 1850 | - let mut readback_ms = 0f64; | |
| 1851 | - let mut pending: Vec<Frame> = Vec::new(); | |
| 1852 | - let target = 719usize; | |
| 1853 | - 'outer: for pass in 0..16 { | |
| 1854 | - if pass > 0 { | |
| 1855 | - decoder.reset(); | |
| 1856 | - } | |
| 1857 | - for (i, unit) in units.iter().enumerate() { | |
| 1858 | - decoder.decode(unit, i as i64).expect("decode"); | |
| 1859 | - while let Some(frame) = decoder.next_frame() { | |
| 1860 | - // Hold a few frames before reading any back: a decoder that is | |
| 1861 | - // read one frame per submission spends its time waiting for the | |
| 1862 | - // GPU, which measures latency rather than throughput. | |
| 1863 | - pending.push(frame); | |
| 1864 | - if pending.len() < 4 { | |
| 1865 | - continue; | |
| 1866 | - } | |
| 1867 | - let start = std::time::Instant::now(); | |
| 1868 | - for frame in pending.drain(..) { | |
| 1869 | - let planes = frame.to_i420().expect("readback"); | |
| 1870 | - std::hint::black_box(&planes); | |
| 1871 | - decoded += 1; | |
| 1872 | - } | |
| 1873 | - readback_ms += start.elapsed().as_secs_f64() * 1000.0; | |
| 1874 | - if decoded == 60 { | |
| 1875 | - baseline = rss_kb(); | |
| 1876 | - } | |
| 1877 | - if decoded >= target { | |
| 1878 | - break 'outer; | |
| 1879 | - } | |
| 1880 | - } | |
| 1881 | - } | |
| 1882 | - } | |
| 1883 | - decoder.flush().expect("flush"); | |
| 1884 | - let end = rss_kb(); | |
| 1885 | - let delta_mb = (end.saturating_sub(baseline)) as f64 / 1024.0; | |
| 1886 | - println!( | |
| 1887 | - "{decoded} frames decoded and read back: RSS {baseline} -> {end} kB (delta {delta_mb:.1} MB), \ | |
| 1888 | - decode and read back {:.2} ms/frame at 1920x1080", | |
| 1889 | - readback_ms / decoded as f64 | |
| 1890 | - ); | |
| 1891 | - assert!(decoded >= target, "only {decoded} frames decoded"); | |
| 1892 | - assert!( | |
| 1893 | - delta_mb < 50.0, | |
| 1894 | - "resident set grew {delta_mb:.1} MB over {decoded} frames" | |
| 1895 | - ); | |
| 1896 | -} | |
| 1897 | - | |
| 1898 | -/// The zero-copy path: a decoded surface exports as DRM PRIME file descriptors. | |
| 1899 | -/// | |
| 1900 | -/// This is what edith's `engine-hw` imports into gbm, so the fds and the plane | |
| 1901 | -/// layout matter as much as the pixels do. | |
| 1902 | -#[test] | |
| 1903 | -fn frames_export_as_dma_buf() { | |
| 1904 | - let Some(display) = display() else { return }; | |
| 1905 | - let path = ec_testkit::fixture("bitstreams/h264-1080p-23.976-8bit.264"); | |
| 1906 | - let data = std::fs::read(&path).expect("fixture is readable"); | |
| 1907 | - let mut decoder = Decoder::new(&display, Codec::H264).expect("decoder opens"); | |
| 1908 | - let mut exported = 0usize; | |
| 1909 | - decode_stream(&mut decoder, Codec::H264, &data, 2, |frame| { | |
| 1910 | - let prime = frame.export_prime().expect("export"); | |
| 1911 | - assert_eq!(prime.fourcc, ec_va::va::VA_FOURCC_NV12); | |
| 1912 | - assert_eq!((prime.width, prime.height), frame.coded_size); | |
| 1913 | - assert!(!prime.objects.is_empty(), "no DRM objects exported"); | |
| 1914 | - assert!(!prime.layers.is_empty(), "no layers exported"); | |
| 1915 | - let planes: usize = prime.layers.iter().map(|l| l.planes.len()).sum(); | |
| 1916 | - assert!( | |
| 1917 | - planes >= 2, | |
| 1918 | - "NV12 needs a luma and a chroma plane, got {planes}" | |
| 1919 | - ); | |
| 1920 | - exported += 1; | |
| 1921 | - }) | |
| 1922 | - .expect("decode"); | |
| 1923 | - assert!(exported >= 1, "nothing was exported"); | |
| 1924 | - println!("DRM PRIME export: {exported} frames"); | |
| 1925 | -} | |
| 1926 | - | |
| 1927 | -// --------------------------------------------------------------------------- | |
| 1928 | -// His library | |
| 1929 | -// --------------------------------------------------------------------------- | |
| 1930 | - | |
| 1931 | -/// Turn any container into an elementary stream ffmpeg and this crate agree on. | |
| 1932 | -/// | |
| 1933 | -/// `frames` bounds the extraction: piping a two-hour 4K film through memory to | |
| 1934 | -/// compare its first five hundred pictures is several gigabytes of nothing. | |
| 1935 | -fn elementary(path: &Path, codec: Codec, frames: usize) -> Option<Vec<u8>> { | |
| 1936 | - let args: &[&str] = match codec { | |
| 1937 | - Codec::H264 => &["-bsf:v", "h264_mp4toannexb", "-f", "h264"], | |
| 1938 | - Codec::H265 => &["-bsf:v", "hevc_mp4toannexb", "-f", "hevc"], | |
| 1939 | - Codec::Vp9 | Codec::Av1 => &["-f", "ivf"], | |
| 1940 | - }; | |
| 1941 | - let out = ec_testkit::ffmpeg() | |
| 1942 | - .args(["-nostdin", "-v", "error", "-i"]) | |
| 1943 | - .arg(path) | |
| 1944 | - .args(["-map", "0:v:0", "-c:v", "copy"]) | |
| 1945 | - // A few more coded pictures than frames wanted: reordering means the | |
| 1946 | - // last few packets have not been shown yet. | |
| 1947 | - .args(["-frames:v", &(frames + 16).to_string()]) | |
| 1948 | - .args(args) | |
| 1949 | - .arg("-") | |
| 1950 | - .stderr(Stdio::null()) | |
| 1951 | - .output() | |
| 1952 | - .ok()?; | |
| 1953 | - (!out.stdout.is_empty()).then_some(out.stdout) | |
| 1954 | -} | |
| 1955 | - | |
| 1956 | -#[test] | |
| 1957 | -fn real_library_spot_check() { | |
| 1958 | - let Some(display) = display() else { return }; | |
| 1959 | - let wanted: Vec<(PathBuf, Codec, bool)> = [ | |
| 1960 | - ("open/sintel_trailer-480p.mp4", Codec::H264, false), | |
| 1961 | - ("open/sintel_trailer-1080p.mp4", Codec::H264, false), | |
| 1962 | - ("derived/sintel720-x265-main10.mp4", Codec::H265, true), | |
| 1963 | - ] | |
| 1964 | - .into_iter() | |
| 1965 | - .map(|(rel, codec, ten_bit)| (ec_testkit::fixture(rel), codec, ten_bit)) | |
| 1966 | - .collect(); | |
| 1967 | - | |
| 1968 | - // 500 frames per file by default; a diagnostic run can ask for fewer. | |
| 1969 | - let limit: usize = std::env::var("EC_HW_SWEEP_FRAMES") | |
| 1970 | - .ok() | |
| 1971 | - .and_then(|v| v.parse().ok()) | |
| 1972 | - .unwrap_or(500); | |
| 1973 | - let mut table = Vec::new(); | |
| 1974 | - for (path, codec, ten_bit) in &wanted { | |
| 1975 | - let path = Path::new(path); | |
| 1976 | - let data = elementary(path, *codec, limit).expect("elementary stream"); | |
| 1977 | - let mut decoder = Decoder::new(&display, *codec).expect("decoder opens"); | |
| 1978 | - let mut reference: Option<Reference> = None; | |
| 1979 | - let mut worst = f64::INFINITY; | |
| 1980 | - let mut compared = 0usize; | |
| 1981 | - let mut failed: Option<String> = None; | |
| 1982 | - let result = decode_stream(&mut decoder, *codec, &data, limit, |frame| { | |
| 1983 | - let (w, h) = frame.display_size; | |
| 1984 | - let reference = reference | |
| 1985 | - .get_or_insert_with(|| Reference::open(path, w, h, *ten_bit).expect("ffmpeg runs")); | |
| 1986 | - let Some(want) = reference.next(w, h) else { | |
| 1987 | - return; | |
| 1988 | - }; | |
| 1989 | - let got = if *ten_bit { | |
| 1990 | - Planes::from_16bit(&frame.to_i420_16().expect("readback")) | |
| 1991 | - } else { | |
| 1992 | - Planes::from_8bit(&frame.to_i420().expect("readback")) | |
| 1993 | - }; | |
| 1994 | - if got.y.len() != want.y.len() { | |
| 1995 | - failed = Some("frame size disagrees with ffmpeg".to_string()); | |
| 1996 | - return; | |
| 1997 | - } | |
| 1998 | - let db = psnr(&got, &want); | |
| 1999 | - if std::env::var_os("EC_HW_DEBUG").is_some() { | |
| 2000 | - eprintln!(" {} frame {compared}: {db:.1} dB", short(path)); | |
| 2001 | - } | |
| 2002 | - worst = worst.min(db); | |
| 2003 | - compared += 1; | |
| 2004 | - }); | |
| 2005 | - match result { | |
| 2006 | - Ok(decoded) => table.push(format!( | |
| 2007 | - "{:<52} {decoded:>4} frames, {compared} compared, worst {}", | |
| 2008 | - short(path), | |
| 2009 | - if worst.is_infinite() { | |
| 2010 | - "exact".to_string() | |
| 2011 | - } else { | |
| 2012 | - format!("{worst:.1} dB") | |
| 2013 | - } | |
| 2014 | - )), | |
| 2015 | - Err(e) => failed = Some(e.to_string()), | |
| 2016 | - } | |
| 2017 | - if let Some(reason) = failed { | |
| 2018 | - table.push(format!("{:<52} FAIL {reason}", short(path))); | |
| 2019 | - } | |
| 2020 | - assert!(compared > 0, "{}: nothing decoded", short(path)); | |
| 2021 | - assert!( | |
| 2022 | - worst >= 40.0, | |
| 2023 | - "{}: worst frame {worst:.1} dB against ffmpeg", | |
| 2024 | - short(path) | |
| 2025 | - ); | |
| 2026 | - } | |
| 2027 | - for row in table { | |
| 2028 | - println!("{row}"); | |
| 2029 | - } | |
| 2030 | -} | |
| 2031 | - | |
| 2032 | -/// A library path without the directory tree, so a report can carry it. | |
| 2033 | -fn short(path: &Path) -> String { | |
| 2034 | - path.file_name() | |
| 2035 | - .map(|n| n.to_string_lossy().to_string()) | |
| 2036 | - .unwrap_or_default() | |
| 2037 | -} | |
| 2038 | - | |
| 2039 | -/// PSNR of one plane, in dB (`f64::INFINITY` for an exact match). | |
| 2040 | -fn plane_psnr(a: &[u16], b: &[u16], peak: f64) -> f64 { | |
| 2041 | - let n = a.len().min(b.len()); | |
| 2042 | - let mse: f64 = a[..n] | |
| 2043 | - .iter() | |
| 2044 | - .zip(&b[..n]) | |
| 2045 | - .map(|(&p, &q)| { | |
| 2046 | - let d = f64::from(p) - f64::from(q); | |
| 2047 | - d * d | |
| 2048 | - }) | |
| 2049 | - .sum::<f64>() | |
| 2050 | - / n as f64; | |
| 2051 | - if mse == 0.0 { | |
| 2052 | - f64::INFINITY | |
| 2053 | - } else { | |
| 2054 | - 10.0 * (peak * peak / mse).log10() | |
| 2055 | - } | |
| 2056 | -} | |
| 2057 | - | |
| 2058 | -/// | |
| 2059 | -/// `real_library_spot_check` already pins the whole-frame PSNR at >= 40 dB | |
| 2060 | -/// for a mix of files; this isolates Y from U/V on this specific 10-bit film, | |
| 2061 | -/// against both `yuv420p10le` (the lossless comparison) and `yuv420p` (the | |
| 2062 | -/// truncating `to_i420` path, which rounds ffmpeg's dithered 8-bit output | |
| 2063 | -/// against this crate's un-dithered right-shift -- a real but small gap, not | |
| 2064 | -/// a bug). A collapsed U/V PSNR here (a grey frame) would mean the chroma | |
| 2065 | -/// plane is being read at the wrong stride/offset; it is not, on this file. | |
| 2066 | -#[test] | |
| 2067 | -fn ten_bit_chroma_is_not_grey() { | |
| 2068 | - let Some(display) = display() else { return }; | |
| 2069 | - let path = &ec_testkit::fixture("derived/sintel720-x265-main10.mp4"); | |
| 2070 | - let frames = 3usize; | |
| 2071 | - let data = elementary(path, Codec::H265, frames).expect("elementary stream"); | |
| 2072 | - let mut decoder = Decoder::new(&display, Codec::H265).expect("decoder opens"); | |
| 2073 | - let mut ref10: Option<Reference> = None; | |
| 2074 | - let mut ref8: Option<Reference> = None; | |
| 2075 | - let mut compared = 0usize; | |
| 2076 | - decode_stream(&mut decoder, Codec::H265, &data, frames, |frame| { | |
| 2077 | - let (w, h) = frame.display_size; | |
| 2078 | - let ref10 = | |
| 2079 | - ref10.get_or_insert_with(|| Reference::open(path, w, h, true).expect("ffmpeg runs")); | |
| 2080 | - let want10 = ref10.next(w, h).expect("ffmpeg has a frame"); | |
| 2081 | - let got16 = Planes::from_16bit(&frame.to_i420_16().expect("readback")); | |
| 2082 | - let y_db = plane_psnr(&got16.y, &want10.y, 1023.0); | |
| 2083 | - let uv_db = plane_psnr( | |
| 2084 | - &[got16.u.as_slice(), got16.v.as_slice()].concat(), | |
| 2085 | - &[want10.u.as_slice(), want10.v.as_slice()].concat(), | |
| 2086 | - 1023.0, | |
| 2087 | - ); | |
| 2088 | - println!("frame {compared} to_i420_16 vs yuv420p10le: Y {y_db:.1} dB, UV {uv_db:.1} dB"); | |
| 2089 | - assert!( | |
| 2090 | - y_db >= 50.0, | |
| 2091 | - "frame {compared}: Y PSNR collapsed to {y_db:.1} dB" | |
| 2092 | - ); | |
| 2093 | - assert!( | |
| 2094 | - uv_db >= 50.0, | |
| 2095 | - "frame {compared}: chroma PSNR collapsed to {uv_db:.1} dB (grey frame)" | |
| 2096 | - ); | |
| 2097 | - | |
| 2098 | - let ref8 = | |
| 2099 | - ref8.get_or_insert_with(|| Reference::open(path, w, h, false).expect("ffmpeg runs")); | |
| 2100 | - let want8 = ref8.next(w, h).expect("ffmpeg has a frame"); | |
| 2101 | - let got8 = Planes::from_8bit(&frame.to_i420().expect("readback")); | |
| 2102 | - let y_db8 = plane_psnr(&got8.y, &want8.y, 255.0); | |
| 2103 | - let uv_db8 = plane_psnr( | |
| 2104 | - &[got8.u.as_slice(), got8.v.as_slice()].concat(), | |
| 2105 | - &[want8.u.as_slice(), want8.v.as_slice()].concat(), | |
| 2106 | - 255.0, | |
| 2107 | - ); | |
| 2108 | - println!("frame {compared} to_i420 vs yuv420p: Y {y_db8:.1} dB, UV {uv_db8:.1} dB"); | |
| 2109 | - // ffmpeg dithers its 8-bit downconversion; this crate truncates. Both | |
| 2110 | - // are legitimate 10-to-8 roundings, so the floor here is the | |
| 2111 | - // dithering noise floor, not the lossless bound above. | |
| 2112 | - assert!( | |
| 2113 | - y_db8 >= 30.0, | |
| 2114 | - "frame {compared}: 8-bit Y PSNR {y_db8:.1} dB" | |
| 2115 | - ); | |
| 2116 | - assert!( | |
| 2117 | - uv_db8 >= 30.0, | |
| 2118 | - "frame {compared}: 8-bit chroma PSNR collapsed to {uv_db8:.1} dB (grey frame)" | |
| 2119 | - ); | |
| 2120 | - compared += 1; | |
| 2121 | - }) | |
| 2122 | - .expect("decode"); | |
| 2123 | - assert_eq!(compared, frames, "not all frames were compared"); | |
| 2124 | -} | |
| 2125 | - | |
| 2126 | -/// An SDR H.264 stream, which carries no HDR SEI at all: `Frame::colour` | |
| 2127 | -/// either resolves from the VUI or answers [`None`], but never panics. | |
| 2128 | -#[test] | |
| 2129 | -fn sdr_h264_colour_never_panics() { | |
| 2130 | - let Some(display) = display() else { return }; | |
| 2131 | - let paths = ec_testkit::fixtures("bitstreams", "264"); | |
| 2132 | - let path = &paths[0]; | |
| 2133 | - let data = std::fs::read(path).expect("fixture is readable"); | |
| 2134 | - let mut decoder = Decoder::new(&display, Codec::H264).expect("decoder opens"); | |
| 2135 | - let mut seen = 0usize; | |
| 2136 | - decode_stream(&mut decoder, Codec::H264, &data, 2, |frame| { | |
| 2137 | - seen += 1; | |
| 2138 | - // No SEI parsing on this codec: content light is always absent. | |
| 2139 | - if let Some(colour) = frame.colour() { | |
| 2140 | - assert_eq!(colour.light.max_cll, None); | |
| 2141 | - } | |
| 2142 | - }) | |
| 2143 | - .expect("decode"); | |
| 2144 | - assert!(seen > 0, "{}: nothing decoded", short(path)); | |
| 2145 | -} | |
| 2146 | - | |
| 2147 | -/// A CRA GOP boundary stores its RASL leading pictures *after* the CRA in | |
| 2148 | -/// decode order, even though they display before it (they predict from | |
| 2149 | -/// pictures the CRA's own random-access point does not have). A decoder | |
| 2150 | -/// started fresh at that CRA — what a seek does — must therefore drop those | |
| 2151 | -/// RASL pictures per H.265 8.1.3's `NoRaslOutputFlag`, or its output shifts by | |
| 2152 | -/// however many RASL pictures the GOP has, handing back the wrong picture for | |
| 2153 | -/// every display index at or after the seek target. | |
| 2154 | -#[test] | |
| 2155 | -fn hevc_seek_matches_linear_mkv() { | |
| 2156 | - let Some(display) = display() else { return }; | |
| 2157 | - let path = ec_testkit::fixture("video/hevc-open-gop.mkv"); | |
| 2158 | - let data = elementary(&path, Codec::H265, 45).expect("elementary stream"); | |
| 2159 | - let units = split_access_units(&data, Codec::H265); | |
| 2160 | - | |
| 2161 | - // Linear decode: every picture from the start, frame 30 kept for | |
| 2162 | - // comparison (the file's second CRA, per `test_hevc.mkv`'s 30-picture | |
| 2163 | - // GOPs). | |
| 2164 | - const TARGET: usize = 30; | |
| 2165 | - let mut decoder = Decoder::new(&display, Codec::H265).expect("decoder opens"); | |
| 2166 | - let mut linear_frame_30 = None; | |
| 2167 | - let mut index = 0usize; | |
| 2168 | - decode_stream(&mut decoder, Codec::H265, &data, 45, |frame| { | |
| 2169 | - if index == TARGET { | |
| 2170 | - linear_frame_30 = Some(frame.to_i420().expect("readback")); | |
| 2171 | - } | |
| 2172 | - index += 1; | |
| 2173 | - }) | |
| 2174 | - .expect("linear decode"); | |
| 2175 | - let linear_frame_30 = linear_frame_30.expect("linear decode reached frame 30"); | |
| 2176 | - | |
| 2177 | - // Find the access unit whose first VCL NAL is the CRA at this GOP | |
| 2178 | - // boundary, and feed the decoder from there on, exactly as a seek would: | |
| 2179 | - // nothing from before it goes in. | |
| 2180 | - let cra_at = units | |
| 2181 | - .iter() | |
| 2182 | - .position(|au| starts_with_cra(au)) | |
| 2183 | - .expect("a CRA access unit exists"); | |
| 2184 | - | |
| 2185 | - // A seek reuses the parameter sets a decoder already learned; a fresh one | |
| 2186 | - // has none, so it is primed the same way `ec_hw::Decoder::reset` expects a | |
| 2187 | - // caller to: decode the leading VPS/SPS/PPS (their IDR picture is thrown | |
| 2188 | - // away) and reset picture state before feeding the seek target. | |
| 2189 | - let mut seek_decoder = Decoder::new(&display, Codec::H265).expect("decoder opens"); | |
| 2190 | - seek_decoder | |
| 2191 | - .decode(units[0], 0) | |
| 2192 | - .expect("prime parameter sets"); | |
| 2193 | - seek_decoder.reset(); | |
| 2194 | - let mut seeked_frame = None; | |
| 2195 | - for (i, unit) in units[cra_at..].iter().enumerate() { | |
| 2196 | - seek_decoder.decode(unit, i as i64).expect("seek decode"); | |
| 2197 | - if let Some(frame) = seek_decoder.next_frame() { | |
| 2198 | - seeked_frame = Some(frame.to_i420().expect("readback")); | |
| 2199 | - break; | |
| 2200 | - } | |
| 2201 | - } | |
| 2202 | - if seeked_frame.is_none() { | |
| 2203 | - seek_decoder.flush().expect("flush"); | |
| 2204 | - seeked_frame = seek_decoder | |
| 2205 | - .next_frame() | |
| 2206 | - .map(|f| f.to_i420().expect("readback")); | |
| 2207 | - } | |
| 2208 | - let seeked_frame = seeked_frame.expect("a frame came out after the seek"); | |
| 2209 | - | |
| 2210 | - assert_eq!( | |
| 2211 | - seeked_frame, linear_frame_30, | |
| 2212 | - "seeking to the CRA before frame 30 handed back a different picture \ | |
| 2213 | - than a linear decode of frame 30 — RASL pictures were not dropped" | |
| 2214 | - ); | |
| 2215 | -} | |
| 2216 | - | |
| 2217 | -/// An H.264 open-GOP I picture is not an IDR: it is a plain I slice | |
| 2218 | -/// (`nal_unit_type` 1) whose predecessors in decode order can still hold | |
| 2219 | -/// references from before it, so leading pictures between it and the next | |
| 2220 | -/// IDR may predict from a picture never decoded since a fresh start there — | |
| 2221 | -/// exactly what a seek does. A decoder started at that I must drop those | |
| 2222 | -/// leading pictures per D.2.8's recovery point default, or its output shifts | |
| 2223 | -/// by however many leading pictures the GOP has. | |
| 2224 | -#[test] | |
| 2225 | -fn h264_seek_matches_linear_open_gop() { | |
| 2226 | - let Some(display) = display() else { return }; | |
| 2227 | - let path = ec_testkit::fixture("video/h264-open-gop.mp4"); | |
| 2228 | - let data = elementary(&path, Codec::H264, 60).expect("elementary stream"); | |
| 2229 | - let units = split_access_units(&data, Codec::H264); | |
| 2230 | - | |
| 2231 | - // Linear decode: every picture from the start, frame 30 kept for | |
| 2232 | - // comparison (the fixture's second I picture, `keyint=30`). | |
| 2233 | - const TARGET: usize = 30; | |
| 2234 | - let mut decoder = Decoder::new(&display, Codec::H264).expect("decoder opens"); | |
| 2235 | - let mut linear_frame_30 = None; | |
| 2236 | - let mut index = 0usize; | |
| 2237 | - decode_stream(&mut decoder, Codec::H264, &data, 60, |frame| { | |
| 2238 | - if index == TARGET { | |
| 2239 | - linear_frame_30 = Some(frame.to_i420().expect("readback")); | |
| 2240 | - } | |
| 2241 | - index += 1; | |
| 2242 | - }) | |
| 2243 | - .expect("linear decode"); | |
| 2244 | - let linear_frame_30 = linear_frame_30.expect("linear decode reached frame 30"); | |
| 2245 | - | |
| 2246 | - // Find the access unit whose first VCL NAL is the open-GOP I picture at | |
| 2247 | - // this GOP boundary, and feed the decoder from there on, exactly as a | |
| 2248 | - // seek would: nothing from before it goes in. | |
| 2249 | - let open_gop_at = units | |
| 2250 | - .iter() | |
| 2251 | - .position(|au| is_open_gop_i(au)) | |
| 2252 | - .expect("an open-GOP I access unit exists"); | |
| 2253 | - | |
| 2254 | - // A seek reuses the parameter sets a decoder already learned; a fresh one | |
| 2255 | - // has none, so it is primed the same way `ec_hw::Decoder::reset` expects a | |
| 2256 | - // caller to: decode the leading IDR (its picture is thrown away) and | |
| 2257 | - // reset picture state before feeding the seek target. | |
| 2258 | - let mut seek_decoder = Decoder::new(&display, Codec::H264).expect("decoder opens"); | |
| 2259 | - seek_decoder | |
| 2260 | - .decode(units[0], 0) | |
| 2261 | - .expect("prime parameter sets"); | |
| 2262 | - seek_decoder.reset(); | |
| 2263 | - let mut seeked_frame = None; | |
| 2264 | - for (i, unit) in units[open_gop_at..].iter().enumerate() { | |
| 2265 | - seek_decoder.decode(unit, i as i64).expect("seek decode"); | |
| 2266 | - if let Some(frame) = seek_decoder.next_frame() { | |
| 2267 | - seeked_frame = Some(frame.to_i420().expect("readback")); | |
| 2268 | - break; | |
| 2269 | - } | |
| 2270 | - } | |
| 2271 | - if seeked_frame.is_none() { | |
| 2272 | - seek_decoder.flush().expect("flush"); | |
| 2273 | - seeked_frame = seek_decoder | |
| 2274 | - .next_frame() | |
| 2275 | - .map(|f| f.to_i420().expect("readback")); | |
| 2276 | - } | |
| 2277 | - let seeked_frame = seeked_frame.expect("a frame came out after the seek"); | |
| 2278 | - | |
| 2279 | - assert_eq!( | |
| 2280 | - seeked_frame, linear_frame_30, | |
| 2281 | - "seeking to the open-GOP I before frame 30 handed back a different \ | |
| 2282 | - picture than a linear decode of frame 30 — leading pictures with \ | |
| 2283 | - missing references were not dropped" | |
| 2284 | - ); | |
| 2285 | -} | |
| 2286 | - | |
| 2287 | -/// True when an access unit's first VCL NAL is an H.264 open-GOP I slice | |
| 2288 | -/// (`nal_unit_type` 1, `slice_type % 5 == 2`), found by scanning for the | |
| 2289 | -/// access unit's first start code rather than assuming a fixed prefix length. | |
| 2290 | -fn is_open_gop_i(au: &[u8]) -> bool { | |
| 2291 | - let mut i = 0usize; | |
| 2292 | - while i + 3 < au.len() { | |
| 2293 | - if au[i] != 0 || au[i + 1] != 0 || au[i + 2] != 1 { | |
| 2294 | - i += 1; | |
| 2295 | - continue; | |
| 2296 | - } | |
| 2297 | - let header = au[i + 3]; | |
| 2298 | - if header & 0x1f != 1 { | |
| 2299 | - return false; | |
| 2300 | - } | |
| 2301 | - let mut r = ec_core::BitReader::new(&au[i + 4..]); | |
| 2302 | - if r.read_ue().is_err() { | |
| 2303 | - return false; | |
| 2304 | - } | |
| 2305 | - return matches!(r.read_ue(), Ok(code) if code % 5 == 2); | |
| 2306 | - } | |
| 2307 | - false | |
| 2308 | -} | |
| 2309 | - | |
| 2310 | -/// True when an access unit's first VCL NAL is an HEVC CRA (`nal_type` 21). | |
| 2311 | -/// A CRA's access unit may open with its own VPS/SPS/PPS, so this skips past | |
| 2312 | -/// non-VCL NALs to the first one that carries a slice. | |
| 2313 | -fn starts_with_cra(au: &[u8]) -> bool { | |
| 2314 | - let mut i = 0usize; | |
| 2315 | - while i + 3 < au.len() { | |
| 2316 | - if au[i] == 0 && au[i + 1] == 0 && au[i + 2] == 1 { | |
| 2317 | - let t = (au[i + 3] >> 1) & 0x3f; | |
| 2318 | - if t <= 31 { | |
| 2319 | - return t == 21; | |
| 2320 | - } | |
| 2321 | - i += 3; | |
| 2322 | - continue; | |
| 2323 | - } | |
| 2324 | - i += 1; | |
| 2325 | - } | |
| 2326 | - false | |
| 2327 | -} | |
| 2328 | - | |
| 2329 | -/// `ffmpeg -bsf:v trace_headers` over a bitstream, returning every | |
| 2330 | -/// `name = value` line it prints — the slice header fields the driver wrote. | |
| 2331 | -fn trace_headers(path: &Path, codec: &str) -> Vec<(String, i64)> { | |
| 2332 | - let out = ec_testkit::ffmpeg() | |
| 2333 | - .args(["-v", "trace", "-hide_banner", "-nostats", "-f", codec, "-i"]) | |
| 2334 | - .arg(path) | |
| 2335 | - .args(["-c:v", "copy", "-bsf:v", "trace_headers", "-f", "null", "-"]) | |
| 2336 | - .output() | |
| 2337 | - .expect("ffmpeg runs"); | |
| 2338 | - let text = String::from_utf8_lossy(&out.stderr); | |
| 2339 | - text.lines() | |
| 2340 | - .filter_map(|line| { | |
| 2341 | - // "[trace_headers @ 0x...] 16 frame_num 0000 = 0" | |
| 2342 | - let (lhs, value) = line.rsplit_once(" = ")?; | |
| 2343 | - let mut words = lhs.split_whitespace().rev(); | |
| 2344 | - let _bits = words.next()?; | |
| 2345 | - let name = words.next()?; | |
| 2346 | - Some((name.to_string(), value.trim().parse().ok()?)) | |
| 2347 | - }) | |
| 2348 | - .collect() | |
| 2349 | -} | |
| 2350 | - | |
| 2351 | -/// Phone-class stateful decoders order output from `frame_num` and the POC | |
| 2352 | -/// fields, so a stream whose every slice says 0/0 judders there even though | |
| 2353 | -/// desktop decoders (which re-derive from decode order) play it cleanly. | |
| 2354 | -/// Encode a long P-run and read the fields back the way such a decoder does. | |
| 2355 | -fn slice_counters( | |
| 2356 | - codec: EncCodec, | |
| 2357 | - width: u32, | |
| 2358 | - height: u32, | |
| 2359 | - frames: u32, | |
| 2360 | -) -> (PathBuf, Vec<(String, i64)>) { | |
| 2361 | - let Some(display) = display() else { | |
| 2362 | - return (PathBuf::new(), Vec::new()); | |
| 2363 | - }; | |
| 2364 | - let mut config = EncoderConfig::new(codec, width, height); | |
| 2365 | - config.gop_size = frames * 2; | |
| 2366 | - config.framerate = (30, 1); | |
| 2367 | - config.rate_control = RateControlMode::ConstantQp { qp: 30 }; | |
| 2368 | - let mut encoder = Encoder::new(&display, config).expect("encoder"); | |
| 2369 | - let mut out = Vec::new(); | |
| 2370 | - for t in 0..frames { | |
| 2371 | - let coded = encoder | |
| 2372 | - .encode( | |
| 2373 | - &source_frame(width, height, t), | |
| 2374 | - FrameMetadata { | |
| 2375 | - timestamp: i64::from(t), | |
| 2376 | - force_keyframe: false, | |
| 2377 | - }, | |
| 2378 | - ) | |
| 2379 | - .expect("encode"); | |
| 2380 | - assert_eq!(coded.is_keyframe, t == 0, "one IDR then P-frames at {t}"); | |
| 2381 | - out.extend_from_slice(&coded.data); | |
| 2382 | - } | |
| 2383 | - let dir = std::env::temp_dir().join(format!("ec-hw-counters-{codec:?}")); | |
| 2384 | - std::fs::create_dir_all(&dir).expect("temp dir"); | |
| 2385 | - let (name, fmt) = match codec { | |
| 2386 | - EncCodec::H264 => ("out.264", "h264"), | |
| 2387 | - EncCodec::H265 => ("out.265", "hevc"), | |
| 2388 | - EncCodec::Av1 => unreachable!(), | |
| 2389 | - }; | |
| 2390 | - let path = dir.join(name); | |
| 2391 | - std::fs::write(&path, &out).expect("write"); | |
| 2392 | - let fields = trace_headers(&path, fmt); | |
| 2393 | - (path, fields) | |
| 2394 | -} | |
| 2395 | - | |
| 2396 | -fn values(fields: &[(String, i64)], name: &str) -> Vec<i64> { | |
| 2397 | - fields | |
| 2398 | - .iter() | |
| 2399 | - .filter(|(n, _)| n == name) | |
| 2400 | - .map(|(_, v)| *v) | |
| 2401 | - .collect() | |
| 2402 | -} | |
| 2403 | - | |
| 2404 | -#[test] | |
| 2405 | -fn h264_slice_headers_count_frames_for_stateful_decoders() { | |
| 2406 | - let frames = 64u32; | |
| 2407 | - let (path, fields) = slice_counters(EncCodec::H264, 640, 360, frames); | |
| 2408 | - if fields.is_empty() { | |
| 2409 | - return; | |
| 2410 | - } | |
| 2411 | - let frame_num = values(&fields, "frame_num"); | |
| 2412 | - assert_eq!( | |
| 2413 | - frame_num.len(), | |
| 2414 | - frames as usize, | |
| 2415 | - "one slice per picture in {}", | |
| 2416 | - path.display() | |
| 2417 | - ); | |
| 2418 | - let log2_max = values(&fields, "log2_max_frame_num_minus4")[0] + 4; | |
| 2419 | - let max_frame_num = 1i64 << log2_max; | |
| 2420 | - let expected: Vec<i64> = (0..frames as i64).map(|n| n % max_frame_num).collect(); | |
| 2421 | - assert_eq!( | |
| 2422 | - frame_num, expected, | |
| 2423 | - "frame_num steps +1 mod {max_frame_num}" | |
| 2424 | - ); | |
| 2425 | - // pic_order_cnt_type 2: POC = 2 * FrameNumOffset-adjusted frame_num, no lsb is | |
| 2426 | - // written — the decoder's output order is the decode order by construction. | |
| 2427 | - let poc_type = values(&fields, "pic_order_cnt_type"); | |
| 2428 | - assert!( | |
| 2429 | - !poc_type.is_empty() && poc_type.iter().all(|&t| t == 2), | |
| 2430 | - "POC type 2 in the SPS: {poc_type:?}" | |
| 2431 | - ); | |
| 2432 | - assert!( | |
| 2433 | - values(&fields, "pic_order_cnt_lsb").is_empty(), | |
| 2434 | - "no POC lsb under type 2" | |
| 2435 | - ); | |
| 2436 | - assert!( | |
| 2437 | - values(&fields, "level_idc").iter().all(|&l| l == 30), | |
| 2438 | - "640x360@30 is level 3.0" | |
| 2439 | - ); | |
| 2440 | -} | |
| 2441 | - | |
| 2442 | -#[test] | |
| 2443 | -fn hevc_slice_headers_count_pocs_for_stateful_decoders() { | |
| 2444 | - let frames = 64u32; | |
| 2445 | - let (path, fields) = slice_counters(EncCodec::H265, 640, 360, frames); | |
| 2446 | - if fields.is_empty() { | |
| 2447 | - return; | |
| 2448 | - } | |
| 2449 | - let lsb = values(&fields, "slice_pic_order_cnt_lsb"); | |
| 2450 | - assert_eq!( | |
| 2451 | - lsb.len(), | |
| 2452 | - frames as usize - 1, | |
| 2453 | - "every non-IDR slice carries a POC lsb in {}", | |
| 2454 | - path.display() | |
| 2455 | - ); | |
| 2456 | - let log2_max = values(&fields, "log2_max_pic_order_cnt_lsb_minus4")[0] + 4; | |
| 2457 | - let max_lsb = 1i64 << log2_max; | |
| 2458 | - let expected: Vec<i64> = (1..frames as i64).map(|n| n % max_lsb).collect(); | |
| 2459 | - assert_eq!(lsb, expected, "POC lsb steps +1 mod {max_lsb}"); | |
| 2460 | -} | |
| 2461 | - | |
| 2462 | -// --------------------------------------------------------------------------- | |
| 2463 | -// Rate control: achieved bitrate against the request, and PSNR at that rate | |
| 2464 | -// --------------------------------------------------------------------------- | |
| 2465 | - | |
| 2466 | -/// Write 8-bit 4:2:0 frames as a y4m file, the reference ffmpeg compares with. | |
| 2467 | -fn write_y4m_8(path: &Path, frames: &[I420], fps: u32) -> bool { | |
| 2468 | - use std::io::Write; | |
| 2469 | - let Some(first) = frames.first() else { | |
| 2470 | - return false; | |
| 2471 | - }; | |
| 2472 | - let Ok(file) = std::fs::File::create(path) else { | |
| 2473 | - return false; | |
| 2474 | - }; | |
| 2475 | - let mut out = std::io::BufWriter::new(file); | |
| 2476 | - let header = format!( | |
| 2477 | - "YUV4MPEG2 W{} H{} F{fps}:1 Ip A1:1 C420jpeg\n", | |
| 2478 | - first.width, first.height | |
| 2479 | - ); | |
| 2480 | - if out.write_all(header.as_bytes()).is_err() { | |
| 2481 | - return false; | |
| 2482 | - } | |
| 2483 | - for f in frames { | |
| 2484 | - if out.write_all(b"FRAME\n").is_err() | |
| 2485 | - || out.write_all(&f.y).is_err() | |
| 2486 | - || out.write_all(&f.u).is_err() | |
| 2487 | - || out.write_all(&f.v).is_err() | |
| 2488 | - { | |
| 2489 | - return false; | |
| 2490 | - } | |
| 2491 | - } | |
| 2492 | - out.flush().is_ok() | |
| 2493 | -} | |
| 2494 | - | |
| 2495 | -/// Average PSNR (dB) of a raw elementary stream against its source y4m. | |
| 2496 | -fn psnr_of_elementary(coded: &Path, format: &str, source: &Path, fps: u32) -> Option<f64> { | |
| 2497 | - let rate = fps.to_string(); | |
| 2498 | - let out = ec_testkit::ffmpeg() | |
| 2499 | - .args(["-nostdin", "-v", "info", "-f", format, "-r", &rate, "-i"]) | |
| 2500 | - .arg(coded) | |
| 2501 | - .args(["-r", &rate, "-i"]) | |
| 2502 | - .arg(source) | |
| 2503 | - .args(["-lavfi", "psnr", "-f", "null", "-"]) | |
| 2504 | - .output() | |
| 2505 | - .ok()?; | |
| 2506 | - let text = String::from_utf8_lossy(&out.stderr); | |
| 2507 | - let field = text.split("average:").nth(1)?; | |
| 2508 | - field | |
| 2509 | - .split_whitespace() | |
| 2510 | - .next()? | |
| 2511 | - .parse::<f64>() | |
| 2512 | - .ok() | |
| 2513 | - .filter(|v| v.is_finite()) | |
| 2514 | -} | |
| 2515 | - | |
| 2516 | -/// One CBR encode of `frames` at `bitrate`: the stream, and the bits per second | |
| 2517 | -/// it actually spent over the clip. | |
| 2518 | -fn cbr_encode( | |
| 2519 | - display: &Rc<Display>, | |
| 2520 | - codec: EncCodec, | |
| 2521 | - (width, height, fps): (u32, u32, u32), | |
| 2522 | - bitrate: u32, | |
| 2523 | - frames: &[I420], | |
| 2524 | -) -> Result<(Vec<u8>, f64), ec_hw::Error> { | |
| 2525 | - let mut config = EncoderConfig::new(codec, width, height); | |
| 2526 | - config.framerate = (fps, 1); | |
| 2527 | - config.gop_size = 30; | |
| 2528 | - config.bitrate = bitrate; | |
| 2529 | - config.rate_control = RateControlMode::ConstantBitrate; | |
| 2530 | - let mut encoder = Encoder::new(display, config)?; | |
| 2531 | - let mut out = Vec::new(); | |
| 2532 | - for (t, frame) in frames.iter().enumerate() { | |
| 2533 | - let coded = encoder.encode( | |
| 2534 | - frame, | |
| 2535 | - FrameMetadata { | |
| 2536 | - timestamp: t as i64, | |
| 2537 | - force_keyframe: false, | |
| 2538 | - }, | |
| 2539 | - )?; | |
| 2540 | - out.extend_from_slice(&coded.data); | |
| 2541 | - } | |
| 2542 | - let delivered = out.len() as f64 * 8.0 * f64::from(fps) / frames.len() as f64; | |
| 2543 | - Ok((out, delivered)) | |
| 2544 | -} | |
| 2545 | - | |
| 2546 | -/// CBR must land within +/-5% of the request on every codec, clip and rate, | |
| 2547 | -/// and the PSNR it reaches at that rate is printed for the report. | |
| 2548 | -#[test] | |
| 2549 | -fn cbr_lands_within_five_percent_of_the_request() { | |
| 2550 | - let Some(display) = display() else { return }; | |
| 2551 | - // 8 s: a 2 s clip also carries the start-up of the rate controller, which | |
| 2552 | - // is measured apart from the steady-state rate the request is about. | |
| 2553 | - let (width, height, fps, frames) = (1280u32, 720u32, 30u32, 240u32); | |
| 2554 | - let dir = std::env::temp_dir().join("ec-hw-rc-measure"); | |
| 2555 | - std::fs::create_dir_all(&dir).expect("temp dir"); | |
| 2556 | - | |
| 2557 | - // Two clips: a synthetic moving box, and ffmpeg's testsrc2 (the content the | |
| 2558 | - // edith measurements used), both generated here so nothing depends on a | |
| 2559 | - // personal library. | |
| 2560 | - let synthetic: Vec<I420> = (0..frames) | |
| 2561 | - .map(|t| source_frame(width, height, t)) | |
| 2562 | - .collect(); | |
| 2563 | - let synthetic_y4m = dir.join("cbr-synthetic.y4m"); | |
| 2564 | - assert!(write_y4m_8(&synthetic_y4m, &synthetic, fps), "write source"); | |
| 2565 | - let testsrc_y4m = dir.join("cbr-testsrc2.y4m"); | |
| 2566 | - let generated = ec_testkit::ffmpeg() | |
| 2567 | - .args(["-nostdin", "-v", "error", "-y", "-f", "lavfi", "-i"]) | |
| 2568 | - .arg(format!("testsrc2=size={width}x{height}:rate={fps}")) | |
| 2569 | - .args(["-frames:v", &frames.to_string(), "-pix_fmt", "yuv420p"]) | |
| 2570 | - .arg(&testsrc_y4m) | |
| 2571 | - .status() | |
| 2572 | - .is_ok_and(|s| s.success()); | |
| 2573 | - let testsrc = generated | |
| 2574 | - .then(|| raw_frames(&testsrc_y4m, width, height, frames)) | |
| 2575 | - .flatten() | |
| 2576 | - .expect("ffmpeg generates testsrc2"); | |
| 2577 | - let clips: [(&str, Vec<I420>, PathBuf); 2] = [ | |
| 2578 | - ("moving box", synthetic, synthetic_y4m), | |
| 2579 | - ("testsrc2", testsrc, testsrc_y4m), | |
| 2580 | - ]; | |
| 2581 | - let mut failures = Vec::new(); | |
| 2582 | - println!("CBR, {width}x{height} {fps} fps, {frames} frames:"); | |
| 2583 | - for (codec, name, format) in [ | |
| 2584 | - (EncCodec::H264, "H.264", "h264"), | |
| 2585 | - (EncCodec::H265, "HEVC", "hevc"), | |
| 2586 | - (EncCodec::Av1, "AV1", "obu"), | |
| 2587 | - ] { | |
| 2588 | - for (clip_name, pictures, source) in &clips { | |
| 2589 | - for target in [1_000_000u32, 3_000_000, 8_000_000] { | |
| 2590 | - let (stream, delivered) = | |
| 2591 | - match cbr_encode(&display, codec, (width, height, fps), target, pictures) { | |
| 2592 | - Ok(encoded) => encoded, | |
| 2593 | - Err(e) => panic!("{name} {clip_name} at {target} bps: encode failed ({e})"), | |
| 2594 | - }; | |
| 2595 | - let coded = dir.join(format!( | |
| 2596 | - "{name}-{}-{target}.{format}", | |
| 2597 | - clip_name.replace(' ', "-") | |
| 2598 | - )); | |
| 2599 | - std::fs::write(&coded, &stream).expect("write stream"); | |
| 2600 | - let db = psnr_of_elementary(&coded, format, source, fps).unwrap_or(f64::NAN); | |
| 2601 | - let error = delivered / f64::from(target) - 1.0; | |
| 2602 | - println!( | |
| 2603 | - " {name:<6} {clip_name:<12} target {:>5} kbps -> {:>6.0} kbps ({:+5.1}%), {db:.2} dB", | |
| 2604 | - target / 1000, | |
| 2605 | - delivered / 1000.0, | |
| 2606 | - error * 100.0 | |
| 2607 | - ); | |
| 2608 | - if error.abs() > 0.05 { | |
| 2609 | - failures.push(format!( | |
| 2610 | - "{name} {clip_name} at {target} bps: {:+.1}%", | |
| 2611 | - error * 100.0 | |
| 2612 | - )); | |
| 2613 | - } | |
| 2614 | - } | |
| 2615 | - } | |
| 2616 | - } | |
| 2617 | - assert!(failures.is_empty(), "outside +/-5%: {failures:?}"); | |
| 2618 | -} | |
| 2619 | - | |
| 2620 | -fn imported_nv12( | |
| 2621 | - display: &Rc<Display>, | |
| 2622 | - frame: &I420, | |
| 2623 | -) -> Rc<ec_va::va::Surface<ec_va::surface::PrimeImport>> { | |
| 2624 | - use ec_va::SurfaceExt; | |
| 2625 | - | |
| 2626 | - let (w, h) = (frame.width, frame.height); | |
| 2627 | - let mut pool = | |
| 2628 | - ec_va::create_pool(display, &ec_va::SurfaceSpec::nv12(w, h), 1).expect("surface"); | |
| 2629 | - let surface = pool.pop().expect("one surface"); | |
| 2630 | - { | |
| 2631 | - let format = | |
| 2632 | - ec_va::surface::image_format(display, ec_va::va::VA_FOURCC_NV12).expect("format"); | |
| 2633 | - let mut image = | |
| 2634 | - ec_va::surface::create_image(&surface, format, (w, h), (w, h)).expect("image"); | |
| 2635 | - let layout = *image.image(); | |
| 2636 | - let data = AsMut::<[u8]>::as_mut(&mut image); | |
| 2637 | - let (wu, hu) = (w as usize, h as usize); | |
| 2638 | - let (cw, ch) = (wu.div_ceil(2), hu.div_ceil(2)); | |
| 2639 | - for row in 0..hu { | |
| 2640 | - let d = layout.offsets[0] as usize + row * layout.pitches[0] as usize; | |
| 2641 | - data[d..d + wu].copy_from_slice(&frame.y[row * wu..row * wu + wu]); | |
| 2642 | - } | |
| 2643 | - for row in 0..ch { | |
| 2644 | - let d = layout.offsets[1] as usize + row * layout.pitches[1] as usize; | |
| 2645 | - for col in 0..cw { | |
| 2646 | - data[d + col * 2] = frame.u[row * cw + col]; | |
| 2647 | - data[d + col * 2 + 1] = frame.v[row * cw + col]; | |
| 2648 | - } | |
| 2649 | - } | |
| 2650 | - } | |
| 2651 | - let prime = surface.export().expect("export"); | |
| 2652 | - let objects: Vec<ec_va::RawPrimeObject> = prime | |
| 2653 | - .objects | |
| 2654 | - .iter() | |
| 2655 | - .map(|o| ec_va::RawPrimeObject { | |
| 2656 | - fd: std::os::fd::AsRawFd::as_raw_fd(&o.fd), | |
| 2657 | - size: o.size, | |
| 2658 | - modifier: o.modifier, | |
| 2659 | - }) | |
| 2660 | - .collect(); | |
| 2661 | - let imported = ec_va::import_prime_raw( | |
| 2662 | - display, | |
| 2663 | - prime.fourcc, | |
| 2664 | - (prime.width, prime.height), | |
| 2665 | - &objects, | |
| 2666 | - &prime.layers, | |
| 2667 | - ) | |
| 2668 | - .expect("import"); | |
| 2669 | - drop(prime); | |
| 2670 | - Rc::new(imported) | |
| 2671 | -} | |
| 2672 | - | |
| 2673 | -/// Encoding an imported DMA-BUF must give the bytes the CPU path gives for the | |
| 2674 | -/// same pixels: the import is only a different way of handing over the source. | |
| 2675 | -#[test] | |
| 2676 | -fn encode_surface_of_an_imported_dma_buf_matches_the_cpu_path() { | |
| 2677 | - let Some(display) = display() else { return }; | |
| 2678 | - let (w, h) = (640u32, 480u32); | |
| 2679 | - for codec in [EncCodec::H264, EncCodec::H265] { | |
| 2680 | - let mut config = EncoderConfig::new(codec, w, h); | |
| 2681 | - config.gop_size = 3; | |
| 2682 | - config.rate_control = RateControlMode::ConstantQp { qp: 30 }; | |
| 2683 | - let mut cpu = Encoder::new(&display, config).expect("cpu encoder"); | |
| 2684 | - let mut dma = Encoder::new(&display, config).expect("dma encoder"); | |
| 2685 | - for t in 0..4u32 { | |
| 2686 | - let frame = source_frame(w, h, t); | |
| 2687 | - let meta = FrameMetadata { | |
| 2688 | - timestamp: i64::from(t), | |
| 2689 | - force_keyframe: false, | |
| 2690 | - }; | |
| 2691 | - let want = cpu.encode(&frame, meta).expect("cpu encode"); | |
| 2692 | - let surface = imported_nv12(&display, &frame); | |
| 2693 | - let got = dma | |
| 2694 | - .encode_surface(&surface, (w, h), meta) | |
| 2695 | - .expect("encode_surface"); | |
| 2696 | - assert_eq!(got.is_keyframe, want.is_keyframe, "{codec:?} frame {t}"); | |
| 2697 | - assert_eq!( | |
| 2698 | - got.data.len(), | |
| 2699 | - want.data.len(), | |
| 2700 | - "{codec:?} frame {t}: imported source coded to a different size" | |
| 2701 | - ); | |
| 2702 | - assert!(got.data == want.data, "{codec:?} frame {t}: bytes differ"); | |
| 2703 | - } | |
| 2704 | - } | |
| 2705 | -} | |
| 2706 | - | |
| 2707 | -// --------------------------------------------------------------------------- | |
| 2708 | -// Broken streams: an inter picture whose references were never decoded | |
| 2709 | -// --------------------------------------------------------------------------- | |
| 2710 | - | |
| 2711 | -/// The OBUs of an AV1 temporal unit, as whole byte slices (each with its header). | |
| 2712 | -fn av1_obus(tu: &[u8]) -> Vec<&[u8]> { | |
| 2713 | - let mut out = Vec::new(); | |
| 2714 | - let mut i = 0usize; | |
| 2715 | - while i < tu.len() { | |
| 2716 | - let header = tu[i]; | |
| 2717 | - let ext = usize::from((header >> 2) & 1); | |
| 2718 | - if (header >> 1) & 1 == 0 { | |
| 2719 | - break; // no obu_size: the rest of the unit is one OBU | |
| 2720 | - } | |
| 2721 | - let mut size = 0usize; | |
| 2722 | - let mut pos = i + 1 + ext; | |
| 2723 | - for shift in (0..64).step_by(7) { | |
| 2724 | - let Some(&byte) = tu.get(pos) else { return out }; | |
| 2725 | - pos += 1; | |
| 2726 | - size |= usize::from(byte & 0x7f) << shift; | |
| 2727 | - if byte & 0x80 == 0 { | |
| 2728 | - break; | |
| 2729 | - } | |
| 2730 | - } | |
| 2731 | - let end = (pos + size).min(tu.len()); | |
| 2732 | - out.push(&tu[i..end]); | |
| 2733 | - i = end; | |
| 2734 | - } | |
| 2735 | - out | |
| 2736 | -} | |
| 2737 | - | |
| 2738 | -/// The Annex B NAL units of an access unit, without their start codes. | |
| 2739 | -fn annexb_nals(au: &[u8]) -> Vec<&[u8]> { | |
| 2740 | - let mut starts = Vec::new(); | |
| 2741 | - let mut i = 0usize; | |
| 2742 | - while i + 3 <= au.len() { | |
| 2743 | - if au[i] == 0 && au[i + 1] == 0 && au[i + 2] == 1 { | |
| 2744 | - starts.push(i + 3); | |
| 2745 | - i += 3; | |
| 2746 | - } else { | |
| 2747 | - i += 1; | |
| 2748 | - } | |
| 2749 | - } | |
| 2750 | - starts | |
| 2751 | - .iter() | |
| 2752 | - .enumerate() | |
| 2753 | - .map(|(n, &start)| { | |
| 2754 | - let end = starts.get(n + 1).map_or(au.len(), |&next| next - 3); | |
| 2755 | - let mut nal = &au[start..end]; | |
| 2756 | - while let [rest @ .., 0] = nal { | |
| 2757 | - nal = rest; // trailing zeros belong to the next start code | |
| 2758 | - } | |
| 2759 | - nal | |
| 2760 | - }) | |
| 2761 | - .collect() | |
| 2762 | -} | |
| 2763 | - | |
| 2764 | -/// A stream that starts at an inter picture: the parameter sets of the first | |
| 2765 | -/// access unit, then the access unit that follows it, with the picture that | |
| 2766 | -/// would have filled its references (the first access unit) left out. | |
| 2767 | -fn broken_gop(codec: Codec, data: &[u8]) -> Option<Vec<u8>> { | |
| 2768 | - let mut stream = Vec::new(); | |
| 2769 | - match codec { | |
| 2770 | - Codec::Av1 => { | |
| 2771 | - let units = split_ivf(data); | |
| 2772 | - // The sequence header OBU, which the first temporal unit carries. | |
| 2773 | - let seq = av1_obus(units.first()?) | |
| 2774 | - .into_iter() | |
| 2775 | - .find(|obu| (obu[0] >> 3) & 0xf == 1)?; | |
| 2776 | - stream.extend_from_slice(seq); | |
| 2777 | - stream.extend_from_slice(units.get(1)?); | |
| 2778 | - } | |
| 2779 | - Codec::Vp9 => { | |
| 2780 | - // VP9 carries its parameters in the frame header: the inter frame | |
| 2781 | - // alone is the broken stream. | |
| 2782 | - stream.extend_from_slice(split_ivf(data).get(1)?); | |
| 2783 | - } | |
| 2784 | - Codec::H264 | Codec::H265 => { | |
| 2785 | - let units = split_access_units(data, codec); | |
| 2786 | - let is_parameter_set = |nal: &[u8]| { | |
| 2787 | - let t = match codec { | |
| 2788 | - Codec::H264 => nal[0] & 0x1f, | |
| 2789 | - _ => (nal[0] >> 1) & 0x3f, | |
| 2790 | - }; | |
| 2791 | - match codec { | |
| 2792 | - Codec::H264 => t == 7 || t == 8, | |
| 2793 | - _ => (32..=34).contains(&t), | |
| 2794 | - } | |
| 2795 | - }; | |
| 2796 | - for nal in annexb_nals(units.first()?) { | |
| 2797 | - if is_parameter_set(nal) { | |
| 2798 | - stream.extend_from_slice(&[0, 0, 0, 1]); | |
| 2799 | - stream.extend_from_slice(nal); | |
| 2800 | - } | |
| 2801 | - } | |
| 2802 | - stream.extend_from_slice(units.get(1)?); | |
| 2803 | - } | |
| 2804 | - } | |
| 2805 | - Some(stream) | |
| 2806 | -} | |
| 2807 | - | |
| 2808 | -/// Each codec's broken GOP is refused with an error at the first access unit | |
| 2809 | -/// that needs the missing picture, and never produces a picture. Refusing an | |
| 2810 | -/// inter frame whose references were never filled is what the software | |
| 2811 | -/// decoders do (ec-av1: "no saved CDF state"). | |
| 2812 | -#[test] | |
| 2813 | -fn a_broken_gop_is_refused_on_every_codec() { | |
| 2814 | - let Some(display) = display() else { return }; | |
| 2815 | - let cases = [ | |
| 2816 | - (Codec::Av1, "av1-1080p-23.976-8bit.ivf"), | |
| 2817 | - (Codec::Vp9, "vp9-1080p-23.976-8bit.ivf"), | |
| 2818 | - (Codec::H264, "h264-bframes-320.264"), | |
| 2819 | - (Codec::H265, "hevc-bframes-320.265"), | |
| 2820 | - ]; | |
| 2821 | - for (codec, name) in cases { | |
| 2822 | - let path = ec_testkit::fixture(&format!("bitstreams/{name}")); | |
| 2823 | - let data = std::fs::read(&path).expect("fixture is readable"); | |
| 2824 | - let stream = broken_gop(codec, &data).expect("the fixture has a second access unit"); | |
| 2825 | - let mut decoder = Decoder::new(&display, codec).expect("decoder"); | |
| 2826 | - let refusal = decoder.decode(&stream, 0).err().map(|e| e.to_string()); | |
| 2827 | - let mut pictures = 0usize; | |
| 2828 | - while decoder.next_frame().is_some() { | |
| 2829 | - pictures += 1; | |
| 2830 | - } | |
| 2831 | - assert!( | |
| 2832 | - refusal.is_some(), | |
| 2833 | - "{codec:?} {name}: the broken GOP decoded without an error ({pictures} pictures)" | |
| 2834 | - ); |
crates/ec-hw/tests/idr_counting.rsmodified+3 -11
| @@ -10,24 +10,16 @@ | ||
| 10 | 10 | |
| 11 | 11 | use std::path::{Path, PathBuf}; |
| 12 | 12 | use std::process::Stdio; |
| 13 | -use std::rc::Rc; | |
| 14 | 13 | |
| 15 | 14 | use ec_hw::{EncCodec, Encoder, EncoderConfig, FrameMetadata, I420, RateControlMode}; |
| 16 | -use ec_va::Display; | |
| 15 | + | |
| 16 | +mod common; | |
| 17 | +use common::display; | |
| 17 | 18 | |
| 18 | 19 | const WIDTH: u32 = 384; |
| 19 | 20 | const HEIGHT: u32 = 256; |
| 20 | 21 | const FPS: u32 = 30; |
| 21 | 22 | |
| 22 | -fn display() -> Option<Rc<Display>> { | |
| 23 | - match ec_va::open() { | |
| 24 | - Ok(display) => Some(display), | |
| 25 | - Err(e) => { | |
| 26 | - eprintln!("skipped: no VA display ({e})"); | |
| 27 | - None | |
| 28 | - } | |
| 29 | - } | |
| 30 | -} | |
| 31 | 23 | |
| 32 | 24 | fn scratch(name: &str) -> PathBuf { |
| 33 | 25 | let dir = std::env::temp_dir().join(format!("ec-hw-idr-{name}")); |
crates/ec-vk/examples/av1_encode.rsdeleted+0 -77
| @@ -1,77 +0,0 @@ | ||
| 1 | -use ec_vk::{Av1Encoder, Av1EncoderConfig, Gpu, RateControl}; | |
| 2 | - | |
| 3 | -const W: u32 = 1280; | |
| 4 | -const H: u32 = 720; | |
| 5 | -const FPS: u32 = 30; | |
| 6 | -const FRAMES: u32 = 60; | |
| 7 | - | |
| 8 | -fn frame(n: u32) -> (Vec<u8>, Vec<u8>, Vec<u8>) { | |
| 9 | - let y = (0..H) | |
| 10 | - .flat_map(|row| (0..W).map(move |col| ((col + row + 4 * n) % 256) as u8)) | |
| 11 | - .collect(); | |
| 12 | - let u = (0..H / 2) | |
| 13 | - .flat_map(|_| (0..W / 2).map(move |col| ((col * 2 + n) % 256) as u8)) | |
| 14 | - .collect(); | |
| 15 | - let v = (0..H / 2) | |
| 16 | - .flat_map(|row| (0..W / 2).map(move |_| ((row * 2 + 2 * n) % 256) as u8)) | |
| 17 | - .collect(); | |
| 18 | - (y, u, v) | |
| 19 | -} | |
| 20 | - | |
| 21 | -fn main() { | |
| 22 | - let path = std::env::args() | |
| 23 | - .nth(1) | |
| 24 | - .expect("usage: av1_encode <out.ivf> [cbr_bitrate]"); | |
| 25 | - let gpu = Gpu::open().expect("open Vulkan Video device"); | |
| 26 | - let cfg = Av1EncoderConfig { | |
| 27 | - width: W, | |
| 28 | - height: H, | |
| 29 | - fps: (FPS, 1), | |
| 30 | - level: 23, | |
| 31 | - gop_size: 30, | |
| 32 | - rate: match std::env::args().nth(2) { | |
| 33 | - Some(b) => RateControl::Cbr { | |
| 34 | - bitrate: b.parse().expect("bitrate"), | |
| 35 | - buffer_ms: 1000, | |
| 36 | - }, | |
| 37 | - None => RateControl::ConstantQp { qp: 26 }, | |
| 38 | - }, | |
| 39 | - bit_depth: 8, | |
| 40 | - colour: None, | |
| 41 | - quality: 0, | |
| 42 | - }; | |
| 43 | - let mut encoder = Av1Encoder::new(&gpu, cfg).expect("create encoder"); | |
| 44 | - | |
| 45 | - let mut out = Vec::new(); | |
| 46 | - out.extend_from_slice(b"DKIF"); | |
| 47 | - out.extend_from_slice(&0u16.to_le_bytes()); | |
| 48 | - out.extend_from_slice(&32u16.to_le_bytes()); | |
| 49 | - out.extend_from_slice(b"AV01"); | |
| 50 | - out.extend_from_slice(&(W as u16).to_le_bytes()); | |
| 51 | - out.extend_from_slice(&(H as u16).to_le_bytes()); | |
| 52 | - out.extend_from_slice(&FPS.to_le_bytes()); | |
| 53 | - out.extend_from_slice(&1u32.to_le_bytes()); | |
| 54 | - out.extend_from_slice(&FRAMES.to_le_bytes()); | |
| 55 | - out.extend_from_slice(&0u32.to_le_bytes()); | |
| 56 | - | |
| 57 | - let mut total = 0usize; | |
| 58 | - for n in 0..FRAMES { | |
| 59 | - let (y, u, v) = frame(n); | |
| 60 | - let coded = encoder.encode(&y, &u, &v, false).expect("encode frame"); | |
| 61 | - println!( | |
| 62 | - "frame {n}: {} bytes keyframe {}", | |
| 63 | - coded.data.len(), | |
| 64 | - coded.keyframe | |
| 65 | - ); | |
| 66 | - out.extend_from_slice(&(coded.data.len() as u32).to_le_bytes()); | |
| 67 | - out.extend_from_slice(&(n as u64).to_le_bytes()); | |
| 68 | - out.extend_from_slice(&coded.data); | |
| 69 | - total += coded.data.len(); | |
| 70 | - } | |
| 71 | - let seconds = FRAMES as f64 / FPS as f64; | |
| 72 | - println!( | |
| 73 | - "total {total} bytes, {:.1} kb/s", | |
| 74 | - total as f64 * 8.0 / seconds / 1000.0 | |
| 75 | - ); | |
| 76 | - std::fs::write(&path, out).expect("write output"); | |
| 77 | -} |
crates/ec-vk/examples/h264_encode.rsdeleted+0 -55
| @@ -1,55 +0,0 @@ | ||
| 1 | -use ec_vk::{Gpu, H264Encoder, H264EncoderConfig, H264Profile, RateControl}; | |
| 2 | - | |
| 3 | -const W: u32 = 1280; | |
| 4 | -const H: u32 = 720; | |
| 5 | -const FRAMES: u32 = 60; | |
| 6 | - | |
| 7 | -fn frame(n: u32) -> (Vec<u8>, Vec<u8>, Vec<u8>) { | |
| 8 | - let y = (0..H) | |
| 9 | - .flat_map(|row| (0..W).map(move |col| ((col + row + 4 * n) % 256) as u8)) | |
| 10 | - .collect(); | |
| 11 | - let u = (0..H / 2) | |
| 12 | - .flat_map(|_| (0..W / 2).map(move |col| ((col * 2 + n) % 256) as u8)) | |
| 13 | - .collect(); | |
| 14 | - let v = (0..H / 2) | |
| 15 | - .flat_map(|row| (0..W / 2).map(move |_| ((row * 2 + 2 * n) % 256) as u8)) | |
| 16 | - .collect(); | |
| 17 | - (y, u, v) | |
| 18 | -} | |
| 19 | - | |
| 20 | -fn main() { | |
| 21 | - let path = std::env::args() | |
| 22 | - .nth(1) | |
| 23 | - .expect("usage: h264_encode <out.h264>"); | |
| 24 | - let gpu = Gpu::open().expect("open Vulkan Video device"); | |
| 25 | - let cfg = H264EncoderConfig { | |
| 26 | - width: W, | |
| 27 | - height: H, | |
| 28 | - fps: (30, 1), | |
| 29 | - level: 62, | |
| 30 | - gop_size: 30, | |
| 31 | - profile: H264Profile::High, | |
| 32 | - colour: None, | |
| 33 | - quality: 0, | |
| 34 | - rate: match std::env::args().nth(2) { | |
| 35 | - Some(b) => RateControl::Cbr { | |
| 36 | - bitrate: b.parse().expect("bitrate"), | |
| 37 | - buffer_ms: 1000, | |
| 38 | - }, | |
| 39 | - None => RateControl::ConstantQp { qp: 26 }, | |
| 40 | - }, | |
| 41 | - }; | |
| 42 | - let mut encoder = H264Encoder::new(&gpu, cfg).expect("create encoder"); | |
| 43 | - let mut out = Vec::new(); | |
| 44 | - for n in 0..FRAMES { | |
| 45 | - let (y, u, v) = frame(n); | |
| 46 | - let coded = encoder.encode(&y, &u, &v, false).expect("encode frame"); | |
| 47 | - println!( | |
| 48 | - "frame {n}: {} bytes keyframe {}", | |
| 49 | - coded.data.len(), | |
| 50 | - coded.keyframe | |
| 51 | - ); | |
| 52 | - out.extend_from_slice(&coded.data); | |
| 53 | - } | |
| 54 | - std::fs::write(&path, out).expect("write output"); | |
| 55 | -} |
crates/ec-vk/examples/h265_encode.rsdeleted+0 -55
| @@ -1,55 +0,0 @@ | ||
| 1 | -use ec_vk::{Gpu, H265Encoder, H265EncoderConfig, RateControl}; | |
| 2 | - | |
| 3 | -const W: u32 = 1280; | |
| 4 | -const H: u32 = 720; | |
| 5 | -const FRAMES: u32 = 60; | |
| 6 | - | |
| 7 | -fn frame(n: u32) -> (Vec<u8>, Vec<u8>, Vec<u8>) { | |
| 8 | - let y = (0..H) | |
| 9 | - .flat_map(|row| (0..W).map(move |col| ((col + row + 4 * n) % 256) as u8)) | |
| 10 | - .collect(); | |
| 11 | - let u = (0..H / 2) | |
| 12 | - .flat_map(|_| (0..W / 2).map(move |col| ((col * 2 + n) % 256) as u8)) | |
| 13 | - .collect(); | |
| 14 | - let v = (0..H / 2) | |
| 15 | - .flat_map(|row| (0..W / 2).map(move |_| ((row * 2 + 2 * n) % 256) as u8)) | |
| 16 | - .collect(); | |
| 17 | - (y, u, v) | |
| 18 | -} | |
| 19 | - | |
| 20 | -fn main() { | |
| 21 | - let path = std::env::args() | |
| 22 | - .nth(1) | |
| 23 | - .expect("usage: h265_encode <out.hevc> [cbr_bitrate]"); | |
| 24 | - let gpu = Gpu::open().expect("open Vulkan Video device"); | |
| 25 | - let cfg = H265EncoderConfig { | |
| 26 | - width: W, | |
| 27 | - height: H, | |
| 28 | - fps: (30, 1), | |
| 29 | - level: 186, | |
| 30 | - gop_size: 30, | |
| 31 | - rate: match std::env::args().nth(2) { | |
| 32 | - Some(b) => RateControl::Cbr { | |
| 33 | - bitrate: b.parse().expect("bitrate"), | |
| 34 | - buffer_ms: 1000, | |
| 35 | - }, | |
| 36 | - None => RateControl::ConstantQp { qp: 26 }, | |
| 37 | - }, | |
| 38 | - bit_depth: 8, | |
| 39 | - colour: None, | |
| 40 | - quality: 0, | |
| 41 | - }; | |
| 42 | - let mut encoder = H265Encoder::new(&gpu, cfg).expect("create encoder"); | |
| 43 | - let mut out = Vec::new(); | |
| 44 | - for n in 0..FRAMES { | |
| 45 | - let (y, u, v) = frame(n); | |
| 46 | - let coded = encoder.encode(&y, &u, &v, false).expect("encode frame"); | |
| 47 | - println!( | |
| 48 | - "frame {n}: {} bytes keyframe {}", | |
| 49 | - coded.data.len(), | |
| 50 | - coded.keyframe | |
| 51 | - ); | |
| 52 | - out.extend_from_slice(&coded.data); | |
| 53 | - } | |
| 54 | - std::fs::write(&path, out).expect("write output"); | |
| 55 | -} |
crates/ec-vk/src/h265.rsmodified+6 -1
| @@ -244,7 +244,12 @@ impl H265Encoder { | ||
| 244 | 244 | .history |
| 245 | 245 | .next(force_keyframe || self.position >= self.gop_size); |
| 246 | 246 | self.poc = if step.key { 0 } else { self.poc + 1 }; |
| 247 | - let keep = self.history.kept(&step); | |
| 247 | + let reference = step.reference.map(|(slot, _)| slot as usize); | |
| 248 | + let keep = std::array::from_fn(|i| { | |
| 249 | + self.history.slots[i] | |
| 250 | + .filter(|_| i != step.slot as usize && Some(i) != reference) | |
| 251 | + .map(|h| h.data) | |
| 252 | + }); | |
| 248 | 253 | self.history.store(&step, self.poc); |
| 249 | 254 | self.position = if step.key { 1 } else { self.position + 1 }; |
| 250 | 255 | self.flight.push(Meta { |
crates/ec-vk/src/history.rsmodified+3 -12
| @@ -5,10 +5,10 @@ const ANCHOR_EVERY: u64 = 16; | ||
| 5 | 5 | const MAX_AGE: u64 = 120; |
| 6 | 6 | |
| 7 | 7 | #[derive(Debug, Clone, Copy)] |
| 8 | -struct Held<T> { | |
| 8 | +pub(crate) struct Held<T> { | |
| 9 | 9 | id: u64, |
| 10 | 10 | acked: bool, |
| 11 | - data: T, | |
| 11 | + pub(crate) data: T, | |
| 12 | 12 | } |
| 13 | 13 | |
| 14 | 14 | /// Where the next picture goes and what it references. |
| @@ -26,7 +26,7 @@ pub(crate) struct Step<T> { | ||
| 26 | 26 | /// acknowledged them, the last two chain each picture to the previous one. |
| 27 | 27 | pub(crate) struct History<T> { |
| 28 | 28 | next_id: u64, |
| 29 | - slots: [Option<Held<T>>; DPB_SLOTS], | |
| 29 | + pub(crate) slots: [Option<Held<T>>; DPB_SLOTS], | |
| 30 | 30 | last: Option<(usize, T)>, |
| 31 | 31 | next_anchor: usize, |
| 32 | 32 | armed: bool, |
| @@ -107,15 +107,6 @@ impl<T: Copy> History<T> { | ||
| 107 | 107 | self.last = Some((slot, data)); |
| 108 | 108 | } |
| 109 | 109 | |
| 110 | - pub(crate) fn kept(&self, step: &Step<T>) -> [Option<T>; DPB_SLOTS] { | |
| 111 | - let reference = step.reference.map(|(slot, _)| slot as usize); | |
| 112 | - std::array::from_fn(|i| { | |
| 113 | - self.slots[i] | |
| 114 | - .filter(|_| i != step.slot as usize && Some(i) != reference) | |
| 115 | - .map(|h| h.data) | |
| 116 | - }) | |
| 117 | - } | |
| 118 | - | |
| 119 | 110 | fn newest_acked(&self, id: u64) -> Option<(usize, T)> { |
| 120 | 111 | (0..DPB_SLOTS) |
| 121 | 112 | .filter_map(|i| self.slots[i].map(|h| (i, h))) |