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