3 * Copyright (c) 2003 The FFmpeg Project
5 * This demuxer will generate a 1 byte extradata for VP6F content.
7 * - upper 4 bits: difference between encoded width and visible width
8 * - lower 4 bits: 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 trust_datasize; ///< trust data size of FLVTag
48 int dump_full_metadata; ///< Dump full metadata of the onMetadata
49 int wrong_dts; ///< wrong dts due to negative cts
50 uint8_t *new_extradata[FLV_STREAM_TYPE_NB];
51 int new_extradata_size[FLV_STREAM_TYPE_NB];
62 uint8_t resync_buffer[2*RESYNC_BUFFER_SIZE];
67 int last_keyframe_stream_index;
69 int64_t video_bit_rate;
70 int64_t audio_bit_rate;
71 int64_t *keyframe_times;
72 int64_t *keyframe_filepositions;
80 static int probe(AVProbeData *p, int live)
82 const uint8_t *d = p->buf;
83 unsigned offset = AV_RB32(d + 5);
88 d[3] < 5 && d[5] == 0 &&
89 offset + 100 < p->buf_size &&
91 int is_live = !memcmp(d + offset + 40, "NGINX RTMP", 10);
94 return AVPROBE_SCORE_MAX;
99 static int flv_probe(AVProbeData *p)
104 static int live_flv_probe(AVProbeData *p)
109 static void add_keyframes_index(AVFormatContext *s)
111 FLVContext *flv = s->priv_data;
112 AVStream *stream = NULL;
115 if (flv->last_keyframe_stream_index < 0) {
116 av_log(s, AV_LOG_DEBUG, "keyframe stream hasn't been created\n");
120 av_assert0(flv->last_keyframe_stream_index <= s->nb_streams);
121 stream = s->streams[flv->last_keyframe_stream_index];
123 if (stream->nb_index_entries == 0) {
124 for (i = 0; i < flv->keyframe_count; i++) {
125 av_log(s, AV_LOG_TRACE, "keyframe filepositions = %"PRId64" times = %"PRId64"\n",
126 flv->keyframe_filepositions[i], flv->keyframe_times[i] * 1000);
127 av_add_index_entry(stream, flv->keyframe_filepositions[i],
128 flv->keyframe_times[i] * 1000, 0, 0, AVINDEX_KEYFRAME);
131 av_log(s, AV_LOG_WARNING, "Skipping duplicate index\n");
133 if (stream->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
134 av_freep(&flv->keyframe_times);
135 av_freep(&flv->keyframe_filepositions);
136 flv->keyframe_count = 0;
140 static AVStream *create_stream(AVFormatContext *s, int codec_type)
142 FLVContext *flv = s->priv_data;
143 AVStream *st = avformat_new_stream(s, NULL);
146 st->codecpar->codec_type = codec_type;
147 if (s->nb_streams>=3 ||( s->nb_streams==2
148 && s->streams[0]->codecpar->codec_type != AVMEDIA_TYPE_SUBTITLE
149 && s->streams[1]->codecpar->codec_type != AVMEDIA_TYPE_SUBTITLE
150 && s->streams[0]->codecpar->codec_type != AVMEDIA_TYPE_DATA
151 && s->streams[1]->codecpar->codec_type != AVMEDIA_TYPE_DATA))
152 s->ctx_flags &= ~AVFMTCTX_NOHEADER;
153 if (codec_type == AVMEDIA_TYPE_AUDIO) {
154 st->codecpar->bit_rate = flv->audio_bit_rate;
155 flv->missing_streams &= ~FLV_HEADER_FLAG_HASAUDIO;
157 if (codec_type == AVMEDIA_TYPE_VIDEO) {
158 st->codecpar->bit_rate = flv->video_bit_rate;
159 flv->missing_streams &= ~FLV_HEADER_FLAG_HASVIDEO;
160 st->avg_frame_rate = flv->framerate;
164 avpriv_set_pts_info(st, 32, 1, 1000); /* 32 bit pts in ms */
165 flv->last_keyframe_stream_index = s->nb_streams - 1;
166 add_keyframes_index(s);
170 static int flv_same_audio_codec(AVCodecParameters *apar, int flags)
172 int bits_per_coded_sample = (flags & FLV_AUDIO_SAMPLESIZE_MASK) ? 16 : 8;
173 int flv_codecid = flags & FLV_AUDIO_CODECID_MASK;
176 if (!apar->codec_id && !apar->codec_tag)
179 if (apar->bits_per_coded_sample != bits_per_coded_sample)
182 switch (flv_codecid) {
183 // no distinction between S16 and S8 PCM codec flags
184 case FLV_CODECID_PCM:
185 codec_id = bits_per_coded_sample == 8
188 : AV_CODEC_ID_PCM_S16BE;
190 : AV_CODEC_ID_PCM_S16LE;
192 return codec_id == apar->codec_id;
193 case FLV_CODECID_PCM_LE:
194 codec_id = bits_per_coded_sample == 8
196 : AV_CODEC_ID_PCM_S16LE;
197 return codec_id == apar->codec_id;
198 case FLV_CODECID_AAC:
199 return apar->codec_id == AV_CODEC_ID_AAC;
200 case FLV_CODECID_ADPCM:
201 return apar->codec_id == AV_CODEC_ID_ADPCM_SWF;
202 case FLV_CODECID_SPEEX:
203 return apar->codec_id == AV_CODEC_ID_SPEEX;
204 case FLV_CODECID_MP3:
205 return apar->codec_id == AV_CODEC_ID_MP3;
206 case FLV_CODECID_NELLYMOSER_8KHZ_MONO:
207 case FLV_CODECID_NELLYMOSER_16KHZ_MONO:
208 case FLV_CODECID_NELLYMOSER:
209 return apar->codec_id == AV_CODEC_ID_NELLYMOSER;
210 case FLV_CODECID_PCM_MULAW:
211 return apar->sample_rate == 8000 &&
212 apar->codec_id == AV_CODEC_ID_PCM_MULAW;
213 case FLV_CODECID_PCM_ALAW:
214 return apar->sample_rate == 8000 &&
215 apar->codec_id == AV_CODEC_ID_PCM_ALAW;
217 return apar->codec_tag == (flv_codecid >> FLV_AUDIO_CODECID_OFFSET);
221 static void flv_set_audio_codec(AVFormatContext *s, AVStream *astream,
222 AVCodecParameters *apar, int flv_codecid)
224 switch (flv_codecid) {
225 // no distinction between S16 and S8 PCM codec flags
226 case FLV_CODECID_PCM:
227 apar->codec_id = apar->bits_per_coded_sample == 8
230 : AV_CODEC_ID_PCM_S16BE;
232 : AV_CODEC_ID_PCM_S16LE;
235 case FLV_CODECID_PCM_LE:
236 apar->codec_id = apar->bits_per_coded_sample == 8
238 : AV_CODEC_ID_PCM_S16LE;
240 case FLV_CODECID_AAC:
241 apar->codec_id = AV_CODEC_ID_AAC;
243 case FLV_CODECID_ADPCM:
244 apar->codec_id = AV_CODEC_ID_ADPCM_SWF;
246 case FLV_CODECID_SPEEX:
247 apar->codec_id = AV_CODEC_ID_SPEEX;
248 apar->sample_rate = 16000;
250 case FLV_CODECID_MP3:
251 apar->codec_id = AV_CODEC_ID_MP3;
252 astream->need_parsing = AVSTREAM_PARSE_FULL;
254 case FLV_CODECID_NELLYMOSER_8KHZ_MONO:
255 // in case metadata does not otherwise declare samplerate
256 apar->sample_rate = 8000;
257 apar->codec_id = AV_CODEC_ID_NELLYMOSER;
259 case FLV_CODECID_NELLYMOSER_16KHZ_MONO:
260 apar->sample_rate = 16000;
261 apar->codec_id = AV_CODEC_ID_NELLYMOSER;
263 case FLV_CODECID_NELLYMOSER:
264 apar->codec_id = AV_CODEC_ID_NELLYMOSER;
266 case FLV_CODECID_PCM_MULAW:
267 apar->sample_rate = 8000;
268 apar->codec_id = AV_CODEC_ID_PCM_MULAW;
270 case FLV_CODECID_PCM_ALAW:
271 apar->sample_rate = 8000;
272 apar->codec_id = AV_CODEC_ID_PCM_ALAW;
275 avpriv_request_sample(s, "Audio codec (%x)",
276 flv_codecid >> FLV_AUDIO_CODECID_OFFSET);
277 apar->codec_tag = flv_codecid >> FLV_AUDIO_CODECID_OFFSET;
281 static int flv_same_video_codec(AVCodecParameters *vpar, int flags)
283 int flv_codecid = flags & FLV_VIDEO_CODECID_MASK;
285 if (!vpar->codec_id && !vpar->codec_tag)
288 switch (flv_codecid) {
289 case FLV_CODECID_H263:
290 return vpar->codec_id == AV_CODEC_ID_FLV1;
291 case FLV_CODECID_SCREEN:
292 return vpar->codec_id == AV_CODEC_ID_FLASHSV;
293 case FLV_CODECID_SCREEN2:
294 return vpar->codec_id == AV_CODEC_ID_FLASHSV2;
295 case FLV_CODECID_VP6:
296 return vpar->codec_id == AV_CODEC_ID_VP6F;
297 case FLV_CODECID_VP6A:
298 return vpar->codec_id == AV_CODEC_ID_VP6A;
299 case FLV_CODECID_H264:
300 return vpar->codec_id == AV_CODEC_ID_H264;
302 return vpar->codec_tag == flv_codecid;
306 static int flv_set_video_codec(AVFormatContext *s, AVStream *vstream,
307 int flv_codecid, int read)
310 AVCodecParameters *par = vstream->codecpar;
311 enum AVCodecID old_codec_id = vstream->codecpar->codec_id;
312 switch (flv_codecid) {
313 case FLV_CODECID_H263:
314 par->codec_id = AV_CODEC_ID_FLV1;
316 case FLV_CODECID_REALH263:
317 par->codec_id = AV_CODEC_ID_H263;
318 break; // Really mean it this time
319 case FLV_CODECID_SCREEN:
320 par->codec_id = AV_CODEC_ID_FLASHSV;
322 case FLV_CODECID_SCREEN2:
323 par->codec_id = AV_CODEC_ID_FLASHSV2;
325 case FLV_CODECID_VP6:
326 par->codec_id = AV_CODEC_ID_VP6F;
327 case FLV_CODECID_VP6A:
328 if (flv_codecid == FLV_CODECID_VP6A)
329 par->codec_id = AV_CODEC_ID_VP6A;
331 if (par->extradata_size != 1) {
332 ff_alloc_extradata(par, 1);
335 par->extradata[0] = avio_r8(s->pb);
339 ret = 1; // 1 byte body size adjustment for flv_read_packet()
341 case FLV_CODECID_H264:
342 par->codec_id = AV_CODEC_ID_H264;
343 vstream->need_parsing = AVSTREAM_PARSE_HEADERS;
344 ret = 3; // not 4, reading packet type will consume one byte
346 case FLV_CODECID_MPEG4:
347 par->codec_id = AV_CODEC_ID_MPEG4;
351 avpriv_request_sample(s, "Video codec (%x)", flv_codecid);
352 par->codec_tag = flv_codecid;
355 if (!vstream->internal->need_context_update && par->codec_id != old_codec_id) {
356 avpriv_request_sample(s, "Changing the codec id midstream");
357 return AVERROR_PATCHWELCOME;
363 static int amf_get_string(AVIOContext *ioc, char *buffer, int buffsize)
365 int length = avio_rb16(ioc);
366 if (length >= buffsize) {
367 avio_skip(ioc, length);
371 avio_read(ioc, buffer, length);
373 buffer[length] = '\0';
378 static int parse_keyframes_index(AVFormatContext *s, AVIOContext *ioc, int64_t max_pos)
380 FLVContext *flv = s->priv_data;
381 unsigned int timeslen = 0, fileposlen = 0, i;
383 int64_t *times = NULL;
384 int64_t *filepositions = NULL;
385 int ret = AVERROR(ENOSYS);
386 int64_t initial_pos = avio_tell(ioc);
388 if (flv->keyframe_count > 0) {
389 av_log(s, AV_LOG_DEBUG, "keyframes have been paresed\n");
392 av_assert0(!flv->keyframe_times);
393 av_assert0(!flv->keyframe_filepositions);
395 if (s->flags & AVFMT_FLAG_IGNIDX)
398 while (avio_tell(ioc) < max_pos - 2 &&
399 amf_get_string(ioc, str_val, sizeof(str_val)) > 0) {
400 int64_t **current_array;
401 unsigned int arraylen;
403 // Expect array object in context
404 if (avio_r8(ioc) != AMF_DATA_TYPE_ARRAY)
407 arraylen = avio_rb32(ioc);
411 if (!strcmp(KEYFRAMES_TIMESTAMP_TAG , str_val) && !times) {
412 current_array = ×
414 } else if (!strcmp(KEYFRAMES_BYTEOFFSET_TAG, str_val) &&
416 current_array = &filepositions;
417 fileposlen = arraylen;
419 // unexpected metatag inside keyframes, will not use such
420 // metadata for indexing
423 if (!(*current_array = av_mallocz(sizeof(**current_array) * arraylen))) {
424 ret = AVERROR(ENOMEM);
428 for (i = 0; i < arraylen && avio_tell(ioc) < max_pos - 1; i++) {
429 if (avio_r8(ioc) != AMF_DATA_TYPE_NUMBER)
431 current_array[0][i] = av_int2double(avio_rb64(ioc));
433 if (times && filepositions) {
434 // All done, exiting at a position allowing amf_parse_object
435 // to finish parsing the object
441 if (timeslen == fileposlen && fileposlen>1 && max_pos <= filepositions[0]) {
442 for (i = 0; i < FFMIN(2,fileposlen); i++) {
443 flv->validate_index[i].pos = filepositions[i];
444 flv->validate_index[i].dts = times[i] * 1000;
445 flv->validate_count = i + 1;
447 flv->keyframe_times = times;
448 flv->keyframe_filepositions = filepositions;
449 flv->keyframe_count = timeslen;
451 filepositions = NULL;
454 av_log(s, AV_LOG_WARNING, "Invalid keyframes object, skipping.\n");
459 av_freep(&filepositions);
460 avio_seek(ioc, initial_pos, SEEK_SET);
464 static int amf_parse_object(AVFormatContext *s, AVStream *astream,
465 AVStream *vstream, const char *key,
466 int64_t max_pos, int depth)
468 AVCodecParameters *apar, *vpar;
469 FLVContext *flv = s->priv_data;
471 AMFDataType amf_type;
477 amf_type = avio_r8(ioc);
480 case AMF_DATA_TYPE_NUMBER:
481 num_val = av_int2double(avio_rb64(ioc));
483 case AMF_DATA_TYPE_BOOL:
484 num_val = avio_r8(ioc);
486 case AMF_DATA_TYPE_STRING:
487 if (amf_get_string(ioc, str_val, sizeof(str_val)) < 0) {
488 av_log(s, AV_LOG_ERROR, "AMF_DATA_TYPE_STRING parsing failed\n");
492 case AMF_DATA_TYPE_OBJECT:
494 (ioc->seekable & AVIO_SEEKABLE_NORMAL) &&
495 !strcmp(KEYFRAMES_TAG, key) && depth == 1)
496 if (parse_keyframes_index(s, ioc,
498 av_log(s, AV_LOG_ERROR, "Keyframe index parsing failed\n");
500 add_keyframes_index(s);
501 while (avio_tell(ioc) < max_pos - 2 &&
502 amf_get_string(ioc, str_val, sizeof(str_val)) > 0)
503 if (amf_parse_object(s, astream, vstream, str_val, max_pos,
505 return -1; // if we couldn't skip, bomb out.
506 if (avio_r8(ioc) != AMF_END_OF_OBJECT) {
507 av_log(s, AV_LOG_ERROR, "Missing AMF_END_OF_OBJECT in AMF_DATA_TYPE_OBJECT\n");
511 case AMF_DATA_TYPE_NULL:
512 case AMF_DATA_TYPE_UNDEFINED:
513 case AMF_DATA_TYPE_UNSUPPORTED:
514 break; // these take up no additional space
515 case AMF_DATA_TYPE_MIXEDARRAY:
518 avio_skip(ioc, 4); // skip 32-bit max array index
519 while (avio_tell(ioc) < max_pos - 2 &&
520 amf_get_string(ioc, str_val, sizeof(str_val)) > 0)
521 // this is the only case in which we would want a nested
522 // parse to not skip over the object
523 if (amf_parse_object(s, astream, vstream, str_val, max_pos,
527 if (v != AMF_END_OF_OBJECT) {
528 av_log(s, AV_LOG_ERROR, "Missing AMF_END_OF_OBJECT in AMF_DATA_TYPE_MIXEDARRAY, found %d\n", v);
533 case AMF_DATA_TYPE_ARRAY:
535 unsigned int arraylen, i;
537 arraylen = avio_rb32(ioc);
538 for (i = 0; i < arraylen && avio_tell(ioc) < max_pos - 1; i++)
539 if (amf_parse_object(s, NULL, NULL, NULL, max_pos,
541 return -1; // if we couldn't skip, bomb out.
544 case AMF_DATA_TYPE_DATE:
545 avio_skip(ioc, 8 + 2); // timestamp (double) and UTC offset (int16)
547 default: // unsupported type, we couldn't skip
548 av_log(s, AV_LOG_ERROR, "unsupported amf type %d\n", amf_type);
553 apar = astream ? astream->codecpar : NULL;
554 vpar = vstream ? vstream->codecpar : NULL;
556 // stream info doesn't live any deeper than the first object
558 if (amf_type == AMF_DATA_TYPE_NUMBER ||
559 amf_type == AMF_DATA_TYPE_BOOL) {
560 if (!strcmp(key, "duration"))
561 s->duration = num_val * AV_TIME_BASE;
562 else if (!strcmp(key, "videodatarate") &&
563 0 <= (int)(num_val * 1024.0))
564 flv->video_bit_rate = num_val * 1024.0;
565 else if (!strcmp(key, "audiodatarate") &&
566 0 <= (int)(num_val * 1024.0))
567 flv->audio_bit_rate = num_val * 1024.0;
568 else if (!strcmp(key, "datastream")) {
569 AVStream *st = create_stream(s, AVMEDIA_TYPE_SUBTITLE);
571 return AVERROR(ENOMEM);
572 st->codecpar->codec_id = AV_CODEC_ID_TEXT;
573 } else if (!strcmp(key, "framerate")) {
574 flv->framerate = av_d2q(num_val, 1000);
576 vstream->avg_frame_rate = flv->framerate;
577 } else if (flv->trust_metadata) {
578 if (!strcmp(key, "videocodecid") && vpar) {
579 int ret = flv_set_video_codec(s, vstream, num_val, 0);
582 } else if (!strcmp(key, "audiocodecid") && apar) {
583 int id = ((int)num_val) << FLV_AUDIO_CODECID_OFFSET;
584 flv_set_audio_codec(s, astream, apar, id);
585 } else if (!strcmp(key, "audiosamplerate") && apar) {
586 apar->sample_rate = num_val;
587 } else if (!strcmp(key, "audiosamplesize") && apar) {
588 apar->bits_per_coded_sample = num_val;
589 } else if (!strcmp(key, "stereo") && apar) {
590 apar->channels = num_val + 1;
591 apar->channel_layout = apar->channels == 2 ?
592 AV_CH_LAYOUT_STEREO :
594 } else if (!strcmp(key, "width") && vpar) {
595 vpar->width = num_val;
596 } else if (!strcmp(key, "height") && vpar) {
597 vpar->height = num_val;
601 if (amf_type == AMF_DATA_TYPE_STRING) {
602 if (!strcmp(key, "encoder")) {
604 if (1 == sscanf(str_val, "Open Broadcaster Software v0.%d", &version)) {
605 if (version > 0 && version <= 655)
606 flv->broken_sizes = 1;
608 } else if (!strcmp(key, "metadatacreator")) {
609 if ( !strcmp (str_val, "MEGA")
610 || !strncmp(str_val, "FlixEngine", 10))
611 flv->broken_sizes = 1;
616 if (amf_type == AMF_DATA_TYPE_OBJECT && s->nb_streams == 1 &&
617 ((!apar && !strcmp(key, "audiocodecid")) ||
618 (!vpar && !strcmp(key, "videocodecid"))))
619 s->ctx_flags &= ~AVFMTCTX_NOHEADER; //If there is either audio/video missing, codecid will be an empty object
621 if ((!strcmp(key, "duration") ||
622 !strcmp(key, "filesize") ||
623 !strcmp(key, "width") ||
624 !strcmp(key, "height") ||
625 !strcmp(key, "videodatarate") ||
626 !strcmp(key, "framerate") ||
627 !strcmp(key, "videocodecid") ||
628 !strcmp(key, "audiodatarate") ||
629 !strcmp(key, "audiosamplerate") ||
630 !strcmp(key, "audiosamplesize") ||
631 !strcmp(key, "stereo") ||
632 !strcmp(key, "audiocodecid") ||
633 !strcmp(key, "datastream")) && !flv->dump_full_metadata)
636 s->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
637 if (amf_type == AMF_DATA_TYPE_BOOL) {
638 av_strlcpy(str_val, num_val > 0 ? "true" : "false",
640 av_dict_set(&s->metadata, key, str_val, 0);
641 } else if (amf_type == AMF_DATA_TYPE_NUMBER) {
642 snprintf(str_val, sizeof(str_val), "%.f", num_val);
643 av_dict_set(&s->metadata, key, str_val, 0);
644 } else if (amf_type == AMF_DATA_TYPE_STRING)
645 av_dict_set(&s->metadata, key, str_val, 0);
651 #define TYPE_ONTEXTDATA 1
652 #define TYPE_ONCAPTION 2
653 #define TYPE_ONCAPTIONINFO 3
654 #define TYPE_UNKNOWN 9
656 static int flv_read_metabody(AVFormatContext *s, int64_t next_pos)
658 FLVContext *flv = s->priv_data;
660 AVStream *stream, *astream, *vstream;
661 AVStream av_unused *dstream;
671 // first object needs to be "onMetaData" string
673 if (type != AMF_DATA_TYPE_STRING ||
674 amf_get_string(ioc, buffer, sizeof(buffer)) < 0)
677 if (!strcmp(buffer, "onTextData"))
678 return TYPE_ONTEXTDATA;
680 if (!strcmp(buffer, "onCaption"))
681 return TYPE_ONCAPTION;
683 if (!strcmp(buffer, "onCaptionInfo"))
684 return TYPE_ONCAPTIONINFO;
686 if (strcmp(buffer, "onMetaData") && strcmp(buffer, "onCuePoint")) {
687 av_log(s, AV_LOG_DEBUG, "Unknown type %s\n", buffer);
691 // find the streams now so that amf_parse_object doesn't need to do
692 // the lookup every time it is called.
693 for (i = 0; i < s->nb_streams; i++) {
694 stream = s->streams[i];
695 if (stream->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
697 flv->last_keyframe_stream_index = i;
698 } else if (stream->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
700 if (flv->last_keyframe_stream_index == -1)
701 flv->last_keyframe_stream_index = i;
703 else if (stream->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE)
707 // parse the second object (we want a mixed array)
708 if (amf_parse_object(s, astream, vstream, buffer, next_pos, 0) < 0)
714 static int flv_read_header(AVFormatContext *s)
717 FLVContext *flv = s->priv_data;
719 int pre_tag_size = 0;
722 flags = avio_r8(s->pb);
724 flv->missing_streams = flags & (FLV_HEADER_FLAG_HASVIDEO | FLV_HEADER_FLAG_HASAUDIO);
726 s->ctx_flags |= AVFMTCTX_NOHEADER;
728 offset = avio_rb32(s->pb);
729 avio_seek(s->pb, offset, SEEK_SET);
731 /* Annex E. The FLV File Format
734 * PreviousTagSize0 UI32 Always 0
736 pre_tag_size = avio_rb32(s->pb);
738 av_log(s, AV_LOG_WARNING, "Read FLV header error, input file is not a standard flv format, first PreviousTagSize0 always is 0\n");
742 flv->sum_flv_tag_size = 0;
743 flv->last_keyframe_stream_index = -1;
748 static int flv_read_close(AVFormatContext *s)
751 FLVContext *flv = s->priv_data;
752 for (i=0; i<FLV_STREAM_TYPE_NB; i++)
753 av_freep(&flv->new_extradata[i]);
754 av_freep(&flv->keyframe_times);
755 av_freep(&flv->keyframe_filepositions);
759 static int flv_get_extradata(AVFormatContext *s, AVStream *st, int size)
764 av_freep(&st->codecpar->extradata);
765 if (ff_get_extradata(s, st->codecpar, s->pb, size) < 0)
766 return AVERROR(ENOMEM);
767 st->internal->need_context_update = 1;
771 static int flv_queue_extradata(FLVContext *flv, AVIOContext *pb, int stream,
777 av_free(flv->new_extradata[stream]);
778 flv->new_extradata[stream] = av_mallocz(size +
779 AV_INPUT_BUFFER_PADDING_SIZE);
780 if (!flv->new_extradata[stream])
781 return AVERROR(ENOMEM);
782 flv->new_extradata_size[stream] = size;
783 avio_read(pb, flv->new_extradata[stream], size);
787 static void clear_index_entries(AVFormatContext *s, int64_t pos)
790 av_log(s, AV_LOG_WARNING,
791 "Found invalid index entries, clearing the index.\n");
792 for (i = 0; i < s->nb_streams; i++) {
793 AVStream *st = s->streams[i];
794 /* Remove all index entries that point to >= pos */
796 for (j = 0; j < st->nb_index_entries; j++)
797 if (st->index_entries[j].pos < pos)
798 st->index_entries[out++] = st->index_entries[j];
799 st->nb_index_entries = out;
803 static int amf_skip_tag(AVIOContext *pb, AMFDataType type)
805 int nb = -1, ret, parse_name = 1;
808 case AMF_DATA_TYPE_NUMBER:
811 case AMF_DATA_TYPE_BOOL:
814 case AMF_DATA_TYPE_STRING:
815 avio_skip(pb, avio_rb16(pb));
817 case AMF_DATA_TYPE_ARRAY:
819 case AMF_DATA_TYPE_MIXEDARRAY:
821 case AMF_DATA_TYPE_OBJECT:
822 while(!pb->eof_reached && (nb-- > 0 || type != AMF_DATA_TYPE_ARRAY)) {
824 int size = avio_rb16(pb);
831 if ((ret = amf_skip_tag(pb, avio_r8(pb))) < 0)
835 case AMF_DATA_TYPE_NULL:
836 case AMF_DATA_TYPE_OBJECT_END:
839 return AVERROR_INVALIDDATA;
844 static int flv_data_packet(AVFormatContext *s, AVPacket *pkt,
845 int64_t dts, int64_t next)
847 AVIOContext *pb = s->pb;
850 int ret = AVERROR_INVALIDDATA;
854 switch (avio_r8(pb)) {
855 case AMF_DATA_TYPE_ARRAY:
857 case AMF_DATA_TYPE_MIXEDARRAY:
858 avio_seek(pb, 4, SEEK_CUR);
859 case AMF_DATA_TYPE_OBJECT:
865 while (array || (ret = amf_get_string(pb, buf, sizeof(buf))) > 0) {
866 AMFDataType type = avio_r8(pb);
867 if (type == AMF_DATA_TYPE_STRING && (array || !strcmp(buf, "text"))) {
868 length = avio_rb16(pb);
869 ret = av_get_packet(pb, pkt, length);
875 if ((ret = amf_skip_tag(pb, type)) < 0)
881 ret = AVERROR_INVALIDDATA;
885 for (i = 0; i < s->nb_streams; i++) {
887 if (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE)
891 if (i == s->nb_streams) {
892 st = create_stream(s, AVMEDIA_TYPE_SUBTITLE);
894 return AVERROR(ENOMEM);
895 st->codecpar->codec_id = AV_CODEC_ID_TEXT;
902 pkt->stream_index = st->index;
903 pkt->flags |= AV_PKT_FLAG_KEY;
906 avio_seek(s->pb, next + 4, SEEK_SET);
911 static int resync(AVFormatContext *s)
913 FLVContext *flv = s->priv_data;
915 int64_t pos = avio_tell(s->pb);
917 for (i=0; !avio_feof(s->pb); i++) {
918 int j = i & (RESYNC_BUFFER_SIZE-1);
919 int j1 = j + RESYNC_BUFFER_SIZE;
920 flv->resync_buffer[j ] =
921 flv->resync_buffer[j1] = avio_r8(s->pb);
924 uint8_t *d = flv->resync_buffer + j1 - 8;
928 d[3] < 5 && d[5] == 0) {
929 av_log(s, AV_LOG_WARNING, "Concatenated FLV detected, might fail to demux, decode and seek %"PRId64"\n", flv->last_ts);
930 flv->time_offset = flv->last_ts + 1;
931 flv->time_pos = avio_tell(s->pb);
936 unsigned lsize2 = AV_RB32(flv->resync_buffer + j1 - 4);
937 if (lsize2 >= 11 && lsize2 + 8LL < FFMIN(i, RESYNC_BUFFER_SIZE)) {
938 unsigned size2 = AV_RB24(flv->resync_buffer + j1 - lsize2 + 1 - 4);
939 unsigned lsize1 = AV_RB32(flv->resync_buffer + j1 - lsize2 - 8);
940 if (lsize1 >= 11 && lsize1 + 8LL + lsize2 < FFMIN(i, RESYNC_BUFFER_SIZE)) {
941 unsigned size1 = AV_RB24(flv->resync_buffer + j1 - lsize1 + 1 - lsize2 - 8);
942 if (size1 == lsize1 - 11 && size2 == lsize2 - 11) {
943 avio_seek(s->pb, pos + i - lsize1 - lsize2 - 8, SEEK_SET);
953 static int flv_read_packet(AVFormatContext *s, AVPacket *pkt)
955 FLVContext *flv = s->priv_data;
956 int ret, i, size, flags;
957 enum FlvTagType type;
959 int64_t next, pos, meta_pos;
960 int64_t dts, pts = AV_NOPTS_VALUE;
961 int av_uninit(channels);
962 int av_uninit(sample_rate);
968 /* pkt size is repeated at end. skip it */
969 pos = avio_tell(s->pb);
970 type = (avio_r8(s->pb) & 0x1F);
972 size = avio_rb24(s->pb);
973 flv->sum_flv_tag_size += size + 11;
974 dts = avio_rb24(s->pb);
975 dts |= (unsigned)avio_r8(s->pb) << 24;
976 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));
977 if (avio_feof(s->pb))
979 avio_skip(s->pb, 3); /* stream id, always 0 */
982 if (flv->validate_next < flv->validate_count) {
983 int64_t validate_pos = flv->validate_index[flv->validate_next].pos;
984 if (pos == validate_pos) {
985 if (FFABS(dts - flv->validate_index[flv->validate_next].dts) <=
986 VALIDATE_INDEX_TS_THRESH) {
987 flv->validate_next++;
989 clear_index_entries(s, validate_pos);
990 flv->validate_count = 0;
992 } else if (pos > validate_pos) {
993 clear_index_entries(s, validate_pos);
994 flv->validate_count = 0;
1003 next = size + avio_tell(s->pb);
1005 if (type == FLV_TAG_TYPE_AUDIO) {
1006 stream_type = FLV_STREAM_TYPE_AUDIO;
1007 flags = avio_r8(s->pb);
1009 } else if (type == FLV_TAG_TYPE_VIDEO) {
1010 stream_type = FLV_STREAM_TYPE_VIDEO;
1011 flags = avio_r8(s->pb);
1013 if ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_VIDEO_INFO_CMD)
1015 } else if (type == FLV_TAG_TYPE_META) {
1016 stream_type=FLV_STREAM_TYPE_SUBTITLE;
1017 if (size > 13 + 1 + 4) { // Header-type metadata stuff
1019 meta_pos = avio_tell(s->pb);
1020 type = flv_read_metabody(s, next);
1021 if (type == 0 && dts == 0 || type < 0) {
1022 if (type < 0 && flv->validate_count &&
1023 flv->validate_index[0].pos > next &&
1024 flv->validate_index[0].pos - 4 < next
1026 av_log(s, AV_LOG_WARNING, "Adjusting next position due to index mismatch\n");
1027 next = flv->validate_index[0].pos - 4;
1030 } else if (type == TYPE_ONTEXTDATA) {
1031 avpriv_request_sample(s, "OnTextData packet");
1032 return flv_data_packet(s, pkt, dts, next);
1033 } else if (type == TYPE_ONCAPTION) {
1034 return flv_data_packet(s, pkt, dts, next);
1035 } else if (type == TYPE_UNKNOWN) {
1036 stream_type = FLV_STREAM_TYPE_DATA;
1038 avio_seek(s->pb, meta_pos, SEEK_SET);
1041 av_log(s, AV_LOG_DEBUG,
1042 "Skipping flv packet: type %d, size %d, flags %d.\n",
1045 if (avio_seek(s->pb, next, SEEK_SET) != next) {
1046 // This can happen if flv_read_metabody above read past
1047 // next, on a non-seekable input, and the preceding data has
1048 // been flushed out from the IO buffer.
1049 av_log(s, AV_LOG_ERROR, "Unable to seek to the next packet\n");
1050 return AVERROR_INVALIDDATA;
1056 /* skip empty data packets */
1062 /* now find stream */
1063 for (i = 0; i < s->nb_streams; i++) {
1065 if (stream_type == FLV_STREAM_TYPE_AUDIO) {
1066 if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO &&
1067 (s->audio_codec_id || flv_same_audio_codec(st->codecpar, flags)))
1069 } else if (stream_type == FLV_STREAM_TYPE_VIDEO) {
1070 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
1071 (s->video_codec_id || flv_same_video_codec(st->codecpar, flags)))
1073 } else if (stream_type == FLV_STREAM_TYPE_SUBTITLE) {
1074 if (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE)
1076 } else if (stream_type == FLV_STREAM_TYPE_DATA) {
1077 if (st->codecpar->codec_type == AVMEDIA_TYPE_DATA)
1081 if (i == s->nb_streams) {
1082 static const enum AVMediaType stream_types[] = {AVMEDIA_TYPE_VIDEO, AVMEDIA_TYPE_AUDIO, AVMEDIA_TYPE_SUBTITLE, AVMEDIA_TYPE_DATA};
1083 st = create_stream(s, stream_types[stream_type]);
1085 return AVERROR(ENOMEM);
1088 av_log(s, AV_LOG_TRACE, "%d %X %d \n", stream_type, flags, st->discard);
1090 if (flv->time_pos <= pos) {
1091 dts += flv->time_offset;
1094 if ((s->pb->seekable & AVIO_SEEKABLE_NORMAL) &&
1095 ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY ||
1096 stream_type == FLV_STREAM_TYPE_AUDIO))
1097 av_add_index_entry(st, pos, dts, size, 0, AVINDEX_KEYFRAME);
1099 if ( (st->discard >= AVDISCARD_NONKEY && !((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY || (stream_type == FLV_STREAM_TYPE_AUDIO)))
1100 ||(st->discard >= AVDISCARD_BIDIR && ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_DISP_INTER && (stream_type == FLV_STREAM_TYPE_VIDEO)))
1101 || st->discard >= AVDISCARD_ALL
1103 avio_seek(s->pb, next, SEEK_SET);
1108 // if not streamed and no duration from metadata then seek to end to find
1109 // the duration from the timestamps
1110 if ((s->pb->seekable & AVIO_SEEKABLE_NORMAL) &&
1111 (!s->duration || s->duration == AV_NOPTS_VALUE) &&
1112 !flv->searched_for_end) {
1114 const int64_t pos = avio_tell(s->pb);
1115 // Read the last 4 bytes of the file, this should be the size of the
1116 // previous FLV tag. Use the timestamp of its payload as duration.
1117 int64_t fsize = avio_size(s->pb);
1119 avio_seek(s->pb, fsize - 4, SEEK_SET);
1120 size = avio_rb32(s->pb);
1121 if (size > 0 && size < fsize) {
1122 // Seek to the start of the last FLV tag at position (fsize - 4 - size)
1123 // but skip the byte indicating the type.
1124 avio_seek(s->pb, fsize - 3 - size, SEEK_SET);
1125 if (size == avio_rb24(s->pb) + 11) {
1126 uint32_t ts = avio_rb24(s->pb);
1127 ts |= avio_r8(s->pb) << 24;
1129 s->duration = ts * (int64_t)AV_TIME_BASE / 1000;
1130 else if (fsize >= 8 && fsize - 8 >= size) {
1132 goto retry_duration;
1137 avio_seek(s->pb, pos, SEEK_SET);
1138 flv->searched_for_end = 1;
1141 if (stream_type == FLV_STREAM_TYPE_AUDIO) {
1142 int bits_per_coded_sample;
1143 channels = (flags & FLV_AUDIO_CHANNEL_MASK) == FLV_STEREO ? 2 : 1;
1144 sample_rate = 44100 << ((flags & FLV_AUDIO_SAMPLERATE_MASK) >>
1145 FLV_AUDIO_SAMPLERATE_OFFSET) >> 3;
1146 bits_per_coded_sample = (flags & FLV_AUDIO_SAMPLESIZE_MASK) ? 16 : 8;
1147 if (!st->codecpar->channels || !st->codecpar->sample_rate ||
1148 !st->codecpar->bits_per_coded_sample) {
1149 st->codecpar->channels = channels;
1150 st->codecpar->channel_layout = channels == 1
1152 : AV_CH_LAYOUT_STEREO;
1153 st->codecpar->sample_rate = sample_rate;
1154 st->codecpar->bits_per_coded_sample = bits_per_coded_sample;
1156 if (!st->codecpar->codec_id) {
1157 flv_set_audio_codec(s, st, st->codecpar,
1158 flags & FLV_AUDIO_CODECID_MASK);
1159 flv->last_sample_rate =
1160 sample_rate = st->codecpar->sample_rate;
1161 flv->last_channels =
1162 channels = st->codecpar->channels;
1164 AVCodecParameters *par = avcodec_parameters_alloc();
1166 ret = AVERROR(ENOMEM);
1169 par->sample_rate = sample_rate;
1170 par->bits_per_coded_sample = bits_per_coded_sample;
1171 flv_set_audio_codec(s, st, par, flags & FLV_AUDIO_CODECID_MASK);
1172 sample_rate = par->sample_rate;
1173 avcodec_parameters_free(&par);
1175 } else if (stream_type == FLV_STREAM_TYPE_VIDEO) {
1176 int ret = flv_set_video_codec(s, st, flags & FLV_VIDEO_CODECID_MASK, 1);
1180 } else if (stream_type == FLV_STREAM_TYPE_SUBTITLE) {
1181 st->codecpar->codec_id = AV_CODEC_ID_TEXT;
1182 } else if (stream_type == FLV_STREAM_TYPE_DATA) {
1183 st->codecpar->codec_id = AV_CODEC_ID_NONE; // Opaque AMF data
1186 if (st->codecpar->codec_id == AV_CODEC_ID_AAC ||
1187 st->codecpar->codec_id == AV_CODEC_ID_H264 ||
1188 st->codecpar->codec_id == AV_CODEC_ID_MPEG4) {
1189 int type = avio_r8(s->pb);
1193 ret = AVERROR_INVALIDDATA;
1197 if (st->codecpar->codec_id == AV_CODEC_ID_H264 || st->codecpar->codec_id == AV_CODEC_ID_MPEG4) {
1199 int32_t cts = (avio_rb24(s->pb) + 0xff800000) ^ 0xff800000;
1201 if (cts < 0) { // dts might be wrong
1202 if (!flv->wrong_dts)
1203 av_log(s, AV_LOG_WARNING,
1204 "Negative cts, previous timestamps might be wrong.\n");
1206 } else if (FFABS(dts - pts) > 1000*60*15) {
1207 av_log(s, AV_LOG_WARNING,
1208 "invalid timestamps %"PRId64" %"PRId64"\n", dts, pts);
1209 dts = pts = AV_NOPTS_VALUE;
1212 if (type == 0 && (!st->codecpar->extradata || st->codecpar->codec_id == AV_CODEC_ID_AAC ||
1213 st->codecpar->codec_id == AV_CODEC_ID_H264)) {
1214 AVDictionaryEntry *t;
1216 if (st->codecpar->extradata) {
1217 if ((ret = flv_queue_extradata(flv, s->pb, stream_type, size)) < 0)
1222 if ((ret = flv_get_extradata(s, st, size)) < 0)
1225 /* Workaround for buggy Omnia A/XE encoder */
1226 t = av_dict_get(s->metadata, "Encoder", NULL, 0);
1227 if (st->codecpar->codec_id == AV_CODEC_ID_AAC && t && !strcmp(t->value, "Omnia A/XE"))
1228 st->codecpar->extradata_size = 2;
1230 if (st->codecpar->codec_id == AV_CODEC_ID_AAC && 0) {
1231 MPEG4AudioConfig cfg;
1233 if (avpriv_mpeg4audio_get_config(&cfg, st->codecpar->extradata,
1234 st->codecpar->extradata_size * 8, 1) >= 0) {
1235 st->codecpar->channels = cfg.channels;
1236 st->codecpar->channel_layout = 0;
1237 if (cfg.ext_sample_rate)
1238 st->codecpar->sample_rate = cfg.ext_sample_rate;
1240 st->codecpar->sample_rate = cfg.sample_rate;
1241 av_log(s, AV_LOG_TRACE, "mp4a config channels %d sample rate %d\n",
1242 st->codecpar->channels, st->codecpar->sample_rate);
1251 /* skip empty data packets */
1257 ret = av_get_packet(s->pb, pkt, size);
1261 pkt->pts = pts == AV_NOPTS_VALUE ? dts : pts;
1262 pkt->stream_index = st->index;
1264 if (flv->new_extradata[stream_type]) {
1265 uint8_t *side = av_packet_new_side_data(pkt, AV_PKT_DATA_NEW_EXTRADATA,
1266 flv->new_extradata_size[stream_type]);
1268 memcpy(side, flv->new_extradata[stream_type],
1269 flv->new_extradata_size[stream_type]);
1270 av_freep(&flv->new_extradata[stream_type]);
1271 flv->new_extradata_size[stream_type] = 0;
1274 if (stream_type == FLV_STREAM_TYPE_AUDIO &&
1275 (sample_rate != flv->last_sample_rate ||
1276 channels != flv->last_channels)) {
1277 flv->last_sample_rate = sample_rate;
1278 flv->last_channels = channels;
1279 ff_add_param_change(pkt, channels, 0, sample_rate, 0, 0);
1282 if ( stream_type == FLV_STREAM_TYPE_AUDIO ||
1283 ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY) ||
1284 stream_type == FLV_STREAM_TYPE_SUBTITLE ||
1285 stream_type == FLV_STREAM_TYPE_DATA)
1286 pkt->flags |= AV_PKT_FLAG_KEY;
1289 last = avio_rb32(s->pb);
1290 if (!flv->trust_datasize) {
1291 if (last != orig_size + 11 && last != orig_size + 10 &&
1292 !avio_feof(s->pb) &&
1293 (last != orig_size || !last) && last != flv->sum_flv_tag_size &&
1294 !flv->broken_sizes) {
1295 av_log(s, AV_LOG_ERROR, "Packet mismatch %d %d %d\n", last, orig_size + 11, flv->sum_flv_tag_size);
1296 avio_seek(s->pb, pos + 1, SEEK_SET);
1298 av_packet_unref(pkt);
1306 flv->last_ts = pkt->dts;
1311 static int flv_read_seek(AVFormatContext *s, int stream_index,
1312 int64_t ts, int flags)
1314 FLVContext *flv = s->priv_data;
1315 flv->validate_count = 0;
1316 return avio_seek_time(s->pb, stream_index, ts, flags);
1319 #define OFFSET(x) offsetof(FLVContext, x)
1320 #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
1321 static const AVOption options[] = {
1322 { "flv_metadata", "Allocate streams according to the onMetaData array", OFFSET(trust_metadata), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VD },
1323 { "flv_full_metadata", "Dump full metadata of the onMetadata", OFFSET(dump_full_metadata), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VD },
1324 { "flv_ignore_prevtag", "Ignore the Size of previous tag", OFFSET(trust_datasize), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VD },
1325 { "missing_streams", "", OFFSET(missing_streams), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 0xFF, VD | AV_OPT_FLAG_EXPORT | AV_OPT_FLAG_READONLY },
1329 static const AVClass flv_class = {
1330 .class_name = "flvdec",
1331 .item_name = av_default_item_name,
1333 .version = LIBAVUTIL_VERSION_INT,
1336 AVInputFormat ff_flv_demuxer = {
1338 .long_name = NULL_IF_CONFIG_SMALL("FLV (Flash Video)"),
1339 .priv_data_size = sizeof(FLVContext),
1340 .read_probe = flv_probe,
1341 .read_header = flv_read_header,
1342 .read_packet = flv_read_packet,
1343 .read_seek = flv_read_seek,
1344 .read_close = flv_read_close,
1345 .extensions = "flv",
1346 .priv_class = &flv_class,
1349 static const AVClass live_flv_class = {
1350 .class_name = "live_flvdec",
1351 .item_name = av_default_item_name,
1353 .version = LIBAVUTIL_VERSION_INT,
1356 AVInputFormat ff_live_flv_demuxer = {
1358 .long_name = NULL_IF_CONFIG_SMALL("live RTMP FLV (Flash Video)"),
1359 .priv_data_size = sizeof(FLVContext),
1360 .read_probe = live_flv_probe,
1361 .read_header = flv_read_header,
1362 .read_packet = flv_read_packet,
1363 .read_seek = flv_read_seek,
1364 .read_close = flv_read_close,
1365 .extensions = "flv",
1366 .priv_class = &live_flv_class,
1367 .flags = AVFMT_TS_DISCONT