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 *keyframe_times;
68 int64_t *keyframe_filepositions;
71 static int probe(AVProbeData *p, int live)
73 const uint8_t *d = p->buf;
74 unsigned offset = AV_RB32(d + 5);
79 d[3] < 5 && d[5] == 0 &&
80 offset + 100 < p->buf_size &&
82 int is_live = !memcmp(d + offset + 40, "NGINX RTMP", 10);
85 return AVPROBE_SCORE_MAX;
90 static int flv_probe(AVProbeData *p)
95 static int live_flv_probe(AVProbeData *p)
100 static void add_keyframes_index(AVFormatContext *s)
102 FLVContext *flv = s->priv_data;
103 AVStream *stream = NULL;
106 if (flv->last_keyframe_stream_index < 0) {
107 av_log(s, AV_LOG_DEBUG, "keyframe stream hasn't been created\n");
111 av_assert0(flv->last_keyframe_stream_index <= s->nb_streams);
112 stream = s->streams[flv->last_keyframe_stream_index];
114 if (stream->nb_index_entries == 0) {
115 for (i = 0; i < flv->keyframe_count; i++) {
116 av_add_index_entry(stream, flv->keyframe_filepositions[i],
117 flv->keyframe_times[i] * 1000, 0, 0, AVINDEX_KEYFRAME);
120 av_log(s, AV_LOG_WARNING, "Skipping duplicate index\n");
122 if (stream->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
123 av_freep(&flv->keyframe_times);
124 av_freep(&flv->keyframe_filepositions);
125 flv->keyframe_count = 0;
129 static AVStream *create_stream(AVFormatContext *s, int codec_type)
131 FLVContext *flv = s->priv_data;
132 AVStream *st = avformat_new_stream(s, NULL);
135 st->codecpar->codec_type = codec_type;
136 if (s->nb_streams>=3 ||( s->nb_streams==2
137 && s->streams[0]->codecpar->codec_type != AVMEDIA_TYPE_SUBTITLE
138 && s->streams[1]->codecpar->codec_type != AVMEDIA_TYPE_SUBTITLE))
139 s->ctx_flags &= ~AVFMTCTX_NOHEADER;
141 avpriv_set_pts_info(st, 32, 1, 1000); /* 32 bit pts in ms */
142 flv->last_keyframe_stream_index = s->nb_streams - 1;
143 add_keyframes_index(s);
147 static int flv_same_audio_codec(AVCodecParameters *apar, int flags)
149 int bits_per_coded_sample = (flags & FLV_AUDIO_SAMPLESIZE_MASK) ? 16 : 8;
150 int flv_codecid = flags & FLV_AUDIO_CODECID_MASK;
153 if (!apar->codec_id && !apar->codec_tag)
156 if (apar->bits_per_coded_sample != bits_per_coded_sample)
159 switch (flv_codecid) {
160 // no distinction between S16 and S8 PCM codec flags
161 case FLV_CODECID_PCM:
162 codec_id = bits_per_coded_sample == 8
165 : AV_CODEC_ID_PCM_S16BE;
167 : AV_CODEC_ID_PCM_S16LE;
169 return codec_id == apar->codec_id;
170 case FLV_CODECID_PCM_LE:
171 codec_id = bits_per_coded_sample == 8
173 : AV_CODEC_ID_PCM_S16LE;
174 return codec_id == apar->codec_id;
175 case FLV_CODECID_AAC:
176 return apar->codec_id == AV_CODEC_ID_AAC;
177 case FLV_CODECID_ADPCM:
178 return apar->codec_id == AV_CODEC_ID_ADPCM_SWF;
179 case FLV_CODECID_SPEEX:
180 return apar->codec_id == AV_CODEC_ID_SPEEX;
181 case FLV_CODECID_MP3:
182 return apar->codec_id == AV_CODEC_ID_MP3;
183 case FLV_CODECID_NELLYMOSER_8KHZ_MONO:
184 case FLV_CODECID_NELLYMOSER_16KHZ_MONO:
185 case FLV_CODECID_NELLYMOSER:
186 return apar->codec_id == AV_CODEC_ID_NELLYMOSER;
187 case FLV_CODECID_PCM_MULAW:
188 return apar->sample_rate == 8000 &&
189 apar->codec_id == AV_CODEC_ID_PCM_MULAW;
190 case FLV_CODECID_PCM_ALAW:
191 return apar->sample_rate == 8000 &&
192 apar->codec_id == AV_CODEC_ID_PCM_ALAW;
194 return apar->codec_tag == (flv_codecid >> FLV_AUDIO_CODECID_OFFSET);
198 static void flv_set_audio_codec(AVFormatContext *s, AVStream *astream,
199 AVCodecParameters *apar, int flv_codecid)
201 switch (flv_codecid) {
202 // no distinction between S16 and S8 PCM codec flags
203 case FLV_CODECID_PCM:
204 apar->codec_id = apar->bits_per_coded_sample == 8
207 : AV_CODEC_ID_PCM_S16BE;
209 : AV_CODEC_ID_PCM_S16LE;
212 case FLV_CODECID_PCM_LE:
213 apar->codec_id = apar->bits_per_coded_sample == 8
215 : AV_CODEC_ID_PCM_S16LE;
217 case FLV_CODECID_AAC:
218 apar->codec_id = AV_CODEC_ID_AAC;
220 case FLV_CODECID_ADPCM:
221 apar->codec_id = AV_CODEC_ID_ADPCM_SWF;
223 case FLV_CODECID_SPEEX:
224 apar->codec_id = AV_CODEC_ID_SPEEX;
225 apar->sample_rate = 16000;
227 case FLV_CODECID_MP3:
228 apar->codec_id = AV_CODEC_ID_MP3;
229 astream->need_parsing = AVSTREAM_PARSE_FULL;
231 case FLV_CODECID_NELLYMOSER_8KHZ_MONO:
232 // in case metadata does not otherwise declare samplerate
233 apar->sample_rate = 8000;
234 apar->codec_id = AV_CODEC_ID_NELLYMOSER;
236 case FLV_CODECID_NELLYMOSER_16KHZ_MONO:
237 apar->sample_rate = 16000;
238 apar->codec_id = AV_CODEC_ID_NELLYMOSER;
240 case FLV_CODECID_NELLYMOSER:
241 apar->codec_id = AV_CODEC_ID_NELLYMOSER;
243 case FLV_CODECID_PCM_MULAW:
244 apar->sample_rate = 8000;
245 apar->codec_id = AV_CODEC_ID_PCM_MULAW;
247 case FLV_CODECID_PCM_ALAW:
248 apar->sample_rate = 8000;
249 apar->codec_id = AV_CODEC_ID_PCM_ALAW;
252 avpriv_request_sample(s, "Audio codec (%x)",
253 flv_codecid >> FLV_AUDIO_CODECID_OFFSET);
254 apar->codec_tag = flv_codecid >> FLV_AUDIO_CODECID_OFFSET;
258 static int flv_same_video_codec(AVCodecParameters *vpar, int flags)
260 int flv_codecid = flags & FLV_VIDEO_CODECID_MASK;
262 if (!vpar->codec_id && !vpar->codec_tag)
265 switch (flv_codecid) {
266 case FLV_CODECID_H263:
267 return vpar->codec_id == AV_CODEC_ID_FLV1;
268 case FLV_CODECID_SCREEN:
269 return vpar->codec_id == AV_CODEC_ID_FLASHSV;
270 case FLV_CODECID_SCREEN2:
271 return vpar->codec_id == AV_CODEC_ID_FLASHSV2;
272 case FLV_CODECID_VP6:
273 return vpar->codec_id == AV_CODEC_ID_VP6F;
274 case FLV_CODECID_VP6A:
275 return vpar->codec_id == AV_CODEC_ID_VP6A;
276 case FLV_CODECID_H264:
277 return vpar->codec_id == AV_CODEC_ID_H264;
279 return vpar->codec_tag == flv_codecid;
283 static int flv_set_video_codec(AVFormatContext *s, AVStream *vstream,
284 int flv_codecid, int read)
286 AVCodecParameters *par = vstream->codecpar;
287 switch (flv_codecid) {
288 case FLV_CODECID_H263:
289 par->codec_id = AV_CODEC_ID_FLV1;
291 case FLV_CODECID_REALH263:
292 par->codec_id = AV_CODEC_ID_H263;
293 break; // Really mean it this time
294 case FLV_CODECID_SCREEN:
295 par->codec_id = AV_CODEC_ID_FLASHSV;
297 case FLV_CODECID_SCREEN2:
298 par->codec_id = AV_CODEC_ID_FLASHSV2;
300 case FLV_CODECID_VP6:
301 par->codec_id = AV_CODEC_ID_VP6F;
302 case FLV_CODECID_VP6A:
303 if (flv_codecid == FLV_CODECID_VP6A)
304 par->codec_id = AV_CODEC_ID_VP6A;
306 if (par->extradata_size != 1) {
307 ff_alloc_extradata(par, 1);
310 par->extradata[0] = avio_r8(s->pb);
314 return 1; // 1 byte body size adjustment for flv_read_packet()
315 case FLV_CODECID_H264:
316 par->codec_id = AV_CODEC_ID_H264;
317 vstream->need_parsing = AVSTREAM_PARSE_HEADERS;
318 return 3; // not 4, reading packet type will consume one byte
319 case FLV_CODECID_MPEG4:
320 par->codec_id = AV_CODEC_ID_MPEG4;
323 avpriv_request_sample(s, "Video codec (%x)", flv_codecid);
324 par->codec_tag = flv_codecid;
330 static int amf_get_string(AVIOContext *ioc, char *buffer, int buffsize)
332 int length = avio_rb16(ioc);
333 if (length >= buffsize) {
334 avio_skip(ioc, length);
338 avio_read(ioc, buffer, length);
340 buffer[length] = '\0';
345 static int parse_keyframes_index(AVFormatContext *s, AVIOContext *ioc, int64_t max_pos)
347 FLVContext *flv = s->priv_data;
348 unsigned int timeslen = 0, fileposlen = 0, i;
350 int64_t *times = NULL;
351 int64_t *filepositions = NULL;
352 int ret = AVERROR(ENOSYS);
353 int64_t initial_pos = avio_tell(ioc);
355 if (flv->keyframe_count > 0) {
356 av_log(s, AV_LOG_DEBUG, "keyframes have been paresed\n");
359 av_assert0(!flv->keyframe_times);
360 av_assert0(!flv->keyframe_filepositions);
362 if (s->flags & AVFMT_FLAG_IGNIDX)
365 while (avio_tell(ioc) < max_pos - 2 &&
366 amf_get_string(ioc, str_val, sizeof(str_val)) > 0) {
367 int64_t **current_array;
368 unsigned int arraylen;
370 // Expect array object in context
371 if (avio_r8(ioc) != AMF_DATA_TYPE_ARRAY)
374 arraylen = avio_rb32(ioc);
378 if (!strcmp(KEYFRAMES_TIMESTAMP_TAG , str_val) && !times) {
379 current_array = ×
381 } else if (!strcmp(KEYFRAMES_BYTEOFFSET_TAG, str_val) &&
383 current_array = &filepositions;
384 fileposlen = arraylen;
386 // unexpected metatag inside keyframes, will not use such
387 // metadata for indexing
390 if (!(*current_array = av_mallocz(sizeof(**current_array) * arraylen))) {
391 ret = AVERROR(ENOMEM);
395 for (i = 0; i < arraylen && avio_tell(ioc) < max_pos - 1; i++) {
396 if (avio_r8(ioc) != AMF_DATA_TYPE_NUMBER)
398 current_array[0][i] = av_int2double(avio_rb64(ioc));
400 if (times && filepositions) {
401 // All done, exiting at a position allowing amf_parse_object
402 // to finish parsing the object
408 if (timeslen == fileposlen && fileposlen>1 && max_pos <= filepositions[0]) {
409 for (i = 0; i < FFMIN(2,fileposlen); i++) {
410 flv->validate_index[i].pos = filepositions[i];
411 flv->validate_index[i].dts = times[i] * 1000;
412 flv->validate_count = i + 1;
414 flv->keyframe_times = times;
415 flv->keyframe_filepositions = filepositions;
416 flv->keyframe_count = timeslen;
418 filepositions = NULL;
421 av_log(s, AV_LOG_WARNING, "Invalid keyframes object, skipping.\n");
426 av_freep(&filepositions);
427 avio_seek(ioc, initial_pos, SEEK_SET);
431 static int amf_parse_object(AVFormatContext *s, AVStream *astream,
432 AVStream *vstream, const char *key,
433 int64_t max_pos, int depth)
435 AVCodecParameters *apar, *vpar;
436 FLVContext *flv = s->priv_data;
438 AMFDataType amf_type;
444 amf_type = avio_r8(ioc);
447 case AMF_DATA_TYPE_NUMBER:
448 num_val = av_int2double(avio_rb64(ioc));
450 case AMF_DATA_TYPE_BOOL:
451 num_val = avio_r8(ioc);
453 case AMF_DATA_TYPE_STRING:
454 if (amf_get_string(ioc, str_val, sizeof(str_val)) < 0) {
455 av_log(s, AV_LOG_ERROR, "AMF_DATA_TYPE_STRING parsing failed\n");
459 case AMF_DATA_TYPE_OBJECT:
462 !strcmp(KEYFRAMES_TAG, key) && depth == 1)
463 if (parse_keyframes_index(s, ioc,
465 av_log(s, AV_LOG_ERROR, "Keyframe index parsing failed\n");
467 add_keyframes_index(s);
468 while (avio_tell(ioc) < max_pos - 2 &&
469 amf_get_string(ioc, str_val, sizeof(str_val)) > 0)
470 if (amf_parse_object(s, astream, vstream, str_val, max_pos,
472 return -1; // if we couldn't skip, bomb out.
473 if (avio_r8(ioc) != AMF_END_OF_OBJECT) {
474 av_log(s, AV_LOG_ERROR, "Missing AMF_END_OF_OBJECT in AMF_DATA_TYPE_OBJECT\n");
478 case AMF_DATA_TYPE_NULL:
479 case AMF_DATA_TYPE_UNDEFINED:
480 case AMF_DATA_TYPE_UNSUPPORTED:
481 break; // these take up no additional space
482 case AMF_DATA_TYPE_MIXEDARRAY:
485 avio_skip(ioc, 4); // skip 32-bit max array index
486 while (avio_tell(ioc) < max_pos - 2 &&
487 amf_get_string(ioc, str_val, sizeof(str_val)) > 0)
488 // this is the only case in which we would want a nested
489 // parse to not skip over the object
490 if (amf_parse_object(s, astream, vstream, str_val, max_pos,
494 if (v != AMF_END_OF_OBJECT) {
495 av_log(s, AV_LOG_ERROR, "Missing AMF_END_OF_OBJECT in AMF_DATA_TYPE_MIXEDARRAY, found %d\n", v);
500 case AMF_DATA_TYPE_ARRAY:
502 unsigned int arraylen, i;
504 arraylen = avio_rb32(ioc);
505 for (i = 0; i < arraylen && avio_tell(ioc) < max_pos - 1; i++)
506 if (amf_parse_object(s, NULL, NULL, NULL, max_pos,
508 return -1; // if we couldn't skip, bomb out.
511 case AMF_DATA_TYPE_DATE:
512 avio_skip(ioc, 8 + 2); // timestamp (double) and UTC offset (int16)
514 default: // unsupported type, we couldn't skip
515 av_log(s, AV_LOG_ERROR, "unsupported amf type %d\n", amf_type);
520 apar = astream ? astream->codecpar : NULL;
521 vpar = vstream ? vstream->codecpar : NULL;
523 // stream info doesn't live any deeper than the first object
525 if (amf_type == AMF_DATA_TYPE_NUMBER ||
526 amf_type == AMF_DATA_TYPE_BOOL) {
527 if (!strcmp(key, "duration"))
528 s->duration = num_val * AV_TIME_BASE;
529 else if (!strcmp(key, "videodatarate") && vpar &&
530 0 <= (int)(num_val * 1024.0))
531 vpar->bit_rate = num_val * 1024.0;
532 else if (!strcmp(key, "audiodatarate") && apar &&
533 0 <= (int)(num_val * 1024.0))
534 apar->bit_rate = num_val * 1024.0;
535 else if (!strcmp(key, "datastream")) {
536 AVStream *st = create_stream(s, AVMEDIA_TYPE_SUBTITLE);
538 return AVERROR(ENOMEM);
539 st->codecpar->codec_id = AV_CODEC_ID_TEXT;
540 } else if (flv->trust_metadata) {
541 if (!strcmp(key, "videocodecid") && vpar) {
542 flv_set_video_codec(s, vstream, num_val, 0);
543 } else if (!strcmp(key, "audiocodecid") && apar) {
544 int id = ((int)num_val) << FLV_AUDIO_CODECID_OFFSET;
545 flv_set_audio_codec(s, astream, apar, id);
546 } else if (!strcmp(key, "audiosamplerate") && apar) {
547 apar->sample_rate = num_val;
548 } else if (!strcmp(key, "audiosamplesize") && apar) {
549 apar->bits_per_coded_sample = num_val;
550 } else if (!strcmp(key, "stereo") && apar) {
551 apar->channels = num_val + 1;
552 apar->channel_layout = apar->channels == 2 ?
553 AV_CH_LAYOUT_STEREO :
555 } else if (!strcmp(key, "width") && vpar) {
556 vpar->width = num_val;
557 } else if (!strcmp(key, "height") && vpar) {
558 vpar->height = num_val;
562 if (amf_type == AMF_DATA_TYPE_STRING) {
563 if (!strcmp(key, "encoder")) {
565 if (1 == sscanf(str_val, "Open Broadcaster Software v0.%d", &version)) {
566 if (version > 0 && version <= 655)
567 flv->broken_sizes = 1;
569 } else if (!strcmp(key, "metadatacreator") && !strcmp(str_val, "MEGA")) {
570 flv->broken_sizes = 1;
575 if (amf_type == AMF_DATA_TYPE_OBJECT && s->nb_streams == 1 &&
576 ((!apar && !strcmp(key, "audiocodecid")) ||
577 (!vpar && !strcmp(key, "videocodecid"))))
578 s->ctx_flags &= ~AVFMTCTX_NOHEADER; //If there is either audio/video missing, codecid will be an empty object
580 if (!strcmp(key, "duration") ||
581 !strcmp(key, "filesize") ||
582 !strcmp(key, "width") ||
583 !strcmp(key, "height") ||
584 !strcmp(key, "videodatarate") ||
585 !strcmp(key, "framerate") ||
586 !strcmp(key, "videocodecid") ||
587 !strcmp(key, "audiodatarate") ||
588 !strcmp(key, "audiosamplerate") ||
589 !strcmp(key, "audiosamplesize") ||
590 !strcmp(key, "stereo") ||
591 !strcmp(key, "audiocodecid") ||
592 !strcmp(key, "datastream"))
595 s->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
596 if (amf_type == AMF_DATA_TYPE_BOOL) {
597 av_strlcpy(str_val, num_val > 0 ? "true" : "false",
599 av_dict_set(&s->metadata, key, str_val, 0);
600 } else if (amf_type == AMF_DATA_TYPE_NUMBER) {
601 snprintf(str_val, sizeof(str_val), "%.f", num_val);
602 av_dict_set(&s->metadata, key, str_val, 0);
603 } else if (amf_type == AMF_DATA_TYPE_STRING)
604 av_dict_set(&s->metadata, key, str_val, 0);
610 #define TYPE_ONTEXTDATA 1
611 #define TYPE_ONCAPTION 2
612 #define TYPE_ONCAPTIONINFO 3
613 #define TYPE_UNKNOWN 9
615 static int flv_read_metabody(AVFormatContext *s, int64_t next_pos)
617 FLVContext *flv = s->priv_data;
619 AVStream *stream, *astream, *vstream;
620 AVStream av_unused *dstream;
623 // only needs to hold the string "onMetaData".
624 // Anything longer is something we don't want.
632 // first object needs to be "onMetaData" string
634 if (type != AMF_DATA_TYPE_STRING ||
635 amf_get_string(ioc, buffer, sizeof(buffer)) < 0)
638 if (!strcmp(buffer, "onTextData"))
639 return TYPE_ONTEXTDATA;
641 if (!strcmp(buffer, "onCaption"))
642 return TYPE_ONCAPTION;
644 if (!strcmp(buffer, "onCaptionInfo"))
645 return TYPE_ONCAPTIONINFO;
647 if (strcmp(buffer, "onMetaData") && strcmp(buffer, "onCuePoint")) {
648 av_log(s, AV_LOG_DEBUG, "Unknown type %s\n", buffer);
652 // find the streams now so that amf_parse_object doesn't need to do
653 // the lookup every time it is called.
654 for (i = 0; i < s->nb_streams; i++) {
655 stream = s->streams[i];
656 if (stream->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
658 flv->last_keyframe_stream_index = i;
659 } else if (stream->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
661 if (flv->last_keyframe_stream_index == -1)
662 flv->last_keyframe_stream_index = i;
664 else if (stream->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE)
668 // parse the second object (we want a mixed array)
669 if (amf_parse_object(s, astream, vstream, buffer, next_pos, 0) < 0)
675 static int flv_read_header(AVFormatContext *s)
677 FLVContext *flv = s->priv_data;
681 avio_r8(s->pb); // flags
683 s->ctx_flags |= AVFMTCTX_NOHEADER;
685 offset = avio_rb32(s->pb);
686 avio_seek(s->pb, offset, SEEK_SET);
690 flv->sum_flv_tag_size = 0;
691 flv->last_keyframe_stream_index = -1;
696 static int flv_read_close(AVFormatContext *s)
699 FLVContext *flv = s->priv_data;
700 for (i=0; i<FLV_STREAM_TYPE_NB; i++)
701 av_freep(&flv->new_extradata[i]);
702 av_freep(&flv->keyframe_times);
703 av_freep(&flv->keyframe_filepositions);
707 static int flv_get_extradata(AVFormatContext *s, AVStream *st, int size)
709 av_freep(&st->codecpar->extradata);
710 if (ff_get_extradata(s, st->codecpar, s->pb, size) < 0)
711 return AVERROR(ENOMEM);
715 static int flv_queue_extradata(FLVContext *flv, AVIOContext *pb, int stream,
718 av_free(flv->new_extradata[stream]);
719 flv->new_extradata[stream] = av_mallocz(size +
720 AV_INPUT_BUFFER_PADDING_SIZE);
721 if (!flv->new_extradata[stream])
722 return AVERROR(ENOMEM);
723 flv->new_extradata_size[stream] = size;
724 avio_read(pb, flv->new_extradata[stream], size);
728 static void clear_index_entries(AVFormatContext *s, int64_t pos)
731 av_log(s, AV_LOG_WARNING,
732 "Found invalid index entries, clearing the index.\n");
733 for (i = 0; i < s->nb_streams; i++) {
734 AVStream *st = s->streams[i];
735 /* Remove all index entries that point to >= pos */
737 for (j = 0; j < st->nb_index_entries; j++)
738 if (st->index_entries[j].pos < pos)
739 st->index_entries[out++] = st->index_entries[j];
740 st->nb_index_entries = out;
744 static int amf_skip_tag(AVIOContext *pb, AMFDataType type)
746 int nb = -1, ret, parse_name = 1;
749 case AMF_DATA_TYPE_NUMBER:
752 case AMF_DATA_TYPE_BOOL:
755 case AMF_DATA_TYPE_STRING:
756 avio_skip(pb, avio_rb16(pb));
758 case AMF_DATA_TYPE_ARRAY:
760 case AMF_DATA_TYPE_MIXEDARRAY:
762 case AMF_DATA_TYPE_OBJECT:
763 while(!pb->eof_reached && (nb-- > 0 || type != AMF_DATA_TYPE_ARRAY)) {
765 int size = avio_rb16(pb);
772 if ((ret = amf_skip_tag(pb, avio_r8(pb))) < 0)
776 case AMF_DATA_TYPE_NULL:
777 case AMF_DATA_TYPE_OBJECT_END:
780 return AVERROR_INVALIDDATA;
785 static int flv_data_packet(AVFormatContext *s, AVPacket *pkt,
786 int64_t dts, int64_t next)
788 AVIOContext *pb = s->pb;
791 int ret = AVERROR_INVALIDDATA;
795 switch (avio_r8(pb)) {
796 case AMF_DATA_TYPE_ARRAY:
798 case AMF_DATA_TYPE_MIXEDARRAY:
799 avio_seek(pb, 4, SEEK_CUR);
800 case AMF_DATA_TYPE_OBJECT:
806 while (array || (ret = amf_get_string(pb, buf, sizeof(buf))) > 0) {
807 AMFDataType type = avio_r8(pb);
808 if (type == AMF_DATA_TYPE_STRING && (array || !strcmp(buf, "text"))) {
809 length = avio_rb16(pb);
810 ret = av_get_packet(pb, pkt, length);
816 if ((ret = amf_skip_tag(pb, type)) < 0)
822 ret = AVERROR_INVALIDDATA;
826 for (i = 0; i < s->nb_streams; i++) {
828 if (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE)
832 if (i == s->nb_streams) {
833 st = create_stream(s, AVMEDIA_TYPE_SUBTITLE);
835 return AVERROR(ENOMEM);
836 st->codecpar->codec_id = AV_CODEC_ID_TEXT;
843 pkt->stream_index = st->index;
844 pkt->flags |= AV_PKT_FLAG_KEY;
847 avio_seek(s->pb, next + 4, SEEK_SET);
852 static int resync(AVFormatContext *s)
854 FLVContext *flv = s->priv_data;
856 int64_t pos = avio_tell(s->pb);
858 for (i=0; !avio_feof(s->pb); i++) {
859 int j = i & (RESYNC_BUFFER_SIZE-1);
860 int j1 = j + RESYNC_BUFFER_SIZE;
861 flv->resync_buffer[j ] =
862 flv->resync_buffer[j1] = avio_r8(s->pb);
865 unsigned lsize2 = AV_RB32(flv->resync_buffer + j1 - 4);
866 if (lsize2 >= 11 && lsize2 + 8LL < FFMIN(i, RESYNC_BUFFER_SIZE)) {
867 unsigned size2 = AV_RB24(flv->resync_buffer + j1 - lsize2 + 1 - 4);
868 unsigned lsize1 = AV_RB32(flv->resync_buffer + j1 - lsize2 - 8);
869 if (lsize1 >= 11 && lsize1 + 8LL + lsize2 < FFMIN(i, RESYNC_BUFFER_SIZE)) {
870 unsigned size1 = AV_RB24(flv->resync_buffer + j1 - lsize1 + 1 - lsize2 - 8);
871 if (size1 == lsize1 - 11 && size2 == lsize2 - 11) {
872 avio_seek(s->pb, pos + i - lsize1 - lsize2 - 8, SEEK_SET);
882 static int flv_read_packet(AVFormatContext *s, AVPacket *pkt)
884 FLVContext *flv = s->priv_data;
885 int ret, i, size, flags;
886 enum FlvTagType type;
888 int64_t next, pos, meta_pos;
889 int64_t dts, pts = AV_NOPTS_VALUE;
890 int av_uninit(channels);
891 int av_uninit(sample_rate);
897 /* pkt size is repeated at end. skip it */
898 pos = avio_tell(s->pb);
899 type = (avio_r8(s->pb) & 0x1F);
901 size = avio_rb24(s->pb);
902 flv->sum_flv_tag_size += size + 11;
903 dts = avio_rb24(s->pb);
904 dts |= (unsigned)avio_r8(s->pb) << 24;
905 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));
906 if (avio_feof(s->pb))
908 avio_skip(s->pb, 3); /* stream id, always 0 */
911 if (flv->validate_next < flv->validate_count) {
912 int64_t validate_pos = flv->validate_index[flv->validate_next].pos;
913 if (pos == validate_pos) {
914 if (FFABS(dts - flv->validate_index[flv->validate_next].dts) <=
915 VALIDATE_INDEX_TS_THRESH) {
916 flv->validate_next++;
918 clear_index_entries(s, validate_pos);
919 flv->validate_count = 0;
921 } else if (pos > validate_pos) {
922 clear_index_entries(s, validate_pos);
923 flv->validate_count = 0;
932 next = size + avio_tell(s->pb);
934 if (type == FLV_TAG_TYPE_AUDIO) {
935 stream_type = FLV_STREAM_TYPE_AUDIO;
936 flags = avio_r8(s->pb);
938 } else if (type == FLV_TAG_TYPE_VIDEO) {
939 stream_type = FLV_STREAM_TYPE_VIDEO;
940 flags = avio_r8(s->pb);
942 if ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_VIDEO_INFO_CMD)
944 } else if (type == FLV_TAG_TYPE_META) {
945 stream_type=FLV_STREAM_TYPE_DATA;
946 if (size > 13 + 1 + 4) { // Header-type metadata stuff
948 meta_pos = avio_tell(s->pb);
949 type = flv_read_metabody(s, next);
950 if (type == 0 && dts == 0 || type < 0 || type == TYPE_UNKNOWN) {
951 if (type < 0 && flv->validate_count &&
952 flv->validate_index[0].pos > next &&
953 flv->validate_index[0].pos - 4 < next
955 av_log(s, AV_LOG_WARNING, "Adjusting next position due to index mismatch\n");
956 next = flv->validate_index[0].pos - 4;
959 } else if (type == TYPE_ONTEXTDATA) {
960 avpriv_request_sample(s, "OnTextData packet");
961 return flv_data_packet(s, pkt, dts, next);
962 } else if (type == TYPE_ONCAPTION) {
963 return flv_data_packet(s, pkt, dts, next);
965 avio_seek(s->pb, meta_pos, SEEK_SET);
968 av_log(s, AV_LOG_DEBUG,
969 "Skipping flv packet: type %d, size %d, flags %d.\n",
972 avio_seek(s->pb, next, SEEK_SET);
977 /* skip empty data packets */
983 /* now find stream */
984 for (i = 0; i < s->nb_streams; i++) {
986 if (stream_type == FLV_STREAM_TYPE_AUDIO) {
987 if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO &&
988 (s->audio_codec_id || flv_same_audio_codec(st->codecpar, flags)))
990 } else if (stream_type == FLV_STREAM_TYPE_VIDEO) {
991 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
992 (s->video_codec_id || flv_same_video_codec(st->codecpar, flags)))
994 } else if (stream_type == FLV_STREAM_TYPE_DATA) {
995 if (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE)
999 if (i == s->nb_streams) {
1000 static const enum AVMediaType stream_types[] = {AVMEDIA_TYPE_VIDEO, AVMEDIA_TYPE_AUDIO, AVMEDIA_TYPE_SUBTITLE};
1001 av_log(s, AV_LOG_WARNING, "%s stream discovered after head already parsed\n", av_get_media_type_string(stream_types[stream_type]));
1002 st = create_stream(s, stream_types[stream_type]);
1004 return AVERROR(ENOMEM);
1007 av_log(s, AV_LOG_TRACE, "%d %X %d \n", stream_type, flags, st->discard);
1009 if (s->pb->seekable &&
1010 ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY ||
1011 stream_type == FLV_STREAM_TYPE_AUDIO))
1012 av_add_index_entry(st, pos, dts, size, 0, AVINDEX_KEYFRAME);
1014 if ( (st->discard >= AVDISCARD_NONKEY && !((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY || (stream_type == FLV_STREAM_TYPE_AUDIO)))
1015 ||(st->discard >= AVDISCARD_BIDIR && ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_DISP_INTER && (stream_type == FLV_STREAM_TYPE_VIDEO)))
1016 || st->discard >= AVDISCARD_ALL
1018 avio_seek(s->pb, next, SEEK_SET);
1023 // if not streamed and no duration from metadata then seek to end to find
1024 // the duration from the timestamps
1025 if (s->pb->seekable && (!s->duration || s->duration == AV_NOPTS_VALUE) &&
1026 !flv->searched_for_end) {
1028 const int64_t pos = avio_tell(s->pb);
1029 // Read the last 4 bytes of the file, this should be the size of the
1030 // previous FLV tag. Use the timestamp of its payload as duration.
1031 int64_t fsize = avio_size(s->pb);
1033 avio_seek(s->pb, fsize - 4, SEEK_SET);
1034 size = avio_rb32(s->pb);
1035 if (size > 0 && size < fsize) {
1036 // Seek to the start of the last FLV tag at position (fsize - 4 - size)
1037 // but skip the byte indicating the type.
1038 avio_seek(s->pb, fsize - 3 - size, SEEK_SET);
1039 if (size == avio_rb24(s->pb) + 11) {
1040 uint32_t ts = avio_rb24(s->pb);
1041 ts |= avio_r8(s->pb) << 24;
1043 s->duration = ts * (int64_t)AV_TIME_BASE / 1000;
1044 else if (fsize >= 8 && fsize - 8 >= size) {
1046 goto retry_duration;
1051 avio_seek(s->pb, pos, SEEK_SET);
1052 flv->searched_for_end = 1;
1055 if (stream_type == FLV_STREAM_TYPE_AUDIO) {
1056 int bits_per_coded_sample;
1057 channels = (flags & FLV_AUDIO_CHANNEL_MASK) == FLV_STEREO ? 2 : 1;
1058 sample_rate = 44100 << ((flags & FLV_AUDIO_SAMPLERATE_MASK) >>
1059 FLV_AUDIO_SAMPLERATE_OFFSET) >> 3;
1060 bits_per_coded_sample = (flags & FLV_AUDIO_SAMPLESIZE_MASK) ? 16 : 8;
1061 if (!st->codecpar->channels || !st->codecpar->sample_rate ||
1062 !st->codecpar->bits_per_coded_sample) {
1063 st->codecpar->channels = channels;
1064 st->codecpar->channel_layout = channels == 1
1066 : AV_CH_LAYOUT_STEREO;
1067 st->codecpar->sample_rate = sample_rate;
1068 st->codecpar->bits_per_coded_sample = bits_per_coded_sample;
1070 if (!st->codecpar->codec_id) {
1071 flv_set_audio_codec(s, st, st->codecpar,
1072 flags & FLV_AUDIO_CODECID_MASK);
1073 flv->last_sample_rate =
1074 sample_rate = st->codecpar->sample_rate;
1075 flv->last_channels =
1076 channels = st->codecpar->channels;
1078 AVCodecParameters *par = avcodec_parameters_alloc();
1080 ret = AVERROR(ENOMEM);
1083 par->sample_rate = sample_rate;
1084 par->bits_per_coded_sample = bits_per_coded_sample;
1085 flv_set_audio_codec(s, st, par, flags & FLV_AUDIO_CODECID_MASK);
1086 sample_rate = par->sample_rate;
1087 avcodec_parameters_free(&par);
1089 } else if (stream_type == FLV_STREAM_TYPE_VIDEO) {
1090 size -= flv_set_video_codec(s, st, flags & FLV_VIDEO_CODECID_MASK, 1);
1091 } else if (stream_type == FLV_STREAM_TYPE_DATA) {
1092 st->codecpar->codec_id = AV_CODEC_ID_TEXT;
1095 if (st->codecpar->codec_id == AV_CODEC_ID_AAC ||
1096 st->codecpar->codec_id == AV_CODEC_ID_H264 ||
1097 st->codecpar->codec_id == AV_CODEC_ID_MPEG4) {
1098 int type = avio_r8(s->pb);
1100 if (st->codecpar->codec_id == AV_CODEC_ID_H264 || st->codecpar->codec_id == AV_CODEC_ID_MPEG4) {
1102 int32_t cts = (avio_rb24(s->pb) + 0xff800000) ^ 0xff800000;
1104 if (cts < 0) { // dts might be wrong
1105 if (!flv->wrong_dts)
1106 av_log(s, AV_LOG_WARNING,
1107 "Negative cts, previous timestamps might be wrong.\n");
1109 } else if (FFABS(dts - pts) > 1000*60*15) {
1110 av_log(s, AV_LOG_WARNING,
1111 "invalid timestamps %"PRId64" %"PRId64"\n", dts, pts);
1112 dts = pts = AV_NOPTS_VALUE;
1115 if (type == 0 && (!st->codecpar->extradata || st->codecpar->codec_id == AV_CODEC_ID_AAC ||
1116 st->codecpar->codec_id == AV_CODEC_ID_H264)) {
1117 AVDictionaryEntry *t;
1119 if (st->codecpar->extradata) {
1120 if ((ret = flv_queue_extradata(flv, s->pb, stream_type, size)) < 0)
1125 if ((ret = flv_get_extradata(s, st, size)) < 0)
1128 /* Workaround for buggy Omnia A/XE encoder */
1129 t = av_dict_get(s->metadata, "Encoder", NULL, 0);
1130 if (st->codecpar->codec_id == AV_CODEC_ID_AAC && t && !strcmp(t->value, "Omnia A/XE"))
1131 st->codecpar->extradata_size = 2;
1133 if (st->codecpar->codec_id == AV_CODEC_ID_AAC && 0) {
1134 MPEG4AudioConfig cfg;
1136 if (avpriv_mpeg4audio_get_config(&cfg, st->codecpar->extradata,
1137 st->codecpar->extradata_size * 8, 1) >= 0) {
1138 st->codecpar->channels = cfg.channels;
1139 st->codecpar->channel_layout = 0;
1140 if (cfg.ext_sample_rate)
1141 st->codecpar->sample_rate = cfg.ext_sample_rate;
1143 st->codecpar->sample_rate = cfg.sample_rate;
1144 av_log(s, AV_LOG_TRACE, "mp4a config channels %d sample rate %d\n",
1145 st->codecpar->channels, st->codecpar->sample_rate);
1154 /* skip empty data packets */
1160 ret = av_get_packet(s->pb, pkt, size);
1164 pkt->pts = pts == AV_NOPTS_VALUE ? dts : pts;
1165 pkt->stream_index = st->index;
1166 if (flv->new_extradata[stream_type]) {
1167 uint8_t *side = av_packet_new_side_data(pkt, AV_PKT_DATA_NEW_EXTRADATA,
1168 flv->new_extradata_size[stream_type]);
1170 memcpy(side, flv->new_extradata[stream_type],
1171 flv->new_extradata_size[stream_type]);
1172 av_freep(&flv->new_extradata[stream_type]);
1173 flv->new_extradata_size[stream_type] = 0;
1176 if (stream_type == FLV_STREAM_TYPE_AUDIO &&
1177 (sample_rate != flv->last_sample_rate ||
1178 channels != flv->last_channels)) {
1179 flv->last_sample_rate = sample_rate;
1180 flv->last_channels = channels;
1181 ff_add_param_change(pkt, channels, 0, sample_rate, 0, 0);
1184 if ( stream_type == FLV_STREAM_TYPE_AUDIO ||
1185 ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY) ||
1186 stream_type == FLV_STREAM_TYPE_DATA)
1187 pkt->flags |= AV_PKT_FLAG_KEY;
1190 last = avio_rb32(s->pb);
1191 if (last != orig_size + 11 && last != orig_size + 10 &&
1192 !avio_feof(s->pb) &&
1193 (last != orig_size || !last) && last != flv->sum_flv_tag_size &&
1194 !flv->broken_sizes) {
1195 av_log(s, AV_LOG_ERROR, "Packet mismatch %d %d %d\n", last, orig_size + 11, flv->sum_flv_tag_size);
1196 avio_seek(s->pb, pos + 1, SEEK_SET);
1198 av_packet_unref(pkt);
1206 static int flv_read_seek(AVFormatContext *s, int stream_index,
1207 int64_t ts, int flags)
1209 FLVContext *flv = s->priv_data;
1210 flv->validate_count = 0;
1211 return avio_seek_time(s->pb, stream_index, ts, flags);
1214 #define OFFSET(x) offsetof(FLVContext, x)
1215 #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
1216 static const AVOption options[] = {
1217 { "flv_metadata", "Allocate streams according to the onMetaData array", OFFSET(trust_metadata), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VD },
1221 static const AVClass flv_class = {
1222 .class_name = "flvdec",
1223 .item_name = av_default_item_name,
1225 .version = LIBAVUTIL_VERSION_INT,
1228 AVInputFormat ff_flv_demuxer = {
1230 .long_name = NULL_IF_CONFIG_SMALL("FLV (Flash Video)"),
1231 .priv_data_size = sizeof(FLVContext),
1232 .read_probe = flv_probe,
1233 .read_header = flv_read_header,
1234 .read_packet = flv_read_packet,
1235 .read_seek = flv_read_seek,
1236 .read_close = flv_read_close,
1237 .extensions = "flv",
1238 .priv_class = &flv_class,
1241 static const AVClass live_flv_class = {
1242 .class_name = "live_flvdec",
1243 .item_name = av_default_item_name,
1245 .version = LIBAVUTIL_VERSION_INT,
1248 AVInputFormat ff_live_flv_demuxer = {
1250 .long_name = NULL_IF_CONFIG_SMALL("live RTMP FLV (Flash Video)"),
1251 .priv_data_size = sizeof(FLVContext),
1252 .read_probe = live_flv_probe,
1253 .read_header = flv_read_header,
1254 .read_packet = flv_read_packet,
1255 .read_seek = flv_read_seek,
1256 .read_close = flv_read_close,
1257 .extensions = "flv",
1258 .priv_class = &live_flv_class,
1259 .flags = AVFMT_TS_DISCONT