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