vaapi_h264: Convert to use coded bitstream infrastructure
[ffmpeg.git] / libavcodec / vaapi_encode_h264.c
1 /*
2  * This file is part of FFmpeg.
3  *
4  * FFmpeg 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  * FFmpeg 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 FFmpeg; if not, write to the Free Software
16  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17  */
18
19 #include <string.h>
20
21 #include <va/va.h>
22 #include <va/va_enc_h264.h>
23
24 #include "libavutil/avassert.h"
25 #include "libavutil/common.h"
26 #include "libavutil/internal.h"
27 #include "libavutil/opt.h"
28
29 #include "avcodec.h"
30 #include "cbs.h"
31 #include "cbs_h264.h"
32 #include "h264.h"
33 #include "h264_sei.h"
34 #include "internal.h"
35 #include "vaapi_encode.h"
36
37 enum {
38     SEI_TIMING         = 0x01,
39     SEI_IDENTIFIER     = 0x02,
40 };
41
42 // Random (version 4) ISO 11578 UUID.
43 static const uint8_t vaapi_encode_h264_sei_identifier_uuid[16] = {
44     0x59, 0x94, 0x8b, 0x28, 0x11, 0xec, 0x45, 0xaf,
45     0x96, 0x75, 0x19, 0xd4, 0x1f, 0xea, 0xa9, 0x4d,
46 };
47
48 typedef struct VAAPIEncodeH264Context {
49     int mb_width;
50     int mb_height;
51
52     int fixed_qp_idr;
53     int fixed_qp_p;
54     int fixed_qp_b;
55
56     H264RawSPS sps;
57     H264RawPPS pps;
58     H264RawSEI sei;
59     H264RawSlice slice;
60
61     H264RawSEIBufferingPeriod buffering_period;
62     H264RawSEIPicTiming pic_timing;
63     H264RawSEIUserDataUnregistered identifier;
64     char *identifier_string;
65
66     int frame_num;
67     int pic_order_cnt;
68     int next_frame_num;
69     int64_t last_idr_frame;
70     int64_t idr_pic_count;
71
72     int primary_pic_type;
73     int slice_type;
74
75     int cpb_delay;
76     int dpb_delay;
77
78     CodedBitstreamContext *cbc;
79     CodedBitstreamFragment current_access_unit;
80     int sei_needed;
81 } VAAPIEncodeH264Context;
82
83 typedef struct VAAPIEncodeH264Options {
84     int qp;
85     int quality;
86     int low_power;
87     // Entropy encoder type.
88     int coder;
89     int sei;
90 } VAAPIEncodeH264Options;
91
92
93 static int vaapi_encode_h264_write_access_unit(AVCodecContext *avctx,
94                                                char *data, size_t *data_len,
95                                                CodedBitstreamFragment *au)
96 {
97     VAAPIEncodeContext      *ctx = avctx->priv_data;
98     VAAPIEncodeH264Context *priv = ctx->priv_data;
99     int err;
100
101     err = ff_cbs_write_fragment_data(priv->cbc, au);
102     if (err < 0) {
103         av_log(avctx, AV_LOG_ERROR, "Failed to write packed header.\n");
104         return err;
105     }
106
107     if (*data_len < 8 * au->data_size - au->data_bit_padding) {
108         av_log(avctx, AV_LOG_ERROR, "Access unit too large: "
109                "%zu < %zu.\n", *data_len,
110                8 * au->data_size - au->data_bit_padding);
111         return AVERROR(ENOSPC);
112     }
113
114     memcpy(data, au->data, au->data_size);
115     *data_len = 8 * au->data_size - au->data_bit_padding;
116
117     return 0;
118 }
119
120 static int vaapi_encode_h264_add_nal(AVCodecContext *avctx,
121                                      CodedBitstreamFragment *au,
122                                      void *nal_unit)
123 {
124     VAAPIEncodeContext      *ctx = avctx->priv_data;
125     VAAPIEncodeH264Context *priv = ctx->priv_data;
126     H264RawNALUnitHeader *header = nal_unit;
127     int err;
128
129     err = ff_cbs_insert_unit_content(priv->cbc, au, -1,
130                                      header->nal_unit_type, nal_unit);
131     if (err < 0) {
132         av_log(avctx, AV_LOG_ERROR, "Failed to add NAL unit: "
133                "type = %d.\n", header->nal_unit_type);
134         return err;
135     }
136
137     return 0;
138 }
139
140 static int vaapi_encode_h264_write_sequence_header(AVCodecContext *avctx,
141                                                    char *data, size_t *data_len)
142 {
143     VAAPIEncodeContext      *ctx = avctx->priv_data;
144     VAAPIEncodeH264Context *priv = ctx->priv_data;
145     CodedBitstreamFragment   *au = &priv->current_access_unit;
146     int err;
147
148     err = vaapi_encode_h264_add_nal(avctx, au, &priv->sps);
149     if (err < 0)
150         goto fail;
151
152     err = vaapi_encode_h264_add_nal(avctx, au, &priv->pps);
153     if (err < 0)
154         goto fail;
155
156     err = vaapi_encode_h264_write_access_unit(avctx, data, data_len, au);
157 fail:
158     ff_cbs_fragment_uninit(priv->cbc, au);
159     return err;
160 }
161
162 static int vaapi_encode_h264_write_slice_header(AVCodecContext *avctx,
163                                                 VAAPIEncodePicture *pic,
164                                                 VAAPIEncodeSlice *slice,
165                                                 char *data, size_t *data_len)
166 {
167     VAAPIEncodeContext      *ctx = avctx->priv_data;
168     VAAPIEncodeH264Context *priv = ctx->priv_data;
169     CodedBitstreamFragment   *au = &priv->current_access_unit;
170     int err;
171
172     err = vaapi_encode_h264_add_nal(avctx, au, &priv->slice);
173     if (err < 0)
174         goto fail;
175
176     err = vaapi_encode_h264_write_access_unit(avctx, data, data_len, au);
177 fail:
178     ff_cbs_fragment_uninit(priv->cbc, au);
179     return err;
180 }
181
182 static int vaapi_encode_h264_write_extra_header(AVCodecContext *avctx,
183                                                 VAAPIEncodePicture *pic,
184                                                 int index, int *type,
185                                                 char *data, size_t *data_len)
186 {
187     VAAPIEncodeContext      *ctx = avctx->priv_data;
188     VAAPIEncodeH264Context *priv = ctx->priv_data;
189     VAAPIEncodeH264Options  *opt = ctx->codec_options;
190     CodedBitstreamFragment   *au = &priv->current_access_unit;
191     int err, i;
192
193     if (priv->sei_needed) {
194         memset(&priv->sei, 0, sizeof(priv->sei));
195         priv->sei.nal_unit_header.nal_unit_type = H264_NAL_SEI;
196
197         i = 0;
198         if (pic->encode_order == 0 && opt->sei & SEI_IDENTIFIER) {
199             priv->sei.payload[i].payload_type = H264_SEI_TYPE_USER_DATA_UNREGISTERED;
200             priv->sei.payload[i].payload.user_data_unregistered = priv->identifier;
201             ++i;
202         }
203         if (opt->sei & SEI_TIMING) {
204             if (pic->type == PICTURE_TYPE_IDR) {
205                 priv->sei.payload[i].payload_type = H264_SEI_TYPE_BUFFERING_PERIOD;
206                 priv->sei.payload[i].payload.buffering_period = priv->buffering_period;
207                 ++i;
208             }
209             priv->sei.payload[i].payload_type = H264_SEI_TYPE_PIC_TIMING;
210             priv->sei.payload[i].payload.pic_timing = priv->pic_timing;
211             ++i;
212         }
213
214         priv->sei.payload_count = i;
215         av_assert0(priv->sei.payload_count > 0);
216
217         err = vaapi_encode_h264_add_nal(avctx, au, &priv->sei);
218         if (err < 0)
219             goto fail;
220         priv->sei_needed = 0;
221
222         err = vaapi_encode_h264_write_access_unit(avctx, data, data_len, au);
223         if (err < 0)
224             goto fail;
225
226         ff_cbs_fragment_uninit(priv->cbc, au);
227
228         *type = VAEncPackedHeaderH264_SEI;
229         return 0;
230     } else {
231         return AVERROR_EOF;
232     }
233
234 fail:
235     ff_cbs_fragment_uninit(priv->cbc, au);
236     return err;
237 }
238
239 static int vaapi_encode_h264_init_sequence_params(AVCodecContext *avctx)
240 {
241     VAAPIEncodeContext                *ctx = avctx->priv_data;
242     VAAPIEncodeH264Context           *priv = ctx->priv_data;
243     VAAPIEncodeH264Options            *opt = ctx->codec_options;
244     H264RawSPS                        *sps = &priv->sps;
245     H264RawPPS                        *pps = &priv->pps;
246     VAEncSequenceParameterBufferH264 *vseq = ctx->codec_sequence_params;
247     VAEncPictureParameterBufferH264  *vpic = ctx->codec_picture_params;
248
249     memset(&priv->current_access_unit, 0,
250            sizeof(priv->current_access_unit));
251
252     memset(sps, 0, sizeof(*sps));
253     memset(pps, 0, sizeof(*pps));
254
255     sps->nal_unit_header.nal_ref_idc   = 3;
256     sps->nal_unit_header.nal_unit_type = H264_NAL_SPS;
257
258     sps->profile_idc = avctx->profile & 0xff;
259     sps->constraint_set1_flag =
260         !!(avctx->profile & FF_PROFILE_H264_CONSTRAINED);
261     sps->constraint_set3_flag =
262         !!(avctx->profile & FF_PROFILE_H264_INTRA);
263
264     sps->level_idc = avctx->level;
265
266     sps->seq_parameter_set_id = 0;
267     sps->chroma_format_idc    = 1;
268
269     sps->log2_max_frame_num_minus4 = 4;
270     sps->pic_order_cnt_type        = 0;
271     sps->log2_max_pic_order_cnt_lsb_minus4 =
272         av_clip(av_log2(ctx->b_per_p + 1) - 2, 0, 12);
273
274     sps->max_num_ref_frames =
275         (avctx->profile & FF_PROFILE_H264_INTRA) ? 0 :
276         1 + (ctx->b_per_p > 0);
277
278     sps->pic_width_in_mbs_minus1        = priv->mb_width  - 1;
279     sps->pic_height_in_map_units_minus1 = priv->mb_height - 1;
280
281     sps->frame_mbs_only_flag = 1;
282     sps->direct_8x8_inference_flag = 1;
283
284     if (avctx->width  != 16 * priv->mb_width ||
285         avctx->height != 16 * priv->mb_height) {
286         sps->frame_cropping_flag = 1;
287
288         sps->frame_crop_left_offset   = 0;
289         sps->frame_crop_right_offset  =
290             (16 * priv->mb_width - avctx->width) / 2;
291         sps->frame_crop_top_offset    = 0;
292         sps->frame_crop_bottom_offset =
293             (16 * priv->mb_height - avctx->height) / 2;
294     } else {
295         sps->frame_cropping_flag = 0;
296     }
297
298     sps->vui_parameters_present_flag = 1;
299
300     if (avctx->sample_aspect_ratio.num != 0 &&
301         avctx->sample_aspect_ratio.den != 0) {
302         static const AVRational sar_idc[] = {
303             {   0,  0 },
304             {   1,  1 }, {  12, 11 }, {  10, 11 }, {  16, 11 },
305             {  40, 33 }, {  24, 11 }, {  20, 11 }, {  32, 11 },
306             {  80, 33 }, {  18, 11 }, {  15, 11 }, {  64, 33 },
307             { 160, 99 }, {   4,  3 }, {   3,  2 }, {   2,  1 },
308         };
309         int i;
310         for (i = 0; i < FF_ARRAY_ELEMS(sar_idc); i++) {
311             if (avctx->sample_aspect_ratio.num == sar_idc[i].num &&
312                 avctx->sample_aspect_ratio.den == sar_idc[i].den) {
313                 sps->vui.aspect_ratio_idc = i;
314                 break;
315             }
316         }
317         if (i >= FF_ARRAY_ELEMS(sar_idc)) {
318             sps->vui.aspect_ratio_idc = 255;
319             sps->vui.sar_width  = avctx->sample_aspect_ratio.num;
320             sps->vui.sar_height = avctx->sample_aspect_ratio.den;
321         }
322         sps->vui.aspect_ratio_info_present_flag = 1;
323     }
324
325     if (avctx->color_range     != AVCOL_RANGE_UNSPECIFIED ||
326         avctx->color_primaries != AVCOL_PRI_UNSPECIFIED ||
327         avctx->color_trc       != AVCOL_TRC_UNSPECIFIED ||
328         avctx->colorspace      != AVCOL_SPC_UNSPECIFIED) {
329         sps->vui.video_signal_type_present_flag = 1;
330         sps->vui.video_format      = 5; // Unspecified.
331         sps->vui.video_full_range_flag =
332             avctx->color_range == AVCOL_RANGE_JPEG;
333
334         if (avctx->color_primaries != AVCOL_PRI_UNSPECIFIED ||
335             avctx->color_trc       != AVCOL_TRC_UNSPECIFIED ||
336             avctx->colorspace      != AVCOL_SPC_UNSPECIFIED) {
337             sps->vui.colour_description_present_flag = 1;
338             sps->vui.colour_primaries         = avctx->color_primaries;
339             sps->vui.transfer_characteristics = avctx->color_trc;
340             sps->vui.matrix_coefficients      = avctx->colorspace;
341         }
342     } else {
343         sps->vui.video_format             = 5;
344         sps->vui.video_full_range_flag    = 0;
345         sps->vui.colour_primaries         = avctx->color_primaries;
346         sps->vui.transfer_characteristics = avctx->color_trc;
347         sps->vui.matrix_coefficients      = avctx->colorspace;
348     }
349
350     if (avctx->chroma_sample_location != AVCHROMA_LOC_UNSPECIFIED) {
351         sps->vui.chroma_loc_info_present_flag = 1;
352         sps->vui.chroma_sample_loc_type_top_field    =
353         sps->vui.chroma_sample_loc_type_bottom_field =
354             avctx->chroma_sample_location - 1;
355     }
356
357     sps->vui.timing_info_present_flag = 1;
358     if (avctx->framerate.num > 0 && avctx->framerate.den > 0) {
359         sps->vui.num_units_in_tick = avctx->framerate.den;
360         sps->vui.time_scale        = 2 * avctx->framerate.num;
361         sps->vui.fixed_frame_rate_flag = 1;
362     } else {
363         sps->vui.num_units_in_tick = avctx->time_base.num;
364         sps->vui.time_scale        = 2 * avctx->time_base.den;
365         sps->vui.fixed_frame_rate_flag = 0;
366     }
367
368     if (opt->sei & SEI_TIMING) {
369         H264RawHRD *hrd = &sps->vui.nal_hrd_parameters;
370
371         sps->vui.nal_hrd_parameters_present_flag = 1;
372
373         hrd->cpb_cnt_minus1 = 0;
374
375         // Try to scale these to a sensible range so that the
376         // golomb encode of the value is not overlong.
377         hrd->bit_rate_scale =
378             av_clip_uintp2(av_log2(avctx->bit_rate) - 15 - 6, 4);
379         hrd->bit_rate_value_minus1[0] =
380             (avctx->bit_rate >> hrd->bit_rate_scale + 6) - 1;
381
382         hrd->cpb_size_scale =
383             av_clip_uintp2(av_log2(ctx->hrd_params.hrd.buffer_size) - 15 - 4, 4);
384         hrd->cpb_size_value_minus1[0] =
385             (ctx->hrd_params.hrd.buffer_size >> hrd->cpb_size_scale + 4) - 1;
386
387         // CBR mode as defined for the HRD cannot be achieved without filler
388         // data, so this flag cannot be set even with VAAPI CBR modes.
389         hrd->cbr_flag[0] = 0;
390
391         hrd->initial_cpb_removal_delay_length_minus1 = 23;
392         hrd->cpb_removal_delay_length_minus1         = 23;
393         hrd->dpb_output_delay_length_minus1          = 7;
394         hrd->time_offset_length                      = 0;
395
396         priv->buffering_period.seq_parameter_set_id = sps->seq_parameter_set_id;
397
398         // This calculation can easily overflow 32 bits.
399         priv->buffering_period.nal.initial_cpb_removal_delay[0] = 90000 *
400             (uint64_t)ctx->hrd_params.hrd.initial_buffer_fullness /
401             ctx->hrd_params.hrd.buffer_size;
402         priv->buffering_period.nal.initial_cpb_removal_delay_offset[0] = 0;
403     } else {
404         sps->vui.nal_hrd_parameters_present_flag = 0;
405         sps->vui.low_delay_hrd_flag = 1 - sps->vui.fixed_frame_rate_flag;
406     }
407
408     sps->vui.bitstream_restriction_flag    = 1;
409     sps->vui.motion_vectors_over_pic_boundaries_flag = 1;
410     sps->vui.log2_max_mv_length_horizontal = 16;
411     sps->vui.log2_max_mv_length_vertical   = 16;
412     sps->vui.max_num_reorder_frames        = (ctx->b_per_p > 0);
413     sps->vui.max_dec_frame_buffering       = vseq->max_num_ref_frames;
414
415     pps->nal_unit_header.nal_ref_idc = 3;
416     pps->nal_unit_header.nal_unit_type = H264_NAL_PPS;
417
418     pps->pic_parameter_set_id = 0;
419     pps->seq_parameter_set_id = 0;
420
421     pps->entropy_coding_mode_flag =
422         !(sps->profile_idc == FF_PROFILE_H264_BASELINE ||
423           sps->profile_idc == FF_PROFILE_H264_EXTENDED ||
424           sps->profile_idc == FF_PROFILE_H264_CAVLC_444);
425     if (!opt->coder && pps->entropy_coding_mode_flag)
426         pps->entropy_coding_mode_flag = 0;
427
428     pps->num_ref_idx_l0_default_active_minus1 = 0;
429     pps->num_ref_idx_l1_default_active_minus1 = 0;
430
431     pps->pic_init_qp_minus26 = priv->fixed_qp_idr - 26;
432
433     if (sps->profile_idc == FF_PROFILE_H264_BASELINE ||
434         sps->profile_idc == FF_PROFILE_H264_EXTENDED ||
435         sps->profile_idc == FF_PROFILE_H264_MAIN) {
436         pps->more_rbsp_data = 0;
437     } else {
438         pps->more_rbsp_data = 1;
439
440         pps->transform_8x8_mode_flag = 1;
441     }
442
443     *vseq = (VAEncSequenceParameterBufferH264) {
444         .seq_parameter_set_id = sps->seq_parameter_set_id,
445         .level_idc        = sps->level_idc,
446         .intra_period     = avctx->gop_size,
447         .intra_idr_period = avctx->gop_size,
448         .ip_period        = ctx->b_per_p + 1,
449
450         .bits_per_second       = avctx->bit_rate,
451         .max_num_ref_frames    = sps->max_num_ref_frames,
452         .picture_width_in_mbs  = sps->pic_width_in_mbs_minus1 + 1,
453         .picture_height_in_mbs = sps->pic_height_in_map_units_minus1 + 1,
454
455         .seq_fields.bits = {
456             .chroma_format_idc                 = sps->chroma_format_idc,
457             .frame_mbs_only_flag               = sps->frame_mbs_only_flag,
458             .mb_adaptive_frame_field_flag      = sps->mb_adaptive_frame_field_flag,
459             .seq_scaling_matrix_present_flag   = sps->seq_scaling_matrix_present_flag,
460             .direct_8x8_inference_flag         = sps->direct_8x8_inference_flag,
461             .log2_max_frame_num_minus4         = sps->log2_max_frame_num_minus4,
462             .pic_order_cnt_type                = sps->pic_order_cnt_type,
463             .log2_max_pic_order_cnt_lsb_minus4 = sps->log2_max_pic_order_cnt_lsb_minus4,
464             .delta_pic_order_always_zero_flag  = sps->delta_pic_order_always_zero_flag,
465         },
466
467         .bit_depth_luma_minus8   = sps->bit_depth_luma_minus8,
468         .bit_depth_chroma_minus8 = sps->bit_depth_chroma_minus8,
469
470         .frame_cropping_flag      = sps->frame_cropping_flag,
471         .frame_crop_left_offset   = sps->frame_crop_left_offset,
472         .frame_crop_right_offset  = sps->frame_crop_right_offset,
473         .frame_crop_top_offset    = sps->frame_crop_top_offset,
474         .frame_crop_bottom_offset = sps->frame_crop_bottom_offset,
475
476         .vui_parameters_present_flag = sps->vui_parameters_present_flag,
477
478         .vui_fields.bits = {
479             .aspect_ratio_info_present_flag = sps->vui.aspect_ratio_info_present_flag,
480             .timing_info_present_flag       = sps->vui.timing_info_present_flag,
481             .bitstream_restriction_flag     = sps->vui.bitstream_restriction_flag,
482             .log2_max_mv_length_horizontal  = sps->vui.log2_max_mv_length_horizontal,
483             .log2_max_mv_length_vertical    = sps->vui.log2_max_mv_length_vertical,
484         },
485
486         .aspect_ratio_idc  = sps->vui.aspect_ratio_idc,
487         .sar_width         = sps->vui.sar_width,
488         .sar_height        = sps->vui.sar_height,
489         .num_units_in_tick = sps->vui.num_units_in_tick,
490         .time_scale        = sps->vui.time_scale,
491     };
492
493     *vpic = (VAEncPictureParameterBufferH264) {
494         .CurrPic = {
495             .picture_id = VA_INVALID_ID,
496             .flags      = VA_PICTURE_H264_INVALID,
497         },
498
499         .coded_buf = VA_INVALID_ID,
500
501         .pic_parameter_set_id = pps->pic_parameter_set_id,
502         .seq_parameter_set_id = pps->seq_parameter_set_id,
503
504         .pic_init_qp                  = pps->pic_init_qp_minus26 + 26,
505         .num_ref_idx_l0_active_minus1 = pps->num_ref_idx_l0_default_active_minus1,
506         .num_ref_idx_l1_active_minus1 = pps->num_ref_idx_l1_default_active_minus1,
507
508         .chroma_qp_index_offset        = pps->chroma_qp_index_offset,
509         .second_chroma_qp_index_offset = pps->second_chroma_qp_index_offset,
510
511         .pic_fields.bits = {
512             .entropy_coding_mode_flag        = pps->entropy_coding_mode_flag,
513             .weighted_pred_flag              = pps->weighted_pred_flag,
514             .weighted_bipred_idc             = pps->weighted_bipred_idc,
515             .constrained_intra_pred_flag     = pps->constrained_intra_pred_flag,
516             .transform_8x8_mode_flag         = pps->transform_8x8_mode_flag,
517             .deblocking_filter_control_present_flag =
518                 pps->deblocking_filter_control_present_flag,
519             .redundant_pic_cnt_present_flag  = pps->redundant_pic_cnt_present_flag,
520             .pic_order_present_flag          =
521                 pps->bottom_field_pic_order_in_frame_present_flag,
522             .pic_scaling_matrix_present_flag = pps->pic_scaling_matrix_present_flag,
523         },
524     };
525
526     return 0;
527 }
528
529 static int vaapi_encode_h264_init_picture_params(AVCodecContext *avctx,
530                                                  VAAPIEncodePicture *pic)
531 {
532     VAAPIEncodeContext               *ctx = avctx->priv_data;
533     VAAPIEncodeH264Context          *priv = ctx->priv_data;
534     VAAPIEncodeH264Options           *opt = ctx->codec_options;
535     H264RawSPS                       *sps = &priv->sps;
536     VAEncPictureParameterBufferH264 *vpic = pic->codec_picture_params;
537     int i;
538
539     memset(&priv->current_access_unit, 0,
540            sizeof(priv->current_access_unit));
541
542     if (pic->type == PICTURE_TYPE_IDR) {
543         av_assert0(pic->display_order == pic->encode_order);
544         priv->frame_num      = 0;
545         priv->next_frame_num = 1;
546         priv->cpb_delay      = 0;
547         priv->last_idr_frame = pic->display_order;
548         ++priv->idr_pic_count;
549
550         priv->slice_type       = 7;
551         priv->primary_pic_type = 0;
552     } else {
553         priv->frame_num      = priv->next_frame_num;
554
555         if (pic->type != PICTURE_TYPE_B) {
556             // Reference picture, so frame_num advances.
557             priv->next_frame_num = (priv->frame_num + 1) &
558                 ((1 << (4 + sps->log2_max_frame_num_minus4)) - 1);
559         }
560         ++priv->cpb_delay;
561
562         if (pic->type == PICTURE_TYPE_I) {
563             priv->slice_type       = 7;
564             priv->primary_pic_type = 0;
565         } else if (pic->type == PICTURE_TYPE_P) {
566             priv->slice_type       = 5;
567             priv->primary_pic_type = 1;
568         } else {
569             priv->slice_type       = 6;
570             priv->primary_pic_type = 2;
571         }
572     }
573     priv->pic_order_cnt = pic->display_order - priv->last_idr_frame;
574     priv->dpb_delay     = pic->display_order - pic->encode_order + 1;
575
576     if (opt->sei & SEI_IDENTIFIER && pic->encode_order == 0)
577         priv->sei_needed = 1;
578
579     if (opt->sei & SEI_TIMING) {
580         memset(&priv->pic_timing, 0, sizeof(priv->pic_timing));
581
582         priv->pic_timing.cpb_removal_delay =
583             2 * sps->vui.num_units_in_tick * priv->cpb_delay;
584         priv->pic_timing.dpb_output_delay =
585             2 * sps->vui.num_units_in_tick * priv->dpb_delay;
586
587         priv->sei_needed = 1;
588     }
589
590     vpic->CurrPic = (VAPictureH264) {
591         .picture_id          = pic->recon_surface,
592         .frame_idx           = priv->frame_num,
593         .flags               = 0,
594         .TopFieldOrderCnt    = priv->pic_order_cnt,
595         .BottomFieldOrderCnt = priv->pic_order_cnt,
596     };
597
598     for (i = 0; i < pic->nb_refs; i++) {
599         VAAPIEncodePicture *ref = pic->refs[i];
600         unsigned int frame_num = (ref->encode_order - priv->last_idr_frame) &
601             ((1 << (4 + sps->log2_max_frame_num_minus4)) - 1);
602         unsigned int pic_order_cnt = ref->display_order - priv->last_idr_frame;
603
604         av_assert0(ref && ref->encode_order < pic->encode_order);
605         vpic->ReferenceFrames[i] = (VAPictureH264) {
606             .picture_id          = ref->recon_surface,
607             .frame_idx           = frame_num,
608             .flags               = VA_PICTURE_H264_SHORT_TERM_REFERENCE,
609             .TopFieldOrderCnt    = pic_order_cnt,
610             .BottomFieldOrderCnt = pic_order_cnt,
611         };
612     }
613     for (; i < FF_ARRAY_ELEMS(vpic->ReferenceFrames); i++) {
614         vpic->ReferenceFrames[i] = (VAPictureH264) {
615             .picture_id = VA_INVALID_ID,
616             .flags      = VA_PICTURE_H264_INVALID,
617         };
618     }
619
620     vpic->coded_buf = pic->output_buffer;
621
622     vpic->frame_num = priv->frame_num;
623
624     vpic->pic_fields.bits.idr_pic_flag       = (pic->type == PICTURE_TYPE_IDR);
625     vpic->pic_fields.bits.reference_pic_flag = (pic->type != PICTURE_TYPE_B);
626
627     pic->nb_slices = 1;
628
629     return 0;
630 }
631
632 static int vaapi_encode_h264_init_slice_params(AVCodecContext *avctx,
633                                                VAAPIEncodePicture *pic,
634                                                VAAPIEncodeSlice *slice)
635 {
636     VAAPIEncodeContext               *ctx = avctx->priv_data;
637     VAAPIEncodeH264Context          *priv = ctx->priv_data;
638     H264RawSPS                       *sps = &priv->sps;
639     H264RawPPS                       *pps = &priv->pps;
640     H264RawSliceHeader                *sh = &priv->slice.header;
641     VAEncPictureParameterBufferH264 *vpic = pic->codec_picture_params;
642     VAEncSliceParameterBufferH264 *vslice = slice->codec_slice_params;
643     int i;
644
645     if (pic->type == PICTURE_TYPE_IDR) {
646         sh->nal_unit_header.nal_unit_type = H264_NAL_IDR_SLICE;
647         sh->nal_unit_header.nal_ref_idc   = 3;
648     } else {
649         sh->nal_unit_header.nal_unit_type = H264_NAL_SLICE;
650         sh->nal_unit_header.nal_ref_idc   = pic->type != PICTURE_TYPE_B;
651     }
652
653     // Only one slice per frame.
654     sh->first_mb_in_slice = 0;
655     sh->slice_type        = priv->slice_type;
656
657     sh->pic_parameter_set_id = pps->pic_parameter_set_id;
658
659     sh->frame_num  = priv->frame_num;
660     sh->idr_pic_id = priv->idr_pic_count;
661
662     sh->pic_order_cnt_lsb = priv->pic_order_cnt &
663         ((1 << (4 + sps->log2_max_pic_order_cnt_lsb_minus4)) - 1);
664
665     sh->direct_spatial_mv_pred_flag = 1;
666
667     if (pic->type == PICTURE_TYPE_B)
668         sh->slice_qp_delta = priv->fixed_qp_b - (pps->pic_init_qp_minus26 + 26);
669     else if (pic->type == PICTURE_TYPE_P)
670         sh->slice_qp_delta = priv->fixed_qp_p - (pps->pic_init_qp_minus26 + 26);
671     else
672         sh->slice_qp_delta = priv->fixed_qp_idr - (pps->pic_init_qp_minus26 + 26);
673
674
675     vslice->macroblock_address = sh->first_mb_in_slice;
676     vslice->num_macroblocks    = priv->mb_width * priv->mb_height;
677
678     vslice->macroblock_info = VA_INVALID_ID;
679
680     vslice->slice_type           = sh->slice_type % 5;
681     vslice->pic_parameter_set_id = sh->pic_parameter_set_id;
682     vslice->idr_pic_id           = sh->idr_pic_id;
683
684     vslice->pic_order_cnt_lsb = sh->pic_order_cnt_lsb;
685
686     vslice->direct_spatial_mv_pred_flag = sh->direct_spatial_mv_pred_flag;
687
688     for (i = 0; i < FF_ARRAY_ELEMS(vslice->RefPicList0); i++) {
689         vslice->RefPicList0[i].picture_id = VA_INVALID_ID;
690         vslice->RefPicList0[i].flags      = VA_PICTURE_H264_INVALID;
691         vslice->RefPicList1[i].picture_id = VA_INVALID_ID;
692         vslice->RefPicList1[i].flags      = VA_PICTURE_H264_INVALID;
693     }
694
695     av_assert0(pic->nb_refs <= 2);
696     if (pic->nb_refs >= 1) {
697         // Backward reference for P- or B-frame.
698         av_assert0(pic->type == PICTURE_TYPE_P ||
699                    pic->type == PICTURE_TYPE_B);
700         vslice->RefPicList0[0] = vpic->ReferenceFrames[0];
701     }
702     if (pic->nb_refs >= 2) {
703         // Forward reference for B-frame.
704         av_assert0(pic->type == PICTURE_TYPE_B);
705         vslice->RefPicList1[0] = vpic->ReferenceFrames[1];
706     }
707
708     vslice->slice_qp_delta = sh->slice_qp_delta;
709
710     return 0;
711 }
712
713 static av_cold int vaapi_encode_h264_configure(AVCodecContext *avctx)
714 {
715     VAAPIEncodeContext      *ctx = avctx->priv_data;
716     VAAPIEncodeH264Context *priv = ctx->priv_data;
717     VAAPIEncodeH264Options  *opt = ctx->codec_options;
718     int err;
719
720     err = ff_cbs_init(&priv->cbc, AV_CODEC_ID_H264, avctx);
721     if (err < 0)
722         return err;
723
724     priv->mb_width  = FFALIGN(avctx->width,  16) / 16;
725     priv->mb_height = FFALIGN(avctx->height, 16) / 16;
726
727     if (ctx->va_rc_mode == VA_RC_CQP) {
728         priv->fixed_qp_p = opt->qp;
729         if (avctx->i_quant_factor > 0.0)
730             priv->fixed_qp_idr = (int)((priv->fixed_qp_p * avctx->i_quant_factor +
731                                         avctx->i_quant_offset) + 0.5);
732         else
733             priv->fixed_qp_idr = priv->fixed_qp_p;
734         if (avctx->b_quant_factor > 0.0)
735             priv->fixed_qp_b = (int)((priv->fixed_qp_p * avctx->b_quant_factor +
736                                       avctx->b_quant_offset) + 0.5);
737         else
738             priv->fixed_qp_b = priv->fixed_qp_p;
739
740         opt->sei &= ~SEI_TIMING;
741
742         av_log(avctx, AV_LOG_DEBUG, "Using fixed QP = "
743                "%d / %d / %d for IDR- / P- / B-frames.\n",
744                priv->fixed_qp_idr, priv->fixed_qp_p, priv->fixed_qp_b);
745
746     } else if (ctx->va_rc_mode == VA_RC_CBR ||
747                ctx->va_rc_mode == VA_RC_VBR) {
748         // These still need to be  set for pic_init_qp/slice_qp_delta.
749         priv->fixed_qp_idr = 26;
750         priv->fixed_qp_p   = 26;
751         priv->fixed_qp_b   = 26;
752
753         av_log(avctx, AV_LOG_DEBUG, "Using %s-bitrate = %"PRId64" bps.\n",
754                ctx->va_rc_mode == VA_RC_CBR ? "constant" : "variable",
755                avctx->bit_rate);
756
757     } else {
758         av_assert0(0 && "Invalid RC mode.");
759     }
760
761     if (avctx->compression_level == FF_COMPRESSION_DEFAULT)
762         avctx->compression_level = opt->quality;
763
764     if (opt->sei & SEI_IDENTIFIER) {
765         const char *lavc  = LIBAVCODEC_IDENT;
766         const char *vaapi = VA_VERSION_S;
767         const char *driver;
768         int len;
769
770         memcpy(priv->identifier.uuid_iso_iec_11578,
771                vaapi_encode_h264_sei_identifier_uuid,
772                sizeof(priv->identifier.uuid_iso_iec_11578));
773
774         driver = vaQueryVendorString(ctx->hwctx->display);
775         if (!driver)
776             driver = "unknown driver";
777
778         len = snprintf(NULL, 0, "%s / VAAPI %s / %s", lavc, vaapi, driver);
779         if (len >= 0) {
780             priv->identifier_string = av_malloc(len + 1);
781             if (!priv->identifier_string)
782                 return AVERROR(ENOMEM);
783
784             snprintf(priv->identifier_string, len + 1,
785                      "%s / VAAPI %s / %s", lavc, vaapi, driver);
786
787             priv->identifier.data = priv->identifier_string;
788             priv->identifier.data_length = len + 1;
789         }
790     }
791
792     return 0;
793 }
794
795 static const VAAPIEncodeType vaapi_encode_type_h264 = {
796     .priv_data_size        = sizeof(VAAPIEncodeH264Context),
797
798     .configure             = &vaapi_encode_h264_configure,
799
800     .sequence_params_size  = sizeof(VAEncSequenceParameterBufferH264),
801     .init_sequence_params  = &vaapi_encode_h264_init_sequence_params,
802
803     .picture_params_size   = sizeof(VAEncPictureParameterBufferH264),
804     .init_picture_params   = &vaapi_encode_h264_init_picture_params,
805
806     .slice_params_size     = sizeof(VAEncSliceParameterBufferH264),
807     .init_slice_params     = &vaapi_encode_h264_init_slice_params,
808
809     .sequence_header_type  = VAEncPackedHeaderSequence,
810     .write_sequence_header = &vaapi_encode_h264_write_sequence_header,
811
812     .slice_header_type     = VAEncPackedHeaderH264_Slice,
813     .write_slice_header    = &vaapi_encode_h264_write_slice_header,
814
815     .write_extra_header    = &vaapi_encode_h264_write_extra_header,
816 };
817
818 static av_cold int vaapi_encode_h264_init(AVCodecContext *avctx)
819 {
820     VAAPIEncodeContext     *ctx = avctx->priv_data;
821     VAAPIEncodeH264Options *opt =
822         (VAAPIEncodeH264Options*)ctx->codec_options_data;
823
824     ctx->codec = &vaapi_encode_type_h264;
825
826     switch (avctx->profile) {
827     case FF_PROFILE_H264_BASELINE:
828         av_log(avctx, AV_LOG_WARNING, "H.264 baseline profile is not "
829                "supported, using constrained baseline profile instead.\n");
830         avctx->profile = FF_PROFILE_H264_CONSTRAINED_BASELINE;
831     case FF_PROFILE_H264_CONSTRAINED_BASELINE:
832         ctx->va_profile = VAProfileH264ConstrainedBaseline;
833         if (avctx->max_b_frames != 0) {
834             avctx->max_b_frames = 0;
835             av_log(avctx, AV_LOG_WARNING, "H.264 constrained baseline profile "
836                    "doesn't support encoding with B frames, disabling them.\n");
837         }
838         break;
839     case FF_PROFILE_H264_MAIN:
840         ctx->va_profile = VAProfileH264Main;
841         break;
842     case FF_PROFILE_H264_EXTENDED:
843         av_log(avctx, AV_LOG_ERROR, "H.264 extended profile "
844                "is not supported.\n");
845         return AVERROR_PATCHWELCOME;
846     case FF_PROFILE_UNKNOWN:
847     case FF_PROFILE_H264_HIGH:
848         ctx->va_profile = VAProfileH264High;
849         break;
850     case FF_PROFILE_H264_HIGH_10:
851     case FF_PROFILE_H264_HIGH_10_INTRA:
852         av_log(avctx, AV_LOG_ERROR, "H.264 10-bit profiles "
853                "are not supported.\n");
854         return AVERROR_PATCHWELCOME;
855     case FF_PROFILE_H264_HIGH_422:
856     case FF_PROFILE_H264_HIGH_422_INTRA:
857     case FF_PROFILE_H264_HIGH_444:
858     case FF_PROFILE_H264_HIGH_444_PREDICTIVE:
859     case FF_PROFILE_H264_HIGH_444_INTRA:
860     case FF_PROFILE_H264_CAVLC_444:
861         av_log(avctx, AV_LOG_ERROR, "H.264 non-4:2:0 profiles "
862                "are not supported.\n");
863         return AVERROR_PATCHWELCOME;
864     default:
865         av_log(avctx, AV_LOG_ERROR, "Unknown H.264 profile %d.\n",
866                avctx->profile);
867         return AVERROR(EINVAL);
868     }
869     if (opt->low_power) {
870 #if VA_CHECK_VERSION(0, 39, 2)
871         ctx->va_entrypoint = VAEntrypointEncSliceLP;
872 #else
873         av_log(avctx, AV_LOG_ERROR, "Low-power encoding is not "
874                "supported with this VAAPI version.\n");
875         return AVERROR(EINVAL);
876 #endif
877     } else {
878         ctx->va_entrypoint = VAEntrypointEncSlice;
879     }
880
881     // Only 8-bit encode is supported.
882     ctx->va_rt_format = VA_RT_FORMAT_YUV420;
883
884     if (avctx->bit_rate > 0) {
885         if (avctx->rc_max_rate == avctx->bit_rate)
886             ctx->va_rc_mode = VA_RC_CBR;
887         else
888             ctx->va_rc_mode = VA_RC_VBR;
889     } else
890         ctx->va_rc_mode = VA_RC_CQP;
891
892     ctx->va_packed_headers =
893         VA_ENC_PACKED_HEADER_SEQUENCE | // SPS and PPS.
894         VA_ENC_PACKED_HEADER_SLICE    | // Slice headers.
895         VA_ENC_PACKED_HEADER_MISC;      // SEI.
896
897     ctx->surface_width  = FFALIGN(avctx->width,  16);
898     ctx->surface_height = FFALIGN(avctx->height, 16);
899
900     return ff_vaapi_encode_init(avctx);
901 }
902
903 static av_cold int vaapi_encode_h264_close(AVCodecContext *avctx)
904 {
905     VAAPIEncodeContext *ctx = avctx->priv_data;
906     VAAPIEncodeH264Context *priv = ctx->priv_data;
907
908     if (priv) {
909         ff_cbs_close(&priv->cbc);
910         av_freep(&priv->identifier_string);
911     }
912
913     return ff_vaapi_encode_close(avctx);
914 }
915
916 #define OFFSET(x) (offsetof(VAAPIEncodeContext, codec_options_data) + \
917                    offsetof(VAAPIEncodeH264Options, x))
918 #define FLAGS (AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM)
919 static const AVOption vaapi_encode_h264_options[] = {
920     { "qp", "Constant QP (for P-frames; scaled by qfactor/qoffset for I/B)",
921       OFFSET(qp), AV_OPT_TYPE_INT, { .i64 = 20 }, 0, 52, FLAGS },
922     { "quality", "Set encode quality (trades off against speed, higher is faster)",
923       OFFSET(quality), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 8, FLAGS },
924     { "low_power", "Use low-power encoding mode (experimental: only supported "
925       "on some platforms, does not support all features)",
926       OFFSET(low_power), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, FLAGS },
927     { "coder", "Entropy coder type",
928       OFFSET(coder), AV_OPT_TYPE_INT, { .i64 = 1 }, 0, 1, FLAGS, "coder" },
929         { "cavlc", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = 0 }, INT_MIN, INT_MAX, FLAGS, "coder" },
930         { "cabac", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = 1 }, INT_MIN, INT_MAX, FLAGS, "coder" },
931         { "vlc",   NULL, 0, AV_OPT_TYPE_CONST, { .i64 = 0 }, INT_MIN, INT_MAX, FLAGS, "coder" },
932         { "ac",    NULL, 0, AV_OPT_TYPE_CONST, { .i64 = 1 }, INT_MIN, INT_MAX, FLAGS, "coder" },
933
934     { "sei", "Set SEI to include",
935       OFFSET(sei), AV_OPT_TYPE_FLAGS,
936       { .i64 = SEI_IDENTIFIER | SEI_TIMING },
937       0, INT_MAX, FLAGS, "sei" },
938     { "identifier", "Include encoder version identifier",
939       0, AV_OPT_TYPE_CONST, { .i64 = SEI_IDENTIFIER },
940       INT_MIN, INT_MAX, FLAGS, "sei" },
941     { "timing", "Include timing parameters (buffering_period and pic_timing)",
942       0, AV_OPT_TYPE_CONST, { .i64 = SEI_TIMING },
943       INT_MIN, INT_MAX, FLAGS, "sei" },
944     { NULL },
945 };
946
947 static const AVCodecDefault vaapi_encode_h264_defaults[] = {
948     { "profile",        "100" },
949     { "level",          "51"  },
950     { "b",              "0"   },
951     { "bf",             "2"   },
952     { "g",              "120" },
953     { "i_qfactor",      "1"   },
954     { "i_qoffset",      "0"   },
955     { "b_qfactor",      "6/5" },
956     { "b_qoffset",      "0"   },
957     { "qmin",           "0"   },
958     { NULL },
959 };
960
961 static const AVClass vaapi_encode_h264_class = {
962     .class_name = "h264_vaapi",
963     .item_name  = av_default_item_name,
964     .option     = vaapi_encode_h264_options,
965     .version    = LIBAVUTIL_VERSION_INT,
966 };
967
968 AVCodec ff_h264_vaapi_encoder = {
969     .name           = "h264_vaapi",
970     .long_name      = NULL_IF_CONFIG_SMALL("H.264/AVC (VAAPI)"),
971     .type           = AVMEDIA_TYPE_VIDEO,
972     .id             = AV_CODEC_ID_H264,
973     .priv_data_size = (sizeof(VAAPIEncodeContext) +
974                        sizeof(VAAPIEncodeH264Options)),
975     .init           = &vaapi_encode_h264_init,
976     .encode2        = &ff_vaapi_encode2,
977     .close          = &vaapi_encode_h264_close,
978     .priv_class     = &vaapi_encode_h264_class,
979     .capabilities   = AV_CODEC_CAP_DELAY,
980     .defaults       = vaapi_encode_h264_defaults,
981     .pix_fmts = (const enum AVPixelFormat[]) {
982         AV_PIX_FMT_VAAPI,
983         AV_PIX_FMT_NONE,
984     },
985 };