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 "libavutil/time_internal.h"
34 #include "libavcodec/bytestream.h"
35 #include "libavcodec/mpeg4audio.h"
38 #include "avio_internal.h"
41 #define VALIDATE_INDEX_TS_THRESH 2500
43 #define RESYNC_BUFFER_SIZE (1<<20)
45 typedef struct FLVContext {
46 const AVClass *class; ///< Class for private options.
47 int trust_metadata; ///< configure streams according onMetaData
48 int trust_datasize; ///< trust data size of FLVTag
49 int dump_full_metadata; ///< Dump full metadata of the onMetadata
50 int wrong_dts; ///< wrong dts due to negative cts
51 uint8_t *new_extradata[FLV_STREAM_TYPE_NB];
52 int new_extradata_size[FLV_STREAM_TYPE_NB];
63 uint8_t resync_buffer[2*RESYNC_BUFFER_SIZE];
68 int last_keyframe_stream_index;
70 int64_t video_bit_rate;
71 int64_t audio_bit_rate;
72 int64_t *keyframe_times;
73 int64_t *keyframe_filepositions;
82 typedef struct amf_date {
87 static int probe(const AVProbeData *p, int live)
89 const uint8_t *d = p->buf;
90 unsigned offset = AV_RB32(d + 5);
95 d[3] < 5 && d[5] == 0 &&
96 offset + 100 < p->buf_size &&
98 int is_live = !memcmp(d + offset + 40, "NGINX RTMP", 10);
101 return AVPROBE_SCORE_MAX;
106 static int flv_probe(const AVProbeData *p)
111 static int live_flv_probe(const AVProbeData *p)
116 static void add_keyframes_index(AVFormatContext *s)
118 FLVContext *flv = s->priv_data;
119 AVStream *stream = NULL;
122 if (flv->last_keyframe_stream_index < 0) {
123 av_log(s, AV_LOG_DEBUG, "keyframe stream hasn't been created\n");
127 av_assert0(flv->last_keyframe_stream_index <= s->nb_streams);
128 stream = s->streams[flv->last_keyframe_stream_index];
130 if (stream->nb_index_entries == 0) {
131 for (i = 0; i < flv->keyframe_count; i++) {
132 av_log(s, AV_LOG_TRACE, "keyframe filepositions = %"PRId64" times = %"PRId64"\n",
133 flv->keyframe_filepositions[i], flv->keyframe_times[i] * 1000);
134 av_add_index_entry(stream, flv->keyframe_filepositions[i],
135 flv->keyframe_times[i] * 1000, 0, 0, AVINDEX_KEYFRAME);
138 av_log(s, AV_LOG_WARNING, "Skipping duplicate index\n");
140 if (stream->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
141 av_freep(&flv->keyframe_times);
142 av_freep(&flv->keyframe_filepositions);
143 flv->keyframe_count = 0;
147 static AVStream *create_stream(AVFormatContext *s, int codec_type)
149 FLVContext *flv = s->priv_data;
150 AVStream *st = avformat_new_stream(s, NULL);
153 st->codecpar->codec_type = codec_type;
154 if (s->nb_streams>=3 ||( s->nb_streams==2
155 && s->streams[0]->codecpar->codec_type != AVMEDIA_TYPE_SUBTITLE
156 && s->streams[1]->codecpar->codec_type != AVMEDIA_TYPE_SUBTITLE
157 && s->streams[0]->codecpar->codec_type != AVMEDIA_TYPE_DATA
158 && s->streams[1]->codecpar->codec_type != AVMEDIA_TYPE_DATA))
159 s->ctx_flags &= ~AVFMTCTX_NOHEADER;
160 if (codec_type == AVMEDIA_TYPE_AUDIO) {
161 st->codecpar->bit_rate = flv->audio_bit_rate;
162 flv->missing_streams &= ~FLV_HEADER_FLAG_HASAUDIO;
164 if (codec_type == AVMEDIA_TYPE_VIDEO) {
165 st->codecpar->bit_rate = flv->video_bit_rate;
166 flv->missing_streams &= ~FLV_HEADER_FLAG_HASVIDEO;
167 st->avg_frame_rate = flv->framerate;
171 avpriv_set_pts_info(st, 32, 1, 1000); /* 32 bit pts in ms */
172 flv->last_keyframe_stream_index = s->nb_streams - 1;
173 add_keyframes_index(s);
177 static int flv_same_audio_codec(AVCodecParameters *apar, int flags)
179 int bits_per_coded_sample = (flags & FLV_AUDIO_SAMPLESIZE_MASK) ? 16 : 8;
180 int flv_codecid = flags & FLV_AUDIO_CODECID_MASK;
183 if (!apar->codec_id && !apar->codec_tag)
186 if (apar->bits_per_coded_sample != bits_per_coded_sample)
189 switch (flv_codecid) {
190 // no distinction between S16 and S8 PCM codec flags
191 case FLV_CODECID_PCM:
192 codec_id = bits_per_coded_sample == 8
195 : AV_CODEC_ID_PCM_S16BE;
197 : AV_CODEC_ID_PCM_S16LE;
199 return codec_id == apar->codec_id;
200 case FLV_CODECID_PCM_LE:
201 codec_id = bits_per_coded_sample == 8
203 : AV_CODEC_ID_PCM_S16LE;
204 return codec_id == apar->codec_id;
205 case FLV_CODECID_AAC:
206 return apar->codec_id == AV_CODEC_ID_AAC;
207 case FLV_CODECID_ADPCM:
208 return apar->codec_id == AV_CODEC_ID_ADPCM_SWF;
209 case FLV_CODECID_SPEEX:
210 return apar->codec_id == AV_CODEC_ID_SPEEX;
211 case FLV_CODECID_MP3:
212 return apar->codec_id == AV_CODEC_ID_MP3;
213 case FLV_CODECID_NELLYMOSER_8KHZ_MONO:
214 case FLV_CODECID_NELLYMOSER_16KHZ_MONO:
215 case FLV_CODECID_NELLYMOSER:
216 return apar->codec_id == AV_CODEC_ID_NELLYMOSER;
217 case FLV_CODECID_PCM_MULAW:
218 return apar->sample_rate == 8000 &&
219 apar->codec_id == AV_CODEC_ID_PCM_MULAW;
220 case FLV_CODECID_PCM_ALAW:
221 return apar->sample_rate == 8000 &&
222 apar->codec_id == AV_CODEC_ID_PCM_ALAW;
224 return apar->codec_tag == (flv_codecid >> FLV_AUDIO_CODECID_OFFSET);
228 static void flv_set_audio_codec(AVFormatContext *s, AVStream *astream,
229 AVCodecParameters *apar, int flv_codecid)
231 switch (flv_codecid) {
232 // no distinction between S16 and S8 PCM codec flags
233 case FLV_CODECID_PCM:
234 apar->codec_id = apar->bits_per_coded_sample == 8
237 : AV_CODEC_ID_PCM_S16BE;
239 : AV_CODEC_ID_PCM_S16LE;
242 case FLV_CODECID_PCM_LE:
243 apar->codec_id = apar->bits_per_coded_sample == 8
245 : AV_CODEC_ID_PCM_S16LE;
247 case FLV_CODECID_AAC:
248 apar->codec_id = AV_CODEC_ID_AAC;
250 case FLV_CODECID_ADPCM:
251 apar->codec_id = AV_CODEC_ID_ADPCM_SWF;
253 case FLV_CODECID_SPEEX:
254 apar->codec_id = AV_CODEC_ID_SPEEX;
255 apar->sample_rate = 16000;
257 case FLV_CODECID_MP3:
258 apar->codec_id = AV_CODEC_ID_MP3;
259 astream->need_parsing = AVSTREAM_PARSE_FULL;
261 case FLV_CODECID_NELLYMOSER_8KHZ_MONO:
262 // in case metadata does not otherwise declare samplerate
263 apar->sample_rate = 8000;
264 apar->codec_id = AV_CODEC_ID_NELLYMOSER;
266 case FLV_CODECID_NELLYMOSER_16KHZ_MONO:
267 apar->sample_rate = 16000;
268 apar->codec_id = AV_CODEC_ID_NELLYMOSER;
270 case FLV_CODECID_NELLYMOSER:
271 apar->codec_id = AV_CODEC_ID_NELLYMOSER;
273 case FLV_CODECID_PCM_MULAW:
274 apar->sample_rate = 8000;
275 apar->codec_id = AV_CODEC_ID_PCM_MULAW;
277 case FLV_CODECID_PCM_ALAW:
278 apar->sample_rate = 8000;
279 apar->codec_id = AV_CODEC_ID_PCM_ALAW;
282 avpriv_request_sample(s, "Audio codec (%x)",
283 flv_codecid >> FLV_AUDIO_CODECID_OFFSET);
284 apar->codec_tag = flv_codecid >> FLV_AUDIO_CODECID_OFFSET;
288 static int flv_same_video_codec(AVCodecParameters *vpar, int flags)
290 int flv_codecid = flags & FLV_VIDEO_CODECID_MASK;
292 if (!vpar->codec_id && !vpar->codec_tag)
295 switch (flv_codecid) {
296 case FLV_CODECID_H263:
297 return vpar->codec_id == AV_CODEC_ID_FLV1;
298 case FLV_CODECID_SCREEN:
299 return vpar->codec_id == AV_CODEC_ID_FLASHSV;
300 case FLV_CODECID_SCREEN2:
301 return vpar->codec_id == AV_CODEC_ID_FLASHSV2;
302 case FLV_CODECID_VP6:
303 return vpar->codec_id == AV_CODEC_ID_VP6F;
304 case FLV_CODECID_VP6A:
305 return vpar->codec_id == AV_CODEC_ID_VP6A;
306 case FLV_CODECID_H264:
307 return vpar->codec_id == AV_CODEC_ID_H264;
309 return vpar->codec_tag == flv_codecid;
313 static int flv_set_video_codec(AVFormatContext *s, AVStream *vstream,
314 int flv_codecid, int read)
317 AVCodecParameters *par = vstream->codecpar;
318 enum AVCodecID old_codec_id = vstream->codecpar->codec_id;
319 switch (flv_codecid) {
320 case FLV_CODECID_H263:
321 par->codec_id = AV_CODEC_ID_FLV1;
323 case FLV_CODECID_REALH263:
324 par->codec_id = AV_CODEC_ID_H263;
325 break; // Really mean it this time
326 case FLV_CODECID_SCREEN:
327 par->codec_id = AV_CODEC_ID_FLASHSV;
329 case FLV_CODECID_SCREEN2:
330 par->codec_id = AV_CODEC_ID_FLASHSV2;
332 case FLV_CODECID_VP6:
333 par->codec_id = AV_CODEC_ID_VP6F;
334 case FLV_CODECID_VP6A:
335 if (flv_codecid == FLV_CODECID_VP6A)
336 par->codec_id = AV_CODEC_ID_VP6A;
338 if (par->extradata_size != 1) {
339 ff_alloc_extradata(par, 1);
342 par->extradata[0] = avio_r8(s->pb);
346 ret = 1; // 1 byte body size adjustment for flv_read_packet()
348 case FLV_CODECID_H264:
349 par->codec_id = AV_CODEC_ID_H264;
350 vstream->need_parsing = AVSTREAM_PARSE_HEADERS;
351 ret = 3; // not 4, reading packet type will consume one byte
353 case FLV_CODECID_MPEG4:
354 par->codec_id = AV_CODEC_ID_MPEG4;
358 avpriv_request_sample(s, "Video codec (%x)", flv_codecid);
359 par->codec_tag = flv_codecid;
362 if (!vstream->internal->need_context_update && par->codec_id != old_codec_id) {
363 avpriv_request_sample(s, "Changing the codec id midstream");
364 return AVERROR_PATCHWELCOME;
370 static int amf_get_string(AVIOContext *ioc, char *buffer, int buffsize)
372 int length = avio_rb16(ioc);
373 if (length >= buffsize) {
374 avio_skip(ioc, length);
378 avio_read(ioc, buffer, length);
380 buffer[length] = '\0';
385 static int parse_keyframes_index(AVFormatContext *s, AVIOContext *ioc, int64_t max_pos)
387 FLVContext *flv = s->priv_data;
388 unsigned int timeslen = 0, fileposlen = 0, i;
390 int64_t *times = NULL;
391 int64_t *filepositions = NULL;
392 int ret = AVERROR(ENOSYS);
393 int64_t initial_pos = avio_tell(ioc);
395 if (flv->keyframe_count > 0) {
396 av_log(s, AV_LOG_DEBUG, "keyframes have been parsed\n");
399 av_assert0(!flv->keyframe_times);
400 av_assert0(!flv->keyframe_filepositions);
402 if (s->flags & AVFMT_FLAG_IGNIDX)
405 while (avio_tell(ioc) < max_pos - 2 &&
406 amf_get_string(ioc, str_val, sizeof(str_val)) > 0) {
407 int64_t **current_array;
408 unsigned int arraylen;
410 // Expect array object in context
411 if (avio_r8(ioc) != AMF_DATA_TYPE_ARRAY)
414 arraylen = avio_rb32(ioc);
418 if (!strcmp(KEYFRAMES_TIMESTAMP_TAG , str_val) && !times) {
419 current_array = ×
421 } else if (!strcmp(KEYFRAMES_BYTEOFFSET_TAG, str_val) &&
423 current_array = &filepositions;
424 fileposlen = arraylen;
426 // unexpected metatag inside keyframes, will not use such
427 // metadata for indexing
430 if (!(*current_array = av_mallocz(sizeof(**current_array) * arraylen))) {
431 ret = AVERROR(ENOMEM);
435 for (i = 0; i < arraylen && avio_tell(ioc) < max_pos - 1; i++) {
436 if (avio_r8(ioc) != AMF_DATA_TYPE_NUMBER)
438 current_array[0][i] = av_int2double(avio_rb64(ioc));
440 if (times && filepositions) {
441 // All done, exiting at a position allowing amf_parse_object
442 // to finish parsing the object
448 if (timeslen == fileposlen && fileposlen>1 && max_pos <= filepositions[0]) {
449 for (i = 0; i < FFMIN(2,fileposlen); i++) {
450 flv->validate_index[i].pos = filepositions[i];
451 flv->validate_index[i].dts = times[i] * 1000;
452 flv->validate_count = i + 1;
454 flv->keyframe_times = times;
455 flv->keyframe_filepositions = filepositions;
456 flv->keyframe_count = timeslen;
458 filepositions = NULL;
461 av_log(s, AV_LOG_WARNING, "Invalid keyframes object, skipping.\n");
466 av_freep(&filepositions);
467 avio_seek(ioc, initial_pos, SEEK_SET);
471 static int amf_parse_object(AVFormatContext *s, AVStream *astream,
472 AVStream *vstream, const char *key,
473 int64_t max_pos, int depth)
475 AVCodecParameters *apar, *vpar;
476 FLVContext *flv = s->priv_data;
478 AMFDataType amf_type;
485 amf_type = avio_r8(ioc);
488 case AMF_DATA_TYPE_NUMBER:
489 num_val = av_int2double(avio_rb64(ioc));
491 case AMF_DATA_TYPE_BOOL:
492 num_val = avio_r8(ioc);
494 case AMF_DATA_TYPE_STRING:
495 if (amf_get_string(ioc, str_val, sizeof(str_val)) < 0) {
496 av_log(s, AV_LOG_ERROR, "AMF_DATA_TYPE_STRING parsing failed\n");
500 case AMF_DATA_TYPE_OBJECT:
502 (ioc->seekable & AVIO_SEEKABLE_NORMAL) &&
503 !strcmp(KEYFRAMES_TAG, key) && depth == 1)
504 if (parse_keyframes_index(s, ioc,
506 av_log(s, AV_LOG_ERROR, "Keyframe index parsing failed\n");
508 add_keyframes_index(s);
509 while (avio_tell(ioc) < max_pos - 2 &&
510 amf_get_string(ioc, str_val, sizeof(str_val)) > 0)
511 if (amf_parse_object(s, astream, vstream, str_val, max_pos,
513 return -1; // if we couldn't skip, bomb out.
514 if (avio_r8(ioc) != AMF_END_OF_OBJECT) {
515 av_log(s, AV_LOG_ERROR, "Missing AMF_END_OF_OBJECT in AMF_DATA_TYPE_OBJECT\n");
519 case AMF_DATA_TYPE_NULL:
520 case AMF_DATA_TYPE_UNDEFINED:
521 case AMF_DATA_TYPE_UNSUPPORTED:
522 break; // these take up no additional space
523 case AMF_DATA_TYPE_MIXEDARRAY:
526 avio_skip(ioc, 4); // skip 32-bit max array index
527 while (avio_tell(ioc) < max_pos - 2 &&
528 amf_get_string(ioc, str_val, sizeof(str_val)) > 0)
529 // this is the only case in which we would want a nested
530 // parse to not skip over the object
531 if (amf_parse_object(s, astream, vstream, str_val, max_pos,
535 if (v != AMF_END_OF_OBJECT) {
536 av_log(s, AV_LOG_ERROR, "Missing AMF_END_OF_OBJECT in AMF_DATA_TYPE_MIXEDARRAY, found %d\n", v);
541 case AMF_DATA_TYPE_ARRAY:
543 unsigned int arraylen, i;
545 arraylen = avio_rb32(ioc);
546 for (i = 0; i < arraylen && avio_tell(ioc) < max_pos - 1; i++)
547 if (amf_parse_object(s, NULL, NULL, NULL, max_pos,
549 return -1; // if we couldn't skip, bomb out.
552 case AMF_DATA_TYPE_DATE:
553 // timestamp (double) and UTC offset (int16)
554 date.milliseconds = av_int2double(avio_rb64(ioc));
555 date.timezone = avio_rb16(ioc);
557 default: // unsupported type, we couldn't skip
558 av_log(s, AV_LOG_ERROR, "unsupported amf type %d\n", amf_type);
563 apar = astream ? astream->codecpar : NULL;
564 vpar = vstream ? vstream->codecpar : NULL;
566 // stream info doesn't live any deeper than the first object
568 if (amf_type == AMF_DATA_TYPE_NUMBER ||
569 amf_type == AMF_DATA_TYPE_BOOL) {
570 if (!strcmp(key, "duration"))
571 s->duration = num_val * AV_TIME_BASE;
572 else if (!strcmp(key, "videodatarate") &&
573 0 <= (int)(num_val * 1024.0))
574 flv->video_bit_rate = num_val * 1024.0;
575 else if (!strcmp(key, "audiodatarate") &&
576 0 <= (int)(num_val * 1024.0))
577 flv->audio_bit_rate = num_val * 1024.0;
578 else if (!strcmp(key, "datastream")) {
579 AVStream *st = create_stream(s, AVMEDIA_TYPE_SUBTITLE);
581 return AVERROR(ENOMEM);
582 st->codecpar->codec_id = AV_CODEC_ID_TEXT;
583 } else if (!strcmp(key, "framerate")) {
584 flv->framerate = av_d2q(num_val, 1000);
586 vstream->avg_frame_rate = flv->framerate;
587 } else if (flv->trust_metadata) {
588 if (!strcmp(key, "videocodecid") && vpar) {
589 int ret = flv_set_video_codec(s, vstream, num_val, 0);
592 } else if (!strcmp(key, "audiocodecid") && apar) {
593 int id = ((int)num_val) << FLV_AUDIO_CODECID_OFFSET;
594 flv_set_audio_codec(s, astream, apar, id);
595 } else if (!strcmp(key, "audiosamplerate") && apar) {
596 apar->sample_rate = num_val;
597 } else if (!strcmp(key, "audiosamplesize") && apar) {
598 apar->bits_per_coded_sample = num_val;
599 } else if (!strcmp(key, "stereo") && apar) {
600 apar->channels = num_val + 1;
601 apar->channel_layout = apar->channels == 2 ?
602 AV_CH_LAYOUT_STEREO :
604 } else if (!strcmp(key, "width") && vpar) {
605 vpar->width = num_val;
606 } else if (!strcmp(key, "height") && vpar) {
607 vpar->height = num_val;
611 if (amf_type == AMF_DATA_TYPE_STRING) {
612 if (!strcmp(key, "encoder")) {
614 if (1 == sscanf(str_val, "Open Broadcaster Software v0.%d", &version)) {
615 if (version > 0 && version <= 655)
616 flv->broken_sizes = 1;
618 } else if (!strcmp(key, "metadatacreator")) {
619 if ( !strcmp (str_val, "MEGA")
620 || !strncmp(str_val, "FlixEngine", 10))
621 flv->broken_sizes = 1;
626 if (amf_type == AMF_DATA_TYPE_OBJECT && s->nb_streams == 1 &&
627 ((!apar && !strcmp(key, "audiocodecid")) ||
628 (!vpar && !strcmp(key, "videocodecid"))))
629 s->ctx_flags &= ~AVFMTCTX_NOHEADER; //If there is either audio/video missing, codecid will be an empty object
631 if ((!strcmp(key, "duration") ||
632 !strcmp(key, "filesize") ||
633 !strcmp(key, "width") ||
634 !strcmp(key, "height") ||
635 !strcmp(key, "videodatarate") ||
636 !strcmp(key, "framerate") ||
637 !strcmp(key, "videocodecid") ||
638 !strcmp(key, "audiodatarate") ||
639 !strcmp(key, "audiosamplerate") ||
640 !strcmp(key, "audiosamplesize") ||
641 !strcmp(key, "stereo") ||
642 !strcmp(key, "audiocodecid") ||
643 !strcmp(key, "datastream")) && !flv->dump_full_metadata)
646 s->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
647 if (amf_type == AMF_DATA_TYPE_BOOL) {
648 av_strlcpy(str_val, num_val > 0 ? "true" : "false",
650 av_dict_set(&s->metadata, key, str_val, 0);
651 } else if (amf_type == AMF_DATA_TYPE_NUMBER) {
652 snprintf(str_val, sizeof(str_val), "%.f", num_val);
653 av_dict_set(&s->metadata, key, str_val, 0);
654 } else if (amf_type == AMF_DATA_TYPE_STRING) {
655 av_dict_set(&s->metadata, key, str_val, 0);
656 } else if (amf_type == AMF_DATA_TYPE_DATE) {
660 time = date.milliseconds / 1000; // to seconds
661 localtime_r(&time, &t);
662 strftime(datestr, sizeof(datestr), "%a, %d %b %Y %H:%M:%S %z", &t);
664 av_dict_set(&s->metadata, key, datestr, 0);
671 #define TYPE_ONTEXTDATA 1
672 #define TYPE_ONCAPTION 2
673 #define TYPE_ONCAPTIONINFO 3
674 #define TYPE_UNKNOWN 9
676 static int flv_read_metabody(AVFormatContext *s, int64_t next_pos)
678 FLVContext *flv = s->priv_data;
680 AVStream *stream, *astream, *vstream;
681 AVStream av_unused *dstream;
691 // first object needs to be "onMetaData" string
693 if (type != AMF_DATA_TYPE_STRING ||
694 amf_get_string(ioc, buffer, sizeof(buffer)) < 0)
697 if (!strcmp(buffer, "onTextData"))
698 return TYPE_ONTEXTDATA;
700 if (!strcmp(buffer, "onCaption"))
701 return TYPE_ONCAPTION;
703 if (!strcmp(buffer, "onCaptionInfo"))
704 return TYPE_ONCAPTIONINFO;
706 if (strcmp(buffer, "onMetaData") && strcmp(buffer, "onCuePoint")) {
707 av_log(s, AV_LOG_DEBUG, "Unknown type %s\n", buffer);
711 // find the streams now so that amf_parse_object doesn't need to do
712 // the lookup every time it is called.
713 for (i = 0; i < s->nb_streams; i++) {
714 stream = s->streams[i];
715 if (stream->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
717 flv->last_keyframe_stream_index = i;
718 } else if (stream->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
720 if (flv->last_keyframe_stream_index == -1)
721 flv->last_keyframe_stream_index = i;
723 else if (stream->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE)
727 // parse the second object (we want a mixed array)
728 if (amf_parse_object(s, astream, vstream, buffer, next_pos, 0) < 0)
734 static int flv_read_header(AVFormatContext *s)
737 FLVContext *flv = s->priv_data;
739 int pre_tag_size = 0;
742 flags = avio_r8(s->pb);
744 flv->missing_streams = flags & (FLV_HEADER_FLAG_HASVIDEO | FLV_HEADER_FLAG_HASAUDIO);
746 s->ctx_flags |= AVFMTCTX_NOHEADER;
748 offset = avio_rb32(s->pb);
749 avio_seek(s->pb, offset, SEEK_SET);
751 /* Annex E. The FLV File Format
754 * PreviousTagSize0 UI32 Always 0
756 pre_tag_size = avio_rb32(s->pb);
758 av_log(s, AV_LOG_WARNING, "Read FLV header error, input file is not a standard flv format, first PreviousTagSize0 always is 0\n");
762 flv->sum_flv_tag_size = 0;
763 flv->last_keyframe_stream_index = -1;
768 static int flv_read_close(AVFormatContext *s)
771 FLVContext *flv = s->priv_data;
772 for (i=0; i<FLV_STREAM_TYPE_NB; i++)
773 av_freep(&flv->new_extradata[i]);
774 av_freep(&flv->keyframe_times);
775 av_freep(&flv->keyframe_filepositions);
779 static int flv_get_extradata(AVFormatContext *s, AVStream *st, int size)
784 av_freep(&st->codecpar->extradata);
785 if (ff_get_extradata(s, st->codecpar, s->pb, size) < 0)
786 return AVERROR(ENOMEM);
787 st->internal->need_context_update = 1;
791 static int flv_queue_extradata(FLVContext *flv, AVIOContext *pb, int stream,
797 av_free(flv->new_extradata[stream]);
798 flv->new_extradata[stream] = av_mallocz(size +
799 AV_INPUT_BUFFER_PADDING_SIZE);
800 if (!flv->new_extradata[stream])
801 return AVERROR(ENOMEM);
802 flv->new_extradata_size[stream] = size;
803 avio_read(pb, flv->new_extradata[stream], size);
807 static void clear_index_entries(AVFormatContext *s, int64_t pos)
810 av_log(s, AV_LOG_WARNING,
811 "Found invalid index entries, clearing the index.\n");
812 for (i = 0; i < s->nb_streams; i++) {
813 AVStream *st = s->streams[i];
814 /* Remove all index entries that point to >= pos */
816 for (j = 0; j < st->nb_index_entries; j++)
817 if (st->index_entries[j].pos < pos)
818 st->index_entries[out++] = st->index_entries[j];
819 st->nb_index_entries = out;
823 static int amf_skip_tag(AVIOContext *pb, AMFDataType type)
825 int nb = -1, ret, parse_name = 1;
828 case AMF_DATA_TYPE_NUMBER:
831 case AMF_DATA_TYPE_BOOL:
834 case AMF_DATA_TYPE_STRING:
835 avio_skip(pb, avio_rb16(pb));
837 case AMF_DATA_TYPE_ARRAY:
839 case AMF_DATA_TYPE_MIXEDARRAY:
841 case AMF_DATA_TYPE_OBJECT:
842 while(!pb->eof_reached && (nb-- > 0 || type != AMF_DATA_TYPE_ARRAY)) {
844 int size = avio_rb16(pb);
851 if ((ret = amf_skip_tag(pb, avio_r8(pb))) < 0)
855 case AMF_DATA_TYPE_NULL:
856 case AMF_DATA_TYPE_OBJECT_END:
859 return AVERROR_INVALIDDATA;
864 static int flv_data_packet(AVFormatContext *s, AVPacket *pkt,
865 int64_t dts, int64_t next)
867 AVIOContext *pb = s->pb;
870 int ret = AVERROR_INVALIDDATA;
874 switch (avio_r8(pb)) {
875 case AMF_DATA_TYPE_ARRAY:
877 case AMF_DATA_TYPE_MIXEDARRAY:
878 avio_seek(pb, 4, SEEK_CUR);
879 case AMF_DATA_TYPE_OBJECT:
885 while (array || (ret = amf_get_string(pb, buf, sizeof(buf))) > 0) {
886 AMFDataType type = avio_r8(pb);
887 if (type == AMF_DATA_TYPE_STRING && (array || !strcmp(buf, "text"))) {
888 length = avio_rb16(pb);
889 ret = av_get_packet(pb, pkt, length);
895 if ((ret = amf_skip_tag(pb, type)) < 0)
901 ret = AVERROR_INVALIDDATA;
905 for (i = 0; i < s->nb_streams; i++) {
907 if (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE)
911 if (i == s->nb_streams) {
912 st = create_stream(s, AVMEDIA_TYPE_SUBTITLE);
914 return AVERROR(ENOMEM);
915 st->codecpar->codec_id = AV_CODEC_ID_TEXT;
922 pkt->stream_index = st->index;
923 pkt->flags |= AV_PKT_FLAG_KEY;
926 avio_seek(s->pb, next + 4, SEEK_SET);
931 static int resync(AVFormatContext *s)
933 FLVContext *flv = s->priv_data;
935 int64_t pos = avio_tell(s->pb);
937 for (i=0; !avio_feof(s->pb); i++) {
938 int j = i & (RESYNC_BUFFER_SIZE-1);
939 int j1 = j + RESYNC_BUFFER_SIZE;
940 flv->resync_buffer[j ] =
941 flv->resync_buffer[j1] = avio_r8(s->pb);
944 uint8_t *d = flv->resync_buffer + j1 - 8;
948 d[3] < 5 && d[5] == 0) {
949 av_log(s, AV_LOG_WARNING, "Concatenated FLV detected, might fail to demux, decode and seek %"PRId64"\n", flv->last_ts);
950 flv->time_offset = flv->last_ts + 1;
951 flv->time_pos = avio_tell(s->pb);
956 unsigned lsize2 = AV_RB32(flv->resync_buffer + j1 - 4);
957 if (lsize2 >= 11 && lsize2 + 8LL < FFMIN(i, RESYNC_BUFFER_SIZE)) {
958 unsigned size2 = AV_RB24(flv->resync_buffer + j1 - lsize2 + 1 - 4);
959 unsigned lsize1 = AV_RB32(flv->resync_buffer + j1 - lsize2 - 8);
960 if (lsize1 >= 11 && lsize1 + 8LL + lsize2 < FFMIN(i, RESYNC_BUFFER_SIZE)) {
961 unsigned size1 = AV_RB24(flv->resync_buffer + j1 - lsize1 + 1 - lsize2 - 8);
962 if (size1 == lsize1 - 11 && size2 == lsize2 - 11) {
963 avio_seek(s->pb, pos + i - lsize1 - lsize2 - 8, SEEK_SET);
973 static int flv_read_packet(AVFormatContext *s, AVPacket *pkt)
975 FLVContext *flv = s->priv_data;
976 int ret, i, size, flags;
977 enum FlvTagType type;
979 int64_t next, pos, meta_pos;
980 int64_t dts, pts = AV_NOPTS_VALUE;
981 int av_uninit(channels);
982 int av_uninit(sample_rate);
988 /* pkt size is repeated at end. skip it */
989 pos = avio_tell(s->pb);
990 type = (avio_r8(s->pb) & 0x1F);
992 size = avio_rb24(s->pb);
993 flv->sum_flv_tag_size += size + 11;
994 dts = avio_rb24(s->pb);
995 dts |= (unsigned)avio_r8(s->pb) << 24;
996 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));
997 if (avio_feof(s->pb))
999 avio_skip(s->pb, 3); /* stream id, always 0 */
1002 if (flv->validate_next < flv->validate_count) {
1003 int64_t validate_pos = flv->validate_index[flv->validate_next].pos;
1004 if (pos == validate_pos) {
1005 if (FFABS(dts - flv->validate_index[flv->validate_next].dts) <=
1006 VALIDATE_INDEX_TS_THRESH) {
1007 flv->validate_next++;
1009 clear_index_entries(s, validate_pos);
1010 flv->validate_count = 0;
1012 } else if (pos > validate_pos) {
1013 clear_index_entries(s, validate_pos);
1014 flv->validate_count = 0;
1023 next = size + avio_tell(s->pb);
1025 if (type == FLV_TAG_TYPE_AUDIO) {
1026 stream_type = FLV_STREAM_TYPE_AUDIO;
1027 flags = avio_r8(s->pb);
1029 } else if (type == FLV_TAG_TYPE_VIDEO) {
1030 stream_type = FLV_STREAM_TYPE_VIDEO;
1031 flags = avio_r8(s->pb);
1033 if ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_VIDEO_INFO_CMD)
1035 } else if (type == FLV_TAG_TYPE_META) {
1036 stream_type=FLV_STREAM_TYPE_SUBTITLE;
1037 if (size > 13 + 1 + 4) { // Header-type metadata stuff
1039 meta_pos = avio_tell(s->pb);
1040 type = flv_read_metabody(s, next);
1041 if (type == 0 && dts == 0 || type < 0) {
1042 if (type < 0 && flv->validate_count &&
1043 flv->validate_index[0].pos > next &&
1044 flv->validate_index[0].pos - 4 < next
1046 av_log(s, AV_LOG_WARNING, "Adjusting next position due to index mismatch\n");
1047 next = flv->validate_index[0].pos - 4;
1050 } else if (type == TYPE_ONTEXTDATA) {
1051 avpriv_request_sample(s, "OnTextData packet");
1052 return flv_data_packet(s, pkt, dts, next);
1053 } else if (type == TYPE_ONCAPTION) {
1054 return flv_data_packet(s, pkt, dts, next);
1055 } else if (type == TYPE_UNKNOWN) {
1056 stream_type = FLV_STREAM_TYPE_DATA;
1058 avio_seek(s->pb, meta_pos, SEEK_SET);
1061 av_log(s, AV_LOG_DEBUG,
1062 "Skipping flv packet: type %d, size %d, flags %d.\n",
1065 if (avio_seek(s->pb, next, SEEK_SET) != next) {
1066 // This can happen if flv_read_metabody above read past
1067 // next, on a non-seekable input, and the preceding data has
1068 // been flushed out from the IO buffer.
1069 av_log(s, AV_LOG_ERROR, "Unable to seek to the next packet\n");
1070 return AVERROR_INVALIDDATA;
1076 /* skip empty data packets */
1082 /* now find stream */
1083 for (i = 0; i < s->nb_streams; i++) {
1085 if (stream_type == FLV_STREAM_TYPE_AUDIO) {
1086 if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO &&
1087 (s->audio_codec_id || flv_same_audio_codec(st->codecpar, flags)))
1089 } else if (stream_type == FLV_STREAM_TYPE_VIDEO) {
1090 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
1091 (s->video_codec_id || flv_same_video_codec(st->codecpar, flags)))
1093 } else if (stream_type == FLV_STREAM_TYPE_SUBTITLE) {
1094 if (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE)
1096 } else if (stream_type == FLV_STREAM_TYPE_DATA) {
1097 if (st->codecpar->codec_type == AVMEDIA_TYPE_DATA)
1101 if (i == s->nb_streams) {
1102 static const enum AVMediaType stream_types[] = {AVMEDIA_TYPE_VIDEO, AVMEDIA_TYPE_AUDIO, AVMEDIA_TYPE_SUBTITLE, AVMEDIA_TYPE_DATA};
1103 st = create_stream(s, stream_types[stream_type]);
1105 return AVERROR(ENOMEM);
1108 av_log(s, AV_LOG_TRACE, "%d %X %d \n", stream_type, flags, st->discard);
1110 if (flv->time_pos <= pos) {
1111 dts += flv->time_offset;
1114 if ((s->pb->seekable & AVIO_SEEKABLE_NORMAL) &&
1115 ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY ||
1116 stream_type == FLV_STREAM_TYPE_AUDIO))
1117 av_add_index_entry(st, pos, dts, size, 0, AVINDEX_KEYFRAME);
1119 if ( (st->discard >= AVDISCARD_NONKEY && !((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY || (stream_type == FLV_STREAM_TYPE_AUDIO)))
1120 ||(st->discard >= AVDISCARD_BIDIR && ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_DISP_INTER && (stream_type == FLV_STREAM_TYPE_VIDEO)))
1121 || st->discard >= AVDISCARD_ALL
1123 avio_seek(s->pb, next, SEEK_SET);
1128 // if not streamed and no duration from metadata then seek to end to find
1129 // the duration from the timestamps
1130 if ((s->pb->seekable & AVIO_SEEKABLE_NORMAL) &&
1131 (!s->duration || s->duration == AV_NOPTS_VALUE) &&
1132 !flv->searched_for_end) {
1134 const int64_t pos = avio_tell(s->pb);
1135 // Read the last 4 bytes of the file, this should be the size of the
1136 // previous FLV tag. Use the timestamp of its payload as duration.
1137 int64_t fsize = avio_size(s->pb);
1139 avio_seek(s->pb, fsize - 4, SEEK_SET);
1140 size = avio_rb32(s->pb);
1141 if (size > 0 && size < fsize) {
1142 // Seek to the start of the last FLV tag at position (fsize - 4 - size)
1143 // but skip the byte indicating the type.
1144 avio_seek(s->pb, fsize - 3 - size, SEEK_SET);
1145 if (size == avio_rb24(s->pb) + 11) {
1146 uint32_t ts = avio_rb24(s->pb);
1147 ts |= avio_r8(s->pb) << 24;
1149 s->duration = ts * (int64_t)AV_TIME_BASE / 1000;
1150 else if (fsize >= 8 && fsize - 8 >= size) {
1152 goto retry_duration;
1157 avio_seek(s->pb, pos, SEEK_SET);
1158 flv->searched_for_end = 1;
1161 if (stream_type == FLV_STREAM_TYPE_AUDIO) {
1162 int bits_per_coded_sample;
1163 channels = (flags & FLV_AUDIO_CHANNEL_MASK) == FLV_STEREO ? 2 : 1;
1164 sample_rate = 44100 << ((flags & FLV_AUDIO_SAMPLERATE_MASK) >>
1165 FLV_AUDIO_SAMPLERATE_OFFSET) >> 3;
1166 bits_per_coded_sample = (flags & FLV_AUDIO_SAMPLESIZE_MASK) ? 16 : 8;
1167 if (!st->codecpar->channels || !st->codecpar->sample_rate ||
1168 !st->codecpar->bits_per_coded_sample) {
1169 st->codecpar->channels = channels;
1170 st->codecpar->channel_layout = channels == 1
1172 : AV_CH_LAYOUT_STEREO;
1173 st->codecpar->sample_rate = sample_rate;
1174 st->codecpar->bits_per_coded_sample = bits_per_coded_sample;
1176 if (!st->codecpar->codec_id) {
1177 flv_set_audio_codec(s, st, st->codecpar,
1178 flags & FLV_AUDIO_CODECID_MASK);
1179 flv->last_sample_rate =
1180 sample_rate = st->codecpar->sample_rate;
1181 flv->last_channels =
1182 channels = st->codecpar->channels;
1184 AVCodecParameters *par = avcodec_parameters_alloc();
1186 ret = AVERROR(ENOMEM);
1189 par->sample_rate = sample_rate;
1190 par->bits_per_coded_sample = bits_per_coded_sample;
1191 flv_set_audio_codec(s, st, par, flags & FLV_AUDIO_CODECID_MASK);
1192 sample_rate = par->sample_rate;
1193 avcodec_parameters_free(&par);
1195 } else if (stream_type == FLV_STREAM_TYPE_VIDEO) {
1196 int ret = flv_set_video_codec(s, st, flags & FLV_VIDEO_CODECID_MASK, 1);
1200 } else if (stream_type == FLV_STREAM_TYPE_SUBTITLE) {
1201 st->codecpar->codec_id = AV_CODEC_ID_TEXT;
1202 } else if (stream_type == FLV_STREAM_TYPE_DATA) {
1203 st->codecpar->codec_id = AV_CODEC_ID_NONE; // Opaque AMF data
1206 if (st->codecpar->codec_id == AV_CODEC_ID_AAC ||
1207 st->codecpar->codec_id == AV_CODEC_ID_H264 ||
1208 st->codecpar->codec_id == AV_CODEC_ID_MPEG4) {
1209 int type = avio_r8(s->pb);
1213 ret = AVERROR_INVALIDDATA;
1217 if (st->codecpar->codec_id == AV_CODEC_ID_H264 || st->codecpar->codec_id == AV_CODEC_ID_MPEG4) {
1219 int32_t cts = (avio_rb24(s->pb) + 0xff800000) ^ 0xff800000;
1221 if (cts < 0) { // dts might be wrong
1222 if (!flv->wrong_dts)
1223 av_log(s, AV_LOG_WARNING,
1224 "Negative cts, previous timestamps might be wrong.\n");
1226 } else if (FFABS(dts - pts) > 1000*60*15) {
1227 av_log(s, AV_LOG_WARNING,
1228 "invalid timestamps %"PRId64" %"PRId64"\n", dts, pts);
1229 dts = pts = AV_NOPTS_VALUE;
1232 if (type == 0 && (!st->codecpar->extradata || st->codecpar->codec_id == AV_CODEC_ID_AAC ||
1233 st->codecpar->codec_id == AV_CODEC_ID_H264)) {
1234 AVDictionaryEntry *t;
1236 if (st->codecpar->extradata) {
1237 if ((ret = flv_queue_extradata(flv, s->pb, stream_type, size)) < 0)
1242 if ((ret = flv_get_extradata(s, st, size)) < 0)
1245 /* Workaround for buggy Omnia A/XE encoder */
1246 t = av_dict_get(s->metadata, "Encoder", NULL, 0);
1247 if (st->codecpar->codec_id == AV_CODEC_ID_AAC && t && !strcmp(t->value, "Omnia A/XE"))
1248 st->codecpar->extradata_size = 2;
1250 if (st->codecpar->codec_id == AV_CODEC_ID_AAC && 0) {
1251 MPEG4AudioConfig cfg;
1253 if (avpriv_mpeg4audio_get_config(&cfg, st->codecpar->extradata,
1254 st->codecpar->extradata_size * 8, 1) >= 0) {
1255 st->codecpar->channels = cfg.channels;
1256 st->codecpar->channel_layout = 0;
1257 if (cfg.ext_sample_rate)
1258 st->codecpar->sample_rate = cfg.ext_sample_rate;
1260 st->codecpar->sample_rate = cfg.sample_rate;
1261 av_log(s, AV_LOG_TRACE, "mp4a config channels %d sample rate %d\n",
1262 st->codecpar->channels, st->codecpar->sample_rate);
1271 /* skip empty data packets */
1277 ret = av_get_packet(s->pb, pkt, size);
1281 pkt->pts = pts == AV_NOPTS_VALUE ? dts : pts;
1282 pkt->stream_index = st->index;
1284 if (flv->new_extradata[stream_type]) {
1285 uint8_t *side = av_packet_new_side_data(pkt, AV_PKT_DATA_NEW_EXTRADATA,
1286 flv->new_extradata_size[stream_type]);
1288 memcpy(side, flv->new_extradata[stream_type],
1289 flv->new_extradata_size[stream_type]);
1290 av_freep(&flv->new_extradata[stream_type]);
1291 flv->new_extradata_size[stream_type] = 0;
1294 if (stream_type == FLV_STREAM_TYPE_AUDIO &&
1295 (sample_rate != flv->last_sample_rate ||
1296 channels != flv->last_channels)) {
1297 flv->last_sample_rate = sample_rate;
1298 flv->last_channels = channels;
1299 ff_add_param_change(pkt, channels, 0, sample_rate, 0, 0);
1302 if ( stream_type == FLV_STREAM_TYPE_AUDIO ||
1303 ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY) ||
1304 stream_type == FLV_STREAM_TYPE_SUBTITLE ||
1305 stream_type == FLV_STREAM_TYPE_DATA)
1306 pkt->flags |= AV_PKT_FLAG_KEY;
1309 last = avio_rb32(s->pb);
1310 if (!flv->trust_datasize) {
1311 if (last != orig_size + 11 && last != orig_size + 10 &&
1312 !avio_feof(s->pb) &&
1313 (last != orig_size || !last) && last != flv->sum_flv_tag_size &&
1314 !flv->broken_sizes) {
1315 av_log(s, AV_LOG_ERROR, "Packet mismatch %d %d %d\n", last, orig_size + 11, flv->sum_flv_tag_size);
1316 avio_seek(s->pb, pos + 1, SEEK_SET);
1318 av_packet_unref(pkt);
1326 flv->last_ts = pkt->dts;
1331 static int flv_read_seek(AVFormatContext *s, int stream_index,
1332 int64_t ts, int flags)
1334 FLVContext *flv = s->priv_data;
1335 flv->validate_count = 0;
1336 return avio_seek_time(s->pb, stream_index, ts, flags);
1339 #define OFFSET(x) offsetof(FLVContext, x)
1340 #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
1341 static const AVOption options[] = {
1342 { "flv_metadata", "Allocate streams according to the onMetaData array", OFFSET(trust_metadata), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VD },
1343 { "flv_full_metadata", "Dump full metadata of the onMetadata", OFFSET(dump_full_metadata), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VD },
1344 { "flv_ignore_prevtag", "Ignore the Size of previous tag", OFFSET(trust_datasize), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VD },
1345 { "missing_streams", "", OFFSET(missing_streams), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 0xFF, VD | AV_OPT_FLAG_EXPORT | AV_OPT_FLAG_READONLY },
1349 static const AVClass flv_class = {
1350 .class_name = "flvdec",
1351 .item_name = av_default_item_name,
1353 .version = LIBAVUTIL_VERSION_INT,
1356 AVInputFormat ff_flv_demuxer = {
1358 .long_name = NULL_IF_CONFIG_SMALL("FLV (Flash Video)"),
1359 .priv_data_size = sizeof(FLVContext),
1360 .read_probe = 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 = &flv_class,
1369 static const AVClass live_flv_class = {
1370 .class_name = "live_flvdec",
1371 .item_name = av_default_item_name,
1373 .version = LIBAVUTIL_VERSION_INT,
1376 AVInputFormat ff_live_flv_demuxer = {
1378 .long_name = NULL_IF_CONFIG_SMALL("live RTMP FLV (Flash Video)"),
1379 .priv_data_size = sizeof(FLVContext),
1380 .read_probe = live_flv_probe,
1381 .read_header = flv_read_header,
1382 .read_packet = flv_read_packet,
1383 .read_seek = flv_read_seek,
1384 .read_close = flv_read_close,
1385 .extensions = "flv",
1386 .priv_class = &live_flv_class,
1387 .flags = AVFMT_TS_DISCONT