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