84ab2973ab0722435c20b3af80bc5b6b4b874ea1
[ffmpeg.git] / 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(superres_params)(CodedBitstreamContext *ctx, RWContext *rw,
343                                  AV1RawFrameHeader *current)
344 {
345     CodedBitstreamAV1Context  *priv = ctx->priv_data;
346     const AV1RawSequenceHeader *seq = priv->sequence_header;
347     int denom, err;
348
349     if (seq->enable_superres)
350         flag(use_superres);
351     else
352         infer(use_superres, 0);
353
354     if (current->use_superres) {
355         fb(3, coded_denom);
356         denom = current->coded_denom + AV1_SUPERRES_DENOM_MIN;
357     } else {
358         denom = AV1_SUPERRES_NUM;
359     }
360
361     priv->upscaled_width = priv->frame_width;
362     priv->frame_width = (priv->upscaled_width * AV1_SUPERRES_NUM +
363                          denom / 2) / denom;
364
365     return 0;
366 }
367
368 static int FUNC(frame_size)(CodedBitstreamContext *ctx, RWContext *rw,
369                             AV1RawFrameHeader *current)
370 {
371     CodedBitstreamAV1Context  *priv = ctx->priv_data;
372     const AV1RawSequenceHeader *seq = priv->sequence_header;
373     int err;
374
375     if (current->frame_size_override_flag) {
376         fb(seq->frame_width_bits_minus_1 + 1,  frame_width_minus_1);
377         fb(seq->frame_height_bits_minus_1 + 1, frame_height_minus_1);
378
379         priv->frame_width  = current->frame_width_minus_1  + 1;
380         priv->frame_height = current->frame_height_minus_1 + 1;
381     } else {
382         priv->frame_width  = seq->max_frame_width_minus_1  + 1;
383         priv->frame_height = seq->max_frame_height_minus_1 + 1;
384     }
385
386     CHECK(FUNC(superres_params)(ctx, rw, current));
387
388     return 0;
389 }
390
391 static int FUNC(render_size)(CodedBitstreamContext *ctx, RWContext *rw,
392                              AV1RawFrameHeader *current)
393 {
394     CodedBitstreamAV1Context *priv = ctx->priv_data;
395     int err;
396
397     flag(render_and_frame_size_different);
398
399     if (current->render_and_frame_size_different) {
400         fb(16, render_width_minus_1);
401         fb(16, render_height_minus_1);
402
403         priv->render_width  = current->render_width_minus_1  + 1;
404         priv->render_height = current->render_height_minus_1 + 1;
405     } else {
406         priv->render_width  = priv->upscaled_width;
407         priv->render_height = priv->frame_height;
408     }
409
410     return 0;
411 }
412
413 static int FUNC(frame_size_with_refs)(CodedBitstreamContext *ctx, RWContext *rw,
414                                       AV1RawFrameHeader *current)
415 {
416     CodedBitstreamAV1Context *priv = ctx->priv_data;
417     int i, err;
418
419     for (i = 0; i < AV1_REFS_PER_FRAME; i++) {
420         flag(found_ref);
421         if (current->found_ref) {
422             AV1ReferenceFrameState *ref =
423                 &priv->ref[current->ref_frame_idx[i]];
424
425             if (!ref->valid) {
426                 av_log(ctx->log_ctx, AV_LOG_ERROR,
427                        "Missing reference frame needed for frame size "
428                        "(ref = %d, ref_frame_idx = %d).\n",
429                        i, current->ref_frame_idx[i]);
430                 return AVERROR_INVALIDDATA;
431             }
432
433             priv->upscaled_width = ref->upscaled_width;
434             priv->frame_width    = ref->frame_width;
435             priv->frame_height   = ref->frame_height;
436             priv->render_width   = ref->render_width;
437             priv->render_height  = ref->render_height;
438             break;
439         }
440     }
441
442     if (current->found_ref == 0) {
443         CHECK(FUNC(frame_size)(ctx, rw, current));
444         CHECK(FUNC(render_size)(ctx, rw, current));
445     } else {
446         CHECK(FUNC(superres_params)(ctx, rw, current));
447     }
448
449     return 0;
450 }
451
452 static int FUNC(interpolation_filter)(CodedBitstreamContext *ctx, RWContext *rw,
453                                       AV1RawFrameHeader *current)
454 {
455     int err;
456
457     flag(is_filter_switchable);
458     if (current->is_filter_switchable)
459         infer(interpolation_filter,
460               AV1_INTERPOLATION_FILTER_SWITCHABLE);
461     else
462         fb(2, interpolation_filter);
463
464     return 0;
465 }
466
467 static int FUNC(tile_info)(CodedBitstreamContext *ctx, RWContext *rw,
468                            AV1RawFrameHeader *current)
469 {
470     CodedBitstreamAV1Context  *priv = ctx->priv_data;
471     const AV1RawSequenceHeader *seq = priv->sequence_header;
472     int mi_cols, mi_rows, sb_cols, sb_rows, sb_shift, sb_size;
473     int max_tile_width_sb, max_tile_height_sb, max_tile_area_sb;
474     int min_log2_tile_cols, max_log2_tile_cols, max_log2_tile_rows;
475     int min_log2_tiles, min_log2_tile_rows;
476     int i, err;
477
478     mi_cols = 2 * ((priv->frame_width  + 7) >> 3);
479     mi_rows = 2 * ((priv->frame_height + 7) >> 3);
480
481     sb_cols = seq->use_128x128_superblock ? ((mi_cols + 31) >> 5)
482                                           : ((mi_cols + 15) >> 4);
483     sb_rows = seq->use_128x128_superblock ? ((mi_rows + 31) >> 5)
484                                           : ((mi_rows + 15) >> 4);
485
486     sb_shift = seq->use_128x128_superblock ? 5 : 4;
487     sb_size  = sb_shift + 2;
488
489     max_tile_width_sb = AV1_MAX_TILE_WIDTH >> sb_size;
490     max_tile_area_sb  = AV1_MAX_TILE_AREA  >> (2 * sb_size);
491
492     min_log2_tile_cols = cbs_av1_tile_log2(max_tile_width_sb, sb_cols);
493     max_log2_tile_cols = cbs_av1_tile_log2(1, FFMIN(sb_cols, AV1_MAX_TILE_COLS));
494     max_log2_tile_rows = cbs_av1_tile_log2(1, FFMIN(sb_rows, AV1_MAX_TILE_ROWS));
495     min_log2_tiles = FFMAX(min_log2_tile_cols,
496                            cbs_av1_tile_log2(max_tile_area_sb, sb_rows * sb_cols));
497
498     flag(uniform_tile_spacing_flag);
499
500     if (current->uniform_tile_spacing_flag) {
501         int tile_width_sb, tile_height_sb;
502
503         increment(tile_cols_log2, min_log2_tile_cols, max_log2_tile_cols);
504
505         tile_width_sb = (sb_cols + (1 << current->tile_cols_log2) - 1) >>
506             current->tile_cols_log2;
507         current->tile_cols = (sb_cols + tile_width_sb - 1) / tile_width_sb;
508
509         min_log2_tile_rows = FFMAX(min_log2_tiles - current->tile_cols_log2, 0);
510
511         increment(tile_rows_log2, min_log2_tile_rows, max_log2_tile_rows);
512
513         tile_height_sb = (sb_rows + (1 << current->tile_rows_log2) - 1) >>
514             current->tile_rows_log2;
515         current->tile_rows = (sb_rows + tile_height_sb - 1) / tile_height_sb;
516
517     } else {
518         int widest_tile_sb, start_sb, size_sb, max_width, max_height;
519
520         widest_tile_sb = 0;
521
522         start_sb = 0;
523         for (i = 0; start_sb < sb_cols && i < AV1_MAX_TILE_COLS; i++) {
524             max_width = FFMIN(sb_cols - start_sb, max_tile_width_sb);
525             ns(max_width, width_in_sbs_minus_1[i], 1, i);
526             size_sb = current->width_in_sbs_minus_1[i] + 1;
527             widest_tile_sb = FFMAX(size_sb, widest_tile_sb);
528             start_sb += size_sb;
529         }
530         current->tile_cols_log2 = cbs_av1_tile_log2(1, i);
531         current->tile_cols = i;
532
533         if (min_log2_tiles > 0)
534             max_tile_area_sb = (sb_rows * sb_cols) >> (min_log2_tiles + 1);
535         else
536             max_tile_area_sb = sb_rows * sb_cols;
537         max_tile_height_sb = FFMAX(max_tile_area_sb / widest_tile_sb, 1);
538
539         start_sb = 0;
540         for (i = 0; start_sb < sb_rows && i < AV1_MAX_TILE_ROWS; i++) {
541             max_height = FFMIN(sb_rows - start_sb, max_tile_height_sb);
542             ns(max_height, height_in_sbs_minus_1[i], 1, i);
543             size_sb = current->height_in_sbs_minus_1[i] + 1;
544             start_sb += size_sb;
545         }
546         current->tile_rows_log2 = cbs_av1_tile_log2(1, i);
547         current->tile_rows = i;
548     }
549
550     if (current->tile_cols_log2 > 0 ||
551         current->tile_rows_log2 > 0) {
552         fb(current->tile_cols_log2 + current->tile_rows_log2,
553            context_update_tile_id);
554         fb(2, tile_size_bytes_minus1);
555     } else {
556         infer(context_update_tile_id, 0);
557     }
558
559     priv->tile_cols = current->tile_cols;
560     priv->tile_rows = current->tile_rows;
561
562     return 0;
563 }
564
565 static int FUNC(quantization_params)(CodedBitstreamContext *ctx, RWContext *rw,
566                                      AV1RawFrameHeader *current)
567 {
568     CodedBitstreamAV1Context  *priv = ctx->priv_data;
569     const AV1RawSequenceHeader *seq = priv->sequence_header;
570     int err;
571
572     fb(8, base_q_idx);
573
574     delta_q(delta_q_y_dc);
575
576     if (priv->num_planes > 1) {
577         if (seq->color_config.separate_uv_delta_q)
578             flag(diff_uv_delta);
579         else
580             infer(diff_uv_delta, 0);
581
582         delta_q(delta_q_u_dc);
583         delta_q(delta_q_u_ac);
584
585         if (current->diff_uv_delta) {
586             delta_q(delta_q_v_dc);
587             delta_q(delta_q_v_ac);
588         } else {
589             infer(delta_q_v_dc, current->delta_q_u_dc);
590             infer(delta_q_v_ac, current->delta_q_u_ac);
591         }
592     } else {
593         infer(delta_q_u_dc, 0);
594         infer(delta_q_u_ac, 0);
595         infer(delta_q_v_dc, 0);
596         infer(delta_q_v_ac, 0);
597     }
598
599     flag(using_qmatrix);
600     if (current->using_qmatrix) {
601         fb(4, qm_y);
602         fb(4, qm_u);
603         if (seq->color_config.separate_uv_delta_q)
604             fb(4, qm_v);
605         else
606             infer(qm_v, current->qm_u);
607     }
608
609     return 0;
610 }
611
612 static int FUNC(segmentation_params)(CodedBitstreamContext *ctx, RWContext *rw,
613                                      AV1RawFrameHeader *current)
614 {
615     static const uint8_t bits[AV1_SEG_LVL_MAX] = { 8, 6, 6, 6, 6, 3, 0, 0 };
616     static const uint8_t sign[AV1_SEG_LVL_MAX] = { 1, 1, 1, 1, 1, 0, 0, 0 };
617     int i, j, err;
618
619     flag(segmentation_enabled);
620
621     if (current->segmentation_enabled) {
622         if (current->primary_ref_frame == AV1_PRIMARY_REF_NONE) {
623             infer(segmentation_update_map,      1);
624             infer(segmentation_temporal_update, 0);
625             infer(segmentation_update_data,     1);
626         } else {
627             flag(segmentation_update_map);
628             if (current->segmentation_update_map)
629                 flag(segmentation_temporal_update);
630             else
631                 infer(segmentation_temporal_update, 0);
632             flag(segmentation_update_data);
633         }
634
635         if (current->segmentation_update_data) {
636             for (i = 0; i < AV1_MAX_SEGMENTS; i++) {
637                 for (j = 0; j < AV1_SEG_LVL_MAX; j++) {
638                     flags(feature_enabled[i][j], 2, i, j);
639
640                     if (current->feature_enabled[i][j] && bits[j] > 0) {
641                         if (sign[j])
642                             sus(1 + bits[j], feature_value[i][j], 2, i, j);
643                         else
644                             fbs(bits[j], feature_value[i][j], 2, i, j);
645                     } else {
646                         infer(feature_value[i][j], 0);
647                     }
648                 }
649             }
650         }
651     } else {
652         for (i = 0; i < AV1_MAX_SEGMENTS; i++) {
653             for (j = 0; j < AV1_SEG_LVL_MAX; j++) {
654                 infer(feature_enabled[i][j], 0);
655                 infer(feature_value[i][j],   0);
656             }
657         }
658     }
659
660     return 0;
661 }
662
663 static int FUNC(delta_q_params)(CodedBitstreamContext *ctx, RWContext *rw,
664                                 AV1RawFrameHeader *current)
665 {
666     int err;
667
668     if (current->base_q_idx > 0)
669         flag(delta_q_present);
670     else
671         infer(delta_q_present, 0);
672
673     if (current->delta_q_present)
674         fb(2, delta_q_res);
675
676     return 0;
677 }
678
679 static int FUNC(delta_lf_params)(CodedBitstreamContext *ctx, RWContext *rw,
680                                  AV1RawFrameHeader *current)
681 {
682     int err;
683
684     if (current->delta_q_present) {
685         if (!current->allow_intrabc)
686             flag(delta_lf_present);
687         else
688             infer(delta_lf_present, 0);
689         if (current->delta_lf_present) {
690             fb(2, delta_lf_res);
691             flag(delta_lf_multi);
692         } else {
693             infer(delta_lf_res,   0);
694             infer(delta_lf_multi, 0);
695         }
696     } else {
697         infer(delta_lf_present, 0);
698         infer(delta_lf_res,     0);
699         infer(delta_lf_multi,   0);
700     }
701
702     return 0;
703 }
704
705 static int FUNC(loop_filter_params)(CodedBitstreamContext *ctx, RWContext *rw,
706                                     AV1RawFrameHeader *current)
707 {
708     CodedBitstreamAV1Context *priv = ctx->priv_data;
709     int i, err;
710
711     if (priv->coded_lossless || current->allow_intrabc) {
712         infer(loop_filter_level[0], 0);
713         infer(loop_filter_level[1], 0);
714         infer(loop_filter_ref_deltas[AV1_REF_FRAME_INTRA],    1);
715         infer(loop_filter_ref_deltas[AV1_REF_FRAME_LAST],     0);
716         infer(loop_filter_ref_deltas[AV1_REF_FRAME_LAST2],    0);
717         infer(loop_filter_ref_deltas[AV1_REF_FRAME_LAST3],    0);
718         infer(loop_filter_ref_deltas[AV1_REF_FRAME_BWDREF],   0);
719         infer(loop_filter_ref_deltas[AV1_REF_FRAME_GOLDEN],  -1);
720         infer(loop_filter_ref_deltas[AV1_REF_FRAME_ALTREF],  -1);
721         infer(loop_filter_ref_deltas[AV1_REF_FRAME_ALTREF2], -1);
722         for (i = 0; i < 2; i++)
723             infer(loop_filter_mode_deltas[i], 0);
724         return 0;
725     }
726
727     fb(6, loop_filter_level[0]);
728     fb(6, loop_filter_level[1]);
729
730     if (priv->num_planes > 1) {
731         if (current->loop_filter_level[0] ||
732             current->loop_filter_level[1]) {
733             fb(6, loop_filter_level[2]);
734             fb(6, loop_filter_level[3]);
735         }
736     }
737
738     fb(3, loop_filter_sharpness);
739
740     flag(loop_filter_delta_enabled);
741     if (current->loop_filter_delta_enabled) {
742         flag(loop_filter_delta_update);
743         if (current->loop_filter_delta_update) {
744             for (i = 0; i < AV1_TOTAL_REFS_PER_FRAME; i++) {
745                 flags(update_ref_delta[i], 1, i);
746                 if (current->update_ref_delta[i])
747                     sus(1 + 6, loop_filter_ref_deltas[i], 1, i);
748             }
749             for (i = 0; i < 2; i++) {
750                 flags(update_mode_delta[i], 1, i);
751                 if (current->update_mode_delta[i])
752                     sus(1 + 6, loop_filter_mode_deltas[i], 1, i);
753             }
754         }
755     }
756
757     return 0;
758 }
759
760 static int FUNC(cdef_params)(CodedBitstreamContext *ctx, RWContext *rw,
761                              AV1RawFrameHeader *current)
762 {
763     CodedBitstreamAV1Context  *priv = ctx->priv_data;
764     const AV1RawSequenceHeader *seq = priv->sequence_header;
765     int i, err;
766
767     if (priv->coded_lossless || current->allow_intrabc ||
768         !seq->enable_cdef) {
769         infer(cdef_damping_minus_3, 0);
770         infer(cdef_bits, 0);
771         infer(cdef_y_pri_strength[0],  0);
772         infer(cdef_y_sec_strength[0],  0);
773         infer(cdef_uv_pri_strength[0], 0);
774         infer(cdef_uv_sec_strength[0], 0);
775
776         return 0;
777     }
778
779     fb(2, cdef_damping_minus_3);
780     fb(2, cdef_bits);
781
782     for (i = 0; i < (1 << current->cdef_bits); i++) {
783         fbs(4, cdef_y_pri_strength[i], 1, i);
784         fbs(2, cdef_y_sec_strength[i], 1, i);
785
786         if (priv->num_planes > 1) {
787             fbs(4, cdef_uv_pri_strength[i], 1, i);
788             fbs(2, cdef_uv_sec_strength[i], 1, i);
789         }
790     }
791
792     return 0;
793 }
794
795 static int FUNC(lr_params)(CodedBitstreamContext *ctx, RWContext *rw,
796                            AV1RawFrameHeader *current)
797 {
798     CodedBitstreamAV1Context  *priv = ctx->priv_data;
799     const AV1RawSequenceHeader *seq = priv->sequence_header;
800     int uses_lr,  uses_chroma_lr;
801     int i, err;
802
803     if (priv->all_lossless || current->allow_intrabc ||
804         !seq->enable_restoration) {
805         return 0;
806     }
807
808     uses_lr = uses_chroma_lr = 0;
809     for (i = 0; i < priv->num_planes; i++) {
810         fbs(2, lr_type[i], 1, i);
811
812         if (current->lr_type[i] != 0) {
813             uses_lr = 1;
814             if (i > 0)
815                 uses_chroma_lr = 1;
816         }
817     }
818
819     if (uses_lr) {
820         if (seq->use_128x128_superblock)
821             increment(lr_unit_shift, 1, 2);
822         else
823             increment(lr_unit_shift, 0, 2);
824
825         if(seq->color_config.subsampling_x &&
826            seq->color_config.subsampling_y && uses_chroma_lr) {
827             fb(1, lr_uv_shift);
828         } else {
829             infer(lr_uv_shift, 0);
830         }
831     }
832
833     return 0;
834 }
835
836 static int FUNC(read_tx_mode)(CodedBitstreamContext *ctx, RWContext *rw,
837                               AV1RawFrameHeader *current)
838 {
839     CodedBitstreamAV1Context *priv = ctx->priv_data;
840     int err;
841
842     if (priv->coded_lossless)
843         infer(tx_mode, 0);
844     else
845         increment(tx_mode, 1, 2);
846
847     return 0;
848 }
849
850 static int FUNC(frame_reference_mode)(CodedBitstreamContext *ctx, RWContext *rw,
851                                       AV1RawFrameHeader *current)
852 {
853     int err;
854
855     if (current->frame_type == AV1_FRAME_INTRA_ONLY ||
856         current->frame_type == AV1_FRAME_KEY)
857         infer(reference_select, 0);
858     else
859         flag(reference_select);
860
861     return 0;
862 }
863
864 static int FUNC(skip_mode_params)(CodedBitstreamContext *ctx, RWContext *rw,
865                                   AV1RawFrameHeader *current)
866 {
867     CodedBitstreamAV1Context  *priv = ctx->priv_data;
868     const AV1RawSequenceHeader *seq = priv->sequence_header;
869     int skip_mode_allowed;
870     int err;
871
872     if (current->frame_type == AV1_FRAME_KEY ||
873         current->frame_type == AV1_FRAME_INTRA_ONLY ||
874         !current->reference_select || !seq->enable_order_hint) {
875         skip_mode_allowed = 0;
876     } else {
877         int forward_idx,  backward_idx;
878         int forward_hint, backward_hint;
879         int ref_hint, dist, i;
880
881         forward_idx  = -1;
882         backward_idx = -1;
883         for (i = 0; i < AV1_REFS_PER_FRAME; i++) {
884             ref_hint = priv->ref[i].order_hint;
885             dist = cbs_av1_get_relative_dist(seq, ref_hint,
886                                              current->order_hint);
887             if (dist < 0) {
888                 if (forward_idx < 0 ||
889                     cbs_av1_get_relative_dist(seq, ref_hint,
890                                               forward_hint) > 0) {
891                     forward_idx  = i;
892                     forward_hint = ref_hint;
893                 }
894             } else if (dist > 0) {
895                 if (backward_idx < 0 ||
896                     cbs_av1_get_relative_dist(seq, ref_hint,
897                                               backward_hint) < 0) {
898                     backward_idx  = i;
899                     backward_hint = ref_hint;
900                 }
901             }
902         }
903
904         if (forward_idx < 0) {
905             skip_mode_allowed = 0;
906         } else if (backward_idx >= 0) {
907             skip_mode_allowed = 1;
908             // Frames for skip mode are forward_idx and backward_idx.
909         } else {
910             int second_forward_idx;
911             int second_forward_hint;
912
913             second_forward_idx = -1;
914             for (i = 0; i < AV1_REFS_PER_FRAME; i++) {
915                 ref_hint = priv->ref[i].order_hint;
916                 if (cbs_av1_get_relative_dist(seq, ref_hint,
917                                               forward_hint) < 0) {
918                     if (second_forward_idx < 0 ||
919                         cbs_av1_get_relative_dist(seq, ref_hint,
920                                                   second_forward_hint) > 0) {
921                         second_forward_idx  = i;
922                         second_forward_hint = ref_hint;
923                     }
924                 }
925             }
926
927             if (second_forward_idx < 0) {
928                 skip_mode_allowed = 0;
929             } else {
930                 skip_mode_allowed = 1;
931                 // Frames for skip mode are forward_idx and second_forward_idx.
932             }
933         }
934     }
935
936     if (skip_mode_allowed)
937         flag(skip_mode_present);
938     else
939         infer(skip_mode_present, 0);
940
941     return 0;
942 }
943
944 static int FUNC(global_motion_param)(CodedBitstreamContext *ctx, RWContext *rw,
945                                      AV1RawFrameHeader *current,
946                                      int type, int ref, int idx)
947 {
948     uint32_t abs_bits, prec_bits, num_syms;
949     int err;
950
951     if (idx < 2) {
952         if (type == AV1_WARP_MODEL_TRANSLATION) {
953             abs_bits  = AV1_GM_ABS_TRANS_ONLY_BITS  - !current->allow_high_precision_mv;
954             prec_bits = AV1_GM_TRANS_ONLY_PREC_BITS - !current->allow_high_precision_mv;
955         } else {
956             abs_bits  = AV1_GM_ABS_TRANS_BITS;
957             prec_bits = AV1_GM_TRANS_PREC_BITS;
958         }
959     } else {
960         abs_bits  = AV1_GM_ABS_ALPHA_BITS;
961         prec_bits = AV1_GM_ALPHA_PREC_BITS;
962     }
963
964     num_syms = 2 * (1 << abs_bits) + 1;
965     subexp(gm_params[ref][idx], num_syms, 2, ref, idx);
966
967     // Actual gm_params value is not reconstructed here.
968     (void)prec_bits;
969
970     return 0;
971 }
972
973 static int FUNC(global_motion_params)(CodedBitstreamContext *ctx, RWContext *rw,
974                                       AV1RawFrameHeader *current)
975 {
976     int ref, type;
977     int err;
978
979     if (current->frame_type == AV1_FRAME_KEY ||
980         current->frame_type == AV1_FRAME_INTRA_ONLY)
981         return 0;
982
983     for (ref = AV1_REF_FRAME_LAST; ref <= AV1_REF_FRAME_ALTREF; ref++) {
984         flags(is_global[ref], 1, ref);
985         if (current->is_global[ref]) {
986             flags(is_rot_zoom[ref], 1, ref);
987             if (current->is_rot_zoom[ref]) {
988                 type = AV1_WARP_MODEL_ROTZOOM;
989             } else {
990                 flags(is_translation[ref], 1, ref);
991                 type = current->is_translation[ref] ? AV1_WARP_MODEL_TRANSLATION
992                                                     : AV1_WARP_MODEL_AFFINE;
993             }
994         } else {
995             type = AV1_WARP_MODEL_IDENTITY;
996         }
997
998         if (type >= AV1_WARP_MODEL_ROTZOOM) {
999             CHECK(FUNC(global_motion_param)(ctx, rw, current, type, ref, 2));
1000             CHECK(FUNC(global_motion_param)(ctx, rw, current, type, ref, 3));
1001             if (type == AV1_WARP_MODEL_AFFINE) {
1002                 CHECK(FUNC(global_motion_param)(ctx, rw, current, type, ref, 4));
1003                 CHECK(FUNC(global_motion_param)(ctx, rw, current, type, ref, 5));
1004             } else {
1005                 // gm_params[ref][4] = -gm_params[ref][3]
1006                 // gm_params[ref][5] =  gm_params[ref][2]
1007             }
1008         }
1009         if (type >= AV1_WARP_MODEL_TRANSLATION) {
1010             CHECK(FUNC(global_motion_param)(ctx, rw, current, type, ref, 0));
1011             CHECK(FUNC(global_motion_param)(ctx, rw, current, type, ref, 1));
1012         }
1013     }
1014
1015     return 0;
1016 }
1017
1018 static int FUNC(film_grain_params)(CodedBitstreamContext *ctx, RWContext *rw,
1019                                    AV1RawFrameHeader *current)
1020 {
1021     CodedBitstreamAV1Context  *priv = ctx->priv_data;
1022     const AV1RawSequenceHeader *seq = priv->sequence_header;
1023     int num_pos_luma, num_pos_chroma;
1024     int i, err;
1025
1026     if (!seq->film_grain_params_present ||
1027         (!current->show_frame && !current->showable_frame))
1028         return 0;
1029
1030     flag(apply_grain);
1031
1032     if (!current->apply_grain)
1033         return 0;
1034
1035     fb(16, grain_seed);
1036
1037     if (current->frame_type == AV1_FRAME_INTER)
1038         flag(update_grain);
1039     else
1040         infer(update_grain, 1);
1041
1042     if (!current->update_grain) {
1043         fb(3, film_grain_params_ref_idx);
1044         return 0;
1045     }
1046
1047     fb(4, num_y_points);
1048     for (i = 0; i < current->num_y_points; i++) {
1049         fbs(8, point_y_value[i],   1, i);
1050         fbs(8, point_y_scaling[i], 1, i);
1051     }
1052
1053     if (seq->color_config.mono_chrome)
1054         infer(chroma_scaling_from_luma, 0);
1055     else
1056         flag(chroma_scaling_from_luma);
1057
1058     if (seq->color_config.mono_chrome ||
1059         current->chroma_scaling_from_luma ||
1060         (seq->color_config.subsampling_x == 1 &&
1061          seq->color_config.subsampling_y == 1 &&
1062          current->num_y_points == 0)) {
1063         infer(num_cb_points, 0);
1064         infer(num_cr_points, 0);
1065     } else {
1066         fb(4, num_cb_points);
1067         for (i = 0; i < current->num_cb_points; i++) {
1068             fbs(8, point_cb_value[i],   1, i);
1069             fbs(8, point_cb_scaling[i], 1, i);
1070         }
1071         fb(4, num_cr_points);
1072         for (i = 0; i < current->num_cr_points; i++) {
1073             fbs(8, point_cr_value[i],   1, i);
1074             fbs(8, point_cr_scaling[i], 1, i);
1075         }
1076     }
1077
1078     fb(2, grain_scaling_minus_8);
1079     fb(2, ar_coeff_lag);
1080     num_pos_luma = 2 * current->ar_coeff_lag * (current->ar_coeff_lag + 1);
1081     if (current->num_y_points) {
1082         num_pos_chroma = num_pos_luma + 1;
1083         for (i = 0; i < num_pos_luma; i++)
1084             fbs(8, ar_coeffs_y_plus_128[i], 1, i);
1085     } else {
1086         num_pos_chroma = num_pos_luma;
1087     }
1088     if (current->chroma_scaling_from_luma || current->num_cb_points) {
1089         for (i = 0; i < num_pos_chroma; i++)
1090             fbs(8, ar_coeffs_cb_plus_128[i], 1, i);
1091     }
1092     if (current->chroma_scaling_from_luma || current->num_cr_points) {
1093         for (i = 0; i < num_pos_chroma; i++)
1094             fbs(8, ar_coeffs_cr_plus_128[i], 1, i);
1095     }
1096     fb(2, ar_coeff_shift_minus_6);
1097     fb(2, grain_scale_shift);
1098     if (current->num_cb_points) {
1099         fb(8, cb_mult);
1100         fb(8, cb_luma_mult);
1101         fb(9, cb_offset);
1102     }
1103     if (current->num_cr_points) {
1104         fb(8, cr_mult);
1105         fb(8, cr_luma_mult);
1106         fb(9, cr_offset);
1107     }
1108
1109     flag(overlap_flag);
1110     flag(clip_to_restricted_range);
1111
1112     return 0;
1113 }
1114
1115 static int FUNC(uncompressed_header)(CodedBitstreamContext *ctx, RWContext *rw,
1116                                      AV1RawFrameHeader *current)
1117 {
1118     CodedBitstreamAV1Context *priv = ctx->priv_data;
1119     const AV1RawSequenceHeader *seq;
1120     int id_len, diff_len, all_frames, frame_is_intra, order_hint_bits;
1121     int i, err;
1122
1123     if (!priv->sequence_header) {
1124         av_log(ctx->log_ctx, AV_LOG_ERROR, "No sequence header available: "
1125                "unable to decode frame header.\n");
1126         return AVERROR_INVALIDDATA;
1127     }
1128     seq = priv->sequence_header;
1129
1130     id_len = seq->additional_frame_id_length_minus_1 +
1131              seq->delta_frame_id_length_minus_2 + 3;
1132     all_frames = (1 << AV1_NUM_REF_FRAMES) - 1;
1133
1134     if (seq->reduced_still_picture_header) {
1135         infer(show_existing_frame, 0);
1136         infer(frame_type,     AV1_FRAME_KEY);
1137         infer(show_frame,     1);
1138         infer(showable_frame, 0);
1139         frame_is_intra = 1;
1140
1141     } else {
1142         flag(show_existing_frame);
1143
1144         if (current->show_existing_frame) {
1145             AV1ReferenceFrameState *frame;
1146
1147             fb(3, frame_to_show_map_idx);
1148             frame = &priv->ref[current->frame_to_show_map_idx];
1149
1150             if (seq->decoder_model_info_present_flag &&
1151                 !seq->timing_info.equal_picture_interval) {
1152                 fb(seq->decoder_model_info.frame_presentation_time_length_minus_1 + 1,
1153                    frame_presentation_time);
1154             }
1155
1156             if (seq->frame_id_numbers_present_flag)
1157                 fb(id_len, display_frame_id);
1158
1159             if (frame->frame_type == AV1_FRAME_KEY)
1160                 infer(refresh_frame_flags, all_frames);
1161             else
1162                 infer(refresh_frame_flags, 0);
1163
1164             return 0;
1165         }
1166
1167         fb(2, frame_type);
1168         frame_is_intra = (current->frame_type == AV1_FRAME_INTRA_ONLY ||
1169                           current->frame_type == AV1_FRAME_KEY);
1170
1171         flag(show_frame);
1172         if (current->show_frame &&
1173             seq->decoder_model_info_present_flag &&
1174             !seq->timing_info.equal_picture_interval) {
1175             fb(seq->decoder_model_info.frame_presentation_time_length_minus_1 + 1,
1176                frame_presentation_time);
1177         }
1178         if (current->show_frame)
1179             infer(showable_frame, current->frame_type != AV1_FRAME_KEY);
1180         else
1181             flag(showable_frame);
1182
1183         if (current->frame_type == AV1_FRAME_SWITCH ||
1184             (current->frame_type == AV1_FRAME_KEY && current->show_frame))
1185             infer(error_resilient_mode, 1);
1186         else
1187             flag(error_resilient_mode);
1188     }
1189
1190     if (current->frame_type == AV1_FRAME_KEY && current->show_frame) {
1191         for (i = 0; i < AV1_NUM_REF_FRAMES; i++) {
1192             priv->ref[i].valid = 0;
1193             priv->ref[i].order_hint = 0;
1194         }
1195     }
1196
1197     flag(disable_cdf_update);
1198
1199     if (seq->seq_force_screen_content_tools ==
1200         AV1_SELECT_SCREEN_CONTENT_TOOLS) {
1201         flag(allow_screen_content_tools);
1202     } else {
1203         infer(allow_screen_content_tools,
1204               seq->seq_force_screen_content_tools);
1205     }
1206     if (current->allow_screen_content_tools) {
1207         if (seq->seq_force_integer_mv == AV1_SELECT_INTEGER_MV)
1208             flag(force_integer_mv);
1209         else
1210             infer(force_integer_mv, seq->seq_force_integer_mv);
1211     } else {
1212         infer(force_integer_mv, 0);
1213     }
1214
1215     if (seq->frame_id_numbers_present_flag) {
1216         fb(id_len, current_frame_id);
1217
1218         diff_len = seq->delta_frame_id_length_minus_2 + 2;
1219         for (i = 0; i < AV1_NUM_REF_FRAMES; i++) {
1220             if (current->current_frame_id > (1 << diff_len)) {
1221                 if (priv->ref[i].frame_id > current->current_frame_id ||
1222                     priv->ref[i].frame_id < (current->current_frame_id -
1223                                              (1 << diff_len)))
1224                     priv->ref[i].valid = 0;
1225             } else {
1226                 if (priv->ref[i].frame_id > current->current_frame_id &&
1227                     priv->ref[i].frame_id < ((1 << id_len) +
1228                                              current->current_frame_id -
1229                                              (1 << diff_len)))
1230                     priv->ref[i].valid = 0;
1231             }
1232         }
1233     } else {
1234         infer(current_frame_id, 0);
1235     }
1236
1237     if (current->frame_type == AV1_FRAME_SWITCH)
1238         infer(frame_size_override_flag, 1);
1239     else if(seq->reduced_still_picture_header)
1240         infer(frame_size_override_flag, 0);
1241     else
1242         flag(frame_size_override_flag);
1243
1244     order_hint_bits =
1245         seq->enable_order_hint ? seq->order_hint_bits_minus_1 + 1 : 0;
1246     if (order_hint_bits > 0)
1247         fb(order_hint_bits, order_hint);
1248     else
1249         infer(order_hint, 0);
1250
1251     if (frame_is_intra || current->error_resilient_mode)
1252         infer(primary_ref_frame, AV1_PRIMARY_REF_NONE);
1253     else
1254         fb(3, primary_ref_frame);
1255
1256     if (seq->decoder_model_info_present_flag) {
1257         flag(buffer_removal_time_present_flag);
1258         if (current->buffer_removal_time_present_flag) {
1259             for (i = 0; i <= seq->operating_points_cnt_minus_1; i++) {
1260                 if (seq->decoder_model_present_for_this_op[i]) {
1261                     int op_pt_idc = seq->operating_point_idc[i];
1262                     int in_temporal_layer = (op_pt_idc >>  priv->temporal_id    ) & 1;
1263                     int in_spatial_layer  = (op_pt_idc >> (priv->spatial_id + 8)) & 1;
1264                     if (seq->operating_point_idc[i] == 0 ||
1265                         in_temporal_layer || in_spatial_layer) {
1266                         fbs(seq->decoder_model_info.buffer_removal_time_length_minus_1 + 1,
1267                             buffer_removal_time[i], 1, i);
1268                     }
1269                 }
1270             }
1271         }
1272     }
1273
1274     if (current->frame_type == AV1_FRAME_SWITCH ||
1275         (current->frame_type == AV1_FRAME_KEY && current->show_frame))
1276         infer(refresh_frame_flags, all_frames);
1277     else
1278         fb(8, refresh_frame_flags);
1279
1280     if (!frame_is_intra || current->refresh_frame_flags != all_frames) {
1281         if (current->error_resilient_mode && seq->enable_order_hint) {
1282             for (i = 0; i < AV1_NUM_REF_FRAMES; i++) {
1283                 fbs(order_hint_bits, ref_order_hint[i], 1, i);
1284                 if (current->ref_order_hint[i] != priv->ref[i].order_hint)
1285                     priv->ref[i].valid = 0;
1286             }
1287         }
1288     }
1289
1290     if (current->frame_type == AV1_FRAME_KEY ||
1291         current->frame_type == AV1_FRAME_INTRA_ONLY) {
1292         CHECK(FUNC(frame_size)(ctx, rw, current));
1293         CHECK(FUNC(render_size)(ctx, rw, current));
1294
1295         if (current->allow_screen_content_tools &&
1296             priv->upscaled_width == priv->frame_width)
1297             flag(allow_intrabc);
1298         else
1299             infer(allow_intrabc, 0);
1300
1301     } else {
1302         if (!seq->enable_order_hint) {
1303             infer(frame_refs_short_signaling, 0);
1304         } else {
1305             flag(frame_refs_short_signaling);
1306             if (current->frame_refs_short_signaling) {
1307                 fb(3, last_frame_idx);
1308                 fb(3, golden_frame_idx);
1309
1310                 for (i = 0; i < AV1_REFS_PER_FRAME; i++) {
1311                     if (i == 0)
1312                         infer(ref_frame_idx[i], current->last_frame_idx);
1313                     else if (i == AV1_REF_FRAME_GOLDEN -
1314                                   AV1_REF_FRAME_LAST)
1315                         infer(ref_frame_idx[i], current->golden_frame_idx);
1316                     else
1317                         infer(ref_frame_idx[i], -1);
1318                 }
1319             }
1320         }
1321
1322         for (i = 0; i < AV1_REFS_PER_FRAME; i++) {
1323             if (!current->frame_refs_short_signaling)
1324                 fbs(3, ref_frame_idx[i], 1, i);
1325             if (seq->frame_id_numbers_present_flag) {
1326                 fb(seq->delta_frame_id_length_minus_2 + 2,
1327                    delta_frame_id_minus1);
1328             }
1329         }
1330
1331         if (current->frame_size_override_flag &&
1332             !current->error_resilient_mode) {
1333             CHECK(FUNC(frame_size_with_refs)(ctx, rw, current));
1334         } else {
1335             CHECK(FUNC(frame_size)(ctx, rw, current));
1336             CHECK(FUNC(render_size)(ctx, rw, current));
1337         }
1338
1339         if (current->force_integer_mv)
1340             infer(allow_high_precision_mv, 0);
1341         else
1342             flag(allow_high_precision_mv);
1343
1344         CHECK(FUNC(interpolation_filter)(ctx, rw, current));
1345
1346         flag(is_motion_mode_switchable);
1347
1348         if (current->error_resilient_mode ||
1349             !seq->enable_ref_frame_mvs)
1350             infer(use_ref_frame_mvs, 0);
1351         else
1352             flag(use_ref_frame_mvs);
1353
1354         infer(allow_intrabc, 0);
1355     }
1356
1357     if (!frame_is_intra) {
1358         // Derive reference frame sign biases.
1359     }
1360
1361     if (seq->reduced_still_picture_header || current->disable_cdf_update)
1362         infer(disable_frame_end_update_cdf, 1);
1363     else
1364         flag(disable_frame_end_update_cdf);
1365
1366     if (current->primary_ref_frame == AV1_PRIMARY_REF_NONE) {
1367         // Init non-coeff CDFs.
1368         // Setup past independence.
1369     } else {
1370         // Load CDF tables from previous frame.
1371         // Load params from previous frame.
1372     }
1373
1374     if (current->use_ref_frame_mvs) {
1375         // Perform motion field estimation process.
1376     }
1377
1378     CHECK(FUNC(tile_info)(ctx, rw, current));
1379
1380     CHECK(FUNC(quantization_params)(ctx, rw, current));
1381
1382     CHECK(FUNC(segmentation_params)(ctx, rw, current));
1383
1384     CHECK(FUNC(delta_q_params)(ctx, rw, current));
1385
1386     CHECK(FUNC(delta_lf_params)(ctx, rw, current));
1387
1388     // Init coeff CDFs / load previous segments.
1389
1390     priv->coded_lossless = 1;
1391     for (i = 0; i < AV1_MAX_SEGMENTS; i++) {
1392         int qindex;
1393         if (current->feature_enabled[i][AV1_SEG_LVL_ALT_Q]) {
1394             qindex = (current->base_q_idx +
1395                       current->feature_value[i][AV1_SEG_LVL_ALT_Q]);
1396         } else {
1397             qindex = current->base_q_idx;
1398         }
1399         qindex = av_clip_uintp2(qindex, 8);
1400
1401         if (qindex                || current->delta_q_y_dc ||
1402             current->delta_q_u_ac || current->delta_q_u_dc ||
1403             current->delta_q_v_ac || current->delta_q_v_dc) {
1404             priv->coded_lossless = 0;
1405         }
1406     }
1407     priv->all_lossless = priv->coded_lossless &&
1408         priv->frame_width == priv->upscaled_width;
1409
1410     CHECK(FUNC(loop_filter_params)(ctx, rw, current));
1411
1412     CHECK(FUNC(cdef_params)(ctx, rw, current));
1413
1414     CHECK(FUNC(lr_params)(ctx, rw, current));
1415
1416     CHECK(FUNC(read_tx_mode)(ctx, rw, current));
1417
1418     CHECK(FUNC(frame_reference_mode)(ctx, rw, current));
1419
1420     CHECK(FUNC(skip_mode_params)(ctx, rw, current));
1421
1422     if (frame_is_intra || current->error_resilient_mode ||
1423         !seq->enable_warped_motion)
1424         infer(allow_warped_motion, 0);
1425     else
1426         flag(allow_warped_motion);
1427
1428     flag(reduced_tx_set);
1429
1430     CHECK(FUNC(global_motion_params)(ctx, rw, current));
1431
1432     CHECK(FUNC(film_grain_params)(ctx, rw, current));
1433
1434     for (i = 0; i < AV1_NUM_REF_FRAMES; i++) {
1435         if (current->refresh_frame_flags & (1 << i)) {
1436             priv->ref[i] = (AV1ReferenceFrameState) {
1437                 .valid          = 1,
1438                 .frame_id       = current->current_frame_id,
1439                 .upscaled_width = priv->upscaled_width,
1440                 .frame_width    = priv->frame_width,
1441                 .frame_height   = priv->frame_height,
1442                 .render_width   = priv->render_width,
1443                 .render_height  = priv->render_height,
1444                 .frame_type     = current->frame_type,
1445                 .subsampling_x  = seq->color_config.subsampling_x,
1446                 .subsampling_y  = seq->color_config.subsampling_y,
1447                 .bit_depth      = priv->bit_depth,
1448                 .order_hint     = current->order_hint,
1449             };
1450         }
1451     }
1452
1453     av_log(ctx->log_ctx, AV_LOG_DEBUG, "Frame %d:  size %dx%d  "
1454            "upscaled %d  render %dx%d  subsample %dx%d  "
1455            "bitdepth %d  tiles %dx%d.\n", current->order_hint,
1456            priv->frame_width, priv->frame_height, priv->upscaled_width,
1457            priv->render_width, priv->render_height,
1458            seq->color_config.subsampling_x + 1,
1459            seq->color_config.subsampling_y + 1, priv->bit_depth,
1460            priv->tile_rows, priv->tile_cols);
1461
1462     return 0;
1463 }
1464
1465 static int FUNC(frame_header_obu)(CodedBitstreamContext *ctx, RWContext *rw,
1466                                   AV1RawFrameHeader *current)
1467 {
1468     CodedBitstreamAV1Context *priv = ctx->priv_data;
1469     int err;
1470
1471     HEADER("Frame Header");
1472
1473     if (priv->seen_frame_header) {
1474         // Nothing to do.
1475     } else {
1476         priv->seen_frame_header = 1;
1477
1478         CHECK(FUNC(uncompressed_header)(ctx, rw, current));
1479
1480         if (current->show_existing_frame) {
1481             priv->seen_frame_header = 0;
1482         } else {
1483             priv->seen_frame_header = 1;
1484         }
1485     }
1486
1487     return 0;
1488 }
1489
1490 static int FUNC(tile_group_obu)(CodedBitstreamContext *ctx, RWContext *rw,
1491                                 AV1RawTileGroup *current)
1492 {
1493     CodedBitstreamAV1Context *priv = ctx->priv_data;
1494     int num_tiles, tile_bits;
1495     int err;
1496
1497     HEADER("Tile Group");
1498
1499     num_tiles = priv->tile_cols * priv->tile_rows;
1500     if (num_tiles > 1)
1501         flag(tile_start_and_end_present_flag);
1502     else
1503         infer(tile_start_and_end_present_flag, 0);
1504
1505     if (num_tiles == 1 || !current->tile_start_and_end_present_flag) {
1506         infer(tg_start, 0);
1507         infer(tg_end, num_tiles - 1);
1508     } else {
1509         tile_bits = cbs_av1_tile_log2(1, priv->tile_cols) +
1510                     cbs_av1_tile_log2(1, priv->tile_rows);
1511         fb(tile_bits, tg_start);
1512         fb(tile_bits, tg_end);
1513     }
1514
1515     CHECK(FUNC(byte_alignment)(ctx, rw));
1516
1517     // Reset header for next frame.
1518     if (current->tg_end == num_tiles - 1)
1519         priv->seen_frame_header = 0;
1520
1521     // Tile data follows.
1522
1523     return 0;
1524 }
1525
1526 static int FUNC(frame_obu)(CodedBitstreamContext *ctx, RWContext *rw,
1527                            AV1RawFrame *current)
1528 {
1529     int err;
1530
1531     CHECK(FUNC(frame_header_obu)(ctx, rw, &current->header));
1532
1533     CHECK(FUNC(byte_alignment)(ctx, rw));
1534
1535     CHECK(FUNC(tile_group_obu)(ctx, rw, &current->tile_group));
1536
1537     return 0;
1538 }
1539
1540 static int FUNC(tile_list_obu)(CodedBitstreamContext *ctx, RWContext *rw,
1541                                AV1RawTileList *current)
1542 {
1543     int err;
1544
1545     fb(8, output_frame_width_in_tiles_minus_1);
1546     fb(8, output_frame_height_in_tiles_minus_1);
1547
1548     fb(16, tile_count_minus_1);
1549
1550     // Tile data follows.
1551
1552     return 0;
1553 }
1554
1555 static int FUNC(metadata_hdr_cll)(CodedBitstreamContext *ctx, RWContext *rw,
1556                                   AV1RawMetadataHDRCLL *current)
1557 {
1558     int err;
1559
1560     fb(16, max_cll);
1561     fb(16, max_fall);
1562
1563     return 0;
1564 }
1565
1566 static int FUNC(metadata_hdr_mdcv)(CodedBitstreamContext *ctx, RWContext *rw,
1567                                    AV1RawMetadataHDRMDCV *current)
1568 {
1569     int err, i;
1570
1571     for (i = 0; i < 3; i++) {
1572         fcs(16, primary_chromaticity_x[i], 0, 50000, 1, i);
1573         fcs(16, primary_chromaticity_y[i], 0, 50000, 1, i);
1574     }
1575
1576     fc(16, white_point_chromaticity_x, 0, 50000);
1577     fc(16, white_point_chromaticity_y, 0, 50000);
1578
1579     fc(32, luminance_max, 1, MAX_UINT_BITS(32));
1580     fc(32, luminance_min, 0, current->luminance_max >> 6);
1581
1582     return 0;
1583 }
1584
1585 static int FUNC(metadata_scalability)(CodedBitstreamContext *ctx, RWContext *rw,
1586                                       AV1RawMetadataScalability *current)
1587 {
1588     // TODO: scalability metadata.
1589
1590     return AVERROR_PATCHWELCOME;
1591 }
1592
1593 static int FUNC(metadata_itut_t35)(CodedBitstreamContext *ctx, RWContext *rw,
1594                                    AV1RawMetadataITUTT35 *current)
1595 {
1596     int err;
1597     size_t i;
1598
1599     fb(8, itu_t_t35_country_code);
1600     if (current->itu_t_t35_country_code == 0xff)
1601         fb(8, itu_t_t35_country_code_extension_byte);
1602
1603 #ifdef READ
1604     // The payload runs up to the start of the trailing bits, but there might
1605     // be arbitrarily many trailing zeroes so we need to read through twice.
1606     {
1607         GetBitContext tmp = *rw;
1608         current->payload_size = 0;
1609         for (i = 0; get_bits_left(rw) >= 8; i++) {
1610             if (get_bits(rw, 8))
1611                 current->payload_size = i;
1612         }
1613         *rw = tmp;
1614     }
1615
1616     current->payload_ref = av_buffer_alloc(current->payload_size);
1617     if (!current->payload_ref)
1618         return AVERROR(ENOMEM);
1619     current->payload = current->payload_ref->data;
1620 #endif
1621
1622     for (i = 0; i < current->payload_size; i++)
1623         xf(8, itu_t_t35_payload_bytes[i], current->payload[i],
1624            0x00, 0xff, 1, i);
1625
1626     return 0;
1627 }
1628
1629 static int FUNC(metadata_timecode)(CodedBitstreamContext *ctx, RWContext *rw,
1630                                    AV1RawMetadataTimecode *current)
1631 {
1632     int err;
1633
1634     fb(5, counting_type);
1635     flag(full_timestamp_flag);
1636     flag(discontinuity_flag);
1637     flag(cnt_dropped_flag);
1638     fb(9, n_frames);
1639
1640     if (current->full_timestamp_flag) {
1641         fb(6, seconds_value);
1642         fb(6, minutes_value);
1643         fb(5, hours_value);
1644     } else {
1645         flag(seconds_flag);
1646         if (current->seconds_flag) {
1647             fb(6, seconds_value);
1648             flag(minutes_flag);
1649             if (current->minutes_flag) {
1650                 fb(6, minutes_value);
1651                 flag(hours_flag);
1652                 if (current->hours_flag)
1653                     fb(5, hours_value);
1654             }
1655         }
1656     }
1657
1658     fb(5, time_offset_length);
1659     if (current->time_offset_length > 0)
1660         fb(current->time_offset_length, time_offset_value);
1661
1662     return 0;
1663 }
1664
1665 static int FUNC(metadata_obu)(CodedBitstreamContext *ctx, RWContext *rw,
1666                               AV1RawMetadata *current)
1667 {
1668     int err;
1669
1670     leb128(metadata_type);
1671
1672     switch (current->metadata_type) {
1673     case AV1_METADATA_TYPE_HDR_CLL:
1674         CHECK(FUNC(metadata_hdr_cll)(ctx, rw, &current->metadata.hdr_cll));
1675         break;
1676     case AV1_METADATA_TYPE_HDR_MDCV:
1677         CHECK(FUNC(metadata_hdr_mdcv)(ctx, rw, &current->metadata.hdr_mdcv));
1678         break;
1679     case AV1_METADATA_TYPE_SCALABILITY:
1680         CHECK(FUNC(metadata_scalability)(ctx, rw, &current->metadata.scalability));
1681         break;
1682     case AV1_METADATA_TYPE_ITUT_T35:
1683         CHECK(FUNC(metadata_itut_t35)(ctx, rw, &current->metadata.itut_t35));
1684         break;
1685     case AV1_METADATA_TYPE_TIMECODE:
1686         CHECK(FUNC(metadata_timecode)(ctx, rw, &current->metadata.timecode));
1687         break;
1688     default:
1689         // Unknown metadata type.
1690         return AVERROR_PATCHWELCOME;
1691     }
1692
1693     return 0;
1694 }