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