]> git.sesse.net Git - ffmpeg/blob - libavcodec/cbs_av1_syntax_template.c
avcodec/cbs_av1: implement missing set_frame_refs() function
[ffmpeg] / libavcodec / cbs_av1_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(obu_header)(CodedBitstreamContext *ctx, RWContext *rw,
20                             AV1RawOBUHeader *current)
21 {
22     int err;
23     av_unused int zero = 0;
24
25     HEADER("OBU header");
26
27     fc(1, obu_forbidden_bit, 0, 0);
28
29     fc(4, obu_type, 0, AV1_OBU_PADDING);
30     flag(obu_extension_flag);
31     flag(obu_has_size_field);
32
33     fc(1, obu_reserved_1bit, 0, 0);
34
35     if (current->obu_extension_flag) {
36         fb(3, temporal_id);
37         fb(2, spatial_id);
38         fc(3, extension_header_reserved_3bits, 0, 0);
39     }
40
41     return 0;
42 }
43
44 static int FUNC(trailing_bits)(CodedBitstreamContext *ctx, RWContext *rw, int nb_bits)
45 {
46     int err;
47
48     av_assert0(nb_bits > 0);
49
50     fixed(1, trailing_one_bit, 1);
51     --nb_bits;
52
53     while (nb_bits > 0) {
54         fixed(1, trailing_zero_bit, 0);
55         --nb_bits;
56     }
57
58     return 0;
59 }
60
61 static int FUNC(byte_alignment)(CodedBitstreamContext *ctx, RWContext *rw)
62 {
63     int err;
64
65     while (byte_alignment(rw) != 0)
66         fixed(1, zero_bit, 0);
67
68     return 0;
69 }
70
71 static int FUNC(color_config)(CodedBitstreamContext *ctx, RWContext *rw,
72                               AV1RawColorConfig *current, int seq_profile)
73 {
74     CodedBitstreamAV1Context *priv = ctx->priv_data;
75     int err;
76
77     flag(high_bitdepth);
78
79     if (seq_profile == FF_PROFILE_AV1_PROFESSIONAL &&
80         current->high_bitdepth) {
81         flag(twelve_bit);
82         priv->bit_depth = current->twelve_bit ? 12 : 10;
83     } else {
84         priv->bit_depth = current->high_bitdepth ? 10 : 8;
85     }
86
87     if (seq_profile == FF_PROFILE_AV1_HIGH)
88         infer(mono_chrome, 0);
89     else
90         flag(mono_chrome);
91     priv->num_planes = current->mono_chrome ? 1 : 3;
92
93     flag(color_description_present_flag);
94     if (current->color_description_present_flag) {
95         fb(8, color_primaries);
96         fb(8, transfer_characteristics);
97         fb(8, matrix_coefficients);
98     } else {
99         infer(color_primaries,          AVCOL_PRI_UNSPECIFIED);
100         infer(transfer_characteristics, AVCOL_TRC_UNSPECIFIED);
101         infer(matrix_coefficients,      AVCOL_SPC_UNSPECIFIED);
102     }
103
104     if (current->mono_chrome) {
105         flag(color_range);
106
107         infer(subsampling_x, 1);
108         infer(subsampling_y, 1);
109         infer(chroma_sample_position, AV1_CSP_UNKNOWN);
110         infer(separate_uv_delta_q, 0);
111
112     } else if (current->color_primaries          == AVCOL_PRI_BT709 &&
113                current->transfer_characteristics == AVCOL_TRC_IEC61966_2_1 &&
114                current->matrix_coefficients      == AVCOL_SPC_RGB) {
115         infer(color_range,   1);
116         infer(subsampling_x, 0);
117         infer(subsampling_y, 0);
118         flag(separate_uv_delta_q);
119
120     } else {
121         flag(color_range);
122
123         if (seq_profile == FF_PROFILE_AV1_MAIN) {
124             infer(subsampling_x, 1);
125             infer(subsampling_y, 1);
126         } else if (seq_profile == FF_PROFILE_AV1_HIGH) {
127             infer(subsampling_x, 0);
128             infer(subsampling_y, 0);
129         } else {
130             if (priv->bit_depth == 12) {
131                 fb(1, subsampling_x);
132                 if (current->subsampling_x)
133                     fb(1, subsampling_y);
134                 else
135                     infer(subsampling_y, 0);
136             } else {
137                 infer(subsampling_x, 1);
138                 infer(subsampling_y, 0);
139             }
140         }
141         if (current->subsampling_x && current->subsampling_y) {
142             fc(2, chroma_sample_position, AV1_CSP_UNKNOWN,
143                                           AV1_CSP_COLOCATED);
144         }
145
146         flag(separate_uv_delta_q);
147     }
148
149     return 0;
150 }
151
152 static int FUNC(timing_info)(CodedBitstreamContext *ctx, RWContext *rw,
153                              AV1RawTimingInfo *current)
154 {
155     int err;
156
157     fc(32, num_units_in_display_tick, 1, MAX_UINT_BITS(32));
158     fc(32, time_scale,                1, MAX_UINT_BITS(32));
159
160     flag(equal_picture_interval);
161     if (current->equal_picture_interval)
162         uvlc(num_ticks_per_picture_minus_1, 0, MAX_UINT_BITS(32) - 1);
163
164     return 0;
165 }
166
167 static int FUNC(decoder_model_info)(CodedBitstreamContext *ctx, RWContext *rw,
168                                     AV1RawDecoderModelInfo *current)
169 {
170     int err;
171
172     fb(5, buffer_delay_length_minus_1);
173     fb(32, num_units_in_decoding_tick);
174     fb(5,  buffer_removal_time_length_minus_1);
175     fb(5,  frame_presentation_time_length_minus_1);
176
177     return 0;
178 }
179
180 static int FUNC(sequence_header_obu)(CodedBitstreamContext *ctx, RWContext *rw,
181                                      AV1RawSequenceHeader *current)
182 {
183     int i, err;
184
185     HEADER("Sequence Header");
186
187     fc(3, seq_profile, FF_PROFILE_AV1_MAIN,
188                        FF_PROFILE_AV1_PROFESSIONAL);
189     flag(still_picture);
190     flag(reduced_still_picture_header);
191
192     if (current->reduced_still_picture_header) {
193         infer(timing_info_present_flag,           0);
194         infer(decoder_model_info_present_flag,    0);
195         infer(initial_display_delay_present_flag, 0);
196         infer(operating_points_cnt_minus_1,       0);
197         infer(operating_point_idc[0],             0);
198
199         fb(5, seq_level_idx[0]);
200
201         infer(seq_tier[0], 0);
202         infer(decoder_model_present_for_this_op[0],         0);
203         infer(initial_display_delay_present_for_this_op[0], 0);
204
205     } else {
206         flag(timing_info_present_flag);
207         if (current->timing_info_present_flag) {
208             CHECK(FUNC(timing_info)(ctx, rw, &current->timing_info));
209
210             flag(decoder_model_info_present_flag);
211             if (current->decoder_model_info_present_flag) {
212                 CHECK(FUNC(decoder_model_info)
213                           (ctx, rw, &current->decoder_model_info));
214             }
215         } else {
216             infer(decoder_model_info_present_flag, 0);
217         }
218
219         flag(initial_display_delay_present_flag);
220
221         fb(5, operating_points_cnt_minus_1);
222         for (i = 0; i <= current->operating_points_cnt_minus_1; i++) {
223             fbs(12, operating_point_idc[i], 1, i);
224             fbs(5,  seq_level_idx[i], 1, i);
225
226             if (current->seq_level_idx[i] > 7)
227                 flags(seq_tier[i], 1, i);
228             else
229                 infer(seq_tier[i], 0);
230
231             if (current->decoder_model_info_present_flag) {
232                 flags(decoder_model_present_for_this_op[i], 1, i);
233                 if (current->decoder_model_present_for_this_op[i]) {
234                     int n = current->decoder_model_info.buffer_delay_length_minus_1 + 1;
235                     fbs(n, decoder_buffer_delay[i], 1, i);
236                     fbs(n, encoder_buffer_delay[i], 1, i);
237                     flags(low_delay_mode_flag[i], 1, i);
238                 }
239             } else {
240                 infer(decoder_model_present_for_this_op[i], 0);
241             }
242
243             if (current->initial_display_delay_present_flag) {
244                 flags(initial_display_delay_present_for_this_op[i], 1, i);
245                 if (current->initial_display_delay_present_for_this_op[i])
246                     fbs(4, initial_display_delay_minus_1[i], 1, i);
247             }
248         }
249     }
250
251     fb(4, frame_width_bits_minus_1);
252     fb(4, frame_height_bits_minus_1);
253
254     fb(current->frame_width_bits_minus_1  + 1, max_frame_width_minus_1);
255     fb(current->frame_height_bits_minus_1 + 1, max_frame_height_minus_1);
256
257     if (current->reduced_still_picture_header)
258         infer(frame_id_numbers_present_flag, 0);
259     else
260         flag(frame_id_numbers_present_flag);
261     if (current->frame_id_numbers_present_flag) {
262         fb(4, delta_frame_id_length_minus_2);
263         fb(3, additional_frame_id_length_minus_1);
264     }
265
266     flag(use_128x128_superblock);
267     flag(enable_filter_intra);
268     flag(enable_intra_edge_filter);
269
270     if (current->reduced_still_picture_header) {
271         infer(enable_intraintra_compound, 0);
272         infer(enable_masked_compound,     0);
273         infer(enable_warped_motion,       0);
274         infer(enable_dual_filter,         0);
275         infer(enable_order_hint,          0);
276         infer(enable_jnt_comp,            0);
277         infer(enable_ref_frame_mvs,       0);
278
279         infer(seq_force_screen_content_tools,
280               AV1_SELECT_SCREEN_CONTENT_TOOLS);
281         infer(seq_force_integer_mv,
282               AV1_SELECT_INTEGER_MV);
283     } else {
284         flag(enable_intraintra_compound);
285         flag(enable_masked_compound);
286         flag(enable_warped_motion);
287         flag(enable_dual_filter);
288
289         flag(enable_order_hint);
290         if (current->enable_order_hint) {
291             flag(enable_jnt_comp);
292             flag(enable_ref_frame_mvs);
293         } else {
294             infer(enable_jnt_comp,      0);
295             infer(enable_ref_frame_mvs, 0);
296         }
297
298         flag(seq_choose_screen_content_tools);
299         if (current->seq_choose_screen_content_tools)
300             infer(seq_force_screen_content_tools,
301                   AV1_SELECT_SCREEN_CONTENT_TOOLS);
302         else
303             fb(1, seq_force_screen_content_tools);
304         if (current->seq_force_screen_content_tools > 0) {
305             flag(seq_choose_integer_mv);
306             if (current->seq_choose_integer_mv)
307                 infer(seq_force_integer_mv,
308                       AV1_SELECT_INTEGER_MV);
309             else
310                 fb(1, seq_force_integer_mv);
311         } else {
312             infer(seq_force_integer_mv, AV1_SELECT_INTEGER_MV);
313         }
314
315         if (current->enable_order_hint)
316             fb(3, order_hint_bits_minus_1);
317     }
318
319     flag(enable_superres);
320     flag(enable_cdef);
321     flag(enable_restoration);
322
323     CHECK(FUNC(color_config)(ctx, rw, &current->color_config,
324                              current->seq_profile));
325
326     flag(film_grain_params_present);
327
328     return 0;
329 }
330
331 static int FUNC(temporal_delimiter_obu)(CodedBitstreamContext *ctx, RWContext *rw)
332 {
333     CodedBitstreamAV1Context *priv = ctx->priv_data;
334
335     HEADER("Temporal Delimiter");
336
337     priv->seen_frame_header = 0;
338
339     return 0;
340 }
341
342 static int FUNC(set_frame_refs)(CodedBitstreamContext *ctx, RWContext *rw,
343                                 AV1RawFrameHeader *current)
344 {
345     CodedBitstreamAV1Context *priv = ctx->priv_data;
346     const AV1RawSequenceHeader *seq = priv->sequence_header;
347     static const uint8_t ref_frame_list[AV1_NUM_REF_FRAMES - 2] = {
348         AV1_REF_FRAME_LAST2, AV1_REF_FRAME_LAST3, AV1_REF_FRAME_BWDREF,
349         AV1_REF_FRAME_ALTREF2, AV1_REF_FRAME_ALTREF
350     };
351     int8_t ref_frame_idx[AV1_REFS_PER_FRAME], used_frame[AV1_NUM_REF_FRAMES];
352     int8_t shifted_order_hints[AV1_NUM_REF_FRAMES];
353     int cur_frame_hint, latest_order_hint, earliest_order_hint, ref;
354     int i, j;
355
356     for (i = 0; i < AV1_REFS_PER_FRAME; i++)
357         ref_frame_idx[i] = -1;
358     ref_frame_idx[AV1_REF_FRAME_LAST - AV1_REF_FRAME_LAST] = current->last_frame_idx;
359     ref_frame_idx[AV1_REF_FRAME_GOLDEN - AV1_REF_FRAME_LAST] = current->golden_frame_idx;
360
361     for (i = 0; i < AV1_NUM_REF_FRAMES; i++)
362         used_frame[i] = 0;
363     used_frame[current->last_frame_idx] = 1;
364     used_frame[current->golden_frame_idx] = 1;
365
366     cur_frame_hint = 1 << (seq->order_hint_bits_minus_1);
367     for (i = 0; i < AV1_NUM_REF_FRAMES; i++)
368         shifted_order_hints[i] = cur_frame_hint +
369                                  cbs_av1_get_relative_dist(seq, priv->ref[i].order_hint,
370                                                            current->order_hint);
371
372     latest_order_hint = shifted_order_hints[current->last_frame_idx];
373     earliest_order_hint = shifted_order_hints[current->golden_frame_idx];
374
375     ref = -1;
376     for (i = 0; i < AV1_NUM_REF_FRAMES; i++) {
377         int hint = shifted_order_hints[i];
378         if (!used_frame[i] && hint >= cur_frame_hint &&
379             (ref < 0 || hint >= latest_order_hint)) {
380             ref = i;
381             latest_order_hint = hint;
382         }
383     }
384     if (ref >= 0) {
385         ref_frame_idx[AV1_REF_FRAME_ALTREF - AV1_REF_FRAME_LAST] = ref;
386         used_frame[ref] = 1;
387     }
388
389     ref = -1;
390     for (i = 0; i < AV1_NUM_REF_FRAMES; i++) {
391         int hint = shifted_order_hints[i];
392         if (!used_frame[i] && hint >= cur_frame_hint &&
393             (ref < 0 || hint < earliest_order_hint)) {
394             ref = i;
395             earliest_order_hint = hint;
396         }
397     }
398     if (ref >= 0) {
399         ref_frame_idx[AV1_REF_FRAME_BWDREF - AV1_REF_FRAME_LAST] = ref;
400         used_frame[ref] = 1;
401     }
402
403     ref = -1;
404     for (i = 0; i < AV1_NUM_REF_FRAMES; i++) {
405         int hint = shifted_order_hints[i];
406         if (!used_frame[i] && hint >= cur_frame_hint &&
407             (ref < 0 || hint < earliest_order_hint)) {
408             ref = i;
409             earliest_order_hint = hint;
410         }
411     }
412     if (ref >= 0) {
413         ref_frame_idx[AV1_REF_FRAME_ALTREF2 - AV1_REF_FRAME_LAST] = ref;
414         used_frame[ref] = 1;
415     }
416
417     for (i = 0; i < AV1_REFS_PER_FRAME - 2; i++) {
418         int ref_frame = ref_frame_list[i];
419         if (ref_frame_idx[ref_frame - AV1_REF_FRAME_LAST] < 0 ) {
420             ref = -1;
421             for (j = 0; j < AV1_NUM_REF_FRAMES; j++) {
422                 int hint = shifted_order_hints[j];
423                 if (!used_frame[j] && hint < cur_frame_hint &&
424                     (ref < 0 || hint >= latest_order_hint)) {
425                     ref = j;
426                     latest_order_hint = hint;
427                 }
428             }
429             if (ref >= 0) {
430                 ref_frame_idx[ref_frame - AV1_REF_FRAME_LAST] = ref;
431                 used_frame[ref] = 1;
432             }
433         }
434     }
435
436     ref = -1;
437     for (i = 0; i < AV1_NUM_REF_FRAMES; i++) {
438         int hint = shifted_order_hints[i];
439         if (ref < 0 || hint < earliest_order_hint) {
440             ref = i;
441             earliest_order_hint = hint;
442         }
443     }
444     for (i = 0; i < AV1_REFS_PER_FRAME; i++) {
445         if (ref_frame_idx[i] < 0)
446             ref_frame_idx[i] = ref;
447         infer(ref_frame_idx[i], ref_frame_idx[i]);
448     }
449
450     return 0;
451 }
452
453 static int FUNC(superres_params)(CodedBitstreamContext *ctx, RWContext *rw,
454                                  AV1RawFrameHeader *current)
455 {
456     CodedBitstreamAV1Context  *priv = ctx->priv_data;
457     const AV1RawSequenceHeader *seq = priv->sequence_header;
458     int denom, err;
459
460     if (seq->enable_superres)
461         flag(use_superres);
462     else
463         infer(use_superres, 0);
464
465     if (current->use_superres) {
466         fb(3, coded_denom);
467         denom = current->coded_denom + AV1_SUPERRES_DENOM_MIN;
468     } else {
469         denom = AV1_SUPERRES_NUM;
470     }
471
472     priv->upscaled_width = priv->frame_width;
473     priv->frame_width = (priv->upscaled_width * AV1_SUPERRES_NUM +
474                          denom / 2) / denom;
475
476     return 0;
477 }
478
479 static int FUNC(frame_size)(CodedBitstreamContext *ctx, RWContext *rw,
480                             AV1RawFrameHeader *current)
481 {
482     CodedBitstreamAV1Context  *priv = ctx->priv_data;
483     const AV1RawSequenceHeader *seq = priv->sequence_header;
484     int err;
485
486     if (current->frame_size_override_flag) {
487         fb(seq->frame_width_bits_minus_1 + 1,  frame_width_minus_1);
488         fb(seq->frame_height_bits_minus_1 + 1, frame_height_minus_1);
489
490         priv->frame_width  = current->frame_width_minus_1  + 1;
491         priv->frame_height = current->frame_height_minus_1 + 1;
492     } else {
493         priv->frame_width  = seq->max_frame_width_minus_1  + 1;
494         priv->frame_height = seq->max_frame_height_minus_1 + 1;
495     }
496
497     CHECK(FUNC(superres_params)(ctx, rw, current));
498
499     return 0;
500 }
501
502 static int FUNC(render_size)(CodedBitstreamContext *ctx, RWContext *rw,
503                              AV1RawFrameHeader *current)
504 {
505     CodedBitstreamAV1Context *priv = ctx->priv_data;
506     int err;
507
508     flag(render_and_frame_size_different);
509
510     if (current->render_and_frame_size_different) {
511         fb(16, render_width_minus_1);
512         fb(16, render_height_minus_1);
513
514         priv->render_width  = current->render_width_minus_1  + 1;
515         priv->render_height = current->render_height_minus_1 + 1;
516     } else {
517         priv->render_width  = priv->upscaled_width;
518         priv->render_height = priv->frame_height;
519     }
520
521     return 0;
522 }
523
524 static int FUNC(frame_size_with_refs)(CodedBitstreamContext *ctx, RWContext *rw,
525                                       AV1RawFrameHeader *current)
526 {
527     CodedBitstreamAV1Context *priv = ctx->priv_data;
528     int i, err;
529
530     for (i = 0; i < AV1_REFS_PER_FRAME; i++) {
531         flags(found_ref[i], 1, i);
532         if (current->found_ref[i]) {
533             AV1ReferenceFrameState *ref;
534
535             if (current->ref_frame_idx[i] < 0 ||
536                 !priv->ref[current->ref_frame_idx[i]].valid) {
537                 av_log(ctx->log_ctx, AV_LOG_ERROR,
538                        "Missing reference frame needed for frame size "
539                        "(ref = %d, ref_frame_idx = %d).\n",
540                        i, current->ref_frame_idx[i]);
541                 return AVERROR_INVALIDDATA;
542             }
543             ref = &priv->ref[current->ref_frame_idx[i]];
544
545             priv->upscaled_width = ref->upscaled_width;
546             priv->frame_width    = ref->frame_width;
547             priv->frame_height   = ref->frame_height;
548             priv->render_width   = ref->render_width;
549             priv->render_height  = ref->render_height;
550             break;
551         }
552     }
553
554     if (i >= AV1_REFS_PER_FRAME) {
555         CHECK(FUNC(frame_size)(ctx, rw, current));
556         CHECK(FUNC(render_size)(ctx, rw, current));
557     } else {
558         CHECK(FUNC(superres_params)(ctx, rw, current));
559     }
560
561     return 0;
562 }
563
564 static int FUNC(interpolation_filter)(CodedBitstreamContext *ctx, RWContext *rw,
565                                       AV1RawFrameHeader *current)
566 {
567     int err;
568
569     flag(is_filter_switchable);
570     if (current->is_filter_switchable)
571         infer(interpolation_filter,
572               AV1_INTERPOLATION_FILTER_SWITCHABLE);
573     else
574         fb(2, interpolation_filter);
575
576     return 0;
577 }
578
579 static int FUNC(tile_info)(CodedBitstreamContext *ctx, RWContext *rw,
580                            AV1RawFrameHeader *current)
581 {
582     CodedBitstreamAV1Context  *priv = ctx->priv_data;
583     const AV1RawSequenceHeader *seq = priv->sequence_header;
584     int mi_cols, mi_rows, sb_cols, sb_rows, sb_shift, sb_size;
585     int max_tile_width_sb, max_tile_height_sb, max_tile_area_sb;
586     int min_log2_tile_cols, max_log2_tile_cols, max_log2_tile_rows;
587     int min_log2_tiles, min_log2_tile_rows;
588     int i, err;
589
590     mi_cols = 2 * ((priv->frame_width  + 7) >> 3);
591     mi_rows = 2 * ((priv->frame_height + 7) >> 3);
592
593     sb_cols = seq->use_128x128_superblock ? ((mi_cols + 31) >> 5)
594                                           : ((mi_cols + 15) >> 4);
595     sb_rows = seq->use_128x128_superblock ? ((mi_rows + 31) >> 5)
596                                           : ((mi_rows + 15) >> 4);
597
598     sb_shift = seq->use_128x128_superblock ? 5 : 4;
599     sb_size  = sb_shift + 2;
600
601     max_tile_width_sb = AV1_MAX_TILE_WIDTH >> sb_size;
602     max_tile_area_sb  = AV1_MAX_TILE_AREA  >> (2 * sb_size);
603
604     min_log2_tile_cols = cbs_av1_tile_log2(max_tile_width_sb, sb_cols);
605     max_log2_tile_cols = cbs_av1_tile_log2(1, FFMIN(sb_cols, AV1_MAX_TILE_COLS));
606     max_log2_tile_rows = cbs_av1_tile_log2(1, FFMIN(sb_rows, AV1_MAX_TILE_ROWS));
607     min_log2_tiles = FFMAX(min_log2_tile_cols,
608                            cbs_av1_tile_log2(max_tile_area_sb, sb_rows * sb_cols));
609
610     flag(uniform_tile_spacing_flag);
611
612     if (current->uniform_tile_spacing_flag) {
613         int tile_width_sb, tile_height_sb;
614
615         increment(tile_cols_log2, min_log2_tile_cols, max_log2_tile_cols);
616
617         tile_width_sb = (sb_cols + (1 << current->tile_cols_log2) - 1) >>
618             current->tile_cols_log2;
619         current->tile_cols = (sb_cols + tile_width_sb - 1) / tile_width_sb;
620
621         min_log2_tile_rows = FFMAX(min_log2_tiles - current->tile_cols_log2, 0);
622
623         increment(tile_rows_log2, min_log2_tile_rows, max_log2_tile_rows);
624
625         tile_height_sb = (sb_rows + (1 << current->tile_rows_log2) - 1) >>
626             current->tile_rows_log2;
627         current->tile_rows = (sb_rows + tile_height_sb - 1) / tile_height_sb;
628
629     } else {
630         int widest_tile_sb, start_sb, size_sb, max_width, max_height;
631
632         widest_tile_sb = 0;
633
634         start_sb = 0;
635         for (i = 0; start_sb < sb_cols && i < AV1_MAX_TILE_COLS; i++) {
636             max_width = FFMIN(sb_cols - start_sb, max_tile_width_sb);
637             ns(max_width, width_in_sbs_minus_1[i], 1, i);
638             size_sb = current->width_in_sbs_minus_1[i] + 1;
639             widest_tile_sb = FFMAX(size_sb, widest_tile_sb);
640             start_sb += size_sb;
641         }
642         current->tile_cols_log2 = cbs_av1_tile_log2(1, i);
643         current->tile_cols = i;
644
645         if (min_log2_tiles > 0)
646             max_tile_area_sb = (sb_rows * sb_cols) >> (min_log2_tiles + 1);
647         else
648             max_tile_area_sb = sb_rows * sb_cols;
649         max_tile_height_sb = FFMAX(max_tile_area_sb / widest_tile_sb, 1);
650
651         start_sb = 0;
652         for (i = 0; start_sb < sb_rows && i < AV1_MAX_TILE_ROWS; i++) {
653             max_height = FFMIN(sb_rows - start_sb, max_tile_height_sb);
654             ns(max_height, height_in_sbs_minus_1[i], 1, i);
655             size_sb = current->height_in_sbs_minus_1[i] + 1;
656             start_sb += size_sb;
657         }
658         current->tile_rows_log2 = cbs_av1_tile_log2(1, i);
659         current->tile_rows = i;
660     }
661
662     if (current->tile_cols_log2 > 0 ||
663         current->tile_rows_log2 > 0) {
664         fb(current->tile_cols_log2 + current->tile_rows_log2,
665            context_update_tile_id);
666         fb(2, tile_size_bytes_minus1);
667     } else {
668         infer(context_update_tile_id, 0);
669     }
670
671     priv->tile_cols = current->tile_cols;
672     priv->tile_rows = current->tile_rows;
673
674     return 0;
675 }
676
677 static int FUNC(quantization_params)(CodedBitstreamContext *ctx, RWContext *rw,
678                                      AV1RawFrameHeader *current)
679 {
680     CodedBitstreamAV1Context  *priv = ctx->priv_data;
681     const AV1RawSequenceHeader *seq = priv->sequence_header;
682     int err;
683
684     fb(8, base_q_idx);
685
686     delta_q(delta_q_y_dc);
687
688     if (priv->num_planes > 1) {
689         if (seq->color_config.separate_uv_delta_q)
690             flag(diff_uv_delta);
691         else
692             infer(diff_uv_delta, 0);
693
694         delta_q(delta_q_u_dc);
695         delta_q(delta_q_u_ac);
696
697         if (current->diff_uv_delta) {
698             delta_q(delta_q_v_dc);
699             delta_q(delta_q_v_ac);
700         } else {
701             infer(delta_q_v_dc, current->delta_q_u_dc);
702             infer(delta_q_v_ac, current->delta_q_u_ac);
703         }
704     } else {
705         infer(delta_q_u_dc, 0);
706         infer(delta_q_u_ac, 0);
707         infer(delta_q_v_dc, 0);
708         infer(delta_q_v_ac, 0);
709     }
710
711     flag(using_qmatrix);
712     if (current->using_qmatrix) {
713         fb(4, qm_y);
714         fb(4, qm_u);
715         if (seq->color_config.separate_uv_delta_q)
716             fb(4, qm_v);
717         else
718             infer(qm_v, current->qm_u);
719     }
720
721     return 0;
722 }
723
724 static int FUNC(segmentation_params)(CodedBitstreamContext *ctx, RWContext *rw,
725                                      AV1RawFrameHeader *current)
726 {
727     static const uint8_t bits[AV1_SEG_LVL_MAX] = { 8, 6, 6, 6, 6, 3, 0, 0 };
728     static const uint8_t sign[AV1_SEG_LVL_MAX] = { 1, 1, 1, 1, 1, 0, 0, 0 };
729     int i, j, err;
730
731     flag(segmentation_enabled);
732
733     if (current->segmentation_enabled) {
734         if (current->primary_ref_frame == AV1_PRIMARY_REF_NONE) {
735             infer(segmentation_update_map,      1);
736             infer(segmentation_temporal_update, 0);
737             infer(segmentation_update_data,     1);
738         } else {
739             flag(segmentation_update_map);
740             if (current->segmentation_update_map)
741                 flag(segmentation_temporal_update);
742             else
743                 infer(segmentation_temporal_update, 0);
744             flag(segmentation_update_data);
745         }
746
747         if (current->segmentation_update_data) {
748             for (i = 0; i < AV1_MAX_SEGMENTS; i++) {
749                 for (j = 0; j < AV1_SEG_LVL_MAX; j++) {
750                     flags(feature_enabled[i][j], 2, i, j);
751
752                     if (current->feature_enabled[i][j] && bits[j] > 0) {
753                         if (sign[j])
754                             sus(1 + bits[j], feature_value[i][j], 2, i, j);
755                         else
756                             fbs(bits[j], feature_value[i][j], 2, i, j);
757                     } else {
758                         infer(feature_value[i][j], 0);
759                     }
760                 }
761             }
762         }
763     } else {
764         for (i = 0; i < AV1_MAX_SEGMENTS; i++) {
765             for (j = 0; j < AV1_SEG_LVL_MAX; j++) {
766                 infer(feature_enabled[i][j], 0);
767                 infer(feature_value[i][j],   0);
768             }
769         }
770     }
771
772     return 0;
773 }
774
775 static int FUNC(delta_q_params)(CodedBitstreamContext *ctx, RWContext *rw,
776                                 AV1RawFrameHeader *current)
777 {
778     int err;
779
780     if (current->base_q_idx > 0)
781         flag(delta_q_present);
782     else
783         infer(delta_q_present, 0);
784
785     if (current->delta_q_present)
786         fb(2, delta_q_res);
787
788     return 0;
789 }
790
791 static int FUNC(delta_lf_params)(CodedBitstreamContext *ctx, RWContext *rw,
792                                  AV1RawFrameHeader *current)
793 {
794     int err;
795
796     if (current->delta_q_present) {
797         if (!current->allow_intrabc)
798             flag(delta_lf_present);
799         else
800             infer(delta_lf_present, 0);
801         if (current->delta_lf_present) {
802             fb(2, delta_lf_res);
803             flag(delta_lf_multi);
804         } else {
805             infer(delta_lf_res,   0);
806             infer(delta_lf_multi, 0);
807         }
808     } else {
809         infer(delta_lf_present, 0);
810         infer(delta_lf_res,     0);
811         infer(delta_lf_multi,   0);
812     }
813
814     return 0;
815 }
816
817 static int FUNC(loop_filter_params)(CodedBitstreamContext *ctx, RWContext *rw,
818                                     AV1RawFrameHeader *current)
819 {
820     CodedBitstreamAV1Context *priv = ctx->priv_data;
821     int i, err;
822
823     if (priv->coded_lossless || current->allow_intrabc) {
824         infer(loop_filter_level[0], 0);
825         infer(loop_filter_level[1], 0);
826         infer(loop_filter_ref_deltas[AV1_REF_FRAME_INTRA],    1);
827         infer(loop_filter_ref_deltas[AV1_REF_FRAME_LAST],     0);
828         infer(loop_filter_ref_deltas[AV1_REF_FRAME_LAST2],    0);
829         infer(loop_filter_ref_deltas[AV1_REF_FRAME_LAST3],    0);
830         infer(loop_filter_ref_deltas[AV1_REF_FRAME_BWDREF],   0);
831         infer(loop_filter_ref_deltas[AV1_REF_FRAME_GOLDEN],  -1);
832         infer(loop_filter_ref_deltas[AV1_REF_FRAME_ALTREF],  -1);
833         infer(loop_filter_ref_deltas[AV1_REF_FRAME_ALTREF2], -1);
834         for (i = 0; i < 2; i++)
835             infer(loop_filter_mode_deltas[i], 0);
836         return 0;
837     }
838
839     fb(6, loop_filter_level[0]);
840     fb(6, loop_filter_level[1]);
841
842     if (priv->num_planes > 1) {
843         if (current->loop_filter_level[0] ||
844             current->loop_filter_level[1]) {
845             fb(6, loop_filter_level[2]);
846             fb(6, loop_filter_level[3]);
847         }
848     }
849
850     fb(3, loop_filter_sharpness);
851
852     flag(loop_filter_delta_enabled);
853     if (current->loop_filter_delta_enabled) {
854         flag(loop_filter_delta_update);
855         if (current->loop_filter_delta_update) {
856             for (i = 0; i < AV1_TOTAL_REFS_PER_FRAME; i++) {
857                 flags(update_ref_delta[i], 1, i);
858                 if (current->update_ref_delta[i])
859                     sus(1 + 6, loop_filter_ref_deltas[i], 1, i);
860             }
861             for (i = 0; i < 2; i++) {
862                 flags(update_mode_delta[i], 1, i);
863                 if (current->update_mode_delta[i])
864                     sus(1 + 6, loop_filter_mode_deltas[i], 1, i);
865             }
866         }
867     }
868
869     return 0;
870 }
871
872 static int FUNC(cdef_params)(CodedBitstreamContext *ctx, RWContext *rw,
873                              AV1RawFrameHeader *current)
874 {
875     CodedBitstreamAV1Context  *priv = ctx->priv_data;
876     const AV1RawSequenceHeader *seq = priv->sequence_header;
877     int i, err;
878
879     if (priv->coded_lossless || current->allow_intrabc ||
880         !seq->enable_cdef) {
881         infer(cdef_damping_minus_3, 0);
882         infer(cdef_bits, 0);
883         infer(cdef_y_pri_strength[0],  0);
884         infer(cdef_y_sec_strength[0],  0);
885         infer(cdef_uv_pri_strength[0], 0);
886         infer(cdef_uv_sec_strength[0], 0);
887
888         return 0;
889     }
890
891     fb(2, cdef_damping_minus_3);
892     fb(2, cdef_bits);
893
894     for (i = 0; i < (1 << current->cdef_bits); i++) {
895         fbs(4, cdef_y_pri_strength[i], 1, i);
896         fbs(2, cdef_y_sec_strength[i], 1, i);
897
898         if (priv->num_planes > 1) {
899             fbs(4, cdef_uv_pri_strength[i], 1, i);
900             fbs(2, cdef_uv_sec_strength[i], 1, i);
901         }
902     }
903
904     return 0;
905 }
906
907 static int FUNC(lr_params)(CodedBitstreamContext *ctx, RWContext *rw,
908                            AV1RawFrameHeader *current)
909 {
910     CodedBitstreamAV1Context  *priv = ctx->priv_data;
911     const AV1RawSequenceHeader *seq = priv->sequence_header;
912     int uses_lr,  uses_chroma_lr;
913     int i, err;
914
915     if (priv->all_lossless || current->allow_intrabc ||
916         !seq->enable_restoration) {
917         return 0;
918     }
919
920     uses_lr = uses_chroma_lr = 0;
921     for (i = 0; i < priv->num_planes; i++) {
922         fbs(2, lr_type[i], 1, i);
923
924         if (current->lr_type[i] != 0) {
925             uses_lr = 1;
926             if (i > 0)
927                 uses_chroma_lr = 1;
928         }
929     }
930
931     if (uses_lr) {
932         if (seq->use_128x128_superblock)
933             increment(lr_unit_shift, 1, 2);
934         else
935             increment(lr_unit_shift, 0, 2);
936
937         if(seq->color_config.subsampling_x &&
938            seq->color_config.subsampling_y && uses_chroma_lr) {
939             fb(1, lr_uv_shift);
940         } else {
941             infer(lr_uv_shift, 0);
942         }
943     }
944
945     return 0;
946 }
947
948 static int FUNC(read_tx_mode)(CodedBitstreamContext *ctx, RWContext *rw,
949                               AV1RawFrameHeader *current)
950 {
951     CodedBitstreamAV1Context *priv = ctx->priv_data;
952     int err;
953
954     if (priv->coded_lossless)
955         infer(tx_mode, 0);
956     else
957         increment(tx_mode, 1, 2);
958
959     return 0;
960 }
961
962 static int FUNC(frame_reference_mode)(CodedBitstreamContext *ctx, RWContext *rw,
963                                       AV1RawFrameHeader *current)
964 {
965     int err;
966
967     if (current->frame_type == AV1_FRAME_INTRA_ONLY ||
968         current->frame_type == AV1_FRAME_KEY)
969         infer(reference_select, 0);
970     else
971         flag(reference_select);
972
973     return 0;
974 }
975
976 static int FUNC(skip_mode_params)(CodedBitstreamContext *ctx, RWContext *rw,
977                                   AV1RawFrameHeader *current)
978 {
979     CodedBitstreamAV1Context  *priv = ctx->priv_data;
980     const AV1RawSequenceHeader *seq = priv->sequence_header;
981     int skip_mode_allowed;
982     int err;
983
984     if (current->frame_type == AV1_FRAME_KEY ||
985         current->frame_type == AV1_FRAME_INTRA_ONLY ||
986         !current->reference_select || !seq->enable_order_hint) {
987         skip_mode_allowed = 0;
988     } else {
989         int forward_idx,  backward_idx;
990         int forward_hint, backward_hint;
991         int ref_hint, dist, i;
992
993         forward_idx  = -1;
994         backward_idx = -1;
995         for (i = 0; i < AV1_REFS_PER_FRAME; i++) {
996             ref_hint = priv->ref[current->ref_frame_idx[i]].order_hint;
997             dist = cbs_av1_get_relative_dist(seq, ref_hint,
998                                              current->order_hint);
999             if (dist < 0) {
1000                 if (forward_idx < 0 ||
1001                     cbs_av1_get_relative_dist(seq, ref_hint,
1002                                               forward_hint) > 0) {
1003                     forward_idx  = i;
1004                     forward_hint = ref_hint;
1005                 }
1006             } else if (dist > 0) {
1007                 if (backward_idx < 0 ||
1008                     cbs_av1_get_relative_dist(seq, ref_hint,
1009                                               backward_hint) < 0) {
1010                     backward_idx  = i;
1011                     backward_hint = ref_hint;
1012                 }
1013             }
1014         }
1015
1016         if (forward_idx < 0) {
1017             skip_mode_allowed = 0;
1018         } else if (backward_idx >= 0) {
1019             skip_mode_allowed = 1;
1020             // Frames for skip mode are forward_idx and backward_idx.
1021         } else {
1022             int second_forward_idx;
1023             int second_forward_hint;
1024
1025             second_forward_idx = -1;
1026             for (i = 0; i < AV1_REFS_PER_FRAME; i++) {
1027                 ref_hint = priv->ref[current->ref_frame_idx[i]].order_hint;
1028                 if (cbs_av1_get_relative_dist(seq, ref_hint,
1029                                               forward_hint) < 0) {
1030                     if (second_forward_idx < 0 ||
1031                         cbs_av1_get_relative_dist(seq, ref_hint,
1032                                                   second_forward_hint) > 0) {
1033                         second_forward_idx  = i;
1034                         second_forward_hint = ref_hint;
1035                     }
1036                 }
1037             }
1038
1039             if (second_forward_idx < 0) {
1040                 skip_mode_allowed = 0;
1041             } else {
1042                 skip_mode_allowed = 1;
1043                 // Frames for skip mode are forward_idx and second_forward_idx.
1044             }
1045         }
1046     }
1047
1048     if (skip_mode_allowed)
1049         flag(skip_mode_present);
1050     else
1051         infer(skip_mode_present, 0);
1052
1053     return 0;
1054 }
1055
1056 static int FUNC(global_motion_param)(CodedBitstreamContext *ctx, RWContext *rw,
1057                                      AV1RawFrameHeader *current,
1058                                      int type, int ref, int idx)
1059 {
1060     uint32_t abs_bits, prec_bits, num_syms;
1061     int err;
1062
1063     if (idx < 2) {
1064         if (type == AV1_WARP_MODEL_TRANSLATION) {
1065             abs_bits  = AV1_GM_ABS_TRANS_ONLY_BITS  - !current->allow_high_precision_mv;
1066             prec_bits = AV1_GM_TRANS_ONLY_PREC_BITS - !current->allow_high_precision_mv;
1067         } else {
1068             abs_bits  = AV1_GM_ABS_TRANS_BITS;
1069             prec_bits = AV1_GM_TRANS_PREC_BITS;
1070         }
1071     } else {
1072         abs_bits  = AV1_GM_ABS_ALPHA_BITS;
1073         prec_bits = AV1_GM_ALPHA_PREC_BITS;
1074     }
1075
1076     num_syms = 2 * (1 << abs_bits) + 1;
1077     subexp(gm_params[ref][idx], num_syms, 2, ref, idx);
1078
1079     // Actual gm_params value is not reconstructed here.
1080     (void)prec_bits;
1081
1082     return 0;
1083 }
1084
1085 static int FUNC(global_motion_params)(CodedBitstreamContext *ctx, RWContext *rw,
1086                                       AV1RawFrameHeader *current)
1087 {
1088     int ref, type;
1089     int err;
1090
1091     if (current->frame_type == AV1_FRAME_KEY ||
1092         current->frame_type == AV1_FRAME_INTRA_ONLY)
1093         return 0;
1094
1095     for (ref = AV1_REF_FRAME_LAST; ref <= AV1_REF_FRAME_ALTREF; ref++) {
1096         flags(is_global[ref], 1, ref);
1097         if (current->is_global[ref]) {
1098             flags(is_rot_zoom[ref], 1, ref);
1099             if (current->is_rot_zoom[ref]) {
1100                 type = AV1_WARP_MODEL_ROTZOOM;
1101             } else {
1102                 flags(is_translation[ref], 1, ref);
1103                 type = current->is_translation[ref] ? AV1_WARP_MODEL_TRANSLATION
1104                                                     : AV1_WARP_MODEL_AFFINE;
1105             }
1106         } else {
1107             type = AV1_WARP_MODEL_IDENTITY;
1108         }
1109
1110         if (type >= AV1_WARP_MODEL_ROTZOOM) {
1111             CHECK(FUNC(global_motion_param)(ctx, rw, current, type, ref, 2));
1112             CHECK(FUNC(global_motion_param)(ctx, rw, current, type, ref, 3));
1113             if (type == AV1_WARP_MODEL_AFFINE) {
1114                 CHECK(FUNC(global_motion_param)(ctx, rw, current, type, ref, 4));
1115                 CHECK(FUNC(global_motion_param)(ctx, rw, current, type, ref, 5));
1116             } else {
1117                 // gm_params[ref][4] = -gm_params[ref][3]
1118                 // gm_params[ref][5] =  gm_params[ref][2]
1119             }
1120         }
1121         if (type >= AV1_WARP_MODEL_TRANSLATION) {
1122             CHECK(FUNC(global_motion_param)(ctx, rw, current, type, ref, 0));
1123             CHECK(FUNC(global_motion_param)(ctx, rw, current, type, ref, 1));
1124         }
1125     }
1126
1127     return 0;
1128 }
1129
1130 static int FUNC(film_grain_params)(CodedBitstreamContext *ctx, RWContext *rw,
1131                                    AV1RawFrameHeader *current)
1132 {
1133     CodedBitstreamAV1Context  *priv = ctx->priv_data;
1134     const AV1RawSequenceHeader *seq = priv->sequence_header;
1135     int num_pos_luma, num_pos_chroma;
1136     int i, err;
1137
1138     if (!seq->film_grain_params_present ||
1139         (!current->show_frame && !current->showable_frame))
1140         return 0;
1141
1142     flag(apply_grain);
1143
1144     if (!current->apply_grain)
1145         return 0;
1146
1147     fb(16, grain_seed);
1148
1149     if (current->frame_type == AV1_FRAME_INTER)
1150         flag(update_grain);
1151     else
1152         infer(update_grain, 1);
1153
1154     if (!current->update_grain) {
1155         fb(3, film_grain_params_ref_idx);
1156         return 0;
1157     }
1158
1159     fb(4, num_y_points);
1160     for (i = 0; i < current->num_y_points; i++) {
1161         fbs(8, point_y_value[i],   1, i);
1162         fbs(8, point_y_scaling[i], 1, i);
1163     }
1164
1165     if (seq->color_config.mono_chrome)
1166         infer(chroma_scaling_from_luma, 0);
1167     else
1168         flag(chroma_scaling_from_luma);
1169
1170     if (seq->color_config.mono_chrome ||
1171         current->chroma_scaling_from_luma ||
1172         (seq->color_config.subsampling_x == 1 &&
1173          seq->color_config.subsampling_y == 1 &&
1174          current->num_y_points == 0)) {
1175         infer(num_cb_points, 0);
1176         infer(num_cr_points, 0);
1177     } else {
1178         fb(4, num_cb_points);
1179         for (i = 0; i < current->num_cb_points; i++) {
1180             fbs(8, point_cb_value[i],   1, i);
1181             fbs(8, point_cb_scaling[i], 1, i);
1182         }
1183         fb(4, num_cr_points);
1184         for (i = 0; i < current->num_cr_points; i++) {
1185             fbs(8, point_cr_value[i],   1, i);
1186             fbs(8, point_cr_scaling[i], 1, i);
1187         }
1188     }
1189
1190     fb(2, grain_scaling_minus_8);
1191     fb(2, ar_coeff_lag);
1192     num_pos_luma = 2 * current->ar_coeff_lag * (current->ar_coeff_lag + 1);
1193     if (current->num_y_points) {
1194         num_pos_chroma = num_pos_luma + 1;
1195         for (i = 0; i < num_pos_luma; i++)
1196             fbs(8, ar_coeffs_y_plus_128[i], 1, i);
1197     } else {
1198         num_pos_chroma = num_pos_luma;
1199     }
1200     if (current->chroma_scaling_from_luma || current->num_cb_points) {
1201         for (i = 0; i < num_pos_chroma; i++)
1202             fbs(8, ar_coeffs_cb_plus_128[i], 1, i);
1203     }
1204     if (current->chroma_scaling_from_luma || current->num_cr_points) {
1205         for (i = 0; i < num_pos_chroma; i++)
1206             fbs(8, ar_coeffs_cr_plus_128[i], 1, i);
1207     }
1208     fb(2, ar_coeff_shift_minus_6);
1209     fb(2, grain_scale_shift);
1210     if (current->num_cb_points) {
1211         fb(8, cb_mult);
1212         fb(8, cb_luma_mult);
1213         fb(9, cb_offset);
1214     }
1215     if (current->num_cr_points) {
1216         fb(8, cr_mult);
1217         fb(8, cr_luma_mult);
1218         fb(9, cr_offset);
1219     }
1220
1221     flag(overlap_flag);
1222     flag(clip_to_restricted_range);
1223
1224     return 0;
1225 }
1226
1227 static int FUNC(uncompressed_header)(CodedBitstreamContext *ctx, RWContext *rw,
1228                                      AV1RawFrameHeader *current)
1229 {
1230     CodedBitstreamAV1Context *priv = ctx->priv_data;
1231     const AV1RawSequenceHeader *seq;
1232     int id_len, diff_len, all_frames, frame_is_intra, order_hint_bits;
1233     int i, err;
1234
1235     if (!priv->sequence_header) {
1236         av_log(ctx->log_ctx, AV_LOG_ERROR, "No sequence header available: "
1237                "unable to decode frame header.\n");
1238         return AVERROR_INVALIDDATA;
1239     }
1240     seq = priv->sequence_header;
1241
1242     id_len = seq->additional_frame_id_length_minus_1 +
1243              seq->delta_frame_id_length_minus_2 + 3;
1244     all_frames = (1 << AV1_NUM_REF_FRAMES) - 1;
1245
1246     if (seq->reduced_still_picture_header) {
1247         infer(show_existing_frame, 0);
1248         infer(frame_type,     AV1_FRAME_KEY);
1249         infer(show_frame,     1);
1250         infer(showable_frame, 0);
1251         frame_is_intra = 1;
1252
1253     } else {
1254         flag(show_existing_frame);
1255
1256         if (current->show_existing_frame) {
1257             AV1ReferenceFrameState *frame;
1258
1259             fb(3, frame_to_show_map_idx);
1260             frame = &priv->ref[current->frame_to_show_map_idx];
1261
1262             if (seq->decoder_model_info_present_flag &&
1263                 !seq->timing_info.equal_picture_interval) {
1264                 fb(seq->decoder_model_info.frame_presentation_time_length_minus_1 + 1,
1265                    frame_presentation_time);
1266             }
1267
1268             if (seq->frame_id_numbers_present_flag)
1269                 fb(id_len, display_frame_id);
1270
1271             if (frame->frame_type == AV1_FRAME_KEY)
1272                 infer(refresh_frame_flags, all_frames);
1273             else
1274                 infer(refresh_frame_flags, 0);
1275
1276             return 0;
1277         }
1278
1279         fb(2, frame_type);
1280         frame_is_intra = (current->frame_type == AV1_FRAME_INTRA_ONLY ||
1281                           current->frame_type == AV1_FRAME_KEY);
1282
1283         flag(show_frame);
1284         if (current->show_frame &&
1285             seq->decoder_model_info_present_flag &&
1286             !seq->timing_info.equal_picture_interval) {
1287             fb(seq->decoder_model_info.frame_presentation_time_length_minus_1 + 1,
1288                frame_presentation_time);
1289         }
1290         if (current->show_frame)
1291             infer(showable_frame, current->frame_type != AV1_FRAME_KEY);
1292         else
1293             flag(showable_frame);
1294
1295         if (current->frame_type == AV1_FRAME_SWITCH ||
1296             (current->frame_type == AV1_FRAME_KEY && current->show_frame))
1297             infer(error_resilient_mode, 1);
1298         else
1299             flag(error_resilient_mode);
1300     }
1301
1302     if (current->frame_type == AV1_FRAME_KEY && current->show_frame) {
1303         for (i = 0; i < AV1_NUM_REF_FRAMES; i++) {
1304             priv->ref[i].valid = 0;
1305             priv->ref[i].order_hint = 0;
1306         }
1307     }
1308
1309     flag(disable_cdf_update);
1310
1311     if (seq->seq_force_screen_content_tools ==
1312         AV1_SELECT_SCREEN_CONTENT_TOOLS) {
1313         flag(allow_screen_content_tools);
1314     } else {
1315         infer(allow_screen_content_tools,
1316               seq->seq_force_screen_content_tools);
1317     }
1318     if (current->allow_screen_content_tools) {
1319         if (seq->seq_force_integer_mv == AV1_SELECT_INTEGER_MV)
1320             flag(force_integer_mv);
1321         else
1322             infer(force_integer_mv, seq->seq_force_integer_mv);
1323     } else {
1324         infer(force_integer_mv, 0);
1325     }
1326
1327     if (seq->frame_id_numbers_present_flag) {
1328         fb(id_len, current_frame_id);
1329
1330         diff_len = seq->delta_frame_id_length_minus_2 + 2;
1331         for (i = 0; i < AV1_NUM_REF_FRAMES; i++) {
1332             if (current->current_frame_id > (1 << diff_len)) {
1333                 if (priv->ref[i].frame_id > current->current_frame_id ||
1334                     priv->ref[i].frame_id < (current->current_frame_id -
1335                                              (1 << diff_len)))
1336                     priv->ref[i].valid = 0;
1337             } else {
1338                 if (priv->ref[i].frame_id > current->current_frame_id &&
1339                     priv->ref[i].frame_id < ((1 << id_len) +
1340                                              current->current_frame_id -
1341                                              (1 << diff_len)))
1342                     priv->ref[i].valid = 0;
1343             }
1344         }
1345     } else {
1346         infer(current_frame_id, 0);
1347     }
1348
1349     if (current->frame_type == AV1_FRAME_SWITCH)
1350         infer(frame_size_override_flag, 1);
1351     else if(seq->reduced_still_picture_header)
1352         infer(frame_size_override_flag, 0);
1353     else
1354         flag(frame_size_override_flag);
1355
1356     order_hint_bits =
1357         seq->enable_order_hint ? seq->order_hint_bits_minus_1 + 1 : 0;
1358     if (order_hint_bits > 0)
1359         fb(order_hint_bits, order_hint);
1360     else
1361         infer(order_hint, 0);
1362
1363     if (frame_is_intra || current->error_resilient_mode)
1364         infer(primary_ref_frame, AV1_PRIMARY_REF_NONE);
1365     else
1366         fb(3, primary_ref_frame);
1367
1368     if (seq->decoder_model_info_present_flag) {
1369         flag(buffer_removal_time_present_flag);
1370         if (current->buffer_removal_time_present_flag) {
1371             for (i = 0; i <= seq->operating_points_cnt_minus_1; i++) {
1372                 if (seq->decoder_model_present_for_this_op[i]) {
1373                     int op_pt_idc = seq->operating_point_idc[i];
1374                     int in_temporal_layer = (op_pt_idc >>  priv->temporal_id    ) & 1;
1375                     int in_spatial_layer  = (op_pt_idc >> (priv->spatial_id + 8)) & 1;
1376                     if (seq->operating_point_idc[i] == 0 ||
1377                         in_temporal_layer || in_spatial_layer) {
1378                         fbs(seq->decoder_model_info.buffer_removal_time_length_minus_1 + 1,
1379                             buffer_removal_time[i], 1, i);
1380                     }
1381                 }
1382             }
1383         }
1384     }
1385
1386     if (current->frame_type == AV1_FRAME_SWITCH ||
1387         (current->frame_type == AV1_FRAME_KEY && current->show_frame))
1388         infer(refresh_frame_flags, all_frames);
1389     else
1390         fb(8, refresh_frame_flags);
1391
1392     if (!frame_is_intra || current->refresh_frame_flags != all_frames) {
1393         if (current->error_resilient_mode && seq->enable_order_hint) {
1394             for (i = 0; i < AV1_NUM_REF_FRAMES; i++) {
1395                 fbs(order_hint_bits, ref_order_hint[i], 1, i);
1396                 if (current->ref_order_hint[i] != priv->ref[i].order_hint)
1397                     priv->ref[i].valid = 0;
1398             }
1399         }
1400     }
1401
1402     if (current->frame_type == AV1_FRAME_KEY ||
1403         current->frame_type == AV1_FRAME_INTRA_ONLY) {
1404         CHECK(FUNC(frame_size)(ctx, rw, current));
1405         CHECK(FUNC(render_size)(ctx, rw, current));
1406
1407         if (current->allow_screen_content_tools &&
1408             priv->upscaled_width == priv->frame_width)
1409             flag(allow_intrabc);
1410         else
1411             infer(allow_intrabc, 0);
1412
1413     } else {
1414         if (!seq->enable_order_hint) {
1415             infer(frame_refs_short_signaling, 0);
1416         } else {
1417             flag(frame_refs_short_signaling);
1418             if (current->frame_refs_short_signaling) {
1419                 fb(3, last_frame_idx);
1420                 fb(3, golden_frame_idx);
1421                 CHECK(FUNC(set_frame_refs)(ctx, rw, current));
1422             }
1423         }
1424
1425         for (i = 0; i < AV1_REFS_PER_FRAME; i++) {
1426             if (!current->frame_refs_short_signaling)
1427                 fbs(3, ref_frame_idx[i], 1, i);
1428             if (seq->frame_id_numbers_present_flag) {
1429                 fbs(seq->delta_frame_id_length_minus_2 + 2,
1430                     delta_frame_id_minus1[i], 1, i);
1431             }
1432         }
1433
1434         if (current->frame_size_override_flag &&
1435             !current->error_resilient_mode) {
1436             CHECK(FUNC(frame_size_with_refs)(ctx, rw, current));
1437         } else {
1438             CHECK(FUNC(frame_size)(ctx, rw, current));
1439             CHECK(FUNC(render_size)(ctx, rw, current));
1440         }
1441
1442         if (current->force_integer_mv)
1443             infer(allow_high_precision_mv, 0);
1444         else
1445             flag(allow_high_precision_mv);
1446
1447         CHECK(FUNC(interpolation_filter)(ctx, rw, current));
1448
1449         flag(is_motion_mode_switchable);
1450
1451         if (current->error_resilient_mode ||
1452             !seq->enable_ref_frame_mvs)
1453             infer(use_ref_frame_mvs, 0);
1454         else
1455             flag(use_ref_frame_mvs);
1456
1457         infer(allow_intrabc, 0);
1458     }
1459
1460     if (!frame_is_intra) {
1461         // Derive reference frame sign biases.
1462     }
1463
1464     if (seq->reduced_still_picture_header || current->disable_cdf_update)
1465         infer(disable_frame_end_update_cdf, 1);
1466     else
1467         flag(disable_frame_end_update_cdf);
1468
1469     if (current->primary_ref_frame == AV1_PRIMARY_REF_NONE) {
1470         // Init non-coeff CDFs.
1471         // Setup past independence.
1472     } else {
1473         // Load CDF tables from previous frame.
1474         // Load params from previous frame.
1475     }
1476
1477     if (current->use_ref_frame_mvs) {
1478         // Perform motion field estimation process.
1479     }
1480
1481     CHECK(FUNC(tile_info)(ctx, rw, current));
1482
1483     CHECK(FUNC(quantization_params)(ctx, rw, current));
1484
1485     CHECK(FUNC(segmentation_params)(ctx, rw, current));
1486
1487     CHECK(FUNC(delta_q_params)(ctx, rw, current));
1488
1489     CHECK(FUNC(delta_lf_params)(ctx, rw, current));
1490
1491     // Init coeff CDFs / load previous segments.
1492
1493     priv->coded_lossless = 1;
1494     for (i = 0; i < AV1_MAX_SEGMENTS; i++) {
1495         int qindex;
1496         if (current->feature_enabled[i][AV1_SEG_LVL_ALT_Q]) {
1497             qindex = (current->base_q_idx +
1498                       current->feature_value[i][AV1_SEG_LVL_ALT_Q]);
1499         } else {
1500             qindex = current->base_q_idx;
1501         }
1502         qindex = av_clip_uintp2(qindex, 8);
1503
1504         if (qindex                || current->delta_q_y_dc ||
1505             current->delta_q_u_ac || current->delta_q_u_dc ||
1506             current->delta_q_v_ac || current->delta_q_v_dc) {
1507             priv->coded_lossless = 0;
1508         }
1509     }
1510     priv->all_lossless = priv->coded_lossless &&
1511         priv->frame_width == priv->upscaled_width;
1512
1513     CHECK(FUNC(loop_filter_params)(ctx, rw, current));
1514
1515     CHECK(FUNC(cdef_params)(ctx, rw, current));
1516
1517     CHECK(FUNC(lr_params)(ctx, rw, current));
1518
1519     CHECK(FUNC(read_tx_mode)(ctx, rw, current));
1520
1521     CHECK(FUNC(frame_reference_mode)(ctx, rw, current));
1522
1523     CHECK(FUNC(skip_mode_params)(ctx, rw, current));
1524
1525     if (frame_is_intra || current->error_resilient_mode ||
1526         !seq->enable_warped_motion)
1527         infer(allow_warped_motion, 0);
1528     else
1529         flag(allow_warped_motion);
1530
1531     flag(reduced_tx_set);
1532
1533     CHECK(FUNC(global_motion_params)(ctx, rw, current));
1534
1535     CHECK(FUNC(film_grain_params)(ctx, rw, current));
1536
1537     for (i = 0; i < AV1_NUM_REF_FRAMES; i++) {
1538         if (current->refresh_frame_flags & (1 << i)) {
1539             priv->ref[i] = (AV1ReferenceFrameState) {
1540                 .valid          = 1,
1541                 .frame_id       = current->current_frame_id,
1542                 .upscaled_width = priv->upscaled_width,
1543                 .frame_width    = priv->frame_width,
1544                 .frame_height   = priv->frame_height,
1545                 .render_width   = priv->render_width,
1546                 .render_height  = priv->render_height,
1547                 .frame_type     = current->frame_type,
1548                 .subsampling_x  = seq->color_config.subsampling_x,
1549                 .subsampling_y  = seq->color_config.subsampling_y,
1550                 .bit_depth      = priv->bit_depth,
1551                 .order_hint     = current->order_hint,
1552             };
1553         }
1554     }
1555
1556     av_log(ctx->log_ctx, AV_LOG_DEBUG, "Frame %d:  size %dx%d  "
1557            "upscaled %d  render %dx%d  subsample %dx%d  "
1558            "bitdepth %d  tiles %dx%d.\n", current->order_hint,
1559            priv->frame_width, priv->frame_height, priv->upscaled_width,
1560            priv->render_width, priv->render_height,
1561            seq->color_config.subsampling_x + 1,
1562            seq->color_config.subsampling_y + 1, priv->bit_depth,
1563            priv->tile_rows, priv->tile_cols);
1564
1565     return 0;
1566 }
1567
1568 static int FUNC(frame_header_obu)(CodedBitstreamContext *ctx, RWContext *rw,
1569                                   AV1RawFrameHeader *current, int redundant,
1570                                   AVBufferRef *rw_buffer_ref)
1571 {
1572     CodedBitstreamAV1Context *priv = ctx->priv_data;
1573     int start_pos, fh_bits, fh_bytes, err;
1574     uint8_t *fh_start;
1575
1576     if (priv->seen_frame_header) {
1577         if (!redundant) {
1578             av_log(ctx->log_ctx, AV_LOG_ERROR, "Invalid repeated "
1579                    "frame header OBU.\n");
1580             return AVERROR_INVALIDDATA;
1581         } else {
1582             GetBitContext fh;
1583             size_t i, b;
1584             uint32_t val;
1585
1586             HEADER("Redundant Frame Header");
1587
1588             av_assert0(priv->frame_header_ref && priv->frame_header);
1589
1590             init_get_bits(&fh, priv->frame_header,
1591                           priv->frame_header_size);
1592             for (i = 0; i < priv->frame_header_size; i += 8) {
1593                 b = FFMIN(priv->frame_header_size - i, 8);
1594                 val = get_bits(&fh, b);
1595                 xf(b, frame_header_copy[i],
1596                    val, val, val, 1, i / 8);
1597             }
1598         }
1599     } else {
1600         if (redundant)
1601             HEADER("Redundant Frame Header (used as Frame Header)");
1602         else
1603             HEADER("Frame Header");
1604
1605         priv->seen_frame_header = 1;
1606
1607 #ifdef READ
1608         start_pos = get_bits_count(rw);
1609 #else
1610         start_pos = put_bits_count(rw);
1611 #endif
1612
1613         CHECK(FUNC(uncompressed_header)(ctx, rw, current));
1614
1615         if (current->show_existing_frame) {
1616             priv->seen_frame_header = 0;
1617         } else {
1618             priv->seen_frame_header = 1;
1619
1620             av_buffer_unref(&priv->frame_header_ref);
1621
1622 #ifdef READ
1623             fh_bits  = get_bits_count(rw) - start_pos;
1624             fh_start = (uint8_t*)rw->buffer + start_pos / 8;
1625 #else
1626             // Need to flush the bitwriter so that we can copy its output,
1627             // but use a copy so we don't affect the caller's structure.
1628             {
1629                 PutBitContext tmp = *rw;
1630                 flush_put_bits(&tmp);
1631             }
1632
1633             fh_bits  = put_bits_count(rw) - start_pos;
1634             fh_start = rw->buf + start_pos / 8;
1635 #endif
1636             fh_bytes = (fh_bits + 7) / 8;
1637
1638             priv->frame_header_size = fh_bits;
1639
1640             if (rw_buffer_ref) {
1641                 priv->frame_header_ref = av_buffer_ref(rw_buffer_ref);
1642                 if (!priv->frame_header_ref)
1643                     return AVERROR(ENOMEM);
1644                 priv->frame_header = fh_start;
1645             } else {
1646                 priv->frame_header_ref =
1647                     av_buffer_alloc(fh_bytes + AV_INPUT_BUFFER_PADDING_SIZE);
1648                 if (!priv->frame_header_ref)
1649                     return AVERROR(ENOMEM);
1650                 priv->frame_header = priv->frame_header_ref->data;
1651                 memcpy(priv->frame_header, fh_start, fh_bytes);
1652             }
1653         }
1654     }
1655
1656     return 0;
1657 }
1658
1659 static int FUNC(tile_group_obu)(CodedBitstreamContext *ctx, RWContext *rw,
1660                                 AV1RawTileGroup *current)
1661 {
1662     CodedBitstreamAV1Context *priv = ctx->priv_data;
1663     int num_tiles, tile_bits;
1664     int err;
1665
1666     HEADER("Tile Group");
1667
1668     num_tiles = priv->tile_cols * priv->tile_rows;
1669     if (num_tiles > 1)
1670         flag(tile_start_and_end_present_flag);
1671     else
1672         infer(tile_start_and_end_present_flag, 0);
1673
1674     if (num_tiles == 1 || !current->tile_start_and_end_present_flag) {
1675         infer(tg_start, 0);
1676         infer(tg_end, num_tiles - 1);
1677     } else {
1678         tile_bits = cbs_av1_tile_log2(1, priv->tile_cols) +
1679                     cbs_av1_tile_log2(1, priv->tile_rows);
1680         fb(tile_bits, tg_start);
1681         fb(tile_bits, tg_end);
1682     }
1683
1684     CHECK(FUNC(byte_alignment)(ctx, rw));
1685
1686     // Reset header for next frame.
1687     if (current->tg_end == num_tiles - 1)
1688         priv->seen_frame_header = 0;
1689
1690     // Tile data follows.
1691
1692     return 0;
1693 }
1694
1695 static int FUNC(frame_obu)(CodedBitstreamContext *ctx, RWContext *rw,
1696                            AV1RawFrame *current,
1697                            AVBufferRef *rw_buffer_ref)
1698 {
1699     int err;
1700
1701     CHECK(FUNC(frame_header_obu)(ctx, rw, &current->header,
1702                                  0, rw_buffer_ref));
1703
1704     CHECK(FUNC(byte_alignment)(ctx, rw));
1705
1706     CHECK(FUNC(tile_group_obu)(ctx, rw, &current->tile_group));
1707
1708     return 0;
1709 }
1710
1711 static int FUNC(tile_list_obu)(CodedBitstreamContext *ctx, RWContext *rw,
1712                                AV1RawTileList *current)
1713 {
1714     int err;
1715
1716     fb(8, output_frame_width_in_tiles_minus_1);
1717     fb(8, output_frame_height_in_tiles_minus_1);
1718
1719     fb(16, tile_count_minus_1);
1720
1721     // Tile data follows.
1722
1723     return 0;
1724 }
1725
1726 static int FUNC(metadata_hdr_cll)(CodedBitstreamContext *ctx, RWContext *rw,
1727                                   AV1RawMetadataHDRCLL *current)
1728 {
1729     int err;
1730
1731     fb(16, max_cll);
1732     fb(16, max_fall);
1733
1734     return 0;
1735 }
1736
1737 static int FUNC(metadata_hdr_mdcv)(CodedBitstreamContext *ctx, RWContext *rw,
1738                                    AV1RawMetadataHDRMDCV *current)
1739 {
1740     int err, i;
1741
1742     for (i = 0; i < 3; i++) {
1743         fbs(16, primary_chromaticity_x[i], 1, i);
1744         fbs(16, primary_chromaticity_y[i], 1, i);
1745     }
1746
1747     fb(16, white_point_chromaticity_x);
1748     fb(16, white_point_chromaticity_y);
1749
1750     fc(32, luminance_max, 1, MAX_UINT_BITS(32));
1751     // luminance_min must be lower than luminance_max. Convert luminance_max from
1752     // 24.8 fixed point to 18.14 fixed point in order to compare them.
1753     fc(32, luminance_min, 0, FFMIN(((uint64_t)current->luminance_max << 6) - 1,
1754                                    MAX_UINT_BITS(32)));
1755
1756     return 0;
1757 }
1758
1759 static int FUNC(scalability_structure)(CodedBitstreamContext *ctx, RWContext *rw,
1760                                        AV1RawMetadataScalability *current)
1761 {
1762     CodedBitstreamAV1Context *priv = ctx->priv_data;
1763     const AV1RawSequenceHeader *seq;
1764     int err, i, j;
1765
1766     if (!priv->sequence_header) {
1767         av_log(ctx->log_ctx, AV_LOG_ERROR, "No sequence header available: "
1768                "unable to parse scalability metadata.\n");
1769         return AVERROR_INVALIDDATA;
1770     }
1771     seq = priv->sequence_header;
1772
1773     fb(2, spatial_layers_cnt_minus_1);
1774     flag(spatial_layer_dimensions_present_flag);
1775     flag(spatial_layer_description_present_flag);
1776     flag(temporal_group_description_present_flag);
1777     fc(3, scalability_structure_reserved_3bits, 0, 0);
1778     if (current->spatial_layer_dimensions_present_flag) {
1779         for (i = 0; i <= current->spatial_layers_cnt_minus_1; i++) {
1780             fcs(16, spatial_layer_max_width[i],
1781                 0, seq->max_frame_width_minus_1 + 1, 1, i);
1782             fcs(16, spatial_layer_max_height[i],
1783                 0, seq->max_frame_height_minus_1 + 1, 1, i);
1784         }
1785     }
1786     if (current->spatial_layer_description_present_flag) {
1787         for (i = 0; i <= current->spatial_layers_cnt_minus_1; i++)
1788             fbs(8, spatial_layer_ref_id[i], 1, i);
1789     }
1790     if (current->temporal_group_description_present_flag) {
1791         fb(8, temporal_group_size);
1792         for (i = 0; i < current->temporal_group_size; i++) {
1793             fbs(3, temporal_group_temporal_id[i], 1, i);
1794             flags(temporal_group_temporal_switching_up_point_flag[i], 1, i);
1795             flags(temporal_group_spatial_switching_up_point_flag[i], 1, i);
1796             fbs(3, temporal_group_ref_cnt[i], 1, i);
1797             for (j = 0; j < current->temporal_group_ref_cnt[i]; j++) {
1798                 fbs(8, temporal_group_ref_pic_diff[i][j], 2, i, j);
1799             }
1800         }
1801     }
1802
1803     return 0;
1804 }
1805
1806 static int FUNC(metadata_scalability)(CodedBitstreamContext *ctx, RWContext *rw,
1807                                       AV1RawMetadataScalability *current)
1808 {
1809     int err;
1810
1811     fb(8, scalability_mode_idc);
1812
1813     if (current->scalability_mode_idc == AV1_SCALABILITY_SS)
1814         CHECK(FUNC(scalability_structure)(ctx, rw, current));
1815
1816     return 0;
1817 }
1818
1819 static int FUNC(metadata_itut_t35)(CodedBitstreamContext *ctx, RWContext *rw,
1820                                    AV1RawMetadataITUTT35 *current)
1821 {
1822     int err;
1823     size_t i;
1824
1825     fb(8, itu_t_t35_country_code);
1826     if (current->itu_t_t35_country_code == 0xff)
1827         fb(8, itu_t_t35_country_code_extension_byte);
1828
1829 #ifdef READ
1830     // The payload runs up to the start of the trailing bits, but there might
1831     // be arbitrarily many trailing zeroes so we need to read through twice.
1832     current->payload_size = cbs_av1_get_payload_bytes_left(rw);
1833
1834     current->payload_ref = av_buffer_alloc(current->payload_size);
1835     if (!current->payload_ref)
1836         return AVERROR(ENOMEM);
1837     current->payload = current->payload_ref->data;
1838 #endif
1839
1840     for (i = 0; i < current->payload_size; i++)
1841         xf(8, itu_t_t35_payload_bytes[i], current->payload[i],
1842            0x00, 0xff, 1, i);
1843
1844     return 0;
1845 }
1846
1847 static int FUNC(metadata_timecode)(CodedBitstreamContext *ctx, RWContext *rw,
1848                                    AV1RawMetadataTimecode *current)
1849 {
1850     int err;
1851
1852     fb(5, counting_type);
1853     flag(full_timestamp_flag);
1854     flag(discontinuity_flag);
1855     flag(cnt_dropped_flag);
1856     fb(9, n_frames);
1857
1858     if (current->full_timestamp_flag) {
1859         fc(6, seconds_value, 0, 59);
1860         fc(6, minutes_value, 0, 59);
1861         fc(5, hours_value,   0, 23);
1862     } else {
1863         flag(seconds_flag);
1864         if (current->seconds_flag) {
1865             fc(6, seconds_value, 0, 59);
1866             flag(minutes_flag);
1867             if (current->minutes_flag) {
1868                 fc(6, minutes_value, 0, 59);
1869                 flag(hours_flag);
1870                 if (current->hours_flag)
1871                     fc(5, hours_value, 0, 23);
1872             }
1873         }
1874     }
1875
1876     fb(5, time_offset_length);
1877     if (current->time_offset_length > 0)
1878         fb(current->time_offset_length, time_offset_value);
1879     else
1880         infer(time_offset_length, 0);
1881
1882     return 0;
1883 }
1884
1885 static int FUNC(metadata_obu)(CodedBitstreamContext *ctx, RWContext *rw,
1886                               AV1RawMetadata *current)
1887 {
1888     int err;
1889
1890     leb128(metadata_type);
1891
1892     switch (current->metadata_type) {
1893     case AV1_METADATA_TYPE_HDR_CLL:
1894         CHECK(FUNC(metadata_hdr_cll)(ctx, rw, &current->metadata.hdr_cll));
1895         break;
1896     case AV1_METADATA_TYPE_HDR_MDCV:
1897         CHECK(FUNC(metadata_hdr_mdcv)(ctx, rw, &current->metadata.hdr_mdcv));
1898         break;
1899     case AV1_METADATA_TYPE_SCALABILITY:
1900         CHECK(FUNC(metadata_scalability)(ctx, rw, &current->metadata.scalability));
1901         break;
1902     case AV1_METADATA_TYPE_ITUT_T35:
1903         CHECK(FUNC(metadata_itut_t35)(ctx, rw, &current->metadata.itut_t35));
1904         break;
1905     case AV1_METADATA_TYPE_TIMECODE:
1906         CHECK(FUNC(metadata_timecode)(ctx, rw, &current->metadata.timecode));
1907         break;
1908     default:
1909         // Unknown metadata type.
1910         return AVERROR_PATCHWELCOME;
1911     }
1912
1913     return 0;
1914 }
1915
1916 static int FUNC(padding_obu)(CodedBitstreamContext *ctx, RWContext *rw,
1917                              AV1RawPadding *current)
1918 {
1919     int i, err;
1920
1921     HEADER("Padding");
1922
1923 #ifdef READ
1924     // The payload runs up to the start of the trailing bits, but there might
1925     // be arbitrarily many trailing zeroes so we need to read through twice.
1926     current->payload_size = cbs_av1_get_payload_bytes_left(rw);
1927
1928     current->payload_ref = av_buffer_alloc(current->payload_size);
1929     if (!current->payload_ref)
1930         return AVERROR(ENOMEM);
1931     current->payload = current->payload_ref->data;
1932 #endif
1933
1934     for (i = 0; i < current->payload_size; i++)
1935         xf(8, obu_padding_byte[i], current->payload[i], 0x00, 0xff, 1, i);
1936
1937     return 0;
1938 }