3 * Copyright (c) 2003 The FFmpeg Project
5 * This demuxer will generate a 1 byte extradata for VP6F content.
7 * - upper 4bits: difference between encoded width and visible width
8 * - lower 4bits: difference between encoded height and visible height
10 * This file is part of FFmpeg.
12 * FFmpeg is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU Lesser General Public
14 * License as published by the Free Software Foundation; either
15 * version 2.1 of the License, or (at your option) any later version.
17 * FFmpeg is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 * Lesser General Public License for more details.
22 * You should have received a copy of the GNU Lesser General Public
23 * License along with FFmpeg; if not, write to the Free Software
24 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
27 #include "libavutil/avstring.h"
28 #include "libavutil/channel_layout.h"
29 #include "libavutil/dict.h"
30 #include "libavutil/opt.h"
31 #include "libavutil/intfloat.h"
32 #include "libavutil/mathematics.h"
33 #include "libavcodec/bytestream.h"
34 #include "libavcodec/mpeg4audio.h"
37 #include "avio_internal.h"
40 #define VALIDATE_INDEX_TS_THRESH 2500
42 #define RESYNC_BUFFER_SIZE (1<<20)
44 typedef struct FLVContext {
45 const AVClass *class; ///< Class for private options.
46 int trust_metadata; ///< configure streams according onMetaData
47 int wrong_dts; ///< wrong dts due to negative cts
48 uint8_t *new_extradata[FLV_STREAM_TYPE_NB];
49 int new_extradata_size[FLV_STREAM_TYPE_NB];
60 uint8_t resync_buffer[2*RESYNC_BUFFER_SIZE];
65 static int probe(AVProbeData *p, int live)
67 const uint8_t *d = p->buf;
68 unsigned offset = AV_RB32(d + 5);
73 d[3] < 5 && d[5] == 0 &&
74 offset + 100 < p->buf_size &&
76 int is_live = !memcmp(d + offset + 40, "NGINX RTMP", 10);
79 return AVPROBE_SCORE_MAX;
84 static int flv_probe(AVProbeData *p)
89 static int live_flv_probe(AVProbeData *p)
94 static AVStream *create_stream(AVFormatContext *s, int codec_type)
96 AVStream *st = avformat_new_stream(s, NULL);
99 st->codec->codec_type = codec_type;
100 if (s->nb_streams>=3 ||( s->nb_streams==2
101 && s->streams[0]->codec->codec_type != AVMEDIA_TYPE_SUBTITLE
102 && s->streams[1]->codec->codec_type != AVMEDIA_TYPE_SUBTITLE))
103 s->ctx_flags &= ~AVFMTCTX_NOHEADER;
105 avpriv_set_pts_info(st, 32, 1, 1000); /* 32 bit pts in ms */
109 static int flv_same_audio_codec(AVCodecContext *acodec, int flags)
111 int bits_per_coded_sample = (flags & FLV_AUDIO_SAMPLESIZE_MASK) ? 16 : 8;
112 int flv_codecid = flags & FLV_AUDIO_CODECID_MASK;
115 if (!acodec->codec_id && !acodec->codec_tag)
118 if (acodec->bits_per_coded_sample != bits_per_coded_sample)
121 switch (flv_codecid) {
122 // no distinction between S16 and S8 PCM codec flags
123 case FLV_CODECID_PCM:
124 codec_id = bits_per_coded_sample == 8
127 : AV_CODEC_ID_PCM_S16BE;
129 : AV_CODEC_ID_PCM_S16LE;
131 return codec_id == acodec->codec_id;
132 case FLV_CODECID_PCM_LE:
133 codec_id = bits_per_coded_sample == 8
135 : AV_CODEC_ID_PCM_S16LE;
136 return codec_id == acodec->codec_id;
137 case FLV_CODECID_AAC:
138 return acodec->codec_id == AV_CODEC_ID_AAC;
139 case FLV_CODECID_ADPCM:
140 return acodec->codec_id == AV_CODEC_ID_ADPCM_SWF;
141 case FLV_CODECID_SPEEX:
142 return acodec->codec_id == AV_CODEC_ID_SPEEX;
143 case FLV_CODECID_MP3:
144 return acodec->codec_id == AV_CODEC_ID_MP3;
145 case FLV_CODECID_NELLYMOSER_8KHZ_MONO:
146 case FLV_CODECID_NELLYMOSER_16KHZ_MONO:
147 case FLV_CODECID_NELLYMOSER:
148 return acodec->codec_id == AV_CODEC_ID_NELLYMOSER;
149 case FLV_CODECID_PCM_MULAW:
150 return acodec->sample_rate == 8000 &&
151 acodec->codec_id == AV_CODEC_ID_PCM_MULAW;
152 case FLV_CODECID_PCM_ALAW:
153 return acodec->sample_rate == 8000 &&
154 acodec->codec_id == AV_CODEC_ID_PCM_ALAW;
156 return acodec->codec_tag == (flv_codecid >> FLV_AUDIO_CODECID_OFFSET);
160 static void flv_set_audio_codec(AVFormatContext *s, AVStream *astream,
161 AVCodecContext *acodec, int flv_codecid)
163 switch (flv_codecid) {
164 // no distinction between S16 and S8 PCM codec flags
165 case FLV_CODECID_PCM:
166 acodec->codec_id = acodec->bits_per_coded_sample == 8
169 : AV_CODEC_ID_PCM_S16BE;
171 : AV_CODEC_ID_PCM_S16LE;
174 case FLV_CODECID_PCM_LE:
175 acodec->codec_id = acodec->bits_per_coded_sample == 8
177 : AV_CODEC_ID_PCM_S16LE;
179 case FLV_CODECID_AAC:
180 acodec->codec_id = AV_CODEC_ID_AAC;
182 case FLV_CODECID_ADPCM:
183 acodec->codec_id = AV_CODEC_ID_ADPCM_SWF;
185 case FLV_CODECID_SPEEX:
186 acodec->codec_id = AV_CODEC_ID_SPEEX;
187 acodec->sample_rate = 16000;
189 case FLV_CODECID_MP3:
190 acodec->codec_id = AV_CODEC_ID_MP3;
191 astream->need_parsing = AVSTREAM_PARSE_FULL;
193 case FLV_CODECID_NELLYMOSER_8KHZ_MONO:
194 // in case metadata does not otherwise declare samplerate
195 acodec->sample_rate = 8000;
196 acodec->codec_id = AV_CODEC_ID_NELLYMOSER;
198 case FLV_CODECID_NELLYMOSER_16KHZ_MONO:
199 acodec->sample_rate = 16000;
200 acodec->codec_id = AV_CODEC_ID_NELLYMOSER;
202 case FLV_CODECID_NELLYMOSER:
203 acodec->codec_id = AV_CODEC_ID_NELLYMOSER;
205 case FLV_CODECID_PCM_MULAW:
206 acodec->sample_rate = 8000;
207 acodec->codec_id = AV_CODEC_ID_PCM_MULAW;
209 case FLV_CODECID_PCM_ALAW:
210 acodec->sample_rate = 8000;
211 acodec->codec_id = AV_CODEC_ID_PCM_ALAW;
214 avpriv_request_sample(s, "Audio codec (%x)",
215 flv_codecid >> FLV_AUDIO_CODECID_OFFSET);
216 acodec->codec_tag = flv_codecid >> FLV_AUDIO_CODECID_OFFSET;
220 static int flv_same_video_codec(AVCodecContext *vcodec, int flags)
222 int flv_codecid = flags & FLV_VIDEO_CODECID_MASK;
224 if (!vcodec->codec_id && !vcodec->codec_tag)
227 switch (flv_codecid) {
228 case FLV_CODECID_H263:
229 return vcodec->codec_id == AV_CODEC_ID_FLV1;
230 case FLV_CODECID_SCREEN:
231 return vcodec->codec_id == AV_CODEC_ID_FLASHSV;
232 case FLV_CODECID_SCREEN2:
233 return vcodec->codec_id == AV_CODEC_ID_FLASHSV2;
234 case FLV_CODECID_VP6:
235 return vcodec->codec_id == AV_CODEC_ID_VP6F;
236 case FLV_CODECID_VP6A:
237 return vcodec->codec_id == AV_CODEC_ID_VP6A;
238 case FLV_CODECID_H264:
239 return vcodec->codec_id == AV_CODEC_ID_H264;
241 return vcodec->codec_tag == flv_codecid;
245 static int flv_set_video_codec(AVFormatContext *s, AVStream *vstream,
246 int flv_codecid, int read)
248 AVCodecContext *vcodec = vstream->codec;
249 switch (flv_codecid) {
250 case FLV_CODECID_H263:
251 vcodec->codec_id = AV_CODEC_ID_FLV1;
253 case FLV_CODECID_REALH263:
254 vcodec->codec_id = AV_CODEC_ID_H263;
255 break; // Really mean it this time
256 case FLV_CODECID_SCREEN:
257 vcodec->codec_id = AV_CODEC_ID_FLASHSV;
259 case FLV_CODECID_SCREEN2:
260 vcodec->codec_id = AV_CODEC_ID_FLASHSV2;
262 case FLV_CODECID_VP6:
263 vcodec->codec_id = AV_CODEC_ID_VP6F;
264 case FLV_CODECID_VP6A:
265 if (flv_codecid == FLV_CODECID_VP6A)
266 vcodec->codec_id = AV_CODEC_ID_VP6A;
268 if (vcodec->extradata_size != 1) {
269 ff_alloc_extradata(vcodec, 1);
271 if (vcodec->extradata)
272 vcodec->extradata[0] = avio_r8(s->pb);
276 return 1; // 1 byte body size adjustment for flv_read_packet()
277 case FLV_CODECID_H264:
278 vcodec->codec_id = AV_CODEC_ID_H264;
279 vstream->need_parsing = AVSTREAM_PARSE_HEADERS;
280 return 3; // not 4, reading packet type will consume one byte
281 case FLV_CODECID_MPEG4:
282 vcodec->codec_id = AV_CODEC_ID_MPEG4;
285 avpriv_request_sample(s, "Video codec (%x)", flv_codecid);
286 vcodec->codec_tag = flv_codecid;
292 static int amf_get_string(AVIOContext *ioc, char *buffer, int buffsize)
294 int length = avio_rb16(ioc);
295 if (length >= buffsize) {
296 avio_skip(ioc, length);
300 avio_read(ioc, buffer, length);
302 buffer[length] = '\0';
307 static int parse_keyframes_index(AVFormatContext *s, AVIOContext *ioc,
308 AVStream *vstream, int64_t max_pos)
310 FLVContext *flv = s->priv_data;
311 unsigned int timeslen = 0, fileposlen = 0, i;
313 int64_t *times = NULL;
314 int64_t *filepositions = NULL;
315 int ret = AVERROR(ENOSYS);
316 int64_t initial_pos = avio_tell(ioc);
318 if (vstream->nb_index_entries>0) {
319 av_log(s, AV_LOG_WARNING, "Skipping duplicate index\n");
323 if (s->flags & AVFMT_FLAG_IGNIDX)
326 while (avio_tell(ioc) < max_pos - 2 &&
327 amf_get_string(ioc, str_val, sizeof(str_val)) > 0) {
328 int64_t **current_array;
329 unsigned int arraylen;
331 // Expect array object in context
332 if (avio_r8(ioc) != AMF_DATA_TYPE_ARRAY)
335 arraylen = avio_rb32(ioc);
339 if (!strcmp(KEYFRAMES_TIMESTAMP_TAG , str_val) && !times) {
340 current_array = ×
342 } else if (!strcmp(KEYFRAMES_BYTEOFFSET_TAG, str_val) &&
344 current_array = &filepositions;
345 fileposlen = arraylen;
347 // unexpected metatag inside keyframes, will not use such
348 // metadata for indexing
351 if (!(*current_array = av_mallocz(sizeof(**current_array) * arraylen))) {
352 ret = AVERROR(ENOMEM);
356 for (i = 0; i < arraylen && avio_tell(ioc) < max_pos - 1; i++) {
357 if (avio_r8(ioc) != AMF_DATA_TYPE_NUMBER)
359 current_array[0][i] = av_int2double(avio_rb64(ioc));
361 if (times && filepositions) {
362 // All done, exiting at a position allowing amf_parse_object
363 // to finish parsing the object
369 if (timeslen == fileposlen && fileposlen>1 && max_pos <= filepositions[0]) {
370 for (i = 0; i < fileposlen; i++) {
371 av_add_index_entry(vstream, filepositions[i], times[i] * 1000,
372 0, 0, AVINDEX_KEYFRAME);
374 flv->validate_index[i].pos = filepositions[i];
375 flv->validate_index[i].dts = times[i] * 1000;
376 flv->validate_count = i + 1;
381 av_log(s, AV_LOG_WARNING, "Invalid keyframes object, skipping.\n");
386 av_freep(&filepositions);
387 avio_seek(ioc, initial_pos, SEEK_SET);
391 static int amf_parse_object(AVFormatContext *s, AVStream *astream,
392 AVStream *vstream, const char *key,
393 int64_t max_pos, int depth)
395 AVCodecContext *acodec, *vcodec;
396 FLVContext *flv = s->priv_data;
398 AMFDataType amf_type;
404 amf_type = avio_r8(ioc);
407 case AMF_DATA_TYPE_NUMBER:
408 num_val = av_int2double(avio_rb64(ioc));
410 case AMF_DATA_TYPE_BOOL:
411 num_val = avio_r8(ioc);
413 case AMF_DATA_TYPE_STRING:
414 if (amf_get_string(ioc, str_val, sizeof(str_val)) < 0) {
415 av_log(s, AV_LOG_ERROR, "AMF_DATA_TYPE_STRING parsing failed\n");
419 case AMF_DATA_TYPE_OBJECT:
420 if ((vstream || astream) && key &&
422 !strcmp(KEYFRAMES_TAG, key) && depth == 1)
423 if (parse_keyframes_index(s, ioc, vstream ? vstream : astream,
425 av_log(s, AV_LOG_ERROR, "Keyframe index parsing failed\n");
427 while (avio_tell(ioc) < max_pos - 2 &&
428 amf_get_string(ioc, str_val, sizeof(str_val)) > 0)
429 if (amf_parse_object(s, astream, vstream, str_val, max_pos,
431 return -1; // if we couldn't skip, bomb out.
432 if (avio_r8(ioc) != AMF_END_OF_OBJECT) {
433 av_log(s, AV_LOG_ERROR, "Missing AMF_END_OF_OBJECT in AMF_DATA_TYPE_OBJECT\n");
437 case AMF_DATA_TYPE_NULL:
438 case AMF_DATA_TYPE_UNDEFINED:
439 case AMF_DATA_TYPE_UNSUPPORTED:
440 break; // these take up no additional space
441 case AMF_DATA_TYPE_MIXEDARRAY:
444 avio_skip(ioc, 4); // skip 32-bit max array index
445 while (avio_tell(ioc) < max_pos - 2 &&
446 amf_get_string(ioc, str_val, sizeof(str_val)) > 0)
447 // this is the only case in which we would want a nested
448 // parse to not skip over the object
449 if (amf_parse_object(s, astream, vstream, str_val, max_pos,
453 if (v != AMF_END_OF_OBJECT) {
454 av_log(s, AV_LOG_ERROR, "Missing AMF_END_OF_OBJECT in AMF_DATA_TYPE_MIXEDARRAY, found %d\n", v);
459 case AMF_DATA_TYPE_ARRAY:
461 unsigned int arraylen, i;
463 arraylen = avio_rb32(ioc);
464 for (i = 0; i < arraylen && avio_tell(ioc) < max_pos - 1; i++)
465 if (amf_parse_object(s, NULL, NULL, NULL, max_pos,
467 return -1; // if we couldn't skip, bomb out.
470 case AMF_DATA_TYPE_DATE:
471 avio_skip(ioc, 8 + 2); // timestamp (double) and UTC offset (int16)
473 default: // unsupported type, we couldn't skip
474 av_log(s, AV_LOG_ERROR, "unsupported amf type %d\n", amf_type);
479 acodec = astream ? astream->codec : NULL;
480 vcodec = vstream ? vstream->codec : NULL;
482 // stream info doesn't live any deeper than the first object
484 if (amf_type == AMF_DATA_TYPE_NUMBER ||
485 amf_type == AMF_DATA_TYPE_BOOL) {
486 if (!strcmp(key, "duration"))
487 s->duration = num_val * AV_TIME_BASE;
488 else if (!strcmp(key, "videodatarate") && vcodec &&
489 0 <= (int)(num_val * 1024.0))
490 vcodec->bit_rate = num_val * 1024.0;
491 else if (!strcmp(key, "audiodatarate") && acodec &&
492 0 <= (int)(num_val * 1024.0))
493 acodec->bit_rate = num_val * 1024.0;
494 else if (!strcmp(key, "datastream")) {
495 AVStream *st = create_stream(s, AVMEDIA_TYPE_SUBTITLE);
497 return AVERROR(ENOMEM);
498 st->codec->codec_id = AV_CODEC_ID_TEXT;
499 } else if (flv->trust_metadata) {
500 if (!strcmp(key, "videocodecid") && vcodec) {
501 flv_set_video_codec(s, vstream, num_val, 0);
502 } else if (!strcmp(key, "audiocodecid") && acodec) {
503 int id = ((int)num_val) << FLV_AUDIO_CODECID_OFFSET;
504 flv_set_audio_codec(s, astream, acodec, id);
505 } else if (!strcmp(key, "audiosamplerate") && acodec) {
506 acodec->sample_rate = num_val;
507 } else if (!strcmp(key, "audiosamplesize") && acodec) {
508 acodec->bits_per_coded_sample = num_val;
509 } else if (!strcmp(key, "stereo") && acodec) {
510 acodec->channels = num_val + 1;
511 acodec->channel_layout = acodec->channels == 2 ?
512 AV_CH_LAYOUT_STEREO :
514 } else if (!strcmp(key, "width") && vcodec) {
515 vcodec->width = num_val;
516 } else if (!strcmp(key, "height") && vcodec) {
517 vcodec->height = num_val;
521 if (amf_type == AMF_DATA_TYPE_STRING) {
522 if (!strcmp(key, "encoder")) {
524 if (1 == sscanf(str_val, "Open Broadcaster Software v0.%d", &version)) {
525 if (version > 0 && version <= 655)
526 flv->broken_sizes = 1;
528 } else if (!strcmp(key, "metadatacreator") && !strcmp(str_val, "MEGA")) {
529 flv->broken_sizes = 1;
534 if (amf_type == AMF_DATA_TYPE_OBJECT && s->nb_streams == 1 &&
535 ((!acodec && !strcmp(key, "audiocodecid")) ||
536 (!vcodec && !strcmp(key, "videocodecid"))))
537 s->ctx_flags &= ~AVFMTCTX_NOHEADER; //If there is either audio/video missing, codecid will be an empty object
539 if (!strcmp(key, "duration") ||
540 !strcmp(key, "filesize") ||
541 !strcmp(key, "width") ||
542 !strcmp(key, "height") ||
543 !strcmp(key, "videodatarate") ||
544 !strcmp(key, "framerate") ||
545 !strcmp(key, "videocodecid") ||
546 !strcmp(key, "audiodatarate") ||
547 !strcmp(key, "audiosamplerate") ||
548 !strcmp(key, "audiosamplesize") ||
549 !strcmp(key, "stereo") ||
550 !strcmp(key, "audiocodecid") ||
551 !strcmp(key, "datastream"))
554 s->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
555 if (amf_type == AMF_DATA_TYPE_BOOL) {
556 av_strlcpy(str_val, num_val > 0 ? "true" : "false",
558 av_dict_set(&s->metadata, key, str_val, 0);
559 } else if (amf_type == AMF_DATA_TYPE_NUMBER) {
560 snprintf(str_val, sizeof(str_val), "%.f", num_val);
561 av_dict_set(&s->metadata, key, str_val, 0);
562 } else if (amf_type == AMF_DATA_TYPE_STRING)
563 av_dict_set(&s->metadata, key, str_val, 0);
569 #define TYPE_ONTEXTDATA 1
570 #define TYPE_ONCAPTION 2
571 #define TYPE_ONCAPTIONINFO 3
572 #define TYPE_UNKNOWN 9
574 static int flv_read_metabody(AVFormatContext *s, int64_t next_pos)
577 AVStream *stream, *astream, *vstream;
578 AVStream av_unused *dstream;
581 // only needs to hold the string "onMetaData".
582 // Anything longer is something we don't want.
590 // first object needs to be "onMetaData" string
592 if (type != AMF_DATA_TYPE_STRING ||
593 amf_get_string(ioc, buffer, sizeof(buffer)) < 0)
596 if (!strcmp(buffer, "onTextData"))
597 return TYPE_ONTEXTDATA;
599 if (!strcmp(buffer, "onCaption"))
600 return TYPE_ONCAPTION;
602 if (!strcmp(buffer, "onCaptionInfo"))
603 return TYPE_ONCAPTIONINFO;
605 if (strcmp(buffer, "onMetaData") && strcmp(buffer, "onCuePoint")) {
606 av_log(s, AV_LOG_DEBUG, "Unknown type %s\n", buffer);
610 // find the streams now so that amf_parse_object doesn't need to do
611 // the lookup every time it is called.
612 for (i = 0; i < s->nb_streams; i++) {
613 stream = s->streams[i];
614 if (stream->codec->codec_type == AVMEDIA_TYPE_VIDEO)
616 else if (stream->codec->codec_type == AVMEDIA_TYPE_AUDIO)
618 else if (stream->codec->codec_type == AVMEDIA_TYPE_SUBTITLE)
622 // parse the second object (we want a mixed array)
623 if (amf_parse_object(s, astream, vstream, buffer, next_pos, 0) < 0)
629 static int flv_read_header(AVFormatContext *s)
634 flags = avio_r8(s->pb);
636 s->ctx_flags |= AVFMTCTX_NOHEADER;
638 if (flags & FLV_HEADER_FLAG_HASVIDEO)
639 if (!create_stream(s, AVMEDIA_TYPE_VIDEO))
640 return AVERROR(ENOMEM);
641 if (flags & FLV_HEADER_FLAG_HASAUDIO)
642 if (!create_stream(s, AVMEDIA_TYPE_AUDIO))
643 return AVERROR(ENOMEM);
644 // Flag doesn't indicate whether or not there is script-data present. Must
645 // create that stream if it's encountered.
647 offset = avio_rb32(s->pb);
648 avio_seek(s->pb, offset, SEEK_SET);
656 static int flv_read_close(AVFormatContext *s)
659 FLVContext *flv = s->priv_data;
660 for (i=0; i<FLV_STREAM_TYPE_NB; i++)
661 av_freep(&flv->new_extradata[i]);
665 static int flv_get_extradata(AVFormatContext *s, AVStream *st, int size)
667 av_freep(&st->codec->extradata);
668 if (ff_get_extradata(st->codec, s->pb, size) < 0)
669 return AVERROR(ENOMEM);
673 static int flv_queue_extradata(FLVContext *flv, AVIOContext *pb, int stream,
676 av_free(flv->new_extradata[stream]);
677 flv->new_extradata[stream] = av_mallocz(size +
678 AV_INPUT_BUFFER_PADDING_SIZE);
679 if (!flv->new_extradata[stream])
680 return AVERROR(ENOMEM);
681 flv->new_extradata_size[stream] = size;
682 avio_read(pb, flv->new_extradata[stream], size);
686 static void clear_index_entries(AVFormatContext *s, int64_t pos)
689 av_log(s, AV_LOG_WARNING,
690 "Found invalid index entries, clearing the index.\n");
691 for (i = 0; i < s->nb_streams; i++) {
692 AVStream *st = s->streams[i];
693 /* Remove all index entries that point to >= pos */
695 for (j = 0; j < st->nb_index_entries; j++)
696 if (st->index_entries[j].pos < pos)
697 st->index_entries[out++] = st->index_entries[j];
698 st->nb_index_entries = out;
702 static int amf_skip_tag(AVIOContext *pb, AMFDataType type)
704 int nb = -1, ret, parse_name = 1;
707 case AMF_DATA_TYPE_NUMBER:
710 case AMF_DATA_TYPE_BOOL:
713 case AMF_DATA_TYPE_STRING:
714 avio_skip(pb, avio_rb16(pb));
716 case AMF_DATA_TYPE_ARRAY:
718 case AMF_DATA_TYPE_MIXEDARRAY:
720 case AMF_DATA_TYPE_OBJECT:
721 while(!pb->eof_reached && (nb-- > 0 || type != AMF_DATA_TYPE_ARRAY)) {
723 int size = avio_rb16(pb);
730 if ((ret = amf_skip_tag(pb, avio_r8(pb))) < 0)
734 case AMF_DATA_TYPE_NULL:
735 case AMF_DATA_TYPE_OBJECT_END:
738 return AVERROR_INVALIDDATA;
743 static int flv_data_packet(AVFormatContext *s, AVPacket *pkt,
744 int64_t dts, int64_t next)
746 AVIOContext *pb = s->pb;
749 int ret = AVERROR_INVALIDDATA;
753 switch (avio_r8(pb)) {
754 case AMF_DATA_TYPE_ARRAY:
756 case AMF_DATA_TYPE_MIXEDARRAY:
757 avio_seek(pb, 4, SEEK_CUR);
758 case AMF_DATA_TYPE_OBJECT:
764 while (array || (ret = amf_get_string(pb, buf, sizeof(buf))) > 0) {
765 AMFDataType type = avio_r8(pb);
766 if (type == AMF_DATA_TYPE_STRING && (array || !strcmp(buf, "text"))) {
767 length = avio_rb16(pb);
768 ret = av_get_packet(pb, pkt, length);
774 if ((ret = amf_skip_tag(pb, type)) < 0)
780 ret = AVERROR_INVALIDDATA;
784 for (i = 0; i < s->nb_streams; i++) {
786 if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE)
790 if (i == s->nb_streams) {
791 st = create_stream(s, AVMEDIA_TYPE_SUBTITLE);
793 return AVERROR(ENOMEM);
794 st->codec->codec_id = AV_CODEC_ID_TEXT;
801 pkt->stream_index = st->index;
802 pkt->flags |= AV_PKT_FLAG_KEY;
805 avio_seek(s->pb, next + 4, SEEK_SET);
810 static int resync(AVFormatContext *s)
812 FLVContext *flv = s->priv_data;
814 int64_t pos = avio_tell(s->pb);
816 for (i=0; !avio_feof(s->pb); i++) {
817 int j = i & (RESYNC_BUFFER_SIZE-1);
818 int j1 = j + RESYNC_BUFFER_SIZE;
819 flv->resync_buffer[j ] =
820 flv->resync_buffer[j1] = avio_r8(s->pb);
823 unsigned lsize2 = AV_RB32(flv->resync_buffer + j1 - 4);
824 if (lsize2 >= 11 && lsize2 + 8LL < FFMIN(i, RESYNC_BUFFER_SIZE)) {
825 unsigned size2 = AV_RB24(flv->resync_buffer + j1 - lsize2 + 1 - 4);
826 unsigned lsize1 = AV_RB32(flv->resync_buffer + j1 - lsize2 - 8);
827 if (lsize1 >= 11 && lsize1 + 8LL + lsize2 < FFMIN(i, RESYNC_BUFFER_SIZE)) {
828 unsigned size1 = AV_RB24(flv->resync_buffer + j1 - lsize1 + 1 - lsize2 - 8);
829 if (size1 == lsize1 - 11 && size2 == lsize2 - 11) {
830 avio_seek(s->pb, pos + i - lsize1 - lsize2 - 8, SEEK_SET);
840 static int flv_read_packet(AVFormatContext *s, AVPacket *pkt)
842 FLVContext *flv = s->priv_data;
843 int ret, i, size, flags;
844 enum FlvTagType type;
846 int64_t next, pos, meta_pos;
847 int64_t dts, pts = AV_NOPTS_VALUE;
848 int av_uninit(channels);
849 int av_uninit(sample_rate);
855 /* pkt size is repeated at end. skip it */
856 pos = avio_tell(s->pb);
857 type = (avio_r8(s->pb) & 0x1F);
859 size = avio_rb24(s->pb);
860 dts = avio_rb24(s->pb);
861 dts |= (unsigned)avio_r8(s->pb) << 24;
862 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));
863 if (avio_feof(s->pb))
865 avio_skip(s->pb, 3); /* stream id, always 0 */
868 if (flv->validate_next < flv->validate_count) {
869 int64_t validate_pos = flv->validate_index[flv->validate_next].pos;
870 if (pos == validate_pos) {
871 if (FFABS(dts - flv->validate_index[flv->validate_next].dts) <=
872 VALIDATE_INDEX_TS_THRESH) {
873 flv->validate_next++;
875 clear_index_entries(s, validate_pos);
876 flv->validate_count = 0;
878 } else if (pos > validate_pos) {
879 clear_index_entries(s, validate_pos);
880 flv->validate_count = 0;
889 next = size + avio_tell(s->pb);
891 if (type == FLV_TAG_TYPE_AUDIO) {
892 stream_type = FLV_STREAM_TYPE_AUDIO;
893 flags = avio_r8(s->pb);
895 } else if (type == FLV_TAG_TYPE_VIDEO) {
896 stream_type = FLV_STREAM_TYPE_VIDEO;
897 flags = avio_r8(s->pb);
899 if ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_VIDEO_INFO_CMD)
901 } else if (type == FLV_TAG_TYPE_META) {
902 stream_type=FLV_STREAM_TYPE_DATA;
903 if (size > 13 + 1 + 4) { // Header-type metadata stuff
905 meta_pos = avio_tell(s->pb);
906 type = flv_read_metabody(s, next);
907 if (type == 0 && dts == 0 || type < 0 || type == TYPE_UNKNOWN) {
908 if (type < 0 && flv->validate_count &&
909 flv->validate_index[0].pos > next &&
910 flv->validate_index[0].pos - 4 < next
912 av_log(s, AV_LOG_WARNING, "Adjusting next position due to index mismatch\n");
913 next = flv->validate_index[0].pos - 4;
916 } else if (type == TYPE_ONTEXTDATA) {
917 avpriv_request_sample(s, "OnTextData packet");
918 return flv_data_packet(s, pkt, dts, next);
919 } else if (type == TYPE_ONCAPTION) {
920 return flv_data_packet(s, pkt, dts, next);
922 avio_seek(s->pb, meta_pos, SEEK_SET);
925 av_log(s, AV_LOG_DEBUG,
926 "Skipping flv packet: type %d, size %d, flags %d.\n",
929 avio_seek(s->pb, next, SEEK_SET);
934 /* skip empty data packets */
940 /* now find stream */
941 for (i = 0; i < s->nb_streams; i++) {
943 if (stream_type == FLV_STREAM_TYPE_AUDIO) {
944 if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
945 (s->audio_codec_id || flv_same_audio_codec(st->codec, flags)))
947 } else if (stream_type == FLV_STREAM_TYPE_VIDEO) {
948 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
949 (s->video_codec_id || flv_same_video_codec(st->codec, flags)))
951 } else if (stream_type == FLV_STREAM_TYPE_DATA) {
952 if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE)
956 if (i == s->nb_streams) {
957 static const enum AVMediaType stream_types[] = {AVMEDIA_TYPE_VIDEO, AVMEDIA_TYPE_AUDIO, AVMEDIA_TYPE_SUBTITLE};
958 av_log(s, AV_LOG_WARNING, "%s stream discovered after head already parsed\n", av_get_media_type_string(stream_types[stream_type]));
959 st = create_stream(s, stream_types[stream_type]);
961 return AVERROR(ENOMEM);
964 av_log(s, AV_LOG_TRACE, "%d %X %d \n", stream_type, flags, st->discard);
966 if (s->pb->seekable &&
967 ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY ||
968 stream_type == FLV_STREAM_TYPE_AUDIO))
969 av_add_index_entry(st, pos, dts, size, 0, AVINDEX_KEYFRAME);
971 if ( (st->discard >= AVDISCARD_NONKEY && !((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY || (stream_type == FLV_STREAM_TYPE_AUDIO)))
972 ||(st->discard >= AVDISCARD_BIDIR && ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_DISP_INTER && (stream_type == FLV_STREAM_TYPE_VIDEO)))
973 || st->discard >= AVDISCARD_ALL
975 avio_seek(s->pb, next, SEEK_SET);
980 // if not streamed and no duration from metadata then seek to end to find
981 // the duration from the timestamps
982 if (s->pb->seekable && (!s->duration || s->duration == AV_NOPTS_VALUE) && !flv->searched_for_end) {
984 const int64_t pos = avio_tell(s->pb);
985 // Read the last 4 bytes of the file, this should be the size of the
986 // previous FLV tag. Use the timestamp of its payload as duration.
987 int64_t fsize = avio_size(s->pb);
989 avio_seek(s->pb, fsize - 4, SEEK_SET);
990 size = avio_rb32(s->pb);
991 // Seek to the start of the last FLV tag at position (fsize - 4 - size)
992 // but skip the byte indicating the type.
993 avio_seek(s->pb, fsize - 3 - size, SEEK_SET);
994 if (size == avio_rb24(s->pb) + 11) {
995 uint32_t ts = avio_rb24(s->pb);
996 ts |= avio_r8(s->pb) << 24;
998 s->duration = ts * (int64_t)AV_TIME_BASE / 1000;
999 else if (fsize >= 8 && fsize - 8 >= size) {
1001 goto retry_duration;
1005 avio_seek(s->pb, pos, SEEK_SET);
1006 flv->searched_for_end = 1;
1009 if (stream_type == FLV_STREAM_TYPE_AUDIO) {
1010 int bits_per_coded_sample;
1011 channels = (flags & FLV_AUDIO_CHANNEL_MASK) == FLV_STEREO ? 2 : 1;
1012 sample_rate = 44100 << ((flags & FLV_AUDIO_SAMPLERATE_MASK) >>
1013 FLV_AUDIO_SAMPLERATE_OFFSET) >> 3;
1014 bits_per_coded_sample = (flags & FLV_AUDIO_SAMPLESIZE_MASK) ? 16 : 8;
1015 if (!st->codec->channels || !st->codec->sample_rate ||
1016 !st->codec->bits_per_coded_sample) {
1017 st->codec->channels = channels;
1018 st->codec->channel_layout = channels == 1
1020 : AV_CH_LAYOUT_STEREO;
1021 st->codec->sample_rate = sample_rate;
1022 st->codec->bits_per_coded_sample = bits_per_coded_sample;
1024 if (!st->codec->codec_id) {
1025 flv_set_audio_codec(s, st, st->codec,
1026 flags & FLV_AUDIO_CODECID_MASK);
1027 flv->last_sample_rate =
1028 sample_rate = st->codec->sample_rate;
1029 flv->last_channels =
1030 channels = st->codec->channels;
1032 AVCodecContext ctx = {0};
1033 ctx.sample_rate = sample_rate;
1034 ctx.bits_per_coded_sample = bits_per_coded_sample;
1035 flv_set_audio_codec(s, st, &ctx, flags & FLV_AUDIO_CODECID_MASK);
1036 sample_rate = ctx.sample_rate;
1038 } else if (stream_type == FLV_STREAM_TYPE_VIDEO) {
1039 size -= flv_set_video_codec(s, st, flags & FLV_VIDEO_CODECID_MASK, 1);
1040 } else if (stream_type == FLV_STREAM_TYPE_DATA) {
1041 st->codec->codec_id = AV_CODEC_ID_TEXT;
1044 if (st->codec->codec_id == AV_CODEC_ID_AAC ||
1045 st->codec->codec_id == AV_CODEC_ID_H264 ||
1046 st->codec->codec_id == AV_CODEC_ID_MPEG4) {
1047 int type = avio_r8(s->pb);
1049 if (st->codec->codec_id == AV_CODEC_ID_H264 || st->codec->codec_id == AV_CODEC_ID_MPEG4) {
1051 int32_t cts = (avio_rb24(s->pb) + 0xff800000) ^ 0xff800000;
1053 if (cts < 0) { // dts might be wrong
1054 if (!flv->wrong_dts)
1055 av_log(s, AV_LOG_WARNING,
1056 "Negative cts, previous timestamps might be wrong.\n");
1058 } else if (FFABS(dts - pts) > 1000*60*15) {
1059 av_log(s, AV_LOG_WARNING,
1060 "invalid timestamps %"PRId64" %"PRId64"\n", dts, pts);
1061 dts = pts = AV_NOPTS_VALUE;
1064 if (type == 0 && (!st->codec->extradata || st->codec->codec_id == AV_CODEC_ID_AAC ||
1065 st->codec->codec_id == AV_CODEC_ID_H264)) {
1066 AVDictionaryEntry *t;
1068 if (st->codec->extradata) {
1069 if ((ret = flv_queue_extradata(flv, s->pb, stream_type, size)) < 0)
1074 if ((ret = flv_get_extradata(s, st, size)) < 0)
1077 /* Workaround for buggy Omnia A/XE encoder */
1078 t = av_dict_get(s->metadata, "Encoder", NULL, 0);
1079 if (st->codec->codec_id == AV_CODEC_ID_AAC && t && !strcmp(t->value, "Omnia A/XE"))
1080 st->codec->extradata_size = 2;
1082 if (st->codec->codec_id == AV_CODEC_ID_AAC && 0) {
1083 MPEG4AudioConfig cfg;
1085 if (avpriv_mpeg4audio_get_config(&cfg, st->codec->extradata,
1086 st->codec->extradata_size * 8, 1) >= 0) {
1087 st->codec->channels = cfg.channels;
1088 st->codec->channel_layout = 0;
1089 if (cfg.ext_sample_rate)
1090 st->codec->sample_rate = cfg.ext_sample_rate;
1092 st->codec->sample_rate = cfg.sample_rate;
1093 av_log(s, AV_LOG_TRACE, "mp4a config channels %d sample rate %d\n",
1094 st->codec->channels, st->codec->sample_rate);
1103 /* skip empty data packets */
1109 ret = av_get_packet(s->pb, pkt, size);
1113 pkt->pts = pts == AV_NOPTS_VALUE ? dts : pts;
1114 pkt->stream_index = st->index;
1115 if (flv->new_extradata[stream_type]) {
1116 uint8_t *side = av_packet_new_side_data(pkt, AV_PKT_DATA_NEW_EXTRADATA,
1117 flv->new_extradata_size[stream_type]);
1119 memcpy(side, flv->new_extradata[stream_type],
1120 flv->new_extradata_size[stream_type]);
1121 av_freep(&flv->new_extradata[stream_type]);
1122 flv->new_extradata_size[stream_type] = 0;
1125 if (stream_type == FLV_STREAM_TYPE_AUDIO &&
1126 (sample_rate != flv->last_sample_rate ||
1127 channels != flv->last_channels)) {
1128 flv->last_sample_rate = sample_rate;
1129 flv->last_channels = channels;
1130 ff_add_param_change(pkt, channels, 0, sample_rate, 0, 0);
1133 if ( stream_type == FLV_STREAM_TYPE_AUDIO ||
1134 ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY) ||
1135 stream_type == FLV_STREAM_TYPE_DATA)
1136 pkt->flags |= AV_PKT_FLAG_KEY;
1139 last = avio_rb32(s->pb);
1140 if (last != orig_size + 11 &&
1141 (last != orig_size || !last) &&
1142 !flv->broken_sizes) {
1143 av_log(s, AV_LOG_ERROR, "Packet mismatch %d %d\n", last, orig_size + 11);
1144 avio_seek(s->pb, pos + 1, SEEK_SET);
1146 av_packet_unref(pkt);
1154 static int flv_read_seek(AVFormatContext *s, int stream_index,
1155 int64_t ts, int flags)
1157 FLVContext *flv = s->priv_data;
1158 flv->validate_count = 0;
1159 return avio_seek_time(s->pb, stream_index, ts, flags);
1162 #define OFFSET(x) offsetof(FLVContext, x)
1163 #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
1164 static const AVOption options[] = {
1165 { "flv_metadata", "Allocate streams according to the onMetaData array", OFFSET(trust_metadata), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VD },
1169 static const AVClass flv_class = {
1170 .class_name = "flvdec",
1171 .item_name = av_default_item_name,
1173 .version = LIBAVUTIL_VERSION_INT,
1176 AVInputFormat ff_flv_demuxer = {
1178 .long_name = NULL_IF_CONFIG_SMALL("FLV (Flash Video)"),
1179 .priv_data_size = sizeof(FLVContext),
1180 .read_probe = flv_probe,
1181 .read_header = flv_read_header,
1182 .read_packet = flv_read_packet,
1183 .read_seek = flv_read_seek,
1184 .read_close = flv_read_close,
1185 .extensions = "flv",
1186 .priv_class = &flv_class,
1189 static const AVClass live_flv_class = {
1190 .class_name = "live_flvdec",
1191 .item_name = av_default_item_name,
1193 .version = LIBAVUTIL_VERSION_INT,
1196 AVInputFormat ff_live_flv_demuxer = {
1198 .long_name = NULL_IF_CONFIG_SMALL("live RTMP FLV (Flash Video)"),
1199 .priv_data_size = sizeof(FLVContext),
1200 .read_probe = live_flv_probe,
1201 .read_header = flv_read_header,
1202 .read_packet = flv_read_packet,
1203 .read_seek = flv_read_seek,
1204 .read_close = flv_read_close,
1205 .extensions = "flv",
1206 .priv_class = &live_flv_class,
1207 .flags = AVFMT_TS_DISCONT