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;
532 if (amf_type == AMF_DATA_TYPE_OBJECT && s->nb_streams == 1 &&
533 ((!acodec && !strcmp(key, "audiocodecid")) ||
534 (!vcodec && !strcmp(key, "videocodecid"))))
535 s->ctx_flags &= ~AVFMTCTX_NOHEADER; //If there is either audio/video missing, codecid will be an empty object
537 if (!strcmp(key, "duration") ||
538 !strcmp(key, "filesize") ||
539 !strcmp(key, "width") ||
540 !strcmp(key, "height") ||
541 !strcmp(key, "videodatarate") ||
542 !strcmp(key, "framerate") ||
543 !strcmp(key, "videocodecid") ||
544 !strcmp(key, "audiodatarate") ||
545 !strcmp(key, "audiosamplerate") ||
546 !strcmp(key, "audiosamplesize") ||
547 !strcmp(key, "stereo") ||
548 !strcmp(key, "audiocodecid") ||
549 !strcmp(key, "datastream"))
552 s->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
553 if (amf_type == AMF_DATA_TYPE_BOOL) {
554 av_strlcpy(str_val, num_val > 0 ? "true" : "false",
556 av_dict_set(&s->metadata, key, str_val, 0);
557 } else if (amf_type == AMF_DATA_TYPE_NUMBER) {
558 snprintf(str_val, sizeof(str_val), "%.f", num_val);
559 av_dict_set(&s->metadata, key, str_val, 0);
560 } else if (amf_type == AMF_DATA_TYPE_STRING)
561 av_dict_set(&s->metadata, key, str_val, 0);
567 #define TYPE_ONTEXTDATA 1
568 #define TYPE_ONCAPTION 2
569 #define TYPE_ONCAPTIONINFO 3
570 #define TYPE_UNKNOWN 9
572 static int flv_read_metabody(AVFormatContext *s, int64_t next_pos)
575 AVStream *stream, *astream, *vstream;
576 AVStream av_unused *dstream;
579 // only needs to hold the string "onMetaData".
580 // Anything longer is something we don't want.
588 // first object needs to be "onMetaData" string
590 if (type != AMF_DATA_TYPE_STRING ||
591 amf_get_string(ioc, buffer, sizeof(buffer)) < 0)
594 if (!strcmp(buffer, "onTextData"))
595 return TYPE_ONTEXTDATA;
597 if (!strcmp(buffer, "onCaption"))
598 return TYPE_ONCAPTION;
600 if (!strcmp(buffer, "onCaptionInfo"))
601 return TYPE_ONCAPTIONINFO;
603 if (strcmp(buffer, "onMetaData") && strcmp(buffer, "onCuePoint")) {
604 av_log(s, AV_LOG_DEBUG, "Unknown type %s\n", buffer);
608 // find the streams now so that amf_parse_object doesn't need to do
609 // the lookup every time it is called.
610 for (i = 0; i < s->nb_streams; i++) {
611 stream = s->streams[i];
612 if (stream->codec->codec_type == AVMEDIA_TYPE_VIDEO)
614 else if (stream->codec->codec_type == AVMEDIA_TYPE_AUDIO)
616 else if (stream->codec->codec_type == AVMEDIA_TYPE_SUBTITLE)
620 // parse the second object (we want a mixed array)
621 if (amf_parse_object(s, astream, vstream, buffer, next_pos, 0) < 0)
627 static int flv_read_header(AVFormatContext *s)
632 flags = avio_r8(s->pb);
634 s->ctx_flags |= AVFMTCTX_NOHEADER;
636 if (flags & FLV_HEADER_FLAG_HASVIDEO)
637 if (!create_stream(s, AVMEDIA_TYPE_VIDEO))
638 return AVERROR(ENOMEM);
639 if (flags & FLV_HEADER_FLAG_HASAUDIO)
640 if (!create_stream(s, AVMEDIA_TYPE_AUDIO))
641 return AVERROR(ENOMEM);
642 // Flag doesn't indicate whether or not there is script-data present. Must
643 // create that stream if it's encountered.
645 offset = avio_rb32(s->pb);
646 avio_seek(s->pb, offset, SEEK_SET);
654 static int flv_read_close(AVFormatContext *s)
657 FLVContext *flv = s->priv_data;
658 for (i=0; i<FLV_STREAM_TYPE_NB; i++)
659 av_freep(&flv->new_extradata[i]);
663 static int flv_get_extradata(AVFormatContext *s, AVStream *st, int size)
665 av_freep(&st->codec->extradata);
666 if (ff_get_extradata(st->codec, s->pb, size) < 0)
667 return AVERROR(ENOMEM);
671 static int flv_queue_extradata(FLVContext *flv, AVIOContext *pb, int stream,
674 av_free(flv->new_extradata[stream]);
675 flv->new_extradata[stream] = av_mallocz(size +
676 AV_INPUT_BUFFER_PADDING_SIZE);
677 if (!flv->new_extradata[stream])
678 return AVERROR(ENOMEM);
679 flv->new_extradata_size[stream] = size;
680 avio_read(pb, flv->new_extradata[stream], size);
684 static void clear_index_entries(AVFormatContext *s, int64_t pos)
687 av_log(s, AV_LOG_WARNING,
688 "Found invalid index entries, clearing the index.\n");
689 for (i = 0; i < s->nb_streams; i++) {
690 AVStream *st = s->streams[i];
691 /* Remove all index entries that point to >= pos */
693 for (j = 0; j < st->nb_index_entries; j++)
694 if (st->index_entries[j].pos < pos)
695 st->index_entries[out++] = st->index_entries[j];
696 st->nb_index_entries = out;
700 static int amf_skip_tag(AVIOContext *pb, AMFDataType type)
702 int nb = -1, ret, parse_name = 1;
705 case AMF_DATA_TYPE_NUMBER:
708 case AMF_DATA_TYPE_BOOL:
711 case AMF_DATA_TYPE_STRING:
712 avio_skip(pb, avio_rb16(pb));
714 case AMF_DATA_TYPE_ARRAY:
716 case AMF_DATA_TYPE_MIXEDARRAY:
718 case AMF_DATA_TYPE_OBJECT:
719 while(!pb->eof_reached && (nb-- > 0 || type != AMF_DATA_TYPE_ARRAY)) {
721 int size = avio_rb16(pb);
728 if ((ret = amf_skip_tag(pb, avio_r8(pb))) < 0)
732 case AMF_DATA_TYPE_NULL:
733 case AMF_DATA_TYPE_OBJECT_END:
736 return AVERROR_INVALIDDATA;
741 static int flv_data_packet(AVFormatContext *s, AVPacket *pkt,
742 int64_t dts, int64_t next)
744 AVIOContext *pb = s->pb;
747 int ret = AVERROR_INVALIDDATA;
751 switch (avio_r8(pb)) {
752 case AMF_DATA_TYPE_ARRAY:
754 case AMF_DATA_TYPE_MIXEDARRAY:
755 avio_seek(pb, 4, SEEK_CUR);
756 case AMF_DATA_TYPE_OBJECT:
762 while (array || (ret = amf_get_string(pb, buf, sizeof(buf))) > 0) {
763 AMFDataType type = avio_r8(pb);
764 if (type == AMF_DATA_TYPE_STRING && (array || !strcmp(buf, "text"))) {
765 length = avio_rb16(pb);
766 ret = av_get_packet(pb, pkt, length);
772 if ((ret = amf_skip_tag(pb, type)) < 0)
778 ret = AVERROR_INVALIDDATA;
782 for (i = 0; i < s->nb_streams; i++) {
784 if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE)
788 if (i == s->nb_streams) {
789 st = create_stream(s, AVMEDIA_TYPE_SUBTITLE);
791 return AVERROR(ENOMEM);
792 st->codec->codec_id = AV_CODEC_ID_TEXT;
799 pkt->stream_index = st->index;
800 pkt->flags |= AV_PKT_FLAG_KEY;
803 avio_seek(s->pb, next + 4, SEEK_SET);
808 static int resync(AVFormatContext *s)
810 FLVContext *flv = s->priv_data;
812 int64_t pos = avio_tell(s->pb);
814 for (i=0; !avio_feof(s->pb); i++) {
815 int j = i & (RESYNC_BUFFER_SIZE-1);
816 int j1 = j + RESYNC_BUFFER_SIZE;
817 flv->resync_buffer[j ] =
818 flv->resync_buffer[j1] = avio_r8(s->pb);
821 unsigned lsize2 = AV_RB32(flv->resync_buffer + j1 - 4);
822 if (lsize2 >= 11 && lsize2 + 8LL < FFMIN(i, RESYNC_BUFFER_SIZE)) {
823 unsigned size2 = AV_RB24(flv->resync_buffer + j1 - lsize2 + 1 - 4);
824 unsigned lsize1 = AV_RB32(flv->resync_buffer + j1 - lsize2 - 8);
825 if (lsize1 >= 11 && lsize1 + 8LL + lsize2 < FFMIN(i, RESYNC_BUFFER_SIZE)) {
826 unsigned size1 = AV_RB24(flv->resync_buffer + j1 - lsize1 + 1 - lsize2 - 8);
827 if (size1 == lsize1 - 11 && size2 == lsize2 - 11) {
828 avio_seek(s->pb, pos + i - lsize1 - lsize2 - 8, SEEK_SET);
838 static int flv_read_packet(AVFormatContext *s, AVPacket *pkt)
840 FLVContext *flv = s->priv_data;
841 int ret, i, size, flags;
842 enum FlvTagType type;
844 int64_t next, pos, meta_pos;
845 int64_t dts, pts = AV_NOPTS_VALUE;
846 int av_uninit(channels);
847 int av_uninit(sample_rate);
853 /* pkt size is repeated at end. skip it */
854 pos = avio_tell(s->pb);
855 type = (avio_r8(s->pb) & 0x1F);
857 size = avio_rb24(s->pb);
858 dts = avio_rb24(s->pb);
859 dts |= avio_r8(s->pb) << 24;
860 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));
861 if (avio_feof(s->pb))
863 avio_skip(s->pb, 3); /* stream id, always 0 */
866 if (flv->validate_next < flv->validate_count) {
867 int64_t validate_pos = flv->validate_index[flv->validate_next].pos;
868 if (pos == validate_pos) {
869 if (FFABS(dts - flv->validate_index[flv->validate_next].dts) <=
870 VALIDATE_INDEX_TS_THRESH) {
871 flv->validate_next++;
873 clear_index_entries(s, validate_pos);
874 flv->validate_count = 0;
876 } else if (pos > validate_pos) {
877 clear_index_entries(s, validate_pos);
878 flv->validate_count = 0;
883 ret = AVERROR(EAGAIN);
887 next = size + avio_tell(s->pb);
889 if (type == FLV_TAG_TYPE_AUDIO) {
890 stream_type = FLV_STREAM_TYPE_AUDIO;
891 flags = avio_r8(s->pb);
893 } else if (type == FLV_TAG_TYPE_VIDEO) {
894 stream_type = FLV_STREAM_TYPE_VIDEO;
895 flags = avio_r8(s->pb);
897 if ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_VIDEO_INFO_CMD)
899 } else if (type == FLV_TAG_TYPE_META) {
900 stream_type=FLV_STREAM_TYPE_DATA;
901 if (size > 13 + 1 + 4) { // Header-type metadata stuff
903 meta_pos = avio_tell(s->pb);
904 type = flv_read_metabody(s, next);
905 if (type == 0 && dts == 0 || type < 0 || type == TYPE_UNKNOWN) {
906 if (type < 0 && flv->validate_count &&
907 flv->validate_index[0].pos > next &&
908 flv->validate_index[0].pos - 4 < next
910 av_log(s, AV_LOG_WARNING, "Adjusting next position due to index mismatch\n");
911 next = flv->validate_index[0].pos - 4;
914 } else if (type == TYPE_ONTEXTDATA) {
915 avpriv_request_sample(s, "OnTextData packet");
916 return flv_data_packet(s, pkt, dts, next);
917 } else if (type == TYPE_ONCAPTION) {
918 return flv_data_packet(s, pkt, dts, next);
920 avio_seek(s->pb, meta_pos, SEEK_SET);
923 av_log(s, AV_LOG_DEBUG,
924 "Skipping flv packet: type %d, size %d, flags %d.\n",
927 avio_seek(s->pb, next, SEEK_SET);
928 ret = AVERROR(EAGAIN);
932 /* skip empty data packets */
934 ret = AVERROR(EAGAIN);
938 /* now find stream */
939 for (i = 0; i < s->nb_streams; i++) {
941 if (stream_type == FLV_STREAM_TYPE_AUDIO) {
942 if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
943 (s->audio_codec_id || flv_same_audio_codec(st->codec, flags)))
945 } else if (stream_type == FLV_STREAM_TYPE_VIDEO) {
946 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
947 (s->video_codec_id || flv_same_video_codec(st->codec, flags)))
949 } else if (stream_type == FLV_STREAM_TYPE_DATA) {
950 if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE)
954 if (i == s->nb_streams) {
955 static const enum AVMediaType stream_types[] = {AVMEDIA_TYPE_VIDEO, AVMEDIA_TYPE_AUDIO, AVMEDIA_TYPE_SUBTITLE};
956 av_log(s, AV_LOG_WARNING, "%s stream discovered after head already parsed\n", av_get_media_type_string(stream_types[stream_type]));
957 st = create_stream(s, stream_types[stream_type]);
959 return AVERROR(ENOMEM);
962 av_log(s, AV_LOG_TRACE, "%d %X %d \n", stream_type, flags, st->discard);
964 if (s->pb->seekable &&
965 ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY ||
966 stream_type == FLV_STREAM_TYPE_AUDIO))
967 av_add_index_entry(st, pos, dts, size, 0, AVINDEX_KEYFRAME);
969 if ( (st->discard >= AVDISCARD_NONKEY && !((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY || (stream_type == FLV_STREAM_TYPE_AUDIO)))
970 ||(st->discard >= AVDISCARD_BIDIR && ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_DISP_INTER && (stream_type == FLV_STREAM_TYPE_VIDEO)))
971 || st->discard >= AVDISCARD_ALL
973 avio_seek(s->pb, next, SEEK_SET);
974 ret = AVERROR(EAGAIN);
978 // if not streamed and no duration from metadata then seek to end to find
979 // the duration from the timestamps
980 if (s->pb->seekable && (!s->duration || s->duration == AV_NOPTS_VALUE) && !flv->searched_for_end) {
982 const int64_t pos = avio_tell(s->pb);
983 // Read the last 4 bytes of the file, this should be the size of the
984 // previous FLV tag. Use the timestamp of its payload as duration.
985 int64_t fsize = avio_size(s->pb);
987 avio_seek(s->pb, fsize - 4, SEEK_SET);
988 size = avio_rb32(s->pb);
989 // Seek to the start of the last FLV tag at position (fsize - 4 - size)
990 // but skip the byte indicating the type.
991 avio_seek(s->pb, fsize - 3 - size, SEEK_SET);
992 if (size == avio_rb24(s->pb) + 11) {
993 uint32_t ts = avio_rb24(s->pb);
994 ts |= avio_r8(s->pb) << 24;
996 s->duration = ts * (int64_t)AV_TIME_BASE / 1000;
997 else if (fsize >= 8 && fsize - 8 >= size) {
1003 avio_seek(s->pb, pos, SEEK_SET);
1004 flv->searched_for_end = 1;
1007 if (stream_type == FLV_STREAM_TYPE_AUDIO) {
1008 int bits_per_coded_sample;
1009 channels = (flags & FLV_AUDIO_CHANNEL_MASK) == FLV_STEREO ? 2 : 1;
1010 sample_rate = 44100 << ((flags & FLV_AUDIO_SAMPLERATE_MASK) >>
1011 FLV_AUDIO_SAMPLERATE_OFFSET) >> 3;
1012 bits_per_coded_sample = (flags & FLV_AUDIO_SAMPLESIZE_MASK) ? 16 : 8;
1013 if (!st->codec->channels || !st->codec->sample_rate ||
1014 !st->codec->bits_per_coded_sample) {
1015 st->codec->channels = channels;
1016 st->codec->channel_layout = channels == 1
1018 : AV_CH_LAYOUT_STEREO;
1019 st->codec->sample_rate = sample_rate;
1020 st->codec->bits_per_coded_sample = bits_per_coded_sample;
1022 if (!st->codec->codec_id) {
1023 flv_set_audio_codec(s, st, st->codec,
1024 flags & FLV_AUDIO_CODECID_MASK);
1025 flv->last_sample_rate =
1026 sample_rate = st->codec->sample_rate;
1027 flv->last_channels =
1028 channels = st->codec->channels;
1030 AVCodecContext ctx = {0};
1031 ctx.sample_rate = sample_rate;
1032 ctx.bits_per_coded_sample = bits_per_coded_sample;
1033 flv_set_audio_codec(s, st, &ctx, flags & FLV_AUDIO_CODECID_MASK);
1034 sample_rate = ctx.sample_rate;
1036 } else if (stream_type == FLV_STREAM_TYPE_VIDEO) {
1037 size -= flv_set_video_codec(s, st, flags & FLV_VIDEO_CODECID_MASK, 1);
1038 } else if (stream_type == FLV_STREAM_TYPE_DATA) {
1039 st->codec->codec_id = AV_CODEC_ID_TEXT;
1042 if (st->codec->codec_id == AV_CODEC_ID_AAC ||
1043 st->codec->codec_id == AV_CODEC_ID_H264 ||
1044 st->codec->codec_id == AV_CODEC_ID_MPEG4) {
1045 int type = avio_r8(s->pb);
1047 if (st->codec->codec_id == AV_CODEC_ID_H264 || st->codec->codec_id == AV_CODEC_ID_MPEG4) {
1049 int32_t cts = (avio_rb24(s->pb) + 0xff800000) ^ 0xff800000;
1051 if (cts < 0) { // dts might be wrong
1052 if (!flv->wrong_dts)
1053 av_log(s, AV_LOG_WARNING,
1054 "Negative cts, previous timestamps might be wrong.\n");
1056 } else if (FFABS(dts - pts) > 1000*60*15) {
1057 av_log(s, AV_LOG_WARNING,
1058 "invalid timestamps %"PRId64" %"PRId64"\n", dts, pts);
1059 dts = pts = AV_NOPTS_VALUE;
1062 if (type == 0 && (!st->codec->extradata || st->codec->codec_id == AV_CODEC_ID_AAC ||
1063 st->codec->codec_id == AV_CODEC_ID_H264)) {
1064 AVDictionaryEntry *t;
1066 if (st->codec->extradata) {
1067 if ((ret = flv_queue_extradata(flv, s->pb, stream_type, size)) < 0)
1069 ret = AVERROR(EAGAIN);
1072 if ((ret = flv_get_extradata(s, st, size)) < 0)
1075 /* Workaround for buggy Omnia A/XE encoder */
1076 t = av_dict_get(s->metadata, "Encoder", NULL, 0);
1077 if (st->codec->codec_id == AV_CODEC_ID_AAC && t && !strcmp(t->value, "Omnia A/XE"))
1078 st->codec->extradata_size = 2;
1080 if (st->codec->codec_id == AV_CODEC_ID_AAC && 0) {
1081 MPEG4AudioConfig cfg;
1083 if (avpriv_mpeg4audio_get_config(&cfg, st->codec->extradata,
1084 st->codec->extradata_size * 8, 1) >= 0) {
1085 st->codec->channels = cfg.channels;
1086 st->codec->channel_layout = 0;
1087 if (cfg.ext_sample_rate)
1088 st->codec->sample_rate = cfg.ext_sample_rate;
1090 st->codec->sample_rate = cfg.sample_rate;
1091 av_log(s, AV_LOG_TRACE, "mp4a config channels %d sample rate %d\n",
1092 st->codec->channels, st->codec->sample_rate);
1096 ret = AVERROR(EAGAIN);
1101 /* skip empty data packets */
1103 ret = AVERROR(EAGAIN);
1107 ret = av_get_packet(s->pb, pkt, size);
1111 pkt->pts = pts == AV_NOPTS_VALUE ? dts : pts;
1112 pkt->stream_index = st->index;
1113 if (flv->new_extradata[stream_type]) {
1114 uint8_t *side = av_packet_new_side_data(pkt, AV_PKT_DATA_NEW_EXTRADATA,
1115 flv->new_extradata_size[stream_type]);
1117 memcpy(side, flv->new_extradata[stream_type],
1118 flv->new_extradata_size[stream_type]);
1119 av_freep(&flv->new_extradata[stream_type]);
1120 flv->new_extradata_size[stream_type] = 0;
1123 if (stream_type == FLV_STREAM_TYPE_AUDIO &&
1124 (sample_rate != flv->last_sample_rate ||
1125 channels != flv->last_channels)) {
1126 flv->last_sample_rate = sample_rate;
1127 flv->last_channels = channels;
1128 ff_add_param_change(pkt, channels, 0, sample_rate, 0, 0);
1131 if ( stream_type == FLV_STREAM_TYPE_AUDIO ||
1132 ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY) ||
1133 stream_type == FLV_STREAM_TYPE_DATA)
1134 pkt->flags |= AV_PKT_FLAG_KEY;
1137 last = avio_rb32(s->pb);
1138 if (last != orig_size + 11 &&
1139 (last != orig_size || !last) &&
1140 !flv->broken_sizes) {
1141 av_log(s, AV_LOG_ERROR, "Packet mismatch %d %d\n", last, orig_size + 11);
1142 avio_seek(s->pb, pos + 1, SEEK_SET);
1144 av_free_packet(pkt);
1152 static int flv_read_seek(AVFormatContext *s, int stream_index,
1153 int64_t ts, int flags)
1155 FLVContext *flv = s->priv_data;
1156 flv->validate_count = 0;
1157 return avio_seek_time(s->pb, stream_index, ts, flags);
1160 #define OFFSET(x) offsetof(FLVContext, x)
1161 #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
1162 static const AVOption options[] = {
1163 { "flv_metadata", "Allocate streams according to the onMetaData array", OFFSET(trust_metadata), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VD },
1167 static const AVClass flv_class = {
1168 .class_name = "flvdec",
1169 .item_name = av_default_item_name,
1171 .version = LIBAVUTIL_VERSION_INT,
1174 AVInputFormat ff_flv_demuxer = {
1176 .long_name = NULL_IF_CONFIG_SMALL("FLV (Flash Video)"),
1177 .priv_data_size = sizeof(FLVContext),
1178 .read_probe = flv_probe,
1179 .read_header = flv_read_header,
1180 .read_packet = flv_read_packet,
1181 .read_seek = flv_read_seek,
1182 .read_close = flv_read_close,
1183 .extensions = "flv",
1184 .priv_class = &flv_class,
1187 static const AVClass live_flv_class = {
1188 .class_name = "live_flvdec",
1189 .item_name = av_default_item_name,
1191 .version = LIBAVUTIL_VERSION_INT,
1194 AVInputFormat ff_live_flv_demuxer = {
1196 .long_name = NULL_IF_CONFIG_SMALL("live RTMP FLV (Flash Video)"),
1197 .priv_data_size = sizeof(FLVContext),
1198 .read_probe = live_flv_probe,
1199 .read_header = flv_read_header,
1200 .read_packet = flv_read_packet,
1201 .read_seek = flv_read_seek,
1202 .read_close = flv_read_close,
1203 .extensions = "flv",
1204 .priv_class = &live_flv_class,
1205 .flags = AVFMT_TS_DISCONT