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