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:
  *  - upper 4bits: difference between encoded width and visible width
  *  - lower 4bits: difference between encoded height and visible height
  *
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
 
ebd61055
 typedef struct {
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;
ebd61055
 } FLVContext;
 
d4f5d74a
 static int flv_probe(AVProbeData *p)
 {
     const uint8_t *d;
 
     d = p->buf;
e4529df9
     if (d[0] == 'F' &&
         d[1] == 'L' &&
         d[2] == 'V' &&
         d[3] < 5 && d[5] == 0 &&
         AV_RB32(d + 5) > 8) {
74248229
         return AVPROBE_SCORE_MAX;
d4f5d74a
     }
     return 0;
 }
 
41f43202
 static AVStream *create_stream(AVFormatContext *s, int codec_type)
21e2dc9f
 {
     AVStream *st = avformat_new_stream(s, NULL);
     if (!st)
         return NULL;
     st->codec->codec_type = codec_type;
ae48547a
     if (s->nb_streams>=3 ||(   s->nb_streams==2
7d82020f
                            && s->streams[0]->codec->codec_type != AVMEDIA_TYPE_DATA
                            && s->streams[1]->codec->codec_type != AVMEDIA_TYPE_DATA))
         s->ctx_flags &= ~AVFMTCTX_NOHEADER;
 
21e2dc9f
     avpriv_set_pts_info(st, 32, 1, 1000); /* 32 bit pts in ms */
     return st;
 }
e4529df9
 
09a445ce
 static int flv_same_audio_codec(AVCodecContext *acodec, int flags)
 {
     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;
 
     if (!acodec->codec_id && !acodec->codec_tag)
         return 1;
 
     if (acodec->bits_per_coded_sample != bits_per_coded_sample)
         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
         return codec_id == acodec->codec_id;
     case FLV_CODECID_PCM_LE:
e4529df9
         codec_id = bits_per_coded_sample == 8
                    ? AV_CODEC_ID_PCM_U8
                    : AV_CODEC_ID_PCM_S16LE;
09a445ce
         return codec_id == acodec->codec_id;
     case FLV_CODECID_AAC:
36ef5369
         return acodec->codec_id == AV_CODEC_ID_AAC;
09a445ce
     case FLV_CODECID_ADPCM:
36ef5369
         return acodec->codec_id == AV_CODEC_ID_ADPCM_SWF;
09a445ce
     case FLV_CODECID_SPEEX:
36ef5369
         return acodec->codec_id == AV_CODEC_ID_SPEEX;
09a445ce
     case FLV_CODECID_MP3:
36ef5369
         return acodec->codec_id == AV_CODEC_ID_MP3;
09a445ce
     case FLV_CODECID_NELLYMOSER_8KHZ_MONO:
     case FLV_CODECID_NELLYMOSER_16KHZ_MONO:
     case FLV_CODECID_NELLYMOSER:
36ef5369
         return acodec->codec_id == AV_CODEC_ID_NELLYMOSER;
09a445ce
     case FLV_CODECID_PCM_MULAW:
         return acodec->sample_rate == 8000 &&
e4529df9
                acodec->codec_id    == AV_CODEC_ID_PCM_MULAW;
09a445ce
     case FLV_CODECID_PCM_ALAW:
390b4d70
         return acodec->sample_rate == 8000 &&
e4529df9
                acodec->codec_id    == AV_CODEC_ID_PCM_ALAW;
09a445ce
     default:
         return acodec->codec_tag == (flv_codecid >> FLV_AUDIO_CODECID_OFFSET);
     }
 }
21e2dc9f
 
e4529df9
 static void flv_set_audio_codec(AVFormatContext *s, AVStream *astream,
                                 AVCodecContext *acodec, int flv_codecid)
 {
     switch (flv_codecid) {
     // no distinction between S16 and S8 PCM codec flags
     case FLV_CODECID_PCM:
         acodec->codec_id = acodec->bits_per_coded_sample == 8
                            ? 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:
         acodec->codec_id = acodec->bits_per_coded_sample == 8
                            ? AV_CODEC_ID_PCM_U8
                            : AV_CODEC_ID_PCM_S16LE;
         break;
     case FLV_CODECID_AAC:
         acodec->codec_id = AV_CODEC_ID_AAC;
         break;
     case FLV_CODECID_ADPCM:
         acodec->codec_id = AV_CODEC_ID_ADPCM_SWF;
         break;
     case FLV_CODECID_SPEEX:
         acodec->codec_id    = AV_CODEC_ID_SPEEX;
         acodec->sample_rate = 16000;
         break;
     case FLV_CODECID_MP3:
         acodec->codec_id      = AV_CODEC_ID_MP3;
         astream->need_parsing = AVSTREAM_PARSE_FULL;
         break;
     case FLV_CODECID_NELLYMOSER_8KHZ_MONO:
         // in case metadata does not otherwise declare samplerate
         acodec->sample_rate = 8000;
         acodec->codec_id    = AV_CODEC_ID_NELLYMOSER;
         break;
     case FLV_CODECID_NELLYMOSER_16KHZ_MONO:
         acodec->sample_rate = 16000;
         acodec->codec_id    = AV_CODEC_ID_NELLYMOSER;
         break;
     case FLV_CODECID_NELLYMOSER:
         acodec->codec_id = AV_CODEC_ID_NELLYMOSER;
         break;
     case FLV_CODECID_PCM_MULAW:
         acodec->sample_rate = 8000;
         acodec->codec_id    = AV_CODEC_ID_PCM_MULAW;
         break;
     case FLV_CODECID_PCM_ALAW:
         acodec->sample_rate = 8000;
         acodec->codec_id    = AV_CODEC_ID_PCM_ALAW;
         break;
     default:
a6881765
         avpriv_request_sample(s, "Audio codec (%x)",
e4529df9
                flv_codecid >> FLV_AUDIO_CODECID_OFFSET);
         acodec->codec_tag = flv_codecid >> FLV_AUDIO_CODECID_OFFSET;
428cc588
     }
 }
 
09a445ce
 static int flv_same_video_codec(AVCodecContext *vcodec, int flags)
 {
     int flv_codecid = flags & FLV_VIDEO_CODECID_MASK;
 
     if (!vcodec->codec_id && !vcodec->codec_tag)
         return 1;
 
     switch (flv_codecid) {
e4529df9
     case FLV_CODECID_H263:
         return vcodec->codec_id == AV_CODEC_ID_FLV1;
     case FLV_CODECID_SCREEN:
         return vcodec->codec_id == AV_CODEC_ID_FLASHSV;
     case FLV_CODECID_SCREEN2:
         return vcodec->codec_id == AV_CODEC_ID_FLASHSV2;
     case FLV_CODECID_VP6:
         return vcodec->codec_id == AV_CODEC_ID_VP6F;
     case FLV_CODECID_VP6A:
         return vcodec->codec_id == AV_CODEC_ID_VP6A;
     case FLV_CODECID_H264:
         return vcodec->codec_id == AV_CODEC_ID_H264;
     default:
         return vcodec->codec_tag == flv_codecid;
09a445ce
     }
 }
 
e4529df9
 static int flv_set_video_codec(AVFormatContext *s, AVStream *vstream,
                                int flv_codecid, int read)
 {
428cc588
     AVCodecContext *vcodec = vstream->codec;
e4529df9
     switch (flv_codecid) {
     case FLV_CODECID_H263:
         vcodec->codec_id = AV_CODEC_ID_FLV1;
         break;
ae48547a
     case FLV_CODECID_REALH263:
         vcodec->codec_id = AV_CODEC_ID_H263;
         break; // Really mean it this time
e4529df9
     case FLV_CODECID_SCREEN:
         vcodec->codec_id = AV_CODEC_ID_FLASHSV;
         break;
     case FLV_CODECID_SCREEN2:
         vcodec->codec_id = AV_CODEC_ID_FLASHSV2;
         break;
     case FLV_CODECID_VP6:
         vcodec->codec_id = AV_CODEC_ID_VP6F;
     case FLV_CODECID_VP6A:
         if (flv_codecid == FLV_CODECID_VP6A)
             vcodec->codec_id = AV_CODEC_ID_VP6A;
         if (read) {
             if (vcodec->extradata_size != 1) {
a807c682
                 ff_alloc_extradata(vcodec, 1);
428cc588
             }
e4529df9
             if (vcodec->extradata)
                 vcodec->extradata[0] = avio_r8(s->pb);
             else
                 avio_skip(s->pb, 1);
         }
         return 1;     // 1 byte body size adjustment for flv_read_packet()
     case FLV_CODECID_H264:
         vcodec->codec_id = AV_CODEC_ID_H264;
cc0e2ba1
         vstream->need_parsing = AVSTREAM_PARSE_HEADERS;
e4529df9
         return 3;     // not 4, reading packet type will consume one byte
ae48547a
     case FLV_CODECID_MPEG4:
         vcodec->codec_id = AV_CODEC_ID_MPEG4;
         return 3;
e4529df9
     default:
a6881765
         avpriv_request_sample(s, "Video codec (%x)", flv_codecid);
e4529df9
         vcodec->codec_tag = flv_codecid;
428cc588
     }
 
     return 0;
 }
 
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
 }
 
e4529df9
 static int parse_keyframes_index(AVFormatContext *s, AVIOContext *ioc,
                                  AVStream *vstream, int64_t max_pos)
 {
     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
 
ae48547a
     if (vstream->nb_index_entries>0) {
4717e297
         av_log(s, AV_LOG_WARNING, "Skiping duplicate index\n");
         return 0;
     }
 
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]) {
7e297a46
         for (i = 0; i < fileposlen; i++) {
e4529df9
             av_add_index_entry(vstream, filepositions[i], times[i] * 1000,
0a7ce3ca
                                0, 0, AVINDEX_KEYFRAME);
7e297a46
             if (i < 2) {
                 flv->validate_index[i].pos = filepositions[i];
                 flv->validate_index[i].dts = times[i] * 1000;
e4529df9
                 flv->validate_count        = i + 1;
7e297a46
             }
         }
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)
 {
428cc588
     AVCodecContext *acodec, *vcodec;
5b54a90c
     FLVContext *flv = s->priv_data;
471fe57e
     AVIOContext *ioc;
428cc588
     AMFDataType amf_type;
cc38e063
     char str_val[256];
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:
         if (amf_get_string(ioc, str_val, sizeof(str_val)) < 0)
             return -1;
         break;
     case AMF_DATA_TYPE_OBJECT:
         if ((vstream || astream) && key &&
ae48547a
             ioc->seekable &&
e4529df9
             !strcmp(KEYFRAMES_TAG, key) && depth == 1)
             if (parse_keyframes_index(s, ioc, vstream ? vstream : astream,
                                       max_pos) < 0)
ae48547a
                 av_log(s, AV_LOG_ERROR, "Keyframe index parsing failed\n");
428cc588
 
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.
         if (avio_r8(ioc) != AMF_END_OF_OBJECT)
428cc588
             return -1;
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:
         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;
e4529df9
         if (avio_r8(ioc) != AMF_END_OF_OBJECT)
428cc588
             return -1;
e4529df9
         break;
     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
         return -1;
428cc588
     }
 
e4529df9
     // only look for metadata values when we are not nested and key != NULL
     if (depth == 1 && key) {
428cc588
         acodec = astream ? astream->codec : NULL;
         vcodec = vstream ? vstream->codec : NULL;
 
e4529df9
         if (amf_type == AMF_DATA_TYPE_NUMBER ||
             amf_type == AMF_DATA_TYPE_BOOL) {
b204c46d
             if (!strcmp(key, "duration"))
                 s->duration = num_val * AV_TIME_BASE;
e4529df9
             else if (!strcmp(key, "videodatarate") && vcodec &&
                      0 <= (int)(num_val * 1024.0))
b204c46d
                 vcodec->bit_rate = num_val * 1024.0;
e4529df9
             else if (!strcmp(key, "audiodatarate") && acodec &&
                      0 <= (int)(num_val * 1024.0))
b204c46d
                 acodec->bit_rate = num_val * 1024.0;
21e2dc9f
             else if (!strcmp(key, "datastream")) {
41f43202
                 AVStream *st = create_stream(s, AVMEDIA_TYPE_DATA);
21e2dc9f
                 if (!st)
                     return AVERROR(ENOMEM);
36ef5369
                 st->codec->codec_id = AV_CODEC_ID_TEXT;
5b54a90c
             } else if (flv->trust_metadata) {
                 if (!strcmp(key, "videocodecid") && vcodec) {
c91c63b5
                     flv_set_video_codec(s, vstream, num_val, 0);
e4529df9
                 } else if (!strcmp(key, "audiocodecid") && acodec) {
c3d01577
                     int id = ((int)num_val) << FLV_AUDIO_CODECID_OFFSET;
                     flv_set_audio_codec(s, astream, acodec, id);
e4529df9
                 } else if (!strcmp(key, "audiosamplerate") && acodec) {
5b54a90c
                     acodec->sample_rate = num_val;
e46a2a73
                 } else if (!strcmp(key, "audiosamplesize") && acodec) {
                     acodec->bits_per_coded_sample = num_val;
                 } else if (!strcmp(key, "stereo") && acodec) {
e4529df9
                     acodec->channels       = num_val + 1;
e46a2a73
                     acodec->channel_layout = acodec->channels == 2 ?
                                              AV_CH_LAYOUT_STEREO :
                                              AV_CH_LAYOUT_MONO;
e4529df9
                 } else if (!strcmp(key, "width") && vcodec) {
5b54a90c
                     vcodec->width = num_val;
e4529df9
                 } else if (!strcmp(key, "height") && vcodec) {
5b54a90c
                     vcodec->height = num_val;
                 }
21e2dc9f
             }
b204c46d
         }
 
8b8a47f6
         if (amf_type == AMF_DATA_TYPE_OBJECT && s->nb_streams == 1 &&
            ((!acodec && !strcmp(key, "audiocodecid")) ||
             (!vcodec && !strcmp(key, "videocodecid"))))
                 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;
 
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;
 }
 
e4529df9
 static int flv_read_metabody(AVFormatContext *s, int64_t next_pos)
 {
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.
     char buffer[11];
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)
         return -1;
 
     if (!strcmp(buffer, "onTextData"))
         return 1;
 
     if (strcmp(buffer, "onMetaData"))
428cc588
         return -1;
 
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];
ae48547a
         if (stream->codec->codec_type == AVMEDIA_TYPE_VIDEO)
e4529df9
             vstream = stream;
ae48547a
         else if (stream->codec->codec_type == AVMEDIA_TYPE_AUDIO)
             astream = stream;
         else if (stream->codec->codec_type == AVMEDIA_TYPE_DATA)
             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
 {
15f14fc7
     int offset, flags;
d4f5d74a
 
45a8a02a
     avio_skip(s->pb, 4);
e63a3628
     flags = avio_r8(s->pb);
031311cb
     /* old flvtool cleared this field */
     /* FIXME: better fix needed */
     if (!flags) {
         flags = FLV_HEADER_FLAG_HASVIDEO | FLV_HEADER_FLAG_HASAUDIO;
e4529df9
         av_log(s, AV_LOG_WARNING,
                "Broken FLV file, which says no streams present, "
                "this might fail\n");
031311cb
     }
d4f5d74a
 
ee0dadc1
     s->ctx_flags |= AVFMTCTX_NOHEADER;
b41497e9
 
e4529df9
     if (flags & FLV_HEADER_FLAG_HASVIDEO)
         if (!create_stream(s, AVMEDIA_TYPE_VIDEO))
769e10f0
             return AVERROR(ENOMEM);
e4529df9
     if (flags & FLV_HEADER_FLAG_HASAUDIO)
         if (!create_stream(s, AVMEDIA_TYPE_AUDIO))
769e10f0
             return AVERROR(ENOMEM);
c054f116
     // Flag doesn't indicate whether or not there is script-data present. Must
     // create that stream if it's encountered.
4eb0c665
 
e63a3628
     offset = avio_rb32(s->pb);
f59d8ff8
     avio_seek(s->pb, offset, SEEK_SET);
45a8a02a
     avio_skip(s->pb, 4);
d4f5d74a
 
aeb20f7f
     s->start_time = 0;
 
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]);
251f320f
     return 0;
 }
 
04fd3e81
 static int flv_get_extradata(AVFormatContext *s, AVStream *st, int size)
 {
     av_free(st->codec->extradata);
d8d5258b
     if (ff_get_extradata(st->codec, s->pb, size) < 0)
04fd3e81
         return AVERROR(ENOMEM);
     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 +
                                             FF_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;
21e2dc9f
 
c951e4b4
     switch (avio_r8(pb)) {
     case AMF_DATA_TYPE_MIXEDARRAY:
21e2dc9f
         avio_seek(pb, 4, SEEK_CUR);
c951e4b4
     case AMF_DATA_TYPE_OBJECT:
         break;
     default:
         goto skip;
     }
21e2dc9f
 
c951e4b4
     while ((ret = amf_get_string(pb, buf, sizeof(buf))) > 0) {
         AMFDataType type = avio_r8(pb);
         if (type == AMF_DATA_TYPE_STRING && !strcmp(buf, "text")) {
             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];
09a445ce
         if (st->codec->codec_type == AVMEDIA_TYPE_DATA)
21e2dc9f
             break;
     }
 
     if (i == s->nb_streams) {
41f43202
         st = create_stream(s, AVMEDIA_TYPE_DATA);
21e2dc9f
         if (!st)
f900f35a
             return AVERROR_INVALIDDATA;
36ef5369
         st->codec->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;
 }
 
d4f5d74a
 static int flv_read_packet(AVFormatContext *s, AVPacket *pkt)
 {
ebd61055
     FLVContext *flv = s->priv_data;
4c050429
     int ret, i, type, size, flags;
     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;
 
     /* pkt size is repeated at end. skip it */
     for (;; avio_skip(s->pb, 4)) {
         pos  = avio_tell(s->pb);
         type = avio_r8(s->pb);
         size = avio_rb24(s->pb);
         dts  = avio_rb24(s->pb);
         dts |= avio_r8(s->pb) << 24;
         av_dlog(s, "type:%d, size:%d, dts:%"PRId64"\n", type, size, dts);
ae48547a
         if (url_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;
             }
         }
 
e4529df9
         if (size == 0)
             continue;
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;
             if (size > 13 + 1 + 4 && dts == 0) { // Header-type metadata stuff
                 meta_pos = avio_tell(s->pb);
                 if (flv_read_metabody(s, next) == 0) {
                     goto skip;
                 }
                 avio_seek(s->pb, meta_pos, SEEK_SET);
f3c51215
             }
e4529df9
         } else {
ae48547a
             av_log(s, AV_LOG_DEBUG,
                    "skipping flv packet: type %d, size %d, flags %d\n",
                    type, size, flags);
e4529df9
 skip:
             avio_seek(s->pb, next, SEEK_SET);
             continue;
c054f116
         }
ae58b54b
 
e4529df9
         /* skip empty data packets */
         if (!size)
             continue;
 
         /* now find stream */
         for (i = 0; i < s->nb_streams; i++) {
             st = s->streams[i];
ae48547a
             if (stream_type == FLV_STREAM_TYPE_AUDIO) {
                 if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
                     (s->audio_codec_id || flv_same_audio_codec(st->codec, flags)))
e4529df9
                     break;
ae48547a
             } else if (stream_type == FLV_STREAM_TYPE_VIDEO) {
                 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
                     (s->video_codec_id || flv_same_video_codec(st->codec, flags)))
                     break;
             } else if (stream_type == FLV_STREAM_TYPE_DATA) {
                 if (st->codec->codec_type == AVMEDIA_TYPE_DATA)
e4529df9
                     break;
09a445ce
             }
         }
ae48547a
         if (i == s->nb_streams) {
             static const enum AVMediaType stream_types[] = {AVMEDIA_TYPE_VIDEO, AVMEDIA_TYPE_AUDIO, AVMEDIA_TYPE_DATA};
             av_log(s, AV_LOG_WARNING, "Stream discovered after head already parsed\n");
             st = create_stream(s, stream_types[stream_type]);
             if (!st)
                 return AVERROR(ENOMEM);
ec794685
 
ae48547a
         }
         av_dlog(s, "%d %X %d \n", stream_type, flags, st->discard);
         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);
             continue;
         }
ae48547a
         if ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY || stream_type == FLV_STREAM_TYPE_AUDIO)
e4529df9
             av_add_index_entry(st, pos, dts, size, 0, AVINDEX_KEYFRAME);
         break;
6ed08157
     }
068f2a22
 
e4529df9
     // if not streamed and no duration from metadata then seek to end to find
     // the duration from the timestamps
ae48547a
     if (s->pb->seekable && (!s->duration || s->duration == AV_NOPTS_VALUE) && !flv->searched_for_end) {
15f14fc7
         int size;
e4529df9
         const int64_t pos   = avio_tell(s->pb);
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);
         avio_seek(s->pb, fsize - 3 - size, SEEK_SET);
         if (size == avio_rb24(s->pb) + 11) {
e63a3628
             uint32_t ts = avio_rb24(s->pb);
e4529df9
             ts         |= avio_r8(s->pb) << 24;
ae48547a
             if (ts)
231ffb92
                 s->duration = ts * (int64_t)AV_TIME_BASE / 1000;
ae48547a
             else if (fsize >= 8 && fsize - 8 >= size) {
231ffb92
                 fsize -= size+4;
                 goto retry_duration;
             }
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;
e4529df9
         if (!st->codec->channels || !st->codec->sample_rate ||
             !st->codec->bits_per_coded_sample) {
2215c39e
             st->codec->channels              = channels;
e4529df9
             st->codec->channel_layout        = channels == 1
                                                ? AV_CH_LAYOUT_MONO
                                                : AV_CH_LAYOUT_STEREO;
2215c39e
             st->codec->sample_rate           = sample_rate;
             st->codec->bits_per_coded_sample = bits_per_coded_sample;
2f3d7ea9
         }
e4529df9
         if (!st->codec->codec_id) {
             flv_set_audio_codec(s, st, st->codec,
                                 flags & FLV_AUDIO_CODECID_MASK);
             flv->last_sample_rate =
             sample_rate           = st->codec->sample_rate;
             flv->last_channels    =
             channels              = st->codec->channels;
2215c39e
         } else {
396ddcf2
             AVCodecContext ctx = {0};
2215c39e
             ctx.sample_rate = sample_rate;
             flv_set_audio_codec(s, st, &ctx, flags & FLV_AUDIO_CODECID_MASK);
             sample_rate = ctx.sample_rate;
068f2a22
         }
ae48547a
     } else if (stream_type == FLV_STREAM_TYPE_VIDEO) {
c91c63b5
         size -= flv_set_video_codec(s, st, flags & FLV_VIDEO_CODECID_MASK, 1);
bb01a3f0
     }
 
36ef5369
     if (st->codec->codec_id == AV_CODEC_ID_AAC ||
7a72695c
         st->codec->codec_id == AV_CODEC_ID_H264 ||
         st->codec->codec_id == AV_CODEC_ID_MPEG4) {
e63a3628
         int type = avio_r8(s->pb);
04fd3e81
         size--;
7a72695c
         if (st->codec->codec_id == AV_CODEC_ID_H264 || st->codec->codec_id == AV_CODEC_ID_MPEG4) {
e4529df9
             // sign extension
             int32_t cts = (avio_rb24(s->pb) + 0xff800000) ^ 0xff800000;
ebd61055
             pts = dts + cts;
             if (cts < 0) { // dts are wrong
                 flv->wrong_dts = 1;
e4529df9
                 av_log(s, AV_LOG_WARNING,
                        "negative cts, previous timestamps might be wrong\n");
ebd61055
             }
             if (flv->wrong_dts)
                 dts = AV_NOPTS_VALUE;
04fd3e81
         }
7a72695c
         if (type == 0 && (!st->codec->extradata || st->codec->codec_id == AV_CODEC_ID_AAC)) {
419787a2
             AVDictionaryEntry *t;
 
251f320f
             if (st->codec->extradata) {
52c522c7
                 if ((ret = flv_queue_extradata(flv, s->pb, stream_type, size)) < 0)
251f320f
                     return ret;
                 ret = AVERROR(EAGAIN);
                 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);
             if (st->codec->codec_id == AV_CODEC_ID_AAC && t && !strcmp(t->value, "Omnia A/XE"))
                 st->codec->extradata_size = 2;
 
f96a6531
             if (st->codec->codec_id == AV_CODEC_ID_AAC && 0) {
d2718187
                 MPEG4AudioConfig cfg;
547f8345
 
5500e653
                 if (avpriv_mpeg4audio_get_config(&cfg, st->codec->extradata,
                                              st->codec->extradata_size * 8, 1) >= 0) {
e4529df9
                 st->codec->channels       = cfg.channels;
644d8d2e
                 st->codec->channel_layout = 0;
7d6096e4
                 if (cfg.ext_sample_rate)
                     st->codec->sample_rate = cfg.ext_sample_rate;
                 else
                     st->codec->sample_rate = cfg.sample_rate;
9ef5a9de
                 av_dlog(s, "mp4a config channels %d sample rate %d\n",
d2718187
                         st->codec->channels, st->codec->sample_rate);
5500e653
                 }
d2718187
             }
 
527c2e64
             ret = AVERROR(EAGAIN);
             goto leave;
04fd3e81
         }
     }
 
fcb4228c
     /* skip empty data packets */
527c2e64
     if (!size) {
         ret = AVERROR(EAGAIN);
         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;
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:
45a8a02a
     avio_skip(s->pb, 4);
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[] = {
f4634ae8
     { "flv_metadata", "Allocate streams according to the onMetaData array", OFFSET(trust_metadata), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VD },
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
 };