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