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