e65a154b3aac25689262497e0a112b06050f6989
[platform/upstream/gstreamer.git] / subprojects / gst-plugins-bad / gst-libs / gst / codecparsers / gstav1parser.c
1 /* gstav1parser.c
2  *
3  *  Copyright (C) 2018 Georg Ottinger
4  *  Copyright (C) 2019-2020 Intel Corporation
5  *    Author: Georg Ottinger <g.ottinger@gmx.at>
6  *    Author: Junyan He <junyan.he@hotmail.com>
7  *    Author: Victor Jaquez <vjaquez@igalia.com>
8  *
9  * This library is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public
11  * License as published by the Free Software Foundation; either
12  * version 2.1 of the License, or (at your option) any later version.
13  *
14  * This library is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with this library; if not, write to the
21  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
22  * Boston, MA 02110-1301, USA.
23  */
24 /**
25  * SECTION:gstav1parser
26  * @title: GstAV1Parser
27  * @short_description: Convenience library for parsing AV1 video bitstream.
28  *
29  * For more details about the structures, you can refer to the AV1 Bitstream &
30  * Decoding Process Specification V1.0.0
31  * [specification](https://aomediacodec.github.io/av1-spec/av1-spec.pdf)
32  *
33  * It offers you bitstream parsing of low overhead bistream format (Section 5)
34  * or Annex B according to the setting of the parser. By calling the function of
35  * gst_av1_parser_reset(), user can switch between bistream mode and Annex B mode.
36  *
37  * To retrieve OBUs and parse its headers, you should firstly call the function of
38  * gst_av1_parser_identify_one_obu() to get the OBU type if succeeds or just discard
39  * the data if fails.
40  *
41  * Then, depending on the #GstAV1OBUType of the newly parsed #GstAV1OBU,
42  * you should call the differents functions to parse the structure details:
43  *
44  *   * #GST_AV1_OBU_SEQUENCE_HEADER: gst_av1_parser_parse_sequence_header_obu()
45  *
46  *   * #GST_AV1_OBU_TEMPORAL_DELIMITER: gst_av1_parser_parse_temporal_delimiter_obu()
47  *
48  *   * #GST_AV1_OBU_FRAME: gst_av1_parser_parse_frame_obu()
49  *
50  *   * #GST_AV1_OBU_FRAME_HEADER: gst_av1_parser_parse_frame_header_obu()
51  *
52  *   * #GST_AV1_OBU_TILE_GROUP: gst_av1_parser_parse_tile_group_obu()
53  *
54  *   * #GST_AV1_OBU_METADATA: gst_av1_parser_parse_metadata_obu()
55  *
56  *   * #GST_AV1_OBU_REDUNDANT_FRAME_HEADER: gst_av1_parser_parse_frame_header_obu()
57  *
58  *   * #GST_AV1_OBU_TILE_LIST: gst_av1_parser_parse_tile_list_obu()
59  *
60  * Note: Some parser functions are dependent on information provided in the sequence
61  * header and reference frame's information. It maintains a state inside itself, which
62  * contains all global vars and reference information during the whole parsing process.
63  * Calling gst_av1_parser_reset() or a new sequence's arriving can clear and reset this
64  * inside state.
65  *
66  * After successfully handled a frame(for example, decode a frame successfully), you
67  * should call gst_av1_parser_reference_frame_update() to update the parser's inside
68  * state(such as reference information, global segmentation information, etc).
69  *
70  * @since: 1.18.00
71  */
72
73 #ifdef HAVE_CONFIG_H
74 #include "config.h"
75 #endif
76
77 #include "gstav1parser.h"
78
79 #include <gst/base/gstbitreader.h>
80
81 #include <string.h>
82 #include <stdlib.h>
83
84 #ifndef GST_DISABLE_GST_DEBUG
85 #define GST_CAT_DEFAULT gst_av1_debug_category_get ()
86 static GstDebugCategory *
87 gst_av1_debug_category_get (void)
88 {
89   static gsize cat_gonce = 0;
90
91   if (g_once_init_enter (&cat_gonce)) {
92     GstDebugCategory *cat = NULL;
93
94     GST_DEBUG_CATEGORY_INIT (cat, "codecparsers_av1", 0, "av1 parse library");
95
96     g_once_init_leave (&cat_gonce, (gsize) cat);
97   }
98
99   return (GstDebugCategory *) cat_gonce;
100 }
101 #endif /* GST_DISABLE_GST_DEBUG */
102
103 #define AV1_READ_BIT(br)    ((guint8) gst_bit_reader_get_bits_uint32_unchecked (br, 1))
104 #define AV1_READ_UINT8(br)  ((guint8) gst_bit_reader_get_bits_uint32_unchecked (br, 8))
105 #define AV1_READ_UINT16(br) ((guint16) gst_bit_reader_get_bits_uint32_unchecked (br, 16))
106 #define AV1_READ_UINT32(br) gst_bit_reader_get_bits_uint32_unchecked (br, 32)
107 #define AV1_READ_UINT64(br) gst_bit_reader_get_bits_uint64_unchecked (br, 64)
108 #define AV1_READ_BITS(br, nbits)                                        \
109   ((nbits <= 32) ? (gst_bit_reader_get_bits_uint32_unchecked (br, nbits)) : \
110    (gst_bit_reader_get_bits_uint64_unchecked (br, nbits)))
111
112 static guint64
113 av1_read_bits_checked (GstBitReader * br, guint nbits,
114     GstAV1ParserResult * retval, const char *func_name, gint line)
115 {
116   guint64 read_bits = 0;
117   gboolean result;
118
119   if (nbits <= 64)
120     result = gst_bit_reader_get_bits_uint64 (br, &read_bits, nbits);
121   else
122     result = FALSE;
123
124   if (result == TRUE) {
125     *retval = GST_AV1_PARSER_OK;
126     return read_bits;
127   } else {
128     *retval = GST_AV1_PARSER_NO_MORE_DATA;
129     GST_WARNING ("Read %d bits failed in func: %s, line %d", nbits, func_name,
130         line);
131     return 0;
132   }
133 }
134
135 #define AV1_READ_BIT_CHECKED(br, ret)                                   \
136   ((guint8) av1_read_bits_checked (br, 1, ret, __func__, __LINE__))
137 #define AV1_READ_UINT8_CHECKED(br, ret)                                 \
138   ((guint8) av1_read_bits_checked (br, 8, ret, __func__, __LINE__))
139 #define AV1_READ_UINT16_CHECKED(br, ret)                                \
140   ((guint16) av1_read_bits_checked (br, 16, ret, __func__, __LINE__))
141 #define AV1_READ_UINT32_CHECKED(br, ret)                                \
142   ((guint32) av1_read_bits_checked (br, 32, ret, __func__, __LINE__))
143 #define AV1_READ_BITS_CHECKED(br, nbits, ret)                   \
144   av1_read_bits_checked (br, nbits, ret, __func__, __LINE__)
145
146 #define AV1_REMAINING_BYTES(br) (gst_bit_reader_get_remaining (br) / 8)
147 #define AV1_REMAINING_BITS(br)  (gst_bit_reader_get_remaining (br))
148
149 /*************************************
150  *                                   *
151  * Helperfunctions                   *
152  *                                   *
153  *************************************/
154
155 /* 4.7
156  *
157  * floor of the base 2 logarithm of the input x */
158 static gint
159 av1_helpers_floor_log2 (guint32 x)
160 {
161   gint s = 0;
162
163   while (x != 0) {
164     x = x >> 1;
165     s++;
166   }
167   return s - 1;
168 }
169
170 /* 5.9.16 Tile size calculation
171  *
172  * returns the smallest value for k such that blkSize << k is greater
173  * than or equal to target */
174 static gint
175 av1_helper_tile_log2 (gint blkSize, gint target)
176 {
177   gint k;
178   for (k = 0; (blkSize << k) < target; k++);
179   return k;
180 }
181
182 /* 5.9.29 */
183 static gint
184 av1_helper_inverse_recenter (gint r, gint v)
185 {
186   if (v > 2 * r)
187     return v;
188   else if (v & 1)
189     return r - ((v + 1) >> 1);
190   else
191     return r + (v >> 1);
192 }
193
194 /* Shift down with rounding for use when n >= 0, value >= 0 */
195 static guint64
196 av1_helper_round_power_of_two (guint64 value, guint16 n)
197 {
198   return (value + (((guint64) (1) << n) >> 1)) >> n;
199 }
200
201  /* Shift down with rounding for signed integers, for use when n >= 0 */
202 static gint64
203 av1_helper_round_power_of_two_signed (gint64 value, guint16 n)
204 {
205   return (value < 0) ? -((gint64) (av1_helper_round_power_of_two (-value, n)))
206       : (gint64) av1_helper_round_power_of_two (value, n);
207 }
208
209 static gint
210 av1_helper_msb (guint n)
211 {
212   int log = 0;
213   guint value = n;
214   int i;
215
216   g_assert (n != 0);
217
218   for (i = 4; i >= 0; --i) {
219     const gint shift = (1 << i);
220     const guint x = value >> shift;
221     if (x != 0) {
222       value = x;
223       log += shift;
224     }
225   }
226   return log;
227 }
228
229 static const guint16 div_lut[GST_AV1_DIV_LUT_NUM + 1] = {
230   16384, 16320, 16257, 16194, 16132, 16070, 16009, 15948, 15888, 15828, 15768,
231   15709, 15650, 15592, 15534, 15477, 15420, 15364, 15308, 15252, 15197, 15142,
232   15087, 15033, 14980, 14926, 14873, 14821, 14769, 14717, 14665, 14614, 14564,
233   14513, 14463, 14413, 14364, 14315, 14266, 14218, 14170, 14122, 14075, 14028,
234   13981, 13935, 13888, 13843, 13797, 13752, 13707, 13662, 13618, 13574, 13530,
235   13487, 13443, 13400, 13358, 13315, 13273, 13231, 13190, 13148, 13107, 13066,
236   13026, 12985, 12945, 12906, 12866, 12827, 12788, 12749, 12710, 12672, 12633,
237   12596, 12558, 12520, 12483, 12446, 12409, 12373, 12336, 12300, 12264, 12228,
238   12193, 12157, 12122, 12087, 12053, 12018, 11984, 11950, 11916, 11882, 11848,
239   11815, 11782, 11749, 11716, 11683, 11651, 11619, 11586, 11555, 11523, 11491,
240   11460, 11429, 11398, 11367, 11336, 11305, 11275, 11245, 11215, 11185, 11155,
241   11125, 11096, 11067, 11038, 11009, 10980, 10951, 10923, 10894, 10866, 10838,
242   10810, 10782, 10755, 10727, 10700, 10673, 10645, 10618, 10592, 10565, 10538,
243   10512, 10486, 10460, 10434, 10408, 10382, 10356, 10331, 10305, 10280, 10255,
244   10230, 10205, 10180, 10156, 10131, 10107, 10082, 10058, 10034, 10010, 9986,
245   9963, 9939, 9916, 9892, 9869, 9846, 9823, 9800, 9777, 9754, 9732,
246   9709, 9687, 9664, 9642, 9620, 9598, 9576, 9554, 9533, 9511, 9489,
247   9468, 9447, 9425, 9404, 9383, 9362, 9341, 9321, 9300, 9279, 9259,
248   9239, 9218, 9198, 9178, 9158, 9138, 9118, 9098, 9079, 9059, 9039,
249   9020, 9001, 8981, 8962, 8943, 8924, 8905, 8886, 8867, 8849, 8830,
250   8812, 8793, 8775, 8756, 8738, 8720, 8702, 8684, 8666, 8648, 8630,
251   8613, 8595, 8577, 8560, 8542, 8525, 8508, 8490, 8473, 8456, 8439,
252   8422, 8405, 8389, 8372, 8355, 8339, 8322, 8306, 8289, 8273, 8257,
253   8240, 8224, 8208, 8192,
254 };
255
256 static gint16
257 av1_helper_resolve_divisor_32 (guint32 D, gint16 * shift)
258 {
259   gint32 f;
260   gint32 e;
261
262   *shift = av1_helper_msb (D);
263   // e is obtained from D after resetting the most significant 1 bit.
264   e = D - ((guint32) 1 << *shift);
265   // Get the most significant DIV_LUT_BITS (8) bits of e into f
266   if (*shift > GST_AV1_DIV_LUT_BITS)
267     f = av1_helper_round_power_of_two (e, *shift - GST_AV1_DIV_LUT_BITS);
268   else
269     f = e << (GST_AV1_DIV_LUT_BITS - *shift);
270   g_assert (f <= GST_AV1_DIV_LUT_NUM);
271   *shift += GST_AV1_DIV_LUT_PREC_BITS;
272   // Use f as lookup into the precomputed table of multipliers
273   return div_lut[f];
274 }
275
276 /*************************************
277  *                                   *
278  * Bitstream Functions               *
279  *                                   *
280  *************************************/
281 /* 4.10.5
282  *
283  * Unsigned integer represented by a variable number of little-endian
284  * bytes. */
285 static guint32
286 av1_bitstreamfn_leb128 (GstBitReader * br, GstAV1ParserResult * retval)
287 {
288   guint8 leb128_byte = 0;
289   guint64 value = 0;
290   gint i;
291
292   for (i = 0; i < 8; i++) {
293     leb128_byte = AV1_READ_UINT8_CHECKED (br, retval);
294     if (*retval != GST_AV1_PARSER_OK)
295       return 0;
296
297     value |= (((gint) leb128_byte & 0x7f) << (i * 7));
298     if (!(leb128_byte & 0x80))
299       break;
300   }
301
302   /* check for bitstream conformance see chapter4.10.5 */
303   if (value < G_MAXUINT32) {
304     return (guint32) value;
305   } else {
306     GST_WARNING ("invalid leb128");
307     *retval = GST_AV1_PARSER_BITSTREAM_ERROR;
308     return 0;
309   }
310 }
311
312 /* 4.10.3
313  *
314  * Variable length unsigned n-bit number appearing directly in the
315  * bitstream */
316 static guint32
317 av1_bitstreamfn_uvlc (GstBitReader * br, GstAV1ParserResult * retval)
318 {
319   guint8 leadingZero = 0;
320   guint32 readv;
321   guint32 value;
322   gboolean done;
323
324   while (1) {
325     done = AV1_READ_BIT_CHECKED (br, retval);
326     if (*retval != GST_AV1_PARSER_OK) {
327       GST_WARNING ("invalid uvlc");
328       return 0;
329     }
330
331     if (done)
332       break;
333     leadingZero++;
334   }
335
336   if (leadingZero >= 32) {
337     value = G_MAXUINT32;
338     return value;
339   }
340   readv = AV1_READ_BITS_CHECKED (br, leadingZero, retval);
341   if (*retval != GST_AV1_PARSER_OK) {
342     GST_WARNING ("invalid uvlc");
343     return 0;
344   }
345
346   value = readv + (1 << leadingZero) - 1;
347
348   return value;
349 }
350
351 /* 4.10.6
352  *
353  * Signed integer converted from an n bits unsigned integer in the
354  * bitstream */
355 static guint32
356 av1_bitstreamfn_su (GstBitReader * br, guint8 n, GstAV1ParserResult * retval)
357 {
358   guint32 v, signMask;
359
360   v = AV1_READ_BITS_CHECKED (br, n, retval);
361   if (*retval != GST_AV1_PARSER_OK)
362     return 0;
363
364   signMask = 1 << (n - 1);
365   if (v & signMask)
366     return v - 2 * signMask;
367   else
368     return v;
369 }
370
371 /* 4.10.7
372  *
373  * Unsigned encoded integer with maximum number of values n */
374 static guint32
375 av1_bitstreamfn_ns (GstBitReader * br, guint32 n, GstAV1ParserResult * retval)
376 {
377   gint w, m, v;
378   gint extra_bit;
379
380   w = av1_helpers_floor_log2 (n) + 1;
381   m = (1 << w) - n;
382   v = AV1_READ_BITS_CHECKED (br, w - 1, retval);
383   if (*retval != GST_AV1_PARSER_OK)
384     return 0;
385
386   if (v < m)
387     return v;
388   extra_bit = AV1_READ_BITS_CHECKED (br, 1, retval);
389   if (*retval != GST_AV1_PARSER_OK)
390     return 0;
391
392   return (v << 1) - m + extra_bit;
393 }
394
395 /* 4.10.4
396  *
397  * Unsigned little-endian n-byte number appearing directly in the
398  * bitstream */
399 static guint
400 av1_bitstreamfn_le (GstBitReader * br, guint8 n, GstAV1ParserResult * retval)
401 {
402   guint t = 0;
403   guint8 byte;
404   gint i;
405
406   for (i = 0; i < n; i++) {
407     byte = AV1_READ_BITS_CHECKED (br, 8, retval);
408     if (*retval != GST_AV1_PARSER_OK)
409       return 0;
410
411     t += (byte << (i * 8));
412   }
413   return t;
414 }
415
416 /* 5.9.13
417  *
418  * Delta quantizer */
419 static gint8
420 av1_bitstreamfn_delta_q (GstBitReader * br, GstAV1ParserResult * retval)
421 {
422   guint8 delta_coded;
423
424   delta_coded = AV1_READ_BIT_CHECKED (br, retval);
425   if (*retval != GST_AV1_PARSER_OK)
426     return 0;
427
428   if (delta_coded) {
429     gint delta_q = av1_bitstreamfn_su (br, 7, retval);
430     if (*retval != GST_AV1_PARSER_OK)
431       return 0;
432     return delta_q;
433   } else {
434     return 0;
435   }
436
437   return 0;
438 }
439
440 /* 5.3.4 */
441 static GstAV1ParserResult
442 av1_bitstreamfn_trailing_bits (GstBitReader * br, guint32 nbBits)
443 {
444   guint8 trailing_one_bit, trailing_zero_bit;
445
446   g_assert (nbBits);
447
448   trailing_one_bit = AV1_READ_BIT (br);
449   if (trailing_one_bit != 1) {
450     return GST_AV1_PARSER_BITSTREAM_ERROR;
451   }
452
453   nbBits--;
454   while (nbBits > 0) {
455     trailing_zero_bit = AV1_READ_BIT (br);
456     if (trailing_zero_bit != 0)
457       return GST_AV1_PARSER_BITSTREAM_ERROR;
458     nbBits--;
459   }
460
461   return GST_AV1_PARSER_OK;
462 }
463
464 static GstAV1ParserResult
465 av1_skip_trailing_bits (GstAV1Parser * parser, GstBitReader * br,
466     GstAV1OBU * obu)
467 {
468   guint32 payloadBits = gst_bit_reader_get_pos (br);
469   GstAV1ParserResult ret;
470
471   if (obu->obu_size > 0
472       && obu->obu_type != GST_AV1_OBU_TILE_GROUP
473       && obu->obu_type != GST_AV1_OBU_TILE_LIST
474       && obu->obu_type != GST_AV1_OBU_FRAME) {
475     if (payloadBits >= obu->obu_size * 8)
476       return GST_AV1_PARSER_NO_MORE_DATA;
477
478     ret = av1_bitstreamfn_trailing_bits (br, obu->obu_size * 8 - payloadBits);
479     if (ret != GST_AV1_PARSER_OK)
480       return ret;
481   }
482   return GST_AV1_PARSER_OK;
483 }
484
485 static gboolean
486 av1_seq_level_idx_is_valid (GstAV1SeqLevels seq_level_idx)
487 {
488   return seq_level_idx == GST_AV1_SEQ_LEVEL_MAX
489       || (seq_level_idx < GST_AV1_SEQ_LEVELS
490       /* The following levels are currently undefined. */
491       && seq_level_idx != GST_AV1_SEQ_LEVEL_2_2
492       && seq_level_idx != GST_AV1_SEQ_LEVEL_2_3
493       && seq_level_idx != GST_AV1_SEQ_LEVEL_3_2
494       && seq_level_idx != GST_AV1_SEQ_LEVEL_3_3
495       && seq_level_idx != GST_AV1_SEQ_LEVEL_4_2
496       && seq_level_idx != GST_AV1_SEQ_LEVEL_4_3
497       && seq_level_idx != GST_AV1_SEQ_LEVEL_7_0
498       && seq_level_idx != GST_AV1_SEQ_LEVEL_7_1
499       && seq_level_idx != GST_AV1_SEQ_LEVEL_7_2
500       && seq_level_idx != GST_AV1_SEQ_LEVEL_7_3);
501 }
502
503 static void
504 av1_parser_init_sequence_header (GstAV1SequenceHeaderOBU * seq_header)
505 {
506   memset (seq_header, 0, sizeof (*seq_header));
507   seq_header->bit_depth = 8;
508   seq_header->num_planes = 1;
509 }
510
511 /*************************************
512  *                                   *
513  * Parser Functions                  *
514  *                                   *
515  *************************************/
516 static void
517 gst_av1_parse_reset_state (GstAV1Parser * parser, gboolean free_sps)
518 {
519   parser->state.begin_first_frame = FALSE;
520
521   parser->state.prev_frame_id = 0;
522   parser->state.current_frame_id = 0;
523   memset (&parser->state.ref_info, 0, sizeof (parser->state.ref_info));
524   parser->state.frame_width = 0;
525   parser->state.frame_height = 0;
526   parser->state.upscaled_width = 0;
527   parser->state.mi_cols = 0;
528   parser->state.mi_rows = 0;
529   parser->state.render_width = 0;
530   parser->state.render_height = 0;
531
532   memset (parser->state.mi_col_starts, 0, sizeof (parser->state.mi_col_starts));
533   memset (parser->state.mi_row_starts, 0, sizeof (parser->state.mi_row_starts));
534
535   parser->state.tile_cols_log2 = 0;
536   parser->state.tile_cols = 0;
537   parser->state.tile_rows_log2 = 0;
538   parser->state.tile_rows = 0;
539   parser->state.tile_size_bytes = 0;
540
541   parser->state.seen_frame_header = 0;
542
543   if (free_sps) {
544     parser->state.sequence_changed = FALSE;
545
546     if (parser->seq_header) {
547       g_slice_free (GstAV1SequenceHeaderOBU, parser->seq_header);
548       parser->seq_header = NULL;
549     }
550   }
551 }
552
553 /**
554  * gst_av1_parser_reset:
555  * @parser: the #GstAV1Parser
556  * @annex_b: indicate whether conforms to annex b
557  *
558  * Reset the current #GstAV1Parser's state totally.
559  *
560  * Since: 1.18
561  */
562 void
563 gst_av1_parser_reset (GstAV1Parser * parser, gboolean annex_b)
564 {
565   g_return_if_fail (parser != NULL);
566
567   parser->annex_b = annex_b;
568   if (parser->annex_b)
569     gst_av1_parser_reset_annex_b (parser);
570
571   gst_av1_parse_reset_state (parser, TRUE);
572 }
573
574 /**
575  * gst_av1_parser_reset_annex_b:
576  * @parser: the #GstAV1Parser
577  *
578  * Only reset the current #GstAV1Parser's annex b context.
579  * The other part of the state is kept.
580  *
581  * Since: 1.20
582  */
583 void
584 gst_av1_parser_reset_annex_b (GstAV1Parser * parser)
585 {
586   g_return_if_fail (parser != NULL);
587   g_return_if_fail (parser->annex_b);
588
589   if (parser->temporal_unit_consumed < parser->temporal_unit_size)
590     GST_DEBUG ("temporal_unit_consumed: %d, temporal_unit_size:%d, "
591         "discard the left %d bytes for a temporal_unit.",
592         parser->temporal_unit_consumed, parser->temporal_unit_size,
593         parser->temporal_unit_size - parser->temporal_unit_consumed);
594
595   if (parser->frame_unit_consumed < parser->frame_unit_size)
596     GST_DEBUG (" frame_unit_consumed %d, frame_unit_size: %d "
597         "discard the left %d bytes for a frame_unit.",
598         parser->frame_unit_consumed, parser->frame_unit_size,
599         parser->frame_unit_size - parser->frame_unit_consumed);
600
601   parser->temporal_unit_consumed = 0;
602   parser->temporal_unit_size = 0;
603   parser->frame_unit_consumed = 0;
604   parser->frame_unit_size = 0;
605 }
606
607 /* 5.3.2 */
608 static GstAV1ParserResult
609 gst_av1_parse_obu_header (GstAV1Parser * parser, GstBitReader * br,
610     GstAV1OBUHeader * obu_header)
611 {
612   guint8 obu_forbidden_bit;
613   guint8 obu_reserved_1bit;
614   guint8 obu_extension_header_reserved_3bits;
615   GstAV1ParserResult ret = GST_AV1_PARSER_OK;
616
617   if (AV1_REMAINING_BYTES (br) < 1) {
618     ret = GST_AV1_PARSER_NO_MORE_DATA;
619     goto error;
620   }
621
622   obu_forbidden_bit = AV1_READ_BIT (br);
623   if (obu_forbidden_bit != 0) {
624     ret = GST_AV1_PARSER_BITSTREAM_ERROR;
625     goto error;
626   }
627
628   obu_header->obu_type = AV1_READ_BITS (br, 4);
629   obu_header->obu_extention_flag = AV1_READ_BIT (br);
630   obu_header->obu_has_size_field = AV1_READ_BIT (br);
631   obu_reserved_1bit = AV1_READ_BIT (br);
632   if (obu_reserved_1bit != 0) {
633     ret = GST_AV1_PARSER_BITSTREAM_ERROR;
634     goto error;
635   }
636
637   if (obu_header->obu_extention_flag) {
638     if (AV1_REMAINING_BYTES (br) < 1) {
639       ret = GST_AV1_PARSER_NO_MORE_DATA;
640       goto error;
641     }
642
643     /* 5.3.3 OBU extension header */
644     obu_header->obu_temporal_id = AV1_READ_BITS (br, 3);
645     obu_header->obu_spatial_id = AV1_READ_BITS (br, 2);
646     obu_extension_header_reserved_3bits = AV1_READ_BITS (br, 3);
647     if (obu_extension_header_reserved_3bits != 0) {
648       ret = GST_AV1_PARSER_BITSTREAM_ERROR;
649       goto error;
650     }
651   }
652
653   return GST_AV1_PARSER_OK;
654
655 error:
656   GST_WARNING ("parse OBU header error %d", ret);
657   return ret;
658 }
659
660 /**
661  * gst_av1_parser_identify_one_obu:
662  * @parser: the #GstAV1Parser
663  * @data: the data to parse
664  * @size: the size of @data
665  * @obu: a #GstAV1OBU to store the identified result
666  * @consumed: (out): the consumed data size
667  *
668  * Identify one @obu's type from the incoming data stream. This function
669  * should be called first to know the type of @obu before other parse APIs.
670  *
671  * Returns: The #GstAV1ParserResult.
672  *
673  * Since: 1.18
674  */
675 GstAV1ParserResult
676 gst_av1_parser_identify_one_obu (GstAV1Parser * parser, const guint8 * data,
677     guint32 size, GstAV1OBU * obu, guint32 * consumed)
678 {
679   GstAV1ParserResult ret = GST_AV1_PARSER_OK;
680   GstBitReader br;
681   guint obu_length = 0;
682   guint32 used;
683
684   g_return_val_if_fail (parser != NULL, GST_AV1_PARSER_INVALID_OPERATION);
685   g_return_val_if_fail (obu != NULL, GST_AV1_PARSER_INVALID_OPERATION);
686   g_return_val_if_fail (data != NULL, GST_AV1_PARSER_INVALID_OPERATION);
687   g_return_val_if_fail (consumed != NULL, GST_AV1_PARSER_INVALID_OPERATION);
688
689   *consumed = 0;
690   memset (obu, 0, sizeof (*obu));
691
692   if (parser->annex_b) {
693     GST_LOG ("temporal_unit_consumed: %d, temporal_unit_size:%d,"
694         " frame_unit_consumed %d, frame_unit_size: %d",
695         parser->temporal_unit_consumed, parser->temporal_unit_size,
696         parser->frame_unit_consumed, parser->frame_unit_size);
697   }
698
699   if (!size) {
700     ret = GST_AV1_PARSER_NO_MORE_DATA;
701     goto error;
702   }
703
704   /* parse the data size if annex_b */
705   if (parser->annex_b) {
706     guint last_pos;
707   annex_b_again:
708     last_pos = 0;
709
710     if (*consumed > size)
711       goto error;
712     if (*consumed == size) {
713       ret = GST_AV1_PARSER_NO_MORE_DATA;
714       goto error;
715     }
716     gst_bit_reader_init (&br, data + *consumed, size - *consumed);
717
718     if (parser->temporal_unit_consumed > parser->temporal_unit_size)
719       goto error;
720
721     if (parser->temporal_unit_consumed &&
722         parser->temporal_unit_consumed == parser->temporal_unit_size) {
723       GST_LOG ("Complete a temporal unit of size %d",
724           parser->temporal_unit_size);
725       parser->temporal_unit_consumed = parser->temporal_unit_size = 0;
726     }
727
728     if (parser->temporal_unit_size == 0) {
729       parser->temporal_unit_size = av1_bitstreamfn_leb128 (&br, &ret);
730       if (ret != GST_AV1_PARSER_OK)
731         goto error;
732
733       g_assert (gst_bit_reader_get_pos (&br) % 8 == 0);
734       used = (gst_bit_reader_get_pos (&br) / 8 - last_pos);
735       last_pos = gst_bit_reader_get_pos (&br) / 8;
736       *consumed += used;
737
738       if (parser->temporal_unit_consumed == parser->temporal_unit_size) {
739         /* Some extreme case like a temporal unit just
740            hold a temporal_unit_size = 0 */
741         goto annex_b_again;
742       }
743     }
744
745     if (parser->frame_unit_consumed > parser->frame_unit_size)
746       goto error;
747
748     if (parser->frame_unit_consumed &&
749         parser->frame_unit_consumed == parser->frame_unit_size) {
750       GST_LOG ("Complete a frame unit of size %d", parser->frame_unit_size);
751       parser->frame_unit_size = parser->frame_unit_consumed = 0;
752     }
753
754     if (parser->frame_unit_size == 0) {
755       parser->frame_unit_size = av1_bitstreamfn_leb128 (&br, &ret);
756       if (ret != GST_AV1_PARSER_OK)
757         goto error;
758
759       g_assert (gst_bit_reader_get_pos (&br) % 8 == 0);
760       used = gst_bit_reader_get_pos (&br) / 8 - last_pos;
761       last_pos = gst_bit_reader_get_pos (&br) / 8;
762       *consumed += used;
763       parser->temporal_unit_consumed += used;
764
765       if (parser->frame_unit_size >
766           parser->temporal_unit_size - parser->temporal_unit_consumed) {
767         GST_INFO ("Error stream, frame unit size %d, bigger than the left"
768             "temporal unit size %d", parser->frame_unit_size,
769             parser->temporal_unit_size - parser->temporal_unit_consumed);
770         ret = GST_AV1_PARSER_BITSTREAM_ERROR;
771         goto error;
772       }
773
774       if (parser->temporal_unit_consumed == parser->temporal_unit_size ||
775           parser->frame_unit_consumed == parser->frame_unit_size) {
776         /* Some extreme case like a temporal unit just hold a frame_unit_size,
777            or a frame unit just hold frame_unit_size = 0 */
778         goto annex_b_again;
779       }
780     }
781
782     obu_length = av1_bitstreamfn_leb128 (&br, &ret);
783     if (ret != GST_AV1_PARSER_OK)
784       goto error;
785
786     if (obu_length > parser->frame_unit_size - parser->frame_unit_consumed) {
787       GST_INFO ("Error stream, obu_length is %d, bigger than the left"
788           "frame unit size %d", obu_length,
789           parser->frame_unit_size - parser->frame_unit_consumed);
790       ret = GST_AV1_PARSER_BITSTREAM_ERROR;
791       goto error;
792     }
793     /* update the consumed */
794     used = gst_bit_reader_get_pos (&br) / 8 - last_pos;
795     last_pos = gst_bit_reader_get_pos (&br) / 8;
796     *consumed += used;
797     parser->temporal_unit_consumed += used;
798     parser->frame_unit_consumed += used;
799
800     if (obu_length == 0) {
801       /* An empty obu? let continue to the next */
802       return GST_AV1_PARSER_DROP;
803     }
804   }
805
806   if (*consumed > size)
807     goto error;
808   if (*consumed == size) {
809     ret = GST_AV1_PARSER_NO_MORE_DATA;
810     goto error;
811   }
812   gst_bit_reader_init (&br, data + *consumed, size - *consumed);
813
814   ret = gst_av1_parse_obu_header (parser, &br, &obu->header);
815   if (ret != GST_AV1_PARSER_OK)
816     goto error;
817
818   obu->obu_type = obu->header.obu_type;
819   GST_LOG ("identify obu type is %d", obu->obu_type);
820
821   if (obu->header.obu_has_size_field) {
822     guint size_sz = gst_bit_reader_get_pos (&br) / 8;
823
824     obu->obu_size = av1_bitstreamfn_leb128 (&br, &ret);
825     if (ret != GST_AV1_PARSER_OK)
826       goto error;
827
828     size_sz = gst_bit_reader_get_pos (&br) / 8 - size_sz;
829     if (obu_length
830         && obu_length - 1 - obu->header.obu_extention_flag - size_sz !=
831         obu->obu_size) {
832       /* If obu_size and obu_length are both present, but inconsistent,
833          then the packed bitstream is deemed invalid. */
834       ret = GST_AV1_PARSER_BITSTREAM_ERROR;
835       goto error;
836     }
837
838     if (AV1_REMAINING_BYTES (&br) < obu->obu_size) {
839       ret = GST_AV1_PARSER_NO_MORE_DATA;
840       goto error;
841     }
842   } else {
843     if (obu_length == 0) {
844       ret = GST_AV1_PARSER_BITSTREAM_ERROR;
845       goto error;
846     }
847
848     obu->obu_size = obu_length - 1 - obu->header.obu_extention_flag;
849   }
850
851   g_assert (gst_bit_reader_get_pos (&br) % 8 == 0);
852   used = gst_bit_reader_get_pos (&br) / 8;
853   /* fail if not a complete obu */
854   if (size - *consumed - used < obu->obu_size) {
855     ret = GST_AV1_PARSER_NO_MORE_DATA;
856     goto error;
857   }
858
859   /* update the consumed */
860   *consumed += used;
861   if (parser->annex_b) {
862     parser->temporal_unit_consumed += used;
863     parser->frame_unit_consumed += used;
864   }
865
866   obu->data = (guint8 *) (data + *consumed);
867
868   *consumed += obu->obu_size;
869   if (parser->annex_b) {
870     parser->temporal_unit_consumed += obu->obu_size;
871     parser->frame_unit_consumed += obu->obu_size;
872   }
873
874   if (obu->obu_type != GST_AV1_OBU_SEQUENCE_HEADER
875       && obu->obu_type != GST_AV1_OBU_TEMPORAL_DELIMITER
876       && parser->state.operating_point_idc && obu->header.obu_extention_flag) {
877     guint32 inTemporalLayer =
878         (parser->state.operating_point_idc >> obu->header.obu_temporal_id) & 1;
879     guint32 inSpatialLayer =
880         (parser->state.operating_point_idc >> (obu->header.obu_spatial_id +
881             8)) & 1;
882     if (!inTemporalLayer || !inSpatialLayer) {
883       return GST_AV1_PARSER_DROP;
884     }
885   }
886
887   return GST_AV1_PARSER_OK;
888
889 error:
890   GST_WARNING ("can not identify obu, error %d", ret);
891   return ret;
892 }
893
894 /* 5.5.2 */
895 static GstAV1ParserResult
896 gst_av1_parse_color_config (GstAV1Parser * parser, GstBitReader * br,
897     GstAV1SequenceHeaderOBU * seq_header, GstAV1ColorConfig * color_config)
898 {
899   GstAV1ParserResult ret = GST_AV1_PARSER_OK;
900
901   color_config->high_bitdepth = AV1_READ_BIT_CHECKED (br, &ret);
902   if (ret != GST_AV1_PARSER_OK)
903     goto error;
904
905   if (seq_header->seq_profile == GST_AV1_PROFILE_2
906       && color_config->high_bitdepth) {
907     color_config->twelve_bit = AV1_READ_BIT_CHECKED (br, &ret);
908     if (ret != GST_AV1_PARSER_OK)
909       goto error;
910
911     seq_header->bit_depth = color_config->twelve_bit ? 12 : 10;
912   } else if (seq_header->seq_profile <= GST_AV1_PROFILE_2) {
913     seq_header->bit_depth = color_config->high_bitdepth ? 10 : 8;
914   } else {
915     GST_INFO ("Unsupported profile/bit-depth combination");
916     ret = GST_AV1_PARSER_BITSTREAM_ERROR;
917     goto error;
918   }
919
920   if (seq_header->seq_profile == GST_AV1_PROFILE_1)
921     color_config->mono_chrome = 0;
922   else {
923     color_config->mono_chrome = AV1_READ_BIT_CHECKED (br, &ret);
924     if (ret != GST_AV1_PARSER_OK)
925       goto error;
926   }
927   seq_header->num_planes = color_config->mono_chrome ? 1 : 3;
928
929   color_config->color_description_present_flag =
930       AV1_READ_BIT_CHECKED (br, &ret);
931   if (ret != GST_AV1_PARSER_OK)
932     goto error;
933
934   if (color_config->color_description_present_flag) {
935     if (AV1_REMAINING_BITS (br) < 8 + 8 + 8) {
936       ret = GST_AV1_PARSER_NO_MORE_DATA;
937       goto error;
938     }
939     color_config->color_primaries = AV1_READ_BITS (br, 8);
940     color_config->transfer_characteristics = AV1_READ_BITS (br, 8);
941     color_config->matrix_coefficients = AV1_READ_BITS (br, 8);
942   } else {
943     color_config->color_primaries = GST_AV1_CP_UNSPECIFIED;
944     color_config->transfer_characteristics = GST_AV1_TC_UNSPECIFIED;
945     color_config->matrix_coefficients = GST_AV1_MC_UNSPECIFIED;
946   }
947
948   if (color_config->mono_chrome) {
949     color_config->color_range = AV1_READ_BIT_CHECKED (br, &ret);
950     if (ret != GST_AV1_PARSER_OK)
951       goto error;
952
953     color_config->subsampling_x = 1;
954     color_config->subsampling_y = 1;
955     color_config->chroma_sample_position = GST_AV1_CSP_UNKNOWN;
956     color_config->separate_uv_delta_q = 0;
957     goto success;
958   } else if (color_config->color_primaries == GST_AV1_CP_BT_709 &&
959       color_config->transfer_characteristics == GST_AV1_TC_SRGB &&
960       color_config->matrix_coefficients == GST_AV1_MC_IDENTITY) {
961     color_config->color_range = 1;
962     color_config->subsampling_x = 0;
963     color_config->subsampling_y = 0;
964     if (!(seq_header->seq_profile == GST_AV1_PROFILE_1 ||
965             (seq_header->seq_profile == GST_AV1_PROFILE_2
966                 && seq_header->bit_depth == 12))) {
967       GST_INFO ("sRGB colorspace not compatible with specified profile");
968       ret = GST_AV1_PARSER_BITSTREAM_ERROR;
969       goto error;
970     }
971   } else {
972     color_config->color_range = AV1_READ_BIT_CHECKED (br, &ret);
973     if (ret != GST_AV1_PARSER_OK)
974       goto error;
975
976     if (seq_header->seq_profile == GST_AV1_PROFILE_0) {
977       /* 420 only */
978       color_config->subsampling_x = 1;
979       color_config->subsampling_y = 1;
980     } else if (seq_header->seq_profile == GST_AV1_PROFILE_1) {
981       /* 444 only */
982       color_config->subsampling_x = 0;
983       color_config->subsampling_y = 0;
984     } else {
985       g_assert (seq_header->seq_profile == GST_AV1_PROFILE_2);
986       if (seq_header->bit_depth == 12) {
987         color_config->subsampling_x = AV1_READ_BIT_CHECKED (br, &ret);
988         if (ret != GST_AV1_PARSER_OK)
989           goto error;
990
991         if (color_config->subsampling_x) {
992           /* 422 or 420 */
993           color_config->subsampling_y = AV1_READ_BIT_CHECKED (br, &ret);
994           if (ret != GST_AV1_PARSER_OK)
995             goto error;
996         } else
997           /* 444 */
998           color_config->subsampling_y = 0;
999       } else {
1000         /* 422 */
1001         color_config->subsampling_x = 1;
1002         color_config->subsampling_y = 0;
1003       }
1004     }
1005
1006     if (color_config->matrix_coefficients == GST_AV1_MC_IDENTITY &&
1007         (color_config->subsampling_x || color_config->subsampling_y)) {
1008       GST_INFO ("Identity CICP Matrix incompatible with"
1009           " non 4:4:4 color sampling");
1010       ret = GST_AV1_PARSER_BITSTREAM_ERROR;
1011       goto error;
1012     }
1013
1014     if (color_config->subsampling_x && color_config->subsampling_y) {
1015       color_config->chroma_sample_position =
1016           AV1_READ_BITS_CHECKED (br, 2, &ret);
1017       if (ret != GST_AV1_PARSER_OK)
1018         goto error;
1019     }
1020   }
1021
1022   color_config->separate_uv_delta_q = AV1_READ_BIT_CHECKED (br, &ret);
1023   if (ret != GST_AV1_PARSER_OK)
1024     goto error;
1025
1026   if (!(color_config->subsampling_x == 0 && color_config->subsampling_y == 0) &&
1027       !(color_config->subsampling_x == 1 && color_config->subsampling_y == 1) &&
1028       !(color_config->subsampling_x == 1 && color_config->subsampling_y == 0)) {
1029     GST_INFO ("Only 4:4:4, 4:2:2 and 4:2:0 are currently supported, "
1030         "%d %d subsampling is not supported.\n",
1031         color_config->subsampling_x, color_config->subsampling_y);
1032     ret = GST_AV1_PARSER_BITSTREAM_ERROR;
1033     goto error;
1034   }
1035
1036 success:
1037   return GST_AV1_PARSER_OK;
1038
1039 error:
1040   GST_WARNING ("parse color config error %d", ret);
1041   return ret;
1042 }
1043
1044 /* 5.5.3 */
1045 static GstAV1ParserResult
1046 gst_av1_parse_timing_info (GstAV1Parser * parser, GstBitReader * br,
1047     GstAV1TimingInfo * timing_info)
1048 {
1049   GstAV1ParserResult ret = GST_AV1_PARSER_OK;
1050
1051   if (AV1_REMAINING_BITS (br) < 32 + 32 + 1) {
1052     ret = GST_AV1_PARSER_NO_MORE_DATA;
1053     goto error;
1054   }
1055
1056   timing_info->num_units_in_display_tick = AV1_READ_UINT32 (br);
1057   timing_info->time_scale = AV1_READ_UINT32 (br);
1058   if (timing_info->num_units_in_display_tick == 0 ||
1059       timing_info->time_scale == 0) {
1060     ret = GST_AV1_PARSER_BITSTREAM_ERROR;
1061     goto error;
1062   }
1063
1064   timing_info->equal_picture_interval = AV1_READ_BIT (br);
1065   if (timing_info->equal_picture_interval) {
1066     timing_info->num_ticks_per_picture_minus_1 =
1067         av1_bitstreamfn_uvlc (br, &ret);
1068     if (ret != GST_AV1_PARSER_OK)
1069       goto error;
1070
1071     if (timing_info->num_ticks_per_picture_minus_1 == G_MAXUINT) {
1072       ret = GST_AV1_PARSER_BITSTREAM_ERROR;
1073       goto error;
1074     }
1075   }
1076
1077   return GST_AV1_PARSER_OK;
1078
1079 error:
1080   GST_WARNING ("parse timing info error %d", ret);
1081   return ret;
1082 }
1083
1084 /* 5.5.4 */
1085 static GstAV1ParserResult
1086 gst_av1_parse_decoder_model_info (GstAV1Parser * parser, GstBitReader * br,
1087     GstAV1DecoderModelInfo * decoder_model_info)
1088 {
1089   if (AV1_REMAINING_BITS (br) < 5 + 32 + 5 + 5)
1090     return GST_AV1_PARSER_NO_MORE_DATA;
1091
1092   decoder_model_info->buffer_delay_length_minus_1 = AV1_READ_BITS (br, 5);
1093   decoder_model_info->num_units_in_decoding_tick = AV1_READ_BITS (br, 32);
1094   decoder_model_info->buffer_removal_time_length_minus_1 =
1095       AV1_READ_BITS (br, 5);
1096   decoder_model_info->frame_presentation_time_length_minus_1 =
1097       AV1_READ_BITS (br, 5);
1098
1099   return GST_AV1_PARSER_OK;
1100 }
1101
1102 /* 5.5.5 */
1103 static GstAV1ParserResult
1104 gst_av1_parse_operating_parameters_info (GstAV1Parser * parser,
1105     GstBitReader * br, GstAV1SequenceHeaderOBU * seq_header,
1106     GstAV1OperatingPoint * op_point)
1107 {
1108   guint32 n = seq_header->decoder_model_info.buffer_delay_length_minus_1 + 1;
1109
1110   if (AV1_REMAINING_BITS (br) < n + n + 1)
1111     return GST_AV1_PARSER_NO_MORE_DATA;
1112
1113   op_point->decoder_buffer_delay = AV1_READ_BITS (br, n);
1114   op_point->encoder_buffer_delay = AV1_READ_BITS (br, n);
1115   op_point->low_delay_mode_flag = AV1_READ_BIT (br);
1116   return GST_AV1_PARSER_OK;
1117 }
1118
1119 /* 5.5.1 General sequence header OBU */
1120 /**
1121  * gst_av1_parser_parse_sequence_header_obu:
1122  * @parser: the #GstAV1Parser
1123  * @obu: a #GstAV1OBU to be parsed
1124  * @seq_header: a #GstAV1SequenceHeaderOBU to store the parsed result.
1125  *
1126  * Parse one sequence header @obu based on the @parser context, store the
1127  * result in the @seq_header.
1128  *
1129  * Returns: The #GstAV1ParserResult.
1130  *
1131  * Since: 1.18
1132  */
1133 GstAV1ParserResult
1134 gst_av1_parser_parse_sequence_header_obu (GstAV1Parser * parser,
1135     GstAV1OBU * obu, GstAV1SequenceHeaderOBU * seq_header)
1136 {
1137   GstAV1ParserResult retval = GST_AV1_PARSER_OK;
1138   gint i;
1139   GstBitReader bit_reader;
1140   GstBitReader *br = &bit_reader;
1141
1142   g_return_val_if_fail (parser != NULL, GST_AV1_PARSER_INVALID_OPERATION);
1143   g_return_val_if_fail (obu != NULL, GST_AV1_PARSER_INVALID_OPERATION);
1144   g_return_val_if_fail (obu->obu_type == GST_AV1_OBU_SEQUENCE_HEADER,
1145       GST_AV1_PARSER_INVALID_OPERATION);
1146   g_return_val_if_fail (seq_header != NULL, GST_AV1_PARSER_INVALID_OPERATION);
1147
1148   av1_parser_init_sequence_header (seq_header);
1149   gst_bit_reader_init (br, obu->data, obu->obu_size);
1150
1151   if (AV1_REMAINING_BITS (br) < 8) {
1152     retval = GST_AV1_PARSER_NO_MORE_DATA;
1153     goto error;
1154   }
1155
1156   seq_header->seq_profile = AV1_READ_BITS (br, 3);
1157   if (seq_header->seq_profile > GST_AV1_PROFILE_2) {
1158     GST_INFO ("Unsupported profile %d", seq_header->seq_profile);
1159     retval = GST_AV1_PARSER_BITSTREAM_ERROR;
1160     goto error;
1161   }
1162
1163   seq_header->still_picture = AV1_READ_BIT (br);
1164   seq_header->reduced_still_picture_header = AV1_READ_BIT (br);
1165   if (!seq_header->still_picture && seq_header->reduced_still_picture_header) {
1166     GST_INFO (" If reduced_still_picture_header is equal to 1, it is a"
1167         " requirement of bitstream conformance that still_picture is equal"
1168         " to 1. ");
1169     retval = GST_AV1_PARSER_BITSTREAM_ERROR;
1170     goto error;
1171   }
1172
1173   if (seq_header->reduced_still_picture_header) {
1174     seq_header->timing_info_present_flag = 0;
1175     seq_header->decoder_model_info_present_flag = 0;
1176     seq_header->initial_display_delay_present_flag = 0;
1177     seq_header->operating_points_cnt_minus_1 = 0;
1178     seq_header->operating_points[0].idc = 0;
1179     seq_header->operating_points[0].seq_level_idx = AV1_READ_BITS (br, 5);
1180     if (!av1_seq_level_idx_is_valid
1181         (seq_header->operating_points[0].seq_level_idx)) {
1182       GST_INFO ("The seq_level_idx is unsupported");
1183       retval = GST_AV1_PARSER_BITSTREAM_ERROR;
1184       goto error;
1185     }
1186     seq_header->operating_points[0].seq_tier = 0;
1187     seq_header->operating_points[0].decoder_model_present_for_this_op = 0;
1188     seq_header->operating_points[0].initial_display_delay_present_for_this_op =
1189         0;
1190   } else {
1191     seq_header->timing_info_present_flag = AV1_READ_BIT (br);
1192
1193     if (seq_header->timing_info_present_flag) {
1194       retval =
1195           gst_av1_parse_timing_info (parser, br, &(seq_header->timing_info));
1196       if (retval != GST_AV1_PARSER_OK)
1197         goto error;
1198
1199       seq_header->decoder_model_info_present_flag =
1200           AV1_READ_BIT_CHECKED (br, &retval);
1201       if (retval != GST_AV1_PARSER_OK)
1202         goto error;
1203
1204       if (seq_header->decoder_model_info_present_flag) {
1205         retval = gst_av1_parse_decoder_model_info (parser, br,
1206             &(seq_header->decoder_model_info));
1207         if (retval != GST_AV1_PARSER_OK)
1208           goto error;
1209       }
1210     } else {
1211       seq_header->decoder_model_info_present_flag = 0;
1212     }
1213
1214     if (AV1_REMAINING_BITS (br) < 6) {
1215       retval = GST_AV1_PARSER_NO_MORE_DATA;
1216       goto error;
1217     }
1218     seq_header->initial_display_delay_present_flag = AV1_READ_BIT (br);
1219     seq_header->operating_points_cnt_minus_1 = AV1_READ_BITS (br, 5);
1220     if (seq_header->operating_points_cnt_minus_1 + 1 >
1221         GST_AV1_MAX_OPERATING_POINTS) {
1222       GST_INFO ("The operating points number %d is too big",
1223           seq_header->operating_points_cnt_minus_1 + 1);
1224       retval = GST_AV1_PARSER_BITSTREAM_ERROR;
1225       goto error;
1226     }
1227
1228     for (i = 0; i < seq_header->operating_points_cnt_minus_1 + 1; i++) {
1229       if (AV1_REMAINING_BITS (br) < 17) {
1230         retval = GST_AV1_PARSER_NO_MORE_DATA;
1231         goto error;
1232       }
1233       seq_header->operating_points[i].idc = AV1_READ_BITS (br, 12);
1234       seq_header->operating_points[i].seq_level_idx = AV1_READ_BITS (br, 5);
1235       if (!av1_seq_level_idx_is_valid
1236           (seq_header->operating_points[i].seq_level_idx)) {
1237         GST_INFO ("The seq_level_idx is unsupported");
1238         retval = GST_AV1_PARSER_BITSTREAM_ERROR;
1239         goto error;
1240       }
1241       if (seq_header->operating_points[i].seq_level_idx > GST_AV1_SEQ_LEVEL_3_3) {
1242         seq_header->operating_points[i].seq_tier = AV1_READ_BIT (br);
1243       } else {
1244         seq_header->operating_points[i].seq_tier = 0;
1245       }
1246       if (seq_header->decoder_model_info_present_flag) {
1247         seq_header->operating_points[i].decoder_model_present_for_this_op =
1248             AV1_READ_BIT (br);
1249         if (seq_header->operating_points[i].decoder_model_present_for_this_op)
1250           retval =
1251               gst_av1_parse_operating_parameters_info (parser, br, seq_header,
1252               &(seq_header->operating_points[i]));
1253         if (retval != GST_AV1_PARSER_OK)
1254           goto error;
1255       } else {
1256         seq_header->operating_points[i].decoder_model_present_for_this_op = 0;
1257       }
1258
1259       if (seq_header->initial_display_delay_present_flag) {
1260         seq_header->
1261             operating_points[i].initial_display_delay_present_for_this_op =
1262             AV1_READ_BIT_CHECKED (br, &retval);
1263         if (retval != GST_AV1_PARSER_OK)
1264           goto error;
1265
1266         if (seq_header->
1267             operating_points[i].initial_display_delay_present_for_this_op) {
1268           seq_header->operating_points[i].initial_display_delay_minus_1 =
1269               AV1_READ_BITS_CHECKED (br, 4, &retval);
1270           if (retval != GST_AV1_PARSER_OK)
1271             goto error;
1272
1273           if (seq_header->operating_points[i].initial_display_delay_minus_1 +
1274               1 > 10) {
1275             GST_INFO ("AV1 does not support more than 10 decoded frames delay");
1276             retval = GST_AV1_PARSER_BITSTREAM_ERROR;
1277             goto error;
1278           }
1279         } else {
1280           seq_header->operating_points[i].initial_display_delay_minus_1 = 9;
1281         }
1282       } else {
1283         seq_header->
1284             operating_points[i].initial_display_delay_present_for_this_op = 0;
1285         seq_header->operating_points[i].initial_display_delay_minus_1 = 9;
1286       }
1287     }
1288   }
1289
1290   /* Let user decide the operatingPoint,
1291      implemented by calling gst_av1_parser_set_operating_point()
1292      operatingPoint = choose_operating_point( )
1293      operating_point_idc = operating_point_idc[ operatingPoint ] */
1294
1295   if (AV1_REMAINING_BITS (br) < 4 + 4 +
1296       (seq_header->frame_width_bits_minus_1 + 1) +
1297       (seq_header->frame_height_bits_minus_1 + 1)) {
1298     retval = GST_AV1_PARSER_NO_MORE_DATA;
1299     goto error;
1300   }
1301
1302   seq_header->frame_width_bits_minus_1 = AV1_READ_BITS (br, 4);
1303   seq_header->frame_height_bits_minus_1 = AV1_READ_BITS (br, 4);
1304   seq_header->max_frame_width_minus_1 =
1305       AV1_READ_BITS (br, seq_header->frame_width_bits_minus_1 + 1);
1306   seq_header->max_frame_height_minus_1 =
1307       AV1_READ_BITS (br, seq_header->frame_height_bits_minus_1 + 1);
1308
1309   if (seq_header->reduced_still_picture_header)
1310     seq_header->frame_id_numbers_present_flag = 0;
1311   else {
1312     seq_header->frame_id_numbers_present_flag =
1313         AV1_READ_BIT_CHECKED (br, &retval);
1314     if (retval != GST_AV1_PARSER_OK)
1315       goto error;
1316   }
1317
1318   if (seq_header->frame_id_numbers_present_flag) {
1319     if (AV1_REMAINING_BITS (br) < 4 + 3) {
1320       retval = GST_AV1_PARSER_NO_MORE_DATA;
1321       goto error;
1322     }
1323     seq_header->delta_frame_id_length_minus_2 = AV1_READ_BITS (br, 4);
1324     seq_header->additional_frame_id_length_minus_1 = AV1_READ_BITS (br, 3);
1325
1326     if (seq_header->additional_frame_id_length_minus_1 + 1 +
1327         seq_header->delta_frame_id_length_minus_2 + 2 > 16) {
1328       GST_INFO ("Invalid frame_id_length");
1329       retval = GST_AV1_PARSER_BITSTREAM_ERROR;
1330       goto error;
1331     }
1332   }
1333
1334   if (AV1_REMAINING_BITS (br) < 3) {
1335     retval = GST_AV1_PARSER_NO_MORE_DATA;
1336     goto error;
1337   }
1338   seq_header->use_128x128_superblock = AV1_READ_BIT (br);
1339   seq_header->enable_filter_intra = AV1_READ_BIT (br);
1340   seq_header->enable_intra_edge_filter = AV1_READ_BIT (br);
1341
1342   if (seq_header->reduced_still_picture_header) {
1343     seq_header->enable_interintra_compound = 0;
1344     seq_header->enable_masked_compound = 0;
1345     seq_header->enable_warped_motion = 0;
1346     seq_header->enable_dual_filter = 0;
1347     seq_header->enable_order_hint = 0;
1348     seq_header->enable_jnt_comp = 0;
1349     seq_header->enable_ref_frame_mvs = 0;
1350     seq_header->seq_force_screen_content_tools =
1351         GST_AV1_SELECT_SCREEN_CONTENT_TOOLS;
1352     seq_header->seq_force_integer_mv = GST_AV1_SELECT_INTEGER_MV;
1353     seq_header->order_hint_bits_minus_1 = -1;
1354     seq_header->order_hint_bits = 0;
1355   } else {
1356     if (AV1_REMAINING_BITS (br) < 5) {
1357       retval = GST_AV1_PARSER_NO_MORE_DATA;
1358       goto error;
1359     }
1360     seq_header->enable_interintra_compound = AV1_READ_BIT (br);
1361     seq_header->enable_masked_compound = AV1_READ_BIT (br);
1362     seq_header->enable_warped_motion = AV1_READ_BIT (br);
1363     seq_header->enable_dual_filter = AV1_READ_BIT (br);
1364     seq_header->enable_order_hint = AV1_READ_BIT (br);
1365     if (seq_header->enable_order_hint) {
1366       if (AV1_REMAINING_BITS (br) < 2) {
1367         retval = GST_AV1_PARSER_NO_MORE_DATA;
1368         goto error;
1369       }
1370       seq_header->enable_jnt_comp = AV1_READ_BIT (br);
1371       seq_header->enable_ref_frame_mvs = AV1_READ_BIT (br);
1372     } else {
1373       seq_header->enable_jnt_comp = 0;
1374       seq_header->enable_ref_frame_mvs = 0;
1375     }
1376
1377     seq_header->seq_choose_screen_content_tools =
1378         AV1_READ_BIT_CHECKED (br, &retval);
1379     if (retval != GST_AV1_PARSER_OK)
1380       goto error;
1381     if (seq_header->seq_choose_screen_content_tools)
1382       seq_header->seq_force_screen_content_tools =
1383           GST_AV1_SELECT_SCREEN_CONTENT_TOOLS;
1384     else {
1385       seq_header->seq_force_screen_content_tools =
1386           AV1_READ_BIT_CHECKED (br, &retval);
1387       if (retval != GST_AV1_PARSER_OK)
1388         goto error;
1389     }
1390
1391     if (seq_header->seq_force_screen_content_tools > 0) {
1392       seq_header->seq_choose_integer_mv = AV1_READ_BIT_CHECKED (br, &retval);
1393       if (retval != GST_AV1_PARSER_OK)
1394         goto error;
1395       if (seq_header->seq_choose_integer_mv)
1396         seq_header->seq_force_integer_mv = GST_AV1_SELECT_INTEGER_MV;
1397       else {
1398         seq_header->seq_force_integer_mv = AV1_READ_BIT_CHECKED (br, &retval);
1399         if (retval != GST_AV1_PARSER_OK)
1400           goto error;
1401       }
1402     } else {
1403       seq_header->seq_force_integer_mv = GST_AV1_SELECT_INTEGER_MV;
1404     }
1405     if (seq_header->enable_order_hint) {
1406       seq_header->order_hint_bits_minus_1 =
1407           AV1_READ_BITS_CHECKED (br, 3, &retval);
1408       if (retval != GST_AV1_PARSER_OK)
1409         goto error;
1410       seq_header->order_hint_bits = seq_header->order_hint_bits_minus_1 + 1;
1411     } else {
1412       seq_header->order_hint_bits_minus_1 = -1;
1413       seq_header->order_hint_bits = 0;
1414     }
1415   }
1416
1417   if (AV1_REMAINING_BITS (br) < 3) {
1418     retval = GST_AV1_PARSER_NO_MORE_DATA;
1419     goto error;
1420   }
1421   seq_header->enable_superres = AV1_READ_BIT (br);
1422   seq_header->enable_cdef = AV1_READ_BIT (br);
1423   seq_header->enable_restoration = AV1_READ_BIT (br);
1424
1425   retval = gst_av1_parse_color_config (parser, br, seq_header,
1426       &seq_header->color_config);
1427   if (retval != GST_AV1_PARSER_OK)
1428     goto error;
1429
1430   seq_header->film_grain_params_present = AV1_READ_BIT_CHECKED (br, &retval);
1431   if (retval != GST_AV1_PARSER_OK)
1432     goto error;
1433
1434   retval = av1_skip_trailing_bits (parser, br, obu);
1435   if (retval != GST_AV1_PARSER_OK)
1436     goto error;
1437
1438   if (parser->seq_header) {
1439     if (!memcmp (parser->seq_header, seq_header,
1440             sizeof (GstAV1SequenceHeaderOBU)))
1441       goto success;
1442
1443     g_slice_free (GstAV1SequenceHeaderOBU, parser->seq_header);
1444   }
1445
1446   parser->seq_header = g_slice_dup (GstAV1SequenceHeaderOBU, seq_header);
1447   gst_av1_parse_reset_state (parser, FALSE);
1448
1449   /* choose_operating_point() set the operating_point */
1450   if (parser->state.operating_point > seq_header->operating_points_cnt_minus_1) {
1451     GST_WARNING ("Invalid operating_point %d set by user, just use 0",
1452         parser->state.operating_point);
1453     parser->state.operating_point_idc = seq_header->operating_points[0].idc;
1454   } else {
1455     parser->state.operating_point_idc =
1456         seq_header->operating_points[parser->state.operating_point].idc;
1457   }
1458
1459   parser->state.sequence_changed = TRUE;
1460
1461 success:
1462   return GST_AV1_PARSER_OK;
1463
1464 error:
1465   GST_WARNING ("parse sequence header error %d", retval);
1466   return retval;
1467 }
1468
1469 /* 5.6 */
1470 /**
1471  * gst_av1_parser_parse_temporal_delimiter_obu:
1472  * @parser: the #GstAV1Parser
1473  * @obu: a #GstAV1OBU to be parsed
1474  *
1475  * Parse one temporal delimiter @obu based on the @parser context.
1476  * The temporal delimiter is just delimiter and contains no content.
1477  *
1478  * Returns: The #GstAV1ParserResult.
1479  *
1480  * Since: 1.18
1481  */
1482 GstAV1ParserResult
1483 gst_av1_parser_parse_temporal_delimiter_obu (GstAV1Parser * parser,
1484     GstAV1OBU * obu)
1485 {
1486   GstBitReader bit_reader;
1487   GstAV1ParserResult ret;
1488
1489   g_return_val_if_fail (parser != NULL, GST_AV1_PARSER_INVALID_OPERATION);
1490   g_return_val_if_fail (obu != NULL, GST_AV1_PARSER_INVALID_OPERATION);
1491   g_return_val_if_fail (obu->obu_type == GST_AV1_OBU_TEMPORAL_DELIMITER,
1492       GST_AV1_PARSER_INVALID_OPERATION);
1493
1494   gst_bit_reader_init (&bit_reader, obu->data, obu->obu_size);
1495
1496   parser->state.seen_frame_header = 0;
1497
1498   ret = av1_skip_trailing_bits (parser, &bit_reader, obu);
1499   if (ret != GST_AV1_PARSER_OK)
1500     GST_WARNING ("parse temporal delimiter error %d", ret);
1501
1502   return ret;
1503 }
1504
1505 /* 5.8.2 */
1506 static GstAV1ParserResult
1507 gst_av1_parse_metadata_itut_t35 (GstAV1Parser * parser, GstBitReader * br,
1508     GstAV1MetadataITUT_T35 * itut_t35)
1509 {
1510   GstAV1ParserResult ret;
1511
1512   itut_t35->itu_t_t35_country_code = AV1_READ_BITS_CHECKED (br, 8, &ret);
1513   if (ret != GST_AV1_PARSER_OK)
1514     return ret;
1515
1516   if (itut_t35->itu_t_t35_country_code == 0xFF) {
1517     itut_t35->itu_t_t35_country_code_extention_byte =
1518         AV1_READ_BITS_CHECKED (br, 8, &ret);
1519     if (ret != GST_AV1_PARSER_OK)
1520       return ret;
1521   }
1522   /* itu_t_t35_payload_bytes is not defined in specification.
1523      Just skip this part. */
1524
1525   return GST_AV1_PARSER_OK;
1526 }
1527
1528 /* 5.8.3 */
1529 static GstAV1ParserResult
1530 gst_av1_parse_metadata_hdr_cll (GstAV1Parser * parser, GstBitReader * br,
1531     GstAV1MetadataHdrCll * hdr_cll)
1532 {
1533   if (AV1_REMAINING_BITS (br) < 32)
1534     return GST_AV1_PARSER_NO_MORE_DATA;
1535
1536   hdr_cll->max_cll = AV1_READ_UINT16 (br);
1537   hdr_cll->max_fall = AV1_READ_UINT16 (br);
1538
1539   return GST_AV1_PARSER_OK;
1540 }
1541
1542 /* 5.8.4 */
1543 static GstAV1ParserResult
1544 gst_av1_parse_metadata_hdr_mdcv (GstAV1Parser * parser, GstBitReader * br,
1545     GstAV1MetadataHdrMdcv * hdr_mdcv)
1546 {
1547   gint i;
1548
1549   if (AV1_REMAINING_BITS (br) < 3 * (16 + 16) + 16 + 16 + 32 + 32)
1550     return GST_AV1_PARSER_NO_MORE_DATA;
1551
1552   for (i = 0; i < 3; i++) {
1553     hdr_mdcv->primary_chromaticity_x[i] = AV1_READ_UINT16 (br);
1554     hdr_mdcv->primary_chromaticity_y[i] = AV1_READ_UINT16 (br);
1555   }
1556
1557   hdr_mdcv->white_point_chromaticity_x = AV1_READ_UINT16 (br);
1558   hdr_mdcv->white_point_chromaticity_y = AV1_READ_UINT16 (br);
1559
1560   hdr_mdcv->luminance_max = AV1_READ_UINT32 (br);
1561   hdr_mdcv->luminance_min = AV1_READ_UINT32 (br);
1562
1563   return GST_AV1_PARSER_OK;
1564 }
1565
1566 /* 5.8.5 */
1567 static GstAV1ParserResult
1568 gst_av1_parse_metadata_scalability (GstAV1Parser * parser,
1569     GstBitReader * br, GstAV1MetadataScalability * scalability)
1570 {
1571   gint i, j;
1572   GstAV1ParserResult ret = GST_AV1_PARSER_OK;
1573   guint8 scalability_structure_reserved_3bits;
1574
1575   scalability->scalability_mode_idc = AV1_READ_UINT8_CHECKED (br, &ret);
1576   if (ret != GST_AV1_PARSER_OK)
1577     goto error;
1578
1579   if (scalability->scalability_mode_idc != GST_AV1_SCALABILITY_SS)
1580     goto success;
1581
1582   if (AV1_REMAINING_BITS (br) < 8) {
1583     ret = GST_AV1_PARSER_NO_MORE_DATA;
1584     goto error;
1585   }
1586
1587   /* 5.8.6 */
1588   scalability->spatial_layers_cnt_minus_1 = AV1_READ_BITS (br, 2);
1589   scalability->spatial_layer_dimensions_present_flag = AV1_READ_BIT (br);
1590   scalability->spatial_layer_description_present_flag = AV1_READ_BIT (br);
1591   scalability->temporal_group_description_present_flag = AV1_READ_BIT (br);
1592   scalability_structure_reserved_3bits = AV1_READ_BITS (br, 3);
1593   /* scalability_structure_reserved_3bits: must be set to zero and
1594      be ignored by decoders. */
1595   if (scalability_structure_reserved_3bits) {
1596     ret = GST_AV1_PARSER_BITSTREAM_ERROR;
1597     goto error;
1598   }
1599
1600   if (scalability->spatial_layer_dimensions_present_flag) {
1601     for (i = 0; i <= scalability->spatial_layers_cnt_minus_1; i++) {
1602       if (AV1_REMAINING_BITS (br) < 16 * 2) {
1603         ret = GST_AV1_PARSER_NO_MORE_DATA;
1604         goto error;
1605       }
1606
1607       scalability->spatial_layer_max_width[i] = AV1_READ_UINT16 (br);
1608       scalability->spatial_layer_max_height[i] = AV1_READ_UINT16 (br);
1609     }
1610   }
1611
1612   if (scalability->spatial_layer_description_present_flag) {
1613     for (i = 0; i <= scalability->spatial_layers_cnt_minus_1; i++) {
1614       scalability->spatial_layer_ref_id[i] = AV1_READ_UINT8_CHECKED (br, &ret);
1615       if (ret != GST_AV1_PARSER_OK)
1616         goto error;
1617     }
1618   }
1619
1620   if (scalability->temporal_group_description_present_flag) {
1621     scalability->temporal_group_size = AV1_READ_UINT8_CHECKED (br, &ret);
1622     if (ret != GST_AV1_PARSER_OK)
1623       goto error;
1624
1625     for (i = 0; i < scalability->temporal_group_size; i++) {
1626       if (AV1_REMAINING_BITS (br) < 8) {
1627         ret = GST_AV1_PARSER_NO_MORE_DATA;
1628         goto error;
1629       }
1630
1631       scalability->temporal_group_temporal_id[i] = AV1_READ_BITS (br, 3);
1632       scalability->temporal_group_temporal_switching_up_point_flag[i] =
1633           AV1_READ_BIT (br);
1634       scalability->temporal_group_spatial_switching_up_point_flag[i] =
1635           AV1_READ_BIT (br);
1636       scalability->temporal_group_ref_cnt[i] = AV1_READ_BITS (br, 3);
1637       for (j = 0; j < scalability->temporal_group_ref_cnt[i]; j++) {
1638         scalability->temporal_group_ref_pic_diff[i][j] =
1639             AV1_READ_UINT8_CHECKED (br, &ret);
1640         if (ret != GST_AV1_PARSER_OK)
1641           goto error;
1642       }
1643     }
1644   }
1645
1646 success:
1647   return GST_AV1_PARSER_OK;
1648
1649 error:
1650   GST_WARNING ("parse metadata scalability error %d", ret);
1651   return ret;
1652 }
1653
1654 /* 5.8.7 */
1655 static GstAV1ParserResult
1656 gst_av1_parse_metadata_timecode (GstAV1Parser * parser, GstBitReader * br,
1657     GstAV1MetadataTimecode * timecode)
1658 {
1659   GstAV1ParserResult ret = GST_AV1_PARSER_OK;
1660
1661   if (AV1_REMAINING_BITS (br) < 17) {
1662     ret = GST_AV1_PARSER_NO_MORE_DATA;
1663     goto error;
1664   }
1665
1666   timecode->counting_type = AV1_READ_BITS (br, 5);
1667   timecode->full_timestamp_flag = AV1_READ_BIT (br);
1668   timecode->discontinuity_flag = AV1_READ_BIT (br);
1669   timecode->cnt_dropped_flag = AV1_READ_BIT (br);
1670   timecode->n_frames = AV1_READ_BITS (br, 9);
1671
1672   if (timecode->full_timestamp_flag) {
1673     if (AV1_REMAINING_BITS (br) < 17) {
1674       ret = GST_AV1_PARSER_NO_MORE_DATA;
1675       goto error;
1676     }
1677     timecode->seconds_value = AV1_READ_BITS (br, 6);
1678     timecode->minutes_value = AV1_READ_BITS (br, 6);
1679     timecode->hours_value = AV1_READ_BITS (br, 5);
1680   } else {
1681     timecode->seconds_flag = AV1_READ_BIT_CHECKED (br, &ret);
1682     if (ret != GST_AV1_PARSER_OK)
1683       goto error;
1684
1685     if (timecode->seconds_flag) {
1686       if (AV1_REMAINING_BITS (br) < 7) {
1687         ret = GST_AV1_PARSER_NO_MORE_DATA;
1688         goto error;
1689       }
1690       timecode->seconds_value = AV1_READ_BITS (br, 6);
1691       timecode->minutes_flag = AV1_READ_BIT (br);
1692
1693       if (timecode->minutes_flag) {
1694         if (AV1_REMAINING_BITS (br) < 7) {
1695           ret = GST_AV1_PARSER_NO_MORE_DATA;
1696           goto error;
1697         }
1698         timecode->minutes_value = AV1_READ_BITS (br, 6);
1699         timecode->hours_flag = AV1_READ_BIT (br);
1700
1701         if (timecode->hours_flag) {
1702           timecode->hours_value = AV1_READ_BITS_CHECKED (br, 6, &ret);
1703           if (ret != GST_AV1_PARSER_OK)
1704             goto error;
1705         }
1706       }
1707     }
1708   }
1709
1710   timecode->time_offset_length = AV1_READ_BITS_CHECKED (br, 5, &ret);
1711   if (ret != GST_AV1_PARSER_OK)
1712     goto error;
1713
1714   if (timecode->time_offset_length > 0) {
1715     timecode->time_offset_value =
1716         AV1_READ_BITS_CHECKED (br, timecode->time_offset_length, &ret);
1717     if (ret != GST_AV1_PARSER_OK)
1718       goto error;
1719   }
1720
1721   return GST_AV1_PARSER_OK;
1722
1723 error:
1724   GST_WARNING ("parse metadata timecode error %d", ret);
1725   return ret;
1726 }
1727
1728 /* 5.8.1 */
1729 /**
1730  * gst_av1_parser_parse_metadata_obu:
1731  * @parser: the #GstAV1Parser
1732  * @obu: a #GstAV1OBU to be parsed
1733  * @metadata: a #GstAV1MetadataOBU to store the parsed result.
1734  *
1735  * Parse one meta data @obu based on the @parser context.
1736  *
1737  * Returns: The #GstAV1ParserResult.
1738  *
1739  * Since: 1.18
1740  */
1741 GstAV1ParserResult
1742 gst_av1_parser_parse_metadata_obu (GstAV1Parser * parser, GstAV1OBU * obu,
1743     GstAV1MetadataOBU * metadata)
1744 {
1745   GstAV1ParserResult retval = GST_AV1_PARSER_OK;
1746   GstBitReader bit_reader;
1747
1748   g_return_val_if_fail (parser != NULL, GST_AV1_PARSER_INVALID_OPERATION);
1749   g_return_val_if_fail (obu != NULL, GST_AV1_PARSER_INVALID_OPERATION);
1750   g_return_val_if_fail (obu->obu_type == GST_AV1_OBU_METADATA,
1751       GST_AV1_PARSER_INVALID_OPERATION);
1752   g_return_val_if_fail (metadata != NULL, GST_AV1_PARSER_INVALID_OPERATION);
1753
1754   gst_bit_reader_init (&bit_reader, obu->data, obu->obu_size);
1755
1756   memset (metadata, 0, sizeof (*metadata));
1757
1758   metadata->metadata_type = av1_bitstreamfn_leb128 (&bit_reader, &retval);
1759   if (retval != GST_AV1_PARSER_OK)
1760     goto error;
1761
1762   switch (metadata->metadata_type) {
1763     case GST_AV1_METADATA_TYPE_ITUT_T35:
1764       retval = gst_av1_parse_metadata_itut_t35 (parser,
1765           &bit_reader, &(metadata->itut_t35));
1766       break;
1767     case GST_AV1_METADATA_TYPE_HDR_CLL:
1768       retval = gst_av1_parse_metadata_hdr_cll (parser,
1769           &bit_reader, &(metadata->hdr_cll));
1770       break;
1771     case GST_AV1_METADATA_TYPE_HDR_MDCV:
1772       retval = gst_av1_parse_metadata_hdr_mdcv (parser,
1773           &bit_reader, &(metadata->hdr_mdcv));
1774       break;
1775     case GST_AV1_METADATA_TYPE_SCALABILITY:
1776       retval = gst_av1_parse_metadata_scalability (parser,
1777           &bit_reader, &(metadata->scalability));
1778       break;
1779     case GST_AV1_METADATA_TYPE_TIMECODE:
1780       retval = gst_av1_parse_metadata_timecode (parser,
1781           &bit_reader, &(metadata->timecode));
1782       break;
1783     default:
1784       GST_WARNING ("Unknown metadata type %u", metadata->metadata_type);
1785       return GST_AV1_PARSER_OK;
1786   }
1787
1788   if (retval != GST_AV1_PARSER_OK)
1789     goto error;
1790
1791   retval = av1_skip_trailing_bits (parser, &bit_reader, obu);
1792   if (retval != GST_AV1_PARSER_OK) {
1793     GST_WARNING ("Metadata type %d may have wrong trailings.",
1794         metadata->metadata_type);
1795     retval = GST_AV1_PARSER_OK;
1796   }
1797
1798   return retval;
1799
1800 error:
1801   GST_WARNING ("parse metadata error %d", retval);
1802   return retval;
1803 }
1804
1805 /* 5.9.8 */
1806 static GstAV1ParserResult
1807 gst_av1_parse_superres_params_compute_image_size (GstAV1Parser * parser,
1808     GstBitReader * br, GstAV1FrameHeaderOBU * frame_header)
1809 {
1810   GstAV1ParserResult ret;
1811   GstAV1SequenceHeaderOBU *seq_header;
1812
1813   g_assert (parser->seq_header);
1814   seq_header = parser->seq_header;
1815
1816   if (seq_header->enable_superres) {
1817     frame_header->use_superres = AV1_READ_BIT_CHECKED (br, &ret);
1818     if (ret != GST_AV1_PARSER_OK)
1819       return ret;
1820   } else {
1821     frame_header->use_superres = 0;
1822   }
1823
1824   if (frame_header->use_superres) {
1825     guint8 coded_denom;
1826     coded_denom = AV1_READ_BITS_CHECKED (br, GST_AV1_SUPERRES_DENOM_BITS, &ret);
1827     if (ret != GST_AV1_PARSER_OK)
1828       return ret;
1829
1830     frame_header->superres_denom = coded_denom + GST_AV1_SUPERRES_DENOM_MIN;
1831   } else {
1832     frame_header->superres_denom = GST_AV1_SUPERRES_NUM;
1833   }
1834   parser->state.upscaled_width = parser->state.frame_width;
1835   parser->state.frame_width =
1836       (parser->state.upscaled_width * GST_AV1_SUPERRES_NUM +
1837       (frame_header->superres_denom / 2)) / frame_header->superres_denom;
1838
1839   /* 5.9.9 compute_image_size */
1840   parser->state.mi_cols = 2 * ((parser->state.frame_width + 7) >> 3);
1841   parser->state.mi_rows = 2 * ((parser->state.frame_height + 7) >> 3);
1842
1843   return GST_AV1_PARSER_OK;
1844 }
1845
1846 /* 5.9.5 */
1847 static GstAV1ParserResult
1848 gst_av1_parse_frame_size (GstAV1Parser * parser, GstBitReader * br,
1849     GstAV1FrameHeaderOBU * frame_header)
1850 {
1851   GstAV1ParserResult retval;
1852   GstAV1SequenceHeaderOBU *seq_header;
1853
1854   g_assert (parser->seq_header);
1855   seq_header = parser->seq_header;
1856
1857   if (frame_header->frame_size_override_flag) {
1858     guint16 frame_width_minus_1;
1859     guint16 frame_height_minus_1;
1860
1861     if (AV1_REMAINING_BITS (br) <
1862         seq_header->frame_width_bits_minus_1 + 1 +
1863         seq_header->frame_height_bits_minus_1 + 1)
1864       return GST_AV1_PARSER_NO_MORE_DATA;
1865
1866     frame_width_minus_1 =
1867         AV1_READ_BITS (br, seq_header->frame_width_bits_minus_1 + 1);
1868     frame_height_minus_1 =
1869         AV1_READ_BITS (br, seq_header->frame_height_bits_minus_1 + 1);
1870     parser->state.frame_width = frame_width_minus_1 + 1;
1871     parser->state.frame_height = frame_height_minus_1 + 1;
1872   } else {
1873     parser->state.frame_width = seq_header->max_frame_width_minus_1 + 1;
1874     parser->state.frame_height = seq_header->max_frame_height_minus_1 + 1;
1875   }
1876
1877   retval = gst_av1_parse_superres_params_compute_image_size (parser, br,
1878       frame_header);
1879   return retval;
1880 }
1881
1882 /* 5.9.6 */
1883 static GstAV1ParserResult
1884 gst_av1_parse_render_size (GstAV1Parser * parser, GstBitReader * br,
1885     GstAV1FrameHeaderOBU * frame_header)
1886 {
1887   GstAV1ParserResult retval;
1888
1889   frame_header->render_and_frame_size_different =
1890       AV1_READ_BIT_CHECKED (br, &retval);
1891   if (retval != GST_AV1_PARSER_OK)
1892     return retval;
1893
1894   if (frame_header->render_and_frame_size_different) {
1895     guint16 render_width_minus_1;
1896     guint16 render_height_minus_1;
1897
1898     if (AV1_REMAINING_BITS (br) < 16 + 16)
1899       return GST_AV1_PARSER_NO_MORE_DATA;
1900
1901     render_width_minus_1 = AV1_READ_UINT16 (br);
1902     render_height_minus_1 = AV1_READ_UINT16 (br);
1903     parser->state.render_width = render_width_minus_1 + 1;
1904     parser->state.render_height = render_height_minus_1 + 1;
1905   } else {
1906     parser->state.render_width = parser->state.upscaled_width;
1907     parser->state.render_height = parser->state.frame_height;
1908   }
1909
1910   return GST_AV1_PARSER_OK;
1911 }
1912
1913 /* 5.9.7 */
1914 static GstAV1ParserResult
1915 gst_av1_parse_frame_size_with_refs (GstAV1Parser * parser,
1916     GstBitReader * br, GstAV1FrameHeaderOBU * frame_header)
1917 {
1918   GstAV1ParserResult retval;
1919   GstAV1ReferenceFrameInfo *ref_info;
1920   gboolean found_ref = FALSE;
1921   gint i;
1922
1923   ref_info = &(parser->state.ref_info);
1924
1925   for (i = 0; i < GST_AV1_REFS_PER_FRAME; i++) {
1926     found_ref = AV1_READ_BIT_CHECKED (br, &retval);
1927     if (retval != GST_AV1_PARSER_OK)
1928       return retval;
1929
1930     if (found_ref == 1) {
1931       gint ref_idx = frame_header->ref_frame_idx[i];
1932       parser->state.upscaled_width =
1933           ref_info->entry[ref_idx].ref_upscaled_width;
1934       parser->state.frame_width = parser->state.upscaled_width;
1935       parser->state.frame_height = ref_info->entry[ref_idx].ref_frame_height;
1936       parser->state.render_width = ref_info->entry[ref_idx].ref_render_width;
1937       parser->state.render_height = ref_info->entry[ref_idx].ref_render_height;
1938       break;
1939     }
1940   }
1941   if (found_ref == 0) {
1942     retval = gst_av1_parse_frame_size (parser, br, frame_header);
1943     if (retval != GST_AV1_PARSER_OK)
1944       return retval;
1945
1946     retval = gst_av1_parse_render_size (parser, br, frame_header);
1947     if (retval != GST_AV1_PARSER_OK)
1948       return retval;
1949   } else {
1950     retval = gst_av1_parse_superres_params_compute_image_size (parser, br,
1951         frame_header);
1952     if (retval != GST_AV1_PARSER_OK)
1953       return retval;
1954   }
1955
1956   return GST_AV1_PARSER_OK;
1957 }
1958
1959 /* 5.9.12 */
1960 static GstAV1ParserResult
1961 gst_av1_parse_quantization_params (GstAV1Parser * parser, GstBitReader * br,
1962     GstAV1FrameHeaderOBU * frame_header)
1963 {
1964   GstAV1ParserResult retval = GST_AV1_PARSER_OK;
1965   GstAV1ColorConfig *color_config;
1966   GstAV1QuantizationParams *quant_params = &(frame_header->quantization_params);
1967
1968   g_assert (parser->seq_header);
1969
1970   color_config = &(parser->seq_header->color_config);
1971
1972   quant_params->base_q_idx = AV1_READ_UINT8_CHECKED (br, &retval);
1973   if (retval != GST_AV1_PARSER_OK)
1974     goto error;
1975
1976   frame_header->quantization_params.delta_q_y_dc =
1977       av1_bitstreamfn_delta_q (br, &retval);
1978   if (retval != GST_AV1_PARSER_OK)
1979     goto error;
1980
1981   if (parser->seq_header->num_planes > 1) {
1982     if (color_config->separate_uv_delta_q) {
1983       quant_params->diff_uv_delta = AV1_READ_BIT_CHECKED (br, &retval);
1984       if (retval != GST_AV1_PARSER_OK)
1985         goto error;
1986     } else {
1987       quant_params->diff_uv_delta = 0;
1988     }
1989     frame_header->quantization_params.delta_q_u_dc =
1990         av1_bitstreamfn_delta_q (br, &retval);
1991     if (retval != GST_AV1_PARSER_OK)
1992       goto error;
1993
1994     frame_header->quantization_params.delta_q_u_ac =
1995         av1_bitstreamfn_delta_q (br, &retval);
1996     if (retval != GST_AV1_PARSER_OK)
1997       goto error;
1998
1999     if (quant_params->diff_uv_delta) {
2000       frame_header->quantization_params.delta_q_v_dc =
2001           av1_bitstreamfn_delta_q (br, &retval);
2002       if (retval != GST_AV1_PARSER_OK)
2003         goto error;
2004
2005       frame_header->quantization_params.delta_q_v_ac =
2006           av1_bitstreamfn_delta_q (br, &retval);
2007       if (retval != GST_AV1_PARSER_OK)
2008         goto error;
2009     } else {
2010       frame_header->quantization_params.delta_q_v_dc =
2011           frame_header->quantization_params.delta_q_u_dc;
2012       frame_header->quantization_params.delta_q_v_ac =
2013           frame_header->quantization_params.delta_q_u_ac;
2014     }
2015   } else {
2016     frame_header->quantization_params.delta_q_u_dc = 0;
2017     frame_header->quantization_params.delta_q_u_ac = 0;
2018     frame_header->quantization_params.delta_q_v_dc = 0;
2019     frame_header->quantization_params.delta_q_v_ac = 0;
2020   }
2021
2022   quant_params->using_qmatrix = AV1_READ_BIT_CHECKED (br, &retval);
2023   if (retval != GST_AV1_PARSER_OK)
2024     goto error;
2025
2026   if (quant_params->using_qmatrix) {
2027     if (AV1_REMAINING_BITS (br) < 4 + 4) {
2028       retval = GST_AV1_PARSER_NO_MORE_DATA;
2029       goto error;
2030     }
2031
2032     quant_params->qm_y = AV1_READ_BITS (br, 4);
2033     quant_params->qm_u = AV1_READ_BITS (br, 4);
2034
2035     if (!color_config->separate_uv_delta_q) {
2036       quant_params->qm_v = quant_params->qm_u;
2037     } else {
2038       quant_params->qm_v = AV1_READ_BITS_CHECKED (br, 4, &retval);
2039       if (retval != GST_AV1_PARSER_OK)
2040         goto error;
2041     }
2042   }
2043
2044   return GST_AV1_PARSER_OK;
2045
2046 error:
2047   GST_WARNING ("parse quantization params error %d", retval);
2048   return retval;
2049 }
2050
2051 /* 5.9.14 */
2052 static GstAV1ParserResult
2053 gst_av1_parse_segmentation_params (GstAV1Parser * parser, GstBitReader * br,
2054     GstAV1FrameHeaderOBU * frame_header)
2055 {
2056   gint i, j;
2057   GstAV1ParserResult retval = GST_AV1_PARSER_OK;
2058   gint clipped_value /* clippedValue */ ;
2059   GstAV1SegmenationParams *seg_params;
2060   gint feature_value = 0;
2061
2062   const guint8 segmentation_feature_bits[GST_AV1_SEG_LVL_MAX] = {
2063     8, 6, 6, 6, 6, 3, 0, 0
2064   };
2065   const guint8 segmentation_feature_signed[GST_AV1_SEG_LVL_MAX] = {
2066     1, 1, 1, 1, 1, 0, 0, 0
2067   };
2068   const guint8 segmentation_feature_max[GST_AV1_SEG_LVL_MAX] = {
2069     255, GST_AV1_MAX_LOOP_FILTER, GST_AV1_MAX_LOOP_FILTER,
2070     GST_AV1_MAX_LOOP_FILTER, GST_AV1_MAX_LOOP_FILTER, 7, 0, 0
2071   };
2072
2073   seg_params = &frame_header->segmentation_params;
2074
2075   seg_params->segmentation_enabled = AV1_READ_BIT_CHECKED (br, &retval);
2076   if (retval != GST_AV1_PARSER_OK)
2077     goto error;
2078
2079   if (seg_params->segmentation_enabled) {
2080     if (frame_header->primary_ref_frame == GST_AV1_PRIMARY_REF_NONE) {
2081       seg_params->segmentation_update_map = 1;
2082       seg_params->segmentation_temporal_update = 0;
2083       seg_params->segmentation_update_data = 1;
2084     } else {
2085       seg_params->segmentation_update_map = AV1_READ_BIT_CHECKED (br, &retval);
2086       if (retval != GST_AV1_PARSER_OK)
2087         goto error;
2088
2089       if (seg_params->segmentation_update_map) {
2090         seg_params->segmentation_temporal_update =
2091             AV1_READ_BIT_CHECKED (br, &retval);
2092         if (retval != GST_AV1_PARSER_OK)
2093           goto error;
2094       }
2095       seg_params->segmentation_update_data = AV1_READ_BIT_CHECKED (br, &retval);
2096       if (retval != GST_AV1_PARSER_OK)
2097         goto error;
2098     }
2099
2100     if (seg_params->segmentation_update_data) {
2101       for (i = 0; i < GST_AV1_MAX_SEGMENTS; i++) {
2102         for (j = 0; j < GST_AV1_SEG_LVL_MAX; j++) {
2103           seg_params->feature_enabled[i][j] =
2104               AV1_READ_BIT_CHECKED (br, &retval);
2105           if (retval != GST_AV1_PARSER_OK)
2106             goto error;
2107
2108           clipped_value = 0;
2109           feature_value = 0;
2110           if (seg_params->feature_enabled[i][j]) {
2111             gint bits_to_read = segmentation_feature_bits[j];
2112             gint limit = segmentation_feature_max[j];
2113             if (segmentation_feature_signed[j]) {
2114               feature_value =
2115                   av1_bitstreamfn_su (br, 1 + bits_to_read, &retval);
2116               if (retval != GST_AV1_PARSER_OK)
2117                 goto error;
2118
2119               clipped_value = CLAMP (feature_value, limit * (-1), limit);
2120             } else {
2121               feature_value = AV1_READ_BITS_CHECKED (br, bits_to_read, &retval);
2122               if (retval != GST_AV1_PARSER_OK)
2123                 goto error;
2124
2125               clipped_value = CLAMP (feature_value, 0, limit);
2126             }
2127           }
2128           seg_params->feature_data[i][j] = clipped_value;
2129         }
2130       }
2131     } else {
2132       gint8 ref_idx;
2133       GstAV1SegmenationParams *ref_seg_params;
2134
2135       /* Copy it from prime_ref */
2136       if (frame_header->primary_ref_frame >= GST_AV1_PRIMARY_REF_NONE) {
2137         GST_WARNING ("Invalid primary_ref_frame %d",
2138             frame_header->primary_ref_frame);
2139         return GST_AV1_PARSER_BITSTREAM_ERROR;
2140       }
2141
2142       ref_idx = frame_header->ref_frame_idx[frame_header->primary_ref_frame];
2143       if (ref_idx >= GST_AV1_NUM_REF_FRAMES || ref_idx < 0) {
2144         GST_WARNING ("Invalid ref_frame_idx %d", ref_idx);
2145         return GST_AV1_PARSER_BITSTREAM_ERROR;
2146       }
2147
2148       if (!parser->state.ref_info.entry[ref_idx].ref_valid) {
2149         GST_WARNING ("Reference frame at index %d is unavailable", ref_idx);
2150         return GST_AV1_PARSER_BITSTREAM_ERROR;
2151       }
2152
2153       ref_seg_params =
2154           &parser->state.ref_info.entry[ref_idx].ref_segmentation_params;
2155
2156       for (i = 0; i < GST_AV1_MAX_SEGMENTS; i++) {
2157         for (j = 0; j < GST_AV1_SEG_LVL_MAX; j++) {
2158           seg_params->feature_enabled[i][j] =
2159               ref_seg_params->feature_enabled[i][j];
2160           seg_params->feature_data[i][j] = ref_seg_params->feature_data[i][j];
2161         }
2162       }
2163     }
2164   } else {
2165     seg_params->segmentation_update_map = 0;
2166     seg_params->segmentation_temporal_update = 0;
2167     seg_params->segmentation_update_data = 0;
2168     for (i = 0; i < GST_AV1_MAX_SEGMENTS; i++) {
2169       for (j = 0; j < GST_AV1_SEG_LVL_MAX; j++) {
2170         seg_params->feature_enabled[i][j] = 0;
2171         seg_params->feature_data[i][j] = 0;
2172       }
2173     }
2174   }
2175
2176   seg_params->seg_id_pre_skip = 0;
2177   seg_params->last_active_seg_id = 0;
2178   for (i = 0; i < GST_AV1_MAX_SEGMENTS; i++) {
2179     for (j = 0; j < GST_AV1_SEG_LVL_MAX; j++) {
2180       if (seg_params->feature_enabled[i][j]) {
2181         seg_params->last_active_seg_id = i;
2182         if (j >= GST_AV1_SEG_LVL_REF_FRAME) {
2183           seg_params->seg_id_pre_skip = 1;
2184         }
2185       }
2186     }
2187   }
2188
2189   return GST_AV1_PARSER_OK;
2190
2191 error:
2192   GST_WARNING ("parse segmentation params error %d", retval);
2193   return retval;
2194 }
2195
2196 /* 5.9.15 */
2197 static GstAV1ParserResult
2198 gst_av1_parse_tile_info (GstAV1Parser * parser, GstBitReader * br,
2199     GstAV1FrameHeaderOBU * frame_header)
2200 {
2201   GstAV1ParserResult retval = GST_AV1_PARSER_OK;
2202   GstAV1SequenceHeaderOBU *seq_header;
2203   GstAV1TileInfo *tile_info;
2204   gint i;
2205   gint start_sb /* startSb */ ;
2206   gint sb_cols /* sbCols */ ;
2207   gint sb_rows /* sbRows */ ;
2208   gint sb_shift /*sbShift */ ;
2209   gint sb_size /* sbSize */ ;
2210   gint max_tile_width_sb /* maxTileWidthSb */ ;
2211   gint max_tile_height_sb /* maxTileHeightSb */ ;
2212   gint max_tile_area_sb /* maxTileAreaSb */ ;
2213   gint min_log2_tile_cols /* minLog2TileCols */ ;
2214   gint max_log2_tile_cols /* maxLog2TileCols */ ;
2215   gint min_log2_tile_rows /* minLog2TileRows */ ;
2216   gint max_log2_tile_rows /* maxLog2TileRows */ ;
2217   gint min_log2_tiles /* minLog2Tiles */ ;
2218   gint tile_width_sb /* tileWidthSb */ ;
2219   gint tile_height_sb /* tileHeightSb */ ;
2220   gint max_width /* maxWidth */ , max_height /* maxHeight */ ;
2221   gint size_sb /* sizeSb */ ;
2222   gint widest_tile_sb /* widestTileSb */ ;
2223
2224   g_assert (parser->seq_header);
2225   seq_header = parser->seq_header;
2226   tile_info = &frame_header->tile_info;
2227
2228   sb_cols = seq_header->use_128x128_superblock ?
2229       ((parser->state.mi_cols + 31) >> 5) : ((parser->state.mi_cols + 15) >> 4);
2230   sb_rows = seq_header->use_128x128_superblock ? ((parser->state.mi_rows +
2231           31) >> 5) : ((parser->state.mi_rows + 15) >> 4);
2232   sb_cols = MIN (GST_AV1_MAX_TILE_COLS, sb_cols);
2233   sb_rows = MIN (GST_AV1_MAX_TILE_ROWS, sb_rows);
2234   sb_shift = seq_header->use_128x128_superblock ? 5 : 4;
2235   sb_size = sb_shift + 2;
2236   max_tile_width_sb = GST_AV1_MAX_TILE_WIDTH >> sb_size;
2237   max_tile_area_sb = GST_AV1_MAX_TILE_AREA >> (2 * sb_size);
2238   min_log2_tile_cols = av1_helper_tile_log2 (max_tile_width_sb, sb_cols);
2239   max_log2_tile_cols = av1_helper_tile_log2 (1, MIN (sb_cols,
2240           GST_AV1_MAX_TILE_COLS));
2241   max_log2_tile_rows = av1_helper_tile_log2 (1, MIN (sb_rows,
2242           GST_AV1_MAX_TILE_ROWS));
2243   min_log2_tiles = MAX (min_log2_tile_cols,
2244       av1_helper_tile_log2 (max_tile_area_sb, sb_rows * sb_cols));
2245
2246   tile_info->uniform_tile_spacing_flag = AV1_READ_BIT_CHECKED (br, &retval);
2247   if (retval != GST_AV1_PARSER_OK)
2248     goto error;
2249
2250   if (tile_info->uniform_tile_spacing_flag) {
2251     parser->state.tile_cols_log2 = min_log2_tile_cols;
2252     while (parser->state.tile_cols_log2 < max_log2_tile_cols) {
2253       gint increment_tile_cols_log2 = AV1_READ_BIT_CHECKED (br, &retval);
2254       if (retval != GST_AV1_PARSER_OK)
2255         goto error;
2256
2257       if (increment_tile_cols_log2 == 1)
2258         parser->state.tile_cols_log2++;
2259       else
2260         break;
2261     }
2262     tile_width_sb = (sb_cols + (1 << parser->state.tile_cols_log2) -
2263         1) >> parser->state.tile_cols_log2;
2264     i = 0;
2265     for (start_sb = 0; start_sb < sb_cols; start_sb += tile_width_sb) {
2266       parser->state.mi_col_starts[i] = start_sb << sb_shift;
2267       i += 1;
2268     }
2269     parser->state.mi_col_starts[i] = parser->state.mi_cols;
2270     parser->state.tile_cols = i;
2271
2272     while (i >= 1) {
2273       tile_info->width_in_sbs_minus_1[i - 1] =
2274           ((parser->state.mi_col_starts[i] - parser->state.mi_col_starts[i - 1]
2275               + ((1 << sb_shift) - 1)) >> sb_shift) - 1;
2276       i--;
2277     }
2278
2279     min_log2_tile_rows = MAX (min_log2_tiles - parser->state.tile_cols_log2, 0);
2280     parser->state.tile_rows_log2 = min_log2_tile_rows;
2281     while (parser->state.tile_rows_log2 < max_log2_tile_rows) {
2282       tile_info->increment_tile_rows_log2 = AV1_READ_BIT_CHECKED (br, &retval);
2283       if (retval != GST_AV1_PARSER_OK)
2284         goto error;
2285
2286       if (tile_info->increment_tile_rows_log2 == 1)
2287         parser->state.tile_rows_log2++;
2288       else
2289         break;
2290     }
2291     tile_height_sb = (sb_rows + (1 << parser->state.tile_rows_log2) -
2292         1) >> parser->state.tile_rows_log2;
2293     i = 0;
2294     for (start_sb = 0; start_sb < sb_rows; start_sb += tile_height_sb) {
2295       parser->state.mi_row_starts[i] = start_sb << sb_shift;
2296       i += 1;
2297     }
2298     parser->state.mi_row_starts[i] = parser->state.mi_rows;
2299     parser->state.tile_rows = i;
2300     while (i >= 1) {
2301       tile_info->height_in_sbs_minus_1[i - 1] =
2302           ((parser->state.mi_row_starts[i] - parser->state.mi_row_starts[i - 1]
2303               + ((1 << sb_shift) - 1)) >> sb_shift) - 1;
2304       i--;
2305     }
2306   } else {
2307     widest_tile_sb = 0;
2308     start_sb = 0;
2309     for (i = 0; start_sb < sb_cols; i++) {
2310       parser->state.mi_col_starts[i] = start_sb << sb_shift;
2311       max_width = MIN (sb_cols - start_sb, max_tile_width_sb);
2312       tile_info->width_in_sbs_minus_1[i] =
2313           av1_bitstreamfn_ns (br, max_width, &retval);
2314       if (retval != GST_AV1_PARSER_OK)
2315         goto error;
2316
2317       size_sb = tile_info->width_in_sbs_minus_1[i] + 1;
2318       widest_tile_sb = MAX (size_sb, widest_tile_sb);
2319       start_sb += size_sb;
2320     }
2321     parser->state.mi_col_starts[i] = parser->state.mi_cols;
2322     parser->state.tile_cols = i;
2323     parser->state.tile_cols_log2 =
2324         av1_helper_tile_log2 (1, parser->state.tile_cols);
2325
2326     if (min_log2_tiles > 0)
2327       max_tile_area_sb = (sb_rows * sb_cols) >> (min_log2_tiles + 1);
2328     else
2329       max_tile_area_sb = sb_rows * sb_cols;
2330
2331     max_tile_height_sb = MAX (max_tile_area_sb / widest_tile_sb, 1);
2332
2333     start_sb = 0;
2334     for (i = 0; start_sb < sb_rows; i++) {
2335       parser->state.mi_row_starts[i] = start_sb << sb_shift;
2336       max_height = MIN (sb_rows - start_sb, max_tile_height_sb);
2337       tile_info->height_in_sbs_minus_1[i] =
2338           av1_bitstreamfn_ns (br, max_height, &retval);
2339       if (retval != GST_AV1_PARSER_OK)
2340         goto error;
2341
2342       size_sb = tile_info->height_in_sbs_minus_1[i] + 1;
2343       start_sb += size_sb;
2344     }
2345
2346     parser->state.mi_row_starts[i] = parser->state.mi_rows;
2347     parser->state.tile_rows = i;
2348     parser->state.tile_rows_log2 =
2349         av1_helper_tile_log2 (1, parser->state.tile_rows);
2350   }
2351
2352   if (parser->state.tile_cols_log2 > 0 || parser->state.tile_rows_log2 > 0) {
2353     tile_info->context_update_tile_id =
2354         AV1_READ_BITS_CHECKED (br,
2355         parser->state.tile_cols_log2 + parser->state.tile_rows_log2, &retval);
2356     if (retval != GST_AV1_PARSER_OK)
2357       goto error;
2358
2359     tile_info->tile_size_bytes_minus_1 = AV1_READ_BITS_CHECKED (br, 2, &retval);
2360     if (retval != GST_AV1_PARSER_OK)
2361       goto error;
2362
2363     parser->state.tile_size_bytes = tile_info->tile_size_bytes_minus_1 + 1;
2364   } else {
2365     tile_info->context_update_tile_id = 0;
2366   }
2367
2368   memcpy (tile_info->mi_col_starts, parser->state.mi_col_starts,
2369       sizeof (guint32) * (GST_AV1_MAX_TILE_COLS + 1));
2370   memcpy (tile_info->mi_row_starts, parser->state.mi_row_starts,
2371       sizeof (guint32) * (GST_AV1_MAX_TILE_ROWS + 1));
2372   tile_info->tile_cols_log2 = parser->state.tile_cols_log2;
2373   tile_info->tile_cols = parser->state.tile_cols;
2374   tile_info->tile_rows_log2 = parser->state.tile_rows_log2;
2375   tile_info->tile_rows = parser->state.tile_rows;
2376   tile_info->tile_size_bytes = parser->state.tile_size_bytes;
2377
2378   return GST_AV1_PARSER_OK;
2379
2380 error:
2381   GST_WARNING ("parse tile info error %d", retval);
2382   return retval;
2383 }
2384
2385 static GstAV1ParserResult
2386 gst_av1_parse_loop_filter_params (GstAV1Parser * parser,
2387     GstBitReader * br, GstAV1FrameHeaderOBU * frame_header)
2388 {
2389   GstAV1ParserResult retval = GST_AV1_PARSER_OK;
2390   GstAV1LoopFilterParams *lf_params;
2391   gint i;
2392   guint8 update_ref_deltas = 0;
2393   guint8 update_mode_deltas = 0;
2394
2395   g_assert (parser->seq_header);
2396
2397   lf_params = &frame_header->loop_filter_params;
2398
2399   if (frame_header->coded_lossless || frame_header->allow_intrabc) {
2400     lf_params->loop_filter_level[0] = 0;
2401     lf_params->loop_filter_level[1] = 0;
2402     lf_params->loop_filter_ref_deltas[GST_AV1_REF_INTRA_FRAME] = 1;
2403     lf_params->loop_filter_ref_deltas[GST_AV1_REF_LAST_FRAME] = 0;
2404     lf_params->loop_filter_ref_deltas[GST_AV1_REF_LAST2_FRAME] = 0;
2405     lf_params->loop_filter_ref_deltas[GST_AV1_REF_LAST3_FRAME] = 0;
2406     lf_params->loop_filter_ref_deltas[GST_AV1_REF_BWDREF_FRAME] = 0;
2407     lf_params->loop_filter_ref_deltas[GST_AV1_REF_GOLDEN_FRAME] = -1;
2408     lf_params->loop_filter_ref_deltas[GST_AV1_REF_ALTREF_FRAME] = -1;
2409     lf_params->loop_filter_ref_deltas[GST_AV1_REF_ALTREF2_FRAME] = -1;
2410     for (i = 0; i < 2; i++)
2411       lf_params->loop_filter_mode_deltas[i] = 0;
2412
2413     goto success;
2414   }
2415
2416   if (AV1_REMAINING_BITS (br) < 6 + 6) {
2417     retval = GST_AV1_PARSER_NO_MORE_DATA;
2418     goto error;
2419   }
2420
2421   lf_params->loop_filter_level[0] = AV1_READ_BITS (br, 6);
2422   lf_params->loop_filter_level[1] = AV1_READ_BITS (br, 6);
2423   if (parser->seq_header->num_planes > 1) {
2424     if (lf_params->loop_filter_level[0] || lf_params->loop_filter_level[1]) {
2425       if (AV1_REMAINING_BITS (br) < 6 + 6) {
2426         retval = GST_AV1_PARSER_NO_MORE_DATA;
2427         goto error;
2428       }
2429
2430       lf_params->loop_filter_level[2] = AV1_READ_BITS (br, 6);
2431       lf_params->loop_filter_level[3] = AV1_READ_BITS (br, 6);
2432     }
2433   }
2434
2435   if (AV1_REMAINING_BITS (br) < 3 + 1) {
2436     retval = GST_AV1_PARSER_NO_MORE_DATA;
2437     goto error;
2438   }
2439
2440   lf_params->loop_filter_sharpness = AV1_READ_BITS (br, 3);
2441
2442   lf_params->loop_filter_delta_enabled = AV1_READ_BIT (br);
2443   if (lf_params->loop_filter_delta_enabled) {
2444     lf_params->loop_filter_delta_update = AV1_READ_BIT_CHECKED (br, &retval);
2445     if (retval != GST_AV1_PARSER_OK)
2446       goto error;
2447
2448     if (lf_params->loop_filter_delta_update) {
2449       for (i = 0; i < GST_AV1_TOTAL_REFS_PER_FRAME; i++) {
2450         update_ref_deltas = AV1_READ_BIT_CHECKED (br, &retval);
2451         if (retval != GST_AV1_PARSER_OK)
2452           goto error;
2453
2454         if (update_ref_deltas) {
2455           lf_params->loop_filter_ref_deltas[i] =
2456               av1_bitstreamfn_su (br, 7, &retval);
2457           if (retval != GST_AV1_PARSER_OK)
2458             goto error;
2459         }
2460       }
2461       for (i = 0; i < 2; i++) {
2462         update_mode_deltas = AV1_READ_BIT_CHECKED (br, &retval);
2463         if (retval != GST_AV1_PARSER_OK)
2464           goto error;
2465
2466         if (update_mode_deltas) {
2467           lf_params->loop_filter_mode_deltas[i] =
2468               av1_bitstreamfn_su (br, 7, &retval);
2469           if (retval != GST_AV1_PARSER_OK)
2470             goto error;
2471         }
2472       }
2473     }
2474   }
2475
2476 success:
2477   return GST_AV1_PARSER_OK;
2478
2479 error:
2480   GST_WARNING ("parse loop filter params error %d", retval);
2481   return retval;
2482 }
2483
2484 /* 5.9.17 */
2485 static GstAV1ParserResult
2486 gst_av1_parse_delta_q_params (GstAV1Parser * parser,
2487     GstBitReader * br, GstAV1QuantizationParams * quant_params)
2488 {
2489   GstAV1ParserResult retval;
2490
2491   quant_params->delta_q_res = 0;
2492   quant_params->delta_q_present = 0;
2493   if (quant_params->base_q_idx > 0) {
2494     quant_params->delta_q_present = AV1_READ_BIT_CHECKED (br, &retval);
2495     if (retval != GST_AV1_PARSER_OK)
2496       return retval;
2497   }
2498
2499   if (quant_params->delta_q_present) {
2500     quant_params->delta_q_res = AV1_READ_BITS_CHECKED (br, 2, &retval);
2501     if (retval != GST_AV1_PARSER_OK)
2502       return retval;
2503   }
2504
2505   return GST_AV1_PARSER_OK;
2506 }
2507
2508 /* 5.9.18 */
2509 static GstAV1ParserResult
2510 gst_av1_parse_delta_lf_params (GstAV1Parser * parser,
2511     GstBitReader * br, GstAV1FrameHeaderOBU * frame_header)
2512 {
2513   GstAV1ParserResult retval;
2514   GstAV1LoopFilterParams *lf_params;
2515
2516   lf_params = &frame_header->loop_filter_params;
2517   lf_params->delta_lf_present = 0;
2518   lf_params->delta_lf_res = 0;
2519   lf_params->delta_lf_multi = 0;
2520
2521   if (frame_header->quantization_params.delta_q_present) {
2522     if (!frame_header->allow_intrabc) {
2523       lf_params->delta_lf_present = AV1_READ_BIT_CHECKED (br, &retval);
2524       if (retval != GST_AV1_PARSER_OK)
2525         return retval;
2526     }
2527     if (lf_params->delta_lf_present) {
2528       if (AV1_REMAINING_BITS (br) < 2 + 1)
2529         return GST_AV1_PARSER_NO_MORE_DATA;
2530       lf_params->delta_lf_res = AV1_READ_BITS (br, 2);
2531       lf_params->delta_lf_multi = AV1_READ_BIT (br);
2532     }
2533   }
2534
2535   return GST_AV1_PARSER_OK;
2536 }
2537
2538 /* 5.9.19 */
2539 static GstAV1ParserResult
2540 gst_av1_parse_cdef_params (GstAV1Parser * parser, GstBitReader * br,
2541     GstAV1FrameHeaderOBU * frame_header)
2542 {
2543   GstAV1SequenceHeaderOBU *seq_header;
2544   GstAV1CDEFParams *cdef_params;
2545   guint8 cdef_damping_minus_3;
2546   gint i;
2547
2548   g_assert (parser->seq_header);
2549
2550   cdef_params = &frame_header->cdef_params;
2551   seq_header = parser->seq_header;
2552
2553   if (frame_header->coded_lossless || frame_header->allow_intrabc
2554       || !seq_header->enable_cdef) {
2555     cdef_params->cdef_bits = 0;
2556     cdef_params->cdef_y_pri_strength[0] = 0;
2557     cdef_params->cdef_y_sec_strength[0] = 0;
2558     cdef_params->cdef_uv_pri_strength[0] = 0;
2559     cdef_params->cdef_uv_sec_strength[0] = 0;
2560     cdef_params->cdef_damping = 3;
2561     return GST_AV1_PARSER_OK;
2562   }
2563
2564   if (AV1_REMAINING_BITS (br) < 2 + 2)
2565     return GST_AV1_PARSER_NO_MORE_DATA;
2566
2567   cdef_damping_minus_3 = AV1_READ_BITS (br, 2);
2568   cdef_params->cdef_damping = cdef_damping_minus_3 + 3;
2569   cdef_params->cdef_bits = AV1_READ_BITS (br, 2);
2570   for (i = 0; i < (1 << cdef_params->cdef_bits); i++) {
2571     if (AV1_REMAINING_BITS (br) < 4 + 2)
2572       return GST_AV1_PARSER_NO_MORE_DATA;
2573
2574     cdef_params->cdef_y_pri_strength[i] = AV1_READ_BITS (br, 4);
2575     cdef_params->cdef_y_sec_strength[i] = AV1_READ_BITS (br, 2);
2576     if (cdef_params->cdef_y_sec_strength[i] == 3)
2577       cdef_params->cdef_y_sec_strength[i] += 1;
2578
2579     if (parser->seq_header->num_planes > 1) {
2580       if (AV1_REMAINING_BITS (br) < 4 + 2)
2581         return GST_AV1_PARSER_NO_MORE_DATA;
2582
2583       cdef_params->cdef_uv_pri_strength[i] = AV1_READ_BITS (br, 4);
2584       cdef_params->cdef_uv_sec_strength[i] = AV1_READ_BITS (br, 2);
2585       if (cdef_params->cdef_uv_sec_strength[i] == 3)
2586         cdef_params->cdef_uv_sec_strength[i] += 1;
2587     }
2588   }
2589
2590   return GST_AV1_PARSER_OK;
2591 }
2592
2593 /* 5.9.20 */
2594 static GstAV1ParserResult
2595 gst_av1_parse_loop_restoration_params (GstAV1Parser * parser,
2596     GstBitReader * br, GstAV1FrameHeaderOBU * frame_header)
2597 {
2598   GstAV1LoopRestorationParams *lr_params;
2599   GstAV1SequenceHeaderOBU *seq_header;
2600   GstAV1ParserResult retval = GST_AV1_PARSER_OK;
2601   guint8 lr_type;
2602   gint i;
2603   guint8 use_chroma_lr /* useChromaLr */ ;
2604   const GstAV1FrameRestorationType remap_lr_type /* Remap_Lr_Type */ [4] = {
2605     GST_AV1_FRAME_RESTORE_NONE,
2606     GST_AV1_FRAME_RESTORE_SWITCHABLE,
2607     GST_AV1_FRAME_RESTORE_WIENER, GST_AV1_FRAME_RESTORE_SGRPROJ
2608   };
2609
2610   g_assert (parser->seq_header);
2611
2612   lr_params = &frame_header->loop_restoration_params;
2613   seq_header = parser->seq_header;
2614
2615   if (frame_header->all_lossless || frame_header->allow_intrabc
2616       || !seq_header->enable_restoration) {
2617     for (i = 0; i < GST_AV1_MAX_NUM_PLANES; i++)
2618       lr_params->frame_restoration_type[i] = GST_AV1_FRAME_RESTORE_NONE;
2619
2620     lr_params->uses_lr = 0;
2621     goto success;
2622   }
2623
2624   lr_params->uses_lr = 0;
2625   use_chroma_lr = 0;
2626   for (i = 0; i < seq_header->num_planes; i++) {
2627     lr_type = AV1_READ_BITS_CHECKED (br, 2, &retval);
2628     if (retval != GST_AV1_PARSER_OK)
2629       goto error;
2630
2631     lr_params->frame_restoration_type[i] = remap_lr_type[lr_type];
2632     if (lr_params->frame_restoration_type[i] != GST_AV1_FRAME_RESTORE_NONE) {
2633       lr_params->uses_lr = 1;
2634       if (i > 0) {
2635         use_chroma_lr = 1;
2636       }
2637     }
2638   }
2639
2640   if (lr_params->uses_lr) {
2641     if (seq_header->use_128x128_superblock) {
2642       lr_params->lr_unit_shift = AV1_READ_BIT_CHECKED (br, &retval);
2643       if (retval != GST_AV1_PARSER_OK)
2644         goto error;
2645
2646       lr_params->lr_unit_shift++;
2647     } else {
2648       guint8 lr_unit_extra_shift;
2649
2650       lr_params->lr_unit_shift = AV1_READ_BIT_CHECKED (br, &retval);
2651       if (retval != GST_AV1_PARSER_OK)
2652         goto error;
2653
2654       if (lr_params->lr_unit_shift) {
2655         lr_unit_extra_shift = AV1_READ_BIT_CHECKED (br, &retval);
2656         if (retval != GST_AV1_PARSER_OK)
2657           goto error;
2658
2659         lr_params->lr_unit_shift += lr_unit_extra_shift;
2660       }
2661     }
2662
2663     lr_params->loop_restoration_size[0] =
2664         GST_AV1_RESTORATION_TILESIZE_MAX >> (2 - lr_params->lr_unit_shift);
2665     if (seq_header->color_config.subsampling_x
2666         && seq_header->color_config.subsampling_y && use_chroma_lr) {
2667       lr_params->lr_uv_shift = AV1_READ_BIT_CHECKED (br, &retval);
2668       if (retval != GST_AV1_PARSER_OK)
2669         goto error;
2670     } else {
2671       lr_params->lr_uv_shift = 0;
2672     }
2673
2674     lr_params->loop_restoration_size[1] =
2675         lr_params->loop_restoration_size[0] >> lr_params->lr_uv_shift;
2676     lr_params->loop_restoration_size[2] =
2677         lr_params->loop_restoration_size[0] >> lr_params->lr_uv_shift;
2678   }
2679
2680 success:
2681   return GST_AV1_PARSER_OK;
2682
2683 error:
2684   GST_WARNING ("parse loop restoration params error %d", retval);
2685   return retval;
2686 }
2687
2688 /* 5.9.21 */
2689 static GstAV1ParserResult
2690 gst_av1_parse_tx_mode (GstAV1Parser * parser, GstBitReader * br,
2691     GstAV1FrameHeaderOBU * frame_header)
2692 {
2693   GstAV1ParserResult retval;
2694
2695   if (frame_header->coded_lossless == 1) {
2696     frame_header->tx_mode = GST_AV1_TX_MODE_ONLY_4x4;
2697   } else {
2698     frame_header->tx_mode_select = AV1_READ_BIT_CHECKED (br, &retval);
2699     if (retval != GST_AV1_PARSER_OK)
2700       return retval;
2701
2702     if (frame_header->tx_mode_select) {
2703       frame_header->tx_mode = GST_AV1_TX_MODE_SELECT;
2704     } else {
2705       frame_header->tx_mode = GST_AV1_TX_MODE_LARGEST;
2706     }
2707   }
2708
2709   return GST_AV1_PARSER_OK;
2710 }
2711
2712 /* 5.9.3 */
2713 static gint
2714 gst_av1_get_relative_dist (GstAV1SequenceHeaderOBU * seq_header, gint a, gint b)
2715 {
2716   gint m, diff;
2717   if (!seq_header->enable_order_hint)
2718     return 0;
2719   diff = a - b;
2720   m = 1 << seq_header->order_hint_bits_minus_1;
2721   diff = (diff & (m - 1)) - (diff & m);
2722   return diff;
2723 }
2724
2725 /* 5.9.22 */
2726 static GstAV1ParserResult
2727 gst_av1_parse_skip_mode_params (GstAV1Parser * parser, GstBitReader * br,
2728     GstAV1FrameHeaderOBU * frame_header)
2729 {
2730   GstAV1ReferenceFrameInfo *ref_info;
2731   GstAV1SequenceHeaderOBU *seq_header;
2732   gint i;
2733   gint skip_mode_allowed /* skipModeAllowed */ ;
2734   GstAV1ParserResult retval;
2735
2736   g_assert (parser->seq_header);
2737
2738   seq_header = parser->seq_header;
2739   ref_info = &(parser->state.ref_info);
2740   skip_mode_allowed = 0;
2741   if (frame_header->frame_is_intra || !frame_header->reference_select
2742       || !seq_header->enable_order_hint) {
2743     skip_mode_allowed = 0;
2744   } else {
2745     gint forward_idx = -1 /* forwardIdx */ ;
2746     gint forward_hint = 0 /* forwardHint */ ;
2747     gint backward_idx = -1 /* backwardIdx */ ;
2748     gint backward_hint = 0 /* backwardHint */ ;
2749     gint ref_hint = 0 /* refHint */ ;
2750
2751     for (i = 0; i < GST_AV1_REFS_PER_FRAME; i++) {
2752       ref_hint = ref_info->entry[frame_header->ref_frame_idx[i]].ref_order_hint;
2753       if (gst_av1_get_relative_dist (parser->seq_header, ref_hint,
2754               frame_header->order_hint) < 0) {
2755         if (forward_idx < 0
2756             || gst_av1_get_relative_dist (parser->seq_header, ref_hint,
2757                 forward_hint) > 0) {
2758           forward_idx = i;
2759           forward_hint = ref_hint;
2760         }
2761       } else
2762           if (gst_av1_get_relative_dist (parser->seq_header, ref_hint,
2763               frame_header->order_hint) > 0) {
2764         if (backward_idx < 0
2765             || gst_av1_get_relative_dist (parser->seq_header, ref_hint,
2766                 backward_hint) < 0) {
2767           backward_idx = i;
2768           backward_hint = ref_hint;
2769         }
2770       }
2771     }
2772
2773     if (forward_idx < 0) {
2774       skip_mode_allowed = 0;
2775     } else if (backward_idx >= 0) {
2776       skip_mode_allowed = 1;
2777       frame_header->skip_mode_frame[0] =
2778           GST_AV1_REF_LAST_FRAME + MIN (forward_idx, backward_idx);
2779       frame_header->skip_mode_frame[1] =
2780           GST_AV1_REF_LAST_FRAME + MAX (forward_idx, backward_idx);
2781     } else {
2782       gint second_forward_idx = -1 /* secondForwardIdx */ ;
2783       gint second_forward_hint = 0 /* secondForwardHint */ ;
2784       for (i = 0; i < GST_AV1_REFS_PER_FRAME; i++) {
2785         ref_hint =
2786             ref_info->entry[frame_header->ref_frame_idx[i]].ref_order_hint;
2787         if (gst_av1_get_relative_dist (parser->seq_header, ref_hint,
2788                 forward_hint) < 0) {
2789           if (second_forward_idx < 0
2790               || gst_av1_get_relative_dist (parser->seq_header, ref_hint,
2791                   second_forward_hint) > 0) {
2792             second_forward_idx = i;
2793             second_forward_hint = ref_hint;
2794           }
2795         }
2796       }
2797
2798       if (second_forward_idx < 0) {
2799         skip_mode_allowed = 0;
2800       } else {
2801         skip_mode_allowed = 1;
2802         frame_header->skip_mode_frame[0] =
2803             GST_AV1_REF_LAST_FRAME + MIN (forward_idx, second_forward_idx);
2804         frame_header->skip_mode_frame[1] =
2805             GST_AV1_REF_LAST_FRAME + MAX (forward_idx, second_forward_idx);
2806       }
2807     }
2808   }
2809
2810   if (skip_mode_allowed) {
2811     frame_header->skip_mode_present = AV1_READ_BIT_CHECKED (br, &retval);
2812     if (retval != GST_AV1_PARSER_OK)
2813       return retval;
2814   } else {
2815     frame_header->skip_mode_present = 0;
2816   }
2817
2818   return GST_AV1_PARSER_OK;
2819 }
2820
2821 /* 5.9.28 */
2822 static gint
2823 gst_av1_decode_subexp (GstBitReader * br, gint numSyms,
2824     GstAV1ParserResult * retval)
2825 {
2826   gint i = 0;
2827   gint mk = 0;
2828   gint k = 3;
2829   gint subexp_final_bits = 0;
2830   gint subexp_more_bits = 0;
2831   gint subexp_bits = 0;
2832
2833   while (1) {
2834     gint b2 = i ? k + i - 1 : k;
2835     gint a = 1 << b2;
2836     if (numSyms <= mk + 3 * a) {
2837       subexp_final_bits = av1_bitstreamfn_ns (br, numSyms - mk, retval);
2838       if (*retval != GST_AV1_PARSER_OK)
2839         return 0;
2840       return subexp_final_bits + mk;
2841     } else {
2842       subexp_more_bits = AV1_READ_BITS_CHECKED (br, 1, retval);
2843       if (*retval != GST_AV1_PARSER_OK)
2844         return 0;
2845       if (subexp_more_bits) {
2846         i++;
2847         mk += a;
2848       } else {
2849         subexp_bits = AV1_READ_BITS_CHECKED (br, b2, retval);
2850         if (*retval != GST_AV1_PARSER_OK)
2851           return 0;
2852         return subexp_bits + mk;
2853       }
2854     }
2855   }
2856 }
2857
2858 /* 5.9.27 */
2859 static gint
2860 gst_av1_decode_unsigned_subexp_with_ref (GstBitReader * br, gint mx,
2861     gint r, GstAV1ParserResult * retval)
2862 {
2863   gint v;
2864
2865   v = gst_av1_decode_subexp (br, mx, retval);
2866   if ((r << 1) <= mx) {
2867     return av1_helper_inverse_recenter (r, v);
2868   } else {
2869     return mx - 1 - av1_helper_inverse_recenter (mx - 1 - r, v);
2870   }
2871 }
2872
2873 /* 5.9.26 */
2874 static gint
2875 gst_av1_decode_signed_subexp_with_ref (GstBitReader * br, gint low,
2876     gint high, gint r, GstAV1ParserResult * retval)
2877 {
2878   return gst_av1_decode_unsigned_subexp_with_ref (br,
2879       high - low, r - low, retval) + low;
2880 }
2881
2882 /* 5.9.25 */
2883 static GstAV1ParserResult
2884 gst_av1_parse_global_param (GstAV1Parser * parser,
2885     GstAV1FrameHeaderOBU * frame_header, GstBitReader * br,
2886     GstAV1GlobalMotionParams * gm_params, GstAV1WarpModelType type,
2887     gint32 prev_gm_params[GST_AV1_NUM_REF_FRAMES][6], gint ref, gint idx)
2888 {
2889   GstAV1ParserResult retval;
2890   gint prec_diff /* precDiff */ , wm_round, mx, r;
2891   gint abs_bits /* absBits */  = GST_AV1_GM_ABS_ALPHA_BITS;
2892   gint prec_bits /* precBits */  = GST_AV1_GM_ALPHA_PREC_BITS;
2893   gint sub;
2894
2895   if (idx < 2) {
2896     if (type == GST_AV1_WARP_MODEL_TRANSLATION) {
2897       abs_bits =
2898           GST_AV1_GM_ABS_TRANS_ONLY_BITS -
2899           (frame_header->allow_high_precision_mv ? 0 : 1);
2900       prec_bits =
2901           GST_AV1_GM_TRANS_ONLY_PREC_BITS -
2902           (frame_header->allow_high_precision_mv ? 0 : 1);
2903     } else {
2904       abs_bits = GST_AV1_GM_ABS_TRANS_BITS;
2905       prec_bits = GST_AV1_GM_TRANS_PREC_BITS;
2906     }
2907   }
2908
2909   prec_diff = GST_AV1_WARPEDMODEL_PREC_BITS - prec_bits;
2910   wm_round = (idx % 3) == 2 ? (1 << GST_AV1_WARPEDMODEL_PREC_BITS) : 0;
2911   sub = (idx % 3) == 2 ? (1 << prec_bits) : 0;
2912   mx = (1 << abs_bits);
2913   r = (prev_gm_params[ref][idx] >> prec_diff) - sub;
2914   gm_params->gm_params[ref][idx] =
2915       (gst_av1_decode_signed_subexp_with_ref (br, -mx, mx + 1, r,
2916           &retval) << prec_diff) + wm_round;
2917   if (retval != GST_AV1_PARSER_OK)
2918     return retval;
2919   return GST_AV1_PARSER_OK;
2920 }
2921
2922 static gboolean
2923 gst_av1_parser_is_shear_params_valid (gint32 gm_params[6])
2924 {
2925   const gint32 *mat = gm_params;
2926   gint16 alpha, beta, gamma, delta;
2927   gint16 shift;
2928   gint16 y;
2929   gint16 v;
2930   guint i;
2931   gboolean default_warp_params;
2932
2933   if (!(mat[2] > 0))
2934     return FALSE;
2935
2936   default_warp_params = TRUE;
2937   for (i = 0; i < 6; i++) {
2938     if (gm_params[i] != ((i % 3 == 2) ? 1 << GST_AV1_WARPEDMODEL_PREC_BITS : 0)) {
2939       default_warp_params = FALSE;
2940       break;
2941     }
2942   }
2943   if (default_warp_params)
2944     return TRUE;
2945
2946   alpha = CLAMP (mat[2] - (1 << GST_AV1_WARPEDMODEL_PREC_BITS),
2947       G_MININT16, G_MAXINT16);
2948   beta = CLAMP (mat[3], G_MININT16, G_MAXINT16);
2949   y = av1_helper_resolve_divisor_32 (ABS (mat[2]), &shift)
2950       * (mat[2] < 0 ? -1 : 1);
2951   v = ((gint64) mat[4] * (1 << GST_AV1_WARPEDMODEL_PREC_BITS)) * y;
2952   gamma =
2953       CLAMP ((gint) av1_helper_round_power_of_two_signed (v, shift), G_MININT16,
2954       G_MAXINT16);
2955   v = ((gint64) mat[3] * mat[4]) * y;
2956   delta =
2957       CLAMP (mat[5] - (gint) av1_helper_round_power_of_two_signed (v,
2958           shift) - (1 << GST_AV1_WARPEDMODEL_PREC_BITS), G_MININT16,
2959       G_MAXINT16);
2960
2961   alpha =
2962       av1_helper_round_power_of_two_signed (alpha,
2963       GST_AV1_WARP_PARAM_REDUCE_BITS) * (1 << GST_AV1_WARP_PARAM_REDUCE_BITS);
2964   beta =
2965       av1_helper_round_power_of_two_signed (beta,
2966       GST_AV1_WARP_PARAM_REDUCE_BITS) * (1 << GST_AV1_WARP_PARAM_REDUCE_BITS);
2967   gamma =
2968       av1_helper_round_power_of_two_signed (gamma,
2969       GST_AV1_WARP_PARAM_REDUCE_BITS) * (1 << GST_AV1_WARP_PARAM_REDUCE_BITS);
2970   delta =
2971       av1_helper_round_power_of_two_signed (delta,
2972       GST_AV1_WARP_PARAM_REDUCE_BITS) * (1 << GST_AV1_WARP_PARAM_REDUCE_BITS);
2973
2974   if ((4 * ABS (alpha) + 7 * ABS (beta) >= (1 << GST_AV1_WARPEDMODEL_PREC_BITS))
2975       || (4 * ABS (gamma) + 4 * ABS (delta) >=
2976           (1 << GST_AV1_WARPEDMODEL_PREC_BITS)))
2977     return FALSE;
2978
2979   return TRUE;
2980 }
2981
2982 /* 5.9.24 */
2983 static GstAV1ParserResult
2984 gst_av1_parse_global_motion_params (GstAV1Parser * parser,
2985     GstBitReader * br, GstAV1FrameHeaderOBU * frame_header)
2986 {
2987   GstAV1WarpModelType type;
2988   GstAV1ParserResult retval = GST_AV1_PARSER_OK;
2989   gint i, ref;
2990   GstAV1GlobalMotionParams *gm_params = &(frame_header->global_motion_params);
2991   gint32 prev_gm_params[GST_AV1_NUM_REF_FRAMES][6] /* PrevGmParams */ ;
2992
2993   /* init value */
2994   gm_params->gm_type[GST_AV1_REF_INTRA_FRAME] = GST_AV1_WARP_MODEL_IDENTITY;
2995   for (ref = GST_AV1_REF_LAST_FRAME; ref <= GST_AV1_REF_ALTREF_FRAME; ref++) {
2996     gm_params->invalid[ref] = 0;
2997     gm_params->gm_type[ref] = GST_AV1_WARP_MODEL_IDENTITY;
2998     for (i = 0; i < 6; i++) {
2999       gm_params->gm_params[ref][i] =
3000           ((i % 3 == 2) ? 1 << GST_AV1_WARPEDMODEL_PREC_BITS : 0);
3001     }
3002   }
3003
3004   if (frame_header->frame_is_intra)
3005     goto success;
3006
3007   if (frame_header->primary_ref_frame != GST_AV1_PRIMARY_REF_NONE) {
3008     GstAV1GlobalMotionParams *ref_global_motion_params =
3009         &parser->state.ref_info.entry[frame_header->
3010         ref_frame_idx[frame_header->primary_ref_frame]].
3011         ref_global_motion_params;
3012     memcpy (prev_gm_params, ref_global_motion_params->gm_params,
3013         sizeof (gint32) * GST_AV1_NUM_REF_FRAMES * 6);
3014   } else {
3015     for (ref = GST_AV1_REF_INTRA_FRAME; ref < GST_AV1_NUM_REF_FRAMES; ref++)
3016       for (i = 0; i < 6; i++)
3017         prev_gm_params[ref][i] =
3018             ((i % 3 == 2) ? 1 << GST_AV1_WARPEDMODEL_PREC_BITS : 0);
3019   }
3020
3021   for (ref = GST_AV1_REF_LAST_FRAME; ref <= GST_AV1_REF_ALTREF_FRAME; ref++) {
3022     gm_params->is_global[ref] = AV1_READ_BIT_CHECKED (br, &retval);
3023     if (retval != GST_AV1_PARSER_OK)
3024       goto error;
3025
3026     if (gm_params->is_global[ref]) {
3027       gm_params->is_rot_zoom[ref] = AV1_READ_BIT_CHECKED (br, &retval);
3028       if (retval != GST_AV1_PARSER_OK)
3029         goto error;
3030
3031       if (gm_params->is_rot_zoom[ref]) {
3032         type = GST_AV1_WARP_MODEL_ROTZOOM;
3033       } else {
3034         gm_params->is_translation[ref] = AV1_READ_BIT_CHECKED (br, &retval);
3035         if (retval != GST_AV1_PARSER_OK)
3036           goto error;
3037         type =
3038             gm_params->is_translation[ref] ? GST_AV1_WARP_MODEL_TRANSLATION :
3039             GST_AV1_WARP_MODEL_AFFINE;
3040       }
3041     } else {
3042       type = GST_AV1_WARP_MODEL_IDENTITY;
3043     }
3044     gm_params->gm_type[ref] = type;
3045
3046     if (type >= GST_AV1_WARP_MODEL_ROTZOOM) {
3047       retval =
3048           gst_av1_parse_global_param (parser, frame_header, br, gm_params, type,
3049           prev_gm_params, ref, 2);
3050       if (retval != GST_AV1_PARSER_OK)
3051         goto error;
3052
3053       retval =
3054           gst_av1_parse_global_param (parser, frame_header, br, gm_params, type,
3055           prev_gm_params, ref, 3);
3056       if (retval != GST_AV1_PARSER_OK)
3057         goto error;
3058
3059       if (type == GST_AV1_WARP_MODEL_AFFINE) {
3060         retval =
3061             gst_av1_parse_global_param (parser, frame_header, br, gm_params,
3062             type, prev_gm_params, ref, 4);
3063         if (retval != GST_AV1_PARSER_OK)
3064           goto error;
3065
3066         retval =
3067             gst_av1_parse_global_param (parser, frame_header, br, gm_params,
3068             type, prev_gm_params, ref, 5);
3069         if (retval != GST_AV1_PARSER_OK)
3070           goto error;
3071       } else {
3072         gm_params->gm_params[ref][4] = gm_params->gm_params[ref][3] * (-1);
3073         gm_params->gm_params[ref][5] = gm_params->gm_params[ref][2];
3074       }
3075     }
3076     if (type >= GST_AV1_WARP_MODEL_TRANSLATION) {
3077       retval =
3078           gst_av1_parse_global_param (parser, frame_header, br, gm_params, type,
3079           prev_gm_params, ref, 0);
3080       if (retval != GST_AV1_PARSER_OK)
3081         goto error;
3082       retval =
3083           gst_av1_parse_global_param (parser, frame_header, br, gm_params, type,
3084           prev_gm_params, ref, 1);
3085       if (retval != GST_AV1_PARSER_OK)
3086         goto error;
3087     }
3088
3089     if (type <= GST_AV1_WARP_MODEL_AFFINE)
3090       gm_params->invalid[ref] =
3091           !gst_av1_parser_is_shear_params_valid (gm_params->gm_params[ref]);
3092   }
3093
3094 success:
3095   return GST_AV1_PARSER_OK;
3096
3097 error:
3098   GST_WARNING ("parse global motion params error %d", retval);
3099   return retval;
3100 }
3101
3102 /* 5.9.30 */
3103 static GstAV1ParserResult
3104 gst_av1_parse_film_grain_params (GstAV1Parser * parser, GstBitReader * br,
3105     GstAV1FrameHeaderOBU * frame_header)
3106 {
3107   GstAV1FilmGrainParams *fg_params;
3108   GstAV1SequenceHeaderOBU *seq_header;
3109   gint i;
3110   gint num_pos_chroma /* numPosChroma */ , num_pos_luma /* numPosLuma */ ;
3111   GstAV1ParserResult ret = GST_AV1_PARSER_OK;
3112
3113   g_assert (parser->seq_header);
3114
3115   fg_params = &frame_header->film_grain_params;
3116   seq_header = parser->seq_header;
3117   if (!seq_header->film_grain_params_present || (!frame_header->show_frame
3118           && !frame_header->showable_frame)) {
3119     /* reset_grain_params() is a function call that indicates that all the
3120        syntax elements read in film_grain_params should be set equal to 0. */
3121     memset (fg_params, 0, sizeof (*fg_params));
3122     goto success;
3123   }
3124
3125   fg_params->apply_grain = AV1_READ_BIT_CHECKED (br, &ret);
3126   if (ret != GST_AV1_PARSER_OK)
3127     goto error;
3128   if (!fg_params->apply_grain) {
3129     /* reset_grain_params() */
3130     memset (fg_params, 0, sizeof (*fg_params));
3131     goto success;
3132   }
3133
3134   fg_params->grain_seed = AV1_READ_UINT16_CHECKED (br, &ret);
3135   if (ret != GST_AV1_PARSER_OK)
3136     goto error;
3137
3138   if (frame_header->frame_type == GST_AV1_INTER_FRAME) {
3139     fg_params->update_grain = AV1_READ_BIT_CHECKED (br, &ret);
3140     if (ret != GST_AV1_PARSER_OK)
3141       goto error;
3142   } else {
3143     fg_params->update_grain = 1;
3144   }
3145
3146   if (!fg_params->update_grain) {
3147     guint16 temp_grain_seed /* tempGrainSeed */ ;
3148     gint j;
3149     gboolean found = FALSE;
3150
3151     fg_params->film_grain_params_ref_idx = AV1_READ_BITS_CHECKED (br, 3, &ret);
3152     if (ret != GST_AV1_PARSER_OK)
3153       goto error;
3154
3155     for (j = 0; j < GST_AV1_REFS_PER_FRAME; j++) {
3156       if (frame_header->ref_frame_idx[j] ==
3157           fg_params->film_grain_params_ref_idx) {
3158         found = TRUE;
3159         break;
3160       }
3161     }
3162
3163     if (!found) {
3164       GST_INFO ("Invalid film grain reference idx %d.",
3165           fg_params->film_grain_params_ref_idx);
3166       ret = GST_AV1_PARSER_BITSTREAM_ERROR;
3167       goto error;
3168     }
3169
3170     if (!parser->state.ref_info.entry[fg_params->film_grain_params_ref_idx].
3171         ref_valid) {
3172       GST_INFO ("Invalid ref info of film grain idx %d.",
3173           fg_params->film_grain_params_ref_idx);
3174       ret = GST_AV1_PARSER_BITSTREAM_ERROR;
3175       goto error;
3176     }
3177
3178     temp_grain_seed = fg_params->grain_seed;
3179     memcpy (fg_params,
3180         &parser->state.ref_info.entry[fg_params->film_grain_params_ref_idx].
3181         ref_film_grain_params, sizeof (GstAV1FilmGrainParams));
3182     fg_params->grain_seed = temp_grain_seed;
3183
3184     goto success;
3185   }
3186
3187   fg_params->num_y_points = AV1_READ_BITS_CHECKED (br, 4, &ret);
3188   if (ret != GST_AV1_PARSER_OK)
3189     goto error;
3190
3191   for (i = 0; i < fg_params->num_y_points; i++) {
3192     if (AV1_REMAINING_BITS (br) < 8 + 8) {
3193       ret = GST_AV1_PARSER_NO_MORE_DATA;
3194       goto error;
3195     }
3196     fg_params->point_y_value[i] = AV1_READ_UINT8 (br);
3197     fg_params->point_y_scaling[i] = AV1_READ_UINT8 (br);
3198   }
3199
3200   if (seq_header->color_config.mono_chrome) {
3201     fg_params->chroma_scaling_from_luma = 0;
3202   } else {
3203     fg_params->chroma_scaling_from_luma = AV1_READ_BIT_CHECKED (br, &ret);
3204     if (ret != GST_AV1_PARSER_OK)
3205       goto error;
3206   }
3207
3208   if (seq_header->color_config.mono_chrome
3209       || fg_params->chroma_scaling_from_luma
3210       || (seq_header->color_config.subsampling_x == 1
3211           && seq_header->color_config.subsampling_y == 1
3212           && fg_params->num_y_points == 0)) {
3213     fg_params->num_cb_points = 0;
3214     fg_params->num_cr_points = 0;
3215   } else {
3216     fg_params->num_cb_points = AV1_READ_BITS_CHECKED (br, 4, &ret);
3217     if (ret != GST_AV1_PARSER_OK)
3218       goto error;
3219     for (i = 0; i < fg_params->num_cb_points; i++) {
3220       if (AV1_REMAINING_BITS (br) < 8 + 8) {
3221         ret = GST_AV1_PARSER_NO_MORE_DATA;
3222         goto error;
3223       }
3224       fg_params->point_cb_value[i] = AV1_READ_UINT8 (br);
3225       fg_params->point_cb_scaling[i] = AV1_READ_UINT8 (br);
3226     }
3227
3228     fg_params->num_cr_points = AV1_READ_BITS_CHECKED (br, 4, &ret);
3229     if (ret != GST_AV1_PARSER_OK)
3230       goto error;
3231     for (i = 0; i < fg_params->num_cr_points; i++) {
3232       if (AV1_REMAINING_BITS (br) < 8 + 8) {
3233         ret = GST_AV1_PARSER_NO_MORE_DATA;
3234         goto error;
3235       }
3236       fg_params->point_cr_value[i] = AV1_READ_UINT8 (br);
3237       fg_params->point_cr_scaling[i] = AV1_READ_UINT8 (br);
3238     }
3239   }
3240
3241   fg_params->grain_scaling_minus_8 = AV1_READ_BITS_CHECKED (br, 2, &ret);
3242   if (ret != GST_AV1_PARSER_OK)
3243     goto error;
3244
3245   fg_params->ar_coeff_lag = AV1_READ_BITS_CHECKED (br, 2, &ret);
3246   if (ret != GST_AV1_PARSER_OK)
3247     goto error;
3248
3249   num_pos_luma = 2 * fg_params->ar_coeff_lag * (fg_params->ar_coeff_lag + 1);
3250   if (fg_params->num_y_points) {
3251     num_pos_chroma = num_pos_luma + 1;
3252     for (i = 0; i < num_pos_luma; i++) {
3253       fg_params->ar_coeffs_y_plus_128[i] = AV1_READ_UINT8_CHECKED (br, &ret);
3254       if (ret != GST_AV1_PARSER_OK)
3255         goto error;
3256     }
3257   } else {
3258     num_pos_chroma = num_pos_luma;
3259   }
3260
3261   if (fg_params->chroma_scaling_from_luma || fg_params->num_cb_points) {
3262     for (i = 0; i < num_pos_chroma; i++) {
3263       fg_params->ar_coeffs_cb_plus_128[i] = AV1_READ_UINT8_CHECKED (br, &ret);
3264       if (ret != GST_AV1_PARSER_OK)
3265         goto error;
3266     }
3267   }
3268
3269   if (fg_params->chroma_scaling_from_luma || fg_params->num_cr_points) {
3270     for (i = 0; i < num_pos_chroma; i++) {
3271       fg_params->ar_coeffs_cr_plus_128[i] = AV1_READ_UINT8_CHECKED (br, &ret);
3272       if (ret != GST_AV1_PARSER_OK)
3273         goto error;
3274     }
3275   }
3276
3277   if (AV1_REMAINING_BITS (br) < 2 + 2) {
3278     ret = GST_AV1_PARSER_NO_MORE_DATA;
3279     goto error;
3280   }
3281   fg_params->ar_coeff_shift_minus_6 = AV1_READ_BITS (br, 2);
3282   fg_params->grain_scale_shift = AV1_READ_BITS (br, 2);
3283
3284   if (fg_params->num_cb_points) {
3285     if (AV1_REMAINING_BITS (br) < 8 + 8 + 9) {
3286       ret = GST_AV1_PARSER_NO_MORE_DATA;
3287       goto error;
3288     }
3289     fg_params->cb_mult = AV1_READ_BITS (br, 8);
3290     fg_params->cb_luma_mult = AV1_READ_BITS (br, 8);
3291     fg_params->cb_offset = AV1_READ_BITS (br, 9);
3292   }
3293
3294   if (fg_params->num_cr_points) {
3295     if (AV1_REMAINING_BITS (br) < 8 + 8 + 9) {
3296       ret = GST_AV1_PARSER_NO_MORE_DATA;
3297       goto error;
3298     }
3299     fg_params->cr_mult = AV1_READ_BITS (br, 8);
3300     fg_params->cr_luma_mult = AV1_READ_BITS (br, 8);
3301     fg_params->cr_offset = AV1_READ_BITS (br, 9);
3302   }
3303
3304   if (AV1_REMAINING_BITS (br) < 2) {
3305     ret = GST_AV1_PARSER_NO_MORE_DATA;
3306     goto error;
3307   }
3308   fg_params->overlap_flag = AV1_READ_BIT (br);
3309   fg_params->clip_to_restricted_range = AV1_READ_BIT (br);
3310
3311 success:
3312   return GST_AV1_PARSER_OK;
3313
3314 error:
3315   GST_WARNING ("parse film grain params error %d", ret);
3316   return ret;
3317 }
3318
3319 /* 5.9.4 */
3320 static void
3321 gst_av1_mark_ref_frames (GstAV1Parser * parser, GstBitReader * br, gint idLen)
3322 {
3323   GstAV1ReferenceFrameInfo *ref_info;
3324   GstAV1SequenceHeaderOBU *seq_header;
3325   gint i, diff_len /* diffLen */ ;
3326
3327   seq_header = parser->seq_header;
3328   ref_info = &(parser->state.ref_info);
3329   diff_len = seq_header->delta_frame_id_length_minus_2 + 2;
3330
3331   for (i = 0; i < GST_AV1_NUM_REF_FRAMES; i++) {
3332     if (parser->state.current_frame_id > (1 << diff_len)) {
3333       if (ref_info->entry[i].ref_frame_id > parser->state.current_frame_id
3334           || ref_info->entry[i].ref_frame_id <
3335           (parser->state.current_frame_id - (1 << diff_len)))
3336         ref_info->entry[i].ref_valid = 0;
3337     } else {
3338       if (ref_info->entry[i].ref_frame_id > parser->state.current_frame_id
3339           && ref_info->entry[i].ref_frame_id <
3340           ((1 << idLen) + parser->state.current_frame_id - (1 << diff_len)))
3341         ref_info->entry[i].ref_valid = 0;
3342     }
3343   }
3344 }
3345
3346 /* 5.11.14 */
3347 static gboolean
3348 gst_av1_seg_feature_active_idx (GstAV1Parser * parser,
3349     GstAV1FrameHeaderOBU * frame_header, gint idx, gint feature)
3350 {
3351   return frame_header->segmentation_params.segmentation_enabled
3352       && frame_header->segmentation_params.feature_enabled[idx][feature];
3353 }
3354
3355 /* 7.12.2 */
3356 static gint
3357 gst_av1_get_qindex (GstAV1Parser * parser,
3358     GstAV1FrameHeaderOBU * frame_header, gboolean ignoreDeltaQ, gint segmentId)
3359 {
3360   gint qindex;
3361   if (gst_av1_seg_feature_active_idx (parser, frame_header, segmentId,
3362           GST_AV1_SEG_LVL_ALT_Q)) {
3363     gint data =
3364         frame_header->
3365         segmentation_params.feature_data[segmentId][GST_AV1_SEG_LVL_ALT_Q];
3366     qindex = frame_header->quantization_params.base_q_idx + data;
3367     if (ignoreDeltaQ == 0 && frame_header->quantization_params.delta_q_present)
3368       qindex = qindex + frame_header->quantization_params.delta_q_res;
3369     return CLAMP (qindex, 0, 255);
3370   } else
3371     return frame_header->quantization_params.base_q_idx;
3372 }
3373
3374 /* 7.8 */
3375 static void
3376 gst_av1_set_frame_refs (GstAV1Parser * parser,
3377     GstAV1SequenceHeaderOBU * seq_header, GstAV1FrameHeaderOBU * frame_header)
3378 {
3379   const GstAV1ReferenceFrame ref_frame_list[GST_AV1_REFS_PER_FRAME - 2] = {
3380     GST_AV1_REF_LAST2_FRAME,
3381     GST_AV1_REF_LAST3_FRAME,
3382     GST_AV1_REF_BWDREF_FRAME,
3383     GST_AV1_REF_ALTREF2_FRAME,
3384     GST_AV1_REF_ALTREF_FRAME
3385   };
3386   gboolean used_frame[GST_AV1_NUM_REF_FRAMES];
3387   gint shifted_order_hints[GST_AV1_NUM_REF_FRAMES];
3388   gint cur_frame_hint = 1 << (seq_header->order_hint_bits - 1);
3389   gint last_order_hint, earliest_order_hint;
3390   gint ref, hint;
3391   gint i, j;
3392
3393   g_assert (seq_header->enable_order_hint);
3394   g_assert (seq_header->order_hint_bits_minus_1 >= 0);
3395
3396   for (i = 0; i < GST_AV1_REFS_PER_FRAME; i++)
3397     frame_header->ref_frame_idx[i] = -1;
3398   frame_header->ref_frame_idx[GST_AV1_REF_LAST_FRAME -
3399       GST_AV1_REF_LAST_FRAME] = frame_header->last_frame_idx;
3400   frame_header->ref_frame_idx[GST_AV1_REF_GOLDEN_FRAME -
3401       GST_AV1_REF_LAST_FRAME] = frame_header->gold_frame_idx;
3402
3403   for (i = 0; i < GST_AV1_NUM_REF_FRAMES; i++)
3404     used_frame[i] = 0;
3405   used_frame[frame_header->last_frame_idx] = 1;
3406   used_frame[frame_header->gold_frame_idx] = 1;
3407
3408   for (i = 0; i < GST_AV1_NUM_REF_FRAMES; i++)
3409     shifted_order_hints[i] = cur_frame_hint +
3410         gst_av1_get_relative_dist (seq_header,
3411         parser->state.ref_info.entry[i].ref_order_hint,
3412         frame_header->order_hint);
3413
3414   last_order_hint = shifted_order_hints[frame_header->last_frame_idx];
3415
3416   /* === Backward Reference Frames === */
3417   /* The ALTREF_FRAME reference is set to be a backward
3418      reference to the frame with highest output order. */
3419   ref = -1;
3420   for (i = 0; i < GST_AV1_NUM_REF_FRAMES; i++) {
3421     hint = shifted_order_hints[i];
3422     if (!used_frame[i] && hint >= cur_frame_hint
3423         && (ref < 0 || hint >= last_order_hint)) {
3424       ref = i;
3425       last_order_hint = hint;
3426     }
3427   }
3428   if (ref >= 0) {
3429     frame_header->ref_frame_idx[GST_AV1_REF_ALTREF_FRAME -
3430         GST_AV1_REF_LAST_FRAME] = ref;
3431     used_frame[ref] = 1;
3432   }
3433
3434   /* The BWDREF_FRAME reference is set to be a backward reference
3435      to the closest frame. */
3436   ref = -1;
3437   earliest_order_hint = last_order_hint;
3438   for (i = 0; i < GST_AV1_NUM_REF_FRAMES; i++) {
3439     hint = shifted_order_hints[i];
3440     if (!used_frame[i] && hint >= cur_frame_hint
3441         && (ref < 0 || hint < earliest_order_hint)) {
3442       ref = i;
3443       earliest_order_hint = hint;
3444     }
3445   }
3446   if (ref >= 0) {
3447     frame_header->ref_frame_idx[GST_AV1_REF_BWDREF_FRAME -
3448         GST_AV1_REF_LAST_FRAME] = ref;
3449     used_frame[ref] = 1;
3450   }
3451
3452   /* The ALTREF2_FRAME reference is set to the next closest
3453      backward reference. */
3454   ref = -1;
3455   earliest_order_hint = last_order_hint;
3456   for (i = 0; i < GST_AV1_NUM_REF_FRAMES; i++) {
3457     hint = shifted_order_hints[i];
3458     if (!used_frame[i] && hint >= cur_frame_hint
3459         && (ref < 0 || hint < earliest_order_hint)) {
3460       ref = i;
3461       earliest_order_hint = hint;
3462     }
3463   }
3464   if (ref >= 0) {
3465     frame_header->ref_frame_idx[GST_AV1_REF_ALTREF2_FRAME -
3466         GST_AV1_REF_LAST_FRAME] = ref;
3467     used_frame[ref] = 1;
3468   }
3469
3470   /* === Forward Reference Frames === */
3471
3472   /* The remaining references are set to be forward references
3473      in anti-chronological order. */
3474   last_order_hint = 0;
3475   for (i = 0; i < GST_AV1_REFS_PER_FRAME - 2; i++) {
3476     GstAV1ReferenceFrame ref_frame = ref_frame_list[i];
3477     if (frame_header->ref_frame_idx[ref_frame - GST_AV1_REF_LAST_FRAME] < 0) {
3478       ref = -1;
3479       for (j = 0; j < GST_AV1_NUM_REF_FRAMES; j++) {
3480         hint = shifted_order_hints[j];
3481         if (!used_frame[j] && hint < cur_frame_hint &&
3482             (ref < 0 || hint >= last_order_hint)) {
3483           ref = j;
3484           last_order_hint = hint;
3485         }
3486       }
3487
3488       if (ref >= 0) {
3489         frame_header->ref_frame_idx[ref_frame - GST_AV1_REF_LAST_FRAME] = ref;
3490         used_frame[ref] = 1;
3491       }
3492     }
3493   }
3494
3495   /* Finally, any remaining references are set to the reference frame
3496      with smallest output order. */
3497   ref = -1;
3498   earliest_order_hint = cur_frame_hint * 2;
3499   for (i = 0; i < GST_AV1_NUM_REF_FRAMES; i++) {
3500     hint = shifted_order_hints[i];
3501     if (ref < 0 || hint < earliest_order_hint) {
3502       ref = i;
3503       earliest_order_hint = hint;
3504     }
3505   }
3506   for (i = 0; i < GST_AV1_REFS_PER_FRAME; i++)
3507     if (frame_header->ref_frame_idx[i] < 0)
3508       frame_header->ref_frame_idx[i] = ref;
3509 }
3510
3511 /* 7.21 */
3512 static void
3513 gst_av1_parser_reference_frame_loading (GstAV1Parser * parser,
3514     GstAV1FrameHeaderOBU * frame_header)
3515 {
3516   GstAV1ReferenceFrameInfo *ref_info = &(parser->state.ref_info);
3517   gint idx = frame_header->frame_to_show_map_idx;
3518   GstAV1TileInfo *ref_tile_info = &ref_info->entry[idx].ref_tile_info;
3519   const gint all_frames = (1 << GST_AV1_NUM_REF_FRAMES) - 1;
3520
3521   /* copy the relevant frame information as these will be needed by
3522    * all subclasses. */
3523   frame_header->frame_type = ref_info->entry[idx].ref_frame_type;
3524   frame_header->upscaled_width = ref_info->entry[idx].ref_upscaled_width;
3525   frame_header->frame_width = ref_info->entry[idx].ref_frame_width;
3526   frame_header->frame_height = ref_info->entry[idx].ref_frame_height;
3527   frame_header->render_width = ref_info->entry[idx].ref_render_width;
3528   frame_header->render_height = ref_info->entry[idx].ref_render_height;
3529
3530   if (parser->seq_header->film_grain_params_present)
3531     frame_header->film_grain_params =
3532         ref_info->entry[idx].ref_film_grain_params;
3533
3534   /* the remaining is only relevant to ensure proper state update and only
3535    * keyframe updates the state. */
3536   if (frame_header->frame_type != GST_AV1_KEY_FRAME)
3537     return;
3538
3539   frame_header->refresh_frame_flags = all_frames;
3540   frame_header->current_frame_id = ref_info->entry[idx].ref_frame_id;
3541   frame_header->order_hint = ref_info->entry[idx].ref_order_hint;
3542   frame_header->segmentation_params =
3543       ref_info->entry[idx].ref_segmentation_params;
3544   frame_header->global_motion_params =
3545       ref_info->entry[idx].ref_global_motion_params;
3546   frame_header->loop_filter_params = ref_info->entry[idx].ref_lf_params;
3547   frame_header->tile_info = *ref_tile_info;
3548
3549   parser->state.current_frame_id = ref_info->entry[idx].ref_frame_id;
3550   parser->state.upscaled_width = ref_info->entry[idx].ref_upscaled_width;
3551   parser->state.frame_width = ref_info->entry[idx].ref_frame_width;
3552   parser->state.frame_height = ref_info->entry[idx].ref_frame_height;
3553   parser->state.render_width = ref_info->entry[idx].ref_render_width;
3554   parser->state.render_height = ref_info->entry[idx].ref_render_height;
3555   parser->state.mi_cols = ref_info->entry[idx].ref_mi_cols;
3556   parser->state.mi_rows = ref_info->entry[idx].ref_mi_rows;
3557
3558   memcpy (parser->state.mi_col_starts, ref_tile_info->mi_col_starts,
3559       sizeof (guint32) * (GST_AV1_MAX_TILE_COLS + 1));
3560   memcpy (parser->state.mi_row_starts, ref_tile_info->mi_row_starts,
3561       sizeof (guint32) * (GST_AV1_MAX_TILE_ROWS + 1));
3562   parser->state.tile_cols_log2 = ref_tile_info->tile_cols_log2;
3563   parser->state.tile_cols = ref_tile_info->tile_cols;
3564   parser->state.tile_rows_log2 = ref_tile_info->tile_rows_log2;
3565   parser->state.tile_rows = ref_tile_info->tile_rows;
3566   parser->state.tile_size_bytes = ref_tile_info->tile_size_bytes;
3567 }
3568
3569 /* 5.9.2 */
3570 static GstAV1ParserResult
3571 gst_av1_parse_uncompressed_frame_header (GstAV1Parser * parser, GstAV1OBU * obu,
3572     GstBitReader * br, GstAV1FrameHeaderOBU * frame_header)
3573 {
3574   GstAV1ParserResult retval = GST_AV1_PARSER_OK;
3575   GstAV1ReferenceFrameInfo *ref_info;
3576   GstAV1SequenceHeaderOBU *seq_header;
3577   gint i, op_num /* opNum */ ;
3578   gint segment_id /* segmentId */ , all_frames /* allFrames */ ;
3579   gint id_len /* idLen */  = 0;
3580
3581   if (!parser->seq_header) {
3582     GST_WARNING ("Missing OBU Reference: seq_header");
3583     retval = GST_AV1_PARSER_MISSING_OBU_REFERENCE;
3584     goto error;
3585   }
3586
3587   seq_header = parser->seq_header;
3588   ref_info = &(parser->state.ref_info);
3589   if (seq_header->frame_id_numbers_present_flag)
3590     id_len = seq_header->additional_frame_id_length_minus_1 + 1 +
3591         seq_header->delta_frame_id_length_minus_2 + 2;
3592   all_frames = (1 << GST_AV1_NUM_REF_FRAMES) - 1;
3593
3594   if (seq_header->reduced_still_picture_header) {
3595     frame_header->show_existing_frame = 0;
3596     frame_header->frame_type = GST_AV1_KEY_FRAME;
3597     frame_header->frame_is_intra = 1;
3598     frame_header->show_frame = 1;
3599     frame_header->showable_frame = 0;
3600     if (parser->state.sequence_changed) {
3601       /* This is the start of a new coded video sequence. */
3602       parser->state.sequence_changed = 0;
3603       parser->state.begin_first_frame = 1;
3604     }
3605   } else {
3606     frame_header->show_existing_frame = AV1_READ_BIT_CHECKED (br, &retval);
3607     if (retval != GST_AV1_PARSER_OK)
3608       goto error;
3609
3610     if (frame_header->show_existing_frame) {
3611       if (parser->state.sequence_changed) {
3612         GST_INFO ("New sequence header starts with a show_existing_frame.");
3613         retval = GST_AV1_PARSER_BITSTREAM_ERROR;
3614         goto error;
3615       }
3616
3617       frame_header->frame_to_show_map_idx =
3618           AV1_READ_BITS_CHECKED (br, 3, &retval);
3619       if (retval != GST_AV1_PARSER_OK)
3620         goto error;
3621
3622       if (!ref_info->entry[frame_header->frame_to_show_map_idx].ref_valid) {
3623         GST_INFO ("The frame_to_show %d is invalid.",
3624             frame_header->frame_to_show_map_idx);
3625         retval = GST_AV1_PARSER_BITSTREAM_ERROR;
3626         goto error;
3627       }
3628
3629       if (seq_header->decoder_model_info_present_flag
3630           && !seq_header->timing_info.equal_picture_interval)
3631         frame_header->frame_presentation_time =
3632             AV1_READ_BITS_CHECKED (br,
3633             seq_header->
3634             decoder_model_info.frame_presentation_time_length_minus_1 + 1,
3635             &retval);
3636       if (retval != GST_AV1_PARSER_OK)
3637         goto error;
3638
3639       frame_header->refresh_frame_flags = 0;
3640       if (seq_header->frame_id_numbers_present_flag) {
3641         g_assert (id_len > 0);
3642         frame_header->display_frame_id =
3643             AV1_READ_BITS_CHECKED (br, id_len, &retval);
3644         if (retval != GST_AV1_PARSER_OK)
3645           goto error;
3646         if (frame_header->display_frame_id !=
3647             ref_info->entry[frame_header->frame_to_show_map_idx].ref_frame_id) {
3648           GST_INFO ("Reference frame ID mismatch");
3649           retval = GST_AV1_PARSER_BITSTREAM_ERROR;
3650           goto error;
3651         }
3652       }
3653
3654       gst_av1_parser_reference_frame_loading (parser, frame_header);
3655       goto success;
3656     }
3657
3658     frame_header->frame_type = AV1_READ_BITS_CHECKED (br, 2, &retval);
3659     if (retval != GST_AV1_PARSER_OK)
3660       goto error;
3661
3662     if (parser->state.sequence_changed) {
3663       if (frame_header->frame_type == GST_AV1_KEY_FRAME) {
3664         /* This is the start of a new coded video sequence. */
3665         parser->state.sequence_changed = FALSE;
3666         parser->state.begin_first_frame = TRUE;
3667       } else {
3668         GST_INFO ("Sequence header has changed without a keyframe.");
3669         retval = GST_AV1_PARSER_BITSTREAM_ERROR;
3670         goto error;
3671       }
3672     }
3673
3674     frame_header->frame_is_intra =
3675         (frame_header->frame_type == GST_AV1_INTRA_ONLY_FRAME
3676         || frame_header->frame_type == GST_AV1_KEY_FRAME);
3677
3678     frame_header->show_frame = AV1_READ_BIT_CHECKED (br, &retval);
3679     if (retval != GST_AV1_PARSER_OK)
3680       goto error;
3681
3682     if (seq_header->still_picture &&
3683         (frame_header->frame_type != GST_AV1_KEY_FRAME
3684             || !frame_header->show_frame)) {
3685       GST_INFO ("Still pictures must be coded as shown keyframes");
3686       retval = GST_AV1_PARSER_BITSTREAM_ERROR;
3687       goto error;
3688     }
3689
3690     if (frame_header->show_frame
3691         && seq_header->decoder_model_info_present_flag
3692         && !seq_header->timing_info.equal_picture_interval) {
3693       frame_header->frame_presentation_time =
3694           AV1_READ_BITS_CHECKED (br,
3695           seq_header->decoder_model_info.
3696           frame_presentation_time_length_minus_1 + 1, &retval);
3697       if (retval != GST_AV1_PARSER_OK)
3698         goto error;
3699     }
3700
3701     if (frame_header->show_frame) {
3702       frame_header->showable_frame =
3703           (frame_header->frame_type != GST_AV1_KEY_FRAME);
3704     } else {
3705       frame_header->showable_frame = AV1_READ_BIT_CHECKED (br, &retval);
3706       if (retval != GST_AV1_PARSER_OK)
3707         goto error;
3708     }
3709
3710     if (frame_header->frame_type == GST_AV1_SWITCH_FRAME
3711         || (frame_header->frame_type == GST_AV1_KEY_FRAME
3712             && frame_header->show_frame))
3713       frame_header->error_resilient_mode = 1;
3714     else {
3715       frame_header->error_resilient_mode = AV1_READ_BIT_CHECKED (br, &retval);
3716       if (retval != GST_AV1_PARSER_OK)
3717         goto error;
3718     }
3719   }
3720
3721   if (frame_header->frame_type == GST_AV1_KEY_FRAME && frame_header->show_frame) {
3722     for (i = 0; i < GST_AV1_NUM_REF_FRAMES; i++) {
3723       ref_info->entry[i].ref_valid = 0;
3724       ref_info->entry[i].ref_order_hint = 0;
3725     }
3726     for (i = 0; i < GST_AV1_REFS_PER_FRAME; i++) {
3727       frame_header->order_hints[GST_AV1_REF_LAST_FRAME + i] = 0;
3728     }
3729   }
3730
3731   frame_header->disable_cdf_update = AV1_READ_BIT_CHECKED (br, &retval);
3732   if (retval != GST_AV1_PARSER_OK)
3733     goto error;
3734
3735   if (seq_header->seq_force_screen_content_tools ==
3736       GST_AV1_SELECT_SCREEN_CONTENT_TOOLS) {
3737     frame_header->allow_screen_content_tools =
3738         AV1_READ_BIT_CHECKED (br, &retval);
3739     if (retval != GST_AV1_PARSER_OK)
3740       goto error;
3741   } else {
3742     frame_header->allow_screen_content_tools =
3743         seq_header->seq_force_screen_content_tools;
3744   }
3745
3746   if (frame_header->allow_screen_content_tools) {
3747     if (seq_header->seq_force_integer_mv == GST_AV1_SELECT_INTEGER_MV) {
3748       frame_header->force_integer_mv = AV1_READ_BIT_CHECKED (br, &retval);
3749       if (retval != GST_AV1_PARSER_OK)
3750         goto error;
3751     } else {
3752       frame_header->force_integer_mv = seq_header->seq_force_integer_mv;
3753     }
3754   } else {
3755     frame_header->force_integer_mv = 0;
3756   }
3757
3758   if (frame_header->frame_is_intra) {
3759     frame_header->force_integer_mv = 1;
3760   }
3761
3762   if (seq_header->frame_id_numbers_present_flag) {
3763     gboolean have_prev_frame_id =
3764         !parser->state.begin_first_frame &&
3765         (!(frame_header->frame_type == GST_AV1_KEY_FRAME
3766             && frame_header->show_frame));
3767     if (have_prev_frame_id)
3768       parser->state.prev_frame_id = parser->state.current_frame_id;
3769
3770     g_assert (id_len > 0);
3771     frame_header->current_frame_id =
3772         AV1_READ_BITS_CHECKED (br, id_len, &retval);
3773     if (retval != GST_AV1_PARSER_OK)
3774       goto error;
3775
3776     parser->state.current_frame_id = frame_header->current_frame_id;
3777     /* Check whether the id and id diff is valid */
3778     if (have_prev_frame_id) {
3779       gint32 diff_frame_id;
3780       if (parser->state.current_frame_id > parser->state.prev_frame_id) {
3781         diff_frame_id =
3782             parser->state.current_frame_id - parser->state.prev_frame_id;
3783       } else {
3784         diff_frame_id = (1 << id_len) +
3785             parser->state.current_frame_id - parser->state.prev_frame_id;
3786       }
3787       if (parser->state.current_frame_id == parser->state.prev_frame_id ||
3788           diff_frame_id >= (1 << (id_len - 1))) {
3789         GST_INFO ("Invalid value of current_frame_id");
3790         retval = GST_AV1_PARSER_BITSTREAM_ERROR;
3791         goto error;
3792       }
3793     }
3794
3795     gst_av1_mark_ref_frames (parser, br, id_len);
3796   } else {
3797     frame_header->current_frame_id = 0;
3798     parser->state.prev_frame_id = parser->state.current_frame_id;
3799     parser->state.current_frame_id = frame_header->current_frame_id;
3800   }
3801
3802   if (frame_header->frame_type == GST_AV1_SWITCH_FRAME) {
3803     frame_header->frame_size_override_flag = 1;
3804   } else if (seq_header->reduced_still_picture_header) {
3805     frame_header->frame_size_override_flag = 0;
3806   } else {
3807     frame_header->frame_size_override_flag = AV1_READ_BIT_CHECKED (br, &retval);
3808     if (retval != GST_AV1_PARSER_OK)
3809       goto error;
3810   }
3811
3812   frame_header->order_hint =
3813       AV1_READ_BITS_CHECKED (br, seq_header->order_hint_bits_minus_1 + 1,
3814       &retval);
3815   if (retval != GST_AV1_PARSER_OK)
3816     goto error;
3817
3818   if (frame_header->frame_is_intra || frame_header->error_resilient_mode) {
3819     frame_header->primary_ref_frame = GST_AV1_PRIMARY_REF_NONE;
3820   } else {
3821     frame_header->primary_ref_frame = AV1_READ_BITS_CHECKED (br, 3, &retval);
3822     if (retval != GST_AV1_PARSER_OK)
3823       goto error;
3824   }
3825
3826   if (seq_header->decoder_model_info_present_flag) {
3827     frame_header->buffer_removal_time_present_flag =
3828         AV1_READ_BIT_CHECKED (br, &retval);
3829     if (retval != GST_AV1_PARSER_OK)
3830       goto error;
3831
3832     if (frame_header->buffer_removal_time_present_flag) {
3833       for (op_num = 0; op_num <= seq_header->operating_points_cnt_minus_1;
3834           op_num++) {
3835         if (seq_header->
3836             operating_points[op_num].decoder_model_present_for_this_op) {
3837           gint op_pt_idc = seq_header->operating_points[op_num].idc;
3838           gint in_temporal_layer =
3839               (op_pt_idc >> obu->header.obu_temporal_id) & 1;
3840           gint in_spatial_layer =
3841               (op_pt_idc >> (obu->header.obu_spatial_id + 8)) & 1;
3842           if (op_pt_idc == 0 || (in_temporal_layer && in_spatial_layer)) {
3843             frame_header->buffer_removal_time[op_num] =
3844                 AV1_READ_BITS_CHECKED (br,
3845                 seq_header->decoder_model_info.
3846                 buffer_removal_time_length_minus_1 + 1, &retval);
3847             if (retval != GST_AV1_PARSER_OK)
3848               goto error;
3849           } else {
3850             frame_header->buffer_removal_time[op_num] = 0;
3851           }
3852         } else {
3853           frame_header->buffer_removal_time[op_num] = 0;
3854         }
3855       }
3856     }
3857   }
3858
3859   frame_header->allow_high_precision_mv = 0;
3860   frame_header->use_ref_frame_mvs = 0;
3861   frame_header->allow_intrabc = 0;
3862   if (frame_header->frame_type == GST_AV1_SWITCH_FRAME ||
3863       (frame_header->frame_type == GST_AV1_KEY_FRAME
3864           && frame_header->show_frame)) {
3865     frame_header->refresh_frame_flags = all_frames;
3866   } else {
3867     frame_header->refresh_frame_flags = AV1_READ_UINT8_CHECKED (br, &retval);
3868     if (retval != GST_AV1_PARSER_OK)
3869       goto error;
3870   }
3871   if (frame_header->frame_type == GST_AV1_INTRA_ONLY_FRAME) {
3872     if (frame_header->refresh_frame_flags == 0xFF) {
3873       GST_INFO ("Intra only frames cannot have refresh flags 0xFF");
3874       retval = GST_AV1_PARSER_BITSTREAM_ERROR;
3875       goto error;
3876     }
3877   }
3878
3879   if (!frame_header->frame_is_intra
3880       || frame_header->refresh_frame_flags != all_frames) {
3881     if (frame_header->error_resilient_mode && seq_header->enable_order_hint) {
3882       for (i = 0; i < GST_AV1_NUM_REF_FRAMES; i++) {
3883         frame_header->ref_order_hint[i] = AV1_READ_BITS_CHECKED (br,
3884             seq_header->order_hint_bits_minus_1 + 1, &retval);
3885         if (retval != GST_AV1_PARSER_OK)
3886           goto error;
3887
3888         if (frame_header->ref_order_hint[i] !=
3889             ref_info->entry[i].ref_order_hint)
3890           ref_info->entry[i].ref_valid = 0;
3891       }
3892     }
3893   }
3894
3895   if (frame_header->frame_is_intra) {
3896     retval = gst_av1_parse_frame_size (parser, br, frame_header);
3897     if (retval != GST_AV1_PARSER_OK)
3898       goto error;
3899     retval = gst_av1_parse_render_size (parser, br, frame_header);
3900     if (retval != GST_AV1_PARSER_OK)
3901       goto error;
3902     if (frame_header->allow_screen_content_tools
3903         && parser->state.upscaled_width == parser->state.frame_width) {
3904       frame_header->allow_intrabc = AV1_READ_BIT_CHECKED (br, &retval);
3905       if (retval != GST_AV1_PARSER_OK)
3906         goto error;
3907     }
3908
3909     frame_header->upscaled_width = parser->state.upscaled_width;
3910     frame_header->frame_width = parser->state.frame_width;
3911     frame_header->frame_height = parser->state.frame_height;
3912     frame_header->render_width = parser->state.render_width;
3913     frame_header->render_height = parser->state.render_height;
3914   } else {
3915     if (!seq_header->enable_order_hint) {
3916       frame_header->frame_refs_short_signaling = 0;
3917     } else {
3918       frame_header->frame_refs_short_signaling =
3919           AV1_READ_BIT_CHECKED (br, &retval);
3920       if (retval != GST_AV1_PARSER_OK)
3921         goto error;
3922
3923       if (frame_header->frame_refs_short_signaling) {
3924         if (AV1_REMAINING_BITS (br) < 3 + 3) {
3925           retval = GST_AV1_PARSER_NO_MORE_DATA;
3926           goto error;
3927         }
3928         frame_header->last_frame_idx = AV1_READ_BITS (br, 3);
3929         frame_header->gold_frame_idx = AV1_READ_BITS (br, 3);
3930         gst_av1_set_frame_refs (parser, seq_header, frame_header);
3931       }
3932     }
3933
3934     for (i = 0; i < GST_AV1_REFS_PER_FRAME; i++) {
3935       if (!frame_header->frame_refs_short_signaling) {
3936         frame_header->ref_frame_idx[i] = AV1_READ_BITS_CHECKED (br, 3, &retval);
3937         if (retval != GST_AV1_PARSER_OK)
3938           goto error;
3939       }
3940
3941       if (seq_header->frame_id_numbers_present_flag) {
3942         gint32 delta_frame_id /* DeltaFrameId */ ;
3943         gint32 expected_frame_id;
3944         guint32 delta_frame_id_minus_1;
3945
3946         g_assert (id_len > 0);
3947
3948         delta_frame_id_minus_1 = AV1_READ_BITS_CHECKED (br,
3949             seq_header->delta_frame_id_length_minus_2 + 2, &retval);
3950         if (retval != GST_AV1_PARSER_OK)
3951           goto error;
3952
3953         delta_frame_id = delta_frame_id_minus_1 + 1;
3954         expected_frame_id = (frame_header->current_frame_id + (1 << id_len) -
3955             delta_frame_id) % (1 << id_len);
3956         if (expected_frame_id !=
3957             parser->state.ref_info.entry[frame_header->
3958                 ref_frame_idx[i]].ref_frame_id) {
3959           GST_INFO ("Reference buffer frame ID mismatch, expectedFrameId"
3960               " is %d wihle ref frame id is %d", expected_frame_id,
3961               parser->state.ref_info.entry[frame_header->
3962                   ref_frame_idx[i]].ref_frame_id);
3963           retval = GST_AV1_PARSER_BITSTREAM_ERROR;
3964           goto error;
3965         }
3966       }
3967     }
3968
3969     if (frame_header->frame_size_override_flag
3970         && !frame_header->error_resilient_mode) {
3971       retval = gst_av1_parse_frame_size_with_refs (parser, br, frame_header);
3972       if (retval != GST_AV1_PARSER_OK)
3973         goto error;
3974     } else {
3975       retval = gst_av1_parse_frame_size (parser, br, frame_header);
3976       if (retval != GST_AV1_PARSER_OK)
3977         goto error;
3978       retval = gst_av1_parse_render_size (parser, br, frame_header);
3979       if (retval != GST_AV1_PARSER_OK)
3980         goto error;
3981     }
3982     frame_header->upscaled_width = parser->state.upscaled_width;
3983     frame_header->frame_width = parser->state.frame_width;
3984     frame_header->frame_height = parser->state.frame_height;
3985     frame_header->render_width = parser->state.render_width;
3986     frame_header->render_height = parser->state.render_height;
3987
3988     if (frame_header->force_integer_mv) {
3989       frame_header->allow_high_precision_mv = 0;
3990     } else {
3991       frame_header->allow_high_precision_mv =
3992           AV1_READ_BIT_CHECKED (br, &retval);
3993       if (retval != GST_AV1_PARSER_OK)
3994         goto error;
3995     }
3996
3997     /* read_interpolation_filter() expand */
3998     frame_header->is_filter_switchable = AV1_READ_BIT_CHECKED (br, &retval);
3999     if (retval != GST_AV1_PARSER_OK)
4000       goto error;
4001
4002     if (frame_header->is_filter_switchable) {
4003       frame_header->interpolation_filter =
4004           GST_AV1_INTERPOLATION_FILTER_SWITCHABLE;
4005     } else {
4006       frame_header->interpolation_filter =
4007           AV1_READ_BITS_CHECKED (br, 2, &retval);
4008       if (retval != GST_AV1_PARSER_OK)
4009         goto error;
4010     }
4011
4012     frame_header->is_motion_mode_switchable =
4013         AV1_READ_BIT_CHECKED (br, &retval);
4014     if (retval != GST_AV1_PARSER_OK)
4015       goto error;
4016
4017     if (frame_header->error_resilient_mode || !seq_header->enable_ref_frame_mvs) {
4018       frame_header->use_ref_frame_mvs = 0;
4019     } else {
4020       frame_header->use_ref_frame_mvs = AV1_READ_BIT_CHECKED (br, &retval);
4021       if (retval != GST_AV1_PARSER_OK)
4022         goto error;
4023     }
4024   }
4025
4026   if (!frame_header->frame_is_intra) {
4027     for (i = 0; i < GST_AV1_REFS_PER_FRAME; i++) {
4028       gint refFrame = GST_AV1_REF_LAST_FRAME + i;
4029       gint hint =
4030           ref_info->entry[frame_header->ref_frame_idx[i]].ref_order_hint;
4031       frame_header->order_hints[refFrame] = hint;
4032       if (!seq_header->enable_order_hint) {
4033         frame_header->ref_frame_sign_bias[refFrame] = 0;
4034       } else {
4035         frame_header->ref_frame_sign_bias[refFrame] =
4036             (gst_av1_get_relative_dist (parser->seq_header, hint,
4037                 frame_header->order_hint) > 0);
4038       }
4039     }
4040   }
4041
4042   if (seq_header->reduced_still_picture_header
4043       || frame_header->disable_cdf_update)
4044     frame_header->disable_frame_end_update_cdf = 1;
4045   else {
4046     frame_header->disable_frame_end_update_cdf =
4047         AV1_READ_BIT_CHECKED (br, &retval);
4048     if (retval != GST_AV1_PARSER_OK)
4049       goto error;
4050   }
4051
4052   if (frame_header->primary_ref_frame != GST_AV1_PRIMARY_REF_NONE &&
4053       !ref_info->entry[frame_header->ref_frame_idx[frame_header->
4054               primary_ref_frame]].ref_valid) {
4055     GST_INFO ("Primary ref point to an invalid frame");
4056     retval = GST_AV1_PARSER_BITSTREAM_ERROR;
4057     goto error;
4058   }
4059
4060   if (frame_header->primary_ref_frame == GST_AV1_PRIMARY_REF_NONE) {
4061     /* do something in setup_past_independence() of parser level */
4062     gint8 *loop_filter_ref_deltas =
4063         frame_header->loop_filter_params.loop_filter_ref_deltas;
4064
4065     frame_header->loop_filter_params.loop_filter_delta_enabled = 1;
4066     loop_filter_ref_deltas[GST_AV1_REF_INTRA_FRAME] = 1;
4067     loop_filter_ref_deltas[GST_AV1_REF_LAST_FRAME] = 0;
4068     loop_filter_ref_deltas[GST_AV1_REF_LAST2_FRAME] = 0;
4069     loop_filter_ref_deltas[GST_AV1_REF_LAST3_FRAME] = 0;
4070     loop_filter_ref_deltas[GST_AV1_REF_BWDREF_FRAME] = 0;
4071     loop_filter_ref_deltas[GST_AV1_REF_GOLDEN_FRAME] = -1;
4072     loop_filter_ref_deltas[GST_AV1_REF_ALTREF_FRAME] = -1;
4073     loop_filter_ref_deltas[GST_AV1_REF_ALTREF2_FRAME] = -1;
4074     frame_header->loop_filter_params.loop_filter_mode_deltas[0] = 0;
4075     frame_header->loop_filter_params.loop_filter_mode_deltas[1] = 0;
4076   } else {
4077     /* do something in load_previous() of parser level */
4078     /*   load_loop_filter_params() */
4079     GstAV1LoopFilterParams *ref_lf_params =
4080         &parser->state.ref_info.entry[frame_header->
4081         ref_frame_idx[frame_header->primary_ref_frame]].ref_lf_params;
4082     gint8 *loop_filter_ref_deltas =
4083         frame_header->loop_filter_params.loop_filter_ref_deltas;
4084
4085     /* Copy all from prime_ref */
4086     g_assert (parser->state.ref_info.
4087         entry[frame_header->ref_frame_idx[frame_header->primary_ref_frame]].
4088         ref_valid);
4089     loop_filter_ref_deltas[GST_AV1_REF_INTRA_FRAME] =
4090         ref_lf_params->loop_filter_ref_deltas[GST_AV1_REF_INTRA_FRAME];
4091     loop_filter_ref_deltas[GST_AV1_REF_LAST_FRAME] =
4092         ref_lf_params->loop_filter_ref_deltas[GST_AV1_REF_LAST_FRAME];
4093     loop_filter_ref_deltas[GST_AV1_REF_LAST2_FRAME] =
4094         ref_lf_params->loop_filter_ref_deltas[GST_AV1_REF_LAST2_FRAME];
4095     loop_filter_ref_deltas[GST_AV1_REF_LAST3_FRAME] =
4096         ref_lf_params->loop_filter_ref_deltas[GST_AV1_REF_LAST3_FRAME];
4097     loop_filter_ref_deltas[GST_AV1_REF_BWDREF_FRAME] =
4098         ref_lf_params->loop_filter_ref_deltas[GST_AV1_REF_BWDREF_FRAME];
4099     loop_filter_ref_deltas[GST_AV1_REF_GOLDEN_FRAME] =
4100         ref_lf_params->loop_filter_ref_deltas[GST_AV1_REF_GOLDEN_FRAME];
4101     loop_filter_ref_deltas[GST_AV1_REF_ALTREF2_FRAME] =
4102         ref_lf_params->loop_filter_ref_deltas[GST_AV1_REF_ALTREF2_FRAME];
4103     loop_filter_ref_deltas[GST_AV1_REF_ALTREF_FRAME] =
4104         ref_lf_params->loop_filter_ref_deltas[GST_AV1_REF_ALTREF_FRAME];
4105     for (i = 0; i < 2; i++)
4106       frame_header->loop_filter_params.loop_filter_mode_deltas[i] =
4107           ref_lf_params->loop_filter_mode_deltas[i];
4108   }
4109
4110   /* @TODO:
4111      if ( primary_ref_frame == PRIMARY_REF_NONE ) {
4112      init_non_coeff_cdfs( )
4113      } else {
4114      load_cdfs( ref_frame_idx[primary_ref_frame] )
4115      }
4116    */
4117   /* @TODO:
4118      if ( use_ref_frame_mvs == 1 )
4119      motion_field_estimation( )
4120    */
4121
4122   retval = gst_av1_parse_tile_info (parser, br, frame_header);
4123   if (retval != GST_AV1_PARSER_OK)
4124     goto error;
4125
4126   retval = gst_av1_parse_quantization_params (parser, br, frame_header);
4127   if (retval != GST_AV1_PARSER_OK)
4128     goto error;
4129
4130   retval = gst_av1_parse_segmentation_params (parser, br, frame_header);
4131   if (retval != GST_AV1_PARSER_OK)
4132     goto error;
4133
4134   retval = gst_av1_parse_delta_q_params (parser, br,
4135       &(frame_header->quantization_params));
4136   if (retval != GST_AV1_PARSER_OK)
4137     goto error;
4138
4139   retval = gst_av1_parse_delta_lf_params (parser, br, frame_header);
4140   if (retval != GST_AV1_PARSER_OK)
4141     goto error;
4142
4143   /* @TODO:
4144      if ( primary_ref_frame == PRIMARY_REF_NONE ) {
4145      init_coeff_cdfs( )
4146      } else {
4147      load_previous_segment_ids( )
4148      }
4149    */
4150
4151   frame_header->coded_lossless = 1;
4152   for (segment_id = 0; segment_id < GST_AV1_MAX_SEGMENTS; segment_id++) {
4153     gint qindex = gst_av1_get_qindex (parser, frame_header, 1, segment_id);
4154     frame_header->lossless_array[segment_id] = (qindex == 0)
4155         && (frame_header->quantization_params.delta_q_y_dc == 0)
4156         && (frame_header->quantization_params.delta_q_u_ac == 0)
4157         && (frame_header->quantization_params.delta_q_u_dc == 0)
4158         && (frame_header->quantization_params.delta_q_v_ac == 0)
4159         && (frame_header->quantization_params.delta_q_v_dc == 0);
4160     if (!frame_header->lossless_array[segment_id])
4161       frame_header->coded_lossless = 0;
4162     if (frame_header->quantization_params.using_qmatrix) {
4163       if (frame_header->lossless_array[segment_id]) {
4164         frame_header->seg_qm_Level[0][segment_id] = 15;
4165         frame_header->seg_qm_Level[1][segment_id] = 15;
4166         frame_header->seg_qm_Level[2][segment_id] = 15;
4167       } else {
4168         frame_header->seg_qm_Level[0][segment_id] =
4169             frame_header->quantization_params.qm_y;
4170         frame_header->seg_qm_Level[1][segment_id] =
4171             frame_header->quantization_params.qm_u;
4172         frame_header->seg_qm_Level[2][segment_id] =
4173             frame_header->quantization_params.qm_v;
4174       }
4175     }
4176   }
4177   frame_header->all_lossless = frame_header->coded_lossless
4178       && (parser->state.frame_width == parser->state.upscaled_width);
4179
4180   retval = gst_av1_parse_loop_filter_params (parser, br, frame_header);
4181   if (retval != GST_AV1_PARSER_OK)
4182     goto error;
4183
4184   retval = gst_av1_parse_cdef_params (parser, br, frame_header);
4185   if (retval != GST_AV1_PARSER_OK)
4186     goto error;
4187
4188   retval = gst_av1_parse_loop_restoration_params (parser, br, frame_header);
4189   if (retval != GST_AV1_PARSER_OK)
4190     goto error;
4191
4192   retval = gst_av1_parse_tx_mode (parser, br, frame_header);
4193   if (retval != GST_AV1_PARSER_OK)
4194     goto error;
4195
4196   /* 5.9.23 inlined frame_reference_mode () */
4197   if (frame_header->frame_is_intra) {
4198     frame_header->reference_select = 0;
4199   } else {
4200     frame_header->reference_select = AV1_READ_BIT_CHECKED (br, &retval);
4201     if (retval != GST_AV1_PARSER_OK)
4202       goto error;
4203   }
4204
4205   retval = gst_av1_parse_skip_mode_params (parser, br, frame_header);
4206   if (retval != GST_AV1_PARSER_OK)
4207     goto error;
4208
4209   if (frame_header->frame_is_intra ||
4210       frame_header->error_resilient_mode || !seq_header->enable_warped_motion)
4211     frame_header->allow_warped_motion = 0;
4212   else {
4213     frame_header->allow_warped_motion = AV1_READ_BIT_CHECKED (br, &retval);
4214     if (retval != GST_AV1_PARSER_OK)
4215       goto error;
4216   }
4217
4218   frame_header->reduced_tx_set = AV1_READ_BIT_CHECKED (br, &retval);
4219   if (retval != GST_AV1_PARSER_OK)
4220     goto error;
4221
4222   retval = gst_av1_parse_global_motion_params (parser, br, frame_header);
4223   if (retval != GST_AV1_PARSER_OK)
4224     goto error;
4225
4226   retval = gst_av1_parse_film_grain_params (parser, br, frame_header);
4227   if (retval != GST_AV1_PARSER_OK)
4228     goto error;
4229
4230 success:
4231   return GST_AV1_PARSER_OK;
4232
4233 error:
4234   GST_WARNING ("parse uncompressed frame header error %d", retval);
4235   return retval;
4236 }
4237
4238 /**
4239  * gst_av1_parser_reference_frame_update:
4240  * @parser: the #GstAV1Parser
4241  * @frame_header: a #GstAV1FrameHeaderOBU to load
4242  *
4243  * Update the context of @frame_header to parser's state. This function is
4244  * used when we finish one frame's decoding/showing, and need to update info
4245  * such as reference, global parameters.
4246  *
4247  * Returns: The #GstAV1ParserResult.
4248  *
4249  * Since: 1.18
4250  */
4251 GstAV1ParserResult
4252 gst_av1_parser_reference_frame_update (GstAV1Parser * parser,
4253     GstAV1FrameHeaderOBU * frame_header)
4254 {
4255   gint i;
4256   GstAV1SequenceHeaderOBU *seq_header;
4257   GstAV1ReferenceFrameInfo *ref_info;
4258
4259   g_return_val_if_fail (parser != NULL, GST_AV1_PARSER_INVALID_OPERATION);
4260   g_return_val_if_fail (frame_header != NULL, GST_AV1_PARSER_INVALID_OPERATION);
4261
4262   if (!parser->seq_header) {
4263     GST_WARNING ("Missing OBU Reference: seq_header");
4264     return GST_AV1_PARSER_MISSING_OBU_REFERENCE;
4265   }
4266
4267   seq_header = parser->seq_header;
4268   ref_info = &(parser->state.ref_info);
4269   if (frame_header->frame_type == GST_AV1_INTRA_ONLY_FRAME
4270       && frame_header->refresh_frame_flags == 0xff)
4271     return GST_AV1_PARSER_BITSTREAM_ERROR;
4272
4273   for (i = 0; i < GST_AV1_NUM_REF_FRAMES; i++) {
4274     if ((frame_header->refresh_frame_flags >> i) & 1) {
4275       ref_info->entry[i].ref_valid = 1;
4276       ref_info->entry[i].ref_frame_id = frame_header->current_frame_id;
4277       ref_info->entry[i].ref_frame_type = frame_header->frame_type;
4278       ref_info->entry[i].ref_upscaled_width = frame_header->upscaled_width;
4279       ref_info->entry[i].ref_frame_width = frame_header->frame_width;
4280       ref_info->entry[i].ref_frame_height = frame_header->frame_height;
4281       ref_info->entry[i].ref_render_width = frame_header->render_width;
4282       ref_info->entry[i].ref_render_height = frame_header->render_height;
4283       ref_info->entry[i].ref_order_hint = frame_header->order_hint;
4284       ref_info->entry[i].ref_mi_cols = parser->state.mi_cols;
4285       ref_info->entry[i].ref_mi_rows = parser->state.mi_rows;
4286       ref_info->entry[i].ref_subsampling_x =
4287           seq_header->color_config.subsampling_x;
4288       ref_info->entry[i].ref_subsampling_y =
4289           seq_header->color_config.subsampling_y;
4290       ref_info->entry[i].ref_bit_depth = seq_header->bit_depth;
4291       ref_info->entry[i].ref_segmentation_params =
4292           frame_header->segmentation_params;
4293       ref_info->entry[i].ref_global_motion_params =
4294           frame_header->global_motion_params;
4295       ref_info->entry[i].ref_lf_params = frame_header->loop_filter_params;
4296       ref_info->entry[i].ref_tile_info = frame_header->tile_info;
4297       if (seq_header->film_grain_params_present)
4298         ref_info->entry[i].ref_film_grain_params =
4299             frame_header->film_grain_params;
4300     }
4301   }
4302
4303   return GST_AV1_PARSER_OK;
4304 }
4305
4306 /* 5.12.1 */
4307 /**
4308  * gst_av1_parser_parse_tile_list_obu:
4309  * @parser: the #GstAV1Parser
4310  * @obu: a #GstAV1OBU to be parsed
4311  * @tile_list: a #GstAV1TileListOBU to store the parsed result.
4312  *
4313  * Parse one tile list @obu based on the @parser context, store the result
4314  * in the @tile_list. It is for large scale tile coding mode.
4315  *
4316  * Returns: The #GstAV1ParserResult.
4317  *
4318  * Since: 1.18
4319  */
4320 GstAV1ParserResult
4321 gst_av1_parser_parse_tile_list_obu (GstAV1Parser * parser,
4322     GstAV1OBU * obu, GstAV1TileListOBU * tile_list)
4323 {
4324   GstAV1ParserResult retval = GST_AV1_PARSER_OK;
4325   GstBitReader *br;
4326   GstBitReader bitreader;
4327   gint tile;
4328
4329   g_return_val_if_fail (parser != NULL, GST_AV1_PARSER_INVALID_OPERATION);
4330   g_return_val_if_fail (obu != NULL, GST_AV1_PARSER_INVALID_OPERATION);
4331   g_return_val_if_fail (obu->obu_type == GST_AV1_OBU_TILE_LIST,
4332       GST_AV1_PARSER_INVALID_OPERATION);
4333   g_return_val_if_fail (tile_list != NULL, GST_AV1_PARSER_INVALID_OPERATION);
4334
4335   br = &bitreader;
4336   memset (tile_list, 0, sizeof (*tile_list));
4337   gst_bit_reader_init (br, obu->data, obu->obu_size);
4338   if (AV1_REMAINING_BITS (br) < 8 + 8 + 16) {
4339     retval = GST_AV1_PARSER_NO_MORE_DATA;
4340     goto error;
4341   }
4342
4343   tile_list->output_frame_width_in_tiles_minus_1 = AV1_READ_BITS (br, 8);
4344   tile_list->output_frame_height_in_tiles_minus_1 = AV1_READ_BITS (br, 8);
4345   tile_list->tile_count_minus_1 = AV1_READ_BITS (br, 16);
4346   for (tile = 0; tile <= tile_list->tile_count_minus_1; tile++) {
4347     if (AV1_REMAINING_BITS (br) < 8 + 8 + 8 + 16) {
4348       retval = GST_AV1_PARSER_NO_MORE_DATA;
4349       goto error;
4350     }
4351     tile_list->entry[tile].anchor_frame_idx = AV1_READ_BITS (br, 8);
4352     tile_list->entry[tile].anchor_tile_row = AV1_READ_BITS (br, 8);
4353     tile_list->entry[tile].anchor_tile_col = AV1_READ_BITS (br, 8);
4354     tile_list->entry[tile].tile_data_size_minus_1 = AV1_READ_BITS (br, 16);
4355
4356     g_assert (gst_bit_reader_get_pos (br) % 8 == 0);
4357
4358     tile_list->entry[tile].coded_tile_data =
4359         obu->data + gst_bit_reader_get_pos (br) / 8;
4360     /* skip the coded_tile_data */
4361     if (!gst_bit_reader_skip (br,
4362             tile_list->entry[tile].tile_data_size_minus_1 + 1)) {
4363       retval = GST_AV1_PARSER_NO_MORE_DATA;
4364       goto error;
4365     }
4366   }
4367
4368   retval = av1_skip_trailing_bits (parser, br, obu);
4369   if (retval != GST_AV1_PARSER_OK)
4370     goto error;
4371
4372   return GST_AV1_PARSER_OK;
4373
4374 error:
4375   GST_WARNING ("parse tile list error %d", retval);
4376   return retval;
4377 }
4378
4379 /* 5.11.1 */
4380 static GstAV1ParserResult
4381 gst_av1_parse_tile_group (GstAV1Parser * parser, GstBitReader * br,
4382     GstAV1TileGroupOBU * tile_group)
4383 {
4384   GstAV1ParserResult retval = GST_AV1_PARSER_OK;
4385   gint tile_num /* TileNum */ , end_bit_pos /* endBitPos */ ;
4386   gint header_bytes /* headerBytes */ , start_bitpos /* startBitPos */ ;
4387   guint32 sz = AV1_REMAINING_BYTES (br);
4388   guint32 tile_row /* tileRow */ ;
4389   guint32 tile_col /* tileCol */ ;
4390   guint32 tile_size /* tileSize */ ;
4391
4392   memset (tile_group, 0, sizeof (*tile_group));
4393   tile_group->num_tiles = parser->state.tile_cols * parser->state.tile_rows;
4394   start_bitpos = gst_bit_reader_get_pos (br);
4395   tile_group->tile_start_and_end_present_flag = 0;
4396
4397   if (tile_group->num_tiles > 1) {
4398     tile_group->tile_start_and_end_present_flag =
4399         AV1_READ_BIT_CHECKED (br, &retval);
4400     if (retval != GST_AV1_PARSER_OK)
4401       goto error;
4402   }
4403   if (tile_group->num_tiles == 1
4404       || !tile_group->tile_start_and_end_present_flag) {
4405     tile_group->tg_start = 0;
4406     tile_group->tg_end = tile_group->num_tiles - 1;
4407   } else {
4408     gint tileBits = parser->state.tile_cols_log2 + parser->state.tile_rows_log2;
4409     tile_group->tg_start = AV1_READ_BITS_CHECKED (br, tileBits, &retval);
4410     if (retval != GST_AV1_PARSER_OK)
4411       goto error;
4412
4413     tile_group->tg_end = AV1_READ_BITS_CHECKED (br, tileBits, &retval);
4414     if (retval != GST_AV1_PARSER_OK)
4415       goto error;
4416   }
4417
4418   if (tile_group->tg_end < tile_group->tg_start) {
4419     retval = GST_AV1_PARSER_NO_MORE_DATA;
4420     goto error;
4421   }
4422
4423   if (!gst_bit_reader_skip_to_byte (br)) {
4424     retval = GST_AV1_PARSER_NO_MORE_DATA;
4425     goto error;
4426   }
4427
4428   end_bit_pos = gst_bit_reader_get_pos (br);
4429   header_bytes = (end_bit_pos - start_bitpos) / 8;
4430   sz -= header_bytes;
4431
4432   for (tile_num = tile_group->tg_start; tile_num <= tile_group->tg_end;
4433       tile_num++) {
4434     tile_row = tile_num / parser->state.tile_cols;
4435     tile_col = tile_num % parser->state.tile_cols;
4436     /* if last tile */
4437     if (tile_num == tile_group->tg_end) {
4438       tile_size = sz;
4439     } else {
4440       gint tile_size_minus_1 = av1_bitstreamfn_le (br,
4441           parser->state.tile_size_bytes, &retval);
4442       if (retval != GST_AV1_PARSER_OK)
4443         goto error;
4444       tile_size = tile_size_minus_1 + 1;
4445       sz -= (tile_size + parser->state.tile_size_bytes);
4446     }
4447
4448     tile_group->entry[tile_num].tile_size = tile_size;
4449     tile_group->entry[tile_num].tile_offset = gst_bit_reader_get_pos (br) / 8;
4450     tile_group->entry[tile_num].tile_row = tile_row;
4451     tile_group->entry[tile_num].tile_col = tile_col;
4452
4453     tile_group->entry[tile_num].mi_row_start =
4454         parser->state.mi_row_starts[tile_row];
4455     tile_group->entry[tile_num].mi_row_end =
4456         parser->state.mi_row_starts[tile_row + 1];
4457     tile_group->entry[tile_num].mi_col_start =
4458         parser->state.mi_col_starts[tile_col];
4459     tile_group->entry[tile_num].mi_col_end =
4460         parser->state.mi_col_starts[tile_col + 1];
4461     /* Not implement here, the real decoder process
4462        init_symbol( tileSize )
4463        decode_tile( )
4464        exit_symbol( )
4465      */
4466
4467     /* Skip the real data to the next one */
4468     if (tile_num < tile_group->tg_end &&
4469         !gst_bit_reader_skip (br, tile_size * 8)) {
4470       retval = GST_AV1_PARSER_NO_MORE_DATA;
4471       goto error;
4472     }
4473   }
4474
4475   if (tile_group->tg_end == tile_group->num_tiles - 1) {
4476     /* Not implement here, the real decoder process
4477        if ( !disable_frame_end_update_cdf ) {
4478        frame_end_update_cdf( )
4479        }
4480        decode_frame_wrapup( )
4481      */
4482     parser->state.seen_frame_header = 0;
4483   }
4484
4485   return GST_AV1_PARSER_OK;
4486
4487 error:
4488   GST_WARNING ("parse tile group error %d", retval);
4489   return retval;
4490 }
4491
4492 /**
4493  * gst_av1_parser_parse_tile_group_obu:
4494  * @parser: the #GstAV1Parser
4495  * @obu: a #GstAV1OBU to be parsed
4496  * @tile_group: a #GstAV1TileGroupOBU to store the parsed result.
4497  *
4498  * Parse one tile group @obu based on the @parser context, store the result
4499  * in the @tile_group.
4500  *
4501  * Returns: The #GstAV1ParserResult.
4502  *
4503  * Since: 1.18
4504  */
4505 GstAV1ParserResult
4506 gst_av1_parser_parse_tile_group_obu (GstAV1Parser * parser, GstAV1OBU * obu,
4507     GstAV1TileGroupOBU * tile_group)
4508 {
4509   GstAV1ParserResult ret;
4510   GstBitReader bit_reader;
4511
4512   g_return_val_if_fail (parser != NULL, GST_AV1_PARSER_INVALID_OPERATION);
4513   g_return_val_if_fail (obu != NULL, GST_AV1_PARSER_INVALID_OPERATION);
4514   g_return_val_if_fail (obu->obu_type == GST_AV1_OBU_TILE_GROUP,
4515       GST_AV1_PARSER_INVALID_OPERATION);
4516   g_return_val_if_fail (tile_group != NULL, GST_AV1_PARSER_INVALID_OPERATION);
4517
4518   if (!parser->state.seen_frame_header) {
4519     GST_WARNING ("Missing OBU Reference: frame_header");
4520     return GST_AV1_PARSER_MISSING_OBU_REFERENCE;
4521   }
4522
4523   gst_bit_reader_init (&bit_reader, obu->data, obu->obu_size);
4524   ret = gst_av1_parse_tile_group (parser, &bit_reader, tile_group);
4525   return ret;
4526 }
4527
4528 static GstAV1ParserResult
4529 gst_av1_parse_frame_header (GstAV1Parser * parser, GstAV1OBU * obu,
4530     GstBitReader * bit_reader, GstAV1FrameHeaderOBU * frame_header)
4531 {
4532   GstAV1ParserResult ret;
4533   guint i;
4534
4535   memset (frame_header, 0, sizeof (*frame_header));
4536   frame_header->frame_is_intra = 1;
4537   frame_header->last_frame_idx = -1;
4538   frame_header->gold_frame_idx = -1;
4539   for (i = 0; i < GST_AV1_REFS_PER_FRAME; i++)
4540     frame_header->ref_frame_idx[i] = -1;
4541
4542   ret = gst_av1_parse_uncompressed_frame_header (parser, obu, bit_reader,
4543       frame_header);
4544   if (ret != GST_AV1_PARSER_OK)
4545     return ret;
4546
4547   if (frame_header->show_existing_frame) {
4548     parser->state.seen_frame_header = 0;
4549   } else {
4550     parser->state.seen_frame_header = 1;
4551   }
4552
4553   return GST_AV1_PARSER_OK;
4554 }
4555
4556 /**
4557  * gst_av1_parser_parse_frame_header_obu:
4558  * @parser: the #GstAV1Parser
4559  * @obu: a #GstAV1OBU to be parsed
4560  * @frame_header: a #GstAV1FrameHeaderOBU to store the parsed result.
4561  *
4562  * Parse one frame header @obu based on the @parser context, store the result
4563  * in the @frame.
4564  *
4565  * Returns: The #GstAV1ParserResult.
4566  *
4567  * Since: 1.18
4568  */
4569 GstAV1ParserResult
4570 gst_av1_parser_parse_frame_header_obu (GstAV1Parser * parser,
4571     GstAV1OBU * obu, GstAV1FrameHeaderOBU * frame_header)
4572 {
4573   GstAV1ParserResult ret;
4574   GstBitReader bit_reader;
4575
4576   g_return_val_if_fail (parser != NULL, GST_AV1_PARSER_INVALID_OPERATION);
4577   g_return_val_if_fail (obu != NULL, GST_AV1_PARSER_INVALID_OPERATION);
4578   g_return_val_if_fail (obu->obu_type == GST_AV1_OBU_FRAME_HEADER ||
4579       obu->obu_type == GST_AV1_OBU_REDUNDANT_FRAME_HEADER,
4580       GST_AV1_PARSER_INVALID_OPERATION);
4581   g_return_val_if_fail (frame_header != NULL, GST_AV1_PARSER_INVALID_OPERATION);
4582
4583   if (obu->obu_type == GST_AV1_OBU_REDUNDANT_FRAME_HEADER
4584       && !parser->state.seen_frame_header) {
4585     GST_WARNING ("no seen of frame header while get redundant frame header");
4586     return GST_AV1_PARSER_BITSTREAM_ERROR;
4587   }
4588
4589   if (obu->obu_type == GST_AV1_OBU_FRAME_HEADER
4590       && parser->state.seen_frame_header) {
4591     GST_WARNING ("already seen a frame header");
4592     return GST_AV1_PARSER_BITSTREAM_ERROR;
4593   }
4594
4595   gst_bit_reader_init (&bit_reader, obu->data, obu->obu_size);
4596   ret = gst_av1_parse_frame_header (parser, obu, &bit_reader, frame_header);
4597   if (ret != GST_AV1_PARSER_OK)
4598     return ret;
4599
4600   ret = av1_skip_trailing_bits (parser, &bit_reader, obu);
4601   return ret;
4602 }
4603
4604 /**
4605  * gst_av1_parser_parse_frame_obu:
4606  * @parser: the #GstAV1Parser
4607  * @obu: a #GstAV1OBU to be parsed
4608  * @frame: a #GstAV1FrameOBU to store the parsed result.
4609  *
4610  * Parse one frame @obu based on the @parser context, store the result
4611  * in the @frame.
4612  *
4613  * Returns: The #GstAV1ParserResult.
4614  *
4615  * Since: 1.18
4616  */
4617 GstAV1ParserResult
4618 gst_av1_parser_parse_frame_obu (GstAV1Parser * parser, GstAV1OBU * obu,
4619     GstAV1FrameOBU * frame)
4620 {
4621   GstAV1ParserResult retval;
4622   GstBitReader bit_reader;
4623
4624   g_return_val_if_fail (parser != NULL, GST_AV1_PARSER_INVALID_OPERATION);
4625   g_return_val_if_fail (obu != NULL, GST_AV1_PARSER_INVALID_OPERATION);
4626   g_return_val_if_fail (obu->obu_type == GST_AV1_OBU_FRAME,
4627       GST_AV1_PARSER_INVALID_OPERATION);
4628   g_return_val_if_fail (frame != NULL, GST_AV1_PARSER_INVALID_OPERATION);
4629
4630   if (parser->state.seen_frame_header) {
4631     GST_WARNING ("already seen a frame header");
4632     return GST_AV1_PARSER_BITSTREAM_ERROR;
4633   }
4634
4635   gst_bit_reader_init (&bit_reader, obu->data, obu->obu_size);
4636   retval = gst_av1_parse_frame_header (parser, obu, &bit_reader,
4637       &(frame->frame_header));
4638   if (retval != GST_AV1_PARSER_OK)
4639     return retval;
4640
4641   if (!gst_bit_reader_skip_to_byte (&bit_reader))
4642     return GST_AV1_PARSER_NO_MORE_DATA;
4643
4644   retval = gst_av1_parse_tile_group (parser, &bit_reader, &(frame->tile_group));
4645   return retval;
4646 }
4647
4648 /**
4649  * gst_av1_parser_set_operating_point:
4650  * @parser: the #GstAV1Parser
4651  * @operating_point: the operating point to set
4652  *
4653  * Set the operating point to filter OBUs.
4654  *
4655  * Returns: The #GstAV1ParserResult.
4656  *
4657  * Since: 1.20
4658  */
4659 GstAV1ParserResult
4660 gst_av1_parser_set_operating_point (GstAV1Parser * parser,
4661     gint32 operating_point)
4662 {
4663   g_return_val_if_fail (parser != NULL, GST_AV1_PARSER_INVALID_OPERATION);
4664   g_return_val_if_fail (operating_point >= 0, GST_AV1_PARSER_INVALID_OPERATION);
4665
4666   if (parser->seq_header &&
4667       operating_point > parser->seq_header->operating_points_cnt_minus_1)
4668     return GST_AV1_PARSER_INVALID_OPERATION;
4669
4670   /* Decide whether it is valid when sequence comes. */
4671   parser->state.operating_point = operating_point;
4672   return GST_AV1_PARSER_OK;
4673 }
4674
4675 /**
4676  * gst_av1_parser_new:
4677  *
4678  * Allocates a new #GstAV1Parser,
4679  *
4680  * Returns: (transfer full): a newly-allocated  #GstAV1Parser
4681  *
4682  * Since: 1.18
4683  */
4684 GstAV1Parser *
4685 gst_av1_parser_new (void)
4686 {
4687   return g_slice_new0 (GstAV1Parser);
4688 }
4689
4690 /**
4691  * gst_av1_parser_free:
4692  * @parser: the #GstAV1Parser to free
4693  *
4694  * If parser is not %NULL, frees its allocated memory.
4695  *
4696  * It cannot be used afterwards.
4697  *
4698  * Since: 1.18
4699  */
4700 void
4701 gst_av1_parser_free (GstAV1Parser * parser)
4702 {
4703   g_return_if_fail (parser != NULL);
4704
4705   if (parser->seq_header)
4706     g_slice_free (GstAV1SequenceHeaderOBU, parser->seq_header);
4707   g_slice_free (GstAV1Parser, parser);
4708 }