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