]> git.sesse.net Git - ffmpeg/blob - libavcodec/vaapi_encode_h264.c
configure: Use correct variable name in libsnappy test
[ffmpeg] / libavcodec / vaapi_encode_h264.c
1 /*
2  * This file is part of Libav.
3  *
4  * Libav is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2.1 of the License, or (at your option) any later version.
8  *
9  * Libav is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with Libav; if not, write to the Free Software
16  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17  */
18
19 #include <va/va.h>
20 #include <va/va_enc_h264.h>
21
22 #include "libavutil/avassert.h"
23 #include "libavutil/internal.h"
24 #include "libavutil/opt.h"
25 #include "libavutil/pixfmt.h"
26
27 #include "avcodec.h"
28 #include "h264.h"
29 #include "h264_sei.h"
30 #include "internal.h"
31 #include "vaapi_encode.h"
32 #include "vaapi_encode_h26x.h"
33
34 enum {
35     SLICE_TYPE_P  = 0,
36     SLICE_TYPE_B  = 1,
37     SLICE_TYPE_I  = 2,
38     SLICE_TYPE_SP = 3,
39     SLICE_TYPE_SI = 4,
40 };
41
42 // This structure contains all possibly-useful per-sequence syntax elements
43 // which are not already contained in the various VAAPI structures.
44 typedef struct VAAPIEncodeH264MiscSequenceParams {
45     unsigned int profile_idc;
46     char constraint_set0_flag;
47     char constraint_set1_flag;
48     char constraint_set2_flag;
49     char constraint_set3_flag;
50     char constraint_set4_flag;
51     char constraint_set5_flag;
52
53     char separate_colour_plane_flag;
54     char qpprime_y_zero_transform_bypass_flag;
55
56     char gaps_in_frame_num_allowed_flag;
57     char delta_pic_order_always_zero_flag;
58     char bottom_field_pic_order_in_frame_present_flag;
59
60     unsigned int num_slice_groups_minus1;
61     unsigned int slice_group_map_type;
62
63     int pic_init_qs_minus26;
64
65     char overscan_info_present_flag;
66     char overscan_appropriate_flag;
67
68     char video_signal_type_present_flag;
69     unsigned int video_format;
70     char video_full_range_flag;
71     char colour_description_present_flag;
72     unsigned int colour_primaries;
73     unsigned int transfer_characteristics;
74     unsigned int matrix_coefficients;
75
76     char chroma_loc_info_present_flag;
77     unsigned int chroma_sample_loc_type_top_field;
78     unsigned int chroma_sample_loc_type_bottom_field;
79
80     // Some timing elements are in VAEncSequenceParameterBufferH264.
81     char fixed_frame_rate_flag;
82
83     char nal_hrd_parameters_present_flag;
84     char vcl_hrd_parameters_present_flag;
85     char low_delay_hrd_flag;
86     char pic_struct_present_flag;
87
88     char motion_vectors_over_pic_boundaries_flag;
89     unsigned int max_bytes_per_pic_denom;
90     unsigned int max_bits_per_mb_denom;
91     unsigned int max_num_reorder_frames;
92     unsigned int max_dec_pic_buffering;
93
94     unsigned int cpb_cnt_minus1;
95     unsigned int bit_rate_scale;
96     unsigned int cpb_size_scale;
97     unsigned int bit_rate_value_minus1[32];
98     unsigned int cpb_size_value_minus1[32];
99     char cbr_flag[32];
100     unsigned int initial_cpb_removal_delay_length_minus1;
101     unsigned int cpb_removal_delay_length_minus1;
102     unsigned int dpb_output_delay_length_minus1;
103     unsigned int time_offset_length;
104
105     unsigned int initial_cpb_removal_delay;
106     unsigned int initial_cpb_removal_delay_offset;
107
108     unsigned int pic_struct;
109 } VAAPIEncodeH264MiscSequenceParams;
110
111 // This structure contains all possibly-useful per-slice syntax elements
112 // which are not already contained in the various VAAPI structures.
113 typedef struct VAAPIEncodeH264MiscSliceParams {
114     unsigned int nal_unit_type;
115     unsigned int nal_ref_idc;
116
117     unsigned int colour_plane_id;
118     char field_pic_flag;
119     char bottom_field_flag;
120
121     unsigned int redundant_pic_cnt;
122
123     char sp_for_switch_flag;
124     int slice_qs_delta;
125
126     char ref_pic_list_modification_flag_l0;
127     char ref_pic_list_modification_flag_l1;
128
129     char no_output_of_prior_pics_flag;
130     char long_term_reference_flag;
131     char adaptive_ref_pic_marking_mode_flag;
132 } VAAPIEncodeH264MiscSliceParams;
133
134 typedef struct VAAPIEncodeH264Slice {
135     VAAPIEncodeH264MiscSliceParams misc_slice_params;
136 } VAAPIEncodeH264Slice;
137
138 typedef struct VAAPIEncodeH264Context {
139     VAAPIEncodeH264MiscSequenceParams misc_sequence_params;
140
141     int mb_width;
142     int mb_height;
143
144     int fixed_qp_idr;
145     int fixed_qp_p;
146     int fixed_qp_b;
147
148     int next_frame_num;
149     int64_t idr_pic_count;
150
151     int cpb_delay;
152     int dpb_delay;
153
154     // Rate control configuration.
155     int send_timing_sei;
156
157 #if VA_CHECK_VERSION(0, 36, 0)
158     // Speed-quality tradeoff setting.
159     struct {
160         VAEncMiscParameterBuffer misc;
161         VAEncMiscParameterBufferQualityLevel quality;
162     } quality_params;
163 #endif
164 } VAAPIEncodeH264Context;
165
166 typedef struct VAAPIEncodeH264Options {
167     int qp;
168     int quality;
169     int low_power;
170 } VAAPIEncodeH264Options;
171
172
173 #define vseq_var(name)     vseq->name, name
174 #define vseq_field(name)   vseq->seq_fields.bits.name, name
175 #define vvui_field(name)   vseq->vui_fields.bits.name, name
176 #define vpic_var(name)     vpic->name, name
177 #define vpic_field(name)   vpic->pic_fields.bits.name, name
178 #define vslice_var(name)   vslice->name, name
179 #define vslice_field(name) vslice->slice_fields.bits.name, name
180 #define mseq_var(name)     mseq->name, name
181 #define mslice_var(name)   mslice->name, name
182
183 static void vaapi_encode_h264_write_nal_header(PutBitContext *pbc,
184                                                int nal_unit_type, int nal_ref_idc)
185 {
186     u(1, 0, forbidden_zero_bit);
187     u(2, nal_ref_idc, nal_ref_idc);
188     u(5, nal_unit_type, nal_unit_type);
189 }
190
191 static void vaapi_encode_h264_write_trailing_rbsp(PutBitContext *pbc)
192 {
193     u(1, 1, rbsp_stop_one_bit);
194     while (put_bits_count(pbc) & 7)
195         u(1, 0, rbsp_alignment_zero_bit);
196 }
197
198 static void vaapi_encode_h264_write_vui(PutBitContext *pbc,
199                                         VAAPIEncodeContext *ctx)
200 {
201     VAEncSequenceParameterBufferH264  *vseq = ctx->codec_sequence_params;
202     VAAPIEncodeH264Context            *priv = ctx->priv_data;
203     VAAPIEncodeH264MiscSequenceParams *mseq = &priv->misc_sequence_params;
204     int i;
205
206     u(1, vvui_field(aspect_ratio_info_present_flag));
207     if (vseq->vui_fields.bits.aspect_ratio_info_present_flag) {
208         u(8, vseq_var(aspect_ratio_idc));
209         if (vseq->aspect_ratio_idc == 255) {
210             u(16, vseq_var(sar_width));
211             u(16, vseq_var(sar_height));
212         }
213     }
214
215     u(1, mseq_var(overscan_info_present_flag));
216     if (mseq->overscan_info_present_flag)
217         u(1, mseq_var(overscan_appropriate_flag));
218
219     u(1, mseq_var(video_signal_type_present_flag));
220     if (mseq->video_signal_type_present_flag) {
221         u(3, mseq_var(video_format));
222         u(1, mseq_var(video_full_range_flag));
223         u(1, mseq_var(colour_description_present_flag));
224         if (mseq->colour_description_present_flag) {
225             u(8, mseq_var(colour_primaries));
226             u(8, mseq_var(transfer_characteristics));
227             u(8, mseq_var(matrix_coefficients));
228         }
229     }
230
231     u(1, mseq_var(chroma_loc_info_present_flag));
232     if (mseq->chroma_loc_info_present_flag) {
233         ue(mseq_var(chroma_sample_loc_type_top_field));
234         ue(mseq_var(chroma_sample_loc_type_bottom_field));
235     }
236
237     u(1, vvui_field(timing_info_present_flag));
238     if (vseq->vui_fields.bits.timing_info_present_flag) {
239         u(32, vseq_var(num_units_in_tick));
240         u(32, vseq_var(time_scale));
241         u(1, mseq_var(fixed_frame_rate_flag));
242     }
243
244     u(1, mseq_var(nal_hrd_parameters_present_flag));
245     if (mseq->nal_hrd_parameters_present_flag) {
246         ue(mseq_var(cpb_cnt_minus1));
247         u(4, mseq_var(bit_rate_scale));
248         u(4, mseq_var(cpb_size_scale));
249         for (i = 0; i <= mseq->cpb_cnt_minus1; i++) {
250             ue(mseq_var(bit_rate_value_minus1[i]));
251             ue(mseq_var(cpb_size_value_minus1[i]));
252             u(1, mseq_var(cbr_flag[i]));
253         }
254         u(5, mseq_var(initial_cpb_removal_delay_length_minus1));
255         u(5, mseq_var(cpb_removal_delay_length_minus1));
256         u(5, mseq_var(dpb_output_delay_length_minus1));
257         u(5, mseq_var(time_offset_length));
258     }
259     u(1, mseq_var(vcl_hrd_parameters_present_flag));
260     if (mseq->vcl_hrd_parameters_present_flag) {
261         av_assert0(0 && "vcl hrd parameters not supported");
262     }
263
264     if (mseq->nal_hrd_parameters_present_flag ||
265         mseq->vcl_hrd_parameters_present_flag)
266         u(1, mseq_var(low_delay_hrd_flag));
267     u(1, mseq_var(pic_struct_present_flag));
268
269     u(1, vvui_field(bitstream_restriction_flag));
270     if (vseq->vui_fields.bits.bitstream_restriction_flag) {
271         u(1, mseq_var(motion_vectors_over_pic_boundaries_flag));
272         ue(mseq_var(max_bytes_per_pic_denom));
273         ue(mseq_var(max_bits_per_mb_denom));
274         ue(vvui_field(log2_max_mv_length_horizontal));
275         ue(vvui_field(log2_max_mv_length_vertical));
276         ue(mseq_var(max_num_reorder_frames));
277         ue(mseq_var(max_dec_pic_buffering));
278     }
279 }
280
281 static void vaapi_encode_h264_write_sps(PutBitContext *pbc,
282                                         VAAPIEncodeContext *ctx)
283 {
284     VAEncSequenceParameterBufferH264  *vseq = ctx->codec_sequence_params;
285     VAAPIEncodeH264Context            *priv = ctx->priv_data;
286     VAAPIEncodeH264MiscSequenceParams *mseq = &priv->misc_sequence_params;
287     int i;
288
289     vaapi_encode_h264_write_nal_header(pbc, H264_NAL_SPS, 3);
290
291     u(8, mseq_var(profile_idc));
292     u(1, mseq_var(constraint_set0_flag));
293     u(1, mseq_var(constraint_set1_flag));
294     u(1, mseq_var(constraint_set2_flag));
295     u(1, mseq_var(constraint_set3_flag));
296     u(1, mseq_var(constraint_set4_flag));
297     u(1, mseq_var(constraint_set5_flag));
298     u(2, 0, reserved_zero_2bits);
299
300     u(8, vseq_var(level_idc));
301
302     ue(vseq_var(seq_parameter_set_id));
303
304     if (mseq->profile_idc == 100 || mseq->profile_idc == 110 ||
305         mseq->profile_idc == 122 || mseq->profile_idc == 244 ||
306         mseq->profile_idc ==  44 || mseq->profile_idc ==  83 ||
307         mseq->profile_idc ==  86 || mseq->profile_idc == 118 ||
308         mseq->profile_idc == 128 || mseq->profile_idc == 138) {
309         ue(vseq_field(chroma_format_idc));
310
311         if (vseq->seq_fields.bits.chroma_format_idc == 3)
312             u(1, mseq_var(separate_colour_plane_flag));
313
314         ue(vseq_var(bit_depth_luma_minus8));
315         ue(vseq_var(bit_depth_chroma_minus8));
316
317         u(1, mseq_var(qpprime_y_zero_transform_bypass_flag));
318
319         u(1, vseq_field(seq_scaling_matrix_present_flag));
320         if (vseq->seq_fields.bits.seq_scaling_matrix_present_flag) {
321             av_assert0(0 && "scaling matrices not supported");
322         }
323     }
324
325     ue(vseq_field(log2_max_frame_num_minus4));
326     ue(vseq_field(pic_order_cnt_type));
327
328     if (vseq->seq_fields.bits.pic_order_cnt_type == 0) {
329         ue(vseq_field(log2_max_pic_order_cnt_lsb_minus4));
330     } else if (vseq->seq_fields.bits.pic_order_cnt_type == 1) {
331         u(1, mseq_var(delta_pic_order_always_zero_flag));
332         se(vseq_var(offset_for_non_ref_pic));
333         se(vseq_var(offset_for_top_to_bottom_field));
334         ue(vseq_var(num_ref_frames_in_pic_order_cnt_cycle));
335
336         for (i = 0; i < vseq->num_ref_frames_in_pic_order_cnt_cycle; i++)
337             se(vseq_var(offset_for_ref_frame[i]));
338     }
339
340     ue(vseq_var(max_num_ref_frames));
341     u(1, mseq_var(gaps_in_frame_num_allowed_flag));
342
343     ue(vseq->picture_width_in_mbs  - 1, pic_width_in_mbs_minus1);
344     ue(vseq->picture_height_in_mbs - 1, pic_height_in_mbs_minus1);
345
346     u(1, vseq_field(frame_mbs_only_flag));
347     if (!vseq->seq_fields.bits.frame_mbs_only_flag)
348         u(1, vseq_field(mb_adaptive_frame_field_flag));
349
350     u(1, vseq_field(direct_8x8_inference_flag));
351
352     u(1, vseq_var(frame_cropping_flag));
353     if (vseq->frame_cropping_flag) {
354         ue(vseq_var(frame_crop_left_offset));
355         ue(vseq_var(frame_crop_right_offset));
356         ue(vseq_var(frame_crop_top_offset));
357         ue(vseq_var(frame_crop_bottom_offset));
358     }
359
360     u(1, vseq_var(vui_parameters_present_flag));
361     if (vseq->vui_parameters_present_flag)
362         vaapi_encode_h264_write_vui(pbc, ctx);
363
364     vaapi_encode_h264_write_trailing_rbsp(pbc);
365 }
366
367 static void vaapi_encode_h264_write_pps(PutBitContext *pbc,
368                                         VAAPIEncodeContext *ctx)
369 {
370     VAEncPictureParameterBufferH264   *vpic = ctx->codec_picture_params;
371     VAAPIEncodeH264Context            *priv = ctx->priv_data;
372     VAAPIEncodeH264MiscSequenceParams *mseq = &priv->misc_sequence_params;
373
374     vaapi_encode_h264_write_nal_header(pbc, H264_NAL_PPS, 3);
375
376     ue(vpic_var(pic_parameter_set_id));
377     ue(vpic_var(seq_parameter_set_id));
378
379     u(1, vpic_field(entropy_coding_mode_flag));
380     u(1, mseq_var(bottom_field_pic_order_in_frame_present_flag));
381
382     ue(mseq_var(num_slice_groups_minus1));
383     if (mseq->num_slice_groups_minus1 > 0) {
384         ue(mseq_var(slice_group_map_type));
385         av_assert0(0 && "slice groups not supported");
386     }
387
388     ue(vpic_var(num_ref_idx_l0_active_minus1));
389     ue(vpic_var(num_ref_idx_l1_active_minus1));
390
391     u(1, vpic_field(weighted_pred_flag));
392     u(2, vpic_field(weighted_bipred_idc));
393
394     se(vpic->pic_init_qp - 26, pic_init_qp_minus26);
395     se(mseq_var(pic_init_qs_minus26));
396     se(vpic_var(chroma_qp_index_offset));
397
398     u(1, vpic_field(deblocking_filter_control_present_flag));
399     u(1, vpic_field(constrained_intra_pred_flag));
400     u(1, vpic_field(redundant_pic_cnt_present_flag));
401     u(1, vpic_field(transform_8x8_mode_flag));
402
403     u(1, vpic_field(pic_scaling_matrix_present_flag));
404     if (vpic->pic_fields.bits.pic_scaling_matrix_present_flag) {
405         av_assert0(0 && "scaling matrices not supported");
406     }
407
408     se(vpic_var(second_chroma_qp_index_offset));
409
410     vaapi_encode_h264_write_trailing_rbsp(pbc);
411 }
412
413 static void vaapi_encode_h264_write_slice_header2(PutBitContext *pbc,
414                                                   VAAPIEncodeContext *ctx,
415                                                   VAAPIEncodePicture *pic,
416                                                   VAAPIEncodeSlice *slice)
417 {
418     VAEncSequenceParameterBufferH264  *vseq = ctx->codec_sequence_params;
419     VAEncPictureParameterBufferH264   *vpic = pic->codec_picture_params;
420     VAEncSliceParameterBufferH264   *vslice = slice->codec_slice_params;
421     VAAPIEncodeH264Context            *priv = ctx->priv_data;
422     VAAPIEncodeH264MiscSequenceParams *mseq = &priv->misc_sequence_params;
423     VAAPIEncodeH264Slice            *pslice = slice->priv_data;
424     VAAPIEncodeH264MiscSliceParams  *mslice = &pslice->misc_slice_params;
425
426     vaapi_encode_h264_write_nal_header(pbc, mslice->nal_unit_type,
427                                        mslice->nal_ref_idc);
428
429     ue(vslice->macroblock_address, first_mb_in_slice);
430     ue(vslice_var(slice_type));
431     ue(vpic_var(pic_parameter_set_id));
432
433     if (mseq->separate_colour_plane_flag) {
434         u(2, mslice_var(colour_plane_id));
435     }
436
437     u(4 + vseq->seq_fields.bits.log2_max_frame_num_minus4,
438       (vpic->frame_num &
439        ((1 << (4 + vseq->seq_fields.bits.log2_max_frame_num_minus4)) - 1)),
440       frame_num);
441
442     if (!vseq->seq_fields.bits.frame_mbs_only_flag) {
443         u(1, mslice_var(field_pic_flag));
444         if (mslice->field_pic_flag)
445             u(1, mslice_var(bottom_field_flag));
446     }
447
448     if (vpic->pic_fields.bits.idr_pic_flag) {
449         ue(vslice_var(idr_pic_id));
450     }
451
452     if (vseq->seq_fields.bits.pic_order_cnt_type == 0) {
453         u(4 + vseq->seq_fields.bits.log2_max_pic_order_cnt_lsb_minus4,
454           vslice_var(pic_order_cnt_lsb));
455         if (mseq->bottom_field_pic_order_in_frame_present_flag &&
456             !mslice->field_pic_flag) {
457             se(vslice_var(delta_pic_order_cnt_bottom));
458         }
459     }
460
461     if (vseq->seq_fields.bits.pic_order_cnt_type == 1 &&
462         !vseq->seq_fields.bits.delta_pic_order_always_zero_flag) {
463         se(vslice_var(delta_pic_order_cnt[0]));
464         if (mseq->bottom_field_pic_order_in_frame_present_flag &&
465             !mslice->field_pic_flag) {
466             se(vslice_var(delta_pic_order_cnt[1]));
467         }
468     }
469
470     if (vpic->pic_fields.bits.redundant_pic_cnt_present_flag) {
471         ue(mslice_var(redundant_pic_cnt));
472     }
473
474     if (vslice->slice_type == SLICE_TYPE_B) {
475         u(1, vslice_var(direct_spatial_mv_pred_flag));
476     }
477
478     if (vslice->slice_type == SLICE_TYPE_P ||
479         vslice->slice_type == SLICE_TYPE_SP ||
480         vslice->slice_type == SLICE_TYPE_B) {
481         u(1, vslice_var(num_ref_idx_active_override_flag));
482         if (vslice->num_ref_idx_active_override_flag) {
483             ue(vslice_var(num_ref_idx_l0_active_minus1));
484             if (vslice->slice_type == SLICE_TYPE_B)
485                 ue(vslice_var(num_ref_idx_l1_active_minus1));
486         }
487     }
488
489     if (mslice->nal_unit_type == 20 || mslice->nal_unit_type == 21) {
490         av_assert0(0 && "no MVC support");
491     } else {
492         if (vslice->slice_type % 5 != 2 && vslice->slice_type % 5 != 4) {
493             u(1, mslice_var(ref_pic_list_modification_flag_l0));
494             if (mslice->ref_pic_list_modification_flag_l0) {
495                 av_assert0(0 && "ref pic list modification");
496             }
497         }
498         if (vslice->slice_type % 5 == 1) {
499             u(1, mslice_var(ref_pic_list_modification_flag_l1));
500             if (mslice->ref_pic_list_modification_flag_l1) {
501                 av_assert0(0 && "ref pic list modification");
502             }
503         }
504     }
505
506     if ((vpic->pic_fields.bits.weighted_pred_flag &&
507          (vslice->slice_type == SLICE_TYPE_P ||
508           vslice->slice_type == SLICE_TYPE_SP)) ||
509         (vpic->pic_fields.bits.weighted_bipred_idc == 1 &&
510          vslice->slice_type == SLICE_TYPE_B)) {
511         av_assert0(0 && "prediction weights not supported");
512     }
513
514     av_assert0(mslice->nal_ref_idc > 0 ==
515                vpic->pic_fields.bits.reference_pic_flag);
516     if (mslice->nal_ref_idc != 0) {
517         if (vpic->pic_fields.bits.idr_pic_flag) {
518             u(1, mslice_var(no_output_of_prior_pics_flag));
519             u(1, mslice_var(long_term_reference_flag));
520         } else {
521             u(1, mslice_var(adaptive_ref_pic_marking_mode_flag));
522             if (mslice->adaptive_ref_pic_marking_mode_flag) {
523                 av_assert0(0 && "MMCOs not supported");
524             }
525         }
526     }
527
528     if (vpic->pic_fields.bits.entropy_coding_mode_flag &&
529         vslice->slice_type != SLICE_TYPE_I &&
530         vslice->slice_type != SLICE_TYPE_SI) {
531         ue(vslice_var(cabac_init_idc));
532     }
533
534     se(vslice_var(slice_qp_delta));
535     if (vslice->slice_type == SLICE_TYPE_SP ||
536         vslice->slice_type == SLICE_TYPE_SI) {
537         if (vslice->slice_type == SLICE_TYPE_SP)
538             u(1, mslice_var(sp_for_switch_flag));
539         se(mslice_var(slice_qs_delta));
540     }
541
542     if (vpic->pic_fields.bits.deblocking_filter_control_present_flag) {
543         ue(vslice_var(disable_deblocking_filter_idc));
544         if (vslice->disable_deblocking_filter_idc != 1) {
545             se(vslice_var(slice_alpha_c0_offset_div2));
546             se(vslice_var(slice_beta_offset_div2));
547         }
548     }
549
550     if (mseq->num_slice_groups_minus1 > 0 &&
551         mseq->slice_group_map_type >= 3 && mseq->slice_group_map_type <= 5) {
552         av_assert0(0 && "slice groups not supported");
553     }
554
555     // No alignment - this need not be a byte boundary.
556 }
557
558 static void vaapi_encode_h264_write_buffering_period(PutBitContext *pbc,
559                                                      VAAPIEncodeContext *ctx,
560                                                      VAAPIEncodePicture *pic)
561 {
562     VAAPIEncodeH264Context            *priv = ctx->priv_data;
563     VAAPIEncodeH264MiscSequenceParams *mseq = &priv->misc_sequence_params;
564     VAEncPictureParameterBufferH264   *vpic = pic->codec_picture_params;
565     int i;
566
567     ue(vpic_var(seq_parameter_set_id));
568
569     if (mseq->nal_hrd_parameters_present_flag) {
570         for (i = 0; i <= mseq->cpb_cnt_minus1; i++) {
571             u(mseq->initial_cpb_removal_delay_length_minus1 + 1,
572               mseq_var(initial_cpb_removal_delay));
573             u(mseq->initial_cpb_removal_delay_length_minus1 + 1,
574               mseq_var(initial_cpb_removal_delay_offset));
575         }
576     }
577     if (mseq->vcl_hrd_parameters_present_flag) {
578         av_assert0(0 && "vcl hrd parameters not supported");
579     }
580 }
581
582 static void vaapi_encode_h264_write_pic_timing(PutBitContext *pbc,
583                                                VAAPIEncodeContext *ctx,
584                                                VAAPIEncodePicture *pic)
585 {
586     VAEncSequenceParameterBufferH264  *vseq = ctx->codec_sequence_params;
587     VAAPIEncodeH264Context            *priv = ctx->priv_data;
588     VAAPIEncodeH264MiscSequenceParams *mseq = &priv->misc_sequence_params;
589     int i, num_clock_ts;
590
591     if (mseq->nal_hrd_parameters_present_flag ||
592         mseq->vcl_hrd_parameters_present_flag) {
593         u(mseq->cpb_removal_delay_length_minus1 + 1,
594           2 * vseq->num_units_in_tick * priv->cpb_delay,
595           cpb_removal_delay);
596         u(mseq->dpb_output_delay_length_minus1 + 1,
597           2 * vseq->num_units_in_tick * priv->dpb_delay,
598           dpb_output_delay);
599     }
600     if (mseq->pic_struct_present_flag) {
601         u(4, mseq_var(pic_struct));
602         num_clock_ts = (mseq->pic_struct <= 2 ? 1 :
603                         mseq->pic_struct <= 4 ? 2 :
604                         mseq->pic_struct <= 8 ? 3 : 0);
605         for (i = 0; i < num_clock_ts; i++) {
606             u(1, 0, clock_timestamp_flag[i]);
607             // No full timestamp information.
608         }
609     }
610 }
611
612 static void vaapi_encode_h264_write_identifier(PutBitContext *pbc,
613                                                VAAPIEncodeContext *ctx,
614                                                VAAPIEncodePicture *pic)
615 {
616     const char *lavc   = LIBAVCODEC_IDENT;
617     const char *vaapi  = VA_VERSION_S;
618     const char *driver = vaQueryVendorString(ctx->hwctx->display);
619     char tmp[256];
620     int i;
621
622     // Random (version 4) ISO 11578 UUID.
623     uint8_t uuid[16] = {
624         0x59, 0x94, 0x8b, 0x28, 0x11, 0xec, 0x45, 0xaf,
625         0x96, 0x75, 0x19, 0xd4, 0x1f, 0xea, 0xa9, 0x4d,
626     };
627
628     for (i = 0; i < 16; i++)
629         u(8, uuid[i], uuid_iso_iec_11578);
630
631     snprintf(tmp, sizeof(tmp), "%s / VAAPI %s / %s", lavc, vaapi, driver);
632     for (i = 0; i < sizeof(tmp) && tmp[i]; i++)
633         u(8, tmp[i], user_data_payload_byte);
634 }
635
636 static void vaapi_encode_h264_write_sei(PutBitContext *pbc,
637                                         VAAPIEncodeContext *ctx,
638                                         VAAPIEncodePicture *pic)
639 {
640     VAAPIEncodeH264Context *priv = ctx->priv_data;
641     PutBitContext payload_bits;
642     char payload[256];
643     int payload_type, payload_size, i;
644     void (*write_payload)(PutBitContext *pbc,
645                           VAAPIEncodeContext *ctx,
646                           VAAPIEncodePicture *pic) = NULL;
647
648     vaapi_encode_h264_write_nal_header(pbc, H264_NAL_SEI, 0);
649
650     for (payload_type = 0; payload_type < 64; payload_type++) {
651         switch (payload_type) {
652         case SEI_TYPE_BUFFERING_PERIOD:
653             if (!priv->send_timing_sei ||
654                 pic->type != PICTURE_TYPE_IDR)
655                 continue;
656             write_payload = &vaapi_encode_h264_write_buffering_period;
657             break;
658         case SEI_TYPE_PIC_TIMING:
659             if (!priv->send_timing_sei)
660                 continue;
661             write_payload = &vaapi_encode_h264_write_pic_timing;
662             break;
663         case SEI_TYPE_USER_DATA_UNREGISTERED:
664             if (pic->encode_order != 0)
665                 continue;
666             write_payload = &vaapi_encode_h264_write_identifier;
667             break;
668         default:
669             continue;
670         }
671
672         init_put_bits(&payload_bits, payload, sizeof(payload));
673         write_payload(&payload_bits, ctx, pic);
674         if (put_bits_count(&payload_bits) & 7) {
675             write_u(&payload_bits, 1, 1, bit_equal_to_one);
676             while (put_bits_count(&payload_bits) & 7)
677                 write_u(&payload_bits, 1, 0, bit_equal_to_zero);
678         }
679         payload_size = put_bits_count(&payload_bits) / 8;
680         flush_put_bits(&payload_bits);
681
682         u(8, payload_type, last_payload_type_byte);
683         u(8, payload_size, last_payload_size_byte);
684         for (i = 0; i < payload_size; i++)
685             u(8, payload[i] & 0xff, sei_payload);
686     }
687
688     vaapi_encode_h264_write_trailing_rbsp(pbc);
689 }
690
691 static int vaapi_encode_h264_write_sequence_header(AVCodecContext *avctx,
692                                                    char *data, size_t *data_len)
693 {
694     VAAPIEncodeContext *ctx = avctx->priv_data;
695     PutBitContext pbc;
696     char tmp[256];
697     int err;
698     size_t nal_len, bit_len, bit_pos, next_len;
699
700     bit_len = *data_len;
701     bit_pos = 0;
702
703     init_put_bits(&pbc, tmp, sizeof(tmp));
704     vaapi_encode_h264_write_sps(&pbc, ctx);
705     nal_len = put_bits_count(&pbc);
706     flush_put_bits(&pbc);
707
708     next_len = bit_len - bit_pos;
709     err = ff_vaapi_encode_h26x_nal_unit_to_byte_stream(data + bit_pos / 8,
710                                                        &next_len,
711                                                        tmp, nal_len);
712     if (err < 0)
713         return err;
714     bit_pos += next_len;
715
716     init_put_bits(&pbc, tmp, sizeof(tmp));
717     vaapi_encode_h264_write_pps(&pbc, ctx);
718     nal_len = put_bits_count(&pbc);
719     flush_put_bits(&pbc);
720
721     next_len = bit_len - bit_pos;
722     err = ff_vaapi_encode_h26x_nal_unit_to_byte_stream(data + bit_pos / 8,
723                                                        &next_len,
724                                                        tmp, nal_len);
725     if (err < 0)
726         return err;
727     bit_pos += next_len;
728
729     *data_len = bit_pos;
730     return 0;
731 }
732
733 static int vaapi_encode_h264_write_slice_header(AVCodecContext *avctx,
734                                                 VAAPIEncodePicture *pic,
735                                                 VAAPIEncodeSlice *slice,
736                                                 char *data, size_t *data_len)
737 {
738     VAAPIEncodeContext *ctx = avctx->priv_data;
739     PutBitContext pbc;
740     char tmp[256];
741     size_t header_len;
742
743     init_put_bits(&pbc, tmp, sizeof(tmp));
744     vaapi_encode_h264_write_slice_header2(&pbc, ctx, pic, slice);
745     header_len = put_bits_count(&pbc);
746     flush_put_bits(&pbc);
747
748     return ff_vaapi_encode_h26x_nal_unit_to_byte_stream(data, data_len,
749                                                         tmp, header_len);
750 }
751
752 static int vaapi_encode_h264_write_extra_header(AVCodecContext *avctx,
753                                                 VAAPIEncodePicture *pic,
754                                                 int index, int *type,
755                                                 char *data, size_t *data_len)
756 {
757     VAAPIEncodeContext *ctx = avctx->priv_data;
758     PutBitContext pbc;
759     char tmp[256];
760     size_t header_len;
761
762     if (index == 0 && ctx->va_rc_mode == VA_RC_CBR) {
763         *type = VAEncPackedHeaderH264_SEI;
764
765         init_put_bits(&pbc, tmp, sizeof(tmp));
766         vaapi_encode_h264_write_sei(&pbc, ctx, pic);
767         header_len = put_bits_count(&pbc);
768         flush_put_bits(&pbc);
769
770         return ff_vaapi_encode_h26x_nal_unit_to_byte_stream(data, data_len,
771                                                             tmp, header_len);
772
773     } else {
774         return AVERROR_EOF;
775     }
776 }
777
778 static int vaapi_encode_h264_init_sequence_params(AVCodecContext *avctx)
779 {
780     VAAPIEncodeContext                 *ctx = avctx->priv_data;
781     VAEncSequenceParameterBufferH264  *vseq = ctx->codec_sequence_params;
782     VAEncPictureParameterBufferH264   *vpic = ctx->codec_picture_params;
783     VAAPIEncodeH264Context            *priv = ctx->priv_data;
784     VAAPIEncodeH264MiscSequenceParams *mseq = &priv->misc_sequence_params;
785     int i;
786
787     {
788         vseq->seq_parameter_set_id = 0;
789
790         vseq->level_idc = avctx->level;
791
792         vseq->max_num_ref_frames = 1 + (avctx->max_b_frames > 0);
793
794         vseq->picture_width_in_mbs  = priv->mb_width;
795         vseq->picture_height_in_mbs = priv->mb_height;
796
797         vseq->seq_fields.bits.chroma_format_idc = 1;
798         vseq->seq_fields.bits.frame_mbs_only_flag = 1;
799         vseq->seq_fields.bits.direct_8x8_inference_flag = 1;
800         vseq->seq_fields.bits.log2_max_frame_num_minus4 = 4;
801         vseq->seq_fields.bits.pic_order_cnt_type = 0;
802
803         if (avctx->width  != ctx->surface_width ||
804             avctx->height != ctx->surface_height) {
805             vseq->frame_cropping_flag = 1;
806
807             vseq->frame_crop_left_offset   = 0;
808             vseq->frame_crop_right_offset  =
809                 (ctx->surface_width - avctx->width) / 2;
810             vseq->frame_crop_top_offset    = 0;
811             vseq->frame_crop_bottom_offset =
812                 (ctx->surface_height - avctx->height) / 2;
813         } else {
814             vseq->frame_cropping_flag = 0;
815         }
816
817         vseq->vui_parameters_present_flag = 1;
818         if (avctx->sample_aspect_ratio.num != 0) {
819             vseq->vui_fields.bits.aspect_ratio_info_present_flag = 1;
820             // There is a large enum of these which we could support
821             // individually rather than using the generic X/Y form?
822             if (avctx->sample_aspect_ratio.num ==
823                 avctx->sample_aspect_ratio.den) {
824                 vseq->aspect_ratio_idc = 1;
825             } else {
826                 vseq->aspect_ratio_idc = 255; // Extended SAR.
827                 vseq->sar_width  = avctx->sample_aspect_ratio.num;
828                 vseq->sar_height = avctx->sample_aspect_ratio.den;
829             }
830         }
831         if (avctx->color_primaries != AVCOL_PRI_UNSPECIFIED ||
832             avctx->color_trc       != AVCOL_TRC_UNSPECIFIED ||
833             avctx->colorspace      != AVCOL_SPC_UNSPECIFIED) {
834             mseq->video_signal_type_present_flag = 1;
835             mseq->video_format             = 5; // Unspecified.
836             mseq->video_full_range_flag    = 0;
837             mseq->colour_description_present_flag = 1;
838             // These enums are derived from the standard and hence
839             // we can just use the values directly.
840             mseq->colour_primaries         = avctx->color_primaries;
841             mseq->transfer_characteristics = avctx->color_trc;
842             mseq->matrix_coefficients      = avctx->colorspace;
843         }
844
845         vseq->vui_fields.bits.bitstream_restriction_flag = 1;
846         mseq->motion_vectors_over_pic_boundaries_flag = 1;
847         mseq->max_bytes_per_pic_denom = 0;
848         mseq->max_bits_per_mb_denom   = 0;
849         vseq->vui_fields.bits.log2_max_mv_length_horizontal = 16;
850         vseq->vui_fields.bits.log2_max_mv_length_vertical   = 16;
851
852         mseq->max_num_reorder_frames = (avctx->max_b_frames > 0);
853         mseq->max_dec_pic_buffering  = vseq->max_num_ref_frames;
854
855         vseq->bits_per_second = avctx->bit_rate;
856
857         vseq->vui_fields.bits.timing_info_present_flag = 1;
858         if (avctx->framerate.num > 0 && avctx->framerate.den > 0) {
859             vseq->num_units_in_tick = avctx->framerate.den;
860             vseq->time_scale        = 2 * avctx->framerate.num;
861             mseq->fixed_frame_rate_flag = 1;
862         } else {
863             vseq->num_units_in_tick = avctx->time_base.num;
864             vseq->time_scale        = 2 * avctx->time_base.den;
865             mseq->fixed_frame_rate_flag = 0;
866         }
867
868         if (ctx->va_rc_mode == VA_RC_CBR) {
869             priv->send_timing_sei = 1;
870             mseq->nal_hrd_parameters_present_flag = 1;
871
872             mseq->cpb_cnt_minus1 = 0;
873
874             // Try to scale these to a sensible range so that the
875             // golomb encode of the value is not overlong.
876             mseq->bit_rate_scale =
877                 av_clip_uintp2(av_log2(avctx->bit_rate) - 15 - 6, 4);
878             mseq->bit_rate_value_minus1[0] =
879                 (avctx->bit_rate >> mseq->bit_rate_scale + 6) - 1;
880
881             mseq->cpb_size_scale =
882                 av_clip_uintp2(av_log2(ctx->hrd_params.hrd.buffer_size) - 15 - 4, 4);
883             mseq->cpb_size_value_minus1[0] =
884                 (ctx->hrd_params.hrd.buffer_size >> mseq->cpb_size_scale + 4) - 1;
885
886             // CBR mode isn't actually available here, despite naming.
887             mseq->cbr_flag[0] = 0;
888
889             mseq->initial_cpb_removal_delay_length_minus1 = 23;
890             mseq->cpb_removal_delay_length_minus1         = 23;
891             mseq->dpb_output_delay_length_minus1          = 7;
892             mseq->time_offset_length = 0;
893
894             // This calculation can easily overflow 32 bits.
895             mseq->initial_cpb_removal_delay = 90000 *
896                 (uint64_t)ctx->hrd_params.hrd.initial_buffer_fullness /
897                 ctx->hrd_params.hrd.buffer_size;
898
899             mseq->initial_cpb_removal_delay_offset = 0;
900         } else {
901             priv->send_timing_sei = 0;
902             mseq->nal_hrd_parameters_present_flag = 0;
903         }
904
905         vseq->intra_period     = ctx->p_per_i * (ctx->b_per_p + 1);
906         vseq->intra_idr_period = vseq->intra_period;
907         vseq->ip_period        = ctx->b_per_p + 1;
908     }
909
910     {
911         vpic->CurrPic.picture_id = VA_INVALID_ID;
912         vpic->CurrPic.flags      = VA_PICTURE_H264_INVALID;
913
914         for (i = 0; i < FF_ARRAY_ELEMS(vpic->ReferenceFrames); i++) {
915             vpic->ReferenceFrames[i].picture_id = VA_INVALID_ID;
916             vpic->ReferenceFrames[i].flags      = VA_PICTURE_H264_INVALID;
917         }
918
919         vpic->coded_buf = VA_INVALID_ID;
920
921         vpic->pic_parameter_set_id = 0;
922         vpic->seq_parameter_set_id = 0;
923
924         vpic->num_ref_idx_l0_active_minus1 = 0;
925         vpic->num_ref_idx_l1_active_minus1 = 0;
926
927         vpic->pic_fields.bits.entropy_coding_mode_flag =
928             ((avctx->profile & 0xff) != 66);
929         vpic->pic_fields.bits.weighted_pred_flag = 0;
930         vpic->pic_fields.bits.weighted_bipred_idc = 0;
931         vpic->pic_fields.bits.transform_8x8_mode_flag =
932             ((avctx->profile & 0xff) >= 100);
933
934         vpic->pic_init_qp = priv->fixed_qp_idr;
935     }
936
937     {
938         mseq->profile_idc = avctx->profile & 0xff;
939
940         if (avctx->profile & FF_PROFILE_H264_CONSTRAINED)
941             mseq->constraint_set1_flag = 1;
942         if (avctx->profile & FF_PROFILE_H264_INTRA)
943             mseq->constraint_set3_flag = 1;
944     }
945
946     return 0;
947 }
948
949 static int vaapi_encode_h264_init_picture_params(AVCodecContext *avctx,
950                                                  VAAPIEncodePicture *pic)
951 {
952     VAAPIEncodeContext                *ctx = avctx->priv_data;
953     VAEncSequenceParameterBufferH264 *vseq = ctx->codec_sequence_params;
954     VAEncPictureParameterBufferH264  *vpic = pic->codec_picture_params;
955     VAAPIEncodeH264Context           *priv = ctx->priv_data;
956     int i;
957
958     if (pic->type == PICTURE_TYPE_IDR) {
959         av_assert0(pic->display_order == pic->encode_order);
960         vpic->frame_num = 0;
961         priv->next_frame_num = 1;
962         priv->cpb_delay = 0;
963     } else {
964         vpic->frame_num = priv->next_frame_num;
965         if (pic->type != PICTURE_TYPE_B) {
966             // nal_ref_idc != 0
967             ++priv->next_frame_num;
968         }
969         ++priv->cpb_delay;
970     }
971     priv->dpb_delay = pic->display_order - pic->encode_order + 1;
972
973     vpic->frame_num = vpic->frame_num &
974         ((1 << (4 + vseq->seq_fields.bits.log2_max_frame_num_minus4)) - 1);
975
976     vpic->CurrPic.picture_id          = pic->recon_surface;
977     vpic->CurrPic.frame_idx           = vpic->frame_num;
978     vpic->CurrPic.flags               = 0;
979     vpic->CurrPic.TopFieldOrderCnt    = pic->display_order;
980     vpic->CurrPic.BottomFieldOrderCnt = pic->display_order;
981
982     for (i = 0; i < pic->nb_refs; i++) {
983         VAAPIEncodePicture *ref = pic->refs[i];
984         av_assert0(ref && ref->encode_order < pic->encode_order);
985         vpic->ReferenceFrames[i].picture_id = ref->recon_surface;
986         vpic->ReferenceFrames[i].frame_idx  = ref->encode_order;
987         vpic->ReferenceFrames[i].flags = VA_PICTURE_H264_SHORT_TERM_REFERENCE;
988         vpic->ReferenceFrames[i].TopFieldOrderCnt    = ref->display_order;
989         vpic->ReferenceFrames[i].BottomFieldOrderCnt = ref->display_order;
990     }
991     for (; i < FF_ARRAY_ELEMS(vpic->ReferenceFrames); i++) {
992         vpic->ReferenceFrames[i].picture_id = VA_INVALID_ID;
993         vpic->ReferenceFrames[i].flags = VA_PICTURE_H264_INVALID;
994     }
995
996     vpic->coded_buf = pic->output_buffer;
997
998     vpic->pic_fields.bits.idr_pic_flag = (pic->type == PICTURE_TYPE_IDR);
999     vpic->pic_fields.bits.reference_pic_flag = (pic->type != PICTURE_TYPE_B);
1000
1001     pic->nb_slices = 1;
1002
1003     return 0;
1004 }
1005
1006 static int vaapi_encode_h264_init_slice_params(AVCodecContext *avctx,
1007                                                VAAPIEncodePicture *pic,
1008                                                VAAPIEncodeSlice *slice)
1009 {
1010     VAAPIEncodeContext                 *ctx = avctx->priv_data;
1011     VAEncSequenceParameterBufferH264  *vseq = ctx->codec_sequence_params;
1012     VAEncPictureParameterBufferH264   *vpic = pic->codec_picture_params;
1013     VAEncSliceParameterBufferH264   *vslice = slice->codec_slice_params;
1014     VAAPIEncodeH264Context            *priv = ctx->priv_data;
1015     VAAPIEncodeH264Slice            *pslice;
1016     VAAPIEncodeH264MiscSliceParams  *mslice;
1017     int i;
1018
1019     slice->priv_data = av_mallocz(sizeof(*pslice));
1020     if (!slice->priv_data)
1021         return AVERROR(ENOMEM);
1022     pslice = slice->priv_data;
1023     mslice = &pslice->misc_slice_params;
1024
1025     if (pic->type == PICTURE_TYPE_IDR)
1026         mslice->nal_unit_type = H264_NAL_IDR_SLICE;
1027     else
1028         mslice->nal_unit_type = H264_NAL_SLICE;
1029
1030     switch (pic->type) {
1031     case PICTURE_TYPE_IDR:
1032         vslice->slice_type  = SLICE_TYPE_I;
1033         mslice->nal_ref_idc = 3;
1034         break;
1035     case PICTURE_TYPE_I:
1036         vslice->slice_type  = SLICE_TYPE_I;
1037         mslice->nal_ref_idc = 2;
1038         break;
1039     case PICTURE_TYPE_P:
1040         vslice->slice_type  = SLICE_TYPE_P;
1041         mslice->nal_ref_idc = 1;
1042         break;
1043     case PICTURE_TYPE_B:
1044         vslice->slice_type  = SLICE_TYPE_B;
1045         mslice->nal_ref_idc = 0;
1046         break;
1047     default:
1048         av_assert0(0 && "invalid picture type");
1049     }
1050
1051     // Only one slice per frame.
1052     vslice->macroblock_address = 0;
1053     vslice->num_macroblocks = priv->mb_width * priv->mb_height;
1054
1055     vslice->macroblock_info = VA_INVALID_ID;
1056
1057     vslice->pic_parameter_set_id = vpic->pic_parameter_set_id;
1058     vslice->idr_pic_id = priv->idr_pic_count++;
1059
1060     vslice->pic_order_cnt_lsb = pic->display_order &
1061         ((1 << (4 + vseq->seq_fields.bits.log2_max_pic_order_cnt_lsb_minus4)) - 1);
1062
1063     for (i = 0; i < FF_ARRAY_ELEMS(vslice->RefPicList0); i++) {
1064         vslice->RefPicList0[i].picture_id = VA_INVALID_ID;
1065         vslice->RefPicList0[i].flags      = VA_PICTURE_H264_INVALID;
1066         vslice->RefPicList1[i].picture_id = VA_INVALID_ID;
1067         vslice->RefPicList1[i].flags      = VA_PICTURE_H264_INVALID;
1068     }
1069
1070     av_assert0(pic->nb_refs <= 2);
1071     if (pic->nb_refs >= 1) {
1072         // Backward reference for P- or B-frame.
1073         av_assert0(pic->type == PICTURE_TYPE_P ||
1074                    pic->type == PICTURE_TYPE_B);
1075
1076         vslice->num_ref_idx_l0_active_minus1 = 0;
1077         vslice->RefPicList0[0] = vpic->ReferenceFrames[0];
1078     }
1079     if (pic->nb_refs >= 2) {
1080         // Forward reference for B-frame.
1081         av_assert0(pic->type == PICTURE_TYPE_B);
1082
1083         vslice->num_ref_idx_l1_active_minus1 = 0;
1084         vslice->RefPicList1[0] = vpic->ReferenceFrames[1];
1085     }
1086
1087     if (pic->type == PICTURE_TYPE_B)
1088         vslice->slice_qp_delta = priv->fixed_qp_b - vpic->pic_init_qp;
1089     else if (pic->type == PICTURE_TYPE_P)
1090         vslice->slice_qp_delta = priv->fixed_qp_p - vpic->pic_init_qp;
1091     else
1092         vslice->slice_qp_delta = priv->fixed_qp_idr - vpic->pic_init_qp;
1093
1094     vslice->direct_spatial_mv_pred_flag = 1;
1095
1096     return 0;
1097 }
1098
1099 static av_cold int vaapi_encode_h264_configure(AVCodecContext *avctx)
1100 {
1101     VAAPIEncodeContext      *ctx = avctx->priv_data;
1102     VAAPIEncodeH264Context *priv = ctx->priv_data;
1103     VAAPIEncodeH264Options  *opt = ctx->codec_options;
1104
1105     priv->mb_width  = FFALIGN(avctx->width,  16) / 16;
1106     priv->mb_height = FFALIGN(avctx->height, 16) / 16;
1107
1108     if (ctx->va_rc_mode == VA_RC_CQP) {
1109         priv->fixed_qp_p = opt->qp;
1110         if (avctx->i_quant_factor > 0.0)
1111             priv->fixed_qp_idr = (int)((priv->fixed_qp_p * avctx->i_quant_factor +
1112                                         avctx->i_quant_offset) + 0.5);
1113         else
1114             priv->fixed_qp_idr = priv->fixed_qp_p;
1115         if (avctx->b_quant_factor > 0.0)
1116             priv->fixed_qp_b = (int)((priv->fixed_qp_p * avctx->b_quant_factor +
1117                                       avctx->b_quant_offset) + 0.5);
1118         else
1119             priv->fixed_qp_b = priv->fixed_qp_p;
1120
1121         av_log(avctx, AV_LOG_DEBUG, "Using fixed QP = "
1122                "%d / %d / %d for IDR- / P- / B-frames.\n",
1123                priv->fixed_qp_idr, priv->fixed_qp_p, priv->fixed_qp_b);
1124
1125     } else if (ctx->va_rc_mode == VA_RC_CBR) {
1126         // These still need to be  set for pic_init_qp/slice_qp_delta.
1127         priv->fixed_qp_idr = 26;
1128         priv->fixed_qp_p   = 26;
1129         priv->fixed_qp_b   = 26;
1130
1131         av_log(avctx, AV_LOG_DEBUG, "Using constant-bitrate = %d bps.\n",
1132                avctx->bit_rate);
1133
1134     } else {
1135         av_assert0(0 && "Invalid RC mode.");
1136     }
1137
1138     if (opt->quality > 0) {
1139 #if VA_CHECK_VERSION(0, 36, 0)
1140         priv->quality_params.misc.type =
1141             VAEncMiscParameterTypeQualityLevel;
1142         priv->quality_params.quality.quality_level = opt->quality;
1143
1144         ctx->global_params[ctx->nb_global_params] =
1145             &priv->quality_params.misc;
1146         ctx->global_params_size[ctx->nb_global_params++] =
1147             sizeof(priv->quality_params);
1148 #else
1149         av_log(avctx, AV_LOG_WARNING, "The encode quality option is not "
1150                "supported with this VAAPI version.\n");
1151 #endif
1152     }
1153
1154     return 0;
1155 }
1156
1157 static const VAAPIEncodeType vaapi_encode_type_h264 = {
1158     .priv_data_size        = sizeof(VAAPIEncodeH264Context),
1159
1160     .configure             = &vaapi_encode_h264_configure,
1161
1162     .sequence_params_size  = sizeof(VAEncSequenceParameterBufferH264),
1163     .init_sequence_params  = &vaapi_encode_h264_init_sequence_params,
1164
1165     .picture_params_size   = sizeof(VAEncPictureParameterBufferH264),
1166     .init_picture_params   = &vaapi_encode_h264_init_picture_params,
1167
1168     .slice_params_size     = sizeof(VAEncSliceParameterBufferH264),
1169     .init_slice_params     = &vaapi_encode_h264_init_slice_params,
1170
1171     .sequence_header_type  = VAEncPackedHeaderSequence,
1172     .write_sequence_header = &vaapi_encode_h264_write_sequence_header,
1173
1174     .slice_header_type     = VAEncPackedHeaderH264_Slice,
1175     .write_slice_header    = &vaapi_encode_h264_write_slice_header,
1176
1177     .write_extra_header    = &vaapi_encode_h264_write_extra_header,
1178 };
1179
1180 static av_cold int vaapi_encode_h264_init(AVCodecContext *avctx)
1181 {
1182     VAAPIEncodeContext     *ctx = avctx->priv_data;
1183     VAAPIEncodeH264Options *opt =
1184         (VAAPIEncodeH264Options*)ctx->codec_options_data;
1185
1186     ctx->codec = &vaapi_encode_type_h264;
1187
1188     switch (avctx->profile) {
1189     case FF_PROFILE_H264_CONSTRAINED_BASELINE:
1190         ctx->va_profile = VAProfileH264ConstrainedBaseline;
1191         break;
1192     case FF_PROFILE_H264_BASELINE:
1193         ctx->va_profile = VAProfileH264Baseline;
1194         break;
1195     case FF_PROFILE_H264_MAIN:
1196         ctx->va_profile = VAProfileH264Main;
1197         break;
1198     case FF_PROFILE_H264_EXTENDED:
1199         av_log(avctx, AV_LOG_ERROR, "H.264 extended profile "
1200                "is not supported.\n");
1201         return AVERROR_PATCHWELCOME;
1202     case FF_PROFILE_UNKNOWN:
1203     case FF_PROFILE_H264_HIGH:
1204         ctx->va_profile = VAProfileH264High;
1205         break;
1206     case FF_PROFILE_H264_HIGH_10:
1207     case FF_PROFILE_H264_HIGH_10_INTRA:
1208         av_log(avctx, AV_LOG_ERROR, "H.264 10-bit profiles "
1209                "are not supported.\n");
1210         return AVERROR_PATCHWELCOME;
1211     case FF_PROFILE_H264_HIGH_422:
1212     case FF_PROFILE_H264_HIGH_422_INTRA:
1213     case FF_PROFILE_H264_HIGH_444:
1214     case FF_PROFILE_H264_HIGH_444_PREDICTIVE:
1215     case FF_PROFILE_H264_HIGH_444_INTRA:
1216     case FF_PROFILE_H264_CAVLC_444:
1217         av_log(avctx, AV_LOG_ERROR, "H.264 non-4:2:0 profiles "
1218                "are not supported.\n");
1219         return AVERROR_PATCHWELCOME;
1220     default:
1221         av_log(avctx, AV_LOG_ERROR, "Unknown H.264 profile %d.\n",
1222                avctx->profile);
1223         return AVERROR(EINVAL);
1224     }
1225     if (opt->low_power) {
1226 #if VA_CHECK_VERSION(0, 39, 2)
1227         ctx->va_entrypoint = VAEntrypointEncSliceLP;
1228 #else
1229         av_log(avctx, AV_LOG_ERROR, "Low-power encoding is not "
1230                "supported with this VAAPI version.\n");
1231         return AVERROR(EINVAL);
1232 #endif
1233     } else {
1234         ctx->va_entrypoint = VAEntrypointEncSlice;
1235     }
1236
1237     // Only 8-bit encode is supported.
1238     ctx->va_rt_format = VA_RT_FORMAT_YUV420;
1239
1240     if (avctx->bit_rate > 0)
1241         ctx->va_rc_mode = VA_RC_CBR;
1242     else
1243         ctx->va_rc_mode = VA_RC_CQP;
1244
1245     ctx->va_packed_headers =
1246         VA_ENC_PACKED_HEADER_SEQUENCE | // SPS and PPS.
1247         VA_ENC_PACKED_HEADER_SLICE    | // Slice headers.
1248         VA_ENC_PACKED_HEADER_MISC;      // SEI.
1249
1250     ctx->surface_width  = FFALIGN(avctx->width,  16);
1251     ctx->surface_height = FFALIGN(avctx->height, 16);
1252
1253     return ff_vaapi_encode_init(avctx);
1254 }
1255
1256 #define OFFSET(x) (offsetof(VAAPIEncodeContext, codec_options_data) + \
1257                    offsetof(VAAPIEncodeH264Options, x))
1258 #define FLAGS (AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM)
1259 static const AVOption vaapi_encode_h264_options[] = {
1260     { "qp", "Constant QP (for P-frames; scaled by qfactor/qoffset for I/B)",
1261       OFFSET(qp), AV_OPT_TYPE_INT, { .i64 = 20 }, 0, 52, FLAGS },
1262     { "quality", "Set encode quality (trades off against speed, higher is faster)",
1263       OFFSET(quality), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 8, FLAGS },
1264     { "low_power", "Use low-power encoding mode (experimental: only supported "
1265       "on some platforms, does not support all features)",
1266       OFFSET(low_power), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, FLAGS },
1267     { NULL },
1268 };
1269
1270 static const AVCodecDefault vaapi_encode_h264_defaults[] = {
1271     { "profile",        "100" },
1272     { "level",          "51"  },
1273     { "b",              "0"   },
1274     { "bf",             "2"   },
1275     { "g",              "120" },
1276     { "i_qfactor",      "1.0" },
1277     { "i_qoffset",      "0.0" },
1278     { "b_qfactor",      "1.2" },
1279     { "b_qoffset",      "0.0" },
1280     { NULL },
1281 };
1282
1283 static const AVClass vaapi_encode_h264_class = {
1284     .class_name = "h264_vaapi",
1285     .item_name  = av_default_item_name,
1286     .option     = vaapi_encode_h264_options,
1287     .version    = LIBAVUTIL_VERSION_INT,
1288 };
1289
1290 AVCodec ff_h264_vaapi_encoder = {
1291     .name           = "h264_vaapi",
1292     .long_name      = NULL_IF_CONFIG_SMALL("H.264/AVC (VAAPI)"),
1293     .type           = AVMEDIA_TYPE_VIDEO,
1294     .id             = AV_CODEC_ID_H264,
1295     .priv_data_size = (sizeof(VAAPIEncodeContext) +
1296                        sizeof(VAAPIEncodeH264Options)),
1297     .init           = &vaapi_encode_h264_init,
1298     .encode2        = &ff_vaapi_encode2,
1299     .close          = &ff_vaapi_encode_close,
1300     .priv_class     = &vaapi_encode_h264_class,
1301     .capabilities   = AV_CODEC_CAP_DELAY,
1302     .defaults       = vaapi_encode_h264_defaults,
1303     .pix_fmts = (const enum AVPixelFormat[]) {
1304         AV_PIX_FMT_VAAPI,
1305         AV_PIX_FMT_NONE,
1306     },
1307 };