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