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