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