forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB4af5b6cTahinli2 hours ago4022 commits

h264.rs245 lines, 7.6 KiBHistoryRawDownload
1//! H.264 encode parameters.
2//!
3//! `pic_order_cnt_type` is 2 — decode order *is* output order — because this
4//! encoder codes no B frames, and type 2 then costs no picture order count in
5//! any slice header. Everything else follows from one reference and one slice
6//! per picture.
7
8use std::rc::Rc;
9
10use ec_va::va::{
11 BufferType, EncPictureParameter, EncPictureParameterBufferH264, EncSequenceParameter,
12 EncSequenceParameterBufferH264, EncSliceParameter, EncSliceParameterBufferH264,
13 H264EncFrameCropOffsets, H264EncPicFields, H264EncSeqFields, H264VuiFields, PictureH264,
14 VABufferID, VA_INVALID_ID,
15};
16
17use super::{Encoder, H264Profile, RateControlMode, headers};
18use crate::error::Result;
19use crate::params::h264::{PICTURE_INVALID, PICTURE_SHORT_TERM_REFERENCE};
20use crate::params::INVALID_SURFACE;
21use crate::pool::PooledSurface;
22
23/// `log2_max_frame_num_minus4` = 0, i.e. `frame_num` wraps at 16 — far beyond
24/// the single reference this encoder keeps.
25const LOG2_MAX_FRAME_NUM: u64 = 4;
26const MAX_FRAME_NUM: u16 = 1 << LOG2_MAX_FRAME_NUM;
27
28/// `frame_num` of the picture `gop_position` pictures after the key frame
29/// (7.4.3): the key frame is 0, every reference picture after it adds one, and
30/// the count wraps at `MaxFrameNum`. It restarts at every IDR, so a decoder sees
31/// the same numbering whichever IDR it started from.
32fn frame_num_at(gop_position: u32) -> u16 {
33 (gop_position % u32::from(MAX_FRAME_NUM)) as u16
34}
35
36/// `frame_num` of the reference picture, one step before `frame_num` (wrapping
37/// at `MaxFrameNum`, not at 2^16).
38fn previous_frame_num(frame_num: u16) -> u16 {
39 (frame_num + MAX_FRAME_NUM - 1) % MAX_FRAME_NUM
40}
41
42/// An unused entry of a reference list: no surface, flagged invalid.
43fn invalid_picture() -> PictureH264 {
44 PictureH264::new(INVALID_SURFACE, 0, PICTURE_INVALID, 0, 0)
45}
46
47/// A short-term reference frame whose top and bottom field order counts are `poc`.
48fn frame_picture(surface: u32, frame_idx: u32, poc: i32) -> PictureH264 {
49 PictureH264::new(
50 surface,
51 frame_idx,
52 PICTURE_SHORT_TERM_REFERENCE,
53 poc,
54 poc,
55 )
56}
57
58pub(super) fn parameters(
59 encoder: &Encoder,
60 recon: &Rc<PooledSurface>,
61 coded_buf: VABufferID,
62 keyframe: bool,
63 out: &mut Vec<BufferType>,
64) -> Result<()> {
65 let config = *encoder.config();
66 let (coded_w, coded_h) = encoder.coded_size();
67 let mb_width = coded_w / 16;
68 let mb_height = coded_h / 16;
69 // Picture order count type 2 (see `pic_order_cnt_type` in the SPS below):
70 // TopFieldOrderCnt = 2 * (FrameNumOffset + frame_num). Both restart at the
71 // key frame, so the count follows the GOP and not the stream.
72 let (frame_num, poc) = if keyframe {
73 (0, 0)
74 } else {
75 let position = encoder.gop_position();
76 (frame_num_at(position), 2 * position as i32)
77 };
78 let level_idc = crate::level::h264(&config);
79 let intra_period = config.gop_size.max(1);
80 let bits_per_second = match config.rate_control {
81 RateControlMode::ConstantQp { .. } => 0,
82 _ => config.bitrate,
83 };
84 // time_scale is twice the frame rate: a "tick" is a field period.
85 let num_units_in_tick = config.framerate.1.max(1);
86 let time_scale = config.framerate.0.max(1) * 2;
87
88 // 4:2:0 in a crop rectangle of two luma samples per unit (7.4.2.1.1).
89 let crop_right = (coded_w - config.width) / 2;
90 let crop_bottom = (coded_h - config.height) / 2;
91 let crop = (coded_w != config.width || coded_h != config.height)
92 .then(|| H264EncFrameCropOffsets::new(0, crop_right, 0, crop_bottom));
93
94 // chroma_format_idc 1, frame_mbs_only, direct_8x8_inference,
95 // log2_max_frame_num_minus4 0, pic_order_cnt_type 2.
96 let seq_fields = H264EncSeqFields::new(1, 1, 0, 0, 1, 0, 2, 0, 0);
97 // timing_info_present_flag, fixed_frame_rate_flag.
98 let vui = H264VuiFields::new(0, 1, 0, 0, 0, 1, 0, 0);
99 let seq = EncSequenceParameterBufferH264::new(
100 0,
101 level_idc,
102 intra_period,
103 intra_period,
104 1,
105 bits_per_second,
106 1,
107 mb_width as u16,
108 mb_height as u16,
109 &seq_fields,
110 0,
111 0,
112 0,
113 0,
114 0,
115 [0; 256],
116 crop,
117 Some(vui),
118 0,
119 0,
120 0,
121 num_units_in_tick,
122 time_scale,
123 );
124 out.push(BufferType::EncSequenceParameter(EncSequenceParameter::H264(seq)));
125
126 let pic_init_qp = match config.rate_control {
127 RateControlMode::ConstantQp { qp } => qp.clamp(1, 51) as u8,
128 _ => 26,
129 };
130 let mut reference_frames: [PictureH264; 16] = std::array::from_fn(|_| invalid_picture());
131 if let Some(reference) = encoder.reference().filter(|_| !keyframe) {
132 reference_frames[0] = frame_picture(
133 reference.id(),
134 u32::from(previous_frame_num(frame_num)),
135 poc - 2,
136 );
137 }
138 let cabac = config.h264_profile.cabac();
139 let transform_8x8 = config.h264_profile == H264Profile::High;
140 // reference_pic_flag = 1; CABAC in Main and High (10% smaller), CAVLC in
141 // Constrained Baseline; deblocking_filter_control_present_flag = 1.
142 let pic_fields = H264EncPicFields::new(
143 u32::from(keyframe),
144 1,
145 u32::from(cabac),
146 0,
147 0,
148 0,
149 u32::from(transform_8x8),
150 1,
151 0,
152 0,
153 0,
154 );
155 let pic = EncPictureParameterBufferH264::new(
156 frame_picture(recon.id(), u32::from(frame_num), poc),
157 reference_frames,
158 coded_buf,
159 0,
160 0,
161 0,
162 frame_num,
163 pic_init_qp,
164 0,
165 0,
166 0,
167 0,
168 &pic_fields,
169 );
170 out.push(BufferType::EncPictureParameter(EncPictureParameter::H264(pic)));
171
172 // idr_pic_id alternates between consecutive IDR pictures (7.4.3).
173 let idr_pic_id = (encoder.idr_count() % 2) as u16;
174 let mut ref_pic_list0: [PictureH264; 32] = std::array::from_fn(|_| invalid_picture());
175 let ref_pic_list1: [PictureH264; 32] = std::array::from_fn(|_| invalid_picture());
176 if !keyframe && let Some(reference) = encoder.reference() {
177 ref_pic_list0[0] = frame_picture(
178 reference.id(),
179 u32::from(previous_frame_num(frame_num)),
180 poc - 2,
181 );
182 }
183 let slice = EncSliceParameterBufferH264::new(
184 0,
185 mb_width * mb_height,
186 VA_INVALID_ID,
187 if keyframe { 2 } else { 0 },
188 0,
189 idr_pic_id,
190 0,
191 0,
192 [0, 0],
193 0,
194 0,
195 0,
196 0,
197 ref_pic_list0,
198 ref_pic_list1,
199 0,
200 0,
201 0,
202 [0; 32],
203 [0; 32],
204 0,
205 [[0; 2]; 32],
206 [[0; 2]; 32],
207 0,
208 [0; 32],
209 [0; 32],
210 0,
211 [[0; 2]; 32],
212 [[0; 2]; 32],
213 0,
214 0,
215 0,
216 0,
217 0,
218 );
219
220 // Packed headers, in bitstream order: the parameter sets open every key
221 // frame (so a stream is seekable and a decoder can start anywhere), and the
222 // slice header opens every picture.
223 let header_params = headers::H264Params {
224 level_idc,
225 mb_width,
226 mb_height,
227 crop_right,
228 crop_bottom,
229 num_units_in_tick,
230 time_scale,
231 pic_init_qp,
232 colour: config.colour,
233 profile: config.h264_profile,
234 };
235 if keyframe {
236 encoder.push_packed(&headers::h264_sps(&header_params), out)?;
237 encoder.push_packed(&headers::h264_pps(&header_params), out)?;
238 }
239 encoder.push_packed(
240 &headers::h264_slice_header(keyframe, u32::from(frame_num), u32::from(idr_pic_id)),
241 out,
242 )?;
243 out.push(BufferType::EncSliceParameter(EncSliceParameter::H264(slice)));
244 Ok(())
245}