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