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