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 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];
65 int last_keyframe_stream_index;
67 int64_t video_bit_rate;
68 int64_t audio_bit_rate;
69 int64_t *keyframe_times;
70 int64_t *keyframe_filepositions;
75 static int probe(AVProbeData *p, int live)
77 const uint8_t *d = p->buf;
78 unsigned offset = AV_RB32(d + 5);
83 d[3] < 5 && d[5] == 0 &&
84 offset + 100 < p->buf_size &&
86 int is_live = !memcmp(d + offset + 40, "NGINX RTMP", 10);
89 return AVPROBE_SCORE_MAX;
94 static int flv_probe(AVProbeData *p)
99 static int live_flv_probe(AVProbeData *p)
104 static void add_keyframes_index(AVFormatContext *s)
106 FLVContext *flv = s->priv_data;
107 AVStream *stream = NULL;
110 if (flv->last_keyframe_stream_index < 0) {
111 av_log(s, AV_LOG_DEBUG, "keyframe stream hasn't been created\n");
115 av_assert0(flv->last_keyframe_stream_index <= s->nb_streams);
116 stream = s->streams[flv->last_keyframe_stream_index];
118 if (stream->nb_index_entries == 0) {
119 for (i = 0; i < flv->keyframe_count; i++) {
120 av_log(s, AV_LOG_TRACE, "keyframe filepositions = %"PRId64" times = %"PRId64"\n",
121 flv->keyframe_filepositions[i], flv->keyframe_times[i] * 1000);
122 av_add_index_entry(stream, flv->keyframe_filepositions[i],
123 flv->keyframe_times[i] * 1000, 0, 0, AVINDEX_KEYFRAME);
126 av_log(s, AV_LOG_WARNING, "Skipping duplicate index\n");
128 if (stream->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
129 av_freep(&flv->keyframe_times);
130 av_freep(&flv->keyframe_filepositions);
131 flv->keyframe_count = 0;
135 static AVStream *create_stream(AVFormatContext *s, int codec_type)
137 FLVContext *flv = s->priv_data;
138 AVStream *st = avformat_new_stream(s, NULL);
141 st->codecpar->codec_type = codec_type;
142 if (s->nb_streams>=3 ||( s->nb_streams==2
143 && s->streams[0]->codecpar->codec_type != AVMEDIA_TYPE_SUBTITLE
144 && s->streams[1]->codecpar->codec_type != AVMEDIA_TYPE_SUBTITLE))
145 s->ctx_flags &= ~AVFMTCTX_NOHEADER;
146 if (codec_type == AVMEDIA_TYPE_AUDIO) {
147 st->codecpar->bit_rate = flv->audio_bit_rate;
148 flv->missing_streams &= ~FLV_HEADER_FLAG_HASAUDIO;
150 if (codec_type == AVMEDIA_TYPE_VIDEO) {
151 st->codecpar->bit_rate = flv->video_bit_rate;
152 flv->missing_streams &= ~FLV_HEADER_FLAG_HASVIDEO;
153 st->avg_frame_rate = flv->framerate;
157 avpriv_set_pts_info(st, 32, 1, 1000); /* 32 bit pts in ms */
158 flv->last_keyframe_stream_index = s->nb_streams - 1;
159 add_keyframes_index(s);
163 static int flv_same_audio_codec(AVCodecParameters *apar, int flags)
165 int bits_per_coded_sample = (flags & FLV_AUDIO_SAMPLESIZE_MASK) ? 16 : 8;
166 int flv_codecid = flags & FLV_AUDIO_CODECID_MASK;
169 if (!apar->codec_id && !apar->codec_tag)
172 if (apar->bits_per_coded_sample != bits_per_coded_sample)
175 switch (flv_codecid) {
176 // no distinction between S16 and S8 PCM codec flags
177 case FLV_CODECID_PCM:
178 codec_id = bits_per_coded_sample == 8
181 : AV_CODEC_ID_PCM_S16BE;
183 : AV_CODEC_ID_PCM_S16LE;
185 return codec_id == apar->codec_id;
186 case FLV_CODECID_PCM_LE:
187 codec_id = bits_per_coded_sample == 8
189 : AV_CODEC_ID_PCM_S16LE;
190 return codec_id == apar->codec_id;
191 case FLV_CODECID_AAC:
192 return apar->codec_id == AV_CODEC_ID_AAC;
193 case FLV_CODECID_ADPCM:
194 return apar->codec_id == AV_CODEC_ID_ADPCM_SWF;
195 case FLV_CODECID_SPEEX:
196 return apar->codec_id == AV_CODEC_ID_SPEEX;
197 case FLV_CODECID_MP3:
198 return apar->codec_id == AV_CODEC_ID_MP3;
199 case FLV_CODECID_NELLYMOSER_8KHZ_MONO:
200 case FLV_CODECID_NELLYMOSER_16KHZ_MONO:
201 case FLV_CODECID_NELLYMOSER:
202 return apar->codec_id == AV_CODEC_ID_NELLYMOSER;
203 case FLV_CODECID_PCM_MULAW:
204 return apar->sample_rate == 8000 &&
205 apar->codec_id == AV_CODEC_ID_PCM_MULAW;
206 case FLV_CODECID_PCM_ALAW:
207 return apar->sample_rate == 8000 &&
208 apar->codec_id == AV_CODEC_ID_PCM_ALAW;
210 return apar->codec_tag == (flv_codecid >> FLV_AUDIO_CODECID_OFFSET);
214 static void flv_set_audio_codec(AVFormatContext *s, AVStream *astream,
215 AVCodecParameters *apar, int flv_codecid)
217 switch (flv_codecid) {
218 // no distinction between S16 and S8 PCM codec flags
219 case FLV_CODECID_PCM:
220 apar->codec_id = apar->bits_per_coded_sample == 8
223 : AV_CODEC_ID_PCM_S16BE;
225 : AV_CODEC_ID_PCM_S16LE;
228 case FLV_CODECID_PCM_LE:
229 apar->codec_id = apar->bits_per_coded_sample == 8
231 : AV_CODEC_ID_PCM_S16LE;
233 case FLV_CODECID_AAC:
234 apar->codec_id = AV_CODEC_ID_AAC;
236 case FLV_CODECID_ADPCM:
237 apar->codec_id = AV_CODEC_ID_ADPCM_SWF;
239 case FLV_CODECID_SPEEX:
240 apar->codec_id = AV_CODEC_ID_SPEEX;
241 apar->sample_rate = 16000;
243 case FLV_CODECID_MP3:
244 apar->codec_id = AV_CODEC_ID_MP3;
245 astream->need_parsing = AVSTREAM_PARSE_FULL;
247 case FLV_CODECID_NELLYMOSER_8KHZ_MONO:
248 // in case metadata does not otherwise declare samplerate
249 apar->sample_rate = 8000;
250 apar->codec_id = AV_CODEC_ID_NELLYMOSER;
252 case FLV_CODECID_NELLYMOSER_16KHZ_MONO:
253 apar->sample_rate = 16000;
254 apar->codec_id = AV_CODEC_ID_NELLYMOSER;
256 case FLV_CODECID_NELLYMOSER:
257 apar->codec_id = AV_CODEC_ID_NELLYMOSER;
259 case FLV_CODECID_PCM_MULAW:
260 apar->sample_rate = 8000;
261 apar->codec_id = AV_CODEC_ID_PCM_MULAW;
263 case FLV_CODECID_PCM_ALAW:
264 apar->sample_rate = 8000;
265 apar->codec_id = AV_CODEC_ID_PCM_ALAW;
268 avpriv_request_sample(s, "Audio codec (%x)",
269 flv_codecid >> FLV_AUDIO_CODECID_OFFSET);
270 apar->codec_tag = flv_codecid >> FLV_AUDIO_CODECID_OFFSET;
274 static int flv_same_video_codec(AVCodecParameters *vpar, int flags)
276 int flv_codecid = flags & FLV_VIDEO_CODECID_MASK;
278 if (!vpar->codec_id && !vpar->codec_tag)
281 switch (flv_codecid) {
282 case FLV_CODECID_H263:
283 return vpar->codec_id == AV_CODEC_ID_FLV1;
284 case FLV_CODECID_SCREEN:
285 return vpar->codec_id == AV_CODEC_ID_FLASHSV;
286 case FLV_CODECID_SCREEN2:
287 return vpar->codec_id == AV_CODEC_ID_FLASHSV2;
288 case FLV_CODECID_VP6:
289 return vpar->codec_id == AV_CODEC_ID_VP6F;
290 case FLV_CODECID_VP6A:
291 return vpar->codec_id == AV_CODEC_ID_VP6A;
292 case FLV_CODECID_H264:
293 return vpar->codec_id == AV_CODEC_ID_H264;
295 return vpar->codec_tag == flv_codecid;
299 static int flv_set_video_codec(AVFormatContext *s, AVStream *vstream,
300 int flv_codecid, int read)
303 AVCodecParameters *par = vstream->codecpar;
304 enum AVCodecID old_codec_id = vstream->codecpar->codec_id;
305 switch (flv_codecid) {
306 case FLV_CODECID_H263:
307 par->codec_id = AV_CODEC_ID_FLV1;
309 case FLV_CODECID_REALH263:
310 par->codec_id = AV_CODEC_ID_H263;
311 break; // Really mean it this time
312 case FLV_CODECID_SCREEN:
313 par->codec_id = AV_CODEC_ID_FLASHSV;
315 case FLV_CODECID_SCREEN2:
316 par->codec_id = AV_CODEC_ID_FLASHSV2;
318 case FLV_CODECID_VP6:
319 par->codec_id = AV_CODEC_ID_VP6F;
320 case FLV_CODECID_VP6A:
321 if (flv_codecid == FLV_CODECID_VP6A)
322 par->codec_id = AV_CODEC_ID_VP6A;
324 if (par->extradata_size != 1) {
325 ff_alloc_extradata(par, 1);
328 par->extradata[0] = avio_r8(s->pb);
332 ret = 1; // 1 byte body size adjustment for flv_read_packet()
334 case FLV_CODECID_H264:
335 par->codec_id = AV_CODEC_ID_H264;
336 vstream->need_parsing = AVSTREAM_PARSE_HEADERS;
337 ret = 3; // not 4, reading packet type will consume one byte
339 case FLV_CODECID_MPEG4:
340 par->codec_id = AV_CODEC_ID_MPEG4;
344 avpriv_request_sample(s, "Video codec (%x)", flv_codecid);
345 par->codec_tag = flv_codecid;
348 if (!vstream->internal->need_context_update && par->codec_id != old_codec_id) {
349 avpriv_request_sample(s, "Changing the codec id midstream");
350 return AVERROR_PATCHWELCOME;
356 static int amf_get_string(AVIOContext *ioc, char *buffer, int buffsize)
358 int length = avio_rb16(ioc);
359 if (length >= buffsize) {
360 avio_skip(ioc, length);
364 avio_read(ioc, buffer, length);
366 buffer[length] = '\0';
371 static int parse_keyframes_index(AVFormatContext *s, AVIOContext *ioc, int64_t max_pos)
373 FLVContext *flv = s->priv_data;
374 unsigned int timeslen = 0, fileposlen = 0, i;
376 int64_t *times = NULL;
377 int64_t *filepositions = NULL;
378 int ret = AVERROR(ENOSYS);
379 int64_t initial_pos = avio_tell(ioc);
381 if (flv->keyframe_count > 0) {
382 av_log(s, AV_LOG_DEBUG, "keyframes have been paresed\n");
385 av_assert0(!flv->keyframe_times);
386 av_assert0(!flv->keyframe_filepositions);
388 if (s->flags & AVFMT_FLAG_IGNIDX)
391 while (avio_tell(ioc) < max_pos - 2 &&
392 amf_get_string(ioc, str_val, sizeof(str_val)) > 0) {
393 int64_t **current_array;
394 unsigned int arraylen;
396 // Expect array object in context
397 if (avio_r8(ioc) != AMF_DATA_TYPE_ARRAY)
400 arraylen = avio_rb32(ioc);
404 if (!strcmp(KEYFRAMES_TIMESTAMP_TAG , str_val) && !times) {
405 current_array = ×
407 } else if (!strcmp(KEYFRAMES_BYTEOFFSET_TAG, str_val) &&
409 current_array = &filepositions;
410 fileposlen = arraylen;
412 // unexpected metatag inside keyframes, will not use such
413 // metadata for indexing
416 if (!(*current_array = av_mallocz(sizeof(**current_array) * arraylen))) {
417 ret = AVERROR(ENOMEM);
421 for (i = 0; i < arraylen && avio_tell(ioc) < max_pos - 1; i++) {
422 if (avio_r8(ioc) != AMF_DATA_TYPE_NUMBER)
424 current_array[0][i] = av_int2double(avio_rb64(ioc));
426 if (times && filepositions) {
427 // All done, exiting at a position allowing amf_parse_object
428 // to finish parsing the object
434 if (timeslen == fileposlen && fileposlen>1 && max_pos <= filepositions[0]) {
435 for (i = 0; i < FFMIN(2,fileposlen); i++) {
436 flv->validate_index[i].pos = filepositions[i];
437 flv->validate_index[i].dts = times[i] * 1000;
438 flv->validate_count = i + 1;
440 flv->keyframe_times = times;
441 flv->keyframe_filepositions = filepositions;
442 flv->keyframe_count = timeslen;
444 filepositions = NULL;
447 av_log(s, AV_LOG_WARNING, "Invalid keyframes object, skipping.\n");
452 av_freep(&filepositions);
453 avio_seek(ioc, initial_pos, SEEK_SET);
457 static int amf_parse_object(AVFormatContext *s, AVStream *astream,
458 AVStream *vstream, const char *key,
459 int64_t max_pos, int depth)
461 AVCodecParameters *apar, *vpar;
462 FLVContext *flv = s->priv_data;
464 AMFDataType amf_type;
470 amf_type = avio_r8(ioc);
473 case AMF_DATA_TYPE_NUMBER:
474 num_val = av_int2double(avio_rb64(ioc));
476 case AMF_DATA_TYPE_BOOL:
477 num_val = avio_r8(ioc);
479 case AMF_DATA_TYPE_STRING:
480 if (amf_get_string(ioc, str_val, sizeof(str_val)) < 0) {
481 av_log(s, AV_LOG_ERROR, "AMF_DATA_TYPE_STRING parsing failed\n");
485 case AMF_DATA_TYPE_OBJECT:
487 (ioc->seekable & AVIO_SEEKABLE_NORMAL) &&
488 !strcmp(KEYFRAMES_TAG, key) && depth == 1)
489 if (parse_keyframes_index(s, ioc,
491 av_log(s, AV_LOG_ERROR, "Keyframe index parsing failed\n");
493 add_keyframes_index(s);
494 while (avio_tell(ioc) < max_pos - 2 &&
495 amf_get_string(ioc, str_val, sizeof(str_val)) > 0)
496 if (amf_parse_object(s, astream, vstream, str_val, max_pos,
498 return -1; // if we couldn't skip, bomb out.
499 if (avio_r8(ioc) != AMF_END_OF_OBJECT) {
500 av_log(s, AV_LOG_ERROR, "Missing AMF_END_OF_OBJECT in AMF_DATA_TYPE_OBJECT\n");
504 case AMF_DATA_TYPE_NULL:
505 case AMF_DATA_TYPE_UNDEFINED:
506 case AMF_DATA_TYPE_UNSUPPORTED:
507 break; // these take up no additional space
508 case AMF_DATA_TYPE_MIXEDARRAY:
511 avio_skip(ioc, 4); // skip 32-bit max array index
512 while (avio_tell(ioc) < max_pos - 2 &&
513 amf_get_string(ioc, str_val, sizeof(str_val)) > 0)
514 // this is the only case in which we would want a nested
515 // parse to not skip over the object
516 if (amf_parse_object(s, astream, vstream, str_val, max_pos,
520 if (v != AMF_END_OF_OBJECT) {
521 av_log(s, AV_LOG_ERROR, "Missing AMF_END_OF_OBJECT in AMF_DATA_TYPE_MIXEDARRAY, found %d\n", v);
526 case AMF_DATA_TYPE_ARRAY:
528 unsigned int arraylen, i;
530 arraylen = avio_rb32(ioc);
531 for (i = 0; i < arraylen && avio_tell(ioc) < max_pos - 1; i++)
532 if (amf_parse_object(s, NULL, NULL, NULL, max_pos,
534 return -1; // if we couldn't skip, bomb out.
537 case AMF_DATA_TYPE_DATE:
538 avio_skip(ioc, 8 + 2); // timestamp (double) and UTC offset (int16)
540 default: // unsupported type, we couldn't skip
541 av_log(s, AV_LOG_ERROR, "unsupported amf type %d\n", amf_type);
546 apar = astream ? astream->codecpar : NULL;
547 vpar = vstream ? vstream->codecpar : NULL;
549 // stream info doesn't live any deeper than the first object
551 if (amf_type == AMF_DATA_TYPE_NUMBER ||
552 amf_type == AMF_DATA_TYPE_BOOL) {
553 if (!strcmp(key, "duration"))
554 s->duration = num_val * AV_TIME_BASE;
555 else if (!strcmp(key, "videodatarate") &&
556 0 <= (int)(num_val * 1024.0))
557 flv->video_bit_rate = num_val * 1024.0;
558 else if (!strcmp(key, "audiodatarate") &&
559 0 <= (int)(num_val * 1024.0))
560 flv->audio_bit_rate = num_val * 1024.0;
561 else if (!strcmp(key, "datastream")) {
562 AVStream *st = create_stream(s, AVMEDIA_TYPE_SUBTITLE);
564 return AVERROR(ENOMEM);
565 st->codecpar->codec_id = AV_CODEC_ID_TEXT;
566 } else if (!strcmp(key, "framerate")) {
567 flv->framerate = av_d2q(num_val, 1000);
569 vstream->avg_frame_rate = flv->framerate;
570 } else if (flv->trust_metadata) {
571 if (!strcmp(key, "videocodecid") && vpar) {
572 int ret = flv_set_video_codec(s, vstream, num_val, 0);
575 } else if (!strcmp(key, "audiocodecid") && apar) {
576 int id = ((int)num_val) << FLV_AUDIO_CODECID_OFFSET;
577 flv_set_audio_codec(s, astream, apar, id);
578 } else if (!strcmp(key, "audiosamplerate") && apar) {
579 apar->sample_rate = num_val;
580 } else if (!strcmp(key, "audiosamplesize") && apar) {
581 apar->bits_per_coded_sample = num_val;
582 } else if (!strcmp(key, "stereo") && apar) {
583 apar->channels = num_val + 1;
584 apar->channel_layout = apar->channels == 2 ?
585 AV_CH_LAYOUT_STEREO :
587 } else if (!strcmp(key, "width") && vpar) {
588 vpar->width = num_val;
589 } else if (!strcmp(key, "height") && vpar) {
590 vpar->height = num_val;
594 if (amf_type == AMF_DATA_TYPE_STRING) {
595 if (!strcmp(key, "encoder")) {
597 if (1 == sscanf(str_val, "Open Broadcaster Software v0.%d", &version)) {
598 if (version > 0 && version <= 655)
599 flv->broken_sizes = 1;
601 } else if (!strcmp(key, "metadatacreator")) {
602 if ( !strcmp (str_val, "MEGA")
603 || !strncmp(str_val, "FlixEngine", 10))
604 flv->broken_sizes = 1;
609 if (amf_type == AMF_DATA_TYPE_OBJECT && s->nb_streams == 1 &&
610 ((!apar && !strcmp(key, "audiocodecid")) ||
611 (!vpar && !strcmp(key, "videocodecid"))))
612 s->ctx_flags &= ~AVFMTCTX_NOHEADER; //If there is either audio/video missing, codecid will be an empty object
614 if (!strcmp(key, "duration") ||
615 !strcmp(key, "filesize") ||
616 !strcmp(key, "width") ||
617 !strcmp(key, "height") ||
618 !strcmp(key, "videodatarate") ||
619 !strcmp(key, "framerate") ||
620 !strcmp(key, "videocodecid") ||
621 !strcmp(key, "audiodatarate") ||
622 !strcmp(key, "audiosamplerate") ||
623 !strcmp(key, "audiosamplesize") ||
624 !strcmp(key, "stereo") ||
625 !strcmp(key, "audiocodecid") ||
626 !strcmp(key, "datastream"))
629 s->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
630 if (amf_type == AMF_DATA_TYPE_BOOL) {
631 av_strlcpy(str_val, num_val > 0 ? "true" : "false",
633 av_dict_set(&s->metadata, key, str_val, 0);
634 } else if (amf_type == AMF_DATA_TYPE_NUMBER) {
635 snprintf(str_val, sizeof(str_val), "%.f", num_val);
636 av_dict_set(&s->metadata, key, str_val, 0);
637 } else if (amf_type == AMF_DATA_TYPE_STRING)
638 av_dict_set(&s->metadata, key, str_val, 0);
644 #define TYPE_ONTEXTDATA 1
645 #define TYPE_ONCAPTION 2
646 #define TYPE_ONCAPTIONINFO 3
647 #define TYPE_UNKNOWN 9
649 static int flv_read_metabody(AVFormatContext *s, int64_t next_pos)
651 FLVContext *flv = s->priv_data;
653 AVStream *stream, *astream, *vstream;
654 AVStream av_unused *dstream;
657 // only needs to hold the string "onMetaData".
658 // Anything longer is something we don't want.
666 // first object needs to be "onMetaData" string
668 if (type != AMF_DATA_TYPE_STRING ||
669 amf_get_string(ioc, buffer, sizeof(buffer)) < 0)
672 if (!strcmp(buffer, "onTextData"))
673 return TYPE_ONTEXTDATA;
675 if (!strcmp(buffer, "onCaption"))
676 return TYPE_ONCAPTION;
678 if (!strcmp(buffer, "onCaptionInfo"))
679 return TYPE_ONCAPTIONINFO;
681 if (strcmp(buffer, "onMetaData") && strcmp(buffer, "onCuePoint")) {
682 av_log(s, AV_LOG_DEBUG, "Unknown type %s\n", buffer);
686 // find the streams now so that amf_parse_object doesn't need to do
687 // the lookup every time it is called.
688 for (i = 0; i < s->nb_streams; i++) {
689 stream = s->streams[i];
690 if (stream->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
692 flv->last_keyframe_stream_index = i;
693 } else if (stream->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
695 if (flv->last_keyframe_stream_index == -1)
696 flv->last_keyframe_stream_index = i;
698 else if (stream->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE)
702 // parse the second object (we want a mixed array)
703 if (amf_parse_object(s, astream, vstream, buffer, next_pos, 0) < 0)
709 static int flv_read_header(AVFormatContext *s)
712 FLVContext *flv = s->priv_data;
714 int pre_tag_size = 0;
717 flags = avio_r8(s->pb);
719 flv->missing_streams = flags & (FLV_HEADER_FLAG_HASVIDEO | FLV_HEADER_FLAG_HASAUDIO);
721 s->ctx_flags |= AVFMTCTX_NOHEADER;
723 offset = avio_rb32(s->pb);
724 avio_seek(s->pb, offset, SEEK_SET);
726 /* Annex E. The FLV File Format
729 * PreviousTagSize0 UI32 Always 0
731 pre_tag_size = avio_rb32(s->pb);
733 av_log(s, AV_LOG_WARNING, "Read FLV header error, input file is not a standard flv format, first PreviousTagSize0 always is 0\n");
737 flv->sum_flv_tag_size = 0;
738 flv->last_keyframe_stream_index = -1;
743 static int flv_read_close(AVFormatContext *s)
746 FLVContext *flv = s->priv_data;
747 for (i=0; i<FLV_STREAM_TYPE_NB; i++)
748 av_freep(&flv->new_extradata[i]);
749 av_freep(&flv->keyframe_times);
750 av_freep(&flv->keyframe_filepositions);
754 static int flv_get_extradata(AVFormatContext *s, AVStream *st, int size)
756 av_freep(&st->codecpar->extradata);
757 if (ff_get_extradata(s, st->codecpar, s->pb, size) < 0)
758 return AVERROR(ENOMEM);
759 st->internal->need_context_update = 1;
763 static int flv_queue_extradata(FLVContext *flv, AVIOContext *pb, int stream,
766 av_free(flv->new_extradata[stream]);
767 flv->new_extradata[stream] = av_mallocz(size +
768 AV_INPUT_BUFFER_PADDING_SIZE);
769 if (!flv->new_extradata[stream])
770 return AVERROR(ENOMEM);
771 flv->new_extradata_size[stream] = size;
772 avio_read(pb, flv->new_extradata[stream], size);
776 static void clear_index_entries(AVFormatContext *s, int64_t pos)
779 av_log(s, AV_LOG_WARNING,
780 "Found invalid index entries, clearing the index.\n");
781 for (i = 0; i < s->nb_streams; i++) {
782 AVStream *st = s->streams[i];
783 /* Remove all index entries that point to >= pos */
785 for (j = 0; j < st->nb_index_entries; j++)
786 if (st->index_entries[j].pos < pos)
787 st->index_entries[out++] = st->index_entries[j];
788 st->nb_index_entries = out;
792 static int amf_skip_tag(AVIOContext *pb, AMFDataType type)
794 int nb = -1, ret, parse_name = 1;
797 case AMF_DATA_TYPE_NUMBER:
800 case AMF_DATA_TYPE_BOOL:
803 case AMF_DATA_TYPE_STRING:
804 avio_skip(pb, avio_rb16(pb));
806 case AMF_DATA_TYPE_ARRAY:
808 case AMF_DATA_TYPE_MIXEDARRAY:
810 case AMF_DATA_TYPE_OBJECT:
811 while(!pb->eof_reached && (nb-- > 0 || type != AMF_DATA_TYPE_ARRAY)) {
813 int size = avio_rb16(pb);
820 if ((ret = amf_skip_tag(pb, avio_r8(pb))) < 0)
824 case AMF_DATA_TYPE_NULL:
825 case AMF_DATA_TYPE_OBJECT_END:
828 return AVERROR_INVALIDDATA;
833 static int flv_data_packet(AVFormatContext *s, AVPacket *pkt,
834 int64_t dts, int64_t next)
836 AVIOContext *pb = s->pb;
839 int ret = AVERROR_INVALIDDATA;
843 switch (avio_r8(pb)) {
844 case AMF_DATA_TYPE_ARRAY:
846 case AMF_DATA_TYPE_MIXEDARRAY:
847 avio_seek(pb, 4, SEEK_CUR);
848 case AMF_DATA_TYPE_OBJECT:
854 while (array || (ret = amf_get_string(pb, buf, sizeof(buf))) > 0) {
855 AMFDataType type = avio_r8(pb);
856 if (type == AMF_DATA_TYPE_STRING && (array || !strcmp(buf, "text"))) {
857 length = avio_rb16(pb);
858 ret = av_get_packet(pb, pkt, length);
864 if ((ret = amf_skip_tag(pb, type)) < 0)
870 ret = AVERROR_INVALIDDATA;
874 for (i = 0; i < s->nb_streams; i++) {
876 if (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE)
880 if (i == s->nb_streams) {
881 st = create_stream(s, AVMEDIA_TYPE_SUBTITLE);
883 return AVERROR(ENOMEM);
884 st->codecpar->codec_id = AV_CODEC_ID_TEXT;
891 pkt->stream_index = st->index;
892 pkt->flags |= AV_PKT_FLAG_KEY;
895 avio_seek(s->pb, next + 4, SEEK_SET);
900 static int resync(AVFormatContext *s)
902 FLVContext *flv = s->priv_data;
904 int64_t pos = avio_tell(s->pb);
906 for (i=0; !avio_feof(s->pb); i++) {
907 int j = i & (RESYNC_BUFFER_SIZE-1);
908 int j1 = j + RESYNC_BUFFER_SIZE;
909 flv->resync_buffer[j ] =
910 flv->resync_buffer[j1] = avio_r8(s->pb);
913 unsigned lsize2 = AV_RB32(flv->resync_buffer + j1 - 4);
914 if (lsize2 >= 11 && lsize2 + 8LL < FFMIN(i, RESYNC_BUFFER_SIZE)) {
915 unsigned size2 = AV_RB24(flv->resync_buffer + j1 - lsize2 + 1 - 4);
916 unsigned lsize1 = AV_RB32(flv->resync_buffer + j1 - lsize2 - 8);
917 if (lsize1 >= 11 && lsize1 + 8LL + lsize2 < FFMIN(i, RESYNC_BUFFER_SIZE)) {
918 unsigned size1 = AV_RB24(flv->resync_buffer + j1 - lsize1 + 1 - lsize2 - 8);
919 if (size1 == lsize1 - 11 && size2 == lsize2 - 11) {
920 avio_seek(s->pb, pos + i - lsize1 - lsize2 - 8, SEEK_SET);
930 static int flv_read_packet(AVFormatContext *s, AVPacket *pkt)
932 FLVContext *flv = s->priv_data;
933 int ret, i, size, flags;
934 enum FlvTagType type;
936 int64_t next, pos, meta_pos;
937 int64_t dts, pts = AV_NOPTS_VALUE;
938 int av_uninit(channels);
939 int av_uninit(sample_rate);
945 /* pkt size is repeated at end. skip it */
946 pos = avio_tell(s->pb);
947 type = (avio_r8(s->pb) & 0x1F);
949 size = avio_rb24(s->pb);
950 flv->sum_flv_tag_size += size + 11;
951 dts = avio_rb24(s->pb);
952 dts |= (unsigned)avio_r8(s->pb) << 24;
953 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));
954 if (avio_feof(s->pb))
956 avio_skip(s->pb, 3); /* stream id, always 0 */
959 if (flv->validate_next < flv->validate_count) {
960 int64_t validate_pos = flv->validate_index[flv->validate_next].pos;
961 if (pos == validate_pos) {
962 if (FFABS(dts - flv->validate_index[flv->validate_next].dts) <=
963 VALIDATE_INDEX_TS_THRESH) {
964 flv->validate_next++;
966 clear_index_entries(s, validate_pos);
967 flv->validate_count = 0;
969 } else if (pos > validate_pos) {
970 clear_index_entries(s, validate_pos);
971 flv->validate_count = 0;
980 next = size + avio_tell(s->pb);
982 if (type == FLV_TAG_TYPE_AUDIO) {
983 stream_type = FLV_STREAM_TYPE_AUDIO;
984 flags = avio_r8(s->pb);
986 } else if (type == FLV_TAG_TYPE_VIDEO) {
987 stream_type = FLV_STREAM_TYPE_VIDEO;
988 flags = avio_r8(s->pb);
990 if ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_VIDEO_INFO_CMD)
992 } else if (type == FLV_TAG_TYPE_META) {
993 stream_type=FLV_STREAM_TYPE_DATA;
994 if (size > 13 + 1 + 4) { // Header-type metadata stuff
996 meta_pos = avio_tell(s->pb);
997 type = flv_read_metabody(s, next);
998 if (type == 0 && dts == 0 || type < 0 || type == TYPE_UNKNOWN) {
999 if (type < 0 && flv->validate_count &&
1000 flv->validate_index[0].pos > next &&
1001 flv->validate_index[0].pos - 4 < next
1003 av_log(s, AV_LOG_WARNING, "Adjusting next position due to index mismatch\n");
1004 next = flv->validate_index[0].pos - 4;
1007 } else if (type == TYPE_ONTEXTDATA) {
1008 avpriv_request_sample(s, "OnTextData packet");
1009 return flv_data_packet(s, pkt, dts, next);
1010 } else if (type == TYPE_ONCAPTION) {
1011 return flv_data_packet(s, pkt, dts, next);
1013 avio_seek(s->pb, meta_pos, SEEK_SET);
1016 av_log(s, AV_LOG_DEBUG,
1017 "Skipping flv packet: type %d, size %d, flags %d.\n",
1020 if (avio_seek(s->pb, next, SEEK_SET) != next) {
1021 // This can happen if flv_read_metabody above read past
1022 // next, on a non-seekable input, and the preceding data has
1023 // been flushed out from the IO buffer.
1024 av_log(s, AV_LOG_ERROR, "Unable to seek to the next packet\n");
1025 return AVERROR_INVALIDDATA;
1031 /* skip empty data packets */
1037 /* now find stream */
1038 for (i = 0; i < s->nb_streams; i++) {
1040 if (stream_type == FLV_STREAM_TYPE_AUDIO) {
1041 if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO &&
1042 (s->audio_codec_id || flv_same_audio_codec(st->codecpar, flags)))
1044 } else if (stream_type == FLV_STREAM_TYPE_VIDEO) {
1045 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
1046 (s->video_codec_id || flv_same_video_codec(st->codecpar, flags)))
1048 } else if (stream_type == FLV_STREAM_TYPE_DATA) {
1049 if (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE)
1053 if (i == s->nb_streams) {
1054 static const enum AVMediaType stream_types[] = {AVMEDIA_TYPE_VIDEO, AVMEDIA_TYPE_AUDIO, AVMEDIA_TYPE_SUBTITLE};
1055 st = create_stream(s, stream_types[stream_type]);
1057 return AVERROR(ENOMEM);
1060 av_log(s, AV_LOG_TRACE, "%d %X %d \n", stream_type, flags, st->discard);
1062 if ((s->pb->seekable & AVIO_SEEKABLE_NORMAL) &&
1063 ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY ||
1064 stream_type == FLV_STREAM_TYPE_AUDIO))
1065 av_add_index_entry(st, pos, dts, size, 0, AVINDEX_KEYFRAME);
1067 if ( (st->discard >= AVDISCARD_NONKEY && !((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY || (stream_type == FLV_STREAM_TYPE_AUDIO)))
1068 ||(st->discard >= AVDISCARD_BIDIR && ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_DISP_INTER && (stream_type == FLV_STREAM_TYPE_VIDEO)))
1069 || st->discard >= AVDISCARD_ALL
1071 avio_seek(s->pb, next, SEEK_SET);
1076 // if not streamed and no duration from metadata then seek to end to find
1077 // the duration from the timestamps
1078 if ((s->pb->seekable & AVIO_SEEKABLE_NORMAL) &&
1079 (!s->duration || s->duration == AV_NOPTS_VALUE) &&
1080 !flv->searched_for_end) {
1082 const int64_t pos = avio_tell(s->pb);
1083 // Read the last 4 bytes of the file, this should be the size of the
1084 // previous FLV tag. Use the timestamp of its payload as duration.
1085 int64_t fsize = avio_size(s->pb);
1087 avio_seek(s->pb, fsize - 4, SEEK_SET);
1088 size = avio_rb32(s->pb);
1089 if (size > 0 && size < fsize) {
1090 // Seek to the start of the last FLV tag at position (fsize - 4 - size)
1091 // but skip the byte indicating the type.
1092 avio_seek(s->pb, fsize - 3 - size, SEEK_SET);
1093 if (size == avio_rb24(s->pb) + 11) {
1094 uint32_t ts = avio_rb24(s->pb);
1095 ts |= avio_r8(s->pb) << 24;
1097 s->duration = ts * (int64_t)AV_TIME_BASE / 1000;
1098 else if (fsize >= 8 && fsize - 8 >= size) {
1100 goto retry_duration;
1105 avio_seek(s->pb, pos, SEEK_SET);
1106 flv->searched_for_end = 1;
1109 if (stream_type == FLV_STREAM_TYPE_AUDIO) {
1110 int bits_per_coded_sample;
1111 channels = (flags & FLV_AUDIO_CHANNEL_MASK) == FLV_STEREO ? 2 : 1;
1112 sample_rate = 44100 << ((flags & FLV_AUDIO_SAMPLERATE_MASK) >>
1113 FLV_AUDIO_SAMPLERATE_OFFSET) >> 3;
1114 bits_per_coded_sample = (flags & FLV_AUDIO_SAMPLESIZE_MASK) ? 16 : 8;
1115 if (!st->codecpar->channels || !st->codecpar->sample_rate ||
1116 !st->codecpar->bits_per_coded_sample) {
1117 st->codecpar->channels = channels;
1118 st->codecpar->channel_layout = channels == 1
1120 : AV_CH_LAYOUT_STEREO;
1121 st->codecpar->sample_rate = sample_rate;
1122 st->codecpar->bits_per_coded_sample = bits_per_coded_sample;
1124 if (!st->codecpar->codec_id) {
1125 flv_set_audio_codec(s, st, st->codecpar,
1126 flags & FLV_AUDIO_CODECID_MASK);
1127 flv->last_sample_rate =
1128 sample_rate = st->codecpar->sample_rate;
1129 flv->last_channels =
1130 channels = st->codecpar->channels;
1132 AVCodecParameters *par = avcodec_parameters_alloc();
1134 ret = AVERROR(ENOMEM);
1137 par->sample_rate = sample_rate;
1138 par->bits_per_coded_sample = bits_per_coded_sample;
1139 flv_set_audio_codec(s, st, par, flags & FLV_AUDIO_CODECID_MASK);
1140 sample_rate = par->sample_rate;
1141 avcodec_parameters_free(&par);
1143 } else if (stream_type == FLV_STREAM_TYPE_VIDEO) {
1144 int ret = flv_set_video_codec(s, st, flags & FLV_VIDEO_CODECID_MASK, 1);
1148 } else if (stream_type == FLV_STREAM_TYPE_DATA) {
1149 st->codecpar->codec_id = AV_CODEC_ID_TEXT;
1152 if (st->codecpar->codec_id == AV_CODEC_ID_AAC ||
1153 st->codecpar->codec_id == AV_CODEC_ID_H264 ||
1154 st->codecpar->codec_id == AV_CODEC_ID_MPEG4) {
1155 int type = avio_r8(s->pb);
1159 ret = AVERROR_INVALIDDATA;
1163 if (st->codecpar->codec_id == AV_CODEC_ID_H264 || st->codecpar->codec_id == AV_CODEC_ID_MPEG4) {
1165 int32_t cts = (avio_rb24(s->pb) + 0xff800000) ^ 0xff800000;
1167 if (cts < 0) { // dts might be wrong
1168 if (!flv->wrong_dts)
1169 av_log(s, AV_LOG_WARNING,
1170 "Negative cts, previous timestamps might be wrong.\n");
1172 } else if (FFABS(dts - pts) > 1000*60*15) {
1173 av_log(s, AV_LOG_WARNING,
1174 "invalid timestamps %"PRId64" %"PRId64"\n", dts, pts);
1175 dts = pts = AV_NOPTS_VALUE;
1178 if (type == 0 && (!st->codecpar->extradata || st->codecpar->codec_id == AV_CODEC_ID_AAC ||
1179 st->codecpar->codec_id == AV_CODEC_ID_H264)) {
1180 AVDictionaryEntry *t;
1182 if (st->codecpar->extradata) {
1183 if ((ret = flv_queue_extradata(flv, s->pb, stream_type, size)) < 0)
1188 if ((ret = flv_get_extradata(s, st, size)) < 0)
1191 /* Workaround for buggy Omnia A/XE encoder */
1192 t = av_dict_get(s->metadata, "Encoder", NULL, 0);
1193 if (st->codecpar->codec_id == AV_CODEC_ID_AAC && t && !strcmp(t->value, "Omnia A/XE"))
1194 st->codecpar->extradata_size = 2;
1196 if (st->codecpar->codec_id == AV_CODEC_ID_AAC && 0) {
1197 MPEG4AudioConfig cfg;
1199 if (avpriv_mpeg4audio_get_config(&cfg, st->codecpar->extradata,
1200 st->codecpar->extradata_size * 8, 1) >= 0) {
1201 st->codecpar->channels = cfg.channels;
1202 st->codecpar->channel_layout = 0;
1203 if (cfg.ext_sample_rate)
1204 st->codecpar->sample_rate = cfg.ext_sample_rate;
1206 st->codecpar->sample_rate = cfg.sample_rate;
1207 av_log(s, AV_LOG_TRACE, "mp4a config channels %d sample rate %d\n",
1208 st->codecpar->channels, st->codecpar->sample_rate);
1217 /* skip empty data packets */
1223 ret = av_get_packet(s->pb, pkt, size);
1227 pkt->pts = pts == AV_NOPTS_VALUE ? dts : pts;
1228 pkt->stream_index = st->index;
1230 if (flv->new_extradata[stream_type]) {
1231 uint8_t *side = av_packet_new_side_data(pkt, AV_PKT_DATA_NEW_EXTRADATA,
1232 flv->new_extradata_size[stream_type]);
1234 memcpy(side, flv->new_extradata[stream_type],
1235 flv->new_extradata_size[stream_type]);
1236 av_freep(&flv->new_extradata[stream_type]);
1237 flv->new_extradata_size[stream_type] = 0;
1240 if (stream_type == FLV_STREAM_TYPE_AUDIO &&
1241 (sample_rate != flv->last_sample_rate ||
1242 channels != flv->last_channels)) {
1243 flv->last_sample_rate = sample_rate;
1244 flv->last_channels = channels;
1245 ff_add_param_change(pkt, channels, 0, sample_rate, 0, 0);
1248 if ( stream_type == FLV_STREAM_TYPE_AUDIO ||
1249 ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY) ||
1250 stream_type == FLV_STREAM_TYPE_DATA)
1251 pkt->flags |= AV_PKT_FLAG_KEY;
1254 last = avio_rb32(s->pb);
1255 if (last != orig_size + 11 && last != orig_size + 10 &&
1256 !avio_feof(s->pb) &&
1257 (last != orig_size || !last) && last != flv->sum_flv_tag_size &&
1258 !flv->broken_sizes) {
1259 av_log(s, AV_LOG_ERROR, "Packet mismatch %d %d %d\n", last, orig_size + 11, flv->sum_flv_tag_size);
1260 avio_seek(s->pb, pos + 1, SEEK_SET);
1262 av_packet_unref(pkt);
1270 static int flv_read_seek(AVFormatContext *s, int stream_index,
1271 int64_t ts, int flags)
1273 FLVContext *flv = s->priv_data;
1274 flv->validate_count = 0;
1275 return avio_seek_time(s->pb, stream_index, ts, flags);
1278 #define OFFSET(x) offsetof(FLVContext, x)
1279 #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
1280 static const AVOption options[] = {
1281 { "flv_metadata", "Allocate streams according to the onMetaData array", OFFSET(trust_metadata), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VD },
1282 { "missing_streams", "", OFFSET(missing_streams), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 0xFF, VD | AV_OPT_FLAG_EXPORT | AV_OPT_FLAG_READONLY },
1286 static const AVClass flv_class = {
1287 .class_name = "flvdec",
1288 .item_name = av_default_item_name,
1290 .version = LIBAVUTIL_VERSION_INT,
1293 AVInputFormat ff_flv_demuxer = {
1295 .long_name = NULL_IF_CONFIG_SMALL("FLV (Flash Video)"),
1296 .priv_data_size = sizeof(FLVContext),
1297 .read_probe = flv_probe,
1298 .read_header = flv_read_header,
1299 .read_packet = flv_read_packet,
1300 .read_seek = flv_read_seek,
1301 .read_close = flv_read_close,
1302 .extensions = "flv",
1303 .priv_class = &flv_class,
1306 static const AVClass live_flv_class = {
1307 .class_name = "live_flvdec",
1308 .item_name = av_default_item_name,
1310 .version = LIBAVUTIL_VERSION_INT,
1313 AVInputFormat ff_live_flv_demuxer = {
1315 .long_name = NULL_IF_CONFIG_SMALL("live RTMP FLV (Flash Video)"),
1316 .priv_data_size = sizeof(FLVContext),
1317 .read_probe = live_flv_probe,
1318 .read_header = flv_read_header,
1319 .read_packet = flv_read_packet,
1320 .read_seek = flv_read_seek,
1321 .read_close = flv_read_close,
1322 .extensions = "flv",
1323 .priv_class = &live_flv_class,
1324 .flags = AVFMT_TS_DISCONT