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