3 * Copyright (c) 2003 The FFmpeg Project
5 * This demuxer will generate a 1 byte extradata for VP6F content.
7 * - upper 4bits: difference between encoded width and visible width
8 * - lower 4bits: difference between encoded height and visible height
10 * This file is part of FFmpeg.
12 * FFmpeg 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.
17 * FFmpeg 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.
22 * You should have received a copy of the GNU Lesser General Public
23 * License along with FFmpeg; if not, write to the Free Software
24 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
27 #include "libavutil/avstring.h"
28 #include "libavutil/channel_layout.h"
29 #include "libavutil/dict.h"
30 #include "libavutil/opt.h"
31 #include "libavutil/intfloat.h"
32 #include "libavutil/mathematics.h"
33 #include "libavcodec/bytestream.h"
34 #include "libavcodec/mpeg4audio.h"
37 #include "avio_internal.h"
40 #define VALIDATE_INDEX_TS_THRESH 2500
42 #define RESYNC_BUFFER_SIZE (1<<20)
44 typedef struct FLVContext {
45 const AVClass *class; ///< Class for private options.
46 int trust_metadata; ///< configure streams according onMetaData
47 int wrong_dts; ///< wrong dts due to negative cts
48 uint8_t *new_extradata[FLV_STREAM_TYPE_NB];
49 int new_extradata_size[FLV_STREAM_TYPE_NB];
60 uint8_t resync_buffer[2*RESYNC_BUFFER_SIZE];
66 static int probe(AVProbeData *p, int live)
68 const uint8_t *d = p->buf;
69 unsigned offset = AV_RB32(d + 5);
74 d[3] < 5 && d[5] == 0 &&
75 offset + 100 < p->buf_size &&
77 int is_live = !memcmp(d + offset + 40, "NGINX RTMP", 10);
80 return AVPROBE_SCORE_MAX;
85 static int flv_probe(AVProbeData *p)
90 static int live_flv_probe(AVProbeData *p)
95 static AVStream *create_stream(AVFormatContext *s, int codec_type)
97 AVStream *st = avformat_new_stream(s, NULL);
100 st->codec->codec_type = codec_type;
101 if (s->nb_streams>=3 ||( s->nb_streams==2
102 && s->streams[0]->codec->codec_type != AVMEDIA_TYPE_SUBTITLE
103 && s->streams[1]->codec->codec_type != AVMEDIA_TYPE_SUBTITLE))
104 s->ctx_flags &= ~AVFMTCTX_NOHEADER;
106 avpriv_set_pts_info(st, 32, 1, 1000); /* 32 bit pts in ms */
110 static int flv_same_audio_codec(AVCodecContext *acodec, int flags)
112 int bits_per_coded_sample = (flags & FLV_AUDIO_SAMPLESIZE_MASK) ? 16 : 8;
113 int flv_codecid = flags & FLV_AUDIO_CODECID_MASK;
116 if (!acodec->codec_id && !acodec->codec_tag)
119 if (acodec->bits_per_coded_sample != bits_per_coded_sample)
122 switch (flv_codecid) {
123 // no distinction between S16 and S8 PCM codec flags
124 case FLV_CODECID_PCM:
125 codec_id = bits_per_coded_sample == 8
128 : AV_CODEC_ID_PCM_S16BE;
130 : AV_CODEC_ID_PCM_S16LE;
132 return codec_id == acodec->codec_id;
133 case FLV_CODECID_PCM_LE:
134 codec_id = bits_per_coded_sample == 8
136 : AV_CODEC_ID_PCM_S16LE;
137 return codec_id == acodec->codec_id;
138 case FLV_CODECID_AAC:
139 return acodec->codec_id == AV_CODEC_ID_AAC;
140 case FLV_CODECID_ADPCM:
141 return acodec->codec_id == AV_CODEC_ID_ADPCM_SWF;
142 case FLV_CODECID_SPEEX:
143 return acodec->codec_id == AV_CODEC_ID_SPEEX;
144 case FLV_CODECID_MP3:
145 return acodec->codec_id == AV_CODEC_ID_MP3;
146 case FLV_CODECID_NELLYMOSER_8KHZ_MONO:
147 case FLV_CODECID_NELLYMOSER_16KHZ_MONO:
148 case FLV_CODECID_NELLYMOSER:
149 return acodec->codec_id == AV_CODEC_ID_NELLYMOSER;
150 case FLV_CODECID_PCM_MULAW:
151 return acodec->sample_rate == 8000 &&
152 acodec->codec_id == AV_CODEC_ID_PCM_MULAW;
153 case FLV_CODECID_PCM_ALAW:
154 return acodec->sample_rate == 8000 &&
155 acodec->codec_id == AV_CODEC_ID_PCM_ALAW;
157 return acodec->codec_tag == (flv_codecid >> FLV_AUDIO_CODECID_OFFSET);
161 static void flv_set_audio_codec(AVFormatContext *s, AVStream *astream,
162 AVCodecContext *acodec, int flv_codecid)
164 switch (flv_codecid) {
165 // no distinction between S16 and S8 PCM codec flags
166 case FLV_CODECID_PCM:
167 acodec->codec_id = acodec->bits_per_coded_sample == 8
170 : AV_CODEC_ID_PCM_S16BE;
172 : AV_CODEC_ID_PCM_S16LE;
175 case FLV_CODECID_PCM_LE:
176 acodec->codec_id = acodec->bits_per_coded_sample == 8
178 : AV_CODEC_ID_PCM_S16LE;
180 case FLV_CODECID_AAC:
181 acodec->codec_id = AV_CODEC_ID_AAC;
183 case FLV_CODECID_ADPCM:
184 acodec->codec_id = AV_CODEC_ID_ADPCM_SWF;
186 case FLV_CODECID_SPEEX:
187 acodec->codec_id = AV_CODEC_ID_SPEEX;
188 acodec->sample_rate = 16000;
190 case FLV_CODECID_MP3:
191 acodec->codec_id = AV_CODEC_ID_MP3;
192 astream->need_parsing = AVSTREAM_PARSE_FULL;
194 case FLV_CODECID_NELLYMOSER_8KHZ_MONO:
195 // in case metadata does not otherwise declare samplerate
196 acodec->sample_rate = 8000;
197 acodec->codec_id = AV_CODEC_ID_NELLYMOSER;
199 case FLV_CODECID_NELLYMOSER_16KHZ_MONO:
200 acodec->sample_rate = 16000;
201 acodec->codec_id = AV_CODEC_ID_NELLYMOSER;
203 case FLV_CODECID_NELLYMOSER:
204 acodec->codec_id = AV_CODEC_ID_NELLYMOSER;
206 case FLV_CODECID_PCM_MULAW:
207 acodec->sample_rate = 8000;
208 acodec->codec_id = AV_CODEC_ID_PCM_MULAW;
210 case FLV_CODECID_PCM_ALAW:
211 acodec->sample_rate = 8000;
212 acodec->codec_id = AV_CODEC_ID_PCM_ALAW;
215 avpriv_request_sample(s, "Audio codec (%x)",
216 flv_codecid >> FLV_AUDIO_CODECID_OFFSET);
217 acodec->codec_tag = flv_codecid >> FLV_AUDIO_CODECID_OFFSET;
221 static int flv_same_video_codec(AVCodecContext *vcodec, int flags)
223 int flv_codecid = flags & FLV_VIDEO_CODECID_MASK;
225 if (!vcodec->codec_id && !vcodec->codec_tag)
228 switch (flv_codecid) {
229 case FLV_CODECID_H263:
230 return vcodec->codec_id == AV_CODEC_ID_FLV1;
231 case FLV_CODECID_SCREEN:
232 return vcodec->codec_id == AV_CODEC_ID_FLASHSV;
233 case FLV_CODECID_SCREEN2:
234 return vcodec->codec_id == AV_CODEC_ID_FLASHSV2;
235 case FLV_CODECID_VP6:
236 return vcodec->codec_id == AV_CODEC_ID_VP6F;
237 case FLV_CODECID_VP6A:
238 return vcodec->codec_id == AV_CODEC_ID_VP6A;
239 case FLV_CODECID_H264:
240 return vcodec->codec_id == AV_CODEC_ID_H264;
242 return vcodec->codec_tag == flv_codecid;
246 static int flv_set_video_codec(AVFormatContext *s, AVStream *vstream,
247 int flv_codecid, int read)
249 AVCodecContext *vcodec = vstream->codec;
250 switch (flv_codecid) {
251 case FLV_CODECID_H263:
252 vcodec->codec_id = AV_CODEC_ID_FLV1;
254 case FLV_CODECID_REALH263:
255 vcodec->codec_id = AV_CODEC_ID_H263;
256 break; // Really mean it this time
257 case FLV_CODECID_SCREEN:
258 vcodec->codec_id = AV_CODEC_ID_FLASHSV;
260 case FLV_CODECID_SCREEN2:
261 vcodec->codec_id = AV_CODEC_ID_FLASHSV2;
263 case FLV_CODECID_VP6:
264 vcodec->codec_id = AV_CODEC_ID_VP6F;
265 case FLV_CODECID_VP6A:
266 if (flv_codecid == FLV_CODECID_VP6A)
267 vcodec->codec_id = AV_CODEC_ID_VP6A;
269 if (vcodec->extradata_size != 1) {
270 ff_alloc_extradata(vcodec, 1);
272 if (vcodec->extradata)
273 vcodec->extradata[0] = avio_r8(s->pb);
277 return 1; // 1 byte body size adjustment for flv_read_packet()
278 case FLV_CODECID_H264:
279 vcodec->codec_id = AV_CODEC_ID_H264;
280 vstream->need_parsing = AVSTREAM_PARSE_HEADERS;
281 return 3; // not 4, reading packet type will consume one byte
282 case FLV_CODECID_MPEG4:
283 vcodec->codec_id = AV_CODEC_ID_MPEG4;
286 avpriv_request_sample(s, "Video codec (%x)", flv_codecid);
287 vcodec->codec_tag = flv_codecid;
293 static int amf_get_string(AVIOContext *ioc, char *buffer, int buffsize)
295 int length = avio_rb16(ioc);
296 if (length >= buffsize) {
297 avio_skip(ioc, length);
301 avio_read(ioc, buffer, length);
303 buffer[length] = '\0';
308 static int parse_keyframes_index(AVFormatContext *s, AVIOContext *ioc,
309 AVStream *vstream, int64_t max_pos)
311 FLVContext *flv = s->priv_data;
312 unsigned int timeslen = 0, fileposlen = 0, i;
314 int64_t *times = NULL;
315 int64_t *filepositions = NULL;
316 int ret = AVERROR(ENOSYS);
317 int64_t initial_pos = avio_tell(ioc);
319 if (vstream->nb_index_entries>0) {
320 av_log(s, AV_LOG_WARNING, "Skipping duplicate index\n");
324 if (s->flags & AVFMT_FLAG_IGNIDX)
327 while (avio_tell(ioc) < max_pos - 2 &&
328 amf_get_string(ioc, str_val, sizeof(str_val)) > 0) {
329 int64_t **current_array;
330 unsigned int arraylen;
332 // Expect array object in context
333 if (avio_r8(ioc) != AMF_DATA_TYPE_ARRAY)
336 arraylen = avio_rb32(ioc);
340 if (!strcmp(KEYFRAMES_TIMESTAMP_TAG , str_val) && !times) {
341 current_array = ×
343 } else if (!strcmp(KEYFRAMES_BYTEOFFSET_TAG, str_val) &&
345 current_array = &filepositions;
346 fileposlen = arraylen;
348 // unexpected metatag inside keyframes, will not use such
349 // metadata for indexing
352 if (!(*current_array = av_mallocz(sizeof(**current_array) * arraylen))) {
353 ret = AVERROR(ENOMEM);
357 for (i = 0; i < arraylen && avio_tell(ioc) < max_pos - 1; i++) {
358 if (avio_r8(ioc) != AMF_DATA_TYPE_NUMBER)
360 current_array[0][i] = av_int2double(avio_rb64(ioc));
362 if (times && filepositions) {
363 // All done, exiting at a position allowing amf_parse_object
364 // to finish parsing the object
370 if (timeslen == fileposlen && fileposlen>1 && max_pos <= filepositions[0]) {
371 for (i = 0; i < fileposlen; i++) {
372 av_add_index_entry(vstream, filepositions[i], times[i] * 1000,
373 0, 0, AVINDEX_KEYFRAME);
375 flv->validate_index[i].pos = filepositions[i];
376 flv->validate_index[i].dts = times[i] * 1000;
377 flv->validate_count = i + 1;
382 av_log(s, AV_LOG_WARNING, "Invalid keyframes object, skipping.\n");
387 av_freep(&filepositions);
388 avio_seek(ioc, initial_pos, SEEK_SET);
392 static int amf_parse_object(AVFormatContext *s, AVStream *astream,
393 AVStream *vstream, const char *key,
394 int64_t max_pos, int depth)
396 AVCodecContext *acodec, *vcodec;
397 FLVContext *flv = s->priv_data;
399 AMFDataType amf_type;
405 amf_type = avio_r8(ioc);
408 case AMF_DATA_TYPE_NUMBER:
409 num_val = av_int2double(avio_rb64(ioc));
411 case AMF_DATA_TYPE_BOOL:
412 num_val = avio_r8(ioc);
414 case AMF_DATA_TYPE_STRING:
415 if (amf_get_string(ioc, str_val, sizeof(str_val)) < 0) {
416 av_log(s, AV_LOG_ERROR, "AMF_DATA_TYPE_STRING parsing failed\n");
420 case AMF_DATA_TYPE_OBJECT:
421 if ((vstream || astream) && key &&
423 !strcmp(KEYFRAMES_TAG, key) && depth == 1)
424 if (parse_keyframes_index(s, ioc, vstream ? vstream : astream,
426 av_log(s, AV_LOG_ERROR, "Keyframe index parsing failed\n");
428 while (avio_tell(ioc) < max_pos - 2 &&
429 amf_get_string(ioc, str_val, sizeof(str_val)) > 0)
430 if (amf_parse_object(s, astream, vstream, str_val, max_pos,
432 return -1; // if we couldn't skip, bomb out.
433 if (avio_r8(ioc) != AMF_END_OF_OBJECT) {
434 av_log(s, AV_LOG_ERROR, "Missing AMF_END_OF_OBJECT in AMF_DATA_TYPE_OBJECT\n");
438 case AMF_DATA_TYPE_NULL:
439 case AMF_DATA_TYPE_UNDEFINED:
440 case AMF_DATA_TYPE_UNSUPPORTED:
441 break; // these take up no additional space
442 case AMF_DATA_TYPE_MIXEDARRAY:
445 avio_skip(ioc, 4); // skip 32-bit max array index
446 while (avio_tell(ioc) < max_pos - 2 &&
447 amf_get_string(ioc, str_val, sizeof(str_val)) > 0)
448 // this is the only case in which we would want a nested
449 // parse to not skip over the object
450 if (amf_parse_object(s, astream, vstream, str_val, max_pos,
454 if (v != AMF_END_OF_OBJECT) {
455 av_log(s, AV_LOG_ERROR, "Missing AMF_END_OF_OBJECT in AMF_DATA_TYPE_MIXEDARRAY, found %d\n", v);
460 case AMF_DATA_TYPE_ARRAY:
462 unsigned int arraylen, i;
464 arraylen = avio_rb32(ioc);
465 for (i = 0; i < arraylen && avio_tell(ioc) < max_pos - 1; i++)
466 if (amf_parse_object(s, NULL, NULL, NULL, max_pos,
468 return -1; // if we couldn't skip, bomb out.
471 case AMF_DATA_TYPE_DATE:
472 avio_skip(ioc, 8 + 2); // timestamp (double) and UTC offset (int16)
474 default: // unsupported type, we couldn't skip
475 av_log(s, AV_LOG_ERROR, "unsupported amf type %d\n", amf_type);
480 acodec = astream ? astream->codec : NULL;
481 vcodec = vstream ? vstream->codec : NULL;
483 // stream info doesn't live any deeper than the first object
485 if (amf_type == AMF_DATA_TYPE_NUMBER ||
486 amf_type == AMF_DATA_TYPE_BOOL) {
487 if (!strcmp(key, "duration"))
488 s->duration = num_val * AV_TIME_BASE;
489 else if (!strcmp(key, "videodatarate") && vcodec &&
490 0 <= (int)(num_val * 1024.0))
491 vcodec->bit_rate = num_val * 1024.0;
492 else if (!strcmp(key, "audiodatarate") && acodec &&
493 0 <= (int)(num_val * 1024.0))
494 acodec->bit_rate = num_val * 1024.0;
495 else if (!strcmp(key, "datastream")) {
496 AVStream *st = create_stream(s, AVMEDIA_TYPE_SUBTITLE);
498 return AVERROR(ENOMEM);
499 st->codec->codec_id = AV_CODEC_ID_TEXT;
500 } else if (flv->trust_metadata) {
501 if (!strcmp(key, "videocodecid") && vcodec) {
502 flv_set_video_codec(s, vstream, num_val, 0);
503 } else if (!strcmp(key, "audiocodecid") && acodec) {
504 int id = ((int)num_val) << FLV_AUDIO_CODECID_OFFSET;
505 flv_set_audio_codec(s, astream, acodec, id);
506 } else if (!strcmp(key, "audiosamplerate") && acodec) {
507 acodec->sample_rate = num_val;
508 } else if (!strcmp(key, "audiosamplesize") && acodec) {
509 acodec->bits_per_coded_sample = num_val;
510 } else if (!strcmp(key, "stereo") && acodec) {
511 acodec->channels = num_val + 1;
512 acodec->channel_layout = acodec->channels == 2 ?
513 AV_CH_LAYOUT_STEREO :
515 } else if (!strcmp(key, "width") && vcodec) {
516 vcodec->width = num_val;
517 } else if (!strcmp(key, "height") && vcodec) {
518 vcodec->height = num_val;
522 if (amf_type == AMF_DATA_TYPE_STRING) {
523 if (!strcmp(key, "encoder")) {
525 if (1 == sscanf(str_val, "Open Broadcaster Software v0.%d", &version)) {
526 if (version > 0 && version <= 655)
527 flv->broken_sizes = 1;
529 } else if (!strcmp(key, "metadatacreator") && !strcmp(str_val, "MEGA")) {
530 flv->broken_sizes = 1;
535 if (amf_type == AMF_DATA_TYPE_OBJECT && s->nb_streams == 1 &&
536 ((!acodec && !strcmp(key, "audiocodecid")) ||
537 (!vcodec && !strcmp(key, "videocodecid"))))
538 s->ctx_flags &= ~AVFMTCTX_NOHEADER; //If there is either audio/video missing, codecid will be an empty object
540 if (!strcmp(key, "duration") ||
541 !strcmp(key, "filesize") ||
542 !strcmp(key, "width") ||
543 !strcmp(key, "height") ||
544 !strcmp(key, "videodatarate") ||
545 !strcmp(key, "framerate") ||
546 !strcmp(key, "videocodecid") ||
547 !strcmp(key, "audiodatarate") ||
548 !strcmp(key, "audiosamplerate") ||
549 !strcmp(key, "audiosamplesize") ||
550 !strcmp(key, "stereo") ||
551 !strcmp(key, "audiocodecid") ||
552 !strcmp(key, "datastream"))
555 s->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
556 if (amf_type == AMF_DATA_TYPE_BOOL) {
557 av_strlcpy(str_val, num_val > 0 ? "true" : "false",
559 av_dict_set(&s->metadata, key, str_val, 0);
560 } else if (amf_type == AMF_DATA_TYPE_NUMBER) {
561 snprintf(str_val, sizeof(str_val), "%.f", num_val);
562 av_dict_set(&s->metadata, key, str_val, 0);
563 } else if (amf_type == AMF_DATA_TYPE_STRING)
564 av_dict_set(&s->metadata, key, str_val, 0);
570 #define TYPE_ONTEXTDATA 1
571 #define TYPE_ONCAPTION 2
572 #define TYPE_ONCAPTIONINFO 3
573 #define TYPE_UNKNOWN 9
575 static int flv_read_metabody(AVFormatContext *s, int64_t next_pos)
578 AVStream *stream, *astream, *vstream;
579 AVStream av_unused *dstream;
582 // only needs to hold the string "onMetaData".
583 // Anything longer is something we don't want.
591 // first object needs to be "onMetaData" string
593 if (type != AMF_DATA_TYPE_STRING ||
594 amf_get_string(ioc, buffer, sizeof(buffer)) < 0)
597 if (!strcmp(buffer, "onTextData"))
598 return TYPE_ONTEXTDATA;
600 if (!strcmp(buffer, "onCaption"))
601 return TYPE_ONCAPTION;
603 if (!strcmp(buffer, "onCaptionInfo"))
604 return TYPE_ONCAPTIONINFO;
606 if (strcmp(buffer, "onMetaData") && strcmp(buffer, "onCuePoint")) {
607 av_log(s, AV_LOG_DEBUG, "Unknown type %s\n", buffer);
611 // find the streams now so that amf_parse_object doesn't need to do
612 // the lookup every time it is called.
613 for (i = 0; i < s->nb_streams; i++) {
614 stream = s->streams[i];
615 if (stream->codec->codec_type == AVMEDIA_TYPE_VIDEO)
617 else if (stream->codec->codec_type == AVMEDIA_TYPE_AUDIO)
619 else if (stream->codec->codec_type == AVMEDIA_TYPE_SUBTITLE)
623 // parse the second object (we want a mixed array)
624 if (amf_parse_object(s, astream, vstream, buffer, next_pos, 0) < 0)
630 static int flv_read_header(AVFormatContext *s)
633 FLVContext *flv = s->priv_data;
636 flags = avio_r8(s->pb);
638 s->ctx_flags |= AVFMTCTX_NOHEADER;
640 if (flags & FLV_HEADER_FLAG_HASVIDEO)
641 if (!create_stream(s, AVMEDIA_TYPE_VIDEO))
642 return AVERROR(ENOMEM);
643 if (flags & FLV_HEADER_FLAG_HASAUDIO)
644 if (!create_stream(s, AVMEDIA_TYPE_AUDIO))
645 return AVERROR(ENOMEM);
646 // Flag doesn't indicate whether or not there is script-data present. Must
647 // create that stream if it's encountered.
649 offset = avio_rb32(s->pb);
650 avio_seek(s->pb, offset, SEEK_SET);
654 flv->sum_flv_tag_size = 0;
659 static int flv_read_close(AVFormatContext *s)
662 FLVContext *flv = s->priv_data;
663 for (i=0; i<FLV_STREAM_TYPE_NB; i++)
664 av_freep(&flv->new_extradata[i]);
668 static int flv_get_extradata(AVFormatContext *s, AVStream *st, int size)
670 av_freep(&st->codec->extradata);
671 if (ff_get_extradata(st->codec, s->pb, size) < 0)
672 return AVERROR(ENOMEM);
676 static int flv_queue_extradata(FLVContext *flv, AVIOContext *pb, int stream,
679 av_free(flv->new_extradata[stream]);
680 flv->new_extradata[stream] = av_mallocz(size +
681 AV_INPUT_BUFFER_PADDING_SIZE);
682 if (!flv->new_extradata[stream])
683 return AVERROR(ENOMEM);
684 flv->new_extradata_size[stream] = size;
685 avio_read(pb, flv->new_extradata[stream], size);
689 static void clear_index_entries(AVFormatContext *s, int64_t pos)
692 av_log(s, AV_LOG_WARNING,
693 "Found invalid index entries, clearing the index.\n");
694 for (i = 0; i < s->nb_streams; i++) {
695 AVStream *st = s->streams[i];
696 /* Remove all index entries that point to >= pos */
698 for (j = 0; j < st->nb_index_entries; j++)
699 if (st->index_entries[j].pos < pos)
700 st->index_entries[out++] = st->index_entries[j];
701 st->nb_index_entries = out;
705 static int amf_skip_tag(AVIOContext *pb, AMFDataType type)
707 int nb = -1, ret, parse_name = 1;
710 case AMF_DATA_TYPE_NUMBER:
713 case AMF_DATA_TYPE_BOOL:
716 case AMF_DATA_TYPE_STRING:
717 avio_skip(pb, avio_rb16(pb));
719 case AMF_DATA_TYPE_ARRAY:
721 case AMF_DATA_TYPE_MIXEDARRAY:
723 case AMF_DATA_TYPE_OBJECT:
724 while(!pb->eof_reached && (nb-- > 0 || type != AMF_DATA_TYPE_ARRAY)) {
726 int size = avio_rb16(pb);
733 if ((ret = amf_skip_tag(pb, avio_r8(pb))) < 0)
737 case AMF_DATA_TYPE_NULL:
738 case AMF_DATA_TYPE_OBJECT_END:
741 return AVERROR_INVALIDDATA;
746 static int flv_data_packet(AVFormatContext *s, AVPacket *pkt,
747 int64_t dts, int64_t next)
749 AVIOContext *pb = s->pb;
752 int ret = AVERROR_INVALIDDATA;
756 switch (avio_r8(pb)) {
757 case AMF_DATA_TYPE_ARRAY:
759 case AMF_DATA_TYPE_MIXEDARRAY:
760 avio_seek(pb, 4, SEEK_CUR);
761 case AMF_DATA_TYPE_OBJECT:
767 while (array || (ret = amf_get_string(pb, buf, sizeof(buf))) > 0) {
768 AMFDataType type = avio_r8(pb);
769 if (type == AMF_DATA_TYPE_STRING && (array || !strcmp(buf, "text"))) {
770 length = avio_rb16(pb);
771 ret = av_get_packet(pb, pkt, length);
777 if ((ret = amf_skip_tag(pb, type)) < 0)
783 ret = AVERROR_INVALIDDATA;
787 for (i = 0; i < s->nb_streams; i++) {
789 if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE)
793 if (i == s->nb_streams) {
794 st = create_stream(s, AVMEDIA_TYPE_SUBTITLE);
796 return AVERROR(ENOMEM);
797 st->codec->codec_id = AV_CODEC_ID_TEXT;
804 pkt->stream_index = st->index;
805 pkt->flags |= AV_PKT_FLAG_KEY;
808 avio_seek(s->pb, next + 4, SEEK_SET);
813 static int resync(AVFormatContext *s)
815 FLVContext *flv = s->priv_data;
817 int64_t pos = avio_tell(s->pb);
819 for (i=0; !avio_feof(s->pb); i++) {
820 int j = i & (RESYNC_BUFFER_SIZE-1);
821 int j1 = j + RESYNC_BUFFER_SIZE;
822 flv->resync_buffer[j ] =
823 flv->resync_buffer[j1] = avio_r8(s->pb);
826 unsigned lsize2 = AV_RB32(flv->resync_buffer + j1 - 4);
827 if (lsize2 >= 11 && lsize2 + 8LL < FFMIN(i, RESYNC_BUFFER_SIZE)) {
828 unsigned size2 = AV_RB24(flv->resync_buffer + j1 - lsize2 + 1 - 4);
829 unsigned lsize1 = AV_RB32(flv->resync_buffer + j1 - lsize2 - 8);
830 if (lsize1 >= 11 && lsize1 + 8LL + lsize2 < FFMIN(i, RESYNC_BUFFER_SIZE)) {
831 unsigned size1 = AV_RB24(flv->resync_buffer + j1 - lsize1 + 1 - lsize2 - 8);
832 if (size1 == lsize1 - 11 && size2 == lsize2 - 11) {
833 avio_seek(s->pb, pos + i - lsize1 - lsize2 - 8, SEEK_SET);
843 static int flv_read_packet(AVFormatContext *s, AVPacket *pkt)
845 FLVContext *flv = s->priv_data;
846 int ret, i, size, flags;
847 enum FlvTagType type;
849 int64_t next, pos, meta_pos;
850 int64_t dts, pts = AV_NOPTS_VALUE;
851 int av_uninit(channels);
852 int av_uninit(sample_rate);
858 /* pkt size is repeated at end. skip it */
859 pos = avio_tell(s->pb);
860 type = (avio_r8(s->pb) & 0x1F);
862 size = avio_rb24(s->pb);
863 flv->sum_flv_tag_size += size + 11;
864 dts = avio_rb24(s->pb);
865 dts |= (unsigned)avio_r8(s->pb) << 24;
866 av_log(s, AV_LOG_TRACE, "type:%d, size:%d, last:%d, dts:%"PRId64" pos:%"PRId64"\n", type, size, last, dts, avio_tell(s->pb));
867 if (avio_feof(s->pb))
869 avio_skip(s->pb, 3); /* stream id, always 0 */
872 if (flv->validate_next < flv->validate_count) {
873 int64_t validate_pos = flv->validate_index[flv->validate_next].pos;
874 if (pos == validate_pos) {
875 if (FFABS(dts - flv->validate_index[flv->validate_next].dts) <=
876 VALIDATE_INDEX_TS_THRESH) {
877 flv->validate_next++;
879 clear_index_entries(s, validate_pos);
880 flv->validate_count = 0;
882 } else if (pos > validate_pos) {
883 clear_index_entries(s, validate_pos);
884 flv->validate_count = 0;
893 next = size + avio_tell(s->pb);
895 if (type == FLV_TAG_TYPE_AUDIO) {
896 stream_type = FLV_STREAM_TYPE_AUDIO;
897 flags = avio_r8(s->pb);
899 } else if (type == FLV_TAG_TYPE_VIDEO) {
900 stream_type = FLV_STREAM_TYPE_VIDEO;
901 flags = avio_r8(s->pb);
903 if ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_VIDEO_INFO_CMD)
905 } else if (type == FLV_TAG_TYPE_META) {
906 stream_type=FLV_STREAM_TYPE_DATA;
907 if (size > 13 + 1 + 4) { // Header-type metadata stuff
909 meta_pos = avio_tell(s->pb);
910 type = flv_read_metabody(s, next);
911 if (type == 0 && dts == 0 || type < 0 || type == TYPE_UNKNOWN) {
912 if (type < 0 && flv->validate_count &&
913 flv->validate_index[0].pos > next &&
914 flv->validate_index[0].pos - 4 < next
916 av_log(s, AV_LOG_WARNING, "Adjusting next position due to index mismatch\n");
917 next = flv->validate_index[0].pos - 4;
920 } else if (type == TYPE_ONTEXTDATA) {
921 avpriv_request_sample(s, "OnTextData packet");
922 return flv_data_packet(s, pkt, dts, next);
923 } else if (type == TYPE_ONCAPTION) {
924 return flv_data_packet(s, pkt, dts, next);
926 avio_seek(s->pb, meta_pos, SEEK_SET);
929 av_log(s, AV_LOG_DEBUG,
930 "Skipping flv packet: type %d, size %d, flags %d.\n",
933 avio_seek(s->pb, next, SEEK_SET);
938 /* skip empty data packets */
944 /* now find stream */
945 for (i = 0; i < s->nb_streams; i++) {
947 if (stream_type == FLV_STREAM_TYPE_AUDIO) {
948 if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
949 (s->audio_codec_id || flv_same_audio_codec(st->codec, flags)))
951 } else if (stream_type == FLV_STREAM_TYPE_VIDEO) {
952 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
953 (s->video_codec_id || flv_same_video_codec(st->codec, flags)))
955 } else if (stream_type == FLV_STREAM_TYPE_DATA) {
956 if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE)
960 if (i == s->nb_streams) {
961 static const enum AVMediaType stream_types[] = {AVMEDIA_TYPE_VIDEO, AVMEDIA_TYPE_AUDIO, AVMEDIA_TYPE_SUBTITLE};
962 av_log(s, AV_LOG_WARNING, "%s stream discovered after head already parsed\n", av_get_media_type_string(stream_types[stream_type]));
963 st = create_stream(s, stream_types[stream_type]);
965 return AVERROR(ENOMEM);
968 av_log(s, AV_LOG_TRACE, "%d %X %d \n", stream_type, flags, st->discard);
970 if (s->pb->seekable &&
971 ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY ||
972 stream_type == FLV_STREAM_TYPE_AUDIO))
973 av_add_index_entry(st, pos, dts, size, 0, AVINDEX_KEYFRAME);
975 if ( (st->discard >= AVDISCARD_NONKEY && !((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY || (stream_type == FLV_STREAM_TYPE_AUDIO)))
976 ||(st->discard >= AVDISCARD_BIDIR && ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_DISP_INTER && (stream_type == FLV_STREAM_TYPE_VIDEO)))
977 || st->discard >= AVDISCARD_ALL
979 avio_seek(s->pb, next, SEEK_SET);
984 // if not streamed and no duration from metadata then seek to end to find
985 // the duration from the timestamps
986 if (s->pb->seekable && (!s->duration || s->duration == AV_NOPTS_VALUE) &&
987 !flv->searched_for_end) {
989 const int64_t pos = avio_tell(s->pb);
990 // Read the last 4 bytes of the file, this should be the size of the
991 // previous FLV tag. Use the timestamp of its payload as duration.
992 int64_t fsize = avio_size(s->pb);
994 avio_seek(s->pb, fsize - 4, SEEK_SET);
995 size = avio_rb32(s->pb);
996 if (size > 0 && size < fsize) {
997 // Seek to the start of the last FLV tag at position (fsize - 4 - size)
998 // but skip the byte indicating the type.
999 avio_seek(s->pb, fsize - 3 - size, SEEK_SET);
1000 if (size == avio_rb24(s->pb) + 11) {
1001 uint32_t ts = avio_rb24(s->pb);
1002 ts |= avio_r8(s->pb) << 24;
1004 s->duration = ts * (int64_t)AV_TIME_BASE / 1000;
1005 else if (fsize >= 8 && fsize - 8 >= size) {
1007 goto retry_duration;
1012 avio_seek(s->pb, pos, SEEK_SET);
1013 flv->searched_for_end = 1;
1016 if (stream_type == FLV_STREAM_TYPE_AUDIO) {
1017 int bits_per_coded_sample;
1018 channels = (flags & FLV_AUDIO_CHANNEL_MASK) == FLV_STEREO ? 2 : 1;
1019 sample_rate = 44100 << ((flags & FLV_AUDIO_SAMPLERATE_MASK) >>
1020 FLV_AUDIO_SAMPLERATE_OFFSET) >> 3;
1021 bits_per_coded_sample = (flags & FLV_AUDIO_SAMPLESIZE_MASK) ? 16 : 8;
1022 if (!st->codec->channels || !st->codec->sample_rate ||
1023 !st->codec->bits_per_coded_sample) {
1024 st->codec->channels = channels;
1025 st->codec->channel_layout = channels == 1
1027 : AV_CH_LAYOUT_STEREO;
1028 st->codec->sample_rate = sample_rate;
1029 st->codec->bits_per_coded_sample = bits_per_coded_sample;
1031 if (!st->codec->codec_id) {
1032 flv_set_audio_codec(s, st, st->codec,
1033 flags & FLV_AUDIO_CODECID_MASK);
1034 flv->last_sample_rate =
1035 sample_rate = st->codec->sample_rate;
1036 flv->last_channels =
1037 channels = st->codec->channels;
1039 AVCodecContext ctx = {0};
1040 ctx.sample_rate = sample_rate;
1041 ctx.bits_per_coded_sample = bits_per_coded_sample;
1042 flv_set_audio_codec(s, st, &ctx, flags & FLV_AUDIO_CODECID_MASK);
1043 sample_rate = ctx.sample_rate;
1045 } else if (stream_type == FLV_STREAM_TYPE_VIDEO) {
1046 size -= flv_set_video_codec(s, st, flags & FLV_VIDEO_CODECID_MASK, 1);
1047 } else if (stream_type == FLV_STREAM_TYPE_DATA) {
1048 st->codec->codec_id = AV_CODEC_ID_TEXT;
1051 if (st->codec->codec_id == AV_CODEC_ID_AAC ||
1052 st->codec->codec_id == AV_CODEC_ID_H264 ||
1053 st->codec->codec_id == AV_CODEC_ID_MPEG4) {
1054 int type = avio_r8(s->pb);
1056 if (st->codec->codec_id == AV_CODEC_ID_H264 || st->codec->codec_id == AV_CODEC_ID_MPEG4) {
1058 int32_t cts = (avio_rb24(s->pb) + 0xff800000) ^ 0xff800000;
1060 if (cts < 0) { // dts might be wrong
1061 if (!flv->wrong_dts)
1062 av_log(s, AV_LOG_WARNING,
1063 "Negative cts, previous timestamps might be wrong.\n");
1065 } else if (FFABS(dts - pts) > 1000*60*15) {
1066 av_log(s, AV_LOG_WARNING,
1067 "invalid timestamps %"PRId64" %"PRId64"\n", dts, pts);
1068 dts = pts = AV_NOPTS_VALUE;
1071 if (type == 0 && (!st->codec->extradata || st->codec->codec_id == AV_CODEC_ID_AAC ||
1072 st->codec->codec_id == AV_CODEC_ID_H264)) {
1073 AVDictionaryEntry *t;
1075 if (st->codec->extradata) {
1076 if ((ret = flv_queue_extradata(flv, s->pb, stream_type, size)) < 0)
1081 if ((ret = flv_get_extradata(s, st, size)) < 0)
1084 /* Workaround for buggy Omnia A/XE encoder */
1085 t = av_dict_get(s->metadata, "Encoder", NULL, 0);
1086 if (st->codec->codec_id == AV_CODEC_ID_AAC && t && !strcmp(t->value, "Omnia A/XE"))
1087 st->codec->extradata_size = 2;
1089 if (st->codec->codec_id == AV_CODEC_ID_AAC && 0) {
1090 MPEG4AudioConfig cfg;
1092 if (avpriv_mpeg4audio_get_config(&cfg, st->codec->extradata,
1093 st->codec->extradata_size * 8, 1) >= 0) {
1094 st->codec->channels = cfg.channels;
1095 st->codec->channel_layout = 0;
1096 if (cfg.ext_sample_rate)
1097 st->codec->sample_rate = cfg.ext_sample_rate;
1099 st->codec->sample_rate = cfg.sample_rate;
1100 av_log(s, AV_LOG_TRACE, "mp4a config channels %d sample rate %d\n",
1101 st->codec->channels, st->codec->sample_rate);
1110 /* skip empty data packets */
1116 ret = av_get_packet(s->pb, pkt, size);
1120 pkt->pts = pts == AV_NOPTS_VALUE ? dts : pts;
1121 pkt->stream_index = st->index;
1122 if (flv->new_extradata[stream_type]) {
1123 uint8_t *side = av_packet_new_side_data(pkt, AV_PKT_DATA_NEW_EXTRADATA,
1124 flv->new_extradata_size[stream_type]);
1126 memcpy(side, flv->new_extradata[stream_type],
1127 flv->new_extradata_size[stream_type]);
1128 av_freep(&flv->new_extradata[stream_type]);
1129 flv->new_extradata_size[stream_type] = 0;
1132 if (stream_type == FLV_STREAM_TYPE_AUDIO &&
1133 (sample_rate != flv->last_sample_rate ||
1134 channels != flv->last_channels)) {
1135 flv->last_sample_rate = sample_rate;
1136 flv->last_channels = channels;
1137 ff_add_param_change(pkt, channels, 0, sample_rate, 0, 0);
1140 if ( stream_type == FLV_STREAM_TYPE_AUDIO ||
1141 ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY) ||
1142 stream_type == FLV_STREAM_TYPE_DATA)
1143 pkt->flags |= AV_PKT_FLAG_KEY;
1146 last = avio_rb32(s->pb);
1147 if (last != orig_size + 11 &&
1148 (last != orig_size || !last) && last != flv->sum_flv_tag_size &&
1149 !flv->broken_sizes) {
1150 av_log(s, AV_LOG_ERROR, "Packet mismatch %d %d\n", last, orig_size + 11);
1151 avio_seek(s->pb, pos + 1, SEEK_SET);
1153 av_packet_unref(pkt);
1161 static int flv_read_seek(AVFormatContext *s, int stream_index,
1162 int64_t ts, int flags)
1164 FLVContext *flv = s->priv_data;
1165 flv->validate_count = 0;
1166 return avio_seek_time(s->pb, stream_index, ts, flags);
1169 #define OFFSET(x) offsetof(FLVContext, x)
1170 #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
1171 static const AVOption options[] = {
1172 { "flv_metadata", "Allocate streams according to the onMetaData array", OFFSET(trust_metadata), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VD },
1176 static const AVClass flv_class = {
1177 .class_name = "flvdec",
1178 .item_name = av_default_item_name,
1180 .version = LIBAVUTIL_VERSION_INT,
1183 AVInputFormat ff_flv_demuxer = {
1185 .long_name = NULL_IF_CONFIG_SMALL("FLV (Flash Video)"),
1186 .priv_data_size = sizeof(FLVContext),
1187 .read_probe = flv_probe,
1188 .read_header = flv_read_header,
1189 .read_packet = flv_read_packet,
1190 .read_seek = flv_read_seek,
1191 .read_close = flv_read_close,
1192 .extensions = "flv",
1193 .priv_class = &flv_class,
1196 static const AVClass live_flv_class = {
1197 .class_name = "live_flvdec",
1198 .item_name = av_default_item_name,
1200 .version = LIBAVUTIL_VERSION_INT,
1203 AVInputFormat ff_live_flv_demuxer = {
1205 .long_name = NULL_IF_CONFIG_SMALL("live RTMP FLV (Flash Video)"),
1206 .priv_data_size = sizeof(FLVContext),
1207 .read_probe = live_flv_probe,
1208 .read_header = flv_read_header,
1209 .read_packet = flv_read_packet,
1210 .read_seek = flv_read_seek,
1211 .read_close = flv_read_close,
1212 .extensions = "flv",
1213 .priv_class = &live_flv_class,
1214 .flags = AVFMT_TS_DISCONT