LCOV - code coverage report
Current view: top level - media_tools - av_parsers.c (source / functions) Hit Total Coverage
Test: coverage.info Lines: 3490 4773 73.1 %
Date: 2021-04-29 23:48:07 Functions: 184 210 87.6 %

          Line data    Source code
       1             : /*
       2             :  *                      GPAC - Multimedia Framework C SDK
       3             :  *
       4             :  *                      Authors: Jean Le Feuvre, Romain Bouqueau, Cyril Concolato
       5             :  *                      Copyright (c) Telecom ParisTech 2000-2021
       6             :  *                                      All rights reserved
       7             :  *
       8             :  *  This file is part of GPAC / Media Tools sub-project
       9             :  *
      10             :  *  GPAC is free software; you can redistribute it and/or modify
      11             :  *  it under the terms of the GNU Lesser General Public License as published by
      12             :  *  the Free Software Foundation; either version 2, or (at your option)
      13             :  *  any later version.
      14             :  *
      15             :  *  GPAC is distributed in the hope that it will be useful,
      16             :  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
      17             :  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
      18             :  *  GNU Lesser General Public License for more details.
      19             :  *
      20             :  *  You should have received a copy of the GNU Lesser General Public
      21             :  *  License along with this library; see the file COPYING.  If not, write to
      22             :  *  the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
      23             :  *
      24             :  */
      25             : 
      26             : #include <gpac/internal/media_dev.h>
      27             : #include <gpac/constants.h>
      28             : #include <gpac/mpeg4_odf.h>
      29             : #include <gpac/maths.h>
      30             : #include <gpac/avparse.h>
      31             : 
      32             : #ifndef GPAC_DISABLE_OGG
      33             : #include <gpac/internal/ogg.h>
      34             : #endif
      35             : 
      36             : //uncomment/define globally to remove all bitstream parsing logging from code (this will break inspect mode ananlyze=bs)
      37             : //#define GPAC_DISABLE_AVPARSE_LOGS
      38             : 
      39             : #ifndef GPAC_DISABLE_AVPARSE_LOGS
      40             : void gf_bs_log_idx(GF_BitStream *bs, u32 nBits, const char *fname, s64 val, s32 idx1, s32 idx2, s32 idx3);
      41             : 
      42             : #define gf_bs_log(_bs, _nBits, _fname, _val) gf_bs_log_idx(_bs, _nBits, _fname, _val, -1, -1, -1)
      43             : 
      44     4999772 : u32 gf_bs_read_int_log_idx3(GF_BitStream *bs, u32 nBits, const char *fname, s32 idx1, s32 idx2, s32 idx3)
      45             : {
      46    16531877 :         u32 val = gf_bs_read_int(bs, nBits);
      47    16531877 :         gf_bs_log_idx(bs, nBits, fname, val, idx1, idx2, idx3);
      48     4999772 :         return val;
      49             : }
      50             : 
      51             : #define gf_bs_read_int_log(_bs, _nBits, _fname) gf_bs_read_int_log_idx3(_bs, _nBits, _fname, -1, -1, -1)
      52             : #define gf_bs_read_int_log_idx(_bs, _nBits, _fname, _idx) gf_bs_read_int_log_idx3(_bs, _nBits, _fname, _idx, -1, -1)
      53             : #define gf_bs_read_int_log_idx2(_bs, _nBits, _fname, _idx1, _idx2) gf_bs_read_int_log_idx3(_bs, _nBits, _fname, (s32) _idx1, (s32) _idx2, -1)
      54             : 
      55             : 
      56             : #else
      57             : 
      58             : #define gf_bs_log(_bs, _nBits, _fname, _val)
      59             : #define gf_bs_log_idx(_bs, _nBits, _fname, _val, _idx1, _idx2, _idx3)
      60             : 
      61             : #define gf_bs_read_int_log(_bs, _nbb, _f) gf_bs_read_int(_bs, _nbb)
      62             : #define gf_bs_read_int_log_idx(_bs, _nbb, _f, _idx) gf_bs_read_int(_bs, _nbb)
      63             : #define gf_bs_read_int_log_idx2(_bs, _nbb, _f, _idx1, _idx2) gf_bs_read_int(_bs, _nbb)
      64             : #define gf_bs_read_int_log_idx3(_bs, _nbb, _f, _idx1, _idx2, _idx3) gf_bs_read_int(_bs, _nbb)
      65             : 
      66             : #endif
      67             : 
      68             : 
      69             : 
      70             : 
      71             : static const struct {
      72             :         u32 w, h;
      73             : } std_par[] =
      74             : {
      75             :         { 4, 3}, {3, 2}, {16, 9}, {5, 3}, {5, 4}, {8, 5}, {2, 1}, {1, 1},
      76             :         {0, 0},
      77             : };
      78             : 
      79             : GF_EXPORT
      80         265 : void gf_media_reduce_aspect_ratio(u32 *width, u32 *height)
      81             : {
      82             :         u32 i = 0;
      83         265 :         u32 w = *width;
      84         265 :         u32 h = *height;
      85        1568 :         while (std_par[i].w) {
      86        1270 :                 if (std_par[i].w * h == std_par[i].h * w) {
      87         232 :                         *width = std_par[i].w;
      88         232 :                         *height = std_par[i].h;
      89         232 :                         return;
      90             :                 }
      91        1038 :                 i++;
      92             :         }
      93             :         //not standard one, reduce by power of 2
      94             :         i = 2;
      95             :         while (1) {
      96         373 :                 if (w <= i) return;
      97         203 :                 if (h <= i) return;
      98             : 
      99         203 :                 if (w % i) return;
     100         184 :                 if (h % i) return;
     101         170 :                 *width = w / i;
     102         170 :                 *height = h / i;
     103         170 :                 i *= 2;
     104             :         }
     105             : }
     106             : 
     107             : GF_EXPORT
     108         643 : void gf_media_get_reduced_frame_rate(u32 *timescale, u32 *sample_dur)
     109             : {
     110             :         u32 res;
     111         643 :         if (!*sample_dur) return;
     112         643 :         res = *timescale / *sample_dur;
     113         643 :         if (res * (*sample_dur) == *timescale) {
     114         634 :                 *timescale = res;
     115         634 :                 *sample_dur = 1;
     116             :         }
     117           9 :         else if ((double)(*timescale * 1001 - (res + 1) * *sample_dur * 1000) / ((res + 1) * *sample_dur * 1000) < 0.001) {
     118           7 :                 *timescale = (res + 1) * 1000;
     119           7 :                 *sample_dur = 1001;
     120             :         }
     121             : }
     122             : 
     123             : struct __m4v_profile
     124             : {
     125             :         u32 value;
     126             :         const char *name;
     127             : } M4VProfiles[] = {
     128             :         {0x00, "Reserved (0x00) Profile"},
     129             :         {0x01, "Simple Profile @ Level 1"},
     130             :         {0x02, "Simple Profile @ Level 2"},
     131             :         {0x03, "Simple Profile @ Level 3"},
     132             :         {0x08, "Simple Profile @ Level 0"},
     133             :         {0x10, "Simple Scalable Profile @ Level 0"},
     134             :         {0x11, "Simple Scalable Profile @ Level 1"},
     135             :         {0x12, "Simple Scalable Profile @ Level 2"},
     136             :         {0x21, "Core Profile @ Level 1"},
     137             :         {0x22, "Core Profile @ Level 2"},
     138             :         {0x32, "Main Profile @ Level 2"},
     139             :         {0x33, "Main Profile @ Level 3"},
     140             :         {0x34, "Main Profile @ Level 4"},
     141             :         {0x42, "N-bit Profile @ Level 2"},
     142             :         {0x51, "Scalable Texture Profile @ Level 1"},
     143             :         {0x61, "Simple Face Animation Profile @ Level 1"},
     144             :         {0x62, "Simple Face Animation Profile @ Level 2"},
     145             :         {0x63, "Simple FBA Profile @ Level 1"},
     146             :         {0x64, "Simple FBA Profile @ Level 2"},
     147             :         {0x71, "Basic Animated Texture Profile @ Level 1"},
     148             :         {0x72, "Basic Animated Texture Profile @ Level 2"},
     149             :         {0x7F, "AVC/H264 Profile"},
     150             :         {0x81, "Hybrid Profile @ Level 1"},
     151             :         {0x82, "Hybrid Profile @ Level 2"},
     152             :         {0x91, "Advanced Real Time Simple Profile @ Level 1"},
     153             :         {0x92, "Advanced Real Time Simple Profile @ Level 2"},
     154             :         {0x93, "Advanced Real Time Simple Profile @ Level 3"},
     155             :         {0x94, "Advanced Real Time Simple Profile @ Level 4"},
     156             :         {0xA1, "Core Scalable Profile @ Level1"},
     157             :         {0xA2, "Core Scalable Profile @ Level2"},
     158             :         {0xA3, "Core Scalable Profile @ Level3"},
     159             :         {0xB1, "Advanced Coding Efficiency Profile @ Level 1"},
     160             :         {0xB2, "Advanced Coding Efficiency Profile @ Level 2"},
     161             :         {0xB3, "Advanced Coding Efficiency Profile @ Level 3"},
     162             :         {0xB4, "Advanced Coding Efficiency Profile @ Level 4"},
     163             :         {0xC1, "Advanced Core Profile @ Level 1"},
     164             :         {0xC2, "Advanced Core Profile @ Level 2"},
     165             :         {0xD1, "Advanced Scalable Texture @ Level1"},
     166             :         {0xD2, "Advanced Scalable Texture @ Level2"},
     167             :         {0xE1, "Simple Studio Profile @ Level 1"},
     168             :         {0xE2, "Simple Studio Profile @ Level 2"},
     169             :         {0xE3, "Simple Studio Profile @ Level 3"},
     170             :         {0xE4, "Simple Studio Profile @ Level 4"},
     171             :         {0xE5, "Core Studio Profile @ Level 1"},
     172             :         {0xE6, "Core Studio Profile @ Level 2"},
     173             :         {0xE7, "Core Studio Profile @ Level 3"},
     174             :         {0xE8, "Core Studio Profile @ Level 4"},
     175             :         {0xF0, "Advanced Simple Profile @ Level 0"},
     176             :         {0xF1, "Advanced Simple Profile @ Level 1"},
     177             :         {0xF2, "Advanced Simple Profile @ Level 2"},
     178             :         {0xF3, "Advanced Simple Profile @ Level 3"},
     179             :         {0xF4, "Advanced Simple Profile @ Level 4"},
     180             :         {0xF5, "Advanced Simple Profile @ Level 5"},
     181             :         {0xF7, "Advanced Simple Profile @ Level 3b"},
     182             :         {0xF8, "Fine Granularity Scalable Profile @ Level 0"},
     183             :         {0xF9, "Fine Granularity Scalable Profile @ Level 1"},
     184             :         {0xFA, "Fine Granularity Scalable Profile @ Level 2"},
     185             :         {0xFB, "Fine Granularity Scalable Profile @ Level 3"},
     186             :         {0xFC, "Fine Granularity Scalable Profile @ Level 4"},
     187             :         {0xFD, "Fine Granularity Scalable Profile @ Level 5"},
     188             :         {0xFE, "Not part of MPEG-4 Visual profiles"},
     189             :         {0xFF, "No visual capability required"}
     190             : };
     191             : 
     192             : GF_EXPORT
     193         101 : const char *gf_m4v_get_profile_name(u8 video_pl)
     194             : {
     195             :         u32 i, count = GF_ARRAY_LENGTH(M4VProfiles);
     196        4921 :         for (i=0; i<count; i++) {
     197        4919 :                 if ((u32)video_pl == M4VProfiles[i].value)
     198          99 :                         return M4VProfiles[i].name;
     199             :         }
     200             :         return "ISO Reserved Profile";
     201             : }
     202             : 
     203             : 
     204             : #ifndef GPAC_DISABLE_AV_PARSERS
     205             : 
     206             : #define MPEG12_START_CODE_PREFIX                0x000001
     207             : #define MPEG12_PICTURE_START_CODE               0x00000100
     208             : #define MPEG12_SLICE_MIN_START                  0x00000101
     209             : #define MPEG12_SLICE_MAX_START                  0x000001af
     210             : #define MPEG12_USER_DATA_START_CODE             0x000001b2
     211             : #define MPEG12_SEQUENCE_START_CODE              0x000001b3
     212             : #define MPEG12_SEQUENCE_ERR_START_CODE  0x000001b4
     213             : #define MPEG12_EXT_START_CODE                   0x000001b5
     214             : #define MPEG12_SEQUENCE_END_START_CODE  0x000001b7
     215             : #define MPEG12_GOP_START_CODE                   0x000001b8
     216             : 
     217       19474 : s32 gf_mv12_next_start_code(unsigned char *pbuffer, u32 buflen, u32 *optr, u32 *scode)
     218             : {
     219             :         u32 value;
     220             :         u32 offset;
     221             : 
     222       22448 :         if (buflen < 4) return -1;
     223    15316634 :         for (offset = 0; offset < buflen - 3; offset++, pbuffer++) {
     224             : #ifdef GPAC_BIG_ENDIAN
     225             :                 value = *(u32 *)pbuffer >> 8;
     226             : #else
     227    15332782 :                 value = (pbuffer[0] << 16) | (pbuffer[1] << 8) | (pbuffer[2] << 0);
     228             : #endif
     229             : 
     230    15332782 :                 if (value == MPEG12_START_CODE_PREFIX) {
     231       14087 :                         *optr = offset;
     232       16148 :                         *scode = (value << 8) | pbuffer[3];
     233       14087 :                         return 0;
     234             :                 }
     235             :         }
     236             :         return -1;
     237             : }
     238             : 
     239        2974 : s32 gf_mv12_next_slice_start(unsigned char *pbuffer, u32 startoffset, u32 buflen, u32 *slice_offset)
     240             : {
     241             :         u32 slicestart, code;
     242        8922 :         while (gf_mv12_next_start_code(pbuffer + startoffset, buflen - startoffset, &slicestart, &code) >= 0) {
     243        2061 :                 if ((code >= MPEG12_SLICE_MIN_START) && (code <= MPEG12_SLICE_MAX_START)) {
     244        2061 :                         *slice_offset = slicestart + startoffset;
     245        2061 :                         return 0;
     246             :                 }
     247           0 :                 startoffset += slicestart + 4;
     248             :         }
     249             :         return -1;
     250             : }
     251             : 
     252             : 
     253             : /*
     254             :         MPEG-4 video (14496-2)
     255             : */
     256             : 
     257             : struct __tag_m4v_parser
     258             : {
     259             :         GF_BitStream *bs;
     260             :         Bool mpeg12, step_mode;
     261             :         u32 current_object_type;
     262             :         u32 force_next_obj_type;
     263             :         u64 current_object_start;
     264             :         u32 tc_dec, prev_tc_dec, tc_disp, prev_tc_disp;
     265             : };
     266             : 
     267             : GF_EXPORT
     268        6384 : GF_M4VParser *gf_m4v_parser_new(u8 *data, u64 data_size, Bool mpeg12video)
     269             : {
     270             :         GF_M4VParser *tmp;
     271        6384 :         if (!data || !data_size) return NULL;
     272        6384 :         GF_SAFEALLOC(tmp, GF_M4VParser);
     273        6384 :         if (!tmp) return NULL;
     274        6384 :         tmp->bs = gf_bs_new(data, data_size, GF_BITSTREAM_READ);
     275        6384 :         tmp->mpeg12 = mpeg12video;
     276        6384 :         return tmp;
     277             : }
     278             : 
     279         151 : GF_M4VParser *gf_m4v_parser_bs_new(GF_BitStream *bs, Bool mpeg12video)
     280             : {
     281             :         GF_M4VParser *tmp;
     282         151 :         GF_SAFEALLOC(tmp, GF_M4VParser);
     283         151 :         if (!tmp) return NULL;
     284         151 :         tmp->bs = bs;
     285         151 :         tmp->mpeg12 = mpeg12video;
     286         151 :         return tmp;
     287             : }
     288             : 
     289             : GF_EXPORT
     290        6437 : void gf_m4v_parser_del(GF_M4VParser *m4v)
     291             : {
     292        6437 :         gf_bs_del(m4v->bs);
     293        6437 :         gf_free(m4v);
     294        6437 : }
     295             : 
     296             : GF_EXPORT
     297          98 : void gf_m4v_parser_del_no_bs(GF_M4VParser *m4v)
     298             : {
     299          98 :         gf_free(m4v);
     300          98 : }
     301             : 
     302             : GF_EXPORT
     303         251 : void gf_m4v_parser_set_inspect(GF_M4VParser *m4v)
     304             : {
     305         251 :         if (m4v) m4v->step_mode = 1;
     306         251 : }
     307             : GF_EXPORT
     308        3104 : u32 gf_m4v_parser_get_obj_type(GF_M4VParser *m4v)
     309             : {
     310        3104 :         if (m4v) return m4v->current_object_type;
     311             :         return 0;
     312             : }
     313             : 
     314             : #define M4V_CACHE_SIZE          4096
     315      278527 : s32 M4V_LoadObject(GF_M4VParser *m4v)
     316             : {
     317             :         u32 v, bpos, found;
     318             :         char m4v_cache[M4V_CACHE_SIZE];
     319             :         u64 end, cache_start, load_size;
     320      278527 :         if (!m4v) return 0;
     321      278527 :         if (m4v->force_next_obj_type) {
     322           7 :                 m4v->current_object_type = m4v->force_next_obj_type - 1;
     323           7 :                 m4v->force_next_obj_type = 0;
     324           7 :                 return (s32)m4v->current_object_type;
     325             :         }
     326             : 
     327             :         bpos = 0;
     328             :         found = 0;
     329             :         load_size = 0;
     330             :         end = 0;
     331             :         cache_start = 0;
     332             :         v = 0xffffffff;
     333             :         while (!end) {
     334             :                 /*refill cache*/
     335    96704644 :                 if (bpos == (u32)load_size) {
     336      295827 :                         if (!gf_bs_available(m4v->bs)) break;
     337      281577 :                         load_size = gf_bs_available(m4v->bs);
     338      281577 :                         if (load_size > M4V_CACHE_SIZE) load_size = M4V_CACHE_SIZE;
     339             :                         bpos = 0;
     340      281577 :                         cache_start = gf_bs_get_position(m4v->bs);
     341      281577 :                         gf_bs_read_data(m4v->bs, m4v_cache, (u32)load_size);
     342             :                 }
     343    96690394 :                 v = ((v << 8) & 0xFFFFFF00) | ((u8)m4v_cache[bpos]);
     344    96690394 :                 bpos++;
     345    96690394 :                 if ((v & 0xFFFFFF00) == 0x00000100) {
     346      264270 :                         end = cache_start + bpos - 4;
     347             :                         found = 1;
     348             :                         break;
     349             :                 }
     350             :         }
     351             :         if (!found) return -1;
     352      264270 :         m4v->current_object_start = end;
     353      264270 :         gf_bs_seek(m4v->bs, end + 3);
     354      264270 :         m4v->current_object_type = gf_bs_read_u8(m4v->bs);
     355      264270 :         return (s32)m4v->current_object_type;
     356             : }
     357             : 
     358             : 
     359             : GF_EXPORT
     360           3 : void gf_m4v_rewrite_pl(u8 **o_data, u32 *o_dataLen, u8 PL)
     361             : {
     362             :         u32 pos = 0;
     363           3 :         unsigned char *data = (unsigned char *)*o_data;
     364           3 :         u32 dataLen = *o_dataLen;
     365             : 
     366           6 :         while (pos + 4 < dataLen) {
     367           3 :                 if (!data[pos] && !data[pos + 1] && (data[pos + 2] == 0x01) && (data[pos + 3] == M4V_VOS_START_CODE)) {
     368           3 :                         data[pos + 4] = PL;
     369           3 :                         return;
     370             :                 }
     371           0 :                 pos++;
     372             :         }
     373             :         /*emulate VOS at beggining*/
     374           0 :         (*o_data) = (char *)gf_malloc(sizeof(char)*(dataLen + 5));
     375           0 :         (*o_data)[0] = 0;
     376           0 :         (*o_data)[1] = 0;
     377           0 :         (*o_data)[2] = 1;
     378           0 :         (*o_data)[3] = (char)M4V_VOS_START_CODE;
     379           0 :         (*o_data)[4] = PL;
     380           0 :         memcpy((*o_data + 5), data, sizeof(char)*dataLen);
     381           0 :         gf_free(data);
     382           0 :         (*o_dataLen) = dataLen + 5;
     383             : }
     384             : 
     385             : static GF_Err M4V_Reset(GF_M4VParser *m4v, u64 start)
     386             : {
     387       41719 :         gf_bs_seek(m4v->bs, start);
     388             : 
     389             :         assert(start < (u64)1<<31);
     390       41719 :         m4v->current_object_start = (u32)start;
     391       41719 :         m4v->current_object_type = 0;
     392             :         return GF_OK;
     393             : }
     394             : 
     395       21618 : void gf_m4v_parser_reset(GF_M4VParser *m4v, u8 sc_type)
     396             : {
     397       21618 :         m4v->current_object_start = 0;
     398       21618 :         m4v->current_object_type = 0;
     399       21618 :         m4v->force_next_obj_type = sc_type;
     400       21618 : }
     401         175 : static GF_Err gf_m4v_parse_config_mpeg12(GF_M4VParser *m4v, GF_M4VDecSpecInfo *dsi)
     402             : {
     403             :         unsigned char p[4];
     404             :         u32 ext_type;
     405             :         s32 o_type;
     406             :         u8 go, par;
     407             : 
     408         175 :         if (!m4v || !dsi) return GF_BAD_PARAM;
     409             : 
     410             :         memset(dsi, 0, sizeof(GF_M4VDecSpecInfo));
     411         175 :         dsi->VideoPL = 0;
     412             : 
     413             :         go = 1;
     414         175 :         while (go) {
     415         815 :                 o_type = M4V_LoadObject(m4v);
     416         815 :                 switch (o_type) {
     417         173 :                 case M2V_SEQ_START_CODE:
     418         173 :                         dsi->RAP_stream = 1;
     419         173 :                         gf_bs_read_data(m4v->bs, (char *)p, 4);
     420         173 :                         dsi->width = (p[0] << 4) | ((p[1] >> 4) & 0xf);
     421         173 :                         dsi->height = ((p[1] & 0xf) << 8) | p[2];
     422             : 
     423         173 :                         dsi->VideoPL = GF_CODECID_MPEG1;
     424         173 :                         par = (p[3] >> 4) & 0xf;
     425         173 :                         switch (par) {
     426          18 :                         case 2:
     427          18 :                                 dsi->par_num = dsi->height / 3;
     428          18 :                                 dsi->par_den = dsi->width / 4;
     429          18 :                                 break;
     430         100 :                         case 3:
     431         100 :                                 dsi->par_num = dsi->height / 9;
     432         100 :                                 dsi->par_den = dsi->width / 16;
     433         100 :                                 break;
     434           0 :                         case 4:
     435           0 :                                 dsi->par_num = dsi->height / 2;
     436           0 :                                 dsi->par_den = dsi->width / 21;
     437           0 :                                 break;
     438          55 :                         default:
     439          55 :                                 dsi->par_den = dsi->par_num = 0;
     440          55 :                                 break;
     441             :                         }
     442         173 :                         switch (p[3] & 0xf) {
     443             :                         case 0:
     444             :                                 break;
     445           0 :                         case 1:
     446           0 :                                 dsi->fps = 24000.0 / 1001.0;
     447           0 :                                 break;
     448           0 :                         case 2:
     449           0 :                                 dsi->fps = 24.0;
     450           0 :                                 break;
     451         173 :                         case 3:
     452         173 :                                 dsi->fps = 25.0;
     453         173 :                                 break;
     454           0 :                         case 4:
     455           0 :                                 dsi->fps = 30000.0 / 1001.0;
     456           0 :                                 break;
     457           0 :                         case 5:
     458           0 :                                 dsi->fps = 30.0;
     459           0 :                                 break;
     460           0 :                         case 6:
     461           0 :                                 dsi->fps = 50.0;
     462           0 :                                 break;
     463           0 :                         case 7:
     464           0 :                                 dsi->fps = ((60.0*1000.0) / 1001.0);
     465           0 :                                 break;
     466           0 :                         case 8:
     467           0 :                                 dsi->fps = 60.0;
     468           0 :                                 break;
     469           0 :                         case 9:
     470           0 :                                 dsi->fps = 1;
     471           0 :                                 break;
     472           0 :                         case 10:
     473           0 :                                 dsi->fps = 5;
     474           0 :                                 break;
     475           0 :                         case 11:
     476           0 :                                 dsi->fps = 10;
     477           0 :                                 break;
     478           0 :                         case 12:
     479           0 :                                 dsi->fps = 12;
     480           0 :                                 break;
     481           0 :                         case 13:
     482           0 :                                 dsi->fps = 15;
     483           0 :                                 break;
     484             :                         }
     485             :                         break;
     486         146 :                 case M2V_EXT_START_CODE:
     487         146 :                         gf_bs_read_data(m4v->bs, (char *)p, 4);
     488         146 :                         ext_type = ((p[0] >> 4) & 0xf);
     489         146 :                         if (ext_type == 1) {
     490         131 :                                 dsi->VideoPL = 0x65;
     491         131 :                                 dsi->height = ((p[1] & 0x1) << 13) | ((p[2] & 0x80) << 5) | (dsi->height & 0x0fff);
     492         131 :                                 dsi->width = (((p[2] >> 5) & 0x3) << 12) | (dsi->width & 0x0fff);
     493             :                         }
     494             :                         break;
     495         186 :                 case M2V_PIC_START_CODE:
     496         186 :                         if (dsi->width) go = 0;
     497             :                         break;
     498             :                 default:
     499             :                         break;
     500             :                         /*EOS*/
     501           2 :                 case -1:
     502             :                         go = 0;
     503           2 :                         m4v->current_object_start = gf_bs_get_position(m4v->bs);
     504             :                         break;
     505             :                 }
     506             :         }
     507             :         M4V_Reset(m4v, 0);
     508         175 :         return GF_OK;
     509             : }
     510             : 
     511             : 
     512             : static const struct {
     513             :         u32 w, h;
     514             : } m4v_sar[6] = { { 0,   0 }, { 1,   1 }, { 12, 11 }, { 10, 11 }, { 16, 11 }, { 40, 33 } };
     515             : 
     516             : static u8 m4v_get_sar_idx(u32 w, u32 h)
     517             : {
     518             :         u32 i;
     519          18 :         for (i = 0; i < 6; i++) {
     520          18 :                 if ((m4v_sar[i].w == w) && (m4v_sar[i].h == h)) return i;
     521             :         }
     522             :         return 0xF;
     523             : }
     524             : 
     525         191 : static void gf_m4v_parse_vol(GF_M4VParser *m4v, GF_M4VDecSpecInfo *dsi)
     526             : {
     527             :         u8 verid, par;
     528             :         s32 clock_rate;
     529         191 :         u8 vpl = dsi->VideoPL;
     530             : 
     531             :         memset(dsi, 0, sizeof(GF_M4VDecSpecInfo));
     532         191 :         dsi->VideoPL = vpl;
     533             : 
     534             :         verid = 0;
     535         191 :         dsi->RAP_stream = gf_bs_read_int(m4v->bs, 1);
     536         191 :         dsi->objectType = gf_bs_read_int(m4v->bs, 8);
     537         191 :         if (gf_bs_read_int(m4v->bs, 1)) {
     538          15 :                 verid = gf_bs_read_int(m4v->bs, 4);
     539          15 :                 gf_bs_read_int(m4v->bs, 3);
     540             :         }
     541         191 :         par = gf_bs_read_int(m4v->bs, 4);
     542         191 :         if (par == 0xF) {
     543           3 :                 dsi->par_num = gf_bs_read_int(m4v->bs, 8);
     544           3 :                 dsi->par_den = gf_bs_read_int(m4v->bs, 8);
     545         188 :         } else if (par<6) {
     546         188 :                 dsi->par_num = m4v_sar[par].w;
     547         188 :                 dsi->par_den = m4v_sar[par].h;
     548             :         }
     549         191 :         if (gf_bs_read_int(m4v->bs, 1)) {
     550         191 :                 gf_bs_read_int(m4v->bs, 3);
     551         191 :                 if (gf_bs_read_int(m4v->bs, 1)) gf_bs_read_int(m4v->bs, 79);
     552             :         }
     553         191 :         dsi->has_shape = gf_bs_read_int(m4v->bs, 2);
     554         191 :         if (dsi->has_shape && (verid!=1) ) gf_bs_read_int(m4v->bs, 4);
     555         191 :         gf_bs_read_int(m4v->bs, 1);
     556             :         /*clock rate*/
     557         191 :         dsi->clock_rate = gf_bs_read_int(m4v->bs, 16);
     558             :         /*marker*/
     559         191 :         gf_bs_read_int(m4v->bs, 1);
     560             : 
     561         191 :         clock_rate = dsi->clock_rate-1;
     562             :         if (clock_rate >= 65536) clock_rate = 65535;
     563         191 :         if (clock_rate > 0) {
     564         955 :                 for (dsi->NumBitsTimeIncrement = 1; dsi->NumBitsTimeIncrement < 16; dsi->NumBitsTimeIncrement++)    {
     565         955 :                         if (clock_rate == 1) break;
     566         764 :                         clock_rate = (clock_rate >> 1);
     567             :                 }
     568             :         } else {
     569             :                 /*fix from vivien for divX*/
     570           0 :                 dsi->NumBitsTimeIncrement = 1;
     571             :         }
     572             :         /*fixed FPS stream*/
     573         191 :         dsi->time_increment = 0;
     574         191 :         if (gf_bs_read_int(m4v->bs, 1)) {
     575         176 :                 dsi->time_increment = gf_bs_read_int(m4v->bs, dsi->NumBitsTimeIncrement);
     576             :         }
     577         191 :         if (!dsi->has_shape) {
     578         191 :                 gf_bs_read_int(m4v->bs, 1);
     579         191 :                 dsi->width = gf_bs_read_int(m4v->bs, 13);
     580         191 :                 gf_bs_read_int(m4v->bs, 1);
     581         191 :                 dsi->height = gf_bs_read_int(m4v->bs, 13);
     582             :         } else {
     583           0 :                 dsi->width = dsi->height = 0;
     584             :         }
     585         191 :         gf_bs_align(m4v->bs);
     586         191 : }
     587             : 
     588         191 : static GF_Err gf_m4v_parse_config_mpeg4(GF_M4VParser *m4v, GF_M4VDecSpecInfo *dsi)
     589             : {
     590             :         s32 o_type;
     591             :         u8 go;
     592             : 
     593         191 :         if (!m4v || !dsi) return GF_BAD_PARAM;
     594             : 
     595             :         memset(dsi, 0, sizeof(GF_M4VDecSpecInfo));
     596             : 
     597             :         go = 1;
     598         191 :         while (go) {
     599        1036 :                 o_type = M4V_LoadObject(m4v);
     600        1036 :                 switch (o_type) {
     601             :                         /*vosh*/
     602          99 :                 case M4V_VOS_START_CODE:
     603          99 :                         dsi->VideoPL = (u8)gf_bs_read_u8(m4v->bs);
     604          99 :                         break;
     605             : 
     606         190 :                 case M4V_VOL_START_CODE:
     607         190 :                         gf_m4v_parse_vol(m4v, dsi);
     608             :                         /*shape will be done later*/
     609         190 :                         gf_bs_align(m4v->bs);
     610         190 :                         break;
     611             : 
     612             :                 case M4V_VOP_START_CODE:
     613             :                 case M4V_GOV_START_CODE:
     614             :                         go = 0;
     615             :                         break;
     616             :                         /*EOS*/
     617          52 :                 case -1:
     618          52 :                         m4v->current_object_start = gf_bs_get_position(m4v->bs);
     619          52 :                         return GF_EOS;
     620             :                         /*don't interest us*/
     621             :                 case M4V_UDTA_START_CODE:
     622             :                 default:
     623             :                         break;
     624             :                 }
     625             :         }
     626             :         return GF_OK;
     627             : }
     628             : 
     629             : GF_EXPORT
     630         366 : GF_Err gf_m4v_parse_config(GF_M4VParser *m4v, GF_M4VDecSpecInfo *dsi)
     631             : {
     632         366 :         if (m4v->mpeg12) {
     633         175 :                 return gf_m4v_parse_config_mpeg12(m4v, dsi);
     634             :         }
     635             :         else {
     636         191 :                 return gf_m4v_parse_config_mpeg4(m4v, dsi);
     637             :         }
     638             : }
     639             : 
     640       11664 : static GF_Err gf_m4v_parse_frame_mpeg12(GF_M4VParser *m4v, GF_M4VDecSpecInfo *dsi, u8 *frame_type, u32 *time_inc, u64 *size, u64 *start, Bool *is_coded)
     641             : {
     642             :         u8 go, hasVOP, firstObj, val;
     643             :         s32 o_type;
     644             : 
     645       11664 :         if (!m4v || !size || !start || !frame_type) return GF_BAD_PARAM;
     646             : 
     647       11664 :         *size = 0;
     648             :         firstObj = 1;
     649             :         hasVOP = 0;
     650       11664 :         *is_coded = GF_FALSE;
     651       11664 :         m4v->current_object_type = (u32)-1;
     652       11664 :         *frame_type = 0;
     653             : 
     654       11664 :         if (!m4v->step_mode)
     655       11664 :                 M4V_Reset(m4v, m4v->current_object_start);
     656             : 
     657             :         go = 1;
     658      149244 :         while (go) {
     659      145554 :                 o_type = M4V_LoadObject(m4v);
     660      145554 :                 switch (o_type) {
     661       12922 :                 case M2V_PIC_START_CODE:
     662             :                         /*done*/
     663       12922 :                         if (hasVOP) {
     664             :                                 go = 0;
     665             :                                 break;
     666             :                         }
     667        9455 :                         if (firstObj) {
     668        8911 :                                 *start = m4v->current_object_start;
     669             :                                 firstObj = 0;
     670             :                         }
     671             :                         hasVOP = 1;
     672        9455 :                         *is_coded = 1;
     673             : 
     674        9455 :                         /*val = */gf_bs_read_u8(m4v->bs);
     675        9455 :                         val = gf_bs_read_u8(m4v->bs);
     676        9455 :                         *frame_type = ((val >> 3) & 0x7) - 1;
     677             :                         break;
     678         717 :                 case M2V_GOP_START_CODE:
     679         717 :                         if (firstObj) {
     680         343 :                                 *start = m4v->current_object_start;
     681             :                                 firstObj = 0;
     682             :                         }
     683         717 :                         if (hasVOP) go = 0;
     684             :                         break;
     685             : 
     686         253 :                 case M2V_SEQ_START_CODE:
     687         253 :                         if (firstObj) {
     688         203 :                                 *start = m4v->current_object_start;
     689             :                                 firstObj = 0;
     690             :                         }
     691         253 :                         if (hasVOP) {
     692             :                                 go = 0;
     693             :                                 break;
     694             :                         }
     695             : 
     696             :                         /**/
     697             :                         break;
     698             : 
     699             :                 default:
     700             :                         break;
     701             : 
     702        7974 :                 case -1:
     703        7974 :                         *size = gf_bs_get_position(m4v->bs) - *start;
     704             :                         return GF_EOS;
     705             :                 }
     706      137580 :                 if (m4v->step_mode)
     707             :                         return GF_OK;
     708             :         }
     709        3690 :         *size = m4v->current_object_start - *start;
     710             :         return GF_OK;
     711             : }
     712             : 
     713       30387 : static GF_Err gf_m4v_parse_frame_mpeg4(GF_M4VParser *m4v, GF_M4VDecSpecInfo *dsi, u8 *frame_type, u32 *time_inc, u64 *size, u64 *start, Bool *is_coded)
     714             : {
     715             :         u8 go, hasVOP, firstObj, secs;
     716             :         s32 o_type;
     717             :         u32 vop_inc = 0;
     718             : 
     719       30387 :         if (!m4v || !size || !start || !frame_type) return GF_BAD_PARAM;
     720             : 
     721       30387 :         *size = 0;
     722             :         firstObj = 1;
     723             :         hasVOP = 0;
     724       30387 :         *is_coded = 0;
     725       30387 :         m4v->current_object_type = (u32)-1;
     726       30387 :         *frame_type = 0;
     727       30387 :         *start = 0;
     728             : 
     729       30387 :         if (!m4v->step_mode)
     730       29880 :                 M4V_Reset(m4v, m4v->current_object_start);
     731             : 
     732             :         go = 1;
     733      155019 :         while (go) {
     734      131110 :                 o_type = M4V_LoadObject(m4v);
     735      131110 :                 switch (o_type) {
     736       51117 :                 case M4V_VOP_START_CODE:
     737             :                         /*done*/
     738       51117 :                         if (hasVOP) {
     739             :                                 go = 0;
     740             :                                 break;
     741             :                         }
     742       27243 :                         if (firstObj) {
     743       27083 :                                 *start = m4v->current_object_start;
     744             :                                 firstObj = 0;
     745             :                         }
     746             :                         hasVOP = 1;
     747             : 
     748             :                         /*coding type*/
     749       27243 :                         *frame_type = gf_bs_read_int(m4v->bs, 2);
     750             :                         /*modulo time base*/
     751             :                         secs = 0;
     752       55458 :                         while (gf_bs_read_int(m4v->bs, 1) != 0)
     753         972 :                                 secs++;
     754             :                         /*no support for B frames in parsing*/
     755       27243 :                         secs += (dsi->enh_layer || *frame_type!=2) ? m4v->tc_dec : m4v->tc_disp;
     756             :                         /*marker*/
     757       27243 :                         gf_bs_read_int(m4v->bs, 1);
     758             :                         /*vop_time_inc*/
     759       27243 :                         if (dsi->NumBitsTimeIncrement)
     760       26329 :                                 vop_inc = gf_bs_read_int(m4v->bs, dsi->NumBitsTimeIncrement);
     761             : 
     762       27243 :                         m4v->prev_tc_dec = m4v->tc_dec;
     763       27243 :                         m4v->prev_tc_disp = m4v->tc_disp;
     764       27243 :                         if (dsi->enh_layer || *frame_type!=2) {
     765       10721 :                                 m4v->tc_disp = m4v->tc_dec;
     766       10721 :                                 m4v->tc_dec = secs;
     767             :                         }
     768       27243 :                         *time_inc = secs * dsi->clock_rate + vop_inc;
     769             :                         /*marker*/
     770       27243 :                         gf_bs_read_int(m4v->bs, 1);
     771             :                         /*coded*/
     772       27243 :                         *is_coded = gf_bs_read_int(m4v->bs, 1);
     773       27243 :                         gf_bs_align(m4v->bs);
     774       27243 :                         break;
     775          77 :                 case M4V_GOV_START_CODE:
     776          77 :                         if (firstObj) {
     777          44 :                                 *start = m4v->current_object_start;
     778             :                                 firstObj = 0;
     779             :                         }
     780          77 :                         if (hasVOP) go = 0;
     781             :                         break;
     782             : 
     783         370 :                 case M4V_VOL_START_CODE:
     784         370 :                         if (m4v->step_mode)
     785           1 :                                 gf_m4v_parse_vol(m4v, dsi);
     786             :                 case M4V_VOS_START_CODE:
     787         570 :                         if (hasVOP) {
     788             :                                 go = 0;
     789             :                         }
     790         536 :                         else if (firstObj) {
     791         232 :                                 *start = m4v->current_object_start;
     792             :                                 firstObj = 0;
     793             :                         }
     794             :                         break;
     795             : 
     796             :                 case M4V_VO_START_CODE:
     797             :                 default:
     798             :                         break;
     799             : 
     800        6222 :                 case -1:
     801        6222 :                         *size = gf_bs_get_position(m4v->bs) - *start;
     802        6222 :                         return GF_EOS;
     803             :                 }
     804      124888 :                 if (m4v->step_mode)
     805             :                         return GF_OK;
     806             :         }
     807             :         assert(m4v->current_object_start >= *start);
     808       23909 :         *size = m4v->current_object_start - *start;
     809       23909 :         return GF_OK;
     810             : }
     811             : 
     812             : GF_EXPORT
     813       42051 : GF_Err gf_m4v_parse_frame(GF_M4VParser *m4v, GF_M4VDecSpecInfo *dsi, u8 *frame_type, u32 *time_inc, u64 *size, u64 *start, Bool *is_coded)
     814             : {
     815       42051 :         if (m4v->mpeg12) {
     816       11664 :                 return gf_m4v_parse_frame_mpeg12(m4v, dsi, frame_type, time_inc, size, start, is_coded);
     817             :         }
     818             :         else {
     819       30387 :                 return gf_m4v_parse_frame_mpeg4(m4v, dsi, frame_type, time_inc, size, start, is_coded);
     820             :         }
     821             : }
     822             : 
     823           3 : GF_Err gf_m4v_rewrite_par(u8 **o_data, u32 *o_dataLen, s32 par_n, s32 par_d)
     824             : {
     825             :         u64 start, end, size;
     826             :         GF_BitStream *mod;
     827             :         GF_M4VParser *m4v;
     828             :         Bool go = 1;
     829             : 
     830           3 :         m4v = gf_m4v_parser_new(*o_data, *o_dataLen, 0);
     831           3 :         mod = gf_bs_new(NULL, 0, GF_BITSTREAM_WRITE);
     832             : 
     833             :         start = 0;
     834           3 :         while (go) {
     835          12 :                 u32 type = M4V_LoadObject(m4v);
     836             : 
     837          12 :                 end = gf_bs_get_position(m4v->bs) - 4;
     838          12 :                 size = end - start;
     839             :                 /*store previous object*/
     840          12 :                 if (size) {
     841             :                         assert (size < (u64)1<<31);
     842           9 :                         gf_bs_write_data(mod, *o_data + start, (u32)size);
     843             :                         start = end;
     844             :                 }
     845             : 
     846          12 :                 switch (type) {
     847           3 :                 case M4V_VOL_START_CODE:
     848           3 :                         gf_bs_write_int(mod, 0, 8);
     849           3 :                         gf_bs_write_int(mod, 0, 8);
     850           3 :                         gf_bs_write_int(mod, 1, 8);
     851           3 :                         gf_bs_write_int(mod, M4V_VOL_START_CODE, 8);
     852           3 :                         gf_bs_write_int(mod, gf_bs_read_int(m4v->bs, 1), 1);
     853           3 :                         gf_bs_write_int(mod, gf_bs_read_int(m4v->bs, 8), 8);
     854           3 :                         start = gf_bs_read_int(m4v->bs, 1);
     855           3 :                         gf_bs_write_int(mod, (u32)start, 1);
     856           3 :                         if (start) {
     857           0 :                                 gf_bs_write_int(mod, gf_bs_read_int(m4v->bs, 7), 7);
     858             :                         }
     859           3 :                         start = gf_bs_read_int(m4v->bs, 4);
     860           3 :                         if (start == 0xF) {
     861           0 :                                 gf_bs_read_int(m4v->bs, 8);
     862           0 :                                 gf_bs_read_int(m4v->bs, 8);
     863             :                         }
     864           3 :                         if ((par_n >= 0) && (par_d >= 0)) {
     865           3 :                                 u8 par = m4v_get_sar_idx(par_n, par_d);
     866           3 :                                 gf_bs_write_int(mod, par, 4);
     867           3 :                                 if (par == 0xF) {
     868           3 :                                         gf_bs_write_int(mod, par_n, 8);
     869           3 :                                         gf_bs_write_int(mod, par_d, 8);
     870             :                                 }
     871             :                         }
     872             :                         else {
     873           0 :                                 gf_bs_write_int(mod, 0x0, 4);
     874             :                         }
     875             :                 case -1:
     876             :                         go = 0;
     877             :                         break;
     878             :                 default:
     879             :                         break;
     880             :                 }
     881             :         }
     882         897 :         while (gf_bs_bits_available(m4v->bs)) {
     883         894 :                 u32 b = gf_bs_read_int(m4v->bs, 1);
     884         894 :                 gf_bs_write_int(mod, b, 1);
     885             :         }
     886             : 
     887           3 :         gf_m4v_parser_del(m4v);
     888           3 :         gf_free(*o_data);
     889           3 :         gf_bs_get_content(mod, o_data, o_dataLen);
     890           3 :         gf_bs_del(mod);
     891           3 :         return GF_OK;
     892             : }
     893             : 
     894             : GF_EXPORT
     895       13163 : u64 gf_m4v_get_object_start(GF_M4VParser *m4v)
     896             : {
     897       13163 :         return m4v->current_object_start;
     898             : }
     899             : 
     900             : #if 0 //unused
     901             : Bool gf_m4v_is_valid_object_type(GF_M4VParser *m4v)
     902             : {
     903             :         return ((s32)m4v->current_object_type == -1) ? 0 : 1;
     904             : }
     905             : #endif
     906             : 
     907             : 
     908             : GF_EXPORT
     909          52 : GF_Err gf_m4v_get_config(u8 *rawdsi, u32 rawdsi_size, GF_M4VDecSpecInfo *dsi)
     910             : {
     911             :         GF_Err e;
     912             :         GF_M4VParser *vparse;
     913          52 :         if (!rawdsi || !rawdsi_size) return GF_NON_COMPLIANT_BITSTREAM;
     914          52 :         vparse = gf_m4v_parser_new(rawdsi, rawdsi_size, 0);
     915          52 :         e = gf_m4v_parse_config(vparse, dsi);
     916          52 :         dsi->next_object_start = (u32)vparse->current_object_start;
     917          52 :         gf_m4v_parser_del(vparse);
     918          52 :         return e < 0 ? e : GF_OK;
     919             : }
     920             : 
     921             : GF_EXPORT
     922           1 : GF_Err gf_mpegv12_get_config(u8 *rawdsi, u32 rawdsi_size, GF_M4VDecSpecInfo *dsi)
     923             : {
     924             :         GF_Err e;
     925             :         GF_M4VParser *vparse;
     926           1 :         if (!rawdsi || !rawdsi_size) return GF_NON_COMPLIANT_BITSTREAM;
     927           0 :         vparse = gf_m4v_parser_new(rawdsi, rawdsi_size, GF_TRUE);
     928           0 :         e = gf_m4v_parse_config(vparse, dsi);
     929           0 :         dsi->next_object_start = (u32)vparse->current_object_start;
     930           0 :         gf_m4v_parser_del(vparse);
     931           0 :         return e;
     932             : }
     933             : 
     934             : #endif
     935             : 
     936             : 
     937             : /*
     938             :         AAC parser
     939             : */
     940             : 
     941             : struct __m4a_oti
     942             : {
     943             :         u32 type;
     944             :         const char *name;
     945             : } M4AObjectTypes[] = {
     946             :         {0, "MPEG-4 Audio Reserved"},
     947             :         {1, "MPEG-4 Audio AAC Main"},
     948             :         {2, "MPEG-4 Audio AAC LC"},
     949             :         {3, "MPEG-4 Audio AAC SSR"},
     950             :         {4, "MPEG-4 Audio AAC LTP"},
     951             :         {5, "MPEG-4 Audio SBR"},
     952             :         {6, "MPEG-4 Audio AAC Scalable"},
     953             :         {7, "MPEG-4 Audio TwinVQ"},
     954             :         {8, "MPEG-4 Audio CELP"},
     955             :         {9, "MPEG-4 Audio HVXC"},
     956             :         {10, "MPEG-4 Audio Reserved"},
     957             :         {11, "MPEG-4 Audio Reserved"},
     958             :         {12, "MPEG-4 Audio TTSI"},
     959             :         {13, "MPEG-4 Audio Main synthetic"},
     960             :         {14, "MPEG-4 Audio Wavetable synthesis"},
     961             :         {15, "MPEG-4 Audio General MIDI"},
     962             :         {16, "MPEG-4 Audio Algorithmic Synthesis and Audio FX"},
     963             :         {17, "MPEG-4 Audio ER AAC LC"},
     964             :         {18, "MPEG-4 Audio Reserved"},
     965             :         {19, "MPEG-4 Audio ER AAC LTP"},
     966             :         {20, "MPEG-4 Audio ER AAC scalable"},
     967             :         {21, "MPEG-4 Audio ER TwinVQ"},
     968             :         {22, "MPEG-4 Audio ER BSAC"},
     969             :         {23, "MPEG-4 Audio ER AAC LD"},
     970             :         {24, "MPEG-4 Audio ER CELP"},
     971             :         {25, "MPEG-4 Audio ER HVXC"},
     972             :         {26, "MPEG-4 Audio ER HILN"},
     973             :         {27, "MPEG-4 Audio ER Parametric"},
     974             :         {28, "MPEG-4 Audio SSC"},
     975             :         {29, "MPEG-4 Audio ParametricStereo"},
     976             :         {30, "MPEG-4 Audio Reserved"},
     977             :         {31, "MPEG-4 Audio Reserved"},
     978             :         {32, "MPEG-1 Audio Layer-1"},
     979             :         {33, "MPEG-1 Audio Layer-2"},
     980             :         {34, "MPEG-1 Audio Layer-3"},
     981             :         {35, "MPEG-4 Audio DST"},
     982             :         {36, "MPEG-4 Audio ALS"},
     983             :         {37, "MPEG-4 Audio SLS"},
     984             :         {42, "MPEG Audio xHE-AAC"},
     985             : };
     986             : 
     987             : GF_EXPORT
     988          23 : const char *gf_m4a_object_type_name(u32 objectType)
     989             : {
     990             :         u32 i, count = GF_ARRAY_LENGTH(M4AObjectTypes);
     991         104 :         for (i=0; i<count; i++) {
     992         104 :                 if (objectType==M4AObjectTypes[i].type)
     993          23 :                         return M4AObjectTypes[i].name;
     994             :         }
     995             :         return "MPEG-4 Audio Unknown";
     996             : }
     997             : 
     998             : struct __m4a_profile
     999             : {
    1000             :         u32 value;
    1001             :         const char *name;
    1002             : } M4AProfiles[] = {
    1003             :         {0x00, "ISO Reserved (0x00)"},
    1004             :         {0x01, "Main Audio Profile @ Level 1"},
    1005             :         {0x02, "Main Audio Profile @ Level 2"},
    1006             :         {0x03, "Main Audio Profile @ Level 3"},
    1007             :         {0x04, "Main Audio Profile @ Level 4"},
    1008             :         {0x05, "Scalable Audio Profile @ Level 1"},
    1009             :         {0x06, "Scalable Audio Profile @ Level 2"},
    1010             :         {0x07, "Scalable Audio Profile @ Level 3"},
    1011             :         {0x08, "Scalable Audio Profile @ Level 4"},
    1012             :         {0x09, "Speech Audio Profile @ Level 1"},
    1013             :         {0x0A, "Speech Audio Profile @ Level 2"},
    1014             :         {0x0B, "Synthetic Audio Profile @ Level 1"},
    1015             :         {0x0C, "Synthetic Audio Profile @ Level 2"},
    1016             :         {0x0D, "Synthetic Audio Profile @ Level 3"},
    1017             :         {0x0E, "High Quality Audio Profile @ Level 1"},
    1018             :         {0x0F, "High Quality Audio Profile @ Level 2"},
    1019             :         {0x10, "High Quality Audio Profile @ Level 3"},
    1020             :         {0x11, "High Quality Audio Profile @ Level 4"},
    1021             :         {0x12, "High Quality Audio Profile @ Level 5"},
    1022             :         {0x13, "High Quality Audio Profile @ Level 6"},
    1023             :         {0x14, "High Quality Audio Profile @ Level 7"},
    1024             :         {0x15, "High Quality Audio Profile @ Level 8"},
    1025             :         {0x16, "Low Delay Audio Profile @ Level 1"},
    1026             :         {0x17, "Low Delay Audio Profile @ Level 2"},
    1027             :         {0x18, "Low Delay Audio Profile @ Level 3"},
    1028             :         {0x19, "Low Delay Audio Profile @ Level 4"},
    1029             :         {0x1A, "Low Delay Audio Profile @ Level 5"},
    1030             :         {0x1B, "Low Delay Audio Profile @ Level 6"},
    1031             :         {0x1C, "Low Delay Audio Profile @ Level 7"},
    1032             :         {0x1D, "Low Delay Audio Profile @ Level 8"},
    1033             :         {0x1E, "Natural Audio Profile @ Level 1"},
    1034             :         {0x1F, "Natural Audio Profile @ Level 2"},
    1035             :         {0x20, "Natural Audio Profile @ Level 3"},
    1036             :         {0x21, "Natural Audio Profile @ Level 4"},
    1037             :         {0x22, "Mobile Audio Internetworking Profile @ Level 1"},
    1038             :         {0x23, "Mobile Audio Internetworking Profile @ Level 2"},
    1039             :         {0x24, "Mobile Audio Internetworking Profile @ Level 3"},
    1040             :         {0x25, "Mobile Audio Internetworking Profile @ Level 4"},
    1041             :         {0x26, "Mobile Audio Internetworking Profile @ Level 5"},
    1042             :         {0x27, "Mobile Audio Internetworking Profile @ Level 6"},
    1043             :         {0x28, "AAC Profile @ Level 1"},
    1044             :         {0x29, "AAC Profile @ Level 2"},
    1045             :         {0x2A, "AAC Profile @ Level 4"},
    1046             :         {0x2B, "AAC Profile @ Level 5"},
    1047             :         {0x2C, "High Efficiency AAC Profile @ Level 2"},
    1048             :         {0x2D, "High Efficiency AAC Profile @ Level 3"},
    1049             :         {0x2E, "High Efficiency AAC Profile @ Level 4"},
    1050             :         {0x2F, "High Efficiency AAC Profile @ Level 5"},
    1051             :         {0x30, "High Efficiency AAC v2 Profile @ Level 2"},
    1052             :         {0x31, "High Efficiency AAC v2 Profile @ Level 3"},
    1053             :         {0x32, "High Efficiency AAC v2 Profile @ Level 4"},
    1054             :         {0x33, "High Efficiency AAC v2 Profile @ Level 5"},
    1055             :         {0x34, "Low Delay AAC Profile"},
    1056             :         {0x35, "Baseline MPEG Surround Profile @ Level 1"},
    1057             :         {0x36, "Baseline MPEG Surround Profile @ Level 2"},
    1058             :         {0x37, "Baseline MPEG Surround Profile @ Level 3"},
    1059             :         {0x38, "Baseline MPEG Surround Profile @ Level 4"},
    1060             :         {0x39, "Baseline MPEG Surround Profile @ Level 5"},
    1061             :         {0x3A, "Baseline MPEG Surround Profile @ Level 6"},
    1062             :         {0x3B, "High Definition AAC Profile @ Level 1"},
    1063             :         {0x3C, "ALS Simple Profile @ Level 1"},
    1064             :         {0x50, "AAC Profile @ Level 6"},
    1065             :         {0x51, "AAC Profile @ Level 7"},
    1066             :         {0x52, "High Efficiency AAC Profile @ Level 6"},
    1067             :         {0x53, "High Efficiency AAC Profile @ Level 7"},
    1068             :         {0x54, "High Efficiency AAC v2 Profile @ Level 6"},
    1069             :         {0x55, "High Efficiency AAC v2 Profile @ Level 7"},
    1070             :         {0x56, "Extended High Efficiency AAC Profile @ Level 6"},
    1071             :         {0x57, "Extended High Efficiency AAC Profile @ Level 7"},
    1072             :         {0xFE, "Not part of MPEG-4 audio profiles"},
    1073             :         {0xFF, "No audio capability required"}
    1074             : };
    1075             : 
    1076             : GF_EXPORT
    1077          74 : const char *gf_m4a_get_profile_name(u8 audio_pl)
    1078             : {
    1079             :         u32 i, count = GF_ARRAY_LENGTH(M4AProfiles);
    1080        4093 :         for (i=0; i<count; i++) {
    1081        4093 :                 if ((u32) audio_pl==M4AProfiles[i].value)
    1082          74 :                         return M4AProfiles[i].name;
    1083             :         }
    1084             :         return "ISO Reserved / User Private";
    1085             : }
    1086             : 
    1087             : #ifndef GPAC_DISABLE_AV_PARSERS
    1088             : 
    1089             : GF_EXPORT
    1090       20424 : u32 gf_m4a_get_profile(GF_M4ADecSpecInfo *cfg)
    1091             : {
    1092       20424 :         switch (cfg->base_object_type) {
    1093       13137 :         case 2: /*AAC LC*/
    1094       13137 :                 if (cfg->nb_chan <= 2)
    1095       12951 :                         return (cfg->base_sr <= 24000) ? 0x28 : 0x29; /*LC@L1 or LC@L2*/
    1096         186 :                 if (cfg->nb_chan <= 5)
    1097         101 :                         return (cfg->base_sr <= 48000) ? 0x2A : 0x2B; /*LC@L4 or LC@L5*/
    1098          85 :                 return (cfg->base_sr <= 48000) ? 0x50 : 0x51; /*LC@L4 or LC@L5*/
    1099         279 :         case 5: /*HE-AAC - SBR*/
    1100         279 :                 if (cfg->nb_chan <= 2)
    1101         142 :                         return (cfg->base_sr <= 24000) ? 0x2C : 0x2D; /*HE@L2 or HE@L3*/
    1102         137 :                 if (cfg->nb_chan <= 5)
    1103          53 :                         return (cfg->base_sr <= 48000) ? 0x2E : 0x2F; /*HE@L4 or HE@L5*/
    1104          84 :                 return (cfg->base_sr <= 48000) ? 0x52 : 0x53; /*HE@L6 or HE@L7*/
    1105         281 :         case 29: /*HE-AACv2 - SBR+PS*/
    1106         281 :                 if (cfg->nb_chan <= 2)
    1107         281 :                         return (cfg->base_sr <= 24000) ? 0x30 : 0x31; /*HE-AACv2@L2 or HE-AACv2@L3*/
    1108           0 :                 if (cfg->nb_chan <= 5)
    1109           0 :                         return (cfg->base_sr <= 48000) ? 0x32 : 0x33; /*HE-AACv2@L4 or HE-AACv2@L5*/
    1110           0 :                 return (cfg->base_sr <= 48000) ? 0x54 : 0x55; /*HE-AACv2@L6 or HE-AACv2@L7*/
    1111             :         /*default to HQ*/
    1112        6727 :         default:
    1113        6727 :                 if (cfg->nb_chan <= 2) return (cfg->base_sr < 24000) ? 0x0E : 0x0F; /*HQ@L1 or HQ@L2*/
    1114             :                 return 0x10; /*HQ@L3*/
    1115             :         }
    1116             : }
    1117             : 
    1118             : GF_EXPORT
    1119          68 : GF_Err gf_m4a_parse_program_config_element(GF_BitStream *bs, GF_M4ADecSpecInfo *cfg)
    1120             : {
    1121             :         u32 i;
    1122             : 
    1123          68 :         cfg->program_config_element_present = 1;
    1124          68 :         cfg->cpe_channels = 0;
    1125             : 
    1126          68 :         cfg->element_instance_tag = gf_bs_read_int_log(bs, 4, "element_instance_tag");
    1127          68 :         cfg->object_type = gf_bs_read_int_log(bs, 2, "object_type");
    1128          68 :         cfg->sampling_frequency_index = gf_bs_read_int_log(bs, 4, "sampling_frequency_index");
    1129          68 :         cfg->num_front_channel_elements = gf_bs_read_int_log(bs, 4, "num_front_channel_elements");
    1130          68 :         cfg->num_side_channel_elements = gf_bs_read_int_log(bs, 4, "num_side_channel_elements");
    1131          68 :         cfg->num_back_channel_elements = gf_bs_read_int_log(bs, 4, "num_back_channel_elements");
    1132          68 :         cfg->num_lfe_channel_elements = gf_bs_read_int_log(bs, 2, "num_lfe_channel_elements");
    1133          68 :         cfg->num_assoc_data_elements = gf_bs_read_int_log(bs, 3, "num_assoc_data_elements");
    1134          68 :         cfg->num_valid_cc_elements = gf_bs_read_int_log(bs, 4, "num_valid_cc_elements");
    1135          68 :         cfg->mono_mixdown_present = (Bool)gf_bs_read_int_log(bs, 1, "mono_mixdown_present");
    1136          68 :         if (cfg->mono_mixdown_present) {
    1137          25 :                 cfg->mono_mixdown_element_number = gf_bs_read_int_log(bs, 4, "mono_mixdown_element_number");
    1138             :         }
    1139          68 :         cfg->stereo_mixdown_present = gf_bs_read_int_log(bs, 1, "stereo_mixdown_present");
    1140          68 :         if (cfg->stereo_mixdown_present) {
    1141          43 :                 cfg->stereo_mixdown_element_number = gf_bs_read_int_log(bs, 4, "stereo_mixdown_element_number");
    1142             :         }
    1143          68 :         cfg->matrix_mixdown_idx_present = gf_bs_read_int_log(bs, 1, "matrix_mixdown_idx_present");
    1144          68 :         if (cfg->matrix_mixdown_idx_present) {
    1145          39 :                 cfg->matrix_mixdown_idx = gf_bs_read_int_log(bs, 2, "matrix_mixdown_idx");
    1146          39 :                 cfg->pseudo_surround_enable = gf_bs_read_int_log(bs, 1, "pseudo_surround_enable");
    1147             :         }
    1148         411 :         for (i = 0; i < cfg->num_front_channel_elements; i++) {
    1149         822 :                 cfg->front_element_is_cpe[i] = gf_bs_read_int_log_idx(bs, 1, "front_element_is_cpe", i);
    1150         411 :                 cfg->front_element_tag_select[i] = gf_bs_read_int_log_idx(bs, 4, "front_element_tag_select", i);
    1151         411 :                 if (cfg->front_element_is_cpe[i]) cfg->cpe_channels++;
    1152             :         }
    1153         525 :         for (i = 0; i < cfg->num_side_channel_elements; i++) {
    1154        1050 :                 cfg->side_element_is_cpe[i] = gf_bs_read_int_log_idx(bs, 1, "side_element_is_cpe", i);
    1155         525 :                 cfg->side_element_tag_select[i] = gf_bs_read_int_log_idx(bs, 4, "side_element_tag_select", i);
    1156         525 :                 if (cfg->side_element_is_cpe[i]) cfg->cpe_channels++;
    1157             :         }
    1158         527 :         for (i = 0; i < cfg->num_back_channel_elements; i++) {
    1159        1054 :                 cfg->back_element_is_cpe[i] = gf_bs_read_int_log_idx(bs, 1, "back_element_is_cpe", i);
    1160         527 :                 cfg->back_element_tag_select[i] = gf_bs_read_int_log_idx(bs, 4, "back_element_tag_select", i);
    1161         527 :                 if (cfg->back_element_is_cpe[i]) cfg->cpe_channels++;
    1162             :         }
    1163         117 :         for (i = 0; i < cfg->num_lfe_channel_elements; i++) {
    1164         234 :                 cfg->lfe_element_tag_select[i] = gf_bs_read_int_log_idx(bs, 4, "lfe_element_tag_select", i);
    1165             :         }
    1166         149 :         for (i = 0; i < cfg->num_assoc_data_elements; i++) {
    1167         298 :                 cfg->assoc_data_element_tag_select[i] = gf_bs_read_int_log_idx(bs, 4, "assoc_data_element_tag_select", i);
    1168             :         }
    1169             : 
    1170         419 :         for (i = 0; i < cfg->num_valid_cc_elements; i++) {
    1171         838 :                 cfg->cc_element_is_ind_sw[i] = gf_bs_read_int_log_idx(bs, 1, "cc_element_is_ind_sw", i);
    1172         419 :                 cfg->valid_cc_element_tag_select[i] = gf_bs_read_int_log_idx(bs, 4, "valid_cc_element_tag_select", i);
    1173             :         }
    1174          68 :         gf_bs_align(bs);
    1175          68 :         cfg->comment_field_bytes = gf_bs_read_int_log(bs, 8, "comment_field_bytes");
    1176          68 :         gf_bs_read_data(bs, (char *)cfg->comments, cfg->comment_field_bytes);
    1177             : 
    1178          68 :         cfg->nb_chan = cfg->num_front_channel_elements + cfg->num_back_channel_elements + cfg->num_side_channel_elements + cfg->num_lfe_channel_elements;
    1179          68 :         cfg->nb_chan += cfg->cpe_channels;
    1180             : 
    1181          68 :         return GF_OK;
    1182             : }
    1183             : 
    1184             : GF_EXPORT
    1185       20271 : GF_Err gf_m4a_parse_config(GF_BitStream *bs, GF_M4ADecSpecInfo *cfg, Bool size_known)
    1186             : {
    1187             :         u32 audio_obj_type;
    1188             :         memset(cfg, 0, sizeof(GF_M4ADecSpecInfo));
    1189       20271 :         cfg->base_object_type = gf_bs_read_int_log(bs, 5, "base_object_type");
    1190             :         /*extended object type*/
    1191       20271 :         if (cfg->base_object_type == 31) {
    1192         519 :                 cfg->base_object_type = 32 + gf_bs_read_int_log(bs, 6, "extended_base_object_type");
    1193             :         }
    1194       20271 :         cfg->base_sr_index = gf_bs_read_int_log(bs, 4, "base_samplerate_index");
    1195       20271 :         if (cfg->base_sr_index == 0x0F) {
    1196         550 :                 cfg->base_sr = gf_bs_read_int_log(bs, 24, "base_samplerate");
    1197             :         }
    1198             :         else {
    1199       19721 :                 cfg->base_sr = GF_M4ASampleRates[cfg->base_sr_index];
    1200             :         }
    1201             : 
    1202       20271 :         cfg->chan_cfg = gf_bs_read_int_log(bs, 4, "channel_configuration");
    1203       20271 :         if (cfg->chan_cfg) {
    1204       20003 :                 cfg->nb_chan = GF_M4ANumChannels[cfg->chan_cfg - 1];
    1205             :         }
    1206             : 
    1207       20271 :         audio_obj_type = cfg->base_object_type;
    1208       20271 :         if (cfg->base_object_type == 5 || cfg->base_object_type == 29) {
    1209         555 :                 if (cfg->base_object_type == 29) {
    1210         278 :                         cfg->has_ps = 1;
    1211         278 :                         cfg->nb_chan = 1;
    1212             :                 }
    1213         555 :                 cfg->has_sbr = GF_TRUE;
    1214         555 :                 cfg->sbr_sr_index = gf_bs_read_int_log(bs, 4, "sbr_samplerate_index");
    1215         555 :                 if (cfg->sbr_sr_index == 0x0F) {
    1216          11 :                         cfg->sbr_sr = gf_bs_read_int_log(bs, 24, "sbr_samplerate");
    1217             :                 }
    1218             :                 else {
    1219         544 :                         cfg->sbr_sr = GF_M4ASampleRates[cfg->sbr_sr_index];
    1220             :                 }
    1221         555 :                 cfg->sbr_object_type = gf_bs_read_int_log(bs, 5, "sbr_object_type");
    1222         555 :                 if (cfg->sbr_object_type==31)
    1223          80 :                         cfg->sbr_object_type = 32 + gf_bs_read_int_log(bs, 6, "audioObjectTypeExt");
    1224         555 :                 audio_obj_type = cfg->sbr_object_type;
    1225         555 :                 if (cfg->sbr_object_type==22) {
    1226           0 :                         /*ext_chan_cfg = */gf_bs_read_int_log(bs, 4, "channel_configuration");
    1227             :                 }
    1228             :         }
    1229             : 
    1230             :         /*object cfg*/
    1231             :         switch (audio_obj_type) {
    1232       16039 :         case 1:
    1233             :         case 2:
    1234             :         case 3:
    1235             :         case 4:
    1236             :         case 6:
    1237             :         case 7:
    1238             :         case 17:
    1239             :         case 19:
    1240             :         case 20:
    1241             :         case 21:
    1242             :         case 22:
    1243             :         case 23:
    1244             :         case 42:
    1245             :         {
    1246             :                 Bool ext_flag;
    1247       16039 :                 gf_bs_read_int_log(bs, 1, "frame_length_flag");
    1248       16039 :                 if (gf_bs_read_int_log(bs, 1, "depends_on_core_coder"))
    1249        1764 :                         gf_bs_read_int_log(bs, 14, "delay");
    1250             :                 ext_flag = gf_bs_read_int_log(bs, 1, "extension_flag");
    1251             : 
    1252       16039 :                 if (!cfg->chan_cfg) {
    1253          68 :                         gf_m4a_parse_program_config_element(bs, cfg);
    1254             :                 }
    1255             : 
    1256       16039 :                 if ((cfg->base_object_type == 6) || (cfg->base_object_type == 20)) {
    1257         262 :                         gf_bs_read_int_log(bs, 3, "layerN");
    1258             :                 }
    1259       16039 :                 if (ext_flag) {
    1260        1540 :                         if (cfg->base_object_type == 22) {
    1261         230 :                                 gf_bs_read_int_log(bs, 5, "numOfSubFrame");
    1262         230 :                                 gf_bs_read_int_log(bs, 11, "layer_length");
    1263             :                         }
    1264        3080 :                         if ((cfg->base_object_type == 17)
    1265        1540 :                                 || (cfg->base_object_type == 19)
    1266        1491 :                                 || (cfg->base_object_type == 20)
    1267        1357 :                                 || (cfg->base_object_type == 23)
    1268             :                         ) {
    1269         410 :                                 gf_bs_read_int_log(bs, 1, "aacSectionDataResilienceFlag");
    1270         410 :                                 gf_bs_read_int_log(bs, 1, "aacScalefactorDataResilienceFlag");
    1271         410 :                                 gf_bs_read_int_log(bs, 1, "aacSpectralDataResilienceFlag");
    1272             :                         }
    1273        1540 :                         gf_bs_read_int_log(bs, 1, "extensionFlag3");
    1274             :                 }
    1275             :         }
    1276             :         break;
    1277             :         }
    1278             :         /*ER cfg*/
    1279             :         switch (audio_obj_type) {
    1280             :         case 17:
    1281             :         case 19:
    1282             :         case 20:
    1283             :         case 21:
    1284             :         case 22:
    1285             :         case 23:
    1286             :         case 24:
    1287             :         case 25:
    1288             :         case 26:
    1289             :         case 27:
    1290             :         {
    1291             :                 u32 epConfig = gf_bs_read_int_log(bs, 2, "epConfig");
    1292             :                 if ((epConfig == 2) || (epConfig == 3)) {
    1293             :                 }
    1294        2643 :                 if (epConfig == 3) {
    1295         502 :                         gf_bs_read_int_log(bs, 1, "directMapping");
    1296             :                 }
    1297             :         }
    1298             :         break;
    1299             :         }
    1300             : 
    1301       20271 :         if (size_known && (cfg->base_object_type != 5) && (cfg->base_object_type != 29)) {
    1302       12642 :                 while (gf_bs_available(bs) >= 2) {
    1303          35 :                         u32 sync = gf_bs_peek_bits(bs, 11, 0);
    1304          35 :                         if (sync == 0x2b7) {
    1305          25 :                                 gf_bs_read_int_log(bs, 11, "syncExtensionType");
    1306          25 :                                 cfg->sbr_object_type = gf_bs_read_int_log(bs, 5, "extensionAudioObjectType ");
    1307          25 :                                 cfg->has_sbr = gf_bs_read_int_log(bs, 1, "sbrPresentFlag");
    1308          25 :                                 if (cfg->has_sbr) {
    1309          10 :                                         cfg->sbr_sr_index = gf_bs_read_int_log(bs, 4, "extensionSamplingFrequencyIndex");
    1310          10 :                                         if (cfg->sbr_sr_index == 0x0F) {
    1311           0 :                                                 cfg->sbr_sr = gf_bs_read_int_log(bs, 24, "extensionSamplingFrequency");
    1312             :                                         }
    1313             :                                         else {
    1314          10 :                                                 cfg->sbr_sr = GF_M4ASampleRates[cfg->sbr_sr_index];
    1315             :                                         }
    1316             :                                 }
    1317             :                         }
    1318          10 :                         else if (sync == 0x548) {
    1319           5 :                                 gf_bs_read_int_log(bs, 11, "syncExtensionType");
    1320           5 :                                 cfg->has_ps = gf_bs_read_int_log(bs, 1, "hasParametricStereo");
    1321           5 :                                 if (cfg->has_ps)
    1322           5 :                                         cfg->nb_chan = 1;
    1323             :                         }
    1324             :                         else {
    1325             :                                 break;
    1326             :                         }
    1327             :                 }
    1328             :         }
    1329       20271 :         cfg->audioPL = gf_m4a_get_profile(cfg);
    1330       20271 :         return GF_OK;
    1331             : }
    1332             : 
    1333             : GF_EXPORT
    1334       12633 : GF_Err gf_m4a_get_config(u8 *dsi, u32 dsi_size, GF_M4ADecSpecInfo *cfg)
    1335             : {
    1336             :         GF_BitStream *bs;
    1337       12633 :         if (!dsi || !dsi_size || (dsi_size < 2)) return GF_NON_COMPLIANT_BITSTREAM;
    1338       12633 :         bs = gf_bs_new(dsi, dsi_size, GF_BITSTREAM_READ);
    1339       12633 :         gf_m4a_parse_config(bs, cfg, GF_TRUE);
    1340       12633 :         gf_bs_del(bs);
    1341       12633 :         return GF_OK;
    1342             : }
    1343             : 
    1344        1609 : u32 gf_latm_get_value(GF_BitStream *bs)
    1345             : {
    1346             :         u32 i, tmp, value = 0;
    1347        1609 :         u32 bytesForValue = gf_bs_read_int(bs, 2);
    1348        5315 :         for (i = 0; i <= bytesForValue; i++) {
    1349        3706 :                 value <<= 8;
    1350        3706 :                 tmp = gf_bs_read_int(bs, 8);
    1351        3706 :                 value += tmp;
    1352             :         }
    1353        1609 :         return value;
    1354             : }
    1355             : 
    1356             : GF_EXPORT
    1357         162 : u32 gf_m4a_get_channel_cfg(u32 nb_chan)
    1358             : {
    1359             :         u32 i, count = sizeof(GF_M4ANumChannels) / sizeof(u32);
    1360         311 :         for (i = 0; i < count; i++) {
    1361         311 :                 if (GF_M4ANumChannels[i] == nb_chan) return i + 1;
    1362             :         }
    1363             :         return 0;
    1364             : }
    1365             : 
    1366             : GF_EXPORT
    1367           0 : GF_Err gf_m4a_write_program_config_element_bs(GF_BitStream *bs, GF_M4ADecSpecInfo *cfg)
    1368             : {
    1369             :         u32 i;
    1370           0 :         gf_bs_write_int(bs, cfg->element_instance_tag, 4);
    1371           0 :         gf_bs_write_int(bs, cfg->object_type, 2);
    1372           0 :         gf_bs_write_int(bs, cfg->sampling_frequency_index, 4);
    1373           0 :         gf_bs_write_int(bs, cfg->num_front_channel_elements, 4);
    1374           0 :         gf_bs_write_int(bs, cfg->num_side_channel_elements, 4);
    1375           0 :         gf_bs_write_int(bs, cfg->num_back_channel_elements, 4);
    1376           0 :         gf_bs_write_int(bs, cfg->num_lfe_channel_elements, 2);
    1377           0 :         gf_bs_write_int(bs, cfg->num_assoc_data_elements, 3);
    1378           0 :         gf_bs_write_int(bs, cfg->num_valid_cc_elements, 4);
    1379           0 :         gf_bs_write_int(bs, cfg->mono_mixdown_present, 1);
    1380           0 :         if (cfg->mono_mixdown_present) {
    1381           0 :                 gf_bs_write_int(bs, cfg->mono_mixdown_element_number, 4);
    1382             :         }
    1383           0 :         gf_bs_write_int(bs, cfg->stereo_mixdown_present, 1);
    1384           0 :         if (cfg->stereo_mixdown_present) {
    1385           0 :                 gf_bs_write_int(bs, cfg->stereo_mixdown_element_number, 4);
    1386             :         }
    1387           0 :         gf_bs_write_int(bs, cfg->matrix_mixdown_idx_present, 1);
    1388           0 :         if (cfg->matrix_mixdown_idx_present) {
    1389           0 :                 gf_bs_write_int(bs, cfg->matrix_mixdown_idx, 2);
    1390           0 :                 gf_bs_write_int(bs, cfg->pseudo_surround_enable, 1);
    1391             :         }
    1392           0 :         for (i = 0; i < cfg->num_front_channel_elements; i++) {
    1393           0 :                 gf_bs_write_int(bs, cfg->front_element_is_cpe[i], 1);
    1394           0 :                 gf_bs_write_int(bs, cfg->front_element_tag_select[i], 4);
    1395             :         }
    1396           0 :         for (i = 0; i < cfg->num_side_channel_elements; i++) {
    1397           0 :                 gf_bs_write_int(bs, cfg->side_element_is_cpe[i], 1);
    1398           0 :                 gf_bs_write_int(bs, cfg->side_element_tag_select[i], 4);
    1399             :         }
    1400           0 :         for (i = 0; i < cfg->num_back_channel_elements; i++) {
    1401           0 :                 gf_bs_write_int(bs, cfg->back_element_is_cpe[i], 1);
    1402           0 :                 gf_bs_write_int(bs, cfg->back_element_tag_select[i], 4);
    1403             :         }
    1404           0 :         for (i = 0; i < cfg->num_lfe_channel_elements; i++) {
    1405           0 :                 gf_bs_write_int(bs, cfg->lfe_element_tag_select[i], 4);
    1406             :         }
    1407           0 :         for (i = 0; i < cfg->num_assoc_data_elements; i++) {
    1408           0 :                 gf_bs_write_int(bs, cfg->assoc_data_element_tag_select[i], 4);
    1409             :         }
    1410             : 
    1411           0 :         for (i = 0; i < cfg->num_valid_cc_elements; i++) {
    1412           0 :                 gf_bs_write_int(bs, cfg->cc_element_is_ind_sw[i], 1);
    1413           0 :                 gf_bs_write_int(bs, cfg->valid_cc_element_tag_select[i], 4);
    1414             :         }
    1415           0 :         gf_bs_align(bs);
    1416           0 :         gf_bs_write_int(bs, cfg->comment_field_bytes, 8);
    1417           0 :         gf_bs_write_data(bs, (char *)cfg->comments, cfg->comment_field_bytes);
    1418           0 :         return GF_OK;
    1419             : }
    1420             : 
    1421             : GF_EXPORT
    1422         162 : GF_Err gf_m4a_write_config_bs(GF_BitStream *bs, GF_M4ADecSpecInfo *cfg)
    1423             : {
    1424         162 :         if (!cfg->base_sr_index) {
    1425           7 :                 if (!cfg->base_sr) return GF_BAD_PARAM;
    1426          47 :                 while (GF_M4ASampleRates[cfg->base_sr_index]) {
    1427          47 :                         if (GF_M4ASampleRates[cfg->base_sr_index] == cfg->base_sr)
    1428             :                                 break;
    1429          40 :                         cfg->base_sr_index++;
    1430             :                 }
    1431             :         }
    1432         162 :         if (cfg->sbr_sr && !cfg->sbr_sr_index) {
    1433           0 :                 while (GF_M4ASampleRates[cfg->sbr_sr_index]) {
    1434           0 :                         if (GF_M4ASampleRates[cfg->sbr_sr_index] == cfg->sbr_sr)
    1435             :                                 break;
    1436           0 :                         cfg->sbr_sr_index++;
    1437             :                 }
    1438             :         }
    1439             :         /*extended object type*/
    1440         162 :         if (cfg->base_object_type >= 32) {
    1441           3 :                 gf_bs_write_int(bs, 31, 5);
    1442           3 :                 gf_bs_write_int(bs, cfg->base_object_type - 32, 6);
    1443             :         }
    1444             :         else {
    1445         159 :                 gf_bs_write_int(bs, cfg->base_object_type, 5);
    1446             :         }
    1447         162 :         gf_bs_write_int(bs, cfg->base_sr_index, 4);
    1448         162 :         if (cfg->base_sr_index == 0x0F) {
    1449           0 :                 gf_bs_write_int(bs, cfg->base_sr, 24);
    1450             :         }
    1451             : 
    1452         162 :         if (cfg->program_config_element_present) {
    1453           0 :                 gf_bs_write_int(bs, 0, 4);
    1454             :         } else {
    1455         162 :                 cfg->chan_cfg = gf_m4a_get_channel_cfg(cfg->nb_chan);
    1456         162 :                 if (!cfg->chan_cfg) {
    1457           0 :                         GF_LOG(GF_LOG_ERROR, GF_LOG_CODING, ("[AAC] Cannot write decoder config, ProgramConfigElement is missing and channel configuration is not a predefined one !\n"));
    1458             :                         return GF_BAD_PARAM;
    1459             :                 }
    1460         162 :                 gf_bs_write_int(bs, cfg->chan_cfg, 4);
    1461             :         }
    1462             : 
    1463         162 :         if (cfg->base_object_type == 5 || cfg->base_object_type == 29) {
    1464           5 :                 if (cfg->base_object_type == 29) {
    1465           3 :                         cfg->has_ps = 1;
    1466           3 :                         cfg->nb_chan = 1;
    1467             :                 }
    1468           5 :                 cfg->has_sbr = 1;
    1469           5 :                 gf_bs_write_int(bs, cfg->sbr_sr_index, 4);
    1470           5 :                 if (cfg->sbr_sr_index == 0x0F) {
    1471           0 :                         gf_bs_write_int(bs, cfg->sbr_sr, 24);
    1472             :                 }
    1473           5 :                 gf_bs_write_int(bs, cfg->sbr_object_type, 5);
    1474             :         }
    1475             : 
    1476             :         /*object cfg*/
    1477         162 :         switch (cfg->base_object_type) {
    1478         157 :         case 1:
    1479             :         case 2:
    1480             :         case 3:
    1481             :         case 4:
    1482             :         case 6:
    1483             :         case 7:
    1484             :         case 17:
    1485             :         case 19:
    1486             :         case 20:
    1487             :         case 21:
    1488             :         case 22:
    1489             :         case 23:
    1490             :         case 42:
    1491             :         {
    1492             :                 /*frame length flag*/
    1493         157 :                 gf_bs_write_int(bs, 0, 1);
    1494             :                 /*depends on core coder*/
    1495         157 :                 gf_bs_write_int(bs, 0, 1);
    1496             :                 /*ext flag*/
    1497         157 :                 gf_bs_write_int(bs, 0, 1);
    1498             : 
    1499         157 :                 if (cfg->program_config_element_present) {
    1500           0 :                         gf_m4a_write_program_config_element_bs(bs, cfg);
    1501             :                 }
    1502             : 
    1503         157 :                 if ((cfg->base_object_type == 6) || (cfg->base_object_type == 20)) {
    1504           0 :                         gf_bs_write_int(bs, 0, 3);
    1505             :                 }
    1506             :         }
    1507             :         break;
    1508             :         }
    1509             :         /*ER cfg - not supported*/
    1510             : 
    1511             :         /*implicit sbr/ps signaling not written here, cf reframe_adts*/
    1512             :         return GF_OK;
    1513             : }
    1514             : 
    1515             : GF_EXPORT
    1516          11 : GF_Err gf_m4a_write_config(GF_M4ADecSpecInfo *cfg, u8 **dsi, u32 *dsi_size)
    1517             : {
    1518          11 :         GF_BitStream *bs = gf_bs_new(NULL, 0, GF_BITSTREAM_WRITE);
    1519          11 :         gf_m4a_write_config_bs(bs, cfg);
    1520          11 :         gf_bs_get_content(bs, dsi, dsi_size);
    1521          11 :         gf_bs_del(bs);
    1522          11 :         return GF_OK;
    1523             : }
    1524             : 
    1525             : 
    1526             : /*AV1 parsing*/
    1527             : 
    1528           6 : static u32 av1_read_ns(GF_BitStream *bs, u32 n, const char *fname)
    1529             : {
    1530             :         u32 v, res;
    1531             :         Bool extra_bit;
    1532           6 :         int w = (u32)(log(n) / log(2)) + 1;
    1533           6 :         u32 m = (1 << w) - n;
    1534             :         assert(w < 32);
    1535           6 :         v = gf_bs_read_int(bs, w - 1);
    1536           6 :         if (v < m) {
    1537           6 :                 if (fname) {
    1538           0 :                         gf_bs_log(bs, w-1, fname, v);
    1539             :                 }
    1540             :                 return v;
    1541             :         }
    1542           0 :         extra_bit = gf_bs_read_int(bs, 1);
    1543           0 :         res = (v << 1) - m + extra_bit;
    1544           0 :         if (fname) {
    1545           0 :                 gf_bs_log(bs, w, fname, res);
    1546             :         }
    1547             :         return res;
    1548             : }
    1549             : 
    1550        1318 : static void av1_color_config(GF_BitStream *bs, AV1State *state)
    1551             : {
    1552        2636 :         state->config->high_bitdepth = gf_bs_read_int_log(bs, 1, "high_bitdepth");
    1553        1318 :         state->bit_depth = 8;
    1554        1318 :         if (state->config->seq_profile == 2 && state->config->high_bitdepth) {
    1555           0 :                 state->config->twelve_bit = gf_bs_read_int_log(bs, 1, "twelve_bit");
    1556           0 :                 state->bit_depth = state->config->twelve_bit ? 12 : 10;
    1557             :         }
    1558        1318 :         else if (state->config->seq_profile <= 2) {
    1559        1317 :                 state->bit_depth = state->config->high_bitdepth ? 10 : 8;
    1560             :         }
    1561             : 
    1562        1318 :         state->config->monochrome = GF_FALSE;
    1563        1318 :         if (state->config->seq_profile == 1) {
    1564           3 :                 state->config->monochrome = GF_FALSE;
    1565             :         }
    1566             :         else {
    1567        1315 :                 state->config->monochrome = gf_bs_read_int_log(bs, 1, "monochrome");
    1568             :         }
    1569             :         /*NumPlanes = mono_chrome ? 1 : 3;*/
    1570        1318 :         state->color_description_present_flag = gf_bs_read_int_log(bs, 1, "color_description_present_flag");
    1571        1318 :         if (state->color_description_present_flag) {
    1572           1 :                 state->color_primaries = gf_bs_read_int_log(bs, 8, "color_primaries");
    1573           1 :                 state->transfer_characteristics = gf_bs_read_int_log(bs, 8, "transfer_characteristics");
    1574           1 :                 state->matrix_coefficients = gf_bs_read_int_log(bs, 8, "matrix_coefficients");
    1575             :         }
    1576             :         else {
    1577        1317 :                 state->color_primaries = 2/*CP_UNSPECIFIED*/;
    1578        1317 :                 state->transfer_characteristics = 2/*TC_UNSPECIFIED*/;
    1579        1317 :                 state->matrix_coefficients = 2/*MC_UNSPECIFIED*/;
    1580             :         }
    1581        1318 :         if (state->config->monochrome) {
    1582           2 :                 state->color_range = gf_bs_read_int_log(bs, 1, "color_range");
    1583           2 :                 state->config->chroma_subsampling_x = GF_TRUE;
    1584           2 :                 state->config->chroma_subsampling_y = GF_TRUE;
    1585           2 :                 state->config->chroma_sample_position = 0/*CSP_UNKNOWN*/;
    1586           2 :                 state->separate_uv_delta_q = 0;
    1587           2 :                 return;
    1588             :         }
    1589        1316 :         else if (state->color_primaries == 0/*CP_BT_709*/ &&
    1590           0 :                 state->transfer_characteristics == 13/*TC_SRGB*/ &&
    1591           0 :                 state->matrix_coefficients == 0/*MC_IDENTITY*/) {
    1592           0 :                 state->color_range = GF_TRUE;
    1593           0 :                 state->config->chroma_subsampling_x = GF_FALSE;
    1594           0 :                 state->config->chroma_subsampling_y = GF_FALSE;
    1595             :         }
    1596             :         else {
    1597        1316 :                 state->config->chroma_subsampling_x = GF_FALSE;
    1598        1316 :                 state->config->chroma_subsampling_y = GF_FALSE;
    1599             : 
    1600        1316 :                 state->color_range = gf_bs_read_int_log(bs, 1, "color_range");
    1601        1316 :                 if (state->config->seq_profile == 0) {
    1602        1313 :                         state->config->chroma_subsampling_x = GF_TRUE;
    1603        1313 :                         state->config->chroma_subsampling_y = GF_TRUE;
    1604             :                 }
    1605           3 :                 else if (state->config->seq_profile == 1) {
    1606           3 :                         state->config->chroma_subsampling_x = GF_FALSE;
    1607           3 :                         state->config->chroma_subsampling_y = GF_FALSE;
    1608             :                 }
    1609             :                 else {
    1610           0 :                         if (state->bit_depth == 12) {
    1611           0 :                                 state->config->chroma_subsampling_x = gf_bs_read_int_log(bs, 1, "chroma_subsampling_x");
    1612           0 :                                 if (state->config->chroma_subsampling_x)
    1613           0 :                                         state->config->chroma_subsampling_y = gf_bs_read_int_log(bs, 1, "chroma_subsampling_y");
    1614             :                                 else
    1615           0 :                                         state->config->chroma_subsampling_y = GF_FALSE;
    1616             :                         }
    1617             :                         else {
    1618           0 :                                 state->config->chroma_subsampling_x = GF_TRUE;
    1619           0 :                                 state->config->chroma_subsampling_y = GF_FALSE;
    1620             :                         }
    1621             :                 }
    1622        1316 :                 if (state->config->chroma_subsampling_x && state->config->chroma_subsampling_y) {
    1623        1313 :                         state->config->chroma_sample_position = gf_bs_read_int_log(bs, 2, "chroma_sample_position");
    1624             :                 }
    1625             :         }
    1626        1316 :         state->separate_uv_delta_q = gf_bs_read_int_log(bs, 1, "separate_uv_delta_q");
    1627             : }
    1628             : 
    1629             : 
    1630           0 : static u32 av1_uvlc(GF_BitStream *bs, const char *fname)
    1631             : {
    1632             :         u32 res;
    1633             :         u8 leadingZeros = 0;
    1634           0 :         while (1) {
    1635           0 :                 Bool done = gf_bs_read_int(bs, 1);
    1636           0 :                 if (done)
    1637             :                         break;
    1638           0 :                 leadingZeros++;
    1639             :         }
    1640           0 :         if (leadingZeros >= 32) {
    1641             :                 return 0xFFFFFFFF;
    1642             :         }
    1643           0 :         res = gf_bs_read_int(bs, leadingZeros) + (1 << leadingZeros) - 1;
    1644           0 :         gf_bs_log(bs, 2*leadingZeros, fname, res);
    1645           0 :         return res;
    1646             : }
    1647             : 
    1648           0 : static void timing_info(GF_BitStream *bs, AV1State *state) {
    1649             :         u32 time_scale = 0;
    1650             :         u32 num_units_in_display_tick = gf_bs_read_int_log(bs, 32, "num_units_in_display_tick");
    1651           0 :         if (num_units_in_display_tick == 0) {
    1652           0 :                 GF_LOG(GF_LOG_ERROR, GF_LOG_CODING, ("[AV1] num_units_in_display_tick must be greater than 0.\n"));
    1653             :         }
    1654             :         time_scale = gf_bs_read_int_log(bs, 32, "time_scale");
    1655           0 :         if (time_scale == 0) {
    1656           0 :                 GF_LOG(GF_LOG_ERROR, GF_LOG_CODING, ("[AV1] time_scale must be greater than 0.\n"));
    1657             :         }
    1658           0 :         state->equal_picture_interval = gf_bs_read_int_log(bs, 1, "equal_picture_interval");
    1659           0 :         if (state->equal_picture_interval) {
    1660           0 :                 u32 num_ticks_per_picture_minus_1 = av1_uvlc(bs, "num_ticks_per_picture_minus_1");
    1661           0 :                 state->tb_num = time_scale;
    1662           0 :                 state->tb_den = (num_ticks_per_picture_minus_1 + 1)*num_units_in_display_tick;
    1663             :         }
    1664             :         else {
    1665           0 :                 GF_LOG(GF_LOG_ERROR, GF_LOG_CODING, ("[AV1] VFR not supported.\n"));
    1666             :                 //TODO: upload num_units_in_display_tick (eq. to the POC in H264), compute delta between frames, set it as dts_inc in gf_import_aom_av1()
    1667             :         }
    1668           0 : }
    1669             : 
    1670           0 : static void decoder_model_info(AV1State *state, GF_BitStream *bs) {
    1671           0 :         state->buffer_delay_length = 1 + gf_bs_read_int_log(bs, 5, "buffer_delay_length_minus1");
    1672           0 :         gf_bs_read_int_log(bs, 32, "num_units_in_decoding_tick");
    1673           0 :         state->buffer_removal_time_length = gf_bs_read_int_log(bs, 5, "buffer_removal_time_length");
    1674           0 :         state->frame_presentation_time_length = 1 + gf_bs_read_int_log(bs, 5, "frame_presentation_time_length_minus1");
    1675           0 : }
    1676             : 
    1677           0 : static void operating_parameters_info(GF_BitStream *bs, const u8 idx, const u8 buffer_delay_length_minus_1) {
    1678           0 :         const u8 n = buffer_delay_length_minus_1 + 1;
    1679           0 :         gf_bs_read_int_log(bs, n, "decoder_buffer_delay");
    1680           0 :         gf_bs_read_int_log(bs, n, "encoder_buffer_delay");
    1681           0 :         gf_bs_read_int_log(bs, 1, "low_delay_mode_flag");
    1682           0 : }
    1683             : 
    1684        1318 : static void av1_parse_sequence_header_obu(GF_BitStream *bs, AV1State *state)
    1685             : {
    1686             :         u8 buffer_delay_length_minus_1 = 0;
    1687        1318 :         state->frame_state.seen_seq_header = GF_TRUE;
    1688        1318 :         state->config->seq_profile = gf_bs_read_int_log(bs, 3, "seq_profile");
    1689        1318 :         state->still_picture = gf_bs_read_int_log(bs, 1, "still_picture");
    1690        1318 :         state->reduced_still_picture_header = gf_bs_read_int_log(bs, 1, "reduced_still_picture_header");
    1691        1318 :         if (state->reduced_still_picture_header) {
    1692             :                 //timing_info_present_flag = GF_FALSE;
    1693             :                 //initial_display_delay_present_flag = GF_FALSE;
    1694           4 :                 state->operating_points_count = 1;
    1695           4 :                 state->config->seq_level_idx_0 = gf_bs_read_int_log(bs, 5, "seq_level_idx_0");
    1696             :         }
    1697             :         else {
    1698             :                 u8 i = 0;
    1699             :                 Bool initial_display_delay_present_flag;
    1700             :                 Bool timing_info_present_flag = gf_bs_read_int_log(bs, 1, "timing_info_present_flag");
    1701        1314 :                 if (timing_info_present_flag) {
    1702           0 :                         timing_info(bs, state);
    1703           0 :                         state->decoder_model_info_present_flag = gf_bs_read_int_log(bs, 1, "decoder_model_info_present_flag");
    1704           0 :                         if (state->decoder_model_info_present_flag) {
    1705           0 :                                 decoder_model_info(state, bs);
    1706             :                         }
    1707             :                 }
    1708             :                 else {
    1709        1314 :                         state->decoder_model_info_present_flag = GF_FALSE;
    1710             :                 }
    1711             :                 initial_display_delay_present_flag = gf_bs_read_int_log(bs, 1, "initial_display_delay_present_flag");
    1712        1314 :                 state->operating_points_count = 1 + gf_bs_read_int_log(bs, 5, "operating_points_count_minus1");
    1713        2762 :                 for (i = 0; i < state->operating_points_count; i++) {
    1714             :                         u8 seq_level_idx_i, seq_tier = 0;
    1715             : 
    1716        2896 :                         state->operating_point_idc[i] = gf_bs_read_int_log_idx(bs, 12, "operating_point_idc", i);
    1717             : 
    1718        1448 :                         seq_level_idx_i = gf_bs_read_int_log_idx(bs, 5, "seq_level_idx", i);
    1719        1448 :                         if (i == 0) state->config->seq_level_idx_0 = seq_level_idx_i;
    1720             : 
    1721        1448 :                         if (seq_level_idx_i > 7) {
    1722           7 :                                 seq_tier = gf_bs_read_int_log_idx(bs, 1, "seq_tier", i);
    1723             :                         }
    1724        1448 :                         if (i == 0) state->config->seq_tier_0 = seq_tier;
    1725             : 
    1726        1448 :                         if (state->decoder_model_info_present_flag) {
    1727           0 :                                 state->decoder_model_present_for_this_op[i] = gf_bs_read_int_log_idx(bs, 1, "decoder_model_present_for_this_op", i);
    1728           0 :                                 if (state->decoder_model_present_for_this_op[i]) {
    1729           0 :                                         operating_parameters_info(bs, i, buffer_delay_length_minus_1);
    1730             :                                 }
    1731             :                         }
    1732             :                         else {
    1733        1448 :                                 state->decoder_model_present_for_this_op[i] = 0;
    1734             :                         }
    1735        1448 :                         if (initial_display_delay_present_flag) {
    1736           7 :                                 if (gf_bs_read_int_log_idx(bs, 1, "initial_display_delay_present_for_this_op", i) ) {
    1737           2 :                                         gf_bs_read_int_log_idx(bs, 4, "initial_display_delay_minus1", i);
    1738             :                                 }
    1739             :                         }
    1740             :                 }
    1741             :         }
    1742             : 
    1743             :         //operatingPoint = av1_choose_operating_point(bs);
    1744        1318 :         state->OperatingPointIdc = 0;//TODO: operating_point_idc[operatingPoint];
    1745             : 
    1746        1318 :         state->frame_width_bits_minus_1 = gf_bs_read_int_log(bs, 4, "frame_width_bits_minus1");
    1747        1318 :         state->frame_height_bits_minus_1 = gf_bs_read_int_log(bs, 4, "frame_height_bits_minus1");
    1748        2636 :         state->width = gf_bs_read_int_log(bs, state->frame_width_bits_minus_1 + 1, "width_minus1") + 1;
    1749        2636 :         state->height = gf_bs_read_int_log(bs, state->frame_height_bits_minus_1 + 1, "height_minus1") + 1;
    1750        1318 :         state->sequence_width = state->width;
    1751        1318 :         state->sequence_height = state->height;
    1752        1318 :         state->frame_id_numbers_present_flag = GF_FALSE;
    1753        1318 :         if (!state->reduced_still_picture_header) {
    1754        1314 :                 state->frame_id_numbers_present_flag = gf_bs_read_int_log(bs, 1, "frame_id_numbers_present_flag");
    1755             :         }
    1756        1318 :         if (state->frame_id_numbers_present_flag) {
    1757           0 :                 state->delta_frame_id_length_minus_2 = gf_bs_read_int_log(bs, 4, "delta_frame_id_length_minus2");
    1758           0 :                 state->additional_frame_id_length_minus_1 = gf_bs_read_int_log(bs, 3, "additional_frame_id_length_minus1");
    1759             :         }
    1760        1318 :         state->use_128x128_superblock = gf_bs_read_int_log(bs, 1, "use_128x128_superblock");
    1761        1318 :         gf_bs_read_int_log(bs, 1, "enable_filter_intra");
    1762        1318 :         gf_bs_read_int_log(bs, 1, "enable_intra_edge_filter");
    1763        1318 :         if (state->reduced_still_picture_header) {
    1764             :                 /*enable_interintra_compound = 0;
    1765             :                 enable_masked_compound = 0;
    1766             :                 enable_dual_filter = 0;
    1767             :                 enable_jnt_comp = 0;
    1768             :                 enable_ref_frame_mvs = 0;*/
    1769           4 :                 state->enable_warped_motion = 0;
    1770           4 :                 state->enable_order_hint = GF_FALSE;
    1771           4 :                 state->OrderHintBits = 0;
    1772           4 :                 state->seq_force_integer_mv = 2/*SELECT_INTEGER_MV*/;
    1773           4 :                 state->seq_force_screen_content_tools = 2/*SELECT_SCREEN_CONTENT_TOOLS*/;
    1774             :         }
    1775             :         else {
    1776             :                 Bool seq_choose_screen_content_tools;
    1777        1314 :                 gf_bs_read_int_log(bs, 1, "enable_interintra_compound");
    1778        1314 :                 gf_bs_read_int_log(bs, 1, "enable_masked_compound");
    1779        1314 :                 state->enable_warped_motion = gf_bs_read_int_log(bs, 1, "enable_warped_motion");
    1780        1314 :                 gf_bs_read_int_log(bs, 1, "enable_dual_filter");
    1781        1314 :                 state->enable_order_hint = gf_bs_read_int_log(bs, 1, "enable_order_hint");
    1782        1314 :                 if (state->enable_order_hint) {
    1783        1297 :                         gf_bs_read_int_log(bs, 1, "enable_jnt_comp");
    1784        1297 :                         state->enable_ref_frame_mvs = gf_bs_read_int_log(bs, 1, "enable_ref_frame_mvs");
    1785             :                 }
    1786             :                 else {
    1787             :                         /*enable_jnt_comp =  0*/;
    1788             :                         /*enable_ref_frame_mvs = 0*/;
    1789             :                 }
    1790             :                 seq_choose_screen_content_tools = gf_bs_read_int_log(bs, 1, "seq_choose_screen_content_tools");
    1791        1314 :                 state->seq_force_screen_content_tools = 0;
    1792        1314 :                 if (seq_choose_screen_content_tools) {
    1793        1297 :                         state->seq_force_screen_content_tools = 2/*SELECT_SCREEN_CONTENT_TOOLS*/;
    1794             :                 }
    1795             :                 else {
    1796          17 :                         state->seq_force_screen_content_tools = gf_bs_read_int_log(bs, 1, "seq_force_screen_content_tools");
    1797             :                 }
    1798             : 
    1799        1314 :                 state->seq_force_integer_mv = 0;
    1800        1314 :                 if (state->seq_force_screen_content_tools > 0) {
    1801             :                         const Bool seq_choose_integer_mv = gf_bs_read_int_log(bs, 1, "seq_choose_integer_mv");
    1802        1297 :                         if (seq_choose_integer_mv) {
    1803        1297 :                                 state->seq_force_integer_mv = 2/*SELECT_INTEGER_MV*/;
    1804             :                         }
    1805             :                         else {
    1806           0 :                                 state->seq_force_integer_mv = gf_bs_read_int_log(bs, 1, "seq_force_integer_mv");
    1807             :                         }
    1808             :                 }
    1809             :                 else {
    1810          17 :                         state->seq_force_integer_mv = 2/*SELECT_INTEGER_MV*/;
    1811             :                 }
    1812        1314 :                 if (state->enable_order_hint) {
    1813        1297 :                         u8 order_hint_bits_minus_1 = gf_bs_read_int_log(bs, 3, "order_hint_bits_minus1");
    1814        1297 :                         state->OrderHintBits = order_hint_bits_minus_1 + 1;
    1815             :                 }
    1816             :                 else {
    1817          17 :                         state->OrderHintBits = 0;
    1818             :                 }
    1819             :         }
    1820             : 
    1821        1318 :         state->enable_superres = gf_bs_read_int_log(bs, 1, "enable_superres");
    1822        1318 :         state->enable_cdef = gf_bs_read_int_log(bs, 1, "enable_cdef");
    1823        1318 :         state->enable_restoration = gf_bs_read_int_log(bs, 1, "enable_restoration");
    1824        1318 :         av1_color_config(bs, state);
    1825        1318 :         state->film_grain_params_present = gf_bs_read_int_log(bs, 1, "film_grain_params_present");
    1826        1318 : }
    1827             : 
    1828             : 
    1829             : 
    1830             : #define IVF_FILE_HEADER_SIZE 32
    1831             : 
    1832        3152 : Bool gf_media_probe_ivf(GF_BitStream *bs)
    1833             : {
    1834             :         u32 dw = 0;
    1835        3152 :         if (gf_bs_available(bs) < IVF_FILE_HEADER_SIZE) return GF_FALSE;
    1836             : 
    1837        3148 :         dw = gf_bs_peek_bits(bs, 32, 0);
    1838        3148 :         if (dw != GF_4CC('D', 'K', 'I', 'F')) {
    1839             :                 return GF_FALSE;
    1840             :         }
    1841          32 :         return GF_TRUE;
    1842             : }
    1843             : 
    1844          16 : GF_Err gf_media_parse_ivf_file_header(GF_BitStream *bs, u32 *width, u32 *height, u32 *codec_fourcc, u32 *timebase_num, u32 *timebase_den, u32 *num_frames)
    1845             : {
    1846             :         u32 dw = 0;
    1847             : 
    1848          16 :         if (!width || !height || !codec_fourcc || !timebase_den || !timebase_num || !num_frames) {
    1849             :                 assert(0);
    1850             :                 return GF_BAD_PARAM;
    1851             :         }
    1852             : 
    1853          16 :         if (gf_bs_available(bs) < IVF_FILE_HEADER_SIZE) {
    1854           0 :                 GF_LOG(GF_LOG_ERROR, GF_LOG_CODING, ("[IVF] Not enough bytes available ("LLU").\n", gf_bs_available(bs)));
    1855             :                 return GF_NON_COMPLIANT_BITSTREAM;
    1856             :         }
    1857             : 
    1858          16 :         dw = gf_bs_read_u32(bs);
    1859          16 :         if (dw != GF_4CC('D', 'K', 'I', 'F')) {
    1860           0 :                 GF_LOG(GF_LOG_INFO, GF_LOG_CODING, ("[IVF] Invalid signature\n"));
    1861             :                 return GF_NON_COMPLIANT_BITSTREAM;
    1862             :         }
    1863             : 
    1864          16 :         dw = gf_bs_read_u16_le(bs);
    1865          16 :         if (dw != 0) {
    1866           0 :                 GF_LOG(GF_LOG_ERROR, GF_LOG_CODING, ("[IVF] Wrong IVF version. 0 expected, got %u\n", dw));
    1867             :                 return GF_NON_COMPLIANT_BITSTREAM;
    1868             :         }
    1869             : 
    1870          16 :         dw = gf_bs_read_u16_le(bs); //length of header in bytes
    1871          16 :         if (dw != IVF_FILE_HEADER_SIZE) {
    1872           0 :                 GF_LOG(GF_LOG_ERROR, GF_LOG_CODING, ("[IVF] Wrong IVF header length. Expected 32 bytes, got %u\n", dw));
    1873             :                 return GF_NON_COMPLIANT_BITSTREAM;
    1874             :         }
    1875             : 
    1876          16 :         *codec_fourcc = gf_bs_read_u32(bs);
    1877             : 
    1878          16 :         *width = gf_bs_read_u16_le(bs);
    1879          16 :         *height = gf_bs_read_u16_le(bs);
    1880             : 
    1881          16 :         *timebase_num = gf_bs_read_u32_le(bs);
    1882          16 :         *timebase_den = gf_bs_read_u32_le(bs);
    1883             : 
    1884          16 :         *num_frames = gf_bs_read_u32_le(bs);
    1885          16 :         gf_bs_read_u32_le(bs); //skip unused
    1886             : 
    1887          16 :         return GF_OK;
    1888             : }
    1889             : 
    1890       58633 : GF_Err gf_media_parse_ivf_frame_header(GF_BitStream *bs, u64 *frame_size, u64 *pts)
    1891             : {
    1892       58633 :         if (!frame_size) return GF_BAD_PARAM;
    1893       58633 :         if (gf_bs_available(bs) < 12)
    1894             :                 return GF_BUFFER_TOO_SMALL;
    1895             : 
    1896       58633 :         *frame_size = gf_bs_read_u32_le(bs);
    1897       58633 :         if (*frame_size > 256 * 1024 * 1024) {
    1898           0 :                 GF_LOG(GF_LOG_ERROR, GF_LOG_CODING, ("[IVF] Wrong frame size %u\n", *frame_size));
    1899           0 :                 *frame_size = 0;
    1900           0 :                 return GF_NON_COMPLIANT_BITSTREAM;
    1901             :         }
    1902             : 
    1903       58633 :         *pts = gf_bs_read_u64_le(bs);
    1904             : 
    1905       58633 :         return GF_OK;
    1906             : }
    1907             : 
    1908        3439 : GF_Err gf_media_vp9_parse_superframe(GF_BitStream *bs, u64 ivf_frame_size, u32 *num_frames_in_superframe, u32 frame_sizes[VP9_MAX_FRAMES_IN_SUPERFRAME], u32 *superframe_index_size)
    1909             : {
    1910             :         u32 byte, bytes_per_framesize;
    1911        3439 :         u64 pos = gf_bs_get_position(bs), i = 0;
    1912             :         GF_Err e;
    1913             : 
    1914             :         assert(bs && num_frames_in_superframe);
    1915             : 
    1916             :         /*initialize like there is no superframe*/
    1917             :         memset(frame_sizes, 0, VP9_MAX_FRAMES_IN_SUPERFRAME * sizeof(frame_sizes[0]));
    1918        3439 :         *num_frames_in_superframe = 1;
    1919        3439 :         frame_sizes[0] = (u32)ivf_frame_size;
    1920        3439 :         *superframe_index_size = 0;
    1921             : 
    1922        3439 :         e = gf_bs_seek(bs, pos + ivf_frame_size - 1);
    1923        3439 :         if (e) return e;
    1924             : 
    1925        3439 :         byte = gf_bs_read_u8(bs);
    1926        3439 :         if ((byte & 0xe0) != 0xc0)
    1927             :                 goto exit; /*no superframe*/
    1928             : 
    1929           0 :         bytes_per_framesize = 1 + ((byte & 0x18) >> 3);
    1930           0 :         *num_frames_in_superframe = (u32)(1 + (byte & 0x7));
    1931             : 
    1932             :         /*superframe_index()*/
    1933           0 :         *superframe_index_size = 2 + bytes_per_framesize * *num_frames_in_superframe;
    1934           0 :         gf_bs_seek(bs, pos + ivf_frame_size - *superframe_index_size);
    1935           0 :         byte = gf_bs_read_u8(bs);
    1936           0 :         if ((byte & 0xe0) != 0xc0)
    1937             :                 goto exit; /*no superframe*/
    1938             : 
    1939           0 :         frame_sizes[0] = 0;
    1940           0 :         for (i = 0; i < *num_frames_in_superframe; ++i) {
    1941           0 :                 gf_bs_read_data(bs, (char*)(frame_sizes + i), bytes_per_framesize);
    1942             :         }
    1943             : 
    1944        3439 : exit:
    1945        3439 :         gf_bs_seek(bs, pos);
    1946        3439 :         return e;
    1947             : }
    1948             : 
    1949             : 
    1950         141 : static Bool vp9_frame_sync_code(GF_BitStream *bs)
    1951             : {
    1952         141 :         u8 val = gf_bs_read_int_log(bs, 8, "syncbyte1");
    1953         141 :         if (val != 0x49)
    1954             :                 return GF_FALSE;
    1955             : 
    1956         141 :         val = gf_bs_read_int_log(bs, 8, "syncbyte2");
    1957         141 :         if (val != 0x83)
    1958             :                 return GF_FALSE;
    1959             : 
    1960         141 :         val = gf_bs_read_int_log(bs, 8, "syncbyte3");
    1961         141 :         if (val != 0x42)
    1962             :                 return GF_FALSE;
    1963             : 
    1964         141 :         return GF_TRUE;
    1965             : }
    1966             : 
    1967             : typedef enum {
    1968             :         CS_UNKNOWN = 0,
    1969             :         CS_BT_601 = 1,
    1970             :         CS_BT_709 = 2,
    1971             :         CS_SMPTE_170 = 3,
    1972             :         CS_SMPTE_240 = 4,
    1973             :         CS_BT_2020 = 5,
    1974             :         CS_RESERVED = 6,
    1975             :         CS_RGB = 7,
    1976             : } VP9_color_space;
    1977             : 
    1978             : static const int VP9_CS_to_23001_8_colour_primaries[] = { -1/*undefined*/, 5, 1, 6, 7, 9, -1/*reserved*/, 1 };
    1979             : static const int VP9_CS_to_23001_8_transfer_characteristics[] = { -1/*undefined*/, 5, 1, 6, 7, 9, -1/*reserved*/, 13 };
    1980             : static const int VP9_CS_to_23001_8_matrix_coefficients[] = { -1/*undefined*/, 6, 1, -1, -1, 9, -1/*reserved*/, 0 };
    1981             : 
    1982         141 : static GF_Err vp9_color_config(GF_BitStream *bs, GF_VPConfig *vp9_cfg)
    1983             : {
    1984             :         VP9_color_space color_space;
    1985             : 
    1986         141 :         if (vp9_cfg->profile >= 2) {
    1987             :                 Bool ten_or_twelve_bit = gf_bs_read_int_log(bs, 1, "ten_or_twelve_bit");
    1988           0 :                 vp9_cfg->bit_depth = ten_or_twelve_bit ? 12 : 10;
    1989             :         }
    1990             :         else {
    1991         141 :                 vp9_cfg->bit_depth = 8;
    1992             :         }
    1993             : 
    1994             :         color_space = gf_bs_read_int_log(bs, 3, "color_space");
    1995         141 :         vp9_cfg->colour_primaries = VP9_CS_to_23001_8_colour_primaries[color_space];
    1996         141 :         vp9_cfg->transfer_characteristics = VP9_CS_to_23001_8_transfer_characteristics[color_space];
    1997         141 :         vp9_cfg->matrix_coefficients = VP9_CS_to_23001_8_matrix_coefficients[color_space];
    1998         141 :         if (color_space != CS_RGB) {
    1999         141 :                 vp9_cfg->video_fullRange_flag = gf_bs_read_int_log(bs, 1, "video_fullRange_flag");
    2000         141 :                 if (vp9_cfg->profile == 1 || vp9_cfg->profile == 3) {
    2001           0 :                         u8 subsampling_x, subsampling_y, subsampling_xy_to_chroma_subsampling[2][2] = { {3, 0}, {2, 0} };
    2002             :                         subsampling_x = gf_bs_read_int_log(bs, 1, "subsampling_x");
    2003             :                         subsampling_y = gf_bs_read_int_log(bs, 1, "subsampling_x");
    2004           0 :                         vp9_cfg->chroma_subsampling = subsampling_xy_to_chroma_subsampling[subsampling_x][subsampling_y];
    2005             :                         Bool reserved_zero = gf_bs_read_int_log(bs, 1, "reserved_zero");
    2006           0 :                         if (reserved_zero) {
    2007           0 :                                 GF_LOG(GF_LOG_ERROR, GF_LOG_CODING, ("[VP9] color config reserved zero (1) is not zero.\n"));
    2008           0 :                                 return GF_NON_COMPLIANT_BITSTREAM;
    2009             :                         }
    2010             :                 }
    2011             :                 else {
    2012         141 :                         vp9_cfg->chroma_subsampling = 0;
    2013             :                 }
    2014             :         }
    2015             :         else {
    2016           0 :                 vp9_cfg->video_fullRange_flag = GF_TRUE;
    2017           0 :                 if (vp9_cfg->profile == 1 || vp9_cfg->profile == 3) {
    2018           0 :                         vp9_cfg->chroma_subsampling = 3;
    2019             :                         Bool reserved_zero = gf_bs_read_int_log(bs, 1, "reserved_zero");
    2020           0 :                         if (reserved_zero) {
    2021           0 :                                 GF_LOG(GF_LOG_ERROR, GF_LOG_CODING, ("[VP9] color config reserved zero (2) is not zero.\n"));
    2022             :                                 return GF_NON_COMPLIANT_BITSTREAM;
    2023             :                         }
    2024             :                 }
    2025             :         }
    2026             : 
    2027             :         return GF_OK;
    2028             : }
    2029             : 
    2030             : static void vp9_compute_image_size(int FrameWidth, int FrameHeight, int *Sb64Cols, int *Sb64Rows)
    2031             : {
    2032        3439 :         int MiCols = (FrameWidth + 7) >> 3;
    2033        3439 :         int MiRows = (FrameHeight + 7) >> 3;
    2034        3439 :         *Sb64Cols = (MiCols + 7) >> 3;
    2035        3439 :         *Sb64Rows = (MiRows + 7) >> 3;
    2036             : }
    2037             : 
    2038         141 : static void vp9_frame_size(GF_BitStream *bs, int *FrameWidth, int *FrameHeight, int *Sb64Cols, int *Sb64Rows)
    2039             : {
    2040         141 :         int frame_width_minus_1 = gf_bs_read_int_log(bs, 16, "frame_width_minus_1");
    2041         141 :         int frame_height_minus_1 = gf_bs_read_int_log(bs, 16, "frame_height_minus_1");
    2042         141 :         if (frame_width_minus_1 + 1 != *FrameWidth || frame_height_minus_1 + 1 != *FrameHeight) {
    2043         141 :                 if (*FrameWidth || *FrameHeight)
    2044           0 :                         GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[VP9] inconsistent frame dimensions: previous was %dx%d, new one is %dx%d.\n", *FrameWidth, *FrameHeight, frame_width_minus_1 + 1, frame_height_minus_1 + 1));
    2045             :         }
    2046         141 :         *FrameWidth = frame_width_minus_1 + 1;
    2047         141 :         *FrameHeight = frame_height_minus_1 + 1;
    2048         141 :         vp9_compute_image_size(*FrameWidth, *FrameHeight, Sb64Cols, Sb64Rows);
    2049         141 : }
    2050             : 
    2051        3439 : static void vp9_render_size(GF_BitStream *bs, int FrameWidth, int FrameHeight, int *renderWidth, int *renderHeight)
    2052             : {
    2053             :         Bool render_and_frame_size_different = gf_bs_read_int_log(bs, 1, "render_and_frame_size_different");
    2054        3439 :         if (render_and_frame_size_different == 1) {
    2055           0 :                 int render_width_minus_1 = gf_bs_read_int_log(bs, 16, "render_width_minus_1");
    2056           0 :                 int render_height_minus_1 = gf_bs_read_int_log(bs, 16, "render_height_minus_1");
    2057           0 :                 *renderWidth = render_width_minus_1 + 1;
    2058           0 :                 *renderHeight = render_height_minus_1 + 1;
    2059             :         }
    2060             :         else {
    2061        3439 :                 *renderWidth = FrameWidth;
    2062        3439 :                 *renderHeight = FrameHeight;
    2063             :         }
    2064        3439 : }
    2065             : 
    2066         423 : static s64 vp9_s(GF_BitStream *bs, int n, const char *fname, u32 idx) {
    2067         423 :         s64 value = gf_bs_read_int(bs, n);
    2068         423 :         Bool sign = gf_bs_read_int(bs, 1);
    2069         423 :         if (sign) value = -value;
    2070         423 :         gf_bs_log_idx(bs, n+1, fname, value, idx, -1, -1);
    2071         423 :         return value;
    2072             : }
    2073             : 
    2074        3439 : static void vp9_loop_filter_params(GF_BitStream *bs)
    2075             : {
    2076        3439 :         /*loop_filter_level = */gf_bs_read_int_log(bs, 6, "loop_filter_level");
    2077        3439 :         /*loop_filter_sharpness = */gf_bs_read_int_log(bs, 3, "loop_filter_sharpness");
    2078             :         Bool loop_filter_delta_enabled = gf_bs_read_int_log(bs, 1, "loop_filter_delta_enabled");
    2079        3439 :         if (loop_filter_delta_enabled == 1) {
    2080             :                 Bool loop_filter_delta_update = gf_bs_read_int_log(bs, 1, "loop_filter_delta_update");
    2081        3439 :                 if (loop_filter_delta_update == GF_TRUE) {
    2082             :                         int i;
    2083         564 :                         for (i = 0; i < 4; i++) {
    2084             :                                 Bool update_ref_delta = gf_bs_read_int_log_idx(bs, 1, "update_ref_delta", i);
    2085         564 :                                 if (update_ref_delta == GF_TRUE)
    2086         423 :                                         vp9_s(bs, 6, "loop_filter_ref_deltas", i);
    2087             :                         }
    2088         282 :                         for (i = 0; i < 2; i++) {
    2089             :                                 Bool update_mode_delta = gf_bs_read_int_log_idx(bs, 1, "update_mode_delta", i);
    2090         282 :                                 if (update_mode_delta == GF_TRUE)
    2091           0 :                                         vp9_s(bs, 6, "loop_filter_mode_deltas", i);
    2092             :                         }
    2093             :                 }
    2094             :         }
    2095        3439 : }
    2096             : 
    2097             : static void vp9_quantization_params(GF_BitStream *bs)
    2098             : {
    2099        3439 :         /*base_q_idx = */gf_bs_read_int_log(bs, 8, "base_q_idx");
    2100             : }
    2101             : 
    2102             : #define VP9_MAX_SEGMENTS 8
    2103             : #define VP9_SEG_LVL_MAX 4
    2104             : static const int segmentation_feature_bits[VP9_SEG_LVL_MAX] = { 8, 6, 2, 0 };
    2105             : static const int segmentation_feature_signed[VP9_SEG_LVL_MAX] = { 1, 1, 0, 0 };
    2106             : 
    2107             : #define VP9_MIN_TILE_WIDTH_B64 4
    2108             : #define VP9_MAX_TILE_WIDTH_B64 64
    2109             : 
    2110        3439 : static void vp9_segmentation_params(GF_BitStream *bs)
    2111             : {
    2112             :         Bool segmentation_enabled = gf_bs_read_int_log(bs, 1, "segmentation_enabled");
    2113        3439 :         if (segmentation_enabled == 1) {
    2114             :                 int i;
    2115             :                 Bool segmentation_update_map = gf_bs_read_int_log(bs, 1, "segmentation_update_map");
    2116           0 :                 if (segmentation_update_map) {
    2117           0 :                         for (i = 0; i < 7; i++)
    2118             :                                 /*segmentation_tree_probs[i] = read_prob()*/
    2119           0 :                                 /*segmentation_temporal_update = */gf_bs_read_int_log(bs, 1, "segmentation_temporal_update");
    2120             :                         /*for (i = 0; i < 3; i++)
    2121             :                                 segmentation_pred_prob[i] = segmentation_temporal_update ? read_prob() : 255*/
    2122             :                 }
    2123             :                 Bool segmentation_update_data = gf_bs_read_int_log(bs, 1, "segmentation_update_data");
    2124           0 :                 if (segmentation_update_data == 1) {
    2125           0 :                         /*segmentation_abs_or_delta_update =*/ gf_bs_read_int_log(bs, 1, "segmentation_abs_or_delta_update");
    2126           0 :                         for (i = 0; i < VP9_MAX_SEGMENTS; i++) {
    2127             :                                 int j;
    2128           0 :                                 for (j = 0; j < VP9_SEG_LVL_MAX; j++) {
    2129             :                                         /*feature_value = 0*/
    2130             :                                         Bool feature_enabled = gf_bs_read_int_log(bs, 1, "feature_enabled");
    2131             :                                         /*FeatureEnabled[i][j] = feature_enabled*/
    2132           0 :                                         if (feature_enabled) {
    2133           0 :                                                 int bits_to_read = segmentation_feature_bits[j];
    2134           0 :                                                 /*feature_value =*/ gf_bs_read_int_log(bs, bits_to_read, "feature_value");
    2135           0 :                                                 if (segmentation_feature_signed[j] == 1) {
    2136           0 :                                                         /*Bool feature_sign = */gf_bs_read_int_log(bs, 1, "feature_sign");
    2137             :                                                         /*if (feature_sign == 1)
    2138             :                                                                 feature_value *= -1*/
    2139             :                                                 }
    2140             :                                         }
    2141             :                                         /*FeatureData[i][j] = feature_value*/
    2142             :                                 }
    2143             :                         }
    2144             :                 }
    2145             :         }
    2146        3439 : }
    2147             : 
    2148             : static int calc_min_log2_tile_cols(int Sb64Cols) {
    2149             :         int minLog2 = 0;
    2150        3439 :         while ((VP9_MAX_TILE_WIDTH_B64 << minLog2) < Sb64Cols)
    2151           0 :                 minLog2++;
    2152             : 
    2153             :         return minLog2;
    2154             : }
    2155             : 
    2156             : static int calc_max_log2_tile_cols(int Sb64Cols) {
    2157             :         int maxLog2 = 1;
    2158        5155 :         while ((Sb64Cols >> maxLog2) >= VP9_MIN_TILE_WIDTH_B64)
    2159        1716 :                 maxLog2++;
    2160             : 
    2161        3439 :         return maxLog2 - 1;
    2162             : }
    2163             : 
    2164        3439 : static void vp9_tile_info(GF_BitStream *bs, int Sb64Cols)
    2165             : {
    2166             :         Bool tile_rows_log2;
    2167             :         int minLog2TileCols = calc_min_log2_tile_cols(Sb64Cols);
    2168             :         int maxLog2TileCols = calc_max_log2_tile_cols(Sb64Cols);
    2169             :         int tile_cols_log2 = minLog2TileCols;
    2170        6878 :         while (tile_cols_log2 < maxLog2TileCols) {
    2171             :                 Bool increment_tile_cols_log2 = gf_bs_read_int_log(bs, 1, "increment_tile_cols_log2");
    2172         858 :                 if (increment_tile_cols_log2)
    2173           0 :                         tile_cols_log2++;
    2174             :                 else
    2175             :                         break;
    2176             :         }
    2177             :         tile_rows_log2 = gf_bs_read_int_log(bs, 1, "tile_rows_log2");
    2178        3439 :         if (tile_rows_log2) {
    2179           0 :                 /*Bool increment_tile_rows_log2 = */gf_bs_read_int_log(bs, 1, "increment_tile_rows_log2");
    2180             :                 //tile_rows_log2 += increment_tile_rows_log2;
    2181             :         }
    2182        3439 : }
    2183             : 
    2184        3298 : static void vp9_frame_size_with_refs(GF_BitStream *bs, u8 refresh_frame_flags, u8 * ref_frame_idx, int * RefFrameWidth, int *RefFrameHeight,
    2185             :         int *FrameWidth, int *FrameHeight, int *RenderWidth, int *RenderHeight, int *Sb64Cols, int *Sb64Rows)
    2186             : {
    2187             :         Bool found_ref;
    2188             :         int i;
    2189        3298 :         for (i = 0; i < 3; i++) {
    2190             :                 found_ref = gf_bs_read_int_log(bs, 1, "found_ref");
    2191        3298 :                 if (found_ref) {
    2192        3298 :                         *FrameWidth  = RefFrameWidth [ref_frame_idx[i]];
    2193        3298 :                         *FrameHeight = RefFrameHeight[ref_frame_idx[i]];
    2194        3298 :                         break;
    2195             :                 }
    2196             :         }
    2197        3298 :         if (found_ref == 0) {
    2198           0 :                 vp9_frame_size(bs, FrameWidth, FrameHeight, Sb64Cols, Sb64Rows);
    2199             :         }
    2200             :         else {
    2201        3298 :                 vp9_compute_image_size(*FrameWidth, *FrameHeight, Sb64Cols, Sb64Rows);
    2202             :         }
    2203             : 
    2204        3298 :         vp9_render_size(bs, *FrameWidth, *FrameHeight, RenderWidth, RenderHeight);
    2205        3298 : }
    2206             : 
    2207        3298 : static void vp9_read_interpolation_filter(GF_BitStream *bs)
    2208             : {
    2209             :         Bool is_filter_switchable = gf_bs_read_int_log(bs, 1, "is_filter_switchable");
    2210        3298 :         if (!is_filter_switchable) {
    2211         604 :                 /*raw_interpolation_filter = */gf_bs_read_int_log(bs, 2, "raw_interpolation_filter");
    2212             :         }
    2213        3298 : }
    2214             : 
    2215             : 
    2216             : #define VP9_KEY_FRAME 0
    2217             : 
    2218        3439 : GF_Err gf_media_vp9_parse_sample(GF_BitStream *bs, GF_VPConfig *vp9_cfg, Bool *key_frame, u32 *FrameWidth, u32 *FrameHeight, u32 *renderWidth, u32 *renderHeight)
    2219             : {
    2220             :         Bool FrameIsIntra = GF_FALSE, profile_low_bit, profile_high_bit, show_existing_frame = GF_FALSE, frame_type = GF_FALSE, show_frame = GF_FALSE, error_resilient_mode = GF_FALSE;
    2221             :         /*u8 frame_context_idx = 0, reset_frame_context = 0, frame_marker = 0*/;
    2222        3439 :         int Sb64Cols = 0, Sb64Rows = 0, i;
    2223             :         u8 refresh_frame_flags = 0;
    2224             : 
    2225             :         assert(bs && key_frame);
    2226             : 
    2227             :         /*uncompressed header*/
    2228        3439 :         /*frame_marker = */gf_bs_read_int_log(bs, 2, "frame_marker");
    2229             :         profile_low_bit = gf_bs_read_int_log(bs, 1, "profile_low_bit");
    2230             :         profile_high_bit = gf_bs_read_int_log(bs, 1, "profile_high_bit");
    2231        3439 :         vp9_cfg->profile = (profile_high_bit << 1) + profile_low_bit;
    2232        3439 :         if (vp9_cfg->profile == 3) {
    2233             :                 Bool reserved_zero = gf_bs_read_int_log(bs, 1, "reserved_zero");
    2234           0 :                 if (reserved_zero) {
    2235           0 :                         GF_LOG(GF_LOG_ERROR, GF_LOG_CODING, ("[VP9] uncompressed header reserved zero is not zero.\n"));
    2236             :                         return GF_NON_COMPLIANT_BITSTREAM;
    2237             :                 }
    2238             :         }
    2239             : 
    2240             :         show_existing_frame = gf_bs_read_int_log(bs, 1, "show_existing_frame");
    2241        3439 :         if (show_existing_frame == GF_TRUE) {
    2242           0 :                 /*frame_to_show_map_idx = */gf_bs_read_int_log(bs, 3, "frame_to_show_map_idx");
    2243           0 :                 return GF_OK;
    2244             :         }
    2245             : 
    2246             :         frame_type = gf_bs_read_int_log(bs, 1, "frame_type");
    2247             :         show_frame = gf_bs_read_int_log(bs, 1, "show_frame");
    2248             :         error_resilient_mode = gf_bs_read_int_log(bs, 1, "error_resilient_mode");
    2249        3439 :         if (frame_type == VP9_KEY_FRAME) {
    2250         141 :                 if (!vp9_frame_sync_code(bs))
    2251             :                         return GF_NON_COMPLIANT_BITSTREAM;
    2252         141 :                 if (vp9_color_config(bs, vp9_cfg) != GF_OK)
    2253             :                         return GF_NON_COMPLIANT_BITSTREAM;
    2254         141 :                 vp9_frame_size(bs, FrameWidth, FrameHeight, &Sb64Cols, &Sb64Rows);
    2255         141 :                 vp9_render_size(bs, *FrameWidth, *FrameHeight, renderWidth, renderHeight);
    2256             :                 refresh_frame_flags = 0xFF;
    2257         141 :                 *key_frame = GF_TRUE;
    2258             :                 FrameIsIntra = GF_TRUE;
    2259             :         }
    2260             :         else {
    2261             :                 Bool intra_only = GF_FALSE;
    2262        3298 :                 *key_frame = GF_FALSE;
    2263             : 
    2264        3298 :                 if (show_frame == GF_FALSE) {
    2265             :                         intra_only = gf_bs_read_int_log(bs, 1, "intra_only");
    2266             :                 }
    2267             :                 FrameIsIntra = intra_only;
    2268             : 
    2269        3298 :                 if (error_resilient_mode == GF_FALSE) {
    2270        3298 :                         /*reset_frame_context = */gf_bs_read_int_log(bs, 2, "reset_frame_context");
    2271             :                 }
    2272             : 
    2273        3298 :                 if (intra_only == GF_TRUE) {
    2274           0 :                         if (!vp9_frame_sync_code(bs))
    2275             :                                 return GF_NON_COMPLIANT_BITSTREAM;
    2276             : 
    2277           0 :                         if (vp9_cfg->profile > 0) {
    2278           0 :                                 if (vp9_color_config(bs, vp9_cfg) != GF_OK)
    2279             :                                         return GF_NON_COMPLIANT_BITSTREAM;
    2280             :                         }
    2281             :                         else {
    2282             :                                 u8 color_space = CS_BT_601;
    2283           0 :                                 vp9_cfg->colour_primaries = VP9_CS_to_23001_8_colour_primaries[color_space];
    2284           0 :                                 vp9_cfg->transfer_characteristics = VP9_CS_to_23001_8_transfer_characteristics[color_space];
    2285           0 :                                 vp9_cfg->matrix_coefficients = VP9_CS_to_23001_8_matrix_coefficients[color_space];
    2286           0 :                                 vp9_cfg->chroma_subsampling = 0;
    2287           0 :                                 vp9_cfg->bit_depth = 8;
    2288             :                         }
    2289           0 :                         refresh_frame_flags = gf_bs_read_int_log(bs, 8, "refresh_frame_flags");
    2290           0 :                         vp9_frame_size(bs, FrameWidth, FrameHeight, &Sb64Cols, &Sb64Rows);
    2291           0 :                         vp9_render_size(bs, *FrameWidth, *FrameHeight, renderWidth, renderHeight);
    2292             :                 }
    2293             :                 else {
    2294        3298 :                         refresh_frame_flags = gf_bs_read_int_log(bs, 8, "refresh_frame_flags");
    2295             :                         u8 ref_frame_idx[3];
    2296       13192 :                         for (i = 0; i < 3; i++) {
    2297        9894 :                                 ref_frame_idx[i] = gf_bs_read_int_log_idx(bs, 3, "ref_frame_idx", i);
    2298        9894 :                                 /*ref_frame_sign_bias[LAST_FRAME + i] = */gf_bs_read_int_log_idx(bs, 1, "ref_frame_sign_bias", i);
    2299             :                         }
    2300        3298 :                         vp9_frame_size_with_refs(bs, refresh_frame_flags, ref_frame_idx, vp9_cfg->RefFrameWidth, vp9_cfg->RefFrameHeight, FrameWidth, FrameHeight, renderWidth, renderHeight, &Sb64Cols, &Sb64Rows);
    2301        3298 :                         /*allow_high_precision_mv = */gf_bs_read_int_log(bs, 1, "allow_high_precision_mv");
    2302        3298 :                         vp9_read_interpolation_filter(bs);
    2303             :                 }
    2304             :         }
    2305             : 
    2306        3439 :         if (error_resilient_mode == 0) {
    2307        3439 :                 /*refresh_frame_context = */gf_bs_read_int_log(bs, 1, "refresh_frame_context");
    2308        3439 :                 /*frame_parallel_decoding_mode = */gf_bs_read_int_log(bs, 1, "frame_parallel_decoding_mode");
    2309             :         }
    2310             : 
    2311        3439 :         /*frame_context_idx = */gf_bs_read_int_log(bs, 2, "frame_context_idx");
    2312             :         if (FrameIsIntra || error_resilient_mode) {
    2313             :                 /*setup_past_independence + save_probs ...*/
    2314             :                 //frame_context_idx = 0;
    2315             :         }
    2316             : 
    2317        3439 :         vp9_loop_filter_params(bs);
    2318             :         vp9_quantization_params(bs);
    2319        3439 :         vp9_segmentation_params(bs);
    2320        3439 :         vp9_tile_info(bs, Sb64Cols);
    2321             : 
    2322        3439 :         /*header_size_in_bytes = */gf_bs_read_int_log(bs, 16, "header_size_in_bytes");
    2323             : 
    2324             :         /*Reference frame update process (8.10 - partial)*/
    2325       30951 :         for (i = 0; i < VP9_NUM_REF_FRAMES; i++) {
    2326       27512 :                 if ((refresh_frame_flags >> i) & 1) {
    2327        4707 :                         vp9_cfg->RefFrameWidth[i] = *FrameWidth;
    2328        4707 :                         vp9_cfg->RefFrameHeight[i] = *FrameHeight;
    2329             :                 }
    2330             :         }
    2331             : 
    2332             :         return GF_OK;
    2333             : }
    2334             : 
    2335      183122 : GF_Err gf_av1_parse_obu_header(GF_BitStream *bs, ObuType *obu_type, Bool *obu_extension_flag, Bool *obu_has_size_field, u8 *temporal_id, u8 *spatial_id)
    2336             : {
    2337      183122 :         Bool forbidden = gf_bs_read_int(bs, 1);
    2338      183122 :         if (forbidden) {
    2339             :                 return GF_NON_COMPLIANT_BITSTREAM;
    2340             :         }
    2341             : 
    2342      182348 :         *obu_type = gf_bs_read_int(bs, 4);
    2343      182348 :         *obu_extension_flag = gf_bs_read_int(bs, 1);
    2344      182348 :         *obu_has_size_field = gf_bs_read_int(bs, 1);
    2345      182348 :         if (gf_bs_read_int(bs, 1) /*obu_reserved_1bit*/) {
    2346             :                 return GF_NON_COMPLIANT_BITSTREAM;
    2347             :         }
    2348      181449 :         if (*obu_extension_flag) {
    2349         551 :                 *temporal_id = gf_bs_read_int(bs, 3);
    2350         551 :                 *spatial_id = gf_bs_read_int(bs, 2);
    2351         551 :                 /*extension_header_reserved_3bits = */gf_bs_read_int(bs, 3);
    2352             :         }
    2353             : 
    2354             :         return GF_OK;
    2355             : }
    2356             : 
    2357             : #endif // GPAC_DISABLE_AV_PARSERS
    2358             : 
    2359             : GF_EXPORT
    2360       26951 : const char *gf_av1_get_obu_name(ObuType obu_type)
    2361             : {
    2362       26951 :         switch (obu_type) {
    2363             :         case OBU_SEQUENCE_HEADER: return "seq_header";
    2364           0 :         case OBU_TEMPORAL_DELIMITER: return "delimiter";
    2365        6714 :         case OBU_FRAME_HEADER: return "frame_header";
    2366          40 :         case OBU_TILE_GROUP: return "tile_group";
    2367           0 :         case OBU_METADATA: return "metadata";
    2368       19972 :         case OBU_FRAME: return "frame";
    2369           0 :         case OBU_REDUNDANT_FRAME_HEADER: return "redundant_frame_header";
    2370           0 :         case OBU_TILE_LIST: return "tile_list";
    2371           0 :         case OBU_PADDING: return "padding";
    2372           0 :         case OBU_RESERVED_0:
    2373             :         case OBU_RESERVED_9:
    2374             :         case OBU_RESERVED_10:
    2375             :         case OBU_RESERVED_11:
    2376             :         case OBU_RESERVED_12:
    2377             :         case OBU_RESERVED_13:
    2378             :         case OBU_RESERVED_14:
    2379           0 :                 return "reserved";
    2380           0 :         default: return "unknown";
    2381             :         }
    2382             : }
    2383             : 
    2384         682 : Bool av1_is_obu_header(ObuType obu_type) {
    2385       94533 :         switch (obu_type) {
    2386             :         case OBU_SEQUENCE_HEADER:
    2387             :         case OBU_METADATA:
    2388             :                 // TODO add check based on the metadata type
    2389             :                 return GF_TRUE;
    2390           0 :         default:
    2391           0 :                 return GF_FALSE;
    2392             :         }
    2393             : }
    2394             : 
    2395             : #ifndef GPAC_DISABLE_AV_PARSERS
    2396             : 
    2397             : static Bool av1_is_obu_frame(AV1State *state, ObuType obu_type)
    2398             : {
    2399       92031 :         switch (obu_type) {
    2400             :         case OBU_PADDING:
    2401             :         case OBU_REDUNDANT_FRAME_HEADER:
    2402             :                 return GF_FALSE;
    2403       37397 :         case OBU_TEMPORAL_DELIMITER:
    2404       37397 :                 return state->keep_temporal_delim ? GF_TRUE : GF_FALSE;
    2405             :         default:
    2406             :                 return GF_TRUE;
    2407             :         }
    2408             : }
    2409             : 
    2410      130929 : u64 gf_av1_leb128_read(GF_BitStream *bs, u8 *opt_Leb128Bytes) {
    2411             :         u64 value = 0;
    2412             :         u8 Leb128Bytes = 0, i = 0;
    2413      316446 :         for (i = 0; i < 8; i++) {
    2414      185442 :                 u8 leb128_byte = gf_bs_read_u8(bs);
    2415      185442 :                 value |= ( ((u64) (leb128_byte & 0x7f)) << (i * 7));
    2416      185442 :                 Leb128Bytes += 1;
    2417      185442 :                 if (!(leb128_byte & 0x80)) {
    2418             :                         break;
    2419             :                 }
    2420             :         }
    2421             : 
    2422      130929 :         if (opt_Leb128Bytes) {
    2423        3169 :                 *opt_Leb128Bytes = Leb128Bytes;
    2424             :         }
    2425      130929 :         return value;
    2426             : }
    2427             : 
    2428         751 : u32 gf_av1_leb128_size(u64 value)
    2429             : {
    2430             :         u32 gf_av1_leb128_size = 0;
    2431             :         do {
    2432        2065 :                 ++gf_av1_leb128_size;
    2433        2065 :         } while ((value >>= 7) != 0);
    2434             : 
    2435         751 :         return gf_av1_leb128_size;
    2436             : }
    2437             : 
    2438         750 : u64 gf_av1_leb128_write(GF_BitStream *bs, u64 value)
    2439             : {
    2440             :         u32 i, leb_size = gf_av1_leb128_size(value);
    2441         985 :         for (i = 0; i < leb_size; ++i) {
    2442         985 :                 u8 byte = value & 0x7f;
    2443         985 :                 value >>= 7;
    2444         985 :                 if (value != 0) byte |= 0x80; //more bytes follow
    2445         985 :                 gf_bs_write_u8(bs, byte);
    2446             :         }
    2447             : 
    2448         750 :         return leb_size;
    2449             : }
    2450             : 
    2451             : #define OBU_BLOCK_SIZE 4096
    2452       55154 : static void av1_add_obu_internal(GF_BitStream *bs, u64 pos, u64 obu_length, ObuType obu_type, GF_List **obu_list, AV1State *state)
    2453             : {
    2454             :         char block[OBU_BLOCK_SIZE];
    2455       55154 :         Bool has_size_field = 0, obu_extension_flag = 0;
    2456             :         u8 temporal_id, spatial_id;
    2457             :         GF_AV1_OBUArrayEntry *a = NULL;
    2458             : 
    2459       55154 :         if (state && state->mem_mode) {
    2460       54353 :                 if (!state->bs) state->bs = gf_bs_new(NULL, 0, GF_BITSTREAM_WRITE);
    2461       54276 :                 else gf_bs_reassign_buffer(state->bs, state->frame_obus, state->frame_obus_alloc);
    2462             :         }
    2463             :         else {
    2464         801 :                 GF_SAFEALLOC(a, GF_AV1_OBUArrayEntry);
    2465         801 :                 if (!a) {
    2466           0 :                         GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[AV1] Failed to allocate OBU\n"));
    2467       54353 :                         return;
    2468             :                 }
    2469             :         }
    2470             : 
    2471       55154 :         gf_bs_seek(bs, pos);
    2472       55154 :         gf_av1_parse_obu_header(bs, &obu_type, &obu_extension_flag, &has_size_field, &temporal_id, &spatial_id);
    2473       55154 :         gf_bs_seek(bs, pos);
    2474             : 
    2475       55154 :         if (has_size_field) {
    2476       55136 :                 if (a) {
    2477         797 :                         a->obu = gf_malloc((size_t)obu_length);
    2478         797 :                         gf_bs_read_data(bs, a->obu, (u32)obu_length);
    2479         797 :                         a->obu_length = obu_length;
    2480             :                 }
    2481             :                 else {
    2482       54339 :                         u32 remain = (u32)obu_length;
    2483      172507 :                         while (remain) {
    2484             :                                 u32 block_size = OBU_BLOCK_SIZE;
    2485       63829 :                                 if (block_size > remain) block_size = remain;
    2486       63829 :                                 gf_bs_read_data(bs, block, block_size);
    2487       63829 :                                 gf_bs_write_data(state->bs, block, block_size);
    2488       63829 :                                 remain -= block_size;
    2489             :                         }
    2490             :                         return;
    2491             :                 }
    2492             :         }
    2493             :         else {
    2494          18 :                 u8 i, hdr_size = obu_extension_flag ? 2 : 1;
    2495             :                 const u32 leb_size = (u32)gf_av1_leb128_size(obu_length);
    2496          18 :                 const u64 obu_size = obu_length - hdr_size;
    2497             : 
    2498          18 :                 if (a) {
    2499           4 :                         a->obu = gf_malloc((size_t)obu_length + leb_size);
    2500           4 :                         a->obu_length = obu_length + leb_size;
    2501           8 :                         for (i = 0; i < hdr_size; ++i) {
    2502           4 :                                 a->obu[i] = gf_bs_read_u8(bs);
    2503             :                                 /*add size field flag*/
    2504           4 :                                 if (i == 0) a->obu[0] |= 0x02;
    2505             :                         }
    2506             :                         {
    2507           4 :                                 u32 out_size = 0;
    2508           4 :                                 u8 *output = NULL;
    2509           4 :                                 GF_BitStream *bsLeb128 = gf_bs_new(NULL, 0, GF_BITSTREAM_WRITE);
    2510             :                                 /*write size field*/
    2511           4 :                                 gf_av1_leb128_write(bsLeb128, obu_size);
    2512             :                                 assert(gf_bs_get_position(bsLeb128) == leb_size);
    2513           4 :                                 gf_bs_get_content(bsLeb128, &output, &out_size);
    2514           4 :                                 gf_bs_del(bsLeb128);
    2515           4 :                                 memcpy(a->obu + hdr_size, output, out_size);
    2516           4 :                                 gf_free(output);
    2517             :                         }
    2518           4 :                         gf_bs_read_data(bs, a->obu + hdr_size + leb_size, (u32)(obu_size));
    2519             :                         assert(gf_bs_get_position(bs) == pos + obu_length);
    2520             :                 }
    2521             :                 else {
    2522             :                         u32 remain;
    2523          14 :                         for (i = 0; i < hdr_size; ++i) {
    2524          14 :                                 u8 hdr_b = gf_bs_read_u8(bs);
    2525          14 :                                 if (i == 0) hdr_b |= 0x02; /*add size field flag*/
    2526          14 :                                 gf_bs_write_u8(state->bs, hdr_b);
    2527             :                         }
    2528             :                         /*add size field */
    2529          14 :                         gf_av1_leb128_write(state->bs, obu_size);
    2530          14 :                         remain = (u32)obu_length - hdr_size;
    2531          42 :                         while (remain) {
    2532             :                                 u32 block_size = OBU_BLOCK_SIZE;
    2533          14 :                                 if (block_size > remain) block_size = remain;
    2534          14 :                                 gf_bs_read_data(bs, block, block_size);
    2535          14 :                                 gf_bs_write_data(state->bs, block, block_size);
    2536          14 :                                 remain -= block_size;
    2537             :                         }
    2538             :                         assert(gf_bs_get_position(bs) == pos + obu_length);
    2539             :                         return;
    2540             :                 }
    2541             :         }
    2542         801 :         if (!obu_list) {
    2543           0 :                 GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[AV1] internal error, no OBU list cannot add\n"));
    2544           0 :                 gf_free(a->obu);
    2545           0 :                 gf_free(a);
    2546           0 :                 return;
    2547             :         }
    2548         801 :         a->obu_type = obu_type;
    2549         801 :         if (! *obu_list)
    2550         366 :                 *obu_list = gf_list_new();
    2551         801 :         gf_list_add(*obu_list, a);
    2552             : }
    2553             : 
    2554       93851 : static void av1_populate_state_from_obu(GF_BitStream *bs, u64 pos, u64 obu_length, ObuType obu_type, AV1State *state)
    2555             : {
    2556             :         if (av1_is_obu_header(obu_type)) {
    2557         520 :                 av1_add_obu_internal(bs, pos, obu_length, obu_type, &state->frame_state.header_obus, NULL);
    2558             :         }
    2559      131248 :         if (!state->skip_frames && av1_is_obu_frame(state, obu_type)) {
    2560       54634 :                 if (!state->mem_mode) {
    2561         281 :                         av1_add_obu_internal(bs, pos, obu_length, obu_type, &state->frame_state.frame_obus, NULL);
    2562             :                 }
    2563             :                 else {
    2564       54353 :                         av1_add_obu_internal(bs, pos, obu_length, obu_type, NULL, state);
    2565             :                 }
    2566             :         }
    2567       93851 : }
    2568             : 
    2569        5477 : GF_Err aom_av1_parse_temporal_unit_from_section5(GF_BitStream *bs, AV1State *state)
    2570             : {
    2571        5477 :         if (!state) return GF_BAD_PARAM;
    2572        5477 :         state->obu_type = -1;
    2573             : 
    2574       16202 :         while (state->obu_type != OBU_TEMPORAL_DELIMITER) {
    2575             :                 GF_Err e;
    2576        8400 :                 if (!gf_bs_available(bs))
    2577        3263 :                         return state->unframed ? GF_BUFFER_TOO_SMALL : GF_OK;
    2578             : 
    2579        8289 :                 u64 pos = gf_bs_get_position(bs), obu_length = 0;
    2580             : 
    2581        8289 :                 e = gf_av1_parse_obu(bs, &state->obu_type, &obu_length, NULL, state);
    2582        8289 :                 if (e)
    2583             :                         return e;
    2584             : 
    2585        5248 :                 if (obu_length != gf_bs_get_position(bs) - pos) {
    2586           0 :                         GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[AV1] OBU (Section 5) frame size "LLU" different from consumed bytes "LLU".\n", obu_length, gf_bs_get_position(bs) - pos));
    2587             :                         return GF_NON_COMPLIANT_BITSTREAM;
    2588             :                 }
    2589             : 
    2590        5248 :                 GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[AV1] Section5 OBU detected (size "LLU")\n", obu_length));
    2591        5248 :                 av1_populate_state_from_obu(bs, pos, obu_length, state->obu_type, state);
    2592             :         }
    2593             : 
    2594             :         return GF_OK;
    2595             : }
    2596             : 
    2597        3120 : Bool gf_media_aom_probe_annexb(GF_BitStream *bs)
    2598             : {
    2599             :         Bool res = GF_TRUE;
    2600        3120 :         u64 init_pos = gf_bs_get_position(bs);
    2601        3120 :         u64 sz = gf_av1_leb128_read(bs, NULL);
    2602        3120 :         if (!sz) res = GF_FALSE;
    2603        3226 :         while (sz > 0) {
    2604        1856 :                 u8 Leb128Bytes = 0;
    2605        1856 :                 u64 frame_unit_size = gf_av1_leb128_read(bs, &Leb128Bytes);
    2606             : 
    2607        1856 :                 if (!frame_unit_size) {
    2608             :                         res = GF_FALSE;
    2609        1750 :                         break;
    2610             :                 }
    2611             : 
    2612        1770 :                 if (sz < Leb128Bytes + frame_unit_size) {
    2613             :                         res = GF_FALSE;
    2614             :                         break;
    2615             :                 }
    2616         848 :                 sz -= Leb128Bytes + frame_unit_size;
    2617             : 
    2618        2031 :                 while (frame_unit_size > 0) {
    2619             :                         ObuType obu_type;
    2620        1077 :                         u64 pos, obu_length = gf_av1_leb128_read(bs, &Leb128Bytes);
    2621        1077 :                         if (frame_unit_size < Leb128Bytes + obu_length) {
    2622             :                                 res = GF_FALSE;
    2623         742 :                                 break;
    2624             :                         }
    2625         771 :                         pos = gf_bs_get_position(bs);
    2626         771 :                         frame_unit_size -= Leb128Bytes;
    2627             : 
    2628             :                         u8 tid, sid;
    2629             :                         Bool extflag, has_size;
    2630         771 :                         GF_Err e = gf_av1_parse_obu_header(bs, &obu_type, &extflag, &has_size, &tid, &sid);
    2631         771 :                         if (e) {
    2632             :                                 res = GF_FALSE;
    2633             :                                 break;
    2634             :                         }
    2635             : 
    2636         437 :                         if (has_size) {
    2637         381 :                                 obu_length = (u32)gf_av1_leb128_read(bs, NULL);
    2638             :                         }
    2639             :                         else {
    2640          56 :                                 if (obu_length >= 1 + extflag) {
    2641          19 :                                         obu_length = obu_length - 1 - extflag;
    2642             :                                 }
    2643             :                                 else {
    2644             :                                         res = GF_FALSE;
    2645             :                                         break;
    2646             :                                 }
    2647             :                         }
    2648         400 :                         u32 hdr_size = (u32)(gf_bs_get_position(bs) - pos);
    2649         400 :                         obu_length += hdr_size;
    2650             : 
    2651         400 :                         if (frame_unit_size < obu_length) {
    2652             :                                 res = GF_FALSE;
    2653             :                                 break;
    2654             :                         }
    2655         335 :                         frame_unit_size -= obu_length;
    2656         335 :                         gf_bs_skip_bytes(bs, obu_length - hdr_size);
    2657             :                 }
    2658         106 :                 if (!res) break;
    2659             :         }
    2660        3120 :         gf_bs_seek(bs, init_pos);
    2661        3120 :         return res;
    2662             : }
    2663             : 
    2664          59 : GF_Err aom_av1_parse_temporal_unit_from_annexb(GF_BitStream *bs, AV1State *state)
    2665             : {
    2666             :         GF_Err e;
    2667             :         u64 tupos;
    2668             :         u64 tusize, sz;
    2669          59 :         if (!bs || !state) return GF_BAD_PARAM;
    2670             : 
    2671          59 :         state->bs_overread = GF_FALSE;
    2672          59 :         tusize = sz = gf_av1_leb128_read(bs, NULL);
    2673          59 :         tupos = gf_bs_get_position(bs);
    2674          59 :         if (!sz) {
    2675           0 :                 GF_LOG(GF_LOG_INFO, GF_LOG_CODING, ("[AV1] temporal unit size is 0, likely not annex B\n"));
    2676             :                 return GF_NON_COMPLIANT_BITSTREAM;
    2677             :         }
    2678             : 
    2679          59 :         GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[AV1] Annex B temporal unit detected (size "LLU") ***** \n", sz));
    2680         120 :         while (sz > 0) {
    2681          61 :                 u8 Leb128Bytes = 0;
    2682          61 :                 u64 frame_unit_size = gf_av1_leb128_read(bs, &Leb128Bytes);
    2683             : 
    2684          61 :                 if (state->bs_overread) {
    2685           0 :                         return GF_BUFFER_TOO_SMALL;
    2686             :                 }
    2687          61 :                 if (sz < Leb128Bytes + frame_unit_size) {
    2688           0 :                         GF_LOG(GF_LOG_ERROR, GF_LOG_CODING, ("[AV1] Annex B sz("LLU") < Leb128Bytes("LLU") + frame_unit_size("LLU")\n", sz, Leb128Bytes, frame_unit_size));
    2689             :                         return GF_NON_COMPLIANT_BITSTREAM;
    2690             :                 }
    2691          61 :                 GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[AV1] Annex B frame unit detected (size "LLU")\n", frame_unit_size));
    2692          61 :                 sz -= Leb128Bytes + frame_unit_size;
    2693             : 
    2694         297 :                 while (frame_unit_size > 0) {
    2695         175 :                         u64 pos, obu_length = gf_av1_leb128_read(bs, &Leb128Bytes);
    2696             : 
    2697         175 :                         if (state->bs_overread) {
    2698           0 :                                 return GF_BUFFER_TOO_SMALL;
    2699             :                         }
    2700         175 :                         if (frame_unit_size < Leb128Bytes + obu_length) {
    2701           0 :                                 GF_LOG(GF_LOG_ERROR, GF_LOG_CODING, ("[AV1] Annex B frame_unit_size("LLU") < Leb128Bytes("LLU") + obu_length("LLU")\n", frame_unit_size, Leb128Bytes, obu_length));
    2702             :                                 return GF_NON_COMPLIANT_BITSTREAM;
    2703             :                         }
    2704         175 :                         GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[AV1] Annex B OBU detected (size "LLU")\n", obu_length));
    2705         175 :                         pos = gf_bs_get_position(bs);
    2706         175 :                         frame_unit_size -= Leb128Bytes;
    2707             : 
    2708         175 :                         e = gf_av1_parse_obu(bs, &state->obu_type, &obu_length, NULL, state);
    2709         175 :                         if (e) return e;
    2710             : 
    2711         175 :                         if (obu_length != gf_bs_get_position(bs) - pos) {
    2712           0 :                                 GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[AV1] Annex B frame size "LLU" different from consumed bytes "LLU".\n", obu_length, gf_bs_get_position(bs) - pos));
    2713             :                                 return GF_NON_COMPLIANT_BITSTREAM;
    2714             :                         }
    2715             : 
    2716         175 :                         av1_populate_state_from_obu(bs, pos, obu_length, state->obu_type, state);
    2717         175 :                         if (frame_unit_size < obu_length) {
    2718           0 :                                 GF_LOG(GF_LOG_ERROR, GF_LOG_CODING, ("[AV1] Annex B frame_unit_size("LLU") < OBU size ("LLU")\n", frame_unit_size, obu_length));
    2719             :                                 return GF_NON_COMPLIANT_BITSTREAM;
    2720             :                         }
    2721         175 :                         frame_unit_size -= obu_length;
    2722             :                 }
    2723             :         }
    2724             :         assert(sz == 0);
    2725          59 :         if (tusize != gf_bs_get_position(bs) - tupos) {
    2726           0 :                 GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[AV1] Annex B TU size "LLU" different from consumed bytes "LLU".\n", tusize, gf_bs_get_position(bs) - tupos));
    2727             :                 return GF_NON_COMPLIANT_BITSTREAM;
    2728             :         }
    2729             :         return GF_OK;
    2730             : }
    2731             : 
    2732       56227 : GF_Err aom_av1_parse_temporal_unit_from_ivf(GF_BitStream *bs, AV1State *state)
    2733             : {
    2734             :         u64 frame_size, pts_ignored;
    2735             :         GF_Err e;
    2736       56227 :         if (gf_bs_available(bs)<12) return GF_EOS;
    2737       56140 :         e = gf_media_parse_ivf_frame_header(bs, &frame_size, &pts_ignored);
    2738       56140 :         if (e) return e;
    2739       56140 :         GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[AV1] IVF frame detected (size "LLU")\n", frame_size));
    2740             : 
    2741       56140 :         if (gf_bs_available(bs) < frame_size) return GF_EOS;
    2742             : 
    2743      124306 :         while (frame_size > 0) {
    2744       88428 :                 u64 obu_size = 0, pos = gf_bs_get_position(bs);
    2745             : 
    2746       88428 :                 e = gf_av1_parse_obu(bs, &state->obu_type, &obu_size, NULL, state);
    2747       88428 :                 if (e != GF_OK)
    2748           0 :                         return e;
    2749             : 
    2750       88428 :                 if (obu_size != gf_bs_get_position(bs) - pos) {
    2751           0 :                         GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[AV1] IVF frame size "LLU" different from consumed bytes "LLU".\n", obu_size, gf_bs_get_position(bs) - pos));
    2752             :                         return GF_NON_COMPLIANT_BITSTREAM;
    2753             :                 }
    2754             : 
    2755       88428 :                 av1_populate_state_from_obu(bs, pos, obu_size, state->obu_type, state);
    2756             : 
    2757       88428 :                 frame_size -= obu_size;
    2758             :         }
    2759             :         return GF_OK;
    2760             : }
    2761             : 
    2762             : #define AV1_NUM_REF_FRAMES 8
    2763             : #define AV1_ALL_FRAMES ((1 << AV1_NUM_REF_FRAMES) - 1)
    2764             : 
    2765             : #define AV1_SUPERRES_DENOM_MIN 9
    2766             : #define AV1_SUPERRES_DENOM_BITS 3
    2767             : #define AV1_SUPERRES_NUM 8
    2768             : 
    2769             : #define AV1_REFS_PER_FRAME 7
    2770             : #define AV1_PRIMARY_REF_NONE 7
    2771             : 
    2772             : #define MAX_TILE_WIDTH 4096
    2773             : #define MAX_TILE_AREA (4096 * 2304)
    2774             : 
    2775             : static u32 aom_av1_tile_log2(u32 blkSize, u32 target)
    2776             : {
    2777             :         u32 k;
    2778      234813 :         for (k = 0; (blkSize << k) < target; k++) {
    2779             :         }
    2780             :         return k;
    2781             : }
    2782             : 
    2783      175813 : static u64 aom_av1_le(GF_BitStream *bs, u32 n, const char *name) {
    2784             :         u32 i = 0;
    2785             :         u64 t = 0;
    2786      461060 :         for (i = 0; i < n; i++) {
    2787      285247 :                 u8 byte = gf_bs_read_int(bs, 8);
    2788      285247 :                 t += (byte << (i * 8));
    2789             :         }
    2790      175813 :         gf_bs_log(bs, n*8, name, t);
    2791      175813 :         return t;
    2792             : }
    2793             : 
    2794             : 
    2795       63902 : static void av1_parse_tile_info(GF_BitStream *bs, AV1State *state)
    2796             : {
    2797             :         u32 i;
    2798       63902 :         u32 MiCols = 2 * ((state->width + 7) >> 3);
    2799       63902 :         u32 MiRows = 2 * ((state->height + 7) >> 3);
    2800       63902 :         u32 sbCols = state->use_128x128_superblock ? ((MiCols + 31) >> 5) : ((MiCols + 15) >> 4);
    2801       63902 :         u32 sbRows = state->use_128x128_superblock ? ((MiRows + 31) >> 5) : ((MiRows + 15) >> 4);
    2802       63902 :         u32 sbShift = state->use_128x128_superblock ? 5 : 4;
    2803       63902 :         u32 sbSize = sbShift + 2;
    2804       63902 :         u32 maxTileWidthSb = MAX_TILE_WIDTH >> sbSize;
    2805       63902 :         u32 maxTileAreaSb = MAX_TILE_AREA >> (2 * sbSize);
    2806             :         u32 minLog2tileCols = aom_av1_tile_log2(maxTileWidthSb, sbCols);
    2807       63902 :         u32 maxLog2tileCols = aom_av1_tile_log2(1, MIN(sbCols, AV1_MAX_TILE_COLS));
    2808       63902 :         u32 maxLog2tileRows = aom_av1_tile_log2(1, MIN(sbRows, AV1_MAX_TILE_ROWS));
    2809      127804 :         u32 minLog2Tiles = MAX(minLog2tileCols, aom_av1_tile_log2(maxTileAreaSb, sbRows * sbCols));
    2810             :         Bool uniform_tile_spacing_flag = gf_bs_read_int_log(bs, 1, "uniform_tile_spacing_flag");
    2811       63902 :         if (uniform_tile_spacing_flag) {
    2812             :                 u32 startSb, tileWidthSb, tileHeightSb, minLog2tileRows;
    2813       63902 :                 state->tileColsLog2 = minLog2tileCols;
    2814      244906 :                 while (state->tileColsLog2 < maxLog2tileCols) {
    2815             :                         Bool increment_tile_cols_log2 = gf_bs_read_int_log(bs, 1, "increment_tile_cols_log2");
    2816      117234 :                         if (increment_tile_cols_log2 == 1)
    2817      117102 :                                 state->tileColsLog2++;
    2818             :                         else
    2819             :                                 break;
    2820             :                 }
    2821             : 
    2822       63902 :                 tileWidthSb = (sbCols + (1 << state->tileColsLog2) - 1) >> state->tileColsLog2;
    2823             :                 i = 0;
    2824      303392 :                 for (startSb = 0; startSb < sbCols; startSb += tileWidthSb) {
    2825      239490 :                         i += 1;
    2826             :                 }
    2827       63902 :                 state->tileCols = i;
    2828       63902 :                 minLog2tileRows = MAX((int)(minLog2Tiles - state->tileColsLog2), 0);
    2829       63902 :                 state->tileRowsLog2 = minLog2tileRows;
    2830      128128 :                 while (state->tileRowsLog2 < maxLog2tileRows) {
    2831             :                         Bool increment_tile_rows_log2 = gf_bs_read_int_log(bs, 1, "increment_tile_rows_log2");
    2832       58862 :                         if (increment_tile_rows_log2 == 1)
    2833         324 :                                 state->tileRowsLog2++;
    2834             :                         else
    2835             :                                 break;
    2836             :                 }
    2837             : 
    2838       63902 :                 tileHeightSb = (sbRows + (1 << state->tileRowsLog2) - 1) >> state->tileRowsLog2;
    2839             :                 i = 0;
    2840      128205 :                 for (startSb = 0; startSb < sbRows; startSb += tileHeightSb) {
    2841       64303 :                         i += 1;
    2842             :                 }
    2843       63902 :                 state->tileRows = i;
    2844             :         }
    2845             :         else {
    2846             :                 u32 startSb, maxTileHeightSb, widestTileSb;
    2847             :                 widestTileSb = 0;
    2848             :                 startSb = 0;
    2849           0 :                 for (i = 0; startSb < sbCols; i++) {
    2850           0 :                         u32 maxWidth = MIN((int)(sbCols - startSb), maxTileWidthSb);
    2851           0 :                         u32 width_in_sbs_minus_1 = av1_read_ns(bs, maxWidth, "width_in_sbs_minus_1");
    2852           0 :                         u32 sizeSb = width_in_sbs_minus_1 + 1;
    2853           0 :                         widestTileSb = MAX(sizeSb, widestTileSb);
    2854           0 :                         startSb += sizeSb;
    2855             :                 }
    2856           0 :                 if (!widestTileSb) {
    2857           0 :                         GF_LOG(GF_LOG_ERROR, GF_LOG_CODING, ("[AV1] widest tile is 0, broken bitstream\n"));
    2858             :                         return;
    2859             :                 }
    2860           0 :                 state->tileCols = i;
    2861           0 :                 state->tileColsLog2 = aom_av1_tile_log2(1, state->tileCols);
    2862             : 
    2863           0 :                 if (minLog2Tiles > 0)
    2864           0 :                         maxTileAreaSb = (sbRows * sbCols) >> (minLog2Tiles + 1);
    2865             :                 else
    2866             :                         maxTileAreaSb = sbRows * sbCols;
    2867           0 :                 maxTileHeightSb = MAX(maxTileAreaSb / widestTileSb, 1);
    2868             : 
    2869             :                 startSb = 0;
    2870           0 :                 for (i = 0; startSb < sbRows; i++) {
    2871           0 :                         u32 maxHeight = MIN((int)(sbRows - startSb), maxTileHeightSb);
    2872           0 :                         u32 height_in_sbs_minus_1 = av1_read_ns(bs, maxHeight, "height_in_sbs_minus_1");
    2873           0 :                         u32 sizeSb = height_in_sbs_minus_1 + 1;
    2874           0 :                         startSb += sizeSb;
    2875             :                 }
    2876             : 
    2877           0 :                 state->tileRows = i;
    2878           0 :                 state->tileRowsLog2 = aom_av1_tile_log2(1, state->tileRows);
    2879             :         }
    2880       63902 :         if (state->tileColsLog2 > 0 || state->tileRowsLog2 > 0) {
    2881       58733 :                 gf_bs_read_int_log(bs, state->tileRowsLog2 + state->tileColsLog2, "context_update_tile_id");
    2882       58733 :                 state->tile_size_bytes = gf_bs_read_int_log(bs, 2, "tile_size_bytes_minus1") + 1;
    2883             :         }
    2884             : }
    2885             : 
    2886       63902 : static void superres_params(GF_BitStream *bs, AV1State *state)
    2887             : {
    2888             :         u32 SuperresDenom;
    2889             :         Bool use_superres;
    2890             : 
    2891       63902 :         if (state->enable_superres) {
    2892             :                 use_superres = gf_bs_read_int_log(bs, 1, "use_superres");
    2893             :         }
    2894             :         else {
    2895             :                 use_superres = GF_FALSE;
    2896             :         }
    2897           0 :         if (use_superres) {
    2898             :                 u8 coded_denom = gf_bs_read_int_log(bs, AV1_SUPERRES_DENOM_BITS, "coded_denom");
    2899           0 :                 SuperresDenom = coded_denom + AV1_SUPERRES_DENOM_MIN;
    2900             :         }
    2901             :         else {
    2902             :                 SuperresDenom = AV1_SUPERRES_NUM;
    2903             :         }
    2904       63902 :         state->UpscaledWidth = state->width;
    2905       63902 :         state->width = (state->UpscaledWidth * AV1_SUPERRES_NUM + (SuperresDenom / 2)) / SuperresDenom;
    2906       63902 : }
    2907             : 
    2908       63886 : static void av1_frame_size(GF_BitStream *bs, AV1State *state, Bool frame_size_override_flag)
    2909             : {
    2910       63886 :         if (frame_size_override_flag) {
    2911             :                 u32 frame_width_minus_1, frame_height_minus_1;
    2912          64 :                 u8 n = state->frame_width_bits_minus_1 + 1;
    2913          64 :                 frame_width_minus_1 = gf_bs_read_int_log(bs, n, "frame_width_minus_1");
    2914          64 :                 n = state->frame_height_bits_minus_1 + 1;
    2915          64 :                 frame_height_minus_1 = gf_bs_read_int_log(bs, n, "frame_height_minus_1");
    2916          64 :                 state->width = frame_width_minus_1 + 1;
    2917          64 :                 state->height = frame_height_minus_1 + 1;
    2918             :         } else {
    2919       63822 :                 state->width = state->sequence_width;
    2920       63822 :                 state->height = state->sequence_height;
    2921             :         }
    2922       63886 :         superres_params(bs, state);
    2923             :         //compute_image_size(); //no bits
    2924       63886 : }
    2925             : 
    2926       63886 : static void av1_render_size(GF_BitStream *bs)
    2927             : {
    2928             :         Bool render_and_frame_size_different = gf_bs_read_int_log(bs, 1, "render_and_frame_size_different_flag");
    2929       63886 :         if (render_and_frame_size_different == GF_TRUE) {
    2930          64 :                 gf_bs_read_int_log(bs, 16, "render_width_minus_1");
    2931          64 :                 gf_bs_read_int_log(bs, 16, "render_height_minus_1");
    2932             :                 //RenderWidth = render_width_minus_1 + 1;
    2933             :                 //RenderHeight = render_height_minus_1 + 1;
    2934             :         }
    2935             :         else {
    2936             :                 //RenderWidth = UpscaledWidth;
    2937             :                 //RenderHeight = FrameHeight;
    2938             :         }
    2939       63886 : }
    2940             : 
    2941       63283 : static void read_interpolation_filter(GF_BitStream *bs)
    2942             : {
    2943             :         Bool is_filter_switchable = gf_bs_read_int_log(bs, 1, "is_filter_switchable");
    2944       63283 :         if (!is_filter_switchable) {
    2945       13032 :                 /*interpolation_filter =*/ gf_bs_read_int_log(bs, 2, "interpolation_filter");
    2946             :         }
    2947       63283 : }
    2948             : 
    2949          22 : static void frame_size_with_refs(GF_BitStream *bs, AV1State *state, Bool frame_size_override_flag, s8 *ref_frame_idx)
    2950             : {
    2951             :         Bool found_ref = GF_FALSE;
    2952             :         u32 i = 0;
    2953          88 :         for (i = 0; i < AV1_REFS_PER_FRAME; i++) {
    2954          82 :                 found_ref = gf_bs_read_int_log_idx(bs, 1, "found_ref", i);
    2955          82 :                 if (found_ref == 1) {
    2956          16 :                         state->UpscaledWidth = state->RefUpscaledWidth[ref_frame_idx[i]];
    2957          16 :                         state->width = state->UpscaledWidth;
    2958          16 :                         state->height = state->RefFrameHeight[ref_frame_idx[i]];
    2959          16 :                         break;
    2960             :                 }
    2961             :         }
    2962          22 :         if (found_ref == 0) {
    2963           6 :                 av1_frame_size(bs, state, frame_size_override_flag);
    2964           6 :                 av1_render_size(bs);
    2965             :         }
    2966             :         else {
    2967          16 :                 superres_params(bs, state);
    2968             :                 //compute_image_size();
    2969             :         }
    2970          22 : }
    2971             : 
    2972      191706 : static s32 av1_delta_q(GF_BitStream *bs, const char *name_flag, const char *name)
    2973             : {
    2974             :         Bool delta_coded = gf_bs_read_int_log(bs, 1, name_flag);
    2975             :         s32 delta_q = 0;
    2976      191706 :         if (delta_coded) {
    2977             :                 u32 signMask = 1 << (7 - 1);
    2978           0 :                 delta_q = gf_bs_read_int_log(bs, 7, name);
    2979           0 :                 if (delta_q & signMask)
    2980           0 :                         delta_q = delta_q - 2 * signMask;
    2981             :         }
    2982      191706 :         return delta_q;
    2983             : }
    2984             : 
    2985             : static u8 Segmentation_Feature_Bits[] = { 8,6,6,6,6,3,0,0 };
    2986             : static u8 Segmentation_Feature_Signed[] = { 1, 1, 1, 1, 1, 0, 0, 0 };
    2987             : 
    2988             : static u8 av1_get_qindex(Bool ignoreDeltaQ, u32 segmentId, u32 base_q_idx, u32 delta_q_present, u32 CurrentQIndex, Bool segmentation_enabled, u8 *features_SEG_LVL_ALT_Q_enabled, s32 *features_SEG_LVL_ALT_Q)
    2989             : {
    2990             :         //If seg_feature_active_idx( segmentId, SEG_LVL_ALT_Q ) is equal to 1 the following ordered steps apply:
    2991      511216 :         if (segmentation_enabled && features_SEG_LVL_ALT_Q_enabled[segmentId]) {
    2992             :                 //Set the variable data equal to FeatureData[ segmentId ][ SEG_LVL_ALT_Q ].
    2993          58 :                 s32 data = features_SEG_LVL_ALT_Q[segmentId];
    2994          58 :                 s32 qindex = base_q_idx + data;
    2995             :                 //If ignoreDeltaQ is equal to 0 and delta_q_present is equal to 1, set qindex equal to CurrentQIndex + data.
    2996             :                 if ((ignoreDeltaQ == 0) && (delta_q_present == 1)) qindex = CurrentQIndex + data;
    2997             :                 //Return Clip3( 0, 255, qindex ).
    2998          58 :                 if (qindex < 0) return 0;
    2999          58 :                 else if (qindex > 255) return 255;
    3000           0 :                 else return (u8)qindex;
    3001             :         }
    3002             :         //Otherwise, if ignoreDeltaQ is equal to 0 and delta_q_present is equal to 1, return CurrentQIndex.
    3003             :         if ((ignoreDeltaQ == 0) && (delta_q_present == 1)) return CurrentQIndex;
    3004             :         //otherwise
    3005             :         return base_q_idx;
    3006             : }
    3007             : 
    3008             : enum {
    3009             :         AV1_RESTORE_NONE = 0,
    3010             :         AV1_RESTORE_SWITCHABLE,
    3011             :         AV1_RESTORE_WIENER,
    3012             :         AV1_RESTORE_SGRPROJ
    3013             : };
    3014             : 
    3015             : #define AV1_GMC_IDENTITY  0
    3016             : #define AV1_GMC_TRANSLATION 1
    3017             : #define AV1_GMC_ROTZOOM 2
    3018             : #define AV1_GMC_AFFINE 3
    3019             : 
    3020             : #define AV1_LAST_FRAME 1
    3021             : #define AV1_LAST2_FRAME 2
    3022             : #define AV1_LAST3_FRAME 3
    3023             : #define AV1_GOLDEN_FRAME 4
    3024             : #define AV1_BWDREF_FRAME 5
    3025             : #define AV1_ALTREF2_FRAME 6
    3026             : #define AV1_ALTREF_FRAME 7
    3027             : 
    3028             : #define GM_ABS_ALPHA_BITS 12
    3029             : #define GM_ALPHA_PREC_BITS 15
    3030             : #define GM_ABS_TRANS_ONLY_BITS 9
    3031             : #define GM_TRANS_ONLY_PREC_BITS 3
    3032             : #define GM_ABS_TRANS_BITS 12
    3033             : #define GM_TRANS_PREC_BITS 6
    3034             : #define WARPEDMODEL_PREC_BITS 16
    3035             : 
    3036             : 
    3037       26200 : static u32 av1_decode_subexp(GF_BitStream *bs, s32 numSyms)
    3038             : {
    3039             :         s32 i = 0;
    3040             :         s32 mk = 0;
    3041             :         s32 k = 3;
    3042       81458 :         while (1) {
    3043      107658 :                 s32 b2 = i ? k + i - 1 : k;
    3044      107658 :                 s32 a = 1 << b2;
    3045      107658 :                 if (numSyms <= mk + 3 * a) {
    3046           6 :                         s32 subexp_final_bits = av1_read_ns(bs, numSyms - mk, NULL);
    3047           6 :                         return subexp_final_bits + mk;
    3048             :                 }
    3049             :                 else {
    3050      107652 :                         s32 subexp_more_bits = gf_bs_read_int(bs, 1);
    3051      107652 :                         if (subexp_more_bits) {
    3052       81458 :                                 i++;
    3053       81458 :                                 mk += a;
    3054             :                         }
    3055             :                         else {
    3056       26194 :                                 s32 subexp_bits = gf_bs_read_int(bs, b2);
    3057       26194 :                                 return subexp_bits + mk;
    3058             :                         }
    3059             :                 }
    3060             :         }
    3061             : }
    3062             : 
    3063             : static GFINLINE s32 inverse_recenter(s32 r, u32 v)
    3064             : {
    3065       26200 :         if ((s64)v > (s64)(2 * r))
    3066           0 :                 return v;
    3067       26200 :         else if (v & 1)
    3068       11944 :                 return r - ((v + 1) >> 1);
    3069             :         else
    3070       14256 :                 return r + (v >> 1);
    3071             : }
    3072             : 
    3073       26200 : static s32 av1_decode_unsigned_subexp_with_ref(GF_BitStream *bs, s32 mx, s32 r)
    3074             : {
    3075       26200 :         u32 v = av1_decode_subexp(bs, mx);
    3076       26200 :         if ((r < 0) && (-(-r << 1) <= mx)) {
    3077             :                 return inverse_recenter(r, v);
    3078             :         }
    3079       26200 :         else if ((r << 1) <= mx) {
    3080             :                 return inverse_recenter(r, v);
    3081             :         }
    3082             :         else {
    3083        7464 :                 return mx - 1 - inverse_recenter(mx - 1 - r, v);
    3084             :         }
    3085             : }
    3086             : static s16 av1_decode_signed_subexp_with_ref(GF_BitStream *bs, s32 low, s32 high, s32 r)
    3087             : {
    3088       26200 :         s16 x = av1_decode_unsigned_subexp_with_ref(bs, high - low, r - low);
    3089       26200 :         return x + low;
    3090             : }
    3091             : 
    3092       26200 : static void av1_read_global_param(AV1State *state, GF_BitStream *bs, u8 type, u8 ref, u8 idx)
    3093             : {
    3094             :         u8 absBits = GM_ABS_ALPHA_BITS;
    3095             :         u8 precBits = GM_ALPHA_PREC_BITS;
    3096       26200 :         if (idx < 2) {
    3097       13104 :                 if (type == AV1_GMC_TRANSLATION) {
    3098           8 :                         absBits = GM_ABS_TRANS_ONLY_BITS - (!state->frame_state.allow_high_precision_mv ? 1 : 0);
    3099           8 :                         precBits = GM_TRANS_ONLY_PREC_BITS - (!state->frame_state.allow_high_precision_mv ? 1 : 0);
    3100             :                 }
    3101             :                 else {
    3102             :                         absBits = GM_ABS_TRANS_BITS;
    3103             :                         precBits = GM_TRANS_PREC_BITS;
    3104             :                 }
    3105             :         }
    3106       26200 :         s32 precDiff = WARPEDMODEL_PREC_BITS - precBits;
    3107       26200 :         s32 round = (idx % 3) == 2 ? (1 << WARPEDMODEL_PREC_BITS) : 0;
    3108       26200 :         s32 sub = (idx % 3) == 2 ? (1 << precBits) : 0;
    3109       26200 :         s32 mx = (1 << absBits);
    3110       26200 :         s32 r = (state->PrevGmParams.coefs[ref][idx] >> precDiff) - sub;
    3111       52400 :         s32 val = av1_decode_signed_subexp_with_ref(bs, -mx, mx + 1, r);
    3112             : 
    3113       26200 :         if (val < 0) {
    3114       12666 :                 val = -val;
    3115       12666 :                 state->GmParams.coefs[ref][idx] = (-(val << precDiff) + round);
    3116             :         }
    3117             :         else {
    3118       13534 :                 state->GmParams.coefs[ref][idx] = (val << precDiff) + round;
    3119             :         }
    3120       26200 : }
    3121             : 
    3122             : static s32 av1_get_relative_dist(s32 a, s32 b, AV1State *state)
    3123             : {
    3124         104 :         if (!state->enable_order_hint)
    3125             :                 return 0;
    3126      774376 :         s32 diff = a - b;
    3127      482822 :         s32 m = 1 << (state->OrderHintBits - 1);
    3128      774376 :         diff = (diff & (m - 1)) - (diff & m);
    3129             :         return diff;
    3130             : }
    3131             : 
    3132             : static void av1_setup_past_independence(AV1State *state)
    3133             : {
    3134             :         u32 ref, i;
    3135       17080 :         for (ref = AV1_LAST_FRAME; ref <= AV1_ALTREF_FRAME; ref++) {
    3136      102480 :                 for (i = 0; i <= 5; i++) {
    3137      102480 :                         state->PrevGmParams.coefs[ref][i] = ((i % 3 == 2) ? 1 << WARPEDMODEL_PREC_BITS : 0);
    3138             :                 }
    3139             :         }
    3140             : }
    3141             : 
    3142       61462 : static void av1_load_previous(AV1State *state, u8 primary_ref_frame, s8 *ref_frame_idx)
    3143             : {
    3144       61462 :         s8 prevFrame = ref_frame_idx[primary_ref_frame];
    3145       61462 :         if (prevFrame < 0) {
    3146           0 :                 GF_LOG(GF_LOG_ERROR, GF_LOG_CODING, ("[AV1] load_previous: prevFrame reference index %d is invalid\n", prevFrame));
    3147             :         }
    3148             :         else {
    3149       61462 :                 state->PrevGmParams = state->SavedGmParams[prevFrame];
    3150             :                 // load_loop_filter_params( prevFrame )
    3151             :                 // load_segmentation_params( prevFrame )
    3152             :         }
    3153       61462 : }
    3154             : 
    3155       83699 : static void av1_decode_frame_wrapup(AV1State *state)
    3156             : {
    3157             :         u32 i;
    3158      753291 :         for (i = 0; i < AV1_NUM_REF_FRAMES; i++) {
    3159      669592 :                 if ((state->frame_state.refresh_frame_flags >> i) & 1) {
    3160       68243 :                         state->RefOrderHint[i] = state->frame_state.order_hint;
    3161       68243 :                         state->SavedGmParams[i] = state->GmParams;
    3162       68243 :                         state->RefFrameType[i] = state->frame_state.frame_type;
    3163       68243 :                         state->RefUpscaledWidth[i] = state->UpscaledWidth;
    3164       68243 :                         state->RefFrameHeight[i] = state->height;
    3165             :                 }
    3166             :         }
    3167       83699 :         state->frame_state.seen_frame_header = GF_FALSE;
    3168             :         //Otherwise (show_existing_frame is equal to 1), if frame_type is equal to KEY_FRAME, the reference frame loading process as specified in section 7.21 is invoked
    3169       83699 :         if ((state->frame_state.show_existing_frame) && (state->frame_state.frame_type == AV1_KEY_FRAME)) {
    3170           3 :                 state->frame_state.order_hint = state->RefOrderHint[state->frame_state.frame_to_show_map_idx];
    3171             :                 //OrderHints[ j + LAST_FRAME ] is set equal to SavedOrderHints[state->frame_to_show_map_idx ][ j + LAST_FRAME ] for j = 0..REFS_PER_FRAME-1.
    3172             : 
    3173             :                 //gm_params[ ref ][ j ] is set equal to SavedGmParams[ frame_to_show_map_idx ][ ref ][ j ] for ref = LAST_FRAME..ALTREF_FRAME, for j = 0..5.
    3174           3 :                 state->GmParams = state->SavedGmParams[state->frame_state.frame_to_show_map_idx];
    3175             : 
    3176             :         }
    3177       83699 : }
    3178             : 
    3179             : static s32 find_latest_forward(u32 curFrameHint, u8 *shiftedOrderHints, u8 *usedFrame)
    3180             : {
    3181             :         u32 i;
    3182             :         s32 ref = -1;
    3183             :         s32 latestOrderHint = 0;
    3184         480 :         for (i = 0; i < AV1_NUM_REF_FRAMES; i++) {
    3185         480 :                 s32 hint = shiftedOrderHints[i];
    3186         480 :                 if (!usedFrame[i] && ((u32)hint < curFrameHint) && (ref < 0 || hint >= latestOrderHint)) {
    3187         230 :                         ref = i;
    3188             :                         latestOrderHint = hint;
    3189             :                 }
    3190             :         }
    3191             :         return ref;
    3192             : }
    3193             : 
    3194             : //see 7.8 of AV1 spec
    3195          13 : static void av1_set_frame_refs(AV1State *state, u8 last_frame_idx, u8 gold_frame_idx, s8 *ref_frame_idx)
    3196             : {
    3197             :         u32 i;
    3198             :         u8 usedFrame[AV1_NUM_REF_FRAMES];
    3199             :         u8 shiftedOrderHints[AV1_NUM_REF_FRAMES];
    3200             : 
    3201         104 :         for (i = 0; i < AV1_REFS_PER_FRAME; i++)
    3202          91 :                 ref_frame_idx[i] = -1;
    3203             : 
    3204          13 :         ref_frame_idx[AV1_LAST_FRAME - AV1_LAST_FRAME] = last_frame_idx;
    3205          13 :         ref_frame_idx[AV1_GOLDEN_FRAME - AV1_LAST_FRAME] = gold_frame_idx;
    3206             : 
    3207         117 :         for (i = 0; i < AV1_NUM_REF_FRAMES; i++) {
    3208         104 :                 usedFrame[i] = 0;
    3209             :         }
    3210             : 
    3211          13 :         usedFrame[last_frame_idx] = 1;
    3212          13 :         usedFrame[gold_frame_idx] = 1;
    3213          13 :         u32 curFrameHint = 1 << (state->OrderHintBits - 1);
    3214             : 
    3215         117 :         for (i = 0; i < AV1_NUM_REF_FRAMES; i++) {
    3216         208 :                 shiftedOrderHints[i] = curFrameHint + av1_get_relative_dist(state->RefOrderHint[i], state->frame_state.order_hint, state);
    3217             :         }
    3218             : 
    3219          13 :         u8 lastOrderHint = shiftedOrderHints[last_frame_idx];
    3220          13 :         u8 goldOrderHint = shiftedOrderHints[gold_frame_idx];
    3221             : 
    3222             :         //It is a requirement of bitstream conformance that lastOrderHint is strictly less than curFrameHint.
    3223          13 :         if (lastOrderHint >= curFrameHint) {
    3224           0 :                 GF_LOG(GF_LOG_WARNING, GF_LOG_CODING, ("[AV1] non conformant bitstream detected while setting up frame refs: lastOrderHint(%d) shall be stricly less than curFrameHint(%d)\n", lastOrderHint, curFrameHint));
    3225             :         }
    3226             :         //It is a requirement of bitstream conformance that goldOrderHint is strictly less than curFrameHint.
    3227          13 :         if (goldOrderHint >= curFrameHint) {
    3228           0 :                 GF_LOG(GF_LOG_WARNING, GF_LOG_CODING, ("[AV1] non conformant bitstream detected while setting up frame refs: goldOrderHint(%d) shall be stricly less than curFrameHint(%d)\n", lastOrderHint, curFrameHint));
    3229             :         }
    3230             : 
    3231             :         //find_latest_backward() {
    3232             :         s32 ref = -1;
    3233             :         s32 latestOrderHint = 0;
    3234         117 :         for (i = 0; i < AV1_NUM_REF_FRAMES; i++) {
    3235         104 :                 s32 hint = shiftedOrderHints[i];
    3236         104 :                 if (!usedFrame[i] && ((u32)hint >= curFrameHint) && (ref < 0 || hint >= latestOrderHint)) {
    3237           5 :                         ref = i;
    3238             :                         latestOrderHint = hint;
    3239             :                 }
    3240             :         }
    3241          13 :         if (ref >= 0) {
    3242           5 :                 ref_frame_idx[AV1_ALTREF_FRAME - AV1_LAST_FRAME] = ref;
    3243           5 :                 usedFrame[ref] = 1;
    3244             :         }
    3245             :         //find_earliest_backward() for BWDREF_FRAME
    3246             :         ref = -1;
    3247             :         s32 earliestOrderHint = 0;
    3248         117 :         for (i = 0; i < AV1_NUM_REF_FRAMES; i++) {
    3249         104 :                 s32 hint = shiftedOrderHints[i];
    3250         104 :                 if (!usedFrame[i] && ((u32)hint >= curFrameHint) && (ref < 0 || hint < earliestOrderHint)) {
    3251           0 :                         ref = i;
    3252             :                         earliestOrderHint = hint;
    3253             :                 }
    3254             :         }
    3255          13 :         if (ref >= 0) {
    3256           0 :                 ref_frame_idx[AV1_BWDREF_FRAME - AV1_LAST_FRAME] = ref;
    3257           0 :                 usedFrame[ref] = 1;
    3258             :         }
    3259             : 
    3260             :         //find_earliest_backward() for ALTREF2_FRAME
    3261             :         ref = -1;
    3262             :         earliestOrderHint = 0;
    3263         117 :         for (i = 0; i < AV1_NUM_REF_FRAMES; i++) {
    3264         104 :                 s32 hint = shiftedOrderHints[i];
    3265         104 :                 if (!usedFrame[i] && ((u32)hint >= curFrameHint) && (ref < 0 || hint < earliestOrderHint)) {
    3266           0 :                         ref = i;
    3267             :                         earliestOrderHint = hint;
    3268             :                 }
    3269             :         }
    3270          13 :         if (ref >= 0) {
    3271           0 :                 ref_frame_idx[AV1_ALTREF2_FRAME - AV1_LAST_FRAME] = ref;
    3272           0 :                 usedFrame[ref] = 1;
    3273             :         }
    3274             : 
    3275             :         //The remaining references are set to be forward references in anti-chronological order as follows:
    3276             : 
    3277          13 :         const u8 Ref_Frame_List[AV1_REFS_PER_FRAME - 2] = {
    3278             :                 AV1_LAST2_FRAME, AV1_LAST3_FRAME, AV1_BWDREF_FRAME, AV1_ALTREF2_FRAME, AV1_ALTREF_FRAME
    3279             :         };
    3280             : 
    3281          78 :         for (i = 0; i < AV1_REFS_PER_FRAME - 2; i++) {
    3282          65 :                 u8 refFrame = Ref_Frame_List[i];
    3283          65 :                 if (ref_frame_idx[refFrame - AV1_LAST_FRAME] < 0) {
    3284             :                         s32 last_ref = find_latest_forward(curFrameHint, shiftedOrderHints, usedFrame);
    3285          60 :                         if (last_ref >= 0) {
    3286          60 :                                 ref_frame_idx[refFrame - AV1_LAST_FRAME] = last_ref;
    3287          60 :                                 usedFrame[last_ref] = 1;
    3288             :                         }
    3289             :                 }
    3290             :         }
    3291             :         //Finally, any remaining references are set to the reference frame with smallest output order as follows:
    3292             :         ref = -1;
    3293         104 :         for (i = 0; i < AV1_NUM_REF_FRAMES; i++) {
    3294         104 :                 s32 hint = shiftedOrderHints[i];
    3295         104 :                 if (ref < 0 || hint < earliestOrderHint) {
    3296          13 :                         ref = i;
    3297             :                         earliestOrderHint = hint;
    3298             :                 }
    3299             :         }
    3300          91 :         for (i = 0; i < AV1_REFS_PER_FRAME; i++) {
    3301          91 :                 if (ref_frame_idx[i] < 0) {
    3302           0 :                         ref_frame_idx[i] = ref;
    3303             :                 }
    3304             :         }
    3305          13 : }
    3306             : 
    3307             : 
    3308       83699 : static void av1_parse_uncompressed_header(GF_BitStream *bs, AV1State *state)
    3309             : {
    3310             :         Bool error_resilient_mode = GF_FALSE, allow_screen_content_tools = GF_FALSE, force_integer_mv = GF_FALSE;
    3311             :         Bool /*use_ref_frame_mvs = GF_FALSE,*/ FrameIsIntra = GF_FALSE, frame_size_override_flag = GF_FALSE;
    3312             :         Bool disable_cdf_update = GF_FALSE;
    3313             :         u8 showable_frame;
    3314             :         u8 primary_ref_frame;
    3315             :         u16 idLen = 0;
    3316             :         u32 idx;
    3317             :         s8 ref_frame_idx[AV1_REFS_PER_FRAME];
    3318             :         AV1StateFrame *frame_state = &state->frame_state;
    3319             : 
    3320       83699 :         if (state->frame_id_numbers_present_flag) {
    3321           0 :                 idLen = (state->additional_frame_id_length_minus_1 + state->delta_frame_id_length_minus_2 + 3);
    3322             :         }
    3323       83699 :         frame_state->refresh_frame_flags = 0;
    3324             : 
    3325             :         showable_frame = 0;
    3326       83699 :         if (state->reduced_still_picture_header) {
    3327           0 :                 frame_state->key_frame = GF_TRUE;
    3328             :                 FrameIsIntra = GF_TRUE;
    3329           0 :                 frame_state->frame_type = AV1_KEY_FRAME;
    3330           0 :                 frame_state->show_frame = GF_TRUE;
    3331           0 :                 frame_state->show_existing_frame = 0;
    3332             :         }
    3333             :         else {
    3334       83699 :                 frame_state->show_existing_frame = gf_bs_read_int_log(bs, 1, "show_existing_frame");
    3335       83699 :                 if (frame_state->show_existing_frame == GF_TRUE) {
    3336       19797 :                         frame_state->frame_to_show_map_idx = gf_bs_read_int_log(bs, 3, "frame_to_show_map_idx");
    3337       19797 :                         frame_state->frame_type = state->RefFrameType[frame_state->frame_to_show_map_idx];
    3338             : 
    3339       19797 :                         if (state->decoder_model_info_present_flag && !state->equal_picture_interval) {
    3340           0 :                                 gf_bs_read_int_log(bs, state->frame_presentation_time_length, "frame_presentation_time");
    3341             :                         }
    3342             : 
    3343       19797 :                         frame_state->refresh_frame_flags = 0;
    3344       19797 :                         if (state->frame_id_numbers_present_flag) {
    3345           0 :                                 gf_bs_read_int_log(bs, idLen, "display_frame_id");
    3346             :                         }
    3347       19797 :                         if (frame_state->frame_type == AV1_KEY_FRAME) {
    3348           3 :                                 frame_state->refresh_frame_flags = AV1_ALL_FRAMES;
    3349             :                         }
    3350             :                         /*
    3351             :                         if (film_grain_params_present) {
    3352             :                                 load_grain_params(frame_to_show_map_idx)
    3353             :                         }*/
    3354       19797 :                         return;
    3355             :                 }
    3356       63902 :                 frame_state->frame_type = gf_bs_read_int_log(bs, 2, "frame_type");
    3357       63902 :                 FrameIsIntra = (frame_state->frame_type == AV1_INTRA_ONLY_FRAME || frame_state->frame_type == AV1_KEY_FRAME);
    3358       63902 :                 frame_state->show_frame = gf_bs_read_int_log(bs, 1, "show_frame");
    3359       63902 :                 if (frame_state->is_first_frame) {
    3360       25121 :                         frame_state->key_frame = frame_state->seen_seq_header && frame_state->show_frame && frame_state->frame_type == AV1_KEY_FRAME && frame_state->seen_frame_header;
    3361             :                 }
    3362       63902 :                 if (frame_state->show_frame && state->decoder_model_info_present_flag && !state->equal_picture_interval) {
    3363           0 :                         gf_bs_read_int_log(bs, state->frame_presentation_time_length, "frame_presentation_time");
    3364             :                 }
    3365       63902 :                 if (frame_state->show_frame) {
    3366       38864 :                         showable_frame = frame_state->frame_type != AV1_KEY_FRAME;
    3367             : 
    3368             :                 }
    3369             :                 else {
    3370       25038 :                         showable_frame = gf_bs_read_int_log(bs, 1, "showable_frame");
    3371             :                 }
    3372       63902 :                 if (frame_state->frame_type == AV1_SWITCH_FRAME || (frame_state->frame_type == AV1_KEY_FRAME && frame_state->show_frame))
    3373             :                         error_resilient_mode = GF_TRUE;
    3374             :                 else
    3375             :                         error_resilient_mode = gf_bs_read_int_log(bs, 1, "error_resilient_mode");
    3376             :         }
    3377             : 
    3378       63902 :         if ((frame_state->frame_type == AV1_KEY_FRAME) && frame_state->show_frame) {
    3379             :                 u32 i;
    3380        4952 :                 for (i = 0; i < AV1_NUM_REF_FRAMES; i++) {
    3381        4952 :                         state->RefValid[i] = 0;
    3382        4952 :                         state->RefOrderHint[i] = 0;
    3383             :                 }
    3384        4952 :                 for (i = 0; i < AV1_REFS_PER_FRAME; i++) {
    3385        4333 :                         state->OrderHints[AV1_LAST_FRAME + i] = 0;
    3386             :                 }
    3387             :         }
    3388             : 
    3389             :         disable_cdf_update = gf_bs_read_int_log(bs, 1, "disable_cdf_update");
    3390       63902 :         if (state->seq_force_screen_content_tools == 2/*SELECT_SCREEN_CONTENT_TOOLS*/) {
    3391             :                 allow_screen_content_tools = gf_bs_read_int_log(bs, 1, "allow_screen_content_tools");
    3392             :         }
    3393             :         else {
    3394         117 :                 allow_screen_content_tools = state->seq_force_screen_content_tools;
    3395             :         }
    3396       63902 :         if (allow_screen_content_tools) {
    3397        4137 :                 if (state->seq_force_integer_mv == 2/*SELECT_INTEGER_MV*/) {
    3398             :                         force_integer_mv = gf_bs_read_int_log(bs, 1, "force_integer_mv");
    3399             :                 }
    3400             :                 else {
    3401           0 :                         force_integer_mv = state->seq_force_integer_mv;
    3402             :                 }
    3403             :         }
    3404             :         else {
    3405             :                 force_integer_mv = 0;
    3406             :         }
    3407       63902 :         if (FrameIsIntra) {
    3408             :                 force_integer_mv = 1;
    3409             :         }
    3410       63902 :         if (state->frame_id_numbers_present_flag) {
    3411           0 :                 gf_bs_read_int_log(bs, idLen, "current_frame_id");
    3412             :         }
    3413       63902 :         if (frame_state->frame_type == AV1_SWITCH_FRAME)
    3414             :                 frame_size_override_flag = GF_TRUE;
    3415       63902 :         else if (state->reduced_still_picture_header)
    3416             :                 frame_size_override_flag = GF_FALSE;
    3417             :         else
    3418             :                 frame_size_override_flag = gf_bs_read_int_log(bs, 1, "frame_size_override_flag");
    3419             : 
    3420      127804 :         frame_state->order_hint = gf_bs_read_int_log(bs, state->OrderHintBits, "order_hint");
    3421       63902 :         if (FrameIsIntra || error_resilient_mode) {
    3422             :                 primary_ref_frame = AV1_PRIMARY_REF_NONE;
    3423             :         }
    3424             :         else {
    3425       63207 :                 primary_ref_frame = gf_bs_read_int_log(bs, 3, "primary_ref_frame");
    3426             :         }
    3427             : 
    3428       63902 :         if (state->decoder_model_info_present_flag) {
    3429           0 :                 u8 buffer_removal_time_present_flag = gf_bs_read_int_log(bs, 1, "buffer_removal_time_present_flag");
    3430           0 :                 if (buffer_removal_time_present_flag) {
    3431             :                         u32 opNum;
    3432           0 :                         for (opNum = 0; opNum < state->operating_points_count; opNum++) {
    3433           0 :                                 if (state->decoder_model_present_for_this_op[opNum]) {
    3434           0 :                                         u8 opPtIdc = state->operating_point_idc[opNum];
    3435           0 :                                         u8 inTemporalLayer = (opPtIdc >> state->temporal_id) & 1;
    3436           0 :                                         u8 inSpatialLayer = (opPtIdc >> (state->spatial_id + 8)) & 1;
    3437           0 :                                         if (opPtIdc == 0 || (inTemporalLayer && inSpatialLayer)) {
    3438           0 :                                                 gf_bs_read_int_log_idx(bs, state->buffer_removal_time_length, "buffer_removal_time", opNum);
    3439             :                                         }
    3440             :                                 }
    3441             :                         }
    3442             :                 }
    3443             :         }
    3444             : 
    3445       63902 :         if (frame_state->frame_type == AV1_SWITCH_FRAME || (frame_state->frame_type == AV1_KEY_FRAME && frame_state->show_frame)) {
    3446         619 :                 frame_state->refresh_frame_flags = AV1_ALL_FRAMES;
    3447             :         }
    3448             :         else {
    3449       63283 :                 frame_state->refresh_frame_flags = gf_bs_read_int_log(bs, 8, "refresh_frame_flags");
    3450             :         }
    3451       63902 :         if (!FrameIsIntra || frame_state->refresh_frame_flags != AV1_ALL_FRAMES) {
    3452       63283 :                 if (error_resilient_mode && state->enable_order_hint) {
    3453             :                         u32 i = 0;
    3454           0 :                         for (i = 0; i < AV1_NUM_REF_FRAMES; i++) {
    3455           0 :                                 u8 ref_order_hint = gf_bs_read_int_log_idx(bs, state->OrderHintBits, "ref_order_hint", i);
    3456           0 :                                 if (ref_order_hint != state->RefOrderHint[i]) {
    3457           0 :                                         state->RefValid[i] = 0;
    3458             :                                 }
    3459           0 :                                 state->RefOrderHint[i] = ref_order_hint;
    3460             :                         }
    3461             :                 }
    3462             :         }
    3463             : 
    3464             :         u8 allow_intrabc = 0;
    3465       63902 :         if (frame_state->frame_type == AV1_KEY_FRAME) {
    3466         619 :                 av1_frame_size(bs, state, frame_size_override_flag);
    3467         619 :                 av1_render_size(bs);
    3468         619 :                 if (allow_screen_content_tools && state->UpscaledWidth == state->width) {
    3469          91 :                         allow_intrabc = gf_bs_read_int_log(bs, 1, "allow_intrabc");
    3470             :                 }
    3471             :         }
    3472             :         else {
    3473       63283 :                 if (frame_state->frame_type == AV1_INTRA_ONLY_FRAME) {
    3474           0 :                         av1_frame_size(bs, state, frame_size_override_flag);
    3475           0 :                         av1_render_size(bs);
    3476           0 :                         if (allow_screen_content_tools && state->UpscaledWidth == state->width) {
    3477           0 :                                 allow_intrabc = gf_bs_read_int_log(bs, 1, "allow_intrabc");
    3478             :                         }
    3479             :                 }
    3480             :                 else {
    3481             :                         u32 i = 0;
    3482             :                         Bool frame_refs_short_signaling = GF_FALSE;
    3483       63283 :                         if (state->enable_order_hint) {
    3484             :                                 frame_refs_short_signaling = gf_bs_read_int_log(bs, 1, "frame_refs_short_signaling");
    3485       63172 :                                 if (frame_refs_short_signaling) {
    3486             :                                         u8 last_frame_idx = gf_bs_read_int_log(bs, 3, "last_frame_idx");
    3487             :                                         u8 gold_frame_idx = gf_bs_read_int_log(bs, 3, "gold_frame_idx");
    3488          13 :                                         av1_set_frame_refs(state, last_frame_idx, gold_frame_idx, ref_frame_idx);
    3489             :                                 }
    3490             :                         }
    3491      506264 :                         for (i = 0; i < AV1_REFS_PER_FRAME; i++) {
    3492      442981 :                                 if (!frame_refs_short_signaling)
    3493      885780 :                                         ref_frame_idx[i] = gf_bs_read_int_log_idx(bs, 3, "ref_frame_idx", i);
    3494             : 
    3495      442981 :                                 if (state->frame_id_numbers_present_flag) {
    3496           0 :                                         u32 n = state->delta_frame_id_length_minus_2 + 2;
    3497           0 :                                         /*delta_frame_id_minus_1 =*/ gf_bs_read_int_log_idx(bs, n, "delta_frame_id_minus1", i);
    3498             :                                         //DeltaFrameId = delta_frame_id_minus_1 + 1;
    3499             :                                         //expectedFrameId[i] = ((current_frame_id + (1 << idLen) - DeltaFrameId) % (1 << idLen));
    3500             :                                 }
    3501             :                         }
    3502       63283 :                         if (frame_size_override_flag && !error_resilient_mode) {
    3503          22 :                                 frame_size_with_refs(bs, state, frame_size_override_flag, ref_frame_idx);
    3504             :                         }
    3505             :                         else {
    3506       63261 :                                 av1_frame_size(bs, state, frame_size_override_flag);
    3507       63261 :                                 av1_render_size(bs);
    3508             :                         }
    3509       63283 :                         frame_state->allow_high_precision_mv = 0;
    3510       63283 :                         if (!force_integer_mv) {
    3511       59978 :                                 frame_state->allow_high_precision_mv = gf_bs_read_int_log(bs, 1, "allow_high_precision_mv");
    3512             :                         }
    3513             : 
    3514       63283 :                         read_interpolation_filter(bs);
    3515             : 
    3516       63283 :                         gf_bs_read_int_log(bs, 1, "is_motion_mode_switchable");
    3517       63283 :                         if (!(error_resilient_mode || !state->enable_ref_frame_mvs)) {
    3518       63172 :                                 gf_bs_read_int_log(bs, 1, "use_ref_frame_mvs");
    3519             :                         }
    3520             :                 }
    3521             :         }
    3522             : 
    3523       63902 :         if (!FrameIsIntra) {
    3524             :                 u32 i;
    3525      442981 :                 for (i = 0; i < AV1_REFS_PER_FRAME; i++) {
    3526      442981 :                         u8 refFrame = AV1_LAST_FRAME + i;
    3527      442981 :                         u8 ridx = ref_frame_idx[i];
    3528             :                         if (ridx >= 0) {
    3529      442981 :                                 u8 hint = state->RefOrderHint[ridx];
    3530      442981 :                                 state->OrderHints[refFrame] = hint;
    3531             :                                 /*                      if ( !enable_order_hint ) {
    3532             :                                                                 RefFrameSignBias[ refFrame ] = 0;
    3533             :                                                         } else {
    3534             :                                                                 RefFrameSignBias[ refFrame ] = get_relative_dist( hint, OrderHint) > 0;
    3535             :                                                         }
    3536             :                                 */
    3537             :                         }
    3538             : 
    3539             :                 }
    3540             :         }
    3541             : 
    3542       63902 :         if (!(state->reduced_still_picture_header || disable_cdf_update))
    3543       63902 :                 gf_bs_read_int_log(bs, 1, "disable_frame_end_update_cdf");
    3544             : 
    3545       63902 :         if (primary_ref_frame == AV1_PRIMARY_REF_NONE) {
    3546             :                 //init_non_coeff_cdfs();
    3547             :                 av1_setup_past_independence(state);
    3548             :         }
    3549             :         else {
    3550             :                 //load_cdfs(ref_frame_idx[primary_ref_frame]);
    3551       61462 :                 av1_load_previous(state, primary_ref_frame, ref_frame_idx);
    3552             :         }
    3553             : 
    3554       63902 :         av1_parse_tile_info(bs, state);
    3555             :         //quantization_params( ):
    3556       63902 :         u8 base_q_idx = gf_bs_read_int_log(bs, 8, "base_q_idx");
    3557             :         s32 DeltaQUDc = 0;
    3558             :         s32 DeltaQUAc = 0;
    3559             :         s32 DeltaQVDc = 0;
    3560             :         s32 DeltaQVAc = 0;
    3561       63902 :         s32 DeltaQYDc = av1_delta_q(bs, "DeltaQYDc_coded", "DeltaQYDc");
    3562       63902 :         if (!state->config->monochrome) {
    3563             :                 u8 diff_uv_delta = 0;
    3564       63902 :                 if (state->separate_uv_delta_q)
    3565           0 :                         diff_uv_delta = gf_bs_read_int_log(bs, 1, "diff_uv_delta");
    3566             : 
    3567       63902 :                 DeltaQUDc = av1_delta_q(bs, "DeltaQUDc_coded", "DeltaQUDc");
    3568       63902 :                 DeltaQUAc = av1_delta_q(bs, "DeltaQUAc_coded", "DeltaQUAc");
    3569       63902 :                 if (diff_uv_delta) {
    3570           0 :                         DeltaQVDc = av1_delta_q(bs, "DeltaQVDc_coded", "DeltaQVDc");
    3571           0 :                         DeltaQVAc = av1_delta_q(bs, "DeltaQVAc_coded", "DeltaQVAc");
    3572             :                 }
    3573             :         }
    3574       63902 :         if (gf_bs_read_int_log(bs, 1, "using_qmatrix")) {
    3575           0 :                 gf_bs_read_int_log(bs, 4, "qm_y");
    3576           0 :                 gf_bs_read_int_log(bs, 4, "qm_u");
    3577           0 :                 if (!state->separate_uv_delta_q) {
    3578           0 :                         gf_bs_read_int_log(bs, 4, "qm_v");
    3579             :                 }
    3580             :         }
    3581             : 
    3582       63902 :         u8 seg_features_SEG_LVL_ALT_Q_enabled[8] = { 0,0,0,0,0,0,0,0 };
    3583       63902 :         s32 seg_features_SEG_LVL_ALT_Q[8] = { 0,0,0,0,0,0,0,0 };
    3584             : 
    3585             :         //segmentation_params( ):
    3586       63902 :         u8 segmentation_enabled = gf_bs_read_int_log(bs, 1, "segmentation_enabled");
    3587       63902 :         if (segmentation_enabled) {
    3588             :                 /*u8 segmentation_temporal_update = 0;*/
    3589             :                 u8 segmentation_update_data = 1;
    3590          29 :                 if (primary_ref_frame != AV1_PRIMARY_REF_NONE) {
    3591          18 :                         u8 segmentation_update_map = gf_bs_read_int_log(bs, 1, "segmentation_update_map");
    3592          18 :                         if (segmentation_update_map == 1)
    3593          18 :                                 gf_bs_read_int_log(bs, 1, "segmentation_temporal_update");
    3594          18 :                         segmentation_update_data = gf_bs_read_int_log(bs, 1, "segmentation_update_data");
    3595             :                 }
    3596          18 :                 if (segmentation_update_data == 1) {
    3597             :                         u32 i, j;
    3598         232 :                         for (i = 0; i < 8/*=MAX_SEGMENTS*/; i++) {
    3599        1856 :                                 for (j = 0; j < 8 /*=SEG_LVL_MAX*/; j++) {
    3600        3712 :                                         if (/*feature_enabled = */gf_bs_read_int_log_idx2(bs, 1, "feature_enabled", i, j) == 1) {
    3601             :                                                 s32 val;
    3602          58 :                                                 u32 bitsToRead = Segmentation_Feature_Bits[j];
    3603             :                                                 //this is SEG_LVL_ALT_Q
    3604          58 :                                                 if (!j) seg_features_SEG_LVL_ALT_Q_enabled[i] = 1;
    3605             : 
    3606          58 :                                                 if (Segmentation_Feature_Signed[j] == 1) {
    3607         116 :                                                         val = gf_bs_read_int_log_idx2(bs, 1 + bitsToRead, "signed_feature_value", i, j);
    3608             :                                                 }
    3609             :                                                 else {
    3610           0 :                                                         val = gf_bs_read_int_log_idx2(bs, bitsToRead, "feature_value", i, j);
    3611             :                                                 }
    3612          58 :                                                 if (!j) seg_features_SEG_LVL_ALT_Q[i] = val;
    3613             :                                         }
    3614             :                                 }
    3615             :                         }
    3616             :                         //ignore all init steps
    3617             :                 }
    3618             : 
    3619             :         }
    3620             : 
    3621             :         //delta_q_params():
    3622             :         /*u8 delta_q_res = 0;*/
    3623             :         u8 delta_q_present = 0;
    3624       63902 :         if (base_q_idx > 0) {
    3625       63902 :                 delta_q_present = gf_bs_read_int_log(bs, 1, "delta_q_present");
    3626             :         }
    3627       63902 :         if (delta_q_present) {
    3628           0 :                 gf_bs_read_int_log(bs, 2, "delta_q_res");
    3629             :         }
    3630             : 
    3631             :         //delta_lf_params():
    3632             :         u8 delta_lf_present = 0;
    3633             :         /*u8 delta_lf_res = 0;
    3634             :         u8 delta_lf_multi = 0;*/
    3635       63902 :         if (delta_q_present) {
    3636           0 :                 if (!allow_intrabc) {
    3637           0 :                         delta_lf_present = gf_bs_read_int_log(bs, 1, "delta_lf_present");
    3638             :                 }
    3639           0 :                 if (delta_lf_present) {
    3640           0 :                         gf_bs_read_int_log(bs, 2, "delta_lf_res");
    3641           0 :                         gf_bs_read_int_log(bs, 1, "delta_lf_multi");
    3642             :                 }
    3643             :         }
    3644             : 
    3645             :         //init lossless stuff!
    3646             :         u8 CodedLossless = 1;
    3647      511216 :         for (idx = 0; idx < 8; idx++) {
    3648             :                 u8 qindex = av1_get_qindex(GF_TRUE, idx, base_q_idx, delta_q_present, 0/*CurrentQIndex always ignored at this level of parsin*/, segmentation_enabled, seg_features_SEG_LVL_ALT_Q_enabled, seg_features_SEG_LVL_ALT_Q);
    3649      511216 :                 Bool LosslessArray = (qindex == 0) && (DeltaQYDc == 0) && (DeltaQUAc == 0) && (DeltaQUDc == 0) && (DeltaQVAc == 0) && (DeltaQVDc == 0);
    3650             :                 if (!LosslessArray)
    3651             :                         CodedLossless = 0;
    3652             :         }
    3653       63902 :         Bool AllLossless = CodedLossless && (state->width == state->UpscaledWidth);
    3654             : 
    3655             :         //loop_filter_params():
    3656       63902 :         if (!CodedLossless && !allow_intrabc) {
    3657       63902 :                 u8 loop_filter_level_0 = gf_bs_read_int_log(bs, 6, "loop_filter_level_0");
    3658       63902 :                 u8 loop_filter_level_1 = gf_bs_read_int_log(bs, 6, "loop_filter_level_1");
    3659       63902 :                 if (!state->config->monochrome) {
    3660       63902 :                         if (loop_filter_level_0 || loop_filter_level_1) {
    3661       57722 :                                 gf_bs_read_int_log(bs, 6, "loop_filter_level_2");
    3662       57722 :                                 gf_bs_read_int_log(bs, 6, "loop_filter_level_3");
    3663             :                         }
    3664             :                 }
    3665       63902 :                 gf_bs_read_int_log(bs, 3, "loop_filter_sharpness");
    3666       63902 :                 u8 loop_filter_delta_enabled = gf_bs_read_int_log(bs, 1, "loop_filter_delta_enabled");
    3667       63902 :                 if (loop_filter_delta_enabled == 1) {
    3668       63902 :                         u8 loop_filter_delta_update = gf_bs_read_int_log(bs, 1, "loop_filter_delta_update");
    3669       63902 :                         if (loop_filter_delta_update) {
    3670             :                                 u32 i;
    3671       18776 :                                 for (i = 0; i < 8/*TOTAL_REFS_PER_FRAME*/; i++) {
    3672       37552 :                                         u8 update_ref_delta = gf_bs_read_int_log_idx(bs, 1, "update_ref_delta", i);
    3673       18776 :                                         if (update_ref_delta == 1) {
    3674           0 :                                                 gf_bs_read_int_log_idx(bs, 1 + 6, "loop_filter_ref_deltas", i);
    3675             :                                         }
    3676             :                                 }
    3677        4694 :                                 for (i = 0; i < 2; i++) {
    3678        9388 :                                         u8 update_mode_delta = gf_bs_read_int_log_idx(bs, 1, "update_mode_delta", i);
    3679        4694 :                                         if (update_mode_delta) {
    3680           0 :                                                 gf_bs_read_int_log_idx(bs, 1 + 6, "loop_filter_mode_deltas", i);
    3681             :                                         }
    3682             :                                 }
    3683             :                         }
    3684             :                 }
    3685             :         }
    3686             :         //cdef_params( ):
    3687       63902 :         if (!CodedLossless && !allow_intrabc && state->enable_cdef) {
    3688       63902 :                 gf_bs_read_int_log(bs, 2, "cdef_damping_minus_3");
    3689             :                 u8 cdef_bits = gf_bs_read_int_log(bs, 2, "cdef_bits");
    3690       63902 :                 u32 i, num_cd = 1 << cdef_bits;
    3691      291445 :                 for (i = 0; i < num_cd; i++) {
    3692      227543 :                         gf_bs_read_int_log_idx(bs, 4, "cdef_y_pri_strength", i);
    3693      227543 :                         gf_bs_read_int_log_idx(bs, 2, "cdef_y_sec_strength", i);
    3694      227543 :                         if (!state->config->monochrome) {
    3695      227543 :                                 gf_bs_read_int_log_idx(bs, 4, "cdef_uv_pri_strength", i);
    3696      227543 :                                 gf_bs_read_int_log_idx(bs, 2, "cdef_uv_sec_strength", i);
    3697             :                         }
    3698             :                 }
    3699             :         }
    3700             : 
    3701             :         //lr_params( ) :
    3702       63902 :         if (!AllLossless && !allow_intrabc && state->enable_restoration) {
    3703       63785 :                 u32 i, nb_planes = state->config->monochrome ? 1 : 3;
    3704             :                 u8 UsesLr = 0;
    3705             :                 u8 usesChromaLr = 0;
    3706      255140 :                 for (i = 0; i < nb_planes; i++) {
    3707      382710 :                         u8 lr_type = gf_bs_read_int_log_idx(bs, 2, "lr_type", i);
    3708             :                         //FrameRestorationType[i] = Remap_Lr_Type[lr_type]
    3709      191355 :                         if (lr_type != AV1_RESTORE_NONE) {
    3710             :                                 UsesLr = 1;
    3711       58049 :                                 if (i > 0) {
    3712             :                                         usesChromaLr = 1;
    3713             :                                 }
    3714             :                         }
    3715             :                 }
    3716       63785 :                 if (UsesLr) {
    3717       38104 :                         if (state->use_128x128_superblock) {
    3718       38004 :                                 gf_bs_read_int_log(bs, 1, "lr_unit_shift_minus_1");
    3719             :                         }
    3720             :                         else {
    3721         100 :                                 u8 lr_unit_shift = gf_bs_read_int_log(bs, 1, "lr_unit_shift");
    3722         100 :                                 if (lr_unit_shift) {
    3723         100 :                                         gf_bs_read_int_log(bs, 1, "lr_unit_extra_shift");
    3724             :                                         //lr_unit_shift += lr_unit_extra_shift;
    3725             :                                 }
    3726             :                         }
    3727       38104 :                         if (state->config->chroma_subsampling_x && state->config->chroma_subsampling_y && usesChromaLr) {
    3728       13857 :                                 gf_bs_read_int_log(bs, 1, "lr_uv_shift");
    3729             :                         }
    3730             :                 }
    3731             :         }
    3732             :         //read_tx_mode():
    3733       63902 :         if (CodedLossless == 1) {
    3734             :         }
    3735             :         else {
    3736       63902 :                 gf_bs_read_int_log(bs, 1, "tx_mode_select");
    3737             :         }
    3738             : 
    3739             :         //frame_reference_mode( ):
    3740             :         u8 reference_select = 0;
    3741       63902 :         if (FrameIsIntra) {
    3742             :         }
    3743             :         else {
    3744       63283 :                 reference_select = gf_bs_read_int_log(bs, 1, "reference_select");
    3745             :         }
    3746             : 
    3747             :         //skip_mode_params( ):
    3748             :         u8 skipModeAllowed = 0;
    3749       63902 :         if (FrameIsIntra || !reference_select || !state->enable_order_hint) {
    3750             :         }
    3751             :         else {
    3752             :                 u32 i;
    3753             :                 s32 forwardIdx = -1;
    3754             :                 s32 backwardIdx = -1;
    3755             :                 s32 forwardHint = 0;
    3756             :                 s32 backwardHint = 0;
    3757      357350 :                 for (i = 0; i < AV1_REFS_PER_FRAME; i++) {
    3758      357350 :                         u8 refHint = state->RefOrderHint[ref_frame_idx[i]];
    3759      714700 :                         if (av1_get_relative_dist(refHint, frame_state->order_hint, state) < 0) {
    3760      498414 :                                 if (forwardIdx < 0 || av1_get_relative_dist(refHint, forwardHint, state) > 0) {
    3761       68850 :                                         forwardIdx = i;
    3762             :                                         forwardHint = refHint;
    3763             :                                 }
    3764             :                         }
    3765       82618 :                         else if (av1_get_relative_dist(refHint, frame_state->order_hint, state) > 0) {
    3766      119912 :                                 if (backwardIdx < 0 || av1_get_relative_dist(refHint, backwardHint, state) < 0) {
    3767       44928 :                                         backwardIdx = i;
    3768             :                                         backwardHint = refHint;
    3769             :                                 }
    3770             :                         }
    3771             :                 }
    3772       51050 :                 if (forwardIdx < 0) {
    3773             :                         skipModeAllowed = 0;
    3774             :                 }
    3775       51050 :                 else if (backwardIdx >= 0) {
    3776             :                         skipModeAllowed = 1;
    3777             :                         //SkipModeFrame[0] = AV1_LAST_FRAME + MIN(forwardIdx, backwardIdx);
    3778             :                         //SkipModeFrame[1] = AV1_LAST_FRAME + MAX(forwardIdx, backwardIdx);
    3779             :                 }
    3780             :                 else {
    3781             :                         s32 secondForwardIdx = -1;
    3782             :                         s32 secondForwardHint = 0;
    3783       42854 :                         for (i = 0; i < AV1_REFS_PER_FRAME; i++) {
    3784       42854 :                                 u8 refHint = state->RefOrderHint[ref_frame_idx[i]];
    3785       85708 :                                 if (av1_get_relative_dist(refHint, forwardHint, state) < 0) {
    3786       66674 :                                         if (secondForwardIdx < 0 || av1_get_relative_dist(refHint, secondForwardHint, state) > 0) {
    3787        6258 :                                                 secondForwardIdx = i;
    3788             :                                                 secondForwardHint = refHint;
    3789             :                                         }
    3790             :                                 }
    3791             :                         }
    3792        6122 :                         if (secondForwardIdx < 0) {
    3793             :                                 skipModeAllowed = 0;
    3794             :                         }
    3795             :                         else {
    3796             :                                 skipModeAllowed = 1;
    3797             :                                 //SkipModeFrame[ 0 ] = LAST_FRAME + Min(forwardIdx, secondForwardIdx)
    3798             :                                 //SkipModeFrame[ 1 ] = LAST_FRAME + Max(forwardIdx, secondForwardIdx)
    3799             :                         }
    3800             :                 }
    3801             :         }
    3802             :         if (skipModeAllowed) {
    3803       51050 :                 gf_bs_read_int_log(bs, 1, "skip_mode_present");
    3804             :         }
    3805             : 
    3806             : 
    3807       63902 :         if (FrameIsIntra || error_resilient_mode || !state->enable_warped_motion) {
    3808             : 
    3809             :         }
    3810             :         else {
    3811       63172 :                 gf_bs_read_int_log(bs, 1, "allow_warped_motion");
    3812             :         }
    3813             : 
    3814       63902 :         gf_bs_read_int_log(bs, 1, "reduced_tx");
    3815             : 
    3816             :         //global_motion_params( )
    3817             :         u32 ref;
    3818      511216 :         for (ref = AV1_LAST_FRAME; ref <= AV1_ALTREF_FRAME; ref++) {
    3819             :                 u32 i;
    3820     2683884 :                 for (i = 0; i < 6; i++) {
    3821     2683884 :                         state->GmParams.coefs[ref][i] = ((i % 3 == 2) ? 1 << WARPEDMODEL_PREC_BITS : 0);
    3822             :                 }
    3823             :         }
    3824       63902 :         if (!FrameIsIntra) {
    3825             :                 u32 refs;
    3826      442981 :                 for (refs = AV1_LAST_FRAME; refs <= AV1_ALTREF_FRAME; refs++) {
    3827             :                         u8 type = AV1_GMC_IDENTITY;
    3828      442981 :                         Bool is_global = gf_bs_read_int_log_idx(bs, 1, "is_global", refs);
    3829      442981 :                         if (is_global) {
    3830             :                                 Bool is_rot_zoom = gf_bs_read_int_log_idx(bs, 1, "is_rot_zoom", refs);
    3831        6552 :                                 if (is_rot_zoom) {
    3832             :                                         type = AV1_GMC_ROTZOOM;
    3833             :                                 }
    3834             :                                 else {
    3835             :                                         Bool is_trans = gf_bs_read_int_log_idx(bs, 1, "is_translation", refs);
    3836           4 :                                         type = is_trans ? AV1_GMC_TRANSLATION : AV1_GMC_AFFINE;
    3837             : 
    3838             :                                 }
    3839             :                         }
    3840             : 
    3841             :                         if (type >= AV1_GMC_ROTZOOM) {
    3842        6548 :                                 av1_read_global_param(state, bs, type, refs, 2);
    3843        6548 :                                 av1_read_global_param(state, bs, type, refs, 3);
    3844        6548 :                                 if (type == AV1_GMC_AFFINE) {
    3845           0 :                                         av1_read_global_param(state, bs, type, refs, 4);
    3846           0 :                                         av1_read_global_param(state, bs, type, refs, 5);
    3847             :                                 }
    3848             :                                 else {
    3849        6548 :                                         state->GmParams.coefs[refs][4] = -state->GmParams.coefs[refs][3];
    3850        6548 :                                         state->GmParams.coefs[refs][5] = state->GmParams.coefs[refs][2];
    3851             : 
    3852             :                                 }
    3853             :                         }
    3854      442981 :                         if (type >= AV1_GMC_TRANSLATION) {
    3855        6552 :                                 av1_read_global_param(state, bs, type, refs, 0);
    3856        6552 :                                 av1_read_global_param(state, bs, type, refs, 1);
    3857             :                         }
    3858             :                 }
    3859             :         }
    3860             : 
    3861             :         //film_grain_params()
    3862       63902 :         if (!state->film_grain_params_present || (!state->frame_state.show_frame && !showable_frame)) {
    3863             :         }
    3864             :         else {
    3865       17900 :                 u8 apply_grain = gf_bs_read_int_log(bs, 1, "apply_grain");
    3866       17900 :                 if (apply_grain) {
    3867       17900 :                         gf_bs_read_int_log(bs, 16, "grain_seed");
    3868             :                         u8 update_grain = 1;
    3869       17900 :                         if (state->frame_state.frame_type == AV1_INTER_FRAME) {
    3870       17745 :                                 update_grain = gf_bs_read_int_log(bs, 1, "update_grain");
    3871             :                         }
    3872       17745 :                         if (!update_grain) {
    3873           0 :                                 gf_bs_read_int_log(bs, 3, "film_grain_params_ref_idx");
    3874             :                         }
    3875             :                         else {
    3876             :                                 u32 i, num_y_points = gf_bs_read_int_log(bs, 4, "num_y_points");
    3877      117358 :                                 for (i = 0; i < num_y_points; i++) {
    3878       99458 :                                         gf_bs_read_int_log_idx(bs, 8, "point_y_value", i);
    3879       99458 :                                         gf_bs_read_int_log_idx(bs, 8, "point_y_scaling", i);
    3880             :                                 }
    3881             :                                 u8 chroma_scaling_from_luma = 0;
    3882       17900 :                                 if (!state->config->monochrome)
    3883       17900 :                                         chroma_scaling_from_luma = gf_bs_read_int_log(bs, 1, "chroma_scaling_from_luma");
    3884             : 
    3885             :                                 u8 num_cb_points = 0;
    3886             :                                 u8 num_cr_points = 0;
    3887       35800 :                                 if (state->config->monochrome || chroma_scaling_from_luma ||
    3888       35800 :                                         ((state->config->chroma_subsampling_x == 1) && (state->config->chroma_subsampling_y == 1) && (num_y_points == 0))
    3889             :                                         ) {
    3890             :                                 }
    3891             :                                 else {
    3892       17900 :                                         num_cb_points = gf_bs_read_int_log(bs, 4, "num_cb_points");
    3893      104076 :                                         for (i = 0; i < num_cb_points; i++) {
    3894       86176 :                                                 gf_bs_read_int_log_idx(bs, 8, "point_cb_value", i);
    3895       86176 :                                                 gf_bs_read_int_log_idx(bs, 8, "point_cb_scaling", i);
    3896             :                                         }
    3897       17900 :                                         num_cr_points = gf_bs_read_int_log(bs, 4, "num_cr_points");
    3898       99722 :                                         for (i = 0; i < num_cr_points; i++) {
    3899       81822 :                                                 gf_bs_read_int_log_idx(bs, 8, "point_cr_value", i);
    3900       81822 :                                                 gf_bs_read_int_log_idx(bs, 8, "point_cr_scaling", i);
    3901             :                                         }
    3902             :                                 }
    3903       17900 :                                 gf_bs_read_int_log(bs, 2, "grain_scaling_minus_8");
    3904       17900 :                                 u8 ar_coeff_lag = gf_bs_read_int_log(bs, 2, "ar_coeff_lag");
    3905       17900 :                                 u16 numPosLuma = 2 * ar_coeff_lag * (ar_coeff_lag + 1);
    3906             :                                 u16 numPosChroma = numPosLuma;
    3907       17900 :                                 if (num_y_points) {
    3908       17900 :                                         numPosChroma = numPosLuma + 1;
    3909      447500 :                                         for (i = 0; i < numPosLuma; i++) {
    3910      429600 :                                                 gf_bs_read_int_log_idx(bs, 8, "ar_coeffs_y_plus_128", i);
    3911             :                                         }
    3912             :                                 }
    3913       17900 :                                 if (chroma_scaling_from_luma || num_cb_points) {
    3914      447500 :                                         for (i = 0; i < numPosChroma; i++) {
    3915      447500 :                                                 gf_bs_read_int_log_idx(bs, 8, "ar_coeffs_cb_plus_128", i);
    3916             :                                         }
    3917             :                                 }
    3918       17900 :                                 if (chroma_scaling_from_luma || num_cr_points) {
    3919      447500 :                                         for (i = 0; i < numPosChroma; i++) {
    3920      447500 :                                                 gf_bs_read_int_log_idx(bs, 8, "ar_coeffs_cr_plus_128", i);
    3921             :                                         }
    3922             :                                 }
    3923       17900 :                                 gf_bs_read_int_log(bs, 2, "ar_coeff_shift_minus_6");
    3924       17900 :                                 gf_bs_read_int_log(bs, 2, "grain_scale_shift");
    3925       17900 :                                 if (num_cb_points) {
    3926       17900 :                                         gf_bs_read_int_log(bs, 8, "cb_mult");
    3927       17900 :                                         gf_bs_read_int_log(bs, 8, "cb_luma_mult");
    3928       17900 :                                         gf_bs_read_int_log(bs, 9, "cb_offset");
    3929             :                                 }
    3930       17900 :                                 if (num_cr_points) {
    3931       17900 :                                         gf_bs_read_int_log(bs, 8, "cr_mult");
    3932       17900 :                                         gf_bs_read_int_log(bs, 8, "cr_luma_mult");
    3933       17900 :                                         gf_bs_read_int_log(bs, 9, "cr_offset");
    3934             :                                 }
    3935       17900 :                                 gf_bs_read_int_log(bs, 1, "overlap_flag");
    3936       17900 :                                 gf_bs_read_int_log(bs, 1, "clip_to_restricted_range");
    3937             :                         }
    3938             :                 }
    3939             :         }
    3940             : 
    3941             :         //end of uncompressed header !!
    3942             : }
    3943             : 
    3944             : GF_EXPORT
    3945        3696 : void gf_av1_init_state(AV1State *state)
    3946             : {
    3947        3696 :         if (!state) return;
    3948             :         memset(state, 0, sizeof(AV1State));
    3949        3696 :         state->color_primaries = 2;
    3950        3696 :         state->transfer_characteristics = 2;
    3951        3696 :         state->matrix_coefficients = 2;
    3952             : }
    3953             : 
    3954             : GF_EXPORT
    3955       42665 : void gf_av1_reset_state(AV1State *state, Bool is_destroy)
    3956             : {
    3957             :         GF_List *l1, *l2;
    3958             : 
    3959       42665 :         if (state->frame_state.header_obus) {
    3960       38545 :                 while (gf_list_count(state->frame_state.header_obus)) {
    3961         128 :                         GF_AV1_OBUArrayEntry *a = (GF_AV1_OBUArrayEntry*)gf_list_pop_back(state->frame_state.header_obus);
    3962         128 :                         if (a->obu) gf_free(a->obu);
    3963         128 :                         gf_free(a);
    3964             :                 }
    3965             :         }
    3966             : 
    3967       42665 :         if (state->frame_state.frame_obus) {
    3968         476 :                 while (gf_list_count(state->frame_state.frame_obus)) {
    3969         281 :                         GF_AV1_OBUArrayEntry *a = (GF_AV1_OBUArrayEntry*)gf_list_pop_back(state->frame_state.frame_obus);
    3970         281 :                         if (a->obu) gf_free(a->obu);
    3971         281 :                         gf_free(a);
    3972             :                 }
    3973             :         }
    3974       42665 :         l1 = state->frame_state.frame_obus;
    3975       42665 :         l2 = state->frame_state.header_obus;
    3976       42665 :         memset(&state->frame_state, 0, sizeof(AV1StateFrame));
    3977       42665 :         state->frame_state.is_first_frame = GF_TRUE;
    3978             : 
    3979       42665 :         if (is_destroy) {
    3980        3783 :                 gf_list_del(l1);
    3981        3783 :                 gf_list_del(l2);
    3982        3783 :                 if (state->bs) {
    3983          77 :                         if (gf_bs_get_position(state->bs)) {
    3984             :                                 u32 size;
    3985           1 :                                 gf_bs_get_content_no_truncate(state->bs, &state->frame_obus, &size, &state->frame_obus_alloc);
    3986             :                         }
    3987          77 :                         gf_bs_del(state->bs);
    3988             :                 }
    3989        3783 :                 state->bs = NULL;
    3990             :         }
    3991             :         else {
    3992       38882 :                 state->frame_state.frame_obus = l1;
    3993       38882 :                 state->frame_state.header_obus = l2;
    3994       38882 :                 if (state->bs)
    3995       37318 :                         gf_bs_seek(state->bs, 0);
    3996             :         }
    3997       42665 : }
    3998             : 
    3999       64208 : static GF_Err av1_parse_tile_group(GF_BitStream *bs, AV1State *state, u64 obu_start, u64 obu_size)
    4000             : {
    4001             :         u32 TileNum, tg_start = 0, tg_end = 0;
    4002       64208 :         Bool numTiles = state->tileCols * state->tileRows;
    4003             :         Bool tile_start_and_end_present_flag = GF_FALSE;
    4004             :         GF_Err e = GF_OK;
    4005       64208 :         if (numTiles > 1)
    4006             :                 tile_start_and_end_present_flag = gf_bs_read_int_log(bs, 1, "tile_start_and_end_present_flag");
    4007             : 
    4008       64208 :         if (numTiles == 1 || !tile_start_and_end_present_flag) {
    4009             :                 tg_start = 0;
    4010       63772 :                 tg_end = numTiles - 1;
    4011             :                 /*state->frame_state.tg[0].start_idx = 0;
    4012             :                 state->frame_state.tg[0].end_idx = numTiles - 1;*/
    4013             :         }
    4014             :         else {
    4015         436 :                 u32 tileBits = state->tileColsLog2 + state->tileRowsLog2;
    4016             :                 /*state->frame_state.tg[state->frame_state.tg_idx].start_idx*/ tg_start = gf_bs_read_int_log(bs, tileBits, "tg_start");
    4017             :                 /*state->frame_state.tg[state->frame_state.tg_idx].end_idx*/ tg_end = gf_bs_read_int_log(bs, tileBits, "tg_end");
    4018             :         }
    4019             :         /*state->frame_state.tg_idx++;*/
    4020             : 
    4021       64208 :         gf_bs_align(bs);
    4022             : 
    4023       64208 :         if (tg_end >= GF_ARRAY_LENGTH(state->frame_state.tiles))
    4024             :                 return GF_NON_COMPLIANT_BITSTREAM;
    4025             : 
    4026       64208 :         state->frame_state.nb_tiles_in_obu = 0;
    4027      304229 :         for (TileNum = tg_start; TileNum <= tg_end; TileNum++) {
    4028             :                 u32 tile_start_offset, tile_size;
    4029             :                 /*u32 tileRow = TileNum / state->tileCols;
    4030             :                 u32 tileCol = TileNum % state->tileCols;*/
    4031             :                 Bool lastTile = TileNum == tg_end;
    4032      240021 :                 u64 pos = gf_bs_get_position(bs);
    4033      240021 :                 if (lastTile) {
    4034       64208 :                         tile_start_offset = (u32)(pos - obu_start);
    4035       64208 :                         tile_size = (u32)(obu_size - (pos - obu_start));
    4036             :                 }
    4037             :                 else {
    4038      175813 :                         u64 tile_size_minus_1 = aom_av1_le(bs, state->tile_size_bytes, "tile_size_minus_1");
    4039      175813 :                         pos = gf_bs_get_position(bs);
    4040      175813 :                         tile_start_offset = (u32)(pos - obu_start);
    4041      175813 :                         tile_size = (u32)(tile_size_minus_1 + 1/* + state->tile_size_bytes*/);
    4042             :                 }
    4043             : 
    4044             : 
    4045      240021 :                 if (tile_start_offset + tile_size > obu_size) {
    4046           0 :                         GF_LOG(GF_LOG_ERROR, GF_LOG_CODING, ("[AV1] Error parsing tile group, tile %d start %d + size %d exceeds OBU length %d\n", TileNum, tile_start_offset, tile_size, obu_size));
    4047             :                         e = GF_NON_COMPLIANT_BITSTREAM;
    4048             :                         break;
    4049             :                 }
    4050             : 
    4051      240021 :                 state->frame_state.tiles[state->frame_state.nb_tiles_in_obu].obu_start_offset = tile_start_offset;
    4052      240021 :                 state->frame_state.tiles[state->frame_state.nb_tiles_in_obu].size = tile_size;
    4053      240021 :                 gf_bs_skip_bytes(bs, tile_size);
    4054      240021 :                 state->frame_state.nb_tiles_in_obu++;
    4055             :         }
    4056       64208 :         if (tg_end == numTiles - 1) {
    4057       63902 :                 av1_decode_frame_wrapup(state);
    4058             :         }
    4059             :         return e;
    4060             : }
    4061             : 
    4062       83699 : static void av1_parse_frame_header(GF_BitStream *bs, AV1State *state)
    4063             : {
    4064             :         AV1StateFrame *frame_state = &state->frame_state;
    4065       83699 :         if (frame_state->seen_frame_header == GF_FALSE) {
    4066       83699 :                 u64 pos = gf_bs_get_position(bs);
    4067       83699 :                 state->frame_state.show_existing_frame = GF_FALSE;
    4068       83699 :                 frame_state->seen_frame_header = GF_TRUE;
    4069       83699 :                 av1_parse_uncompressed_header(bs, state);
    4070       83699 :                 state->frame_state.is_first_frame = GF_FALSE;
    4071       83699 :                 state->frame_state.uncompressed_header_bytes = (u32) (gf_bs_get_position(bs) - pos);
    4072             : 
    4073       83699 :                 if (state->frame_state.show_existing_frame) {
    4074       19797 :                         av1_decode_frame_wrapup(state);
    4075       19797 :                         frame_state->seen_frame_header = GF_FALSE;
    4076             :                 }
    4077             :                 else {
    4078             :                         //TileNum = 0;
    4079       63902 :                         frame_state->seen_frame_header = GF_TRUE;
    4080             :                 }
    4081             :         }
    4082       83699 : }
    4083             : 
    4084       63772 : static GF_Err av1_parse_frame(GF_BitStream *bs, AV1State *state, u64 obu_start, u64 obu_size)
    4085             : {
    4086       63772 :         av1_parse_frame_header(bs, state);
    4087             :         //byte alignment
    4088       63772 :         gf_bs_align(bs);
    4089       63772 :         return av1_parse_tile_group(bs, state, obu_start, obu_size);
    4090             : }
    4091             : 
    4092           0 : static void on_aom_av1_eos(void *_state)
    4093             : {
    4094             :         AV1State *state = (AV1State *)_state;
    4095           0 :         state->bs_overread = GF_TRUE;
    4096           0 : }
    4097             : 
    4098             : GF_EXPORT
    4099      126811 : GF_Err gf_av1_parse_obu(GF_BitStream *bs, ObuType *obu_type, u64 *obu_size, u32 *obu_hdr_size, AV1State *state)
    4100             : {
    4101             :         GF_Err e = GF_OK;
    4102             :         u32 hdr_size;
    4103      126811 :         u64 pos = gf_bs_get_position(bs);
    4104             : 
    4105      126811 :         if (!bs || !obu_type || !state)
    4106             :                 return GF_BAD_PARAM;
    4107             : 
    4108      126811 :         state->bs_overread = GF_FALSE;
    4109      126811 :         gf_bs_set_eos_callback(bs, on_aom_av1_eos, state);
    4110             : 
    4111      126811 :         state->obu_extension_flag = state->obu_has_size_field = 0;
    4112      126811 :         state->temporal_id = state->spatial_id = 0;
    4113      126811 :         state->frame_state.uncompressed_header_bytes = 0;
    4114      126811 :         e = gf_av1_parse_obu_header(bs, obu_type, &state->obu_extension_flag, &state->obu_has_size_field, &state->temporal_id, &state->spatial_id);
    4115      126811 :         if (e)
    4116             :                 return e;
    4117             : 
    4118      125472 :         if (state->obu_has_size_field) {
    4119      123814 :                 *obu_size = (u32)gf_av1_leb128_read(bs, NULL);
    4120             :         }
    4121             :         else {
    4122        1658 :                 if (*obu_size >= 1 + state->obu_extension_flag) {
    4123          22 :                         *obu_size = *obu_size - 1 - state->obu_extension_flag;
    4124             :                 }
    4125             :                 else {
    4126        1636 :                         GF_LOG(state->config ? GF_LOG_WARNING : GF_LOG_DEBUG, GF_LOG_CODING, ("[AV1] computed OBU size "LLD" (input value = "LLU"). Skipping.\n", *obu_size - 1 - state->obu_extension_flag, *obu_size));
    4127             :                         return GF_NON_COMPLIANT_BITSTREAM;
    4128             :                 }
    4129             :         }
    4130      123836 :         hdr_size = (u32)(gf_bs_get_position(bs) - pos);
    4131      123836 :         if ((gf_bs_available(bs) < *obu_size) || state->bs_overread) {
    4132          66 :                 gf_bs_seek(bs, pos);
    4133          66 :                 return GF_BUFFER_TOO_SMALL;
    4134             :         }
    4135      123770 :         *obu_size += hdr_size;
    4136      123770 :         if (obu_hdr_size) *obu_hdr_size = hdr_size;
    4137             : 
    4138             : 
    4139      207960 :         if (*obu_type != OBU_SEQUENCE_HEADER && *obu_type != OBU_TEMPORAL_DELIMITER &&
    4140       84190 :                 state->OperatingPointIdc != 0 && state->obu_extension_flag == 1)
    4141             :         {
    4142           0 :                 u32 inTemporalLayer = (state->OperatingPointIdc >> state->temporal_id) & 1;
    4143           0 :                 u32 inSpatialLayer = (state->OperatingPointIdc >> (state->spatial_id + 8)) & 1;
    4144           0 :                 if (!inTemporalLayer || !inSpatialLayer) {
    4145           0 :                         *obu_type = -1;
    4146           0 :                         gf_bs_seek(bs, pos + *obu_size);
    4147           0 :                         return GF_OK;
    4148             :                 }
    4149             :         }
    4150             : 
    4151             :         e = GF_OK;
    4152      123770 :         switch (*obu_type) {
    4153        1318 :         case OBU_SEQUENCE_HEADER:
    4154        1318 :                 av1_parse_sequence_header_obu(bs, state);
    4155        1318 :                 if (gf_bs_get_position(bs) > pos + *obu_size) {
    4156           0 :                         GF_LOG(GF_LOG_WARNING, GF_LOG_CODING, ("[AV1] Sequence header parsing consumed too many bytes !\n"));
    4157             :                         e = GF_NON_COMPLIANT_BITSTREAM;
    4158             :                 }
    4159        1318 :                 gf_bs_seek(bs, pos + *obu_size);
    4160        1318 :                 break;
    4161             : 
    4162           8 :         case OBU_METADATA:
    4163             : #if 0
    4164             :                 //TODO + sample groups
    4165             :                 const ObuMetadataType metadata_type = (u32)read_leb128(bs, NULL); we should check for 16 bits limit(AV1MetadataSampleGroupEntry) for ISOBMFF bindings, see https ://github.com/AOMediaCodec/av1-isobmff/pull/86#issuecomment-416659538
    4166             :                 if (metadata_type == OBU_METADATA_TYPE_ITUT_T35) {
    4167             :                 }
    4168             :                 else if (metadata_type == OBU_METADATA_TYPE_HDR_CLL) {
    4169             :                 }
    4170             :                 else if (metadata_type == OBU_METADATA_TYPE_HDR_MDCV) {
    4171             :                 }
    4172             :                 else if (metadata_type == OBU_METADATA_TYPE_SCALABILITY) {
    4173             :                 }
    4174             :                 else if (metadata_type == METADATA_TYPE_TIMECODE) {
    4175             :                 }
    4176             : #endif
    4177           8 :                 GF_LOG(GF_LOG_INFO, GF_LOG_CODING, ("[AV1] parsing for metadata is not implemented. Forwarding.\n"));
    4178             : 
    4179           8 :                 if (gf_bs_get_position(bs) > pos + *obu_size) {
    4180           0 :                         GF_LOG(GF_LOG_WARNING, GF_LOG_CODING, ("[AV1] Metadata parsing consumed too many bytes !\n"));
    4181             :                         e = GF_NON_COMPLIANT_BITSTREAM;
    4182             :                 }
    4183           8 :                 gf_bs_seek(bs, pos + *obu_size);
    4184           8 :                 break;
    4185             : 
    4186       19927 :         case OBU_FRAME_HEADER:
    4187             :         case OBU_REDUNDANT_FRAME_HEADER:
    4188       19927 :                 if (state->config) {
    4189       19927 :                         av1_parse_frame_header(bs, state);
    4190       19927 :                         if (gf_bs_get_position(bs) > pos + *obu_size) {
    4191           0 :                                 GF_LOG(GF_LOG_WARNING, GF_LOG_CODING, ("[AV1] Frame header parsing consumed too many bytes !\n"));
    4192             :                                 e = GF_NON_COMPLIANT_BITSTREAM;
    4193             :                         }
    4194             :                 }
    4195       19927 :                 gf_bs_seek(bs, pos + *obu_size);
    4196       19927 :                 break;
    4197       63772 :         case OBU_FRAME:
    4198       63772 :                 e = av1_parse_frame(bs, state, pos, *obu_size);
    4199       63772 :                 if (gf_bs_get_position(bs) != pos + *obu_size) {
    4200           0 :                         GF_LOG(GF_LOG_WARNING, GF_LOG_CODING, ("[AV1] Frame parsing did not consume the right number of bytes !\n"));
    4201             :                         e = GF_NON_COMPLIANT_BITSTREAM;
    4202             :                 }
    4203       63772 :                 gf_bs_seek(bs, pos + *obu_size);
    4204       63772 :                 break;
    4205         436 :         case OBU_TILE_GROUP:
    4206         436 :                 if (state->config) {
    4207         436 :                         e = av1_parse_tile_group(bs, state, pos, *obu_size);
    4208         436 :                         if (gf_bs_get_position(bs) != pos + *obu_size) {
    4209           0 :                                 GF_LOG(GF_LOG_WARNING, GF_LOG_CODING, ("[AV1] Tile group parsing did not consume the right number of bytes !\n"));
    4210             :                                 e = GF_NON_COMPLIANT_BITSTREAM;
    4211             :                         }
    4212             :                 }
    4213         436 :                 gf_bs_seek(bs, pos + *obu_size);
    4214         436 :                 break;
    4215       38262 :         case OBU_TEMPORAL_DELIMITER:
    4216       38262 :                 state->frame_state.seen_frame_header = GF_FALSE;
    4217       38262 :         case OBU_PADDING:
    4218       38262 :                 gf_bs_seek(bs, pos + *obu_size);
    4219       38262 :                 break;
    4220          47 :         default:
    4221          47 :                 GF_LOG(GF_LOG_WARNING, GF_LOG_CODING, ("[AV1] unknown OBU type %u (size "LLU"). Skipping.\n", *obu_type, *obu_size));
    4222          47 :                 gf_bs_seek(bs, pos + *obu_size);
    4223          47 :                 break;
    4224             :         }
    4225             :         return e;
    4226             : }
    4227             : 
    4228             : 
    4229             : GF_EXPORT
    4230        3169 : GF_Err gf_media_prores_parse_bs(GF_BitStream *bs, GF_ProResFrameInfo *prores_frame)
    4231             : {
    4232             :         u32 i, j;
    4233             :         u64 start, pos;
    4234             :         memset(prores_frame, 0, sizeof(GF_ProResFrameInfo));
    4235             : 
    4236        3169 :         start = gf_bs_get_position(bs);
    4237        3169 :         if (gf_bs_available(bs) < 10)
    4238             :                 return GF_BUFFER_TOO_SMALL;
    4239             : 
    4240        3169 :         prores_frame->frame_size = gf_bs_read_u32(bs);
    4241        3169 :         prores_frame->frame_identifier = gf_bs_read_u32(bs);
    4242        3169 :         if (prores_frame->frame_identifier != GF_4CC('i','c','p','f')) {
    4243           0 :                 GF_LOG(GF_LOG_ERROR, GF_LOG_CODING, ("[ProRes] Invalid frame identifier, expected \"icpf\" got \"%s\"\n", gf_4cc_to_str(prores_frame->frame_identifier) ));
    4244           0 :                 gf_bs_seek(bs, start);
    4245           0 :                 return GF_NON_COMPLIANT_BITSTREAM;
    4246             :         }
    4247             :         /*parse frame header*/
    4248        3169 :         pos = gf_bs_get_position(bs);
    4249        3169 :         prores_frame->frame_hdr_size = gf_bs_read_u16(bs);
    4250        3169 :         if (gf_bs_available(bs) + 2 < prores_frame->frame_hdr_size) {
    4251           3 :                 gf_bs_seek(bs, start);
    4252           3 :                 return GF_BUFFER_TOO_SMALL;
    4253             :         }
    4254        3166 :         gf_bs_read_u8(bs);
    4255        3166 :         prores_frame->version = gf_bs_read_u8(bs);
    4256        3166 :         prores_frame->encoder_id = gf_bs_read_u32(bs);
    4257        3166 :         prores_frame->width = gf_bs_read_u16(bs);
    4258        3166 :         prores_frame->height = gf_bs_read_u16(bs);
    4259        3166 :         prores_frame->chroma_format = gf_bs_read_int(bs, 2);
    4260        3166 :         gf_bs_read_int(bs, 2);
    4261        3166 :         prores_frame->interlaced_mode = gf_bs_read_int(bs, 2);
    4262        3166 :         gf_bs_read_int(bs, 2);
    4263        3166 :         prores_frame->aspect_ratio_information = gf_bs_read_int(bs, 4);
    4264        3166 :         prores_frame->framerate_code = gf_bs_read_int(bs, 4);
    4265        3166 :         prores_frame->color_primaries = gf_bs_read_u8(bs);
    4266        3166 :         prores_frame->transfer_characteristics = gf_bs_read_u8(bs);
    4267        3166 :         prores_frame->matrix_coefficients = gf_bs_read_u8(bs);
    4268        3166 :         gf_bs_read_int(bs, 4);
    4269        3166 :         prores_frame->alpha_channel_type = gf_bs_read_int(bs, 4);
    4270        3166 :         gf_bs_read_int(bs, 14);
    4271        3166 :         prores_frame->load_luma_quant_matrix = gf_bs_read_int(bs, 1);
    4272        3166 :         prores_frame->load_chroma_quant_matrix = gf_bs_read_int(bs, 1);
    4273        3166 :         if (prores_frame->load_luma_quant_matrix) {
    4274       25328 :                 for (i=0; i<8; i++) {
    4275      202624 :                         for (j=0; j<8; j++) {
    4276      202624 :                                 prores_frame->luma_quant_matrix[i][j] = gf_bs_read_u8(bs);
    4277             :                         }
    4278             :                 }
    4279             :         }
    4280        3166 :         if (prores_frame->load_chroma_quant_matrix) {
    4281       25328 :                 for (i=0; i<8; i++) {
    4282      202624 :                         for (j=0; j<8; j++) {
    4283      202624 :                                 prores_frame->chroma_quant_matrix[i][j] = gf_bs_read_u8(bs);
    4284             :                         }
    4285             :                 }
    4286             :         }
    4287        3166 :         pos = gf_bs_get_position(bs) - pos;
    4288        3166 :         if (pos != prores_frame->frame_hdr_size) {
    4289           0 :                 GF_LOG(GF_LOG_ERROR, GF_LOG_CODING, ("[ProRes] Invalid frame header size, expected %d got %d\n", prores_frame->frame_hdr_size, (u32) pos));
    4290           0 :                 gf_bs_seek(bs, start);
    4291           0 :                 return GF_NON_COMPLIANT_BITSTREAM;
    4292             :         }
    4293        3166 :         prores_frame->nb_pic = ((prores_frame->interlaced_mode==1) || (prores_frame->interlaced_mode==2)) ? 2 : 1;
    4294        3166 :         gf_bs_seek(bs, start);
    4295             : 
    4296        3166 :         return GF_OK;
    4297             : }
    4298             : 
    4299             : #endif /*GPAC_DISABLE_AV_PARSERS*/
    4300             : 
    4301             : GF_EXPORT
    4302      366871 : u8 gf_mp3_version(u32 hdr)
    4303             : {
    4304      366871 :         return ((hdr >> 19) & 0x3);
    4305             : }
    4306             : 
    4307             : GF_EXPORT
    4308           1 : const char *gf_mp3_version_name(u32 hdr)
    4309             : {
    4310           1 :         u32 v = gf_mp3_version(hdr);
    4311           1 :         switch (v) {
    4312             :         case 0:
    4313             :                 return "MPEG-2.5";
    4314           0 :         case 1:
    4315           0 :                 return "Reserved";
    4316           0 :         case 2:
    4317           0 :                 return "MPEG-2";
    4318           0 :         case 3:
    4319           0 :                 return "MPEG-1";
    4320           0 :         default:
    4321           0 :                 return "Unknown";
    4322             :         }
    4323             : }
    4324             : 
    4325             : #ifndef GPAC_DISABLE_AV_PARSERS
    4326             : 
    4327             : GF_EXPORT
    4328      225933 : u8 gf_mp3_layer(u32 hdr)
    4329             : {
    4330      225933 :         return 4 - (((hdr >> 17) & 0x3));
    4331             : }
    4332             : 
    4333             : GF_EXPORT
    4334       25282 : u8 gf_mp3_num_channels(u32 hdr)
    4335             : {
    4336       25282 :         if (((hdr >> 6) & 0x3) == 3) return 1;
    4337       20975 :         return 2;
    4338             : }
    4339             : 
    4340             : GF_EXPORT
    4341      116697 : u16 gf_mp3_sampling_rate(u32 hdr)
    4342             : {
    4343             :         u16 res;
    4344             :         /* extract the necessary fields from the MP3 header */
    4345      116697 :         u8 version = gf_mp3_version(hdr);
    4346      116697 :         u8 sampleRateIndex = (hdr >> 10) & 0x3;
    4347             : 
    4348      116697 :         switch (sampleRateIndex) {
    4349             :         case 0:
    4350             :                 res = 44100;
    4351             :                 break;
    4352       23405 :         case 1:
    4353             :                 res = 48000;
    4354       23405 :                 break;
    4355        1104 :         case 2:
    4356             :                 res = 32000;
    4357        1104 :                 break;
    4358           0 :         default:
    4359           0 :                 GF_LOG(GF_LOG_ERROR, GF_LOG_CODING, ("[MPEG-1/2 Audio] Samplerate index not valid\n"));
    4360             :                 return 0;
    4361             :         }
    4362             :         /*reserved or MPEG-1*/
    4363      116697 :         if (version & 1) return res;
    4364             : 
    4365             :         /*MPEG-2*/
    4366       62459 :         res /= 2;
    4367             :         /*MPEG-2.5*/
    4368       62459 :         if (version == 0) res /= 2;
    4369             :         return res;
    4370             : }
    4371             : 
    4372             : GF_EXPORT
    4373       56244 : u16 gf_mp3_window_size(u32 hdr)
    4374             : {
    4375       56244 :         u8 version = gf_mp3_version(hdr);
    4376       56244 :         u8 layer = gf_mp3_layer(hdr);
    4377             : 
    4378       56244 :         if (layer == 3) {
    4379       36968 :                 if (version == 3) return 1152;
    4380       36034 :                 return 576;
    4381             :         }
    4382       19276 :         if (layer == 2) return 1152;
    4383           1 :         return 384;
    4384             : }
    4385             : 
    4386             : GF_EXPORT
    4387       23431 : u8 gf_mp3_object_type_indication(u32 hdr)
    4388             : {
    4389       23431 :         switch (gf_mp3_version(hdr)) {
    4390             :         case 3:
    4391             :                 return GF_CODECID_MPEG_AUDIO;
    4392       13468 :         case 2:
    4393             :         case 0:
    4394       13468 :                 return GF_CODECID_MPEG2_PART3;
    4395           0 :         default:
    4396           0 :                 return 0x00;
    4397             :         }
    4398             : }
    4399             : 
    4400             : /*aligned bitrate parsing with libMAD*/
    4401             : 
    4402             : static
    4403             : u32 const bitrate_table[5][15] = {
    4404             :         /* MPEG-1 */
    4405             :         {       0,  32000,  64000,  96000, 128000, 160000, 192000, 224000,  /* Layer I   */
    4406             :                 256000, 288000, 320000, 352000, 384000, 416000, 448000
    4407             :         },
    4408             :         {       0,  32000,  48000,  56000,  64000,  80000,  96000, 112000,  /* Layer II  */
    4409             :                 128000, 160000, 192000, 224000, 256000, 320000, 384000
    4410             :         },
    4411             :         {       0,  32000,  40000,  48000,  56000,  64000,  80000,  96000,  /* Layer III */
    4412             :                 112000, 128000, 160000, 192000, 224000, 256000, 320000
    4413             :         },
    4414             : 
    4415             :         /* MPEG-2 LSF */
    4416             :         {       0,  32000,  48000,  56000,  64000,  80000,  96000, 112000,  /* Layer I   */
    4417             :                 128000, 144000, 160000, 176000, 192000, 224000, 256000
    4418             :         },
    4419             :         {       0,   8000,  16000,  24000,  32000,  40000,  48000,  56000,  /* Layers    */
    4420             :                 64000,  80000,  96000, 112000, 128000, 144000, 160000
    4421             :         } /* II & III  */
    4422             : };
    4423             : 
    4424             : 
    4425       84102 : u32 gf_mp3_bit_rate(u32 hdr)
    4426             : {
    4427       84102 :         u8 version = gf_mp3_version(hdr);
    4428       84102 :         u8 layer = gf_mp3_layer(hdr);
    4429       84102 :         u8 bitRateIndex = (hdr >> 12) & 0xF;
    4430             :         u32 lidx;
    4431             :         /*MPEG-1*/
    4432       84102 :         if (version & 1) {
    4433       43965 :                 if (!layer) {
    4434           0 :                         GF_LOG(GF_LOG_ERROR, GF_LOG_CODING, ("[MPEG-1/2 Audio] layer index not valid\n"));
    4435             :                         return 0;
    4436             :                 }
    4437       43965 :                 lidx = layer - 1;
    4438             :         }
    4439             :         /*MPEG-2/2.5*/
    4440             :         else {
    4441       40137 :                 lidx = 3 + (layer >> 1);
    4442             :         }
    4443       84102 :         if (lidx>4) {
    4444           0 :                 GF_LOG(GF_LOG_ERROR, GF_LOG_CODING, ("[MPEG-1/2 Audio] layer index not valid\n"));
    4445             :                 return 0;
    4446             :         }
    4447       84102 :         return bitrate_table[lidx][bitRateIndex];
    4448             : }
    4449             : 
    4450             : 
    4451             : 
    4452             : GF_EXPORT
    4453       83712 : u16 gf_mp3_frame_size(u32 hdr)
    4454             : {
    4455       83712 :         u8 version = gf_mp3_version(hdr);
    4456       83712 :         u8 layer = gf_mp3_layer(hdr);
    4457       83712 :         u32 pad = ((hdr >> 9) & 0x1) ? 1 : 0;
    4458       83712 :         u32 bitrate = gf_mp3_bit_rate(hdr);
    4459       83712 :         u32 samplerate = gf_mp3_sampling_rate(hdr);
    4460             : 
    4461             :         u32 frameSize = 0;
    4462       83712 :         if (!samplerate || !bitrate) return 0;
    4463             : 
    4464       83712 :         if (layer == 1) {
    4465        2187 :                 frameSize = ((12 * bitrate / samplerate) + pad) * 4;
    4466             :         }
    4467             :         else {
    4468             :                 u32 slots_per_frame = 144;
    4469       81525 :                 if ((layer == 3) && !(version & 1)) slots_per_frame = 72;
    4470       81525 :                 frameSize = (slots_per_frame * bitrate / samplerate) + pad;
    4471             :         }
    4472       83712 :         return (u16)frameSize;
    4473             : }
    4474             : 
    4475             : 
    4476             : GF_EXPORT
    4477        9150 : u32 gf_mp3_get_next_header(FILE* in)
    4478             : {
    4479             :         u8 b, state = 0;
    4480             :         u32 dropped = 0;
    4481             :         unsigned char bytes[4];
    4482        9150 :         bytes[0] = bytes[1] = bytes[2] = bytes[3] = 0;
    4483             : 
    4484             :         while (1) {
    4485       37475 :                 if (gf_fread(&b, 1, in) == 0) return 0;
    4486             : 
    4487       37450 :                 if (state == 3) {
    4488        9125 :                         bytes[state] = b;
    4489        9125 :                         return GF_4CC((u32)bytes[0], bytes[1], bytes[2], bytes[3]);
    4490             :                 }
    4491       28325 :                 if (state == 2) {
    4492        9125 :                         if (((b & 0xF0) == 0) || ((b & 0xF0) == 0xF0) || ((b & 0x0C) == 0x0C)) {
    4493           0 :                                 if (bytes[1] == 0xFF) state = 1;
    4494             :                                 else state = 0;
    4495             :                         }
    4496             :                         else {
    4497        9125 :                                 bytes[state] = b;
    4498             :                                 state = 3;
    4499             :                         }
    4500             :                 }
    4501       19200 :                 if (state == 1) {
    4502        9125 :                         if (((b & 0xE0) == 0xE0) && ((b & 0x18) != 0x08) && ((b & 0x06) != 0)) {
    4503        9125 :                                 bytes[state] = b;
    4504             :                                 state = 2;
    4505             :                         }
    4506             :                         else {
    4507             :                                 state = 0;
    4508             :                         }
    4509             :                 }
    4510             : 
    4511       19200 :                 if (state == 0) {
    4512       10075 :                         if (b == 0xFF) {
    4513        9126 :                                 bytes[state] = b;
    4514             :                                 state = 1;
    4515             :                         }
    4516             :                         else {
    4517         949 :                                 if ((dropped == 0) && ((b & 0xE0) == 0xE0) && ((b & 0x18) != 0x08) && ((b & 0x06) != 0)) {
    4518           0 :                                         bytes[0] = (u8)0xFF;
    4519           0 :                                         bytes[1] = b;
    4520           0 :                                         state = 2;
    4521             :                                 }
    4522             :                                 else {
    4523         949 :                                         dropped++;
    4524             :                                 }
    4525             :                         }
    4526             :                 }
    4527             :         }
    4528             :         return 0;
    4529             : }
    4530             : 
    4531             : GF_EXPORT
    4532       39203 : u32 gf_mp3_get_next_header_mem(const u8 *buffer, u32 size, u32 *pos)
    4533             : {
    4534             :         u32 cur;
    4535             :         u8 b, state = 0;
    4536             :         u32 dropped = 0;
    4537             :         unsigned char bytes[4];
    4538       39203 :         bytes[0] = bytes[1] = bytes[2] = bytes[3] = 0;
    4539             : 
    4540             :         cur = 0;
    4541       39203 :         *pos = 0;
    4542     8876897 :         while (cur < size) {
    4543     8835497 :                 b = (u8)buffer[cur];
    4544     8835497 :                 cur++;
    4545             : 
    4546     8835497 :                 if (state == 3) {
    4547             :                         u32 val;
    4548       37006 :                         bytes[state] = b;
    4549       37006 :                         val = GF_4CC((u32)bytes[0], bytes[1], bytes[2], bytes[3]);
    4550       37006 :                         if (gf_mp3_frame_size(val)) {
    4551       37006 :                                 *pos = dropped;
    4552       37006 :                                 return val;
    4553             :                         }
    4554             :                         state = 0;
    4555             :                         dropped = cur;
    4556             :                 }
    4557     8798491 :                 if (state == 2) {
    4558      100088 :                         if (((b & 0xF0) == 0) || ((b & 0xF0) == 0xF0) || ((b & 0x0C) == 0x0C)) {
    4559       63082 :                                 if (bytes[1] == 0xFF) {
    4560             :                                         state = 1;
    4561       54197 :                                         dropped += 1;
    4562             :                                 }
    4563             :                                 else {
    4564             :                                         state = 0;
    4565             :                                         dropped = cur;
    4566             :                                 }
    4567             :                         }
    4568             :                         else {
    4569       37006 :                                 bytes[state] = b;
    4570             :                                 state = 3;
    4571             :                         }
    4572             :                 }
    4573     8698403 :                 if (state == 1) {
    4574      211155 :                         if (((b & 0xE0) == 0xE0) && ((b & 0x18) != 0x08) && ((b & 0x06) != 0)) {
    4575      100098 :                                 bytes[state] = b;
    4576             :                                 state = 2;
    4577             :                         }
    4578             :                         else {
    4579             :                                 state = 0;
    4580             :                                 dropped = cur;
    4581             :                         }
    4582             :                 }
    4583             : 
    4584     8587336 :                 if (state == 0) {
    4585     8661387 :                         if (b == 0xFF) {
    4586      156980 :                                 bytes[state] = b;
    4587             :                                 state = 1;
    4588             :                         }
    4589             :                         else {
    4590     8504407 :                                 dropped++;
    4591             :                         }
    4592             :                 }
    4593             :         }
    4594             :         return 0;
    4595             : }
    4596             : 
    4597             : #endif /*GPAC_DISABLE_AV_PARSERS*/
    4598             : 
    4599             : 
    4600             : GF_EXPORT
    4601        7821 : Bool gf_avc_is_rext_profile(u8 profile_idc)
    4602             : {
    4603        7821 :         switch (profile_idc) {
    4604             :         case 100:
    4605             :         case 110:
    4606             :         case 122:
    4607             :         case 244:
    4608             :         case 44:
    4609             :         case 83:
    4610             :         case 86:
    4611             :         case 118:
    4612             :         case 128:
    4613             :         case 138:
    4614             :         case 139:
    4615             :         case 134:
    4616             :         case 135:
    4617             :                 return GF_TRUE;
    4618        2981 :         default:
    4619        2981 :                 return GF_FALSE;
    4620             :         }
    4621             : }
    4622             : 
    4623             : GF_EXPORT
    4624          28 : const char *gf_avc_get_profile_name(u8 video_prof)
    4625             : {
    4626          28 :         switch (video_prof) {
    4627             :         case 0x42:
    4628             :                 return "Baseline";
    4629           1 :         case 0x4D:
    4630           1 :                 return "Main";
    4631           0 :         case 0x53:
    4632           0 :                 return "Scalable Baseline";
    4633           1 :         case 0x56:
    4634           1 :                 return "Scalable High";
    4635           0 :         case 0x58:
    4636           0 :                 return "Extended";
    4637          24 :         case 0x64:
    4638          24 :                 return "High";
    4639           0 :         case 0x6E:
    4640           0 :                 return "High 10";
    4641           0 :         case 0x7A:
    4642           0 :                 return "High 4:2:2";
    4643           0 :         case 0x90:
    4644             :         case 0xF4:
    4645           0 :                 return "High 4:4:4";
    4646           0 :         default:
    4647           0 :                 return "Unknown";
    4648             :         }
    4649             : }
    4650             : 
    4651             : GF_EXPORT
    4652          16 : const char *gf_hevc_get_profile_name(u8 video_prof)
    4653             : {
    4654          16 :         switch (video_prof) {
    4655             :         case 0x01:
    4656             :                 return "Main";
    4657           0 :         case 0x02:
    4658           0 :                 return "Main 10";
    4659           0 :         case 0x03:
    4660           0 :                 return "Main Still Picture";
    4661           0 :         default:
    4662           0 :                 return "Unknown";
    4663             :         }
    4664             : }
    4665             : GF_EXPORT
    4666          75 : const char *gf_avc_hevc_get_chroma_format_name(u8 chroma_format)
    4667             : {
    4668          75 :         switch (chroma_format) {
    4669             :         case 1:
    4670             :                 return "YUV 4:2:0";
    4671           0 :         case 2:
    4672           0 :                 return "YUV 4:2:2";
    4673           0 :         case 3:
    4674           0 :                 return "YUV 4:4:4";
    4675           0 :         default:
    4676           0 :                 return "Unknown";
    4677             :         }
    4678             : }
    4679             : 
    4680             : #ifndef GPAC_DISABLE_AV_PARSERS
    4681             : 
    4682     4636618 : u32 gf_bs_read_ue_log_idx3(GF_BitStream *bs, const char *fname, s32 idx1, s32 idx2, s32 idx3)
    4683             : {
    4684             :         u32 val=0, code;
    4685             :         s32 nb_lead = -1;
    4686             :         u32 bits = 0;
    4687    12369664 :         for (code=0; !code; nb_lead++) {
    4688     7733046 :                 if (nb_lead>=32) {
    4689             :                         //gf_bs_read_int keeps returning 0 on EOS, so if no more bits available, rbsp was truncated otherwise code is broken in rbsp)
    4690             :                         //we only test once nb_lead>=32 to avoid testing at each bit read
    4691           0 :                         if (!gf_bs_available(bs)) {
    4692           0 :                                 GF_LOG(GF_LOG_ERROR, GF_LOG_CODING, ("[Core] exp-golomb read failed, not enough bits in bitstream !\n"));
    4693             :                         } else {
    4694           0 :                                 GF_LOG(GF_LOG_ERROR, GF_LOG_CODING, ("[Core] corrupted exp-golomb code, %d leading zeros, max 31 allowed !\n", nb_lead));
    4695             :                         }
    4696             :                         return 0;
    4697             :                 }
    4698             : 
    4699     7733046 :                 code = gf_bs_read_int(bs, 1);
    4700     7733046 :                 bits++;
    4701             :         }
    4702             : 
    4703     4636618 :         if (nb_lead) {
    4704     1845002 :                 val = gf_bs_read_int(bs, nb_lead);
    4705     1845002 :                 val += (1 << nb_lead) - 1;
    4706     1845002 :                 bits += nb_lead;
    4707             :         }
    4708             : 
    4709     4636618 :         if (fname) {
    4710     3791099 :                 gf_bs_log_idx(bs, bits, fname, val, idx1, idx2, idx3);
    4711             :         }
    4712             :         return val;
    4713             : }
    4714             : 
    4715             : #define gf_bs_read_ue_log_idx2(_bs, _fname, _idx1, _idx2) gf_bs_read_ue_log_idx3(_bs, _fname, (s32) _idx1, (s32) _idx2, -1)
    4716             : #define gf_bs_read_ue_log_idx(_bs, _fname, _idx) gf_bs_read_ue_log_idx3(_bs, _fname, (s32) _idx, -1, -1)
    4717             : #define gf_bs_read_ue_log(_bs, _fname) gf_bs_read_ue_log_idx3(_bs, _fname, -1, -1, -1)
    4718             : 
    4719             : 
    4720       32630 : u32 gf_bs_read_ue(GF_BitStream *bs)
    4721             : {
    4722      845519 :         return gf_bs_read_ue_log(bs, NULL);
    4723             : }
    4724             : 
    4725      812889 : s32 gf_bs_read_se(GF_BitStream *bs)
    4726             : {
    4727             :         u32 v = gf_bs_read_ue(bs);
    4728      812889 :         if ((v & 0x1) == 0) return (s32)(0 - (v >> 1));
    4729      143498 :         return (v + 1) >> 1;
    4730             : }
    4731             : 
    4732      577724 : s32 gf_bs_read_se_log_idx2(GF_BitStream *bs, const char *fname, s32 idx1, s32 idx2)
    4733             : {
    4734      577724 :         s32 res = gf_bs_read_se(bs);
    4735      577724 :         if (fname)
    4736      577724 :                 gf_bs_log_idx(bs, -1, fname, res, idx1, idx2, -1);
    4737      577724 :         return res;
    4738             : }
    4739             : #define gf_bs_read_se_log_idx(_bs, _fname, _idx) gf_bs_read_se_log_idx2(_bs, _fname, (s32) _idx, -1)
    4740             : #define gf_bs_read_se_log(_bs, _fname) gf_bs_read_se_log_idx2(_bs, _fname, -1, -1)
    4741             : 
    4742             : 
    4743             : 
    4744       70297 : void gf_bs_write_ue(GF_BitStream *bs, u32 num) {
    4745             :         s32 length = 1;
    4746       70297 :         s32 temp = ++num;
    4747             : 
    4748      177107 :         while (temp != 1) {
    4749       36513 :                 temp >>= 1;
    4750       36513 :                 length += 2;
    4751             :         }
    4752             : 
    4753       70297 :         gf_bs_write_int(bs, 0, length >> 1);
    4754       70297 :         gf_bs_write_int(bs, num, (length + 1) >> 1);
    4755       70297 : }
    4756             : 
    4757       18879 : void gf_bs_write_se(GF_BitStream *bs, s32 num)
    4758             : {
    4759             :         u32 v;
    4760       18879 :         if (num <= 0)
    4761        3007 :                 v = (-1 * num) << 1;
    4762             :         else
    4763       15872 :                 v = (num << 1) - 1;
    4764             : 
    4765       18879 :         gf_bs_write_ue(bs, v);
    4766       18879 : }
    4767             : 
    4768      251235 : u32 gf_media_nalu_is_start_code(GF_BitStream *bs)
    4769             : {
    4770             :         u8 s1, s2, s3, s4;
    4771             :         Bool is_sc = 0;
    4772      251235 :         u64 pos = gf_bs_get_position(bs);
    4773      251235 :         s1 = gf_bs_read_int(bs, 8);
    4774      251235 :         s2 = gf_bs_read_int(bs, 8);
    4775      251235 :         if (!s1 && !s2) {
    4776      251235 :                 s3 = gf_bs_read_int(bs, 8);
    4777      251235 :                 if (s3 == 0x01) is_sc = 3;
    4778      183702 :                 else if (!s3) {
    4779      183702 :                         s4 = gf_bs_read_int(bs, 8);
    4780      183702 :                         if (s4 == 0x01) is_sc = 4;
    4781             :                 }
    4782             :         }
    4783      251235 :         gf_bs_seek(bs, pos + is_sc);
    4784      251235 :         return is_sc;
    4785             : }
    4786             : 
    4787             : /*read that amount of data at each IO access rather than fetching byte by byte...*/
    4788             : #define AVC_CACHE_SIZE  4096
    4789             : 
    4790      251235 : static u32 gf_media_nalu_locate_start_code_bs(GF_BitStream *bs, Bool locate_trailing)
    4791             : {
    4792             :         u32 v, bpos, nb_cons_zeros = 0;
    4793             :         char avc_cache[AVC_CACHE_SIZE];
    4794             :         u64 end, cache_start, load_size;
    4795      251235 :         u64 start = gf_bs_get_position(bs);
    4796      251235 :         if (start < 3) return 0;
    4797             : 
    4798             :         load_size = 0;
    4799             :         bpos = 0;
    4800             :         cache_start = 0;
    4801             :         end = 0;
    4802             :         v = 0xffffffff;
    4803   137630666 :         while (!end) {
    4804             :                 /*refill cache*/
    4805   137379595 :                 if (bpos == (u32)load_size) {
    4806      264047 :                         if (!gf_bs_available(bs)) break;
    4807      263883 :                         load_size = gf_bs_available(bs);
    4808      263883 :                         if (load_size > AVC_CACHE_SIZE) load_size = AVC_CACHE_SIZE;
    4809             :                         bpos = 0;
    4810      263883 :                         cache_start = gf_bs_get_position(bs);
    4811      263883 :                         gf_bs_read_data(bs, avc_cache, (u32)load_size);
    4812             :                 }
    4813   137379431 :                 v = ( (v<<8) & 0xFFFFFF00) | ((u32) avc_cache[bpos]);
    4814   137379431 :                 bpos++;
    4815             : 
    4816   137379431 :                 if (locate_trailing) {
    4817           0 :                         if ((v & 0x000000FF) == 0) nb_cons_zeros++;
    4818             :                         else nb_cons_zeros = 0;
    4819             :                 }
    4820             : 
    4821   137379431 :                 if (v == 0x00000001) end = cache_start + bpos - 4;
    4822   137195893 :                 else if ((v & 0x00FFFFFF) == 0x00000001) end = cache_start + bpos - 3;
    4823             :         }
    4824             : 
    4825      251235 :         gf_bs_seek(bs, start);
    4826      251235 :         if (!end) end = gf_bs_get_size(bs);
    4827      251235 :         if (locate_trailing) {
    4828           0 :                 if (nb_cons_zeros >= 3)
    4829           0 :                         return (u32)(end - start - nb_cons_zeros);
    4830             :         }
    4831      251235 :         return (u32)(end - start);
    4832             : }
    4833             : 
    4834             : GF_EXPORT
    4835      251235 : u32 gf_media_nalu_next_start_code_bs(GF_BitStream *bs)
    4836             : {
    4837      251235 :         return gf_media_nalu_locate_start_code_bs(bs, 0);
    4838             : }
    4839             : 
    4840             : GF_EXPORT
    4841     1649850 : u32 gf_media_nalu_next_start_code(const u8 *data, u32 data_len, u32 *sc_size)
    4842             : {
    4843             :         u32 avail = data_len;
    4844             :         const u8 *cur = data;
    4845             : 
    4846    13664193 :         while (cur) {
    4847             :                 u32 v, bpos;
    4848    12014343 :                 u8 *next_zero = memchr(cur, 0, avail);
    4849    12014343 :                 if (!next_zero) return data_len;
    4850             : 
    4851             :                 v = 0xffffff00;
    4852    11940902 :                 bpos = (u32)(next_zero - data) + 1;
    4853             :                 while (1) {
    4854             :                         u8 cval;
    4855    16720665 :                         if (bpos == (u32)data_len)
    4856             :                                 return data_len;
    4857             : 
    4858    16718137 :                         cval = data[bpos];
    4859    16718137 :                         v = ((v << 8) & 0xFFFFFF00) | ((u32)cval);
    4860    16718137 :                         bpos++;
    4861    16718137 :                         if (v == 0x00000001) {
    4862      990566 :                                 *sc_size = 4;
    4863      990566 :                                 return bpos - 4;
    4864             :                         }
    4865    15727571 :                         else if ((v & 0x00FFFFFF) == 0x00000001) {
    4866      582247 :                                 *sc_size = 3;
    4867      582247 :                                 return bpos - 3;
    4868             :                         }
    4869    15145324 :                         if (cval)
    4870             :                                 break;
    4871             :                 }
    4872    10365561 :                 if (bpos >= data_len)
    4873             :                         break;
    4874    10364493 :                 cur = data + bpos;
    4875    10364493 :                 avail = data_len - bpos;
    4876             :         }
    4877             :         return data_len;
    4878             : }
    4879             : 
    4880      171134 : Bool gf_media_avc_slice_is_intra(AVCState *avc)
    4881             : {
    4882      171134 :         switch (avc->s_info.slice_type) {
    4883             :         case GF_AVC_TYPE_I:
    4884             :         case GF_AVC_TYPE2_I:
    4885             :         case GF_AVC_TYPE_SI:
    4886             :         case GF_AVC_TYPE2_SI:
    4887             :                 return 1;
    4888      164720 :         default:
    4889      164720 :                 return 0;
    4890             :         }
    4891             : }
    4892             : 
    4893             : #if 0 //unused
    4894             : Bool gf_media_avc_slice_is_IDR(AVCState *avc)
    4895             : {
    4896             :         if (avc->sei.recovery_point.valid)
    4897             :         {
    4898             :                 avc->sei.recovery_point.valid = 0;
    4899             :                 return 1;
    4900             :         }
    4901             :         if (avc->s_info.nal_unit_type != GF_AVC_NALU_IDR_SLICE)
    4902             :                 return 0;
    4903             :         return gf_media_avc_slice_is_intra(avc);
    4904             : }
    4905             : #endif
    4906             : 
    4907             : static const struct  {
    4908             :         u32 w, h;
    4909             : } avc_hevc_sar[] = {
    4910             :         { 0,   0 }, { 1,   1 }, { 12, 11 }, { 10, 11 },
    4911             :         { 16, 11 }, { 40, 33 }, { 24, 11 }, { 20, 11 },
    4912             :         { 32, 11 }, { 80, 33 }, { 18, 11 }, { 15, 11 },
    4913             :         { 64, 33 }, { 160,99 }, {  4,  3 }, {  3,  2 },
    4914             :         {  2,  1 }
    4915             : };
    4916             : 
    4917             : 
    4918             : /*ISO 14496-10 (N11084) E.1.2*/
    4919         173 : static void avc_parse_hrd_parameters(GF_BitStream *bs, AVC_HRD *hrd)
    4920             : {
    4921             :         int i, cpb_cnt_minus1;
    4922             : 
    4923         173 :         cpb_cnt_minus1 = gf_bs_read_ue_log(bs, "cpb_cnt_minus1");
    4924         173 :         if (cpb_cnt_minus1 > 31)
    4925           0 :                 GF_LOG(GF_LOG_WARNING, GF_LOG_CODING, ("[avc-h264] invalid cpb_cnt_minus1 value: %d (expected in [0;31])\n", cpb_cnt_minus1));
    4926         173 :         gf_bs_read_int_log(bs, 4, "bit_rate_scale");
    4927         173 :         gf_bs_read_int_log(bs, 4, "cpb_size_scale");
    4928             : 
    4929             :         /*for( SchedSelIdx = 0; SchedSelIdx <= cpb_cnt_minus1; SchedSelIdx++ ) {*/
    4930         346 :         for (i = 0; i <= cpb_cnt_minus1; i++) {
    4931         173 :                 gf_bs_read_ue_log_idx(bs, "bit_rate_value_minus1", i);
    4932         173 :                 gf_bs_read_ue_log_idx(bs, "cpb_size_value_minus1", i);
    4933         173 :                 gf_bs_read_int_log_idx(bs, 1, "cbr_flag", i);
    4934             :         }
    4935         173 :         gf_bs_read_int_log(bs, 5, "initial_cpb_removal_delay_length_minus1");
    4936         173 :         hrd->cpb_removal_delay_length_minus1 = gf_bs_read_int_log(bs, 5, "cpb_removal_delay_length_minus1");
    4937         173 :         hrd->dpb_output_delay_length_minus1 = gf_bs_read_int_log(bs, 5, "dpb_output_delay_length_minus1");
    4938         173 :         hrd->time_offset_length = gf_bs_read_int_log(bs, 5, "time_offset_length");
    4939         173 :         return;
    4940             : }
    4941             : 
    4942             : /*returns the nal_size without emulation prevention bytes*/
    4943       32336 : u32 gf_media_nalu_emulation_bytes_add_count(u8 *buffer, u32 nal_size)
    4944             : {
    4945             :         u32 i = 0, emulation_bytes_count = 0;
    4946             :         u8 num_zero = 0;
    4947             : 
    4948     6476747 :         while (i < nal_size) {
    4949             :                 /*ISO 14496-10: "Within the NAL unit, any four-byte sequence that starts with 0x000003
    4950             :                 other than the following sequences shall not occur at any byte-aligned position:
    4951             :                 \96 0x00000300
    4952             :                 \96 0x00000301
    4953             :                 \96 0x00000302
    4954             :                 \96 0x00000303"
    4955             :                 */
    4956     6412056 :                 if (num_zero == 2 && (u8)buffer[i] < 0x04) {
    4957             :                         /*emulation code found*/
    4958             :                         num_zero = 0;
    4959        3259 :                         emulation_bytes_count++;
    4960        3259 :                         if (!buffer[i])
    4961             :                                 num_zero = 1;
    4962             :                 }
    4963             :                 else {
    4964     6408797 :                         if (!buffer[i])
    4965       44933 :                                 num_zero++;
    4966             :                         else
    4967             :                                 num_zero = 0;
    4968             :                 }
    4969     6412056 :                 i++;
    4970             :         }
    4971       32336 :         return emulation_bytes_count;
    4972             : }
    4973             : 
    4974       32355 : u32 gf_media_nalu_add_emulation_bytes(const u8 *buffer_src, u8 *buffer_dst, u32 nal_size)
    4975             : {
    4976             :         u32 i = 0, emulation_bytes_count = 0;
    4977             :         u8 num_zero = 0;
    4978             : 
    4979     6476766 :         while (i < nal_size) {
    4980             :                 /*ISO 14496-10: "Within the NAL unit, any four-byte sequence that starts with 0x000003
    4981             :                 other than the following sequences shall not occur at any byte-aligned position:
    4982             :                 0x00000300
    4983             :                 0x00000301
    4984             :                 0x00000302
    4985             :                 0x00000303"
    4986             :                 */
    4987     6412056 :                 if (num_zero == 2 && (u8)buffer_src[i] < 0x04) {
    4988             :                         /*add emulation code*/
    4989             :                         num_zero = 0;
    4990        3259 :                         buffer_dst[i + emulation_bytes_count] = 0x03;
    4991        3259 :                         emulation_bytes_count++;
    4992        3259 :                         if (!buffer_src[i])
    4993             :                                 num_zero = 1;
    4994             :                 }
    4995             :                 else {
    4996     6408797 :                         if (!buffer_src[i])
    4997       44933 :                                 num_zero++;
    4998             :                         else
    4999             :                                 num_zero = 0;
    5000             :                 }
    5001     6412056 :                 buffer_dst[i + emulation_bytes_count] = buffer_src[i];
    5002     6412056 :                 i++;
    5003             :         }
    5004       32355 :         return nal_size + emulation_bytes_count;
    5005             : }
    5006             : 
    5007             : /*returns the nal_size without emulation prevention bytes*/
    5008          11 : u32 gf_media_nalu_emulation_bytes_remove_count(const u8 *buffer, u32 nal_size)
    5009             : {
    5010             :         u32 i = 0, emulation_bytes_count = 0;
    5011             :         u8 num_zero = 0;
    5012          11 :         if (!buffer || !nal_size) return 0;
    5013             : 
    5014         253 :         while (i < nal_size)
    5015             :         {
    5016             :                 /*ISO 14496-10: "Within the NAL unit, any four-byte sequence that starts with 0x000003
    5017             :                   other than the following sequences shall not occur at any byte-aligned position:
    5018             :                   \96 0x00000300
    5019             :                   \96 0x00000301
    5020             :                   \96 0x00000302
    5021             :                   \96 0x00000303"
    5022             :                 */
    5023         242 :                 if (num_zero == 2
    5024          44 :                         && buffer[i] == 0x03
    5025          33 :                         && i + 1 < nal_size /*next byte is readable*/
    5026          33 :                         && (u8)buffer[i + 1] < 0x04)
    5027             :                 {
    5028             :                         /*emulation code found*/
    5029             :                         num_zero = 0;
    5030          33 :                         emulation_bytes_count++;
    5031             :                         i++;
    5032             :                 }
    5033             : 
    5034         242 :                 if (!buffer[i])
    5035         110 :                         num_zero++;
    5036             :                 else
    5037             :                         num_zero = 0;
    5038             : 
    5039         242 :                 i++;
    5040             :         }
    5041             : 
    5042             :         return emulation_bytes_count;
    5043             : }
    5044             : 
    5045             : /*nal_size is updated to allow better error detection*/
    5046             : GF_EXPORT
    5047       32274 : u32 gf_media_nalu_remove_emulation_bytes(const u8 *buffer_src, u8 *buffer_dst, u32 nal_size)
    5048             : {
    5049             :         u32 i = 0, emulation_bytes_count = 0;
    5050             :         u8 num_zero = 0;
    5051             : 
    5052     6473128 :         while (i < nal_size)
    5053             :         {
    5054             :                 /*ISO 14496-10: "Within the NAL unit, any four-byte sequence that starts with 0x000003
    5055             :                   other than the following sequences shall not occur at any byte-aligned position:
    5056             :                   0x00000300
    5057             :                   0x00000301
    5058             :                   0x00000302
    5059             :                   0x00000303"
    5060             :                 */
    5061     6408580 :                 if (num_zero == 2
    5062        5311 :                         && buffer_src[i] == 0x03
    5063        3060 :                         && i + 1 < nal_size /*next byte is readable*/
    5064        3060 :                         && (u8)buffer_src[i + 1] < 0x04)
    5065             :                 {
    5066             :                         /*emulation code found*/
    5067             :                         num_zero = 0;
    5068        3060 :                         emulation_bytes_count++;
    5069             :                         i++;
    5070             :                 }
    5071             : 
    5072     6408580 :                 buffer_dst[i - emulation_bytes_count] = buffer_src[i];
    5073             : 
    5074     6408580 :                 if (!buffer_src[i])
    5075       46717 :                         num_zero++;
    5076             :                 else
    5077             :                         num_zero = 0;
    5078             : 
    5079     6408580 :                 i++;
    5080             :         }
    5081             : 
    5082       32274 :         return nal_size - emulation_bytes_count;
    5083             : }
    5084             : 
    5085        4735 : static s32 gf_avc_read_sps_bs_internal(GF_BitStream *bs, AVCState *avc, u32 subseq_sps, u32 *vui_flag_pos, u32 nal_hdr)
    5086             : {
    5087             :         AVC_SPS *sps;
    5088             :         s32 mb_width, mb_height, sps_id = -1;
    5089             :         u32 profile_idc, level_idc, pcomp, i, chroma_format_idc, cl = 0, cr = 0, ct = 0, cb = 0, luma_bd, chroma_bd;
    5090             :         u8 separate_colour_plane_flag = 0;
    5091             : 
    5092        4735 :         if (!vui_flag_pos) {
    5093        4730 :                 gf_bs_enable_emulation_byte_removal(bs, GF_TRUE);
    5094             :         }
    5095             : 
    5096        4735 :         if (!bs) {
    5097             :                 return -1;
    5098             :         }
    5099             : 
    5100        4735 :         if (!nal_hdr) {
    5101        1414 :                 gf_bs_read_int_log(bs, 1, "forbidden_zero_bit");
    5102        1414 :                 gf_bs_read_int_log(bs, 2, "nal_ref_idc");
    5103        1414 :                 gf_bs_read_int_log(bs, 5, "nal_unit_type");
    5104             :         }
    5105             :         profile_idc = gf_bs_read_int_log(bs, 8, "profile_idc");
    5106             : 
    5107             :         pcomp = gf_bs_read_int_log(bs, 8, "profile_compatibility");
    5108             :         /*sanity checks*/
    5109        4735 :         if (pcomp & 0x3)
    5110             :                 return -1;
    5111             : 
    5112             :         level_idc = gf_bs_read_int_log(bs, 8, "level_idc");
    5113             : 
    5114             :         /*SubsetSps is used to be sure that AVC SPS are not going to be scratched
    5115             :         by subset SPS. According to the SVC standard, subset SPS can have the same sps_id
    5116             :         than its base layer, but it does not refer to the same SPS. */
    5117        4734 :         sps_id = gf_bs_read_ue_log(bs, "sps_id") + GF_SVC_SSPS_ID_SHIFT * subseq_sps;
    5118        4734 :         if ((sps_id < 0) || (sps_id >= 32)) {
    5119             :                 return -1;
    5120             :         }
    5121             : 
    5122             :         luma_bd = chroma_bd = 0;
    5123             :         sps = &avc->sps[sps_id];
    5124        4734 :         chroma_format_idc = sps->ChromaArrayType = 1;
    5125        4734 :         sps->state |= subseq_sps ? AVC_SUBSPS_PARSED : AVC_SPS_PARSED;
    5126             : 
    5127             :         /*High Profile and SVC*/
    5128        4734 :         switch (profile_idc) {
    5129         787 :         case 100:
    5130             :         case 110:
    5131             :         case 122:
    5132             :         case 244:
    5133             :         case 44:
    5134             :                 /*sanity checks: note1 from 7.4.2.1.1 of iso/iec 14496-10-N11084*/
    5135         787 :                 if (pcomp & 0xE0)
    5136             :                         return -1;
    5137             :         case 83:
    5138             :         case 86:
    5139             :         case 118:
    5140             :         case 128:
    5141         846 :                 chroma_format_idc = gf_bs_read_ue_log(bs, "chroma_format_idc");
    5142         846 :                 sps->ChromaArrayType = chroma_format_idc;
    5143         846 :                 if (chroma_format_idc == 3) {
    5144           2 :                         separate_colour_plane_flag = gf_bs_read_int_log(bs, 1, "separate_colour_plane_flag");
    5145             :                         /*
    5146             :                         Depending on the value of separate_colour_plane_flag, the value of the variable ChromaArrayType is assigned as follows.
    5147             :                         \96     If separate_colour_plane_flag is equal to 0, ChromaArrayType is set equal to chroma_format_idc.
    5148             :                         \96     Otherwise (separate_colour_plane_flag is equal to 1), ChromaArrayType is set equal to 0.
    5149             :                         */
    5150           2 :                         if (separate_colour_plane_flag) sps->ChromaArrayType = 0;
    5151             :                 }
    5152         846 :                 luma_bd = gf_bs_read_ue_log(bs, "luma_bit_depth");
    5153         846 :                 chroma_bd = gf_bs_read_ue_log(bs, "chroma_bit_depth");
    5154         846 :                 /*qpprime_y_zero_transform_bypass_flag = */ gf_bs_read_int_log(bs, 1, "qpprime_y_zero_transform_bypass_flag");
    5155             :                 /*seq_scaling_matrix_present_flag*/
    5156         846 :                 if (gf_bs_read_int_log(bs, 1, "seq_scaling_matrix_present_flag")) {
    5157             :                         u32 k;
    5158           0 :                         for (k = 0; k < 8; k++) {
    5159           0 :                                 if (gf_bs_read_int_log_idx(bs, 1, "seq_scaling_list_present_flag", k)) {
    5160             :                                         u32 z, last = 8, next = 8;
    5161           0 :                                         u32 sl = k < 6 ? 16 : 64;
    5162           0 :                                         for (z = 0; z < sl; z++) {
    5163           0 :                                                 if (next) {
    5164           0 :                                                         s32 delta = gf_bs_read_se(bs);
    5165           0 :                                                         next = (last + delta + 256) % 256;
    5166             :                                                 }
    5167           0 :                                                 last = next ? next : last;
    5168             :                                         }
    5169             :                                 }
    5170             :                         }
    5171             :                 }
    5172             :                 break;
    5173             :         }
    5174             : 
    5175        4734 :         sps->profile_idc = profile_idc;
    5176        4734 :         sps->level_idc = level_idc;
    5177        4734 :         sps->prof_compat = pcomp;
    5178        4734 :         sps->log2_max_frame_num = gf_bs_read_ue_log(bs, "log2_max_frame_num") + 4;
    5179        4734 :         sps->poc_type = gf_bs_read_ue_log(bs, "poc_type");
    5180        4734 :         sps->chroma_format = chroma_format_idc;
    5181        4734 :         sps->luma_bit_depth_m8 = luma_bd;
    5182        4734 :         sps->chroma_bit_depth_m8 = chroma_bd;
    5183             : 
    5184        4734 :         if (sps->poc_type == 0) {
    5185         936 :                 sps->log2_max_poc_lsb = gf_bs_read_ue_log(bs, "log2_max_poc_lsb") + 4;
    5186             :         }
    5187        3798 :         else if (sps->poc_type == 1) {
    5188           0 :                 sps->delta_pic_order_always_zero_flag = gf_bs_read_int_log(bs, 1, "delta_pic_order_always_zero_flag");
    5189           0 :                 sps->offset_for_non_ref_pic = gf_bs_read_se_log(bs, "offset_for_non_ref_pic");
    5190           0 :                 sps->offset_for_top_to_bottom_field = gf_bs_read_se_log(bs, "offset_for_top_to_bottom_field");
    5191           0 :                 sps->poc_cycle_length = gf_bs_read_ue_log(bs, "poc_cycle_length");
    5192           0 :                 if (sps->poc_cycle_length > GF_ARRAY_LENGTH(sps->offset_for_ref_frame)) {
    5193           0 :                         GF_LOG(GF_LOG_ERROR, GF_LOG_CODING, ("[avc-h264] offset_for_ref_frame overflow from poc_cycle_length\n"));
    5194             :                         return -1;
    5195             :                 }
    5196           0 :                 for (i = 0; i < sps->poc_cycle_length; i++)
    5197           0 :                         sps->offset_for_ref_frame[i] = gf_bs_read_se_log_idx(bs, "offset_for_ref_frame", i);
    5198             :         }
    5199        4734 :         if (sps->poc_type > 2) {
    5200             :                 return -1;
    5201             :         }
    5202        4734 :         sps->max_num_ref_frames = gf_bs_read_ue_log(bs, "max_num_ref_frames");
    5203        4734 :         sps->gaps_in_frame_num_value_allowed_flag = gf_bs_read_int_log(bs, 1, "gaps_in_frame_num_value_allowed_flag");
    5204        4734 :         mb_width = gf_bs_read_ue_log(bs, "pic_width_in_mbs_minus1") + 1;
    5205        4734 :         mb_height = gf_bs_read_ue_log(bs, "pic_height_in_map_units_minus1") + 1;
    5206             : 
    5207        4734 :         sps->frame_mbs_only_flag = gf_bs_read_int_log(bs, 1, "frame_mbs_only_flag");
    5208             : 
    5209        4734 :         sps->width = mb_width * 16;
    5210        4734 :         sps->height = (2 - sps->frame_mbs_only_flag) * mb_height * 16;
    5211             : 
    5212        4754 :         if (!sps->frame_mbs_only_flag) sps->mb_adaptive_frame_field_flag = gf_bs_read_int_log(bs, 1, "mb_adaptive_frame_field_flag");
    5213        4734 :         gf_bs_read_int_log(bs, 1, "direct_8x8_inference_flag");
    5214             : 
    5215        4734 :         if (gf_bs_read_int_log(bs, 1, "frame_cropping_flag")) {
    5216             :                 int CropUnitX, CropUnitY, SubWidthC = -1, SubHeightC = -1;
    5217             : 
    5218        2101 :                 if (chroma_format_idc == 1) {
    5219             :                         SubWidthC = 2; SubHeightC = 2;
    5220             :                 }
    5221           4 :                 else if (chroma_format_idc == 2) {
    5222             :                         SubWidthC = 2; SubHeightC = 1;
    5223             :                 }
    5224           2 :                 else if ((chroma_format_idc == 3) && (separate_colour_plane_flag == 0)) {
    5225             :                         SubWidthC = 1; SubHeightC = 1;
    5226             :                 }
    5227             : 
    5228        2101 :                 if (sps->ChromaArrayType == 0) {
    5229             :                         assert(SubWidthC == -1);
    5230             :                         CropUnitX = 1;
    5231           0 :                         CropUnitY = 2 - sps->frame_mbs_only_flag;
    5232             :                 }
    5233             :                 else {
    5234             :                         CropUnitX = SubWidthC;
    5235        2101 :                         CropUnitY = SubHeightC * (2 - sps->frame_mbs_only_flag);
    5236             :                 }
    5237             : 
    5238        2101 :                 cl = gf_bs_read_ue_log(bs, "frame_crop_left_offset");
    5239        2101 :                 cr = gf_bs_read_ue_log(bs, "frame_crop_right_offset");
    5240        2101 :                 ct = gf_bs_read_ue_log(bs, "frame_crop_top_offset");
    5241        2101 :                 cb = gf_bs_read_ue_log(bs, "frame_crop_bottom_offset");
    5242             : 
    5243        2101 :                 sps->width -= CropUnitX * (cl + cr);
    5244        2101 :                 sps->height -= CropUnitY * (ct + cb);
    5245        2101 :                 cl *= CropUnitX;
    5246        2101 :                 cr *= CropUnitX;
    5247        2101 :                 ct *= CropUnitY;
    5248        2101 :                 cb *= CropUnitY;
    5249             :         }
    5250        4734 :         sps->crop.left = cl;
    5251        4734 :         sps->crop.right = cr;
    5252        4734 :         sps->crop.top = ct;
    5253        4734 :         sps->crop.bottom = cb;
    5254             : 
    5255        4734 :         if (vui_flag_pos) {
    5256           5 :                 *vui_flag_pos = (u32)gf_bs_get_bit_offset(bs);
    5257             :         }
    5258             :         /*vui_parameters_present_flag*/
    5259        4734 :         sps->vui_parameters_present_flag = gf_bs_read_int_log(bs, 1, "vui_parameters_present_flag");
    5260        4734 :         if (sps->vui_parameters_present_flag) {
    5261        4656 :                 sps->vui.aspect_ratio_info_present_flag = gf_bs_read_int_log(bs, 1, "aspect_ratio_info_present_flag");
    5262        4656 :                 if (sps->vui.aspect_ratio_info_present_flag) {
    5263         263 :                         s32 aspect_ratio_idc = gf_bs_read_int_log(bs, 8, "aspect_ratio_idc");
    5264         263 :                         if (aspect_ratio_idc == 255) {
    5265           6 :                                 sps->vui.par_num = gf_bs_read_int_log(bs, 16, "aspect_ratio_num");
    5266           6 :                                 sps->vui.par_den = gf_bs_read_int_log(bs, 16, "aspect_ratio_den");
    5267             :                         }
    5268         257 :                         else if (aspect_ratio_idc < GF_ARRAY_LENGTH(avc_hevc_sar) ) {
    5269         257 :                                 sps->vui.par_num = avc_hevc_sar[aspect_ratio_idc].w;
    5270         257 :                                 sps->vui.par_den = avc_hevc_sar[aspect_ratio_idc].h;
    5271             :                         }
    5272             :                         else {
    5273           0 :                                 GF_LOG(GF_LOG_WARNING, GF_LOG_CODING, ("[avc-h264] Unknown aspect_ratio_idc: your video may have a wrong aspect ratio. Contact the GPAC team!\n"));
    5274             :                         }
    5275             :                 }
    5276        4656 :                 sps->vui.overscan_info_present_flag = gf_bs_read_int_log(bs, 1, "overscan_info_present_flag");
    5277        4656 :                 if (sps->vui.overscan_info_present_flag)
    5278          72 :                         gf_bs_read_int_log(bs, 1, "overscan_appropriate_flag");
    5279             : 
    5280             :                 /* default values */
    5281        4656 :                 sps->vui.video_format = 5;
    5282        4656 :                 sps->vui.colour_primaries = 2;
    5283        4656 :                 sps->vui.transfer_characteristics = 2;
    5284        4656 :                 sps->vui.matrix_coefficients = 2;
    5285             :                 /* now read values if possible */
    5286        4656 :                 sps->vui.video_signal_type_present_flag = gf_bs_read_int_log(bs, 1, "video_signal_type_present_flag");
    5287        4656 :                 if (sps->vui.video_signal_type_present_flag) {
    5288         140 :                         sps->vui.video_format = gf_bs_read_int_log(bs, 3, "video_format");
    5289         140 :                         sps->vui.video_full_range_flag = gf_bs_read_int_log(bs, 1, "video_full_range_flag");
    5290         140 :                         sps->vui.colour_description_present_flag = gf_bs_read_int_log(bs, 1, "colour_description_present_flag");
    5291         140 :                         if (sps->vui.colour_description_present_flag) {
    5292         104 :                                 sps->vui.colour_primaries = gf_bs_read_int_log(bs, 8, "colour_primaries");
    5293         104 :                                 sps->vui.transfer_characteristics = gf_bs_read_int_log(bs, 8, "transfer_characteristics");
    5294         104 :                                 sps->vui.matrix_coefficients = gf_bs_read_int_log(bs, 8, "matrix_coefficients");
    5295             :                         }
    5296             :                 }
    5297             : 
    5298        4656 :                 if (gf_bs_read_int_log(bs, 1, "chroma_location_info_present_flag")) {
    5299          52 :                         gf_bs_read_ue_log(bs, "chroma_sample_location_type_top_field");
    5300          52 :                         gf_bs_read_ue_log(bs, "chroma_sample_location_type_bottom_field");
    5301             :                 }
    5302             : 
    5303        4656 :                 sps->vui.timing_info_present_flag = gf_bs_read_int_log(bs, 1, "timing_info_present_flag");
    5304        4656 :                 if (sps->vui.timing_info_present_flag) {
    5305        4624 :                         sps->vui.num_units_in_tick = gf_bs_read_int_log(bs, 32, "num_units_in_tick");
    5306        4624 :                         sps->vui.time_scale = gf_bs_read_int_log(bs, 32, "time_scale");
    5307        4624 :                         sps->vui.fixed_frame_rate_flag = gf_bs_read_int_log(bs, 1, "fixed_frame_rate_flag");
    5308             :                 }
    5309             : 
    5310        4656 :                 sps->vui.nal_hrd_parameters_present_flag = gf_bs_read_int_log(bs, 1, "nal_hrd_parameters_present_flag");
    5311        4656 :                 if (sps->vui.nal_hrd_parameters_present_flag)
    5312         121 :                         avc_parse_hrd_parameters(bs, &sps->vui.hrd);
    5313             : 
    5314        4656 :                 sps->vui.vcl_hrd_parameters_present_flag = gf_bs_read_int_log(bs, 1, "vcl_hrd_parameters_present_flag");
    5315        4656 :                 if (sps->vui.vcl_hrd_parameters_present_flag)
    5316          52 :                         avc_parse_hrd_parameters(bs, &sps->vui.hrd);
    5317             : 
    5318        4656 :                 if (sps->vui.nal_hrd_parameters_present_flag || sps->vui.vcl_hrd_parameters_present_flag)
    5319         121 :                         sps->vui.low_delay_hrd_flag = gf_bs_read_int_log(bs, 1, "low_delay_hrd_flag");
    5320             : 
    5321        4656 :                 sps->vui.pic_struct_present_flag = gf_bs_read_int_log(bs, 1, "pic_struct_present_flag");
    5322             :         }
    5323             :         /*end of seq_parameter_set_data*/
    5324             : 
    5325        4734 :         if (subseq_sps) {
    5326          56 :                 if ((profile_idc == 83) || (profile_idc == 86)) {
    5327             :                         u8 extended_spatial_scalability_idc;
    5328             :                         /*parsing seq_parameter_set_svc_extension*/
    5329             : 
    5330          56 :                         gf_bs_read_int_log(bs, 1, "inter_layer_deblocking_filter_control_present_flag");
    5331          56 :                         extended_spatial_scalability_idc = gf_bs_read_int_log(bs, 2, "extended_spatial_scalability_idc");
    5332          56 :                         if (sps->ChromaArrayType == 1 || sps->ChromaArrayType == 2) {
    5333          56 :                                 gf_bs_read_int_log(bs, 1, "chroma_phase_x_plus1_flag");
    5334             :                         }
    5335          56 :                         if (sps->ChromaArrayType == 1) {
    5336          56 :                                 gf_bs_read_int_log(bs, 2, "chroma_phase_y_plus1");
    5337             :                         }
    5338          56 :                         if (extended_spatial_scalability_idc == 1) {
    5339           0 :                                 if (sps->ChromaArrayType > 0) {
    5340           0 :                                         gf_bs_read_int_log(bs, 1, "seq_ref_layer_chroma_phase_x_plus1_flag");
    5341           0 :                                         gf_bs_read_int_log(bs, 2, "seq_ref_layer_chroma_phase_y_plus1");
    5342             :                                 }
    5343           0 :                                 gf_bs_read_se_log(bs, "seq_scaled_ref_layer_left_offset");
    5344           0 :                                 gf_bs_read_se_log(bs, "seq_scaled_ref_layer_top_offset");
    5345           0 :                                 gf_bs_read_se_log(bs, "seq_scaled_ref_layer_right_offset");
    5346           0 :                                 gf_bs_read_se_log(bs, "seq_scaled_ref_layer_bottom_offset");
    5347             :                         }
    5348          56 :                         if (gf_bs_read_int_log(bs, 1, "seq_tcoeff_level_prediction_flag")) {
    5349          15 :                                 gf_bs_read_int_log(bs, 1, "adaptive_tcoeff_level_prediction_flag");
    5350             :                         }
    5351          56 :                         gf_bs_read_int_log(bs, 1, "slice_header_restriction_flag");
    5352             : 
    5353          56 :                         if (gf_bs_read_int_log(bs, 1, "svc_vui_parameters_present")) {
    5354           0 :                                 u32 vui_ext_num_entries_minus1 = gf_bs_read_ue_log(bs, "vui_ext_num_entries_minus1");
    5355             : 
    5356           0 :                                 for (i = 0; i <= vui_ext_num_entries_minus1; i++) {
    5357             :                                         u8 vui_ext_nal_hrd_parameters_present_flag, vui_ext_vcl_hrd_parameters_present_flag, vui_ext_timing_info_present_flag;
    5358           0 :                                         gf_bs_read_int_log(bs, 3, "vui_ext_dependency_id");
    5359           0 :                                         gf_bs_read_int_log(bs, 4, "vui_ext_quality_id");
    5360           0 :                                         gf_bs_read_int_log(bs, 3, "vui_ext_temporal_id");
    5361           0 :                                         vui_ext_timing_info_present_flag = gf_bs_read_int_log(bs, 1, "vui_ext_timing_info_present_flag");
    5362           0 :                                         if (vui_ext_timing_info_present_flag) {
    5363           0 :                                                 gf_bs_read_int_log(bs, 32, "vui_ext_num_units_in_tick");
    5364           0 :                                                 gf_bs_read_int_log(bs, 32, "vui_ext_time_scale");
    5365           0 :                                                 gf_bs_read_int_log(bs, 1, "vui_ext_fixed_frame_rate_flag");
    5366             :                                         }
    5367           0 :                                         vui_ext_nal_hrd_parameters_present_flag = gf_bs_read_int_log(bs, 1, "vui_ext_nal_hrd_parameters_present_flag");
    5368             :                                         if (vui_ext_nal_hrd_parameters_present_flag) {
    5369             :                                                 //hrd_parameters( )
    5370             :                                         }
    5371           0 :                                         vui_ext_vcl_hrd_parameters_present_flag = gf_bs_read_int_log(bs, 1, "vui_ext_vcl_hrd_parameters_present_flag");
    5372             :                                         if (vui_ext_vcl_hrd_parameters_present_flag) {
    5373             :                                                 //hrd_parameters( )
    5374             :                                         }
    5375           0 :                                         if (vui_ext_nal_hrd_parameters_present_flag || vui_ext_vcl_hrd_parameters_present_flag) {
    5376           0 :                                                 gf_bs_read_int_log(bs, 1, "vui_ext_low_delay_hrd_flag");
    5377             :                                         }
    5378           0 :                                         gf_bs_read_int_log(bs, 1, "vui_ext_pic_struct_present_flag");
    5379             :                                 }
    5380             :                         }
    5381             :                 }
    5382           0 :                 else if ((profile_idc == 118) || (profile_idc == 128)) {
    5383           0 :                         GF_LOG(GF_LOG_INFO, GF_LOG_CODING, ("[avc-h264] MVC parsing not implemented - skipping parsing end of Subset SPS\n"));
    5384             :                         return sps_id;
    5385             :                 }
    5386             : 
    5387          56 :                 if (gf_bs_read_int_log(bs, 1, "additional_extension2")) {
    5388           0 :                         GF_LOG(GF_LOG_WARNING, GF_LOG_CODING, ("[avc-h264] skipping parsing end of Subset SPS (additional_extension2)\n"));
    5389             :                         return sps_id;
    5390             :                 }
    5391             :         }
    5392             :         return sps_id;
    5393             : }
    5394             : 
    5395             : GF_EXPORT
    5396        1414 : s32 gf_avc_read_sps_bs(GF_BitStream *bs, AVCState *avc, u32 subseq_sps, u32 *vui_flag_pos)
    5397             : {
    5398        1414 :         return gf_avc_read_sps_bs_internal(bs, avc, subseq_sps, vui_flag_pos, 0);
    5399             : }
    5400             : 
    5401             : GF_EXPORT
    5402         318 : s32 gf_avc_read_sps(const u8 *sps_data, u32 sps_size, AVCState *avc, u32 subseq_sps, u32 *vui_flag_pos)
    5403             : {
    5404             :         s32 sps_id = -1;
    5405             :         GF_BitStream *bs;
    5406             :         char *sps_data_without_emulation_bytes = NULL;
    5407             :         u32 sps_data_without_emulation_bytes_size = 0;
    5408             : 
    5409         318 :         if (vui_flag_pos) {
    5410             :                 /*SPS still contains emulation bytes*/
    5411           5 :                 sps_data_without_emulation_bytes = gf_malloc(sps_size * sizeof(char));
    5412           5 :                 sps_data_without_emulation_bytes_size = gf_media_nalu_remove_emulation_bytes(sps_data, sps_data_without_emulation_bytes, sps_size);
    5413           5 :                 bs = gf_bs_new(sps_data_without_emulation_bytes, sps_data_without_emulation_bytes_size, GF_BITSTREAM_READ);
    5414             : 
    5415           5 :                 *vui_flag_pos = 0;
    5416             :         }
    5417             :         else {
    5418         313 :                 bs = gf_bs_new(sps_data, sps_size, GF_BITSTREAM_READ);
    5419             :         }
    5420             : 
    5421         318 :         if (!bs) {
    5422             :                 sps_id = -1;
    5423             :                 goto exit;
    5424             :         }
    5425             : 
    5426         318 :         sps_id = gf_avc_read_sps_bs(bs, avc, subseq_sps, vui_flag_pos);
    5427             : 
    5428         318 : exit:
    5429         318 :         gf_bs_del(bs);
    5430         318 :         if (sps_data_without_emulation_bytes) gf_free(sps_data_without_emulation_bytes);
    5431         318 :         return sps_id;
    5432             : }
    5433             : 
    5434        8115 : static s32 gf_avc_read_pps_bs_internal(GF_BitStream *bs, AVCState *avc, u32 nal_hdr)
    5435             : {
    5436             :         s32 pps_id;
    5437             :         AVC_PPS *pps;
    5438             : 
    5439        8115 :         gf_bs_enable_emulation_byte_removal(bs, GF_TRUE);
    5440             : 
    5441        8115 :         if (!nal_hdr) {
    5442        2077 :                 gf_bs_read_int_log(bs, 1, "forbidden_zero_bit");
    5443        2077 :                 gf_bs_read_int_log(bs, 2, "nal_ref_idc");
    5444        2077 :                 gf_bs_read_int_log(bs, 5, "nal_unit_type");
    5445             :         }
    5446        8115 :         pps_id = gf_bs_read_ue_log(bs, "pps_id");
    5447        8115 :         if ((pps_id<0) || (pps_id >= 255)) {
    5448             :                 return -1;
    5449             :         }
    5450             :         pps = &avc->pps[pps_id];
    5451        8115 :         pps->id = pps_id;
    5452             : 
    5453        8115 :         if (!pps->status) pps->status = 1;
    5454        8115 :         pps->sps_id = gf_bs_read_ue_log(bs, "sps_id");
    5455        8115 :         if ((pps->sps_id<0) || (pps->sps_id >= 32)) {
    5456           0 :                 pps->sps_id = 0;
    5457           0 :                 return -1;
    5458             :         }
    5459             :         /*sps_id may be refer to regular SPS or subseq sps, depending on the coded slice referring to the pps*/
    5460        8115 :         if (!avc->sps[pps->sps_id].state && !avc->sps[pps->sps_id + GF_SVC_SSPS_ID_SHIFT].state) {
    5461             :                 return -1;
    5462             :         }
    5463        8115 :         avc->pps_active_idx = pps->id; /*set active sps*/
    5464        8115 :         avc->sps_active_idx = pps->sps_id; /*set active sps*/
    5465        8115 :         pps->entropy_coding_mode_flag = gf_bs_read_int_log(bs, 1, "entropy_coding_mode_flag");
    5466        8115 :         pps->pic_order_present = gf_bs_read_int_log(bs, 1, "pic_order_present");
    5467        8115 :         pps->slice_group_count = gf_bs_read_ue_log(bs, "slice_group_count_minus1") + 1;
    5468        8115 :         if (pps->slice_group_count > 1) {
    5469             :                 u32 iGroup;
    5470           0 :                 pps->mb_slice_group_map_type = gf_bs_read_ue_log(bs, "mb_slice_group_map_type");
    5471           0 :                 if (pps->mb_slice_group_map_type == 0) {
    5472           0 :                         for (iGroup = 0; iGroup <= pps->slice_group_count - 1; iGroup++)
    5473           0 :                                 gf_bs_read_ue_log_idx(bs, "run_length_minus1", iGroup);
    5474             :                 }
    5475           0 :                 else if (pps->mb_slice_group_map_type == 2) {
    5476           0 :                         for (iGroup = 0; iGroup < pps->slice_group_count - 1; iGroup++) {
    5477           0 :                                 gf_bs_read_ue_log_idx(bs, "top_left", iGroup);
    5478           0 :                                 gf_bs_read_ue_log_idx(bs, "bottom_right", iGroup);
    5479             :                         }
    5480             :                 }
    5481           0 :                 else if (pps->mb_slice_group_map_type == 3 || pps->mb_slice_group_map_type == 4 || pps->mb_slice_group_map_type == 5) {
    5482           0 :                         gf_bs_read_int_log(bs, 1, "slice_group_change_direction_flag");
    5483           0 :                         gf_bs_read_ue_log(bs, "slice_group_change_rate_minus1");
    5484             :                 }
    5485           0 :                 else if (pps->mb_slice_group_map_type == 6) {
    5486             :                         u32 i;
    5487           0 :                         pps->pic_size_in_map_units_minus1 = gf_bs_read_ue_log(bs, "pic_size_in_map_units_minus1");
    5488           0 :                         for (i = 0; i <= pps->pic_size_in_map_units_minus1; i++) {
    5489           0 :                                 gf_bs_read_int_log_idx(bs, (u32)ceil(log(pps->slice_group_count) / log(2)), "slice_group_id", i);
    5490             :                         }
    5491             :                 }
    5492             :         }
    5493        8115 :         pps->num_ref_idx_l0_default_active_minus1 = gf_bs_read_ue_log(bs, "num_ref_idx_l0_default_active_minus1");
    5494        8115 :         pps->num_ref_idx_l1_default_active_minus1 = gf_bs_read_ue_log(bs, "num_ref_idx_l1_default_active_minus1");
    5495             : 
    5496             :         /*
    5497             :         if ((pps->ref_count[0] > 32) || (pps->ref_count[1] > 32)) goto exit;
    5498             :         */
    5499             : 
    5500        8115 :         pps->weighted_pred_flag = gf_bs_read_int_log(bs, 1, "weighted_pred_flag");
    5501        8115 :         gf_bs_read_int_log(bs, 2, "weighted_bipred_idc");
    5502        8115 :         gf_bs_read_se_log(bs, "init_qp_minus26");
    5503        8115 :         gf_bs_read_se_log(bs, "init_qs_minus26");
    5504        8115 :         gf_bs_read_se_log(bs, "chroma_qp_index_offset");
    5505        8115 :         pps->deblocking_filter_control_present_flag = gf_bs_read_int_log(bs, 1, "deblocking_filter_control_present_flag");
    5506        8115 :         gf_bs_read_int_log(bs, 1, "constrained_intra_pred");
    5507        8115 :         pps->redundant_pic_cnt_present = gf_bs_read_int_log(bs, 1, "redundant_pic_cnt_present");
    5508             : 
    5509        8115 :         return pps_id;
    5510             : }
    5511             : 
    5512             : GF_EXPORT
    5513        2077 : s32 gf_avc_read_pps_bs(GF_BitStream *bs, AVCState *avc)
    5514             : {
    5515        2077 :         return gf_avc_read_pps_bs_internal(bs, avc, 0);
    5516             : }
    5517             : 
    5518             : GF_EXPORT
    5519          66 : s32 gf_avc_read_pps(const u8 *pps_data, u32 pps_size, AVCState *avc)
    5520             : {
    5521             :         GF_BitStream *bs;
    5522             :         s32 pps_id;
    5523             : 
    5524             :         /*PPS still contains emulation bytes*/
    5525          66 :         bs = gf_bs_new(pps_data, pps_size, GF_BITSTREAM_READ);
    5526          66 :         if (!bs) {
    5527             :                 return -1;
    5528             :         }
    5529          66 :         gf_bs_enable_emulation_byte_removal(bs, GF_TRUE);
    5530          66 :         pps_id = gf_avc_read_pps_bs(bs, avc);
    5531          66 :         gf_bs_del(bs);
    5532          66 :         return pps_id;
    5533             : }
    5534             : 
    5535             : #if 0 //unused
    5536             : 
    5537             : s32 gf_avc_read_sps_ext(const char *spse_data, u32 spse_size)
    5538             : {
    5539             :         GF_BitStream *bs;
    5540             :         s32 sps_id;
    5541             : 
    5542             :         bs = gf_bs_new(spse_data, spse_size, GF_BITSTREAM_READ);
    5543             :         sps_id = gf_avc_read_sps_ext_bs(bs);
    5544             : 
    5545             :         gf_bs_del(bs);
    5546             :         return sps_id;
    5547             : }
    5548             : #endif
    5549             : 
    5550        4013 : static s32 SVC_ReadNal_header_extension(GF_BitStream *bs, SVC_NALUHeader *NalHeader)
    5551             : {
    5552        4013 :         gf_bs_read_int_log(bs, 1, "reserved_one_bit");
    5553        4013 :         NalHeader->idr_pic_flag = gf_bs_read_int_log(bs, 1, "idr_flag");
    5554        4013 :         NalHeader->priority_id = gf_bs_read_int_log(bs, 6, "priority_id");
    5555        4013 :         gf_bs_read_int_log(bs, 1, "no_inter_layer_pred_flag");
    5556        4013 :         NalHeader->dependency_id = gf_bs_read_int_log(bs, 3, "DependencyId");
    5557        4013 :         NalHeader->quality_id = gf_bs_read_int_log(bs, 4, "quality_id");
    5558        4013 :         NalHeader->temporal_id = gf_bs_read_int_log(bs, 3, "temporal_id");
    5559        4013 :         gf_bs_read_int_log(bs, 1, "use_ref_base_pic_flag");
    5560        4013 :         gf_bs_read_int_log(bs, 1, "discardable_flag");
    5561        4013 :         gf_bs_read_int_log(bs, 1, "output_flag");
    5562        4013 :         gf_bs_read_int_log(bs, 2, "reserved_three_2bits");
    5563        4013 :         return 1;
    5564             : }
    5565             : 
    5566      216286 : static void ref_pic_list_modification(GF_BitStream *bs, u32 slice_type) {
    5567      216286 :         if (slice_type % 5 != 2 && slice_type % 5 != 4) {
    5568      208173 :                 if (gf_bs_read_int_log(bs, 1, "ref_pic_list_modification_flag_l0")) {
    5569             :                         u32 idx=0, modification_of_pic_nums_idc;
    5570             :                         do {
    5571      114677 :                                 modification_of_pic_nums_idc = gf_bs_read_ue_log_idx(bs, "modification_of_pic_nums_idc", idx);
    5572      114677 :                                 if (modification_of_pic_nums_idc == 0 || modification_of_pic_nums_idc == 1) {
    5573       88658 :                                         gf_bs_read_ue_log_idx(bs, "abs_diff_pic_num_minus1", idx);
    5574             :                                 }
    5575       26019 :                                 else if (modification_of_pic_nums_idc == 2) {
    5576           0 :                                         gf_bs_read_ue_log_idx(bs, "long_term_pic_num", idx);
    5577             :                                 }
    5578      114677 :                                 idx++;
    5579      114677 :                         } while ((modification_of_pic_nums_idc != 3) && gf_bs_available(bs));
    5580             :                 }
    5581             :         }
    5582      216286 :         if (slice_type % 5 == 1) {
    5583       84531 :                 if (gf_bs_read_int_log(bs, 1, "ref_pic_list_modification_flag_l1")) {
    5584             :                         u32 idx=0, modification_of_pic_nums_idc;
    5585             :                         do {
    5586        2598 :                                 modification_of_pic_nums_idc = gf_bs_read_ue_log_idx(bs, "modification_of_pic_nums_idc", idx);
    5587        2598 :                                 if (modification_of_pic_nums_idc == 0 || modification_of_pic_nums_idc == 1) {
    5588        1449 :                                         gf_bs_read_ue_log_idx(bs, "abs_diff_pic_num_minus1", idx);
    5589             :                                 }
    5590        1149 :                                 else if (modification_of_pic_nums_idc == 2) {
    5591           0 :                                         gf_bs_read_ue_log_idx(bs, "long_term_pic_num", idx);
    5592             :                                 }
    5593        2598 :                                 idx++;
    5594        2598 :                         } while ((modification_of_pic_nums_idc != 3) && gf_bs_available(bs));
    5595             :                 }
    5596             :         }
    5597      216286 : }
    5598             : 
    5599       29524 : static void pred_weight_table(GF_BitStream *bs, u32 slice_type, u32 ChromaArrayType, u32 num_ref_idx_l0_active_minus1, u32 num_ref_idx_l1_active_minus1) {
    5600             :         u32 i, j;
    5601       29524 :         gf_bs_read_ue_log(bs, "luma_log2_weight_denom");
    5602       29524 :         if (ChromaArrayType != 0) {
    5603       29524 :                 gf_bs_read_ue_log(bs, "chroma_log2_weight_denom");
    5604             :         }
    5605       91497 :         for (i = 0; i <= num_ref_idx_l0_active_minus1; i++) {
    5606      182994 :                 if (gf_bs_read_int_log_idx(bs, 1, "luma_weight_l0_flag", i)) {
    5607       13336 :                         gf_bs_read_se_log_idx(bs, "luma_weight_l0", i);
    5608       13336 :                         gf_bs_read_se_log_idx(bs, "luma_offset_l0", i);
    5609             :                 }
    5610       91497 :                 if (ChromaArrayType != 0) {
    5611       91497 :                         if (gf_bs_read_int_log_idx(bs, 1, "chroma_weight_l0_flag", i))
    5612         196 :                                 for (j = 0; j < 2; j++) {
    5613         196 :                                         gf_bs_read_se_log_idx2(bs, "chroma_weight_l0", i, j);
    5614         196 :                                         gf_bs_read_se_log_idx2(bs, "chroma_offset_l0", i, j);
    5615             :                                 }
    5616             :                 }
    5617             :         }
    5618       29524 :         if (slice_type % 5 == 1) {
    5619           0 :                 for (i = 0; i <= num_ref_idx_l1_active_minus1; i++) {
    5620           0 :                         if (gf_bs_read_int_log_idx(bs, 1, "luma_weight_l1_flag", i)) {
    5621           0 :                                 gf_bs_read_se_log_idx(bs, "luma_weight_l1", i);
    5622           0 :                                 gf_bs_read_se_log_idx(bs, "luma_offset_l1", i);
    5623             :                         }
    5624           0 :                         if (ChromaArrayType != 0) {
    5625           0 :                                 if (gf_bs_read_int_log_idx(bs, 1, "chroma_weight_l1_flag", i)) {
    5626           0 :                                         for (j = 0; j < 2; j++) {
    5627           0 :                                                 gf_bs_read_se_log_idx2(bs, "chroma_weight_l1", i, j);
    5628           0 :                                                 gf_bs_read_se_log_idx2(bs, "chroma_offset_l1", i, j);
    5629             :                                         }
    5630             :                                 }
    5631             :                         }
    5632             :                 }
    5633             :         }
    5634       29524 : }
    5635             : 
    5636      154202 : static void dec_ref_pic_marking(GF_BitStream *bs, Bool IdrPicFlag) {
    5637      154202 :         if (IdrPicFlag) {
    5638        7540 :                 gf_bs_read_int_log(bs, 1, "no_output_of_prior_pics_flag");
    5639        7540 :                 gf_bs_read_int_log(bs, 1, "long_term_reference_flag");
    5640             :         }
    5641             :         else {
    5642      146662 :                 if (gf_bs_read_int_log(bs, 1, "adaptive_ref_pic_marking_mode_flag")) {
    5643             :                         u32 idx=0, memory_management_control_operation;
    5644             :                         do {
    5645       61523 :                                 memory_management_control_operation = gf_bs_read_ue_log_idx(bs, "memory_management_control_operation", idx);
    5646       61523 :                                 if (memory_management_control_operation == 1 || memory_management_control_operation == 3)
    5647       39677 :                                         gf_bs_read_ue_log_idx(bs, "difference_of_pic_nums_minus1", idx);
    5648       61523 :                                 if (memory_management_control_operation == 2)
    5649           0 :                                         gf_bs_read_ue_log_idx(bs, "long_term_pic_num", idx);
    5650       61523 :                                 if (memory_management_control_operation == 3 || memory_management_control_operation == 6)
    5651           0 :                                         gf_bs_read_ue_log_idx(bs, "long_term_frame_idx", idx);
    5652       61523 :                                 if (memory_management_control_operation == 4)
    5653           0 :                                         gf_bs_read_ue_log_idx(bs, "max_long_term_frame_idx_plus1", idx);
    5654       61523 :                                 idx++;
    5655       61523 :                         } while (memory_management_control_operation != 0);
    5656             :                 }
    5657             :         }
    5658      154202 : }
    5659             : 
    5660      216563 : static s32 avc_parse_slice(GF_BitStream *bs, AVCState *avc, Bool svc_idr_flag, AVCSliceInfo *si)
    5661             : {
    5662             :         s32 pps_id, num_ref_idx_l0_active_minus1 = 0, num_ref_idx_l1_active_minus1 = 0;
    5663             : 
    5664             :         /*s->current_picture.reference= h->nal_ref_idc != 0;*/
    5665      216563 :         gf_bs_read_ue_log(bs, "first_mb_in_slice");
    5666      216563 :         si->slice_type = gf_bs_read_ue_log(bs, "slice_type");
    5667      216563 :         if (si->slice_type > 9) return -1;
    5668             : 
    5669      216563 :         pps_id = gf_bs_read_ue_log(bs, "pps_id");
    5670      216563 :         if (pps_id > 255) return -1;
    5671      216563 :         si->pps = &avc->pps[pps_id];
    5672      216563 :         if (!si->pps->slice_group_count) return -2;
    5673      216286 :         si->sps = &avc->sps[si->pps->sps_id];
    5674      216286 :         if (!si->sps->log2_max_frame_num) return -2;
    5675      216286 :         avc->sps_active_idx = si->pps->sps_id;
    5676      216286 :         avc->pps_active_idx = pps_id;
    5677             : 
    5678      432572 :         si->frame_num = gf_bs_read_int_log(bs, si->sps->log2_max_frame_num, "frame_num");
    5679             : 
    5680      216286 :         si->field_pic_flag = 0;
    5681      216286 :         si->bottom_field_flag = 0;
    5682      216286 :         if (!si->sps->frame_mbs_only_flag) {
    5683         506 :                 si->field_pic_flag = gf_bs_read_int_log(bs, 1, "field_pic_flag");
    5684         506 :                 if (si->field_pic_flag)
    5685         112 :                         si->bottom_field_flag = gf_bs_read_int_log(bs, 1, "bottom_field_flag");
    5686             :         }
    5687             : 
    5688      216286 :         if ((si->nal_unit_type == GF_AVC_NALU_IDR_SLICE) || svc_idr_flag)
    5689        7540 :                 si->idr_pic_id = gf_bs_read_ue_log(bs, "idr_pic_id");
    5690             : 
    5691      216286 :         if (si->sps->poc_type == 0) {
    5692      290584 :                 si->poc_lsb = gf_bs_read_int_log(bs, si->sps->log2_max_poc_lsb, "poc_lsb");
    5693      145292 :                 if (si->pps->pic_order_present && !si->field_pic_flag) {
    5694        2708 :                         si->delta_poc_bottom = gf_bs_read_se_log(bs, "poc_lsb");
    5695             :                 }
    5696             :         }
    5697       70994 :         else if ((si->sps->poc_type == 1) && !si->sps->delta_pic_order_always_zero_flag) {
    5698           0 :                 si->delta_poc[0] = gf_bs_read_se_log(bs, "delta_poc0");
    5699           0 :                 if ((si->pps->pic_order_present == 1) && !si->field_pic_flag)
    5700           0 :                         si->delta_poc[1] = gf_bs_read_se_log(bs, "delta_poc1");
    5701             :         }
    5702             : 
    5703      216286 :         if (si->pps->redundant_pic_cnt_present) {
    5704           0 :                 si->redundant_pic_cnt = gf_bs_read_ue_log(bs, "redundant_pic_cnt");
    5705             :         }
    5706             : 
    5707      216286 :         if (si->slice_type % 5 == GF_AVC_TYPE_B) {
    5708       84531 :                 gf_bs_read_int_log(bs, 1, "direct_spatial_mv_pred_flag");
    5709             :         }
    5710             : 
    5711      216286 :         num_ref_idx_l0_active_minus1 = si->pps->num_ref_idx_l0_default_active_minus1;
    5712      216286 :         num_ref_idx_l1_active_minus1 = si->pps->num_ref_idx_l1_default_active_minus1;
    5713             : 
    5714      216286 :         if (si->slice_type % 5 == GF_AVC_TYPE_P || si->slice_type % 5 == GF_AVC_TYPE_SP || si->slice_type % 5 == GF_AVC_TYPE_B) {
    5715             :                 Bool num_ref_idx_active_override_flag = gf_bs_read_int_log(bs, 1, "num_ref_idx_active_override_flag");
    5716      208173 :                 if (num_ref_idx_active_override_flag) {
    5717      113985 :                         num_ref_idx_l0_active_minus1 = gf_bs_read_ue_log(bs, "num_ref_idx_l0_active_minus1");
    5718      113985 :                         if (si->slice_type % 5 == GF_AVC_TYPE_B) {
    5719       66311 :                                 num_ref_idx_l1_active_minus1 = gf_bs_read_ue_log(bs, "num_ref_idx_l1_active_minus1");
    5720             :                         }
    5721             :                 }
    5722             :         }
    5723             : 
    5724      216286 :         if (si->nal_unit_type == 20 || si->nal_unit_type == 21) {
    5725             :                 //ref_pic_list_mvc_modification(); /* specified in Annex H */
    5726           0 :                 GF_LOG(GF_LOG_ERROR, GF_LOG_CODING, ("[avc-h264] unimplemented ref_pic_list_mvc_modification() in slide header\n"));
    5727             :                 assert(0);
    5728             :                 return -1;
    5729             :         }
    5730             :         else {
    5731      216286 :                 ref_pic_list_modification(bs, si->slice_type);
    5732             :         }
    5733             : 
    5734      216286 :         if ((si->pps->weighted_pred_flag && (si->slice_type % 5 == GF_AVC_TYPE_P || si->slice_type % 5 == GF_AVC_TYPE_SP))
    5735      186762 :                 || (si->pps->weighted_bipred_idc == 1 && si->slice_type % 5 == GF_AVC_TYPE_B)) {
    5736       29524 :                 pred_weight_table(bs, si->slice_type, si->sps->ChromaArrayType, num_ref_idx_l0_active_minus1, num_ref_idx_l1_active_minus1);
    5737             :         }
    5738             : 
    5739      216286 :         if (si->nal_ref_idc != 0) {
    5740      154202 :                 dec_ref_pic_marking(bs, (si->nal_unit_type == GF_AVC_NALU_IDR_SLICE));
    5741             :         }
    5742             : 
    5743      216286 :         if (si->pps->entropy_coding_mode_flag && si->slice_type % 5 != GF_AVC_TYPE_I && si->slice_type % 5 != GF_AVC_TYPE_SI) {
    5744      138194 :                 gf_bs_read_ue_log(bs, "cabac_init_idc");
    5745             :         }
    5746             : 
    5747      216286 :         /*slice_qp_delta = */gf_bs_read_se(bs);
    5748      216286 :         if (si->slice_type % 5 == GF_AVC_TYPE_SP || si->slice_type % 5 == GF_AVC_TYPE_SI) {
    5749           0 :                 if (si->slice_type % 5 == GF_AVC_TYPE_SP) {
    5750           0 :                         gf_bs_read_int_log(bs, 1, "sp_for_switch_flag");
    5751             :                 }
    5752           0 :                 gf_bs_read_se_log(bs, "slice_qs_delta");
    5753             :         }
    5754             : 
    5755      216286 :         if (si->pps->deblocking_filter_control_present_flag) {
    5756      214057 :                 if (gf_bs_read_ue_log(bs, "disable_deblocking_filter_idc") != 1) {
    5757      204349 :                         gf_bs_read_se_log(bs, "slice_alpha_c0_offset_div2");
    5758      204349 :                         gf_bs_read_se_log(bs, "slice_beta_offset_div2");
    5759             :                 }
    5760             :         }
    5761             : 
    5762      216286 :         if (si->pps->slice_group_count > 1 && si->pps->mb_slice_group_map_type >= 3 && si->pps->mb_slice_group_map_type <= 5) {
    5763           0 :                 gf_bs_read_int_log(bs, (u32)ceil(log1p((si->pps->pic_size_in_map_units_minus1 + 1) / (si->pps->slice_group_change_rate_minus1 + 1) ) / log(2)), "slice_group_change_cycle");
    5764             :         }
    5765             :         return 0;
    5766             : }
    5767             : 
    5768             : 
    5769        2751 : static s32 svc_parse_slice(GF_BitStream *bs, AVCState *avc, AVCSliceInfo *si)
    5770             : {
    5771             :         s32 pps_id;
    5772             : 
    5773             :         /*s->current_picture.reference= h->nal_ref_idc != 0;*/
    5774        2751 :         gf_bs_read_ue_log(bs, "first_mb_in_slice");
    5775        2751 :         si->slice_type = gf_bs_read_ue_log(bs, "slice_type");
    5776        2751 :         if (si->slice_type > 9) return -1;
    5777             : 
    5778        2751 :         pps_id = gf_bs_read_ue_log(bs, "pps_id");
    5779        2751 :         if (pps_id > 255)
    5780             :                 return -1;
    5781        2751 :         si->pps = &avc->pps[pps_id];
    5782        2751 :         si->pps->id = pps_id;
    5783        2751 :         if (!si->pps->slice_group_count)
    5784             :                 return -2;
    5785        2751 :         si->sps = &avc->sps[si->pps->sps_id + GF_SVC_SSPS_ID_SHIFT];
    5786        2751 :         if (!si->sps->log2_max_frame_num)
    5787             :                 return -2;
    5788             : 
    5789        4502 :         si->frame_num = gf_bs_read_int_log(bs, si->sps->log2_max_frame_num, "frame_num");
    5790             : 
    5791        2251 :         si->field_pic_flag = 0;
    5792        2251 :         if (si->sps->frame_mbs_only_flag) {
    5793             :                 /*s->picture_structure= PICT_FRAME;*/
    5794             :         }
    5795             :         else {
    5796           0 :                 si->field_pic_flag = gf_bs_read_int_log(bs, 1, "field_pic_flag");
    5797           0 :                 if (si->field_pic_flag) si->bottom_field_flag = gf_bs_read_int_log(bs, 1, "bottom_field_flag");
    5798             :         }
    5799        2251 :         if (si->nal_unit_type == GF_AVC_NALU_IDR_SLICE || si->NalHeader.idr_pic_flag)
    5800          47 :                 si->idr_pic_id = gf_bs_read_ue_log(bs, "idr_pic_id");
    5801             : 
    5802        2251 :         if (si->sps->poc_type == 0) {
    5803        4502 :                 si->poc_lsb = gf_bs_read_int_log(bs, si->sps->log2_max_poc_lsb, "poc_lsb");
    5804        2251 :                 if (si->pps->pic_order_present && !si->field_pic_flag) {
    5805        1244 :                         si->delta_poc_bottom = gf_bs_read_se_log(bs, "delta_poc_bottom");
    5806             :                 }
    5807             :         }
    5808           0 :         else if ((si->sps->poc_type == 1) && !si->sps->delta_pic_order_always_zero_flag) {
    5809           0 :                 si->delta_poc[0] = gf_bs_read_se_log(bs, "delta_poc0");
    5810           0 :                 if ((si->pps->pic_order_present == 1) && !si->field_pic_flag)
    5811           0 :                         si->delta_poc[1] = gf_bs_read_se_log(bs, "delta_poc1");
    5812             :         }
    5813        2251 :         if (si->pps->redundant_pic_cnt_present) {
    5814           0 :                 si->redundant_pic_cnt = gf_bs_read_ue_log(bs, "redundant_pic_cnt");
    5815             :         }
    5816             :         return 0;
    5817             : }
    5818             : 
    5819             : 
    5820         336 : static s32 avc_parse_recovery_point_sei(GF_BitStream *bs, AVCState *avc)
    5821             : {
    5822             :         AVCSeiRecoveryPoint *rp = &avc->sei.recovery_point;
    5823             : 
    5824         336 :         rp->frame_cnt = gf_bs_read_ue_log(bs, "frame_cnt");
    5825         336 :         rp->exact_match_flag = gf_bs_read_int_log(bs, 1, "exact_match_flag");
    5826         336 :         rp->broken_link_flag = gf_bs_read_int_log(bs, 1, "broken_link_flag");
    5827         336 :         rp->changing_slice_group_idc = gf_bs_read_int_log(bs, 2, "changing_slice_group_idc");
    5828         336 :         rp->valid = 1;
    5829             : 
    5830         336 :         return 0;
    5831             : }
    5832             : 
    5833             : /*for interpretation see ISO 14496-10 N.11084, table D-1*/
    5834        2191 : static s32 avc_parse_pic_timing_sei(GF_BitStream *bs, AVCState *avc)
    5835             : {
    5836        2191 :         int sps_id = avc->sps_active_idx;
    5837        2191 :         const char NumClockTS[] = { 1, 1, 1, 2, 2, 3, 3, 2, 3 };
    5838             :         AVCSeiPicTiming *pt = &avc->sei.pic_timing;
    5839             : 
    5840        2191 :         if (sps_id < 0) {
    5841             :                 /*sps_active_idx equals -1 when no sps has been detected. In this case SEI should not be decoded.*/
    5842             :                 assert(0);
    5843             :                 return 1;
    5844             :         }
    5845        2191 :         if (avc->sps[sps_id].vui.nal_hrd_parameters_present_flag || avc->sps[sps_id].vui.vcl_hrd_parameters_present_flag) { /*CpbDpbDelaysPresentFlag, see 14496-10(2003) E.11*/
    5846        1659 :                 gf_bs_read_int_log(bs, 1 + avc->sps[sps_id].vui.hrd.cpb_removal_delay_length_minus1, "cpb_removal_delay_minus1");
    5847        1659 :                 gf_bs_read_int_log(bs, 1 + avc->sps[sps_id].vui.hrd.dpb_output_delay_length_minus1, "dpb_output_delay_minus1");
    5848             :         }
    5849             : 
    5850             :         /*ISO 14496-10 (2003), D.8.2: we need to get pic_struct in order to know if we display top field first or bottom field first*/
    5851        2191 :         if (avc->sps[sps_id].vui.pic_struct_present_flag) {
    5852             :                 int i;
    5853        2165 :                 pt->pic_struct = gf_bs_read_int_log(bs, 4, "pic_struct");
    5854        2165 :                 if (pt->pic_struct > 8) {
    5855           0 :                         GF_LOG(GF_LOG_ERROR, GF_LOG_CODING, ("[avc-h264] invalid pic_struct value %d\n", pt->pic_struct));
    5856             :                         return 1;
    5857             :                 }
    5858             : 
    5859        2559 :                 for (i = 0; i < NumClockTS[pt->pic_struct]; i++) {
    5860        2559 :                         if (gf_bs_read_int_log_idx(bs, 1, "clock_timestamp_flag", i)) {
    5861             :                                 Bool full_timestamp_flag;
    5862        1659 :                                 gf_bs_read_int_log_idx(bs, 2, "ct_type", i);
    5863        1659 :                                 gf_bs_read_int_log_idx(bs, 1, "nuit_field_based_flag", i);
    5864        1659 :                                 gf_bs_read_int_log_idx(bs, 5, "counting_type", i);
    5865             :                                 full_timestamp_flag = gf_bs_read_int_log_idx(bs, 1, "full_timestamp_flag", i);
    5866        1659 :                                 gf_bs_read_int_log_idx(bs, 1, "discontinuity_flag", i);
    5867        1659 :                                 gf_bs_read_int_log_idx(bs, 1, "cnt_dropped_flag", i);
    5868        1659 :                                 gf_bs_read_int_log_idx(bs, 8, "n_frames", i);
    5869        1659 :                                 if (full_timestamp_flag) {
    5870           0 :                                         gf_bs_read_int_log_idx(bs, 6, "seconds_value", i);
    5871           0 :                                         gf_bs_read_int_log_idx(bs, 6, "minutes_value", i);
    5872           0 :                                         gf_bs_read_int_log_idx(bs, 5, "hours_value", i);
    5873             :                                 }
    5874             :                                 else {
    5875        1659 :                                         if (gf_bs_read_int_log_idx(bs, 1, "seconds_flag", i)) {
    5876         507 :                                                 gf_bs_read_int_log_idx(bs, 6, "seconds_value", i);
    5877         507 :                                                 if (gf_bs_read_int_log_idx(bs, 1, "minutes_flag", i)) {
    5878           0 :                                                         gf_bs_read_int_log_idx(bs, 6, "minutes_value", i);
    5879           0 :                                                         if (gf_bs_read_int_log_idx(bs, 1, "hours_flag", i)) {
    5880           0 :                                                                 gf_bs_read_int_log_idx(bs, 5, "hours_value", i);
    5881             :                                                         }
    5882             :                                                 }
    5883             :                                         }
    5884        1659 :                                         if (avc->sps[sps_id].vui.hrd.time_offset_length > 0)
    5885        1659 :                                                 gf_bs_read_int_log_idx(bs, avc->sps[sps_id].vui.hrd.time_offset_length, "time_offset", i);
    5886             :                                 }
    5887             :                         }
    5888             :                 }
    5889             :         }
    5890             : 
    5891             :         return 0;
    5892             : }
    5893             : 
    5894             : 
    5895             : #if !defined(GPAC_DISABLE_HEVC)
    5896           0 : static void avc_parse_itu_t_t35_sei(GF_BitStream* bs, AVCSeiItuTT35DolbyVision *dovi)
    5897             : {
    5898           0 :         u8 itu_t_t35_country_code = gf_bs_read_u8(bs);
    5899           0 :         u16 terminal_provider_code = gf_bs_read_u16(bs);
    5900           0 :         u32 user_id = gf_bs_read_u32(bs);
    5901           0 :         u8 data_type_code = gf_bs_read_u8(bs);
    5902           0 :         if (itu_t_t35_country_code == 0xB5 && terminal_provider_code == 0x31 && user_id == 0x47413934 && (data_type_code == 0x8 || data_type_code == 0x9)) {
    5903           0 :                 dovi->rpu_flag = GF_TRUE;
    5904             :         }
    5905           0 : }
    5906             : #endif
    5907             : 
    5908      219037 : static void avc_compute_poc(AVCSliceInfo *si)
    5909             : {
    5910             :         enum {
    5911             :                 AVC_PIC_FRAME,
    5912             :                 AVC_PIC_FIELD_TOP,
    5913             :                 AVC_PIC_FIELD_BOTTOM,
    5914             :         } pic_type;
    5915             :         s32 field_poc[2] = { 0,0 };
    5916             :         s32 max_frame_num;
    5917             : 
    5918      219037 :         if (!si->sps) return;
    5919             : 
    5920      219037 :         max_frame_num = 1 << (si->sps->log2_max_frame_num);
    5921             : 
    5922             :         /* picture type */
    5923      219037 :         if (si->sps->frame_mbs_only_flag || !si->field_pic_flag) pic_type = AVC_PIC_FRAME;
    5924         112 :         else if (si->bottom_field_flag) pic_type = AVC_PIC_FIELD_BOTTOM;
    5925             :         else pic_type = AVC_PIC_FIELD_TOP;
    5926             : 
    5927             :         /* frame_num_offset */
    5928      219037 :         if (si->nal_unit_type == GF_AVC_NALU_IDR_SLICE) {
    5929        7540 :                 si->poc_lsb_prev = 0;
    5930        7540 :                 si->poc_msb_prev = 0;
    5931        7540 :                 si->frame_num_offset = 0;
    5932             :         }
    5933             :         else {
    5934      211497 :                 if (si->frame_num < si->frame_num_prev)
    5935        3059 :                         si->frame_num_offset = si->frame_num_offset_prev + max_frame_num;
    5936             :                 else
    5937      208438 :                         si->frame_num_offset = si->frame_num_offset_prev;
    5938             :         }
    5939             : 
    5940             :         /*ISO 14496-10 N.11084 8.2.1.1*/
    5941      219037 :         if (si->sps->poc_type == 0)
    5942             :         {
    5943      148043 :                 const u32 max_poc_lsb = 1 << (si->sps->log2_max_poc_lsb);
    5944             : 
    5945             :                 /*ISO 14496-10 N.11084 eq (8-3)*/
    5946      212149 :                 if ((si->poc_lsb < si->poc_lsb_prev) &&
    5947       64106 :                         (si->poc_lsb_prev - si->poc_lsb >= max_poc_lsb / 2))
    5948         673 :                         si->poc_msb = si->poc_msb_prev + max_poc_lsb;
    5949      225134 :                 else if ((si->poc_lsb > si->poc_lsb_prev) &&
    5950       77764 :                         (si->poc_lsb - si->poc_lsb_prev > max_poc_lsb / 2))
    5951         593 :                         si->poc_msb = si->poc_msb_prev - max_poc_lsb;
    5952             :                 else
    5953      146777 :                         si->poc_msb = si->poc_msb_prev;
    5954             : 
    5955             :                 /*ISO 14496-10 N.11084 eq (8-4)*/
    5956      148043 :                 if (pic_type != AVC_PIC_FIELD_BOTTOM)
    5957      147987 :                         field_poc[0] = si->poc_msb + si->poc_lsb;
    5958             : 
    5959             :                 /*ISO 14496-10 N.11084 eq (8-5)*/
    5960      148043 :                 if (pic_type != AVC_PIC_FIELD_TOP) {
    5961      147987 :                         if (!si->field_pic_flag)
    5962      147931 :                                 field_poc[1] = field_poc[0] + si->delta_poc_bottom;
    5963             :                         else
    5964          56 :                                 field_poc[1] = si->poc_msb + si->poc_lsb;
    5965             :                 }
    5966             :         }
    5967             :         /*ISO 14496-10 N.11084 8.2.1.2*/
    5968       70994 :         else if (si->sps->poc_type == 1)
    5969             :         {
    5970             :                 u32 i;
    5971             :                 s32 abs_frame_num, expected_delta_per_poc_cycle, expected_poc;
    5972             : 
    5973           0 :                 if (si->sps->poc_cycle_length)
    5974           0 :                         abs_frame_num = si->frame_num_offset + si->frame_num;
    5975             :                 else
    5976             :                         abs_frame_num = 0;
    5977             : 
    5978           0 :                 if (!si->nal_ref_idc && (abs_frame_num > 0)) abs_frame_num--;
    5979             : 
    5980             :                 expected_delta_per_poc_cycle = 0;
    5981           0 :                 for (i = 0; i < si->sps->poc_cycle_length; i++)
    5982           0 :                         expected_delta_per_poc_cycle += si->sps->offset_for_ref_frame[i];
    5983             : 
    5984           0 :                 if (abs_frame_num > 0) {
    5985           0 :                         const u32 poc_cycle_cnt = (abs_frame_num - 1) / si->sps->poc_cycle_length;
    5986           0 :                         const u32 frame_num_in_poc_cycle = (abs_frame_num - 1) % si->sps->poc_cycle_length;
    5987             : 
    5988           0 :                         expected_poc = poc_cycle_cnt * expected_delta_per_poc_cycle;
    5989           0 :                         for (i = 0; i <= frame_num_in_poc_cycle; i++)
    5990           0 :                                 expected_poc += si->sps->offset_for_ref_frame[i];
    5991             :                 }
    5992             :                 else {
    5993             :                         expected_poc = 0;
    5994             :                 }
    5995             : 
    5996           0 :                 if (!si->nal_ref_idc) expected_poc += si->sps->offset_for_non_ref_pic;
    5997             : 
    5998           0 :                 field_poc[0] = expected_poc + si->delta_poc[0];
    5999           0 :                 field_poc[1] = field_poc[0] + si->sps->offset_for_top_to_bottom_field;
    6000           0 :                 if (pic_type == AVC_PIC_FRAME) field_poc[1] += si->delta_poc[1];
    6001             :         }
    6002             :         /*ISO 14496-10 N.11084 8.2.1.3*/
    6003       70994 :         else if (si->sps->poc_type == 2)
    6004             :         {
    6005             :                 int poc;
    6006       70994 :                 if (si->nal_unit_type == GF_AVC_NALU_IDR_SLICE) {
    6007             :                         poc = 0;
    6008             :                 }
    6009             :                 else {
    6010       68121 :                         const int abs_frame_num = si->frame_num_offset + si->frame_num;
    6011       68121 :                         poc = 2 * abs_frame_num;
    6012       68121 :                         if (!si->nal_ref_idc) poc -= 1;
    6013             :                 }
    6014             :                 field_poc[0] = poc;
    6015             :                 field_poc[1] = poc;
    6016             :         }
    6017             : 
    6018             :         /*ISO 14496-10 N.11084 eq (8-1)*/
    6019      219037 :         if (pic_type == AVC_PIC_FRAME)
    6020      218925 :                 si->poc = MIN(field_poc[0], field_poc[1]);
    6021         112 :         else if (pic_type == AVC_PIC_FIELD_TOP)
    6022          56 :                 si->poc = field_poc[0];
    6023             :         else
    6024          56 :                 si->poc = field_poc[1];
    6025             : }
    6026             : 
    6027             : GF_EXPORT
    6028      243590 : s32 gf_avc_parse_nalu(GF_BitStream *bs, AVCState *avc)
    6029             : {
    6030             :         u8 idr_flag;
    6031             :         s32 slice, ret;
    6032             :         u32 nal_hdr;
    6033             :         AVCSliceInfo n_state;
    6034             : 
    6035      243590 :         gf_bs_enable_emulation_byte_removal(bs, GF_TRUE);
    6036             : 
    6037      243590 :         nal_hdr = gf_bs_read_u8(bs);
    6038             : 
    6039             :         slice = 0;
    6040      243590 :         memcpy(&n_state, &avc->s_info, sizeof(AVCSliceInfo));
    6041      243590 :         avc->last_nal_type_parsed = n_state.nal_unit_type = nal_hdr & 0x1F;
    6042      243590 :         n_state.nal_ref_idc = (nal_hdr >> 5) & 0x3;
    6043             : 
    6044             :         idr_flag = 0;
    6045             : 
    6046      243590 :         switch (n_state.nal_unit_type) {
    6047             :         case GF_AVC_NALU_ACCESS_UNIT:
    6048             :         case GF_AVC_NALU_END_OF_SEQ:
    6049             :         case GF_AVC_NALU_END_OF_STREAM:
    6050             :                 ret = 1;
    6051             :                 break;
    6052             : 
    6053        2751 :         case GF_AVC_NALU_SVC_SLICE:
    6054        2751 :                 SVC_ReadNal_header_extension(bs, &n_state.NalHeader);
    6055             :                 // slice buffer - read the info and compare.
    6056        2751 :                 /*ret = */svc_parse_slice(bs, avc, &n_state);
    6057        2751 :                 if (avc->s_info.nal_ref_idc) {
    6058        1380 :                         n_state.poc_lsb_prev = avc->s_info.poc_lsb;
    6059        1380 :                         n_state.poc_msb_prev = avc->s_info.poc_msb;
    6060             :                 }
    6061        2751 :                 avc_compute_poc(&n_state);
    6062             : 
    6063        2751 :                 if (avc->s_info.poc != n_state.poc) {
    6064             :                         memcpy(&avc->s_info, &n_state, sizeof(AVCSliceInfo));
    6065         247 :                         return 1;
    6066             :                 }
    6067             :                 memcpy(&avc->s_info, &n_state, sizeof(AVCSliceInfo));
    6068        2504 :                 return 0;
    6069             : 
    6070        1262 :         case GF_AVC_NALU_SVC_PREFIX_NALU:
    6071        1262 :                 SVC_ReadNal_header_extension(bs, &n_state.NalHeader);
    6072        1262 :                 return 0;
    6073             : 
    6074      216563 :         case GF_AVC_NALU_IDR_SLICE:
    6075             :         case GF_AVC_NALU_NON_IDR_SLICE:
    6076             :         case GF_AVC_NALU_DP_A_SLICE:
    6077             :         case GF_AVC_NALU_DP_B_SLICE:
    6078             :         case GF_AVC_NALU_DP_C_SLICE:
    6079             :                 slice = 1;
    6080             :                 /* slice buffer - read the info and compare.*/
    6081      216563 :                 ret = avc_parse_slice(bs, avc, idr_flag, &n_state);
    6082      216563 :                 if (ret < 0) return ret;
    6083             :                 ret = 0;
    6084      216286 :                 if (
    6085      216286 :                         ((avc->s_info.nal_unit_type > GF_AVC_NALU_IDR_SLICE) || (avc->s_info.nal_unit_type < GF_AVC_NALU_NON_IDR_SLICE))
    6086      216286 :                         && (avc->s_info.nal_unit_type != GF_AVC_NALU_SVC_SLICE)
    6087             :                         ) {
    6088             :                         break;
    6089             :                 }
    6090      207588 :                 if (avc->s_info.frame_num != n_state.frame_num) {
    6091             :                         ret = 1;
    6092             :                         break;
    6093             :                 }
    6094             : 
    6095       62386 :                 if (avc->s_info.field_pic_flag != n_state.field_pic_flag) {
    6096             :                         ret = 1;
    6097             :                         break;
    6098             :                 }
    6099       62386 :                 if ((avc->s_info.nal_ref_idc != n_state.nal_ref_idc) &&
    6100        8519 :                         (!avc->s_info.nal_ref_idc || !n_state.nal_ref_idc)) {
    6101             :                         ret = 1;
    6102             :                         break;
    6103             :                 }
    6104             :                 assert(avc->s_info.sps);
    6105             : 
    6106       29250 :                 if (avc->s_info.sps->poc_type == n_state.sps->poc_type) {
    6107       29250 :                         if (!avc->s_info.sps->poc_type) {
    6108       29209 :                                 if (!n_state.bottom_field_flag && (avc->s_info.poc_lsb != n_state.poc_lsb)) {
    6109             :                                         ret = 1;
    6110             :                                         break;
    6111             :                                 }
    6112        7964 :                                 if (avc->s_info.delta_poc_bottom != n_state.delta_poc_bottom) {
    6113             :                                         ret = 1;
    6114             :                                         break;
    6115             :                                 }
    6116             :                         }
    6117          41 :                         else if (avc->s_info.sps->poc_type == 1) {
    6118           0 :                                 if (avc->s_info.delta_poc[0] != n_state.delta_poc[0]) {
    6119             :                                         ret = 1;
    6120             :                                         break;
    6121             :                                 }
    6122           0 :                                 if (avc->s_info.delta_poc[1] != n_state.delta_poc[1]) {
    6123             :                                         ret = 1;
    6124             :                                         break;
    6125             :                                 }
    6126             :                         }
    6127             :                 }
    6128             : 
    6129        8005 :                 if (n_state.nal_unit_type == GF_AVC_NALU_IDR_SLICE) {
    6130         315 :                         if (avc->s_info.nal_unit_type != GF_AVC_NALU_IDR_SLICE) { /*IdrPicFlag differs in value*/
    6131             :                                 ret = 1;
    6132             :                                 break;
    6133             :                         }
    6134         315 :                         else if (avc->s_info.idr_pic_id != n_state.idr_pic_id) { /*both IDR and idr_pic_id differs*/
    6135             :                                 ret = 1;
    6136             :                                 break;
    6137             :                         }
    6138             :                 }
    6139             :                 break;
    6140        3272 :         case GF_AVC_NALU_SEQ_PARAM:
    6141        3272 :                 avc->last_ps_idx = gf_avc_read_sps_bs_internal(bs, avc, 0, NULL, nal_hdr);
    6142        3272 :                 if (avc->last_ps_idx < 0) return -1;
    6143        3272 :                 return 0;
    6144             : 
    6145        6038 :         case GF_AVC_NALU_PIC_PARAM:
    6146        6038 :                 avc->last_ps_idx = gf_avc_read_pps_bs_internal(bs, avc, nal_hdr);
    6147        6038 :                 if (avc->last_ps_idx < 0) return -1;
    6148        6038 :                 return 0;
    6149          49 :         case GF_AVC_NALU_SVC_SUBSEQ_PARAM:
    6150          49 :                 avc->last_ps_idx = gf_avc_read_sps_bs_internal(bs, avc, 1, NULL, nal_hdr);
    6151          49 :                 if (avc->last_ps_idx < 0) return -1;
    6152          49 :                 return 0;
    6153             :         case GF_AVC_NALU_SEQ_PARAM_EXT:
    6154           0 :                 avc->last_ps_idx = (s32) gf_bs_read_ue(bs);
    6155           0 :                 if (avc->last_ps_idx < 0) return -1;
    6156           0 :                 return 0;
    6157             : 
    6158             :         case GF_AVC_NALU_SEI:
    6159             :         case GF_AVC_NALU_FILLER_DATA:
    6160             :                 return 0;
    6161             : 
    6162           0 :         default:
    6163           0 :                 if (avc->s_info.nal_unit_type <= GF_AVC_NALU_IDR_SLICE) ret = 1;
    6164             :                 //To detect change of AU when multiple sps and pps in stream
    6165           0 :                 else if ((nal_hdr & 0x1F) == GF_AVC_NALU_SEI && avc->s_info.nal_unit_type == GF_AVC_NALU_SVC_SLICE)
    6166             :                         ret = 1;
    6167           0 :                 else if ((nal_hdr & 0x1F) == GF_AVC_NALU_SEQ_PARAM && avc->s_info.nal_unit_type == GF_AVC_NALU_SVC_SLICE)
    6168             :                         ret = 1;
    6169             :                 else
    6170             :                         ret = 0;
    6171             :                 break;
    6172             :         }
    6173             : 
    6174             :         /* save _prev values */
    6175      216659 :         if (ret && avc->s_info.sps) {
    6176      207892 :                 n_state.frame_num_offset_prev = avc->s_info.frame_num_offset;
    6177      207892 :                 if ((avc->s_info.sps->poc_type != 2) || (avc->s_info.nal_ref_idc != 0))
    6178      207892 :                         n_state.frame_num_prev = avc->s_info.frame_num;
    6179      207892 :                 if (avc->s_info.nal_ref_idc) {
    6180      149399 :                         n_state.poc_lsb_prev = avc->s_info.poc_lsb;
    6181      149399 :                         n_state.poc_msb_prev = avc->s_info.poc_msb;
    6182             :                 }
    6183             :         }
    6184      224632 :         if (slice)
    6185      216286 :                 avc_compute_poc(&n_state);
    6186             :         memcpy(&avc->s_info, &n_state, sizeof(AVCSliceInfo));
    6187      224632 :         return ret;
    6188             : }
    6189             : 
    6190             : 
    6191        3760 : u32 gf_media_avc_reformat_sei(u8 *buffer, u32 nal_size, Bool isobmf_rewrite, AVCState *avc)
    6192             : {
    6193             :         u32 ptype, psize, hdr, var;
    6194             :         u32 start;
    6195             :         GF_BitStream *bs;
    6196             :         GF_BitStream *bs_dest = NULL;
    6197             :         u8 nhdr;
    6198             :         Bool sei_removed = GF_FALSE;
    6199             :         char store;
    6200             : 
    6201        3760 :         hdr = buffer[0];
    6202        3760 :         if ((hdr & 0x1F) != GF_AVC_NALU_SEI) return 0;
    6203             : 
    6204        3760 :         if (isobmf_rewrite) bs_dest = gf_bs_new(NULL, 0, GF_BITSTREAM_WRITE);
    6205             : 
    6206        3760 :         bs = gf_bs_new(buffer, nal_size, GF_BITSTREAM_READ);
    6207        3760 :         gf_bs_enable_emulation_byte_removal(bs, GF_TRUE);
    6208             : 
    6209        3760 :         nhdr = gf_bs_read_int(bs, 8);
    6210        3760 :         if (bs_dest) gf_bs_write_int(bs_dest, nhdr, 8);
    6211             : 
    6212             :         /*parse SEI*/
    6213        3813 :         while (gf_bs_available(bs)) {
    6214             :                 Bool do_copy;
    6215             :                 ptype = 0;
    6216             :                 while (1) {
    6217        3813 :                         u8 v = gf_bs_read_int(bs, 8);
    6218        3813 :                         ptype += v;
    6219        3813 :                         if (v != 0xFF) break;
    6220             :                 }
    6221             : 
    6222             :                 psize = 0;
    6223             :                 while (1) {
    6224        4196 :                         u8 v = gf_bs_read_int(bs, 8);
    6225        4196 :                         psize += v;
    6226        4196 :                         if (v != 0xFF) break;
    6227             :                 }
    6228             : 
    6229        3813 :                 start = (u32)gf_bs_get_position(bs);
    6230             : 
    6231             :                 do_copy = 1;
    6232             : 
    6233        3813 :                 if (start + psize >= nal_size) {
    6234           0 :                         GF_LOG(GF_LOG_WARNING, GF_LOG_CODING, ("[avc-h264] SEI user message type %d size error (%d but %d remain), keeping full SEI untouched\n", ptype, psize, nal_size - start));
    6235           0 :                         if (bs_dest) gf_bs_del(bs_dest);
    6236             :                         return nal_size;
    6237             :                 }
    6238        3813 :                 switch (ptype) {
    6239             :                         /*remove SEI messages forbidden in MP4*/
    6240           0 :                 case 3: /*filler data*/
    6241             :                 case 10: /*sub_seq info*/
    6242             :                 case 11: /*sub_seq_layer char*/
    6243             :                 case 12: /*sub_seq char*/
    6244             :                         do_copy = 0;
    6245             :                         sei_removed = GF_TRUE;
    6246           0 :                         break;
    6247        1173 :                 case 5: /*user unregistered */
    6248        1173 :                         store = buffer[start + psize];
    6249        1173 :                         buffer[start + psize] = 0;
    6250        1173 :                         GF_LOG(GF_LOG_DEBUG, GF_LOG_CODING, ("[avc-h264] SEI user message %s\n", buffer + start + 16));
    6251        1173 :                         buffer[start + psize] = store;
    6252        1173 :                         break;
    6253             : 
    6254         336 :                 case 6: /*recovery point*/
    6255         336 :                         avc_parse_recovery_point_sei(bs, avc);
    6256         336 :                         break;
    6257             : 
    6258        2191 :                 case 1: /*pic_timing*/
    6259        2191 :                         avc_parse_pic_timing_sei(bs, avc);
    6260        2191 :                         break;
    6261             : 
    6262             :                 case 0: /*buffering period*/
    6263             :                 case 2: /*pan scan rect*/
    6264             :                 case 4: /*user registered ITU t35*/
    6265             :                 case 7: /*def_rec_pic_marking_repetition*/
    6266             :                 case 8: /*spare_pic*/
    6267             :                 case 9: /*scene info*/
    6268             :                 case 13: /*full frame freeze*/
    6269             :                 case 14: /*full frame freeze release*/
    6270             :                 case 15: /*full frame snapshot*/
    6271             :                 case 16: /*progressive refinement segment start*/
    6272             :                 case 17: /*progressive refinement segment end*/
    6273             :                 case 18: /*motion constrained slice group*/
    6274             :                 default: /*add all unknown SEIs*/
    6275             :                         break;
    6276             :                 }
    6277             : 
    6278        3813 :                 if (do_copy && bs_dest) {
    6279             :                         var = ptype;
    6280        3813 :                         while (var >= 255) {
    6281           0 :                                 gf_bs_write_int(bs_dest, 0xFF, 8);
    6282           0 :                                 var -= 255;
    6283             :                         }
    6284        3813 :                         gf_bs_write_int(bs_dest, var, 8);
    6285             : 
    6286             :                         var = psize;
    6287        8009 :                         while (var >= 255) {
    6288         383 :                                 gf_bs_write_int(bs_dest, 0xFF, 8);
    6289         383 :                                 var -= 255;
    6290             :                         }
    6291        3813 :                         gf_bs_write_int(bs_dest, var, 8);
    6292        3813 :                         gf_bs_seek(bs, start);
    6293             : 
    6294             :                         //bs_read_data does not skip EPB, read byte per byte
    6295             :                         var = psize;
    6296      182544 :                         while (var) {
    6297      174918 :                                 gf_bs_write_u8(bs_dest, gf_bs_read_u8(bs));
    6298      174918 :                                 var--;
    6299             :                         }
    6300             :                 }
    6301             :                 else {
    6302           0 :                         gf_bs_seek(bs, start);
    6303             : 
    6304             :                         //bs_skip_bytes does not skip EPB, skip byte per byte
    6305           0 :                         while (psize) {
    6306           0 :                                 gf_bs_read_u8(bs);
    6307           0 :                                 psize--;
    6308             :                         }
    6309             :                 }
    6310             : 
    6311        3813 :                 if (gf_bs_available(bs) <= 2) {
    6312        3760 :                         var = gf_bs_read_int(bs, 8);
    6313        3760 :                         if (var != 0x80) {
    6314           0 :                                 GF_LOG(GF_LOG_WARNING, GF_LOG_CODING, ("[avc-h264] SEI user message has less than 2 bytes remaining but no end of sei found\n"));
    6315             :                         }
    6316        3760 :                         if (bs_dest) gf_bs_write_int(bs_dest, 0x80, 8);
    6317             :                         break;
    6318             :                 }
    6319             :         }
    6320        3760 :         gf_bs_del(bs);
    6321             :         //we cannot compare final size and original size since original may have EPB and final does not yet have them
    6322        3760 :         if (bs_dest && sei_removed) {
    6323           0 :                 u8 *dst_no_epb = NULL;
    6324           0 :                 u32 dst_no_epb_size = 0;
    6325           0 :                 gf_bs_get_content(bs_dest, &dst_no_epb, &dst_no_epb_size);
    6326           0 :                 nal_size = gf_media_nalu_add_emulation_bytes(buffer, dst_no_epb, dst_no_epb_size);
    6327             :         }
    6328        3760 :         if (bs_dest) gf_bs_del(bs_dest);
    6329             :         return nal_size;
    6330             : }
    6331             : 
    6332             : 
    6333             : static u8 avc_hevc_get_sar_idx(u32 w, u32 h)
    6334             : {
    6335             :         u32 i, count = GF_ARRAY_LENGTH(avc_hevc_sar);
    6336         102 :         for (i = 0; i < count; i++) {
    6337         102 :                 if ((avc_hevc_sar[i].w == w) && (avc_hevc_sar[i].h == h))
    6338           0 :                         return i;
    6339             :         }
    6340             :         return 0xFF;
    6341             : }
    6342             : 
    6343           8 : static void avc_hevc_rewrite_vui(GF_VUIInfo *vui_info, GF_BitStream *orig, GF_BitStream *mod)
    6344             : {
    6345             :         /* VUI present flag*/
    6346           8 :         Bool vui_present_flag = gf_bs_read_int(orig, 1);
    6347             : 
    6348             :         /*setup default values*/
    6349             :         Bool aspect_ratio_info_present_flag = 0;
    6350             :         s32 aspect_ratio_idc = -1;
    6351             :         u32 ar_n=0, ar_d=0;
    6352             :         Bool overscan_info_present_flag = 0;
    6353             :         u32 overscan_info=0;
    6354             :         u32 video_signal_type_present_flag=0;
    6355             :         u32 video_format = 5;
    6356             :         u32 video_full_range_flag = 0;
    6357             :         u32 colour_description_present_flag = 0;
    6358             :         u32 colour_primaries = 2;
    6359             :         u32 transfer_characteristics = 2;
    6360             :         u32 matrix_coefficients = 2;
    6361             : 
    6362             :         //if VUI is present, read all SAR and overscan values
    6363           8 :         if (vui_present_flag) { /* VUI found in input bitstream */
    6364           8 :                 aspect_ratio_info_present_flag = gf_bs_read_int(orig, 1);
    6365           8 :                 if (aspect_ratio_info_present_flag) {
    6366           0 :                         aspect_ratio_idc = gf_bs_read_int(orig, 8); /*aspect_ratio_idc*/
    6367           0 :                         if (aspect_ratio_idc == 255) {
    6368           0 :                                 ar_n = gf_bs_read_int(orig, 16); /*sar_width*/
    6369           0 :                                 ar_d = gf_bs_read_int(orig, 16); /*sar_height*/
    6370             :                         }
    6371             :                 }
    6372             : 
    6373             :                 /*overscan_info_present_flag */
    6374           8 :                 overscan_info_present_flag = gf_bs_read_int(orig, 1);
    6375           8 :                 if(overscan_info_present_flag) {
    6376           0 :                         overscan_info = gf_bs_read_int(orig, 1);
    6377             :                 }
    6378             : 
    6379             :                 /* read all video signal related flags first */
    6380           8 :                 video_signal_type_present_flag = gf_bs_read_int(orig, 1);
    6381           8 :                 if(video_signal_type_present_flag) {
    6382           0 :                         video_format = gf_bs_read_int(orig, 3);
    6383           0 :                         video_full_range_flag = gf_bs_read_int(orig, 1);
    6384           0 :                         colour_description_present_flag = gf_bs_read_int(orig, 1);
    6385           0 :                         if(colour_description_present_flag) {
    6386           0 :                                 colour_primaries = gf_bs_read_int(orig, 8);
    6387           0 :                                 transfer_characteristics = gf_bs_read_int(orig, 8);
    6388           0 :                                 matrix_coefficients = gf_bs_read_int(orig, 8);
    6389             :                         }
    6390             :                 }
    6391             :         }
    6392             : 
    6393             :         //recompute values
    6394             :         //no change
    6395           8 :         if ((vui_info->ar_num<0) || (vui_info->ar_den<0)) {
    6396             :         }
    6397             :         //remove par
    6398           6 :         else if ((vui_info->ar_num==0) || (vui_info->ar_den==0)) {
    6399             :                 aspect_ratio_info_present_flag = 0;
    6400             :         }
    6401             :         //set par
    6402             :         else {
    6403             :                 aspect_ratio_info_present_flag = 1;
    6404           6 :                 ar_n = vui_info->ar_num;
    6405           6 :                 ar_d = vui_info->ar_den;
    6406           6 :                 aspect_ratio_idc = avc_hevc_get_sar_idx((u32) ar_n, (u32) ar_d);
    6407             :         }
    6408             : 
    6409           8 :         if (vui_info->remove_video_info) {
    6410             :                 video_signal_type_present_flag = 0;
    6411             :         }
    6412             :         /* correct the values of each flags */
    6413           8 :         else if ((vui_info->fullrange==0) && (vui_info->video_format==5) && (vui_info->color_prim==2) && (vui_info->color_tfc==2) && (vui_info->color_matrix==2)) {
    6414             :                 video_signal_type_present_flag = 0; /* all default, nothing to write*/
    6415             :         } else {
    6416             :                 video_signal_type_present_flag = 1;
    6417           8 :                 video_format = (vui_info->video_format < 0) ? video_format : vui_info->video_format;
    6418           8 :                 video_full_range_flag = (vui_info->fullrange < 0) ? video_full_range_flag : vui_info->fullrange;
    6419           8 :                 if ((vui_info->color_prim==2) && (vui_info->color_tfc==2) && (vui_info->color_matrix==2)) {
    6420             :                         colour_description_present_flag = 0;
    6421             :                 } else {
    6422             :                         colour_description_present_flag = 1;
    6423           8 :                         colour_primaries = (vui_info->color_prim < 0) ? colour_primaries : vui_info->color_prim;
    6424           8 :                         transfer_characteristics = (vui_info->color_tfc < 0) ? transfer_characteristics : vui_info->color_tfc;
    6425           8 :                         matrix_coefficients = (vui_info->color_matrix < 0) ? matrix_coefficients : vui_info->color_matrix;
    6426             :                 }
    6427           8 :                 if ((colour_primaries==2) && (transfer_characteristics==2) && (matrix_coefficients==2)) {
    6428             :                         colour_description_present_flag = 0;
    6429           8 :                         if ((video_format==5) && (video_full_range_flag==0))
    6430             :                                 video_signal_type_present_flag = 0;
    6431             :                 }
    6432             :         }
    6433             : 
    6434             :         //always rewrite VUI
    6435           8 :         gf_bs_write_int(mod, 1, 1);
    6436           8 :         gf_bs_write_int(mod, aspect_ratio_info_present_flag, 1);
    6437           8 :         if (aspect_ratio_info_present_flag) {
    6438           6 :                 gf_bs_write_int(mod, aspect_ratio_idc, 8);
    6439           6 :                 if (aspect_ratio_idc == 255) {
    6440           6 :                         gf_bs_write_int(mod, ar_n, 16);
    6441           6 :                         gf_bs_write_int(mod, ar_d, 16);
    6442             :                 }
    6443           6 :                 if (vui_info->update) {
    6444           4 :                         vui_info->ar_num = ar_n;
    6445           4 :                         vui_info->ar_den = ar_d;
    6446             :                 }
    6447             :         }
    6448           8 :         gf_bs_write_int(mod, overscan_info_present_flag, 1);
    6449           8 :         if (overscan_info_present_flag) {
    6450           0 :                 gf_bs_write_int(mod, overscan_info, 1);
    6451             :         }
    6452             : 
    6453           8 :         gf_bs_write_int(mod, video_signal_type_present_flag, 1);
    6454           8 :         if (video_signal_type_present_flag) {
    6455           1 :                 gf_bs_write_int(mod, video_format, 3);
    6456           1 :                 gf_bs_write_int(mod, video_full_range_flag, 1);
    6457           1 :                 gf_bs_write_int(mod, colour_description_present_flag, 1);
    6458             : 
    6459           1 :                 if (colour_description_present_flag) {
    6460           0 :                         gf_bs_write_int(mod, colour_primaries, 8);
    6461           0 :                         gf_bs_write_int(mod, transfer_characteristics, 8);
    6462           0 :                         gf_bs_write_int(mod, matrix_coefficients, 8);
    6463             :                 }
    6464             : 
    6465           1 :                 if (vui_info->update) {
    6466           0 :                         vui_info->video_format = video_format;
    6467           0 :                         vui_info->fullrange = video_full_range_flag;
    6468           0 :                         if (colour_description_present_flag) {
    6469           0 :                                 vui_info->color_prim = colour_primaries;
    6470           0 :                                 vui_info->color_tfc = transfer_characteristics;
    6471           0 :                                 vui_info->color_matrix = matrix_coefficients;
    6472             :                         }
    6473             :                 }
    6474             :         }
    6475             : 
    6476             :         /*no VUI in input bitstream but we just inserted one, set all remaining vui flags to 0*/
    6477           8 :         if (!vui_present_flag) {
    6478           0 :                 gf_bs_write_int(mod, 0, 1);             /*chroma_location_info_present_flag */
    6479           0 :                 gf_bs_write_int(mod, 0, 1);             /*timing_info_present_flag*/
    6480           0 :                 gf_bs_write_int(mod, 0, 1);             /*nal_hrd_parameters_present*/
    6481           0 :                 gf_bs_write_int(mod, 0, 1);             /*vcl_hrd_parameters_present*/
    6482           0 :                 gf_bs_write_int(mod, 0, 1);             /*pic_struct_present*/
    6483           0 :                 gf_bs_write_int(mod, 0, 1);             /*bitstream_restriction*/
    6484             :         }
    6485             :         /*otherwise we copy over th bits from the input bitrate*/
    6486           8 : }
    6487             : 
    6488           5 : GF_Err gf_avc_change_vui(GF_AVCConfig *avcc, GF_VUIInfo *vui_info)
    6489             : {
    6490             :         GF_BitStream *orig, *mod;
    6491             :         AVCState avc;
    6492             :         u32 i, bit_offset, flag;
    6493             :         s32 idx;
    6494             :         GF_AVCConfigSlot *slc;
    6495             :         orig = NULL;
    6496             : 
    6497             :         memset(&avc, 0, sizeof(AVCState));
    6498           5 :         avc.sps_active_idx = -1;
    6499             : 
    6500           5 :         i=0;
    6501          15 :         while ((slc = (GF_AVCConfigSlot *)gf_list_enum(avcc->sequenceParameterSets, &i))) {
    6502           5 :                 u8 *no_emulation_buf = NULL;
    6503             :                 u32 no_emulation_buf_size = 0, emulation_bytes = 0;
    6504           5 :                 idx = gf_avc_read_sps(slc->data, slc->size, &avc, 0, &bit_offset);
    6505           5 :                 if (idx<0) {
    6506             :                         if ( orig )
    6507             :                                 gf_bs_del(orig);
    6508           0 :                         continue;
    6509             :                 }
    6510             : 
    6511             :                 /*SPS still contains emulation bytes*/
    6512           5 :                 no_emulation_buf = gf_malloc((slc->size - 1) * sizeof(char));
    6513           5 :                 no_emulation_buf_size = gf_media_nalu_remove_emulation_bytes(slc->data + 1, no_emulation_buf, slc->size - 1);
    6514             : 
    6515           5 :                 orig = gf_bs_new(no_emulation_buf, no_emulation_buf_size, GF_BITSTREAM_READ);
    6516           5 :                 gf_bs_read_data(orig, no_emulation_buf, no_emulation_buf_size);
    6517           5 :                 gf_bs_seek(orig, 0);
    6518           5 :                 mod = gf_bs_new(NULL, 0, GF_BITSTREAM_WRITE);
    6519             : 
    6520             :                 /*copy over till vui flag*/
    6521             :                 assert(bit_offset >= 8);
    6522         330 :                 while (bit_offset - 8/*bit_offset doesn't take care of the first byte (NALU type)*/) {
    6523         320 :                         flag = gf_bs_read_int(orig, 1);
    6524         320 :                         gf_bs_write_int(mod, flag, 1);
    6525         320 :                         bit_offset--;
    6526             :                 }
    6527             : 
    6528           5 :                 avc_hevc_rewrite_vui(vui_info, orig, mod);
    6529             : 
    6530             :                 /*finally copy over remaining*/
    6531         510 :                 while (gf_bs_bits_available(orig)) {
    6532         500 :                         flag = gf_bs_read_int(orig, 1);
    6533         500 :                         gf_bs_write_int(mod, flag, 1);
    6534             :                 }
    6535           5 :                 gf_bs_del(orig);
    6536             :                 orig = NULL;
    6537           5 :                 gf_free(no_emulation_buf);
    6538             : 
    6539             :                 /*set anti-emulation*/
    6540           5 :                 gf_bs_get_content(mod, &no_emulation_buf, &flag);
    6541           5 :                 emulation_bytes = gf_media_nalu_emulation_bytes_add_count(no_emulation_buf, flag);
    6542           5 :                 if (flag+emulation_bytes+1>slc->size)
    6543           4 :                         slc->data = (char*)gf_realloc(slc->data, flag+emulation_bytes+1);
    6544           5 :                 slc->size = gf_media_nalu_add_emulation_bytes(no_emulation_buf, slc->data + 1, flag) + 1;
    6545             : 
    6546           5 :                 gf_bs_del(mod);
    6547           5 :                 gf_free(no_emulation_buf);
    6548             :         }
    6549           5 :         return GF_OK;
    6550             : }
    6551             : 
    6552             : GF_EXPORT
    6553           1 : GF_Err gf_media_avc_change_par(GF_AVCConfig *avcc, s32 ar_n, s32 ar_d)
    6554             : {
    6555             :         GF_VUIInfo vuii;
    6556             :         memset(&vuii, 0, sizeof(GF_VUIInfo));
    6557           1 :         vuii.ar_num = ar_n;
    6558           1 :         vuii.ar_den = ar_d;
    6559           1 :         vuii.fullrange = -1;
    6560           1 :         vuii.video_format = -1;
    6561           1 :         vuii.color_prim = -1;
    6562           1 :         vuii.color_tfc = -1;
    6563           1 :         vuii.color_matrix = -1;
    6564           1 :         return gf_avc_change_vui(avcc, &vuii);
    6565             : }
    6566             : 
    6567             : GF_EXPORT
    6568           2 : GF_Err gf_media_avc_change_color(GF_AVCConfig *avcc, s32 fullrange, s32 vidformat, s32 colorprim, s32 transfer, s32 colmatrix)
    6569             : {
    6570             :         GF_VUIInfo vuii;
    6571             :         memset(&vuii, 0, sizeof(GF_VUIInfo));
    6572           2 :         vuii.ar_num = -1;
    6573           2 :         vuii.ar_den = -1;
    6574           2 :         vuii.fullrange = fullrange;
    6575           2 :         vuii.video_format = vidformat;
    6576           2 :         vuii.color_prim = colorprim;
    6577           2 :         vuii.color_tfc = transfer;
    6578           2 :         vuii.color_matrix = colmatrix;
    6579           2 :         return gf_avc_change_vui(avcc, &vuii);
    6580             : }
    6581             : 
    6582             : 
    6583             : GF_EXPORT
    6584          30 : GF_Err gf_avc_get_sps_info(u8 *sps_data, u32 sps_size, u32 *sps_id, u32 *width, u32 *height, s32 *par_n, s32 *par_d)
    6585             : {
    6586             :         AVCState avc;
    6587             :         s32 idx;
    6588             :         memset(&avc, 0, sizeof(AVCState));
    6589          30 :         avc.sps_active_idx = -1;
    6590             : 
    6591          30 :         idx = gf_avc_read_sps(sps_data, sps_size, &avc, 0, NULL);
    6592          30 :         if (idx < 0) {
    6593             :                 return GF_NON_COMPLIANT_BITSTREAM;
    6594             :         }
    6595          30 :         if (sps_id) *sps_id = idx;
    6596             : 
    6597          30 :         if (width) *width = avc.sps[idx].width;
    6598          30 :         if (height) *height = avc.sps[idx].height;
    6599          30 :         if (par_n) *par_n = avc.sps[idx].vui.par_num ? avc.sps[idx].vui.par_num : (u32)-1;
    6600          30 :         if (par_d) *par_d = avc.sps[idx].vui.par_den ? avc.sps[idx].vui.par_den : (u32)-1;
    6601             : 
    6602             :         return GF_OK;
    6603             : }
    6604             : 
    6605             : GF_EXPORT
    6606           0 : GF_Err gf_avc_get_pps_info(u8 *pps_data, u32 pps_size, u32 *pps_id, u32 *sps_id)
    6607             : {
    6608             :         GF_BitStream *bs;
    6609             :         GF_Err e = GF_OK;
    6610             : 
    6611           0 :         bs = gf_bs_new(pps_data, pps_size, GF_BITSTREAM_READ);
    6612           0 :         if (!bs) {
    6613             :                 e = GF_NON_COMPLIANT_BITSTREAM;
    6614             :                 goto exit;
    6615             :         }
    6616           0 :         gf_bs_enable_emulation_byte_removal(bs, GF_TRUE);
    6617           0 :         /*nal hdr*/ gf_bs_read_int(bs, 8);
    6618             : 
    6619           0 :         *pps_id = gf_bs_read_ue(bs);
    6620           0 :         *sps_id = gf_bs_read_ue(bs);
    6621             : 
    6622           0 : exit:
    6623           0 :         gf_bs_del(bs);
    6624           0 :         return e;
    6625             : }
    6626             : 
    6627             : #ifndef GPAC_DISABLE_HEVC
    6628             : 
    6629             : /**********
    6630             : HEVC parsing
    6631             : **********/
    6632             : 
    6633      487793 : Bool gf_hevc_slice_is_intra(HEVCState *hevc)
    6634             : {
    6635      487793 :         switch (hevc->s_info.nal_unit_type) {
    6636             :         case GF_HEVC_NALU_SLICE_BLA_W_LP:
    6637             :         case GF_HEVC_NALU_SLICE_BLA_W_DLP:
    6638             :         case GF_HEVC_NALU_SLICE_BLA_N_LP:
    6639             :         case GF_HEVC_NALU_SLICE_IDR_W_DLP:
    6640             :         case GF_HEVC_NALU_SLICE_IDR_N_LP:
    6641             :         case GF_HEVC_NALU_SLICE_CRA:
    6642             :                 return GF_TRUE;
    6643      470370 :         default:
    6644      470370 :                 return GF_FALSE;
    6645             :         }
    6646             : }
    6647             : 
    6648      975586 : Bool gf_hevc_slice_is_IDR(HEVCState *hevc)
    6649             : {
    6650      975586 :         if (hevc->sei.recovery_point.valid)
    6651             :         {
    6652           0 :                 hevc->sei.recovery_point.valid = 0;
    6653           0 :                 return GF_TRUE;
    6654             :         }
    6655      975586 :         switch (hevc->s_info.nal_unit_type) {
    6656             :         case GF_HEVC_NALU_SLICE_IDR_W_DLP:
    6657             :         case GF_HEVC_NALU_SLICE_IDR_N_LP:
    6658             :                 return GF_TRUE;
    6659      941412 :         default:
    6660      941412 :                 return GF_FALSE;
    6661             :         }
    6662             : }
    6663             : 
    6664       94547 : static Bool hevc_parse_short_term_ref_pic_set(GF_BitStream *bs, HEVC_SPS *sps, u32 idx_rps)
    6665             : {
    6666             :         u32 i;
    6667             :         Bool inter_ref_pic_set_prediction_flag = 0;
    6668       94547 :         if (idx_rps != 0)
    6669         536 :                 inter_ref_pic_set_prediction_flag = gf_bs_read_int_log_idx(bs, 1, "inter_ref_pic_set_prediction_flag", idx_rps);
    6670             : 
    6671         536 :         if (inter_ref_pic_set_prediction_flag) {
    6672             :                 HEVC_ReferencePictureSets *ref_ps, *rps;
    6673             :                 u32 delta_idx_minus1 = 0;
    6674             :                 u32 ref_idx;
    6675             :                 u32 delta_rps_sign;
    6676             :                 u32 abs_delta_rps_minus1, nb_ref_pics;
    6677             :                 s32 deltaRPS;
    6678             :                 u32 k = 0, k0 = 0, k1 = 0;
    6679          75 :                 if (idx_rps == sps->num_short_term_ref_pic_sets)
    6680           0 :                         delta_idx_minus1 = gf_bs_read_ue_log_idx(bs, "delta_idx_minus1", idx_rps);
    6681             : 
    6682             :                 assert(delta_idx_minus1 <= idx_rps - 1);
    6683          75 :                 ref_idx = idx_rps - 1 - delta_idx_minus1;
    6684             :                 delta_rps_sign = gf_bs_read_int_log_idx(bs, 1, "delta_rps_sign", idx_rps);
    6685          75 :                 abs_delta_rps_minus1 = gf_bs_read_ue_log_idx(bs, "abs_delta_rps_minus1", idx_rps);
    6686          75 :                 deltaRPS = (1 - (delta_rps_sign << 1)) * (abs_delta_rps_minus1 + 1);
    6687             : 
    6688             :                 rps = &sps->rps[idx_rps];
    6689             :                 ref_ps = &sps->rps[ref_idx];
    6690          75 :                 nb_ref_pics = ref_ps->num_negative_pics + ref_ps->num_positive_pics;
    6691         470 :                 for (i = 0; i <= nb_ref_pics; i++) {
    6692             :                         s32 ref_idc;
    6693         790 :                         s32 used_by_curr_pic_flag = gf_bs_read_int_log_idx2(bs, 1, "used_by_curr_pic_flag", idx_rps, i);
    6694         395 :                         ref_idc = used_by_curr_pic_flag ? 1 : 0;
    6695         395 :                         if (!used_by_curr_pic_flag) {
    6696          85 :                                 used_by_curr_pic_flag = gf_bs_read_int_log_idx2(bs, 1, "used_by_curr_pic_flag", idx_rps, i);
    6697          85 :                                 ref_idc = used_by_curr_pic_flag << 1;
    6698             :                         }
    6699         395 :                         if ((ref_idc == 1) || (ref_idc == 2)) {
    6700             :                                 s32 deltaPOC = deltaRPS;
    6701         328 :                                 if (i < nb_ref_pics)
    6702         276 :                                         deltaPOC += ref_ps->delta_poc[i];
    6703             : 
    6704         328 :                                 rps->delta_poc[k] = deltaPOC;
    6705             : 
    6706         328 :                                 if (deltaPOC < 0)  k0++;
    6707         123 :                                 else k1++;
    6708             : 
    6709         328 :                                 k++;
    6710             :                         }
    6711             :                 }
    6712          75 :                 rps->num_negative_pics = k0;
    6713          75 :                 rps->num_positive_pics = k1;
    6714             :         }
    6715             :         else {
    6716             :                 s32 prev = 0, poc;
    6717       94472 :                 sps->rps[idx_rps].num_negative_pics = gf_bs_read_ue_log_idx(bs, "num_negative_pics", idx_rps);
    6718       94472 :                 sps->rps[idx_rps].num_positive_pics = gf_bs_read_ue_log_idx(bs, "num_positive_pics", idx_rps);
    6719       94472 :                 if (sps->rps[idx_rps].num_negative_pics > 16)
    6720             :                         return GF_FALSE;
    6721       94472 :                 if (sps->rps[idx_rps].num_positive_pics > 16)
    6722             :                         return GF_FALSE;
    6723      188071 :                 for (i = 0; i < sps->rps[idx_rps].num_negative_pics; i++) {
    6724      188071 :                         u32 delta_poc_s0_minus1 = gf_bs_read_ue_log_idx2(bs, "delta_poc_s0_minus1", idx_rps, i);
    6725      188071 :                         poc = prev - delta_poc_s0_minus1 - 1;
    6726             :                         prev = poc;
    6727      188071 :                         sps->rps[idx_rps].delta_poc[i] = poc;
    6728      188071 :                         gf_bs_read_int_log_idx2(bs, 1, "delta_poc_s0_minus1", idx_rps, i);
    6729             :                 }
    6730          96 :                 for (i = 0; i < sps->rps[idx_rps].num_positive_pics; i++) {
    6731          96 :                         u32 delta_poc_s1_minus1 = gf_bs_read_ue_log_idx2(bs, "delta_poc_s1_minus1" , idx_rps, i);
    6732          96 :                         poc = prev + delta_poc_s1_minus1 + 1;
    6733             :                         prev = poc;
    6734          96 :                         sps->rps[idx_rps].delta_poc[i] = poc;
    6735          96 :                         gf_bs_read_int_log_idx2(bs, 1, "used_by_curr_pic_s1_flag", idx_rps, i);
    6736             :                 }
    6737             :         }
    6738             :         return GF_TRUE;
    6739             : }
    6740             : 
    6741           0 : void hevc_pred_weight_table(GF_BitStream *bs, HEVCState *hevc, HEVCSliceInfo *si, HEVC_PPS *pps, HEVC_SPS *sps, u32 num_ref_idx_l0_active, u32 num_ref_idx_l1_active)
    6742             : {
    6743             :         u32 i, num_ref_idx;
    6744             :         Bool first_pass = GF_TRUE;
    6745             :         u8 luma_weights[20], chroma_weights[20];
    6746           0 :         u32 ChromaArrayType = sps->separate_colour_plane_flag ? 0 : sps->chroma_format_idc;
    6747             : 
    6748             :         num_ref_idx = num_ref_idx_l0_active;
    6749             : 
    6750           0 :         gf_bs_read_ue_log(bs, "luma_log2_weight_denom");
    6751           0 :         if (ChromaArrayType != 0)
    6752           0 :                 gf_bs_read_se_log(bs, "delta_chroma_log2_weight_denom");
    6753             : 
    6754           0 : parse_weights:
    6755           0 :         for (i = 0; i < num_ref_idx; i++) {
    6756           0 :                 luma_weights[i] = gf_bs_read_int_log_idx(bs, 1, "luma_weights", i);
    6757             :                 //infered to be 0 if not present
    6758           0 :                 chroma_weights[i] = 0;
    6759             :         }
    6760           0 :         if (ChromaArrayType != 0) {
    6761           0 :                 for (i = 0; i < num_ref_idx; i++) {
    6762           0 :                         chroma_weights[i] = gf_bs_read_int_log_idx(bs, 1, "chroma_weights", i);
    6763             :                 }
    6764             :         }
    6765           0 :         for (i = 0; i < num_ref_idx; i++) {
    6766           0 :                 if (luma_weights[i]) {
    6767           0 :                         gf_bs_read_se_log_idx(bs, "delta_luma_weight_l0", i);
    6768           0 :                         gf_bs_read_se_log_idx(bs, "luma_offset_l0", i);
    6769             :                 }
    6770           0 :                 if (chroma_weights[i]) {
    6771           0 :                         gf_bs_read_se_log_idx(bs, "delta_chroma_weight_l0_0", i);
    6772           0 :                         gf_bs_read_se_log_idx(bs, "delta_chroma_offset_l0_0", i);
    6773             : 
    6774           0 :                         gf_bs_read_se_log_idx(bs, "delta_chroma_weight_l0_1", i);
    6775           0 :                         gf_bs_read_se_log_idx(bs, "delta_chroma_offset_l0_1", i);
    6776             :                 }
    6777             :         }
    6778             : 
    6779           0 :         if (si->slice_type == GF_HEVC_SLICE_TYPE_B) {
    6780           0 :                 if (!first_pass) return;
    6781             :                 first_pass = GF_FALSE;
    6782             :                 num_ref_idx = num_ref_idx_l1_active;
    6783             :                 goto parse_weights;
    6784             :         }
    6785             : }
    6786             : 
    6787             : static
    6788           0 : Bool ref_pic_lists_modification(GF_BitStream *bs, u32 slice_type, u32 num_ref_idx_l0_active, u32 num_ref_idx_l1_active)
    6789             : {
    6790             :         //u32 i;
    6791             :         Bool ref_pic_list_modification_flag_l0 = gf_bs_read_int_log(bs, 1, "ref_pic_list_modification_flag_l0");
    6792           0 :         if (ref_pic_list_modification_flag_l0) {
    6793             :                 /*for (i=0; i<num_ref_idx_l0_active; i++) {
    6794             :                         list_entry_l0[i] = *//*gf_bs_read_int(bs, (u32)ceil(log(getNumPicTotalCurr())/log(2)));
    6795             :                 }*/
    6796             :                 return GF_FALSE;
    6797             :         }
    6798           0 :         if (slice_type == GF_HEVC_SLICE_TYPE_B) {
    6799             :                 Bool ref_pic_list_modification_flag_l1 = gf_bs_read_int_log(bs, 1, "ref_pic_list_modification_flag_l1");
    6800           0 :                 if (ref_pic_list_modification_flag_l1) {
    6801             :                         /*for (i=0; i<num_ref_idx_l1_active; i++) {
    6802             :                                 list_entry_l1[i] = *//*gf_bs_read_int(bs, (u32)ceil(log(getNumPicTotalCurr()) / log(2)));
    6803             :                         }*/
    6804             :                         return GF_FALSE;
    6805             :                 }
    6806             :         }
    6807             : 
    6808             :         return GF_TRUE;
    6809             : }
    6810             : 
    6811             : static
    6812      729693 : s32 hevc_parse_slice_segment(GF_BitStream *bs, HEVCState *hevc, HEVCSliceInfo *si)
    6813             : {
    6814             :         u32 i, j;
    6815             :         u32 num_ref_idx_l0_active = 0, num_ref_idx_l1_active = 0;
    6816             :         HEVC_PPS *pps;
    6817             :         HEVC_SPS *sps;
    6818             :         s32 pps_id;
    6819             :         Bool RapPicFlag = GF_FALSE;
    6820             :         Bool IDRPicFlag = GF_FALSE;
    6821             : 
    6822      729693 :         si->first_slice_segment_in_pic_flag = gf_bs_read_int_log(bs, 1, "first_slice_segment_in_pic_flag");
    6823             : 
    6824      729693 :         switch (si->nal_unit_type) {
    6825             :         case GF_HEVC_NALU_SLICE_IDR_W_DLP:
    6826             :         case GF_HEVC_NALU_SLICE_IDR_N_LP:
    6827             :                 IDRPicFlag = GF_TRUE;
    6828             :                 RapPicFlag = GF_TRUE;
    6829             :                 break;
    6830             :         case GF_HEVC_NALU_SLICE_BLA_W_LP:
    6831             :         case GF_HEVC_NALU_SLICE_BLA_W_DLP:
    6832             :         case GF_HEVC_NALU_SLICE_BLA_N_LP:
    6833             :         case GF_HEVC_NALU_SLICE_CRA:
    6834             :                 RapPicFlag = GF_TRUE;
    6835             :                 break;
    6836             :         }
    6837             : 
    6838             :         if (RapPicFlag) {
    6839       30288 :                 gf_bs_read_int_log(bs, 1, "no_output_of_prior_pics_flag");
    6840             :         }
    6841             : 
    6842      729693 :         pps_id = gf_bs_read_ue_log(bs, "pps_id");
    6843      729693 :         if ((pps_id<0) || (pps_id >= 64))
    6844             :                 return -1;
    6845             : 
    6846      729693 :         pps = &hevc->pps[pps_id];
    6847      729693 :         sps = &hevc->sps[pps->sps_id];
    6848      729693 :         si->sps = sps;
    6849      729693 :         si->pps = pps;
    6850             : 
    6851      729693 :         if (!si->first_slice_segment_in_pic_flag && pps->dependent_slice_segments_enabled_flag) {
    6852           0 :                 si->dependent_slice_segment_flag = gf_bs_read_int_log(bs, 1, "dependent_slice_segment_flag");
    6853             :         }
    6854             :         else {
    6855      729693 :                 si->dependent_slice_segment_flag = GF_FALSE;
    6856             :         }
    6857             : 
    6858      729693 :         if (!si->first_slice_segment_in_pic_flag) {
    6859     1151634 :                 si->slice_segment_address = gf_bs_read_int_log(bs, sps->bitsSliceSegmentAddress, "slice_segment_address");
    6860             :         }
    6861             :         else {
    6862      153876 :                 si->slice_segment_address = 0;
    6863             :         }
    6864             : 
    6865      729693 :         if (!si->dependent_slice_segment_flag) {
    6866             :                 Bool deblocking_filter_override_flag = 0;
    6867             :                 Bool slice_temporal_mvp_enabled_flag = 0;
    6868             :                 Bool slice_sao_luma_flag = 0;
    6869             :                 Bool slice_sao_chroma_flag = 0;
    6870             :                 Bool slice_deblocking_filter_disabled_flag = 0;
    6871             : 
    6872             :                 //"slice_reserved_undetermined_flag[]"
    6873      729693 :                 gf_bs_read_int_log(bs, pps->num_extra_slice_header_bits, "slice_reserved_undetermined_flag");
    6874             : 
    6875      729693 :                 si->slice_type = gf_bs_read_ue_log(bs, "slice_type");
    6876             : 
    6877      729693 :                 if (pps->output_flag_present_flag)
    6878           0 :                         gf_bs_read_int_log(bs, 1, "pic_output_flag");
    6879             : 
    6880      729693 :                 if (sps->separate_colour_plane_flag == 1)
    6881           0 :                         gf_bs_read_int_log(bs, 2, "colour_plane_id");
    6882             : 
    6883      729693 :                 if (IDRPicFlag) {
    6884       29942 :                         si->poc_lsb = 0;
    6885             : 
    6886             :                         //if not asked to parse full header, abort since we know the poc
    6887       29942 :                         if (!hevc->full_slice_header_parse) return 0;
    6888             : 
    6889             :                 }
    6890             :                 else {
    6891     1399502 :                         si->poc_lsb = gf_bs_read_int_log(bs, sps->log2_max_pic_order_cnt_lsb, "poc_lsb");
    6892             : 
    6893             :                         //if not asked to parse full header, abort once we have the poc
    6894      699751 :                         if (!hevc->full_slice_header_parse) return 0;
    6895             : 
    6896       93611 :                         if (gf_bs_read_int_log(bs, 1, "short_term_ref_pic_set_sps_flag") == 0) {
    6897       93611 :                                 Bool ret = hevc_parse_short_term_ref_pic_set(bs, sps, sps->num_short_term_ref_pic_sets);
    6898       93611 :                                 if (!ret)
    6899             :                                         return -1;
    6900             :                         }
    6901           0 :                         else if (sps->num_short_term_ref_pic_sets > 1) {
    6902             :                                 u32 numbits = 0;
    6903             : 
    6904           0 :                                 while ((u32)(1 << numbits) < sps->num_short_term_ref_pic_sets)
    6905           0 :                                         numbits++;
    6906           0 :                                 if (numbits > 0)
    6907           0 :                                         gf_bs_read_int_log(bs, numbits, "short_term_ref_pic_set_idx");
    6908             :                                 /*else
    6909             :                                         short_term_ref_pic_set_idx = 0;*/
    6910             :                         }
    6911       93611 :                         if (sps->long_term_ref_pics_present_flag) {
    6912             :                                 u8 DeltaPocMsbCycleLt[32];
    6913             :                                 u32 num_long_term_sps = 0;
    6914             :                                 u32 num_long_term_pics = 0;
    6915             : 
    6916             :                                 memset(DeltaPocMsbCycleLt, 0, sizeof(u8) * 32);
    6917             :                                 
    6918           0 :                                 if (sps->num_long_term_ref_pic_sps > 0) {
    6919           0 :                                         num_long_term_sps = gf_bs_read_ue_log(bs, "num_long_term_sps");
    6920             :                                 }
    6921           0 :                                 num_long_term_pics = gf_bs_read_ue_log(bs, "num_long_term_pics");
    6922             : 
    6923           0 :                                 for (i = 0; i < num_long_term_sps + num_long_term_pics; i++) {
    6924           0 :                                         if (i < num_long_term_sps) {
    6925           0 :                                                 if (sps->num_long_term_ref_pic_sps > 1)
    6926           0 :                                                         gf_bs_read_int_log_idx(bs, gf_get_bit_size(sps->num_long_term_ref_pic_sps), "lt_idx_sps", i);
    6927             :                                         }
    6928             :                                         else {
    6929           0 :                                                 gf_bs_read_int_log_idx(bs, sps->log2_max_pic_order_cnt_lsb, "PocLsbLt", i);
    6930           0 :                                                 gf_bs_read_int_log_idx(bs, 1, "UsedByCurrPicLt", i);
    6931             :                                         }
    6932           0 :                                         if (gf_bs_read_int_log_idx(bs, 1, "delta_poc_msb_present_flag", i)) {
    6933           0 :                                                 if (i == 0 || i == num_long_term_sps)
    6934           0 :                                                         DeltaPocMsbCycleLt[i] = gf_bs_read_ue_log_idx(bs, "DeltaPocMsbCycleLt", i);
    6935             :                                                 else
    6936           0 :                                                         DeltaPocMsbCycleLt[i] = gf_bs_read_ue_log_idx(bs, "DeltaPocMsbCycleLt", i) + DeltaPocMsbCycleLt[i - 1];
    6937             :                                         }
    6938             :                                 }
    6939             :                         }
    6940       93611 :                         if (sps->temporal_mvp_enable_flag)
    6941             :                                 slice_temporal_mvp_enabled_flag = gf_bs_read_int_log(bs, 1, "slice_temporal_mvp_enabled_flag");
    6942             :                 }
    6943       97808 :                 if (sps->sample_adaptive_offset_enabled_flag) {
    6944       97808 :                         u32 ChromaArrayType = sps->separate_colour_plane_flag ? 0 : sps->chroma_format_idc;
    6945             :                         slice_sao_luma_flag = gf_bs_read_int_log(bs, 1, "slice_sao_luma_flag");
    6946       97808 :                         if (ChromaArrayType != 0)
    6947             :                                 slice_sao_chroma_flag = gf_bs_read_int_log(bs, 1, "slice_sao_chroma_flag");
    6948             :                 }
    6949             : 
    6950       97808 :                 if (si->slice_type == GF_HEVC_SLICE_TYPE_P || si->slice_type == GF_HEVC_SLICE_TYPE_B) {
    6951             :                         //u32 NumPocTotalCurr;
    6952       93611 :                         num_ref_idx_l0_active = pps->num_ref_idx_l0_default_active;
    6953             :                         num_ref_idx_l1_active = 0;
    6954       93611 :                         if (si->slice_type == GF_HEVC_SLICE_TYPE_B)
    6955           0 :                                 num_ref_idx_l1_active = pps->num_ref_idx_l1_default_active;
    6956             : 
    6957       93611 :                         if (gf_bs_read_int_log(bs, 1, "num_ref_idx_active_override_flag")) {
    6958       49691 :                                 num_ref_idx_l0_active = 1 + gf_bs_read_ue_log(bs, "num_ref_idx_l0_active");
    6959       49691 :                                 if (si->slice_type == GF_HEVC_SLICE_TYPE_B)
    6960           0 :                                         num_ref_idx_l1_active = 1 + gf_bs_read_ue_log(bs, "num_ref_idx_l1_active");
    6961             :                         }
    6962             : 
    6963       93611 :                         if (pps->lists_modification_present_flag /*TODO: && NumPicTotalCurr > 1*/) {
    6964           0 :                                 if (!ref_pic_lists_modification(bs, si->slice_type, num_ref_idx_l0_active, num_ref_idx_l1_active)) {
    6965           0 :                                         GF_LOG(GF_LOG_WARNING, GF_LOG_CODING, ("[hevc] ref_pic_lists_modification( ) not implemented\n"));
    6966             :                                         return -1;
    6967             :                                 }
    6968             :                         }
    6969             : 
    6970       93611 :                         if (si->slice_type == GF_HEVC_SLICE_TYPE_B)
    6971           0 :                                 gf_bs_read_int_log(bs, 1, "mvd_l1_zero_flag");
    6972       93611 :                         if (pps->cabac_init_present_flag)
    6973           0 :                                 gf_bs_read_int_log(bs, 1, "cabac_init_flag");
    6974             : 
    6975       93611 :                         if (slice_temporal_mvp_enabled_flag) {
    6976             :                                 // When collocated_from_l0_flag is not present, it is inferred to be equal to 1.
    6977             :                                 Bool collocated_from_l0_flag = 1;
    6978           0 :                                 if (si->slice_type == GF_HEVC_SLICE_TYPE_B)
    6979             :                                         collocated_from_l0_flag = gf_bs_read_int_log(bs, 1, "collocated_from_l0_flag");
    6980             : 
    6981           0 :                                 if ((collocated_from_l0_flag && (num_ref_idx_l0_active > 1))
    6982           0 :                                         || (!collocated_from_l0_flag && (num_ref_idx_l1_active > 1))
    6983             :                                 ) {
    6984           0 :                                         gf_bs_read_ue_log(bs, "collocated_ref_idx");
    6985             :                                 }
    6986             :                         }
    6987             : 
    6988       93611 :                         if ((pps->weighted_pred_flag && si->slice_type == GF_HEVC_SLICE_TYPE_P)
    6989       93611 :                                 || (pps->weighted_bipred_flag && si->slice_type == GF_HEVC_SLICE_TYPE_B)
    6990             :                                 ) {
    6991           0 :                                 hevc_pred_weight_table(bs, hevc, si, pps, sps, num_ref_idx_l0_active, num_ref_idx_l1_active);
    6992             :                         }
    6993       93611 :                         gf_bs_read_ue_log(bs, "five_minus_max_num_merge_cand");
    6994             :                 }
    6995       97808 :                 si->slice_qp_delta_start_bits = (s32) (gf_bs_get_position(bs) - 1) * 8 + gf_bs_get_bit_position(bs);
    6996       97808 :                 si->slice_qp_delta = gf_bs_read_se_log(bs, "slice_qp_delta");
    6997             : 
    6998       97808 :                 if (pps->slice_chroma_qp_offsets_present_flag) {
    6999           0 :                         gf_bs_read_se_log(bs, "slice_cb_qp_offset");
    7000           0 :                         gf_bs_read_se_log(bs, "slice_cr_qp_offset");
    7001             :                 }
    7002       97808 :                 if (pps->deblocking_filter_override_enabled_flag) {
    7003             :                         deblocking_filter_override_flag = gf_bs_read_int_log(bs, 1, "deblocking_filter_override_flag");
    7004             :                 }
    7005             : 
    7006           0 :                 if (deblocking_filter_override_flag) {
    7007             :                         slice_deblocking_filter_disabled_flag = gf_bs_read_int_log(bs, 1, "slice_deblocking_filter_disabled_flag");
    7008           0 :                         if (!slice_deblocking_filter_disabled_flag) {
    7009           0 :                                 gf_bs_read_se_log(bs, "slice_beta_offset_div2");
    7010           0 :                                 gf_bs_read_se_log(bs, "slice_tc_offset_div2");
    7011             :                         }
    7012             :                 }
    7013       97808 :                 if (pps->loop_filter_across_slices_enabled_flag
    7014           0 :                         && (slice_sao_luma_flag || slice_sao_chroma_flag || !slice_deblocking_filter_disabled_flag)
    7015             :                 ) {
    7016           0 :                         gf_bs_read_int_log(bs, 1, "slice_loop_filter_across_slices_enabled_flag");
    7017             :                 }
    7018             :         }
    7019             :         //dependent slice segment
    7020             :         else {
    7021             :                 //if not asked to parse full header, abort
    7022           0 :                 if (!hevc->full_slice_header_parse) return 0;
    7023             :         }
    7024             : 
    7025       97808 :         si->entry_point_start_bits = ((u32)gf_bs_get_position(bs) - 1) * 8 + gf_bs_get_bit_position(bs);
    7026             : 
    7027       97808 :         if (pps->tiles_enabled_flag || pps->entropy_coding_sync_enabled_flag) {
    7028       79058 :                 u32 num_entry_point_offsets = gf_bs_read_ue_log(bs, "num_entry_point_offsets");
    7029       79058 :                 if (num_entry_point_offsets > 0) {
    7030           0 :                         u32 offset = gf_bs_read_ue_log(bs, "offset") + 1;
    7031           0 :                         u32 segments = offset >> 4;
    7032           0 :                         s32 remain = (offset & 15);
    7033             : 
    7034           0 :                         for (i = 0; i < num_entry_point_offsets; i++) {
    7035             :                                 //u32 res = 0;
    7036           0 :                                 for (j = 0; j < segments; j++) {
    7037             :                                         //res <<= 16;
    7038           0 :                                         /*res +=*/ gf_bs_read_int(bs, 16);
    7039             :                                 }
    7040           0 :                                 if (remain) {
    7041             :                                         //res <<= remain;
    7042           0 :                                         /* res += */ gf_bs_read_int(bs, remain);
    7043             :                                 }
    7044             :                                 // entry_point_offset = val + 1; // +1; // +1 to get the size
    7045             :                         }
    7046             :                 }
    7047             :         }
    7048             : 
    7049       97808 :         if (pps->slice_segment_header_extension_present_flag) {
    7050           0 :                 u32 size_ext = gf_bs_read_ue_log(bs, "size_ext");
    7051           0 :                 while (size_ext) {
    7052           0 :                         gf_bs_read_int(bs, 8);
    7053           0 :                         size_ext--;
    7054             :                 }
    7055             :         }
    7056             : 
    7057       97808 :         si->header_size_bits = (gf_bs_get_position(bs) - 1) * 8 + gf_bs_get_bit_position(bs); // av_parser.c modified on 16 jan. 2019 
    7058             : 
    7059       97808 :         if (gf_bs_read_int_log(bs, 1, "byte_align") == 0) {
    7060           0 :                 GF_LOG(GF_LOG_WARNING, GF_LOG_CODING, ("Error parsing slice header: byte_align not found at end of header !\n"));
    7061             :         }
    7062             : 
    7063       97808 :         gf_bs_align(bs);
    7064       97808 :         si->payload_start_offset = (s32)gf_bs_get_position(bs);
    7065       97808 :         return 0;
    7066             : }
    7067             : 
    7068        2099 : static void gf_hevc_vvc_parse_sei(char *buffer, u32 nal_size, HEVCState *hevc, VVCState *vvc)
    7069             : {
    7070             :         u32 ptype, psize, hdr;
    7071             :         u64 start;
    7072             :         GF_BitStream *bs;
    7073             : 
    7074        2099 :         hdr = buffer[0];
    7075        2099 :         if (((hdr & 0x7e) >> 1) != GF_HEVC_NALU_SEI_PREFIX) return;
    7076             : 
    7077        2099 :         bs = gf_bs_new(buffer, nal_size, GF_BITSTREAM_READ);
    7078        2099 :         gf_bs_enable_emulation_byte_removal(bs, GF_TRUE);
    7079             : 
    7080        2099 :         gf_bs_read_int(bs, 16);
    7081             : 
    7082             :         /*parse SEI*/
    7083        2131 :         while (gf_bs_available(bs)) {
    7084             :                 u32 consumed;
    7085             :                 ptype = 0;
    7086        2131 :                 while (gf_bs_peek_bits(bs, 8, 0)==0xFF) {
    7087           0 :                         gf_bs_read_int(bs, 8);
    7088           0 :                         ptype += 255;
    7089             :                 }
    7090        2131 :                 ptype += gf_bs_read_int(bs, 8);
    7091             :                 psize = 0;
    7092        2131 :                 while (gf_bs_peek_bits(bs, 8, 0)==0xFF) {
    7093           0 :                         gf_bs_read_int(bs, 8);
    7094           0 :                         psize += 255;
    7095             :                 }
    7096        2131 :                 psize += gf_bs_read_int(bs, 8);
    7097             : 
    7098        2131 :                 start = gf_bs_get_position(bs);
    7099        2131 :                 if (start+psize >= nal_size) {
    7100           0 :                         GF_LOG(GF_LOG_WARNING, GF_LOG_CODING, ("[%s] SEI user message type %d size error (%d but %d remain), skipping SEI message\n", hevc ? "HEVC" : "VVC", ptype, psize, nal_size-start));
    7101             :                         break;
    7102             :                 }
    7103             : 
    7104        2131 :                 switch (ptype) {
    7105           0 :                 case 4: /*user registered ITU-T T35*/
    7106           0 :                         if (hevc) {
    7107           0 :                                 avc_parse_itu_t_t35_sei(bs, &hevc->sei.dovi);
    7108             :                         }
    7109             :                         break;
    7110             :                 default:
    7111             :                         break;
    7112             :                 }
    7113             : 
    7114        2131 :                 gf_bs_align(bs);
    7115        2131 :                 consumed = (u32) (gf_bs_get_position(bs) - start);
    7116        2131 :                 psize-=consumed;
    7117        2131 :                 gf_bs_skip_bytes(bs, psize);
    7118        2131 :                 if (gf_bs_available(bs) <= 2)
    7119             :                         break;
    7120             :         }
    7121        2099 :         gf_bs_del(bs);
    7122             : }
    7123             : 
    7124        2099 : void gf_hevc_parse_sei(char *buffer, u32 nal_size, HEVCState *hevc)
    7125             : {
    7126        2099 :         gf_hevc_vvc_parse_sei(buffer, nal_size, hevc, NULL);
    7127        2099 : }
    7128             : 
    7129     1459386 : static void hevc_compute_poc(HEVCSliceInfo *si)
    7130             : {
    7131     1459386 :         u32 max_poc_lsb = 1 << (si->sps->log2_max_pic_order_cnt_lsb);
    7132             : 
    7133             :         /*POC reset for IDR frames, NOT for CRA*/
    7134     1459386 :         switch (si->nal_unit_type) {
    7135       59884 :         case GF_HEVC_NALU_SLICE_IDR_W_DLP:
    7136             :         case GF_HEVC_NALU_SLICE_IDR_N_LP:
    7137       59884 :                 si->poc_lsb_prev = 0;
    7138       59884 :                 si->poc_msb_prev = 0;
    7139       59884 :                 break;
    7140             :         }
    7141             : 
    7142     1459386 :         if ((si->poc_lsb < si->poc_lsb_prev) && (si->poc_lsb_prev - si->poc_lsb >= max_poc_lsb / 2))
    7143         527 :                 si->poc_msb = si->poc_msb_prev + max_poc_lsb;
    7144     1458859 :         else if ((si->poc_lsb > si->poc_lsb_prev) && (si->poc_lsb - si->poc_lsb_prev > max_poc_lsb / 2))
    7145         419 :                 si->poc_msb = si->poc_msb_prev - max_poc_lsb;
    7146             :         else
    7147     1458440 :                 si->poc_msb = si->poc_msb_prev;
    7148             : 
    7149     1459386 :         switch (si->nal_unit_type) {
    7150           0 :         case GF_HEVC_NALU_SLICE_BLA_W_LP:
    7151             :         case GF_HEVC_NALU_SLICE_BLA_W_DLP:
    7152             :         case GF_HEVC_NALU_SLICE_BLA_N_LP:
    7153           0 :                 si->poc_msb = 0;
    7154           0 :                 break;
    7155             :         }
    7156     1459386 :         si->poc = si->poc_msb + si->poc_lsb;
    7157     1459386 : }
    7158             : 
    7159             : 
    7160      942628 : static Bool hevc_parse_nal_header(GF_BitStream *bs, u8 *nal_unit_type, u8 *temporal_id, u8 *layer_id)
    7161             : {
    7162             :         u32 val;
    7163             :         val = gf_bs_read_int_log(bs, 1, "forbidden_zero");
    7164      942628 :         if (val) return GF_FALSE;
    7165             : 
    7166             :         val = gf_bs_read_int_log(bs, 6, "nuh_type");
    7167      942628 :         if (nal_unit_type) *nal_unit_type = val;
    7168             : 
    7169             :         val = gf_bs_read_int_log(bs, 6, "layerID");
    7170      942628 :         if (layer_id) *layer_id = val;
    7171             : 
    7172             :         val = gf_bs_read_int_log(bs, 3, "temporalID");
    7173      942628 :         if (!val)
    7174             :                 return GF_FALSE;
    7175      942628 :         val -= 1;
    7176      942628 :         if (temporal_id) *temporal_id = val;
    7177             :         return GF_TRUE;
    7178             : }
    7179             : 
    7180             : 
    7181        6152 : void hevc_profile_tier_level(GF_BitStream *bs, Bool ProfilePresentFlag, u8 MaxNumSubLayersMinus1, HEVC_ProfileTierLevel *ptl, u32 idx)
    7182             : {
    7183             :         u32 i;
    7184        6152 :         if (ProfilePresentFlag) {
    7185       12280 :                 ptl->profile_space = gf_bs_read_int_log_idx(bs, 2, "profile_space", idx);
    7186        6140 :                 ptl->tier_flag = gf_bs_read_int_log_idx(bs, 1, "tier_flag", idx);
    7187        6140 :                 ptl->profile_idc = gf_bs_read_int_log_idx(bs, 5, "profile_idc", idx);
    7188             : 
    7189        6140 :                 ptl->profile_compatibility_flag = gf_bs_read_int_log_idx(bs, 32, "profile_compatibility_flag", idx);
    7190             : 
    7191        6140 :                 ptl->general_progressive_source_flag = gf_bs_read_int_log_idx(bs, 1, "general_progressive_source_flag", idx);
    7192        6140 :                 ptl->general_interlaced_source_flag = gf_bs_read_int_log_idx(bs, 1, "general_interlaced_source_flag", idx);
    7193        6140 :                 ptl->general_non_packed_constraint_flag = gf_bs_read_int_log_idx(bs, 1, "general_non_packed_constraint_flag", idx);
    7194        6140 :                 ptl->general_frame_only_constraint_flag = gf_bs_read_int_log_idx(bs, 1, "general_frame_only_constraint_flag", idx);
    7195        6140 :                 ptl->general_reserved_44bits = gf_bs_read_long_int(bs, 44);
    7196             :         }
    7197        6152 :         ptl->level_idc = gf_bs_read_int_log(bs, 8, "level_idc");
    7198        8389 :         for (i = 0; i < MaxNumSubLayersMinus1; i++) {
    7199        4474 :                 ptl->sub_ptl[i].profile_present_flag = gf_bs_read_int_log_idx2(bs, 1, "profile_present_flag", idx, i);
    7200        2237 :                 ptl->sub_ptl[i].level_present_flag = gf_bs_read_int_log_idx2(bs, 1, "level_present_flag", idx, i);
    7201             :         }
    7202        6152 :         if (MaxNumSubLayersMinus1 > 0) {
    7203       15147 :                 for (i = MaxNumSubLayersMinus1; i < 8; i++) {
    7204       15147 :                         /*reserved_zero_2bits*/gf_bs_read_int(bs, 2);
    7205             :                 }
    7206             :         }
    7207             : 
    7208        2237 :         for (i = 0; i < MaxNumSubLayersMinus1; i++) {
    7209        2237 :                 if (ptl->sub_ptl[i].profile_present_flag) {
    7210           0 :                         ptl->sub_ptl[i].profile_space = gf_bs_read_int_log_idx2(bs, 2, "sublayer_profile_space", idx, i);
    7211           0 :                         ptl->sub_ptl[i].tier_flag = gf_bs_read_int_log_idx2(bs, 1, "sublayer_tier_flag", idx, i);
    7212           0 :                         ptl->sub_ptl[i].profile_idc = gf_bs_read_int_log_idx2(bs, 5, "sublayer_profile_idc", idx, i);
    7213           0 :                         ptl->sub_ptl[i].profile_compatibility_flag = gf_bs_read_int_log_idx2(bs, 32, "sublayer_profile_compatibility_flag", idx, i);
    7214           0 :                         /*ptl->sub_ptl[i].progressive_source_flag =*/ gf_bs_read_int_log_idx2(bs, 1, "sublayer_progressive_source_flag", idx, i);
    7215           0 :                         /*ptl->sub_ptl[i].interlaced_source_flag =*/ gf_bs_read_int_log_idx2(bs, 1, "sublayer_interlaced_source_flag", idx, i);
    7216           0 :                         /*ptl->sub_ptl[i].non_packed_constraint_flag =*/ gf_bs_read_int_log_idx2(bs, 1, "sublayer_non_packed_constraint_flag", idx, i);
    7217           0 :                         /*ptl->sub_ptl[i].frame_only_constraint_flag =*/ gf_bs_read_int_log_idx2(bs, 1, "sublayer_frame_only_constraint_flag", idx, i);
    7218           0 :                         /*ptl->sub_ptl[i].reserved_44bits =*/ gf_bs_read_long_int(bs, 44);
    7219             :                 }
    7220        2237 :                 if (ptl->sub_ptl[i].level_present_flag)
    7221           0 :                         ptl->sub_ptl[i].level_idc = gf_bs_read_int_log_idx2(bs, 8, "sublayer_level_idc", idx, i);
    7222             :         }
    7223        6152 : }
    7224             : 
    7225             : static u32 scalability_type_to_idx(HEVC_VPS *vps, u32 scalability_type)
    7226             : {
    7227             :         u32 idx = 0, type;
    7228          24 :         for (type = 0; type < scalability_type; type++) {
    7229          24 :                 idx += (vps->scalability_mask[type] ? 1 : 0);
    7230             :         }
    7231             :         return idx;
    7232             : }
    7233             : 
    7234             : #define LHVC_VIEW_ORDER_INDEX  1
    7235             : #define LHVC_SCALABILITY_INDEX  2
    7236             : 
    7237             : static u32 lhvc_get_scalability_id(HEVC_VPS *vps, u32 layer_id_in_vps, u32 scalability_type)
    7238             : {
    7239             :         u32 idx;
    7240          24 :         if (!vps->scalability_mask[scalability_type]) return 0;
    7241             :         idx = scalability_type_to_idx(vps, scalability_type);
    7242          24 :         return vps->dimension_id[layer_id_in_vps][idx];
    7243             : }
    7244             : 
    7245             : static u32 lhvc_get_view_index(HEVC_VPS *vps, u32 id)
    7246             : {
    7247          12 :         return lhvc_get_scalability_id(vps, vps->layer_id_in_vps[id], LHVC_VIEW_ORDER_INDEX);
    7248             : }
    7249             : 
    7250          12 : static u32 lhvc_get_num_views(HEVC_VPS *vps)
    7251             : {
    7252             :         u32 numViews = 1, i;
    7253          36 :         for (i = 0; i < vps->max_layers; i++) {
    7254          24 :                 u32 layer_id = vps->layer_id_in_nuh[i];
    7255          48 :                 if (i > 0 && (lhvc_get_view_index(vps, layer_id) != lhvc_get_scalability_id(vps, i - 1, LHVC_VIEW_ORDER_INDEX))) {
    7256          12 :                         numViews++;
    7257             :                 }
    7258             :         }
    7259          12 :         return numViews;
    7260             : }
    7261             : 
    7262          20 : static void lhvc_parse_rep_format(HEVC_RepFormat *fmt, GF_BitStream *bs, u32 idx)
    7263             : {
    7264             :         u8 chroma_bitdepth_present_flag;
    7265          40 :         fmt->pic_width_luma_samples = gf_bs_read_int_log_idx(bs, 16, "pic_width_luma_samples", idx);
    7266          20 :         fmt->pic_height_luma_samples = gf_bs_read_int_log_idx(bs, 16, "pic_height_luma_samples", idx);
    7267          20 :         chroma_bitdepth_present_flag = gf_bs_read_int_log_idx(bs, 1, "chroma_bitdepth_present_flag", idx);
    7268          20 :         if (chroma_bitdepth_present_flag) {
    7269          20 :                 fmt->chroma_format_idc = gf_bs_read_int_log_idx(bs, 2, "chroma_format_idc", idx);
    7270             : 
    7271          20 :                 if (fmt->chroma_format_idc == 3)
    7272           0 :                         fmt->separate_colour_plane_flag = gf_bs_read_int_log_idx(bs, 1, "separate_colour_plane_flag", idx);
    7273          20 :                 fmt->bit_depth_luma = 8 + gf_bs_read_int_log_idx(bs, 4, "bit_depth_luma_minus8", idx);
    7274          20 :                 fmt->bit_depth_chroma = 8 + gf_bs_read_int_log_idx(bs, 4, "bit_depth_chroma_minus8", idx);
    7275             :         }
    7276          20 :         if (gf_bs_read_int_log_idx(bs, 1, "conformance_window_vps_flag", idx)) {
    7277          20 :                 gf_bs_read_ue_log_idx(bs, "conf_win_vps_left_offset", idx);
    7278          20 :                 gf_bs_read_ue_log_idx(bs, "conf_win_vps_right_offset", idx);
    7279          20 :                 gf_bs_read_ue_log_idx(bs, "conf_win_vps_top_offset", idx);
    7280          20 :                 gf_bs_read_ue_log_idx(bs, "conf_win_vps_bottom_offset", idx);
    7281             :         }
    7282          20 : }
    7283             : 
    7284             : 
    7285          12 : static Bool hevc_parse_vps_extension(HEVC_VPS *vps, GF_BitStream *bs)
    7286             : {
    7287             :         u8 splitting_flag, vps_nuh_layer_id_present_flag, view_id_len;
    7288             :         u32 i, j, num_scalability_types, num_add_olss, num_add_layer_set, num_indepentdent_layers, nb_bits, default_output_layer_idc = 0;
    7289             :         u8 dimension_id_len[16], dim_bit_offset[16];
    7290             :         u8 /*avc_base_layer_flag, */NumLayerSets, /*default_one_target_output_layer_flag, */rep_format_idx_present_flag, ols_ids_to_ls_idx;
    7291             :         u8 layer_set_idx_for_ols_minus1[MAX_LHVC_LAYERS];
    7292             :         u8 nb_output_layers_in_output_layer_set[MAX_LHVC_LAYERS + 1];
    7293             :         u8 ols_highest_output_layer_id[MAX_LHVC_LAYERS + 1];
    7294             : 
    7295             :         u32 k, d, r, p, iNuhLId, jNuhLId;
    7296             :         u8 num_direct_ref_layers[64], num_pred_layers[64], num_layers_in_tree_partition[MAX_LHVC_LAYERS];
    7297             :         u8 dependency_flag[MAX_LHVC_LAYERS][MAX_LHVC_LAYERS], id_pred_layers[64][MAX_LHVC_LAYERS];
    7298             :         //      u8 num_ref_layers[64];
    7299             :         //      u8 tree_partition_layer_id[MAX_LHVC_LAYERS][MAX_LHVC_LAYERS];
    7300             :         //      u8 id_ref_layers[64][MAX_LHVC_LAYERS];
    7301             :         //      u8 id_direct_ref_layers[64][MAX_LHVC_LAYERS];
    7302             :         u8 layer_id_in_list_flag[64];
    7303             :         Bool OutputLayerFlag[MAX_LHVC_LAYERS][MAX_LHVC_LAYERS];
    7304             : 
    7305          12 :         vps->vps_extension_found = 1;
    7306          12 :         if ((vps->max_layers > 1) && vps->base_layer_internal_flag)
    7307          12 :                 hevc_profile_tier_level(bs, 0, vps->max_sub_layers - 1, &vps->ext_ptl[0], 0);
    7308             : 
    7309          12 :         splitting_flag = gf_bs_read_int_log(bs, 1, "splitting_flag");
    7310             :         num_scalability_types = 0;
    7311         204 :         for (i = 0; i < 16; i++) {
    7312         384 :                 vps->scalability_mask[i] = gf_bs_read_int_log_idx(bs, 1, "scalability_mask", i);
    7313         192 :                 num_scalability_types += vps->scalability_mask[i];
    7314             :         }
    7315          12 :         if (num_scalability_types >= 16) {
    7316             :                 num_scalability_types = 16;
    7317             :         }
    7318          12 :         dimension_id_len[0] = 0;
    7319          24 :         for (i = 0; i < (num_scalability_types - splitting_flag); i++) {
    7320          24 :                 dimension_id_len[i] = 1 + gf_bs_read_int_log_idx(bs, 3, "dimension_id_len_minus1", i);
    7321             :         }
    7322             : 
    7323          12 :         if (splitting_flag) {
    7324           0 :                 for (i = 0; i < num_scalability_types; i++) {
    7325           0 :                         dim_bit_offset[i] = 0;
    7326           0 :                         for (j = 0; j < i; j++)
    7327           0 :                                 dim_bit_offset[i] += dimension_id_len[j];
    7328             :                 }
    7329           0 :                 dimension_id_len[num_scalability_types - 1] = 1 + (5 - dim_bit_offset[num_scalability_types - 1]);
    7330           0 :                 dim_bit_offset[num_scalability_types] = 6;
    7331             :         }
    7332             : 
    7333          12 :         vps_nuh_layer_id_present_flag = gf_bs_read_int_log(bs, 1, "vps_nuh_layer_id_present_flag");
    7334          12 :         vps->layer_id_in_nuh[0] = 0;
    7335          12 :         vps->layer_id_in_vps[0] = 0;
    7336          24 :         for (i = 1; i < vps->max_layers; i++) {
    7337          12 :                 if (vps_nuh_layer_id_present_flag) {
    7338           0 :                         vps->layer_id_in_nuh[i] = gf_bs_read_int_log_idx(bs, 6, "layer_id_in_nuh", i);
    7339             :                 }
    7340             :                 else {
    7341          12 :                         vps->layer_id_in_nuh[i] = i;
    7342             :                 }
    7343          12 :                 vps->layer_id_in_vps[vps->layer_id_in_nuh[i]] = i;
    7344             : 
    7345          12 :                 if (!splitting_flag) {
    7346          12 :                         for (j = 0; j < num_scalability_types; j++) {
    7347          24 :                                 vps->dimension_id[i][j] = gf_bs_read_int_log_idx2(bs, dimension_id_len[j], "dimension_id", i, j);
    7348             :                         }
    7349             :                 }
    7350             :         }
    7351             : 
    7352          12 :         if (splitting_flag) {
    7353           0 :                 for (i = 0; i < vps->max_layers; i++)
    7354           0 :                         for (j = 0; j < num_scalability_types; j++)
    7355           0 :                                 vps->dimension_id[i][j] = ((vps->layer_id_in_nuh[i] & ((1 << dim_bit_offset[j + 1]) - 1)) >> dim_bit_offset[j]);
    7356             :         }
    7357             :         else {
    7358          12 :                 for (j = 0; j < num_scalability_types; j++)
    7359          12 :                         vps->dimension_id[0][j] = 0;
    7360             :         }
    7361             : 
    7362          12 :         view_id_len = gf_bs_read_int_log(bs, 4, "view_id_len");
    7363          12 :         if (view_id_len > 0) {
    7364           8 :                 for (i = 0; i < lhvc_get_num_views(vps); i++) {
    7365           8 :                         gf_bs_read_int_log_idx(bs, view_id_len, "view_id_val", i);
    7366             :                 }
    7367             :         }
    7368             : 
    7369          12 :         for (i = 1; i < vps->max_layers; i++) {
    7370          12 :                 for (j = 0; j < i; j++) {
    7371          24 :                         vps->direct_dependency_flag[i][j] = gf_bs_read_int_log_idx(bs, 1, "direct_dependency_flag", i);
    7372             :                 }
    7373             :         }
    7374             : 
    7375             :         //we do the test on MAX_LHVC_LAYERS and break in the loop to avoid a wrong GCC 4.8 warning on array bounds
    7376          24 :         for (i = 0; i < MAX_LHVC_LAYERS; i++) {
    7377          36 :                 if (i >= vps->max_layers) break;
    7378          48 :                 for (j = 0; j < vps->max_layers; j++) {
    7379          48 :                         dependency_flag[i][j] = vps->direct_dependency_flag[i][j];
    7380          72 :                         for (k = 0; k < i; k++)
    7381          24 :                                 if (vps->direct_dependency_flag[i][k] && vps->direct_dependency_flag[k][j])
    7382           0 :                                         dependency_flag[i][j] = 1;
    7383             :                 }
    7384             :         }
    7385             : 
    7386          24 :         for (i = 0; i < vps->max_layers; i++) {
    7387          24 :                 iNuhLId = vps->layer_id_in_nuh[i];
    7388             :                 d = r = p = 0;
    7389          72 :                 for (j = 0; j < vps->max_layers; j++) {
    7390          48 :                         jNuhLId = vps->layer_id_in_nuh[j];
    7391          48 :                         if (vps->direct_dependency_flag[i][j]) {
    7392             :                                 //                              id_direct_ref_layers[iNuhLId][d] = jNuhLId;
    7393          12 :                                 d++;
    7394             :                         }
    7395             :                         if (dependency_flag[i][j]) {
    7396             :                                 //                              id_ref_layers[iNuhLId][r] = jNuhLId;
    7397             :                                 r++;
    7398             :                         }
    7399             : 
    7400          48 :                         if (dependency_flag[j][i])
    7401          12 :                                 id_pred_layers[iNuhLId][p++] = jNuhLId;
    7402             :                 }
    7403          24 :                 num_direct_ref_layers[iNuhLId] = d;
    7404             :                 //              num_ref_layers[iNuhLId] = r;
    7405          24 :                 num_pred_layers[iNuhLId] = p;
    7406             :         }
    7407             : 
    7408             :         memset(layer_id_in_list_flag, 0, 64 * sizeof(u8));
    7409             :         k = 0; //num_indepentdent_layers
    7410          36 :         for (i = 0; i < vps->max_layers; i++) {
    7411          24 :                 iNuhLId = vps->layer_id_in_nuh[i];
    7412          24 :                 if (!num_direct_ref_layers[iNuhLId]) {
    7413             :                         u32 h = 1;
    7414             :                         //tree_partition_layer_id[k][0] = iNuhLId;
    7415          12 :                         for (j = 0; j < num_pred_layers[iNuhLId]; j++) {
    7416          12 :                                 u32 predLId = id_pred_layers[iNuhLId][j];
    7417          12 :                                 if (!layer_id_in_list_flag[predLId]) {
    7418             :                                         //tree_partition_layer_id[k][h++] = predLId;
    7419          12 :                                         layer_id_in_list_flag[predLId] = 1;
    7420             :                                 }
    7421             :                         }
    7422          12 :                         num_layers_in_tree_partition[k++] = h;
    7423             :                 }
    7424             :         }
    7425             :         num_indepentdent_layers = k;
    7426             : 
    7427             :         num_add_layer_set = 0;
    7428          12 :         if (num_indepentdent_layers > 1)
    7429           0 :                 num_add_layer_set = gf_bs_read_ue_log(bs, "num_add_layer_set");
    7430             : 
    7431          12 :         for (i = 0; i < num_add_layer_set; i++)
    7432           0 :                 for (j = 1; j < num_indepentdent_layers; j++) {
    7433             :                         nb_bits = 1;
    7434           0 :                         while ((1 << nb_bits) < (num_layers_in_tree_partition[j] + 1))
    7435           0 :                                 nb_bits++;
    7436           0 :                         gf_bs_read_int_log_idx2(bs, nb_bits, "highest_layer_idx_plus1", i, j);
    7437             :                 }
    7438             : 
    7439             : 
    7440          12 :         if (gf_bs_read_int_log(bs, 1, "vps_sub_layers_max_minus1_present_flag")) {
    7441          16 :                 for (i = 0; i < vps->max_layers; i++) {
    7442          16 :                         gf_bs_read_int_log_idx(bs, 3, "sub_layers_vps_max_minus1", i);
    7443             :                 }
    7444             :         }
    7445             : 
    7446          12 :         if (gf_bs_read_int_log(bs, 1, "max_tid_ref_present_flag")) {
    7447          16 :                 for (i = 0; i < (vps->max_layers - 1); i++) {
    7448          16 :                         for (j = i + 1; j < vps->max_layers; j++) {
    7449           8 :                                 if (vps->direct_dependency_flag[j][i])
    7450           8 :                                         gf_bs_read_int_log_idx2(bs, 3, "max_tid_il_ref_pics_plus1", i, j);
    7451             :                         }
    7452             :                 }
    7453             :         }
    7454          12 :         gf_bs_read_int_log(bs, 1, "default_ref_layers_active_flag");
    7455             : 
    7456          12 :         vps->num_profile_tier_level = 1 + gf_bs_read_ue_log(bs, "num_profile_tier_level");
    7457          12 :         if (vps->num_profile_tier_level > MAX_LHVC_LAYERS) {
    7458           0 :                 GF_LOG(GF_LOG_ERROR, GF_LOG_CODING, ("[HEVC] Wrong number of PTLs in VPS %d\n", vps->num_profile_tier_level));
    7459           0 :                 vps->num_profile_tier_level = 1;
    7460           0 :                 return GF_FALSE;
    7461             :         }
    7462             : 
    7463          24 :         for (i = vps->base_layer_internal_flag ? 2 : 1; i < vps->num_profile_tier_level; i++) {
    7464          12 :                 Bool vps_profile_present_flag = gf_bs_read_int_log_idx(bs, 1, "vps_profile_present_flag", i);
    7465          12 :                 hevc_profile_tier_level(bs, vps_profile_present_flag, vps->max_sub_layers - 1, &vps->ext_ptl[i - 1], i-1);
    7466             :         }
    7467             : 
    7468          12 :         NumLayerSets = vps->num_layer_sets + num_add_layer_set;
    7469             :         num_add_olss = 0;
    7470             : 
    7471          12 :         if (NumLayerSets > 1) {
    7472          12 :                 num_add_olss = gf_bs_read_ue_log(bs, "num_add_olss");
    7473             :                 default_output_layer_idc = gf_bs_read_int_log(bs, 2, "default_output_layer_idc");
    7474          12 :                 default_output_layer_idc = default_output_layer_idc < 2 ? default_output_layer_idc : 2;
    7475             :         }
    7476          12 :         vps->num_output_layer_sets = num_add_olss + NumLayerSets;
    7477             : 
    7478             : 
    7479          12 :         layer_set_idx_for_ols_minus1[0] = 1;
    7480          12 :         vps->output_layer_flag[0][0] = 1;
    7481             : 
    7482          36 :         for (i = 0; i < vps->num_output_layer_sets; i++) {
    7483          24 :                 if ((NumLayerSets > 2) && (i >= NumLayerSets)) {
    7484             :                         nb_bits = 1;
    7485           0 :                         while ((1 << nb_bits) < (NumLayerSets - 1))
    7486           0 :                                 nb_bits++;
    7487           0 :                         layer_set_idx_for_ols_minus1[i] = gf_bs_read_int_log_idx(bs, nb_bits, "layer_set_idx_for_ols_minus1", i);
    7488             :                 }
    7489             :                 else
    7490          24 :                         layer_set_idx_for_ols_minus1[i] = 0;
    7491          24 :                 ols_ids_to_ls_idx = i < NumLayerSets ? i : layer_set_idx_for_ols_minus1[i] + 1;
    7492             : 
    7493          24 :                 if ((i > (vps->num_layer_sets - 1)) || (default_output_layer_idc == 2)) {
    7494           0 :                         for (j = 0; j < vps->num_layers_in_id_list[ols_ids_to_ls_idx]; j++)
    7495           0 :                                 vps->output_layer_flag[i][j] = gf_bs_read_int_log_idx2(bs, 1, "output_layer_flag", i, j);
    7496             :                 }
    7497             : 
    7498          24 :                 if ((default_output_layer_idc == 0) || (default_output_layer_idc == 1)) {
    7499          36 :                         for (j = 0; j < vps->num_layers_in_id_list[ols_ids_to_ls_idx]; j++) {
    7500          36 :                                 if ((default_output_layer_idc == 0) || (vps->LayerSetLayerIdList[i][j] == vps->LayerSetLayerIdListMax[i]))
    7501          24 :                                         OutputLayerFlag[i][j] = GF_TRUE;
    7502             :                                 else
    7503          12 :                                         OutputLayerFlag[i][j] = GF_FALSE;
    7504             :                         }
    7505             :                 }
    7506             : 
    7507          36 :                 for (j = 0; j < vps->num_layers_in_id_list[ols_ids_to_ls_idx]; j++) {
    7508          36 :                         if (OutputLayerFlag[i][j]) {
    7509             :                                 u32 curLayerID;
    7510          24 :                                 vps->necessary_layers_flag[i][j] = GF_TRUE;
    7511          24 :                                 curLayerID = vps->LayerSetLayerIdList[i][j];
    7512          36 :                                 for (k = 0; k < j; k++) {
    7513          12 :                                         u32 refLayerId = vps->LayerSetLayerIdList[i][k];
    7514          12 :                                         if (dependency_flag[vps->layer_id_in_vps[curLayerID]][vps->layer_id_in_vps[refLayerId]])
    7515          12 :                                                 vps->necessary_layers_flag[i][k] = GF_TRUE;
    7516             :                                 }
    7517             :                         }
    7518             :                 }
    7519          24 :                 vps->num_necessary_layers[i] = 0;
    7520          60 :                 for (j = 0; j < vps->num_layers_in_id_list[ols_ids_to_ls_idx]; j++) {
    7521          36 :                         if (vps->necessary_layers_flag[i][j])
    7522          36 :                                 vps->num_necessary_layers[i] += 1;
    7523             :                 }
    7524             : 
    7525          24 :                 if (i == 0) {
    7526          12 :                         if (vps->base_layer_internal_flag) {
    7527          12 :                                 if (vps->max_layers > 1)
    7528          12 :                                         vps->profile_tier_level_idx[0][0] = 1;
    7529             :                                 else
    7530           0 :                                         vps->profile_tier_level_idx[0][0] = 0;
    7531             :                         }
    7532          12 :                         continue;
    7533             :                 }
    7534             :                 nb_bits = 1;
    7535          24 :                 while ((u32)(1 << nb_bits) < vps->num_profile_tier_level)
    7536          12 :                         nb_bits++;
    7537          24 :                 for (j = 0; j < vps->num_layers_in_id_list[ols_ids_to_ls_idx]; j++)
    7538          24 :                         if (vps->necessary_layers_flag[i][j] && vps->num_profile_tier_level)
    7539          48 :                                 vps->profile_tier_level_idx[i][j] = gf_bs_read_int_log_idx2(bs, nb_bits, "profile_tier_level_idx", i, j);
    7540             :                         else
    7541           0 :                                 vps->profile_tier_level_idx[i][j] = 0;
    7542             : 
    7543             : 
    7544          12 :                 nb_output_layers_in_output_layer_set[i] = 0;
    7545          36 :                 for (j = 0; j < vps->num_layers_in_id_list[ols_ids_to_ls_idx]; j++) {
    7546          24 :                         nb_output_layers_in_output_layer_set[i] += OutputLayerFlag[i][j];
    7547          24 :                         if (OutputLayerFlag[i][j]) {
    7548          12 :                                 ols_highest_output_layer_id[i] = vps->LayerSetLayerIdList[ols_ids_to_ls_idx][j];
    7549             :                         }
    7550             :                 }
    7551          12 :                 if (nb_output_layers_in_output_layer_set[i] == 1 && ols_highest_output_layer_id[i] > 0)
    7552          24 :                         vps->alt_output_layer_flag[i] = gf_bs_read_int_log_idx(bs, 1, "alt_output_layer_flag", i);
    7553             :         }
    7554             : 
    7555          12 :         vps->num_rep_formats = 1 + gf_bs_read_ue_log(bs, "num_rep_formats_minus1");
    7556          12 :         if (vps->num_rep_formats > 16) {
    7557           0 :                 GF_LOG(GF_LOG_ERROR, GF_LOG_CODING, ("[HEVC] Wrong number of rep formats in VPS %d\n", vps->num_rep_formats));
    7558           0 :                 vps->num_rep_formats = 0;
    7559           0 :                 return GF_FALSE;
    7560             :         }
    7561             : 
    7562          20 :         for (i = 0; i < vps->num_rep_formats; i++) {
    7563          20 :                 lhvc_parse_rep_format(&vps->rep_formats[i], bs, i);
    7564             :         }
    7565          12 :         if (vps->num_rep_formats > 1)
    7566           8 :                 rep_format_idx_present_flag = gf_bs_read_int_log(bs, 1, "rep_format_idx_present_flag");
    7567             :         else
    7568             :                 rep_format_idx_present_flag = 0;
    7569             : 
    7570          12 :         vps->rep_format_idx[0] = 0;
    7571             :         nb_bits = 1;
    7572          24 :         while ((u32)(1 << nb_bits) < vps->num_rep_formats)
    7573           0 :                 nb_bits++;
    7574          24 :         for (i = vps->base_layer_internal_flag ? 1 : 0; i < vps->max_layers; i++) {
    7575          12 :                 if (rep_format_idx_present_flag) {
    7576          16 :                         vps->rep_format_idx[i] = gf_bs_read_int_log_idx(bs, nb_bits, "rep_format_idx", i);
    7577             :                 }
    7578             :                 else {
    7579           4 :                         vps->rep_format_idx[i] = i < vps->num_rep_formats - 1 ? i : vps->num_rep_formats - 1;
    7580             :                 }
    7581             :         }
    7582             :         //TODO - we don't use the rest ...
    7583             : 
    7584             :         return GF_TRUE;
    7585             : }
    7586             : 
    7587           0 : static void sub_layer_hrd_parameters(GF_BitStream *bs, int subLayerId, u32 cpb_cnt, Bool sub_pic_hrd_params_present_flag, u32 idx1, u32 idx2)
    7588             : {
    7589             :         u32 i;
    7590           0 :         if (!gf_bs_available(bs)) return;
    7591             : 
    7592           0 :         for (i = 0; i <= cpb_cnt; i++) {
    7593           0 :                 gf_bs_read_ue_log_idx3(bs, "bit_rate_value_minus1", idx1, idx2, i);
    7594           0 :                 gf_bs_read_ue_log_idx3(bs, "cpb_size_value_minus1", idx1, idx2, i);
    7595           0 :                 if (sub_pic_hrd_params_present_flag) {
    7596           0 :                         gf_bs_read_ue_log_idx3(bs, "cpb_size_du_value_minus1", idx1, idx2, i);
    7597           0 :                         gf_bs_read_ue_log_idx3(bs, "bit_rate_du_value_minus1", idx1, idx2, i);
    7598             :                 }
    7599           0 :                 gf_bs_read_int_log_idx3(bs, 1, "cbr_flag", idx1, idx2, i);
    7600             :         }
    7601             : }
    7602             : 
    7603           0 : static void hevc_parse_hrd_parameters(GF_BitStream *bs, Bool commonInfPresentFlag, int maxNumSubLayersMinus1, u32 idx)
    7604             : {
    7605             :         int i;
    7606             :         Bool nal_hrd_parameters_present_flag = GF_FALSE;
    7607             :         Bool vcl_hrd_parameters_present_flag = GF_FALSE;
    7608             :         Bool sub_pic_hrd_params_present_flag = GF_FALSE;
    7609             : 
    7610           0 :         if (commonInfPresentFlag) {
    7611           0 :                 nal_hrd_parameters_present_flag = gf_bs_read_int_log_idx(bs, 1, "nal_hrd_parameters_present_flag", idx);
    7612             :                 vcl_hrd_parameters_present_flag = gf_bs_read_int_log_idx(bs, 1, "vcl_hrd_parameters_present_flag", idx);
    7613           0 :                 if (nal_hrd_parameters_present_flag || vcl_hrd_parameters_present_flag) {
    7614             :                         sub_pic_hrd_params_present_flag = gf_bs_read_int_log_idx(bs, 1, "sub_pic_hrd_params_present_flag", idx);
    7615           0 :                         if (sub_pic_hrd_params_present_flag) {
    7616           0 :                                 gf_bs_read_int_log_idx(bs, 8, "tick_divisor_minus2", idx);
    7617           0 :                                 gf_bs_read_int_log_idx(bs, 5, "du_cpb_removal_delay_increment_length_minus1", idx);
    7618           0 :                                 gf_bs_read_int_log_idx(bs, 1, "sub_pic_cpb_params_in_pic_timing_sei_flag", idx);
    7619           0 :                                 gf_bs_read_int_log_idx(bs, 5, "dpb_output_delay_du_length_minus1", idx);
    7620             :                         }
    7621           0 :                         gf_bs_read_int_log_idx(bs, 4, "bit_rate_scale", idx);
    7622           0 :                         gf_bs_read_int_log_idx(bs, 4, "cpb_size_scale", idx);
    7623           0 :                         if (sub_pic_hrd_params_present_flag) {
    7624           0 :                                 gf_bs_read_int_log_idx(bs, 4, "cpb_size_du_scale", idx);
    7625             :                         }
    7626           0 :                         gf_bs_read_int_log_idx(bs, 5, "initial_cpb_removal_delay_length_minus1", idx);
    7627           0 :                         gf_bs_read_int_log_idx(bs, 5, "au_cpb_removal_delay_length_minus1", idx);
    7628           0 :                         gf_bs_read_int_log_idx(bs, 5, "dpb_output_delay_length_minus1", idx);
    7629             :                 }
    7630             :         }
    7631           0 :         for (i = 0; i <= maxNumSubLayersMinus1; i++) {
    7632           0 :                 Bool fixed_pic_rate_general_flag_i = gf_bs_read_int_log_idx(bs, 1, "fixed_pic_rate_general_flag", idx);
    7633             :                 Bool fixed_pic_rate_within_cvs_flag_i = GF_TRUE;
    7634             :                 Bool low_delay_hrd_flag_i = GF_FALSE;
    7635             :                 u32 cpb_cnt_minus1_i = 0;
    7636           0 :                 if (!fixed_pic_rate_general_flag_i) {
    7637             :                         fixed_pic_rate_within_cvs_flag_i = gf_bs_read_int_log_idx(bs, 1, "fixed_pic_rate_within_cvs_flag", idx);
    7638             :                 }
    7639           0 :                 if (fixed_pic_rate_within_cvs_flag_i)
    7640           0 :                         gf_bs_read_ue_log_idx(bs, "elemental_duration_in_tc_minus1", idx);
    7641             :                 else
    7642             :                         low_delay_hrd_flag_i = gf_bs_read_int_log_idx(bs, 1, "low_delay_hrd_flag", idx);
    7643           0 :                 if (!low_delay_hrd_flag_i) {
    7644           0 :                         cpb_cnt_minus1_i = gf_bs_read_ue_log_idx(bs, "cpb_cnt_minus1", idx);
    7645             :                 }
    7646           0 :                 if (nal_hrd_parameters_present_flag) {
    7647           0 :                         sub_layer_hrd_parameters(bs, i, cpb_cnt_minus1_i, sub_pic_hrd_params_present_flag, idx, i);
    7648             :                 }
    7649           0 :                 if (vcl_hrd_parameters_present_flag) {
    7650           0 :                         sub_layer_hrd_parameters(bs, i, cpb_cnt_minus1_i, sub_pic_hrd_params_present_flag, idx, i);
    7651             :                 }
    7652             :         }
    7653           0 : }
    7654             : 
    7655        3068 : static s32 gf_hevc_read_vps_bs_internal(GF_BitStream *bs, HEVCState *hevc, Bool stop_at_vps_ext)
    7656             : {
    7657             :         u8 vps_sub_layer_ordering_info_present_flag, vps_extension_flag;
    7658             :         u32 i, j;
    7659             :         s32 vps_id;
    7660             :         HEVC_VPS *vps;
    7661             :         u8 layer_id_included_flag[MAX_LHVC_LAYERS][64];
    7662             : 
    7663             :         //nalu header already parsed
    7664        3068 :         vps_id = gf_bs_read_int_log(bs, 4, "vps_id");
    7665             : 
    7666        3068 :         if ((vps_id<0) || (vps_id >= 16)) return -1;
    7667             : 
    7668        3068 :         vps = &hevc->vps[vps_id];
    7669        3068 :         vps->bit_pos_vps_extensions = -1;
    7670        3068 :         if (!vps->state) {
    7671         352 :                 vps->id = vps_id;
    7672         352 :                 vps->state = 1;
    7673             :         }
    7674             : 
    7675        3068 :         vps->base_layer_internal_flag = gf_bs_read_int_log(bs, 1, "base_layer_internal_flag");
    7676        3068 :         vps->base_layer_available_flag = gf_bs_read_int_log(bs, 1, "base_layer_available_flag");
    7677        3068 :         vps->max_layers = 1 + gf_bs_read_int_log(bs, 6, "max_layers_minus1");
    7678        3068 :         if (vps->max_layers > MAX_LHVC_LAYERS) {
    7679           0 :                 GF_LOG(GF_LOG_ERROR, GF_LOG_CODING, ("[HEVC] sorry, %d layers in VPS but only %d supported\n", vps->max_layers, MAX_LHVC_LAYERS));
    7680             :                 return -1;
    7681             :         }
    7682        3068 :         vps->max_sub_layers = gf_bs_read_int_log(bs, 3, "max_sub_layers_minus1") + 1;
    7683        3068 :         vps->temporal_id_nesting = gf_bs_read_int_log(bs, 1, "temporal_id_nesting");
    7684        3068 :         gf_bs_read_int_log(bs, 16, "vps_reserved_ffff_16bits");
    7685        3068 :         hevc_profile_tier_level(bs, 1, vps->max_sub_layers - 1, &vps->ptl, 0);
    7686             : 
    7687        3068 :         vps_sub_layer_ordering_info_present_flag = gf_bs_read_int_log(bs, 1, "vps_sub_layer_ordering_info_present_flag");
    7688        6166 :         for (i = (vps_sub_layer_ordering_info_present_flag ? 0 : vps->max_sub_layers - 1); i < vps->max_sub_layers; i++) {
    7689        3098 :                 gf_bs_read_ue_log_idx(bs, "vps_max_dec_pic_buffering_minus1", i);
    7690        3098 :                 gf_bs_read_ue_log_idx(bs, "vps_max_num_reorder_pics", i);
    7691        3098 :                 gf_bs_read_ue_log_idx(bs, "vps_max_latency_increase_plus1", i);
    7692             :         }
    7693        3068 :         vps->max_layer_id = gf_bs_read_int_log(bs, 6, "max_layer_id");
    7694        3068 :         if (vps->max_layer_id > MAX_LHVC_LAYERS) {
    7695           0 :                 GF_LOG(GF_LOG_ERROR, GF_LOG_CODING, ("[HEVC] VPS max layer ID %u but GPAC only supports %u\n", vps->max_layer_id, MAX_LHVC_LAYERS));
    7696             :                 return -1;
    7697             :         }
    7698        3068 :         vps->num_layer_sets = gf_bs_read_ue_log(bs, "num_layer_sets_minus1") + 1;
    7699        3068 :         if (vps->num_layer_sets > MAX_LHVC_LAYERS) {
    7700           0 :                 GF_LOG(GF_LOG_ERROR, GF_LOG_CODING, ("[HEVC] Wrong number of layer sets in VPS %d\n", vps->num_layer_sets));
    7701             :                 return -1;
    7702             :         }
    7703          12 :         for (i = 1; i < vps->num_layer_sets; i++) {
    7704          24 :                 for (j = 0; j <= vps->max_layer_id; j++) {
    7705          48 :                         layer_id_included_flag[i][j] = gf_bs_read_int_log_idx2(bs, 1, "layer_id_included_flag", i, j);
    7706             :                 }
    7707             :         }
    7708        3068 :         vps->num_layers_in_id_list[0] = 1;
    7709        3080 :         for (i = 1; i < vps->num_layer_sets; i++) {
    7710             :                 u32 n, m;
    7711             :                 n = 0;
    7712          24 :                 for (m = 0; m <= vps->max_layer_id; m++) {
    7713          24 :                         if (layer_id_included_flag[i][m]) {
    7714          24 :                                 vps->LayerSetLayerIdList[i][n++] = m;
    7715          24 :                                 if (vps->LayerSetLayerIdListMax[i] < m)
    7716          11 :                                         vps->LayerSetLayerIdListMax[i] = m;
    7717             :                         }
    7718             :                 }
    7719          12 :                 vps->num_layers_in_id_list[i] = n;
    7720             :         }
    7721        3068 :         if (gf_bs_read_int_log(bs, 1, "vps_timing_info_present_flag")) {
    7722             :                 u32 vps_num_hrd_parameters;
    7723          76 :                 gf_bs_read_int_log(bs, 32, "vps_num_units_in_tick");
    7724          76 :                 gf_bs_read_int_log(bs, 32, "vps_time_scale");
    7725          76 :                 if (gf_bs_read_int_log(bs, 1, "vps_poc_proportional_to_timing_flag")) {
    7726          68 :                         gf_bs_read_ue_log(bs, "vps_num_ticks_poc_diff_one_minus1");
    7727             :                 }
    7728          76 :                 vps_num_hrd_parameters = gf_bs_read_ue_log(bs, "vps_num_hrd_parameters");
    7729          76 :                 for (i = 0; i < vps_num_hrd_parameters; i++) {
    7730             :                         Bool cprms_present_flag = GF_TRUE;
    7731           0 :                         gf_bs_read_ue_log_idx(bs, "hrd_layer_set_idx", i);
    7732           0 :                         if (i > 0)
    7733             :                                 cprms_present_flag = gf_bs_read_int_log(bs, 1, "cprms_present_flag");
    7734           0 :                         hevc_parse_hrd_parameters(bs, cprms_present_flag, vps->max_sub_layers - 1, i);
    7735             :                 }
    7736             :         }
    7737        3068 :         if (stop_at_vps_ext) {
    7738             :                 return vps_id;
    7739             :         }
    7740             : 
    7741        3057 :         vps_extension_flag = gf_bs_read_int_log(bs, 1, "vps_extension_flag");
    7742        3057 :         if (vps_extension_flag) {
    7743             :                 Bool res;
    7744          12 :                 gf_bs_align(bs);
    7745          12 :                 res = hevc_parse_vps_extension(vps, bs);
    7746          12 :                 if (res != GF_TRUE) {
    7747           0 :                         GF_LOG(GF_LOG_ERROR, GF_LOG_CODING, ("[HEVC] Failed to parse VPS extensions\n"));
    7748             :                         return -1;
    7749             :                 }
    7750             :                 if (gf_bs_read_int_log(bs, 1, "vps_extension2_flag")) {
    7751             : #if 0
    7752             :                         while (gf_bs_available(bs)) {
    7753             :                                 /*vps_extension_data_flag */ gf_bs_read_int(bs, 1);
    7754             :                         }
    7755             : #endif
    7756             : 
    7757             :                 }
    7758             :         }
    7759             :         return vps_id;
    7760             : }
    7761             : 
    7762             : GF_EXPORT
    7763          76 : s32 gf_hevc_read_vps_ex(u8 *data, u32 *size, HEVCState *hevc, Bool remove_extensions)
    7764             : {
    7765             :         GF_BitStream *bs;
    7766             :         char *data_without_emulation_bytes = NULL;
    7767             :         u32 data_without_emulation_bytes_size = 0;
    7768             :         s32 vps_id = -1;
    7769             : 
    7770             :         /*still contains emulation bytes*/
    7771          76 :         data_without_emulation_bytes_size = remove_extensions ? gf_media_nalu_emulation_bytes_remove_count(data, (*size)) : 0;
    7772          11 :         if (!data_without_emulation_bytes_size) {
    7773          65 :                 bs = gf_bs_new(data, (*size), GF_BITSTREAM_READ);
    7774          65 :                 gf_bs_enable_emulation_byte_removal(bs, GF_TRUE);
    7775             :         }
    7776             :         //when removing VPS ext, we have to get the full buffer without emulation prevention bytes becuase we do a bit-by-bit copy of the vps
    7777             :         else {
    7778          11 :                 data_without_emulation_bytes = gf_malloc((*size) * sizeof(char));
    7779          11 :                 data_without_emulation_bytes_size = gf_media_nalu_remove_emulation_bytes(data, data_without_emulation_bytes, (*size));
    7780          11 :                 bs = gf_bs_new(data_without_emulation_bytes, data_without_emulation_bytes_size, GF_BITSTREAM_READ);
    7781             :         }
    7782          76 :         if (!bs) goto exit;
    7783             : 
    7784             : 
    7785          76 :         if (!hevc_parse_nal_header(bs, NULL, NULL, NULL)) goto exit;
    7786             : 
    7787          76 :         vps_id = gf_hevc_read_vps_bs_internal(bs, hevc, remove_extensions);
    7788          76 :         if (vps_id < 0) goto exit;
    7789             : 
    7790          76 :         if (remove_extensions) {
    7791             :                 u8 *new_vps;
    7792             :                 u32 new_vps_size, emulation_bytes;
    7793          11 :                 u32 bit_pos = gf_bs_get_bit_offset(bs);
    7794          11 :                 GF_BitStream *w_bs = gf_bs_new(NULL, 0, GF_BITSTREAM_WRITE);
    7795          11 :                 gf_bs_seek(bs, 0);
    7796          11 :                 gf_bs_write_u8(w_bs, gf_bs_read_u8(bs) );
    7797          11 :                 gf_bs_write_u8(w_bs, gf_bs_read_u8(bs) );
    7798          11 :                 gf_bs_write_u8(w_bs, gf_bs_read_u8(bs) );
    7799          11 :                 gf_bs_write_u8(w_bs, gf_bs_read_u8(bs) );
    7800          11 :                 gf_bs_write_u16(w_bs, gf_bs_read_u16(bs) );
    7801          11 :                 bit_pos -= 48;
    7802        1408 :                 while (bit_pos) {
    7803        1386 :                         u32 v = gf_bs_read_int(bs, 1);
    7804        1386 :                         gf_bs_write_int(w_bs, v, 1);
    7805        1386 :                         bit_pos--;
    7806             :                 }
    7807             :                 /*vps extension flag*/
    7808          11 :                 gf_bs_write_int(w_bs, 0, 1);
    7809          11 :                 new_vps = NULL;
    7810          11 :                 gf_bs_get_content(w_bs, &new_vps, &new_vps_size);
    7811          11 :                 gf_bs_del(w_bs);
    7812             : 
    7813          11 :                 emulation_bytes = gf_media_nalu_emulation_bytes_add_count(new_vps, new_vps_size);
    7814          11 :                 if (emulation_bytes + new_vps_size > *size) {
    7815           0 :                         GF_LOG(GF_LOG_ERROR, GF_LOG_CODING, ("Buffer too small to rewrite VPS - skipping rewrite\n"));
    7816             :                 }
    7817             :                 else {
    7818          11 :                         *size = gf_media_nalu_add_emulation_bytes(new_vps, data, new_vps_size);
    7819             :                 }
    7820          11 :                 if (new_vps)
    7821          11 :                         gf_free(new_vps);
    7822             :         }
    7823             : 
    7824         141 : exit:
    7825          76 :         if (bs)
    7826          76 :                 gf_bs_del(bs);
    7827          76 :         if (data_without_emulation_bytes) gf_free(data_without_emulation_bytes);
    7828          76 :         return vps_id;
    7829             : }
    7830             : 
    7831             : GF_EXPORT
    7832          65 : s32 gf_hevc_read_vps(u8 *data, u32 size, HEVCState *hevc)
    7833             : {
    7834          65 :         return gf_hevc_read_vps_ex(data, &size, hevc, GF_FALSE);
    7835             : }
    7836             : 
    7837             : GF_EXPORT
    7838           1 : s32 gf_hevc_read_vps_bs(GF_BitStream *bs, HEVCState *hevc)
    7839             : {
    7840           1 :         if (!bs || !hevc) return -1;
    7841           0 :         gf_bs_enable_emulation_byte_removal(bs, GF_TRUE);
    7842           0 :         if (!hevc_parse_nal_header(bs, NULL, NULL, NULL)) return -1;
    7843           0 :         return gf_hevc_read_vps_bs_internal(bs, hevc, GF_FALSE);
    7844             : }
    7845             : 
    7846           0 : static void hevc_scaling_list_data(GF_BitStream *bs)
    7847             : {
    7848             :         u32 i, sizeId, matrixId;
    7849           0 :         for (sizeId = 0; sizeId < 4; sizeId++) {
    7850           0 :                 for (matrixId = 0; matrixId < 6; matrixId += (sizeId == 3) ? 3 : 1) {
    7851           0 :                         u32 idx = sizeId*100 + 10*matrixId;
    7852           0 :                         u32 scaling_list_pred_mode_flag_sizeId_matrixId = gf_bs_read_int_log_idx(bs, 1, "scaling_list_pred_mode_flag_sizeId_matrixId", idx);
    7853           0 :                         if (!scaling_list_pred_mode_flag_sizeId_matrixId) {
    7854           0 :                                 gf_bs_read_ue_log_idx(bs, "scaling_list_pred_matrix_id_delta", idx);
    7855             :                         }
    7856             :                         else {
    7857             :                                 //u32 nextCoef = 8;
    7858           0 :                                 u32 coefNum = MIN(64, (1 << (4 + (sizeId << 1))));
    7859           0 :                                 if (sizeId > 1) {
    7860           0 :                                         gf_bs_read_se_log_idx(bs, "scaling_list_dc_coef_minus8", idx);
    7861             :                                 }
    7862           0 :                                 for (i = 0; i < coefNum; i++) {
    7863           0 :                                         gf_bs_read_se_log_idx2(bs, "scaling_list_delta_coef", idx, i);
    7864             :                                 }
    7865             :                         }
    7866             :                 }
    7867             :         }
    7868           0 : }
    7869             : 
    7870             : 
    7871             : static const struct {
    7872             :         u32 w, h;
    7873             : } hevc_sar[17] =
    7874             : {
    7875             :         { 0,   0 }, { 1,   1 }, { 12, 11 }, { 10, 11 },
    7876             :         { 16, 11 }, { 40, 33 }, { 24, 11 }, { 20, 11 },
    7877             :         { 32, 11 }, { 80, 33 }, { 18, 11 }, { 15, 11 },
    7878             :         { 64, 33 }, { 160,99 }, { 4,3}, { 3,2}, { 2,1}
    7879             : };
    7880             : 
    7881        3069 : static s32 gf_hevc_read_sps_bs_internal(GF_BitStream *bs, HEVCState *hevc, u8 layer_id, u32 *vui_flag_pos)
    7882             : {
    7883             :         s32 vps_id, sps_id = -1;
    7884             :         u32 i, nb_CTUs, depth;
    7885             :         HEVC_SPS *sps;
    7886             :         HEVC_VPS *vps;
    7887             :         HEVC_ProfileTierLevel ptl;
    7888             :         Bool multiLayerExtSpsFlag;
    7889             :         u8 sps_ext_or_max_sub_layers_minus1, max_sub_layers_minus1;
    7890             : 
    7891        3069 :         if (vui_flag_pos) *vui_flag_pos = 0;
    7892             : 
    7893             :         //nalu header already parsed
    7894        3069 :         vps_id = gf_bs_read_int_log(bs, 4, "vps_id");
    7895        3069 :         if ((vps_id<0) || (vps_id >= 16)) {
    7896             :                 return -1;
    7897             :         }
    7898             :         memset(&ptl, 0, sizeof(ptl));
    7899             :         max_sub_layers_minus1 = 0;
    7900             :         sps_ext_or_max_sub_layers_minus1 = 0;
    7901        3069 :         if (layer_id == 0)
    7902        3060 :                 max_sub_layers_minus1 = gf_bs_read_int_log(bs, 3, "max_sub_layers_minus1");
    7903             :         else
    7904           9 :                 sps_ext_or_max_sub_layers_minus1 = gf_bs_read_int_log(bs, 3, "sps_ext_or_max_sub_layers_minus1");
    7905        3069 :         multiLayerExtSpsFlag = (layer_id != 0) && (sps_ext_or_max_sub_layers_minus1 == 7);
    7906        3069 :         if (!multiLayerExtSpsFlag) {
    7907        3060 :                 gf_bs_read_int_log(bs, 1, "temporal_id_nesting_flag");
    7908        3060 :                 hevc_profile_tier_level(bs, 1, max_sub_layers_minus1, &ptl, 0);
    7909             :         }
    7910             : 
    7911        3069 :         sps_id = gf_bs_read_ue_log(bs, "sps_id");
    7912        3069 :         if ((sps_id < 0) || (sps_id >= 16)) {
    7913             :                 return -1;
    7914             :         }
    7915             : 
    7916        3069 :         sps = &hevc->sps[sps_id];
    7917        3069 :         if (!sps->state) {
    7918         365 :                 sps->state = 1;
    7919         365 :                 sps->id = sps_id;
    7920         365 :                 sps->vps_id = vps_id;
    7921             :         }
    7922        3069 :         sps->ptl = ptl;
    7923             :         vps = &hevc->vps[vps_id];
    7924        3069 :         sps->max_sub_layers_minus1 = 0;
    7925        3069 :         sps->sps_ext_or_max_sub_layers_minus1 = 0;
    7926             : 
    7927             :         /* default values */
    7928        3069 :         sps->colour_primaries = 2;
    7929        3069 :         sps->transfer_characteristic = 2;
    7930        3069 :         sps->matrix_coeffs = 2;
    7931             : 
    7932             :         //sps_rep_format_idx = 0;
    7933        3069 :         if (multiLayerExtSpsFlag) {
    7934           9 :                 sps->update_rep_format_flag = gf_bs_read_int_log(bs, 1, "update_rep_format_flag");
    7935           9 :                 if (sps->update_rep_format_flag) {
    7936           0 :                         sps->rep_format_idx = gf_bs_read_int_log(bs, 8, "rep_format_idx");
    7937             :                 }
    7938             :                 else {
    7939           9 :                         sps->rep_format_idx = vps->rep_format_idx[layer_id];
    7940             :                 }
    7941           9 :                 sps->width = vps->rep_formats[sps->rep_format_idx].pic_width_luma_samples;
    7942           9 :                 sps->height = vps->rep_formats[sps->rep_format_idx].pic_height_luma_samples;
    7943           9 :                 sps->chroma_format_idc = vps->rep_formats[sps->rep_format_idx].chroma_format_idc;
    7944           9 :                 sps->bit_depth_luma = vps->rep_formats[sps->rep_format_idx].bit_depth_luma;
    7945           9 :                 sps->bit_depth_chroma = vps->rep_formats[sps->rep_format_idx].bit_depth_chroma;
    7946           9 :                 sps->separate_colour_plane_flag = vps->rep_formats[sps->rep_format_idx].separate_colour_plane_flag;
    7947             : 
    7948             :                 //TODO this is crude ...
    7949           9 :                 sps->ptl = vps->ext_ptl[0];
    7950             :         }
    7951             :         else {
    7952        3060 :                 sps->chroma_format_idc = gf_bs_read_ue_log(bs, "chroma_format_idc");
    7953        3060 :                 if (sps->chroma_format_idc == 3)
    7954           2 :                         sps->separate_colour_plane_flag = gf_bs_read_int_log(bs, 1, "separate_colour_plane_flag");
    7955        3060 :                 sps->width = gf_bs_read_ue_log(bs, "width");
    7956        3060 :                 sps->height = gf_bs_read_ue_log(bs, "height");
    7957        3060 :                 if ((sps->cw_flag = gf_bs_read_int_log(bs, 1, "conformance_window_flag"))) {
    7958             :                         u32 SubWidthC, SubHeightC;
    7959             : 
    7960          18 :                         if (sps->chroma_format_idc == 1) {
    7961             :                                 SubWidthC = SubHeightC = 2;
    7962             :                         }
    7963           4 :                         else if (sps->chroma_format_idc == 2) {
    7964             :                                 SubWidthC = 2;
    7965             :                                 SubHeightC = 1;
    7966             :                         }
    7967             :                         else {
    7968             :                                 SubWidthC = SubHeightC = 1;
    7969             :                         }
    7970             : 
    7971          18 :                         sps->cw_left = gf_bs_read_ue_log(bs, "conformance_window_left");
    7972          18 :                         sps->cw_right = gf_bs_read_ue_log(bs, "conformance_window_right");
    7973          18 :                         sps->cw_top = gf_bs_read_ue_log(bs, "conformance_window_top");
    7974          18 :                         sps->cw_bottom = gf_bs_read_ue_log(bs, "conformance_window_bottom");
    7975             : 
    7976          18 :                         sps->width -= SubWidthC * (sps->cw_left + sps->cw_right);
    7977          18 :                         sps->height -= SubHeightC * (sps->cw_top + sps->cw_bottom);
    7978             :                 }
    7979        3060 :                 sps->bit_depth_luma = 8 + gf_bs_read_ue_log(bs, "bit_depth_luma_minus8");
    7980        3060 :                 sps->bit_depth_chroma = 8 + gf_bs_read_ue_log(bs, "bit_depth_chroma_minus8");
    7981             :         }
    7982             : 
    7983        3069 :         sps->log2_max_pic_order_cnt_lsb = 4 + gf_bs_read_ue_log(bs, "log2_max_pic_order_cnt_lsb_minus4");
    7984             : 
    7985        3069 :         if (!multiLayerExtSpsFlag) {
    7986        3060 :                 sps->sub_layer_ordering_info_present_flag = gf_bs_read_int_log(bs, 1, "sub_layer_ordering_info_present_flag");
    7987        6120 :                 for (i = sps->sub_layer_ordering_info_present_flag ? 0 : sps->max_sub_layers_minus1; i <= sps->max_sub_layers_minus1; i++) {
    7988        3060 :                         gf_bs_read_ue_log_idx(bs, "max_dec_pic_buffering", i);
    7989        3060 :                         gf_bs_read_ue_log_idx(bs, "num_reorder_pics", i);
    7990        3060 :                         gf_bs_read_ue_log_idx(bs, "max_latency_increase", i);
    7991             :                 }
    7992             :         }
    7993             : 
    7994        3069 :         sps->log2_min_luma_coding_block_size = 3 + gf_bs_read_ue_log(bs, "log2_min_luma_coding_block_size_minus3");
    7995        3069 :         sps->log2_diff_max_min_luma_coding_block_size = gf_bs_read_ue_log(bs, "log2_diff_max_min_luma_coding_block_size");
    7996        3069 :         sps->max_CU_width = (1 << (sps->log2_min_luma_coding_block_size + sps->log2_diff_max_min_luma_coding_block_size));
    7997        3069 :         sps->max_CU_height = (1 << (sps->log2_min_luma_coding_block_size + sps->log2_diff_max_min_luma_coding_block_size));
    7998             : 
    7999        3069 :         sps->log2_min_transform_block_size = 2 + gf_bs_read_ue_log(bs, "log2_min_transform_block_size_minus2");
    8000        3069 :         sps->log2_max_transform_block_size = sps->log2_min_transform_block_size  + gf_bs_read_ue_log(bs, "log2_max_transform_block_size");
    8001             : 
    8002             :         depth = 0;
    8003        3069 :         sps->max_transform_hierarchy_depth_inter = gf_bs_read_ue_log(bs, "max_transform_hierarchy_depth_inter");
    8004        3069 :         sps->max_transform_hierarchy_depth_intra = gf_bs_read_ue_log(bs, "max_transform_hierarchy_depth_intra");
    8005        9247 :         while ((u32)(sps->max_CU_width >> sps->log2_diff_max_min_luma_coding_block_size) > (u32)(1 << (sps->log2_min_transform_block_size + depth)))
    8006             :         {
    8007        3109 :                 depth++;
    8008             :         }
    8009        3069 :         sps->max_CU_depth = sps->log2_diff_max_min_luma_coding_block_size + depth;
    8010             : 
    8011        3069 :         nb_CTUs = ((sps->width + sps->max_CU_width - 1) / sps->max_CU_width) * ((sps->height + sps->max_CU_height - 1) / sps->max_CU_height);
    8012        3069 :         sps->bitsSliceSegmentAddress = 0;
    8013       23436 :         while (nb_CTUs > (u32)(1 << sps->bitsSliceSegmentAddress)) {
    8014       17298 :                 sps->bitsSliceSegmentAddress++;
    8015             :         }
    8016             : 
    8017        3069 :         sps->scaling_list_enable_flag = gf_bs_read_int_log(bs, 1, "scaling_list_enable_flag");
    8018        3069 :         if (sps->scaling_list_enable_flag) {
    8019           0 :                 sps->infer_scaling_list_flag = 0;
    8020           0 :                 sps->scaling_list_ref_layer_id = 0;
    8021           0 :                 if (multiLayerExtSpsFlag) {
    8022           0 :                         sps->infer_scaling_list_flag = gf_bs_read_int_log(bs, 1, "infer_scaling_list_flag");
    8023             :                 }
    8024           0 :                 if (sps->infer_scaling_list_flag) {
    8025           0 :                         sps->scaling_list_ref_layer_id = gf_bs_read_int_log(bs, 6, "scaling_list_ref_layer_id");
    8026             :                 }
    8027             :                 else {
    8028           0 :                         sps->scaling_list_data_present_flag = gf_bs_read_int_log(bs, 1, "scaling_list_data_present_flag");
    8029           0 :                         if (sps->scaling_list_data_present_flag) {
    8030           0 :                                 hevc_scaling_list_data(bs);
    8031             :                         }
    8032             :                 }
    8033             :         }
    8034        3069 :         sps->asymmetric_motion_partitions_enabled_flag = gf_bs_read_int_log(bs, 1, "asymmetric_motion_partitions_enabled_flag");
    8035        3069 :         sps->sample_adaptive_offset_enabled_flag = gf_bs_read_int_log(bs, 1, "sample_adaptive_offset_enabled_flag");
    8036        3069 :         if ( (sps->pcm_enabled_flag = gf_bs_read_int_log(bs, 1, "pcm_enabled_flag")) ) {
    8037           0 :                 sps->pcm_sample_bit_depth_luma_minus1 = gf_bs_read_int_log(bs, 4, "pcm_sample_bit_depth_luma_minus1");
    8038           0 :                 sps->pcm_sample_bit_depth_chroma_minus1 = gf_bs_read_int_log(bs, 4, "pcm_sample_bit_depth_chroma_minus1");
    8039           0 :                 sps->log2_min_pcm_luma_coding_block_size_minus3 = gf_bs_read_ue_log(bs, "log2_min_pcm_luma_coding_block_size_minus3");
    8040           0 :                 sps->log2_diff_max_min_pcm_luma_coding_block_size = gf_bs_read_ue_log(bs, "log2_diff_max_min_pcm_luma_coding_block_size");
    8041           0 :                 sps->pcm_loop_filter_disable_flag = gf_bs_read_int_log(bs, 1, "pcm_loop_filter_disable_flag");
    8042             :         }
    8043        3069 :         sps->num_short_term_ref_pic_sets = gf_bs_read_ue_log(bs, "num_short_term_ref_pic_sets");
    8044        3069 :         if (sps->num_short_term_ref_pic_sets > 64) {
    8045           0 :                 GF_LOG(GF_LOG_ERROR, GF_LOG_CODING, ("[HEVC] Invalid number of short term reference picture sets %d\n", sps->num_short_term_ref_pic_sets));
    8046             :                 return -1;
    8047             :         }
    8048             : 
    8049         936 :         for (i = 0; i < sps->num_short_term_ref_pic_sets; i++) {
    8050         936 :                 Bool ret = hevc_parse_short_term_ref_pic_set(bs, sps, i);
    8051             :                 /*cannot parse short_term_ref_pic_set, skip VUI parsing*/
    8052         936 :                 if (!ret) {
    8053           0 :                         GF_LOG(GF_LOG_ERROR, GF_LOG_CODING, ("[HEVC] Invalid short_term_ref_pic_set\n"));
    8054             :                         return -1;
    8055             :                 }
    8056             :         }
    8057        3069 :         sps->long_term_ref_pics_present_flag = gf_bs_read_int_log(bs, 1, "long_term_ref_pics_present_flag");
    8058        3069 :         if (sps->long_term_ref_pics_present_flag) {
    8059           6 :                 sps->num_long_term_ref_pic_sps = gf_bs_read_ue_log(bs, "num_long_term_ref_pic_sps");
    8060           6 :                 for (i = 0; i < sps->num_long_term_ref_pic_sps; i++) {
    8061           0 :                         gf_bs_read_int_log_idx(bs, sps->log2_max_pic_order_cnt_lsb, "lt_ref_pic_poc_lsb_sps", i);
    8062           0 :                         gf_bs_read_int_log_idx(bs, 1, "used_by_curr_pic_lt_sps_flag", i);
    8063             :                 }
    8064             :         }
    8065        3069 :         sps->temporal_mvp_enable_flag = gf_bs_read_int_log(bs, 1, "temporal_mvp_enable_flag");
    8066        3069 :         sps->strong_intra_smoothing_enable_flag = gf_bs_read_int_log(bs, 1, "strong_intra_smoothing_enable_flag");
    8067             : 
    8068        3069 :         if (vui_flag_pos)
    8069           3 :                 *vui_flag_pos = (u32)gf_bs_get_bit_offset(bs);
    8070             : 
    8071        3069 :         if ((sps->vui_parameters_present_flag = gf_bs_read_int_log(bs, 1, "vui_parameters_present_flag")) ) {
    8072        2916 :                 sps->aspect_ratio_info_present_flag = gf_bs_read_int_log(bs, 1, "aspect_ratio_info_present_flag");
    8073        2916 :                 if (sps->aspect_ratio_info_present_flag) {
    8074         324 :                         sps->sar_idc = gf_bs_read_int_log(bs, 8, "aspect_ratio_idc");
    8075         324 :                         if (sps->sar_idc == 255) {
    8076           1 :                                 sps->sar_width = gf_bs_read_int_log(bs, 16, "aspect_ratio_width");
    8077           1 :                                 sps->sar_height = gf_bs_read_int_log(bs, 16, "aspect_ratio_height");
    8078             :                         }
    8079         323 :                         else if (sps->sar_idc < 17) {
    8080         323 :                                 sps->sar_width = hevc_sar[sps->sar_idc].w;
    8081         323 :                                 sps->sar_height = hevc_sar[sps->sar_idc].h;
    8082             :                         }
    8083             :                 }
    8084             : 
    8085        2916 :                 if ((sps->overscan_info_present = gf_bs_read_int_log(bs, 1, "overscan_info_present")))
    8086           0 :                         sps->overscan_appropriate = gf_bs_read_int_log(bs, 1, "overscan_appropriate");
    8087             : 
    8088        2916 :                 sps->video_signal_type_present_flag = gf_bs_read_int_log(bs, 1, "video_signal_type_present_flag");
    8089        2916 :                 if (sps->video_signal_type_present_flag) {
    8090           2 :                         sps->video_format = gf_bs_read_int_log(bs, 3, "video_format");
    8091           2 :                         sps->video_full_range_flag = gf_bs_read_int_log(bs, 1, "video_full_range_flag");
    8092           2 :                         if ((sps->colour_description_present_flag = gf_bs_read_int_log(bs, 1, "colour_description_present_flag"))) {
    8093           2 :                                 sps->colour_primaries = gf_bs_read_int_log(bs, 8, "colour_primaries");
    8094           2 :                                 sps->transfer_characteristic = gf_bs_read_int_log(bs, 8, "transfer_characteristic");
    8095           2 :                                 sps->matrix_coeffs = gf_bs_read_int_log(bs, 8, "matrix_coefficients");
    8096             :                         }
    8097             :                 }
    8098             : 
    8099        2916 :                 if ((sps->chroma_loc_info_present_flag = gf_bs_read_int_log(bs, 1, "chroma_loc_info_present_flag"))) {
    8100           0 :                         sps->chroma_sample_loc_type_top_field = gf_bs_read_ue_log(bs, "chroma_sample_loc_type_top_field");
    8101           0 :                         sps->chroma_sample_loc_type_bottom_field = gf_bs_read_ue_log(bs, "chroma_sample_loc_type_bottom_field");
    8102             :                 }
    8103             : 
    8104        2916 :                 sps->neutra_chroma_indication_flag = gf_bs_read_int_log(bs, 1, "neutra_chroma_indication_flag");
    8105        2916 :                 sps->field_seq_flag = gf_bs_read_int_log(bs, 1, "field_seq_flag");
    8106        2916 :                 sps->frame_field_info_present_flag = gf_bs_read_int_log(bs, 1, "frame_field_info_present_flag");
    8107             : 
    8108        2916 :                 if ((sps->default_display_window_flag = gf_bs_read_int_log(bs, 1, "default_display_window_flag"))) {
    8109           0 :                         sps->left_offset = gf_bs_read_ue_log(bs, "display_window_left_offset");
    8110           0 :                         sps->right_offset = gf_bs_read_ue_log(bs, "display_window_right_offset");
    8111           0 :                         sps->top_offset = gf_bs_read_ue_log(bs, "display_window_top_offset");
    8112           0 :                         sps->bottom_offset = gf_bs_read_ue_log(bs, "display_window_bottom_offset");
    8113             :                 }
    8114             : 
    8115        2916 :                 sps->has_timing_info = gf_bs_read_int_log(bs, 1, "has_timing_info");
    8116        2916 :                 if (sps->has_timing_info) {
    8117        1603 :                         sps->num_units_in_tick = gf_bs_read_int_log(bs, 32, "num_units_in_tick");
    8118        1603 :                         sps->time_scale = gf_bs_read_int_log(bs, 32, "time_scale");
    8119        1603 :                         sps->poc_proportional_to_timing_flag = gf_bs_read_int_log(bs, 1, "poc_proportional_to_timing_flag");
    8120        1603 :                         if (sps->poc_proportional_to_timing_flag)
    8121          70 :                                 sps->num_ticks_poc_diff_one_minus1 = gf_bs_read_ue_log(bs, "num_ticks_poc_diff_one_minus1");
    8122        1603 :                         if ((sps->hrd_parameters_present_flag = gf_bs_read_int_log(bs, 1, "hrd_parameters_present_flag"))) {
    8123             :                                 //                              GF_LOG(GF_LOG_INFO, GF_LOG_CODING, ("[HEVC] HRD param parsing not implemented\n"));
    8124             :                                 return sps_id;
    8125             :                         }
    8126             :                 }
    8127             : 
    8128        2846 :                 if (gf_bs_read_int_log(bs, 1, "bitstream_restriction_flag")) {
    8129           0 :                         gf_bs_read_int_log(bs, 1, "tiles_fixed_structure_flag");
    8130           0 :                         gf_bs_read_int_log(bs, 1, "motion_vectors_over_pic_boundaries_flag");
    8131           0 :                         gf_bs_read_int_log(bs, 1, "restricted_ref_pic_lists_flag");
    8132           0 :                         gf_bs_read_ue_log(bs, "min_spatial_segmentation_idc");
    8133           0 :                         gf_bs_read_ue_log(bs, "max_bytes_per_pic_denom");
    8134           0 :                         gf_bs_read_ue_log(bs, "max_bits_per_min_cu_denom");
    8135           0 :                         gf_bs_read_ue_log(bs, "log2_max_mv_length_horizontal");
    8136           0 :                         gf_bs_read_ue_log(bs, "log2_max_mv_length_vertical");
    8137             :                 }
    8138             :         }
    8139             : 
    8140             :         if (gf_bs_read_int_log(bs, 1, "sps_extension_flag")) {
    8141             : #if 0
    8142             :                 while (gf_bs_available(bs)) {
    8143             :                         /*sps_extension_data_flag */ gf_bs_read_int(bs, 1);
    8144             :                 }
    8145             : #endif
    8146             : 
    8147             :         }
    8148             : 
    8149        2999 :         return sps_id;
    8150             : }
    8151             : 
    8152             : GF_EXPORT
    8153          72 : s32 gf_hevc_read_sps_ex(char *data, u32 size, HEVCState *hevc, u32 *vui_flag_pos)
    8154             : {
    8155             :         GF_BitStream *bs;
    8156             :         s32 sps_id = -1;
    8157             :         u8 layer_id;
    8158             : 
    8159          72 :         if (vui_flag_pos) *vui_flag_pos = 0;
    8160             : 
    8161          72 :         bs = gf_bs_new(data, size, GF_BITSTREAM_READ);
    8162          72 :         if (!bs) goto exit;
    8163          72 :         gf_bs_enable_emulation_byte_removal(bs, GF_TRUE);
    8164             : 
    8165          72 :         if (!hevc_parse_nal_header(bs, NULL, NULL, &layer_id)) goto exit;
    8166          72 :         sps_id = gf_hevc_read_sps_bs_internal(bs, hevc, layer_id, vui_flag_pos);
    8167             : 
    8168          72 : exit:
    8169          72 :         if (bs) gf_bs_del(bs);
    8170          72 :         return sps_id;
    8171             : }
    8172             : 
    8173             : GF_EXPORT
    8174          69 : s32 gf_hevc_read_sps(u8 *data, u32 size, HEVCState *hevc)
    8175             : {
    8176          69 :         return gf_hevc_read_sps_ex(data, size, hevc, NULL);
    8177             : }
    8178             : 
    8179             : GF_EXPORT
    8180           1 : s32 gf_hevc_read_sps_bs(GF_BitStream *bs, HEVCState *hevc)
    8181             : {
    8182             :         u8 layer_id;
    8183           1 :         if (!bs || !hevc) return -1;
    8184           0 :         gf_bs_enable_emulation_byte_removal(bs, GF_TRUE);
    8185           0 :         if (!hevc_parse_nal_header(bs, NULL, NULL, &layer_id)) return -1;
    8186           0 :         return gf_hevc_read_sps_bs_internal(bs, hevc, layer_id, NULL);
    8187             : }
    8188             : 
    8189             : 
    8190        3201 : static s32 gf_hevc_read_pps_bs_internal(GF_BitStream *bs, HEVCState *hevc)
    8191             : {
    8192             :         u32 i;
    8193             :         s32 pps_id;
    8194             :         HEVC_PPS *pps;
    8195             : 
    8196             :         //NAL header already read
    8197        3201 :         pps_id = gf_bs_read_ue_log(bs, "pps_id");
    8198             : 
    8199        3201 :         if ((pps_id < 0) || (pps_id >= 64)) {
    8200           0 :                 GF_LOG(GF_LOG_ERROR, GF_LOG_CODING, ("[HEVC] wrong PPS ID %d in PPS\n", pps_id));
    8201             :                 return -1;
    8202             :         }
    8203             :         pps = &hevc->pps[pps_id];
    8204             : 
    8205        3201 :         if (!pps->state) {
    8206         497 :                 pps->id = pps_id;
    8207         497 :                 pps->state = 1;
    8208             :         }
    8209        3201 :         pps->sps_id = gf_bs_read_ue_log(bs, "sps_id");
    8210        3201 :         if (((s32)pps->sps_id<0) || (pps->sps_id >= 16)) {
    8211           0 :                 GF_LOG(GF_LOG_ERROR, GF_LOG_CODING, ("[HEVC] wrong SPS ID %d in PPS\n", pps->sps_id));
    8212           0 :                 pps->sps_id=0;
    8213           0 :                 return -1;
    8214             :         }
    8215        3201 :         hevc->sps_active_idx = pps->sps_id; /*set active sps*/
    8216        3201 :         pps->dependent_slice_segments_enabled_flag = gf_bs_read_int_log(bs, 1, "dependent_slice_segments_enabled_flag");
    8217             : 
    8218        3201 :         pps->output_flag_present_flag = gf_bs_read_int_log(bs, 1, "output_flag_present_flag");
    8219        3201 :         pps->num_extra_slice_header_bits = gf_bs_read_int_log(bs, 3, "num_extra_slice_header_bits");
    8220        3201 :         pps->sign_data_hiding_flag = gf_bs_read_int_log(bs, 1, "sign_data_hiding_flag");
    8221        3201 :         pps->cabac_init_present_flag = gf_bs_read_int_log(bs, 1, "cabac_init_present_flag");
    8222        3201 :         pps->num_ref_idx_l0_default_active = 1 + gf_bs_read_ue_log(bs, "num_ref_idx_l0_default_active");
    8223        3201 :         pps->num_ref_idx_l1_default_active = 1 + gf_bs_read_ue_log(bs, "num_ref_idx_l1_default_active");
    8224        3201 :         pps->pic_init_qp_minus26 = gf_bs_read_se_log(bs, "pic_init_qp_minus26");
    8225        3201 :         pps->constrained_intra_pred_flag = gf_bs_read_int_log(bs, 1, "constrained_intra_pred_flag");
    8226        3201 :         pps->transform_skip_enabled_flag = gf_bs_read_int_log(bs, 1, "transform_skip_enabled_flag");
    8227        3201 :         if ((pps->cu_qp_delta_enabled_flag = gf_bs_read_int_log(bs, 1, "cu_qp_delta_enabled_flag")))
    8228        1567 :                 pps->diff_cu_qp_delta_depth = gf_bs_read_ue_log(bs, "diff_cu_qp_delta_depth");
    8229             : 
    8230        3201 :         pps->pic_cb_qp_offset = gf_bs_read_se_log(bs, "pic_cb_qp_offset");
    8231        3201 :         pps->pic_cr_qp_offset = gf_bs_read_se_log(bs, "pic_cr_qp_offset");
    8232        3201 :         pps->slice_chroma_qp_offsets_present_flag = gf_bs_read_int_log(bs, 1, "slice_chroma_qp_offsets_present_flag");
    8233        3201 :         pps->weighted_pred_flag = gf_bs_read_int_log(bs, 1, "weighted_pred_flag");
    8234        3201 :         pps->weighted_bipred_flag = gf_bs_read_int_log(bs, 1, "weighted_bipred_flag");
    8235        3201 :         pps->transquant_bypass_enable_flag = gf_bs_read_int_log(bs, 1, "transquant_bypass_enable_flag");
    8236        3201 :         pps->tiles_enabled_flag = gf_bs_read_int_log(bs, 1, "tiles_enabled_flag");
    8237        3201 :         pps->entropy_coding_sync_enabled_flag = gf_bs_read_int_log(bs, 1, "entropy_coding_sync_enabled_flag");
    8238        3201 :         if (pps->tiles_enabled_flag) {
    8239        1101 :                 pps->num_tile_columns = 1 + gf_bs_read_ue_log(bs, "num_tile_columns_minus1");
    8240        1101 :                 pps->num_tile_rows = 1 + gf_bs_read_ue_log(bs, "num_tile_rows_minus1");
    8241        1101 :                 pps->uniform_spacing_flag = gf_bs_read_int_log(bs, 1, "uniform_spacing_flag");
    8242        1101 :                 if (!pps->uniform_spacing_flag) {
    8243           0 :                         for (i = 0; i < pps->num_tile_columns - 1; i++) {
    8244           0 :                                 pps->column_width[i] = 1 + gf_bs_read_ue_log_idx(bs, "column_width_minus1", i);
    8245             :                         }
    8246           0 :                         for (i = 0; i < pps->num_tile_rows - 1; i++) {
    8247           0 :                                 pps->row_height[i] = 1 + gf_bs_read_ue_log_idx(bs, "row_height_minus1", i);
    8248             :                         }
    8249             :                 }
    8250        1101 :                 pps->loop_filter_across_tiles_enabled_flag = gf_bs_read_int_log(bs, 1, "loop_filter_across_tiles_enabled_flag");
    8251             :         }
    8252        3201 :         pps->loop_filter_across_slices_enabled_flag = gf_bs_read_int_log(bs, 1, "loop_filter_across_slices_enabled_flag");
    8253        3201 :         if ((pps->deblocking_filter_control_present_flag = gf_bs_read_int_log(bs, 1, "deblocking_filter_control_present_flag"))) {
    8254        3129 :                 pps->deblocking_filter_override_enabled_flag = gf_bs_read_int_log(bs, 1, "deblocking_filter_override_enabled_flag");
    8255        3129 :                 if (! (pps->pic_disable_deblocking_filter_flag = gf_bs_read_int_log(bs, 1, "pic_disable_deblocking_filter_flag"))) {
    8256        3127 :                         pps->beta_offset_div2 = gf_bs_read_se_log(bs, "beta_offset_div2");
    8257        3127 :                         pps->tc_offset_div2 = gf_bs_read_se_log(bs, "tc_offset_div2");
    8258             :                 }
    8259             :         }
    8260        3201 :         if ((pps->pic_scaling_list_data_present_flag = gf_bs_read_int_log(bs, 1, "pic_scaling_list_data_present_flag"))) {
    8261           0 :                 hevc_scaling_list_data(bs);
    8262             :         }
    8263        3201 :         pps->lists_modification_present_flag = gf_bs_read_int_log(bs, 1, "lists_modification_present_flag");
    8264        3201 :         pps->log2_parallel_merge_level_minus2 = gf_bs_read_ue_log(bs, "log2_parallel_merge_level_minus2");
    8265        3201 :         pps->slice_segment_header_extension_present_flag = gf_bs_read_int_log(bs, 1, "slice_segment_header_extension_present_flag");
    8266             :         if (gf_bs_read_int_log(bs, 1, "pps_extension_flag")) {
    8267             : #if 0
    8268             :                 while (gf_bs_available(bs)) {
    8269             :                         /*pps_extension_data_flag */ gf_bs_read_int(bs, 1);
    8270             :                 }
    8271             : #endif
    8272             : 
    8273             :         }
    8274        3201 :         return pps_id;
    8275             : }
    8276             : 
    8277             : 
    8278             : GF_EXPORT
    8279         279 : s32 gf_hevc_read_pps(u8 *data, u32 size, HEVCState *hevc)
    8280             : {
    8281             :         GF_BitStream *bs;
    8282             :         s32 pps_id = -1;
    8283             : 
    8284         279 :         bs = gf_bs_new(data, size, GF_BITSTREAM_READ);
    8285         279 :         if (!bs) goto exit;
    8286         279 :         gf_bs_enable_emulation_byte_removal(bs, GF_TRUE);
    8287             : 
    8288         279 :         if (!hevc_parse_nal_header(bs, NULL, NULL, NULL)) goto exit;
    8289             : 
    8290         279 :         pps_id = gf_hevc_read_pps_bs_internal(bs, hevc);
    8291             : 
    8292         279 : exit:
    8293         279 :         if (bs) gf_bs_del(bs);
    8294         279 :         return pps_id;
    8295             : }
    8296             : 
    8297             : GF_EXPORT
    8298           1 : s32 gf_hevc_read_pps_bs(GF_BitStream *bs, HEVCState *hevc)
    8299             : {
    8300           1 :         if (!bs || !hevc) return -1;
    8301           0 :         gf_bs_enable_emulation_byte_removal(bs, GF_TRUE);
    8302           0 :         if (!hevc_parse_nal_header(bs, NULL, NULL, NULL)) return -1;
    8303           0 :         return gf_hevc_read_pps_bs_internal(bs, hevc);
    8304             : }
    8305             : 
    8306             : GF_EXPORT
    8307      942201 : s32 gf_hevc_parse_nalu_bs(GF_BitStream *bs, HEVCState *hevc, u8 *nal_unit_type, u8 *temporal_id, u8 *layer_id)
    8308             : {
    8309             :         Bool is_slice = GF_FALSE;
    8310             :         s32 ret = -1;
    8311             :         HEVCSliceInfo n_state;
    8312             : 
    8313      942201 :         gf_bs_enable_emulation_byte_removal(bs, GF_TRUE);
    8314             : 
    8315      942201 :         memcpy(&n_state, &hevc->s_info, sizeof(HEVCSliceInfo));
    8316      942201 :         if (!hevc_parse_nal_header(bs, nal_unit_type, temporal_id, layer_id)) return -1;
    8317             : 
    8318      942201 :         n_state.nal_unit_type = *nal_unit_type;
    8319             : 
    8320      942201 :         switch (n_state.nal_unit_type) {
    8321             :         case GF_HEVC_NALU_ACCESS_UNIT:
    8322             :         case GF_HEVC_NALU_END_OF_SEQ:
    8323             :         case GF_HEVC_NALU_END_OF_STREAM:
    8324             :                 ret = 1;
    8325             :                 break;
    8326             : 
    8327             :                 /*slice_segment_layer_rbsp*/
    8328      729693 :         case GF_HEVC_NALU_SLICE_TRAIL_N:
    8329             :         case GF_HEVC_NALU_SLICE_TRAIL_R:
    8330             :         case GF_HEVC_NALU_SLICE_TSA_N:
    8331             :         case GF_HEVC_NALU_SLICE_TSA_R:
    8332             :         case GF_HEVC_NALU_SLICE_STSA_N:
    8333             :         case GF_HEVC_NALU_SLICE_STSA_R:
    8334             :         case GF_HEVC_NALU_SLICE_BLA_W_LP:
    8335             :         case GF_HEVC_NALU_SLICE_BLA_W_DLP:
    8336             :         case GF_HEVC_NALU_SLICE_BLA_N_LP:
    8337             :         case GF_HEVC_NALU_SLICE_IDR_W_DLP:
    8338             :         case GF_HEVC_NALU_SLICE_IDR_N_LP:
    8339             :         case GF_HEVC_NALU_SLICE_CRA:
    8340             :         case GF_HEVC_NALU_SLICE_RADL_N:
    8341             :         case GF_HEVC_NALU_SLICE_RADL_R:
    8342             :         case GF_HEVC_NALU_SLICE_RASL_N:
    8343             :         case GF_HEVC_NALU_SLICE_RASL_R:
    8344             :                 is_slice = GF_TRUE;
    8345             :                 /* slice - read the info and compare.*/
    8346      729693 :                 ret = hevc_parse_slice_segment(bs, hevc, &n_state);
    8347      729693 :                 if (ret < 0) return ret;
    8348             : 
    8349      729693 :                 hevc_compute_poc(&n_state);
    8350             : 
    8351             :                 ret = 0;
    8352             : 
    8353      729693 :                 if (hevc->s_info.poc != n_state.poc) {
    8354             :                         ret = 1;
    8355             :                         break;
    8356             :                 }
    8357      581512 :                 if (n_state.first_slice_segment_in_pic_flag) {
    8358        5695 :                         if (!(*layer_id) || (n_state.prev_layer_id_plus1 && ((*layer_id) <= n_state.prev_layer_id_plus1 - 1))) {
    8359             :                                 ret = 1;
    8360             :                                 break;
    8361             :                         }
    8362             :                 }
    8363             :                 break;
    8364        2997 :         case GF_HEVC_NALU_SEQ_PARAM:
    8365        2997 :                 hevc->last_parsed_sps_id = gf_hevc_read_sps_bs_internal(bs, hevc, *layer_id, NULL);
    8366        2997 :                 ret = (hevc->last_parsed_sps_id>=0) ? 0 : -1;
    8367             :                 break;
    8368        2922 :         case GF_HEVC_NALU_PIC_PARAM:
    8369        2922 :                 hevc->last_parsed_pps_id = gf_hevc_read_pps_bs_internal(bs, hevc);
    8370        2922 :                 ret = (hevc->last_parsed_pps_id>=0) ? 0 : -1;
    8371             :                 break;
    8372        2992 :         case GF_HEVC_NALU_VID_PARAM:
    8373        2992 :                 hevc->last_parsed_vps_id = gf_hevc_read_vps_bs_internal(bs, hevc, GF_FALSE);
    8374        2992 :                 ret = (hevc->last_parsed_vps_id>=0) ? 0 : -1;
    8375             :                 break;
    8376             :         default:
    8377             :                 ret = 0;
    8378             :                 break;
    8379             :         }
    8380             : 
    8381             :         /* save _prev values */
    8382      198458 :         if ((ret>0) && hevc->s_info.sps) {
    8383      198122 :                 n_state.frame_num_offset_prev = hevc->s_info.frame_num_offset;
    8384      198122 :                 n_state.frame_num_prev = hevc->s_info.frame_num;
    8385             : 
    8386      198122 :                 n_state.poc_lsb_prev = hevc->s_info.poc_lsb;
    8387      198122 :                 n_state.poc_msb_prev = hevc->s_info.poc_msb;
    8388      198122 :                 if (is_slice)
    8389      149826 :                         n_state.prev_layer_id_plus1 = *layer_id + 1;
    8390             :         }
    8391      942201 :         if (is_slice) hevc_compute_poc(&n_state);
    8392             :         memcpy(&hevc->s_info, &n_state, sizeof(HEVCSliceInfo));
    8393             : 
    8394      942201 :         return ret;
    8395             : }
    8396             : 
    8397             : GF_EXPORT
    8398      210952 : s32 gf_hevc_parse_nalu(u8 *data, u32 size, HEVCState *hevc, u8 *nal_unit_type, u8 *temporal_id, u8 *layer_id)
    8399             : {
    8400             :         GF_BitStream *bs = NULL;
    8401             :         s32 ret = -1;
    8402             : 
    8403      210952 :         if (!hevc) {
    8404           0 :                 if (nal_unit_type) (*nal_unit_type) = (data[0] & 0x7E) >> 1;
    8405           0 :                 if (layer_id) {
    8406           0 :                         u8 id = data[0] & 1;
    8407           0 :                         id <<= 5;
    8408           0 :                         id |= (data[1] >> 3) & 0x1F;
    8409           0 :                         (*layer_id) = id;
    8410             :                 }
    8411           0 :                 if (temporal_id) (*temporal_id) = (data[1] & 0x7);
    8412             :                 return -1;
    8413             :         }
    8414             : 
    8415      210952 :         bs = gf_bs_new(data, size, GF_BITSTREAM_READ);
    8416      210952 :         if (!bs) return -1;
    8417      210952 :         gf_bs_enable_emulation_byte_removal(bs, GF_TRUE);
    8418             : 
    8419      210952 :         ret = gf_hevc_parse_nalu_bs(bs, hevc, nal_unit_type, temporal_id, layer_id);
    8420             : 
    8421      210952 :         gf_bs_del(bs);
    8422      210952 :         return ret;
    8423             : }
    8424             : 
    8425             : GF_EXPORT
    8426           3 : GF_Err gf_hevc_change_vui(GF_HEVCConfig *hvcc, GF_VUIInfo *vui_info)
    8427             : {
    8428             :         GF_BitStream *orig, *mod;
    8429             :         HEVCState hevc;
    8430             :         u32 i, bit_offset, flag;
    8431             :         s32 idx;
    8432             :         GF_NALUFFParamArray *spss;
    8433             :         GF_NALUFFParam *slc;
    8434             :         orig = NULL;
    8435             : 
    8436             :         memset(&hevc, 0, sizeof(HEVCState));
    8437           3 :         hevc.sps_active_idx = -1;
    8438             : 
    8439           3 :         i = 0;
    8440             :         spss = NULL;
    8441           9 :         while ((spss = (GF_NALUFFParamArray *)gf_list_enum(hvcc->param_array, &i))) {
    8442           6 :                 if (spss->type == GF_HEVC_NALU_SEQ_PARAM)
    8443             :                         break;
    8444             :                 spss = NULL;
    8445             :         }
    8446           3 :         if (!spss) return GF_NON_COMPLIANT_BITSTREAM;
    8447             : 
    8448           3 :         i = 0;
    8449           9 :         while ((slc = (GF_NALUFFParam *)gf_list_enum(spss->nalus, &i))) {
    8450             :                 u8 *no_emulation_buf;
    8451             :                 u32 no_emulation_buf_size, emulation_bytes;
    8452             : 
    8453             :                 /*SPS may still contains emulation bytes*/
    8454           3 :                 no_emulation_buf = gf_malloc((slc->size) * sizeof(char));
    8455           3 :                 no_emulation_buf_size = gf_media_nalu_remove_emulation_bytes(slc->data, no_emulation_buf, slc->size);
    8456             : 
    8457           3 :                 idx = gf_hevc_read_sps_ex(no_emulation_buf, no_emulation_buf_size, &hevc, &bit_offset);
    8458           3 :                 if (idx < 0) {
    8459             :                         if (orig)
    8460             :                                 gf_bs_del(orig);
    8461           0 :                         gf_free(no_emulation_buf);
    8462           0 :                         continue;
    8463             :                 }
    8464             : 
    8465           3 :                 orig = gf_bs_new(no_emulation_buf, no_emulation_buf_size, GF_BITSTREAM_READ);
    8466           3 :                 mod = gf_bs_new(NULL, 0, GF_BITSTREAM_WRITE);
    8467             : 
    8468             :                 /*copy over till vui flag*/
    8469             :                 assert(bit_offset >= 0);
    8470         660 :                 while (bit_offset) {
    8471         654 :                         flag = gf_bs_read_int(orig, 1);
    8472         654 :                         gf_bs_write_int(mod, flag, 1);
    8473         654 :                         bit_offset--;
    8474             :                 }
    8475             : 
    8476           3 :                 avc_hevc_rewrite_vui(vui_info, orig, mod);
    8477             : 
    8478             :                 /*finally copy over remaining*/
    8479          36 :                 while (gf_bs_bits_available(orig)) {
    8480          30 :                         flag = gf_bs_read_int(orig, 1);
    8481          30 :                         gf_bs_write_int(mod, flag, 1);
    8482             :                 }
    8483           3 :                 gf_bs_del(orig);
    8484             :                 orig = NULL;
    8485           3 :                 gf_free(no_emulation_buf);
    8486             : 
    8487             :                 /*set anti-emulation*/
    8488           3 :                 gf_bs_get_content(mod, &no_emulation_buf, &no_emulation_buf_size);
    8489           3 :                 emulation_bytes = gf_media_nalu_emulation_bytes_add_count(no_emulation_buf, no_emulation_buf_size);
    8490           3 :                 if (no_emulation_buf_size + emulation_bytes > slc->size)
    8491           3 :                         slc->data = (char*)gf_realloc(slc->data, no_emulation_buf_size + emulation_bytes);
    8492             : 
    8493           3 :                 slc->size = gf_media_nalu_add_emulation_bytes(no_emulation_buf, slc->data, no_emulation_buf_size);
    8494             : 
    8495           3 :                 gf_bs_del(mod);
    8496           3 :                 gf_free(no_emulation_buf);
    8497             :         }
    8498             :         return GF_OK;
    8499             : }
    8500             : 
    8501             : 
    8502             : GF_EXPORT
    8503           1 : GF_Err gf_hevc_change_par(GF_HEVCConfig *hvcc, s32 ar_n, s32 ar_d)
    8504             : {
    8505             :         GF_VUIInfo vuii;
    8506             :         memset(&vuii, 0, sizeof(GF_VUIInfo));
    8507           1 :         vuii.ar_num = ar_n;
    8508           1 :         vuii.ar_den = ar_d;
    8509           1 :         vuii.fullrange = -1;
    8510           1 :         vuii.video_format = -1;
    8511           1 :         vuii.color_prim = -1;
    8512           1 :         vuii.color_tfc = -1;
    8513           1 :         vuii.color_matrix = -1;
    8514           1 :         return gf_hevc_change_vui(hvcc, &vuii);
    8515             : }
    8516             : 
    8517             : GF_EXPORT
    8518           0 : GF_Err gf_hevc_change_color(GF_HEVCConfig *hvcc, s32 fullrange, s32 vidformat, s32 colorprim, s32 transfer, s32 colmatrix)
    8519             : {
    8520             :         GF_VUIInfo vuii;
    8521             :         memset(&vuii, 0, sizeof(GF_VUIInfo));
    8522           0 :         vuii.ar_num = -1;
    8523           0 :         vuii.ar_den = -1;
    8524           0 :         vuii.fullrange = fullrange;
    8525           0 :         vuii.video_format = vidformat;
    8526           0 :         vuii.color_prim = colorprim;
    8527           0 :         vuii.color_tfc = transfer;
    8528           0 :         vuii.color_matrix = colmatrix;
    8529           0 :         return gf_hevc_change_vui(hvcc, &vuii);
    8530             : }
    8531             : 
    8532             : 
    8533             : GF_EXPORT
    8534          19 : GF_Err gf_hevc_get_sps_info_with_state(HEVCState *hevc, u8 *sps_data, u32 sps_size, u32 *sps_id, u32 *width, u32 *height, s32 *par_n, s32 *par_d)
    8535             : {
    8536             :         s32 idx;
    8537          19 :         idx = gf_hevc_read_sps(sps_data, sps_size, hevc);
    8538          19 :         if (idx < 0) {
    8539             :                 return GF_NON_COMPLIANT_BITSTREAM;
    8540             :         }
    8541          19 :         if (sps_id) *sps_id = idx;
    8542             : 
    8543          19 :         if (width) *width = hevc->sps[idx].width;
    8544          19 :         if (height) *height = hevc->sps[idx].height;
    8545          19 :         if (par_n) *par_n = hevc->sps[idx].aspect_ratio_info_present_flag ? hevc->sps[idx].sar_width : (u32)-1;
    8546          19 :         if (par_d) *par_d = hevc->sps[idx].aspect_ratio_info_present_flag ? hevc->sps[idx].sar_height : (u32)-1;
    8547             :         return GF_OK;
    8548             : }
    8549             : 
    8550             : GF_EXPORT
    8551           2 : GF_Err gf_hevc_get_sps_info(u8 *sps_data, u32 sps_size, u32 *sps_id, u32 *width, u32 *height, s32 *par_n, s32 *par_d)
    8552             : {
    8553             :         HEVCState hevc;
    8554             :         memset(&hevc, 0, sizeof(HEVCState));
    8555           2 :         hevc.sps_active_idx = -1;
    8556           2 :         return gf_hevc_get_sps_info_with_state(&hevc, sps_data, sps_size, sps_id, width, height, par_n, par_d);
    8557             : }
    8558             : 
    8559             : 
    8560             : #endif //GPAC_DISABLE_HEVC
    8561             : 
    8562             : static u32 AC3_FindSyncCode(u8 *buf, u32 buflen)
    8563             : {
    8564        3218 :         u32 end = buflen - 6;
    8565             :         u32 offset = 0;
    8566    11603554 :         while (offset <= end) {
    8567    11600571 :                 if (buf[offset] == 0x0b && buf[offset + 1] == 0x77) {
    8568             :                         return offset;
    8569             :                 }
    8570    11600336 :                 offset++;
    8571             :         }
    8572             :         return buflen;
    8573             : }
    8574             : 
    8575             : 
    8576       16767 : static Bool AC3_FindSyncCodeBS(GF_BitStream *bs)
    8577             : {
    8578             :         u8 b1;
    8579       16767 :         u64 pos = gf_bs_get_position(bs);
    8580       16767 :         u64 end = gf_bs_get_size(bs);
    8581             : 
    8582       16767 :         pos += 1;
    8583       16767 :         b1 = gf_bs_read_u8(bs);
    8584       33534 :         while (pos + 1 <= end) {
    8585       16767 :                 u8 b2 = gf_bs_read_u8(bs);
    8586       16767 :                 if ((b1 == 0x0b) && (b2 == 0x77)) {
    8587       16767 :                         gf_bs_seek(bs, pos - 1);
    8588       16767 :                         return GF_TRUE;
    8589             :                 }
    8590             :                 pos++;
    8591             :                 b1 = b2;
    8592             :         }
    8593             :         return GF_FALSE;
    8594             : }
    8595             : 
    8596             : static const u32 ac3_sizecod_to_bitrate[] = {
    8597             :         32000, 40000, 48000, 56000, 64000, 80000, 96000,
    8598             :         112000, 128000, 160000, 192000, 224000, 256000,
    8599             :         320000, 384000, 448000, 512000, 576000, 640000
    8600             : };
    8601             : 
    8602             : static const u32 ac3_sizecod2_to_framesize[] = {
    8603             :         96, 120, 144, 168, 192, 240, 288, 336, 384, 480, 576, 672,
    8604             :         768, 960, 1152, 1344, 1536, 1728, 1920
    8605             : };
    8606             : 
    8607             : static const u32 ac3_sizecod1_to_framesize[] = {
    8608             :         69, 87, 104, 121, 139, 174, 208, 243, 278, 348, 417, 487,
    8609             :         557, 696, 835, 975, 1114, 1253, 1393
    8610             : };
    8611             : static const u32 ac3_sizecod0_to_framesize[] = {
    8612             :         64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384, 448,
    8613             :         512, 640, 768, 896, 1024, 1152, 1280
    8614             : };
    8615             : 
    8616             : static const u32 ac3_mod_to_chans[] = {
    8617             :         2, 1, 2, 3, 3, 4, 4, 5
    8618             : };
    8619             : 
    8620             : GF_EXPORT
    8621           3 : u32 gf_ac3_get_channels(u32 acmod)
    8622             : {
    8623             :         u32 nb_ch;
    8624           3 :         nb_ch = ac3_mod_to_chans[acmod];
    8625           3 :         return nb_ch;
    8626             : }
    8627             : 
    8628             : GF_EXPORT
    8629           2 : u32 gf_ac3_get_bitrate(u32 brcode)
    8630             : {
    8631           2 :         return ac3_sizecod_to_bitrate[brcode];
    8632             : }
    8633             : 
    8634        3218 : Bool gf_ac3_parser(u8 *buf, u32 buflen, u32 *pos, GF_AC3Config *hdr, Bool full_parse)
    8635             : {
    8636             :         GF_BitStream *bs;
    8637             :         Bool ret;
    8638             : 
    8639        3218 :         if (buflen < 6) return GF_FALSE;
    8640        3218 :         (*pos) = AC3_FindSyncCode(buf, buflen);
    8641        3218 :         if (*pos >= buflen) return GF_FALSE;
    8642             : 
    8643         235 :         bs = gf_bs_new((const char*)(buf + *pos), buflen, GF_BITSTREAM_READ);
    8644         235 :         ret = gf_ac3_parser_bs(bs, hdr, full_parse);
    8645         235 :         gf_bs_del(bs);
    8646             : 
    8647         235 :         return ret;
    8648             : }
    8649             : 
    8650             : GF_EXPORT
    8651       11429 : Bool gf_ac3_parser_bs(GF_BitStream *bs, GF_AC3Config *hdr, Bool full_parse)
    8652             : {
    8653             :         u32 fscod, frmsizecod, bsid, ac3_mod, freq, framesize, bsmod, syncword;
    8654             :         u64 pos;
    8655       11429 :         if (!hdr || (gf_bs_available(bs) < 6)) return GF_FALSE;
    8656       11423 :         if (!AC3_FindSyncCodeBS(bs)) return GF_FALSE;
    8657             : 
    8658       11423 :         pos = gf_bs_get_position(bs);
    8659             : 
    8660       11423 :         syncword = gf_bs_read_u16(bs);
    8661       11423 :         if (syncword != 0x0B77) {
    8662           0 :                 GF_LOG(GF_LOG_ERROR, GF_LOG_CODING, ("[AC3] Wrong sync word detected (0x%X - expecting 0x0B77).\n", syncword));
    8663             :                 return GF_FALSE;
    8664             :         }
    8665       11423 :         gf_bs_read_int_log(bs, 16, "crc1");
    8666             :         fscod = gf_bs_read_int_log(bs, 2, "fscod");
    8667             :         frmsizecod = gf_bs_read_int_log(bs, 6, "frmsizecod");
    8668             :         bsid = gf_bs_read_int_log(bs, 5, "bsid");
    8669             :         bsmod = gf_bs_read_int_log(bs, 3, "bsmod");
    8670             :         ac3_mod = gf_bs_read_int_log(bs, 3, "ac3_mod");
    8671       11423 :         if (frmsizecod >= 2 * sizeof(ac3_sizecod_to_bitrate) / sizeof(u32))
    8672             :                 return GF_FALSE;
    8673             : 
    8674       11410 :         hdr->bitrate = ac3_sizecod_to_bitrate[frmsizecod / 2];
    8675       11410 :         if (bsid > 8) hdr->bitrate = hdr->bitrate >> (bsid - 8);
    8676             : 
    8677       11410 :         switch (fscod) {
    8678             :         case 0:
    8679             :                 if (frmsizecod >=  2 * sizeof(ac3_sizecod0_to_framesize) / sizeof(u32))
    8680             :                         return GF_FALSE;
    8681             :                 freq = 48000;
    8682          28 :                 framesize = ac3_sizecod0_to_framesize[frmsizecod / 2] * 2;
    8683          28 :                 break;
    8684             :         case 1:
    8685             :                 if (frmsizecod >= 2 * sizeof(ac3_sizecod1_to_framesize) / sizeof(u32))
    8686             :                         return GF_FALSE;
    8687             :                 freq = 44100;
    8688       11375 :                 framesize = (ac3_sizecod1_to_framesize[frmsizecod / 2] + (frmsizecod & 0x1)) * 2;
    8689       11375 :                 break;
    8690             :         case 2:
    8691             :                 if (frmsizecod >= 2 * sizeof(ac3_sizecod2_to_framesize) / sizeof(u32))
    8692             :                         return GF_FALSE;
    8693             :                 freq = 32000;
    8694           7 :                 framesize = ac3_sizecod2_to_framesize[frmsizecod / 2] * 2;
    8695           7 :                 break;
    8696             :         default:
    8697             :                 return GF_FALSE;
    8698             :         }
    8699       11410 :         hdr->sample_rate = freq;
    8700       11410 :         hdr->framesize = framesize;
    8701             : 
    8702       11410 :         if (full_parse) {
    8703        7589 :                 hdr->streams[0].bsid = bsid;
    8704        7589 :                 hdr->streams[0].bsmod = bsmod;
    8705        7589 :                 hdr->streams[0].acmod = ac3_mod;
    8706        7589 :                 hdr->streams[0].lfon = 0;
    8707        7589 :                 hdr->streams[0].fscod = fscod;
    8708        7589 :                 hdr->brcode = frmsizecod / 2;
    8709             :         }
    8710       11410 :         if (ac3_mod >= 2 * sizeof(ac3_mod_to_chans) / sizeof(u32))
    8711             :                 return GF_FALSE;
    8712             : 
    8713       11410 :         hdr->channels = ac3_mod_to_chans[ac3_mod];
    8714       11410 :         if ((ac3_mod & 0x1) && (ac3_mod != 1)) gf_bs_read_int_log(bs, 2, "cmixlev");
    8715       11410 :         if (ac3_mod & 0x4) gf_bs_read_int_log(bs, 2, "surmixlev");
    8716       11410 :         if (ac3_mod == 0x2) gf_bs_read_int_log(bs, 2, "dsurmod");
    8717             : 
    8718       11410 :         if (gf_bs_read_int_log(bs, 1, "lfeon")) {
    8719          30 :                 hdr->channels += 1;
    8720          30 :                 hdr->streams[0].lfon = 1;
    8721             :         }
    8722             : 
    8723       11410 :         gf_bs_seek(bs, pos);
    8724             : 
    8725       11410 :         return GF_TRUE;
    8726             : }
    8727             : 
    8728             : GF_EXPORT
    8729        2747 : Bool gf_eac3_parser_bs(GF_BitStream *bs, GF_AC3Config *hdr, Bool full_parse)
    8730             : {
    8731             :         u32 fscod, bsid, ac3_mod, freq, framesize, syncword, substreamid, lfon, channels, numblkscod, strmtyp, frmsiz;
    8732             :         u64 pos;
    8733             :         u16 chanmap;
    8734             :         static u32 numblks[4] = {1, 2, 3, 6};
    8735             : 
    8736        2747 :         if (!hdr || (gf_bs_available(bs) < 6))
    8737             :                 return GF_FALSE;
    8738        2747 :         if (!AC3_FindSyncCodeBS(bs))
    8739             :                 return GF_FALSE;
    8740             : 
    8741        2747 :         pos = gf_bs_get_position(bs);
    8742             :         framesize = 0;
    8743             :         numblkscod = 0;
    8744             :         memset(hdr, 0, sizeof(GF_AC3Config));
    8745             : 
    8746             : block:
    8747        5344 :         syncword = gf_bs_read_u16(bs);
    8748        5344 :         if (syncword != 0x0B77) {
    8749           0 :                 GF_LOG(GF_LOG_ERROR, GF_LOG_CODING, ("[E-AC3] Wrong sync word detected (0x%X - expecting 0x0B77).\n", syncword));
    8750             :                 return GF_FALSE;
    8751             :         }
    8752             : 
    8753             :         strmtyp = gf_bs_read_int_log(bs, 2, "strmtyp");
    8754             :         substreamid = gf_bs_read_int_log(bs, 3, "substreamid");
    8755             :         //next main (independent) AU, done with this frame
    8756        5344 :         if ((strmtyp!=0x1) && ((hdr->substreams >> substreamid) & 0x1)) {
    8757        2597 :                 hdr->framesize = framesize;
    8758        2597 :                 gf_bs_seek(bs, pos);
    8759        2597 :                 return GF_TRUE;
    8760             :         }
    8761             : 
    8762             :         frmsiz = gf_bs_read_int_log(bs, 11, "frmsiz");
    8763        2747 :         framesize += 2 * (1 + frmsiz);
    8764             :         fscod = gf_bs_read_int_log(bs, 2, "fscod");
    8765        2747 :         if (fscod == 0x3) {
    8766             :                 fscod = gf_bs_read_int_log(bs, 2, "fscod2");
    8767           0 :                 numblkscod += 6;
    8768             :         }
    8769             :         else {
    8770        2747 :                 numblkscod += gf_bs_read_int_log(bs, 2, "numblkscod");
    8771             :         }
    8772             :         assert(numblkscod <= 9);
    8773             : 
    8774             : 
    8775        2747 :         if ((hdr->substreams >> substreamid) & 0x1) {
    8776             :                 //we still have sync frames following
    8777           0 :                 if (substreamid) {
    8778           0 :                         if (gf_bs_seek(bs, pos + framesize) != GF_OK) {
    8779           0 :                                 gf_bs_seek(bs, pos);
    8780           0 :                                 return GF_FALSE;
    8781             :                         }
    8782           0 :                         if ((gf_bs_available(bs) < 6) || !AC3_FindSyncCodeBS(bs)) {
    8783           0 :                                 gf_bs_seek(bs, pos);
    8784           0 :                                 return GF_FALSE;
    8785             :                         }
    8786             :                         goto block;
    8787             :                 }
    8788             :         }
    8789             : 
    8790        2747 :         hdr->substreams |= (1 << substreamid);
    8791             : 
    8792        2747 :         switch (fscod) {
    8793             :         case 0:
    8794             :                 freq = 48000;
    8795             :                 break;
    8796        2747 :         case 1:
    8797             :                 freq = 44100;
    8798        2747 :                 break;
    8799           0 :         case 2:
    8800             :                 freq = 32000;
    8801           0 :                 break;
    8802             :         default:
    8803             :                 return GF_FALSE;
    8804             :         }
    8805             : 
    8806             :         ac3_mod = gf_bs_read_int_log(bs, 3, "ac3_mod");
    8807             :         lfon = gf_bs_read_int_log(bs, 1, "lfon");
    8808             :         bsid = gf_bs_read_int_log(bs, 5, "bsid");
    8809        2747 :         if (!substreamid && (bsid != 16/*E-AC3*/))
    8810             :                 return GF_FALSE;
    8811        2747 :         gf_bs_read_int_log(bs, 5, "dialnorm");
    8812        2747 :         if (gf_bs_read_int_log(bs, 1, "compre")) {
    8813           0 :                 gf_bs_read_int_log(bs, 8, "compr");
    8814             :         }
    8815        2747 :         if (ac3_mod==0) {
    8816           0 :                 gf_bs_read_int_log(bs, 5, "dialnorm2");
    8817           0 :                 if (gf_bs_read_int_log(bs, 1, "compr2e")) {
    8818           0 :                         gf_bs_read_int_log(bs, 8, "compr2");
    8819             :                 }
    8820             :         }
    8821             :         chanmap = 0;
    8822        2747 :         if (strmtyp==0x1) {
    8823           0 :                 if (gf_bs_read_int_log(bs, 1, "chanmape")) {
    8824           0 :                         chanmap = gf_bs_read_int_log(bs, 16, "chanmap");
    8825             :                 }
    8826             :         }
    8827             : 
    8828        2747 :         channels = ac3_mod_to_chans[ac3_mod];
    8829        2747 :         if (lfon)
    8830           0 :                 channels += 1;
    8831             : 
    8832        2747 :         hdr->bitrate = 0;
    8833        2747 :         hdr->sample_rate = freq;
    8834        2747 :         hdr->framesize = framesize;
    8835        2747 :         if (strmtyp != 1) {
    8836        2747 :                 hdr->channels = channels;
    8837        2747 :                 hdr->streams[substreamid].lfon = lfon;
    8838        2747 :                 if (full_parse) {
    8839        1885 :                         hdr->streams[substreamid].bsid = bsid;
    8840        1885 :                         hdr->streams[substreamid].bsmod = 0;
    8841        1885 :                         hdr->streams[substreamid].acmod = ac3_mod;
    8842        1885 :                         hdr->streams[substreamid].fscod = fscod;
    8843        1885 :                         hdr->brcode = 0;
    8844             :                 }
    8845        2747 :                 hdr->nb_streams++;
    8846             :                 //not clear if this is only for the independent streams
    8847        2747 :                 hdr->brcode += ((frmsiz+1) * freq) / (numblks[numblkscod]*16) / 1000;
    8848             : 
    8849        2747 :                 if (lfon)
    8850           0 :                         hdr->channels += 1;
    8851             : 
    8852             :         } else {
    8853           0 :                 hdr->streams[substreamid].nb_dep_sub = substreamid;
    8854           0 :                 hdr->streams[substreamid].chan_loc |= chanmap;
    8855             :         }
    8856             : 
    8857        2747 :         if (numblkscod < 6) { //we need 6 blocks to make a sample
    8858        2747 :                 if (gf_bs_seek(bs, pos + framesize) != GF_OK) {
    8859         141 :                         gf_bs_seek(bs, pos);
    8860         141 :                         return GF_FALSE;
    8861             :                 }
    8862             : 
    8863        2606 :                 if ((gf_bs_available(bs) < 6) || !AC3_FindSyncCodeBS(bs))
    8864             :                         return GF_FALSE;
    8865             :                 goto block;
    8866             :         }
    8867             : 
    8868           0 :         gf_bs_seek(bs, pos);
    8869             : 
    8870           0 :         return GF_TRUE;
    8871             : }
    8872             : 
    8873             : #endif /*GPAC_DISABLE_AV_PARSERS*/
    8874             : 
    8875         114 : u32 gf_id3_read_size(GF_BitStream *bs)
    8876             : {
    8877             :         u32 size = 0;
    8878         114 :         gf_bs_read_int(bs, 1);
    8879         114 :         size |= gf_bs_read_int(bs, 7);
    8880         114 :         size<<=7;
    8881         114 :         gf_bs_read_int(bs, 1);
    8882         114 :         size |= gf_bs_read_int(bs, 7);
    8883         114 :         size<<=7;
    8884         114 :         gf_bs_read_int(bs, 1);
    8885         114 :         size |= gf_bs_read_int(bs, 7);
    8886         114 :         size<<=7;
    8887         114 :         gf_bs_read_int(bs, 1);
    8888         114 :         size |= gf_bs_read_int(bs, 7);
    8889         114 :         return size;
    8890             : }
    8891             : 
    8892             : 
    8893             : #if !defined(GPAC_DISABLE_AV_PARSERS) && !defined (GPAC_DISABLE_OGG)
    8894             : 
    8895             : /*
    8896             :         Vorbis parser
    8897             : */
    8898             : 
    8899         143 : static u32 vorbis_book_maptype1_quantvals(u32 entries, u32 dim)
    8900             : {
    8901         143 :         u32 vals = (u32)floor(pow(entries, 1.0 / dim));
    8902             :         while (1) {
    8903             :                 u32 acc = 1;
    8904             :                 u32 acc1 = 1;
    8905             :                 u32 i;
    8906         528 :                 for (i = 0; i < dim; i++) {
    8907         385 :                         acc *= vals;
    8908         385 :                         acc1 *= vals + 1;
    8909             :                 }
    8910         143 :                 if (acc <= entries && acc1 > entries) return (vals);
    8911             :                 else {
    8912           0 :                         if (acc > entries) vals--;
    8913           0 :                         else vals++;
    8914             :                 }
    8915             :         }
    8916             : }
    8917             : 
    8918             : static u32 ilog(u32 v, Bool dec)
    8919             : {
    8920             :         u32 ret = 0;
    8921           0 :         if (dec && v) --v;
    8922         495 :         while (v) {
    8923         418 :                 ret++;
    8924         418 :                 v >>= 1;
    8925             :         }
    8926             :         return (ret);
    8927             : }
    8928             : 
    8929             : static u32 icount(u32 v)
    8930             : {
    8931             :         u32 ret = 0;
    8932         770 :         while (v) {
    8933         550 :                 ret += v & 1;
    8934         550 :                 v >>= 1;
    8935             :         }
    8936             :         return(ret);
    8937             : }
    8938             : 
    8939             : 
    8940             : GF_EXPORT
    8941          33 : Bool gf_vorbis_parse_header(GF_VorbisParser *vp, u8 *data, u32 data_len)
    8942             : {
    8943             :         u32 pack_type, i, j, k, times, nb_part, nb_books, nb_modes;
    8944             :         u32 l;
    8945             :         char szNAME[8];
    8946             :         oggpack_buffer opb;
    8947             : 
    8948          33 :         oggpack_readinit(&opb, (u8*)data, data_len);
    8949          33 :         pack_type = oggpack_read(&opb, 8);
    8950             :         i = 0;
    8951         264 :         while (i < 6) {
    8952         198 :                 szNAME[i] = oggpack_read(&opb, 8);
    8953         198 :                 i++;
    8954             :         }
    8955          33 :         szNAME[i] = 0;
    8956          33 :         if (strcmp(szNAME, "vorbis")) {
    8957             :                 return GF_FALSE;
    8958             :         }
    8959             : 
    8960          33 :         switch (pack_type) {
    8961          11 :         case 0x01:
    8962          11 :                 vp->version = oggpack_read(&opb, 32);
    8963          11 :                 if (vp->version != 0) {
    8964             :                         return GF_FALSE;
    8965             :                 }
    8966          11 :                 vp->channels = oggpack_read(&opb, 8);
    8967          11 :                 vp->sample_rate = oggpack_read(&opb, 32);
    8968          11 :                 vp->max_r = oggpack_read(&opb, 32);
    8969          11 :                 vp->avg_r = oggpack_read(&opb, 32);
    8970          11 :                 vp->low_r = oggpack_read(&opb, 32);
    8971             : 
    8972          11 :                 vp->min_block = 1<<oggpack_read(&opb, 4);
    8973          11 :                 vp->max_block = 1<<oggpack_read(&opb, 4);
    8974          11 :                 if (vp->sample_rate < 1 || vp->channels < 1 || vp->min_block < 8 || vp->max_block < vp->min_block
    8975          11 :                     || oggpack_read(&opb, 1) != 1) {
    8976             :                         return GF_FALSE;
    8977             :                 }
    8978          11 :                 vp->nb_init=1;
    8979          11 :                 return GF_TRUE;
    8980             : 
    8981          11 :         case 0x03:
    8982             :                 /*trash comments*/
    8983          11 :                 vp->nb_init++;
    8984          11 :                 return GF_TRUE;
    8985          11 :         case 0x05:
    8986             :                 /*need at least bitstream header to make sure we're parsing the right thing*/
    8987          11 :                 if (!vp->nb_init) return GF_FALSE;
    8988             :                 break;
    8989             :         default:
    8990             :                 return GF_FALSE;
    8991             :         }
    8992             :         /*OK parse codebook*/
    8993          11 :         nb_books = oggpack_read(&opb, 8) + 1;
    8994             :         /*skip vorbis static books*/
    8995         473 :         for (i = 0; i < nb_books; i++) {
    8996             :                 u32 map_type, qb, qq;
    8997             :                 u32 entries, dim;
    8998         462 :                 oggpack_read(&opb, 24);
    8999         462 :                 dim = oggpack_read(&opb, 16);
    9000         462 :                 entries = oggpack_read(&opb, 24);
    9001         462 :                 if ((s32)entries < 0) entries = 0;
    9002         462 :                 if (oggpack_read(&opb, 1) == 0) {
    9003         451 :                         if (oggpack_read(&opb, 1)) {
    9004       19723 :                                 for (j = 0; j < entries; j++) {
    9005       19723 :                                         if (oggpack_read(&opb, 1)) {
    9006       15224 :                                                 oggpack_read(&opb, 5);
    9007             :                                         }
    9008             :                                 }
    9009             :                         }
    9010             :                         else {
    9011       29865 :                                 for (j = 0; j < entries; j++)
    9012       29865 :                                         oggpack_read(&opb, 5);
    9013             :                         }
    9014             :                 }
    9015             :                 else {
    9016          11 :                         oggpack_read(&opb, 5);
    9017          99 :                         for (j = 0; j < entries;) {
    9018         154 :                                 u32 num = oggpack_read(&opb, ilog(entries - j, GF_FALSE));
    9019          77 :                                 for (k = 0; k < num && j < entries; k++, j++) {
    9020             :                                 }
    9021             :                         }
    9022             :                 }
    9023         462 :                 switch ((map_type = oggpack_read(&opb, 4))) {
    9024             :                 case 0:
    9025             :                         break;
    9026         143 :                 case 1:
    9027             :                 case 2:
    9028         143 :                         oggpack_read(&opb, 32);
    9029         143 :                         oggpack_read(&opb, 32);
    9030         143 :                         qq = oggpack_read(&opb, 4) + 1;
    9031         143 :                         oggpack_read(&opb, 1);
    9032         143 :                         if (map_type == 1) qb = vorbis_book_maptype1_quantvals(entries, dim);
    9033           0 :                         else if (map_type == 2) qb = entries * dim;
    9034             :                         else qb = 0;
    9035         143 :                         for (j = 0; j < qb; j++) oggpack_read(&opb, qq);
    9036             :                         break;
    9037             :                 }
    9038             :         }
    9039          11 :         times = oggpack_read(&opb, 6) + 1;
    9040          11 :         for (i = 0; i < times; i++) oggpack_read(&opb, 16);
    9041          11 :         times = oggpack_read(&opb, 6) + 1;
    9042          33 :         for (i = 0; i < times; i++) {
    9043          22 :                 u32 type = oggpack_read(&opb, 16);
    9044          22 :                 if (type) {
    9045             :                         u32 *parts, *class_dims, count, rangebits;
    9046             :                         u32 max_class = 0;
    9047          22 :                         nb_part = oggpack_read(&opb, 5);
    9048          22 :                         parts = (u32*)gf_malloc(sizeof(u32) * nb_part);
    9049         176 :                         for (j = 0; j < nb_part; j++) {
    9050         154 :                                 parts[j] = oggpack_read(&opb, 4);
    9051         154 :                                 if (max_class < parts[j]) max_class = parts[j];
    9052             :                         }
    9053          22 :                         class_dims = (u32*)gf_malloc(sizeof(u32) * (max_class + 1));
    9054         121 :                         for (j = 0; j < max_class + 1; j++) {
    9055             :                                 u32 class_sub;
    9056          99 :                                 class_dims[j] = oggpack_read(&opb, 3) + 1;
    9057          99 :                                 class_sub = oggpack_read(&opb, 2);
    9058          99 :                                 if (class_sub) oggpack_read(&opb, 8);
    9059         264 :                                 for (k = 0; k < (u32)(1 << class_sub); k++) oggpack_read(&opb, 8);
    9060             :                         }
    9061          22 :                         oggpack_read(&opb, 2);
    9062          22 :                         rangebits = oggpack_read(&opb, 4);
    9063             :                         count = 0;
    9064         176 :                         for (j = 0, k = 0; j < nb_part; j++) {
    9065         154 :                                 count += class_dims[parts[j]];
    9066         154 :                                 for (; k < count; k++) oggpack_read(&opb, rangebits);
    9067             :                         }
    9068          22 :                         gf_free(parts);
    9069          22 :                         gf_free(class_dims);
    9070             :                 }
    9071             :                 else {
    9072           0 :                         oggpack_read(&opb, 8 + 16 + 16 + 6 + 8);
    9073           0 :                         nb_books = oggpack_read(&opb, 4) + 1;
    9074           0 :                         for (j = 0; j < nb_books; j++)
    9075           0 :                                 oggpack_read(&opb, 8);
    9076             :                 }
    9077             :         }
    9078          11 :         times = oggpack_read(&opb, 6) + 1;
    9079          33 :         for (i = 0; i < times; i++) {
    9080             :                 u32 acc = 0;
    9081          22 :                 oggpack_read(&opb, 16);/*type*/
    9082          22 :                 oggpack_read(&opb, 24);
    9083          22 :                 oggpack_read(&opb, 24);
    9084          22 :                 oggpack_read(&opb, 24);
    9085          22 :                 nb_part = oggpack_read(&opb, 6) + 1;
    9086          22 :                 oggpack_read(&opb, 8);
    9087         242 :                 for (j = 0; j < nb_part; j++) {
    9088         220 :                         u32 cascade = oggpack_read(&opb, 3);
    9089         220 :                         if (oggpack_read(&opb, 1)) cascade |= (oggpack_read(&opb, 5) << 3);
    9090         220 :                         acc += icount(cascade);
    9091             :                 }
    9092         286 :                 for (j = 0; j < acc; j++) oggpack_read(&opb, 8);
    9093             :         }
    9094          11 :         times = oggpack_read(&opb, 6) + 1;
    9095          33 :         for (i = 0; i < times; i++) {
    9096             :                 u32 sub_maps = 1;
    9097          22 :                 oggpack_read(&opb, 16);
    9098          22 :                 if (oggpack_read(&opb, 1)) sub_maps = oggpack_read(&opb, 4) + 1;
    9099          22 :                 if (oggpack_read(&opb, 1)) {
    9100           0 :                         u32 nb_steps = oggpack_read(&opb, 8) + 1;
    9101           0 :                         for (j = 0; j < nb_steps; j++) {
    9102           0 :                                 oggpack_read(&opb, ilog(vp->channels, GF_TRUE));
    9103           0 :                                 oggpack_read(&opb, ilog(vp->channels, GF_TRUE));
    9104             :                         }
    9105             :                 }
    9106          22 :                 oggpack_read(&opb, 2);
    9107          22 :                 if (sub_maps>1) {
    9108           0 :                         for(l=0; l<vp->channels; l++)
    9109           0 :                                 oggpack_read(&opb, 4);
    9110             :                 }
    9111          22 :                 for (j = 0; j < sub_maps; j++) {
    9112          22 :                         oggpack_read(&opb, 8);
    9113          22 :                         oggpack_read(&opb, 8);
    9114          22 :                         oggpack_read(&opb, 8);
    9115             :                 }
    9116             :         }
    9117          11 :         nb_modes = oggpack_read(&opb, 6) + 1;
    9118          33 :         for (i = 0; i < nb_modes; i++) {
    9119          22 :                 vp->mode_flag[i] = oggpack_read(&opb, 1);
    9120          22 :                 oggpack_read(&opb, 16);
    9121          22 :                 oggpack_read(&opb, 16);
    9122          22 :                 oggpack_read(&opb, 8);
    9123             :         }
    9124             : 
    9125          11 :         vp->modebits = 0;
    9126             :         j = nb_modes;
    9127          33 :         while (j > 1) {
    9128          11 :                 vp->modebits++;
    9129          11 :                 j >>= 1;
    9130             :         }
    9131             : 
    9132             :         return GF_TRUE;
    9133             : }
    9134             : 
    9135             : GF_EXPORT
    9136       22317 : u32 gf_vorbis_check_frame(GF_VorbisParser *vp, u8 *data, u32 data_length)
    9137             : {
    9138             :         s32 block_size;
    9139             :         oggpack_buffer opb;
    9140       22317 :         if (!vp) return 0;
    9141       22317 :         oggpack_readinit(&opb, (unsigned char*)data, data_length);
    9142             :         /*not audio*/
    9143       22317 :         if (oggpack_read(&opb, 1) != 0) return 0;
    9144       22313 :         block_size = oggpack_read(&opb, vp->modebits);
    9145       22313 :         if (block_size == -1) return 0;
    9146       22313 :         return ((vp->mode_flag[block_size]) ? vp->max_block : vp->min_block) / (2);
    9147             : }
    9148             : 
    9149             : /*call with vorbis header packets - initializes the parser on success, leave it to NULL otherwise
    9150             : returns 1 if success, 0 if error.*/
    9151           3 : Bool gf_opus_parse_header(GF_OpusParser *opus, u8 *data, u32 data_len)
    9152             : {
    9153             :         char tag[9];
    9154           3 :         GF_BitStream *bs = gf_bs_new(data, data_len, GF_BITSTREAM_READ);
    9155           3 :         gf_bs_read_data(bs, tag, 8);
    9156           3 :         tag[8]=0;
    9157             : 
    9158           3 :         if (memcmp(data, "OpusHead", sizeof(char)*8)) {
    9159           0 :                 gf_bs_del(bs);
    9160           0 :                 return GF_FALSE;
    9161             :         }
    9162             :         /*Identification Header*/
    9163           3 :         opus->version = gf_bs_read_u8(bs); /*version*/
    9164           3 :         if (opus->version != 1) {
    9165           0 :                 gf_bs_del(bs);
    9166           0 :                 GF_LOG(GF_LOG_ERROR, GF_LOG_CODING, ("[Opus] Unsupported version %d\n", opus->version));
    9167             :                 return GF_FALSE;
    9168             :         }
    9169           3 :         opus->OutputChannelCount = gf_bs_read_u8(bs);
    9170           3 :         opus->PreSkip = gf_bs_read_u16_le(bs);
    9171           3 :         opus->InputSampleRate = gf_bs_read_u32_le(bs);
    9172           3 :         opus->OutputGain = gf_bs_read_u16_le(bs);
    9173           3 :         opus->ChannelMappingFamily = gf_bs_read_u8(bs);
    9174           3 :         if (opus->ChannelMappingFamily != 0) {
    9175           3 :                 opus->StreamCount = gf_bs_read_u8(bs);
    9176           3 :                 opus->CoupledCount = gf_bs_read_u8(bs);
    9177           3 :                 gf_bs_read_data(bs, (char *) opus->ChannelMapping, opus->OutputChannelCount);
    9178             :         }
    9179           3 :         gf_bs_del(bs);
    9180           3 :         return GF_TRUE;
    9181             : }
    9182             : 
    9183             : /*returns 0 if init error or not a vorbis frame, otherwise returns the number of audio samples
    9184             : in this frame*/
    9185         923 : u32 gf_opus_check_frame(GF_OpusParser *op, u8 *data, u32 data_length)
    9186             : {
    9187             :         u32 block_size;
    9188             : 
    9189         923 :         if (!memcmp(data, "OpusHead", sizeof(char)*8))
    9190             :                 return 0;
    9191         923 :         if (!memcmp(data, "OpusTags", sizeof(char)*8))
    9192             :                 return 0;
    9193             : 
    9194             :         /*consider the whole packet as Ogg packets and ISOBMFF samples for Opus are framed similarly*/
    9195             :         static const int OpusFrameDurIn48k[] = { 480, 960, 1920, 2880, 480, 960, 1920, 2880, 480, 960, 1920, 2880,
    9196             :                 480, 960, 480, 960,
    9197             :                 120, 240, 480, 960, 120, 240, 480, 960, 120, 240, 480, 960, 120, 240, 480, 960,
    9198             :         };
    9199         920 :         int TOC_config = (data[0] & 0xf8) >> 3;
    9200             :         //int s = (data[0] & 0x04) >> 2;
    9201         920 :         block_size = OpusFrameDurIn48k[TOC_config];
    9202             : 
    9203             :         int c = data[0] & 0x03;
    9204         920 :         if (c == 1 || c == 2) {
    9205           0 :                 block_size *= 2;
    9206         920 :         } else if (c == 3) {
    9207             :                 /*unknown number of frames*/
    9208           0 :                 int num_frames = data[1] & 0x3f;
    9209           0 :                 block_size *= num_frames;
    9210             :         }
    9211             :         return block_size;
    9212             : }
    9213             : 
    9214             : #endif /*!defined(GPAC_DISABLE_AV_PARSERS) && !defined (GPAC_DISABLE_OGG)*/
    9215             : 
    9216       58467 : u64 gf_mpegh_escaped_value(GF_BitStream *bs, u32 nBits1, u32 nBits2, u32 nBits3)
    9217             : {
    9218       58467 :         u64 value = gf_bs_read_int(bs, nBits1);
    9219       58467 :         if (value == (1<<nBits1)-1) {
    9220         235 :                 u32 vadd = gf_bs_read_int(bs, nBits2);
    9221         235 :                 value += vadd;
    9222         235 :                 if (vadd == (1<<nBits2)-1) {
    9223           0 :                         vadd = gf_bs_read_int(bs, nBits3);
    9224           0 :                         value += vadd;
    9225             :                 }
    9226             :         }
    9227       58467 :         return value;
    9228             : }
    9229             : 
    9230             : GF_EXPORT
    9231           2 : s32 gf_mpegh_get_mhas_pl(u8 *ptr, u32 size, u64 *ch_layout)
    9232             : {
    9233             :         s32 PL = -1;
    9234             :         GF_BitStream *bs;
    9235             :         u32 i;
    9236             :         s32 sync_pos=-1;
    9237           2 :         for (i=0; i<size-3; i++) {
    9238           2 :                 if ((ptr[i]==0xC0) && (ptr[i+1]== 0x01) && (ptr[i+2]==0xA5)) {
    9239           2 :                         sync_pos = i;
    9240           2 :                         break;
    9241             :                 }
    9242             :         }
    9243           2 :         if (sync_pos<0) return 0;
    9244           2 :         if (ch_layout) *ch_layout = 0;
    9245           2 :         bs = gf_bs_new(ptr, size, GF_BITSTREAM_READ);
    9246           2 :         gf_bs_skip_bytes(bs, sync_pos);
    9247             : 
    9248           6 :         while (gf_bs_available(bs)) {
    9249           4 :                 u32 type = (u32) gf_mpegh_escaped_value(bs, 3, 8, 8);
    9250           4 :                 /*u64 label = */gf_mpegh_escaped_value(bs, 2, 8, 32);
    9251           4 :                 u64 mh_size = gf_mpegh_escaped_value(bs, 11, 24, 24);
    9252           4 :                 if (mh_size > gf_bs_available(bs))
    9253             :                         break;
    9254             :                 //MHAS config
    9255           4 :                 if (type==1) {
    9256           2 :                         PL = gf_bs_read_int(bs, 8);
    9257           2 :                         if (ch_layout) {
    9258           2 :                                 u32 idx = gf_bs_read_int(bs, 5);
    9259           2 :                                 if (idx==0x1f)
    9260           0 :                                         gf_bs_read_int(bs, 24);
    9261           2 :                                 /*idx = */gf_bs_read_int(bs, 3);
    9262           2 :                                 gf_bs_read_int(bs, 1);
    9263           2 :                                 gf_bs_read_int(bs, 1);
    9264             : 
    9265             :                                 //speaker config
    9266           2 :                                 idx = gf_bs_read_int(bs, 2);
    9267           2 :                                 if (idx == 0) {
    9268           2 :                                         *ch_layout = gf_audio_fmt_get_layout_from_cicp( gf_bs_read_int(bs, 6) );
    9269             :                                 }
    9270             :                         }
    9271             :                         break;
    9272             :                 }
    9273           2 :                 gf_bs_skip_bytes(bs, mh_size);
    9274             :         }
    9275           2 :         gf_bs_del(bs);
    9276           2 :         return PL;
    9277             : }
    9278             : 
    9279             : 
    9280             : GF_EXPORT
    9281           0 : void gf_media_vvc_parse_sei(char *buffer, u32 nal_size, VVCState *vvc)
    9282             : {
    9283           0 :         gf_hevc_vvc_parse_sei(buffer, nal_size, NULL, vvc);
    9284           0 : }
    9285             : 
    9286           0 : static Bool vvc_parse_nal_header(GF_BitStream *bs, u8 *nal_unit_type, u8 *temporal_id, u8 *layer_id)
    9287             : {
    9288             :         u32 val;
    9289             :         val = gf_bs_read_int_log(bs, 1, "forbidden_zero");
    9290           0 :         if (val) return GF_FALSE;
    9291             :         val = gf_bs_read_int_log(bs, 1, "resevred0");
    9292           0 :         if (val) return GF_FALSE;
    9293             : 
    9294             :         val = gf_bs_read_int_log(bs, 6, "layerID");
    9295           0 :         if (layer_id) *layer_id = val;
    9296             : 
    9297             :         val = gf_bs_read_int_log(bs, 5, "nuh_type");
    9298           0 :         if (nal_unit_type) *nal_unit_type = val;
    9299             : 
    9300             :         val = gf_bs_read_int_log(bs, 3, "temporalID");
    9301           0 :         if (!val) return GF_FALSE;
    9302           0 :         val -= 1;
    9303           0 :         if (temporal_id) *temporal_id = val;
    9304             :         return GF_TRUE;
    9305             : }
    9306             : 
    9307           0 : static void vvc_profile_tier_level(GF_BitStream *bs, VVC_ProfileTierLevel *ptl, u32 idx)
    9308             : {
    9309             :         u32 i;
    9310           0 :         if (ptl->pt_present) {
    9311           0 :                 ptl->general_profile_idc = gf_bs_read_int_log_idx(bs, 7, "general_profile_idc", idx);
    9312           0 :                 ptl->general_tier_flag = gf_bs_read_int_log_idx(bs, 1, "general_tier_flag", idx);
    9313             :         }
    9314           0 :         ptl->general_level_idc = gf_bs_read_int_log_idx(bs, 8, "general_level_idc", idx);
    9315           0 :         ptl->frame_only_constraint = gf_bs_read_int_log_idx(bs, 1, "frame_only_constraint", idx);
    9316           0 :         ptl->multilayer_enabled = gf_bs_read_int_log_idx(bs, 1, "multilayer_enabled", idx);
    9317             :         //general constraints info - max size if 1 + 81 + 8 + 255
    9318           0 :         if (ptl->pt_present) {
    9319             :                 //              general_constraints_info
    9320           0 :                 ptl->gci_present = gf_bs_read_int_log_idx(bs, 1, "gci_present", idx);
    9321           0 :                 if (ptl->gci_present) {
    9322             :                         u8 res;
    9323           0 :                         ptl->gci[0] = 0x80;
    9324           0 :                         ptl->gci[0] |= gf_bs_read_int(bs, 7);
    9325             :                         //81-7 = 74 bits till reserved
    9326           0 :                         gf_bs_read_data(bs, ptl->gci+1, 9);
    9327           0 :                         ptl->gci[10] = gf_bs_read_int(bs, 2)<<6;
    9328             :                         //skip extensions
    9329           0 :                         ptl->gci[11] = 0;
    9330           0 :                         res = gf_bs_read_int(bs, 8);
    9331           0 :                         gf_bs_read_int(bs, res);
    9332             :                 }
    9333           0 :                 gf_bs_align(bs);
    9334             :         }
    9335           0 :         for (i=ptl->ptl_max_tid; i>0; i--) {
    9336           0 :                 ptl->sub_ptl[i-1].level_present_flag = gf_bs_read_int_log_idx2(bs, 1, "level_present_flag", idx, i);
    9337             :         }
    9338           0 :         gf_bs_align(bs);
    9339           0 :         for (i=ptl->ptl_max_tid; i>0; i--) {
    9340           0 :                 if (ptl->sub_ptl[i-1].level_present_flag)
    9341           0 :                         ptl->sub_ptl[i-1].sublayer_level_idc = gf_bs_read_int_log_idx2(bs, 8, "sublayer_level_idc", idx, i);
    9342             :         }
    9343           0 :         if (ptl->pt_present) {
    9344           0 :                 ptl->num_sub_profiles = gf_bs_read_int_log_idx(bs, 8, "num_sub_profiles", idx);
    9345           0 :                 for (i=0; i<ptl->num_sub_profiles; i++) {
    9346           0 :                         ptl->sub_profile_idc[i] = gf_bs_read_int_log_idx2(bs, 32, "sub_profile_idc", idx, i);
    9347             :                 }
    9348             :         }
    9349           0 : }
    9350             : 
    9351           0 : static s32 gf_media_vvc_read_vps_bs_internal(GF_BitStream *bs, VVCState *vvc, Bool stop_at_vps_ext)
    9352             : {
    9353             :         u32 i, j;
    9354             :         s32 vps_id;
    9355             :         VVC_VPS *vps;
    9356             :         Bool vps_default_ptl_dpb_hrd_max_tid_flag=0;
    9357             : 
    9358             :         //nalu header already parsed
    9359           0 :         vps_id = gf_bs_read_int_log(bs, 4, "vps_id");
    9360           0 :         if ((vps_id<0) || (vps_id >= 16)) return -1;
    9361           0 :         if (!vps_id) {
    9362           0 :                 GF_LOG(GF_LOG_ERROR, GF_LOG_CODING, ("[VVC] VPS ID 0 is forbidden\n"));
    9363             :                 return -1;
    9364             :         }
    9365             :         vps = &vvc->vps[vps_id];
    9366           0 :         if (!vps->state) {
    9367           0 :                 vps->id = vps_id;
    9368           0 :                 vps->state = 1;
    9369             :         }
    9370           0 :         vps->max_layers = 1 + gf_bs_read_int_log(bs, 6, "max_layers");
    9371           0 :         if (vps->max_layers > MAX_LHVC_LAYERS) {
    9372           0 :                 GF_LOG(GF_LOG_ERROR, GF_LOG_CODING, ("[VVC] sorry, %d layers in VPS but only %d supported\n", vps->max_layers, MAX_LHVC_LAYERS));
    9373             :                 return -1;
    9374             :         }
    9375           0 :         vps->max_sub_layers = gf_bs_read_int_log(bs, 3, "max_sub_layers_minus1") + 1;
    9376             : 
    9377           0 :         if ((vps->max_layers>1) && (vps->max_sub_layers>1))
    9378             :                 vps_default_ptl_dpb_hrd_max_tid_flag = gf_bs_read_int_log(bs, 1, "vps_default_ptl_dpb_hrd_max_tid_flag");
    9379             : 
    9380           0 :         if (vps->max_layers>1)
    9381           0 :                 vps->all_layers_independent = gf_bs_read_int_log(bs, 1, "all_layers_independent");
    9382             : 
    9383           0 :         for (i=0; i<vps->max_layers; i++) {
    9384           0 :                 u32 layer_id = gf_bs_read_int_log_idx(bs, 6, "layer_id", i);
    9385           0 :                 if (layer_id>vps->max_layer_id) vps->max_layer_id = layer_id;
    9386           0 :                 if (i && !vps->all_layers_independent) {
    9387             :                         Bool layer_indep = gf_bs_read_int_log_idx(bs, 1, "layer_independent", i);
    9388           0 :                         if (!layer_indep) {
    9389             :                                 Bool vps_max_tid_ref_present_flag = gf_bs_read_int_log_idx(bs, 1, "vps_max_tid_ref_present_flag", i);
    9390           0 :                                 for (j=0; j<i; j++) {
    9391           0 :                                         Bool vps_direct_ref_layer_flag = gf_bs_read_int_log_idx2(bs, 1, "vps_direct_ref_layer_flag", i, j);
    9392           0 :                                         if (vps_max_tid_ref_present_flag && vps_direct_ref_layer_flag) {
    9393           0 :                                                 gf_bs_read_int_log_idx2(bs, 3, "vps_max_tid_il_ref_pics_plus1", i, j);
    9394             :                                         }
    9395             :                                 }
    9396             :                         }
    9397             :                 }
    9398             :         }
    9399           0 :         vps->num_ptl = 1;
    9400           0 :         if (vps->max_layers > 1) {
    9401           0 :                 if (vps->all_layers_independent) {
    9402           0 :                         vps->each_layer_is_ols = gf_bs_read_int_log(bs, 1, "each_layer_is_ols");
    9403             :                 }
    9404           0 :                 if (!vps->each_layer_is_ols) {
    9405             :                         u32 vps_ols_mode_idc = 2;
    9406           0 :                         if (!vps->all_layers_independent) {
    9407             :                                 vps_ols_mode_idc = gf_bs_read_int_log(bs, 2, "vps_ols_mode_idc");
    9408             :                         }
    9409           0 :                         if (vps_ols_mode_idc==2) {
    9410           0 :                                 u8 vps_num_output_layer_sets = 2 + gf_bs_read_int_log(bs, 8, "vps_num_output_layer_sets_minus2");
    9411           0 :                                 for (i=0; i<vps_num_output_layer_sets; i++) {
    9412           0 :                                         for (j=0; j<vps->max_layers; j++) {
    9413           0 :                                                 gf_bs_read_int_log_idx2(bs, 1, "vps_ols_output_layer_flag", i, j);
    9414             :                                         }
    9415             :                                 }
    9416             :                         }
    9417             :                 }
    9418           0 :                 vps->num_ptl = 1 + gf_bs_read_int_log(bs, 8, "num_ptl_minus1");
    9419             :         }
    9420           0 :         vps->ptl[0].pt_present = 1;
    9421           0 :         for (i=0; i<vps->num_ptl; i++) {
    9422           0 :                 if (i)
    9423           0 :                         vps->ptl[i].pt_present = gf_bs_read_int_log_idx(bs, 1, "pt_present", i);
    9424           0 :                 if (!vps_default_ptl_dpb_hrd_max_tid_flag)
    9425           0 :                         vps->ptl[i].ptl_max_tid = gf_bs_read_int_log_idx(bs, 3, "ptl_max_tid", i);
    9426             :                 else
    9427           0 :                         vps->ptl[i].ptl_max_tid = vps->max_sub_layers - 1;;
    9428             :         }
    9429             :         //align
    9430           0 :         gf_bs_align(bs);
    9431             : 
    9432           0 :         for (i=0; i<vps->num_ptl; i++) {
    9433           0 :                 vvc_profile_tier_level(bs, &vps->ptl[i], i);
    9434             :         }
    9435             : 
    9436             :         //TODO, parse multilayer stuff
    9437             :         return vps_id;
    9438             : }
    9439             : 
    9440             : 
    9441           0 : static s32 gf_media_vvc_read_sps_bs_internal(GF_BitStream *bs, VVCState *vvc, u8 layer_id, u32 *vui_flag_pos)
    9442             : {
    9443             :         s32 vps_id, sps_id;
    9444             :         u32 i, CtbSizeY;
    9445             :         VVC_SPS *sps;
    9446             :         u8 sps_ptl_dpb_hrd_params_present_flag;
    9447             : 
    9448           0 :         if (vui_flag_pos) *vui_flag_pos = 0;
    9449             : 
    9450           0 :         sps_id = gf_bs_read_int_log(bs, 4, "sps_id");
    9451           0 :         if ((sps_id<0) || (sps_id >= 16)) {
    9452             :                 return -1;
    9453             :         }
    9454             :         vps_id = gf_bs_read_int_log(bs, 4, "vps_id");
    9455           0 :         if ((vps_id<0) || (vps_id >= 16)) {
    9456             :                 return -1;
    9457             :         }
    9458           0 :         if (!vps_id && !vvc->vps[0].state) {
    9459           0 :                 vvc->vps[0].state = 1;
    9460           0 :                 vvc->vps[0].num_ptl = 1;
    9461           0 :                 vvc->vps[0].max_layers = 1;
    9462           0 :                 vvc->vps[0].all_layers_independent = 1;
    9463             :         }
    9464             : 
    9465             :         sps = &vvc->sps[sps_id];
    9466           0 :         if (!sps->state) {
    9467           0 :                 sps->state = 1;
    9468           0 :                 sps->id = sps_id;
    9469           0 :                 sps->vps_id = vps_id;
    9470             :         }
    9471           0 :         sps->max_sublayers = 1 + gf_bs_read_int_log(bs, 3, "max_sublayers_minus1");
    9472           0 :         sps->chroma_format_idc = gf_bs_read_int_log(bs, 2, "chroma_format_idc");
    9473           0 :         sps->log2_ctu_size = 5 + gf_bs_read_int_log(bs, 2, "log2_ctu_size_minus5");
    9474           0 :         CtbSizeY = 1<<sps->log2_ctu_size;
    9475             : 
    9476           0 :         sps_ptl_dpb_hrd_params_present_flag = gf_bs_read_int_log(bs, 1, "sps_ptl_dpb_hrd_params_present_flag");
    9477           0 :         if (sps_ptl_dpb_hrd_params_present_flag) {
    9478             :                 VVC_ProfileTierLevel ptl, *p_ptl;
    9479           0 :                 if (sps->vps_id) {
    9480             :                         p_ptl = &ptl;
    9481             :                 } else {
    9482           0 :                         p_ptl = &vvc->vps[0].ptl[0];
    9483             :                 }
    9484             :                 memset(p_ptl, 0, sizeof(VVC_ProfileTierLevel));
    9485           0 :                 p_ptl->pt_present = 1;
    9486           0 :                 p_ptl->ptl_max_tid = sps->max_sublayers-1;
    9487           0 :                 vvc_profile_tier_level(bs, p_ptl, 0);
    9488             :         }
    9489           0 :         sps->gdr_enabled = gf_bs_read_int_log(bs, 1, "gdr_enabled");
    9490           0 :         sps->ref_pic_resampling = gf_bs_read_int_log(bs, 1, "ref_pic_resampling");
    9491           0 :         if (sps->ref_pic_resampling)
    9492           0 :                 sps->res_change_in_clvs = gf_bs_read_int_log(bs, 1, "res_change_in_clvs");
    9493           0 :         sps->width = gf_bs_read_ue_log(bs, "width");
    9494           0 :         sps->height = gf_bs_read_ue_log(bs, "height");
    9495           0 :         sps->conf_window = gf_bs_read_int_log(bs, 1, "conformance_window_present_flag");
    9496           0 :         if (sps->conf_window) {
    9497           0 :                 sps->cw_left = gf_bs_read_ue_log(bs, "conformance_window_left");
    9498           0 :                 sps->cw_right = gf_bs_read_ue_log(bs, "conformance_window_right");
    9499           0 :                 sps->cw_top = gf_bs_read_ue_log(bs, "conformance_window_top");
    9500           0 :                 sps->cw_bottom = gf_bs_read_ue_log(bs, "conformance_window_bottom");
    9501             :         }
    9502           0 :         sps->subpic_info_present = gf_bs_read_int_log(bs, 1, "subpic_info_present");
    9503           0 :         if (sps->subpic_info_present) {
    9504           0 :                 sps->nb_subpics = 1 + gf_bs_read_ue_log(bs, "nb_subpics_minus1");
    9505           0 :                 if (sps->nb_subpics>1) {
    9506             :                         u32 tmpWidthVal, tmpHeightVal;
    9507           0 :                         sps->independent_subpic_flags = gf_bs_read_int_log(bs, 1, "independent_subpic_flags");
    9508           0 :                         sps->subpic_same_size = gf_bs_read_int_log(bs, 1, "subpic_same_size");
    9509             : 
    9510           0 :                         tmpWidthVal = (sps->width + CtbSizeY-1) / CtbSizeY;
    9511           0 :                         tmpWidthVal = gf_get_bit_size(tmpWidthVal);
    9512           0 :                         tmpHeightVal = (sps->height + CtbSizeY-1) / CtbSizeY;
    9513           0 :                         tmpHeightVal = gf_get_bit_size(tmpHeightVal);
    9514             : 
    9515           0 :                         for (i=0; i<sps->nb_subpics; i++) {
    9516           0 :                                 if( !sps->subpic_same_size || !i) {
    9517           0 :                                         if (i && (sps->width > CtbSizeY))
    9518           0 :                                                 gf_bs_read_int_log(bs, tmpWidthVal, "subpic_ctu_top_left_x");
    9519           0 :                                         if (i && (sps->height > CtbSizeY))
    9520           0 :                                                 gf_bs_read_int_log(bs, tmpHeightVal, "subpic_ctu_top_left_y");
    9521           0 :                                         if ((i+1 < sps->nb_subpics) && (sps->width > CtbSizeY))
    9522           0 :                                                 gf_bs_read_int_log(bs, tmpWidthVal, "subpic_width_minus1");
    9523           0 :                                         if ((i+1 < sps->nb_subpics) && (sps->height > CtbSizeY))
    9524           0 :                                                 gf_bs_read_int_log(bs, tmpHeightVal, "subpic_height_minus1");
    9525             :                                 }
    9526           0 :                                 if (!sps->independent_subpic_flags) {
    9527           0 :                                         gf_bs_read_int_log(bs, 1, "subpic_treated_as_pic_flag");
    9528           0 :                                         gf_bs_read_int_log(bs, 1, "loop_filter_across_subpic_enabled_flag");
    9529             :                                 }
    9530             :                         }
    9531           0 :                         sps->subpicid_len = gf_bs_read_ue_log(bs, "subpic_id_len_minus1") + 1;
    9532           0 :                         sps->subpicid_mapping_explicit = gf_bs_read_int_log(bs, 1, "subpic_id_mapping_explicitly_signalled_flag");
    9533           0 :                         if (sps->subpicid_mapping_explicit) {
    9534           0 :                                 sps->subpicid_mapping_present = gf_bs_read_int_log(bs, 1, "subpic_id_mapping_present_flag");
    9535           0 :                                 if (sps->subpicid_mapping_present) {
    9536           0 :                                         for (i=0; i<sps->nb_subpics; i++) {
    9537           0 :                                                 gf_bs_read_ue_log(bs, "subpic_id");
    9538             :                                         }
    9539             :                                 }
    9540             :                         }
    9541             :                 }
    9542             :         }
    9543           0 :         sps->bitdepth = gf_bs_read_ue_log(bs, "bitdepth_minus8") + 8;
    9544           0 :         gf_bs_read_int_log(bs, 1, "entropy_coding_sync_enabled_flag");
    9545           0 :         gf_bs_read_int_log(bs, 1, "entry_point_offsets_present_flag");
    9546           0 :         sps->log2_max_poc_lsb = 4 + gf_bs_read_int_log(bs, 4, "log2_max_poc_lsb_minus4");
    9547           0 :         if ((sps->poc_msb_cycle_flag = gf_bs_read_int_log(bs, 1, "poc_msb_cycle_flag")))
    9548           0 :                 sps->poc_msb_cycle_len = 1 + gf_bs_read_ue_log(bs, "poc_msb_cycle_len_minus1");
    9549             : 
    9550           0 :         u8 sps_num_extra_ph_bits = 8 * gf_bs_read_int_log(bs, 2, "sps_num_extra_ph_bytes");
    9551           0 :         for (i=0; i<sps_num_extra_ph_bits; i++) {
    9552           0 :                 if (gf_bs_read_int_log_idx(bs, 1, "extra_ph_bit_present_flag", 1))
    9553           0 :                         sps->ph_num_extra_bits++;
    9554             :         }
    9555           0 :         u8 sps_num_extra_sh_bits = 8 * gf_bs_read_int_log(bs, 2, "num_extra_sh_bytes");
    9556           0 :         for (i=0; i<sps_num_extra_sh_bits; i++) {
    9557           0 :                 if (gf_bs_read_int_log_idx(bs, 1, "extra_sh_bit_present_flag", i))
    9558           0 :                         sps->sh_num_extra_bits++;
    9559             :         }
    9560             : 
    9561           0 :         if (sps_ptl_dpb_hrd_params_present_flag) {
    9562             :                 u8 sps_sublayer_dpb_params_flag = 0;
    9563           0 :                 if (sps->max_sublayers>1) {
    9564           0 :                         sps_sublayer_dpb_params_flag = gf_bs_read_int_log(bs, 1, "sps_sublayer_dpb_params_flag");
    9565             :                 }
    9566           0 :                 for (i=(sps_sublayer_dpb_params_flag ? 0 : sps->max_sublayers-1); i < sps->max_sublayers; i++ ) {
    9567           0 :                         gf_bs_read_ue_log_idx(bs, "dpb_max_dec_pic_buffering_minus1", i);
    9568           0 :                         gf_bs_read_ue_log_idx(bs, "dpb_max_num_reorder_pics", i);
    9569           0 :                         gf_bs_read_ue_log_idx(bs, "dpb_max_latency_increase_plus1", i);
    9570             :                 }
    9571             :         }
    9572           0 :         gf_bs_read_ue_log(bs, "sps_log2_min_luma_coding_block_size_minus2");
    9573           0 :         gf_bs_read_int_log(bs, 1, "sps_partition_constraints_override_enabled_flag");
    9574           0 :         gf_bs_read_ue_log(bs, "sps_log2_min_luma_coding_block_size_minus2");
    9575           0 :         u8 sps_max_mtt_hierarchy_depth_intra_slice_luma = gf_bs_read_ue_log(bs, "sps_max_mtt_hierarchy_depth_intra_slice_luma");
    9576           0 :         if (sps_max_mtt_hierarchy_depth_intra_slice_luma != 0) {
    9577           0 :                 gf_bs_read_ue_log(bs, "sps_log2_diff_max_bt_min_qt_intra_slice_luma");
    9578           0 :                 gf_bs_read_ue_log(bs, "sps_log2_diff_max_tt_min_qt_intra_slice_luma");
    9579             :         }
    9580             :         u8 sps_qtbtt_dual_tree_intra_flag = 0;
    9581           0 :         if (sps->chroma_format_idc) {
    9582           0 :                 sps_qtbtt_dual_tree_intra_flag = gf_bs_read_int_log(bs, 1, "sps_qtbtt_dual_tree_intra_flag");
    9583             :         }
    9584           0 :         if (sps_qtbtt_dual_tree_intra_flag) {
    9585           0 :                 gf_bs_read_ue_log(bs, "sps_log2_diff_min_qt_min_cb_intra_slice_chroma");
    9586           0 :                 u8 sps_max_mtt_hierarchy_depth_intra_slice_chroma = gf_bs_read_ue_log(bs, "sps_max_mtt_hierarchy_depth_intra_slice_chroma");
    9587           0 :                 if( sps_max_mtt_hierarchy_depth_intra_slice_chroma != 0) {
    9588           0 :                         gf_bs_read_ue_log(bs, "sps_log2_diff_max_bt_min_qt_intra_slice_chroma");
    9589           0 :                         gf_bs_read_ue_log(bs, "sps_log2_diff_max_tt_min_qt_intra_slice_chroma");
    9590             :                 }
    9591             :         }
    9592             : 
    9593           0 :         gf_bs_read_ue_log(bs, "sps_log2_diff_min_qt_min_cb_inter_slice");
    9594           0 :         u8 sps_max_mtt_hierarchy_depth_inter_slice = gf_bs_read_ue_log(bs, "sps_max_mtt_hierarchy_depth_inter_slice");
    9595           0 :         if (sps_max_mtt_hierarchy_depth_inter_slice != 0) {
    9596           0 :                 gf_bs_read_ue_log(bs, "sps_log2_diff_max_bt_min_qt_inter_slice");
    9597           0 :                 gf_bs_read_ue_log(bs, "sps_log2_diff_max_tt_min_qt_inter_slice");
    9598             :         }
    9599             :         //u8 sps_max_luma_transform_size_64_flag = 0;
    9600           0 :         if (CtbSizeY > 32) {
    9601           0 :                 /*sps_max_luma_transform_size_64_flag = */gf_bs_read_int_log(bs, 1, "sps_max_luma_transform_size_64_flag");
    9602             :         }
    9603           0 :         u8 sps_transform_skip_enabled_flag = gf_bs_read_int_log(bs, 1, "sps_transform_skip_enabled_flag");
    9604             : 
    9605           0 :         if (sps_transform_skip_enabled_flag) {
    9606           0 :                 gf_bs_read_ue_log(bs, "sps_log2_transform_skip_max_size_minus2");
    9607           0 :                 gf_bs_read_int_log(bs, 1, "sps_bdpcm_enabled_flag");
    9608             :         }
    9609           0 :         if (gf_bs_read_int_log(bs, 1, "sps_mts_enabled_flag")) {
    9610           0 :                 gf_bs_read_int_log(bs, 1, "sps_explicit_mts_intra_enabled_flag");
    9611           0 :                 gf_bs_read_int_log(bs, 1, "sps_explicit_mts_inter_enabled_flag");
    9612             :         }
    9613           0 :         gf_bs_read_int_log(bs, 1, "sps_lfnst_enabled_flag");
    9614           0 :         if (sps->chroma_format_idc) {
    9615           0 :                 u8 sps_joint_cbcr_enabled_flag = gf_bs_read_int_log(bs, 1, "sps_joint_cbcr_enabled_flag");
    9616           0 :                 u8 sps_same_qp_table_for_chroma_flag = gf_bs_read_int_log(bs, 1, "sps_same_qp_table_for_chroma_flag");
    9617           0 :                 u32 numQpTables = sps_same_qp_table_for_chroma_flag ? 1 : (sps_joint_cbcr_enabled_flag ? 3 : 2);
    9618           0 :                 for (i=0; i<numQpTables; i++) {
    9619           0 :                         gf_bs_read_se_log_idx(bs, "sps_qp_table_start_minus26", i);
    9620           0 :                         u32 j, sps_num_points_in_qp_table = 1 + gf_bs_read_ue_log_idx(bs, "sps_num_points_in_qp_table_minus1", i);
    9621           0 :                         for (j=0; j<sps_num_points_in_qp_table; j++) {
    9622           0 :                                 gf_bs_read_ue_log_idx2(bs, "sps_delta_qp_in_val_minus1", i, j);
    9623           0 :                                 gf_bs_read_ue_log_idx2(bs, "sps_delta_qp_diff_val", i, j);
    9624             :                         }
    9625             :                 }
    9626             :         }
    9627           0 :         gf_bs_read_int_log(bs, 1, "sps_sao_enabled_flag");
    9628           0 :         sps->alf_enabled_flag = gf_bs_read_int_log(bs, 1, "sps_alf_enabled_flag");
    9629           0 :         if (sps->alf_enabled_flag && sps->chroma_format_idc) {
    9630           0 :                 gf_bs_read_int_log(bs, 1, "sps_ccalf_enabled_flag");
    9631             :         }
    9632             :         /*! TODO parse the rest !*/
    9633             : 
    9634             :         return sps_id;
    9635             : }
    9636             : 
    9637           0 : static s32 gf_media_vvc_read_pps_bs_internal(GF_BitStream *bs, VVCState *vvc)
    9638             : {
    9639             :         u32 i;
    9640             :         s32 pps_id;
    9641             :         VVC_PPS *pps;
    9642             : 
    9643             :         //NAL header already read
    9644           0 :         pps_id = gf_bs_read_int_log(bs, 6, "pps_id");
    9645             : 
    9646           0 :         if ((pps_id < 0) || (pps_id >= 64)) {
    9647           0 :                 GF_LOG(GF_LOG_ERROR, GF_LOG_CODING, ("[VVC] wrong PPS ID %d in PPS\n", pps_id));
    9648             :                 return -1;
    9649             :         }
    9650             :         pps = &vvc->pps[pps_id];
    9651             : 
    9652           0 :         if (!pps->state) {
    9653           0 :                 pps->id = pps_id;
    9654           0 :                 pps->state = 1;
    9655             :         }
    9656           0 :         pps->sps_id = gf_bs_read_int_log(bs, 4, "sps_id");
    9657           0 :         if (((s32)pps->sps_id<0) || (pps->sps_id >= 16)) {
    9658           0 :                 GF_LOG(GF_LOG_ERROR, GF_LOG_CODING, ("[VVC] wrong SPS ID %d in PPS\n", pps->sps_id));
    9659           0 :                 pps->sps_id=0;
    9660           0 :                 return -1;
    9661             :         }
    9662           0 :         vvc->sps_active_idx = pps->sps_id; /*set active sps*/
    9663           0 :         pps->mixed_nal_types = gf_bs_read_int_log(bs, 1, "mixed_nal_types");
    9664           0 :         pps->width = gf_bs_read_ue_log(bs, "width");
    9665           0 :         pps->height = gf_bs_read_ue_log(bs, "height");
    9666           0 :         pps->conf_window = gf_bs_read_int_log(bs, 1, "conformance_window_flag");
    9667           0 :         if (pps->conf_window) {
    9668           0 :                 pps->cw_left = gf_bs_read_ue_log(bs, "conf_win_left_offset");
    9669           0 :                 pps->cw_right = gf_bs_read_ue_log(bs, "conf_win_right_offset");
    9670           0 :                 pps->cw_top = gf_bs_read_ue_log(bs, "conf_win_top_offset");
    9671           0 :                 pps->cw_bottom = gf_bs_read_ue_log(bs, "conf_win_bottom_offset");
    9672             :         }
    9673             :         //scaling window
    9674           0 :         if (gf_bs_read_int_log(bs, 1, "scaling_window_explicit_signaling_flag")) {
    9675           0 :                 gf_bs_read_se_log(bs, "scaling_win_left_offset");
    9676           0 :                 gf_bs_read_se_log(bs, "scaling_win_right_offset");
    9677           0 :                 gf_bs_read_se_log(bs, "scaling_win_top_offset");
    9678           0 :                 gf_bs_read_se_log(bs, "scaling_win_bottom_offset");
    9679             :         }
    9680           0 :         pps->output_flag_present_flag = gf_bs_read_int_log(bs, 1, "output_flag_present_flag");
    9681           0 :         pps->no_pic_partition_flag = gf_bs_read_int_log(bs, 1, "no_pic_partition_flag");
    9682           0 :         pps->subpic_id_mapping_present_flag = gf_bs_read_int_log(bs, 1, "subpic_id_mapping_present_flag");
    9683           0 :         if (pps->subpic_id_mapping_present_flag) {
    9684             :                 u32 pps_subpic_id_len, pps_num_subpics=0;
    9685           0 :                 if (!pps->no_pic_partition_flag) {
    9686           0 :                         pps_num_subpics = 1+gf_bs_read_ue_log(bs, "pps_num_subpics_minus1");
    9687             :                 }
    9688           0 :                 pps_subpic_id_len = 1 + gf_bs_read_ue(bs);
    9689           0 :                 for (i=0; i<pps_num_subpics; i++) {
    9690           0 :                         gf_bs_read_int_log_idx(bs, pps_subpic_id_len, "subpic_id", i);
    9691             :                 }
    9692             :         }
    9693           0 :         if (!pps->no_pic_partition_flag) {
    9694           0 :                 gf_bs_read_int_log(bs, 2, "pps_log2_ctu_size_minus5");
    9695           0 :                 u32 num_exp_tile_columns = 1 + gf_bs_read_ue_log(bs, "num_exp_tile_columns_minus1");
    9696           0 :                 u32 num_exp_tile_rows = 1 + gf_bs_read_ue_log(bs, "num_exp_tile_rows_minus1");
    9697           0 :                 for (i=0; i<num_exp_tile_columns; i++)
    9698           0 :                         gf_bs_read_ue_log_idx(bs, "tile_column_width_minus1", i);
    9699           0 :                 for (i=0; i<num_exp_tile_rows; i++)
    9700           0 :                         gf_bs_read_ue_log_idx(bs, "tile_row_height_minus1", i);
    9701             : 
    9702             :                 //todo parse the rest
    9703             :                 return pps_id;
    9704             :         }
    9705             : 
    9706             : 
    9707             :         //todo parse the rest
    9708             : 
    9709             :         return pps_id;
    9710             : }
    9711             : 
    9712             : static
    9713           0 : s32 vvc_parse_picture_header(GF_BitStream *bs, VVCState *vvc, VVCSliceInfo *si)
    9714             : {
    9715             :         s32 pps_id;
    9716             : 
    9717           0 :         si->irap_or_gdr_pic = gf_bs_read_int_log(bs, 1, "irap_or_gdr_pic");
    9718           0 :         si->non_ref_pic = gf_bs_read_int_log(bs, 1, "non_ref_pic");
    9719           0 :         if (si->irap_or_gdr_pic)
    9720           0 :                 si->gdr_pic = gf_bs_read_int_log(bs, 1, "gdr_pic");
    9721           0 :         if ((si->inter_slice_allowed_flag = gf_bs_read_int_log(bs, 1, "inter_slice_allowed_flag")))
    9722           0 :                 si->intra_slice_allowed_flag = gf_bs_read_int_log(bs, 1, "intra_slice_allowed_flag");
    9723             : 
    9724           0 :         pps_id = gf_bs_read_ue_log(bs, "pps_id");
    9725           0 :         if ((pps_id<0) || (pps_id >= 64))
    9726             :                 return -1;
    9727           0 :         si->pps = &vvc->pps[pps_id];
    9728           0 :         si->sps = &vvc->sps[si->pps->sps_id];
    9729           0 :         si->poc_lsb = gf_bs_read_int_log(bs, si->sps->log2_max_poc_lsb, "poc_lsb");
    9730             : 
    9731           0 :         si->recovery_point_valid = 0;
    9732           0 :         si->gdr_recovery_count = 0;
    9733           0 :         if (si->gdr_pic) {
    9734           0 :                 si->recovery_point_valid = 1;
    9735           0 :                 si->gdr_recovery_count = gf_bs_read_ue_log(bs, "gdr_recovery_count");
    9736             :         }
    9737           0 :         gf_bs_read_int_log(bs, si->sps->ph_num_extra_bits, "ph_extra_bits");
    9738             : 
    9739           0 :         if (si->sps->poc_msb_cycle_flag) {
    9740           0 :                 if ( (si->poc_msb_cycle_present_flag = gf_bs_read_int_log(bs, 1, "poc_msb_cycle_present_flag"))) {
    9741           0 :                         si->poc_msb_cycle = gf_bs_read_int_log(bs, si->sps->poc_msb_cycle_len, "poc_msb_cycle");
    9742             :                 }
    9743             :         }
    9744             : 
    9745             :         return 0;
    9746             : }
    9747             : 
    9748           0 : static s32 vvc_parse_slice(GF_BitStream *bs, VVCState *vvc, VVCSliceInfo *si)
    9749             : {
    9750             : //      u32 CurrSubpicIdx = 0;
    9751             : 
    9752           0 :         si->picture_header_in_slice_header_flag = gf_bs_read_int_log(bs, 1, "picture_header_in_slice_header_flag");
    9753           0 :         if (si->picture_header_in_slice_header_flag) {
    9754           0 :                 GF_LOG(GF_LOG_DEBUG, GF_LOG_CODING, ("[VVC] Picture header in slice header incomplete support, cannot guess slice type\n"));
    9755           0 :                 si->slice_type = GF_VVC_SLICE_TYPE_UNKNOWN;
    9756           0 :                 return vvc_parse_picture_header(bs, vvc, si);
    9757             :         }
    9758           0 :         if (!si->sps) return -1;
    9759           0 :         si->slice_type = GF_VVC_SLICE_TYPE_I;
    9760           0 :         if (gf_bs_read_int_log(bs, 1, "sps_subpic_info_present_flag")) {
    9761           0 :                 gf_bs_read_int_log(bs, si->sps->subpicid_len, "subpic_id");
    9762             :                 //todo update CurrSubpicIdx
    9763             :         }
    9764             : 
    9765           0 :         if (si->pps->rect_slice_flag ) {
    9766           0 :                 GF_LOG(GF_LOG_WARNING, GF_LOG_CODING, ("[VVC] tiling parsing not supported - patch welcome\n"));
    9767             :                 return 0;
    9768             :         }
    9769           0 :         gf_bs_read_int_log(bs, si->sps->sh_num_extra_bits, "num_extra_bits");
    9770             :         /*
    9771             :                 if( !pps_rect_slice_flag  &&  NumTilesInPic − sh_slice_address > 1 )
    9772             :                 sh_num_tiles_in_slice_minus1
    9773             : 
    9774             :          */
    9775             : 
    9776           0 :         if (si->inter_slice_allowed_flag )
    9777           0 :                 si->slice_type = gf_bs_read_int_log(bs, 2, "slice_type");
    9778             : 
    9779             :         return 0;
    9780             : }
    9781             : 
    9782             : /*this needs further tests !*/
    9783           0 : static void vvc_compute_poc(VVCSliceInfo *si)
    9784             : {
    9785           0 :         u32 max_poc_lsb = 1 << (si->sps->log2_max_poc_lsb);
    9786             : 
    9787             :         /*POC reset for IDR frames, NOT for CRA*/
    9788           0 :         if (si->irap_or_gdr_pic && !si->gdr_pic) {
    9789           0 :                 si->poc_lsb_prev = 0;
    9790           0 :                 si->poc_msb_prev = 0;
    9791             :         }
    9792             : 
    9793           0 :         if (si->poc_msb_cycle_present_flag) {
    9794           0 :                 si->poc_msb = si->poc_msb_cycle;
    9795             :         } else {
    9796           0 :                 if ((si->poc_lsb < si->poc_lsb_prev) && (si->poc_lsb_prev - si->poc_lsb >= max_poc_lsb / 2))
    9797           0 :                         si->poc_msb = si->poc_msb_prev + max_poc_lsb;
    9798           0 :                 else if ((si->poc_lsb > si->poc_lsb_prev) && (si->poc_lsb - si->poc_lsb_prev > max_poc_lsb / 2))
    9799           0 :                         si->poc_msb = si->poc_msb_prev - max_poc_lsb;
    9800             :                 else
    9801           0 :                         si->poc_msb = si->poc_msb_prev;
    9802             :         }
    9803             : 
    9804           0 :         si->poc = si->poc_msb + si->poc_lsb;
    9805           0 : }
    9806             : 
    9807             : 
    9808             : GF_EXPORT
    9809           0 : s32 gf_media_vvc_parse_nalu_bs(GF_BitStream *bs, VVCState *vvc, u8 *nal_unit_type, u8 *temporal_id, u8 *layer_id)
    9810             : {
    9811             :         Bool is_slice = GF_FALSE;
    9812             :         s32 ret = -1;
    9813             :         VVCSliceInfo n_state;
    9814             : 
    9815           0 :         gf_bs_enable_emulation_byte_removal(bs, GF_TRUE);
    9816             : 
    9817           0 :         memcpy(&n_state, &vvc->s_info, sizeof(VVCSliceInfo));
    9818           0 :         if (!vvc_parse_nal_header(bs, nal_unit_type, temporal_id, layer_id)) return -1;
    9819             : 
    9820           0 :         n_state.nal_unit_type = *nal_unit_type;
    9821             : 
    9822           0 :         switch (n_state.nal_unit_type) {
    9823             :         case GF_VVC_NALU_ACCESS_UNIT:
    9824             :         case GF_VVC_NALU_END_OF_SEQ:
    9825             :         case GF_VVC_NALU_END_OF_STREAM:
    9826             :                 ret = 1;
    9827             :                 break;
    9828             : 
    9829           0 :         case GF_VVC_NALU_SLICE_TRAIL:
    9830             :         case GF_VVC_NALU_SLICE_STSA:
    9831             :         case GF_VVC_NALU_SLICE_RADL:
    9832             :         case GF_VVC_NALU_SLICE_RASL:
    9833             :         case GF_VVC_NALU_SLICE_IDR_W_RADL:
    9834             :         case GF_VVC_NALU_SLICE_IDR_N_LP:
    9835             :         case GF_VVC_NALU_SLICE_CRA:
    9836             :         case GF_VVC_NALU_SLICE_GDR:
    9837             :                 /* slice - read the info and compare.*/
    9838           0 :                 ret = vvc_parse_slice(bs, vvc, &n_state);
    9839           0 :                 if (ret < 0) return ret;
    9840             : 
    9841             :                 ret = 0;
    9842           0 :                 if (n_state.picture_header_in_slice_header_flag) {
    9843             :                         is_slice = GF_TRUE;
    9844           0 :                         vvc_compute_poc(&n_state);
    9845           0 :                         if (vvc->s_info.poc != n_state.poc) {
    9846             :                                 ret = 1;
    9847             :                                 break;
    9848             :                         }
    9849           0 :                         if (!(*layer_id) || (n_state.prev_layer_id_plus1 && ((*layer_id) <= n_state.prev_layer_id_plus1 - 1))) {
    9850             :                                 ret = 1;
    9851             :                                 break;
    9852             :                         }
    9853             :                 }
    9854             :                 break;
    9855             : 
    9856           0 :         case GF_VVC_NALU_PIC_HEADER:
    9857           0 :                 if (vvc_parse_picture_header(bs, vvc, &n_state)<0) {
    9858             :                         ret = -1;
    9859             :                         break;
    9860             :                 }
    9861             :                 is_slice = GF_TRUE;
    9862           0 :                 vvc_compute_poc(&n_state);
    9863           0 :                 if (!(*layer_id) || (n_state.prev_layer_id_plus1 && ((*layer_id) <= n_state.prev_layer_id_plus1 - 1))) {
    9864             :                         ret = 1;
    9865             :                 }
    9866             :                 break;
    9867           0 :         case GF_VVC_NALU_SEQ_PARAM:
    9868           0 :                 vvc->last_parsed_sps_id = gf_media_vvc_read_sps_bs_internal(bs, vvc, *layer_id, NULL);
    9869           0 :                 ret = (vvc->last_parsed_sps_id>=0) ? 0 : -1;
    9870             :                 break;
    9871           0 :         case GF_VVC_NALU_PIC_PARAM:
    9872           0 :                 vvc->last_parsed_pps_id = gf_media_vvc_read_pps_bs_internal(bs, vvc);
    9873           0 :                 ret = (vvc->last_parsed_pps_id>=0) ? 0 : -1;
    9874             :                 break;
    9875           0 :         case GF_VVC_NALU_VID_PARAM:
    9876           0 :                 vvc->last_parsed_vps_id = gf_media_vvc_read_vps_bs_internal(bs, vvc, GF_FALSE);
    9877           0 :                 ret = (vvc->last_parsed_vps_id>=0) ? 0 : -1;
    9878             :                 break;
    9879             :         case GF_VVC_NALU_DEC_PARAM:
    9880             :                 ret = 0;
    9881             :                 break;
    9882             :         case GF_VVC_NALU_APS_PREFIX:
    9883             :                 //we use the mix aps type + aps id (first 8 bits) as unique identifier
    9884           0 :                 vvc->last_parsed_aps_id = gf_bs_read_int_log(bs, 8, "aps_id");
    9885             :                 ret = 0;
    9886             :                 break;
    9887             :         default:
    9888             :                 ret = 0;
    9889             :                 break;
    9890             :         }
    9891             : 
    9892             :         /* save _prev values */
    9893           0 :         if ((ret>0) && vvc->s_info.sps) {
    9894             : //              n_state.frame_num_offset_prev = vvc->s_info.frame_num_offset;
    9895             : //              n_state.frame_num_prev = vvc->s_info.frame_num;
    9896             : 
    9897           0 :                 n_state.poc_lsb_prev = vvc->s_info.poc_lsb;
    9898           0 :                 n_state.poc_msb_prev = vvc->s_info.poc_msb;
    9899           0 :                 if (is_slice)
    9900           0 :                         n_state.prev_layer_id_plus1 = *layer_id + 1;
    9901             :         }
    9902           0 :         if (is_slice) vvc_compute_poc(&n_state);
    9903             :         memcpy(&vvc->s_info, &n_state, sizeof(VVCSliceInfo));
    9904             : 
    9905           0 :         return ret;
    9906             : }
    9907             : 
    9908             : GF_EXPORT
    9909           0 : s32 gf_media_vvc_parse_nalu(u8 *data, u32 size, VVCState *vvc, u8 *nal_unit_type, u8 *temporal_id, u8 *layer_id)
    9910             : {
    9911             :         GF_BitStream *bs = NULL;
    9912             :         s32 ret;
    9913             : 
    9914           0 :         if (!vvc) {
    9915           0 :                 if (nal_unit_type) (*nal_unit_type) = data[1] >> 3;
    9916           0 :                 if (layer_id) (*layer_id) = data[0] & 0x3f;
    9917           0 :                 if (temporal_id) (*temporal_id) = (data[1] & 0x7);
    9918             :                 return -1;
    9919             :         }
    9920           0 :         bs = gf_bs_new(data, size, GF_BITSTREAM_READ);
    9921           0 :         if (!bs) return -1;
    9922           0 :         gf_bs_enable_emulation_byte_removal(bs, GF_TRUE);
    9923             : 
    9924           0 :         ret = gf_media_vvc_parse_nalu_bs(bs, vvc, nal_unit_type, temporal_id, layer_id);
    9925           0 :         gf_bs_del(bs);
    9926           0 :         return ret;
    9927             : }
    9928             : 
    9929           0 : Bool gf_media_vvc_slice_is_ref(VVCState *vvc)
    9930             : {
    9931           0 :         if (!vvc->s_info.irap_or_gdr_pic) {
    9932             :                 return GF_FALSE;
    9933             :         }
    9934           0 :         if (vvc->s_info.gdr_pic) {
    9935           0 :                 if (vvc->s_info.recovery_point_valid) {
    9936           0 :                         vvc->s_info.recovery_point_valid = 0;
    9937           0 :                         return GF_TRUE;
    9938             :                 }
    9939             :                 return GF_FALSE;
    9940             :         }
    9941             :         return GF_TRUE;
    9942             : }

Generated by: LCOV version 1.13