]> git.sesse.net Git - ffmpeg/blob - libavformat/flvdec.c
flvdec: Fix mistakenly discarding metadata at dts==0
[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 || amf_type == AMF_DATA_TYPE_BOOL) {
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                     int id = ((int)num_val) << FLV_AUDIO_CODECID_OFFSET;
419                     flv_set_audio_codec(s, astream, acodec, id);
420                 } else
421                 if (!strcmp(key, "audiosamplerate") && acodec) {
422                     acodec->sample_rate = num_val;
423                 } else if (!strcmp(key, "audiosamplesize") && acodec) {
424                     acodec->bits_per_coded_sample = num_val;
425                 } else if (!strcmp(key, "stereo") && acodec) {
426                     acodec->channels = num_val + 1;
427                     acodec->channel_layout = acodec->channels == 2 ?
428                                              AV_CH_LAYOUT_STEREO :
429                                              AV_CH_LAYOUT_MONO;
430                 } else
431                 if (!strcmp(key, "width") && vcodec) {
432                     vcodec->width = num_val;
433                 } else
434                 if (!strcmp(key, "height") && vcodec) {
435                     vcodec->height = num_val;
436                 }
437             }
438         }
439
440         if (amf_type == AMF_DATA_TYPE_OBJECT && s->nb_streams == 1 &&
441            ((!acodec && !strcmp(key, "audiocodecid")) ||
442             (!vcodec && !strcmp(key, "videocodecid"))))
443                 s->ctx_flags &= ~AVFMTCTX_NOHEADER; //If there is either audio/video missing, codecid will be an empty object
444
445         if (!strcmp(key, "duration")        ||
446             !strcmp(key, "filesize")        ||
447             !strcmp(key, "width")           ||
448             !strcmp(key, "height")          ||
449             !strcmp(key, "videodatarate")   ||
450             !strcmp(key, "framerate")       ||
451             !strcmp(key, "videocodecid")    ||
452             !strcmp(key, "audiodatarate")   ||
453             !strcmp(key, "audiosamplerate") ||
454             !strcmp(key, "audiosamplesize") ||
455             !strcmp(key, "stereo")          ||
456             !strcmp(key, "audiocodecid"))
457             return 0;
458
459         if(amf_type == AMF_DATA_TYPE_BOOL) {
460             av_strlcpy(str_val, num_val > 0 ? "true" : "false", sizeof(str_val));
461             av_dict_set(&s->metadata, key, str_val, 0);
462         } else if(amf_type == AMF_DATA_TYPE_NUMBER) {
463             snprintf(str_val, sizeof(str_val), "%.f", num_val);
464             av_dict_set(&s->metadata, key, str_val, 0);
465         } else if (amf_type == AMF_DATA_TYPE_STRING)
466             av_dict_set(&s->metadata, key, str_val, 0);
467     }
468
469     return 0;
470 }
471
472 static int flv_read_metabody(AVFormatContext *s, int64_t next_pos) {
473     AMFDataType type;
474     AVStream *stream, *astream, *vstream, *dstream;
475     AVIOContext *ioc;
476     int i;
477     char buffer[11]; //only needs to hold the string "onMetaData". Anything longer is something we don't want.
478
479     vstream = astream = dstream = NULL;
480     ioc = s->pb;
481
482     //first object needs to be "onMetaData" string
483     type = avio_r8(ioc);
484     if (type != AMF_DATA_TYPE_STRING ||
485         amf_get_string(ioc, buffer, sizeof(buffer)) < 0)
486         return -1;
487
488     if (!strcmp(buffer, "onTextData"))
489         return 1;
490
491     if (strcmp(buffer, "onMetaData"))
492         return -1;
493
494     //find the streams now so that amf_parse_object doesn't need to do the lookup every time it is called.
495     for(i = 0; i < s->nb_streams; i++) {
496         stream = s->streams[i];
497         if(stream->codec->codec_type == AVMEDIA_TYPE_VIDEO) vstream = stream;
498         else if(stream->codec->codec_type == AVMEDIA_TYPE_AUDIO) astream = stream;
499         else if(stream->codec->codec_type == AVMEDIA_TYPE_DATA) dstream = stream;
500     }
501
502     //parse the second object (we want a mixed array)
503     if(amf_parse_object(s, astream, vstream, buffer, next_pos, 0) < 0)
504         return -1;
505
506     return 0;
507 }
508
509 static int flv_read_header(AVFormatContext *s)
510 {
511     int offset, flags;
512
513     avio_skip(s->pb, 4);
514     flags = avio_r8(s->pb);
515     /* old flvtool cleared this field */
516     /* FIXME: better fix needed */
517     if (!flags) {
518         flags = FLV_HEADER_FLAG_HASVIDEO | FLV_HEADER_FLAG_HASAUDIO;
519         av_log(s, AV_LOG_WARNING, "Broken FLV file, which says no streams present, this might fail\n");
520     }
521
522     s->ctx_flags |= AVFMTCTX_NOHEADER;
523
524     if(flags & FLV_HEADER_FLAG_HASVIDEO){
525         if(!create_stream(s, AVMEDIA_TYPE_VIDEO))
526             return AVERROR(ENOMEM);
527     }
528     if(flags & FLV_HEADER_FLAG_HASAUDIO){
529         if(!create_stream(s, AVMEDIA_TYPE_AUDIO))
530             return AVERROR(ENOMEM);
531     }
532     // Flag doesn't indicate whether or not there is script-data present. Must
533     // create that stream if it's encountered.
534
535     offset = avio_rb32(s->pb);
536     avio_seek(s->pb, offset, SEEK_SET);
537     avio_skip(s->pb, 4);
538
539     s->start_time = 0;
540
541     return 0;
542 }
543
544 static int flv_read_close(AVFormatContext *s)
545 {
546     int i;
547     FLVContext *flv = s->priv_data;
548     for(i=0; i<FLV_STREAM_TYPE_NB; i++)
549         av_freep(&flv->new_extradata[i]);
550     return 0;
551 }
552
553 static int flv_get_extradata(AVFormatContext *s, AVStream *st, int size)
554 {
555     av_free(st->codec->extradata);
556     st->codec->extradata = av_mallocz(size + FF_INPUT_BUFFER_PADDING_SIZE);
557     if (!st->codec->extradata)
558         return AVERROR(ENOMEM);
559     st->codec->extradata_size = size;
560     avio_read(s->pb, st->codec->extradata, st->codec->extradata_size);
561     return 0;
562 }
563
564 static int flv_queue_extradata(FLVContext *flv, AVIOContext *pb, int stream,
565                                int size)
566 {
567     av_free(flv->new_extradata[stream]);
568     flv->new_extradata[stream] = av_mallocz(size + FF_INPUT_BUFFER_PADDING_SIZE);
569     if (!flv->new_extradata[stream])
570         return AVERROR(ENOMEM);
571     flv->new_extradata_size[stream] = size;
572     avio_read(pb, flv->new_extradata[stream], size);
573     return 0;
574 }
575
576 static void clear_index_entries(AVFormatContext *s, int64_t pos)
577 {
578     int i, j, out;
579     av_log(s, AV_LOG_WARNING, "Found invalid index entries, clearing the index.\n");
580     for (i = 0; i < s->nb_streams; i++) {
581         AVStream *st = s->streams[i];
582         /* Remove all index entries that point to >= pos */
583         out = 0;
584         for (j = 0; j < st->nb_index_entries; j++) {
585             if (st->index_entries[j].pos < pos)
586                 st->index_entries[out++] = st->index_entries[j];
587         }
588         st->nb_index_entries = out;
589     }
590 }
591
592
593 static int flv_data_packet(AVFormatContext *s, AVPacket *pkt,
594                            int64_t dts, int64_t next)
595 {
596     int ret = AVERROR_INVALIDDATA, i;
597     AVIOContext *pb = s->pb;
598     AVStream *st = NULL;
599     AMFDataType type;
600     char buf[20];
601     int length;
602
603     type = avio_r8(pb);
604     if (type == AMF_DATA_TYPE_MIXEDARRAY)
605         avio_seek(pb, 4, SEEK_CUR);
606     else if (type != AMF_DATA_TYPE_OBJECT)
607         goto out;
608
609     amf_get_string(pb, buf, sizeof(buf));
610     if (strcmp(buf, "type") || avio_r8(pb) != AMF_DATA_TYPE_STRING)
611         goto out;
612
613     amf_get_string(pb, buf, sizeof(buf));
614     //FIXME parse it as codec_id
615     amf_get_string(pb, buf, sizeof(buf));
616     if (strcmp(buf, "text") || avio_r8(pb) != AMF_DATA_TYPE_STRING)
617         goto out;
618
619     length = avio_rb16(pb);
620     ret = av_get_packet(s->pb, pkt, length);
621     if (ret < 0) {
622         ret = AVERROR(EIO);
623         goto out;
624     }
625
626     for (i = 0; i < s->nb_streams; i++) {
627         st = s->streams[i];
628         if (st->codec->codec_type == AVMEDIA_TYPE_DATA)
629             break;
630     }
631
632     if (i == s->nb_streams) {
633         st = create_stream(s, AVMEDIA_TYPE_DATA);
634         if (!st)
635             goto out;
636         st->codec->codec_id = AV_CODEC_ID_TEXT;
637     }
638
639     pkt->dts  = dts;
640     pkt->pts  = dts;
641     pkt->size = ret;
642
643     pkt->stream_index = st->index;
644     pkt->flags |= AV_PKT_FLAG_KEY;
645
646     avio_seek(s->pb, next + 4, SEEK_SET);
647 out:
648     return ret;
649 }
650
651 static int flv_read_packet(AVFormatContext *s, AVPacket *pkt)
652 {
653     FLVContext *flv = s->priv_data;
654     int ret, i, type, size, flags;
655     int stream_type=-1;
656     int64_t next, pos, meta_pos;
657     int64_t dts, pts = AV_NOPTS_VALUE;
658     int av_uninit(channels);
659     int av_uninit(sample_rate);
660     AVStream *st = NULL;
661
662  for(;;avio_skip(s->pb, 4)){ /* pkt size is repeated at end. skip it */
663     pos = avio_tell(s->pb);
664     type = avio_r8(s->pb);
665     size = avio_rb24(s->pb);
666     dts = avio_rb24(s->pb);
667     dts |= avio_r8(s->pb) << 24;
668     av_dlog(s, "type:%d, size:%d, dts:%"PRId64"\n", type, size, dts);
669     if (url_feof(s->pb))
670         return AVERROR_EOF;
671     avio_skip(s->pb, 3); /* stream id, always 0 */
672     flags = 0;
673
674     if (flv->validate_next < flv->validate_count) {
675         int64_t validate_pos = flv->validate_index[flv->validate_next].pos;
676         if (pos == validate_pos) {
677             if (FFABS(dts - flv->validate_index[flv->validate_next].dts) <=
678                 VALIDATE_INDEX_TS_THRESH) {
679                 flv->validate_next++;
680             } else {
681                 clear_index_entries(s, validate_pos);
682                 flv->validate_count = 0;
683             }
684         } else if (pos > validate_pos) {
685             clear_index_entries(s, validate_pos);
686             flv->validate_count = 0;
687         }
688     }
689
690     if(size == 0)
691         continue;
692
693     next= size + avio_tell(s->pb);
694
695     if (type == FLV_TAG_TYPE_AUDIO) {
696         stream_type=FLV_STREAM_TYPE_AUDIO;
697         flags = avio_r8(s->pb);
698         size--;
699     } else if (type == FLV_TAG_TYPE_VIDEO) {
700         stream_type=FLV_STREAM_TYPE_VIDEO;
701         flags = avio_r8(s->pb);
702         size--;
703         if ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_VIDEO_INFO_CMD)
704             goto skip;
705     } else if (type == FLV_TAG_TYPE_META) {
706         stream_type=FLV_STREAM_TYPE_DATA;
707         if (size > 13+1+4 && dts == 0) { // Header-type metadata stuff
708             meta_pos = avio_tell(s->pb);
709             if (flv_read_metabody(s, next) == 0){
710                 goto skip;
711             }
712             avio_seek(s->pb, meta_pos, SEEK_SET);
713         }
714     } else {
715         av_log(s, AV_LOG_DEBUG, "skipping flv packet: type %d, size %d, flags %d\n", type, size, flags);
716     skip:
717         avio_seek(s->pb, next, SEEK_SET);
718         continue;
719     }
720
721     /* skip empty data packets */
722     if (!size)
723         continue;
724
725     /* now find stream */
726     for(i=0;i<s->nb_streams;i++) {
727         st = s->streams[i];
728         if (stream_type == FLV_STREAM_TYPE_AUDIO) {
729             if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
730                 (s->audio_codec_id || flv_same_audio_codec(st->codec, flags))) {
731                 break;
732             }
733         } else
734         if (stream_type == FLV_STREAM_TYPE_VIDEO) {
735             if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
736                 (s->video_codec_id || flv_same_video_codec(st->codec, flags))) {
737                 break;
738             }
739         } else if (stream_type == FLV_STREAM_TYPE_DATA) {
740             if (st->codec->codec_type == AVMEDIA_TYPE_DATA)
741                 break;
742         }
743     }
744     if(i == s->nb_streams){
745         static const enum AVMediaType stream_types[] = {AVMEDIA_TYPE_VIDEO, AVMEDIA_TYPE_AUDIO, AVMEDIA_TYPE_DATA};
746         av_log(s, AV_LOG_WARNING, "Stream discovered after head already parsed\n");
747         st = create_stream(s,
748                            stream_types[stream_type]);
749         if (!st)
750             return AVERROR(ENOMEM);
751
752     }
753     av_dlog(s, "%d %X %d \n", stream_type, flags, st->discard);
754     if(  (st->discard >= AVDISCARD_NONKEY && !((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY || (stream_type == FLV_STREAM_TYPE_AUDIO)))
755        ||(st->discard >= AVDISCARD_BIDIR  &&  ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_DISP_INTER && (stream_type == FLV_STREAM_TYPE_VIDEO)))
756        || st->discard >= AVDISCARD_ALL
757        ){
758         avio_seek(s->pb, next, SEEK_SET);
759         continue;
760     }
761     if ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY || stream_type == FLV_STREAM_TYPE_AUDIO)
762         av_add_index_entry(st, pos, dts, size, 0, AVINDEX_KEYFRAME);
763     break;
764  }
765
766     // if not streamed and no duration from metadata then seek to end to find the duration from the timestamps
767     if(s->pb->seekable && (!s->duration || s->duration==AV_NOPTS_VALUE) && !flv->searched_for_end){
768         int size;
769         const int64_t pos= avio_tell(s->pb);
770         int64_t fsize= avio_size(s->pb);
771 retry_duration:
772         avio_seek(s->pb, fsize-4, SEEK_SET);
773         size= avio_rb32(s->pb);
774         avio_seek(s->pb, fsize-3-size, SEEK_SET);
775         if(size == avio_rb24(s->pb) + 11){
776             uint32_t ts = avio_rb24(s->pb);
777             ts |= avio_r8(s->pb) << 24;
778             if(ts)
779                 s->duration = ts * (int64_t)AV_TIME_BASE / 1000;
780             else if (fsize >= 8 && fsize - 8 >= size){
781                 fsize -= size+4;
782                 goto retry_duration;
783             }
784         }
785
786         avio_seek(s->pb, pos, SEEK_SET);
787         flv->searched_for_end = 1;
788     }
789
790     if(stream_type == FLV_STREAM_TYPE_AUDIO){
791         int bits_per_coded_sample;
792         channels    = (flags & FLV_AUDIO_CHANNEL_MASK) == FLV_STEREO ? 2 : 1;
793         sample_rate = (44100 << ((flags & FLV_AUDIO_SAMPLERATE_MASK) >> FLV_AUDIO_SAMPLERATE_OFFSET) >> 3);
794         bits_per_coded_sample = (flags & FLV_AUDIO_SAMPLESIZE_MASK) ? 16 : 8;
795         if(!st->codec->channels || !st->codec->sample_rate || !st->codec->bits_per_coded_sample) {
796             st->codec->channels              = channels;
797             st->codec->channel_layout        = channels == 1 ? AV_CH_LAYOUT_MONO :
798                                                                AV_CH_LAYOUT_STEREO;
799             st->codec->sample_rate           = sample_rate;
800             st->codec->bits_per_coded_sample = bits_per_coded_sample;
801         }
802         if(!st->codec->codec_id){
803             flv_set_audio_codec(s, st, st->codec, flags & FLV_AUDIO_CODECID_MASK);
804             flv->last_sample_rate = sample_rate = st->codec->sample_rate;
805             flv->last_channels    = channels    = st->codec->channels;
806         } else {
807             AVCodecContext ctx;
808             ctx.sample_rate = sample_rate;
809             flv_set_audio_codec(s, st, &ctx, flags & FLV_AUDIO_CODECID_MASK);
810             sample_rate = ctx.sample_rate;
811         }
812     } else if(stream_type == FLV_STREAM_TYPE_VIDEO) {
813         size -= flv_set_video_codec(s, st, flags & FLV_VIDEO_CODECID_MASK, 1);
814     }
815
816     if (st->codec->codec_id == AV_CODEC_ID_AAC ||
817         st->codec->codec_id == AV_CODEC_ID_H264 ||
818         st->codec->codec_id == AV_CODEC_ID_MPEG4) {
819         int type = avio_r8(s->pb);
820         size--;
821         if (st->codec->codec_id == AV_CODEC_ID_H264 || st->codec->codec_id == AV_CODEC_ID_MPEG4) {
822             int32_t cts = (avio_rb24(s->pb)+0xff800000)^0xff800000; // sign extension
823             pts = dts + cts;
824             if (cts < 0) { // dts are wrong
825                 flv->wrong_dts = 1;
826                 av_log(s, AV_LOG_WARNING, "negative cts, previous timestamps might be wrong\n");
827             }
828             if (flv->wrong_dts)
829                 dts = AV_NOPTS_VALUE;
830         }
831         if (type == 0 && (!st->codec->extradata || st->codec->codec_id == AV_CODEC_ID_AAC)) {
832             if (st->codec->extradata) {
833                 if ((ret = flv_queue_extradata(flv, s->pb, stream_type, size)) < 0)
834                     return ret;
835                 ret = AVERROR(EAGAIN);
836                 goto leave;
837             }
838             if ((ret = flv_get_extradata(s, st, size)) < 0)
839                 return ret;
840             if (st->codec->codec_id == AV_CODEC_ID_AAC && 0) {
841                 MPEG4AudioConfig cfg;
842                 if (avpriv_mpeg4audio_get_config(&cfg, st->codec->extradata,
843                                              st->codec->extradata_size * 8, 1) >= 0) {
844                 st->codec->channels = cfg.channels;
845                 st->codec->channel_layout = 0;
846                 if (cfg.ext_sample_rate)
847                     st->codec->sample_rate = cfg.ext_sample_rate;
848                 else
849                     st->codec->sample_rate = cfg.sample_rate;
850                 av_dlog(s, "mp4a config channels %d sample rate %d\n",
851                         st->codec->channels, st->codec->sample_rate);
852                 }
853             }
854
855             ret = AVERROR(EAGAIN);
856             goto leave;
857         }
858     }
859
860     /* skip empty data packets */
861     if (!size) {
862         ret = AVERROR(EAGAIN);
863         goto leave;
864     }
865
866     ret= av_get_packet(s->pb, pkt, size);
867     if (ret < 0)
868         return ret;
869     pkt->dts = dts;
870     pkt->pts = pts == AV_NOPTS_VALUE ? dts : pts;
871     pkt->stream_index = st->index;
872     if (flv->new_extradata[stream_type]) {
873         uint8_t *side = av_packet_new_side_data(pkt, AV_PKT_DATA_NEW_EXTRADATA,
874                                                 flv->new_extradata_size[stream_type]);
875         if (side) {
876             memcpy(side, flv->new_extradata[stream_type],
877                    flv->new_extradata_size[stream_type]);
878             av_freep(&flv->new_extradata[stream_type]);
879             flv->new_extradata_size[stream_type] = 0;
880         }
881     }
882     if (stream_type == FLV_STREAM_TYPE_AUDIO && (sample_rate != flv->last_sample_rate ||
883                      channels != flv->last_channels)) {
884         flv->last_sample_rate = sample_rate;
885         flv->last_channels    = channels;
886         ff_add_param_change(pkt, channels, 0, sample_rate, 0, 0);
887     }
888
889     if (    stream_type == FLV_STREAM_TYPE_AUDIO ||
890             ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY) ||
891             stream_type == FLV_STREAM_TYPE_DATA)
892         pkt->flags |= AV_PKT_FLAG_KEY;
893
894 leave:
895     avio_skip(s->pb, 4);
896     return ret;
897 }
898
899 static int flv_read_seek(AVFormatContext *s, int stream_index,
900     int64_t ts, int flags)
901 {
902     FLVContext *flv = s->priv_data;
903     flv->validate_count = 0;
904     return avio_seek_time(s->pb, stream_index, ts, flags);
905 }
906
907 #define OFFSET(x) offsetof(FLVContext, x)
908 #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
909 static const AVOption options[] = {
910     { "flv_metadata", "Allocate streams according the onMetaData array",      OFFSET(trust_metadata), AV_OPT_TYPE_INT,    { .i64 = 0 }, 0, 1, VD},
911     { NULL }
912 };
913
914 static const AVClass class = {
915     .class_name = "flvdec",
916     .item_name  = av_default_item_name,
917     .option     = options,
918     .version    = LIBAVUTIL_VERSION_INT,
919 };
920
921 AVInputFormat ff_flv_demuxer = {
922     .name           = "flv",
923     .long_name      = NULL_IF_CONFIG_SMALL("FLV (Flash Video)"),
924     .priv_data_size = sizeof(FLVContext),
925     .read_probe     = flv_probe,
926     .read_header    = flv_read_header,
927     .read_packet    = flv_read_packet,
928     .read_seek      = flv_read_seek,
929     .read_close     = flv_read_close,
930     .extensions     = "flv",
931     .priv_class     = &class,
932 };