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