avcodec/pnm: Avoid structure pointer dereferences in inner loop in pnm_get()
[ffmpeg.git] / 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     u(1, forbidden_zero_bit, 0, 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         u(6, nal_unit_type, 0, 63);
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                                 H265RawPSExtensionData *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), 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         u(5, general_profile_idc, 0, 31);
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     u(8, general_level_idc, 0, 255);
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             us(5, sub_layer_profile_idc[i], 0, 31,  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             us(8, sub_layer_level_idc[i], 0, 255, 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                 u(8, tick_divisor_minus2, 0, 255);
269                 u(5, du_cpb_removal_delay_increment_length_minus1, 0, 31);
270                 flag(sub_pic_cpb_params_in_pic_timing_sei_flag);
271                 u(5, dpb_output_delay_du_length_minus1, 0, 31);
272             }
273
274             u(4, bit_rate_scale, 0, 15);
275             u(4, cpb_size_scale, 0, 15);
276             if (current->sub_pic_hrd_params_present_flag)
277                 u(4, cpb_size_du_scale, 0, 15);
278
279             u(5, initial_cpb_removal_delay_length_minus1, 0, 31);
280             u(5, au_cpb_removal_delay_length_minus1,      0, 31);
281             u(5, dpb_output_delay_length_minus1,          0, 31);
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         u(8, aspect_ratio_idc, 0, 255);
327         if (current->aspect_ratio_idc == 255) {
328             u(16, sar_width,  0, 65535);
329             u(16, sar_height, 0, 65535);
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         u(3, video_format, 0, 7);
342         flag(video_full_range_flag);
343         flag(colour_description_present_flag);
344         if (current->colour_description_present_flag) {
345             u(8, colour_primaries,         0, 255);
346             u(8, transfer_characteristics, 0, 255);
347             u(8, matrix_coefficients,      0, 255);
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     u(4, vps_video_parameter_set_id, 0, 15);
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;
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
542         flag(delta_rps_sign);
543         ue(abs_delta_rps_minus1, 0, INT16_MAX);
544         delta_rps = (1 - 2 * current->delta_rps_sign) *
545             (current->abs_delta_rps_minus1 + 1);
546
547         for (j = 0; j <= num_delta_pocs; j++) {
548             flags(used_by_curr_pic_flag[j], 1, j);
549             if (!current->used_by_curr_pic_flag[j])
550                 flags(use_delta_flag[j], 1, j);
551             else
552                 infer(use_delta_flag[j], 1);
553         }
554
555         // Since the stored form of an RPS here is actually the delta-step
556         // form used when inter_ref_pic_set_prediction_flag is not set, we
557         // need to reconstruct that here in order to be able to refer to
558         // the RPS later (which is required for parsing, because we don't
559         // even know what syntax elements appear without it).  Therefore,
560         // this code takes the delta-step form of the reference set, turns
561         // it into the delta-array form, applies the prediction process of
562         // 7.4.8, converts the result back to the delta-step form, and
563         // stores that as the current set for future use.  Note that the
564         // inferences here mean that writers using prediction will need
565         // to fill in the delta-step values correctly as well - since the
566         // whole RPS prediction process is somewhat overly sophisticated,
567         // this hopefully forms a useful check for them to ensure their
568         // predicted form actually matches what was intended rather than
569         // an onerous additional requirement.
570
571         d_poc = 0;
572         for (i = 0; i < ref->num_negative_pics; i++) {
573             d_poc -= ref->delta_poc_s0_minus1[i] + 1;
574             ref_delta_poc_s0[i] = d_poc;
575         }
576         d_poc = 0;
577         for (i = 0; i < ref->num_positive_pics; i++) {
578             d_poc += ref->delta_poc_s1_minus1[i] + 1;
579             ref_delta_poc_s1[i] = d_poc;
580         }
581
582         i = 0;
583         for (j = ref->num_positive_pics - 1; j >= 0; j--) {
584             d_poc = ref_delta_poc_s1[j] + delta_rps;
585             if (d_poc < 0 && current->use_delta_flag[ref->num_negative_pics + j]) {
586                 delta_poc_s0[i] = d_poc;
587                 used_by_curr_pic_s0[i++] =
588                     current->used_by_curr_pic_flag[ref->num_negative_pics + j];
589             }
590         }
591         if (delta_rps < 0 && current->use_delta_flag[num_delta_pocs]) {
592             delta_poc_s0[i] = delta_rps;
593             used_by_curr_pic_s0[i++] =
594                 current->used_by_curr_pic_flag[num_delta_pocs];
595         }
596         for (j = 0; j < ref->num_negative_pics; j++) {
597             d_poc = ref_delta_poc_s0[j] + delta_rps;
598             if (d_poc < 0 && current->use_delta_flag[j]) {
599                 delta_poc_s0[i] = d_poc;
600                 used_by_curr_pic_s0[i++] = current->used_by_curr_pic_flag[j];
601             }
602         }
603
604         infer(num_negative_pics, i);
605         for (i = 0; i < current->num_negative_pics; i++) {
606             infer(delta_poc_s0_minus1[i],
607                   -(delta_poc_s0[i] - (i == 0 ? 0 : delta_poc_s0[i - 1])) - 1);
608             infer(used_by_curr_pic_s0_flag[i], used_by_curr_pic_s0[i]);
609         }
610
611         i = 0;
612         for (j = ref->num_negative_pics - 1; j >= 0; j--) {
613             d_poc = ref_delta_poc_s0[j] + delta_rps;
614             if (d_poc > 0 && current->use_delta_flag[j]) {
615                 delta_poc_s1[i] = d_poc;
616                 used_by_curr_pic_s1[i++] = current->used_by_curr_pic_flag[j];
617             }
618         }
619         if (delta_rps > 0 && current->use_delta_flag[num_delta_pocs]) {
620             delta_poc_s1[i] = delta_rps;
621             used_by_curr_pic_s1[i++] =
622                 current->used_by_curr_pic_flag[num_delta_pocs];
623         }
624         for (j = 0; j < ref->num_positive_pics; j++) {
625             d_poc = ref_delta_poc_s1[j] + delta_rps;
626             if (d_poc > 0 && current->use_delta_flag[ref->num_negative_pics + j]) {
627                 delta_poc_s1[i] = d_poc;
628                 used_by_curr_pic_s1[i++] =
629                     current->used_by_curr_pic_flag[ref->num_negative_pics + j];
630             }
631         }
632
633         infer(num_positive_pics, i);
634         for (i = 0; i < current->num_positive_pics; i++) {
635             infer(delta_poc_s1_minus1[i],
636                   delta_poc_s1[i] - (i == 0 ? 0 : delta_poc_s1[i - 1]) - 1);
637             infer(used_by_curr_pic_s1_flag[i], used_by_curr_pic_s1[i]);
638         }
639
640     } else {
641         ue(num_negative_pics, 0, 15);
642         ue(num_positive_pics, 0, 15 - current->num_negative_pics);
643
644         for (i = 0; i < current->num_negative_pics; i++) {
645             ues(delta_poc_s0_minus1[i], 0, INT16_MAX, 1, i);
646             flags(used_by_curr_pic_s0_flag[i],        1, i);
647         }
648
649         for (i = 0; i < current->num_positive_pics; i++) {
650             ues(delta_poc_s1_minus1[i], 0, INT16_MAX, 1, i);
651             flags(used_by_curr_pic_s1_flag[i],        1, i);
652         }
653     }
654
655     return 0;
656 }
657
658 static int FUNC(scaling_list_data)(CodedBitstreamContext *ctx, RWContext *rw,
659                                    H265RawScalingList *current)
660 {
661     int sizeId, matrixId;
662     int err, n, i;
663
664     for (sizeId = 0; sizeId < 4; sizeId++) {
665         for (matrixId = 0; matrixId < 6; matrixId += (sizeId == 3 ? 3 : 1)) {
666             flags(scaling_list_pred_mode_flag[sizeId][matrixId],
667                   2, sizeId, matrixId);
668             if (!current->scaling_list_pred_mode_flag[sizeId][matrixId]) {
669                 ues(scaling_list_pred_matrix_id_delta[sizeId][matrixId],
670                     0, sizeId == 3 ? matrixId / 3 : matrixId,
671                     2, sizeId, matrixId);
672             } else {
673                 n = FFMIN(64, 1 << (4 + (sizeId << 1)));
674                 if (sizeId > 1) {
675                     ses(scaling_list_dc_coef_minus8[sizeId - 2][matrixId], -7, +247,
676                         2, sizeId - 2, matrixId);
677                 }
678                 for (i = 0; i < n; i++) {
679                     ses(scaling_list_delta_coeff[sizeId][matrixId][i],
680                         -128, +127, 3, sizeId, matrixId, i);
681                 }
682             }
683         }
684     }
685
686     return 0;
687 }
688
689 static int FUNC(sps_range_extension)(CodedBitstreamContext *ctx, RWContext *rw,
690                                      H265RawSPS *current)
691 {
692     int err;
693
694     flag(transform_skip_rotation_enabled_flag);
695     flag(transform_skip_context_enabled_flag);
696     flag(implicit_rdpcm_enabled_flag);
697     flag(explicit_rdpcm_enabled_flag);
698     flag(extended_precision_processing_flag);
699     flag(intra_smoothing_disabled_flag);
700     flag(high_precision_offsets_enabled_flag);
701     flag(persistent_rice_adaptation_enabled_flag);
702     flag(cabac_bypass_alignment_enabled_flag);
703
704     return 0;
705 }
706
707 static int FUNC(sps_scc_extension)(CodedBitstreamContext *ctx, RWContext *rw,
708                                    H265RawSPS *current)
709 {
710     int err, comp, i;
711
712     flag(sps_curr_pic_ref_enabled_flag);
713
714     flag(palette_mode_enabled_flag);
715     if (current->palette_mode_enabled_flag) {
716         ue(palette_max_size, 0, 64);
717         ue(delta_palette_max_predictor_size, 0, 128);
718
719         flag(sps_palette_predictor_initializer_present_flag);
720         if (current->sps_palette_predictor_initializer_present_flag) {
721             ue(sps_num_palette_predictor_initializer_minus1, 0, 128);
722             for (comp = 0; comp < (current->chroma_format_idc ? 3 : 1); comp++) {
723                 int bit_depth = comp == 0 ? current->bit_depth_luma_minus8 + 8
724                                           : current->bit_depth_chroma_minus8 + 8;
725                 for (i = 0; i <= current->sps_num_palette_predictor_initializer_minus1; i++)
726                     us(bit_depth, sps_palette_predictor_initializers[comp][i],
727                        0, MAX_UINT_BITS(bit_depth), 2, comp, i);
728             }
729         }
730     }
731
732     u(2, motion_vector_resolution_control_idc, 0, 2);
733     flag(intra_boundary_filtering_disable_flag);
734
735     return 0;
736 }
737
738 static int FUNC(sps)(CodedBitstreamContext *ctx, RWContext *rw,
739                      H265RawSPS *current)
740 {
741     CodedBitstreamH265Context *h265 = ctx->priv_data;
742     const H265RawVPS *vps;
743     int err, i;
744     unsigned int min_cb_log2_size_y, ctb_log2_size_y,
745                  min_cb_size_y,   min_tb_log2_size_y;
746
747     HEADER("Sequence Parameter Set");
748
749     CHECK(FUNC(nal_unit_header)(ctx, rw, &current->nal_unit_header, HEVC_NAL_SPS));
750
751     u(4, sps_video_parameter_set_id, 0, 15);
752     h265->active_vps = vps = h265->vps[current->sps_video_parameter_set_id];
753
754     u(3, sps_max_sub_layers_minus1, 0, HEVC_MAX_SUB_LAYERS - 1);
755     flag(sps_temporal_id_nesting_flag);
756     if (vps) {
757         if (vps->vps_max_sub_layers_minus1 > current->sps_max_sub_layers_minus1) {
758             av_log(ctx->log_ctx, AV_LOG_ERROR, "Invalid stream: "
759                    "sps_max_sub_layers_minus1 (%d) must be less than or equal to "
760                    "vps_max_sub_layers_minus1 (%d).\n",
761                    vps->vps_max_sub_layers_minus1,
762                    current->sps_max_sub_layers_minus1);
763             return AVERROR_INVALIDDATA;
764         }
765         if (vps->vps_temporal_id_nesting_flag &&
766             !current->sps_temporal_id_nesting_flag) {
767             av_log(ctx->log_ctx, AV_LOG_ERROR, "Invalid stream: "
768                    "sps_temporal_id_nesting_flag must be 1 if "
769                    "vps_temporal_id_nesting_flag is 1.\n");
770             return AVERROR_INVALIDDATA;
771         }
772     }
773
774     CHECK(FUNC(profile_tier_level)(ctx, rw, &current->profile_tier_level,
775                                    1, current->sps_max_sub_layers_minus1));
776
777     ue(sps_seq_parameter_set_id, 0, 15);
778
779     ue(chroma_format_idc, 0, 3);
780     if (current->chroma_format_idc == 3)
781         flag(separate_colour_plane_flag);
782     else
783         infer(separate_colour_plane_flag, 0);
784
785     ue(pic_width_in_luma_samples,  1, HEVC_MAX_WIDTH);
786     ue(pic_height_in_luma_samples, 1, HEVC_MAX_HEIGHT);
787
788     flag(conformance_window_flag);
789     if (current->conformance_window_flag) {
790         ue(conf_win_left_offset,   0, current->pic_width_in_luma_samples);
791         ue(conf_win_right_offset,  0, current->pic_width_in_luma_samples);
792         ue(conf_win_top_offset,    0, current->pic_height_in_luma_samples);
793         ue(conf_win_bottom_offset, 0, current->pic_height_in_luma_samples);
794     } else {
795         infer(conf_win_left_offset,   0);
796         infer(conf_win_right_offset,  0);
797         infer(conf_win_top_offset,    0);
798         infer(conf_win_bottom_offset, 0);
799     }
800
801     ue(bit_depth_luma_minus8,   0, 8);
802     ue(bit_depth_chroma_minus8, 0, 8);
803
804     ue(log2_max_pic_order_cnt_lsb_minus4, 0, 12);
805
806     flag(sps_sub_layer_ordering_info_present_flag);
807     for (i = (current->sps_sub_layer_ordering_info_present_flag ?
808               0 : current->sps_max_sub_layers_minus1);
809          i <= current->sps_max_sub_layers_minus1; i++) {
810         ues(sps_max_dec_pic_buffering_minus1[i],
811             0, HEVC_MAX_DPB_SIZE - 1,                        1, i);
812         ues(sps_max_num_reorder_pics[i],
813             0, current->sps_max_dec_pic_buffering_minus1[i], 1, i);
814         ues(sps_max_latency_increase_plus1[i],
815             0, UINT32_MAX - 1,                               1, i);
816     }
817     if (!current->sps_sub_layer_ordering_info_present_flag) {
818         for (i = 0; i < current->sps_max_sub_layers_minus1; i++) {
819             infer(sps_max_dec_pic_buffering_minus1[i],
820                   current->sps_max_dec_pic_buffering_minus1[current->sps_max_sub_layers_minus1]);
821             infer(sps_max_num_reorder_pics[i],
822                   current->sps_max_num_reorder_pics[current->sps_max_sub_layers_minus1]);
823             infer(sps_max_latency_increase_plus1[i],
824                   current->sps_max_latency_increase_plus1[current->sps_max_sub_layers_minus1]);
825         }
826     }
827
828     ue(log2_min_luma_coding_block_size_minus3,   0, 3);
829     min_cb_log2_size_y = current->log2_min_luma_coding_block_size_minus3 + 3;
830
831     ue(log2_diff_max_min_luma_coding_block_size, 0, 3);
832     ctb_log2_size_y = min_cb_log2_size_y +
833         current->log2_diff_max_min_luma_coding_block_size;
834
835     min_cb_size_y = 1 << min_cb_log2_size_y;
836     if (current->pic_width_in_luma_samples  % min_cb_size_y ||
837         current->pic_height_in_luma_samples % min_cb_size_y) {
838         av_log(ctx->log_ctx, AV_LOG_ERROR, "Invalid dimensions: %ux%u not divisible "
839                "by MinCbSizeY = %u.\n", current->pic_width_in_luma_samples,
840                current->pic_height_in_luma_samples, min_cb_size_y);
841         return AVERROR_INVALIDDATA;
842     }
843
844     ue(log2_min_luma_transform_block_size_minus2, 0, min_cb_log2_size_y - 3);
845     min_tb_log2_size_y = current->log2_min_luma_transform_block_size_minus2 + 2;
846
847     ue(log2_diff_max_min_luma_transform_block_size,
848        0, FFMIN(ctb_log2_size_y, 5) - min_tb_log2_size_y);
849
850     ue(max_transform_hierarchy_depth_inter,
851        0, ctb_log2_size_y - min_tb_log2_size_y);
852     ue(max_transform_hierarchy_depth_intra,
853        0, ctb_log2_size_y - min_tb_log2_size_y);
854
855     flag(scaling_list_enabled_flag);
856     if (current->scaling_list_enabled_flag) {
857         flag(sps_scaling_list_data_present_flag);
858         if (current->sps_scaling_list_data_present_flag)
859             CHECK(FUNC(scaling_list_data)(ctx, rw, &current->scaling_list));
860     } else {
861         infer(sps_scaling_list_data_present_flag, 0);
862     }
863
864     flag(amp_enabled_flag);
865     flag(sample_adaptive_offset_enabled_flag);
866
867     flag(pcm_enabled_flag);
868     if (current->pcm_enabled_flag) {
869         u(4, pcm_sample_bit_depth_luma_minus1,
870           0, current->bit_depth_luma_minus8 + 8 - 1);
871         u(4, pcm_sample_bit_depth_chroma_minus1,
872           0, current->bit_depth_chroma_minus8 + 8 - 1);
873
874         ue(log2_min_pcm_luma_coding_block_size_minus3,
875            FFMIN(min_cb_log2_size_y, 5) - 3, FFMIN(ctb_log2_size_y, 5) - 3);
876         ue(log2_diff_max_min_pcm_luma_coding_block_size,
877            0, FFMIN(ctb_log2_size_y, 5) - (current->log2_min_pcm_luma_coding_block_size_minus3 + 3));
878
879         flag(pcm_loop_filter_disabled_flag);
880     }
881
882     ue(num_short_term_ref_pic_sets, 0, HEVC_MAX_SHORT_TERM_REF_PIC_SETS);
883     for (i = 0; i < current->num_short_term_ref_pic_sets; i++)
884         CHECK(FUNC(st_ref_pic_set)(ctx, rw, &current->st_ref_pic_set[i], i, current));
885
886     flag(long_term_ref_pics_present_flag);
887     if (current->long_term_ref_pics_present_flag) {
888         ue(num_long_term_ref_pics_sps, 0, HEVC_MAX_LONG_TERM_REF_PICS);
889         for (i = 0; i < current->num_long_term_ref_pics_sps; i++) {
890             us(current->log2_max_pic_order_cnt_lsb_minus4 + 4,
891                lt_ref_pic_poc_lsb_sps[i],
892                0, MAX_UINT_BITS(current->log2_max_pic_order_cnt_lsb_minus4 + 4), 1, i);
893             flags(used_by_curr_pic_lt_sps_flag[i], 1, i);
894         }
895     }
896
897     flag(sps_temporal_mvp_enabled_flag);
898     flag(strong_intra_smoothing_enabled_flag);
899
900     flag(vui_parameters_present_flag);
901     if (current->vui_parameters_present_flag)
902         CHECK(FUNC(vui_parameters)(ctx, rw, &current->vui, current));
903
904     flag(sps_extension_present_flag);
905     if (current->sps_extension_present_flag) {
906         flag(sps_range_extension_flag);
907         flag(sps_multilayer_extension_flag);
908         flag(sps_3d_extension_flag);
909         flag(sps_scc_extension_flag);
910         u(4, sps_extension_4bits, 0, MAX_UINT_BITS(4));
911     }
912
913     if (current->sps_range_extension_flag)
914         CHECK(FUNC(sps_range_extension)(ctx, rw, current));
915     if (current->sps_multilayer_extension_flag)
916         return AVERROR_PATCHWELCOME;
917     if (current->sps_3d_extension_flag)
918         return AVERROR_PATCHWELCOME;
919     if (current->sps_scc_extension_flag)
920         CHECK(FUNC(sps_scc_extension)(ctx, rw, current));
921     if (current->sps_extension_4bits)
922         CHECK(FUNC(extension_data)(ctx, rw, &current->extension_data));
923
924     CHECK(FUNC(rbsp_trailing_bits)(ctx, rw));
925
926     return 0;
927 }
928
929 static int FUNC(pps_range_extension)(CodedBitstreamContext *ctx, RWContext *rw,
930                                      H265RawPPS *current)
931 {
932     CodedBitstreamH265Context *h265 = ctx->priv_data;
933     const H265RawSPS *sps = h265->active_sps;
934     int err, i;
935
936     if (current->transform_skip_enabled_flag)
937         ue(log2_max_transform_skip_block_size_minus2, 0, 3);
938     flag(cross_component_prediction_enabled_flag);
939
940     flag(chroma_qp_offset_list_enabled_flag);
941     if (current->chroma_qp_offset_list_enabled_flag) {
942         ue(diff_cu_chroma_qp_offset_depth,
943            0, sps->log2_diff_max_min_luma_coding_block_size);
944         ue(chroma_qp_offset_list_len_minus1, 0, 5);
945         for (i = 0; i <= current->chroma_qp_offset_list_len_minus1; i++) {
946             ses(cb_qp_offset_list[i], -12, +12, 1, i);
947             ses(cr_qp_offset_list[i], -12, +12, 1, i);
948         }
949     }
950
951     ue(log2_sao_offset_scale_luma,   0, FFMAX(0, sps->bit_depth_luma_minus8   - 2));
952     ue(log2_sao_offset_scale_chroma, 0, FFMAX(0, sps->bit_depth_chroma_minus8 - 2));
953
954     return 0;
955 }
956
957 static int FUNC(pps_scc_extension)(CodedBitstreamContext *ctx, RWContext *rw,
958                                    H265RawPPS *current)
959 {
960     int err, comp, i;
961
962     flag(pps_curr_pic_ref_enabled_flag);
963
964     flag(residual_adaptive_colour_transform_enabled_flag);
965     if (current->residual_adaptive_colour_transform_enabled_flag) {
966         flag(pps_slice_act_qp_offsets_present_flag);
967         se(pps_act_y_qp_offset_plus5,  -7, +17);
968         se(pps_act_cb_qp_offset_plus5, -7, +17);
969         se(pps_act_cr_qp_offset_plus3, -9, +15);
970     } else {
971         infer(pps_slice_act_qp_offsets_present_flag, 0);
972         infer(pps_act_y_qp_offset_plus5,  0);
973         infer(pps_act_cb_qp_offset_plus5, 0);
974         infer(pps_act_cr_qp_offset_plus3, 0);
975     }
976
977     flag(pps_palette_predictor_initializer_present_flag);
978     if (current->pps_palette_predictor_initializer_present_flag) {
979         ue(pps_num_palette_predictor_initializer, 0, 128);
980         if (current->pps_num_palette_predictor_initializer > 0) {
981             flag(monochrome_palette_flag);
982             ue(luma_bit_depth_entry_minus8, 0, 8);
983             if (!current->monochrome_palette_flag)
984                 ue(chroma_bit_depth_entry_minus8, 0, 8);
985             for (comp = 0; comp < (current->monochrome_palette_flag ? 1 : 3); comp++) {
986                 int bit_depth = comp == 0 ? current->luma_bit_depth_entry_minus8 + 8
987                                           : current->chroma_bit_depth_entry_minus8 + 8;
988                 for (i = 0; i < current->pps_num_palette_predictor_initializer; i++)
989                     us(bit_depth, pps_palette_predictor_initializers[comp][i],
990                        0, MAX_UINT_BITS(bit_depth), 2, comp, i);
991             }
992         }
993     }
994
995     return 0;
996 }
997
998 static int FUNC(pps)(CodedBitstreamContext *ctx, RWContext *rw,
999                      H265RawPPS *current)
1000 {
1001     CodedBitstreamH265Context *h265 = ctx->priv_data;
1002     const H265RawSPS *sps;
1003     int err, i;
1004
1005     HEADER("Picture Parameter Set");
1006
1007     CHECK(FUNC(nal_unit_header)(ctx, rw, &current->nal_unit_header, HEVC_NAL_PPS));
1008
1009     ue(pps_pic_parameter_set_id, 0, 63);
1010     ue(pps_seq_parameter_set_id, 0, 15);
1011     sps = h265->sps[current->pps_seq_parameter_set_id];
1012     if (!sps) {
1013         av_log(ctx->log_ctx, AV_LOG_ERROR, "SPS id %d not available.\n",
1014                current->pps_seq_parameter_set_id);
1015         return AVERROR_INVALIDDATA;
1016     }
1017     h265->active_sps = sps;
1018
1019     flag(dependent_slice_segments_enabled_flag);
1020     flag(output_flag_present_flag);
1021     u(3, num_extra_slice_header_bits, 0, 7);
1022     flag(sign_data_hiding_enabled_flag);
1023     flag(cabac_init_present_flag);
1024
1025     ue(num_ref_idx_l0_default_active_minus1, 0, 14);
1026     ue(num_ref_idx_l1_default_active_minus1, 0, 14);
1027
1028     se(init_qp_minus26, -(26 + 6 * sps->bit_depth_luma_minus8), +25);
1029
1030     flag(constrained_intra_pred_flag);
1031     flag(transform_skip_enabled_flag);
1032     flag(cu_qp_delta_enabled_flag);
1033     if (current->cu_qp_delta_enabled_flag)
1034         ue(diff_cu_qp_delta_depth,
1035            0, sps->log2_diff_max_min_luma_coding_block_size);
1036     else
1037         infer(diff_cu_qp_delta_depth, 0);
1038
1039     se(pps_cb_qp_offset, -12, +12);
1040     se(pps_cr_qp_offset, -12, +12);
1041     flag(pps_slice_chroma_qp_offsets_present_flag);
1042
1043     flag(weighted_pred_flag);
1044     flag(weighted_bipred_flag);
1045
1046     flag(transquant_bypass_enabled_flag);
1047     flag(tiles_enabled_flag);
1048     flag(entropy_coding_sync_enabled_flag);
1049
1050     if (current->tiles_enabled_flag) {
1051         ue(num_tile_columns_minus1, 0, HEVC_MAX_TILE_COLUMNS);
1052         ue(num_tile_rows_minus1,    0, HEVC_MAX_TILE_ROWS);
1053         flag(uniform_spacing_flag);
1054         if (!current->uniform_spacing_flag) {
1055             for (i = 0; i < current->num_tile_columns_minus1; i++)
1056                 ues(column_width_minus1[i], 0, sps->pic_width_in_luma_samples,  1, i);
1057             for (i = 0; i < current->num_tile_rows_minus1; i++)
1058                 ues(row_height_minus1[i],   0, sps->pic_height_in_luma_samples, 1, i);
1059         }
1060         flag(loop_filter_across_tiles_enabled_flag);
1061     } else {
1062         infer(num_tile_columns_minus1, 0);
1063         infer(num_tile_rows_minus1,    0);
1064     }
1065
1066     flag(pps_loop_filter_across_slices_enabled_flag);
1067     flag(deblocking_filter_control_present_flag);
1068     if (current->deblocking_filter_control_present_flag) {
1069         flag(deblocking_filter_override_enabled_flag);
1070         flag(pps_deblocking_filter_disabled_flag);
1071         if (!current->pps_deblocking_filter_disabled_flag) {
1072             se(pps_beta_offset_div2, -6, +6);
1073             se(pps_tc_offset_div2,   -6, +6);
1074         } else {
1075             infer(pps_beta_offset_div2, 0);
1076             infer(pps_tc_offset_div2,   0);
1077         }
1078     } else {
1079         infer(deblocking_filter_override_enabled_flag, 0);
1080         infer(pps_deblocking_filter_disabled_flag,     0);
1081         infer(pps_beta_offset_div2, 0);
1082         infer(pps_tc_offset_div2,   0);
1083     }
1084
1085     flag(pps_scaling_list_data_present_flag);
1086     if (current->pps_scaling_list_data_present_flag)
1087         CHECK(FUNC(scaling_list_data)(ctx, rw, &current->scaling_list));
1088
1089     flag(lists_modification_present_flag);
1090
1091     ue(log2_parallel_merge_level_minus2,
1092        0, (sps->log2_min_luma_coding_block_size_minus3 + 3 +
1093            sps->log2_diff_max_min_luma_coding_block_size - 2));
1094
1095     flag(slice_segment_header_extension_present_flag);
1096
1097     flag(pps_extension_present_flag);
1098     if (current->pps_extension_present_flag) {
1099         flag(pps_range_extension_flag);
1100         flag(pps_multilayer_extension_flag);
1101         flag(pps_3d_extension_flag);
1102         flag(pps_scc_extension_flag);
1103         u(4, pps_extension_4bits, 0, MAX_UINT_BITS(4));
1104     }
1105     if (current->pps_range_extension_flag)
1106         CHECK(FUNC(pps_range_extension)(ctx, rw, current));
1107     if (current->pps_multilayer_extension_flag)
1108         return AVERROR_PATCHWELCOME;
1109     if (current->pps_3d_extension_flag)
1110         return AVERROR_PATCHWELCOME;
1111     if (current->pps_scc_extension_flag)
1112         CHECK(FUNC(pps_scc_extension)(ctx, rw, current));
1113     if (current->pps_extension_4bits)
1114         CHECK(FUNC(extension_data)(ctx, rw, &current->extension_data));
1115
1116     CHECK(FUNC(rbsp_trailing_bits)(ctx, rw));
1117
1118     return 0;
1119 }
1120
1121 static int FUNC(aud)(CodedBitstreamContext *ctx, RWContext *rw,
1122                      H265RawAUD *current)
1123 {
1124     int err;
1125
1126     HEADER("Access Unit Delimiter");
1127
1128     CHECK(FUNC(nal_unit_header)(ctx, rw, &current->nal_unit_header, HEVC_NAL_AUD));
1129
1130     u(3, pic_type, 0, 2);
1131
1132     CHECK(FUNC(rbsp_trailing_bits)(ctx, rw));
1133
1134     return 0;
1135 }
1136
1137 static int FUNC(ref_pic_lists_modification)(CodedBitstreamContext *ctx, RWContext *rw,
1138                                             H265RawSliceHeader *current,
1139                                             unsigned int num_pic_total_curr)
1140 {
1141     unsigned int entry_size;
1142     int err, i;
1143
1144     entry_size = av_log2(num_pic_total_curr - 1) + 1;
1145
1146     flag(ref_pic_list_modification_flag_l0);
1147     if (current->ref_pic_list_modification_flag_l0) {
1148         for (i = 0; i <= current->num_ref_idx_l0_active_minus1; i++)
1149             us(entry_size, list_entry_l0[i], 0, num_pic_total_curr - 1, 1, i);
1150     }
1151
1152     if (current->slice_type == HEVC_SLICE_B) {
1153         flag(ref_pic_list_modification_flag_l1);
1154         if (current->ref_pic_list_modification_flag_l1) {
1155             for (i = 0; i <= current->num_ref_idx_l1_active_minus1; i++)
1156                 us(entry_size, list_entry_l1[i], 0, num_pic_total_curr - 1, 1, i);
1157         }
1158     }
1159
1160     return 0;
1161 }
1162
1163 static int FUNC(pred_weight_table)(CodedBitstreamContext *ctx, RWContext *rw,
1164                                    H265RawSliceHeader *current)
1165 {
1166     CodedBitstreamH265Context *h265 = ctx->priv_data;
1167     const H265RawSPS *sps = h265->active_sps;
1168     int err, i, j;
1169     int chroma = !sps->separate_colour_plane_flag &&
1170                   sps->chroma_format_idc != 0;
1171
1172     ue(luma_log2_weight_denom, 0, 7);
1173     if (chroma)
1174         se(delta_chroma_log2_weight_denom, -7, 7);
1175     else
1176         infer(delta_chroma_log2_weight_denom, 0);
1177
1178     for (i = 0; i <= current->num_ref_idx_l0_active_minus1; i++) {
1179         if (1 /* is not same POC and same layer_id */)
1180             flags(luma_weight_l0_flag[i], 1, i);
1181         else
1182             infer(luma_weight_l0_flag[i], 0);
1183     }
1184     if (chroma) {
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(chroma_weight_l0_flag[i], 1, i);
1188             else
1189                 infer(chroma_weight_l0_flag[i], 0);
1190         }
1191     }
1192
1193     for (i = 0; i <= current->num_ref_idx_l0_active_minus1; i++) {
1194         if (current->luma_weight_l0_flag[i]) {
1195             ses(delta_luma_weight_l0[i], -128, +127, 1, i);
1196             ses(luma_offset_l0[i],
1197                 -(1 << (sps->bit_depth_luma_minus8 + 8 - 1)),
1198                 ((1 << (sps->bit_depth_luma_minus8 + 8 - 1)) - 1), 1, i);
1199         } else {
1200             infer(delta_luma_weight_l0[i], 0);
1201             infer(luma_offset_l0[i],       0);
1202         }
1203         if (current->chroma_weight_l0_flag[i]) {
1204             for (j = 0; j < 2; j++) {
1205                 ses(delta_chroma_weight_l0[i][j], -128, +127, 2, i, j);
1206                 ses(chroma_offset_l0[i][j],
1207                     -(4 << (sps->bit_depth_chroma_minus8 + 8 - 1)),
1208                     ((4 << (sps->bit_depth_chroma_minus8 + 8 - 1)) - 1), 2, i, j);
1209             }
1210         } else {
1211             for (j = 0; j < 2; j++) {
1212                 infer(delta_chroma_weight_l0[i][j], 0);
1213                 infer(chroma_offset_l0[i][j],       0);
1214             }
1215         }
1216     }
1217
1218     if (current->slice_type == HEVC_SLICE_B) {
1219         for (i = 0; i <= current->num_ref_idx_l1_active_minus1; i++) {
1220             if (1 /* RefPicList1[i] is not CurrPic, nor is it in a different layer */)
1221                 flags(luma_weight_l1_flag[i], 1, i);
1222             else
1223                 infer(luma_weight_l1_flag[i], 0);
1224         }
1225         if (chroma) {
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(chroma_weight_l1_flag[i], 1, i);
1229                 else
1230                     infer(chroma_weight_l1_flag[i], 0);
1231             }
1232         }
1233
1234         for (i = 0; i <= current->num_ref_idx_l1_active_minus1; i++) {
1235             if (current->luma_weight_l1_flag[i]) {
1236                 ses(delta_luma_weight_l1[i], -128, +127, 1, i);
1237                 ses(luma_offset_l1[i],
1238                     -(1 << (sps->bit_depth_luma_minus8 + 8 - 1)),
1239                     ((1 << (sps->bit_depth_luma_minus8 + 8 - 1)) - 1), 1, i);
1240             } else {
1241                 infer(delta_luma_weight_l1[i], 0);
1242                 infer(luma_offset_l1[i],       0);
1243             }
1244             if (current->chroma_weight_l1_flag[i]) {
1245                 for (j = 0; j < 2; j++) {
1246                     ses(delta_chroma_weight_l1[i][j], -128, +127, 2, i, j);
1247                     ses(chroma_offset_l1[i][j],
1248                         -(4 << (sps->bit_depth_chroma_minus8 + 8 - 1)),
1249                         ((4 << (sps->bit_depth_chroma_minus8 + 8 - 1)) - 1), 2, i, j);
1250                 }
1251             } else {
1252                 for (j = 0; j < 2; j++) {
1253                     infer(delta_chroma_weight_l1[i][j], 0);
1254                     infer(chroma_offset_l1[i][j],       0);
1255                 }
1256             }
1257         }
1258     }
1259
1260     return 0;
1261 }
1262
1263 static int FUNC(slice_segment_header)(CodedBitstreamContext *ctx, RWContext *rw,
1264                                       H265RawSliceHeader *current)
1265 {
1266     CodedBitstreamH265Context *h265 = ctx->priv_data;
1267     const H265RawSPS *sps;
1268     const H265RawPPS *pps;
1269     unsigned int min_cb_log2_size_y, ctb_log2_size_y, ctb_size_y;
1270     unsigned int pic_width_in_ctbs_y, pic_height_in_ctbs_y, pic_size_in_ctbs_y;
1271     unsigned int num_pic_total_curr = 0;
1272     int err, i;
1273
1274     HEADER("Slice Segment Header");
1275
1276     CHECK(FUNC(nal_unit_header)(ctx, rw, &current->nal_unit_header, -1));
1277
1278     flag(first_slice_segment_in_pic_flag);
1279
1280     if (current->nal_unit_header.nal_unit_type >= HEVC_NAL_BLA_W_LP &&
1281         current->nal_unit_header.nal_unit_type <= HEVC_NAL_IRAP_VCL23)
1282         flag(no_output_of_prior_pics_flag);
1283
1284     ue(slice_pic_parameter_set_id, 0, 63);
1285
1286     pps = h265->pps[current->slice_pic_parameter_set_id];
1287     if (!pps) {
1288         av_log(ctx->log_ctx, AV_LOG_ERROR, "PPS id %d not available.\n",
1289                current->slice_pic_parameter_set_id);
1290         return AVERROR_INVALIDDATA;
1291     }
1292     h265->active_pps = pps;
1293
1294     sps = h265->sps[pps->pps_seq_parameter_set_id];
1295     if (!sps) {
1296         av_log(ctx->log_ctx, AV_LOG_ERROR, "SPS id %d not available.\n",
1297                pps->pps_seq_parameter_set_id);
1298         return AVERROR_INVALIDDATA;
1299     }
1300     h265->active_sps = sps;
1301
1302     min_cb_log2_size_y = sps->log2_min_luma_coding_block_size_minus3 + 3;
1303     ctb_log2_size_y = min_cb_log2_size_y + sps->log2_diff_max_min_luma_coding_block_size;
1304     ctb_size_y = 1 << ctb_log2_size_y;
1305     pic_width_in_ctbs_y =
1306         (sps->pic_width_in_luma_samples + ctb_size_y - 1) / ctb_size_y;
1307     pic_height_in_ctbs_y =
1308         (sps->pic_height_in_luma_samples + ctb_size_y - 1) / ctb_size_y;
1309     pic_size_in_ctbs_y = pic_width_in_ctbs_y * pic_height_in_ctbs_y;
1310
1311     if (!current->first_slice_segment_in_pic_flag) {
1312         unsigned int address_size = av_log2(pic_size_in_ctbs_y - 1) + 1;
1313         if (pps->dependent_slice_segments_enabled_flag)
1314             flag(dependent_slice_segment_flag);
1315         else
1316             infer(dependent_slice_segment_flag, 0);
1317         u(address_size, slice_segment_address, 0, pic_size_in_ctbs_y - 1);
1318     } else {
1319         infer(dependent_slice_segment_flag, 0);
1320     }
1321
1322     if (!current->dependent_slice_segment_flag) {
1323         for (i = 0; i < pps->num_extra_slice_header_bits; i++)
1324             flags(slice_reserved_flag[i], 1, i);
1325
1326         ue(slice_type, 0, 2);
1327
1328         if (pps->output_flag_present_flag)
1329             flag(pic_output_flag);
1330
1331         if (sps->separate_colour_plane_flag)
1332             u(2, colour_plane_id, 0, 2);
1333
1334         if (current->nal_unit_header.nal_unit_type != HEVC_NAL_IDR_W_RADL &&
1335             current->nal_unit_header.nal_unit_type != HEVC_NAL_IDR_N_LP) {
1336             const H265RawSTRefPicSet *rps;
1337
1338             u(sps->log2_max_pic_order_cnt_lsb_minus4 + 4, slice_pic_order_cnt_lsb,
1339               0, MAX_UINT_BITS(sps->log2_max_pic_order_cnt_lsb_minus4 + 4));
1340
1341             flag(short_term_ref_pic_set_sps_flag);
1342             if (!current->short_term_ref_pic_set_sps_flag) {
1343                 CHECK(FUNC(st_ref_pic_set)(ctx, rw, &current->short_term_ref_pic_set,
1344                                            sps->num_short_term_ref_pic_sets, sps));
1345                 rps = &current->short_term_ref_pic_set;
1346             } else if (sps->num_short_term_ref_pic_sets > 1) {
1347                 unsigned int idx_size = av_log2(sps->num_short_term_ref_pic_sets - 1) + 1;
1348                 u(idx_size, short_term_ref_pic_set_idx,
1349                   0, sps->num_short_term_ref_pic_sets - 1);
1350                 rps = &sps->st_ref_pic_set[current->short_term_ref_pic_set_idx];
1351             } else {
1352                 infer(short_term_ref_pic_set_idx, 0);
1353                 rps = &sps->st_ref_pic_set[0];
1354             }
1355
1356             num_pic_total_curr = 0;
1357             for (i = 0; i < rps->num_negative_pics; i++)
1358                 if (rps->used_by_curr_pic_s0_flag[i])
1359                     ++num_pic_total_curr;
1360             for (i = 0; i < rps->num_positive_pics; i++)
1361                 if (rps->used_by_curr_pic_s1_flag[i])
1362                     ++num_pic_total_curr;
1363
1364             if (sps->long_term_ref_pics_present_flag) {
1365                 unsigned int idx_size;
1366
1367                 if (sps->num_long_term_ref_pics_sps > 0) {
1368                     ue(num_long_term_sps, 0, sps->num_long_term_ref_pics_sps);
1369                     idx_size = av_log2(sps->num_long_term_ref_pics_sps - 1) + 1;
1370                 } else {
1371                     infer(num_long_term_sps, 0);
1372                     idx_size = 0;
1373                 }
1374                 ue(num_long_term_pics, 0, HEVC_MAX_LONG_TERM_REF_PICS);
1375
1376                 for (i = 0; i < current->num_long_term_sps +
1377                                 current->num_long_term_pics; i++) {
1378                     if (i < current->num_long_term_sps) {
1379                         if (sps->num_long_term_ref_pics_sps > 1)
1380                             us(idx_size, lt_idx_sps[i],
1381                                0, sps->num_long_term_ref_pics_sps - 1, 1, i);
1382                         if (sps->used_by_curr_pic_lt_sps_flag[current->lt_idx_sps[i]])
1383                             ++num_pic_total_curr;
1384                     } else {
1385                         us(sps->log2_max_pic_order_cnt_lsb_minus4 + 4, poc_lsb_lt[i],
1386                            0, MAX_UINT_BITS(sps->log2_max_pic_order_cnt_lsb_minus4 + 4), 1, i);
1387                         flags(used_by_curr_pic_lt_flag[i], 1, i);
1388                         if (current->used_by_curr_pic_lt_flag[i])
1389                             ++num_pic_total_curr;
1390                     }
1391                     flags(delta_poc_msb_present_flag[i], 1, i);
1392                     if (current->delta_poc_msb_present_flag[i])
1393                         ues(delta_poc_msb_cycle_lt[i], 0, UINT32_MAX - 1, 1, i);
1394                     else
1395                         infer(delta_poc_msb_cycle_lt[i], 0);
1396                 }
1397             }
1398
1399             if (sps->sps_temporal_mvp_enabled_flag)
1400                 flag(slice_temporal_mvp_enabled_flag);
1401             else
1402                 infer(slice_temporal_mvp_enabled_flag, 0);
1403
1404             if (pps->pps_curr_pic_ref_enabled_flag)
1405                 ++num_pic_total_curr;
1406         }
1407
1408         if (sps->sample_adaptive_offset_enabled_flag) {
1409             flag(slice_sao_luma_flag);
1410             if (!sps->separate_colour_plane_flag && sps->chroma_format_idc != 0)
1411                 flag(slice_sao_chroma_flag);
1412             else
1413                 infer(slice_sao_chroma_flag, 0);
1414         } else {
1415             infer(slice_sao_luma_flag,   0);
1416             infer(slice_sao_chroma_flag, 0);
1417         }
1418
1419         if (current->slice_type == HEVC_SLICE_P ||
1420             current->slice_type == HEVC_SLICE_B) {
1421             flag(num_ref_idx_active_override_flag);
1422             if (current->num_ref_idx_active_override_flag) {
1423                 ue(num_ref_idx_l0_active_minus1, 0, 14);
1424                 if (current->slice_type == HEVC_SLICE_B)
1425                     ue(num_ref_idx_l1_active_minus1, 0, 14);
1426                 else
1427                     infer(num_ref_idx_l1_active_minus1, pps->num_ref_idx_l1_default_active_minus1);
1428             } else {
1429                 infer(num_ref_idx_l0_active_minus1, pps->num_ref_idx_l0_default_active_minus1);
1430                 infer(num_ref_idx_l1_active_minus1, pps->num_ref_idx_l1_default_active_minus1);
1431             }
1432
1433             if (pps->lists_modification_present_flag && num_pic_total_curr > 1)
1434                 CHECK(FUNC(ref_pic_lists_modification)(ctx, rw, current,
1435                                                        num_pic_total_curr));
1436
1437             if (current->slice_type == HEVC_SLICE_B)
1438                 flag(mvd_l1_zero_flag);
1439             if (pps->cabac_init_present_flag)
1440                 flag(cabac_init_flag);
1441             else
1442                 infer(cabac_init_flag, 0);
1443             if (current->slice_temporal_mvp_enabled_flag) {
1444                 if (current->slice_type == HEVC_SLICE_B)
1445                     flag(collocated_from_l0_flag);
1446                 else
1447                     infer(collocated_from_l0_flag, 1);
1448                 if (current->collocated_from_l0_flag) {
1449                     if (current->num_ref_idx_l0_active_minus1 > 0)
1450                         ue(collocated_ref_idx, 0, current->num_ref_idx_l0_active_minus1);
1451                     else
1452                         infer(collocated_ref_idx, 0);
1453                 } else {
1454                     if (current->num_ref_idx_l1_active_minus1 > 0)
1455                         ue(collocated_ref_idx, 0, current->num_ref_idx_l1_active_minus1);
1456                     else
1457                         infer(collocated_ref_idx, 0);
1458                 }
1459             }
1460
1461             if ((pps->weighted_pred_flag   && current->slice_type == HEVC_SLICE_P) ||
1462                 (pps->weighted_bipred_flag && current->slice_type == HEVC_SLICE_B))
1463                 CHECK(FUNC(pred_weight_table)(ctx, rw, current));
1464
1465             ue(five_minus_max_num_merge_cand, 0, 4);
1466             if (sps->motion_vector_resolution_control_idc == 2)
1467                 flag(use_integer_mv_flag);
1468             else
1469                 infer(use_integer_mv_flag, sps->motion_vector_resolution_control_idc);
1470         }
1471
1472         se(slice_qp_delta,
1473            - 6 * sps->bit_depth_luma_minus8 - (pps->init_qp_minus26 + 26),
1474            + 51 - (pps->init_qp_minus26 + 26));
1475         if (pps->pps_slice_chroma_qp_offsets_present_flag) {
1476             se(slice_cb_qp_offset, -12, +12);
1477             se(slice_cr_qp_offset, -12, +12);
1478         } else {
1479             infer(slice_cb_qp_offset, 0);
1480             infer(slice_cr_qp_offset, 0);
1481         }
1482         if (pps->pps_slice_act_qp_offsets_present_flag) {
1483             se(slice_act_y_qp_offset,
1484                -12 - (pps->pps_act_y_qp_offset_plus5 - 5),
1485                +12 - (pps->pps_act_y_qp_offset_plus5 - 5));
1486             se(slice_act_cb_qp_offset,
1487                -12 - (pps->pps_act_cb_qp_offset_plus5 - 5),
1488                +12 - (pps->pps_act_cb_qp_offset_plus5 - 5));
1489             se(slice_act_cr_qp_offset,
1490                -12 - (pps->pps_act_cr_qp_offset_plus3 - 3),
1491                +12 - (pps->pps_act_cr_qp_offset_plus3 - 3));
1492         } else {
1493             infer(slice_act_y_qp_offset,  0);
1494             infer(slice_act_cb_qp_offset, 0);
1495             infer(slice_act_cr_qp_offset, 0);
1496         }
1497         if (pps->chroma_qp_offset_list_enabled_flag)
1498             flag(cu_chroma_qp_offset_enabled_flag);
1499         else
1500             infer(cu_chroma_qp_offset_enabled_flag, 0);
1501
1502         if (pps->deblocking_filter_override_enabled_flag)
1503             flag(deblocking_filter_override_flag);
1504         else
1505             infer(deblocking_filter_override_flag, 0);
1506         if (current->deblocking_filter_override_flag) {
1507             flag(slice_deblocking_filter_disabled_flag);
1508             if (!current->slice_deblocking_filter_disabled_flag) {
1509                 se(slice_beta_offset_div2, -6, +6);
1510                 se(slice_tc_offset_div2,   -6, +6);
1511             } else {
1512                 infer(slice_beta_offset_div2, pps->pps_beta_offset_div2);
1513                 infer(slice_tc_offset_div2,   pps->pps_tc_offset_div2);
1514             }
1515         } else {
1516             infer(slice_deblocking_filter_disabled_flag,
1517                   pps->pps_deblocking_filter_disabled_flag);
1518             infer(slice_beta_offset_div2, pps->pps_beta_offset_div2);
1519             infer(slice_tc_offset_div2,   pps->pps_tc_offset_div2);
1520         }
1521         if (pps->pps_loop_filter_across_slices_enabled_flag &&
1522             (current->slice_sao_luma_flag || current->slice_sao_chroma_flag ||
1523              !current->slice_deblocking_filter_disabled_flag))
1524             flag(slice_loop_filter_across_slices_enabled_flag);
1525         else
1526             infer(slice_loop_filter_across_slices_enabled_flag,
1527                   pps->pps_loop_filter_across_slices_enabled_flag);
1528     }
1529
1530     if (pps->tiles_enabled_flag || pps->entropy_coding_sync_enabled_flag) {
1531         unsigned int num_entry_point_offsets_limit;
1532         if (!pps->tiles_enabled_flag && pps->entropy_coding_sync_enabled_flag)
1533             num_entry_point_offsets_limit = pic_height_in_ctbs_y - 1;
1534         else if (pps->tiles_enabled_flag && !pps->entropy_coding_sync_enabled_flag)
1535             num_entry_point_offsets_limit =
1536                 (pps->num_tile_columns_minus1 + 1) * (pps->num_tile_rows_minus1 + 1);
1537         else
1538             num_entry_point_offsets_limit =
1539                 (pps->num_tile_columns_minus1 + 1) * pic_height_in_ctbs_y - 1;
1540         ue(num_entry_point_offsets, 0, num_entry_point_offsets_limit);
1541
1542         if (current->num_entry_point_offsets > HEVC_MAX_ENTRY_POINT_OFFSETS) {
1543             av_log(ctx->log_ctx, AV_LOG_ERROR, "Too many entry points: "
1544                    "%"PRIu16".\n", current->num_entry_point_offsets);
1545             return AVERROR_PATCHWELCOME;
1546         }
1547
1548         if (current->num_entry_point_offsets > 0) {
1549             ue(offset_len_minus1, 0, 31);
1550             for (i = 0; i < current->num_entry_point_offsets; i++)
1551                 us(current->offset_len_minus1 + 1, entry_point_offset_minus1[i],
1552                    0, MAX_UINT_BITS(current->offset_len_minus1 + 1), 1, i);
1553         }
1554     }
1555
1556     if (pps->slice_segment_header_extension_present_flag) {
1557         ue(slice_segment_header_extension_length, 0, 256);
1558         for (i = 0; i < current->slice_segment_header_extension_length; i++)
1559             us(8, slice_segment_header_extension_data_byte[i], 0x00, 0xff, 1, i);
1560     }
1561
1562     CHECK(FUNC(byte_alignment)(ctx, rw));
1563
1564     return 0;
1565 }
1566
1567 static int FUNC(sei_buffering_period)(CodedBitstreamContext *ctx, RWContext *rw,
1568                                       H265RawSEIBufferingPeriod *current,
1569                                       uint32_t *payload_size)
1570 {
1571     CodedBitstreamH265Context *h265 = ctx->priv_data;
1572     const H265RawSPS *sps;
1573     const H265RawHRDParameters *hrd;
1574     int err, i, length;
1575
1576 #ifdef READ
1577     int start_pos, end_pos, bits_left;
1578     start_pos = get_bits_count(rw);
1579 #endif
1580
1581     HEADER("Buffering Period");
1582
1583     ue(bp_seq_parameter_set_id, 0, HEVC_MAX_SPS_COUNT - 1);
1584
1585     sps = h265->sps[current->bp_seq_parameter_set_id];
1586     if (!sps) {
1587         av_log(ctx->log_ctx, AV_LOG_ERROR, "SPS id %d not available.\n",
1588                current->bp_seq_parameter_set_id);
1589         return AVERROR_INVALIDDATA;
1590     }
1591     h265->active_sps = sps;
1592
1593     if (!sps->vui_parameters_present_flag ||
1594         !sps->vui.vui_hrd_parameters_present_flag) {
1595         av_log(ctx->log_ctx, AV_LOG_ERROR, "Buffering period SEI requires "
1596                "HRD parameters to be present in SPS.\n");
1597         return AVERROR_INVALIDDATA;
1598     }
1599     hrd = &sps->vui.hrd_parameters;
1600     if (!hrd->nal_hrd_parameters_present_flag &&
1601         !hrd->vcl_hrd_parameters_present_flag) {
1602         av_log(ctx->log_ctx, AV_LOG_ERROR, "Buffering period SEI requires "
1603                "NAL or VCL HRD parameters to be present.\n");
1604         return AVERROR_INVALIDDATA;
1605     }
1606
1607     if (!hrd->sub_pic_hrd_params_present_flag)
1608         flag(irap_cpb_params_present_flag);
1609     else
1610         infer(irap_cpb_params_present_flag, 0);
1611     if (current->irap_cpb_params_present_flag) {
1612         length = hrd->au_cpb_removal_delay_length_minus1 + 1;
1613         u(length, cpb_delay_offset, 0, MAX_UINT_BITS(length));
1614         length = hrd->dpb_output_delay_length_minus1 + 1;
1615         u(length, dpb_delay_offset, 0, MAX_UINT_BITS(length));
1616     } else {
1617         infer(cpb_delay_offset, 0);
1618         infer(dpb_delay_offset, 0);
1619     }
1620
1621     flag(concatenation_flag);
1622
1623     length = hrd->au_cpb_removal_delay_length_minus1 + 1;
1624     u(length, au_cpb_removal_delay_delta_minus1, 0, MAX_UINT_BITS(length));
1625
1626     if (hrd->nal_hrd_parameters_present_flag) {
1627         for (i = 0; i <= hrd->cpb_cnt_minus1[0]; i++) {
1628             length = hrd->initial_cpb_removal_delay_length_minus1 + 1;
1629
1630             us(length, nal_initial_cpb_removal_delay[i],
1631                0, MAX_UINT_BITS(length), 1, i);
1632             us(length, nal_initial_cpb_removal_offset[i],
1633                0, MAX_UINT_BITS(length), 1, i);
1634
1635             if (hrd->sub_pic_hrd_params_present_flag ||
1636                 current->irap_cpb_params_present_flag) {
1637                 us(length, nal_initial_alt_cpb_removal_delay[i],
1638                    0, MAX_UINT_BITS(length), 1, i);
1639                 us(length, nal_initial_alt_cpb_removal_offset[i],
1640                    0, MAX_UINT_BITS(length), 1, i);
1641             }
1642         }
1643     }
1644     if (hrd->vcl_hrd_parameters_present_flag) {
1645         for (i = 0; i <= hrd->cpb_cnt_minus1[0]; i++) {
1646             length = hrd->initial_cpb_removal_delay_length_minus1 + 1;
1647
1648             us(length, vcl_initial_cpb_removal_delay[i],
1649                0, MAX_UINT_BITS(length), 1, i);
1650             us(length, vcl_initial_cpb_removal_offset[i],
1651                0, MAX_UINT_BITS(length), 1, i);
1652
1653             if (hrd->sub_pic_hrd_params_present_flag ||
1654                 current->irap_cpb_params_present_flag) {
1655                 us(length, vcl_initial_alt_cpb_removal_delay[i],
1656                    0, MAX_UINT_BITS(length), 1, i);
1657                 us(length, vcl_initial_alt_cpb_removal_offset[i],
1658                    0, MAX_UINT_BITS(length), 1, i);
1659             }
1660         }
1661     }
1662
1663 #ifdef READ
1664     // payload_extension_present() - true if we are before the last 1-bit
1665     // in the payload structure, which must be in the last byte.
1666     end_pos = get_bits_count(rw);
1667     bits_left = *payload_size * 8 - (end_pos - start_pos);
1668     if (bits_left > 0 &&
1669         (bits_left > 7 || ff_ctz(show_bits(rw, bits_left)) < bits_left - 1))
1670         flag(use_alt_cpb_params_flag);
1671     else
1672         infer(use_alt_cpb_params_flag, 0);
1673 #else
1674     if (current->use_alt_cpb_params_flag)
1675         flag(use_alt_cpb_params_flag);
1676 #endif
1677
1678     return 0;
1679 }
1680
1681 static int FUNC(sei_pic_timing)(CodedBitstreamContext *ctx, RWContext *rw,
1682                                 H265RawSEIPicTiming *current)
1683 {
1684     CodedBitstreamH265Context *h265 = ctx->priv_data;
1685     const H265RawSPS *sps;
1686     const H265RawHRDParameters *hrd;
1687     int err, expected_source_scan_type, i, length;
1688
1689     HEADER("Picture Timing");
1690
1691     sps = h265->active_sps;
1692     if (!sps) {
1693         av_log(ctx->log_ctx, AV_LOG_ERROR,
1694                "No active SPS for pic_timing.\n");
1695         return AVERROR_INVALIDDATA;
1696     }
1697
1698     expected_source_scan_type = 2 -
1699         2 * sps->profile_tier_level.general_interlaced_source_flag -
1700         sps->profile_tier_level.general_progressive_source_flag;
1701
1702     if (sps->vui.frame_field_info_present_flag) {
1703         u(4, pic_struct, 0, 12);
1704         u(2, source_scan_type,
1705           expected_source_scan_type >= 0 ? expected_source_scan_type : 0,
1706           expected_source_scan_type >= 0 ? expected_source_scan_type : 2);
1707         flag(duplicate_flag);
1708     } else {
1709         infer(pic_struct, 0);
1710         infer(source_scan_type,
1711               expected_source_scan_type >= 0 ? expected_source_scan_type : 2);
1712         infer(duplicate_flag, 0);
1713     }
1714
1715     if (sps->vui_parameters_present_flag &&
1716         sps->vui.vui_hrd_parameters_present_flag)
1717         hrd = &sps->vui.hrd_parameters;
1718     else
1719         hrd = NULL;
1720     if (hrd && (hrd->nal_hrd_parameters_present_flag ||
1721                 hrd->vcl_hrd_parameters_present_flag)) {
1722         length = hrd->au_cpb_removal_delay_length_minus1 + 1;
1723         u(length, au_cpb_removal_delay_minus1, 0, MAX_UINT_BITS(length));
1724
1725         length = hrd->dpb_output_delay_length_minus1 + 1;
1726         u(length, pic_dpb_output_delay, 0, MAX_UINT_BITS(length));
1727
1728         if (hrd->sub_pic_hrd_params_present_flag) {
1729             length = hrd->dpb_output_delay_du_length_minus1 + 1;
1730             u(length, pic_dpb_output_du_delay, 0, MAX_UINT_BITS(length));
1731         }
1732
1733         if (hrd->sub_pic_hrd_params_present_flag &&
1734             hrd->sub_pic_cpb_params_in_pic_timing_sei_flag) {
1735             // Each decoding unit must contain at least one slice segment.
1736             ue(num_decoding_units_minus1, 0, HEVC_MAX_SLICE_SEGMENTS);
1737             flag(du_common_cpb_removal_delay_flag);
1738
1739             length = hrd->du_cpb_removal_delay_increment_length_minus1 + 1;
1740             if (current->du_common_cpb_removal_delay_flag)
1741                 u(length, du_common_cpb_removal_delay_increment_minus1,
1742                   0, MAX_UINT_BITS(length));
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                     us(length, du_cpb_removal_delay_increment_minus1[i],
1750                       0, MAX_UINT_BITS(length), 1, i);
1751             }
1752         }
1753     }
1754
1755     return 0;
1756 }
1757
1758 static int FUNC(sei_pan_scan_rect)(CodedBitstreamContext *ctx, RWContext *rw,
1759                                    H265RawSEIPanScanRect *current)
1760 {
1761     int err, i;
1762
1763     HEADER("Pan-Scan Rectangle");
1764
1765     ue(pan_scan_rect_id, 0, UINT32_MAX - 1);
1766     flag(pan_scan_rect_cancel_flag);
1767
1768     if (!current->pan_scan_rect_cancel_flag) {
1769         ue(pan_scan_cnt_minus1, 0, 2);
1770
1771         for (i = 0; i <= current->pan_scan_cnt_minus1; i++) {
1772             ses(pan_scan_rect_left_offset[i],   INT32_MIN + 1, INT32_MAX, 1, i);
1773             ses(pan_scan_rect_right_offset[i],  INT32_MIN + 1, INT32_MAX, 1, i);
1774             ses(pan_scan_rect_top_offset[i],    INT32_MIN + 1, INT32_MAX, 1, i);
1775             ses(pan_scan_rect_bottom_offset[i], INT32_MIN + 1, INT32_MAX, 1, i);
1776         }
1777
1778         flag(pan_scan_rect_persistence_flag);
1779     }
1780
1781     return 0;
1782 }
1783
1784 static int FUNC(sei_user_data_registered)(CodedBitstreamContext *ctx, RWContext *rw,
1785                                           H265RawSEIUserDataRegistered *current,
1786                                           uint32_t *payload_size)
1787 {
1788     int err, i, j;
1789
1790     HEADER("User Data Registered ITU-T T.35");
1791
1792     u(8, itu_t_t35_country_code, 0x00, 0xff);
1793     if (current->itu_t_t35_country_code != 0xff)
1794         i = 1;
1795     else {
1796         u(8, itu_t_t35_country_code_extension_byte, 0x00, 0xff);
1797         i = 2;
1798     }
1799
1800 #ifdef READ
1801     if (*payload_size < i) {
1802         av_log(ctx->log_ctx, AV_LOG_ERROR,
1803                "Invalid SEI user data registered payload.\n");
1804         return AVERROR_INVALIDDATA;
1805     }
1806     current->data_length = *payload_size - i;
1807 #else
1808     *payload_size = i + current->data_length;
1809 #endif
1810
1811     allocate(current->data, current->data_length);
1812     for (j = 0; j < current->data_length; j++)
1813         xu(8, itu_t_t35_payload_byte[i], current->data[j], 0x00, 0xff, 1, i + j);
1814
1815     return 0;
1816 }
1817
1818 static int FUNC(sei_user_data_unregistered)(CodedBitstreamContext *ctx, RWContext *rw,
1819                                             H265RawSEIUserDataUnregistered *current,
1820                                             uint32_t *payload_size)
1821 {
1822     int err, i;
1823
1824     HEADER("User Data Unregistered");
1825
1826 #ifdef READ
1827     if (*payload_size < 16) {
1828         av_log(ctx->log_ctx, AV_LOG_ERROR,
1829                "Invalid SEI user data unregistered payload.\n");
1830         return AVERROR_INVALIDDATA;
1831     }
1832     current->data_length = *payload_size - 16;
1833 #else
1834     *payload_size = 16 + current->data_length;
1835 #endif
1836
1837     for (i = 0; i < 16; i++)
1838         us(8, uuid_iso_iec_11578[i], 0x00, 0xff, 1, i);
1839
1840     allocate(current->data, current->data_length);
1841
1842     for (i = 0; i < current->data_length; i++)
1843         xu(8, user_data_payload_byte[i], current->data[i], 0x00, 0xff, 1, i);
1844
1845     return 0;
1846 }
1847
1848 static int FUNC(sei_recovery_point)(CodedBitstreamContext *ctx, RWContext *rw,
1849                                     H265RawSEIRecoveryPoint *current)
1850 {
1851     int err;
1852
1853     HEADER("Recovery Point");
1854
1855     se(recovery_poc_cnt, -32768, 32767);
1856
1857     flag(exact_match_flag);
1858     flag(broken_link_flag);
1859
1860     return 0;
1861 }
1862
1863 static int FUNC(sei_display_orientation)(CodedBitstreamContext *ctx, RWContext *rw,
1864                                          H265RawSEIDisplayOrientation *current)
1865 {
1866     int err;
1867
1868     HEADER("Display Orientation");
1869
1870     flag(display_orientation_cancel_flag);
1871     if (!current->display_orientation_cancel_flag) {
1872         flag(hor_flip);
1873         flag(ver_flip);
1874         u(16, anticlockwise_rotation, 0, 65535);
1875         flag(display_orientation_persistence_flag);
1876     }
1877
1878     return 0;
1879 }
1880
1881 static int FUNC(sei_active_parameter_sets)(CodedBitstreamContext *ctx, RWContext *rw,
1882                                            H265RawSEIActiveParameterSets *current)
1883 {
1884     CodedBitstreamH265Context *h265 = ctx->priv_data;
1885     const H265RawVPS *vps;
1886     int err, i;
1887
1888     HEADER("Active Parameter Sets");
1889
1890     u(4, active_video_parameter_set_id, 0, HEVC_MAX_VPS_COUNT);
1891     vps = h265->vps[current->active_video_parameter_set_id];
1892     if (!vps) {
1893         av_log(ctx->log_ctx, AV_LOG_ERROR, "VPS id %d not available for active "
1894                "parameter sets.\n", current->active_video_parameter_set_id);
1895         return AVERROR_INVALIDDATA;
1896     }
1897     h265->active_vps = vps;
1898
1899     flag(self_contained_cvs_flag);
1900     flag(no_parameter_set_update_flag);
1901
1902     ue(num_sps_ids_minus1, 0, HEVC_MAX_SPS_COUNT - 1);
1903     for (i = 0; i <= current->num_sps_ids_minus1; i++)
1904         ues(active_seq_parameter_set_id[i], 0, HEVC_MAX_SPS_COUNT - 1, 1, i);
1905
1906     for (i = vps->vps_base_layer_internal_flag;
1907          i <= FFMIN(62, vps->vps_max_layers_minus1); i++) {
1908         ues(layer_sps_idx[i], 0, current->num_sps_ids_minus1, 1, i);
1909
1910         if (i == 0)
1911             h265->active_sps = h265->sps[current->active_seq_parameter_set_id[current->layer_sps_idx[0]]];
1912     }
1913
1914     return 0;
1915 }
1916
1917 static int FUNC(sei_decoded_picture_hash)(CodedBitstreamContext *ctx, RWContext *rw,
1918                                           H265RawSEIDecodedPictureHash *current)
1919 {
1920     CodedBitstreamH265Context *h265 = ctx->priv_data;
1921     const H265RawSPS *sps = h265->active_sps;
1922     int err, c, i;
1923
1924     HEADER("Decoded Picture Hash");
1925
1926     if (!sps) {
1927         av_log(ctx->log_ctx, AV_LOG_ERROR,
1928                "No active SPS for decoded picture hash.\n");
1929         return AVERROR_INVALIDDATA;
1930     }
1931
1932     u(8, hash_type, 0, 2);
1933
1934     for (c = 0; c < (sps->chroma_format_idc == 0 ? 1 : 3); c++) {
1935         if (current->hash_type == 0) {
1936             for (i = 0; i < 16; i++)
1937                 us(8, picture_md5[c][i], 0x00, 0xff, 2, c, i);
1938         } else if (current->hash_type == 1) {
1939             us(16, picture_crc[c], 0x0000, 0xffff, 1, c);
1940         } else if (current->hash_type == 2) {
1941             us(32, picture_checksum[c], 0x00000000, 0xffffffff, 1, c);
1942         }
1943     }
1944
1945     return 0;
1946 }
1947
1948 static int FUNC(sei_time_code)(CodedBitstreamContext *ctx, RWContext *rw,
1949                                H265RawSEITimeCode *current)
1950 {
1951     int err, i;
1952
1953     HEADER("Time Code");
1954
1955     u(2, num_clock_ts, 1, 3);
1956
1957     for (i = 0; i < current->num_clock_ts; i++) {
1958         flags(clock_timestamp_flag[i],   1, i);
1959
1960         if (current->clock_timestamp_flag[i]) {
1961             flags(units_field_based_flag[i], 1, i);
1962             us(5, counting_type[i], 0, 6,    1, i);
1963             flags(full_timestamp_flag[i],    1, i);
1964             flags(discontinuity_flag[i],     1, i);
1965             flags(cnt_dropped_flag[i],       1, i);
1966
1967             us(9, n_frames[i], 0, MAX_UINT_BITS(9), 1, i);
1968
1969             if (current->full_timestamp_flag[i]) {
1970                 us(6, seconds_value[i], 0, 59, 1, i);
1971                 us(6, minutes_value[i], 0, 59, 1, i);
1972                 us(5, hours_value[i],   0, 23, 1, i);
1973             } else {
1974                 flags(seconds_flag[i], 1, i);
1975                 if (current->seconds_flag[i]) {
1976                     us(6, seconds_value[i], 0, 59, 1, i);
1977                     flags(minutes_flag[i], 1, i);
1978                     if (current->minutes_flag[i]) {
1979                         us(6, minutes_value[i], 0, 59, 1, i);
1980                         flags(hours_flag[i], 1, i);
1981                         if (current->hours_flag[i])
1982                             us(5, hours_value[i], 0, 23, 1, i);
1983                     }
1984                 }
1985             }
1986
1987             us(5, time_offset_length[i], 0, 31, 1, i);
1988             if (current->time_offset_length[i] > 0)
1989                 us(current->time_offset_length[i], time_offset_value[i],
1990                    0, MAX_UINT_BITS(current->time_offset_length[i]), 1, i);
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     u(16, max_content_light_level, 0, MAX_UINT_BITS(16));
2028     u(16, max_pic_average_light_level, 0, MAX_UINT_BITS(16));
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     u(8, preferred_transfer_characteristics, 0, 255);
2042
2043     return 0;
2044 }
2045
2046 static int FUNC(sei_payload)(CodedBitstreamContext *ctx, RWContext *rw,
2047                              H265RawSEIPayload *current, int prefix)
2048 {
2049     int err, i;
2050     int start_position, end_position;
2051
2052 #ifdef READ
2053     start_position = get_bits_count(rw);
2054 #else
2055     start_position = put_bits_count(rw);
2056 #endif
2057
2058     switch (current->payload_type) {
2059 #define SEI_TYPE_CHECK_VALID(name, prefix_valid, suffix_valid) do { \
2060             if (prefix && !prefix_valid) { \
2061                 av_log(ctx->log_ctx, AV_LOG_ERROR, "SEI type %s invalid " \
2062                        "as prefix SEI!\n", #name); \
2063                 return AVERROR_INVALIDDATA; \
2064             } \
2065             if (!prefix && !suffix_valid) { \
2066                 av_log(ctx->log_ctx, AV_LOG_ERROR, "SEI type %s invalid " \
2067                        "as suffix SEI!\n", #name); \
2068                 return AVERROR_INVALIDDATA; \
2069             } \
2070         } while (0)
2071 #define SEI_TYPE_N(type, prefix_valid, suffix_valid, name) \
2072     case HEVC_SEI_TYPE_ ## type: \
2073         SEI_TYPE_CHECK_VALID(name, prefix_valid, suffix_valid); \
2074         CHECK(FUNC(sei_ ## name)(ctx, rw, &current->payload.name)); \
2075         break
2076 #define SEI_TYPE_S(type, prefix_valid, suffix_valid, name) \
2077     case HEVC_SEI_TYPE_ ## type: \
2078         SEI_TYPE_CHECK_VALID(name, prefix_valid, suffix_valid); \
2079         CHECK(FUNC(sei_ ## name)(ctx, rw, &current->payload.name, \
2080                                  &current->payload_size)); \
2081         break
2082
2083         SEI_TYPE_S(BUFFERING_PERIOD,         1, 0, buffering_period);
2084         SEI_TYPE_N(PICTURE_TIMING,           1, 0, pic_timing);
2085         SEI_TYPE_N(PAN_SCAN_RECT,            1, 0, pan_scan_rect);
2086         SEI_TYPE_S(USER_DATA_REGISTERED_ITU_T_T35,
2087                                              1, 1, user_data_registered);
2088         SEI_TYPE_S(USER_DATA_UNREGISTERED,   1, 1, user_data_unregistered);
2089         SEI_TYPE_N(RECOVERY_POINT,           1, 0, recovery_point);
2090         SEI_TYPE_N(DISPLAY_ORIENTATION,      1, 0, display_orientation);
2091         SEI_TYPE_N(ACTIVE_PARAMETER_SETS,    1, 0, active_parameter_sets);
2092         SEI_TYPE_N(DECODED_PICTURE_HASH,     0, 1, decoded_picture_hash);
2093         SEI_TYPE_N(TIME_CODE,                1, 0, time_code);
2094         SEI_TYPE_N(MASTERING_DISPLAY_INFO,   1, 0, mastering_display);
2095         SEI_TYPE_N(CONTENT_LIGHT_LEVEL_INFO, 1, 0, content_light_level);
2096         SEI_TYPE_N(ALTERNATIVE_TRANSFER_CHARACTERISTICS,
2097                                              1, 0, alternative_transfer_characteristics);
2098
2099 #undef SEI_TYPE
2100     default:
2101         {
2102 #ifdef READ
2103             current->payload.other.data_length = current->payload_size;
2104 #endif
2105             allocate(current->payload.other.data, current->payload.other.data_length);
2106
2107             for (i = 0; i < current->payload_size; i++)
2108                 xu(8, payload_byte[i], current->payload.other.data[i], 0, 255,
2109                    1, i);
2110         }
2111     }
2112
2113     if (byte_alignment(rw)) {
2114         fixed(1, bit_equal_to_one, 1);
2115         while (byte_alignment(rw))
2116             fixed(1, bit_equal_to_zero, 0);
2117     }
2118
2119 #ifdef READ
2120     end_position = get_bits_count(rw);
2121     if (end_position < start_position + 8 * current->payload_size) {
2122         av_log(ctx->log_ctx, AV_LOG_ERROR, "Incorrect SEI payload length: "
2123                "header %"PRIu32" bits, actually %d bits.\n",
2124                8 * current->payload_size,
2125                end_position - start_position);
2126         return AVERROR_INVALIDDATA;
2127     }
2128 #else
2129     end_position = put_bits_count(rw);
2130     current->payload_size = (end_position - start_position) >> 3;
2131 #endif
2132
2133     return 0;
2134 }
2135
2136 static int FUNC(sei)(CodedBitstreamContext *ctx, RWContext *rw,
2137                      H265RawSEI *current, int prefix)
2138 {
2139     int err, k;
2140
2141     if (prefix)
2142         HEADER("Prefix Supplemental Enhancement Information");
2143     else
2144         HEADER("Suffix Supplemental Enhancement Information");
2145
2146     CHECK(FUNC(nal_unit_header)(ctx, rw, &current->nal_unit_header,
2147                                 prefix ? HEVC_NAL_SEI_PREFIX
2148                                        : HEVC_NAL_SEI_SUFFIX));
2149
2150 #ifdef READ
2151     for (k = 0; k < H265_MAX_SEI_PAYLOADS; k++) {
2152         uint32_t payload_type = 0;
2153         uint32_t payload_size = 0;
2154         uint32_t tmp;
2155
2156         while (show_bits(rw, 8) == 0xff) {
2157             fixed(8, ff_byte, 0xff);
2158             payload_type += 255;
2159         }
2160         xu(8, last_payload_type_byte, tmp, 0, 254, 0);
2161         payload_type += tmp;
2162
2163         while (show_bits(rw, 8) == 0xff) {
2164             fixed(8, ff_byte, 0xff);
2165             payload_size += 255;
2166         }
2167         xu(8, last_payload_size_byte, tmp, 0, 254, 0);
2168         payload_size += tmp;
2169
2170         current->payload[k].payload_type = payload_type;
2171         current->payload[k].payload_size = payload_size;
2172
2173         CHECK(FUNC(sei_payload)(ctx, rw, &current->payload[k], prefix));
2174
2175         if (!cbs_h2645_read_more_rbsp_data(rw))
2176             break;
2177     }
2178     if (k >= H265_MAX_SEI_PAYLOADS) {
2179         av_log(ctx->log_ctx, AV_LOG_ERROR, "Too many payloads in "
2180                "SEI message: found %d.\n", k);
2181         return AVERROR_INVALIDDATA;
2182     }
2183     current->payload_count = k + 1;
2184 #else
2185     for (k = 0; k < current->payload_count; k++) {
2186         PutBitContext start_state;
2187         uint32_t tmp;
2188         int need_size, i;
2189
2190         // Somewhat clumsy: we write the payload twice when
2191         // we don't know the size in advance.  This will mess
2192         // with trace output, but is otherwise harmless.
2193         start_state = *rw;
2194         need_size = !current->payload[k].payload_size;
2195         for (i = 0; i < 1 + need_size; i++) {
2196             *rw = start_state;
2197
2198             tmp = current->payload[k].payload_type;
2199             while (tmp >= 255) {
2200                 fixed(8, ff_byte, 0xff);
2201                 tmp -= 255;
2202             }
2203             xu(8, last_payload_type_byte, tmp, 0, 254, 0);
2204
2205             tmp = current->payload[k].payload_size;
2206             while (tmp >= 255) {
2207                 fixed(8, ff_byte, 0xff);
2208                 tmp -= 255;
2209             }
2210             xu(8, last_payload_size_byte, tmp, 0, 254, 0);
2211
2212             CHECK(FUNC(sei_payload)(ctx, rw, &current->payload[k], prefix));
2213         }
2214     }
2215 #endif
2216
2217     CHECK(FUNC(rbsp_trailing_bits)(ctx, rw));
2218
2219     return 0;
2220 }