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