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