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