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