]> git.sesse.net Git - ffmpeg/blob - libavformat/flvdec.c
avformat/nutdec: fix obvious typo
[ffmpeg] / libavformat / flvdec.c
1 /*
2  * FLV demuxer
3  * Copyright (c) 2003 The FFmpeg Project
4  *
5  * This demuxer will generate a 1 byte extradata for VP6F content.
6  * It is composed of:
7  *  - upper 4 bits: difference between encoded width and visible width
8  *  - lower 4 bits: difference between encoded height and visible height
9  *
10  * This file is part of FFmpeg.
11  *
12  * FFmpeg is free software; you can redistribute it and/or
13  * modify it under the terms of the GNU Lesser General Public
14  * License as published by the Free Software Foundation; either
15  * version 2.1 of the License, or (at your option) any later version.
16  *
17  * FFmpeg is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
20  * Lesser General Public License for more details.
21  *
22  * You should have received a copy of the GNU Lesser General Public
23  * License along with FFmpeg; if not, write to the Free Software
24  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
25  */
26
27 #include "libavutil/avstring.h"
28 #include "libavutil/channel_layout.h"
29 #include "libavutil/dict.h"
30 #include "libavutil/opt.h"
31 #include "libavutil/intfloat.h"
32 #include "libavutil/mathematics.h"
33 #include "libavcodec/bytestream.h"
34 #include "libavcodec/mpeg4audio.h"
35 #include "avformat.h"
36 #include "internal.h"
37 #include "avio_internal.h"
38 #include "flv.h"
39
40 #define VALIDATE_INDEX_TS_THRESH 2500
41
42 #define RESYNC_BUFFER_SIZE (1<<20)
43
44 typedef struct FLVContext {
45     const AVClass *class; ///< Class for private options.
46     int trust_metadata;   ///< configure streams according onMetaData
47     int trust_datasize;   ///< trust data size of FLVTag
48     int dump_full_metadata;   ///< Dump full metadata of the onMetadata
49     int wrong_dts;        ///< wrong dts due to negative cts
50     uint8_t *new_extradata[FLV_STREAM_TYPE_NB];
51     int new_extradata_size[FLV_STREAM_TYPE_NB];
52     int last_sample_rate;
53     int last_channels;
54     struct {
55         int64_t dts;
56         int64_t pos;
57     } validate_index[2];
58     int validate_next;
59     int validate_count;
60     int searched_for_end;
61
62     uint8_t resync_buffer[2*RESYNC_BUFFER_SIZE];
63
64     int broken_sizes;
65     int sum_flv_tag_size;
66
67     int last_keyframe_stream_index;
68     int keyframe_count;
69     int64_t video_bit_rate;
70     int64_t audio_bit_rate;
71     int64_t *keyframe_times;
72     int64_t *keyframe_filepositions;
73     int missing_streams;
74     AVRational framerate;
75 } FLVContext;
76
77 static int probe(AVProbeData *p, int live)
78 {
79     const uint8_t *d = p->buf;
80     unsigned offset = AV_RB32(d + 5);
81
82     if (d[0] == 'F' &&
83         d[1] == 'L' &&
84         d[2] == 'V' &&
85         d[3] < 5 && d[5] == 0 &&
86         offset + 100 < p->buf_size &&
87         offset > 8) {
88         int is_live = !memcmp(d + offset + 40, "NGINX RTMP", 10);
89
90         if (live == is_live)
91             return AVPROBE_SCORE_MAX;
92     }
93     return 0;
94 }
95
96 static int flv_probe(AVProbeData *p)
97 {
98     return probe(p, 0);
99 }
100
101 static int live_flv_probe(AVProbeData *p)
102 {
103     return probe(p, 1);
104 }
105
106 static void add_keyframes_index(AVFormatContext *s)
107 {
108     FLVContext *flv   = s->priv_data;
109     AVStream *stream  = NULL;
110     unsigned int i    = 0;
111
112     if (flv->last_keyframe_stream_index < 0) {
113         av_log(s, AV_LOG_DEBUG, "keyframe stream hasn't been created\n");
114         return;
115     }
116
117     av_assert0(flv->last_keyframe_stream_index <= s->nb_streams);
118     stream = s->streams[flv->last_keyframe_stream_index];
119
120     if (stream->nb_index_entries == 0) {
121         for (i = 0; i < flv->keyframe_count; i++) {
122             av_log(s, AV_LOG_TRACE, "keyframe filepositions = %"PRId64" times = %"PRId64"\n",
123                    flv->keyframe_filepositions[i], flv->keyframe_times[i] * 1000);
124             av_add_index_entry(stream, flv->keyframe_filepositions[i],
125                 flv->keyframe_times[i] * 1000, 0, 0, AVINDEX_KEYFRAME);
126         }
127     } else
128         av_log(s, AV_LOG_WARNING, "Skipping duplicate index\n");
129
130     if (stream->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
131         av_freep(&flv->keyframe_times);
132         av_freep(&flv->keyframe_filepositions);
133         flv->keyframe_count = 0;
134     }
135 }
136
137 static AVStream *create_stream(AVFormatContext *s, int codec_type)
138 {
139     FLVContext *flv   = s->priv_data;
140     AVStream *st = avformat_new_stream(s, NULL);
141     if (!st)
142         return NULL;
143     st->codecpar->codec_type = codec_type;
144     if (s->nb_streams>=3 ||(   s->nb_streams==2
145                            && s->streams[0]->codecpar->codec_type != AVMEDIA_TYPE_SUBTITLE
146                            && s->streams[1]->codecpar->codec_type != AVMEDIA_TYPE_SUBTITLE
147                            && s->streams[0]->codecpar->codec_type != AVMEDIA_TYPE_DATA
148                            && s->streams[1]->codecpar->codec_type != AVMEDIA_TYPE_DATA))
149         s->ctx_flags &= ~AVFMTCTX_NOHEADER;
150     if (codec_type == AVMEDIA_TYPE_AUDIO) {
151         st->codecpar->bit_rate = flv->audio_bit_rate;
152         flv->missing_streams &= ~FLV_HEADER_FLAG_HASAUDIO;
153     }
154     if (codec_type == AVMEDIA_TYPE_VIDEO) {
155         st->codecpar->bit_rate = flv->video_bit_rate;
156         flv->missing_streams &= ~FLV_HEADER_FLAG_HASVIDEO;
157         st->avg_frame_rate = flv->framerate;
158     }
159
160
161     avpriv_set_pts_info(st, 32, 1, 1000); /* 32 bit pts in ms */
162     flv->last_keyframe_stream_index = s->nb_streams - 1;
163     add_keyframes_index(s);
164     return st;
165 }
166
167 static int flv_same_audio_codec(AVCodecParameters *apar, int flags)
168 {
169     int bits_per_coded_sample = (flags & FLV_AUDIO_SAMPLESIZE_MASK) ? 16 : 8;
170     int flv_codecid           = flags & FLV_AUDIO_CODECID_MASK;
171     int codec_id;
172
173     if (!apar->codec_id && !apar->codec_tag)
174         return 1;
175
176     if (apar->bits_per_coded_sample != bits_per_coded_sample)
177         return 0;
178
179     switch (flv_codecid) {
180     // no distinction between S16 and S8 PCM codec flags
181     case FLV_CODECID_PCM:
182         codec_id = bits_per_coded_sample == 8
183                    ? AV_CODEC_ID_PCM_U8
184 #if HAVE_BIGENDIAN
185                    : AV_CODEC_ID_PCM_S16BE;
186 #else
187                    : AV_CODEC_ID_PCM_S16LE;
188 #endif
189         return codec_id == apar->codec_id;
190     case FLV_CODECID_PCM_LE:
191         codec_id = bits_per_coded_sample == 8
192                    ? AV_CODEC_ID_PCM_U8
193                    : AV_CODEC_ID_PCM_S16LE;
194         return codec_id == apar->codec_id;
195     case FLV_CODECID_AAC:
196         return apar->codec_id == AV_CODEC_ID_AAC;
197     case FLV_CODECID_ADPCM:
198         return apar->codec_id == AV_CODEC_ID_ADPCM_SWF;
199     case FLV_CODECID_SPEEX:
200         return apar->codec_id == AV_CODEC_ID_SPEEX;
201     case FLV_CODECID_MP3:
202         return apar->codec_id == AV_CODEC_ID_MP3;
203     case FLV_CODECID_NELLYMOSER_8KHZ_MONO:
204     case FLV_CODECID_NELLYMOSER_16KHZ_MONO:
205     case FLV_CODECID_NELLYMOSER:
206         return apar->codec_id == AV_CODEC_ID_NELLYMOSER;
207     case FLV_CODECID_PCM_MULAW:
208         return apar->sample_rate == 8000 &&
209                apar->codec_id    == AV_CODEC_ID_PCM_MULAW;
210     case FLV_CODECID_PCM_ALAW:
211         return apar->sample_rate == 8000 &&
212                apar->codec_id    == AV_CODEC_ID_PCM_ALAW;
213     default:
214         return apar->codec_tag == (flv_codecid >> FLV_AUDIO_CODECID_OFFSET);
215     }
216 }
217
218 static void flv_set_audio_codec(AVFormatContext *s, AVStream *astream,
219                                 AVCodecParameters *apar, int flv_codecid)
220 {
221     switch (flv_codecid) {
222     // no distinction between S16 and S8 PCM codec flags
223     case FLV_CODECID_PCM:
224         apar->codec_id = apar->bits_per_coded_sample == 8
225                            ? AV_CODEC_ID_PCM_U8
226 #if HAVE_BIGENDIAN
227                            : AV_CODEC_ID_PCM_S16BE;
228 #else
229                            : AV_CODEC_ID_PCM_S16LE;
230 #endif
231         break;
232     case FLV_CODECID_PCM_LE:
233         apar->codec_id = apar->bits_per_coded_sample == 8
234                            ? AV_CODEC_ID_PCM_U8
235                            : AV_CODEC_ID_PCM_S16LE;
236         break;
237     case FLV_CODECID_AAC:
238         apar->codec_id = AV_CODEC_ID_AAC;
239         break;
240     case FLV_CODECID_ADPCM:
241         apar->codec_id = AV_CODEC_ID_ADPCM_SWF;
242         break;
243     case FLV_CODECID_SPEEX:
244         apar->codec_id    = AV_CODEC_ID_SPEEX;
245         apar->sample_rate = 16000;
246         break;
247     case FLV_CODECID_MP3:
248         apar->codec_id      = AV_CODEC_ID_MP3;
249         astream->need_parsing = AVSTREAM_PARSE_FULL;
250         break;
251     case FLV_CODECID_NELLYMOSER_8KHZ_MONO:
252         // in case metadata does not otherwise declare samplerate
253         apar->sample_rate = 8000;
254         apar->codec_id    = AV_CODEC_ID_NELLYMOSER;
255         break;
256     case FLV_CODECID_NELLYMOSER_16KHZ_MONO:
257         apar->sample_rate = 16000;
258         apar->codec_id    = AV_CODEC_ID_NELLYMOSER;
259         break;
260     case FLV_CODECID_NELLYMOSER:
261         apar->codec_id = AV_CODEC_ID_NELLYMOSER;
262         break;
263     case FLV_CODECID_PCM_MULAW:
264         apar->sample_rate = 8000;
265         apar->codec_id    = AV_CODEC_ID_PCM_MULAW;
266         break;
267     case FLV_CODECID_PCM_ALAW:
268         apar->sample_rate = 8000;
269         apar->codec_id    = AV_CODEC_ID_PCM_ALAW;
270         break;
271     default:
272         avpriv_request_sample(s, "Audio codec (%x)",
273                flv_codecid >> FLV_AUDIO_CODECID_OFFSET);
274         apar->codec_tag = flv_codecid >> FLV_AUDIO_CODECID_OFFSET;
275     }
276 }
277
278 static int flv_same_video_codec(AVCodecParameters *vpar, int flags)
279 {
280     int flv_codecid = flags & FLV_VIDEO_CODECID_MASK;
281
282     if (!vpar->codec_id && !vpar->codec_tag)
283         return 1;
284
285     switch (flv_codecid) {
286     case FLV_CODECID_H263:
287         return vpar->codec_id == AV_CODEC_ID_FLV1;
288     case FLV_CODECID_SCREEN:
289         return vpar->codec_id == AV_CODEC_ID_FLASHSV;
290     case FLV_CODECID_SCREEN2:
291         return vpar->codec_id == AV_CODEC_ID_FLASHSV2;
292     case FLV_CODECID_VP6:
293         return vpar->codec_id == AV_CODEC_ID_VP6F;
294     case FLV_CODECID_VP6A:
295         return vpar->codec_id == AV_CODEC_ID_VP6A;
296     case FLV_CODECID_H264:
297         return vpar->codec_id == AV_CODEC_ID_H264;
298     default:
299         return vpar->codec_tag == flv_codecid;
300     }
301 }
302
303 static int flv_set_video_codec(AVFormatContext *s, AVStream *vstream,
304                                int flv_codecid, int read)
305 {
306     int ret = 0;
307     AVCodecParameters *par = vstream->codecpar;
308     enum AVCodecID old_codec_id = vstream->codecpar->codec_id;
309     switch (flv_codecid) {
310     case FLV_CODECID_H263:
311         par->codec_id = AV_CODEC_ID_FLV1;
312         break;
313     case FLV_CODECID_REALH263:
314         par->codec_id = AV_CODEC_ID_H263;
315         break; // Really mean it this time
316     case FLV_CODECID_SCREEN:
317         par->codec_id = AV_CODEC_ID_FLASHSV;
318         break;
319     case FLV_CODECID_SCREEN2:
320         par->codec_id = AV_CODEC_ID_FLASHSV2;
321         break;
322     case FLV_CODECID_VP6:
323         par->codec_id = AV_CODEC_ID_VP6F;
324     case FLV_CODECID_VP6A:
325         if (flv_codecid == FLV_CODECID_VP6A)
326             par->codec_id = AV_CODEC_ID_VP6A;
327         if (read) {
328             if (par->extradata_size != 1) {
329                 ff_alloc_extradata(par, 1);
330             }
331             if (par->extradata)
332                 par->extradata[0] = avio_r8(s->pb);
333             else
334                 avio_skip(s->pb, 1);
335         }
336         ret = 1;     // 1 byte body size adjustment for flv_read_packet()
337         break;
338     case FLV_CODECID_H264:
339         par->codec_id = AV_CODEC_ID_H264;
340         vstream->need_parsing = AVSTREAM_PARSE_HEADERS;
341         ret = 3;     // not 4, reading packet type will consume one byte
342         break;
343     case FLV_CODECID_MPEG4:
344         par->codec_id = AV_CODEC_ID_MPEG4;
345         ret = 3;
346         break;
347     default:
348         avpriv_request_sample(s, "Video codec (%x)", flv_codecid);
349         par->codec_tag = flv_codecid;
350     }
351
352     if (!vstream->internal->need_context_update && par->codec_id != old_codec_id) {
353         avpriv_request_sample(s, "Changing the codec id midstream");
354         return AVERROR_PATCHWELCOME;
355     }
356
357     return ret;
358 }
359
360 static int amf_get_string(AVIOContext *ioc, char *buffer, int buffsize)
361 {
362     int length = avio_rb16(ioc);
363     if (length >= buffsize) {
364         avio_skip(ioc, length);
365         return -1;
366     }
367
368     avio_read(ioc, buffer, length);
369
370     buffer[length] = '\0';
371
372     return length;
373 }
374
375 static int parse_keyframes_index(AVFormatContext *s, AVIOContext *ioc, int64_t max_pos)
376 {
377     FLVContext *flv       = s->priv_data;
378     unsigned int timeslen = 0, fileposlen = 0, i;
379     char str_val[256];
380     int64_t *times         = NULL;
381     int64_t *filepositions = NULL;
382     int ret                = AVERROR(ENOSYS);
383     int64_t initial_pos    = avio_tell(ioc);
384
385     if (flv->keyframe_count > 0) {
386         av_log(s, AV_LOG_DEBUG, "keyframes have been paresed\n");
387         return 0;
388     }
389     av_assert0(!flv->keyframe_times);
390     av_assert0(!flv->keyframe_filepositions);
391
392     if (s->flags & AVFMT_FLAG_IGNIDX)
393         return 0;
394
395     while (avio_tell(ioc) < max_pos - 2 &&
396            amf_get_string(ioc, str_val, sizeof(str_val)) > 0) {
397         int64_t **current_array;
398         unsigned int arraylen;
399
400         // Expect array object in context
401         if (avio_r8(ioc) != AMF_DATA_TYPE_ARRAY)
402             break;
403
404         arraylen = avio_rb32(ioc);
405         if (arraylen>>28)
406             break;
407
408         if       (!strcmp(KEYFRAMES_TIMESTAMP_TAG , str_val) && !times) {
409             current_array = &times;
410             timeslen      = arraylen;
411         } else if (!strcmp(KEYFRAMES_BYTEOFFSET_TAG, str_val) &&
412                    !filepositions) {
413             current_array = &filepositions;
414             fileposlen    = arraylen;
415         } else
416             // unexpected metatag inside keyframes, will not use such
417             // metadata for indexing
418             break;
419
420         if (!(*current_array = av_mallocz(sizeof(**current_array) * arraylen))) {
421             ret = AVERROR(ENOMEM);
422             goto finish;
423         }
424
425         for (i = 0; i < arraylen && avio_tell(ioc) < max_pos - 1; i++) {
426             if (avio_r8(ioc) != AMF_DATA_TYPE_NUMBER)
427                 goto invalid;
428             current_array[0][i] = av_int2double(avio_rb64(ioc));
429         }
430         if (times && filepositions) {
431             // All done, exiting at a position allowing amf_parse_object
432             // to finish parsing the object
433             ret = 0;
434             break;
435         }
436     }
437
438     if (timeslen == fileposlen && fileposlen>1 && max_pos <= filepositions[0]) {
439         for (i = 0; i < FFMIN(2,fileposlen); i++) {
440             flv->validate_index[i].pos = filepositions[i];
441             flv->validate_index[i].dts = times[i] * 1000;
442             flv->validate_count        = i + 1;
443         }
444         flv->keyframe_times = times;
445         flv->keyframe_filepositions = filepositions;
446         flv->keyframe_count = timeslen;
447         times = NULL;
448         filepositions = NULL;
449     } else {
450 invalid:
451         av_log(s, AV_LOG_WARNING, "Invalid keyframes object, skipping.\n");
452     }
453
454 finish:
455     av_freep(&times);
456     av_freep(&filepositions);
457     avio_seek(ioc, initial_pos, SEEK_SET);
458     return ret;
459 }
460
461 static int amf_parse_object(AVFormatContext *s, AVStream *astream,
462                             AVStream *vstream, const char *key,
463                             int64_t max_pos, int depth)
464 {
465     AVCodecParameters *apar, *vpar;
466     FLVContext *flv = s->priv_data;
467     AVIOContext *ioc;
468     AMFDataType amf_type;
469     char str_val[1024];
470     double num_val;
471
472     num_val  = 0;
473     ioc      = s->pb;
474     amf_type = avio_r8(ioc);
475
476     switch (amf_type) {
477     case AMF_DATA_TYPE_NUMBER:
478         num_val = av_int2double(avio_rb64(ioc));
479         break;
480     case AMF_DATA_TYPE_BOOL:
481         num_val = avio_r8(ioc);
482         break;
483     case AMF_DATA_TYPE_STRING:
484         if (amf_get_string(ioc, str_val, sizeof(str_val)) < 0) {
485             av_log(s, AV_LOG_ERROR, "AMF_DATA_TYPE_STRING parsing failed\n");
486             return -1;
487         }
488         break;
489     case AMF_DATA_TYPE_OBJECT:
490         if (key &&
491             (ioc->seekable & AVIO_SEEKABLE_NORMAL) &&
492             !strcmp(KEYFRAMES_TAG, key) && depth == 1)
493             if (parse_keyframes_index(s, ioc,
494                                       max_pos) < 0)
495                 av_log(s, AV_LOG_ERROR, "Keyframe index parsing failed\n");
496             else
497                 add_keyframes_index(s);
498         while (avio_tell(ioc) < max_pos - 2 &&
499                amf_get_string(ioc, str_val, sizeof(str_val)) > 0)
500             if (amf_parse_object(s, astream, vstream, str_val, max_pos,
501                                  depth + 1) < 0)
502                 return -1;     // if we couldn't skip, bomb out.
503         if (avio_r8(ioc) != AMF_END_OF_OBJECT) {
504             av_log(s, AV_LOG_ERROR, "Missing AMF_END_OF_OBJECT in AMF_DATA_TYPE_OBJECT\n");
505             return -1;
506         }
507         break;
508     case AMF_DATA_TYPE_NULL:
509     case AMF_DATA_TYPE_UNDEFINED:
510     case AMF_DATA_TYPE_UNSUPPORTED:
511         break;     // these take up no additional space
512     case AMF_DATA_TYPE_MIXEDARRAY:
513     {
514         unsigned v;
515         avio_skip(ioc, 4);     // skip 32-bit max array index
516         while (avio_tell(ioc) < max_pos - 2 &&
517                amf_get_string(ioc, str_val, sizeof(str_val)) > 0)
518             // this is the only case in which we would want a nested
519             // parse to not skip over the object
520             if (amf_parse_object(s, astream, vstream, str_val, max_pos,
521                                  depth + 1) < 0)
522                 return -1;
523         v = avio_r8(ioc);
524         if (v != AMF_END_OF_OBJECT) {
525             av_log(s, AV_LOG_ERROR, "Missing AMF_END_OF_OBJECT in AMF_DATA_TYPE_MIXEDARRAY, found %d\n", v);
526             return -1;
527         }
528         break;
529     }
530     case AMF_DATA_TYPE_ARRAY:
531     {
532         unsigned int arraylen, i;
533
534         arraylen = avio_rb32(ioc);
535         for (i = 0; i < arraylen && avio_tell(ioc) < max_pos - 1; i++)
536             if (amf_parse_object(s, NULL, NULL, NULL, max_pos,
537                                  depth + 1) < 0)
538                 return -1;      // if we couldn't skip, bomb out.
539     }
540     break;
541     case AMF_DATA_TYPE_DATE:
542         avio_skip(ioc, 8 + 2);  // timestamp (double) and UTC offset (int16)
543         break;
544     default:                    // unsupported type, we couldn't skip
545         av_log(s, AV_LOG_ERROR, "unsupported amf type %d\n", amf_type);
546         return -1;
547     }
548
549     if (key) {
550         apar = astream ? astream->codecpar : NULL;
551         vpar = vstream ? vstream->codecpar : NULL;
552
553         // stream info doesn't live any deeper than the first object
554         if (depth == 1) {
555             if (amf_type == AMF_DATA_TYPE_NUMBER ||
556                 amf_type == AMF_DATA_TYPE_BOOL) {
557                 if (!strcmp(key, "duration"))
558                     s->duration = num_val * AV_TIME_BASE;
559                 else if (!strcmp(key, "videodatarate") &&
560                          0 <= (int)(num_val * 1024.0))
561                     flv->video_bit_rate = num_val * 1024.0;
562                 else if (!strcmp(key, "audiodatarate") &&
563                          0 <= (int)(num_val * 1024.0))
564                     flv->audio_bit_rate = num_val * 1024.0;
565                 else if (!strcmp(key, "datastream")) {
566                     AVStream *st = create_stream(s, AVMEDIA_TYPE_SUBTITLE);
567                     if (!st)
568                         return AVERROR(ENOMEM);
569                     st->codecpar->codec_id = AV_CODEC_ID_TEXT;
570                 } else if (!strcmp(key, "framerate")) {
571                     flv->framerate = av_d2q(num_val, 1000);
572                     if (vstream)
573                         vstream->avg_frame_rate = flv->framerate;
574                 } else if (flv->trust_metadata) {
575                     if (!strcmp(key, "videocodecid") && vpar) {
576                         int ret = flv_set_video_codec(s, vstream, num_val, 0);
577                         if (ret < 0)
578                             return ret;
579                     } else if (!strcmp(key, "audiocodecid") && apar) {
580                         int id = ((int)num_val) << FLV_AUDIO_CODECID_OFFSET;
581                         flv_set_audio_codec(s, astream, apar, id);
582                     } else if (!strcmp(key, "audiosamplerate") && apar) {
583                         apar->sample_rate = num_val;
584                     } else if (!strcmp(key, "audiosamplesize") && apar) {
585                         apar->bits_per_coded_sample = num_val;
586                     } else if (!strcmp(key, "stereo") && apar) {
587                         apar->channels       = num_val + 1;
588                         apar->channel_layout = apar->channels == 2 ?
589                                                AV_CH_LAYOUT_STEREO :
590                                                AV_CH_LAYOUT_MONO;
591                     } else if (!strcmp(key, "width") && vpar) {
592                         vpar->width = num_val;
593                     } else if (!strcmp(key, "height") && vpar) {
594                         vpar->height = num_val;
595                     }
596                 }
597             }
598             if (amf_type == AMF_DATA_TYPE_STRING) {
599                 if (!strcmp(key, "encoder")) {
600                     int version = -1;
601                     if (1 == sscanf(str_val, "Open Broadcaster Software v0.%d", &version)) {
602                         if (version > 0 && version <= 655)
603                             flv->broken_sizes = 1;
604                     }
605                 } else if (!strcmp(key, "metadatacreator")) {
606                     if (   !strcmp (str_val, "MEGA")
607                         || !strncmp(str_val, "FlixEngine", 10))
608                         flv->broken_sizes = 1;
609                 }
610             }
611         }
612
613         if (amf_type == AMF_DATA_TYPE_OBJECT && s->nb_streams == 1 &&
614            ((!apar && !strcmp(key, "audiocodecid")) ||
615             (!vpar && !strcmp(key, "videocodecid"))))
616                 s->ctx_flags &= ~AVFMTCTX_NOHEADER; //If there is either audio/video missing, codecid will be an empty object
617
618         if ((!strcmp(key, "duration")        ||
619             !strcmp(key, "filesize")        ||
620             !strcmp(key, "width")           ||
621             !strcmp(key, "height")          ||
622             !strcmp(key, "videodatarate")   ||
623             !strcmp(key, "framerate")       ||
624             !strcmp(key, "videocodecid")    ||
625             !strcmp(key, "audiodatarate")   ||
626             !strcmp(key, "audiosamplerate") ||
627             !strcmp(key, "audiosamplesize") ||
628             !strcmp(key, "stereo")          ||
629             !strcmp(key, "audiocodecid")    ||
630             !strcmp(key, "datastream")) && !flv->dump_full_metadata)
631             return 0;
632
633         s->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
634         if (amf_type == AMF_DATA_TYPE_BOOL) {
635             av_strlcpy(str_val, num_val > 0 ? "true" : "false",
636                        sizeof(str_val));
637             av_dict_set(&s->metadata, key, str_val, 0);
638         } else if (amf_type == AMF_DATA_TYPE_NUMBER) {
639             snprintf(str_val, sizeof(str_val), "%.f", num_val);
640             av_dict_set(&s->metadata, key, str_val, 0);
641         } else if (amf_type == AMF_DATA_TYPE_STRING)
642             av_dict_set(&s->metadata, key, str_val, 0);
643     }
644
645     return 0;
646 }
647
648 #define TYPE_ONTEXTDATA 1
649 #define TYPE_ONCAPTION 2
650 #define TYPE_ONCAPTIONINFO 3
651 #define TYPE_UNKNOWN 9
652
653 static int flv_read_metabody(AVFormatContext *s, int64_t next_pos)
654 {
655     FLVContext *flv = s->priv_data;
656     AMFDataType type;
657     AVStream *stream, *astream, *vstream;
658     AVStream av_unused *dstream;
659     AVIOContext *ioc;
660     int i;
661     char buffer[32];
662
663     astream = NULL;
664     vstream = NULL;
665     dstream = NULL;
666     ioc     = s->pb;
667
668     // first object needs to be "onMetaData" string
669     type = avio_r8(ioc);
670     if (type != AMF_DATA_TYPE_STRING ||
671         amf_get_string(ioc, buffer, sizeof(buffer)) < 0)
672         return TYPE_UNKNOWN;
673
674     if (!strcmp(buffer, "onTextData"))
675         return TYPE_ONTEXTDATA;
676
677     if (!strcmp(buffer, "onCaption"))
678         return TYPE_ONCAPTION;
679
680     if (!strcmp(buffer, "onCaptionInfo"))
681         return TYPE_ONCAPTIONINFO;
682
683     if (strcmp(buffer, "onMetaData") && strcmp(buffer, "onCuePoint")) {
684         av_log(s, AV_LOG_DEBUG, "Unknown type %s\n", buffer);
685         return TYPE_UNKNOWN;
686     }
687
688     // find the streams now so that amf_parse_object doesn't need to do
689     // the lookup every time it is called.
690     for (i = 0; i < s->nb_streams; i++) {
691         stream = s->streams[i];
692         if (stream->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
693             vstream = stream;
694             flv->last_keyframe_stream_index = i;
695         } else if (stream->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
696             astream = stream;
697             if (flv->last_keyframe_stream_index == -1)
698                 flv->last_keyframe_stream_index = i;
699         }
700         else if (stream->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE)
701             dstream = stream;
702     }
703
704     // parse the second object (we want a mixed array)
705     if (amf_parse_object(s, astream, vstream, buffer, next_pos, 0) < 0)
706         return -1;
707
708     return 0;
709 }
710
711 static int flv_read_header(AVFormatContext *s)
712 {
713     int flags;
714     FLVContext *flv = s->priv_data;
715     int offset;
716     int pre_tag_size = 0;
717
718     avio_skip(s->pb, 4);
719     flags = avio_r8(s->pb);
720
721     flv->missing_streams = flags & (FLV_HEADER_FLAG_HASVIDEO | FLV_HEADER_FLAG_HASAUDIO);
722
723     s->ctx_flags |= AVFMTCTX_NOHEADER;
724
725     offset = avio_rb32(s->pb);
726     avio_seek(s->pb, offset, SEEK_SET);
727
728     /* Annex E. The FLV File Format
729      * E.3 TheFLVFileBody
730      *     Field               Type    Comment
731      *     PreviousTagSize0    UI32    Always 0
732      * */
733     pre_tag_size = avio_rb32(s->pb);
734     if (pre_tag_size) {
735         av_log(s, AV_LOG_WARNING, "Read FLV header error, input file is not a standard flv format, first PreviousTagSize0 always is 0\n");
736     }
737
738     s->start_time = 0;
739     flv->sum_flv_tag_size = 0;
740     flv->last_keyframe_stream_index = -1;
741
742     return 0;
743 }
744
745 static int flv_read_close(AVFormatContext *s)
746 {
747     int i;
748     FLVContext *flv = s->priv_data;
749     for (i=0; i<FLV_STREAM_TYPE_NB; i++)
750         av_freep(&flv->new_extradata[i]);
751     av_freep(&flv->keyframe_times);
752     av_freep(&flv->keyframe_filepositions);
753     return 0;
754 }
755
756 static int flv_get_extradata(AVFormatContext *s, AVStream *st, int size)
757 {
758     if (!size)
759         return 0;
760
761     av_freep(&st->codecpar->extradata);
762     if (ff_get_extradata(s, st->codecpar, s->pb, size) < 0)
763         return AVERROR(ENOMEM);
764     st->internal->need_context_update = 1;
765     return 0;
766 }
767
768 static int flv_queue_extradata(FLVContext *flv, AVIOContext *pb, int stream,
769                                int size)
770 {
771     if (!size)
772         return 0;
773
774     av_free(flv->new_extradata[stream]);
775     flv->new_extradata[stream] = av_mallocz(size +
776                                             AV_INPUT_BUFFER_PADDING_SIZE);
777     if (!flv->new_extradata[stream])
778         return AVERROR(ENOMEM);
779     flv->new_extradata_size[stream] = size;
780     avio_read(pb, flv->new_extradata[stream], size);
781     return 0;
782 }
783
784 static void clear_index_entries(AVFormatContext *s, int64_t pos)
785 {
786     int i, j, out;
787     av_log(s, AV_LOG_WARNING,
788            "Found invalid index entries, clearing the index.\n");
789     for (i = 0; i < s->nb_streams; i++) {
790         AVStream *st = s->streams[i];
791         /* Remove all index entries that point to >= pos */
792         out = 0;
793         for (j = 0; j < st->nb_index_entries; j++)
794             if (st->index_entries[j].pos < pos)
795                 st->index_entries[out++] = st->index_entries[j];
796         st->nb_index_entries = out;
797     }
798 }
799
800 static int amf_skip_tag(AVIOContext *pb, AMFDataType type)
801 {
802     int nb = -1, ret, parse_name = 1;
803
804     switch (type) {
805     case AMF_DATA_TYPE_NUMBER:
806         avio_skip(pb, 8);
807         break;
808     case AMF_DATA_TYPE_BOOL:
809         avio_skip(pb, 1);
810         break;
811     case AMF_DATA_TYPE_STRING:
812         avio_skip(pb, avio_rb16(pb));
813         break;
814     case AMF_DATA_TYPE_ARRAY:
815         parse_name = 0;
816     case AMF_DATA_TYPE_MIXEDARRAY:
817         nb = avio_rb32(pb);
818     case AMF_DATA_TYPE_OBJECT:
819         while(!pb->eof_reached && (nb-- > 0 || type != AMF_DATA_TYPE_ARRAY)) {
820             if (parse_name) {
821                 int size = avio_rb16(pb);
822                 if (!size) {
823                     avio_skip(pb, 1);
824                     break;
825                 }
826                 avio_skip(pb, size);
827             }
828             if ((ret = amf_skip_tag(pb, avio_r8(pb))) < 0)
829                 return ret;
830         }
831         break;
832     case AMF_DATA_TYPE_NULL:
833     case AMF_DATA_TYPE_OBJECT_END:
834         break;
835     default:
836         return AVERROR_INVALIDDATA;
837     }
838     return 0;
839 }
840
841 static int flv_data_packet(AVFormatContext *s, AVPacket *pkt,
842                            int64_t dts, int64_t next)
843 {
844     AVIOContext *pb = s->pb;
845     AVStream *st    = NULL;
846     char buf[20];
847     int ret = AVERROR_INVALIDDATA;
848     int i, length = -1;
849     int array = 0;
850
851     switch (avio_r8(pb)) {
852     case AMF_DATA_TYPE_ARRAY:
853         array = 1;
854     case AMF_DATA_TYPE_MIXEDARRAY:
855         avio_seek(pb, 4, SEEK_CUR);
856     case AMF_DATA_TYPE_OBJECT:
857         break;
858     default:
859         goto skip;
860     }
861
862     while (array || (ret = amf_get_string(pb, buf, sizeof(buf))) > 0) {
863         AMFDataType type = avio_r8(pb);
864         if (type == AMF_DATA_TYPE_STRING && (array || !strcmp(buf, "text"))) {
865             length = avio_rb16(pb);
866             ret    = av_get_packet(pb, pkt, length);
867             if (ret < 0)
868                 goto skip;
869             else
870                 break;
871         } else {
872             if ((ret = amf_skip_tag(pb, type)) < 0)
873                 goto skip;
874         }
875     }
876
877     if (length < 0) {
878         ret = AVERROR_INVALIDDATA;
879         goto skip;
880     }
881
882     for (i = 0; i < s->nb_streams; i++) {
883         st = s->streams[i];
884         if (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE)
885             break;
886     }
887
888     if (i == s->nb_streams) {
889         st = create_stream(s, AVMEDIA_TYPE_SUBTITLE);
890         if (!st)
891             return AVERROR(ENOMEM);
892         st->codecpar->codec_id = AV_CODEC_ID_TEXT;
893     }
894
895     pkt->dts  = dts;
896     pkt->pts  = dts;
897     pkt->size = ret;
898
899     pkt->stream_index = st->index;
900     pkt->flags       |= AV_PKT_FLAG_KEY;
901
902 skip:
903     avio_seek(s->pb, next + 4, SEEK_SET);
904
905     return ret;
906 }
907
908 static int resync(AVFormatContext *s)
909 {
910     FLVContext *flv = s->priv_data;
911     int64_t i;
912     int64_t pos = avio_tell(s->pb);
913
914     for (i=0; !avio_feof(s->pb); i++) {
915         int j  = i & (RESYNC_BUFFER_SIZE-1);
916         int j1 = j + RESYNC_BUFFER_SIZE;
917         flv->resync_buffer[j ] =
918         flv->resync_buffer[j1] = avio_r8(s->pb);
919
920         if (i > 22) {
921             unsigned lsize2 = AV_RB32(flv->resync_buffer + j1 - 4);
922             if (lsize2 >= 11 && lsize2 + 8LL < FFMIN(i, RESYNC_BUFFER_SIZE)) {
923                 unsigned  size2 = AV_RB24(flv->resync_buffer + j1 - lsize2 + 1 - 4);
924                 unsigned lsize1 = AV_RB32(flv->resync_buffer + j1 - lsize2 - 8);
925                 if (lsize1 >= 11 && lsize1 + 8LL + lsize2 < FFMIN(i, RESYNC_BUFFER_SIZE)) {
926                     unsigned  size1 = AV_RB24(flv->resync_buffer + j1 - lsize1 + 1 - lsize2 - 8);
927                     if (size1 == lsize1 - 11 && size2  == lsize2 - 11) {
928                         avio_seek(s->pb, pos + i - lsize1 - lsize2 - 8, SEEK_SET);
929                         return 1;
930                     }
931                 }
932             }
933         }
934     }
935     return AVERROR_EOF;
936 }
937
938 static int flv_read_packet(AVFormatContext *s, AVPacket *pkt)
939 {
940     FLVContext *flv = s->priv_data;
941     int ret, i, size, flags;
942     enum FlvTagType type;
943     int stream_type=-1;
944     int64_t next, pos, meta_pos;
945     int64_t dts, pts = AV_NOPTS_VALUE;
946     int av_uninit(channels);
947     int av_uninit(sample_rate);
948     AVStream *st    = NULL;
949     int last = -1;
950     int orig_size;
951
952 retry:
953     /* pkt size is repeated at end. skip it */
954         pos  = avio_tell(s->pb);
955         type = (avio_r8(s->pb) & 0x1F);
956         orig_size =
957         size = avio_rb24(s->pb);
958         flv->sum_flv_tag_size += size + 11;
959         dts  = avio_rb24(s->pb);
960         dts |= (unsigned)avio_r8(s->pb) << 24;
961         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));
962         if (avio_feof(s->pb))
963             return AVERROR_EOF;
964         avio_skip(s->pb, 3); /* stream id, always 0 */
965         flags = 0;
966
967         if (flv->validate_next < flv->validate_count) {
968             int64_t validate_pos = flv->validate_index[flv->validate_next].pos;
969             if (pos == validate_pos) {
970                 if (FFABS(dts - flv->validate_index[flv->validate_next].dts) <=
971                     VALIDATE_INDEX_TS_THRESH) {
972                     flv->validate_next++;
973                 } else {
974                     clear_index_entries(s, validate_pos);
975                     flv->validate_count = 0;
976                 }
977             } else if (pos > validate_pos) {
978                 clear_index_entries(s, validate_pos);
979                 flv->validate_count = 0;
980             }
981         }
982
983         if (size == 0) {
984             ret = FFERROR_REDO;
985             goto leave;
986         }
987
988         next = size + avio_tell(s->pb);
989
990         if (type == FLV_TAG_TYPE_AUDIO) {
991             stream_type = FLV_STREAM_TYPE_AUDIO;
992             flags    = avio_r8(s->pb);
993             size--;
994         } else if (type == FLV_TAG_TYPE_VIDEO) {
995             stream_type = FLV_STREAM_TYPE_VIDEO;
996             flags    = avio_r8(s->pb);
997             size--;
998             if ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_VIDEO_INFO_CMD)
999                 goto skip;
1000         } else if (type == FLV_TAG_TYPE_META) {
1001             stream_type=FLV_STREAM_TYPE_SUBTITLE;
1002             if (size > 13 + 1 + 4) { // Header-type metadata stuff
1003                 int type;
1004                 meta_pos = avio_tell(s->pb);
1005                 type = flv_read_metabody(s, next);
1006                 if (type == 0 && dts == 0 || type < 0) {
1007                     if (type < 0 && flv->validate_count &&
1008                         flv->validate_index[0].pos     > next &&
1009                         flv->validate_index[0].pos - 4 < next
1010                     ) {
1011                         av_log(s, AV_LOG_WARNING, "Adjusting next position due to index mismatch\n");
1012                         next = flv->validate_index[0].pos - 4;
1013                     }
1014                     goto skip;
1015                 } else if (type == TYPE_ONTEXTDATA) {
1016                     avpriv_request_sample(s, "OnTextData packet");
1017                     return flv_data_packet(s, pkt, dts, next);
1018                 } else if (type == TYPE_ONCAPTION) {
1019                     return flv_data_packet(s, pkt, dts, next);
1020                 } else if (type == TYPE_UNKNOWN) {
1021                     stream_type = FLV_STREAM_TYPE_DATA;
1022                 }
1023                 avio_seek(s->pb, meta_pos, SEEK_SET);
1024             }
1025         } else {
1026             av_log(s, AV_LOG_DEBUG,
1027                    "Skipping flv packet: type %d, size %d, flags %d.\n",
1028                    type, size, flags);
1029 skip:
1030             if (avio_seek(s->pb, next, SEEK_SET) != next) {
1031                  // This can happen if flv_read_metabody above read past
1032                  // next, on a non-seekable input, and the preceding data has
1033                  // been flushed out from the IO buffer.
1034                  av_log(s, AV_LOG_ERROR, "Unable to seek to the next packet\n");
1035                  return AVERROR_INVALIDDATA;
1036             }
1037             ret = FFERROR_REDO;
1038             goto leave;
1039         }
1040
1041         /* skip empty data packets */
1042         if (!size) {
1043             ret = FFERROR_REDO;
1044             goto leave;
1045         }
1046
1047         /* now find stream */
1048         for (i = 0; i < s->nb_streams; i++) {
1049             st = s->streams[i];
1050             if (stream_type == FLV_STREAM_TYPE_AUDIO) {
1051                 if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO &&
1052                     (s->audio_codec_id || flv_same_audio_codec(st->codecpar, flags)))
1053                     break;
1054             } else if (stream_type == FLV_STREAM_TYPE_VIDEO) {
1055                 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
1056                     (s->video_codec_id || flv_same_video_codec(st->codecpar, flags)))
1057                     break;
1058             } else if (stream_type == FLV_STREAM_TYPE_SUBTITLE) {
1059                 if (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE)
1060                     break;
1061             } else if (stream_type == FLV_STREAM_TYPE_DATA) {
1062                 if (st->codecpar->codec_type == AVMEDIA_TYPE_DATA)
1063                     break;
1064             }
1065         }
1066         if (i == s->nb_streams) {
1067             static const enum AVMediaType stream_types[] = {AVMEDIA_TYPE_VIDEO, AVMEDIA_TYPE_AUDIO, AVMEDIA_TYPE_SUBTITLE, AVMEDIA_TYPE_DATA};
1068             st = create_stream(s, stream_types[stream_type]);
1069             if (!st)
1070                 return AVERROR(ENOMEM);
1071
1072         }
1073         av_log(s, AV_LOG_TRACE, "%d %X %d \n", stream_type, flags, st->discard);
1074
1075         if ((s->pb->seekable & AVIO_SEEKABLE_NORMAL) &&
1076             ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY ||
1077               stream_type == FLV_STREAM_TYPE_AUDIO))
1078             av_add_index_entry(st, pos, dts, size, 0, AVINDEX_KEYFRAME);
1079
1080         if (  (st->discard >= AVDISCARD_NONKEY && !((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY || (stream_type == FLV_STREAM_TYPE_AUDIO)))
1081             ||(st->discard >= AVDISCARD_BIDIR  &&  ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_DISP_INTER && (stream_type == FLV_STREAM_TYPE_VIDEO)))
1082             || st->discard >= AVDISCARD_ALL
1083         ) {
1084             avio_seek(s->pb, next, SEEK_SET);
1085             ret = FFERROR_REDO;
1086             goto leave;
1087         }
1088
1089     // if not streamed and no duration from metadata then seek to end to find
1090     // the duration from the timestamps
1091     if ((s->pb->seekable & AVIO_SEEKABLE_NORMAL) &&
1092         (!s->duration || s->duration == AV_NOPTS_VALUE) &&
1093         !flv->searched_for_end) {
1094         int size;
1095         const int64_t pos   = avio_tell(s->pb);
1096         // Read the last 4 bytes of the file, this should be the size of the
1097         // previous FLV tag. Use the timestamp of its payload as duration.
1098         int64_t fsize       = avio_size(s->pb);
1099 retry_duration:
1100         avio_seek(s->pb, fsize - 4, SEEK_SET);
1101         size = avio_rb32(s->pb);
1102         if (size > 0 && size < fsize) {
1103             // Seek to the start of the last FLV tag at position (fsize - 4 - size)
1104             // but skip the byte indicating the type.
1105             avio_seek(s->pb, fsize - 3 - size, SEEK_SET);
1106             if (size == avio_rb24(s->pb) + 11) {
1107                 uint32_t ts = avio_rb24(s->pb);
1108                 ts         |= avio_r8(s->pb) << 24;
1109                 if (ts)
1110                     s->duration = ts * (int64_t)AV_TIME_BASE / 1000;
1111                 else if (fsize >= 8 && fsize - 8 >= size) {
1112                     fsize -= size+4;
1113                     goto retry_duration;
1114                 }
1115             }
1116         }
1117
1118         avio_seek(s->pb, pos, SEEK_SET);
1119         flv->searched_for_end = 1;
1120     }
1121
1122     if (stream_type == FLV_STREAM_TYPE_AUDIO) {
1123         int bits_per_coded_sample;
1124         channels = (flags & FLV_AUDIO_CHANNEL_MASK) == FLV_STEREO ? 2 : 1;
1125         sample_rate = 44100 << ((flags & FLV_AUDIO_SAMPLERATE_MASK) >>
1126                                 FLV_AUDIO_SAMPLERATE_OFFSET) >> 3;
1127         bits_per_coded_sample = (flags & FLV_AUDIO_SAMPLESIZE_MASK) ? 16 : 8;
1128         if (!st->codecpar->channels || !st->codecpar->sample_rate ||
1129             !st->codecpar->bits_per_coded_sample) {
1130             st->codecpar->channels              = channels;
1131             st->codecpar->channel_layout        = channels == 1
1132                                                ? AV_CH_LAYOUT_MONO
1133                                                : AV_CH_LAYOUT_STEREO;
1134             st->codecpar->sample_rate           = sample_rate;
1135             st->codecpar->bits_per_coded_sample = bits_per_coded_sample;
1136         }
1137         if (!st->codecpar->codec_id) {
1138             flv_set_audio_codec(s, st, st->codecpar,
1139                                 flags & FLV_AUDIO_CODECID_MASK);
1140             flv->last_sample_rate =
1141             sample_rate           = st->codecpar->sample_rate;
1142             flv->last_channels    =
1143             channels              = st->codecpar->channels;
1144         } else {
1145             AVCodecParameters *par = avcodec_parameters_alloc();
1146             if (!par) {
1147                 ret = AVERROR(ENOMEM);
1148                 goto leave;
1149             }
1150             par->sample_rate = sample_rate;
1151             par->bits_per_coded_sample = bits_per_coded_sample;
1152             flv_set_audio_codec(s, st, par, flags & FLV_AUDIO_CODECID_MASK);
1153             sample_rate = par->sample_rate;
1154             avcodec_parameters_free(&par);
1155         }
1156     } else if (stream_type == FLV_STREAM_TYPE_VIDEO) {
1157         int ret = flv_set_video_codec(s, st, flags & FLV_VIDEO_CODECID_MASK, 1);
1158         if (ret < 0)
1159             return ret;
1160         size -= ret;
1161     } else if (stream_type == FLV_STREAM_TYPE_SUBTITLE) {
1162         st->codecpar->codec_id = AV_CODEC_ID_TEXT;
1163     } else if (stream_type == FLV_STREAM_TYPE_DATA) {
1164         st->codecpar->codec_id = AV_CODEC_ID_NONE; // Opaque AMF data
1165     }
1166
1167     if (st->codecpar->codec_id == AV_CODEC_ID_AAC ||
1168         st->codecpar->codec_id == AV_CODEC_ID_H264 ||
1169         st->codecpar->codec_id == AV_CODEC_ID_MPEG4) {
1170         int type = avio_r8(s->pb);
1171         size--;
1172
1173         if (size < 0) {
1174             ret = AVERROR_INVALIDDATA;
1175             goto leave;
1176         }
1177
1178         if (st->codecpar->codec_id == AV_CODEC_ID_H264 || st->codecpar->codec_id == AV_CODEC_ID_MPEG4) {
1179             // sign extension
1180             int32_t cts = (avio_rb24(s->pb) + 0xff800000) ^ 0xff800000;
1181             pts = dts + cts;
1182             if (cts < 0) { // dts might be wrong
1183                 if (!flv->wrong_dts)
1184                     av_log(s, AV_LOG_WARNING,
1185                         "Negative cts, previous timestamps might be wrong.\n");
1186                 flv->wrong_dts = 1;
1187             } else if (FFABS(dts - pts) > 1000*60*15) {
1188                 av_log(s, AV_LOG_WARNING,
1189                        "invalid timestamps %"PRId64" %"PRId64"\n", dts, pts);
1190                 dts = pts = AV_NOPTS_VALUE;
1191             }
1192         }
1193         if (type == 0 && (!st->codecpar->extradata || st->codecpar->codec_id == AV_CODEC_ID_AAC ||
1194             st->codecpar->codec_id == AV_CODEC_ID_H264)) {
1195             AVDictionaryEntry *t;
1196
1197             if (st->codecpar->extradata) {
1198                 if ((ret = flv_queue_extradata(flv, s->pb, stream_type, size)) < 0)
1199                     return ret;
1200                 ret = FFERROR_REDO;
1201                 goto leave;
1202             }
1203             if ((ret = flv_get_extradata(s, st, size)) < 0)
1204                 return ret;
1205
1206             /* Workaround for buggy Omnia A/XE encoder */
1207             t = av_dict_get(s->metadata, "Encoder", NULL, 0);
1208             if (st->codecpar->codec_id == AV_CODEC_ID_AAC && t && !strcmp(t->value, "Omnia A/XE"))
1209                 st->codecpar->extradata_size = 2;
1210
1211             if (st->codecpar->codec_id == AV_CODEC_ID_AAC && 0) {
1212                 MPEG4AudioConfig cfg;
1213
1214                 if (avpriv_mpeg4audio_get_config(&cfg, st->codecpar->extradata,
1215                                                  st->codecpar->extradata_size * 8, 1) >= 0) {
1216                 st->codecpar->channels       = cfg.channels;
1217                 st->codecpar->channel_layout = 0;
1218                 if (cfg.ext_sample_rate)
1219                     st->codecpar->sample_rate = cfg.ext_sample_rate;
1220                 else
1221                     st->codecpar->sample_rate = cfg.sample_rate;
1222                 av_log(s, AV_LOG_TRACE, "mp4a config channels %d sample rate %d\n",
1223                         st->codecpar->channels, st->codecpar->sample_rate);
1224                 }
1225             }
1226
1227             ret = FFERROR_REDO;
1228             goto leave;
1229         }
1230     }
1231
1232     /* skip empty data packets */
1233     if (!size) {
1234         ret = FFERROR_REDO;
1235         goto leave;
1236     }
1237
1238     ret = av_get_packet(s->pb, pkt, size);
1239     if (ret < 0)
1240         return ret;
1241     pkt->dts          = dts;
1242     pkt->pts          = pts == AV_NOPTS_VALUE ? dts : pts;
1243     pkt->stream_index = st->index;
1244     pkt->pos          = pos;
1245     if (flv->new_extradata[stream_type]) {
1246         uint8_t *side = av_packet_new_side_data(pkt, AV_PKT_DATA_NEW_EXTRADATA,
1247                                                 flv->new_extradata_size[stream_type]);
1248         if (side) {
1249             memcpy(side, flv->new_extradata[stream_type],
1250                    flv->new_extradata_size[stream_type]);
1251             av_freep(&flv->new_extradata[stream_type]);
1252             flv->new_extradata_size[stream_type] = 0;
1253         }
1254     }
1255     if (stream_type == FLV_STREAM_TYPE_AUDIO &&
1256                     (sample_rate != flv->last_sample_rate ||
1257                      channels    != flv->last_channels)) {
1258         flv->last_sample_rate = sample_rate;
1259         flv->last_channels    = channels;
1260         ff_add_param_change(pkt, channels, 0, sample_rate, 0, 0);
1261     }
1262
1263     if (    stream_type == FLV_STREAM_TYPE_AUDIO ||
1264             ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY) ||
1265             stream_type == FLV_STREAM_TYPE_SUBTITLE ||
1266             stream_type == FLV_STREAM_TYPE_DATA)
1267         pkt->flags |= AV_PKT_FLAG_KEY;
1268
1269 leave:
1270     last = avio_rb32(s->pb);
1271     if (!flv->trust_datasize) {
1272         if (last != orig_size + 11 && last != orig_size + 10 &&
1273             !avio_feof(s->pb) &&
1274             (last != orig_size || !last) && last != flv->sum_flv_tag_size &&
1275             !flv->broken_sizes) {
1276             av_log(s, AV_LOG_ERROR, "Packet mismatch %d %d %d\n", last, orig_size + 11, flv->sum_flv_tag_size);
1277             avio_seek(s->pb, pos + 1, SEEK_SET);
1278             ret = resync(s);
1279             av_packet_unref(pkt);
1280             if (ret >= 0) {
1281                 goto retry;
1282             }
1283         }
1284     }
1285     return ret;
1286 }
1287
1288 static int flv_read_seek(AVFormatContext *s, int stream_index,
1289                          int64_t ts, int flags)
1290 {
1291     FLVContext *flv = s->priv_data;
1292     flv->validate_count = 0;
1293     return avio_seek_time(s->pb, stream_index, ts, flags);
1294 }
1295
1296 #define OFFSET(x) offsetof(FLVContext, x)
1297 #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
1298 static const AVOption options[] = {
1299     { "flv_metadata", "Allocate streams according to the onMetaData array", OFFSET(trust_metadata), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VD },
1300     { "flv_full_metadata", "Dump full metadata of the onMetadata", OFFSET(dump_full_metadata), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VD },
1301     { "flv_ignore_prevtag", "Ignore the Size of previous tag", OFFSET(trust_datasize), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VD },
1302     { "missing_streams", "", OFFSET(missing_streams), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 0xFF, VD | AV_OPT_FLAG_EXPORT | AV_OPT_FLAG_READONLY },
1303     { NULL }
1304 };
1305
1306 static const AVClass flv_class = {
1307     .class_name = "flvdec",
1308     .item_name  = av_default_item_name,
1309     .option     = options,
1310     .version    = LIBAVUTIL_VERSION_INT,
1311 };
1312
1313 AVInputFormat ff_flv_demuxer = {
1314     .name           = "flv",
1315     .long_name      = NULL_IF_CONFIG_SMALL("FLV (Flash Video)"),
1316     .priv_data_size = sizeof(FLVContext),
1317     .read_probe     = flv_probe,
1318     .read_header    = flv_read_header,
1319     .read_packet    = flv_read_packet,
1320     .read_seek      = flv_read_seek,
1321     .read_close     = flv_read_close,
1322     .extensions     = "flv",
1323     .priv_class     = &flv_class,
1324 };
1325
1326 static const AVClass live_flv_class = {
1327     .class_name = "live_flvdec",
1328     .item_name  = av_default_item_name,
1329     .option     = options,
1330     .version    = LIBAVUTIL_VERSION_INT,
1331 };
1332
1333 AVInputFormat ff_live_flv_demuxer = {
1334     .name           = "live_flv",
1335     .long_name      = NULL_IF_CONFIG_SMALL("live RTMP FLV (Flash Video)"),
1336     .priv_data_size = sizeof(FLVContext),
1337     .read_probe     = live_flv_probe,
1338     .read_header    = flv_read_header,
1339     .read_packet    = flv_read_packet,
1340     .read_seek      = flv_read_seek,
1341     .read_close     = flv_read_close,
1342     .extensions     = "flv",
1343     .priv_class     = &live_flv_class,
1344     .flags          = AVFMT_TS_DISCONT
1345 };