]> git.sesse.net Git - ffmpeg/blob - libavformat/flvdec.c
lavc: allow decoders to override frame parameters.
[ffmpeg] / libavformat / flvdec.c
1 /*
2  * FLV demuxer
3  * Copyright (c) 2003 The Libav 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 Libav.
11  *
12  * Libav 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  * Libav 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 Libav; 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 KEYFRAMES_TAG            "keyframes"
41 #define KEYFRAMES_TIMESTAMP_TAG  "times"
42 #define KEYFRAMES_BYTEOFFSET_TAG "filepositions"
43
44 #define VALIDATE_INDEX_TS_THRESH 2500
45
46 typedef struct {
47     const AVClass *class; ///< Class for private options.
48     int trust_metadata; ///< configure streams according onMetaData
49     int wrong_dts; ///< wrong dts due to negative cts
50     uint8_t *new_extradata[2];
51     int      new_extradata_size[2];
52     int      last_sample_rate;
53     int      last_channels;
54     struct {
55         int64_t dts;
56         int64_t pos;
57     } validate_index[2];
58     int validate_next;
59     int validate_count;
60 } FLVContext;
61
62 static int flv_probe(AVProbeData *p)
63 {
64     const uint8_t *d;
65
66     d = p->buf;
67     if (d[0] == 'F' && d[1] == 'L' && d[2] == 'V' && d[3] < 5 && d[5]==0 && AV_RB32(d+5)>8) {
68         return AVPROBE_SCORE_MAX;
69     }
70     return 0;
71 }
72
73 static AVStream *create_stream(AVFormatContext *s, int codec_type)
74 {
75     AVStream *st = avformat_new_stream(s, NULL);
76     if (!st)
77         return NULL;
78     st->codec->codec_type = codec_type;
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 ? AV_CODEC_ID_PCM_U8 :
98 #if HAVE_BIGENDIAN
99                             AV_CODEC_ID_PCM_S16BE;
100 #else
101                             AV_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 ? AV_CODEC_ID_PCM_U8 : AV_CODEC_ID_PCM_S16LE;
106         return codec_id == acodec->codec_id;
107     case FLV_CODECID_AAC:
108         return acodec->codec_id == AV_CODEC_ID_AAC;
109     case FLV_CODECID_ADPCM:
110         return acodec->codec_id == AV_CODEC_ID_ADPCM_SWF;
111     case FLV_CODECID_SPEEX:
112         return acodec->codec_id == AV_CODEC_ID_SPEEX;
113     case FLV_CODECID_MP3:
114         return acodec->codec_id == AV_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 == AV_CODEC_ID_NELLYMOSER;
119     case FLV_CODECID_PCM_MULAW:
120         return acodec->sample_rate == 8000 &&
121                acodec->codec_id == AV_CODEC_ID_PCM_MULAW;
122     case FLV_CODECID_PCM_ALAW:
123         return acodec->sample_rate = 8000 &&
124                acodec->codec_id == AV_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 ? AV_CODEC_ID_PCM_U8 :
137 #if HAVE_BIGENDIAN
138                                 AV_CODEC_ID_PCM_S16BE;
139 #else
140                                 AV_CODEC_ID_PCM_S16LE;
141 #endif
142             break;
143         case FLV_CODECID_PCM_LE:
144             acodec->codec_id = acodec->bits_per_coded_sample == 8 ? AV_CODEC_ID_PCM_U8 : AV_CODEC_ID_PCM_S16LE; break;
145         case FLV_CODECID_AAC  : acodec->codec_id = AV_CODEC_ID_AAC;                                    break;
146         case FLV_CODECID_ADPCM: acodec->codec_id = AV_CODEC_ID_ADPCM_SWF;                              break;
147         case FLV_CODECID_SPEEX:
148             acodec->codec_id = AV_CODEC_ID_SPEEX;
149             acodec->sample_rate = 16000;
150             break;
151         case FLV_CODECID_MP3  : acodec->codec_id = AV_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 = AV_CODEC_ID_NELLYMOSER;
155             break;
156         case FLV_CODECID_NELLYMOSER_16KHZ_MONO:
157             acodec->sample_rate = 16000;
158             acodec->codec_id = AV_CODEC_ID_NELLYMOSER;
159             break;
160         case FLV_CODECID_NELLYMOSER:
161             acodec->codec_id = AV_CODEC_ID_NELLYMOSER;
162             break;
163         case FLV_CODECID_PCM_MULAW:
164             acodec->sample_rate = 8000;
165             acodec->codec_id = AV_CODEC_ID_PCM_MULAW;
166             break;
167         case FLV_CODECID_PCM_ALAW:
168             acodec->sample_rate = 8000;
169             acodec->codec_id = AV_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 == AV_CODEC_ID_FLV1;
187         case FLV_CODECID_SCREEN:
188             return vcodec->codec_id == AV_CODEC_ID_FLASHSV;
189         case FLV_CODECID_SCREEN2:
190             return vcodec->codec_id == AV_CODEC_ID_FLASHSV2;
191         case FLV_CODECID_VP6:
192             return vcodec->codec_id == AV_CODEC_ID_VP6F;
193         case FLV_CODECID_VP6A:
194             return vcodec->codec_id == AV_CODEC_ID_VP6A;
195         case FLV_CODECID_H264:
196             return vcodec->codec_id == AV_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, int read) {
205     AVCodecContext *vcodec = vstream->codec;
206     switch(flv_codecid) {
207         case FLV_CODECID_H263  : vcodec->codec_id = AV_CODEC_ID_FLV1   ; break;
208         case FLV_CODECID_SCREEN: vcodec->codec_id = AV_CODEC_ID_FLASHSV; break;
209         case FLV_CODECID_SCREEN2: vcodec->codec_id = AV_CODEC_ID_FLASHSV2; break;
210         case FLV_CODECID_VP6   : vcodec->codec_id = AV_CODEC_ID_VP6F   ;
211         case FLV_CODECID_VP6A  :
212             if(flv_codecid == FLV_CODECID_VP6A)
213                 vcodec->codec_id = AV_CODEC_ID_VP6A;
214             if (read) {
215                 if (vcodec->extradata_size != 1) {
216                     vcodec->extradata = av_malloc(1);
217                     if (vcodec->extradata)
218                         vcodec->extradata_size = 1;
219                 }
220                 if (vcodec->extradata)
221                     vcodec->extradata[0] = avio_r8(s->pb);
222                 else
223                     avio_skip(s->pb, 1);
224             }
225             return 1; // 1 byte body size adjustment for flv_read_packet()
226         case FLV_CODECID_H264:
227             vcodec->codec_id = AV_CODEC_ID_H264;
228             return 3; // not 4, reading packet type will consume one byte
229         default:
230             av_log(s, AV_LOG_INFO, "Unsupported video codec (%x)\n", flv_codecid);
231             vcodec->codec_tag = flv_codecid;
232     }
233
234     return 0;
235 }
236
237 static int amf_get_string(AVIOContext *ioc, char *buffer, int buffsize) {
238     int length = avio_rb16(ioc);
239     if(length >= buffsize) {
240         avio_skip(ioc, length);
241         return -1;
242     }
243
244     avio_read(ioc, buffer, length);
245
246     buffer[length] = '\0';
247
248     return length;
249 }
250
251 static int parse_keyframes_index(AVFormatContext *s, AVIOContext *ioc, AVStream *vstream, int64_t max_pos) {
252     FLVContext *flv = s->priv_data;
253     unsigned int arraylen = 0, timeslen = 0, fileposlen = 0, i;
254     double num_val;
255     char str_val[256];
256     int64_t *times = NULL;
257     int64_t *filepositions = NULL;
258     int ret = AVERROR(ENOSYS);
259     int64_t initial_pos = avio_tell(ioc);
260
261     if (s->flags & AVFMT_FLAG_IGNIDX)
262         return 0;
263
264     while (avio_tell(ioc) < max_pos - 2 && amf_get_string(ioc, str_val, sizeof(str_val)) > 0) {
265         int64_t* current_array;
266
267         // Expect array object in context
268         if (avio_r8(ioc) != AMF_DATA_TYPE_ARRAY)
269             break;
270
271         arraylen = avio_rb32(ioc);
272         if (arraylen >> 28)
273             break;
274
275         /*
276          * Expect only 'times' or 'filepositions' sub-arrays in other case refuse to use such metadata
277          * for indexing
278          */
279         if (!strcmp(KEYFRAMES_TIMESTAMP_TAG, str_val) && !times) {
280             if (!(times = av_mallocz(sizeof(*times) * arraylen))) {
281                 ret = AVERROR(ENOMEM);
282                 goto finish;
283             }
284             timeslen = arraylen;
285             current_array = times;
286         } else if (!strcmp(KEYFRAMES_BYTEOFFSET_TAG, str_val) && !filepositions) {
287             if (!(filepositions = av_mallocz(sizeof(*filepositions) * arraylen))) {
288                 ret = AVERROR(ENOMEM);
289                 goto finish;
290             }
291             fileposlen = arraylen;
292             current_array = filepositions;
293         } else // unexpected metatag inside keyframes, will not use such metadata for indexing
294             break;
295
296         for (i = 0; i < arraylen && avio_tell(ioc) < max_pos - 1; i++) {
297             if (avio_r8(ioc) != AMF_DATA_TYPE_NUMBER)
298                 goto finish;
299             num_val = av_int2double(avio_rb64(ioc));
300             current_array[i] = num_val;
301         }
302         if (times && filepositions) {
303             // All done, exiting at a position allowing amf_parse_object
304             // to finish parsing the object
305             ret = 0;
306             break;
307         }
308     }
309
310     if (!ret && timeslen == fileposlen) {
311         for (i = 0; i < fileposlen; i++) {
312             av_add_index_entry(vstream, filepositions[i], times[i]*1000,
313                                0, 0, AVINDEX_KEYFRAME);
314             if (i < 2) {
315                 flv->validate_index[i].pos = filepositions[i];
316                 flv->validate_index[i].dts = times[i] * 1000;
317                 flv->validate_count = i + 1;
318             }
319         }
320     } else
321         av_log(s, AV_LOG_WARNING, "Invalid keyframes object, skipping.\n");
322
323 finish:
324     av_freep(&times);
325     av_freep(&filepositions);
326     // If we got unexpected data, but successfully reset back to
327     // the start pos, the caller can continue parsing
328     if (ret < 0 && avio_seek(ioc, initial_pos, SEEK_SET) > 0)
329         return 0;
330     return ret;
331 }
332
333 static int amf_parse_object(AVFormatContext *s, AVStream *astream, AVStream *vstream, const char *key, int64_t max_pos, int depth) {
334     AVCodecContext *acodec, *vcodec;
335     FLVContext *flv = s->priv_data;
336     AVIOContext *ioc;
337     AMFDataType amf_type;
338     char str_val[256];
339     double num_val;
340
341     num_val = 0;
342     ioc = s->pb;
343
344     amf_type = avio_r8(ioc);
345
346     switch(amf_type) {
347         case AMF_DATA_TYPE_NUMBER:
348             num_val = av_int2double(avio_rb64(ioc)); break;
349         case AMF_DATA_TYPE_BOOL:
350             num_val = avio_r8(ioc); break;
351         case AMF_DATA_TYPE_STRING:
352             if(amf_get_string(ioc, str_val, sizeof(str_val)) < 0)
353                 return -1;
354             break;
355         case AMF_DATA_TYPE_OBJECT:
356             if ((vstream || astream) && key && !strcmp(KEYFRAMES_TAG, key) && depth == 1)
357                 if (parse_keyframes_index(s, ioc, vstream ? vstream : astream,
358                                           max_pos) < 0)
359                     return -1;
360
361             while (avio_tell(ioc) < max_pos - 2 && amf_get_string(ioc, str_val, sizeof(str_val)) > 0) {
362                 if (amf_parse_object(s, astream, vstream, str_val, max_pos, depth + 1) < 0)
363                     return -1; //if we couldn't skip, bomb out.
364             }
365             if(avio_r8(ioc) != AMF_END_OF_OBJECT)
366                 return -1;
367             break;
368         case AMF_DATA_TYPE_NULL:
369         case AMF_DATA_TYPE_UNDEFINED:
370         case AMF_DATA_TYPE_UNSUPPORTED:
371             break; //these take up no additional space
372         case AMF_DATA_TYPE_MIXEDARRAY:
373             avio_skip(ioc, 4); //skip 32-bit max array index
374             while(avio_tell(ioc) < max_pos - 2 && amf_get_string(ioc, str_val, sizeof(str_val)) > 0) {
375                 //this is the only case in which we would want a nested parse to not skip over the object
376                 if(amf_parse_object(s, astream, vstream, str_val, max_pos, depth + 1) < 0)
377                     return -1;
378             }
379             if(avio_r8(ioc) != AMF_END_OF_OBJECT)
380                 return -1;
381             break;
382         case AMF_DATA_TYPE_ARRAY: {
383             unsigned int arraylen, i;
384
385             arraylen = avio_rb32(ioc);
386             for(i = 0; i < arraylen && avio_tell(ioc) < max_pos - 1; i++) {
387                 if(amf_parse_object(s, NULL, NULL, NULL, max_pos, depth + 1) < 0)
388                     return -1; //if we couldn't skip, bomb out.
389             }
390         }
391             break;
392         case AMF_DATA_TYPE_DATE:
393             avio_skip(ioc, 8 + 2); //timestamp (double) and UTC offset (int16)
394             break;
395         default: //unsupported type, we couldn't skip
396             return -1;
397     }
398
399     if(depth == 1 && key) { //only look for metadata values when we are not nested and key != NULL
400         acodec = astream ? astream->codec : NULL;
401         vcodec = vstream ? vstream->codec : NULL;
402
403         if (amf_type == AMF_DATA_TYPE_NUMBER) {
404             if (!strcmp(key, "duration"))
405                 s->duration = num_val * AV_TIME_BASE;
406             else if (!strcmp(key, "videodatarate") && vcodec && 0 <= (int)(num_val * 1024.0))
407                 vcodec->bit_rate = num_val * 1024.0;
408             else if (!strcmp(key, "audiodatarate") && acodec && 0 <= (int)(num_val * 1024.0))
409                 acodec->bit_rate = num_val * 1024.0;
410             else if (!strcmp(key, "datastream")) {
411                 AVStream *st = create_stream(s, AVMEDIA_TYPE_DATA);
412                 if (!st)
413                     return AVERROR(ENOMEM);
414                 st->codec->codec_id = AV_CODEC_ID_TEXT;
415             } else if (flv->trust_metadata) {
416                 if (!strcmp(key, "videocodecid") && vcodec) {
417                     flv_set_video_codec(s, vstream, num_val, 0);
418                 } else
419                 if (!strcmp(key, "audiocodecid") && acodec) {
420                     flv_set_audio_codec(s, astream, acodec, num_val);
421                 } else
422                 if (!strcmp(key, "audiosamplerate") && acodec) {
423                     acodec->sample_rate = num_val;
424                 } else
425                 if (!strcmp(key, "width") && vcodec) {
426                     vcodec->width = num_val;
427                 } else
428                 if (!strcmp(key, "height") && vcodec) {
429                     vcodec->height = num_val;
430                 }
431             }
432         }
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;
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     astream = NULL;
469     vstream = NULL;
470     ioc = s->pb;
471
472     //first object needs to be "onMetaData" string
473     type = avio_r8(ioc);
474     if (type != AMF_DATA_TYPE_STRING ||
475         amf_get_string(ioc, buffer, sizeof(buffer)) < 0)
476         return -1;
477
478     if (!strcmp(buffer, "onTextData"))
479         return 1;
480
481     if (strcmp(buffer, "onMetaData"))
482         return -1;
483
484     //find the streams now so that amf_parse_object doesn't need to do the lookup every time it is called.
485     for(i = 0; i < s->nb_streams; i++) {
486         stream = s->streams[i];
487         if     (stream->codec->codec_type == AVMEDIA_TYPE_AUDIO) astream = stream;
488         else if(stream->codec->codec_type == AVMEDIA_TYPE_VIDEO) vstream = 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
511     s->ctx_flags |= AVFMTCTX_NOHEADER;
512
513     if(flags & FLV_HEADER_FLAG_HASVIDEO){
514         if(!create_stream(s, AVMEDIA_TYPE_VIDEO))
515             return AVERROR(ENOMEM);
516     }
517     if(flags & FLV_HEADER_FLAG_HASAUDIO){
518         if(!create_stream(s, AVMEDIA_TYPE_AUDIO))
519             return AVERROR(ENOMEM);
520     }
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     FLVContext *flv = s->priv_data;
534     av_freep(&flv->new_extradata[0]);
535     av_freep(&flv->new_extradata[1]);
536     return 0;
537 }
538
539 static int flv_get_extradata(AVFormatContext *s, AVStream *st, int size)
540 {
541     av_free(st->codec->extradata);
542     st->codec->extradata = av_mallocz(size + FF_INPUT_BUFFER_PADDING_SIZE);
543     if (!st->codec->extradata)
544         return AVERROR(ENOMEM);
545     st->codec->extradata_size = size;
546     avio_read(s->pb, st->codec->extradata, st->codec->extradata_size);
547     return 0;
548 }
549
550 static int flv_queue_extradata(FLVContext *flv, AVIOContext *pb, int stream,
551                                int size)
552 {
553     av_free(flv->new_extradata[stream]);
554     flv->new_extradata[stream] = av_mallocz(size + FF_INPUT_BUFFER_PADDING_SIZE);
555     if (!flv->new_extradata[stream])
556         return AVERROR(ENOMEM);
557     flv->new_extradata_size[stream] = size;
558     avio_read(pb, flv->new_extradata[stream], size);
559     return 0;
560 }
561
562 static void clear_index_entries(AVFormatContext *s, int64_t pos)
563 {
564     int i, j, out;
565     av_log(s, AV_LOG_WARNING, "Found invalid index entries, clearing the index.\n");
566     for (i = 0; i < s->nb_streams; i++) {
567         AVStream *st = s->streams[i];
568         /* Remove all index entries that point to >= pos */
569         out = 0;
570         for (j = 0; j < st->nb_index_entries; j++) {
571             if (st->index_entries[j].pos < pos)
572                 st->index_entries[out++] = st->index_entries[j];
573         }
574         st->nb_index_entries = out;
575     }
576 }
577
578
579 static int flv_data_packet(AVFormatContext *s, AVPacket *pkt,
580                            int64_t dts, int64_t next)
581 {
582     int ret = AVERROR_INVALIDDATA, i;
583     AVIOContext *pb = s->pb;
584     AVStream *st = NULL;
585     AMFDataType type;
586     char buf[20];
587     int length;
588
589     type = avio_r8(pb);
590     if (type == AMF_DATA_TYPE_MIXEDARRAY)
591         avio_seek(pb, 4, SEEK_CUR);
592     else if (type != AMF_DATA_TYPE_OBJECT)
593         goto out;
594
595     amf_get_string(pb, buf, sizeof(buf));
596     if (strcmp(buf, "type") || avio_r8(pb) != AMF_DATA_TYPE_STRING)
597         goto out;
598
599     amf_get_string(pb, buf, sizeof(buf));
600     //FIXME parse it as codec_id
601     amf_get_string(pb, buf, sizeof(buf));
602     if (strcmp(buf, "text") || avio_r8(pb) != AMF_DATA_TYPE_STRING)
603         goto out;
604
605     length = avio_rb16(pb);
606     ret = av_get_packet(s->pb, pkt, length);
607     if (ret < 0) {
608         ret = AVERROR(EIO);
609         goto out;
610     }
611
612     for (i = 0; i < s->nb_streams; i++) {
613         st = s->streams[i];
614         if (st->codec->codec_type == AVMEDIA_TYPE_DATA)
615             break;
616     }
617
618     if (i == s->nb_streams) {
619         st = create_stream(s, AVMEDIA_TYPE_DATA);
620         if (!st)
621             goto out;
622         st->codec->codec_id = AV_CODEC_ID_TEXT;
623     }
624
625     pkt->dts  = dts;
626     pkt->pts  = dts;
627     pkt->size = ret;
628
629     pkt->stream_index = st->index;
630     pkt->flags |= AV_PKT_FLAG_KEY;
631
632     avio_seek(s->pb, next + 4, SEEK_SET);
633 out:
634     return ret;
635 }
636
637 static int flv_read_packet(AVFormatContext *s, AVPacket *pkt)
638 {
639     FLVContext *flv = s->priv_data;
640     int ret, i, type, size, flags, is_audio;
641     int64_t next, pos;
642     int64_t dts, pts = AV_NOPTS_VALUE;
643     int sample_rate = 0, channels = 0;
644     AVStream *st = NULL;
645
646  for(;;avio_skip(s->pb, 4)){ /* pkt size is repeated at end. skip it */
647     pos = avio_tell(s->pb);
648     type = avio_r8(s->pb);
649     size = avio_rb24(s->pb);
650     dts = avio_rb24(s->pb);
651     dts |= avio_r8(s->pb) << 24;
652     av_dlog(s, "type:%d, size:%d, dts:%"PRId64"\n", type, size, dts);
653     if (s->pb->eof_reached)
654         return AVERROR_EOF;
655     avio_skip(s->pb, 3); /* stream id, always 0 */
656     flags = 0;
657
658     if (flv->validate_next < flv->validate_count) {
659         int64_t validate_pos = flv->validate_index[flv->validate_next].pos;
660         if (pos == validate_pos) {
661             if (FFABS(dts - flv->validate_index[flv->validate_next].dts) <=
662                 VALIDATE_INDEX_TS_THRESH) {
663                 flv->validate_next++;
664             } else {
665                 clear_index_entries(s, validate_pos);
666                 flv->validate_count = 0;
667             }
668         } else if (pos > validate_pos) {
669             clear_index_entries(s, validate_pos);
670             flv->validate_count = 0;
671         }
672     }
673
674     if(size == 0)
675         continue;
676
677     next= size + avio_tell(s->pb);
678
679     if (type == FLV_TAG_TYPE_AUDIO) {
680         is_audio=1;
681         flags = avio_r8(s->pb);
682         size--;
683     } else if (type == FLV_TAG_TYPE_VIDEO) {
684         is_audio=0;
685         flags = avio_r8(s->pb);
686         size--;
687         if ((flags & 0xf0) == 0x50) /* video info / command frame */
688             goto skip;
689     } else {
690         if (type == FLV_TAG_TYPE_META && size > 13+1+4)
691             if (flv_read_metabody(s, next) > 0) {
692                 return flv_data_packet(s, pkt, dts, next);
693             }
694         else /* skip packet */
695             av_log(s, AV_LOG_DEBUG, "skipping flv packet: type %d, size %d, flags %d\n", type, size, flags);
696     skip:
697         avio_seek(s->pb, next, SEEK_SET);
698         continue;
699     }
700
701     /* skip empty data packets */
702     if (!size)
703         continue;
704
705     /* now find stream */
706     for(i=0;i<s->nb_streams;i++) {
707         st = s->streams[i];
708         if (is_audio && st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
709             if (flv_same_audio_codec(st->codec, flags)) {
710                 break;
711             }
712         } else
713         if (!is_audio && st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
714             if (flv_same_video_codec(st->codec, flags)) {
715                 break;
716             }
717         }
718     }
719     if(i == s->nb_streams){
720         st = create_stream(s,
721             is_audio ? AVMEDIA_TYPE_AUDIO : AVMEDIA_TYPE_VIDEO);
722     }
723     av_dlog(s, "%d %X %d \n", is_audio, flags, st->discard);
724     if(  (st->discard >= AVDISCARD_NONKEY && !((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY ||         is_audio))
725        ||(st->discard >= AVDISCARD_BIDIR  &&  ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_DISP_INTER && !is_audio))
726        || st->discard >= AVDISCARD_ALL
727        ){
728         avio_seek(s->pb, next, SEEK_SET);
729         continue;
730     }
731     if ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY)
732         av_add_index_entry(st, pos, dts, size, 0, AVINDEX_KEYFRAME);
733     break;
734  }
735
736     // if not streamed and no duration from metadata then seek to end to find the duration from the timestamps
737     if(s->pb->seekable && (!s->duration || s->duration==AV_NOPTS_VALUE)){
738         int size;
739         const int64_t pos= avio_tell(s->pb);
740         const int64_t fsize= avio_size(s->pb);
741         avio_seek(s->pb, fsize-4, SEEK_SET);
742         size= avio_rb32(s->pb);
743         avio_seek(s->pb, fsize-3-size, SEEK_SET);
744         if(size == avio_rb24(s->pb) + 11){
745             uint32_t ts = avio_rb24(s->pb);
746             ts |= avio_r8(s->pb) << 24;
747             s->duration = ts * (int64_t)AV_TIME_BASE / 1000;
748         }
749         avio_seek(s->pb, pos, SEEK_SET);
750     }
751
752     if(is_audio){
753         int bits_per_coded_sample;
754         channels    = (flags & FLV_AUDIO_CHANNEL_MASK) == FLV_STEREO ? 2 : 1;
755         sample_rate = (44100 << ((flags & FLV_AUDIO_SAMPLERATE_MASK) >> FLV_AUDIO_SAMPLERATE_OFFSET) >> 3);
756         bits_per_coded_sample = (flags & FLV_AUDIO_SAMPLESIZE_MASK) ? 16 : 8;
757         if(!st->codec->channels || !st->codec->sample_rate || !st->codec->bits_per_coded_sample) {
758             st->codec->channels              = channels;
759             st->codec->channel_layout        = channels == 1 ? AV_CH_LAYOUT_MONO :
760                                                                AV_CH_LAYOUT_STEREO;
761             st->codec->sample_rate           = sample_rate;
762             st->codec->bits_per_coded_sample = bits_per_coded_sample;
763         }
764         if(!st->codec->codec_id){
765             flv_set_audio_codec(s, st, st->codec, flags & FLV_AUDIO_CODECID_MASK);
766             flv->last_sample_rate = sample_rate = st->codec->sample_rate;
767             flv->last_channels    = channels    = st->codec->channels;
768         } else {
769             AVCodecContext ctx;
770             ctx.sample_rate = sample_rate;
771             flv_set_audio_codec(s, st, &ctx, flags & FLV_AUDIO_CODECID_MASK);
772             sample_rate = ctx.sample_rate;
773         }
774     }else{
775         size -= flv_set_video_codec(s, st, flags & FLV_VIDEO_CODECID_MASK, 1);
776     }
777
778     if (st->codec->codec_id == AV_CODEC_ID_AAC ||
779         st->codec->codec_id == AV_CODEC_ID_H264) {
780         int type = avio_r8(s->pb);
781         size--;
782         if (st->codec->codec_id == AV_CODEC_ID_H264) {
783             int32_t cts = (avio_rb24(s->pb)+0xff800000)^0xff800000; // sign extension
784             pts = dts + cts;
785             if (cts < 0) { // dts are wrong
786                 flv->wrong_dts = 1;
787                 av_log(s, AV_LOG_WARNING, "negative cts, previous timestamps might be wrong\n");
788             }
789             if (flv->wrong_dts)
790                 dts = AV_NOPTS_VALUE;
791         }
792         if (type == 0) {
793             if (st->codec->extradata) {
794                 if ((ret = flv_queue_extradata(flv, s->pb, is_audio, size)) < 0)
795                     return ret;
796                 ret = AVERROR(EAGAIN);
797                 goto leave;
798             }
799             if ((ret = flv_get_extradata(s, st, size)) < 0)
800                 return ret;
801             if (st->codec->codec_id == AV_CODEC_ID_AAC) {
802                 MPEG4AudioConfig cfg;
803                 avpriv_mpeg4audio_get_config(&cfg, st->codec->extradata,
804                                              st->codec->extradata_size * 8, 1);
805                 st->codec->channels = cfg.channels;
806                 st->codec->channel_layout = 0;
807                 if (cfg.ext_sample_rate)
808                     st->codec->sample_rate = cfg.ext_sample_rate;
809                 else
810                     st->codec->sample_rate = cfg.sample_rate;
811                 av_dlog(s, "mp4a config channels %d sample rate %d\n",
812                         st->codec->channels, st->codec->sample_rate);
813             }
814
815             ret = AVERROR(EAGAIN);
816             goto leave;
817         }
818     }
819
820     /* skip empty data packets */
821     if (!size) {
822         ret = AVERROR(EAGAIN);
823         goto leave;
824     }
825
826     ret= av_get_packet(s->pb, pkt, size);
827     if (ret < 0) {
828         return AVERROR(EIO);
829     }
830     /* note: we need to modify the packet size here to handle the last
831        packet */
832     pkt->size = ret;
833     pkt->dts = dts;
834     pkt->pts = pts == AV_NOPTS_VALUE ? dts : pts;
835     pkt->stream_index = st->index;
836     if (flv->new_extradata[is_audio]) {
837         uint8_t *side = av_packet_new_side_data(pkt, AV_PKT_DATA_NEW_EXTRADATA,
838                                                 flv->new_extradata_size[is_audio]);
839         if (side) {
840             memcpy(side, flv->new_extradata[is_audio],
841                    flv->new_extradata_size[is_audio]);
842             av_freep(&flv->new_extradata[is_audio]);
843             flv->new_extradata_size[is_audio] = 0;
844         }
845     }
846     if (is_audio && (sample_rate != flv->last_sample_rate ||
847                      channels != flv->last_channels)) {
848         flv->last_sample_rate = sample_rate;
849         flv->last_channels    = channels;
850         ff_add_param_change(pkt, channels, 0, sample_rate, 0, 0);
851     }
852
853     if (is_audio || ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY))
854         pkt->flags |= AV_PKT_FLAG_KEY;
855
856 leave:
857     avio_skip(s->pb, 4);
858     return ret;
859 }
860
861 static int flv_read_seek(AVFormatContext *s, int stream_index,
862     int64_t ts, int flags)
863 {
864     FLVContext *flv = s->priv_data;
865     flv->validate_count = 0;
866     return avio_seek_time(s->pb, stream_index, ts, flags);
867 }
868
869 #define OFFSET(x) offsetof(FLVContext, x)
870 #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
871 static const AVOption options[] = {
872     { "flv_metadata", "Allocate streams according the onMetaData array",      OFFSET(trust_metadata), AV_OPT_TYPE_INT,    { .i64 = 0 }, 0, 1, VD},
873     { NULL }
874 };
875
876 static const AVClass class = {
877     .class_name = "flvdec",
878     .item_name  = av_default_item_name,
879     .option     = options,
880     .version    = LIBAVUTIL_VERSION_INT,
881 };
882
883 AVInputFormat ff_flv_demuxer = {
884     .name           = "flv",
885     .long_name      = NULL_IF_CONFIG_SMALL("FLV (Flash Video)"),
886     .priv_data_size = sizeof(FLVContext),
887     .read_probe     = flv_probe,
888     .read_header    = flv_read_header,
889     .read_packet    = flv_read_packet,
890     .read_seek      = flv_read_seek,
891     .read_close     = flv_read_close,
892     .extensions     = "flv",
893     .priv_class     = &class,
894 };