]> git.sesse.net Git - ffmpeg/blob - libavcodec/cbs_h265_syntax_template.c
55da1a0a116bdc4e8f2241640bd0102bf85a034f
[ffmpeg] / libavcodec / cbs_h265_syntax_template.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 static int FUNC(rbsp_trailing_bits)(CodedBitstreamContext *ctx, RWContext *rw)
20 {
21     int err;
22
23     fixed(1, rbsp_stop_one_bit, 1);
24     while (byte_alignment(rw) != 0)
25         fixed(1, rbsp_alignment_zero_bit, 0);
26
27     return 0;
28 }
29
30 static int FUNC(nal_unit_header)(CodedBitstreamContext *ctx, RWContext *rw,
31                                  H265RawNALUnitHeader *current,
32                                  int expected_nal_unit_type)
33 {
34     int err;
35
36     fixed(1, forbidden_zero_bit, 0);
37
38     if (expected_nal_unit_type >= 0)
39         u(6, nal_unit_type, expected_nal_unit_type,
40                             expected_nal_unit_type);
41     else
42         ub(6, nal_unit_type);
43
44     u(6, nuh_layer_id,          0, 62);
45     u(3, nuh_temporal_id_plus1, 1,  7);
46
47     return 0;
48 }
49
50 static int FUNC(byte_alignment)(CodedBitstreamContext *ctx, RWContext *rw)
51 {
52     int err;
53
54     fixed(1, alignment_bit_equal_to_one, 1);
55     while (byte_alignment(rw) != 0)
56         fixed(1, alignment_bit_equal_to_zero, 0);
57
58     return 0;
59 }
60
61 static int FUNC(extension_data)(CodedBitstreamContext *ctx, RWContext *rw,
62                                 H265RawExtensionData *current)
63 {
64     int err;
65     size_t k;
66 #ifdef READ
67     GetBitContext start;
68     uint8_t bit;
69     start = *rw;
70     for (k = 0; cbs_h2645_read_more_rbsp_data(rw); k++)
71         skip_bits(rw, 1);
72     current->bit_length = k;
73     if (k > 0) {
74         *rw = start;
75         allocate(current->data, (current->bit_length + 7) / 8);
76         for (k = 0; k < current->bit_length; k++) {
77             xu(1, extension_data, bit, 0, 1, 0);
78             current->data[k / 8] |= bit << (7 - k % 8);
79         }
80     }
81 #else
82     for (k = 0; k < current->bit_length; k++)
83         xu(1, extension_data, current->data[k / 8] >> (7 - k % 8) & 1, 0, 1, 0);
84 #endif
85     return 0;
86 }
87
88 static int FUNC(profile_tier_level)(CodedBitstreamContext *ctx, RWContext *rw,
89                                     H265RawProfileTierLevel *current,
90                                     int profile_present_flag,
91                                     int max_num_sub_layers_minus1)
92 {
93     int err, i, j;
94
95     if (profile_present_flag) {
96         u(2, general_profile_space, 0, 0);
97         flag(general_tier_flag);
98         ub(5, general_profile_idc);
99
100         for (j = 0; j < 32; j++)
101             flags(general_profile_compatibility_flag[j], 1, j);
102
103         flag(general_progressive_source_flag);
104         flag(general_interlaced_source_flag);
105         flag(general_non_packed_constraint_flag);
106         flag(general_frame_only_constraint_flag);
107
108 #define profile_compatible(x) (current->general_profile_idc == (x) || \
109                                current->general_profile_compatibility_flag[x])
110         if (profile_compatible(4) || profile_compatible(5) ||
111             profile_compatible(6) || profile_compatible(7) ||
112             profile_compatible(8) || profile_compatible(9) ||
113             profile_compatible(10)) {
114             flag(general_max_12bit_constraint_flag);
115             flag(general_max_10bit_constraint_flag);
116             flag(general_max_8bit_constraint_flag);
117             flag(general_max_422chroma_constraint_flag);
118             flag(general_max_420chroma_constraint_flag);
119             flag(general_max_monochrome_constraint_flag);
120             flag(general_intra_constraint_flag);
121             flag(general_one_picture_only_constraint_flag);
122             flag(general_lower_bit_rate_constraint_flag);
123
124             if (profile_compatible(5) || profile_compatible(9) ||
125                 profile_compatible(10)) {
126                 flag(general_max_14bit_constraint_flag);
127                 fixed(24, general_reserved_zero_33bits, 0);
128                 fixed( 9, general_reserved_zero_33bits, 0);
129             } else {
130                 fixed(24, general_reserved_zero_34bits, 0);
131                 fixed(10, general_reserved_zero_34bits, 0);
132             }
133         } else if (profile_compatible(2)) {
134             fixed(7, general_reserved_zero_7bits, 0);
135             flag(general_one_picture_only_constraint_flag);
136             fixed(24, general_reserved_zero_35bits, 0);
137             fixed(11, general_reserved_zero_35bits, 0);
138         } else {
139             fixed(24, general_reserved_zero_43bits, 0);
140             fixed(19, general_reserved_zero_43bits, 0);
141         }
142
143         if (profile_compatible(1) || profile_compatible(2) ||
144             profile_compatible(3) || profile_compatible(4) ||
145             profile_compatible(5) || profile_compatible(9)) {
146             flag(general_inbld_flag);
147         } else {
148             fixed(1, general_reserved_zero_bit, 0);
149         }
150 #undef profile_compatible
151     }
152
153     ub(8, general_level_idc);
154
155     for (i = 0; i < max_num_sub_layers_minus1; i++) {
156         flags(sub_layer_profile_present_flag[i], 1, i);
157         flags(sub_layer_level_present_flag[i],   1, i);
158     }
159
160     if (max_num_sub_layers_minus1 > 0) {
161         for (i = max_num_sub_layers_minus1; i < 8; i++)
162             fixed(2, reserved_zero_2bits, 0);
163     }
164
165     for (i = 0; i < max_num_sub_layers_minus1; i++) {
166         if (current->sub_layer_profile_present_flag[i]) {
167             us(2, sub_layer_profile_space[i], 0, 0, 1, i);
168             flags(sub_layer_tier_flag[i],           1, i);
169             ubs(5, sub_layer_profile_idc[i], 1, i);
170
171             for (j = 0; j < 32; j++)
172                 flags(sub_layer_profile_compatibility_flag[i][j], 2, i, j);
173
174             flags(sub_layer_progressive_source_flag[i],    1, i);
175             flags(sub_layer_interlaced_source_flag[i],     1, i);
176             flags(sub_layer_non_packed_constraint_flag[i], 1, i);
177             flags(sub_layer_frame_only_constraint_flag[i], 1, i);
178
179 #define profile_compatible(x) (current->sub_layer_profile_idc[i] == (x) ||   \
180                                current->sub_layer_profile_compatibility_flag[i][x])
181             if (profile_compatible(4) || profile_compatible(5) ||
182                 profile_compatible(6) || profile_compatible(7) ||
183                 profile_compatible(8) || profile_compatible(9) ||
184                 profile_compatible(10)) {
185                 flags(sub_layer_max_12bit_constraint_flag[i],        1, i);
186                 flags(sub_layer_max_10bit_constraint_flag[i],        1, i);
187                 flags(sub_layer_max_8bit_constraint_flag[i],         1, i);
188                 flags(sub_layer_max_422chroma_constraint_flag[i],    1, i);
189                 flags(sub_layer_max_420chroma_constraint_flag[i],    1, i);
190                 flags(sub_layer_max_monochrome_constraint_flag[i],   1, i);
191                 flags(sub_layer_intra_constraint_flag[i],            1, i);
192                 flags(sub_layer_one_picture_only_constraint_flag[i], 1, i);
193                 flags(sub_layer_lower_bit_rate_constraint_flag[i],   1, i);
194
195                 if (profile_compatible(5)) {
196                     flags(sub_layer_max_14bit_constraint_flag[i], 1, i);
197                     fixed(24, sub_layer_reserved_zero_33bits, 0);
198                     fixed( 9, sub_layer_reserved_zero_33bits, 0);
199                 } else {
200                     fixed(24, sub_layer_reserved_zero_34bits, 0);
201                     fixed(10, sub_layer_reserved_zero_34bits, 0);
202                 }
203             } else if (profile_compatible(2)) {
204                 fixed(7, sub_layer_reserved_zero_7bits, 0);
205                 flags(sub_layer_one_picture_only_constraint_flag[i], 1, i);
206                 fixed(24, sub_layer_reserved_zero_43bits, 0);
207                 fixed(11, sub_layer_reserved_zero_43bits, 0);
208             } else {
209                 fixed(24, sub_layer_reserved_zero_43bits, 0);
210                 fixed(19, sub_layer_reserved_zero_43bits, 0);
211             }
212
213             if (profile_compatible(1) || profile_compatible(2) ||
214                 profile_compatible(3) || profile_compatible(4) ||
215                 profile_compatible(5) || profile_compatible(9)) {
216                 flags(sub_layer_inbld_flag[i], 1, i);
217             } else {
218                 fixed(1, sub_layer_reserved_zero_bit, 0);
219             }
220 #undef profile_compatible
221         }
222         if (current->sub_layer_level_present_flag[i])
223             ubs(8, sub_layer_level_idc[i], 1, i);
224     }
225
226     return 0;
227 }
228
229 static int FUNC(sub_layer_hrd_parameters)(CodedBitstreamContext *ctx, RWContext *rw,
230                                           H265RawHRDParameters *hrd,
231                                           int nal, int sub_layer_id)
232 {
233     H265RawSubLayerHRDParameters *current;
234     int err, i;
235
236     if (nal)
237         current = &hrd->nal_sub_layer_hrd_parameters[sub_layer_id];
238     else
239         current = &hrd->vcl_sub_layer_hrd_parameters[sub_layer_id];
240
241     for (i = 0; i <= hrd->cpb_cnt_minus1[sub_layer_id]; i++) {
242         ues(bit_rate_value_minus1[i], 0, UINT32_MAX - 1, 1, i);
243         ues(cpb_size_value_minus1[i], 0, UINT32_MAX - 1, 1, i);
244         if (hrd->sub_pic_hrd_params_present_flag) {
245             ues(cpb_size_du_value_minus1[i], 0, UINT32_MAX - 1, 1, i);
246             ues(bit_rate_du_value_minus1[i], 0, UINT32_MAX - 1, 1, i);
247         }
248         flags(cbr_flag[i], 1, i);
249     }
250
251     return 0;
252 }
253
254 static int FUNC(hrd_parameters)(CodedBitstreamContext *ctx, RWContext *rw,
255                                 H265RawHRDParameters *current, int common_inf_present_flag,
256                                 int max_num_sub_layers_minus1)
257 {
258     int err, i;
259
260     if (common_inf_present_flag) {
261         flag(nal_hrd_parameters_present_flag);
262         flag(vcl_hrd_parameters_present_flag);
263
264         if (current->nal_hrd_parameters_present_flag ||
265             current->vcl_hrd_parameters_present_flag) {
266             flag(sub_pic_hrd_params_present_flag);
267             if (current->sub_pic_hrd_params_present_flag) {
268                 ub(8, tick_divisor_minus2);
269                 ub(5, du_cpb_removal_delay_increment_length_minus1);
270                 flag(sub_pic_cpb_params_in_pic_timing_sei_flag);
271                 ub(5, dpb_output_delay_du_length_minus1);
272             }
273
274             ub(4, bit_rate_scale);
275             ub(4, cpb_size_scale);
276             if (current->sub_pic_hrd_params_present_flag)
277                 ub(4, cpb_size_du_scale);
278
279             ub(5, initial_cpb_removal_delay_length_minus1);
280             ub(5, au_cpb_removal_delay_length_minus1);
281             ub(5, dpb_output_delay_length_minus1);
282         } else {
283             infer(sub_pic_hrd_params_present_flag, 0);
284
285             infer(initial_cpb_removal_delay_length_minus1, 23);
286             infer(au_cpb_removal_delay_length_minus1,      23);
287             infer(dpb_output_delay_length_minus1,          23);
288         }
289     }
290
291     for (i = 0; i <= max_num_sub_layers_minus1; i++) {
292         flags(fixed_pic_rate_general_flag[i], 1, i);
293
294         if (!current->fixed_pic_rate_general_flag[i])
295             flags(fixed_pic_rate_within_cvs_flag[i], 1, i);
296         else
297             infer(fixed_pic_rate_within_cvs_flag[i], 1);
298
299         if (current->fixed_pic_rate_within_cvs_flag[i]) {
300             ues(elemental_duration_in_tc_minus1[i], 0, 2047, 1, i);
301             infer(low_delay_hrd_flag[i], 0);
302         } else
303             flags(low_delay_hrd_flag[i], 1, i);
304
305         if (!current->low_delay_hrd_flag[i])
306             ues(cpb_cnt_minus1[i], 0, 31, 1, i);
307         else
308             infer(cpb_cnt_minus1[i], 0);
309
310         if (current->nal_hrd_parameters_present_flag)
311             CHECK(FUNC(sub_layer_hrd_parameters)(ctx, rw, current, 0, i));
312         if (current->vcl_hrd_parameters_present_flag)
313             CHECK(FUNC(sub_layer_hrd_parameters)(ctx, rw, current, 1, i));
314     }
315
316     return 0;
317 }
318
319 static int FUNC(vui_parameters)(CodedBitstreamContext *ctx, RWContext *rw,
320                                 H265RawVUI *current, const H265RawSPS *sps)
321 {
322     int err;
323
324     flag(aspect_ratio_info_present_flag);
325     if (current->aspect_ratio_info_present_flag) {
326         ub(8, aspect_ratio_idc);
327         if (current->aspect_ratio_idc == 255) {
328             ub(16, sar_width);
329             ub(16, sar_height);
330         }
331     } else {
332         infer(aspect_ratio_idc, 0);
333     }
334
335     flag(overscan_info_present_flag);
336     if (current->overscan_info_present_flag)
337         flag(overscan_appropriate_flag);
338
339     flag(video_signal_type_present_flag);
340     if (current->video_signal_type_present_flag) {
341         ub(3, video_format);
342         flag(video_full_range_flag);
343         flag(colour_description_present_flag);
344         if (current->colour_description_present_flag) {
345             ub(8, colour_primaries);
346             ub(8, transfer_characteristics);
347             ub(8, matrix_coefficients);
348         } else {
349             infer(colour_primaries,         2);
350             infer(transfer_characteristics, 2);
351             infer(matrix_coefficients,      2);
352         }
353     } else {
354         infer(video_format,             5);
355         infer(video_full_range_flag,    0);
356         infer(colour_primaries,         2);
357         infer(transfer_characteristics, 2);
358         infer(matrix_coefficients,      2);
359     }
360
361     flag(chroma_loc_info_present_flag);
362     if (current->chroma_loc_info_present_flag) {
363         ue(chroma_sample_loc_type_top_field,    0, 5);
364         ue(chroma_sample_loc_type_bottom_field, 0, 5);
365     } else {
366         infer(chroma_sample_loc_type_top_field,    0);
367         infer(chroma_sample_loc_type_bottom_field, 0);
368     }
369
370     flag(neutral_chroma_indication_flag);
371     flag(field_seq_flag);
372     flag(frame_field_info_present_flag);
373
374     flag(default_display_window_flag);
375     if (current->default_display_window_flag) {
376         ue(def_disp_win_left_offset,   0, 16384);
377         ue(def_disp_win_right_offset,  0, 16384);
378         ue(def_disp_win_top_offset,    0, 16384);
379         ue(def_disp_win_bottom_offset, 0, 16384);
380     }
381
382     flag(vui_timing_info_present_flag);
383     if (current->vui_timing_info_present_flag) {
384         u(32, vui_num_units_in_tick, 1, UINT32_MAX);
385         u(32, vui_time_scale,        1, UINT32_MAX);
386         flag(vui_poc_proportional_to_timing_flag);
387         if (current->vui_poc_proportional_to_timing_flag)
388             ue(vui_num_ticks_poc_diff_one_minus1, 0, UINT32_MAX - 1);
389
390         flag(vui_hrd_parameters_present_flag);
391         if (current->vui_hrd_parameters_present_flag) {
392             CHECK(FUNC(hrd_parameters)(ctx, rw, &current->hrd_parameters,
393                                        1, sps->sps_max_sub_layers_minus1));
394         }
395     }
396
397     flag(bitstream_restriction_flag);
398     if (current->bitstream_restriction_flag) {
399         flag(tiles_fixed_structure_flag);
400         flag(motion_vectors_over_pic_boundaries_flag);
401         flag(restricted_ref_pic_lists_flag);
402         ue(min_spatial_segmentation_idc,  0, 4095);
403         ue(max_bytes_per_pic_denom,       0, 16);
404         ue(max_bits_per_min_cu_denom,     0, 16);
405         ue(log2_max_mv_length_horizontal, 0, 16);
406         ue(log2_max_mv_length_vertical,   0, 16);
407     } else {
408         infer(tiles_fixed_structure_flag,    0);
409         infer(motion_vectors_over_pic_boundaries_flag, 1);
410         infer(min_spatial_segmentation_idc,  0);
411         infer(max_bytes_per_pic_denom,       2);
412         infer(max_bits_per_min_cu_denom,     1);
413         infer(log2_max_mv_length_horizontal, 15);
414         infer(log2_max_mv_length_vertical,   15);
415     }
416
417     return 0;
418 }
419
420 static int FUNC(vps)(CodedBitstreamContext *ctx, RWContext *rw,
421                      H265RawVPS *current)
422 {
423     int err, i, j;
424
425     HEADER("Video Parameter Set");
426
427     CHECK(FUNC(nal_unit_header)(ctx, rw, &current->nal_unit_header, HEVC_NAL_VPS));
428
429     ub(4, vps_video_parameter_set_id);
430
431     flag(vps_base_layer_internal_flag);
432     flag(vps_base_layer_available_flag);
433     u(6, vps_max_layers_minus1,     0, HEVC_MAX_LAYERS - 1);
434     u(3, vps_max_sub_layers_minus1, 0, HEVC_MAX_SUB_LAYERS - 1);
435     flag(vps_temporal_id_nesting_flag);
436
437     if (current->vps_max_sub_layers_minus1 == 0 &&
438         current->vps_temporal_id_nesting_flag != 1) {
439         av_log(ctx->log_ctx, AV_LOG_ERROR, "Invalid stream: "
440                "vps_temporal_id_nesting_flag must be 1 if "
441                "vps_max_sub_layers_minus1 is 0.\n");
442         return AVERROR_INVALIDDATA;
443     }
444
445     fixed(16, vps_reserved_0xffff_16bits, 0xffff);
446
447     CHECK(FUNC(profile_tier_level)(ctx, rw, &current->profile_tier_level,
448                                    1, current->vps_max_sub_layers_minus1));
449
450     flag(vps_sub_layer_ordering_info_present_flag);
451     for (i = (current->vps_sub_layer_ordering_info_present_flag ?
452               0 : current->vps_max_sub_layers_minus1);
453          i <= current->vps_max_sub_layers_minus1; i++) {
454         ues(vps_max_dec_pic_buffering_minus1[i],
455             0, HEVC_MAX_DPB_SIZE - 1,                        1, i);
456         ues(vps_max_num_reorder_pics[i],
457             0, current->vps_max_dec_pic_buffering_minus1[i], 1, i);
458         ues(vps_max_latency_increase_plus1[i],
459             0, UINT32_MAX - 1,                               1, i);
460     }
461     if (!current->vps_sub_layer_ordering_info_present_flag) {
462         for (i = 0; i < current->vps_max_sub_layers_minus1; i++) {
463             infer(vps_max_dec_pic_buffering_minus1[i],
464                   current->vps_max_dec_pic_buffering_minus1[current->vps_max_sub_layers_minus1]);
465             infer(vps_max_num_reorder_pics[i],
466                   current->vps_max_num_reorder_pics[current->vps_max_sub_layers_minus1]);
467             infer(vps_max_latency_increase_plus1[i],
468                   current->vps_max_latency_increase_plus1[current->vps_max_sub_layers_minus1]);
469         }
470     }
471
472     u(6, vps_max_layer_id,        0, HEVC_MAX_LAYERS - 1);
473     ue(vps_num_layer_sets_minus1, 0, HEVC_MAX_LAYER_SETS - 1);
474     for (i = 1; i <= current->vps_num_layer_sets_minus1; i++) {
475         for (j = 0; j <= current->vps_max_layer_id; j++)
476             flags(layer_id_included_flag[i][j], 2, i, j);
477     }
478     for (j = 0; j <= current->vps_max_layer_id; j++)
479         infer(layer_id_included_flag[0][j], j == 0);
480
481     flag(vps_timing_info_present_flag);
482     if (current->vps_timing_info_present_flag) {
483         u(32, vps_num_units_in_tick, 1, UINT32_MAX);
484         u(32, vps_time_scale,        1, UINT32_MAX);
485         flag(vps_poc_proportional_to_timing_flag);
486         if (current->vps_poc_proportional_to_timing_flag)
487             ue(vps_num_ticks_poc_diff_one_minus1, 0, UINT32_MAX - 1);
488         ue(vps_num_hrd_parameters, 0, current->vps_num_layer_sets_minus1 + 1);
489         for (i = 0; i < current->vps_num_hrd_parameters; i++) {
490             ues(hrd_layer_set_idx[i],
491                 current->vps_base_layer_internal_flag ? 0 : 1,
492                 current->vps_num_layer_sets_minus1, 1, i);
493             if (i > 0)
494                 flags(cprms_present_flag[i], 1, i);
495             else
496                 infer(cprms_present_flag[0], 1);
497
498             CHECK(FUNC(hrd_parameters)(ctx, rw, &current->hrd_parameters[i],
499                                        current->cprms_present_flag[i],
500                                        current->vps_max_sub_layers_minus1));
501         }
502     }
503
504     flag(vps_extension_flag);
505     if (current->vps_extension_flag)
506         CHECK(FUNC(extension_data)(ctx, rw, &current->extension_data));
507
508     CHECK(FUNC(rbsp_trailing_bits)(ctx, rw));
509
510     return 0;
511 }
512
513 static int FUNC(st_ref_pic_set)(CodedBitstreamContext *ctx, RWContext *rw,
514                                 H265RawSTRefPicSet *current, int st_rps_idx,
515                                 const H265RawSPS *sps)
516 {
517     int err, i, j;
518
519     if (st_rps_idx != 0)
520         flag(inter_ref_pic_set_prediction_flag);
521     else
522         infer(inter_ref_pic_set_prediction_flag, 0);
523
524     if (current->inter_ref_pic_set_prediction_flag) {
525         unsigned int ref_rps_idx, num_delta_pocs, num_ref_pics;
526         const H265RawSTRefPicSet *ref;
527         int delta_rps, d_poc;
528         int ref_delta_poc_s0[HEVC_MAX_REFS], ref_delta_poc_s1[HEVC_MAX_REFS];
529         int delta_poc_s0[HEVC_MAX_REFS], delta_poc_s1[HEVC_MAX_REFS];
530         uint8_t used_by_curr_pic_s0[HEVC_MAX_REFS],
531                 used_by_curr_pic_s1[HEVC_MAX_REFS];
532
533         if (st_rps_idx == sps->num_short_term_ref_pic_sets)
534             ue(delta_idx_minus1, 0, st_rps_idx - 1);
535         else
536             infer(delta_idx_minus1, 0);
537
538         ref_rps_idx = st_rps_idx - (current->delta_idx_minus1 + 1);
539         ref = &sps->st_ref_pic_set[ref_rps_idx];
540         num_delta_pocs = ref->num_negative_pics + ref->num_positive_pics;
541         av_assert0(num_delta_pocs < HEVC_MAX_DPB_SIZE);
542
543         flag(delta_rps_sign);
544         ue(abs_delta_rps_minus1, 0, INT16_MAX);
545         delta_rps = (1 - 2 * current->delta_rps_sign) *
546             (current->abs_delta_rps_minus1 + 1);
547
548         num_ref_pics = 0;
549         for (j = 0; j <= num_delta_pocs; j++) {
550             flags(used_by_curr_pic_flag[j], 1, j);
551             if (!current->used_by_curr_pic_flag[j])
552                 flags(use_delta_flag[j], 1, j);
553             else
554                 infer(use_delta_flag[j], 1);
555             if (current->use_delta_flag[i])
556                 ++num_ref_pics;
557         }
558         if (num_ref_pics >= HEVC_MAX_DPB_SIZE) {
559             av_log(ctx->log_ctx, AV_LOG_ERROR, "Invalid stream: "
560                    "short-term ref pic set %d "
561                    "contains too many pictures.\n", st_rps_idx);
562             return AVERROR_INVALIDDATA;
563         }
564
565         // Since the stored form of an RPS here is actually the delta-step
566         // form used when inter_ref_pic_set_prediction_flag is not set, we
567         // need to reconstruct that here in order to be able to refer to
568         // the RPS later (which is required for parsing, because we don't
569         // even know what syntax elements appear without it).  Therefore,
570         // this code takes the delta-step form of the reference set, turns
571         // it into the delta-array form, applies the prediction process of
572         // 7.4.8, converts the result back to the delta-step form, and
573         // stores that as the current set for future use.  Note that the
574         // inferences here mean that writers using prediction will need
575         // to fill in the delta-step values correctly as well - since the
576         // whole RPS prediction process is somewhat overly sophisticated,
577         // this hopefully forms a useful check for them to ensure their
578         // predicted form actually matches what was intended rather than
579         // an onerous additional requirement.
580
581         d_poc = 0;
582         for (i = 0; i < ref->num_negative_pics; i++) {
583             d_poc -= ref->delta_poc_s0_minus1[i] + 1;
584             ref_delta_poc_s0[i] = d_poc;
585         }
586         d_poc = 0;
587         for (i = 0; i < ref->num_positive_pics; i++) {
588             d_poc += ref->delta_poc_s1_minus1[i] + 1;
589             ref_delta_poc_s1[i] = d_poc;
590         }
591
592         i = 0;
593         for (j = ref->num_positive_pics - 1; j >= 0; j--) {
594             d_poc = ref_delta_poc_s1[j] + delta_rps;
595             if (d_poc < 0 && current->use_delta_flag[ref->num_negative_pics + j]) {
596                 delta_poc_s0[i] = d_poc;
597                 used_by_curr_pic_s0[i++] =
598                     current->used_by_curr_pic_flag[ref->num_negative_pics + j];
599             }
600         }
601         if (delta_rps < 0 && current->use_delta_flag[num_delta_pocs]) {
602             delta_poc_s0[i] = delta_rps;
603             used_by_curr_pic_s0[i++] =
604                 current->used_by_curr_pic_flag[num_delta_pocs];
605         }
606         for (j = 0; j < ref->num_negative_pics; j++) {
607             d_poc = ref_delta_poc_s0[j] + delta_rps;
608             if (d_poc < 0 && current->use_delta_flag[j]) {
609                 delta_poc_s0[i] = d_poc;
610                 used_by_curr_pic_s0[i++] = current->used_by_curr_pic_flag[j];
611             }
612         }
613
614         infer(num_negative_pics, i);
615         for (i = 0; i < current->num_negative_pics; i++) {
616             infer(delta_poc_s0_minus1[i],
617                   -(delta_poc_s0[i] - (i == 0 ? 0 : delta_poc_s0[i - 1])) - 1);
618             infer(used_by_curr_pic_s0_flag[i], used_by_curr_pic_s0[i]);
619         }
620
621         i = 0;
622         for (j = ref->num_negative_pics - 1; j >= 0; j--) {
623             d_poc = ref_delta_poc_s0[j] + delta_rps;
624             if (d_poc > 0 && current->use_delta_flag[j]) {
625                 delta_poc_s1[i] = d_poc;
626                 used_by_curr_pic_s1[i++] = current->used_by_curr_pic_flag[j];
627             }
628         }
629         if (delta_rps > 0 && current->use_delta_flag[num_delta_pocs]) {
630             delta_poc_s1[i] = delta_rps;
631             used_by_curr_pic_s1[i++] =
632                 current->used_by_curr_pic_flag[num_delta_pocs];
633         }
634         for (j = 0; j < ref->num_positive_pics; j++) {
635             d_poc = ref_delta_poc_s1[j] + delta_rps;
636             if (d_poc > 0 && current->use_delta_flag[ref->num_negative_pics + j]) {
637                 delta_poc_s1[i] = d_poc;
638                 used_by_curr_pic_s1[i++] =
639                     current->used_by_curr_pic_flag[ref->num_negative_pics + j];
640             }
641         }
642
643         infer(num_positive_pics, i);
644         for (i = 0; i < current->num_positive_pics; i++) {
645             infer(delta_poc_s1_minus1[i],
646                   delta_poc_s1[i] - (i == 0 ? 0 : delta_poc_s1[i - 1]) - 1);
647             infer(used_by_curr_pic_s1_flag[i], used_by_curr_pic_s1[i]);
648         }
649
650     } else {
651         ue(num_negative_pics, 0, 15);
652         ue(num_positive_pics, 0, 15 - current->num_negative_pics);
653
654         for (i = 0; i < current->num_negative_pics; i++) {
655             ues(delta_poc_s0_minus1[i], 0, INT16_MAX, 1, i);
656             flags(used_by_curr_pic_s0_flag[i],        1, i);
657         }
658
659         for (i = 0; i < current->num_positive_pics; i++) {
660             ues(delta_poc_s1_minus1[i], 0, INT16_MAX, 1, i);
661             flags(used_by_curr_pic_s1_flag[i],        1, i);
662         }
663     }
664
665     return 0;
666 }
667
668 static int FUNC(scaling_list_data)(CodedBitstreamContext *ctx, RWContext *rw,
669                                    H265RawScalingList *current)
670 {
671     int sizeId, matrixId;
672     int err, n, i;
673
674     for (sizeId = 0; sizeId < 4; sizeId++) {
675         for (matrixId = 0; matrixId < 6; matrixId += (sizeId == 3 ? 3 : 1)) {
676             flags(scaling_list_pred_mode_flag[sizeId][matrixId],
677                   2, sizeId, matrixId);
678             if (!current->scaling_list_pred_mode_flag[sizeId][matrixId]) {
679                 ues(scaling_list_pred_matrix_id_delta[sizeId][matrixId],
680                     0, sizeId == 3 ? matrixId / 3 : matrixId,
681                     2, sizeId, matrixId);
682             } else {
683                 n = FFMIN(64, 1 << (4 + (sizeId << 1)));
684                 if (sizeId > 1) {
685                     ses(scaling_list_dc_coef_minus8[sizeId - 2][matrixId], -7, +247,
686                         2, sizeId - 2, matrixId);
687                 }
688                 for (i = 0; i < n; i++) {
689                     ses(scaling_list_delta_coeff[sizeId][matrixId][i],
690                         -128, +127, 3, sizeId, matrixId, i);
691                 }
692             }
693         }
694     }
695
696     return 0;
697 }
698
699 static int FUNC(sps_range_extension)(CodedBitstreamContext *ctx, RWContext *rw,
700                                      H265RawSPS *current)
701 {
702     int err;
703
704     flag(transform_skip_rotation_enabled_flag);
705     flag(transform_skip_context_enabled_flag);
706     flag(implicit_rdpcm_enabled_flag);
707     flag(explicit_rdpcm_enabled_flag);
708     flag(extended_precision_processing_flag);
709     flag(intra_smoothing_disabled_flag);
710     flag(high_precision_offsets_enabled_flag);
711     flag(persistent_rice_adaptation_enabled_flag);
712     flag(cabac_bypass_alignment_enabled_flag);
713
714     return 0;
715 }
716
717 static int FUNC(sps_scc_extension)(CodedBitstreamContext *ctx, RWContext *rw,
718                                    H265RawSPS *current)
719 {
720     int err, comp, i;
721
722     flag(sps_curr_pic_ref_enabled_flag);
723
724     flag(palette_mode_enabled_flag);
725     if (current->palette_mode_enabled_flag) {
726         ue(palette_max_size, 0, 64);
727         ue(delta_palette_max_predictor_size, 0, 128);
728
729         flag(sps_palette_predictor_initializer_present_flag);
730         if (current->sps_palette_predictor_initializer_present_flag) {
731             ue(sps_num_palette_predictor_initializer_minus1, 0, 128);
732             for (comp = 0; comp < (current->chroma_format_idc ? 3 : 1); comp++) {
733                 int bit_depth = comp == 0 ? current->bit_depth_luma_minus8 + 8
734                                           : current->bit_depth_chroma_minus8 + 8;
735                 for (i = 0; i <= current->sps_num_palette_predictor_initializer_minus1; i++)
736                     ubs(bit_depth, sps_palette_predictor_initializers[comp][i], 2, comp, i);
737             }
738         }
739     }
740
741     u(2, motion_vector_resolution_control_idc, 0, 2);
742     flag(intra_boundary_filtering_disable_flag);
743
744     return 0;
745 }
746
747 static int FUNC(sps)(CodedBitstreamContext *ctx, RWContext *rw,
748                      H265RawSPS *current)
749 {
750     CodedBitstreamH265Context *h265 = ctx->priv_data;
751     const H265RawVPS *vps;
752     int err, i;
753     unsigned int min_cb_log2_size_y, ctb_log2_size_y,
754                  min_cb_size_y,   min_tb_log2_size_y;
755
756     HEADER("Sequence Parameter Set");
757
758     CHECK(FUNC(nal_unit_header)(ctx, rw, &current->nal_unit_header, HEVC_NAL_SPS));
759
760     ub(4, sps_video_parameter_set_id);
761     h265->active_vps = vps = h265->vps[current->sps_video_parameter_set_id];
762
763     u(3, sps_max_sub_layers_minus1, 0, HEVC_MAX_SUB_LAYERS - 1);
764     flag(sps_temporal_id_nesting_flag);
765     if (vps) {
766         if (vps->vps_max_sub_layers_minus1 > current->sps_max_sub_layers_minus1) {
767             av_log(ctx->log_ctx, AV_LOG_ERROR, "Invalid stream: "
768                    "sps_max_sub_layers_minus1 (%d) must be less than or equal to "
769                    "vps_max_sub_layers_minus1 (%d).\n",
770                    vps->vps_max_sub_layers_minus1,
771                    current->sps_max_sub_layers_minus1);
772             return AVERROR_INVALIDDATA;
773         }
774         if (vps->vps_temporal_id_nesting_flag &&
775             !current->sps_temporal_id_nesting_flag) {
776             av_log(ctx->log_ctx, AV_LOG_ERROR, "Invalid stream: "
777                    "sps_temporal_id_nesting_flag must be 1 if "
778                    "vps_temporal_id_nesting_flag is 1.\n");
779             return AVERROR_INVALIDDATA;
780         }
781     }
782
783     CHECK(FUNC(profile_tier_level)(ctx, rw, &current->profile_tier_level,
784                                    1, current->sps_max_sub_layers_minus1));
785
786     ue(sps_seq_parameter_set_id, 0, 15);
787
788     ue(chroma_format_idc, 0, 3);
789     if (current->chroma_format_idc == 3)
790         flag(separate_colour_plane_flag);
791     else
792         infer(separate_colour_plane_flag, 0);
793
794     ue(pic_width_in_luma_samples,  1, HEVC_MAX_WIDTH);
795     ue(pic_height_in_luma_samples, 1, HEVC_MAX_HEIGHT);
796
797     flag(conformance_window_flag);
798     if (current->conformance_window_flag) {
799         ue(conf_win_left_offset,   0, current->pic_width_in_luma_samples);
800         ue(conf_win_right_offset,  0, current->pic_width_in_luma_samples);
801         ue(conf_win_top_offset,    0, current->pic_height_in_luma_samples);
802         ue(conf_win_bottom_offset, 0, current->pic_height_in_luma_samples);
803     } else {
804         infer(conf_win_left_offset,   0);
805         infer(conf_win_right_offset,  0);
806         infer(conf_win_top_offset,    0);
807         infer(conf_win_bottom_offset, 0);
808     }
809
810     ue(bit_depth_luma_minus8,   0, 8);
811     ue(bit_depth_chroma_minus8, 0, 8);
812
813     ue(log2_max_pic_order_cnt_lsb_minus4, 0, 12);
814
815     flag(sps_sub_layer_ordering_info_present_flag);
816     for (i = (current->sps_sub_layer_ordering_info_present_flag ?
817               0 : current->sps_max_sub_layers_minus1);
818          i <= current->sps_max_sub_layers_minus1; i++) {
819         ues(sps_max_dec_pic_buffering_minus1[i],
820             0, HEVC_MAX_DPB_SIZE - 1,                        1, i);
821         ues(sps_max_num_reorder_pics[i],
822             0, current->sps_max_dec_pic_buffering_minus1[i], 1, i);
823         ues(sps_max_latency_increase_plus1[i],
824             0, UINT32_MAX - 1,                               1, i);
825     }
826     if (!current->sps_sub_layer_ordering_info_present_flag) {
827         for (i = 0; i < current->sps_max_sub_layers_minus1; i++) {
828             infer(sps_max_dec_pic_buffering_minus1[i],
829                   current->sps_max_dec_pic_buffering_minus1[current->sps_max_sub_layers_minus1]);
830             infer(sps_max_num_reorder_pics[i],
831                   current->sps_max_num_reorder_pics[current->sps_max_sub_layers_minus1]);
832             infer(sps_max_latency_increase_plus1[i],
833                   current->sps_max_latency_increase_plus1[current->sps_max_sub_layers_minus1]);
834         }
835     }
836
837     ue(log2_min_luma_coding_block_size_minus3,   0, 3);
838     min_cb_log2_size_y = current->log2_min_luma_coding_block_size_minus3 + 3;
839
840     ue(log2_diff_max_min_luma_coding_block_size, 0, 3);
841     ctb_log2_size_y = min_cb_log2_size_y +
842         current->log2_diff_max_min_luma_coding_block_size;
843
844     min_cb_size_y = 1 << min_cb_log2_size_y;
845     if (current->pic_width_in_luma_samples  % min_cb_size_y ||
846         current->pic_height_in_luma_samples % min_cb_size_y) {
847         av_log(ctx->log_ctx, AV_LOG_ERROR, "Invalid dimensions: %ux%u not divisible "
848                "by MinCbSizeY = %u.\n", current->pic_width_in_luma_samples,
849                current->pic_height_in_luma_samples, min_cb_size_y);
850         return AVERROR_INVALIDDATA;
851     }
852
853     ue(log2_min_luma_transform_block_size_minus2, 0, min_cb_log2_size_y - 3);
854     min_tb_log2_size_y = current->log2_min_luma_transform_block_size_minus2 + 2;
855
856     ue(log2_diff_max_min_luma_transform_block_size,
857        0, FFMIN(ctb_log2_size_y, 5) - min_tb_log2_size_y);
858
859     ue(max_transform_hierarchy_depth_inter,
860        0, ctb_log2_size_y - min_tb_log2_size_y);
861     ue(max_transform_hierarchy_depth_intra,
862        0, ctb_log2_size_y - min_tb_log2_size_y);
863
864     flag(scaling_list_enabled_flag);
865     if (current->scaling_list_enabled_flag) {
866         flag(sps_scaling_list_data_present_flag);
867         if (current->sps_scaling_list_data_present_flag)
868             CHECK(FUNC(scaling_list_data)(ctx, rw, &current->scaling_list));
869     } else {
870         infer(sps_scaling_list_data_present_flag, 0);
871     }
872
873     flag(amp_enabled_flag);
874     flag(sample_adaptive_offset_enabled_flag);
875
876     flag(pcm_enabled_flag);
877     if (current->pcm_enabled_flag) {
878         u(4, pcm_sample_bit_depth_luma_minus1,
879           0, current->bit_depth_luma_minus8 + 8 - 1);
880         u(4, pcm_sample_bit_depth_chroma_minus1,
881           0, current->bit_depth_chroma_minus8 + 8 - 1);
882
883         ue(log2_min_pcm_luma_coding_block_size_minus3,
884            FFMIN(min_cb_log2_size_y, 5) - 3, FFMIN(ctb_log2_size_y, 5) - 3);
885         ue(log2_diff_max_min_pcm_luma_coding_block_size,
886            0, FFMIN(ctb_log2_size_y, 5) - (current->log2_min_pcm_luma_coding_block_size_minus3 + 3));
887
888         flag(pcm_loop_filter_disabled_flag);
889     }
890
891     ue(num_short_term_ref_pic_sets, 0, HEVC_MAX_SHORT_TERM_REF_PIC_SETS);
892     for (i = 0; i < current->num_short_term_ref_pic_sets; i++)
893         CHECK(FUNC(st_ref_pic_set)(ctx, rw, &current->st_ref_pic_set[i], i, current));
894
895     flag(long_term_ref_pics_present_flag);
896     if (current->long_term_ref_pics_present_flag) {
897         ue(num_long_term_ref_pics_sps, 0, HEVC_MAX_LONG_TERM_REF_PICS);
898         for (i = 0; i < current->num_long_term_ref_pics_sps; i++) {
899             ubs(current->log2_max_pic_order_cnt_lsb_minus4 + 4,
900                 lt_ref_pic_poc_lsb_sps[i], 1, i);
901             flags(used_by_curr_pic_lt_sps_flag[i], 1, i);
902         }
903     }
904
905     flag(sps_temporal_mvp_enabled_flag);
906     flag(strong_intra_smoothing_enabled_flag);
907
908     flag(vui_parameters_present_flag);
909     if (current->vui_parameters_present_flag)
910         CHECK(FUNC(vui_parameters)(ctx, rw, &current->vui, current));
911
912     flag(sps_extension_present_flag);
913     if (current->sps_extension_present_flag) {
914         flag(sps_range_extension_flag);
915         flag(sps_multilayer_extension_flag);
916         flag(sps_3d_extension_flag);
917         flag(sps_scc_extension_flag);
918         ub(4, sps_extension_4bits);
919     }
920
921     if (current->sps_range_extension_flag)
922         CHECK(FUNC(sps_range_extension)(ctx, rw, current));
923     if (current->sps_multilayer_extension_flag)
924         return AVERROR_PATCHWELCOME;
925     if (current->sps_3d_extension_flag)
926         return AVERROR_PATCHWELCOME;
927     if (current->sps_scc_extension_flag)
928         CHECK(FUNC(sps_scc_extension)(ctx, rw, current));
929     if (current->sps_extension_4bits)
930         CHECK(FUNC(extension_data)(ctx, rw, &current->extension_data));
931
932     CHECK(FUNC(rbsp_trailing_bits)(ctx, rw));
933
934     return 0;
935 }
936
937 static int FUNC(pps_range_extension)(CodedBitstreamContext *ctx, RWContext *rw,
938                                      H265RawPPS *current)
939 {
940     CodedBitstreamH265Context *h265 = ctx->priv_data;
941     const H265RawSPS *sps = h265->active_sps;
942     int err, i;
943
944     if (current->transform_skip_enabled_flag)
945         ue(log2_max_transform_skip_block_size_minus2, 0, 3);
946     flag(cross_component_prediction_enabled_flag);
947
948     flag(chroma_qp_offset_list_enabled_flag);
949     if (current->chroma_qp_offset_list_enabled_flag) {
950         ue(diff_cu_chroma_qp_offset_depth,
951            0, sps->log2_diff_max_min_luma_coding_block_size);
952         ue(chroma_qp_offset_list_len_minus1, 0, 5);
953         for (i = 0; i <= current->chroma_qp_offset_list_len_minus1; i++) {
954             ses(cb_qp_offset_list[i], -12, +12, 1, i);
955             ses(cr_qp_offset_list[i], -12, +12, 1, i);
956         }
957     }
958
959     ue(log2_sao_offset_scale_luma,   0, FFMAX(0, sps->bit_depth_luma_minus8   - 2));
960     ue(log2_sao_offset_scale_chroma, 0, FFMAX(0, sps->bit_depth_chroma_minus8 - 2));
961
962     return 0;
963 }
964
965 static int FUNC(pps_scc_extension)(CodedBitstreamContext *ctx, RWContext *rw,
966                                    H265RawPPS *current)
967 {
968     int err, comp, i;
969
970     flag(pps_curr_pic_ref_enabled_flag);
971
972     flag(residual_adaptive_colour_transform_enabled_flag);
973     if (current->residual_adaptive_colour_transform_enabled_flag) {
974         flag(pps_slice_act_qp_offsets_present_flag);
975         se(pps_act_y_qp_offset_plus5,  -7, +17);
976         se(pps_act_cb_qp_offset_plus5, -7, +17);
977         se(pps_act_cr_qp_offset_plus3, -9, +15);
978     } else {
979         infer(pps_slice_act_qp_offsets_present_flag, 0);
980         infer(pps_act_y_qp_offset_plus5,  0);
981         infer(pps_act_cb_qp_offset_plus5, 0);
982         infer(pps_act_cr_qp_offset_plus3, 0);
983     }
984
985     flag(pps_palette_predictor_initializer_present_flag);
986     if (current->pps_palette_predictor_initializer_present_flag) {
987         ue(pps_num_palette_predictor_initializer, 0, 128);
988         if (current->pps_num_palette_predictor_initializer > 0) {
989             flag(monochrome_palette_flag);
990             ue(luma_bit_depth_entry_minus8, 0, 8);
991             if (!current->monochrome_palette_flag)
992                 ue(chroma_bit_depth_entry_minus8, 0, 8);
993             for (comp = 0; comp < (current->monochrome_palette_flag ? 1 : 3); comp++) {
994                 int bit_depth = comp == 0 ? current->luma_bit_depth_entry_minus8 + 8
995                                           : current->chroma_bit_depth_entry_minus8 + 8;
996                 for (i = 0; i < current->pps_num_palette_predictor_initializer; i++)
997                     ubs(bit_depth, pps_palette_predictor_initializers[comp][i], 2, comp, i);
998             }
999         }
1000     }
1001
1002     return 0;
1003 }
1004
1005 static int FUNC(pps)(CodedBitstreamContext *ctx, RWContext *rw,
1006                      H265RawPPS *current)
1007 {
1008     CodedBitstreamH265Context *h265 = ctx->priv_data;
1009     const H265RawSPS *sps;
1010     int err, i;
1011
1012     HEADER("Picture Parameter Set");
1013
1014     CHECK(FUNC(nal_unit_header)(ctx, rw, &current->nal_unit_header, HEVC_NAL_PPS));
1015
1016     ue(pps_pic_parameter_set_id, 0, 63);
1017     ue(pps_seq_parameter_set_id, 0, 15);
1018     sps = h265->sps[current->pps_seq_parameter_set_id];
1019     if (!sps) {
1020         av_log(ctx->log_ctx, AV_LOG_ERROR, "SPS id %d not available.\n",
1021                current->pps_seq_parameter_set_id);
1022         return AVERROR_INVALIDDATA;
1023     }
1024     h265->active_sps = sps;
1025
1026     flag(dependent_slice_segments_enabled_flag);
1027     flag(output_flag_present_flag);
1028     ub(3, num_extra_slice_header_bits);
1029     flag(sign_data_hiding_enabled_flag);
1030     flag(cabac_init_present_flag);
1031
1032     ue(num_ref_idx_l0_default_active_minus1, 0, 14);
1033     ue(num_ref_idx_l1_default_active_minus1, 0, 14);
1034
1035     se(init_qp_minus26, -(26 + 6 * sps->bit_depth_luma_minus8), +25);
1036
1037     flag(constrained_intra_pred_flag);
1038     flag(transform_skip_enabled_flag);
1039     flag(cu_qp_delta_enabled_flag);
1040     if (current->cu_qp_delta_enabled_flag)
1041         ue(diff_cu_qp_delta_depth,
1042            0, sps->log2_diff_max_min_luma_coding_block_size);
1043     else
1044         infer(diff_cu_qp_delta_depth, 0);
1045
1046     se(pps_cb_qp_offset, -12, +12);
1047     se(pps_cr_qp_offset, -12, +12);
1048     flag(pps_slice_chroma_qp_offsets_present_flag);
1049
1050     flag(weighted_pred_flag);
1051     flag(weighted_bipred_flag);
1052
1053     flag(transquant_bypass_enabled_flag);
1054     flag(tiles_enabled_flag);
1055     flag(entropy_coding_sync_enabled_flag);
1056
1057     if (current->tiles_enabled_flag) {
1058         ue(num_tile_columns_minus1, 0, HEVC_MAX_TILE_COLUMNS);
1059         ue(num_tile_rows_minus1,    0, HEVC_MAX_TILE_ROWS);
1060         flag(uniform_spacing_flag);
1061         if (!current->uniform_spacing_flag) {
1062             for (i = 0; i < current->num_tile_columns_minus1; i++)
1063                 ues(column_width_minus1[i], 0, sps->pic_width_in_luma_samples,  1, i);
1064             for (i = 0; i < current->num_tile_rows_minus1; i++)
1065                 ues(row_height_minus1[i],   0, sps->pic_height_in_luma_samples, 1, i);
1066         }
1067         flag(loop_filter_across_tiles_enabled_flag);
1068     } else {
1069         infer(num_tile_columns_minus1, 0);
1070         infer(num_tile_rows_minus1,    0);
1071     }
1072
1073     flag(pps_loop_filter_across_slices_enabled_flag);
1074     flag(deblocking_filter_control_present_flag);
1075     if (current->deblocking_filter_control_present_flag) {
1076         flag(deblocking_filter_override_enabled_flag);
1077         flag(pps_deblocking_filter_disabled_flag);
1078         if (!current->pps_deblocking_filter_disabled_flag) {
1079             se(pps_beta_offset_div2, -6, +6);
1080             se(pps_tc_offset_div2,   -6, +6);
1081         } else {
1082             infer(pps_beta_offset_div2, 0);
1083             infer(pps_tc_offset_div2,   0);
1084         }
1085     } else {
1086         infer(deblocking_filter_override_enabled_flag, 0);
1087         infer(pps_deblocking_filter_disabled_flag,     0);
1088         infer(pps_beta_offset_div2, 0);
1089         infer(pps_tc_offset_div2,   0);
1090     }
1091
1092     flag(pps_scaling_list_data_present_flag);
1093     if (current->pps_scaling_list_data_present_flag)
1094         CHECK(FUNC(scaling_list_data)(ctx, rw, &current->scaling_list));
1095
1096     flag(lists_modification_present_flag);
1097
1098     ue(log2_parallel_merge_level_minus2,
1099        0, (sps->log2_min_luma_coding_block_size_minus3 + 3 +
1100            sps->log2_diff_max_min_luma_coding_block_size - 2));
1101
1102     flag(slice_segment_header_extension_present_flag);
1103
1104     flag(pps_extension_present_flag);
1105     if (current->pps_extension_present_flag) {
1106         flag(pps_range_extension_flag);
1107         flag(pps_multilayer_extension_flag);
1108         flag(pps_3d_extension_flag);
1109         flag(pps_scc_extension_flag);
1110         ub(4, pps_extension_4bits);
1111     }
1112     if (current->pps_range_extension_flag)
1113         CHECK(FUNC(pps_range_extension)(ctx, rw, current));
1114     if (current->pps_multilayer_extension_flag)
1115         return AVERROR_PATCHWELCOME;
1116     if (current->pps_3d_extension_flag)
1117         return AVERROR_PATCHWELCOME;
1118     if (current->pps_scc_extension_flag)
1119         CHECK(FUNC(pps_scc_extension)(ctx, rw, current));
1120     if (current->pps_extension_4bits)
1121         CHECK(FUNC(extension_data)(ctx, rw, &current->extension_data));
1122
1123     CHECK(FUNC(rbsp_trailing_bits)(ctx, rw));
1124
1125     return 0;
1126 }
1127
1128 static int FUNC(aud)(CodedBitstreamContext *ctx, RWContext *rw,
1129                      H265RawAUD *current)
1130 {
1131     int err;
1132
1133     HEADER("Access Unit Delimiter");
1134
1135     CHECK(FUNC(nal_unit_header)(ctx, rw, &current->nal_unit_header, HEVC_NAL_AUD));
1136
1137     u(3, pic_type, 0, 2);
1138
1139     CHECK(FUNC(rbsp_trailing_bits)(ctx, rw));
1140
1141     return 0;
1142 }
1143
1144 static int FUNC(ref_pic_lists_modification)(CodedBitstreamContext *ctx, RWContext *rw,
1145                                             H265RawSliceHeader *current,
1146                                             unsigned int num_pic_total_curr)
1147 {
1148     unsigned int entry_size;
1149     int err, i;
1150
1151     entry_size = av_log2(num_pic_total_curr - 1) + 1;
1152
1153     flag(ref_pic_list_modification_flag_l0);
1154     if (current->ref_pic_list_modification_flag_l0) {
1155         for (i = 0; i <= current->num_ref_idx_l0_active_minus1; i++)
1156             us(entry_size, list_entry_l0[i], 0, num_pic_total_curr - 1, 1, i);
1157     }
1158
1159     if (current->slice_type == HEVC_SLICE_B) {
1160         flag(ref_pic_list_modification_flag_l1);
1161         if (current->ref_pic_list_modification_flag_l1) {
1162             for (i = 0; i <= current->num_ref_idx_l1_active_minus1; i++)
1163                 us(entry_size, list_entry_l1[i], 0, num_pic_total_curr - 1, 1, i);
1164         }
1165     }
1166
1167     return 0;
1168 }
1169
1170 static int FUNC(pred_weight_table)(CodedBitstreamContext *ctx, RWContext *rw,
1171                                    H265RawSliceHeader *current)
1172 {
1173     CodedBitstreamH265Context *h265 = ctx->priv_data;
1174     const H265RawSPS *sps = h265->active_sps;
1175     int err, i, j;
1176     int chroma = !sps->separate_colour_plane_flag &&
1177                   sps->chroma_format_idc != 0;
1178
1179     ue(luma_log2_weight_denom, 0, 7);
1180     if (chroma)
1181         se(delta_chroma_log2_weight_denom, -7, 7);
1182     else
1183         infer(delta_chroma_log2_weight_denom, 0);
1184
1185     for (i = 0; i <= current->num_ref_idx_l0_active_minus1; i++) {
1186         if (1 /* is not same POC and same layer_id */)
1187             flags(luma_weight_l0_flag[i], 1, i);
1188         else
1189             infer(luma_weight_l0_flag[i], 0);
1190     }
1191     if (chroma) {
1192         for (i = 0; i <= current->num_ref_idx_l0_active_minus1; i++) {
1193             if (1 /* is not same POC and same layer_id */)
1194                 flags(chroma_weight_l0_flag[i], 1, i);
1195             else
1196                 infer(chroma_weight_l0_flag[i], 0);
1197         }
1198     }
1199
1200     for (i = 0; i <= current->num_ref_idx_l0_active_minus1; i++) {
1201         if (current->luma_weight_l0_flag[i]) {
1202             ses(delta_luma_weight_l0[i], -128, +127, 1, i);
1203             ses(luma_offset_l0[i],
1204                 -(1 << (sps->bit_depth_luma_minus8 + 8 - 1)),
1205                 ((1 << (sps->bit_depth_luma_minus8 + 8 - 1)) - 1), 1, i);
1206         } else {
1207             infer(delta_luma_weight_l0[i], 0);
1208             infer(luma_offset_l0[i],       0);
1209         }
1210         if (current->chroma_weight_l0_flag[i]) {
1211             for (j = 0; j < 2; j++) {
1212                 ses(delta_chroma_weight_l0[i][j], -128, +127, 2, i, j);
1213                 ses(chroma_offset_l0[i][j],
1214                     -(4 << (sps->bit_depth_chroma_minus8 + 8 - 1)),
1215                     ((4 << (sps->bit_depth_chroma_minus8 + 8 - 1)) - 1), 2, i, j);
1216             }
1217         } else {
1218             for (j = 0; j < 2; j++) {
1219                 infer(delta_chroma_weight_l0[i][j], 0);
1220                 infer(chroma_offset_l0[i][j],       0);
1221             }
1222         }
1223     }
1224
1225     if (current->slice_type == HEVC_SLICE_B) {
1226         for (i = 0; i <= current->num_ref_idx_l1_active_minus1; i++) {
1227             if (1 /* RefPicList1[i] is not CurrPic, nor is it in a different layer */)
1228                 flags(luma_weight_l1_flag[i], 1, i);
1229             else
1230                 infer(luma_weight_l1_flag[i], 0);
1231         }
1232         if (chroma) {
1233             for (i = 0; i <= current->num_ref_idx_l1_active_minus1; i++) {
1234                 if (1 /* RefPicList1[i] is not CurrPic, nor is it in a different layer */)
1235                     flags(chroma_weight_l1_flag[i], 1, i);
1236                 else
1237                     infer(chroma_weight_l1_flag[i], 0);
1238             }
1239         }
1240
1241         for (i = 0; i <= current->num_ref_idx_l1_active_minus1; i++) {
1242             if (current->luma_weight_l1_flag[i]) {
1243                 ses(delta_luma_weight_l1[i], -128, +127, 1, i);
1244                 ses(luma_offset_l1[i],
1245                     -(1 << (sps->bit_depth_luma_minus8 + 8 - 1)),
1246                     ((1 << (sps->bit_depth_luma_minus8 + 8 - 1)) - 1), 1, i);
1247             } else {
1248                 infer(delta_luma_weight_l1[i], 0);
1249                 infer(luma_offset_l1[i],       0);
1250             }
1251             if (current->chroma_weight_l1_flag[i]) {
1252                 for (j = 0; j < 2; j++) {
1253                     ses(delta_chroma_weight_l1[i][j], -128, +127, 2, i, j);
1254                     ses(chroma_offset_l1[i][j],
1255                         -(4 << (sps->bit_depth_chroma_minus8 + 8 - 1)),
1256                         ((4 << (sps->bit_depth_chroma_minus8 + 8 - 1)) - 1), 2, i, j);
1257                 }
1258             } else {
1259                 for (j = 0; j < 2; j++) {
1260                     infer(delta_chroma_weight_l1[i][j], 0);
1261                     infer(chroma_offset_l1[i][j],       0);
1262                 }
1263             }
1264         }
1265     }
1266
1267     return 0;
1268 }
1269
1270 static int FUNC(slice_segment_header)(CodedBitstreamContext *ctx, RWContext *rw,
1271                                       H265RawSliceHeader *current)
1272 {
1273     CodedBitstreamH265Context *h265 = ctx->priv_data;
1274     const H265RawSPS *sps;
1275     const H265RawPPS *pps;
1276     unsigned int min_cb_log2_size_y, ctb_log2_size_y, ctb_size_y;
1277     unsigned int pic_width_in_ctbs_y, pic_height_in_ctbs_y, pic_size_in_ctbs_y;
1278     unsigned int num_pic_total_curr = 0;
1279     int err, i;
1280
1281     HEADER("Slice Segment Header");
1282
1283     CHECK(FUNC(nal_unit_header)(ctx, rw, &current->nal_unit_header, -1));
1284
1285     flag(first_slice_segment_in_pic_flag);
1286
1287     if (current->nal_unit_header.nal_unit_type >= HEVC_NAL_BLA_W_LP &&
1288         current->nal_unit_header.nal_unit_type <= HEVC_NAL_RSV_IRAP_VCL23)
1289         flag(no_output_of_prior_pics_flag);
1290
1291     ue(slice_pic_parameter_set_id, 0, 63);
1292
1293     pps = h265->pps[current->slice_pic_parameter_set_id];
1294     if (!pps) {
1295         av_log(ctx->log_ctx, AV_LOG_ERROR, "PPS id %d not available.\n",
1296                current->slice_pic_parameter_set_id);
1297         return AVERROR_INVALIDDATA;
1298     }
1299     h265->active_pps = pps;
1300
1301     sps = h265->sps[pps->pps_seq_parameter_set_id];
1302     if (!sps) {
1303         av_log(ctx->log_ctx, AV_LOG_ERROR, "SPS id %d not available.\n",
1304                pps->pps_seq_parameter_set_id);
1305         return AVERROR_INVALIDDATA;
1306     }
1307     h265->active_sps = sps;
1308
1309     min_cb_log2_size_y = sps->log2_min_luma_coding_block_size_minus3 + 3;
1310     ctb_log2_size_y = min_cb_log2_size_y + sps->log2_diff_max_min_luma_coding_block_size;
1311     ctb_size_y = 1 << ctb_log2_size_y;
1312     pic_width_in_ctbs_y =
1313         (sps->pic_width_in_luma_samples + ctb_size_y - 1) / ctb_size_y;
1314     pic_height_in_ctbs_y =
1315         (sps->pic_height_in_luma_samples + ctb_size_y - 1) / ctb_size_y;
1316     pic_size_in_ctbs_y = pic_width_in_ctbs_y * pic_height_in_ctbs_y;
1317
1318     if (!current->first_slice_segment_in_pic_flag) {
1319         unsigned int address_size = av_log2(pic_size_in_ctbs_y - 1) + 1;
1320         if (pps->dependent_slice_segments_enabled_flag)
1321             flag(dependent_slice_segment_flag);
1322         else
1323             infer(dependent_slice_segment_flag, 0);
1324         u(address_size, slice_segment_address, 0, pic_size_in_ctbs_y - 1);
1325     } else {
1326         infer(dependent_slice_segment_flag, 0);
1327     }
1328
1329     if (!current->dependent_slice_segment_flag) {
1330         for (i = 0; i < pps->num_extra_slice_header_bits; i++)
1331             flags(slice_reserved_flag[i], 1, i);
1332
1333         ue(slice_type, 0, 2);
1334
1335         if (pps->output_flag_present_flag)
1336             flag(pic_output_flag);
1337
1338         if (sps->separate_colour_plane_flag)
1339             u(2, colour_plane_id, 0, 2);
1340
1341         if (current->nal_unit_header.nal_unit_type != HEVC_NAL_IDR_W_RADL &&
1342             current->nal_unit_header.nal_unit_type != HEVC_NAL_IDR_N_LP) {
1343             const H265RawSTRefPicSet *rps;
1344
1345             ub(sps->log2_max_pic_order_cnt_lsb_minus4 + 4, slice_pic_order_cnt_lsb);
1346
1347             flag(short_term_ref_pic_set_sps_flag);
1348             if (!current->short_term_ref_pic_set_sps_flag) {
1349                 CHECK(FUNC(st_ref_pic_set)(ctx, rw, &current->short_term_ref_pic_set,
1350                                            sps->num_short_term_ref_pic_sets, sps));
1351                 rps = &current->short_term_ref_pic_set;
1352             } else if (sps->num_short_term_ref_pic_sets > 1) {
1353                 unsigned int idx_size = av_log2(sps->num_short_term_ref_pic_sets - 1) + 1;
1354                 u(idx_size, short_term_ref_pic_set_idx,
1355                   0, sps->num_short_term_ref_pic_sets - 1);
1356                 rps = &sps->st_ref_pic_set[current->short_term_ref_pic_set_idx];
1357             } else {
1358                 infer(short_term_ref_pic_set_idx, 0);
1359                 rps = &sps->st_ref_pic_set[0];
1360             }
1361
1362             num_pic_total_curr = 0;
1363             for (i = 0; i < rps->num_negative_pics; i++)
1364                 if (rps->used_by_curr_pic_s0_flag[i])
1365                     ++num_pic_total_curr;
1366             for (i = 0; i < rps->num_positive_pics; i++)
1367                 if (rps->used_by_curr_pic_s1_flag[i])
1368                     ++num_pic_total_curr;
1369
1370             if (sps->long_term_ref_pics_present_flag) {
1371                 unsigned int idx_size;
1372
1373                 if (sps->num_long_term_ref_pics_sps > 0) {
1374                     ue(num_long_term_sps, 0, sps->num_long_term_ref_pics_sps);
1375                     idx_size = av_log2(sps->num_long_term_ref_pics_sps - 1) + 1;
1376                 } else {
1377                     infer(num_long_term_sps, 0);
1378                     idx_size = 0;
1379                 }
1380                 ue(num_long_term_pics, 0, HEVC_MAX_LONG_TERM_REF_PICS);
1381
1382                 for (i = 0; i < current->num_long_term_sps +
1383                                 current->num_long_term_pics; i++) {
1384                     if (i < current->num_long_term_sps) {
1385                         if (sps->num_long_term_ref_pics_sps > 1)
1386                             us(idx_size, lt_idx_sps[i],
1387                                0, sps->num_long_term_ref_pics_sps - 1, 1, i);
1388                         if (sps->used_by_curr_pic_lt_sps_flag[current->lt_idx_sps[i]])
1389                             ++num_pic_total_curr;
1390                     } else {
1391                         ubs(sps->log2_max_pic_order_cnt_lsb_minus4 + 4, poc_lsb_lt[i], 1, i);
1392                         flags(used_by_curr_pic_lt_flag[i], 1, i);
1393                         if (current->used_by_curr_pic_lt_flag[i])
1394                             ++num_pic_total_curr;
1395                     }
1396                     flags(delta_poc_msb_present_flag[i], 1, i);
1397                     if (current->delta_poc_msb_present_flag[i])
1398                         ues(delta_poc_msb_cycle_lt[i], 0, UINT32_MAX - 1, 1, i);
1399                     else
1400                         infer(delta_poc_msb_cycle_lt[i], 0);
1401                 }
1402             }
1403
1404             if (sps->sps_temporal_mvp_enabled_flag)
1405                 flag(slice_temporal_mvp_enabled_flag);
1406             else
1407                 infer(slice_temporal_mvp_enabled_flag, 0);
1408
1409             if (pps->pps_curr_pic_ref_enabled_flag)
1410                 ++num_pic_total_curr;
1411         }
1412
1413         if (sps->sample_adaptive_offset_enabled_flag) {
1414             flag(slice_sao_luma_flag);
1415             if (!sps->separate_colour_plane_flag && sps->chroma_format_idc != 0)
1416                 flag(slice_sao_chroma_flag);
1417             else
1418                 infer(slice_sao_chroma_flag, 0);
1419         } else {
1420             infer(slice_sao_luma_flag,   0);
1421             infer(slice_sao_chroma_flag, 0);
1422         }
1423
1424         if (current->slice_type == HEVC_SLICE_P ||
1425             current->slice_type == HEVC_SLICE_B) {
1426             flag(num_ref_idx_active_override_flag);
1427             if (current->num_ref_idx_active_override_flag) {
1428                 ue(num_ref_idx_l0_active_minus1, 0, 14);
1429                 if (current->slice_type == HEVC_SLICE_B)
1430                     ue(num_ref_idx_l1_active_minus1, 0, 14);
1431                 else
1432                     infer(num_ref_idx_l1_active_minus1, pps->num_ref_idx_l1_default_active_minus1);
1433             } else {
1434                 infer(num_ref_idx_l0_active_minus1, pps->num_ref_idx_l0_default_active_minus1);
1435                 infer(num_ref_idx_l1_active_minus1, pps->num_ref_idx_l1_default_active_minus1);
1436             }
1437
1438             if (pps->lists_modification_present_flag && num_pic_total_curr > 1)
1439                 CHECK(FUNC(ref_pic_lists_modification)(ctx, rw, current,
1440                                                        num_pic_total_curr));
1441
1442             if (current->slice_type == HEVC_SLICE_B)
1443                 flag(mvd_l1_zero_flag);
1444             if (pps->cabac_init_present_flag)
1445                 flag(cabac_init_flag);
1446             else
1447                 infer(cabac_init_flag, 0);
1448             if (current->slice_temporal_mvp_enabled_flag) {
1449                 if (current->slice_type == HEVC_SLICE_B)
1450                     flag(collocated_from_l0_flag);
1451                 else
1452                     infer(collocated_from_l0_flag, 1);
1453                 if (current->collocated_from_l0_flag) {
1454                     if (current->num_ref_idx_l0_active_minus1 > 0)
1455                         ue(collocated_ref_idx, 0, current->num_ref_idx_l0_active_minus1);
1456                     else
1457                         infer(collocated_ref_idx, 0);
1458                 } else {
1459                     if (current->num_ref_idx_l1_active_minus1 > 0)
1460                         ue(collocated_ref_idx, 0, current->num_ref_idx_l1_active_minus1);
1461                     else
1462                         infer(collocated_ref_idx, 0);
1463                 }
1464             }
1465
1466             if ((pps->weighted_pred_flag   && current->slice_type == HEVC_SLICE_P) ||
1467                 (pps->weighted_bipred_flag && current->slice_type == HEVC_SLICE_B))
1468                 CHECK(FUNC(pred_weight_table)(ctx, rw, current));
1469
1470             ue(five_minus_max_num_merge_cand, 0, 4);
1471             if (sps->motion_vector_resolution_control_idc == 2)
1472                 flag(use_integer_mv_flag);
1473             else
1474                 infer(use_integer_mv_flag, sps->motion_vector_resolution_control_idc);
1475         }
1476
1477         se(slice_qp_delta,
1478            - 6 * sps->bit_depth_luma_minus8 - (pps->init_qp_minus26 + 26),
1479            + 51 - (pps->init_qp_minus26 + 26));
1480         if (pps->pps_slice_chroma_qp_offsets_present_flag) {
1481             se(slice_cb_qp_offset, -12, +12);
1482             se(slice_cr_qp_offset, -12, +12);
1483         } else {
1484             infer(slice_cb_qp_offset, 0);
1485             infer(slice_cr_qp_offset, 0);
1486         }
1487         if (pps->pps_slice_act_qp_offsets_present_flag) {
1488             se(slice_act_y_qp_offset,
1489                -12 - (pps->pps_act_y_qp_offset_plus5 - 5),
1490                +12 - (pps->pps_act_y_qp_offset_plus5 - 5));
1491             se(slice_act_cb_qp_offset,
1492                -12 - (pps->pps_act_cb_qp_offset_plus5 - 5),
1493                +12 - (pps->pps_act_cb_qp_offset_plus5 - 5));
1494             se(slice_act_cr_qp_offset,
1495                -12 - (pps->pps_act_cr_qp_offset_plus3 - 3),
1496                +12 - (pps->pps_act_cr_qp_offset_plus3 - 3));
1497         } else {
1498             infer(slice_act_y_qp_offset,  0);
1499             infer(slice_act_cb_qp_offset, 0);
1500             infer(slice_act_cr_qp_offset, 0);
1501         }
1502         if (pps->chroma_qp_offset_list_enabled_flag)
1503             flag(cu_chroma_qp_offset_enabled_flag);
1504         else
1505             infer(cu_chroma_qp_offset_enabled_flag, 0);
1506
1507         if (pps->deblocking_filter_override_enabled_flag)
1508             flag(deblocking_filter_override_flag);
1509         else
1510             infer(deblocking_filter_override_flag, 0);
1511         if (current->deblocking_filter_override_flag) {
1512             flag(slice_deblocking_filter_disabled_flag);
1513             if (!current->slice_deblocking_filter_disabled_flag) {
1514                 se(slice_beta_offset_div2, -6, +6);
1515                 se(slice_tc_offset_div2,   -6, +6);
1516             } else {
1517                 infer(slice_beta_offset_div2, pps->pps_beta_offset_div2);
1518                 infer(slice_tc_offset_div2,   pps->pps_tc_offset_div2);
1519             }
1520         } else {
1521             infer(slice_deblocking_filter_disabled_flag,
1522                   pps->pps_deblocking_filter_disabled_flag);
1523             infer(slice_beta_offset_div2, pps->pps_beta_offset_div2);
1524             infer(slice_tc_offset_div2,   pps->pps_tc_offset_div2);
1525         }
1526         if (pps->pps_loop_filter_across_slices_enabled_flag &&
1527             (current->slice_sao_luma_flag || current->slice_sao_chroma_flag ||
1528              !current->slice_deblocking_filter_disabled_flag))
1529             flag(slice_loop_filter_across_slices_enabled_flag);
1530         else
1531             infer(slice_loop_filter_across_slices_enabled_flag,
1532                   pps->pps_loop_filter_across_slices_enabled_flag);
1533     }
1534
1535     if (pps->tiles_enabled_flag || pps->entropy_coding_sync_enabled_flag) {
1536         unsigned int num_entry_point_offsets_limit;
1537         if (!pps->tiles_enabled_flag && pps->entropy_coding_sync_enabled_flag)
1538             num_entry_point_offsets_limit = pic_height_in_ctbs_y - 1;
1539         else if (pps->tiles_enabled_flag && !pps->entropy_coding_sync_enabled_flag)
1540             num_entry_point_offsets_limit =
1541                 (pps->num_tile_columns_minus1 + 1) * (pps->num_tile_rows_minus1 + 1);
1542         else
1543             num_entry_point_offsets_limit =
1544                 (pps->num_tile_columns_minus1 + 1) * pic_height_in_ctbs_y - 1;
1545         ue(num_entry_point_offsets, 0, num_entry_point_offsets_limit);
1546
1547         if (current->num_entry_point_offsets > HEVC_MAX_ENTRY_POINT_OFFSETS) {
1548             av_log(ctx->log_ctx, AV_LOG_ERROR, "Too many entry points: "
1549                    "%"PRIu16".\n", current->num_entry_point_offsets);
1550             return AVERROR_PATCHWELCOME;
1551         }
1552
1553         if (current->num_entry_point_offsets > 0) {
1554             ue(offset_len_minus1, 0, 31);
1555             for (i = 0; i < current->num_entry_point_offsets; i++)
1556                 ubs(current->offset_len_minus1 + 1, entry_point_offset_minus1[i], 1, i);
1557         }
1558     }
1559
1560     if (pps->slice_segment_header_extension_present_flag) {
1561         ue(slice_segment_header_extension_length, 0, 256);
1562         for (i = 0; i < current->slice_segment_header_extension_length; i++)
1563             us(8, slice_segment_header_extension_data_byte[i], 0x00, 0xff, 1, i);
1564     }
1565
1566     CHECK(FUNC(byte_alignment)(ctx, rw));
1567
1568     return 0;
1569 }
1570
1571 static int FUNC(sei_buffering_period)(CodedBitstreamContext *ctx, RWContext *rw,
1572                                       H265RawSEIBufferingPeriod *current,
1573                                       uint32_t *payload_size,
1574                                       int *more_data)
1575 {
1576     CodedBitstreamH265Context *h265 = ctx->priv_data;
1577     const H265RawSPS *sps;
1578     const H265RawHRDParameters *hrd;
1579     int err, i, length;
1580
1581 #ifdef READ
1582     int start_pos, end_pos;
1583     start_pos = get_bits_count(rw);
1584 #endif
1585
1586     HEADER("Buffering Period");
1587
1588     ue(bp_seq_parameter_set_id, 0, HEVC_MAX_SPS_COUNT - 1);
1589
1590     sps = h265->sps[current->bp_seq_parameter_set_id];
1591     if (!sps) {
1592         av_log(ctx->log_ctx, AV_LOG_ERROR, "SPS id %d not available.\n",
1593                current->bp_seq_parameter_set_id);
1594         return AVERROR_INVALIDDATA;
1595     }
1596     h265->active_sps = sps;
1597
1598     if (!sps->vui_parameters_present_flag ||
1599         !sps->vui.vui_hrd_parameters_present_flag) {
1600         av_log(ctx->log_ctx, AV_LOG_ERROR, "Buffering period SEI requires "
1601                "HRD parameters to be present in SPS.\n");
1602         return AVERROR_INVALIDDATA;
1603     }
1604     hrd = &sps->vui.hrd_parameters;
1605     if (!hrd->nal_hrd_parameters_present_flag &&
1606         !hrd->vcl_hrd_parameters_present_flag) {
1607         av_log(ctx->log_ctx, AV_LOG_ERROR, "Buffering period SEI requires "
1608                "NAL or VCL HRD parameters to be present.\n");
1609         return AVERROR_INVALIDDATA;
1610     }
1611
1612     if (!hrd->sub_pic_hrd_params_present_flag)
1613         flag(irap_cpb_params_present_flag);
1614     else
1615         infer(irap_cpb_params_present_flag, 0);
1616     if (current->irap_cpb_params_present_flag) {
1617         length = hrd->au_cpb_removal_delay_length_minus1 + 1;
1618         ub(length, cpb_delay_offset);
1619         length = hrd->dpb_output_delay_length_minus1 + 1;
1620         ub(length, dpb_delay_offset);
1621     } else {
1622         infer(cpb_delay_offset, 0);
1623         infer(dpb_delay_offset, 0);
1624     }
1625
1626     flag(concatenation_flag);
1627
1628     length = hrd->au_cpb_removal_delay_length_minus1 + 1;
1629     ub(length, au_cpb_removal_delay_delta_minus1);
1630
1631     if (hrd->nal_hrd_parameters_present_flag) {
1632         for (i = 0; i <= hrd->cpb_cnt_minus1[0]; i++) {
1633             length = hrd->initial_cpb_removal_delay_length_minus1 + 1;
1634
1635             ubs(length, nal_initial_cpb_removal_delay[i], 1, i);
1636             ubs(length, nal_initial_cpb_removal_offset[i], 1, i);
1637
1638             if (hrd->sub_pic_hrd_params_present_flag ||
1639                 current->irap_cpb_params_present_flag) {
1640                 ubs(length, nal_initial_alt_cpb_removal_delay[i], 1, i);
1641                 ubs(length, nal_initial_alt_cpb_removal_offset[i], 1, i);
1642             }
1643         }
1644     }
1645     if (hrd->vcl_hrd_parameters_present_flag) {
1646         for (i = 0; i <= hrd->cpb_cnt_minus1[0]; i++) {
1647             length = hrd->initial_cpb_removal_delay_length_minus1 + 1;
1648
1649             ubs(length, vcl_initial_cpb_removal_delay[i], 1, i);
1650             ubs(length, vcl_initial_cpb_removal_offset[i], 1, i);
1651
1652             if (hrd->sub_pic_hrd_params_present_flag ||
1653                 current->irap_cpb_params_present_flag) {
1654                 ubs(length, vcl_initial_alt_cpb_removal_delay[i], 1, i);
1655                 ubs(length, vcl_initial_alt_cpb_removal_offset[i], 1, i);
1656             }
1657         }
1658     }
1659
1660 #ifdef READ
1661     end_pos = get_bits_count(rw);
1662     if (cbs_h265_payload_extension_present(rw, *payload_size,
1663                                            end_pos - start_pos))
1664         flag(use_alt_cpb_params_flag);
1665     else
1666         infer(use_alt_cpb_params_flag, 0);
1667 #else
1668     // If unknown extension data exists, then use_alt_cpb_params_flag is
1669     // coded in the bitstream and must be written even if it's 0.
1670     if (current->use_alt_cpb_params_flag || *more_data) {
1671         flag(use_alt_cpb_params_flag);
1672         // Ensure this bit is not the last in the payload by making the
1673         // more_data_in_payload() check evaluate to true, so it may not
1674         // be mistaken as something else by decoders.
1675         *more_data = 1;
1676     }
1677 #endif
1678
1679     return 0;
1680 }
1681
1682 static int FUNC(sei_pic_timing)(CodedBitstreamContext *ctx, RWContext *rw,
1683                                 H265RawSEIPicTiming *current)
1684 {
1685     CodedBitstreamH265Context *h265 = ctx->priv_data;
1686     const H265RawSPS *sps;
1687     const H265RawHRDParameters *hrd;
1688     int err, expected_source_scan_type, i, length;
1689
1690     HEADER("Picture Timing");
1691
1692     sps = h265->active_sps;
1693     if (!sps) {
1694         av_log(ctx->log_ctx, AV_LOG_ERROR,
1695                "No active SPS for pic_timing.\n");
1696         return AVERROR_INVALIDDATA;
1697     }
1698
1699     expected_source_scan_type = 2 -
1700         2 * sps->profile_tier_level.general_interlaced_source_flag -
1701         sps->profile_tier_level.general_progressive_source_flag;
1702
1703     if (sps->vui.frame_field_info_present_flag) {
1704         u(4, pic_struct, 0, 12);
1705         u(2, source_scan_type,
1706           expected_source_scan_type >= 0 ? expected_source_scan_type : 0,
1707           expected_source_scan_type >= 0 ? expected_source_scan_type : 2);
1708         flag(duplicate_flag);
1709     } else {
1710         infer(pic_struct, 0);
1711         infer(source_scan_type,
1712               expected_source_scan_type >= 0 ? expected_source_scan_type : 2);
1713         infer(duplicate_flag, 0);
1714     }
1715
1716     if (sps->vui_parameters_present_flag &&
1717         sps->vui.vui_hrd_parameters_present_flag)
1718         hrd = &sps->vui.hrd_parameters;
1719     else
1720         hrd = NULL;
1721     if (hrd && (hrd->nal_hrd_parameters_present_flag ||
1722                 hrd->vcl_hrd_parameters_present_flag)) {
1723         length = hrd->au_cpb_removal_delay_length_minus1 + 1;
1724         ub(length, au_cpb_removal_delay_minus1);
1725
1726         length = hrd->dpb_output_delay_length_minus1 + 1;
1727         ub(length, pic_dpb_output_delay);
1728
1729         if (hrd->sub_pic_hrd_params_present_flag) {
1730             length = hrd->dpb_output_delay_du_length_minus1 + 1;
1731             ub(length, pic_dpb_output_du_delay);
1732         }
1733
1734         if (hrd->sub_pic_hrd_params_present_flag &&
1735             hrd->sub_pic_cpb_params_in_pic_timing_sei_flag) {
1736             // Each decoding unit must contain at least one slice segment.
1737             ue(num_decoding_units_minus1, 0, HEVC_MAX_SLICE_SEGMENTS);
1738             flag(du_common_cpb_removal_delay_flag);
1739
1740             length = hrd->du_cpb_removal_delay_increment_length_minus1 + 1;
1741             if (current->du_common_cpb_removal_delay_flag)
1742                 ub(length, du_common_cpb_removal_delay_increment_minus1);
1743
1744             for (i = 0; i <= current->num_decoding_units_minus1; i++) {
1745                 ues(num_nalus_in_du_minus1[i],
1746                     0, HEVC_MAX_SLICE_SEGMENTS, 1, i);
1747                 if (!current->du_common_cpb_removal_delay_flag &&
1748                     i < current->num_decoding_units_minus1)
1749                     ubs(length, du_cpb_removal_delay_increment_minus1[i], 1, i);
1750             }
1751         }
1752     }
1753
1754     return 0;
1755 }
1756
1757 static int FUNC(sei_pan_scan_rect)(CodedBitstreamContext *ctx, RWContext *rw,
1758                                    H265RawSEIPanScanRect *current)
1759 {
1760     int err, i;
1761
1762     HEADER("Pan-Scan Rectangle");
1763
1764     ue(pan_scan_rect_id, 0, UINT32_MAX - 1);
1765     flag(pan_scan_rect_cancel_flag);
1766
1767     if (!current->pan_scan_rect_cancel_flag) {
1768         ue(pan_scan_cnt_minus1, 0, 2);
1769
1770         for (i = 0; i <= current->pan_scan_cnt_minus1; i++) {
1771             ses(pan_scan_rect_left_offset[i],   INT32_MIN + 1, INT32_MAX, 1, i);
1772             ses(pan_scan_rect_right_offset[i],  INT32_MIN + 1, INT32_MAX, 1, i);
1773             ses(pan_scan_rect_top_offset[i],    INT32_MIN + 1, INT32_MAX, 1, i);
1774             ses(pan_scan_rect_bottom_offset[i], INT32_MIN + 1, INT32_MAX, 1, i);
1775         }
1776
1777         flag(pan_scan_rect_persistence_flag);
1778     }
1779
1780     return 0;
1781 }
1782
1783 static int FUNC(sei_user_data_registered)(CodedBitstreamContext *ctx, RWContext *rw,
1784                                           H265RawSEIUserDataRegistered *current,
1785                                           uint32_t *payload_size)
1786 {
1787     int err, i, j;
1788
1789     HEADER("User Data Registered ITU-T T.35");
1790
1791     u(8, itu_t_t35_country_code, 0x00, 0xff);
1792     if (current->itu_t_t35_country_code != 0xff)
1793         i = 1;
1794     else {
1795         u(8, itu_t_t35_country_code_extension_byte, 0x00, 0xff);
1796         i = 2;
1797     }
1798
1799 #ifdef READ
1800     if (*payload_size < i) {
1801         av_log(ctx->log_ctx, AV_LOG_ERROR,
1802                "Invalid SEI user data registered payload.\n");
1803         return AVERROR_INVALIDDATA;
1804     }
1805     current->data_length = *payload_size - i;
1806 #else
1807     *payload_size = i + current->data_length;
1808 #endif
1809
1810     allocate(current->data, current->data_length);
1811     for (j = 0; j < current->data_length; j++)
1812         xu(8, itu_t_t35_payload_byte[i], current->data[j], 0x00, 0xff, 1, i + j);
1813
1814     return 0;
1815 }
1816
1817 static int FUNC(sei_user_data_unregistered)(CodedBitstreamContext *ctx, RWContext *rw,
1818                                             H265RawSEIUserDataUnregistered *current,
1819                                             uint32_t *payload_size)
1820 {
1821     int err, i;
1822
1823     HEADER("User Data Unregistered");
1824
1825 #ifdef READ
1826     if (*payload_size < 16) {
1827         av_log(ctx->log_ctx, AV_LOG_ERROR,
1828                "Invalid SEI user data unregistered payload.\n");
1829         return AVERROR_INVALIDDATA;
1830     }
1831     current->data_length = *payload_size - 16;
1832 #else
1833     *payload_size = 16 + current->data_length;
1834 #endif
1835
1836     for (i = 0; i < 16; i++)
1837         us(8, uuid_iso_iec_11578[i], 0x00, 0xff, 1, i);
1838
1839     allocate(current->data, current->data_length);
1840
1841     for (i = 0; i < current->data_length; i++)
1842         xu(8, user_data_payload_byte[i], current->data[i], 0x00, 0xff, 1, i);
1843
1844     return 0;
1845 }
1846
1847 static int FUNC(sei_recovery_point)(CodedBitstreamContext *ctx, RWContext *rw,
1848                                     H265RawSEIRecoveryPoint *current)
1849 {
1850     int err;
1851
1852     HEADER("Recovery Point");
1853
1854     se(recovery_poc_cnt, -32768, 32767);
1855
1856     flag(exact_match_flag);
1857     flag(broken_link_flag);
1858
1859     return 0;
1860 }
1861
1862 static int FUNC(sei_display_orientation)(CodedBitstreamContext *ctx, RWContext *rw,
1863                                          H265RawSEIDisplayOrientation *current)
1864 {
1865     int err;
1866
1867     HEADER("Display Orientation");
1868
1869     flag(display_orientation_cancel_flag);
1870     if (!current->display_orientation_cancel_flag) {
1871         flag(hor_flip);
1872         flag(ver_flip);
1873         ub(16, anticlockwise_rotation);
1874         flag(display_orientation_persistence_flag);
1875     }
1876
1877     return 0;
1878 }
1879
1880 static int FUNC(sei_active_parameter_sets)(CodedBitstreamContext *ctx, RWContext *rw,
1881                                            H265RawSEIActiveParameterSets *current)
1882 {
1883     CodedBitstreamH265Context *h265 = ctx->priv_data;
1884     const H265RawVPS *vps;
1885     int err, i;
1886
1887     HEADER("Active Parameter Sets");
1888
1889     u(4, active_video_parameter_set_id, 0, HEVC_MAX_VPS_COUNT);
1890     vps = h265->vps[current->active_video_parameter_set_id];
1891     if (!vps) {
1892         av_log(ctx->log_ctx, AV_LOG_ERROR, "VPS id %d not available for active "
1893                "parameter sets.\n", current->active_video_parameter_set_id);
1894         return AVERROR_INVALIDDATA;
1895     }
1896     h265->active_vps = vps;
1897
1898     flag(self_contained_cvs_flag);
1899     flag(no_parameter_set_update_flag);
1900
1901     ue(num_sps_ids_minus1, 0, HEVC_MAX_SPS_COUNT - 1);
1902     for (i = 0; i <= current->num_sps_ids_minus1; i++)
1903         ues(active_seq_parameter_set_id[i], 0, HEVC_MAX_SPS_COUNT - 1, 1, i);
1904
1905     for (i = vps->vps_base_layer_internal_flag;
1906          i <= FFMIN(62, vps->vps_max_layers_minus1); i++) {
1907         ues(layer_sps_idx[i], 0, current->num_sps_ids_minus1, 1, i);
1908
1909         if (i == 0)
1910             h265->active_sps = h265->sps[current->active_seq_parameter_set_id[current->layer_sps_idx[0]]];
1911     }
1912
1913     return 0;
1914 }
1915
1916 static int FUNC(sei_decoded_picture_hash)(CodedBitstreamContext *ctx, RWContext *rw,
1917                                           H265RawSEIDecodedPictureHash *current)
1918 {
1919     CodedBitstreamH265Context *h265 = ctx->priv_data;
1920     const H265RawSPS *sps = h265->active_sps;
1921     int err, c, i;
1922
1923     HEADER("Decoded Picture Hash");
1924
1925     if (!sps) {
1926         av_log(ctx->log_ctx, AV_LOG_ERROR,
1927                "No active SPS for decoded picture hash.\n");
1928         return AVERROR_INVALIDDATA;
1929     }
1930
1931     u(8, hash_type, 0, 2);
1932
1933     for (c = 0; c < (sps->chroma_format_idc == 0 ? 1 : 3); c++) {
1934         if (current->hash_type == 0) {
1935             for (i = 0; i < 16; i++)
1936                 us(8, picture_md5[c][i], 0x00, 0xff, 2, c, i);
1937         } else if (current->hash_type == 1) {
1938             us(16, picture_crc[c], 0x0000, 0xffff, 1, c);
1939         } else if (current->hash_type == 2) {
1940             us(32, picture_checksum[c], 0x00000000, 0xffffffff, 1, c);
1941         }
1942     }
1943
1944     return 0;
1945 }
1946
1947 static int FUNC(sei_time_code)(CodedBitstreamContext *ctx, RWContext *rw,
1948                                H265RawSEITimeCode *current)
1949 {
1950     int err, i;
1951
1952     HEADER("Time Code");
1953
1954     u(2, num_clock_ts, 1, 3);
1955
1956     for (i = 0; i < current->num_clock_ts; i++) {
1957         flags(clock_timestamp_flag[i],   1, i);
1958
1959         if (current->clock_timestamp_flag[i]) {
1960             flags(units_field_based_flag[i], 1, i);
1961             us(5, counting_type[i], 0, 6,    1, i);
1962             flags(full_timestamp_flag[i],    1, i);
1963             flags(discontinuity_flag[i],     1, i);
1964             flags(cnt_dropped_flag[i],       1, i);
1965
1966             ubs(9, n_frames[i], 1, i);
1967
1968             if (current->full_timestamp_flag[i]) {
1969                 us(6, seconds_value[i], 0, 59, 1, i);
1970                 us(6, minutes_value[i], 0, 59, 1, i);
1971                 us(5, hours_value[i],   0, 23, 1, i);
1972             } else {
1973                 flags(seconds_flag[i], 1, i);
1974                 if (current->seconds_flag[i]) {
1975                     us(6, seconds_value[i], 0, 59, 1, i);
1976                     flags(minutes_flag[i], 1, i);
1977                     if (current->minutes_flag[i]) {
1978                         us(6, minutes_value[i], 0, 59, 1, i);
1979                         flags(hours_flag[i], 1, i);
1980                         if (current->hours_flag[i])
1981                             us(5, hours_value[i], 0, 23, 1, i);
1982                     }
1983                 }
1984             }
1985
1986             ubs(5, time_offset_length[i], 1, i);
1987             if (current->time_offset_length[i] > 0)
1988                 ibs(current->time_offset_length[i], time_offset_value[i], 1, i);
1989             else
1990                 infer(time_offset_value[i], 0);
1991         }
1992     }
1993
1994     return 0;
1995 }
1996
1997 static int FUNC(sei_mastering_display)(CodedBitstreamContext *ctx, RWContext *rw,
1998                                        H265RawSEIMasteringDisplayColourVolume *current)
1999 {
2000     int err, c;
2001
2002     HEADER("Mastering Display Colour Volume");
2003
2004     for (c = 0; c < 3; c++) {
2005         us(16, display_primaries_x[c], 0, 50000, 1, c);
2006         us(16, display_primaries_y[c], 0, 50000, 1, c);
2007     }
2008
2009     u(16, white_point_x, 0, 50000);
2010     u(16, white_point_y, 0, 50000);
2011
2012     u(32, max_display_mastering_luminance,
2013       1, MAX_UINT_BITS(32));
2014     u(32, min_display_mastering_luminance,
2015       0, current->max_display_mastering_luminance - 1);
2016
2017     return 0;
2018 }
2019
2020 static int FUNC(sei_content_light_level)(CodedBitstreamContext *ctx, RWContext *rw,
2021                                          H265RawSEIContentLightLevelInfo *current)
2022 {
2023     int err;
2024
2025     HEADER("Content Light Level");
2026
2027     ub(16, max_content_light_level);
2028     ub(16, max_pic_average_light_level);
2029
2030     return 0;
2031 }
2032
2033 static int FUNC(sei_alternative_transfer_characteristics)(CodedBitstreamContext *ctx,
2034                                                           RWContext *rw,
2035                                                           H265RawSEIAlternativeTransferCharacteristics *current)
2036 {
2037     int err;
2038
2039     HEADER("Alternative Transfer Characteristics");
2040
2041     ub(8, preferred_transfer_characteristics);
2042
2043     return 0;
2044 }
2045
2046 static int FUNC(sei_alpha_channel_info)(CodedBitstreamContext *ctx,
2047                                         RWContext *rw,
2048                                         H265RawSEIAlphaChannelInfo *current)
2049 {
2050     int err, length;
2051
2052     HEADER("Alpha Channel Information");
2053
2054     flag(alpha_channel_cancel_flag);
2055     if (!current->alpha_channel_cancel_flag) {
2056         ub(3, alpha_channel_use_idc);
2057         ub(3, alpha_channel_bit_depth_minus8);
2058         length = current->alpha_channel_bit_depth_minus8 + 9;
2059         ub(length, alpha_transparent_value);
2060         ub(length, alpha_opaque_value);
2061         flag(alpha_channel_incr_flag);
2062         flag(alpha_channel_clip_flag);
2063         if (current->alpha_channel_clip_flag)
2064             flag(alpha_channel_clip_type_flag);
2065     } else {
2066        infer(alpha_channel_use_idc,   2);
2067        infer(alpha_channel_incr_flag, 0);
2068        infer(alpha_channel_clip_flag, 0);
2069     }
2070
2071     return 0;
2072 }
2073
2074 static int FUNC(payload_extension)(CodedBitstreamContext *ctx, RWContext *rw,
2075                                    H265RawExtensionData *current, uint32_t payload_size,
2076                                    int cur_pos)
2077 {
2078     int err;
2079     size_t byte_length, k;
2080
2081 #ifdef READ
2082     GetBitContext tmp;
2083     int bits_left, payload_zero_bits;
2084
2085     if (!cbs_h265_payload_extension_present(rw, payload_size, cur_pos))
2086         return 0;
2087
2088     bits_left = 8 * payload_size - cur_pos;
2089     tmp = *rw;
2090     if (bits_left > 8)
2091         skip_bits_long(&tmp, bits_left - 8);
2092     payload_zero_bits = get_bits(&tmp, FFMIN(bits_left, 8));
2093     if (!payload_zero_bits)
2094         return AVERROR_INVALIDDATA;
2095     payload_zero_bits = ff_ctz(payload_zero_bits);
2096     current->bit_length = bits_left - payload_zero_bits - 1;
2097     allocate(current->data, (current->bit_length + 7) / 8);
2098 #endif
2099
2100     byte_length = (current->bit_length + 7) / 8;
2101     for (k = 0; k < byte_length; k++) {
2102         int length = FFMIN(current->bit_length - k * 8, 8);
2103         xu(length, reserved_payload_extension_data, current->data[k],
2104            0, MAX_UINT_BITS(length), 0);
2105     }
2106
2107     return 0;
2108 }
2109
2110 static int FUNC(sei_payload)(CodedBitstreamContext *ctx, RWContext *rw,
2111                              H265RawSEIPayload *current, int prefix)
2112 {
2113     int err, i;
2114     int start_position, current_position;
2115     int more_data = !!current->extension_data.bit_length;
2116
2117 #ifdef READ
2118     start_position = get_bits_count(rw);
2119 #else
2120     start_position = put_bits_count(rw);
2121 #endif
2122
2123     switch (current->payload_type) {
2124 #define SEI_TYPE_CHECK_VALID(name, prefix_valid, suffix_valid) do { \
2125             if (prefix && !prefix_valid) { \
2126                 av_log(ctx->log_ctx, AV_LOG_ERROR, "SEI type %s invalid " \
2127                        "as prefix SEI!\n", #name); \
2128                 return AVERROR_INVALIDDATA; \
2129             } \
2130             if (!prefix && !suffix_valid) { \
2131                 av_log(ctx->log_ctx, AV_LOG_ERROR, "SEI type %s invalid " \
2132                        "as suffix SEI!\n", #name); \
2133                 return AVERROR_INVALIDDATA; \
2134             } \
2135         } while (0)
2136 #define SEI_TYPE_N(type, prefix_valid, suffix_valid, name) \
2137     case HEVC_SEI_TYPE_ ## type: \
2138         SEI_TYPE_CHECK_VALID(name, prefix_valid, suffix_valid); \
2139         CHECK(FUNC(sei_ ## name)(ctx, rw, &current->payload.name)); \
2140         break
2141 #define SEI_TYPE_S(type, prefix_valid, suffix_valid, name) \
2142     case HEVC_SEI_TYPE_ ## type: \
2143         SEI_TYPE_CHECK_VALID(name, prefix_valid, suffix_valid); \
2144         CHECK(FUNC(sei_ ## name)(ctx, rw, &current->payload.name, \
2145                                  &current->payload_size)); \
2146         break
2147 #define SEI_TYPE_E(type, prefix_valid, suffix_valid, name) \
2148     case HEVC_SEI_TYPE_ ## type: \
2149         SEI_TYPE_CHECK_VALID(name, prefix_valid, suffix_valid); \
2150         CHECK(FUNC(sei_ ## name)(ctx, rw, &current->payload.name, \
2151                                  &current->payload_size, \
2152                                  &more_data)); \
2153         break
2154
2155         SEI_TYPE_E(BUFFERING_PERIOD,         1, 0, buffering_period);
2156         SEI_TYPE_N(PICTURE_TIMING,           1, 0, pic_timing);
2157         SEI_TYPE_N(PAN_SCAN_RECT,            1, 0, pan_scan_rect);
2158         SEI_TYPE_S(USER_DATA_REGISTERED_ITU_T_T35,
2159                                              1, 1, user_data_registered);
2160         SEI_TYPE_S(USER_DATA_UNREGISTERED,   1, 1, user_data_unregistered);
2161         SEI_TYPE_N(RECOVERY_POINT,           1, 0, recovery_point);
2162         SEI_TYPE_N(DISPLAY_ORIENTATION,      1, 0, display_orientation);
2163         SEI_TYPE_N(ACTIVE_PARAMETER_SETS,    1, 0, active_parameter_sets);
2164         SEI_TYPE_N(DECODED_PICTURE_HASH,     0, 1, decoded_picture_hash);
2165         SEI_TYPE_N(TIME_CODE,                1, 0, time_code);
2166         SEI_TYPE_N(MASTERING_DISPLAY_INFO,   1, 0, mastering_display);
2167         SEI_TYPE_N(CONTENT_LIGHT_LEVEL_INFO, 1, 0, content_light_level);
2168         SEI_TYPE_N(ALTERNATIVE_TRANSFER_CHARACTERISTICS,
2169                                              1, 0, alternative_transfer_characteristics);
2170         SEI_TYPE_N(ALPHA_CHANNEL_INFO,       1, 0, alpha_channel_info);
2171
2172 #undef SEI_TYPE
2173     default:
2174         {
2175 #ifdef READ
2176             current->payload.other.data_length = current->payload_size;
2177 #endif
2178             allocate(current->payload.other.data, current->payload.other.data_length);
2179
2180             for (i = 0; i < current->payload_size; i++)
2181                 xu(8, payload_byte[i], current->payload.other.data[i], 0, 255,
2182                    1, i);
2183         }
2184     }
2185
2186     // more_data_in_payload()
2187 #ifdef READ
2188     current_position = get_bits_count(rw) - start_position;
2189     if (current_position < 8 * current->payload_size) {
2190 #else
2191     current_position = put_bits_count(rw) - start_position;
2192     if (byte_alignment(rw) || more_data) {
2193 #endif
2194         CHECK(FUNC(payload_extension)(ctx, rw, &current->extension_data,
2195                                       current->payload_size, current_position));
2196         fixed(1, bit_equal_to_one, 1);
2197         while (byte_alignment(rw))
2198             fixed(1, bit_equal_to_zero, 0);
2199     }
2200
2201 #ifdef WRITE
2202     current->payload_size = (put_bits_count(rw) - start_position) >> 3;
2203 #endif
2204
2205     return 0;
2206 }
2207
2208 static int FUNC(sei)(CodedBitstreamContext *ctx, RWContext *rw,
2209                      H265RawSEI *current, int prefix)
2210 {
2211     int err, k;
2212
2213     if (prefix)
2214         HEADER("Prefix Supplemental Enhancement Information");
2215     else
2216         HEADER("Suffix Supplemental Enhancement Information");
2217
2218     CHECK(FUNC(nal_unit_header)(ctx, rw, &current->nal_unit_header,
2219                                 prefix ? HEVC_NAL_SEI_PREFIX
2220                                        : HEVC_NAL_SEI_SUFFIX));
2221
2222 #ifdef READ
2223     for (k = 0; k < H265_MAX_SEI_PAYLOADS; k++) {
2224         uint32_t payload_type = 0;
2225         uint32_t payload_size = 0;
2226         uint32_t tmp;
2227
2228         while (show_bits(rw, 8) == 0xff) {
2229             fixed(8, ff_byte, 0xff);
2230             payload_type += 255;
2231         }
2232         xu(8, last_payload_type_byte, tmp, 0, 254, 0);
2233         payload_type += tmp;
2234
2235         while (show_bits(rw, 8) == 0xff) {
2236             fixed(8, ff_byte, 0xff);
2237             payload_size += 255;
2238         }
2239         xu(8, last_payload_size_byte, tmp, 0, 254, 0);
2240         payload_size += tmp;
2241
2242         current->payload[k].payload_type = payload_type;
2243         current->payload[k].payload_size = payload_size;
2244
2245         current->payload_count++;
2246         CHECK(FUNC(sei_payload)(ctx, rw, &current->payload[k], prefix));
2247
2248         if (!cbs_h2645_read_more_rbsp_data(rw))
2249             break;
2250     }
2251     if (k >= H265_MAX_SEI_PAYLOADS) {
2252         av_log(ctx->log_ctx, AV_LOG_ERROR, "Too many payloads in "
2253                "SEI message: found %d.\n", k);
2254         return AVERROR_INVALIDDATA;
2255     }
2256 #else
2257     for (k = 0; k < current->payload_count; k++) {
2258         PutBitContext start_state;
2259         uint32_t tmp;
2260         int need_size, i;
2261
2262         // Somewhat clumsy: we write the payload twice when
2263         // we don't know the size in advance.  This will mess
2264         // with trace output, but is otherwise harmless.
2265         start_state = *rw;
2266         need_size = !current->payload[k].payload_size;
2267         for (i = 0; i < 1 + need_size; i++) {
2268             *rw = start_state;
2269
2270             tmp = current->payload[k].payload_type;
2271             while (tmp >= 255) {
2272                 fixed(8, ff_byte, 0xff);
2273                 tmp -= 255;
2274             }
2275             xu(8, last_payload_type_byte, tmp, 0, 254, 0);
2276
2277             tmp = current->payload[k].payload_size;
2278             while (tmp >= 255) {
2279                 fixed(8, ff_byte, 0xff);
2280                 tmp -= 255;
2281             }
2282             xu(8, last_payload_size_byte, tmp, 0, 254, 0);
2283
2284             CHECK(FUNC(sei_payload)(ctx, rw, &current->payload[k], prefix));
2285         }
2286     }
2287 #endif
2288
2289     CHECK(FUNC(rbsp_trailing_bits)(ctx, rw));
2290
2291     return 0;
2292 }