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