]> git.sesse.net Git - ffmpeg/blob - libavformat/flvdec.c
swr/resample_template: prevent end_index from overflowing and add check for delta_fra...
[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 4bits: difference between encoded width and visible width
8  *  - lower 4bits: 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 typedef struct {
43     const AVClass *class; ///< Class for private options.
44     int trust_metadata;   ///< configure streams according onMetaData
45     int wrong_dts;        ///< wrong dts due to negative cts
46     uint8_t *new_extradata[FLV_STREAM_TYPE_NB];
47     int new_extradata_size[FLV_STREAM_TYPE_NB];
48     int last_sample_rate;
49     int last_channels;
50     struct {
51         int64_t dts;
52         int64_t pos;
53     } validate_index[2];
54     int validate_next;
55     int validate_count;
56     int searched_for_end;
57 } FLVContext;
58
59 static int flv_probe(AVProbeData *p)
60 {
61     const uint8_t *d;
62
63     d = p->buf;
64     if (d[0] == 'F' &&
65         d[1] == 'L' &&
66         d[2] == 'V' &&
67         d[3] < 5 && d[5] == 0 &&
68         AV_RB32(d + 5) > 8) {
69         return AVPROBE_SCORE_MAX;
70     }
71     return 0;
72 }
73
74 static AVStream *create_stream(AVFormatContext *s, int codec_type)
75 {
76     AVStream *st = avformat_new_stream(s, NULL);
77     if (!st)
78         return NULL;
79     st->codec->codec_type = codec_type;
80     if (s->nb_streams>=3 ||(   s->nb_streams==2
81                            && s->streams[0]->codec->codec_type != AVMEDIA_TYPE_DATA
82                            && s->streams[1]->codec->codec_type != AVMEDIA_TYPE_DATA))
83         s->ctx_flags &= ~AVFMTCTX_NOHEADER;
84
85     avpriv_set_pts_info(st, 32, 1, 1000); /* 32 bit pts in ms */
86     return st;
87 }
88
89 static int flv_same_audio_codec(AVCodecContext *acodec, int flags)
90 {
91     int bits_per_coded_sample = (flags & FLV_AUDIO_SAMPLESIZE_MASK) ? 16 : 8;
92     int flv_codecid           = flags & FLV_AUDIO_CODECID_MASK;
93     int codec_id;
94
95     if (!acodec->codec_id && !acodec->codec_tag)
96         return 1;
97
98     if (acodec->bits_per_coded_sample != bits_per_coded_sample)
99         return 0;
100
101     switch (flv_codecid) {
102     // no distinction between S16 and S8 PCM codec flags
103     case FLV_CODECID_PCM:
104         codec_id = bits_per_coded_sample == 8
105                    ? AV_CODEC_ID_PCM_U8
106 #if HAVE_BIGENDIAN
107                    : AV_CODEC_ID_PCM_S16BE;
108 #else
109                    : AV_CODEC_ID_PCM_S16LE;
110 #endif
111         return codec_id == acodec->codec_id;
112     case FLV_CODECID_PCM_LE:
113         codec_id = bits_per_coded_sample == 8
114                    ? AV_CODEC_ID_PCM_U8
115                    : AV_CODEC_ID_PCM_S16LE;
116         return codec_id == acodec->codec_id;
117     case FLV_CODECID_AAC:
118         return acodec->codec_id == AV_CODEC_ID_AAC;
119     case FLV_CODECID_ADPCM:
120         return acodec->codec_id == AV_CODEC_ID_ADPCM_SWF;
121     case FLV_CODECID_SPEEX:
122         return acodec->codec_id == AV_CODEC_ID_SPEEX;
123     case FLV_CODECID_MP3:
124         return acodec->codec_id == AV_CODEC_ID_MP3;
125     case FLV_CODECID_NELLYMOSER_8KHZ_MONO:
126     case FLV_CODECID_NELLYMOSER_16KHZ_MONO:
127     case FLV_CODECID_NELLYMOSER:
128         return acodec->codec_id == AV_CODEC_ID_NELLYMOSER;
129     case FLV_CODECID_PCM_MULAW:
130         return acodec->sample_rate == 8000 &&
131                acodec->codec_id    == AV_CODEC_ID_PCM_MULAW;
132     case FLV_CODECID_PCM_ALAW:
133         return acodec->sample_rate == 8000 &&
134                acodec->codec_id    == AV_CODEC_ID_PCM_ALAW;
135     default:
136         return acodec->codec_tag == (flv_codecid >> FLV_AUDIO_CODECID_OFFSET);
137     }
138 }
139
140 static void flv_set_audio_codec(AVFormatContext *s, AVStream *astream,
141                                 AVCodecContext *acodec, int flv_codecid)
142 {
143     switch (flv_codecid) {
144     // no distinction between S16 and S8 PCM codec flags
145     case FLV_CODECID_PCM:
146         acodec->codec_id = acodec->bits_per_coded_sample == 8
147                            ? AV_CODEC_ID_PCM_U8
148 #if HAVE_BIGENDIAN
149                            : AV_CODEC_ID_PCM_S16BE;
150 #else
151                            : AV_CODEC_ID_PCM_S16LE;
152 #endif
153         break;
154     case FLV_CODECID_PCM_LE:
155         acodec->codec_id = acodec->bits_per_coded_sample == 8
156                            ? AV_CODEC_ID_PCM_U8
157                            : AV_CODEC_ID_PCM_S16LE;
158         break;
159     case FLV_CODECID_AAC:
160         acodec->codec_id = AV_CODEC_ID_AAC;
161         break;
162     case FLV_CODECID_ADPCM:
163         acodec->codec_id = AV_CODEC_ID_ADPCM_SWF;
164         break;
165     case FLV_CODECID_SPEEX:
166         acodec->codec_id    = AV_CODEC_ID_SPEEX;
167         acodec->sample_rate = 16000;
168         break;
169     case FLV_CODECID_MP3:
170         acodec->codec_id      = AV_CODEC_ID_MP3;
171         astream->need_parsing = AVSTREAM_PARSE_FULL;
172         break;
173     case FLV_CODECID_NELLYMOSER_8KHZ_MONO:
174         // in case metadata does not otherwise declare samplerate
175         acodec->sample_rate = 8000;
176         acodec->codec_id    = AV_CODEC_ID_NELLYMOSER;
177         break;
178     case FLV_CODECID_NELLYMOSER_16KHZ_MONO:
179         acodec->sample_rate = 16000;
180         acodec->codec_id    = AV_CODEC_ID_NELLYMOSER;
181         break;
182     case FLV_CODECID_NELLYMOSER:
183         acodec->codec_id = AV_CODEC_ID_NELLYMOSER;
184         break;
185     case FLV_CODECID_PCM_MULAW:
186         acodec->sample_rate = 8000;
187         acodec->codec_id    = AV_CODEC_ID_PCM_MULAW;
188         break;
189     case FLV_CODECID_PCM_ALAW:
190         acodec->sample_rate = 8000;
191         acodec->codec_id    = AV_CODEC_ID_PCM_ALAW;
192         break;
193     default:
194         avpriv_request_sample(s, "Audio codec (%x)",
195                flv_codecid >> FLV_AUDIO_CODECID_OFFSET);
196         acodec->codec_tag = flv_codecid >> FLV_AUDIO_CODECID_OFFSET;
197     }
198 }
199
200 static int flv_same_video_codec(AVCodecContext *vcodec, int flags)
201 {
202     int flv_codecid = flags & FLV_VIDEO_CODECID_MASK;
203
204     if (!vcodec->codec_id && !vcodec->codec_tag)
205         return 1;
206
207     switch (flv_codecid) {
208     case FLV_CODECID_H263:
209         return vcodec->codec_id == AV_CODEC_ID_FLV1;
210     case FLV_CODECID_SCREEN:
211         return vcodec->codec_id == AV_CODEC_ID_FLASHSV;
212     case FLV_CODECID_SCREEN2:
213         return vcodec->codec_id == AV_CODEC_ID_FLASHSV2;
214     case FLV_CODECID_VP6:
215         return vcodec->codec_id == AV_CODEC_ID_VP6F;
216     case FLV_CODECID_VP6A:
217         return vcodec->codec_id == AV_CODEC_ID_VP6A;
218     case FLV_CODECID_H264:
219         return vcodec->codec_id == AV_CODEC_ID_H264;
220     default:
221         return vcodec->codec_tag == flv_codecid;
222     }
223 }
224
225 static int flv_set_video_codec(AVFormatContext *s, AVStream *vstream,
226                                int flv_codecid, int read)
227 {
228     AVCodecContext *vcodec = vstream->codec;
229     switch (flv_codecid) {
230     case FLV_CODECID_H263:
231         vcodec->codec_id = AV_CODEC_ID_FLV1;
232         break;
233     case FLV_CODECID_REALH263:
234         vcodec->codec_id = AV_CODEC_ID_H263;
235         break; // Really mean it this time
236     case FLV_CODECID_SCREEN:
237         vcodec->codec_id = AV_CODEC_ID_FLASHSV;
238         break;
239     case FLV_CODECID_SCREEN2:
240         vcodec->codec_id = AV_CODEC_ID_FLASHSV2;
241         break;
242     case FLV_CODECID_VP6:
243         vcodec->codec_id = AV_CODEC_ID_VP6F;
244     case FLV_CODECID_VP6A:
245         if (flv_codecid == FLV_CODECID_VP6A)
246             vcodec->codec_id = AV_CODEC_ID_VP6A;
247         if (read) {
248             if (vcodec->extradata_size != 1) {
249                 ff_alloc_extradata(vcodec, 1);
250             }
251             if (vcodec->extradata)
252                 vcodec->extradata[0] = avio_r8(s->pb);
253             else
254                 avio_skip(s->pb, 1);
255         }
256         return 1;     // 1 byte body size adjustment for flv_read_packet()
257     case FLV_CODECID_H264:
258         vcodec->codec_id = AV_CODEC_ID_H264;
259         vstream->need_parsing = AVSTREAM_PARSE_HEADERS;
260         return 3;     // not 4, reading packet type will consume one byte
261     case FLV_CODECID_MPEG4:
262         vcodec->codec_id = AV_CODEC_ID_MPEG4;
263         return 3;
264     default:
265         avpriv_request_sample(s, "Video codec (%x)", flv_codecid);
266         vcodec->codec_tag = flv_codecid;
267     }
268
269     return 0;
270 }
271
272 static int amf_get_string(AVIOContext *ioc, char *buffer, int buffsize)
273 {
274     int length = avio_rb16(ioc);
275     if (length >= buffsize) {
276         avio_skip(ioc, length);
277         return -1;
278     }
279
280     avio_read(ioc, buffer, length);
281
282     buffer[length] = '\0';
283
284     return length;
285 }
286
287 static int parse_keyframes_index(AVFormatContext *s, AVIOContext *ioc,
288                                  AVStream *vstream, int64_t max_pos)
289 {
290     FLVContext *flv       = s->priv_data;
291     unsigned int timeslen = 0, fileposlen = 0, i;
292     char str_val[256];
293     int64_t *times         = NULL;
294     int64_t *filepositions = NULL;
295     int ret                = AVERROR(ENOSYS);
296     int64_t initial_pos    = avio_tell(ioc);
297
298     if (vstream->nb_index_entries>0) {
299         av_log(s, AV_LOG_WARNING, "Skipping duplicate index\n");
300         return 0;
301     }
302
303     if (s->flags & AVFMT_FLAG_IGNIDX)
304         return 0;
305
306     while (avio_tell(ioc) < max_pos - 2 &&
307            amf_get_string(ioc, str_val, sizeof(str_val)) > 0) {
308         int64_t **current_array;
309         unsigned int arraylen;
310
311         // Expect array object in context
312         if (avio_r8(ioc) != AMF_DATA_TYPE_ARRAY)
313             break;
314
315         arraylen = avio_rb32(ioc);
316         if (arraylen>>28)
317             break;
318
319         if       (!strcmp(KEYFRAMES_TIMESTAMP_TAG , str_val) && !times) {
320             current_array = &times;
321             timeslen      = arraylen;
322         } else if (!strcmp(KEYFRAMES_BYTEOFFSET_TAG, str_val) &&
323                    !filepositions) {
324             current_array = &filepositions;
325             fileposlen    = arraylen;
326         } else
327             // unexpected metatag inside keyframes, will not use such
328             // metadata for indexing
329             break;
330
331         if (!(*current_array = av_mallocz(sizeof(**current_array) * arraylen))) {
332             ret = AVERROR(ENOMEM);
333             goto finish;
334         }
335
336         for (i = 0; i < arraylen && avio_tell(ioc) < max_pos - 1; i++) {
337             if (avio_r8(ioc) != AMF_DATA_TYPE_NUMBER)
338                 goto invalid;
339             current_array[0][i] = av_int2double(avio_rb64(ioc));
340         }
341         if (times && filepositions) {
342             // All done, exiting at a position allowing amf_parse_object
343             // to finish parsing the object
344             ret = 0;
345             break;
346         }
347     }
348
349     if (timeslen == fileposlen && fileposlen>1 && max_pos <= filepositions[0]) {
350         for (i = 0; i < fileposlen; i++) {
351             av_add_index_entry(vstream, filepositions[i], times[i] * 1000,
352                                0, 0, AVINDEX_KEYFRAME);
353             if (i < 2) {
354                 flv->validate_index[i].pos = filepositions[i];
355                 flv->validate_index[i].dts = times[i] * 1000;
356                 flv->validate_count        = i + 1;
357             }
358         }
359     } else {
360 invalid:
361         av_log(s, AV_LOG_WARNING, "Invalid keyframes object, skipping.\n");
362     }
363
364 finish:
365     av_freep(&times);
366     av_freep(&filepositions);
367     avio_seek(ioc, initial_pos, SEEK_SET);
368     return ret;
369 }
370
371 static int amf_parse_object(AVFormatContext *s, AVStream *astream,
372                             AVStream *vstream, const char *key,
373                             int64_t max_pos, int depth)
374 {
375     AVCodecContext *acodec, *vcodec;
376     FLVContext *flv = s->priv_data;
377     AVIOContext *ioc;
378     AMFDataType amf_type;
379     char str_val[256];
380     double num_val;
381
382     num_val  = 0;
383     ioc      = s->pb;
384     amf_type = avio_r8(ioc);
385
386     switch (amf_type) {
387     case AMF_DATA_TYPE_NUMBER:
388         num_val = av_int2double(avio_rb64(ioc));
389         break;
390     case AMF_DATA_TYPE_BOOL:
391         num_val = avio_r8(ioc);
392         break;
393     case AMF_DATA_TYPE_STRING:
394         if (amf_get_string(ioc, str_val, sizeof(str_val)) < 0)
395             return -1;
396         break;
397     case AMF_DATA_TYPE_OBJECT:
398         if ((vstream || astream) && key &&
399             ioc->seekable &&
400             !strcmp(KEYFRAMES_TAG, key) && depth == 1)
401             if (parse_keyframes_index(s, ioc, vstream ? vstream : astream,
402                                       max_pos) < 0)
403                 av_log(s, AV_LOG_ERROR, "Keyframe index parsing failed\n");
404
405         while (avio_tell(ioc) < max_pos - 2 &&
406                amf_get_string(ioc, str_val, sizeof(str_val)) > 0)
407             if (amf_parse_object(s, astream, vstream, str_val, max_pos,
408                                  depth + 1) < 0)
409                 return -1;     // if we couldn't skip, bomb out.
410         if (avio_r8(ioc) != AMF_END_OF_OBJECT)
411             return -1;
412         break;
413     case AMF_DATA_TYPE_NULL:
414     case AMF_DATA_TYPE_UNDEFINED:
415     case AMF_DATA_TYPE_UNSUPPORTED:
416         break;     // these take up no additional space
417     case AMF_DATA_TYPE_MIXEDARRAY:
418         avio_skip(ioc, 4);     // skip 32-bit max array index
419         while (avio_tell(ioc) < max_pos - 2 &&
420                amf_get_string(ioc, str_val, sizeof(str_val)) > 0)
421             // this is the only case in which we would want a nested
422             // parse to not skip over the object
423             if (amf_parse_object(s, astream, vstream, str_val, max_pos,
424                                  depth + 1) < 0)
425                 return -1;
426         if (avio_r8(ioc) != AMF_END_OF_OBJECT)
427             return -1;
428         break;
429     case AMF_DATA_TYPE_ARRAY:
430     {
431         unsigned int arraylen, i;
432
433         arraylen = avio_rb32(ioc);
434         for (i = 0; i < arraylen && avio_tell(ioc) < max_pos - 1; i++)
435             if (amf_parse_object(s, NULL, NULL, NULL, max_pos,
436                                  depth + 1) < 0)
437                 return -1;      // if we couldn't skip, bomb out.
438     }
439     break;
440     case AMF_DATA_TYPE_DATE:
441         avio_skip(ioc, 8 + 2);  // timestamp (double) and UTC offset (int16)
442         break;
443     default:                    // unsupported type, we couldn't skip
444         return -1;
445     }
446
447     // only look for metadata values when we are not nested and key != NULL
448     if (depth == 1 && key) {
449         acodec = astream ? astream->codec : NULL;
450         vcodec = vstream ? vstream->codec : NULL;
451
452         if (amf_type == AMF_DATA_TYPE_NUMBER ||
453             amf_type == AMF_DATA_TYPE_BOOL) {
454             if (!strcmp(key, "duration"))
455                 s->duration = num_val * AV_TIME_BASE;
456             else if (!strcmp(key, "videodatarate") && vcodec &&
457                      0 <= (int)(num_val * 1024.0))
458                 vcodec->bit_rate = num_val * 1024.0;
459             else if (!strcmp(key, "audiodatarate") && acodec &&
460                      0 <= (int)(num_val * 1024.0))
461                 acodec->bit_rate = num_val * 1024.0;
462             else if (!strcmp(key, "datastream")) {
463                 AVStream *st = create_stream(s, AVMEDIA_TYPE_DATA);
464                 if (!st)
465                     return AVERROR(ENOMEM);
466                 st->codec->codec_id = AV_CODEC_ID_TEXT;
467             } else if (flv->trust_metadata) {
468                 if (!strcmp(key, "videocodecid") && vcodec) {
469                     flv_set_video_codec(s, vstream, num_val, 0);
470                 } else if (!strcmp(key, "audiocodecid") && acodec) {
471                     int id = ((int)num_val) << FLV_AUDIO_CODECID_OFFSET;
472                     flv_set_audio_codec(s, astream, acodec, id);
473                 } else if (!strcmp(key, "audiosamplerate") && acodec) {
474                     acodec->sample_rate = num_val;
475                 } else if (!strcmp(key, "audiosamplesize") && acodec) {
476                     acodec->bits_per_coded_sample = num_val;
477                 } else if (!strcmp(key, "stereo") && acodec) {
478                     acodec->channels       = num_val + 1;
479                     acodec->channel_layout = acodec->channels == 2 ?
480                                              AV_CH_LAYOUT_STEREO :
481                                              AV_CH_LAYOUT_MONO;
482                 } else if (!strcmp(key, "width") && vcodec) {
483                     vcodec->width = num_val;
484                 } else if (!strcmp(key, "height") && vcodec) {
485                     vcodec->height = num_val;
486                 }
487             }
488         }
489
490         if (amf_type == AMF_DATA_TYPE_OBJECT && s->nb_streams == 1 &&
491            ((!acodec && !strcmp(key, "audiocodecid")) ||
492             (!vcodec && !strcmp(key, "videocodecid"))))
493                 s->ctx_flags &= ~AVFMTCTX_NOHEADER; //If there is either audio/video missing, codecid will be an empty object
494
495         if (!strcmp(key, "duration")        ||
496             !strcmp(key, "filesize")        ||
497             !strcmp(key, "width")           ||
498             !strcmp(key, "height")          ||
499             !strcmp(key, "videodatarate")   ||
500             !strcmp(key, "framerate")       ||
501             !strcmp(key, "videocodecid")    ||
502             !strcmp(key, "audiodatarate")   ||
503             !strcmp(key, "audiosamplerate") ||
504             !strcmp(key, "audiosamplesize") ||
505             !strcmp(key, "stereo")          ||
506             !strcmp(key, "audiocodecid")    ||
507             !strcmp(key, "datastream"))
508             return 0;
509
510         if (amf_type == AMF_DATA_TYPE_BOOL) {
511             av_strlcpy(str_val, num_val > 0 ? "true" : "false",
512                        sizeof(str_val));
513             av_dict_set(&s->metadata, key, str_val, 0);
514         } else if (amf_type == AMF_DATA_TYPE_NUMBER) {
515             snprintf(str_val, sizeof(str_val), "%.f", num_val);
516             av_dict_set(&s->metadata, key, str_val, 0);
517         } else if (amf_type == AMF_DATA_TYPE_STRING)
518             av_dict_set(&s->metadata, key, str_val, 0);
519     }
520
521     return 0;
522 }
523
524 static int flv_read_metabody(AVFormatContext *s, int64_t next_pos)
525 {
526     AMFDataType type;
527     AVStream *stream, *astream, *vstream;
528     AVStream av_unused *dstream;
529     AVIOContext *ioc;
530     int i;
531     // only needs to hold the string "onMetaData".
532     // Anything longer is something we don't want.
533     char buffer[11];
534
535     astream = NULL;
536     vstream = NULL;
537     dstream = NULL;
538     ioc     = s->pb;
539
540     // first object needs to be "onMetaData" string
541     type = avio_r8(ioc);
542     if (type != AMF_DATA_TYPE_STRING ||
543         amf_get_string(ioc, buffer, sizeof(buffer)) < 0)
544         return -1;
545
546     if (!strcmp(buffer, "onTextData"))
547         return 1;
548
549     if (strcmp(buffer, "onMetaData"))
550         return -1;
551
552     // find the streams now so that amf_parse_object doesn't need to do
553     // the lookup every time it is called.
554     for (i = 0; i < s->nb_streams; i++) {
555         stream = s->streams[i];
556         if (stream->codec->codec_type == AVMEDIA_TYPE_VIDEO)
557             vstream = stream;
558         else if (stream->codec->codec_type == AVMEDIA_TYPE_AUDIO)
559             astream = stream;
560         else if (stream->codec->codec_type == AVMEDIA_TYPE_DATA)
561             dstream = stream;
562     }
563
564     // parse the second object (we want a mixed array)
565     if (amf_parse_object(s, astream, vstream, buffer, next_pos, 0) < 0)
566         return -1;
567
568     return 0;
569 }
570
571 static int flv_read_header(AVFormatContext *s)
572 {
573     int offset, flags;
574
575     avio_skip(s->pb, 4);
576     flags = avio_r8(s->pb);
577
578     s->ctx_flags |= AVFMTCTX_NOHEADER;
579
580     if (flags & FLV_HEADER_FLAG_HASVIDEO)
581         if (!create_stream(s, AVMEDIA_TYPE_VIDEO))
582             return AVERROR(ENOMEM);
583     if (flags & FLV_HEADER_FLAG_HASAUDIO)
584         if (!create_stream(s, AVMEDIA_TYPE_AUDIO))
585             return AVERROR(ENOMEM);
586     // Flag doesn't indicate whether or not there is script-data present. Must
587     // create that stream if it's encountered.
588
589     offset = avio_rb32(s->pb);
590     avio_seek(s->pb, offset, SEEK_SET);
591     avio_skip(s->pb, 4);
592
593     s->start_time = 0;
594
595     return 0;
596 }
597
598 static int flv_read_close(AVFormatContext *s)
599 {
600     int i;
601     FLVContext *flv = s->priv_data;
602     for (i=0; i<FLV_STREAM_TYPE_NB; i++)
603         av_freep(&flv->new_extradata[i]);
604     return 0;
605 }
606
607 static int flv_get_extradata(AVFormatContext *s, AVStream *st, int size)
608 {
609     av_free(st->codec->extradata);
610     if (ff_get_extradata(st->codec, s->pb, size) < 0)
611         return AVERROR(ENOMEM);
612     return 0;
613 }
614
615 static int flv_queue_extradata(FLVContext *flv, AVIOContext *pb, int stream,
616                                int size)
617 {
618     av_free(flv->new_extradata[stream]);
619     flv->new_extradata[stream] = av_mallocz(size +
620                                             FF_INPUT_BUFFER_PADDING_SIZE);
621     if (!flv->new_extradata[stream])
622         return AVERROR(ENOMEM);
623     flv->new_extradata_size[stream] = size;
624     avio_read(pb, flv->new_extradata[stream], size);
625     return 0;
626 }
627
628 static void clear_index_entries(AVFormatContext *s, int64_t pos)
629 {
630     int i, j, out;
631     av_log(s, AV_LOG_WARNING,
632            "Found invalid index entries, clearing the index.\n");
633     for (i = 0; i < s->nb_streams; i++) {
634         AVStream *st = s->streams[i];
635         /* Remove all index entries that point to >= pos */
636         out = 0;
637         for (j = 0; j < st->nb_index_entries; j++)
638             if (st->index_entries[j].pos < pos)
639                 st->index_entries[out++] = st->index_entries[j];
640         st->nb_index_entries = out;
641     }
642 }
643
644 static int amf_skip_tag(AVIOContext *pb, AMFDataType type)
645 {
646     int nb = -1, ret, parse_name = 1;
647
648     switch (type) {
649     case AMF_DATA_TYPE_NUMBER:
650         avio_skip(pb, 8);
651         break;
652     case AMF_DATA_TYPE_BOOL:
653         avio_skip(pb, 1);
654         break;
655     case AMF_DATA_TYPE_STRING:
656         avio_skip(pb, avio_rb16(pb));
657         break;
658     case AMF_DATA_TYPE_ARRAY:
659         parse_name = 0;
660     case AMF_DATA_TYPE_MIXEDARRAY:
661         nb = avio_rb32(pb);
662     case AMF_DATA_TYPE_OBJECT:
663         while(!pb->eof_reached && (nb-- > 0 || type != AMF_DATA_TYPE_ARRAY)) {
664             if (parse_name) {
665                 int size = avio_rb16(pb);
666                 if (!size) {
667                     avio_skip(pb, 1);
668                     break;
669                 }
670                 avio_skip(pb, size);
671             }
672             if ((ret = amf_skip_tag(pb, avio_r8(pb))) < 0)
673                 return ret;
674         }
675         break;
676     case AMF_DATA_TYPE_NULL:
677     case AMF_DATA_TYPE_OBJECT_END:
678         break;
679     default:
680         return AVERROR_INVALIDDATA;
681     }
682     return 0;
683 }
684
685 static int flv_data_packet(AVFormatContext *s, AVPacket *pkt,
686                            int64_t dts, int64_t next)
687 {
688     AVIOContext *pb = s->pb;
689     AVStream *st    = NULL;
690     char buf[20];
691     int ret = AVERROR_INVALIDDATA;
692     int i, length = -1;
693
694     switch (avio_r8(pb)) {
695     case AMF_DATA_TYPE_MIXEDARRAY:
696         avio_seek(pb, 4, SEEK_CUR);
697     case AMF_DATA_TYPE_OBJECT:
698         break;
699     default:
700         goto skip;
701     }
702
703     while ((ret = amf_get_string(pb, buf, sizeof(buf))) > 0) {
704         AMFDataType type = avio_r8(pb);
705         if (type == AMF_DATA_TYPE_STRING && !strcmp(buf, "text")) {
706             length = avio_rb16(pb);
707             ret    = av_get_packet(pb, pkt, length);
708             if (ret < 0)
709                 goto skip;
710             else
711                 break;
712         } else {
713             if ((ret = amf_skip_tag(pb, type)) < 0)
714                 goto skip;
715         }
716     }
717
718     if (length < 0) {
719         ret = AVERROR_INVALIDDATA;
720         goto skip;
721     }
722
723     for (i = 0; i < s->nb_streams; i++) {
724         st = s->streams[i];
725         if (st->codec->codec_type == AVMEDIA_TYPE_DATA)
726             break;
727     }
728
729     if (i == s->nb_streams) {
730         st = create_stream(s, AVMEDIA_TYPE_DATA);
731         if (!st)
732             return AVERROR_INVALIDDATA;
733         st->codec->codec_id = AV_CODEC_ID_TEXT;
734     }
735
736     pkt->dts  = dts;
737     pkt->pts  = dts;
738     pkt->size = ret;
739
740     pkt->stream_index = st->index;
741     pkt->flags       |= AV_PKT_FLAG_KEY;
742
743 skip:
744     avio_seek(s->pb, next + 4, SEEK_SET);
745
746     return ret;
747 }
748
749 static int flv_read_packet(AVFormatContext *s, AVPacket *pkt)
750 {
751     FLVContext *flv = s->priv_data;
752     int ret, i, type, size, flags;
753     int stream_type=-1;
754     int64_t next, pos, meta_pos;
755     int64_t dts, pts = AV_NOPTS_VALUE;
756     int av_uninit(channels);
757     int av_uninit(sample_rate);
758     AVStream *st    = NULL;
759
760     /* pkt size is repeated at end. skip it */
761     for (;; avio_skip(s->pb, 4)) {
762         pos  = avio_tell(s->pb);
763         type = avio_r8(s->pb);
764         size = avio_rb24(s->pb);
765         dts  = avio_rb24(s->pb);
766         dts |= avio_r8(s->pb) << 24;
767         av_dlog(s, "type:%d, size:%d, dts:%"PRId64" pos:%"PRId64"\n", type, size, dts, avio_tell(s->pb));
768         if (url_feof(s->pb))
769             return AVERROR_EOF;
770         avio_skip(s->pb, 3); /* stream id, always 0 */
771         flags = 0;
772
773         if (flv->validate_next < flv->validate_count) {
774             int64_t validate_pos = flv->validate_index[flv->validate_next].pos;
775             if (pos == validate_pos) {
776                 if (FFABS(dts - flv->validate_index[flv->validate_next].dts) <=
777                     VALIDATE_INDEX_TS_THRESH) {
778                     flv->validate_next++;
779                 } else {
780                     clear_index_entries(s, validate_pos);
781                     flv->validate_count = 0;
782                 }
783             } else if (pos > validate_pos) {
784                 clear_index_entries(s, validate_pos);
785                 flv->validate_count = 0;
786             }
787         }
788
789         if (size == 0)
790             continue;
791
792         next = size + avio_tell(s->pb);
793
794         if (type == FLV_TAG_TYPE_AUDIO) {
795             stream_type = FLV_STREAM_TYPE_AUDIO;
796             flags    = avio_r8(s->pb);
797             size--;
798         } else if (type == FLV_TAG_TYPE_VIDEO) {
799             stream_type = FLV_STREAM_TYPE_VIDEO;
800             flags    = avio_r8(s->pb);
801             size--;
802             if ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_VIDEO_INFO_CMD)
803                 goto skip;
804         } else if (type == FLV_TAG_TYPE_META) {
805             stream_type=FLV_STREAM_TYPE_DATA;
806             if (size > 13 + 1 + 4 && dts == 0) { // Header-type metadata stuff
807                 meta_pos = avio_tell(s->pb);
808                 if (flv_read_metabody(s, next) == 0) {
809                     goto skip;
810                 }
811                 avio_seek(s->pb, meta_pos, SEEK_SET);
812             }
813         } else {
814             av_log(s, AV_LOG_DEBUG,
815                    "Skipping flv packet: type %d, size %d, flags %d.\n",
816                    type, size, flags);
817 skip:
818             avio_seek(s->pb, next, SEEK_SET);
819             continue;
820         }
821
822         /* skip empty data packets */
823         if (!size)
824             continue;
825
826         /* now find stream */
827         for (i = 0; i < s->nb_streams; i++) {
828             st = s->streams[i];
829             if (stream_type == FLV_STREAM_TYPE_AUDIO) {
830                 if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
831                     (s->audio_codec_id || flv_same_audio_codec(st->codec, flags)))
832                     break;
833             } else if (stream_type == FLV_STREAM_TYPE_VIDEO) {
834                 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
835                     (s->video_codec_id || flv_same_video_codec(st->codec, flags)))
836                     break;
837             } else if (stream_type == FLV_STREAM_TYPE_DATA) {
838                 if (st->codec->codec_type == AVMEDIA_TYPE_DATA)
839                     break;
840             }
841         }
842         if (i == s->nb_streams) {
843             static const enum AVMediaType stream_types[] = {AVMEDIA_TYPE_VIDEO, AVMEDIA_TYPE_AUDIO, AVMEDIA_TYPE_DATA};
844             av_log(s, AV_LOG_WARNING, "Stream discovered after head already parsed\n");
845             st = create_stream(s, stream_types[stream_type]);
846             if (!st)
847                 return AVERROR(ENOMEM);
848
849         }
850         av_dlog(s, "%d %X %d \n", stream_type, flags, st->discard);
851         if (  (st->discard >= AVDISCARD_NONKEY && !((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY || (stream_type == FLV_STREAM_TYPE_AUDIO)))
852             ||(st->discard >= AVDISCARD_BIDIR  &&  ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_DISP_INTER && (stream_type == FLV_STREAM_TYPE_VIDEO)))
853             || st->discard >= AVDISCARD_ALL
854         ) {
855             avio_seek(s->pb, next, SEEK_SET);
856             continue;
857         }
858         if ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY || stream_type == FLV_STREAM_TYPE_AUDIO)
859             av_add_index_entry(st, pos, dts, size, 0, AVINDEX_KEYFRAME);
860         break;
861     }
862
863     // if not streamed and no duration from metadata then seek to end to find
864     // the duration from the timestamps
865     if (s->pb->seekable && (!s->duration || s->duration == AV_NOPTS_VALUE) && !flv->searched_for_end) {
866         int size;
867         const int64_t pos   = avio_tell(s->pb);
868         int64_t fsize       = avio_size(s->pb);
869 retry_duration:
870         avio_seek(s->pb, fsize - 4, SEEK_SET);
871         size = avio_rb32(s->pb);
872         avio_seek(s->pb, fsize - 3 - size, SEEK_SET);
873         if (size == avio_rb24(s->pb) + 11) {
874             uint32_t ts = avio_rb24(s->pb);
875             ts         |= avio_r8(s->pb) << 24;
876             if (ts)
877                 s->duration = ts * (int64_t)AV_TIME_BASE / 1000;
878             else if (fsize >= 8 && fsize - 8 >= size) {
879                 fsize -= size+4;
880                 goto retry_duration;
881             }
882         }
883
884         avio_seek(s->pb, pos, SEEK_SET);
885         flv->searched_for_end = 1;
886     }
887
888     if (stream_type == FLV_STREAM_TYPE_AUDIO) {
889         int bits_per_coded_sample;
890         channels = (flags & FLV_AUDIO_CHANNEL_MASK) == FLV_STEREO ? 2 : 1;
891         sample_rate = 44100 << ((flags & FLV_AUDIO_SAMPLERATE_MASK) >>
892                                 FLV_AUDIO_SAMPLERATE_OFFSET) >> 3;
893         bits_per_coded_sample = (flags & FLV_AUDIO_SAMPLESIZE_MASK) ? 16 : 8;
894         if (!st->codec->channels || !st->codec->sample_rate ||
895             !st->codec->bits_per_coded_sample) {
896             st->codec->channels              = channels;
897             st->codec->channel_layout        = channels == 1
898                                                ? AV_CH_LAYOUT_MONO
899                                                : AV_CH_LAYOUT_STEREO;
900             st->codec->sample_rate           = sample_rate;
901             st->codec->bits_per_coded_sample = bits_per_coded_sample;
902         }
903         if (!st->codec->codec_id) {
904             flv_set_audio_codec(s, st, st->codec,
905                                 flags & FLV_AUDIO_CODECID_MASK);
906             flv->last_sample_rate =
907             sample_rate           = st->codec->sample_rate;
908             flv->last_channels    =
909             channels              = st->codec->channels;
910         } else {
911             AVCodecContext ctx = {0};
912             ctx.sample_rate = sample_rate;
913             flv_set_audio_codec(s, st, &ctx, flags & FLV_AUDIO_CODECID_MASK);
914             sample_rate = ctx.sample_rate;
915         }
916     } else if (stream_type == FLV_STREAM_TYPE_VIDEO) {
917         size -= flv_set_video_codec(s, st, flags & FLV_VIDEO_CODECID_MASK, 1);
918     }
919
920     if (st->codec->codec_id == AV_CODEC_ID_AAC ||
921         st->codec->codec_id == AV_CODEC_ID_H264 ||
922         st->codec->codec_id == AV_CODEC_ID_MPEG4) {
923         int type = avio_r8(s->pb);
924         size--;
925         if (st->codec->codec_id == AV_CODEC_ID_H264 || st->codec->codec_id == AV_CODEC_ID_MPEG4) {
926             // sign extension
927             int32_t cts = (avio_rb24(s->pb) + 0xff800000) ^ 0xff800000;
928             pts = dts + cts;
929             if (cts < 0) { // dts might be wrong
930                 if (!flv->wrong_dts)
931                     av_log(s, AV_LOG_WARNING,
932                         "Negative cts, previous timestamps might be wrong.\n");
933                 flv->wrong_dts = 1;
934             } else if (FFABS(dts - pts) > 1000*60*15) {
935                 av_log(s, AV_LOG_WARNING,
936                        "invalid timestamps %"PRId64" %"PRId64"\n", dts, pts);
937                 dts = pts = AV_NOPTS_VALUE;
938             }
939         }
940         if (type == 0 && (!st->codec->extradata || st->codec->codec_id == AV_CODEC_ID_AAC)) {
941             AVDictionaryEntry *t;
942
943             if (st->codec->extradata) {
944                 if ((ret = flv_queue_extradata(flv, s->pb, stream_type, size)) < 0)
945                     return ret;
946                 ret = AVERROR(EAGAIN);
947                 goto leave;
948             }
949             if ((ret = flv_get_extradata(s, st, size)) < 0)
950                 return ret;
951
952             /* Workaround for buggy Omnia A/XE encoder */
953             t = av_dict_get(s->metadata, "Encoder", NULL, 0);
954             if (st->codec->codec_id == AV_CODEC_ID_AAC && t && !strcmp(t->value, "Omnia A/XE"))
955                 st->codec->extradata_size = 2;
956
957             if (st->codec->codec_id == AV_CODEC_ID_AAC && 0) {
958                 MPEG4AudioConfig cfg;
959
960                 if (avpriv_mpeg4audio_get_config(&cfg, st->codec->extradata,
961                                              st->codec->extradata_size * 8, 1) >= 0) {
962                 st->codec->channels       = cfg.channels;
963                 st->codec->channel_layout = 0;
964                 if (cfg.ext_sample_rate)
965                     st->codec->sample_rate = cfg.ext_sample_rate;
966                 else
967                     st->codec->sample_rate = cfg.sample_rate;
968                 av_dlog(s, "mp4a config channels %d sample rate %d\n",
969                         st->codec->channels, st->codec->sample_rate);
970                 }
971             }
972
973             ret = AVERROR(EAGAIN);
974             goto leave;
975         }
976     }
977
978     /* skip empty data packets */
979     if (!size) {
980         ret = AVERROR(EAGAIN);
981         goto leave;
982     }
983
984     ret = av_get_packet(s->pb, pkt, size);
985     if (ret < 0)
986         return ret;
987     pkt->dts          = dts;
988     pkt->pts          = pts == AV_NOPTS_VALUE ? dts : pts;
989     pkt->stream_index = st->index;
990     if (flv->new_extradata[stream_type]) {
991         uint8_t *side = av_packet_new_side_data(pkt, AV_PKT_DATA_NEW_EXTRADATA,
992                                                 flv->new_extradata_size[stream_type]);
993         if (side) {
994             memcpy(side, flv->new_extradata[stream_type],
995                    flv->new_extradata_size[stream_type]);
996             av_freep(&flv->new_extradata[stream_type]);
997             flv->new_extradata_size[stream_type] = 0;
998         }
999     }
1000     if (stream_type == FLV_STREAM_TYPE_AUDIO &&
1001                     (sample_rate != flv->last_sample_rate ||
1002                      channels    != flv->last_channels)) {
1003         flv->last_sample_rate = sample_rate;
1004         flv->last_channels    = channels;
1005         ff_add_param_change(pkt, channels, 0, sample_rate, 0, 0);
1006     }
1007
1008     if (    stream_type == FLV_STREAM_TYPE_AUDIO ||
1009             ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY) ||
1010             stream_type == FLV_STREAM_TYPE_DATA)
1011         pkt->flags |= AV_PKT_FLAG_KEY;
1012
1013 leave:
1014     avio_skip(s->pb, 4);
1015     return ret;
1016 }
1017
1018 static int flv_read_seek(AVFormatContext *s, int stream_index,
1019                          int64_t ts, int flags)
1020 {
1021     FLVContext *flv = s->priv_data;
1022     flv->validate_count = 0;
1023     return avio_seek_time(s->pb, stream_index, ts, flags);
1024 }
1025
1026 #define OFFSET(x) offsetof(FLVContext, x)
1027 #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
1028 static const AVOption options[] = {
1029     { "flv_metadata", "Allocate streams according to the onMetaData array", OFFSET(trust_metadata), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VD },
1030     { NULL }
1031 };
1032
1033 static const AVClass flv_class = {
1034     .class_name = "flvdec",
1035     .item_name  = av_default_item_name,
1036     .option     = options,
1037     .version    = LIBAVUTIL_VERSION_INT,
1038 };
1039
1040 AVInputFormat ff_flv_demuxer = {
1041     .name           = "flv",
1042     .long_name      = NULL_IF_CONFIG_SMALL("FLV (Flash Video)"),
1043     .priv_data_size = sizeof(FLVContext),
1044     .read_probe     = flv_probe,
1045     .read_header    = flv_read_header,
1046     .read_packet    = flv_read_packet,
1047     .read_seek      = flv_read_seek,
1048     .read_close     = flv_read_close,
1049     .extensions     = "flv",
1050     .priv_class     = &flv_class,
1051 };