libavformat/flvdec.c
d4f5d74a
 /*
7fbde343
  * FLV demuxer
406792e7
  * Copyright (c) 2003 The FFmpeg Project
d4f5d74a
  *
7b94177e
  * This demuxer will generate a 1 byte extradata for VP6F content.
  * It is composed of:
41ed7ab4
  *  - upper 4 bits: difference between encoded width and visible width
  *  - lower 4 bits: difference between encoded height and visible height
7b94177e
  *
b78e7197
  * This file is part of FFmpeg.
  *
  * FFmpeg is free software; you can redistribute it and/or
d4f5d74a
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
b78e7197
  * version 2.1 of the License, or (at your option) any later version.
d4f5d74a
  *
b78e7197
  * FFmpeg is distributed in the hope that it will be useful,
d4f5d74a
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
b78e7197
  * License along with FFmpeg; if not, write to the Free Software
5509bffa
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
d4f5d74a
  */
d2718187
 
df2bd71a
 #include "libavutil/avstring.h"
644d8d2e
 #include "libavutil/channel_layout.h"
d2d67e42
 #include "libavutil/dict.h"
5b54a90c
 #include "libavutil/opt.h"
3383a53e
 #include "libavutil/intfloat.h"
d3f751e6
 #include "libavutil/mathematics.h"
c1c206b3
 #include "libavcodec/bytestream.h"
d2718187
 #include "libavcodec/mpeg4audio.h"
d4f5d74a
 #include "avformat.h"
c3f9ebf7
 #include "internal.h"
933e90a6
 #include "avio_internal.h"
6cac3a3b
 #include "flv.h"
d4f5d74a
 
7e297a46
 #define VALIDATE_INDEX_TS_THRESH 2500
 
cbbd906b
 #define RESYNC_BUFFER_SIZE (1<<20)
 
daf8cf35
 typedef struct FLVContext {
5b54a90c
     const AVClass *class; ///< Class for private options.
e4529df9
     int trust_metadata;   ///< configure streams according onMetaData
     int wrong_dts;        ///< wrong dts due to negative cts
52c522c7
     uint8_t *new_extradata[FLV_STREAM_TYPE_NB];
ae48547a
     int new_extradata_size[FLV_STREAM_TYPE_NB];
e4529df9
     int last_sample_rate;
     int last_channels;
7e297a46
     struct {
         int64_t dts;
         int64_t pos;
     } validate_index[2];
     int validate_next;
     int validate_count;
71a5cd7d
     int searched_for_end;
cbbd906b
 
     uint8_t resync_buffer[2*RESYNC_BUFFER_SIZE];
e3cf978c
 
     int broken_sizes;
9a099526
     int sum_flv_tag_size;
cd141e71
 
     int last_keyframe_stream_index;
     int keyframe_count;
7c5478a2
     int64_t video_bit_rate;
     int64_t audio_bit_rate;
cd141e71
     int64_t *keyframe_times;
     int64_t *keyframe_filepositions;
07793962
     int missing_streams;
e0791c5a
     AVRational framerate;
ebd61055
 } FLVContext;
 
2fbdfba0
 static int probe(AVProbeData *p, int live)
d4f5d74a
 {
2fbdfba0
     const uint8_t *d = p->buf;
     unsigned offset = AV_RB32(d + 5);
d4f5d74a
 
e4529df9
     if (d[0] == 'F' &&
         d[1] == 'L' &&
         d[2] == 'V' &&
         d[3] < 5 && d[5] == 0 &&
2fbdfba0
         offset + 100 < p->buf_size &&
         offset > 8) {
         int is_live = !memcmp(d + offset + 40, "NGINX RTMP", 10);
 
         if (live == is_live)
             return AVPROBE_SCORE_MAX;
d4f5d74a
     }
     return 0;
 }
 
2fbdfba0
 static int flv_probe(AVProbeData *p)
 {
     return probe(p, 0);
 }
 
 static int live_flv_probe(AVProbeData *p)
 {
     return probe(p, 1);
 }
 
cd141e71
 static void add_keyframes_index(AVFormatContext *s)
 {
     FLVContext *flv   = s->priv_data;
     AVStream *stream  = NULL;
     unsigned int i    = 0;
 
     if (flv->last_keyframe_stream_index < 0) {
         av_log(s, AV_LOG_DEBUG, "keyframe stream hasn't been created\n");
         return;
     }
 
     av_assert0(flv->last_keyframe_stream_index <= s->nb_streams);
     stream = s->streams[flv->last_keyframe_stream_index];
 
     if (stream->nb_index_entries == 0) {
         for (i = 0; i < flv->keyframe_count; i++) {
4696f763
             av_log(s, AV_LOG_TRACE, "keyframe filepositions = %"PRId64" times = %"PRId64"\n",
                    flv->keyframe_filepositions[i], flv->keyframe_times[i] * 1000);
cd141e71
             av_add_index_entry(stream, flv->keyframe_filepositions[i],
                 flv->keyframe_times[i] * 1000, 0, 0, AVINDEX_KEYFRAME);
         }
     } else
         av_log(s, AV_LOG_WARNING, "Skipping duplicate index\n");
 
     if (stream->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
         av_freep(&flv->keyframe_times);
         av_freep(&flv->keyframe_filepositions);
         flv->keyframe_count = 0;
     }
 }
 
41f43202
 static AVStream *create_stream(AVFormatContext *s, int codec_type)
21e2dc9f
 {
ad14aab3
     FLVContext *flv   = s->priv_data;
21e2dc9f
     AVStream *st = avformat_new_stream(s, NULL);
     if (!st)
         return NULL;
9200514a
     st->codecpar->codec_type = codec_type;
ae48547a
     if (s->nb_streams>=3 ||(   s->nb_streams==2
6f69f7a8
                            && s->streams[0]->codecpar->codec_type != AVMEDIA_TYPE_SUBTITLE
                            && s->streams[1]->codecpar->codec_type != AVMEDIA_TYPE_SUBTITLE))
7d82020f
         s->ctx_flags &= ~AVFMTCTX_NOHEADER;
af7d0ad9
     if (codec_type == AVMEDIA_TYPE_AUDIO) {
7c5478a2
         st->codecpar->bit_rate = flv->audio_bit_rate;
07793962
         flv->missing_streams &= ~FLV_HEADER_FLAG_HASAUDIO;
af7d0ad9
     }
e0791c5a
     if (codec_type == AVMEDIA_TYPE_VIDEO) {
7c5478a2
         st->codecpar->bit_rate = flv->video_bit_rate;
07793962
         flv->missing_streams &= ~FLV_HEADER_FLAG_HASVIDEO;
e0791c5a
         st->avg_frame_rate = flv->framerate;
     }
07793962
 
7d82020f
 
21e2dc9f
     avpriv_set_pts_info(st, 32, 1, 1000); /* 32 bit pts in ms */
ad14aab3
     flv->last_keyframe_stream_index = s->nb_streams - 1;
     add_keyframes_index(s);
21e2dc9f
     return st;
 }
e4529df9
 
9200514a
 static int flv_same_audio_codec(AVCodecParameters *apar, int flags)
09a445ce
 {
     int bits_per_coded_sample = (flags & FLV_AUDIO_SAMPLESIZE_MASK) ? 16 : 8;
e4529df9
     int flv_codecid           = flags & FLV_AUDIO_CODECID_MASK;
09a445ce
     int codec_id;
 
9200514a
     if (!apar->codec_id && !apar->codec_tag)
09a445ce
         return 1;
 
9200514a
     if (apar->bits_per_coded_sample != bits_per_coded_sample)
09a445ce
         return 0;
 
e4529df9
     switch (flv_codecid) {
     // no distinction between S16 and S8 PCM codec flags
09a445ce
     case FLV_CODECID_PCM:
e4529df9
         codec_id = bits_per_coded_sample == 8
                    ? AV_CODEC_ID_PCM_U8
09a445ce
 #if HAVE_BIGENDIAN
e4529df9
                    : AV_CODEC_ID_PCM_S16BE;
09a445ce
 #else
e4529df9
                    : AV_CODEC_ID_PCM_S16LE;
09a445ce
 #endif
9200514a
         return codec_id == apar->codec_id;
09a445ce
     case FLV_CODECID_PCM_LE:
e4529df9
         codec_id = bits_per_coded_sample == 8
                    ? AV_CODEC_ID_PCM_U8
                    : AV_CODEC_ID_PCM_S16LE;
9200514a
         return codec_id == apar->codec_id;
09a445ce
     case FLV_CODECID_AAC:
9200514a
         return apar->codec_id == AV_CODEC_ID_AAC;
09a445ce
     case FLV_CODECID_ADPCM:
9200514a
         return apar->codec_id == AV_CODEC_ID_ADPCM_SWF;
09a445ce
     case FLV_CODECID_SPEEX:
9200514a
         return apar->codec_id == AV_CODEC_ID_SPEEX;
09a445ce
     case FLV_CODECID_MP3:
9200514a
         return apar->codec_id == AV_CODEC_ID_MP3;
09a445ce
     case FLV_CODECID_NELLYMOSER_8KHZ_MONO:
     case FLV_CODECID_NELLYMOSER_16KHZ_MONO:
     case FLV_CODECID_NELLYMOSER:
9200514a
         return apar->codec_id == AV_CODEC_ID_NELLYMOSER;
09a445ce
     case FLV_CODECID_PCM_MULAW:
9200514a
         return apar->sample_rate == 8000 &&
                apar->codec_id    == AV_CODEC_ID_PCM_MULAW;
09a445ce
     case FLV_CODECID_PCM_ALAW:
9200514a
         return apar->sample_rate == 8000 &&
                apar->codec_id    == AV_CODEC_ID_PCM_ALAW;
09a445ce
     default:
9200514a
         return apar->codec_tag == (flv_codecid >> FLV_AUDIO_CODECID_OFFSET);
09a445ce
     }
 }
21e2dc9f
 
e4529df9
 static void flv_set_audio_codec(AVFormatContext *s, AVStream *astream,
9200514a
                                 AVCodecParameters *apar, int flv_codecid)
e4529df9
 {
     switch (flv_codecid) {
     // no distinction between S16 and S8 PCM codec flags
     case FLV_CODECID_PCM:
9200514a
         apar->codec_id = apar->bits_per_coded_sample == 8
e4529df9
                            ? AV_CODEC_ID_PCM_U8
63613fe6
 #if HAVE_BIGENDIAN
e4529df9
                            : AV_CODEC_ID_PCM_S16BE;
58293e57
 #else
e4529df9
                            : AV_CODEC_ID_PCM_S16LE;
58293e57
 #endif
e4529df9
         break;
     case FLV_CODECID_PCM_LE:
9200514a
         apar->codec_id = apar->bits_per_coded_sample == 8
e4529df9
                            ? AV_CODEC_ID_PCM_U8
                            : AV_CODEC_ID_PCM_S16LE;
         break;
     case FLV_CODECID_AAC:
9200514a
         apar->codec_id = AV_CODEC_ID_AAC;
e4529df9
         break;
     case FLV_CODECID_ADPCM:
9200514a
         apar->codec_id = AV_CODEC_ID_ADPCM_SWF;
e4529df9
         break;
     case FLV_CODECID_SPEEX:
9200514a
         apar->codec_id    = AV_CODEC_ID_SPEEX;
         apar->sample_rate = 16000;
e4529df9
         break;
     case FLV_CODECID_MP3:
9200514a
         apar->codec_id      = AV_CODEC_ID_MP3;
e4529df9
         astream->need_parsing = AVSTREAM_PARSE_FULL;
         break;
     case FLV_CODECID_NELLYMOSER_8KHZ_MONO:
         // in case metadata does not otherwise declare samplerate
9200514a
         apar->sample_rate = 8000;
         apar->codec_id    = AV_CODEC_ID_NELLYMOSER;
e4529df9
         break;
     case FLV_CODECID_NELLYMOSER_16KHZ_MONO:
9200514a
         apar->sample_rate = 16000;
         apar->codec_id    = AV_CODEC_ID_NELLYMOSER;
e4529df9
         break;
     case FLV_CODECID_NELLYMOSER:
9200514a
         apar->codec_id = AV_CODEC_ID_NELLYMOSER;
e4529df9
         break;
     case FLV_CODECID_PCM_MULAW:
9200514a
         apar->sample_rate = 8000;
         apar->codec_id    = AV_CODEC_ID_PCM_MULAW;
e4529df9
         break;
     case FLV_CODECID_PCM_ALAW:
9200514a
         apar->sample_rate = 8000;
         apar->codec_id    = AV_CODEC_ID_PCM_ALAW;
e4529df9
         break;
     default:
a6881765
         avpriv_request_sample(s, "Audio codec (%x)",
e4529df9
                flv_codecid >> FLV_AUDIO_CODECID_OFFSET);
9200514a
         apar->codec_tag = flv_codecid >> FLV_AUDIO_CODECID_OFFSET;
428cc588
     }
 }
 
9200514a
 static int flv_same_video_codec(AVCodecParameters *vpar, int flags)
09a445ce
 {
     int flv_codecid = flags & FLV_VIDEO_CODECID_MASK;
 
9200514a
     if (!vpar->codec_id && !vpar->codec_tag)
09a445ce
         return 1;
 
     switch (flv_codecid) {
e4529df9
     case FLV_CODECID_H263:
9200514a
         return vpar->codec_id == AV_CODEC_ID_FLV1;
e4529df9
     case FLV_CODECID_SCREEN:
9200514a
         return vpar->codec_id == AV_CODEC_ID_FLASHSV;
e4529df9
     case FLV_CODECID_SCREEN2:
9200514a
         return vpar->codec_id == AV_CODEC_ID_FLASHSV2;
e4529df9
     case FLV_CODECID_VP6:
9200514a
         return vpar->codec_id == AV_CODEC_ID_VP6F;
e4529df9
     case FLV_CODECID_VP6A:
9200514a
         return vpar->codec_id == AV_CODEC_ID_VP6A;
e4529df9
     case FLV_CODECID_H264:
9200514a
         return vpar->codec_id == AV_CODEC_ID_H264;
e4529df9
     default:
9200514a
         return vpar->codec_tag == flv_codecid;
09a445ce
     }
 }
 
e4529df9
 static int flv_set_video_codec(AVFormatContext *s, AVStream *vstream,
                                int flv_codecid, int read)
 {
98b3a797
     int ret = 0;
9200514a
     AVCodecParameters *par = vstream->codecpar;
98b3a797
     enum AVCodecID old_codec_id = vstream->codecpar->codec_id;
e4529df9
     switch (flv_codecid) {
     case FLV_CODECID_H263:
9200514a
         par->codec_id = AV_CODEC_ID_FLV1;
e4529df9
         break;
ae48547a
     case FLV_CODECID_REALH263:
6f69f7a8
         par->codec_id = AV_CODEC_ID_H263;
ae48547a
         break; // Really mean it this time
e4529df9
     case FLV_CODECID_SCREEN:
9200514a
         par->codec_id = AV_CODEC_ID_FLASHSV;
e4529df9
         break;
     case FLV_CODECID_SCREEN2:
9200514a
         par->codec_id = AV_CODEC_ID_FLASHSV2;
e4529df9
         break;
     case FLV_CODECID_VP6:
9200514a
         par->codec_id = AV_CODEC_ID_VP6F;
e4529df9
     case FLV_CODECID_VP6A:
         if (flv_codecid == FLV_CODECID_VP6A)
9200514a
             par->codec_id = AV_CODEC_ID_VP6A;
e4529df9
         if (read) {
9200514a
             if (par->extradata_size != 1) {
6f69f7a8
                 ff_alloc_extradata(par, 1);
428cc588
             }
9200514a
             if (par->extradata)
                 par->extradata[0] = avio_r8(s->pb);
e4529df9
             else
                 avio_skip(s->pb, 1);
         }
98b3a797
         ret = 1;     // 1 byte body size adjustment for flv_read_packet()
         break;
e4529df9
     case FLV_CODECID_H264:
9200514a
         par->codec_id = AV_CODEC_ID_H264;
cc0e2ba1
         vstream->need_parsing = AVSTREAM_PARSE_HEADERS;
98b3a797
         ret = 3;     // not 4, reading packet type will consume one byte
         break;
ae48547a
     case FLV_CODECID_MPEG4:
6f69f7a8
         par->codec_id = AV_CODEC_ID_MPEG4;
98b3a797
         ret = 3;
         break;
e4529df9
     default:
a6881765
         avpriv_request_sample(s, "Video codec (%x)", flv_codecid);
9200514a
         par->codec_tag = flv_codecid;
428cc588
     }
 
98b3a797
     if (!vstream->internal->need_context_update && par->codec_id != old_codec_id) {
         avpriv_request_sample(s, "Changing the codec id midstream");
         return AVERROR_PATCHWELCOME;
     }
 
     return ret;
428cc588
 }
 
e4529df9
 static int amf_get_string(AVIOContext *ioc, char *buffer, int buffsize)
 {
e63a3628
     int length = avio_rb16(ioc);
e4529df9
     if (length >= buffsize) {
45a8a02a
         avio_skip(ioc, length);
cc38e063
         return -1;
     }
896bcd2e
 
e63a3628
     avio_read(ioc, buffer, length);
896bcd2e
 
cc38e063
     buffer[length] = '\0';
896bcd2e
 
cc38e063
     return length;
896bcd2e
 }
 
cd141e71
 static int parse_keyframes_index(AVFormatContext *s, AVIOContext *ioc, int64_t max_pos)
e4529df9
 {
     FLVContext *flv       = s->priv_data;
0c4d4a93
     unsigned int timeslen = 0, fileposlen = 0, i;
cb7e2c1c
     char str_val[256];
e4529df9
     int64_t *times         = NULL;
cb7e2c1c
     int64_t *filepositions = NULL;
e4529df9
     int ret                = AVERROR(ENOSYS);
     int64_t initial_pos    = avio_tell(ioc);
cb7e2c1c
 
cd141e71
     if (flv->keyframe_count > 0) {
         av_log(s, AV_LOG_DEBUG, "keyframes have been paresed\n");
4717e297
         return 0;
     }
cd141e71
     av_assert0(!flv->keyframe_times);
     av_assert0(!flv->keyframe_filepositions);
4717e297
 
b70f04c2
     if (s->flags & AVFMT_FLAG_IGNIDX)
         return 0;
 
e4529df9
     while (avio_tell(ioc) < max_pos - 2 &&
            amf_get_string(ioc, str_val, sizeof(str_val)) > 0) {
ae48547a
         int64_t **current_array;
0c4d4a93
         unsigned int arraylen;
cb7e2c1c
 
         // Expect array object in context
         if (avio_r8(ioc) != AMF_DATA_TYPE_ARRAY)
             break;
 
         arraylen = avio_rb32(ioc);
ae48547a
         if (arraylen>>28)
cb7e2c1c
             break;
 
ae48547a
         if       (!strcmp(KEYFRAMES_TIMESTAMP_TAG , str_val) && !times) {
             current_array = &times;
e4529df9
             timeslen      = arraylen;
         } else if (!strcmp(KEYFRAMES_BYTEOFFSET_TAG, str_val) &&
                    !filepositions) {
ae48547a
             current_array = &filepositions;
e4529df9
             fileposlen    = arraylen;
         } else
             // unexpected metatag inside keyframes, will not use such
             // metadata for indexing
0c4d4a93
             break;
 
         if (!(*current_array = av_mallocz(sizeof(**current_array) * arraylen))) {
             ret = AVERROR(ENOMEM);
             goto finish;
         }
 
cb7e2c1c
         for (i = 0; i < arraylen && avio_tell(ioc) < max_pos - 1; i++) {
             if (avio_r8(ioc) != AMF_DATA_TYPE_NUMBER)
83f70805
                 goto invalid;
7fad19a6
             current_array[0][i] = av_int2double(avio_rb64(ioc));
cb7e2c1c
         }
578d6861
         if (times && filepositions) {
             // All done, exiting at a position allowing amf_parse_object
             // to finish parsing the object
             ret = 0;
             break;
         }
cb7e2c1c
     }
 
df0bff66
     if (timeslen == fileposlen && fileposlen>1 && max_pos <= filepositions[0]) {
cd141e71
         for (i = 0; i < FFMIN(2,fileposlen); i++) {
             flv->validate_index[i].pos = filepositions[i];
             flv->validate_index[i].dts = times[i] * 1000;
             flv->validate_count        = i + 1;
7e297a46
         }
cd141e71
         flv->keyframe_times = times;
         flv->keyframe_filepositions = filepositions;
         flv->keyframe_count = timeslen;
         times = NULL;
         filepositions = NULL;
83f70805
     } else {
 invalid:
cb7e2c1c
         av_log(s, AV_LOG_WARNING, "Invalid keyframes object, skipping.\n");
83f70805
     }
cb7e2c1c
 
 finish:
     av_freep(&times);
     av_freep(&filepositions);
ba667e60
     avio_seek(ioc, initial_pos, SEEK_SET);
cb7e2c1c
     return ret;
 }
 
e4529df9
 static int amf_parse_object(AVFormatContext *s, AVStream *astream,
                             AVStream *vstream, const char *key,
                             int64_t max_pos, int depth)
 {
9200514a
     AVCodecParameters *apar, *vpar;
5b54a90c
     FLVContext *flv = s->priv_data;
471fe57e
     AVIOContext *ioc;
428cc588
     AMFDataType amf_type;
eb767a27
     char str_val[1024];
428cc588
     double num_val;
 
e4529df9
     num_val  = 0;
     ioc      = s->pb;
e63a3628
     amf_type = avio_r8(ioc);
428cc588
 
e4529df9
     switch (amf_type) {
     case AMF_DATA_TYPE_NUMBER:
         num_val = av_int2double(avio_rb64(ioc));
         break;
     case AMF_DATA_TYPE_BOOL:
         num_val = avio_r8(ioc);
         break;
     case AMF_DATA_TYPE_STRING:
5c37ffca
         if (amf_get_string(ioc, str_val, sizeof(str_val)) < 0) {
             av_log(s, AV_LOG_ERROR, "AMF_DATA_TYPE_STRING parsing failed\n");
e4529df9
             return -1;
5c37ffca
         }
e4529df9
         break;
     case AMF_DATA_TYPE_OBJECT:
ad14aab3
         if (key &&
4de591e6
             (ioc->seekable & AVIO_SEEKABLE_NORMAL) &&
e4529df9
             !strcmp(KEYFRAMES_TAG, key) && depth == 1)
cd141e71
             if (parse_keyframes_index(s, ioc,
e4529df9
                                       max_pos) < 0)
ae48547a
                 av_log(s, AV_LOG_ERROR, "Keyframe index parsing failed\n");
ad14aab3
             else
                 add_keyframes_index(s);
e4529df9
         while (avio_tell(ioc) < max_pos - 2 &&
                amf_get_string(ioc, str_val, sizeof(str_val)) > 0)
             if (amf_parse_object(s, astream, vstream, str_val, max_pos,
                                  depth + 1) < 0)
                 return -1;     // if we couldn't skip, bomb out.
5c37ffca
         if (avio_r8(ioc) != AMF_END_OF_OBJECT) {
             av_log(s, AV_LOG_ERROR, "Missing AMF_END_OF_OBJECT in AMF_DATA_TYPE_OBJECT\n");
428cc588
             return -1;
5c37ffca
         }
e4529df9
         break;
     case AMF_DATA_TYPE_NULL:
     case AMF_DATA_TYPE_UNDEFINED:
     case AMF_DATA_TYPE_UNSUPPORTED:
         break;     // these take up no additional space
     case AMF_DATA_TYPE_MIXEDARRAY:
6bed88ac
     {
         unsigned v;
e4529df9
         avio_skip(ioc, 4);     // skip 32-bit max array index
         while (avio_tell(ioc) < max_pos - 2 &&
                amf_get_string(ioc, str_val, sizeof(str_val)) > 0)
             // this is the only case in which we would want a nested
             // parse to not skip over the object
             if (amf_parse_object(s, astream, vstream, str_val, max_pos,
                                  depth + 1) < 0)
428cc588
                 return -1;
6bed88ac
         v = avio_r8(ioc);
         if (v != AMF_END_OF_OBJECT) {
             av_log(s, AV_LOG_ERROR, "Missing AMF_END_OF_OBJECT in AMF_DATA_TYPE_MIXEDARRAY, found %d\n", v);
428cc588
             return -1;
5c37ffca
         }
e4529df9
         break;
6bed88ac
     }
e4529df9
     case AMF_DATA_TYPE_ARRAY:
     {
         unsigned int arraylen, i;
 
         arraylen = avio_rb32(ioc);
         for (i = 0; i < arraylen && avio_tell(ioc) < max_pos - 1; i++)
             if (amf_parse_object(s, NULL, NULL, NULL, max_pos,
                                  depth + 1) < 0)
                 return -1;      // if we couldn't skip, bomb out.
     }
     break;
     case AMF_DATA_TYPE_DATE:
         avio_skip(ioc, 8 + 2);  // timestamp (double) and UTC offset (int16)
         break;
     default:                    // unsupported type, we couldn't skip
5c37ffca
         av_log(s, AV_LOG_ERROR, "unsupported amf type %d\n", amf_type);
e4529df9
         return -1;
428cc588
     }
 
93c04e09
     if (key) {
6f69f7a8
         apar = astream ? astream->codecpar : NULL;
         vpar = vstream ? vstream->codecpar : NULL;
0fadbd36
 
93c04e09
         // stream info doesn't live any deeper than the first object
         if (depth == 1) {
             if (amf_type == AMF_DATA_TYPE_NUMBER ||
                 amf_type == AMF_DATA_TYPE_BOOL) {
                 if (!strcmp(key, "duration"))
                     s->duration = num_val * AV_TIME_BASE;
7c5478a2
                 else if (!strcmp(key, "videodatarate") &&
93c04e09
                          0 <= (int)(num_val * 1024.0))
7c5478a2
                     flv->video_bit_rate = num_val * 1024.0;
                 else if (!strcmp(key, "audiodatarate") &&
93c04e09
                          0 <= (int)(num_val * 1024.0))
7c5478a2
                     flv->audio_bit_rate = num_val * 1024.0;
93c04e09
                 else if (!strcmp(key, "datastream")) {
7869b295
                     AVStream *st = create_stream(s, AVMEDIA_TYPE_SUBTITLE);
93c04e09
                     if (!st)
                         return AVERROR(ENOMEM);
9200514a
                     st->codecpar->codec_id = AV_CODEC_ID_TEXT;
e0791c5a
                 } else if (!strcmp(key, "framerate")) {
                     flv->framerate = av_d2q(num_val, 1000);
                     if (vstream)
                         vstream->avg_frame_rate = flv->framerate;
93c04e09
                 } else if (flv->trust_metadata) {
9200514a
                     if (!strcmp(key, "videocodecid") && vpar) {
98b3a797
                         int ret = flv_set_video_codec(s, vstream, num_val, 0);
                         if (ret < 0)
                             return ret;
9200514a
                     } else if (!strcmp(key, "audiocodecid") && apar) {
93c04e09
                         int id = ((int)num_val) << FLV_AUDIO_CODECID_OFFSET;
9200514a
                         flv_set_audio_codec(s, astream, apar, id);
                     } else if (!strcmp(key, "audiosamplerate") && apar) {
                         apar->sample_rate = num_val;
                     } else if (!strcmp(key, "audiosamplesize") && apar) {
                         apar->bits_per_coded_sample = num_val;
                     } else if (!strcmp(key, "stereo") && apar) {
                         apar->channels       = num_val + 1;
                         apar->channel_layout = apar->channels == 2 ?
                                                AV_CH_LAYOUT_STEREO :
                                                AV_CH_LAYOUT_MONO;
                     } else if (!strcmp(key, "width") && vpar) {
                         vpar->width = num_val;
                     } else if (!strcmp(key, "height") && vpar) {
                         vpar->height = num_val;
93c04e09
                     }
5b54a90c
                 }
21e2dc9f
             }
e3cf978c
             if (amf_type == AMF_DATA_TYPE_STRING) {
                 if (!strcmp(key, "encoder")) {
                     int version = -1;
                     if (1 == sscanf(str_val, "Open Broadcaster Software v0.%d", &version)) {
                         if (version > 0 && version <= 655)
                             flv->broken_sizes = 1;
                     }
ce0834bd
                 } else if (!strcmp(key, "metadatacreator") && !strcmp(str_val, "MEGA")) {
                     flv->broken_sizes = 1;
e3cf978c
                 }
             }
b204c46d
         }
 
8b8a47f6
         if (amf_type == AMF_DATA_TYPE_OBJECT && s->nb_streams == 1 &&
6f69f7a8
            ((!apar && !strcmp(key, "audiocodecid")) ||
             (!vpar && !strcmp(key, "videocodecid"))))
8b8a47f6
                 s->ctx_flags &= ~AVFMTCTX_NOHEADER; //If there is either audio/video missing, codecid will be an empty object
 
5e87222f
         if (!strcmp(key, "duration")        ||
             !strcmp(key, "filesize")        ||
             !strcmp(key, "width")           ||
             !strcmp(key, "height")          ||
             !strcmp(key, "videodatarate")   ||
             !strcmp(key, "framerate")       ||
             !strcmp(key, "videocodecid")    ||
             !strcmp(key, "audiodatarate")   ||
             !strcmp(key, "audiosamplerate") ||
             !strcmp(key, "audiosamplesize") ||
             !strcmp(key, "stereo")          ||
0a9425d7
             !strcmp(key, "audiocodecid")    ||
             !strcmp(key, "datastream"))
5e87222f
             return 0;
 
0f789322
         s->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
e4529df9
         if (amf_type == AMF_DATA_TYPE_BOOL) {
             av_strlcpy(str_val, num_val > 0 ? "true" : "false",
                        sizeof(str_val));
d2d67e42
             av_dict_set(&s->metadata, key, str_val, 0);
e4529df9
         } else if (amf_type == AMF_DATA_TYPE_NUMBER) {
cc38e063
             snprintf(str_val, sizeof(str_val), "%.f", num_val);
d2d67e42
             av_dict_set(&s->metadata, key, str_val, 0);
df2bd71a
         } else if (amf_type == AMF_DATA_TYPE_STRING)
d2d67e42
             av_dict_set(&s->metadata, key, str_val, 0);
428cc588
     }
 
     return 0;
 }
 
efc4bfc1
 #define TYPE_ONTEXTDATA 1
3727cd54
 #define TYPE_ONCAPTION 2
790a3cdf
 #define TYPE_ONCAPTIONINFO 3
3727cd54
 #define TYPE_UNKNOWN 9
efc4bfc1
 
e4529df9
 static int flv_read_metabody(AVFormatContext *s, int64_t next_pos)
 {
cd141e71
     FLVContext *flv = s->priv_data;
428cc588
     AMFDataType type;
61a28d00
     AVStream *stream, *astream, *vstream;
     AVStream av_unused *dstream;
471fe57e
     AVIOContext *ioc;
4eec2606
     int i;
e4529df9
     // only needs to hold the string "onMetaData".
     // Anything longer is something we don't want.
b2fecce3
     char buffer[32];
428cc588
 
     astream = NULL;
     vstream = NULL;
ae48547a
     dstream = NULL;
e4529df9
     ioc     = s->pb;
428cc588
 
e4529df9
     // first object needs to be "onMetaData" string
e63a3628
     type = avio_r8(ioc);
21e2dc9f
     if (type != AMF_DATA_TYPE_STRING ||
         amf_get_string(ioc, buffer, sizeof(buffer)) < 0)
efc4bfc1
         return TYPE_UNKNOWN;
21e2dc9f
 
     if (!strcmp(buffer, "onTextData"))
efc4bfc1
         return TYPE_ONTEXTDATA;
21e2dc9f
 
3727cd54
     if (!strcmp(buffer, "onCaption"))
         return TYPE_ONCAPTION;
 
790a3cdf
     if (!strcmp(buffer, "onCaptionInfo"))
         return TYPE_ONCAPTIONINFO;
 
108b738d
     if (strcmp(buffer, "onMetaData") && strcmp(buffer, "onCuePoint")) {
         av_log(s, AV_LOG_DEBUG, "Unknown type %s\n", buffer);
efc4bfc1
         return TYPE_UNKNOWN;
108b738d
     }
428cc588
 
e4529df9
     // find the streams now so that amf_parse_object doesn't need to do
     // the lookup every time it is called.
     for (i = 0; i < s->nb_streams; i++) {
428cc588
         stream = s->streams[i];
cd141e71
         if (stream->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
e4529df9
             vstream = stream;
cd141e71
             flv->last_keyframe_stream_index = i;
         } else if (stream->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
ae48547a
             astream = stream;
cd141e71
             if (flv->last_keyframe_stream_index == -1)
                 flv->last_keyframe_stream_index = i;
         }
6f69f7a8
         else if (stream->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE)
ae48547a
             dstream = stream;
428cc588
     }
 
e4529df9
     // parse the second object (we want a mixed array)
     if (amf_parse_object(s, astream, vstream, buffer, next_pos, 0) < 0)
428cc588
         return -1;
 
     return 0;
 }
 
6e9651d1
 static int flv_read_header(AVFormatContext *s)
d4f5d74a
 {
07793962
     int flags;
9a099526
     FLVContext *flv = s->priv_data;
09ae7b81
     int offset;
c0628919
     int pre_tag_size = 0;
d4f5d74a
 
45a8a02a
     avio_skip(s->pb, 4);
07793962
     flags = avio_r8(s->pb);
 
     flv->missing_streams = flags & (FLV_HEADER_FLAG_HASVIDEO | FLV_HEADER_FLAG_HASAUDIO);
d4f5d74a
 
ee0dadc1
     s->ctx_flags |= AVFMTCTX_NOHEADER;
b41497e9
 
e63a3628
     offset = avio_rb32(s->pb);
f59d8ff8
     avio_seek(s->pb, offset, SEEK_SET);
c0628919
 
     /* Annex E. The FLV File Format
      * E.3 TheFLVFileBody
      *     Field               Type    Comment
      *     PreviousTagSize0    UI32    Always 0
      * */
     pre_tag_size = avio_rb32(s->pb);
     if (pre_tag_size) {
         av_log(s, AV_LOG_WARNING, "Read FLV header error, input file is not a standard flv format, first PreviousTagSize0 always is 0\n");
     }
d4f5d74a
 
aeb20f7f
     s->start_time = 0;
9a099526
     flv->sum_flv_tag_size = 0;
cd141e71
     flv->last_keyframe_stream_index = -1;
aeb20f7f
 
d4f5d74a
     return 0;
 }
 
251f320f
 static int flv_read_close(AVFormatContext *s)
 {
52c522c7
     int i;
251f320f
     FLVContext *flv = s->priv_data;
ae48547a
     for (i=0; i<FLV_STREAM_TYPE_NB; i++)
52c522c7
         av_freep(&flv->new_extradata[i]);
cd141e71
     av_freep(&flv->keyframe_times);
     av_freep(&flv->keyframe_filepositions);
251f320f
     return 0;
 }
 
04fd3e81
 static int flv_get_extradata(AVFormatContext *s, AVStream *st, int size)
 {
6f69f7a8
     av_freep(&st->codecpar->extradata);
323b8c95
     if (ff_get_extradata(s, st->codecpar, s->pb, size) < 0)
04fd3e81
         return AVERROR(ENOMEM);
4d2b9ece
     st->internal->need_context_update = 1;
04fd3e81
     return 0;
 }
 
251f320f
 static int flv_queue_extradata(FLVContext *flv, AVIOContext *pb, int stream,
                                int size)
 {
     av_free(flv->new_extradata[stream]);
e4529df9
     flv->new_extradata[stream] = av_mallocz(size +
059a9348
                                             AV_INPUT_BUFFER_PADDING_SIZE);
251f320f
     if (!flv->new_extradata[stream])
         return AVERROR(ENOMEM);
     flv->new_extradata_size[stream] = size;
     avio_read(pb, flv->new_extradata[stream], size);
     return 0;
 }
 
7e297a46
 static void clear_index_entries(AVFormatContext *s, int64_t pos)
 {
     int i, j, out;
e4529df9
     av_log(s, AV_LOG_WARNING,
            "Found invalid index entries, clearing the index.\n");
7e297a46
     for (i = 0; i < s->nb_streams; i++) {
         AVStream *st = s->streams[i];
         /* Remove all index entries that point to >= pos */
         out = 0;
e4529df9
         for (j = 0; j < st->nb_index_entries; j++)
7e297a46
             if (st->index_entries[j].pos < pos)
                 st->index_entries[out++] = st->index_entries[j];
         st->nb_index_entries = out;
     }
 }
 
c951e4b4
 static int amf_skip_tag(AVIOContext *pb, AMFDataType type)
 {
     int nb = -1, ret, parse_name = 1;
 
     switch (type) {
     case AMF_DATA_TYPE_NUMBER:
         avio_skip(pb, 8);
         break;
     case AMF_DATA_TYPE_BOOL:
         avio_skip(pb, 1);
         break;
     case AMF_DATA_TYPE_STRING:
         avio_skip(pb, avio_rb16(pb));
         break;
     case AMF_DATA_TYPE_ARRAY:
         parse_name = 0;
     case AMF_DATA_TYPE_MIXEDARRAY:
         nb = avio_rb32(pb);
     case AMF_DATA_TYPE_OBJECT:
         while(!pb->eof_reached && (nb-- > 0 || type != AMF_DATA_TYPE_ARRAY)) {
             if (parse_name) {
                 int size = avio_rb16(pb);
                 if (!size) {
                     avio_skip(pb, 1);
                     break;
                 }
                 avio_skip(pb, size);
             }
             if ((ret = amf_skip_tag(pb, avio_r8(pb))) < 0)
                 return ret;
         }
         break;
     case AMF_DATA_TYPE_NULL:
     case AMF_DATA_TYPE_OBJECT_END:
         break;
     default:
         return AVERROR_INVALIDDATA;
     }
     return 0;
 }
 
21e2dc9f
 static int flv_data_packet(AVFormatContext *s, AVPacket *pkt,
                            int64_t dts, int64_t next)
 {
     AVIOContext *pb = s->pb;
e4529df9
     AVStream *st    = NULL;
21e2dc9f
     char buf[20];
c951e4b4
     int ret = AVERROR_INVALIDDATA;
     int i, length = -1;
3727cd54
     int array = 0;
21e2dc9f
 
c951e4b4
     switch (avio_r8(pb)) {
3727cd54
     case AMF_DATA_TYPE_ARRAY:
         array = 1;
c951e4b4
     case AMF_DATA_TYPE_MIXEDARRAY:
21e2dc9f
         avio_seek(pb, 4, SEEK_CUR);
c951e4b4
     case AMF_DATA_TYPE_OBJECT:
         break;
     default:
         goto skip;
     }
21e2dc9f
 
3727cd54
     while (array || (ret = amf_get_string(pb, buf, sizeof(buf))) > 0) {
c951e4b4
         AMFDataType type = avio_r8(pb);
3727cd54
         if (type == AMF_DATA_TYPE_STRING && (array || !strcmp(buf, "text"))) {
c951e4b4
             length = avio_rb16(pb);
             ret    = av_get_packet(pb, pkt, length);
             if (ret < 0)
                 goto skip;
             else
                 break;
         } else {
             if ((ret = amf_skip_tag(pb, type)) < 0)
                 goto skip;
         }
     }
21e2dc9f
 
c951e4b4
     if (length < 0) {
         ret = AVERROR_INVALIDDATA;
         goto skip;
     }
21e2dc9f
 
     for (i = 0; i < s->nb_streams; i++) {
         st = s->streams[i];
6f69f7a8
         if (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE)
21e2dc9f
             break;
     }
 
     if (i == s->nb_streams) {
7869b295
         st = create_stream(s, AVMEDIA_TYPE_SUBTITLE);
21e2dc9f
         if (!st)
629b2ed0
             return AVERROR(ENOMEM);
9200514a
         st->codecpar->codec_id = AV_CODEC_ID_TEXT;
21e2dc9f
     }
 
     pkt->dts  = dts;
     pkt->pts  = dts;
     pkt->size = ret;
 
     pkt->stream_index = st->index;
e4529df9
     pkt->flags       |= AV_PKT_FLAG_KEY;
21e2dc9f
 
c951e4b4
 skip:
21e2dc9f
     avio_seek(s->pb, next + 4, SEEK_SET);
e4529df9
 
21e2dc9f
     return ret;
 }
 
cbbd906b
 static int resync(AVFormatContext *s)
 {
     FLVContext *flv = s->priv_data;
     int64_t i;
     int64_t pos = avio_tell(s->pb);
 
     for (i=0; !avio_feof(s->pb); i++) {
         int j  = i & (RESYNC_BUFFER_SIZE-1);
         int j1 = j + RESYNC_BUFFER_SIZE;
         flv->resync_buffer[j ] =
         flv->resync_buffer[j1] = avio_r8(s->pb);
 
         if (i > 22) {
             unsigned lsize2 = AV_RB32(flv->resync_buffer + j1 - 4);
             if (lsize2 >= 11 && lsize2 + 8LL < FFMIN(i, RESYNC_BUFFER_SIZE)) {
                 unsigned  size2 = AV_RB24(flv->resync_buffer + j1 - lsize2 + 1 - 4);
                 unsigned lsize1 = AV_RB32(flv->resync_buffer + j1 - lsize2 - 8);
                 if (lsize1 >= 11 && lsize1 + 8LL + lsize2 < FFMIN(i, RESYNC_BUFFER_SIZE)) {
                     unsigned  size1 = AV_RB24(flv->resync_buffer + j1 - lsize1 + 1 - lsize2 - 8);
                     if (size1 == lsize1 - 11 && size2  == lsize2 - 11) {
                         avio_seek(s->pb, pos + i - lsize1 - lsize2 - 8, SEEK_SET);
                         return 1;
                     }
                 }
             }
         }
     }
     return AVERROR_EOF;
 }
 
d4f5d74a
 static int flv_read_packet(AVFormatContext *s, AVPacket *pkt)
 {
ebd61055
     FLVContext *flv = s->priv_data;
00ebf89d
     int ret, i, size, flags;
a7ac1a7b
     enum FlvTagType type;
4c050429
     int stream_type=-1;
f3c51215
     int64_t next, pos, meta_pos;
ebd61055
     int64_t dts, pts = AV_NOPTS_VALUE;
e2c1d3ec
     int av_uninit(channels);
     int av_uninit(sample_rate);
e4529df9
     AVStream *st    = NULL;
fd6296e4
     int last = -1;
cbbd906b
     int orig_size;
e4529df9
 
cbbd906b
 retry:
e4529df9
     /* pkt size is repeated at end. skip it */
         pos  = avio_tell(s->pb);
03efd730
         type = (avio_r8(s->pb) & 0x1F);
cbbd906b
         orig_size =
e4529df9
         size = avio_rb24(s->pb);
9a099526
         flv->sum_flv_tag_size += size + 11;
e4529df9
         dts  = avio_rb24(s->pb);
ab7ff380
         dts |= (unsigned)avio_r8(s->pb) << 24;
fd6296e4
         av_log(s, AV_LOG_TRACE, "type:%d, size:%d, last:%d, dts:%"PRId64" pos:%"PRId64"\n", type, size, last, dts, avio_tell(s->pb));
d34ec64a
         if (avio_feof(s->pb))
e4529df9
             return AVERROR_EOF;
         avio_skip(s->pb, 3); /* stream id, always 0 */
         flags = 0;
 
         if (flv->validate_next < flv->validate_count) {
             int64_t validate_pos = flv->validate_index[flv->validate_next].pos;
             if (pos == validate_pos) {
                 if (FFABS(dts - flv->validate_index[flv->validate_next].dts) <=
                     VALIDATE_INDEX_TS_THRESH) {
                     flv->validate_next++;
                 } else {
                     clear_index_entries(s, validate_pos);
                     flv->validate_count = 0;
                 }
             } else if (pos > validate_pos) {
7e297a46
                 clear_index_entries(s, validate_pos);
                 flv->validate_count = 0;
             }
         }
 
3496a20b
         if (size == 0) {
0bac7a43
             ret = FFERROR_REDO;
3496a20b
             goto leave;
         }
115329f1
 
e4529df9
         next = size + avio_tell(s->pb);
dd9f5916
 
e4529df9
         if (type == FLV_TAG_TYPE_AUDIO) {
ae48547a
             stream_type = FLV_STREAM_TYPE_AUDIO;
e4529df9
             flags    = avio_r8(s->pb);
             size--;
         } else if (type == FLV_TAG_TYPE_VIDEO) {
ae48547a
             stream_type = FLV_STREAM_TYPE_VIDEO;
e4529df9
             flags    = avio_r8(s->pb);
             size--;
ae48547a
             if ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_VIDEO_INFO_CMD)
f3c51215
                 goto skip;
ae48547a
         } else if (type == FLV_TAG_TYPE_META) {
             stream_type=FLV_STREAM_TYPE_DATA;
1df64d6c
             if (size > 13 + 1 + 4) { // Header-type metadata stuff
                 int type;
ae48547a
                 meta_pos = avio_tell(s->pb);
1df64d6c
                 type = flv_read_metabody(s, next);
a86928d2
                 if (type == 0 && dts == 0 || type < 0 || type == TYPE_UNKNOWN) {
56291434
                     if (type < 0 && flv->validate_count &&
                         flv->validate_index[0].pos     > next &&
                         flv->validate_index[0].pos - 4 < next
                     ) {
                         av_log(s, AV_LOG_WARNING, "Adjusting next position due to index mismatch\n");
                         next = flv->validate_index[0].pos - 4;
                     }
ae48547a
                     goto skip;
1df64d6c
                 } else if (type == TYPE_ONTEXTDATA) {
                     avpriv_request_sample(s, "OnTextData packet");
                     return flv_data_packet(s, pkt, dts, next);
3727cd54
                 } else if (type == TYPE_ONCAPTION) {
                     return flv_data_packet(s, pkt, dts, next);
ae48547a
                 }
                 avio_seek(s->pb, meta_pos, SEEK_SET);
f3c51215
             }
e4529df9
         } else {
ae48547a
             av_log(s, AV_LOG_DEBUG,
277ae5a7
                    "Skipping flv packet: type %d, size %d, flags %d.\n",
ae48547a
                    type, size, flags);
e4529df9
 skip:
15537c90
             if (avio_seek(s->pb, next, SEEK_SET) != next) {
                  // This can happen if flv_read_metabody above read past
                  // next, on a non-seekable input, and the preceding data has
                  // been flushed out from the IO buffer.
                  av_log(s, AV_LOG_ERROR, "Unable to seek to the next packet\n");
                  return AVERROR_INVALIDDATA;
             }
0bac7a43
             ret = FFERROR_REDO;
3496a20b
             goto leave;
c054f116
         }
ae58b54b
 
e4529df9
         /* skip empty data packets */
3496a20b
         if (!size) {
0bac7a43
             ret = FFERROR_REDO;
3496a20b
             goto leave;
         }
e4529df9
 
         /* now find stream */
         for (i = 0; i < s->nb_streams; i++) {
             st = s->streams[i];
ae48547a
             if (stream_type == FLV_STREAM_TYPE_AUDIO) {
6f69f7a8
                 if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO &&
                     (s->audio_codec_id || flv_same_audio_codec(st->codecpar, flags)))
e4529df9
                     break;
ae48547a
             } else if (stream_type == FLV_STREAM_TYPE_VIDEO) {
6f69f7a8
                 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
                     (s->video_codec_id || flv_same_video_codec(st->codecpar, flags)))
ae48547a
                     break;
             } else if (stream_type == FLV_STREAM_TYPE_DATA) {
6f69f7a8
                 if (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE)
e4529df9
                     break;
09a445ce
             }
         }
ae48547a
         if (i == s->nb_streams) {
7869b295
             static const enum AVMediaType stream_types[] = {AVMEDIA_TYPE_VIDEO, AVMEDIA_TYPE_AUDIO, AVMEDIA_TYPE_SUBTITLE};
ae48547a
             st = create_stream(s, stream_types[stream_type]);
             if (!st)
                 return AVERROR(ENOMEM);
ec794685
 
ae48547a
         }
40d552da
         av_log(s, AV_LOG_TRACE, "%d %X %d \n", stream_type, flags, st->discard);
fa14804c
 
4de591e6
         if ((s->pb->seekable & AVIO_SEEKABLE_NORMAL) &&
203f9c8f
             ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY ||
               stream_type == FLV_STREAM_TYPE_AUDIO))
fa14804c
             av_add_index_entry(st, pos, dts, size, 0, AVINDEX_KEYFRAME);
 
ae48547a
         if (  (st->discard >= AVDISCARD_NONKEY && !((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY || (stream_type == FLV_STREAM_TYPE_AUDIO)))
             ||(st->discard >= AVDISCARD_BIDIR  &&  ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_DISP_INTER && (stream_type == FLV_STREAM_TYPE_VIDEO)))
             || st->discard >= AVDISCARD_ALL
         ) {
e4529df9
             avio_seek(s->pb, next, SEEK_SET);
0bac7a43
             ret = FFERROR_REDO;
3496a20b
             goto leave;
e4529df9
         }
068f2a22
 
e4529df9
     // if not streamed and no duration from metadata then seek to end to find
     // the duration from the timestamps
83548fe8
     if ((s->pb->seekable & AVIO_SEEKABLE_NORMAL) &&
         (!s->duration || s->duration == AV_NOPTS_VALUE) &&
09f4822e
         !flv->searched_for_end) {
15f14fc7
         int size;
e4529df9
         const int64_t pos   = avio_tell(s->pb);
40665d27
         // Read the last 4 bytes of the file, this should be the size of the
         // previous FLV tag. Use the timestamp of its payload as duration.
ae48547a
         int64_t fsize       = avio_size(s->pb);
231ffb92
 retry_duration:
e4529df9
         avio_seek(s->pb, fsize - 4, SEEK_SET);
         size = avio_rb32(s->pb);
e4eb13ca
         if (size > 0 && size < fsize) {
             // Seek to the start of the last FLV tag at position (fsize - 4 - size)
             // but skip the byte indicating the type.
             avio_seek(s->pb, fsize - 3 - size, SEEK_SET);
             if (size == avio_rb24(s->pb) + 11) {
                 uint32_t ts = avio_rb24(s->pb);
                 ts         |= avio_r8(s->pb) << 24;
e5b5676c
                 if (ts)
                     s->duration = ts * (int64_t)AV_TIME_BASE / 1000;
                 else if (fsize >= 8 && fsize - 8 >= size) {
                     fsize -= size+4;
                     goto retry_duration;
                 }
231ffb92
             }
15f14fc7
         }
231ffb92
 
f59d8ff8
         avio_seek(s->pb, pos, SEEK_SET);
71a5cd7d
         flv->searched_for_end = 1;
15f14fc7
     }
 
ae48547a
     if (stream_type == FLV_STREAM_TYPE_AUDIO) {
2215c39e
         int bits_per_coded_sample;
e4529df9
         channels = (flags & FLV_AUDIO_CHANNEL_MASK) == FLV_STEREO ? 2 : 1;
         sample_rate = 44100 << ((flags & FLV_AUDIO_SAMPLERATE_MASK) >>
                                 FLV_AUDIO_SAMPLERATE_OFFSET) >> 3;
2215c39e
         bits_per_coded_sample = (flags & FLV_AUDIO_SAMPLESIZE_MASK) ? 16 : 8;
9200514a
         if (!st->codecpar->channels || !st->codecpar->sample_rate ||
             !st->codecpar->bits_per_coded_sample) {
             st->codecpar->channels              = channels;
             st->codecpar->channel_layout        = channels == 1
e4529df9
                                                ? AV_CH_LAYOUT_MONO
                                                : AV_CH_LAYOUT_STEREO;
9200514a
             st->codecpar->sample_rate           = sample_rate;
             st->codecpar->bits_per_coded_sample = bits_per_coded_sample;
2f3d7ea9
         }
9200514a
         if (!st->codecpar->codec_id) {
             flv_set_audio_codec(s, st, st->codecpar,
e4529df9
                                 flags & FLV_AUDIO_CODECID_MASK);
             flv->last_sample_rate =
9200514a
             sample_rate           = st->codecpar->sample_rate;
e4529df9
             flv->last_channels    =
9200514a
             channels              = st->codecpar->channels;
2215c39e
         } else {
9200514a
             AVCodecParameters *par = avcodec_parameters_alloc();
             if (!par) {
                 ret = AVERROR(ENOMEM);
                 goto leave;
             }
             par->sample_rate = sample_rate;
             par->bits_per_coded_sample = bits_per_coded_sample;
             flv_set_audio_codec(s, st, par, flags & FLV_AUDIO_CODECID_MASK);
             sample_rate = par->sample_rate;
             avcodec_parameters_free(&par);
068f2a22
         }
ae48547a
     } else if (stream_type == FLV_STREAM_TYPE_VIDEO) {
98b3a797
         int ret = flv_set_video_codec(s, st, flags & FLV_VIDEO_CODECID_MASK, 1);
         if (ret < 0)
             return ret;
         size -= ret;
3727cd54
     } else if (stream_type == FLV_STREAM_TYPE_DATA) {
6f69f7a8
         st->codecpar->codec_id = AV_CODEC_ID_TEXT;
bb01a3f0
     }
 
9200514a
     if (st->codecpar->codec_id == AV_CODEC_ID_AAC ||
6f69f7a8
         st->codecpar->codec_id == AV_CODEC_ID_H264 ||
         st->codecpar->codec_id == AV_CODEC_ID_MPEG4) {
e63a3628
         int type = avio_r8(s->pb);
04fd3e81
         size--;
279e3aaa
 
         if (size < 0) {
             ret = AVERROR_INVALIDDATA;
             goto leave;
         }
 
6f69f7a8
         if (st->codecpar->codec_id == AV_CODEC_ID_H264 || st->codecpar->codec_id == AV_CODEC_ID_MPEG4) {
e4529df9
             // sign extension
             int32_t cts = (avio_rb24(s->pb) + 0xff800000) ^ 0xff800000;
ebd61055
             pts = dts + cts;
7da5ff5c
             if (cts < 0) { // dts might be wrong
                 if (!flv->wrong_dts)
                     av_log(s, AV_LOG_WARNING,
                         "Negative cts, previous timestamps might be wrong.\n");
ebd61055
                 flv->wrong_dts = 1;
dbc3e110
             } else if (FFABS(dts - pts) > 1000*60*15) {
                 av_log(s, AV_LOG_WARNING,
                        "invalid timestamps %"PRId64" %"PRId64"\n", dts, pts);
                 dts = pts = AV_NOPTS_VALUE;
ebd61055
             }
04fd3e81
         }
6f69f7a8
         if (type == 0 && (!st->codecpar->extradata || st->codecpar->codec_id == AV_CODEC_ID_AAC ||
             st->codecpar->codec_id == AV_CODEC_ID_H264)) {
419787a2
             AVDictionaryEntry *t;
 
9200514a
             if (st->codecpar->extradata) {
52c522c7
                 if ((ret = flv_queue_extradata(flv, s->pb, stream_type, size)) < 0)
251f320f
                     return ret;
0bac7a43
                 ret = FFERROR_REDO;
251f320f
                 goto leave;
             }
6298eb81
             if ((ret = flv_get_extradata(s, st, size)) < 0)
04fd3e81
                 return ret;
547f8345
 
419787a2
             /* Workaround for buggy Omnia A/XE encoder */
             t = av_dict_get(s->metadata, "Encoder", NULL, 0);
6f69f7a8
             if (st->codecpar->codec_id == AV_CODEC_ID_AAC && t && !strcmp(t->value, "Omnia A/XE"))
                 st->codecpar->extradata_size = 2;
419787a2
 
6f69f7a8
             if (st->codecpar->codec_id == AV_CODEC_ID_AAC && 0) {
d2718187
                 MPEG4AudioConfig cfg;
547f8345
 
6f69f7a8
                 if (avpriv_mpeg4audio_get_config(&cfg, st->codecpar->extradata,
                                                  st->codecpar->extradata_size * 8, 1) >= 0) {
9200514a
                 st->codecpar->channels       = cfg.channels;
                 st->codecpar->channel_layout = 0;
7d6096e4
                 if (cfg.ext_sample_rate)
9200514a
                     st->codecpar->sample_rate = cfg.ext_sample_rate;
7d6096e4
                 else
9200514a
                     st->codecpar->sample_rate = cfg.sample_rate;
1a3eb042
                 av_log(s, AV_LOG_TRACE, "mp4a config channels %d sample rate %d\n",
6f69f7a8
                         st->codecpar->channels, st->codecpar->sample_rate);
5500e653
                 }
d2718187
             }
 
0bac7a43
             ret = FFERROR_REDO;
527c2e64
             goto leave;
04fd3e81
         }
     }
 
fcb4228c
     /* skip empty data packets */
527c2e64
     if (!size) {
0bac7a43
         ret = FFERROR_REDO;
527c2e64
         goto leave;
     }
fcb4228c
 
e4529df9
     ret = av_get_packet(s->pb, pkt, size);
20044cd9
     if (ret < 0)
         return ret;
e4529df9
     pkt->dts          = dts;
     pkt->pts          = pts == AV_NOPTS_VALUE ? dts : pts;
d4f5d74a
     pkt->stream_index = st->index;
a81494b6
     pkt->pos          = pos;
52c522c7
     if (flv->new_extradata[stream_type]) {
251f320f
         uint8_t *side = av_packet_new_side_data(pkt, AV_PKT_DATA_NEW_EXTRADATA,
52c522c7
                                                 flv->new_extradata_size[stream_type]);
251f320f
         if (side) {
52c522c7
             memcpy(side, flv->new_extradata[stream_type],
                    flv->new_extradata_size[stream_type]);
             av_freep(&flv->new_extradata[stream_type]);
             flv->new_extradata_size[stream_type] = 0;
251f320f
         }
     }
ae48547a
     if (stream_type == FLV_STREAM_TYPE_AUDIO &&
                     (sample_rate != flv->last_sample_rate ||
e4529df9
                      channels    != flv->last_channels)) {
2215c39e
         flv->last_sample_rate = sample_rate;
         flv->last_channels    = channels;
         ff_add_param_change(pkt, channels, 0, sample_rate, 0, 0);
     }
115329f1
 
4c050429
     if (    stream_type == FLV_STREAM_TYPE_AUDIO ||
0078430e
             ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY) ||
4c050429
             stream_type == FLV_STREAM_TYPE_DATA)
cc947f04
         pkt->flags |= AV_PKT_FLAG_KEY;
115329f1
 
527c2e64
 leave:
cbbd906b
     last = avio_rb32(s->pb);
e8931d79
     if (last != orig_size + 11 && last != orig_size + 10 &&
e0faad83
         !avio_feof(s->pb) &&
9a099526
         (last != orig_size || !last) && last != flv->sum_flv_tag_size &&
14f6c435
         !flv->broken_sizes) {
3f380b9b
         av_log(s, AV_LOG_ERROR, "Packet mismatch %d %d %d\n", last, orig_size + 11, flv->sum_flv_tag_size);
cbbd906b
         avio_seek(s->pb, pos + 1, SEEK_SET);
         ret = resync(s);
c2f861ca
         av_packet_unref(pkt);
cbbd906b
         if (ret >= 0) {
             goto retry;
         }
     }
d4f5d74a
     return ret;
 }
 
fc8fa007
 static int flv_read_seek(AVFormatContext *s, int stream_index,
e4529df9
                          int64_t ts, int flags)
fc8fa007
 {
7e297a46
     FLVContext *flv = s->priv_data;
     flv->validate_count = 0;
ff1ec0c3
     return avio_seek_time(s->pb, stream_index, ts, flags);
fc8fa007
 }
 
5b54a90c
 #define OFFSET(x) offsetof(FLVContext, x)
 #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
 static const AVOption options[] = {
43ecec0f
     { "flv_metadata", "Allocate streams according to the onMetaData array", OFFSET(trust_metadata), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VD },
07793962
     { "missing_streams", "", OFFSET(missing_streams), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 0xFF, VD | AV_OPT_FLAG_EXPORT | AV_OPT_FLAG_READONLY },
5b54a90c
     { NULL }
 };
 
0915b531
 static const AVClass flv_class = {
5b54a90c
     .class_name = "flvdec",
     .item_name  = av_default_item_name,
     .option     = options,
     .version    = LIBAVUTIL_VERSION_INT,
 };
 
66355be3
 AVInputFormat ff_flv_demuxer = {
dfc2c4d9
     .name           = "flv",
0177b7d2
     .long_name      = NULL_IF_CONFIG_SMALL("FLV (Flash Video)"),
dfc2c4d9
     .priv_data_size = sizeof(FLVContext),
     .read_probe     = flv_probe,
     .read_header    = flv_read_header,
     .read_packet    = flv_read_packet,
20234a4b
     .read_seek      = flv_read_seek,
     .read_close     = flv_read_close,
     .extensions     = "flv",
0915b531
     .priv_class     = &flv_class,
d4f5d74a
 };
2fbdfba0
 
 static const AVClass live_flv_class = {
dc5972f8
     .class_name = "live_flvdec",
2fbdfba0
     .item_name  = av_default_item_name,
     .option     = options,
     .version    = LIBAVUTIL_VERSION_INT,
 };
 
 AVInputFormat ff_live_flv_demuxer = {
     .name           = "live_flv",
     .long_name      = NULL_IF_CONFIG_SMALL("live RTMP FLV (Flash Video)"),
     .priv_data_size = sizeof(FLVContext),
     .read_probe     = live_flv_probe,
     .read_header    = flv_read_header,
     .read_packet    = flv_read_packet,
     .read_seek      = flv_read_seek,
     .read_close     = flv_read_close,
     .extensions     = "flv",
     .priv_class     = &live_flv_class,
     .flags          = AVFMT_TS_DISCONT
 };