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