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