LCOV - code coverage report
Current view: top level - libavformat - nutdec.c (source / functions) Hit Total Coverage
Test: coverage.info Lines: 481 846 56.9 %
Date: 2017-12-11 04:34:20 Functions: 19 23 82.6 %

          Line data    Source code
       1             : /*
       2             :  * "NUT" Container Format demuxer
       3             :  * Copyright (c) 2004-2006 Michael Niedermayer
       4             :  * Copyright (c) 2003 Alex Beregszaszi
       5             :  *
       6             :  * This file is part of FFmpeg.
       7             :  *
       8             :  * FFmpeg is free software; you can redistribute it and/or
       9             :  * modify it under the terms of the GNU Lesser General Public
      10             :  * License as published by the Free Software Foundation; either
      11             :  * version 2.1 of the License, or (at your option) any later version.
      12             :  *
      13             :  * FFmpeg is distributed in the hope that it will be useful,
      14             :  * but WITHOUT ANY WARRANTY; without even the implied warranty of
      15             :  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
      16             :  * Lesser General Public License for more details.
      17             :  *
      18             :  * You should have received a copy of the GNU Lesser General Public
      19             :  * License along with FFmpeg; if not, write to the Free Software
      20             :  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
      21             :  */
      22             : 
      23             : #include "libavutil/avstring.h"
      24             : #include "libavutil/avassert.h"
      25             : #include "libavutil/bswap.h"
      26             : #include "libavutil/dict.h"
      27             : #include "libavutil/intreadwrite.h"
      28             : #include "libavutil/mathematics.h"
      29             : #include "libavutil/tree.h"
      30             : #include "libavcodec/bytestream.h"
      31             : #include "avio_internal.h"
      32             : #include "isom.h"
      33             : #include "nut.h"
      34             : #include "riff.h"
      35             : 
      36             : #define NUT_MAX_STREAMS 256    /* arbitrary sanity check value */
      37             : 
      38             : static int64_t nut_read_timestamp(AVFormatContext *s, int stream_index,
      39             :                                   int64_t *pos_arg, int64_t pos_limit);
      40             : 
      41         208 : static int get_str(AVIOContext *bc, char *string, unsigned int maxlen)
      42             : {
      43         208 :     unsigned int len = ffio_read_varlen(bc);
      44             : 
      45         208 :     if (len && maxlen)
      46         208 :         avio_read(bc, string, FFMIN(len, maxlen));
      47         416 :     while (len > maxlen) {
      48           0 :         avio_r8(bc);
      49           0 :         len--;
      50           0 :         if (bc->eof_reached)
      51           0 :             len = maxlen;
      52             :     }
      53             : 
      54         208 :     if (maxlen)
      55         208 :         string[FFMIN(len, maxlen - 1)] = 0;
      56             : 
      57         208 :     if (bc->eof_reached)
      58           0 :         return AVERROR_EOF;
      59         208 :     if (maxlen == len)
      60           0 :         return -1;
      61             :     else
      62         208 :         return 0;
      63             : }
      64             : 
      65         382 : static int64_t get_s(AVIOContext *bc)
      66             : {
      67         382 :     int64_t v = ffio_read_varlen(bc) + 1;
      68             : 
      69         382 :     if (v & 1)
      70         276 :         return -(v >> 1);
      71             :     else
      72         106 :         return  (v >> 1);
      73             : }
      74             : 
      75          40 : static uint64_t get_fourcc(AVIOContext *bc)
      76             : {
      77          40 :     unsigned int len = ffio_read_varlen(bc);
      78             : 
      79          40 :     if (len == 2)
      80           0 :         return avio_rl16(bc);
      81          40 :     else if (len == 4)
      82          40 :         return avio_rl32(bc);
      83             :     else {
      84           0 :         av_log(NULL, AV_LOG_ERROR, "Unsupported fourcc length %d\n", len);
      85           0 :         return -1;
      86             :     }
      87             : }
      88             : 
      89         876 : static int get_packetheader(NUTContext *nut, AVIOContext *bc,
      90             :                             int calculate_checksum, uint64_t startcode)
      91             : {
      92             :     int64_t size;
      93             : 
      94         876 :     startcode = av_be2ne64(startcode);
      95         876 :     startcode = ff_crc04C11DB7_update(0, (uint8_t*) &startcode, 8);
      96             : 
      97         876 :     ffio_init_checksum(bc, ff_crc04C11DB7_update, startcode);
      98         876 :     size = ffio_read_varlen(bc);
      99         876 :     if (size > 4096)
     100           0 :         avio_rb32(bc);
     101         876 :     if (ffio_get_checksum(bc) && size > 4096)
     102           0 :         return -1;
     103             : 
     104         876 :     ffio_init_checksum(bc, calculate_checksum ? ff_crc04C11DB7_update : NULL, 0);
     105             : 
     106         876 :     return size;
     107             : }
     108             : 
     109         266 : static uint64_t find_any_startcode(AVIOContext *bc, int64_t pos)
     110             : {
     111         266 :     uint64_t state = 0;
     112             : 
     113         266 :     if (pos >= 0)
     114             :         /* Note, this may fail if the stream is not seekable, but that should
     115             :          * not matter, as in this case we simply start where we currently are */
     116         242 :         avio_seek(bc, pos, SEEK_SET);
     117       13950 :     while (!avio_feof(bc)) {
     118       13684 :         state = (state << 8) | avio_r8(bc);
     119       13684 :         if ((state >> 56) != 'N')
     120       13391 :             continue;
     121         293 :         switch (state) {
     122         266 :         case MAIN_STARTCODE:
     123             :         case STREAM_STARTCODE:
     124             :         case SYNCPOINT_STARTCODE:
     125             :         case INFO_STARTCODE:
     126             :         case INDEX_STARTCODE:
     127         266 :             return state;
     128             :         }
     129             :     }
     130             : 
     131           0 :     return 0;
     132             : }
     133             : 
     134             : /**
     135             :  * Find the given startcode.
     136             :  * @param code the startcode
     137             :  * @param pos the start position of the search, or -1 if the current position
     138             :  * @return the position of the startcode or -1 if not found
     139             :  */
     140         114 : static int64_t find_startcode(AVIOContext *bc, uint64_t code, int64_t pos)
     141             : {
     142          24 :     for (;;) {
     143         114 :         uint64_t startcode = find_any_startcode(bc, pos);
     144         114 :         if (startcode == code)
     145          90 :             return avio_tell(bc) - 8;
     146          24 :         else if (startcode == 0)
     147           0 :             return -1;
     148          24 :         pos = -1;
     149             :     }
     150             : }
     151             : 
     152        6130 : static int nut_probe(AVProbeData *p)
     153             : {
     154             :     int i;
     155             : 
     156   128183395 :     for (i = 0; i < p->buf_size-8; i++) {
     157   128177289 :         if (AV_RB32(p->buf+i) != MAIN_STARTCODE>>32)
     158   128177265 :             continue;
     159          24 :         if (AV_RB32(p->buf+i+4) == (MAIN_STARTCODE & 0xFFFFFFFF))
     160          24 :             return AVPROBE_SCORE_MAX;
     161             :     }
     162        6106 :     return 0;
     163             : }
     164             : 
     165             : #define GET_V(dst, check)                                                     \
     166             :     do {                                                                      \
     167             :         tmp = ffio_read_varlen(bc);                                           \
     168             :         if (!(check)) {                                                       \
     169             :             av_log(s, AV_LOG_ERROR, "Error " #dst " is (%"PRId64")\n", tmp);  \
     170             :             ret = AVERROR_INVALIDDATA;                                        \
     171             :             goto fail;                                                        \
     172             :         }                                                                     \
     173             :         dst = tmp;                                                            \
     174             :     } while (0)
     175             : 
     176         853 : static int skip_reserved(AVIOContext *bc, int64_t pos)
     177             : {
     178         853 :     pos -= avio_tell(bc);
     179         853 :     if (pos < 0) {
     180           0 :         avio_seek(bc, pos, SEEK_CUR);
     181           0 :         return AVERROR_INVALIDDATA;
     182             :     } else {
     183        5310 :         while (pos--) {
     184        3604 :             if (bc->eof_reached)
     185           0 :                 return AVERROR_INVALIDDATA;
     186        3604 :             avio_r8(bc);
     187             :         }
     188         853 :         return 0;
     189             :     }
     190             : }
     191             : 
     192          24 : static int decode_main_header(NUTContext *nut)
     193             : {
     194          24 :     AVFormatContext *s = nut->avf;
     195          24 :     AVIOContext *bc    = s->pb;
     196             :     uint64_t tmp, end;
     197             :     unsigned int stream_count;
     198             :     int i, j, count, ret;
     199             :     int tmp_stream, tmp_mul, tmp_pts, tmp_size, tmp_res, tmp_head_idx;
     200             : 
     201          24 :     end  = get_packetheader(nut, bc, 1, MAIN_STARTCODE);
     202          24 :     end += avio_tell(bc);
     203             : 
     204          24 :     nut->version = ffio_read_varlen(bc);
     205          48 :     if (nut->version < NUT_MIN_VERSION ||
     206          24 :         nut->version > NUT_MAX_VERSION) {
     207           0 :         av_log(s, AV_LOG_ERROR, "Version %d not supported.\n",
     208             :                nut->version);
     209           0 :         return AVERROR(ENOSYS);
     210             :     }
     211          24 :     if (nut->version > 3)
     212           0 :         nut->minor_version = ffio_read_varlen(bc);
     213             : 
     214          24 :     GET_V(stream_count, tmp > 0 && tmp <= NUT_MAX_STREAMS);
     215             : 
     216          24 :     nut->max_distance = ffio_read_varlen(bc);
     217          24 :     if (nut->max_distance > 65536) {
     218           0 :         av_log(s, AV_LOG_DEBUG, "max_distance %d\n", nut->max_distance);
     219           0 :         nut->max_distance = 65536;
     220             :     }
     221             : 
     222          24 :     GET_V(nut->time_base_count, tmp > 0 && tmp < INT_MAX / sizeof(AVRational));
     223          24 :     nut->time_base = av_malloc_array(nut->time_base_count, sizeof(AVRational));
     224          24 :     if (!nut->time_base)
     225           0 :         return AVERROR(ENOMEM);
     226             : 
     227          57 :     for (i = 0; i < nut->time_base_count; i++) {
     228          33 :         GET_V(nut->time_base[i].num, tmp > 0 && tmp < (1ULL << 31));
     229          33 :         GET_V(nut->time_base[i].den, tmp > 0 && tmp < (1ULL << 31));
     230          33 :         if (av_gcd(nut->time_base[i].num, nut->time_base[i].den) != 1) {
     231           0 :             av_log(s, AV_LOG_ERROR, "invalid time base %d/%d\n",
     232           0 :                    nut->time_base[i].num,
     233           0 :                    nut->time_base[i].den);
     234           0 :             ret = AVERROR_INVALIDDATA;
     235           0 :             goto fail;
     236             :         }
     237             :     }
     238          24 :     tmp_pts      = 0;
     239          24 :     tmp_mul      = 1;
     240          24 :     tmp_stream   = 0;
     241          24 :     tmp_head_idx = 0;
     242         300 :     for (i = 0; i < 256;) {
     243         252 :         int tmp_flags  = ffio_read_varlen(bc);
     244         252 :         int tmp_fields = ffio_read_varlen(bc);
     245             : 
     246         252 :         if (tmp_fields > 0)
     247         212 :             tmp_pts = get_s(bc);
     248         252 :         if (tmp_fields > 1)
     249         168 :             tmp_mul = ffio_read_varlen(bc);
     250         252 :         if (tmp_fields > 2)
     251         104 :             tmp_stream = ffio_read_varlen(bc);
     252         252 :         if (tmp_fields > 3)
     253          90 :             tmp_size = ffio_read_varlen(bc);
     254             :         else
     255         162 :             tmp_size = 0;
     256         252 :         if (tmp_fields > 4)
     257          50 :             tmp_res = ffio_read_varlen(bc);
     258             :         else
     259         202 :             tmp_res = 0;
     260         252 :         if (tmp_fields > 5)
     261          50 :             count = ffio_read_varlen(bc);
     262             :         else
     263         202 :             count = tmp_mul - tmp_size;
     264         252 :         if (tmp_fields > 6)
     265           2 :             get_s(bc);
     266         252 :         if (tmp_fields > 7)
     267           2 :             tmp_head_idx = ffio_read_varlen(bc);
     268             : 
     269         504 :         while (tmp_fields-- > 8) {
     270           0 :             if (bc->eof_reached) {
     271           0 :                 av_log(s, AV_LOG_ERROR, "reached EOF while decoding main header\n");
     272           0 :                 ret = AVERROR_INVALIDDATA;
     273           0 :                 goto fail;
     274             :             }
     275           0 :             ffio_read_varlen(bc);
     276             :         }
     277             : 
     278         252 :         if (count <= 0 || count > 256 - (i <= 'N') - i) {
     279           0 :             av_log(s, AV_LOG_ERROR, "illegal count %d at %d\n", count, i);
     280           0 :             ret = AVERROR_INVALIDDATA;
     281           0 :             goto fail;
     282             :         }
     283         252 :         if (tmp_stream >= stream_count) {
     284           0 :             av_log(s, AV_LOG_ERROR, "illegal stream number %d >= %d\n",
     285             :                    tmp_stream, stream_count);
     286           0 :             ret = AVERROR_INVALIDDATA;
     287           0 :             goto fail;
     288             :         }
     289             : 
     290        6396 :         for (j = 0; j < count; j++, i++) {
     291        6144 :             if (i == 'N') {
     292          24 :                 nut->frame_code[i].flags = FLAG_INVALID;
     293          24 :                 j--;
     294          24 :                 continue;
     295             :             }
     296        6120 :             nut->frame_code[i].flags          = tmp_flags;
     297        6120 :             nut->frame_code[i].pts_delta      = tmp_pts;
     298        6120 :             nut->frame_code[i].stream_id      = tmp_stream;
     299        6120 :             nut->frame_code[i].size_mul       = tmp_mul;
     300        6120 :             nut->frame_code[i].size_lsb       = tmp_size + j;
     301        6120 :             nut->frame_code[i].reserved_count = tmp_res;
     302        6120 :             nut->frame_code[i].header_idx     = tmp_head_idx;
     303             :         }
     304             :     }
     305          24 :     av_assert0(nut->frame_code['N'].flags == FLAG_INVALID);
     306             : 
     307          24 :     if (end > avio_tell(bc) + 4) {
     308          24 :         int rem = 1024;
     309          24 :         GET_V(nut->header_count, tmp < 128U);
     310          24 :         nut->header_count++;
     311         168 :         for (i = 1; i < nut->header_count; i++) {
     312             :             uint8_t *hdr;
     313         144 :             GET_V(nut->header_len[i], tmp > 0 && tmp < 256);
     314         144 :             if (rem < nut->header_len[i]) {
     315           0 :                 av_log(s, AV_LOG_ERROR,
     316             :                        "invalid elision header %d : %d > %d\n",
     317           0 :                        i, nut->header_len[i], rem);
     318           0 :                 ret = AVERROR_INVALIDDATA;
     319           0 :                 goto fail;
     320             :             }
     321         144 :             rem -= nut->header_len[i];
     322         144 :             hdr = av_malloc(nut->header_len[i]);
     323         144 :             if (!hdr) {
     324           0 :                 ret = AVERROR(ENOMEM);
     325           0 :                 goto fail;
     326             :             }
     327         144 :             avio_read(bc, hdr, nut->header_len[i]);
     328         144 :             nut->header[i] = hdr;
     329             :         }
     330          24 :         av_assert0(nut->header_len[0] == 0);
     331             :     }
     332             : 
     333             :     // flags had been effectively introduced in version 4
     334          24 :     if (nut->version > 3 && end > avio_tell(bc) + 4) {
     335           0 :         nut->flags = ffio_read_varlen(bc);
     336             :     }
     337             : 
     338          24 :     if (skip_reserved(bc, end) || ffio_get_checksum(bc)) {
     339           0 :         av_log(s, AV_LOG_ERROR, "main header checksum mismatch\n");
     340           0 :         ret = AVERROR_INVALIDDATA;
     341           0 :         goto fail;
     342             :     }
     343             : 
     344          24 :     nut->stream = av_calloc(stream_count, sizeof(StreamContext));
     345          24 :     if (!nut->stream) {
     346           0 :         ret = AVERROR(ENOMEM);
     347           0 :         goto fail;
     348             :     }
     349          64 :     for (i = 0; i < stream_count; i++)
     350          40 :         avformat_new_stream(s, NULL);
     351             : 
     352          24 :     return 0;
     353           0 : fail:
     354           0 :     av_freep(&nut->time_base);
     355           0 :     for (i = 1; i < nut->header_count; i++) {
     356           0 :         av_freep(&nut->header[i]);
     357             :     }
     358           0 :     nut->header_count = 0;
     359           0 :     return ret;
     360             : }
     361             : 
     362          40 : static int decode_stream_header(NUTContext *nut)
     363             : {
     364          40 :     AVFormatContext *s = nut->avf;
     365          40 :     AVIOContext *bc    = s->pb;
     366             :     StreamContext *stc;
     367             :     int class, stream_id, ret;
     368             :     uint64_t tmp, end;
     369          40 :     AVStream *st = NULL;
     370             : 
     371          40 :     end  = get_packetheader(nut, bc, 1, STREAM_STARTCODE);
     372          40 :     end += avio_tell(bc);
     373             : 
     374          40 :     GET_V(stream_id, tmp < s->nb_streams && !nut->stream[tmp].time_base);
     375          40 :     stc = &nut->stream[stream_id];
     376          40 :     st  = s->streams[stream_id];
     377          40 :     if (!st)
     378           0 :         return AVERROR(ENOMEM);
     379             : 
     380          40 :     class                = ffio_read_varlen(bc);
     381          40 :     tmp                  = get_fourcc(bc);
     382          40 :     st->codecpar->codec_tag = tmp;
     383          40 :     switch (class) {
     384          20 :     case 0:
     385          20 :         st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
     386          20 :         st->codecpar->codec_id   = av_codec_get_id((const AVCodecTag * const []) {
     387             :                                                     ff_nut_video_tags,
     388             :                                                     ff_codec_bmp_tags,
     389             :                                                     ff_codec_movvideo_tags,
     390             :                                                     0
     391             :                                                 },
     392             :                                                 tmp);
     393          20 :         break;
     394          20 :     case 1:
     395          20 :         st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
     396          20 :         st->codecpar->codec_id   = av_codec_get_id((const AVCodecTag * const []) {
     397             :                                                     ff_nut_audio_tags,
     398             :                                                     ff_codec_wav_tags,
     399             :                                                     ff_nut_audio_extra_tags,
     400             :                                                     0
     401             :                                                 },
     402             :                                                 tmp);
     403          20 :         break;
     404           0 :     case 2:
     405           0 :         st->codecpar->codec_type = AVMEDIA_TYPE_SUBTITLE;
     406           0 :         st->codecpar->codec_id   = ff_codec_get_id(ff_nut_subtitle_tags, tmp);
     407           0 :         break;
     408           0 :     case 3:
     409           0 :         st->codecpar->codec_type = AVMEDIA_TYPE_DATA;
     410           0 :         st->codecpar->codec_id   = ff_codec_get_id(ff_nut_data_tags, tmp);
     411           0 :         break;
     412           0 :     default:
     413           0 :         av_log(s, AV_LOG_ERROR, "unknown stream class (%d)\n", class);
     414           0 :         return AVERROR(ENOSYS);
     415             :     }
     416          40 :     if (class < 3 && st->codecpar->codec_id == AV_CODEC_ID_NONE)
     417           0 :         av_log(s, AV_LOG_ERROR,
     418             :                "Unknown codec tag '0x%04x' for stream number %d\n",
     419             :                (unsigned int) tmp, stream_id);
     420             : 
     421          40 :     GET_V(stc->time_base_id, tmp < nut->time_base_count);
     422          40 :     GET_V(stc->msb_pts_shift, tmp < 16);
     423          40 :     stc->max_pts_distance = ffio_read_varlen(bc);
     424          40 :     GET_V(stc->decode_delay, tmp < 1000); // sanity limit, raise this if Moore's law is true
     425          40 :     st->codecpar->video_delay = stc->decode_delay;
     426          40 :     ffio_read_varlen(bc); // stream flags
     427             : 
     428          40 :     GET_V(st->codecpar->extradata_size, tmp < (1 << 30));
     429          40 :     if (st->codecpar->extradata_size) {
     430           2 :         if (ff_get_extradata(s, st->codecpar, bc, st->codecpar->extradata_size) < 0)
     431           0 :             return AVERROR(ENOMEM);
     432             :     }
     433             : 
     434          40 :     if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
     435          20 :         GET_V(st->codecpar->width,  tmp > 0);
     436          20 :         GET_V(st->codecpar->height, tmp > 0);
     437          20 :         st->sample_aspect_ratio.num = ffio_read_varlen(bc);
     438          20 :         st->sample_aspect_ratio.den = ffio_read_varlen(bc);
     439          20 :         if ((!st->sample_aspect_ratio.num) != (!st->sample_aspect_ratio.den)) {
     440           0 :             av_log(s, AV_LOG_ERROR, "invalid aspect ratio %d/%d\n",
     441             :                    st->sample_aspect_ratio.num, st->sample_aspect_ratio.den);
     442           0 :             ret = AVERROR_INVALIDDATA;
     443           0 :             goto fail;
     444             :         }
     445          20 :         ffio_read_varlen(bc); /* csp type */
     446          20 :     } else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
     447          20 :         GET_V(st->codecpar->sample_rate, tmp > 0);
     448          20 :         ffio_read_varlen(bc); // samplerate_den
     449          20 :         GET_V(st->codecpar->channels, tmp > 0);
     450             :     }
     451          40 :     if (skip_reserved(bc, end) || ffio_get_checksum(bc)) {
     452           0 :         av_log(s, AV_LOG_ERROR,
     453             :                "stream header %d checksum mismatch\n", stream_id);
     454           0 :         ret = AVERROR_INVALIDDATA;
     455           0 :         goto fail;
     456             :     }
     457          40 :     stc->time_base = &nut->time_base[stc->time_base_id];
     458          40 :     avpriv_set_pts_info(s->streams[stream_id], 63, stc->time_base->num,
     459          40 :                         stc->time_base->den);
     460          40 :     return 0;
     461           0 : fail:
     462           0 :     if (st && st->codecpar) {
     463           0 :         av_freep(&st->codecpar->extradata);
     464           0 :         st->codecpar->extradata_size = 0;
     465             :     }
     466           0 :     return ret;
     467             : }
     468             : 
     469           0 : static void set_disposition_bits(AVFormatContext *avf, char *value,
     470             :                                  int stream_id)
     471             : {
     472           0 :     int flag = 0, i;
     473             : 
     474           0 :     for (i = 0; ff_nut_dispositions[i].flag; ++i)
     475           0 :         if (!strcmp(ff_nut_dispositions[i].str, value))
     476           0 :             flag = ff_nut_dispositions[i].flag;
     477           0 :     if (!flag)
     478           0 :         av_log(avf, AV_LOG_INFO, "unknown disposition type '%s'\n", value);
     479           0 :     for (i = 0; i < avf->nb_streams; ++i)
     480           0 :         if (stream_id == i || stream_id == -1)
     481           0 :             avf->streams[i]->disposition |= flag;
     482           0 : }
     483             : 
     484          64 : static int decode_info_header(NUTContext *nut)
     485             : {
     486          64 :     AVFormatContext *s = nut->avf;
     487          64 :     AVIOContext *bc    = s->pb;
     488             :     uint64_t tmp, chapter_start, chapter_len;
     489             :     unsigned int stream_id_plus1, count;
     490          64 :     int chapter_id, i, ret = 0;
     491             :     int64_t value, end;
     492             :     char name[256], str_value[1024], type_str[256];
     493             :     const char *type;
     494          64 :     int *event_flags        = NULL;
     495          64 :     AVChapter *chapter      = NULL;
     496          64 :     AVStream *st            = NULL;
     497          64 :     AVDictionary **metadata = NULL;
     498          64 :     int metadata_flag       = 0;
     499             : 
     500          64 :     end  = get_packetheader(nut, bc, 1, INFO_STARTCODE);
     501          64 :     end += avio_tell(bc);
     502             : 
     503          64 :     GET_V(stream_id_plus1, tmp <= s->nb_streams);
     504          64 :     chapter_id    = get_s(bc);
     505          64 :     chapter_start = ffio_read_varlen(bc);
     506          64 :     chapter_len   = ffio_read_varlen(bc);
     507          64 :     count         = ffio_read_varlen(bc);
     508             : 
     509          64 :     if (chapter_id && !stream_id_plus1) {
     510           0 :         int64_t start = chapter_start / nut->time_base_count;
     511           0 :         chapter = avpriv_new_chapter(s, chapter_id,
     512           0 :                                      nut->time_base[chapter_start %
     513           0 :                                                     nut->time_base_count],
     514           0 :                                      start, start + chapter_len, NULL);
     515           0 :         if (!chapter) {
     516           0 :             av_log(s, AV_LOG_ERROR, "Could not create chapter.\n");
     517           0 :             return AVERROR(ENOMEM);
     518             :         }
     519           0 :         metadata = &chapter->metadata;
     520          64 :     } else if (stream_id_plus1) {
     521          40 :         st       = s->streams[stream_id_plus1 - 1];
     522          40 :         metadata = &st->metadata;
     523          40 :         event_flags = &st->event_flags;
     524          40 :         metadata_flag = AVSTREAM_EVENT_FLAG_METADATA_UPDATED;
     525             :     } else {
     526          24 :         metadata = &s->metadata;
     527          24 :         event_flags = &s->event_flags;
     528          24 :         metadata_flag = AVFMT_EVENT_FLAG_METADATA_UPDATED;
     529             :     }
     530             : 
     531         168 :     for (i = 0; i < count; i++) {
     532         104 :         ret = get_str(bc, name, sizeof(name));
     533         104 :         if (ret < 0) {
     534           0 :             av_log(s, AV_LOG_ERROR, "get_str failed while decoding info header\n");
     535           0 :             return ret;
     536             :         }
     537         104 :         value = get_s(bc);
     538         104 :         str_value[0] = 0;
     539             : 
     540         104 :         if (value == -1) {
     541         104 :             type = "UTF-8";
     542         104 :             ret = get_str(bc, str_value, sizeof(str_value));
     543           0 :         } else if (value == -2) {
     544           0 :             ret = get_str(bc, type_str, sizeof(type_str));
     545           0 :             if (ret < 0) {
     546           0 :                 av_log(s, AV_LOG_ERROR, "get_str failed while decoding info header\n");
     547           0 :                 return ret;
     548             :             }
     549           0 :             type = type_str;
     550           0 :             ret = get_str(bc, str_value, sizeof(str_value));
     551           0 :         } else if (value == -3) {
     552           0 :             type  = "s";
     553           0 :             value = get_s(bc);
     554           0 :         } else if (value == -4) {
     555           0 :             type  = "t";
     556           0 :             value = ffio_read_varlen(bc);
     557           0 :         } else if (value < -4) {
     558           0 :             type = "r";
     559           0 :             get_s(bc);
     560             :         } else {
     561           0 :             type = "v";
     562             :         }
     563             : 
     564         104 :         if (ret < 0) {
     565           0 :             av_log(s, AV_LOG_ERROR, "get_str failed while decoding info header\n");
     566           0 :             return ret;
     567             :         }
     568             : 
     569         104 :         if (stream_id_plus1 > s->nb_streams) {
     570           0 :             av_log(s, AV_LOG_WARNING,
     571             :                    "invalid stream id %d for info packet\n",
     572             :                    stream_id_plus1);
     573           0 :             continue;
     574             :         }
     575             : 
     576         104 :         if (!strcmp(type, "UTF-8")) {
     577         104 :             if (chapter_id == 0 && !strcmp(name, "Disposition")) {
     578           0 :                 set_disposition_bits(s, str_value, stream_id_plus1 - 1);
     579           0 :                 continue;
     580             :             }
     581             : 
     582         104 :             if (stream_id_plus1 && !strcmp(name, "r_frame_rate")) {
     583          20 :                 sscanf(str_value, "%d/%d", &st->r_frame_rate.num, &st->r_frame_rate.den);
     584          40 :                 if (st->r_frame_rate.num >= 1000LL*st->r_frame_rate.den ||
     585          40 :                     st->r_frame_rate.num < 0 || st->r_frame_rate.num < 0)
     586           0 :                     st->r_frame_rate.num = st->r_frame_rate.den = 0;
     587          20 :                 continue;
     588             :             }
     589             : 
     590         168 :             if (metadata && av_strcasecmp(name, "Uses") &&
     591         168 :                 av_strcasecmp(name, "Depends") && av_strcasecmp(name, "Replaces")) {
     592          84 :                 if (event_flags)
     593          84 :                     *event_flags |= metadata_flag;
     594          84 :                 av_dict_set(metadata, name, str_value, 0);
     595             :             }
     596             :         }
     597             :     }
     598             : 
     599          64 :     if (skip_reserved(bc, end) || ffio_get_checksum(bc)) {
     600           0 :         av_log(s, AV_LOG_ERROR, "info header checksum mismatch\n");
     601           0 :         return AVERROR_INVALIDDATA;
     602             :     }
     603          64 : fail:
     604          64 :     return FFMIN(ret, 0);
     605             : }
     606             : 
     607         701 : static int decode_syncpoint(NUTContext *nut, int64_t *ts, int64_t *back_ptr)
     608             : {
     609         701 :     AVFormatContext *s = nut->avf;
     610         701 :     AVIOContext *bc    = s->pb;
     611             :     int64_t end;
     612             :     uint64_t tmp;
     613             :     int ret;
     614             : 
     615         701 :     nut->last_syncpoint_pos = avio_tell(bc) - 8;
     616             : 
     617         701 :     end  = get_packetheader(nut, bc, 1, SYNCPOINT_STARTCODE);
     618         701 :     end += avio_tell(bc);
     619             : 
     620         701 :     tmp       = ffio_read_varlen(bc);
     621         701 :     *back_ptr = nut->last_syncpoint_pos - 16 * ffio_read_varlen(bc);
     622         701 :     if (*back_ptr < 0)
     623           0 :         return AVERROR_INVALIDDATA;
     624             : 
     625         701 :     ff_nut_reset_ts(nut, nut->time_base[tmp % nut->time_base_count],
     626         701 :                     tmp / nut->time_base_count);
     627             : 
     628         701 :     if (nut->flags & NUT_BROADCAST) {
     629           0 :         tmp = ffio_read_varlen(bc);
     630           0 :         av_log(s, AV_LOG_VERBOSE, "Syncpoint wallclock %"PRId64"\n",
     631           0 :                av_rescale_q(tmp / nut->time_base_count,
     632           0 :                             nut->time_base[tmp % nut->time_base_count],
     633           0 :                             AV_TIME_BASE_Q));
     634             :     }
     635             : 
     636         701 :     if (skip_reserved(bc, end) || ffio_get_checksum(bc)) {
     637           0 :         av_log(s, AV_LOG_ERROR, "sync point checksum mismatch\n");
     638           0 :         return AVERROR_INVALIDDATA;
     639             :     }
     640             : 
     641        2103 :     *ts = tmp / nut->time_base_count *
     642        1402 :           av_q2d(nut->time_base[tmp % nut->time_base_count]) * AV_TIME_BASE;
     643             : 
     644         701 :     if ((ret = ff_nut_add_sp(nut, nut->last_syncpoint_pos, *back_ptr, *ts)) < 0)
     645           0 :         return ret;
     646             : 
     647         701 :     return 0;
     648             : }
     649             : 
     650             : //FIXME calculate exactly, this is just a good approximation.
     651           0 : static int64_t find_duration(NUTContext *nut, int64_t filesize)
     652             : {
     653           0 :     AVFormatContext *s = nut->avf;
     654           0 :     int64_t duration = 0;
     655             : 
     656           0 :     ff_find_last_ts(s, -1, &duration, NULL, nut_read_timestamp);
     657             : 
     658           0 :     if(duration > 0)
     659           0 :         s->duration_estimation_method = AVFMT_DURATION_FROM_PTS;
     660           0 :     return duration;
     661             : }
     662             : 
     663          24 : static int find_and_decode_index(NUTContext *nut)
     664             : {
     665          24 :     AVFormatContext *s = nut->avf;
     666          24 :     AVIOContext *bc    = s->pb;
     667             :     uint64_t tmp, end;
     668             :     int i, j, syncpoint_count;
     669          24 :     int64_t filesize = avio_size(bc);
     670          24 :     int64_t *syncpoints = NULL;
     671             :     uint64_t max_pts;
     672          24 :     int8_t *has_keyframe = NULL;
     673          24 :     int ret = AVERROR_INVALIDDATA;
     674             : 
     675          24 :     if(filesize <= 0)
     676           0 :         return -1;
     677             : 
     678          24 :     avio_seek(bc, filesize - 12, SEEK_SET);
     679          24 :     avio_seek(bc, filesize - avio_rb64(bc), SEEK_SET);
     680          24 :     if (avio_rb64(bc) != INDEX_STARTCODE) {
     681           0 :         av_log(s, AV_LOG_WARNING, "no index at the end\n");
     682             : 
     683           0 :         if(s->duration<=0)
     684           0 :             s->duration = find_duration(nut, filesize);
     685           0 :         return ret;
     686             :     }
     687             : 
     688          24 :     end  = get_packetheader(nut, bc, 1, INDEX_STARTCODE);
     689          24 :     end += avio_tell(bc);
     690             : 
     691          24 :     max_pts = ffio_read_varlen(bc);
     692          24 :     s->duration = av_rescale_q(max_pts / nut->time_base_count,
     693          24 :                                nut->time_base[max_pts % nut->time_base_count],
     694          24 :                                AV_TIME_BASE_Q);
     695          24 :     s->duration_estimation_method = AVFMT_DURATION_FROM_PTS;
     696             : 
     697          24 :     GET_V(syncpoint_count, tmp < INT_MAX / 8 && tmp > 0);
     698          24 :     syncpoints   = av_malloc_array(syncpoint_count, sizeof(int64_t));
     699          24 :     has_keyframe = av_malloc_array(syncpoint_count + 1, sizeof(int8_t));
     700          24 :     if (!syncpoints || !has_keyframe) {
     701           0 :         ret = AVERROR(ENOMEM);
     702           0 :         goto fail;
     703             :     }
     704         709 :     for (i = 0; i < syncpoint_count; i++) {
     705         685 :         syncpoints[i] = ffio_read_varlen(bc);
     706         685 :         if (syncpoints[i] <= 0)
     707           0 :             goto fail;
     708         685 :         if (i)
     709         661 :             syncpoints[i] += syncpoints[i - 1];
     710             :     }
     711             : 
     712          64 :     for (i = 0; i < s->nb_streams; i++) {
     713          40 :         int64_t last_pts = -1;
     714         207 :         for (j = 0; j < syncpoint_count;) {
     715         127 :             uint64_t x = ffio_read_varlen(bc);
     716         127 :             int type   = x & 1;
     717         127 :             int n      = j;
     718         127 :             x >>= 1;
     719         127 :             if (type) {
     720         127 :                 int flag = x & 1;
     721         127 :                 x >>= 1;
     722         127 :                 if (n + x >= syncpoint_count + 1) {
     723           0 :                     av_log(s, AV_LOG_ERROR, "index overflow A %d + %"PRIu64" >= %d\n", n, x, syncpoint_count + 1);
     724           0 :                     goto fail;
     725             :                 }
     726        1012 :                 while (x--)
     727         758 :                     has_keyframe[n++] = flag;
     728         127 :                 has_keyframe[n++] = !flag;
     729             :             } else {
     730           0 :                 if (x <= 1) {
     731           0 :                     av_log(s, AV_LOG_ERROR, "index: x %"PRIu64" is invalid\n", x);
     732           0 :                     goto fail;
     733             :                 }
     734           0 :                 while (x != 1) {
     735           0 :                     if (n >= syncpoint_count + 1) {
     736           0 :                         av_log(s, AV_LOG_ERROR, "index overflow B\n");
     737           0 :                         goto fail;
     738             :                     }
     739           0 :                     has_keyframe[n++] = x & 1;
     740           0 :                     x >>= 1;
     741             :                 }
     742             :             }
     743         127 :             if (has_keyframe[0]) {
     744           0 :                 av_log(s, AV_LOG_ERROR, "keyframe before first syncpoint in index\n");
     745           0 :                 goto fail;
     746             :             }
     747         127 :             av_assert0(n <= syncpoint_count + 1);
     748         990 :             for (; j < n && j < syncpoint_count; j++) {
     749         863 :                 if (has_keyframe[j]) {
     750         686 :                     uint64_t B, A = ffio_read_varlen(bc);
     751         686 :                     if (!A) {
     752           0 :                         A = ffio_read_varlen(bc);
     753           0 :                         B = ffio_read_varlen(bc);
     754             :                         // eor_pts[j][i] = last_pts + A + B
     755             :                     } else
     756         686 :                         B = 0;
     757         686 :                     av_add_index_entry(s->streams[i], 16 * syncpoints[j - 1],
     758         686 :                                        last_pts + A, 0, 0, AVINDEX_KEYFRAME);
     759         686 :                     last_pts += A + B;
     760             :                 }
     761             :             }
     762             :         }
     763             :     }
     764             : 
     765          24 :     if (skip_reserved(bc, end) || ffio_get_checksum(bc)) {
     766           0 :         av_log(s, AV_LOG_ERROR, "index checksum mismatch\n");
     767           0 :         goto fail;
     768             :     }
     769          24 :     ret = 0;
     770             : 
     771          24 : fail:
     772          24 :     av_free(syncpoints);
     773          24 :     av_free(has_keyframe);
     774          24 :     return ret;
     775             : }
     776             : 
     777          24 : static int nut_read_close(AVFormatContext *s)
     778             : {
     779          24 :     NUTContext *nut = s->priv_data;
     780             :     int i;
     781             : 
     782          24 :     av_freep(&nut->time_base);
     783          24 :     av_freep(&nut->stream);
     784          24 :     ff_nut_free_sp(nut);
     785         168 :     for (i = 1; i < nut->header_count; i++)
     786         144 :         av_freep(&nut->header[i]);
     787             : 
     788          24 :     return 0;
     789             : }
     790             : 
     791          24 : static int nut_read_header(AVFormatContext *s)
     792             : {
     793          24 :     NUTContext *nut = s->priv_data;
     794          24 :     AVIOContext *bc = s->pb;
     795             :     int64_t pos;
     796             :     int initialized_stream_count;
     797             : 
     798          24 :     nut->avf = s;
     799             : 
     800             :     /* main header */
     801          24 :     pos = 0;
     802             :     do {
     803          24 :         pos = find_startcode(bc, MAIN_STARTCODE, pos) + 1;
     804          24 :         if (pos < 0 + 1) {
     805           0 :             av_log(s, AV_LOG_ERROR, "No main startcode found.\n");
     806           0 :             goto fail;
     807             :         }
     808          24 :     } while (decode_main_header(nut) < 0);
     809             : 
     810             :     /* stream headers */
     811          24 :     pos = 0;
     812          88 :     for (initialized_stream_count = 0; initialized_stream_count < s->nb_streams;) {
     813          40 :         pos = find_startcode(bc, STREAM_STARTCODE, pos) + 1;
     814          40 :         if (pos < 0 + 1) {
     815           0 :             av_log(s, AV_LOG_ERROR, "Not all stream headers found.\n");
     816           0 :             goto fail;
     817             :         }
     818          40 :         if (decode_stream_header(nut) >= 0)
     819          40 :             initialized_stream_count++;
     820             :     }
     821             : 
     822             :     /* info headers */
     823          24 :     pos = 0;
     824         128 :     for (;;) {
     825         152 :         uint64_t startcode = find_any_startcode(bc, pos);
     826         152 :         pos = avio_tell(bc);
     827             : 
     828         152 :         if (startcode == 0) {
     829           0 :             av_log(s, AV_LOG_ERROR, "EOF before video frames\n");
     830           0 :             goto fail;
     831         152 :         } else if (startcode == SYNCPOINT_STARTCODE) {
     832          24 :             nut->next_startcode = startcode;
     833          24 :             break;
     834         128 :         } else if (startcode != INFO_STARTCODE) {
     835          64 :             continue;
     836             :         }
     837             : 
     838          64 :         decode_info_header(nut);
     839             :     }
     840             : 
     841          24 :     s->internal->data_offset = pos - 8;
     842             : 
     843          24 :     if (bc->seekable & AVIO_SEEKABLE_NORMAL) {
     844          24 :         int64_t orig_pos = avio_tell(bc);
     845          24 :         find_and_decode_index(nut);
     846          24 :         avio_seek(bc, orig_pos, SEEK_SET);
     847             :     }
     848          24 :     av_assert0(nut->next_startcode == SYNCPOINT_STARTCODE);
     849             : 
     850          24 :     ff_metadata_conv_ctx(s, NULL, ff_nut_metadata_conv);
     851             : 
     852          24 :     return 0;
     853             : 
     854           0 : fail:
     855           0 :     nut_read_close(s);
     856             : 
     857           0 :     return AVERROR_INVALIDDATA;
     858             : }
     859             : 
     860           0 : static int read_sm_data(AVFormatContext *s, AVIOContext *bc, AVPacket *pkt, int is_meta, int64_t maxpos)
     861             : {
     862           0 :     int count = ffio_read_varlen(bc);
     863           0 :     int skip_start = 0;
     864           0 :     int skip_end = 0;
     865           0 :     int channels = 0;
     866           0 :     int64_t channel_layout = 0;
     867           0 :     int sample_rate = 0;
     868           0 :     int width = 0;
     869           0 :     int height = 0;
     870             :     int i, ret;
     871             : 
     872           0 :     for (i=0; i<count; i++) {
     873             :         uint8_t name[256], str_value[256], type_str[256];
     874             :         int value;
     875           0 :         if (avio_tell(bc) >= maxpos)
     876           0 :             return AVERROR_INVALIDDATA;
     877           0 :         ret = get_str(bc, name, sizeof(name));
     878           0 :         if (ret < 0) {
     879           0 :             av_log(s, AV_LOG_ERROR, "get_str failed while reading sm data\n");
     880           0 :             return ret;
     881             :         }
     882           0 :         value = get_s(bc);
     883             : 
     884           0 :         if (value == -1) {
     885           0 :             ret = get_str(bc, str_value, sizeof(str_value));
     886           0 :             if (ret < 0) {
     887           0 :                 av_log(s, AV_LOG_ERROR, "get_str failed while reading sm data\n");
     888           0 :                 return ret;
     889             :             }
     890           0 :             av_log(s, AV_LOG_WARNING, "Unknown string %s / %s\n", name, str_value);
     891           0 :         } else if (value == -2) {
     892           0 :             uint8_t *dst = NULL;
     893             :             int64_t v64, value_len;
     894             : 
     895           0 :             ret = get_str(bc, type_str, sizeof(type_str));
     896           0 :             if (ret < 0) {
     897           0 :                 av_log(s, AV_LOG_ERROR, "get_str failed while reading sm data\n");
     898           0 :                 return ret;
     899             :             }
     900           0 :             value_len = ffio_read_varlen(bc);
     901           0 :             if (value_len < 0 || value_len >= maxpos - avio_tell(bc))
     902           0 :                 return AVERROR_INVALIDDATA;
     903           0 :             if (!strcmp(name, "Palette")) {
     904           0 :                 dst = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, value_len);
     905           0 :             } else if (!strcmp(name, "Extradata")) {
     906           0 :                 dst = av_packet_new_side_data(pkt, AV_PKT_DATA_NEW_EXTRADATA, value_len);
     907           0 :             } else if (sscanf(name, "CodecSpecificSide%"SCNd64"", &v64) == 1) {
     908           0 :                 dst = av_packet_new_side_data(pkt, AV_PKT_DATA_MATROSKA_BLOCKADDITIONAL, value_len + 8);
     909           0 :                 if(!dst)
     910           0 :                     return AVERROR(ENOMEM);
     911           0 :                 AV_WB64(dst, v64);
     912           0 :                 dst += 8;
     913           0 :             } else if (!strcmp(name, "ChannelLayout") && value_len == 8) {
     914           0 :                 channel_layout = avio_rl64(bc);
     915           0 :                 continue;
     916             :             } else {
     917           0 :                 av_log(s, AV_LOG_WARNING, "Unknown data %s / %s\n", name, type_str);
     918           0 :                 avio_skip(bc, value_len);
     919           0 :                 continue;
     920             :             }
     921           0 :             if(!dst)
     922           0 :                 return AVERROR(ENOMEM);
     923           0 :             avio_read(bc, dst, value_len);
     924           0 :         } else if (value == -3) {
     925           0 :             value = get_s(bc);
     926           0 :         } else if (value == -4) {
     927           0 :             value = ffio_read_varlen(bc);
     928           0 :         } else if (value < -4) {
     929           0 :             get_s(bc);
     930             :         } else {
     931           0 :             if (!strcmp(name, "SkipStart")) {
     932           0 :                 skip_start = value;
     933           0 :             } else if (!strcmp(name, "SkipEnd")) {
     934           0 :                 skip_end = value;
     935           0 :             } else if (!strcmp(name, "Channels")) {
     936           0 :                 channels = value;
     937           0 :             } else if (!strcmp(name, "SampleRate")) {
     938           0 :                 sample_rate = value;
     939           0 :             } else if (!strcmp(name, "Width")) {
     940           0 :                 width = value;
     941           0 :             } else if (!strcmp(name, "Height")) {
     942           0 :                 height = value;
     943             :             } else {
     944           0 :                 av_log(s, AV_LOG_WARNING, "Unknown integer %s\n", name);
     945             :             }
     946             :         }
     947             :     }
     948             : 
     949           0 :     if (channels || channel_layout || sample_rate || width || height) {
     950           0 :         uint8_t *dst = av_packet_new_side_data(pkt, AV_PKT_DATA_PARAM_CHANGE, 28);
     951           0 :         if (!dst)
     952           0 :             return AVERROR(ENOMEM);
     953           0 :         bytestream_put_le32(&dst,
     954           0 :                             AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_COUNT*(!!channels) +
     955           0 :                             AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_LAYOUT*(!!channel_layout) +
     956           0 :                             AV_SIDE_DATA_PARAM_CHANGE_SAMPLE_RATE*(!!sample_rate) +
     957           0 :                             AV_SIDE_DATA_PARAM_CHANGE_DIMENSIONS*(!!(width|height))
     958             :                            );
     959           0 :         if (channels)
     960           0 :             bytestream_put_le32(&dst, channels);
     961           0 :         if (channel_layout)
     962           0 :             bytestream_put_le64(&dst, channel_layout);
     963           0 :         if (sample_rate)
     964           0 :             bytestream_put_le32(&dst, sample_rate);
     965           0 :         if (width || height){
     966           0 :             bytestream_put_le32(&dst, width);
     967           0 :             bytestream_put_le32(&dst, height);
     968             :         }
     969             :     }
     970             : 
     971           0 :     if (skip_start || skip_end) {
     972           0 :         uint8_t *dst = av_packet_new_side_data(pkt, AV_PKT_DATA_SKIP_SAMPLES, 10);
     973           0 :         if (!dst)
     974           0 :             return AVERROR(ENOMEM);
     975           0 :         AV_WL32(dst, skip_start);
     976           0 :         AV_WL32(dst+4, skip_end);
     977             :     }
     978             : 
     979           0 :     if (avio_tell(bc) >= maxpos)
     980           0 :         return AVERROR_INVALIDDATA;
     981             : 
     982           0 :     return 0;
     983             : }
     984             : 
     985        3246 : static int decode_frame_header(NUTContext *nut, int64_t *pts, int *stream_id,
     986             :                                uint8_t *header_idx, int frame_code)
     987             : {
     988        3246 :     AVFormatContext *s = nut->avf;
     989        3246 :     AVIOContext *bc    = s->pb;
     990             :     StreamContext *stc;
     991             :     int size, flags, size_mul, pts_delta, i, reserved_count, ret;
     992             :     uint64_t tmp;
     993             : 
     994        6492 :     if (!(nut->flags & NUT_PIPE) &&
     995        3246 :         avio_tell(bc) > nut->last_syncpoint_pos + nut->max_distance) {
     996           0 :         av_log(s, AV_LOG_ERROR,
     997             :                "Last frame must have been damaged %"PRId64" > %"PRId64" + %d\n",
     998             :                avio_tell(bc), nut->last_syncpoint_pos, nut->max_distance);
     999           0 :         return AVERROR_INVALIDDATA;
    1000             :     }
    1001             : 
    1002        3246 :     flags          = nut->frame_code[frame_code].flags;
    1003        3246 :     size_mul       = nut->frame_code[frame_code].size_mul;
    1004        3246 :     size           = nut->frame_code[frame_code].size_lsb;
    1005        3246 :     *stream_id     = nut->frame_code[frame_code].stream_id;
    1006        3246 :     pts_delta      = nut->frame_code[frame_code].pts_delta;
    1007        3246 :     reserved_count = nut->frame_code[frame_code].reserved_count;
    1008        3246 :     *header_idx    = nut->frame_code[frame_code].header_idx;
    1009             : 
    1010        3246 :     if (flags & FLAG_INVALID)
    1011           0 :         return AVERROR_INVALIDDATA;
    1012        3246 :     if (flags & FLAG_CODED)
    1013          28 :         flags ^= ffio_read_varlen(bc);
    1014        3246 :     if (flags & FLAG_STREAM_ID) {
    1015          28 :         GET_V(*stream_id, tmp < s->nb_streams);
    1016             :     }
    1017        3246 :     stc = &nut->stream[*stream_id];
    1018        3246 :     if (flags & FLAG_CODED_PTS) {
    1019        3005 :         int coded_pts = ffio_read_varlen(bc);
    1020             :         // FIXME check last_pts validity?
    1021        3005 :         if (coded_pts < (1 << stc->msb_pts_shift)) {
    1022        3005 :             *pts = ff_lsb2full(stc, coded_pts);
    1023             :         } else
    1024           0 :             *pts = coded_pts - (1LL << stc->msb_pts_shift);
    1025             :     } else
    1026         241 :         *pts = stc->last_pts + pts_delta;
    1027        3246 :     if (flags & FLAG_SIZE_MSB)
    1028        3215 :         size += size_mul * ffio_read_varlen(bc);
    1029        3246 :     if (flags & FLAG_MATCH_TIME)
    1030           0 :         get_s(bc);
    1031        3246 :     if (flags & FLAG_HEADER_IDX)
    1032           0 :         *header_idx = ffio_read_varlen(bc);
    1033        3246 :     if (flags & FLAG_RESERVED)
    1034           0 :         reserved_count = ffio_read_varlen(bc);
    1035        3246 :     for (i = 0; i < reserved_count; i++) {
    1036           0 :         if (bc->eof_reached) {
    1037           0 :             av_log(s, AV_LOG_ERROR, "reached EOF while decoding frame header\n");
    1038           0 :             return AVERROR_INVALIDDATA;
    1039             :         }
    1040           0 :         ffio_read_varlen(bc);
    1041             :     }
    1042             : 
    1043        3246 :     if (*header_idx >= (unsigned)nut->header_count) {
    1044           0 :         av_log(s, AV_LOG_ERROR, "header_idx invalid\n");
    1045           0 :         return AVERROR_INVALIDDATA;
    1046             :     }
    1047        3246 :     if (size > 4096)
    1048        1655 :         *header_idx = 0;
    1049        3246 :     size -= nut->header_len[*header_idx];
    1050             : 
    1051        3246 :     if (flags & FLAG_CHECKSUM) {
    1052          28 :         avio_rb32(bc); // FIXME check this
    1053        6436 :     } else if (!(nut->flags & NUT_PIPE) &&
    1054        6436 :                size > 2 * nut->max_distance ||
    1055        3218 :                FFABS(stc->last_pts - *pts) > stc->max_pts_distance) {
    1056           0 :         av_log(s, AV_LOG_ERROR, "frame size > 2max_distance and no checksum\n");
    1057           0 :         return AVERROR_INVALIDDATA;
    1058             :     }
    1059             : 
    1060        3246 :     stc->last_pts   = *pts;
    1061        3246 :     stc->last_flags = flags;
    1062             : 
    1063        3246 :     return size;
    1064           0 : fail:
    1065           0 :     return ret;
    1066             : }
    1067             : 
    1068        3246 : static int decode_frame(NUTContext *nut, AVPacket *pkt, int frame_code)
    1069             : {
    1070        3246 :     AVFormatContext *s = nut->avf;
    1071        3246 :     AVIOContext *bc    = s->pb;
    1072             :     int size, stream_id, discard, ret;
    1073             :     int64_t pts, last_IP_pts;
    1074             :     StreamContext *stc;
    1075             :     uint8_t header_idx;
    1076             : 
    1077        3246 :     size = decode_frame_header(nut, &pts, &stream_id, &header_idx, frame_code);
    1078        3246 :     if (size < 0)
    1079           0 :         return size;
    1080             : 
    1081        3246 :     stc = &nut->stream[stream_id];
    1082             : 
    1083        3246 :     if (stc->last_flags & FLAG_KEY)
    1084        3217 :         stc->skip_until_key_frame = 0;
    1085             : 
    1086        3246 :     discard     = s->streams[stream_id]->discard;
    1087        3246 :     last_IP_pts = s->streams[stream_id]->last_IP_pts;
    1088        3246 :     if ((discard >= AVDISCARD_NONKEY && !(stc->last_flags & FLAG_KEY)) ||
    1089           0 :         (discard >= AVDISCARD_BIDIR  && last_IP_pts != AV_NOPTS_VALUE &&
    1090        3246 :          last_IP_pts > pts) ||
    1091        3246 :         discard >= AVDISCARD_ALL ||
    1092        3246 :         stc->skip_until_key_frame) {
    1093           7 :         avio_skip(bc, size);
    1094           7 :         return 1;
    1095             :     }
    1096             : 
    1097        3239 :     ret = av_new_packet(pkt, size + nut->header_len[header_idx]);
    1098        3239 :     if (ret < 0)
    1099           0 :         return ret;
    1100        3239 :     if (nut->header[header_idx])
    1101          48 :         memcpy(pkt->data, nut->header[header_idx], nut->header_len[header_idx]);
    1102        3239 :     pkt->pos = avio_tell(bc); // FIXME
    1103        3239 :     if (stc->last_flags & FLAG_SM_DATA) {
    1104             :         int sm_size;
    1105           0 :         if (read_sm_data(s, bc, pkt, 0, pkt->pos + size) < 0) {
    1106           0 :             ret = AVERROR_INVALIDDATA;
    1107           0 :             goto fail;
    1108             :         }
    1109           0 :         if (read_sm_data(s, bc, pkt, 1, pkt->pos + size) < 0) {
    1110           0 :             ret = AVERROR_INVALIDDATA;
    1111           0 :             goto fail;
    1112             :         }
    1113           0 :         sm_size = avio_tell(bc) - pkt->pos;
    1114           0 :         size      -= sm_size;
    1115           0 :         pkt->size -= sm_size;
    1116             :     }
    1117             : 
    1118        3239 :     ret = avio_read(bc, pkt->data + nut->header_len[header_idx], size);
    1119        3239 :     if (ret != size) {
    1120           0 :         if (ret < 0)
    1121           0 :             goto fail;
    1122             :     }
    1123        3239 :     av_shrink_packet(pkt, nut->header_len[header_idx] + ret);
    1124             : 
    1125        3239 :     pkt->stream_index = stream_id;
    1126        3239 :     if (stc->last_flags & FLAG_KEY)
    1127        3217 :         pkt->flags |= AV_PKT_FLAG_KEY;
    1128        3239 :     pkt->pts = pts;
    1129             : 
    1130        3239 :     return 0;
    1131           0 : fail:
    1132           0 :     av_packet_unref(pkt);
    1133           0 :     return ret;
    1134             : }
    1135             : 
    1136        3269 : static int nut_read_packet(AVFormatContext *s, AVPacket *pkt)
    1137             : {
    1138        3269 :     NUTContext *nut = s->priv_data;
    1139        3269 :     AVIOContext *bc = s->pb;
    1140        3269 :     int i, frame_code = 0, ret, skip;
    1141             :     int64_t ts, back_ptr;
    1142             : 
    1143          30 :     for (;;) {
    1144        3299 :         int64_t pos  = avio_tell(bc);
    1145        3299 :         uint64_t tmp = nut->next_startcode;
    1146        3299 :         nut->next_startcode = 0;
    1147             : 
    1148        3299 :         if (tmp) {
    1149          24 :             pos -= 8;
    1150             :         } else {
    1151        3275 :             frame_code = avio_r8(bc);
    1152        3275 :             if (avio_feof(bc))
    1153          30 :                 return AVERROR_EOF;
    1154        3245 :             if (frame_code == 'N') {
    1155         700 :                 tmp = frame_code;
    1156        5600 :                 for (i = 1; i < 8; i++)
    1157        4900 :                     tmp = (tmp << 8) + avio_r8(bc);
    1158             :             }
    1159             :         }
    1160        3269 :         switch (tmp) {
    1161          23 :         case MAIN_STARTCODE:
    1162             :         case STREAM_STARTCODE:
    1163             :         case INDEX_STARTCODE:
    1164          23 :             skip = get_packetheader(nut, bc, 0, tmp);
    1165          23 :             avio_skip(bc, skip);
    1166          23 :             break;
    1167           0 :         case INFO_STARTCODE:
    1168           0 :             if (decode_info_header(nut) < 0)
    1169           0 :                 goto resync;
    1170           0 :             break;
    1171         701 :         case SYNCPOINT_STARTCODE:
    1172         701 :             if (decode_syncpoint(nut, &ts, &back_ptr) < 0)
    1173           0 :                 goto resync;
    1174         701 :             frame_code = avio_r8(bc);
    1175        3246 :         case 0:
    1176        3246 :             ret = decode_frame(nut, pkt, frame_code);
    1177        3246 :             if (ret == 0)
    1178        3239 :                 return 0;
    1179           7 :             else if (ret == 1) // OK but discard packet
    1180           7 :                 break;
    1181             :         default:
    1182           0 : resync:
    1183           0 :             av_log(s, AV_LOG_DEBUG, "syncing from %"PRId64"\n", pos);
    1184           0 :             tmp = find_any_startcode(bc, FFMAX(nut->last_syncpoint_pos, nut->last_resync_pos) + 1);
    1185           0 :             nut->last_resync_pos = avio_tell(bc);
    1186           0 :             if (tmp == 0)
    1187           0 :                 return AVERROR_INVALIDDATA;
    1188           0 :             av_log(s, AV_LOG_DEBUG, "sync\n");
    1189           0 :             nut->next_startcode = tmp;
    1190             :         }
    1191             :     }
    1192             : }
    1193             : 
    1194           0 : static int64_t nut_read_timestamp(AVFormatContext *s, int stream_index,
    1195             :                                   int64_t *pos_arg, int64_t pos_limit)
    1196             : {
    1197           0 :     NUTContext *nut = s->priv_data;
    1198           0 :     AVIOContext *bc = s->pb;
    1199             :     int64_t pos, pts, back_ptr;
    1200           0 :     av_log(s, AV_LOG_DEBUG, "read_timestamp(X,%d,%"PRId64",%"PRId64")\n",
    1201             :            stream_index, *pos_arg, pos_limit);
    1202             : 
    1203           0 :     pos = *pos_arg;
    1204             :     do {
    1205           0 :         pos = find_startcode(bc, SYNCPOINT_STARTCODE, pos) + 1;
    1206           0 :         if (pos < 1) {
    1207           0 :             av_log(s, AV_LOG_ERROR, "read_timestamp failed.\n");
    1208           0 :             return AV_NOPTS_VALUE;
    1209             :         }
    1210           0 :     } while (decode_syncpoint(nut, &pts, &back_ptr) < 0);
    1211           0 :     *pos_arg = pos - 1;
    1212           0 :     av_assert0(nut->last_syncpoint_pos == *pos_arg);
    1213             : 
    1214           0 :     av_log(s, AV_LOG_DEBUG, "return %"PRId64" %"PRId64"\n", pts, back_ptr);
    1215           0 :     if (stream_index == -2)
    1216           0 :         return back_ptr;
    1217           0 :     av_assert0(stream_index == -1);
    1218           0 :     return pts;
    1219             : }
    1220             : 
    1221          26 : static int read_seek(AVFormatContext *s, int stream_index,
    1222             :                      int64_t pts, int flags)
    1223             : {
    1224          26 :     NUTContext *nut    = s->priv_data;
    1225          26 :     AVStream *st       = s->streams[stream_index];
    1226          26 :     Syncpoint dummy    = { .ts = pts * av_q2d(st->time_base) * AV_TIME_BASE };
    1227          26 :     Syncpoint nopts_sp = { .ts = AV_NOPTS_VALUE, .back_ptr = AV_NOPTS_VALUE };
    1228          26 :     Syncpoint *sp, *next_node[2] = { &nopts_sp, &nopts_sp };
    1229             :     int64_t pos, pos2, ts;
    1230             :     int i;
    1231             : 
    1232          26 :     if (nut->flags & NUT_PIPE) {
    1233           0 :         return AVERROR(ENOSYS);
    1234             :     }
    1235             : 
    1236          26 :     if (st->index_entries) {
    1237          26 :         int index = av_index_search_timestamp(st, pts, flags);
    1238          26 :         if (index < 0)
    1239          11 :             index = av_index_search_timestamp(st, pts, flags ^ AVSEEK_FLAG_BACKWARD);
    1240          26 :         if (index < 0)
    1241           0 :             return -1;
    1242             : 
    1243          26 :         pos2 = st->index_entries[index].pos;
    1244          26 :         ts   = st->index_entries[index].timestamp;
    1245             :     } else {
    1246           0 :         av_tree_find(nut->syncpoints, &dummy, ff_nut_sp_pts_cmp,
    1247             :                      (void **) next_node);
    1248           0 :         av_log(s, AV_LOG_DEBUG, "%"PRIu64"-%"PRIu64" %"PRId64"-%"PRId64"\n",
    1249           0 :                next_node[0]->pos, next_node[1]->pos, next_node[0]->ts,
    1250           0 :                next_node[1]->ts);
    1251           0 :         pos = ff_gen_search(s, -1, dummy.ts, next_node[0]->pos,
    1252           0 :                             next_node[1]->pos, next_node[1]->pos,
    1253           0 :                             next_node[0]->ts, next_node[1]->ts,
    1254             :                             AVSEEK_FLAG_BACKWARD, &ts, nut_read_timestamp);
    1255           0 :         if (pos < 0)
    1256           0 :             return pos;
    1257             : 
    1258           0 :         if (!(flags & AVSEEK_FLAG_BACKWARD)) {
    1259           0 :             dummy.pos    = pos + 16;
    1260           0 :             next_node[1] = &nopts_sp;
    1261           0 :             av_tree_find(nut->syncpoints, &dummy, ff_nut_sp_pos_cmp,
    1262             :                          (void **) next_node);
    1263           0 :             pos2 = ff_gen_search(s, -2, dummy.pos, next_node[0]->pos,
    1264           0 :                                  next_node[1]->pos, next_node[1]->pos,
    1265           0 :                                  next_node[0]->back_ptr, next_node[1]->back_ptr,
    1266             :                                  flags, &ts, nut_read_timestamp);
    1267           0 :             if (pos2 >= 0)
    1268           0 :                 pos = pos2;
    1269             :             // FIXME dir but I think it does not matter
    1270             :         }
    1271           0 :         dummy.pos = pos;
    1272           0 :         sp = av_tree_find(nut->syncpoints, &dummy, ff_nut_sp_pos_cmp,
    1273             :                           NULL);
    1274             : 
    1275           0 :         av_assert0(sp);
    1276           0 :         pos2 = sp->back_ptr - 15;
    1277             :     }
    1278          26 :     av_log(NULL, AV_LOG_DEBUG, "SEEKTO: %"PRId64"\n", pos2);
    1279          26 :     pos = find_startcode(s->pb, SYNCPOINT_STARTCODE, pos2);
    1280          26 :     avio_seek(s->pb, pos, SEEK_SET);
    1281          26 :     nut->last_syncpoint_pos = pos;
    1282          26 :     av_log(NULL, AV_LOG_DEBUG, "SP: %"PRId64"\n", pos);
    1283          26 :     if (pos2 > pos || pos2 + 15 < pos)
    1284           0 :         av_log(NULL, AV_LOG_ERROR, "no syncpoint at backptr pos\n");
    1285          78 :     for (i = 0; i < s->nb_streams; i++)
    1286          52 :         nut->stream[i].skip_until_key_frame = 1;
    1287             : 
    1288          26 :     nut->last_resync_pos = 0;
    1289             : 
    1290          26 :     return 0;
    1291             : }
    1292             : 
    1293             : AVInputFormat ff_nut_demuxer = {
    1294             :     .name           = "nut",
    1295             :     .long_name      = NULL_IF_CONFIG_SMALL("NUT"),
    1296             :     .flags          = AVFMT_SEEK_TO_PTS,
    1297             :     .priv_data_size = sizeof(NUTContext),
    1298             :     .read_probe     = nut_probe,
    1299             :     .read_header    = nut_read_header,
    1300             :     .read_packet    = nut_read_packet,
    1301             :     .read_close     = nut_read_close,
    1302             :     .read_seek      = read_seek,
    1303             :     .extensions     = "nut",
    1304             :     .codec_tag      = ff_nut_codec_tags,
    1305             : };

Generated by: LCOV version 1.13