]> git.sesse.net Git - ffmpeg/blob - libavcodec/vaapi_encode_h265.c
Merge commit '4de220d2e3751c459f8739a08ac6ca52e63eba30'
[ffmpeg] / libavcodec / vaapi_encode_h265.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 <va/va.h>
20 #include <va/va_enc_hevc.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 "hevc.h"
29 #include "internal.h"
30 #include "put_bits.h"
31 #include "vaapi_encode.h"
32 #include "vaapi_encode_h26x.h"
33
34
35 #define MAX_ST_REF_PIC_SETS  32
36 #define MAX_DPB_PICS         16
37 #define MAX_LAYERS            1
38
39
40 typedef struct VAAPIEncodeH265STRPS {
41     char inter_ref_pic_set_prediction_flag;
42
43     unsigned int num_negative_pics;
44     unsigned int num_positive_pics;
45
46     unsigned int delta_poc_s0_minus1[MAX_DPB_PICS];
47     char used_by_curr_pic_s0_flag[MAX_DPB_PICS];
48
49     unsigned int delta_poc_s1_minus1[MAX_DPB_PICS];
50     char used_by_curr_pic_s1_flag[MAX_DPB_PICS];
51 } VAAPIEncodeH265STRPS;
52
53 // This structure contains all possibly-useful per-sequence syntax elements
54 // which are not already contained in the various VAAPI structures.
55 typedef struct VAAPIEncodeH265MiscSequenceParams {
56
57     // Parameter set IDs.
58     unsigned int video_parameter_set_id;
59     unsigned int seq_parameter_set_id;
60
61     // Layering.
62     unsigned int vps_max_layers_minus1;
63     unsigned int vps_max_sub_layers_minus1;
64     char vps_temporal_id_nesting_flag;
65     unsigned int vps_max_layer_id;
66     unsigned int vps_num_layer_sets_minus1;
67     unsigned int sps_max_sub_layers_minus1;
68     char sps_temporal_id_nesting_flag;
69     char layer_id_included_flag[MAX_LAYERS][64];
70
71     // Profile/tier/level parameters.
72     char general_profile_compatibility_flag[32];
73     char general_progressive_source_flag;
74     char general_interlaced_source_flag;
75     char general_non_packed_constraint_flag;
76     char general_frame_only_constraint_flag;
77     char general_inbld_flag;
78
79     // Decode/display ordering parameters.
80     unsigned int log2_max_pic_order_cnt_lsb_minus4;
81     char vps_sub_layer_ordering_info_present_flag;
82     unsigned int vps_max_dec_pic_buffering_minus1[MAX_LAYERS];
83     unsigned int vps_max_num_reorder_pics[MAX_LAYERS];
84     unsigned int vps_max_latency_increase_plus1[MAX_LAYERS];
85     char sps_sub_layer_ordering_info_present_flag;
86     unsigned int sps_max_dec_pic_buffering_minus1[MAX_LAYERS];
87     unsigned int sps_max_num_reorder_pics[MAX_LAYERS];
88     unsigned int sps_max_latency_increase_plus1[MAX_LAYERS];
89
90     // Timing information.
91     char vps_timing_info_present_flag;
92     unsigned int vps_num_units_in_tick;
93     unsigned int vps_time_scale;
94     char vps_poc_proportional_to_timing_flag;
95     unsigned int vps_num_ticks_poc_diff_minus1;
96
97     // Cropping information.
98     char conformance_window_flag;
99     unsigned int conf_win_left_offset;
100     unsigned int conf_win_right_offset;
101     unsigned int conf_win_top_offset;
102     unsigned int conf_win_bottom_offset;
103
104     // Short-term reference picture sets.
105     unsigned int num_short_term_ref_pic_sets;
106     VAAPIEncodeH265STRPS st_ref_pic_set[MAX_ST_REF_PIC_SETS];
107
108     // Long-term reference pictures.
109     char long_term_ref_pics_present_flag;
110     unsigned int num_long_term_ref_pics_sps;
111     struct {
112         unsigned int lt_ref_pic_poc_lsb_sps;
113         char used_by_curr_pic_lt_sps_flag;
114     } lt_ref_pic;
115
116     // Deblocking filter control.
117     char deblocking_filter_control_present_flag;
118     char deblocking_filter_override_enabled_flag;
119     char pps_deblocking_filter_disabled_flag;
120     int pps_beta_offset_div2;
121     int pps_tc_offset_div2;
122
123     // Video Usability Information.
124     char vui_parameters_present_flag;
125     char aspect_ratio_info_present_flag;
126     unsigned int aspect_ratio_idc;
127     unsigned int sar_width;
128     unsigned int sar_height;
129     char video_signal_type_present_flag;
130     unsigned int video_format;
131     char video_full_range_flag;
132     char colour_description_present_flag;
133     unsigned int colour_primaries;
134     unsigned int transfer_characteristics;
135     unsigned int matrix_coeffs;
136
137     // Oddments.
138     char uniform_spacing_flag;
139     char output_flag_present_flag;
140     char cabac_init_present_flag;
141     unsigned int num_extra_slice_header_bits;
142     char lists_modification_present_flag;
143     char pps_slice_chroma_qp_offsets_present_flag;
144     char pps_slice_chroma_offset_list_enabled_flag;
145 } VAAPIEncodeH265MiscSequenceParams;
146
147 // This structure contains all possibly-useful per-slice syntax elements
148 // which are not already contained in the various VAAPI structures.
149 typedef struct VAAPIEncodeH265MiscSliceParams {
150     // Slice segments.
151     char first_slice_segment_in_pic_flag;
152
153     // Short-term reference picture sets.
154     char short_term_ref_pic_set_sps_flag;
155     unsigned int short_term_ref_pic_idx;
156     VAAPIEncodeH265STRPS st_ref_pic_set;
157
158     // Deblocking filter.
159     char deblocking_filter_override_flag;
160
161     // Oddments.
162     char slice_reserved_flag[8];
163     char no_output_of_prior_pics_flag;
164     char pic_output_flag;
165 } VAAPIEncodeH265MiscSliceParams;
166
167 typedef struct VAAPIEncodeH265Slice {
168     VAAPIEncodeH265MiscSliceParams misc_slice_params;
169
170     int64_t pic_order_cnt;
171 } VAAPIEncodeH265Slice;
172
173 typedef struct VAAPIEncodeH265Context {
174     VAAPIEncodeH265MiscSequenceParams misc_sequence_params;
175
176     unsigned int ctu_width;
177     unsigned int ctu_height;
178
179     int fixed_qp_idr;
180     int fixed_qp_p;
181     int fixed_qp_b;
182
183     int64_t last_idr_frame;
184
185     // Rate control configuration.
186     struct {
187         VAEncMiscParameterBuffer misc;
188         VAEncMiscParameterRateControl rc;
189     } rc_params;
190     struct {
191         VAEncMiscParameterBuffer misc;
192         VAEncMiscParameterHRD hrd;
193     } hrd_params;
194 } VAAPIEncodeH265Context;
195
196 typedef struct VAAPIEncodeH265Options {
197     int qp;
198 } VAAPIEncodeH265Options;
199
200
201 #define vseq_var(name)     vseq->name, name
202 #define vseq_field(name)   vseq->seq_fields.bits.name, name
203 #define vpic_var(name)     vpic->name, name
204 #define vpic_field(name)   vpic->pic_fields.bits.name, name
205 #define vslice_var(name)   vslice->name, name
206 #define vslice_field(name) vslice->slice_fields.bits.name, name
207 #define mseq_var(name)     mseq->name, name
208 #define mslice_var(name)   mslice->name, name
209 #define mstrps_var(name)   mstrps->name, name
210
211 static void vaapi_encode_h265_write_nal_unit_header(PutBitContext *pbc,
212                                                     int nal_unit_type)
213 {
214     u(1, 0, forbidden_zero_bit);
215     u(6, nal_unit_type, nal_unit_type);
216     u(6, 0, nuh_layer_id);
217     u(3, 1, nuh_temporal_id_plus1);
218 }
219
220 static void vaapi_encode_h265_write_rbsp_trailing_bits(PutBitContext *pbc)
221 {
222     u(1, 1, rbsp_stop_one_bit);
223     while (put_bits_count(pbc) & 7)
224         u(1, 0, rbsp_alignment_zero_bit);
225 }
226
227 static void vaapi_encode_h265_write_profile_tier_level(PutBitContext *pbc,
228                                                        VAAPIEncodeContext *ctx)
229 {
230     VAEncSequenceParameterBufferHEVC  *vseq = ctx->codec_sequence_params;
231     VAAPIEncodeH265Context            *priv = ctx->priv_data;
232     VAAPIEncodeH265MiscSequenceParams *mseq = &priv->misc_sequence_params;
233     int j;
234
235     if (1) {
236         u(2, 0, general_profile_space);
237         u(1, vseq_var(general_tier_flag));
238         u(5, vseq_var(general_profile_idc));
239
240         for (j = 0; j < 32; j++) {
241             u(1, mseq_var(general_profile_compatibility_flag[j]));
242         }
243
244         u(1, mseq_var(general_progressive_source_flag));
245         u(1, mseq_var(general_interlaced_source_flag));
246         u(1, mseq_var(general_non_packed_constraint_flag));
247         u(1, mseq_var(general_frame_only_constraint_flag));
248
249         if (0) {
250             // Not main profile.
251             // Lots of extra constraint flags.
252         } else {
253             // put_bits only handles up to 31 bits.
254             u(23, 0, general_reserved_zero_43bits);
255             u(20, 0, general_reserved_zero_43bits);
256         }
257
258         if (vseq->general_profile_idc >= 1 && vseq->general_profile_idc <= 5) {
259             u(1, mseq_var(general_inbld_flag));
260         } else {
261             u(1, 0, general_reserved_zero_bit);
262         }
263     }
264
265     u(8, vseq_var(general_level_idc));
266
267     // No sublayers.
268 }
269
270 static void vaapi_encode_h265_write_vps(PutBitContext *pbc,
271                                         VAAPIEncodeContext *ctx)
272 {
273     VAAPIEncodeH265Context            *priv = ctx->priv_data;
274     VAAPIEncodeH265MiscSequenceParams *mseq = &priv->misc_sequence_params;
275     int i, j;
276
277     vaapi_encode_h265_write_nal_unit_header(pbc, HEVC_NAL_VPS);
278
279     u(4, mseq->video_parameter_set_id, vps_video_parameter_set_id);
280
281     u(1, 1, vps_base_layer_internal_flag);
282     u(1, 1, vps_base_layer_available_flag);
283     u(6, mseq_var(vps_max_layers_minus1));
284     u(3, mseq_var(vps_max_sub_layers_minus1));
285     u(1, mseq_var(vps_temporal_id_nesting_flag));
286
287     u(16, 0xffff, vps_reserved_0xffff_16bits);
288
289     vaapi_encode_h265_write_profile_tier_level(pbc, ctx);
290
291     u(1, mseq_var(vps_sub_layer_ordering_info_present_flag));
292     for (i = (mseq->vps_sub_layer_ordering_info_present_flag ?
293               0 : mseq->vps_max_sub_layers_minus1);
294          i <= mseq->vps_max_sub_layers_minus1; i++) {
295         ue(mseq_var(vps_max_dec_pic_buffering_minus1[i]));
296         ue(mseq_var(vps_max_num_reorder_pics[i]));
297         ue(mseq_var(vps_max_latency_increase_plus1[i]));
298     }
299
300     u(6, mseq_var(vps_max_layer_id));
301     ue(mseq_var(vps_num_layer_sets_minus1));
302     for (i = 1; i <= mseq->vps_num_layer_sets_minus1; i++) {
303         for (j = 0; j < mseq->vps_max_layer_id; j++)
304             u(1, mseq_var(layer_id_included_flag[i][j]));
305     }
306
307     u(1, mseq_var(vps_timing_info_present_flag));
308     if (mseq->vps_timing_info_present_flag) {
309         u(1, 0, put_bits_hack_zero_bit);
310         u(31, mseq_var(vps_num_units_in_tick));
311         u(1, 0, put_bits_hack_zero_bit);
312         u(31, mseq_var(vps_time_scale));
313         u(1, mseq_var(vps_poc_proportional_to_timing_flag));
314         if (mseq->vps_poc_proportional_to_timing_flag) {
315             ue(mseq_var(vps_num_ticks_poc_diff_minus1));
316         }
317         ue(0, vps_num_hrd_parameters);
318     }
319
320     u(1, 0, vps_extension_flag);
321
322     vaapi_encode_h265_write_rbsp_trailing_bits(pbc);
323 }
324
325 static void vaapi_encode_h265_write_st_ref_pic_set(PutBitContext *pbc,
326                                                    int st_rps_idx,
327                                                    VAAPIEncodeH265STRPS *mstrps)
328 {
329     int i;
330
331     if (st_rps_idx != 0)
332        u(1, mstrps_var(inter_ref_pic_set_prediction_flag));
333
334     if (mstrps->inter_ref_pic_set_prediction_flag) {
335         av_assert0(0 && "inter ref pic set prediction not supported");
336     } else {
337         ue(mstrps_var(num_negative_pics));
338         ue(mstrps_var(num_positive_pics));
339
340         for (i = 0; i < mstrps->num_negative_pics; i++) {
341             ue(mstrps_var(delta_poc_s0_minus1[i]));
342             u(1, mstrps_var(used_by_curr_pic_s0_flag[i]));
343         }
344         for (i = 0; i < mstrps->num_positive_pics; i++) {
345             ue(mstrps_var(delta_poc_s1_minus1[i]));
346             u(1, mstrps_var(used_by_curr_pic_s1_flag[i]));
347         }
348     }
349 }
350
351 static void vaapi_encode_h265_write_vui_parameters(PutBitContext *pbc,
352                                                    VAAPIEncodeContext *ctx)
353 {
354     VAAPIEncodeH265Context            *priv = ctx->priv_data;
355     VAAPIEncodeH265MiscSequenceParams *mseq = &priv->misc_sequence_params;
356
357     u(1, mseq_var(aspect_ratio_info_present_flag));
358     if (mseq->aspect_ratio_info_present_flag) {
359         u(8, mseq_var(aspect_ratio_idc));
360         if (mseq->aspect_ratio_idc == 255) {
361             u(16, mseq_var(sar_width));
362             u(16, mseq_var(sar_height));
363         }
364     }
365
366     u(1, 0, overscan_info_present_flag);
367
368     u(1, mseq_var(video_signal_type_present_flag));
369     if (mseq->video_signal_type_present_flag) {
370         u(3, mseq_var(video_format));
371         u(1, mseq_var(video_full_range_flag));
372         u(1, mseq_var(colour_description_present_flag));
373         if (mseq->colour_description_present_flag) {
374             u(8, mseq_var(colour_primaries));
375             u(8, mseq_var(transfer_characteristics));
376             u(8, mseq_var(matrix_coeffs));
377         }
378     }
379
380     u(1, 0, chroma_loc_info_present_flag);
381     u(1, 0, neutral_chroma_indication_flag);
382     u(1, 0, field_seq_flag);
383     u(1, 0, frame_field_info_present_flag);
384     u(1, 0, default_display_window_flag);
385     u(1, 0, vui_timing_info_present_flag);
386     u(1, 0, bitstream_restriction_flag_flag);
387 }
388
389 static void vaapi_encode_h265_write_sps(PutBitContext *pbc,
390                                         VAAPIEncodeContext *ctx)
391 {
392     VAEncSequenceParameterBufferHEVC  *vseq = ctx->codec_sequence_params;
393     VAAPIEncodeH265Context            *priv = ctx->priv_data;
394     VAAPIEncodeH265MiscSequenceParams *mseq = &priv->misc_sequence_params;
395     int i;
396
397     vaapi_encode_h265_write_nal_unit_header(pbc, HEVC_NAL_SPS);
398
399     u(4, mseq->video_parameter_set_id, sps_video_parameter_set_id);
400
401     u(3, mseq_var(sps_max_sub_layers_minus1));
402     u(1, mseq_var(sps_temporal_id_nesting_flag));
403
404     vaapi_encode_h265_write_profile_tier_level(pbc, ctx);
405
406     ue(mseq->seq_parameter_set_id, sps_seq_parameter_set_id);
407     ue(vseq_field(chroma_format_idc));
408     if (vseq->seq_fields.bits.chroma_format_idc == 3)
409         u(1, 0, separate_colour_plane_flag);
410
411     ue(vseq_var(pic_width_in_luma_samples));
412     ue(vseq_var(pic_height_in_luma_samples));
413
414     u(1, mseq_var(conformance_window_flag));
415     if (mseq->conformance_window_flag) {
416         ue(mseq_var(conf_win_left_offset));
417         ue(mseq_var(conf_win_right_offset));
418         ue(mseq_var(conf_win_top_offset));
419         ue(mseq_var(conf_win_bottom_offset));
420     }
421
422     ue(vseq_field(bit_depth_luma_minus8));
423     ue(vseq_field(bit_depth_chroma_minus8));
424
425     ue(mseq_var(log2_max_pic_order_cnt_lsb_minus4));
426
427     u(1, mseq_var(sps_sub_layer_ordering_info_present_flag));
428     for (i = (mseq->sps_sub_layer_ordering_info_present_flag ?
429               0 : mseq->sps_max_sub_layers_minus1);
430          i <= mseq->sps_max_sub_layers_minus1; i++) {
431         ue(mseq_var(sps_max_dec_pic_buffering_minus1[i]));
432         ue(mseq_var(sps_max_num_reorder_pics[i]));
433         ue(mseq_var(sps_max_latency_increase_plus1[i]));
434     }
435
436     ue(vseq_var(log2_min_luma_coding_block_size_minus3));
437     ue(vseq_var(log2_diff_max_min_luma_coding_block_size));
438     ue(vseq_var(log2_min_transform_block_size_minus2));
439     ue(vseq_var(log2_diff_max_min_transform_block_size));
440     ue(vseq_var(max_transform_hierarchy_depth_inter));
441     ue(vseq_var(max_transform_hierarchy_depth_intra));
442
443     u(1, vseq_field(scaling_list_enabled_flag));
444     if (vseq->seq_fields.bits.scaling_list_enabled_flag) {
445         u(1, 0, sps_scaling_list_data_present_flag);
446     }
447
448     u(1, vseq_field(amp_enabled_flag));
449     u(1, vseq_field(sample_adaptive_offset_enabled_flag));
450
451     u(1, vseq_field(pcm_enabled_flag));
452     if (vseq->seq_fields.bits.pcm_enabled_flag) {
453         u(4, vseq_var(pcm_sample_bit_depth_luma_minus1));
454         u(4, vseq_var(pcm_sample_bit_depth_chroma_minus1));
455         ue(vseq_var(log2_min_pcm_luma_coding_block_size_minus3));
456         ue(vseq->log2_max_pcm_luma_coding_block_size_minus3 -
457            vseq->log2_min_pcm_luma_coding_block_size_minus3,
458            log2_diff_max_min_pcm_luma_coding_block_size);
459         u(1, vseq_field(pcm_loop_filter_disabled_flag));
460     }
461
462     ue(mseq_var(num_short_term_ref_pic_sets));
463     for (i = 0; i < mseq->num_short_term_ref_pic_sets; i++)
464         vaapi_encode_h265_write_st_ref_pic_set(pbc, i,
465                                                &mseq->st_ref_pic_set[i]);
466
467     u(1, mseq_var(long_term_ref_pics_present_flag));
468     if (mseq->long_term_ref_pics_present_flag) {
469         ue(0, num_long_term_ref_pics_sps);
470     }
471
472     u(1, vseq_field(sps_temporal_mvp_enabled_flag));
473     u(1, vseq_field(strong_intra_smoothing_enabled_flag));
474
475     u(1, mseq_var(vui_parameters_present_flag));
476     if (mseq->vui_parameters_present_flag) {
477         vaapi_encode_h265_write_vui_parameters(pbc, ctx);
478     }
479
480     u(1, 0, sps_extension_present_flag);
481
482     vaapi_encode_h265_write_rbsp_trailing_bits(pbc);
483 }
484
485 static void vaapi_encode_h265_write_pps(PutBitContext *pbc,
486                                         VAAPIEncodeContext *ctx)
487 {
488     VAEncPictureParameterBufferHEVC   *vpic = ctx->codec_picture_params;
489     VAAPIEncodeH265Context            *priv = ctx->priv_data;
490     VAAPIEncodeH265MiscSequenceParams *mseq = &priv->misc_sequence_params;
491     int i;
492
493     vaapi_encode_h265_write_nal_unit_header(pbc, HEVC_NAL_PPS);
494
495     ue(vpic->slice_pic_parameter_set_id, pps_pic_parameter_set_id);
496     ue(mseq->seq_parameter_set_id, pps_seq_parameter_set_id);
497
498     u(1, vpic_field(dependent_slice_segments_enabled_flag));
499     u(1, mseq_var(output_flag_present_flag));
500     u(3, mseq_var(num_extra_slice_header_bits));
501     u(1, vpic_field(sign_data_hiding_enabled_flag));
502     u(1, mseq_var(cabac_init_present_flag));
503
504     ue(vpic_var(num_ref_idx_l0_default_active_minus1));
505     ue(vpic_var(num_ref_idx_l1_default_active_minus1));
506
507     se(vpic->pic_init_qp - 26, init_qp_minus26);
508
509     u(1, vpic_field(constrained_intra_pred_flag));
510     u(1, vpic_field(transform_skip_enabled_flag));
511
512     u(1, vpic_field(cu_qp_delta_enabled_flag));
513     if (vpic->pic_fields.bits.cu_qp_delta_enabled_flag)
514         ue(vpic_var(diff_cu_qp_delta_depth));
515
516     se(vpic_var(pps_cb_qp_offset));
517     se(vpic_var(pps_cr_qp_offset));
518
519     u(1, mseq_var(pps_slice_chroma_qp_offsets_present_flag));
520     u(1, vpic_field(weighted_pred_flag));
521     u(1, vpic_field(weighted_bipred_flag));
522     u(1, vpic_field(transquant_bypass_enabled_flag));
523     u(1, vpic_field(tiles_enabled_flag));
524     u(1, vpic_field(entropy_coding_sync_enabled_flag));
525
526     if (vpic->pic_fields.bits.tiles_enabled_flag) {
527         ue(vpic_var(num_tile_columns_minus1));
528         ue(vpic_var(num_tile_rows_minus1));
529         u(1, mseq_var(uniform_spacing_flag));
530         if (!mseq->uniform_spacing_flag) {
531             for (i = 0; i < vpic->num_tile_columns_minus1; i++)
532                 ue(vpic_var(column_width_minus1[i]));
533             for (i = 0; i < vpic->num_tile_rows_minus1; i++)
534                 ue(vpic_var(row_height_minus1[i]));
535         }
536         u(1, vpic_field(loop_filter_across_tiles_enabled_flag));
537     }
538
539     u(1, vpic_field(pps_loop_filter_across_slices_enabled_flag));
540     u(1, mseq_var(deblocking_filter_control_present_flag));
541     if (mseq->deblocking_filter_control_present_flag) {
542         u(1, mseq_var(deblocking_filter_override_enabled_flag));
543         u(1, mseq_var(pps_deblocking_filter_disabled_flag));
544         if (!mseq->pps_deblocking_filter_disabled_flag) {
545             se(mseq_var(pps_beta_offset_div2));
546             se(mseq_var(pps_tc_offset_div2));
547         }
548     }
549
550     u(1, 0, pps_scaling_list_data_present_flag);
551     // No scaling list data.
552
553     u(1, mseq_var(lists_modification_present_flag));
554     ue(vpic_var(log2_parallel_merge_level_minus2));
555     u(1, 0, slice_segment_header_extension_present_flag);
556     u(1, 0, pps_extension_present_flag);
557
558     vaapi_encode_h265_write_rbsp_trailing_bits(pbc);
559 }
560
561 static void vaapi_encode_h265_write_slice_header2(PutBitContext *pbc,
562                                                   VAAPIEncodeContext *ctx,
563                                                   VAAPIEncodePicture *pic,
564                                                   VAAPIEncodeSlice *slice)
565 {
566     VAEncSequenceParameterBufferHEVC  *vseq = ctx->codec_sequence_params;
567     VAEncPictureParameterBufferHEVC   *vpic = pic->codec_picture_params;
568     VAEncSliceParameterBufferHEVC   *vslice = slice->codec_slice_params;
569     VAAPIEncodeH265Context            *priv = ctx->priv_data;
570     VAAPIEncodeH265MiscSequenceParams *mseq = &priv->misc_sequence_params;
571     VAAPIEncodeH265Slice            *pslice = slice->priv_data;
572     VAAPIEncodeH265MiscSliceParams  *mslice = &pslice->misc_slice_params;
573     int i;
574
575     vaapi_encode_h265_write_nal_unit_header(pbc, vpic->nal_unit_type);
576
577     u(1, mslice_var(first_slice_segment_in_pic_flag));
578     if (vpic->nal_unit_type >= HEVC_NAL_BLA_W_LP &&
579        vpic->nal_unit_type <= 23)
580         u(1, mslice_var(no_output_of_prior_pics_flag));
581
582     ue(vslice_var(slice_pic_parameter_set_id));
583
584     if (!mslice->first_slice_segment_in_pic_flag) {
585         if (vpic->pic_fields.bits.dependent_slice_segments_enabled_flag)
586             u(1, vslice_field(dependent_slice_segment_flag));
587         u(av_log2((priv->ctu_width * priv->ctu_height) - 1) + 1,
588           vslice_var(slice_segment_address));
589     }
590     if (!vslice->slice_fields.bits.dependent_slice_segment_flag) {
591         for (i = 0; i < mseq->num_extra_slice_header_bits; i++)
592             u(1, mslice_var(slice_reserved_flag[i]));
593
594         ue(vslice_var(slice_type));
595         if (mseq->output_flag_present_flag)
596             u(1, 1, pic_output_flag);
597         if (vseq->seq_fields.bits.separate_colour_plane_flag)
598             u(2, vslice_field(colour_plane_id));
599         if (vpic->nal_unit_type != HEVC_NAL_IDR_W_RADL &&
600            vpic->nal_unit_type != HEVC_NAL_IDR_N_LP) {
601             u(4 + mseq->log2_max_pic_order_cnt_lsb_minus4,
602               (pslice->pic_order_cnt &
603                ((1 << (mseq->log2_max_pic_order_cnt_lsb_minus4 + 4)) - 1)),
604               slice_pic_order_cnt_lsb);
605
606             u(1, mslice_var(short_term_ref_pic_set_sps_flag));
607             if (!mslice->short_term_ref_pic_set_sps_flag) {
608                 vaapi_encode_h265_write_st_ref_pic_set(pbc, mseq->num_short_term_ref_pic_sets,
609                                                        &mslice->st_ref_pic_set);
610             } else if (mseq->num_short_term_ref_pic_sets > 1) {
611                 u(av_log2(mseq->num_short_term_ref_pic_sets - 1) + 1,
612                   mslice_var(short_term_ref_pic_idx));
613             }
614
615             if (mseq->long_term_ref_pics_present_flag) {
616                 av_assert0(0);
617             }
618         }
619
620         if (vseq->seq_fields.bits.sps_temporal_mvp_enabled_flag) {
621             u(1, vslice_field(slice_temporal_mvp_enabled_flag));
622         }
623
624         if (vseq->seq_fields.bits.sample_adaptive_offset_enabled_flag) {
625             u(1, vslice_field(slice_sao_luma_flag));
626             if (!vseq->seq_fields.bits.separate_colour_plane_flag &&
627                 vseq->seq_fields.bits.chroma_format_idc != 0) {
628                 u(1, vslice_field(slice_sao_chroma_flag));
629             }
630         }
631
632         if (vslice->slice_type == HEVC_SLICE_P || vslice->slice_type == HEVC_SLICE_B) {
633             u(1, vslice_field(num_ref_idx_active_override_flag));
634             if (vslice->slice_fields.bits.num_ref_idx_active_override_flag) {
635                 ue(vslice_var(num_ref_idx_l0_active_minus1));
636                 if (vslice->slice_type == HEVC_SLICE_B) {
637                     ue(vslice_var(num_ref_idx_l1_active_minus1));
638                 }
639             }
640
641             if (mseq->lists_modification_present_flag) {
642                 av_assert0(0);
643                 // ref_pic_lists_modification()
644             }
645             if (vslice->slice_type == HEVC_SLICE_B) {
646                 u(1, vslice_field(mvd_l1_zero_flag));
647             }
648             if (mseq->cabac_init_present_flag) {
649                 u(1, vslice_field(cabac_init_flag));
650             }
651             if (vslice->slice_fields.bits.slice_temporal_mvp_enabled_flag) {
652                 if (vslice->slice_type == HEVC_SLICE_B)
653                     u(1, vslice_field(collocated_from_l0_flag));
654                 ue(vpic->collocated_ref_pic_index, collocated_ref_idx);
655             }
656             if ((vpic->pic_fields.bits.weighted_pred_flag &&
657                  vslice->slice_type == HEVC_SLICE_P) ||
658                 (vpic->pic_fields.bits.weighted_bipred_flag &&
659                  vslice->slice_type == HEVC_SLICE_B)) {
660                 av_assert0(0);
661                 // pred_weight_table()
662             }
663             ue(5 - vslice->max_num_merge_cand, five_minus_max_num_merge_cand);
664         }
665
666         se(vslice_var(slice_qp_delta));
667         if (mseq->pps_slice_chroma_qp_offsets_present_flag) {
668             se(vslice_var(slice_cb_qp_offset));
669             se(vslice_var(slice_cr_qp_offset));
670         }
671         if (mseq->pps_slice_chroma_offset_list_enabled_flag) {
672             u(1, 0, cu_chroma_qp_offset_enabled_flag);
673         }
674         if (mseq->deblocking_filter_override_enabled_flag) {
675             u(1, mslice_var(deblocking_filter_override_flag));
676         }
677         if (mslice->deblocking_filter_override_flag) {
678             u(1, vslice_field(slice_deblocking_filter_disabled_flag));
679             if (!vslice->slice_fields.bits.slice_deblocking_filter_disabled_flag) {
680                 se(vslice_var(slice_beta_offset_div2));
681                 se(vslice_var(slice_tc_offset_div2));
682             }
683         }
684         if (vpic->pic_fields.bits.pps_loop_filter_across_slices_enabled_flag &&
685             (vslice->slice_fields.bits.slice_sao_luma_flag ||
686              vslice->slice_fields.bits.slice_sao_chroma_flag ||
687              vslice->slice_fields.bits.slice_deblocking_filter_disabled_flag)) {
688             u(1, vslice_field(slice_loop_filter_across_slices_enabled_flag));
689         }
690
691         if (vpic->pic_fields.bits.tiles_enabled_flag ||
692             vpic->pic_fields.bits.entropy_coding_sync_enabled_flag) {
693             // num_entry_point_offsets
694         }
695
696         if (0) {
697             // slice_segment_header_extension_length
698         }
699     }
700
701     u(1, 1, alignment_bit_equal_to_one);
702     while (put_bits_count(pbc) & 7)
703         u(1, 0, alignment_bit_equal_to_zero);
704 }
705
706 static int vaapi_encode_h265_write_sequence_header(AVCodecContext *avctx,
707                                                    char *data, size_t *data_len)
708 {
709     VAAPIEncodeContext *ctx = avctx->priv_data;
710     PutBitContext pbc;
711     char tmp[256];
712     int err;
713     size_t nal_len, bit_len, bit_pos, next_len;
714
715     bit_len = *data_len;
716     bit_pos = 0;
717
718     init_put_bits(&pbc, tmp, sizeof(tmp));
719     vaapi_encode_h265_write_vps(&pbc, ctx);
720     nal_len = put_bits_count(&pbc);
721     flush_put_bits(&pbc);
722
723     next_len = bit_len - bit_pos;
724     err = ff_vaapi_encode_h26x_nal_unit_to_byte_stream(data + bit_pos / 8,
725                                                        &next_len,
726                                                        tmp, nal_len);
727     if (err < 0)
728         return err;
729     bit_pos += next_len;
730
731     init_put_bits(&pbc, tmp, sizeof(tmp));
732     vaapi_encode_h265_write_sps(&pbc, ctx);
733     nal_len = put_bits_count(&pbc);
734     flush_put_bits(&pbc);
735
736     next_len = bit_len - bit_pos;
737     err = ff_vaapi_encode_h26x_nal_unit_to_byte_stream(data + bit_pos / 8,
738                                                        &next_len,
739                                                        tmp, nal_len);
740     if (err < 0)
741         return err;
742     bit_pos += next_len;
743
744     init_put_bits(&pbc, tmp, sizeof(tmp));
745     vaapi_encode_h265_write_pps(&pbc, ctx);
746     nal_len = put_bits_count(&pbc);
747     flush_put_bits(&pbc);
748
749     next_len = bit_len - bit_pos;
750     err = ff_vaapi_encode_h26x_nal_unit_to_byte_stream(data + bit_pos / 8,
751                                                        &next_len,
752                                                        tmp, nal_len);
753     if (err < 0)
754         return err;
755     bit_pos += next_len;
756
757     *data_len = bit_pos;
758     return 0;
759 }
760
761 static int vaapi_encode_h265_write_slice_header(AVCodecContext *avctx,
762                                                 VAAPIEncodePicture *pic,
763                                                 VAAPIEncodeSlice *slice,
764                                                 char *data, size_t *data_len)
765 {
766     VAAPIEncodeContext *ctx = avctx->priv_data;
767     PutBitContext pbc;
768     char tmp[256];
769     size_t header_len;
770
771     init_put_bits(&pbc, tmp, sizeof(tmp));
772     vaapi_encode_h265_write_slice_header2(&pbc, ctx, pic, slice);
773     header_len = put_bits_count(&pbc);
774     flush_put_bits(&pbc);
775
776     return ff_vaapi_encode_h26x_nal_unit_to_byte_stream(data, data_len,
777                                                         tmp, header_len);
778 }
779
780 static int vaapi_encode_h265_init_sequence_params(AVCodecContext *avctx)
781 {
782     VAAPIEncodeContext                 *ctx = avctx->priv_data;
783     VAEncSequenceParameterBufferHEVC  *vseq = ctx->codec_sequence_params;
784     VAEncPictureParameterBufferHEVC   *vpic = ctx->codec_picture_params;
785     VAAPIEncodeH265Context            *priv = ctx->priv_data;
786     VAAPIEncodeH265MiscSequenceParams *mseq = &priv->misc_sequence_params;
787     int i;
788
789     {
790         // general_profile_space == 0.
791         vseq->general_profile_idc = 1; // Main profile (ctx->codec_profile?)
792         vseq->general_tier_flag = 0;
793
794         vseq->general_level_idc = avctx->level * 3;
795
796         vseq->intra_period = 0;
797         vseq->intra_idr_period = 0;
798         vseq->ip_period = 0;
799
800         vseq->pic_width_in_luma_samples  = ctx->surface_width;
801         vseq->pic_height_in_luma_samples = ctx->surface_height;
802
803         vseq->seq_fields.bits.chroma_format_idc = 1; // 4:2:0.
804         vseq->seq_fields.bits.separate_colour_plane_flag = 0;
805         vseq->seq_fields.bits.bit_depth_luma_minus8 =
806             avctx->profile == FF_PROFILE_HEVC_MAIN_10 ? 2 : 0;
807         vseq->seq_fields.bits.bit_depth_chroma_minus8 =
808             avctx->profile == FF_PROFILE_HEVC_MAIN_10 ? 2 : 0;
809         // Other misc flags all zero.
810
811         // These have to come from the capabilities of the encoder.  We have
812         // no way to query it, so just hardcode ones which worked for me...
813         // CTB size from 8x8 to 32x32.
814         vseq->log2_min_luma_coding_block_size_minus3 = 0;
815         vseq->log2_diff_max_min_luma_coding_block_size = 2;
816         // Transform size from 4x4 to 32x32.
817         vseq->log2_min_transform_block_size_minus2 = 0;
818         vseq->log2_diff_max_min_transform_block_size = 3;
819         // Full transform hierarchy allowed (2-5).
820         vseq->max_transform_hierarchy_depth_inter = 3;
821         vseq->max_transform_hierarchy_depth_intra = 3;
822
823         vseq->vui_parameters_present_flag = 0;
824
825         vseq->bits_per_second = avctx->bit_rate;
826         if (avctx->framerate.num > 0 && avctx->framerate.den > 0) {
827             vseq->vui_num_units_in_tick = avctx->framerate.den;
828             vseq->vui_time_scale        = avctx->framerate.num;
829         } else {
830             vseq->vui_num_units_in_tick = avctx->time_base.num;
831             vseq->vui_time_scale        = avctx->time_base.den;
832         }
833
834         vseq->intra_period     = avctx->gop_size;
835         vseq->intra_idr_period = avctx->gop_size;
836         vseq->ip_period        = ctx->b_per_p + 1;
837     }
838
839     {
840         vpic->decoded_curr_pic.picture_id = VA_INVALID_ID;
841         vpic->decoded_curr_pic.flags      = VA_PICTURE_HEVC_INVALID;
842
843         for (i = 0; i < FF_ARRAY_ELEMS(vpic->reference_frames); i++) {
844             vpic->reference_frames[i].picture_id = VA_INVALID_ID;
845             vpic->reference_frames[i].flags      = VA_PICTURE_HEVC_INVALID;
846         }
847
848         vpic->collocated_ref_pic_index = 0xff;
849
850         vpic->last_picture = 0;
851
852         vpic->pic_init_qp = priv->fixed_qp_idr;
853
854         vpic->diff_cu_qp_delta_depth = 0;
855         vpic->pps_cb_qp_offset = 0;
856         vpic->pps_cr_qp_offset = 0;
857
858         // tiles_enabled_flag == 0, so ignore num_tile_(rows|columns)_minus1.
859
860         vpic->log2_parallel_merge_level_minus2 = 0;
861
862         // No limit on size.
863         vpic->ctu_max_bitsize_allowed = 0;
864
865         vpic->num_ref_idx_l0_default_active_minus1 = 0;
866         vpic->num_ref_idx_l1_default_active_minus1 = 0;
867
868         vpic->slice_pic_parameter_set_id = 0;
869
870         vpic->pic_fields.bits.screen_content_flag = 0;
871         vpic->pic_fields.bits.enable_gpu_weighted_prediction = 0;
872
873         // Per-CU QP changes are required for non-constant-QP modes.
874         vpic->pic_fields.bits.cu_qp_delta_enabled_flag =
875             ctx->va_rc_mode != VA_RC_CQP;
876     }
877
878     {
879         mseq->video_parameter_set_id = 5;
880         mseq->seq_parameter_set_id = 5;
881
882         mseq->vps_max_layers_minus1 = 0;
883         mseq->vps_max_sub_layers_minus1 = 0;
884         mseq->vps_temporal_id_nesting_flag = 1;
885         mseq->sps_max_sub_layers_minus1 = 0;
886         mseq->sps_temporal_id_nesting_flag = 1;
887
888         for (i = 0; i < 32; i++) {
889             mseq->general_profile_compatibility_flag[i] =
890                 (i == vseq->general_profile_idc);
891         }
892
893         mseq->general_progressive_source_flag    = 1;
894         mseq->general_interlaced_source_flag     = 0;
895         mseq->general_non_packed_constraint_flag = 0;
896         mseq->general_frame_only_constraint_flag = 1;
897         mseq->general_inbld_flag = 0;
898
899         mseq->log2_max_pic_order_cnt_lsb_minus4 = 8;
900         mseq->vps_sub_layer_ordering_info_present_flag = 0;
901         mseq->vps_max_dec_pic_buffering_minus1[0] = (avctx->max_b_frames > 0) + 1;
902         mseq->vps_max_num_reorder_pics[0]         = (avctx->max_b_frames > 0);
903         mseq->vps_max_latency_increase_plus1[0]   = 0;
904         mseq->sps_sub_layer_ordering_info_present_flag = 0;
905         mseq->sps_max_dec_pic_buffering_minus1[0] = (avctx->max_b_frames > 0) + 1;
906         mseq->sps_max_num_reorder_pics[0]         = (avctx->max_b_frames > 0);
907         mseq->sps_max_latency_increase_plus1[0]   = 0;
908
909         mseq->vps_timing_info_present_flag = 1;
910         mseq->vps_num_units_in_tick = avctx->time_base.num;
911         mseq->vps_time_scale        = avctx->time_base.den;
912         mseq->vps_poc_proportional_to_timing_flag = 1;
913         mseq->vps_num_ticks_poc_diff_minus1 = 0;
914
915         if (avctx->width  != ctx->surface_width ||
916             avctx->height != ctx->surface_height) {
917             mseq->conformance_window_flag = 1;
918             mseq->conf_win_left_offset   = 0;
919             mseq->conf_win_right_offset  =
920                 (ctx->surface_width - avctx->width) / 2;
921             mseq->conf_win_top_offset    = 0;
922             mseq->conf_win_bottom_offset =
923                 (ctx->surface_height - avctx->height) / 2;
924         } else {
925             mseq->conformance_window_flag = 0;
926         }
927
928         mseq->num_short_term_ref_pic_sets = 0;
929         // STRPSs should ideally be here rather than repeated in each slice.
930
931         mseq->vui_parameters_present_flag = 1;
932         if (avctx->sample_aspect_ratio.num != 0) {
933             mseq->aspect_ratio_info_present_flag = 1;
934             if (avctx->sample_aspect_ratio.num ==
935                 avctx->sample_aspect_ratio.den) {
936                 mseq->aspect_ratio_idc = 1;
937             } else {
938                 mseq->aspect_ratio_idc = 255; // Extended SAR.
939                 mseq->sar_width  = avctx->sample_aspect_ratio.num;
940                 mseq->sar_height = avctx->sample_aspect_ratio.den;
941             }
942         }
943         if (1) {
944             // Should this be conditional on some of these being set?
945             mseq->video_signal_type_present_flag = 1;
946             mseq->video_format = 5; // Unspecified.
947             mseq->video_full_range_flag = 0;
948             mseq->colour_description_present_flag = 1;
949             mseq->colour_primaries = avctx->color_primaries;
950             mseq->transfer_characteristics = avctx->color_trc;
951             mseq->matrix_coeffs = avctx->colorspace;
952         }
953     }
954
955     return 0;
956 }
957
958 static int vaapi_encode_h265_init_picture_params(AVCodecContext *avctx,
959                                                  VAAPIEncodePicture *pic)
960 {
961     VAAPIEncodeContext               *ctx = avctx->priv_data;
962     VAEncPictureParameterBufferHEVC *vpic = pic->codec_picture_params;
963     VAAPIEncodeH265Context          *priv = ctx->priv_data;
964     int i;
965
966     if (pic->type == PICTURE_TYPE_IDR) {
967         av_assert0(pic->display_order == pic->encode_order);
968         priv->last_idr_frame = pic->display_order;
969     } else {
970         av_assert0(pic->encode_order > priv->last_idr_frame);
971         // Display order need not be if we have RA[SD]L pictures, though.
972     }
973
974     vpic->decoded_curr_pic.picture_id    = pic->recon_surface;
975     vpic->decoded_curr_pic.pic_order_cnt =
976         pic->display_order - priv->last_idr_frame;
977     vpic->decoded_curr_pic.flags         = 0;
978
979     for (i = 0; i < pic->nb_refs; i++) {
980         VAAPIEncodePicture *ref = pic->refs[i];
981         av_assert0(ref);
982         vpic->reference_frames[i].picture_id    = ref->recon_surface;
983         vpic->reference_frames[i].pic_order_cnt =
984             ref->display_order - priv->last_idr_frame;
985         vpic->reference_frames[i].flags =
986             (ref->display_order < pic->display_order ?
987              VA_PICTURE_HEVC_RPS_ST_CURR_BEFORE : 0) |
988             (ref->display_order > pic->display_order ?
989              VA_PICTURE_HEVC_RPS_ST_CURR_AFTER  : 0);
990     }
991     for (; i < FF_ARRAY_ELEMS(vpic->reference_frames); i++) {
992         vpic->reference_frames[i].picture_id = VA_INVALID_ID;
993         vpic->reference_frames[i].flags      = VA_PICTURE_HEVC_INVALID;
994     }
995
996     vpic->coded_buf = pic->output_buffer;
997
998     switch (pic->type) {
999     case PICTURE_TYPE_IDR:
1000         vpic->nal_unit_type = HEVC_NAL_IDR_W_RADL;
1001         vpic->pic_fields.bits.idr_pic_flag = 1;
1002         vpic->pic_fields.bits.coding_type  = 1;
1003         vpic->pic_fields.bits.reference_pic_flag = 1;
1004         break;
1005     case PICTURE_TYPE_I:
1006         vpic->nal_unit_type = HEVC_NAL_TRAIL_R;
1007         vpic->pic_fields.bits.idr_pic_flag = 0;
1008         vpic->pic_fields.bits.coding_type  = 1;
1009         vpic->pic_fields.bits.reference_pic_flag = 1;
1010         break;
1011     case PICTURE_TYPE_P:
1012         vpic->nal_unit_type = HEVC_NAL_TRAIL_R;
1013         vpic->pic_fields.bits.idr_pic_flag = 0;
1014         vpic->pic_fields.bits.coding_type  = 2;
1015         vpic->pic_fields.bits.reference_pic_flag = 1;
1016         break;
1017     case PICTURE_TYPE_B:
1018         vpic->nal_unit_type = HEVC_NAL_TRAIL_R;
1019         vpic->pic_fields.bits.idr_pic_flag = 0;
1020         vpic->pic_fields.bits.coding_type  = 3;
1021         vpic->pic_fields.bits.reference_pic_flag = 0;
1022         break;
1023     default:
1024         av_assert0(0 && "invalid picture type");
1025     }
1026
1027     pic->nb_slices = 1;
1028
1029     return 0;
1030 }
1031
1032 static int vaapi_encode_h265_init_slice_params(AVCodecContext *avctx,
1033                                                VAAPIEncodePicture *pic,
1034                                                VAAPIEncodeSlice *slice)
1035 {
1036     VAAPIEncodeContext                *ctx = avctx->priv_data;
1037     VAEncPictureParameterBufferHEVC  *vpic = pic->codec_picture_params;
1038     VAEncSliceParameterBufferHEVC  *vslice = slice->codec_slice_params;
1039     VAAPIEncodeH265Context           *priv = ctx->priv_data;
1040     VAAPIEncodeH265Slice           *pslice;
1041     VAAPIEncodeH265MiscSliceParams *mslice;
1042     int i;
1043
1044     slice->priv_data = av_mallocz(sizeof(*pslice));
1045     if (!slice->priv_data)
1046         return AVERROR(ENOMEM);
1047     pslice = slice->priv_data;
1048     mslice = &pslice->misc_slice_params;
1049
1050     // Currently we only support one slice per frame.
1051     vslice->slice_segment_address = 0;
1052     vslice->num_ctu_in_slice = priv->ctu_width * priv->ctu_height;
1053
1054     switch (pic->type) {
1055     case PICTURE_TYPE_IDR:
1056     case PICTURE_TYPE_I:
1057         vslice->slice_type = HEVC_SLICE_I;
1058         break;
1059     case PICTURE_TYPE_P:
1060         vslice->slice_type = HEVC_SLICE_P;
1061         break;
1062     case PICTURE_TYPE_B:
1063         vslice->slice_type = HEVC_SLICE_B;
1064         break;
1065     default:
1066         av_assert0(0 && "invalid picture type");
1067     }
1068
1069     vslice->slice_pic_parameter_set_id = vpic->slice_pic_parameter_set_id;
1070
1071     pslice->pic_order_cnt = pic->display_order - priv->last_idr_frame;
1072
1073     for (i = 0; i < FF_ARRAY_ELEMS(vslice->ref_pic_list0); i++) {
1074         vslice->ref_pic_list0[i].picture_id = VA_INVALID_ID;
1075         vslice->ref_pic_list0[i].flags      = VA_PICTURE_HEVC_INVALID;
1076         vslice->ref_pic_list1[i].picture_id = VA_INVALID_ID;
1077         vslice->ref_pic_list1[i].flags      = VA_PICTURE_HEVC_INVALID;
1078     }
1079
1080     av_assert0(pic->nb_refs <= 2);
1081     if (pic->nb_refs >= 1) {
1082         // Backward reference for P- or B-frame.
1083         av_assert0(pic->type == PICTURE_TYPE_P ||
1084                    pic->type == PICTURE_TYPE_B);
1085
1086         vslice->num_ref_idx_l0_active_minus1 = 0;
1087         vslice->ref_pic_list0[0] = vpic->reference_frames[0];
1088     }
1089     if (pic->nb_refs >= 2) {
1090         // Forward reference for B-frame.
1091         av_assert0(pic->type == PICTURE_TYPE_B);
1092
1093         vslice->num_ref_idx_l1_active_minus1 = 0;
1094         vslice->ref_pic_list1[0] = vpic->reference_frames[1];
1095     }
1096
1097     vslice->max_num_merge_cand = 5;
1098
1099     if (pic->type == PICTURE_TYPE_B)
1100         vslice->slice_qp_delta = priv->fixed_qp_b  - vpic->pic_init_qp;
1101     else if (pic->type == PICTURE_TYPE_P)
1102         vslice->slice_qp_delta = priv->fixed_qp_p - vpic->pic_init_qp;
1103     else
1104         vslice->slice_qp_delta = priv->fixed_qp_idr - vpic->pic_init_qp;
1105
1106     vslice->slice_fields.bits.last_slice_of_pic_flag = 1;
1107
1108     mslice->first_slice_segment_in_pic_flag = 1;
1109
1110     if (pic->type == PICTURE_TYPE_IDR) {
1111         // No reference pictures.
1112     } else if (0) {
1113         mslice->short_term_ref_pic_set_sps_flag = 1;
1114         mslice->short_term_ref_pic_idx = 0;
1115     } else {
1116         VAAPIEncodePicture *st;
1117         int used;
1118
1119         mslice->short_term_ref_pic_set_sps_flag = 0;
1120         mslice->st_ref_pic_set.inter_ref_pic_set_prediction_flag = 0;
1121
1122         for (st = ctx->pic_start; st; st = st->next) {
1123             if (st->encode_order >= pic->encode_order) {
1124                 // Not yet in DPB.
1125                 continue;
1126             }
1127             used = 0;
1128             for (i = 0; i < pic->nb_refs; i++) {
1129                 if (pic->refs[i] == st)
1130                     used = 1;
1131             }
1132             if (!used) {
1133                 // Currently true, but need not be.
1134                 continue;
1135             }
1136             // This only works for one instance of each (delta_poc_sN_minus1
1137             // is relative to the previous frame in the list, not relative to
1138             // the current frame directly).
1139             if (st->display_order < pic->display_order) {
1140                 i = mslice->st_ref_pic_set.num_negative_pics;
1141                 mslice->st_ref_pic_set.delta_poc_s0_minus1[i] =
1142                     pic->display_order - st->display_order - 1;
1143                 mslice->st_ref_pic_set.used_by_curr_pic_s0_flag[i] = used;
1144                 ++mslice->st_ref_pic_set.num_negative_pics;
1145             } else {
1146                 i = mslice->st_ref_pic_set.num_positive_pics;
1147                 mslice->st_ref_pic_set.delta_poc_s1_minus1[i] =
1148                     st->display_order - pic->display_order - 1;
1149                 mslice->st_ref_pic_set.used_by_curr_pic_s1_flag[i] = used;
1150                 ++mslice->st_ref_pic_set.num_positive_pics;
1151             }
1152         }
1153     }
1154
1155     return 0;
1156 }
1157
1158 static av_cold int vaapi_encode_h265_configure(AVCodecContext *avctx)
1159 {
1160     VAAPIEncodeContext      *ctx = avctx->priv_data;
1161     VAAPIEncodeH265Context *priv = ctx->priv_data;
1162     VAAPIEncodeH265Options  *opt = ctx->codec_options;
1163
1164     priv->ctu_width     = FFALIGN(ctx->surface_width,  32) / 32;
1165     priv->ctu_height    = FFALIGN(ctx->surface_height, 32) / 32;
1166
1167     av_log(avctx, AV_LOG_VERBOSE, "Input %ux%u -> Surface %ux%u -> CTU %ux%u.\n",
1168            avctx->width, avctx->height, ctx->surface_width,
1169            ctx->surface_height, priv->ctu_width, priv->ctu_height);
1170
1171     if (ctx->va_rc_mode == VA_RC_CQP) {
1172         priv->fixed_qp_p = opt->qp;
1173         if (avctx->i_quant_factor > 0.0)
1174             priv->fixed_qp_idr = (int)((priv->fixed_qp_p * avctx->i_quant_factor +
1175                                         avctx->i_quant_offset) + 0.5);
1176         else
1177             priv->fixed_qp_idr = priv->fixed_qp_p;
1178         if (avctx->b_quant_factor > 0.0)
1179             priv->fixed_qp_b = (int)((priv->fixed_qp_p * avctx->b_quant_factor +
1180                                       avctx->b_quant_offset) + 0.5);
1181         else
1182             priv->fixed_qp_b = priv->fixed_qp_p;
1183
1184         av_log(avctx, AV_LOG_DEBUG, "Using fixed QP = "
1185                "%d / %d / %d for IDR- / P- / B-frames.\n",
1186                priv->fixed_qp_idr, priv->fixed_qp_p, priv->fixed_qp_b);
1187
1188     } else if (ctx->va_rc_mode == VA_RC_CBR ||
1189                ctx->va_rc_mode == VA_RC_VBR) {
1190         // These still need to be  set for pic_init_qp/slice_qp_delta.
1191         priv->fixed_qp_idr = 30;
1192         priv->fixed_qp_p   = 30;
1193         priv->fixed_qp_b   = 30;
1194
1195         av_log(avctx, AV_LOG_DEBUG, "Using %s-bitrate = %"PRId64" bps.\n",
1196                ctx->va_rc_mode == VA_RC_CBR ? "constant" : "variable",
1197                avctx->bit_rate);
1198
1199     } else {
1200         av_assert0(0 && "Invalid RC mode.");
1201     }
1202
1203     return 0;
1204 }
1205
1206 static const VAAPIEncodeType vaapi_encode_type_h265 = {
1207     .priv_data_size        = sizeof(VAAPIEncodeH265Context),
1208
1209     .configure             = &vaapi_encode_h265_configure,
1210
1211     .sequence_params_size  = sizeof(VAEncSequenceParameterBufferHEVC),
1212     .init_sequence_params  = &vaapi_encode_h265_init_sequence_params,
1213
1214     .picture_params_size   = sizeof(VAEncPictureParameterBufferHEVC),
1215     .init_picture_params   = &vaapi_encode_h265_init_picture_params,
1216
1217     .slice_params_size     = sizeof(VAEncSliceParameterBufferHEVC),
1218     .init_slice_params     = &vaapi_encode_h265_init_slice_params,
1219
1220     .sequence_header_type  = VAEncPackedHeaderSequence,
1221     .write_sequence_header = &vaapi_encode_h265_write_sequence_header,
1222
1223     .slice_header_type     = VAEncPackedHeaderHEVC_Slice,
1224     .write_slice_header    = &vaapi_encode_h265_write_slice_header,
1225 };
1226
1227 static av_cold int vaapi_encode_h265_init(AVCodecContext *avctx)
1228 {
1229     VAAPIEncodeContext *ctx = avctx->priv_data;
1230
1231     ctx->codec = &vaapi_encode_type_h265;
1232
1233     switch (avctx->profile) {
1234     case FF_PROFILE_HEVC_MAIN:
1235     case FF_PROFILE_UNKNOWN:
1236         ctx->va_profile = VAProfileHEVCMain;
1237         ctx->va_rt_format = VA_RT_FORMAT_YUV420;
1238         break;
1239     case FF_PROFILE_HEVC_MAIN_10:
1240 #ifdef VA_RT_FORMAT_YUV420_10BPP
1241         ctx->va_profile = VAProfileHEVCMain10;
1242         ctx->va_rt_format = VA_RT_FORMAT_YUV420_10BPP;
1243         break;
1244 #else
1245         av_log(avctx, AV_LOG_ERROR, "10-bit encoding is not "
1246                "supported with this VAAPI version.\n");
1247         return AVERROR(ENOSYS);
1248 #endif
1249     default:
1250         av_log(avctx, AV_LOG_ERROR, "Unknown H.265 profile %d.\n",
1251                avctx->profile);
1252         return AVERROR(EINVAL);
1253     }
1254     ctx->va_entrypoint = VAEntrypointEncSlice;
1255
1256     if (avctx->bit_rate > 0) {
1257         if (avctx->rc_max_rate == avctx->bit_rate)
1258             ctx->va_rc_mode = VA_RC_CBR;
1259         else
1260             ctx->va_rc_mode = VA_RC_VBR;
1261     } else
1262         ctx->va_rc_mode = VA_RC_CQP;
1263
1264     ctx->va_packed_headers =
1265         VA_ENC_PACKED_HEADER_SEQUENCE | // VPS, SPS and PPS.
1266         VA_ENC_PACKED_HEADER_SLICE;     // Slice headers.
1267
1268     ctx->surface_width  = FFALIGN(avctx->width,  16);
1269     ctx->surface_height = FFALIGN(avctx->height, 16);
1270
1271     return ff_vaapi_encode_init(avctx);
1272 }
1273
1274 #define OFFSET(x) (offsetof(VAAPIEncodeContext, codec_options_data) + \
1275                    offsetof(VAAPIEncodeH265Options, x))
1276 #define FLAGS (AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM)
1277 static const AVOption vaapi_encode_h265_options[] = {
1278     { "qp", "Constant QP (for P-frames; scaled by qfactor/qoffset for I/B)",
1279       OFFSET(qp), AV_OPT_TYPE_INT, { .i64 = 25 }, 0, 52, FLAGS },
1280     { NULL },
1281 };
1282
1283 static const AVCodecDefault vaapi_encode_h265_defaults[] = {
1284     { "profile",        "1"   },
1285     { "level",          "51"  },
1286     { "b",              "0"   },
1287     { "bf",             "2"   },
1288     { "g",              "120" },
1289     { "i_qfactor",      "1"   },
1290     { "i_qoffset",      "0"   },
1291     { "b_qfactor",      "6/5" },
1292     { "b_qoffset",      "0"   },
1293     { NULL },
1294 };
1295
1296 static const AVClass vaapi_encode_h265_class = {
1297     .class_name = "h265_vaapi",
1298     .item_name  = av_default_item_name,
1299     .option     = vaapi_encode_h265_options,
1300     .version    = LIBAVUTIL_VERSION_INT,
1301 };
1302
1303 AVCodec ff_hevc_vaapi_encoder = {
1304     .name           = "hevc_vaapi",
1305     .long_name      = NULL_IF_CONFIG_SMALL("H.265/HEVC (VAAPI)"),
1306     .type           = AVMEDIA_TYPE_VIDEO,
1307     .id             = AV_CODEC_ID_HEVC,
1308     .priv_data_size = (sizeof(VAAPIEncodeContext) +
1309                        sizeof(VAAPIEncodeH265Options)),
1310     .init           = &vaapi_encode_h265_init,
1311     .encode2        = &ff_vaapi_encode2,
1312     .close          = &ff_vaapi_encode_close,
1313     .priv_class     = &vaapi_encode_h265_class,
1314     .capabilities   = AV_CODEC_CAP_DELAY,
1315     .defaults       = vaapi_encode_h265_defaults,
1316     .pix_fmts = (const enum AVPixelFormat[]) {
1317         AV_PIX_FMT_VAAPI,
1318         AV_PIX_FMT_NONE,
1319     },
1320 };