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;
72 static int probe(AVProbeData *p, int live)
74 const uint8_t *d = p->buf;
75 unsigned offset = AV_RB32(d + 5);
80 d[3] < 5 && d[5] == 0 &&
81 offset + 100 < p->buf_size &&
83 int is_live = !memcmp(d + offset + 40, "NGINX RTMP", 10);
86 return AVPROBE_SCORE_MAX;
91 static int flv_probe(AVProbeData *p)
96 static int live_flv_probe(AVProbeData *p)
101 static void add_keyframes_index(AVFormatContext *s)
103 FLVContext *flv = s->priv_data;
104 AVStream *stream = NULL;
107 if (flv->last_keyframe_stream_index < 0) {
108 av_log(s, AV_LOG_DEBUG, "keyframe stream hasn't been created\n");
112 av_assert0(flv->last_keyframe_stream_index <= s->nb_streams);
113 stream = s->streams[flv->last_keyframe_stream_index];
115 if (stream->nb_index_entries == 0) {
116 for (i = 0; i < flv->keyframe_count; i++) {
117 av_add_index_entry(stream, flv->keyframe_filepositions[i],
118 flv->keyframe_times[i] * 1000, 0, 0, AVINDEX_KEYFRAME);
121 av_log(s, AV_LOG_WARNING, "Skipping duplicate index\n");
123 if (stream->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
124 av_freep(&flv->keyframe_times);
125 av_freep(&flv->keyframe_filepositions);
126 flv->keyframe_count = 0;
130 static AVStream *create_stream(AVFormatContext *s, int codec_type)
132 FLVContext *flv = s->priv_data;
133 AVStream *st = avformat_new_stream(s, NULL);
136 st->codecpar->codec_type = codec_type;
137 if (s->nb_streams>=3 ||( s->nb_streams==2
138 && s->streams[0]->codecpar->codec_type != AVMEDIA_TYPE_SUBTITLE
139 && s->streams[1]->codecpar->codec_type != AVMEDIA_TYPE_SUBTITLE))
140 s->ctx_flags &= ~AVFMTCTX_NOHEADER;
141 if (codec_type == AVMEDIA_TYPE_AUDIO)
142 flv->missing_streams &= ~FLV_HEADER_FLAG_HASAUDIO;
143 if (codec_type == AVMEDIA_TYPE_VIDEO)
144 flv->missing_streams &= ~FLV_HEADER_FLAG_HASVIDEO;
147 avpriv_set_pts_info(st, 32, 1, 1000); /* 32 bit pts in ms */
148 flv->last_keyframe_stream_index = s->nb_streams - 1;
149 add_keyframes_index(s);
153 static int flv_same_audio_codec(AVCodecParameters *apar, int flags)
155 int bits_per_coded_sample = (flags & FLV_AUDIO_SAMPLESIZE_MASK) ? 16 : 8;
156 int flv_codecid = flags & FLV_AUDIO_CODECID_MASK;
159 if (!apar->codec_id && !apar->codec_tag)
162 if (apar->bits_per_coded_sample != bits_per_coded_sample)
165 switch (flv_codecid) {
166 // no distinction between S16 and S8 PCM codec flags
167 case FLV_CODECID_PCM:
168 codec_id = bits_per_coded_sample == 8
171 : AV_CODEC_ID_PCM_S16BE;
173 : AV_CODEC_ID_PCM_S16LE;
175 return codec_id == apar->codec_id;
176 case FLV_CODECID_PCM_LE:
177 codec_id = bits_per_coded_sample == 8
179 : AV_CODEC_ID_PCM_S16LE;
180 return codec_id == apar->codec_id;
181 case FLV_CODECID_AAC:
182 return apar->codec_id == AV_CODEC_ID_AAC;
183 case FLV_CODECID_ADPCM:
184 return apar->codec_id == AV_CODEC_ID_ADPCM_SWF;
185 case FLV_CODECID_SPEEX:
186 return apar->codec_id == AV_CODEC_ID_SPEEX;
187 case FLV_CODECID_MP3:
188 return apar->codec_id == AV_CODEC_ID_MP3;
189 case FLV_CODECID_NELLYMOSER_8KHZ_MONO:
190 case FLV_CODECID_NELLYMOSER_16KHZ_MONO:
191 case FLV_CODECID_NELLYMOSER:
192 return apar->codec_id == AV_CODEC_ID_NELLYMOSER;
193 case FLV_CODECID_PCM_MULAW:
194 return apar->sample_rate == 8000 &&
195 apar->codec_id == AV_CODEC_ID_PCM_MULAW;
196 case FLV_CODECID_PCM_ALAW:
197 return apar->sample_rate == 8000 &&
198 apar->codec_id == AV_CODEC_ID_PCM_ALAW;
200 return apar->codec_tag == (flv_codecid >> FLV_AUDIO_CODECID_OFFSET);
204 static void flv_set_audio_codec(AVFormatContext *s, AVStream *astream,
205 AVCodecParameters *apar, int flv_codecid)
207 switch (flv_codecid) {
208 // no distinction between S16 and S8 PCM codec flags
209 case FLV_CODECID_PCM:
210 apar->codec_id = apar->bits_per_coded_sample == 8
213 : AV_CODEC_ID_PCM_S16BE;
215 : AV_CODEC_ID_PCM_S16LE;
218 case FLV_CODECID_PCM_LE:
219 apar->codec_id = apar->bits_per_coded_sample == 8
221 : AV_CODEC_ID_PCM_S16LE;
223 case FLV_CODECID_AAC:
224 apar->codec_id = AV_CODEC_ID_AAC;
226 case FLV_CODECID_ADPCM:
227 apar->codec_id = AV_CODEC_ID_ADPCM_SWF;
229 case FLV_CODECID_SPEEX:
230 apar->codec_id = AV_CODEC_ID_SPEEX;
231 apar->sample_rate = 16000;
233 case FLV_CODECID_MP3:
234 apar->codec_id = AV_CODEC_ID_MP3;
235 astream->need_parsing = AVSTREAM_PARSE_FULL;
237 case FLV_CODECID_NELLYMOSER_8KHZ_MONO:
238 // in case metadata does not otherwise declare samplerate
239 apar->sample_rate = 8000;
240 apar->codec_id = AV_CODEC_ID_NELLYMOSER;
242 case FLV_CODECID_NELLYMOSER_16KHZ_MONO:
243 apar->sample_rate = 16000;
244 apar->codec_id = AV_CODEC_ID_NELLYMOSER;
246 case FLV_CODECID_NELLYMOSER:
247 apar->codec_id = AV_CODEC_ID_NELLYMOSER;
249 case FLV_CODECID_PCM_MULAW:
250 apar->sample_rate = 8000;
251 apar->codec_id = AV_CODEC_ID_PCM_MULAW;
253 case FLV_CODECID_PCM_ALAW:
254 apar->sample_rate = 8000;
255 apar->codec_id = AV_CODEC_ID_PCM_ALAW;
258 avpriv_request_sample(s, "Audio codec (%x)",
259 flv_codecid >> FLV_AUDIO_CODECID_OFFSET);
260 apar->codec_tag = flv_codecid >> FLV_AUDIO_CODECID_OFFSET;
264 static int flv_same_video_codec(AVCodecParameters *vpar, int flags)
266 int flv_codecid = flags & FLV_VIDEO_CODECID_MASK;
268 if (!vpar->codec_id && !vpar->codec_tag)
271 switch (flv_codecid) {
272 case FLV_CODECID_H263:
273 return vpar->codec_id == AV_CODEC_ID_FLV1;
274 case FLV_CODECID_SCREEN:
275 return vpar->codec_id == AV_CODEC_ID_FLASHSV;
276 case FLV_CODECID_SCREEN2:
277 return vpar->codec_id == AV_CODEC_ID_FLASHSV2;
278 case FLV_CODECID_VP6:
279 return vpar->codec_id == AV_CODEC_ID_VP6F;
280 case FLV_CODECID_VP6A:
281 return vpar->codec_id == AV_CODEC_ID_VP6A;
282 case FLV_CODECID_H264:
283 return vpar->codec_id == AV_CODEC_ID_H264;
285 return vpar->codec_tag == flv_codecid;
289 static int flv_set_video_codec(AVFormatContext *s, AVStream *vstream,
290 int flv_codecid, int read)
292 AVCodecParameters *par = vstream->codecpar;
293 switch (flv_codecid) {
294 case FLV_CODECID_H263:
295 par->codec_id = AV_CODEC_ID_FLV1;
297 case FLV_CODECID_REALH263:
298 par->codec_id = AV_CODEC_ID_H263;
299 break; // Really mean it this time
300 case FLV_CODECID_SCREEN:
301 par->codec_id = AV_CODEC_ID_FLASHSV;
303 case FLV_CODECID_SCREEN2:
304 par->codec_id = AV_CODEC_ID_FLASHSV2;
306 case FLV_CODECID_VP6:
307 par->codec_id = AV_CODEC_ID_VP6F;
308 case FLV_CODECID_VP6A:
309 if (flv_codecid == FLV_CODECID_VP6A)
310 par->codec_id = AV_CODEC_ID_VP6A;
312 if (par->extradata_size != 1) {
313 ff_alloc_extradata(par, 1);
316 par->extradata[0] = avio_r8(s->pb);
320 return 1; // 1 byte body size adjustment for flv_read_packet()
321 case FLV_CODECID_H264:
322 par->codec_id = AV_CODEC_ID_H264;
323 vstream->need_parsing = AVSTREAM_PARSE_HEADERS;
324 return 3; // not 4, reading packet type will consume one byte
325 case FLV_CODECID_MPEG4:
326 par->codec_id = AV_CODEC_ID_MPEG4;
329 avpriv_request_sample(s, "Video codec (%x)", flv_codecid);
330 par->codec_tag = flv_codecid;
336 static int amf_get_string(AVIOContext *ioc, char *buffer, int buffsize)
338 int length = avio_rb16(ioc);
339 if (length >= buffsize) {
340 avio_skip(ioc, length);
344 avio_read(ioc, buffer, length);
346 buffer[length] = '\0';
351 static int parse_keyframes_index(AVFormatContext *s, AVIOContext *ioc, int64_t max_pos)
353 FLVContext *flv = s->priv_data;
354 unsigned int timeslen = 0, fileposlen = 0, i;
356 int64_t *times = NULL;
357 int64_t *filepositions = NULL;
358 int ret = AVERROR(ENOSYS);
359 int64_t initial_pos = avio_tell(ioc);
361 if (flv->keyframe_count > 0) {
362 av_log(s, AV_LOG_DEBUG, "keyframes have been paresed\n");
365 av_assert0(!flv->keyframe_times);
366 av_assert0(!flv->keyframe_filepositions);
368 if (s->flags & AVFMT_FLAG_IGNIDX)
371 while (avio_tell(ioc) < max_pos - 2 &&
372 amf_get_string(ioc, str_val, sizeof(str_val)) > 0) {
373 int64_t **current_array;
374 unsigned int arraylen;
376 // Expect array object in context
377 if (avio_r8(ioc) != AMF_DATA_TYPE_ARRAY)
380 arraylen = avio_rb32(ioc);
384 if (!strcmp(KEYFRAMES_TIMESTAMP_TAG , str_val) && !times) {
385 current_array = ×
387 } else if (!strcmp(KEYFRAMES_BYTEOFFSET_TAG, str_val) &&
389 current_array = &filepositions;
390 fileposlen = arraylen;
392 // unexpected metatag inside keyframes, will not use such
393 // metadata for indexing
396 if (!(*current_array = av_mallocz(sizeof(**current_array) * arraylen))) {
397 ret = AVERROR(ENOMEM);
401 for (i = 0; i < arraylen && avio_tell(ioc) < max_pos - 1; i++) {
402 if (avio_r8(ioc) != AMF_DATA_TYPE_NUMBER)
404 current_array[0][i] = av_int2double(avio_rb64(ioc));
406 if (times && filepositions) {
407 // All done, exiting at a position allowing amf_parse_object
408 // to finish parsing the object
414 if (timeslen == fileposlen && fileposlen>1 && max_pos <= filepositions[0]) {
415 for (i = 0; i < FFMIN(2,fileposlen); i++) {
416 flv->validate_index[i].pos = filepositions[i];
417 flv->validate_index[i].dts = times[i] * 1000;
418 flv->validate_count = i + 1;
420 flv->keyframe_times = times;
421 flv->keyframe_filepositions = filepositions;
422 flv->keyframe_count = timeslen;
424 filepositions = NULL;
427 av_log(s, AV_LOG_WARNING, "Invalid keyframes object, skipping.\n");
432 av_freep(&filepositions);
433 avio_seek(ioc, initial_pos, SEEK_SET);
437 static int amf_parse_object(AVFormatContext *s, AVStream *astream,
438 AVStream *vstream, const char *key,
439 int64_t max_pos, int depth)
441 AVCodecParameters *apar, *vpar;
442 FLVContext *flv = s->priv_data;
444 AMFDataType amf_type;
450 amf_type = avio_r8(ioc);
453 case AMF_DATA_TYPE_NUMBER:
454 num_val = av_int2double(avio_rb64(ioc));
456 case AMF_DATA_TYPE_BOOL:
457 num_val = avio_r8(ioc);
459 case AMF_DATA_TYPE_STRING:
460 if (amf_get_string(ioc, str_val, sizeof(str_val)) < 0) {
461 av_log(s, AV_LOG_ERROR, "AMF_DATA_TYPE_STRING parsing failed\n");
465 case AMF_DATA_TYPE_OBJECT:
468 !strcmp(KEYFRAMES_TAG, key) && depth == 1)
469 if (parse_keyframes_index(s, ioc,
471 av_log(s, AV_LOG_ERROR, "Keyframe index parsing failed\n");
473 add_keyframes_index(s);
474 while (avio_tell(ioc) < max_pos - 2 &&
475 amf_get_string(ioc, str_val, sizeof(str_val)) > 0)
476 if (amf_parse_object(s, astream, vstream, str_val, max_pos,
478 return -1; // if we couldn't skip, bomb out.
479 if (avio_r8(ioc) != AMF_END_OF_OBJECT) {
480 av_log(s, AV_LOG_ERROR, "Missing AMF_END_OF_OBJECT in AMF_DATA_TYPE_OBJECT\n");
484 case AMF_DATA_TYPE_NULL:
485 case AMF_DATA_TYPE_UNDEFINED:
486 case AMF_DATA_TYPE_UNSUPPORTED:
487 break; // these take up no additional space
488 case AMF_DATA_TYPE_MIXEDARRAY:
491 avio_skip(ioc, 4); // skip 32-bit max array index
492 while (avio_tell(ioc) < max_pos - 2 &&
493 amf_get_string(ioc, str_val, sizeof(str_val)) > 0)
494 // this is the only case in which we would want a nested
495 // parse to not skip over the object
496 if (amf_parse_object(s, astream, vstream, str_val, max_pos,
500 if (v != AMF_END_OF_OBJECT) {
501 av_log(s, AV_LOG_ERROR, "Missing AMF_END_OF_OBJECT in AMF_DATA_TYPE_MIXEDARRAY, found %d\n", v);
506 case AMF_DATA_TYPE_ARRAY:
508 unsigned int arraylen, i;
510 arraylen = avio_rb32(ioc);
511 for (i = 0; i < arraylen && avio_tell(ioc) < max_pos - 1; i++)
512 if (amf_parse_object(s, NULL, NULL, NULL, max_pos,
514 return -1; // if we couldn't skip, bomb out.
517 case AMF_DATA_TYPE_DATE:
518 avio_skip(ioc, 8 + 2); // timestamp (double) and UTC offset (int16)
520 default: // unsupported type, we couldn't skip
521 av_log(s, AV_LOG_ERROR, "unsupported amf type %d\n", amf_type);
526 apar = astream ? astream->codecpar : NULL;
527 vpar = vstream ? vstream->codecpar : NULL;
529 // stream info doesn't live any deeper than the first object
531 if (amf_type == AMF_DATA_TYPE_NUMBER ||
532 amf_type == AMF_DATA_TYPE_BOOL) {
533 if (!strcmp(key, "duration"))
534 s->duration = num_val * AV_TIME_BASE;
535 else if (!strcmp(key, "videodatarate") && vpar &&
536 0 <= (int)(num_val * 1024.0))
537 vpar->bit_rate = num_val * 1024.0;
538 else if (!strcmp(key, "audiodatarate") && apar &&
539 0 <= (int)(num_val * 1024.0))
540 apar->bit_rate = num_val * 1024.0;
541 else if (!strcmp(key, "datastream")) {
542 AVStream *st = create_stream(s, AVMEDIA_TYPE_SUBTITLE);
544 return AVERROR(ENOMEM);
545 st->codecpar->codec_id = AV_CODEC_ID_TEXT;
546 } else if (flv->trust_metadata) {
547 if (!strcmp(key, "videocodecid") && vpar) {
548 flv_set_video_codec(s, vstream, num_val, 0);
549 } else if (!strcmp(key, "audiocodecid") && apar) {
550 int id = ((int)num_val) << FLV_AUDIO_CODECID_OFFSET;
551 flv_set_audio_codec(s, astream, apar, id);
552 } else if (!strcmp(key, "audiosamplerate") && apar) {
553 apar->sample_rate = num_val;
554 } else if (!strcmp(key, "audiosamplesize") && apar) {
555 apar->bits_per_coded_sample = num_val;
556 } else if (!strcmp(key, "stereo") && apar) {
557 apar->channels = num_val + 1;
558 apar->channel_layout = apar->channels == 2 ?
559 AV_CH_LAYOUT_STEREO :
561 } else if (!strcmp(key, "width") && vpar) {
562 vpar->width = num_val;
563 } else if (!strcmp(key, "height") && vpar) {
564 vpar->height = num_val;
568 if (amf_type == AMF_DATA_TYPE_STRING) {
569 if (!strcmp(key, "encoder")) {
571 if (1 == sscanf(str_val, "Open Broadcaster Software v0.%d", &version)) {
572 if (version > 0 && version <= 655)
573 flv->broken_sizes = 1;
575 } else if (!strcmp(key, "metadatacreator") && !strcmp(str_val, "MEGA")) {
576 flv->broken_sizes = 1;
581 if (amf_type == AMF_DATA_TYPE_OBJECT && s->nb_streams == 1 &&
582 ((!apar && !strcmp(key, "audiocodecid")) ||
583 (!vpar && !strcmp(key, "videocodecid"))))
584 s->ctx_flags &= ~AVFMTCTX_NOHEADER; //If there is either audio/video missing, codecid will be an empty object
586 if (!strcmp(key, "duration") ||
587 !strcmp(key, "filesize") ||
588 !strcmp(key, "width") ||
589 !strcmp(key, "height") ||
590 !strcmp(key, "videodatarate") ||
591 !strcmp(key, "framerate") ||
592 !strcmp(key, "videocodecid") ||
593 !strcmp(key, "audiodatarate") ||
594 !strcmp(key, "audiosamplerate") ||
595 !strcmp(key, "audiosamplesize") ||
596 !strcmp(key, "stereo") ||
597 !strcmp(key, "audiocodecid") ||
598 !strcmp(key, "datastream"))
601 s->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
602 if (amf_type == AMF_DATA_TYPE_BOOL) {
603 av_strlcpy(str_val, num_val > 0 ? "true" : "false",
605 av_dict_set(&s->metadata, key, str_val, 0);
606 } else if (amf_type == AMF_DATA_TYPE_NUMBER) {
607 snprintf(str_val, sizeof(str_val), "%.f", num_val);
608 av_dict_set(&s->metadata, key, str_val, 0);
609 } else if (amf_type == AMF_DATA_TYPE_STRING)
610 av_dict_set(&s->metadata, key, str_val, 0);
616 #define TYPE_ONTEXTDATA 1
617 #define TYPE_ONCAPTION 2
618 #define TYPE_ONCAPTIONINFO 3
619 #define TYPE_UNKNOWN 9
621 static int flv_read_metabody(AVFormatContext *s, int64_t next_pos)
623 FLVContext *flv = s->priv_data;
625 AVStream *stream, *astream, *vstream;
626 AVStream av_unused *dstream;
629 // only needs to hold the string "onMetaData".
630 // Anything longer is something we don't want.
638 // first object needs to be "onMetaData" string
640 if (type != AMF_DATA_TYPE_STRING ||
641 amf_get_string(ioc, buffer, sizeof(buffer)) < 0)
644 if (!strcmp(buffer, "onTextData"))
645 return TYPE_ONTEXTDATA;
647 if (!strcmp(buffer, "onCaption"))
648 return TYPE_ONCAPTION;
650 if (!strcmp(buffer, "onCaptionInfo"))
651 return TYPE_ONCAPTIONINFO;
653 if (strcmp(buffer, "onMetaData") && strcmp(buffer, "onCuePoint")) {
654 av_log(s, AV_LOG_DEBUG, "Unknown type %s\n", buffer);
658 // find the streams now so that amf_parse_object doesn't need to do
659 // the lookup every time it is called.
660 for (i = 0; i < s->nb_streams; i++) {
661 stream = s->streams[i];
662 if (stream->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
664 flv->last_keyframe_stream_index = i;
665 } else if (stream->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
667 if (flv->last_keyframe_stream_index == -1)
668 flv->last_keyframe_stream_index = i;
670 else if (stream->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE)
674 // parse the second object (we want a mixed array)
675 if (amf_parse_object(s, astream, vstream, buffer, next_pos, 0) < 0)
681 static int flv_read_header(AVFormatContext *s)
684 FLVContext *flv = s->priv_data;
688 flags = avio_r8(s->pb);
690 flv->missing_streams = flags & (FLV_HEADER_FLAG_HASVIDEO | FLV_HEADER_FLAG_HASAUDIO);
692 s->ctx_flags |= AVFMTCTX_NOHEADER;
694 offset = avio_rb32(s->pb);
695 avio_seek(s->pb, offset, SEEK_SET);
699 flv->sum_flv_tag_size = 0;
700 flv->last_keyframe_stream_index = -1;
705 static int flv_read_close(AVFormatContext *s)
708 FLVContext *flv = s->priv_data;
709 for (i=0; i<FLV_STREAM_TYPE_NB; i++)
710 av_freep(&flv->new_extradata[i]);
711 av_freep(&flv->keyframe_times);
712 av_freep(&flv->keyframe_filepositions);
716 static int flv_get_extradata(AVFormatContext *s, AVStream *st, int size)
718 av_freep(&st->codecpar->extradata);
719 if (ff_get_extradata(s, st->codecpar, s->pb, size) < 0)
720 return AVERROR(ENOMEM);
724 static int flv_queue_extradata(FLVContext *flv, AVIOContext *pb, int stream,
727 av_free(flv->new_extradata[stream]);
728 flv->new_extradata[stream] = av_mallocz(size +
729 AV_INPUT_BUFFER_PADDING_SIZE);
730 if (!flv->new_extradata[stream])
731 return AVERROR(ENOMEM);
732 flv->new_extradata_size[stream] = size;
733 avio_read(pb, flv->new_extradata[stream], size);
737 static void clear_index_entries(AVFormatContext *s, int64_t pos)
740 av_log(s, AV_LOG_WARNING,
741 "Found invalid index entries, clearing the index.\n");
742 for (i = 0; i < s->nb_streams; i++) {
743 AVStream *st = s->streams[i];
744 /* Remove all index entries that point to >= pos */
746 for (j = 0; j < st->nb_index_entries; j++)
747 if (st->index_entries[j].pos < pos)
748 st->index_entries[out++] = st->index_entries[j];
749 st->nb_index_entries = out;
753 static int amf_skip_tag(AVIOContext *pb, AMFDataType type)
755 int nb = -1, ret, parse_name = 1;
758 case AMF_DATA_TYPE_NUMBER:
761 case AMF_DATA_TYPE_BOOL:
764 case AMF_DATA_TYPE_STRING:
765 avio_skip(pb, avio_rb16(pb));
767 case AMF_DATA_TYPE_ARRAY:
769 case AMF_DATA_TYPE_MIXEDARRAY:
771 case AMF_DATA_TYPE_OBJECT:
772 while(!pb->eof_reached && (nb-- > 0 || type != AMF_DATA_TYPE_ARRAY)) {
774 int size = avio_rb16(pb);
781 if ((ret = amf_skip_tag(pb, avio_r8(pb))) < 0)
785 case AMF_DATA_TYPE_NULL:
786 case AMF_DATA_TYPE_OBJECT_END:
789 return AVERROR_INVALIDDATA;
794 static int flv_data_packet(AVFormatContext *s, AVPacket *pkt,
795 int64_t dts, int64_t next)
797 AVIOContext *pb = s->pb;
800 int ret = AVERROR_INVALIDDATA;
804 switch (avio_r8(pb)) {
805 case AMF_DATA_TYPE_ARRAY:
807 case AMF_DATA_TYPE_MIXEDARRAY:
808 avio_seek(pb, 4, SEEK_CUR);
809 case AMF_DATA_TYPE_OBJECT:
815 while (array || (ret = amf_get_string(pb, buf, sizeof(buf))) > 0) {
816 AMFDataType type = avio_r8(pb);
817 if (type == AMF_DATA_TYPE_STRING && (array || !strcmp(buf, "text"))) {
818 length = avio_rb16(pb);
819 ret = av_get_packet(pb, pkt, length);
825 if ((ret = amf_skip_tag(pb, type)) < 0)
831 ret = AVERROR_INVALIDDATA;
835 for (i = 0; i < s->nb_streams; i++) {
837 if (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE)
841 if (i == s->nb_streams) {
842 st = create_stream(s, AVMEDIA_TYPE_SUBTITLE);
844 return AVERROR(ENOMEM);
845 st->codecpar->codec_id = AV_CODEC_ID_TEXT;
852 pkt->stream_index = st->index;
853 pkt->flags |= AV_PKT_FLAG_KEY;
856 avio_seek(s->pb, next + 4, SEEK_SET);
861 static int resync(AVFormatContext *s)
863 FLVContext *flv = s->priv_data;
865 int64_t pos = avio_tell(s->pb);
867 for (i=0; !avio_feof(s->pb); i++) {
868 int j = i & (RESYNC_BUFFER_SIZE-1);
869 int j1 = j + RESYNC_BUFFER_SIZE;
870 flv->resync_buffer[j ] =
871 flv->resync_buffer[j1] = avio_r8(s->pb);
874 unsigned lsize2 = AV_RB32(flv->resync_buffer + j1 - 4);
875 if (lsize2 >= 11 && lsize2 + 8LL < FFMIN(i, RESYNC_BUFFER_SIZE)) {
876 unsigned size2 = AV_RB24(flv->resync_buffer + j1 - lsize2 + 1 - 4);
877 unsigned lsize1 = AV_RB32(flv->resync_buffer + j1 - lsize2 - 8);
878 if (lsize1 >= 11 && lsize1 + 8LL + lsize2 < FFMIN(i, RESYNC_BUFFER_SIZE)) {
879 unsigned size1 = AV_RB24(flv->resync_buffer + j1 - lsize1 + 1 - lsize2 - 8);
880 if (size1 == lsize1 - 11 && size2 == lsize2 - 11) {
881 avio_seek(s->pb, pos + i - lsize1 - lsize2 - 8, SEEK_SET);
891 static int flv_read_packet(AVFormatContext *s, AVPacket *pkt)
893 FLVContext *flv = s->priv_data;
894 int ret, i, size, flags;
895 enum FlvTagType type;
897 int64_t next, pos, meta_pos;
898 int64_t dts, pts = AV_NOPTS_VALUE;
899 int av_uninit(channels);
900 int av_uninit(sample_rate);
906 /* pkt size is repeated at end. skip it */
907 pos = avio_tell(s->pb);
908 type = (avio_r8(s->pb) & 0x1F);
910 size = avio_rb24(s->pb);
911 flv->sum_flv_tag_size += size + 11;
912 dts = avio_rb24(s->pb);
913 dts |= (unsigned)avio_r8(s->pb) << 24;
914 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));
915 if (avio_feof(s->pb))
917 avio_skip(s->pb, 3); /* stream id, always 0 */
920 if (flv->validate_next < flv->validate_count) {
921 int64_t validate_pos = flv->validate_index[flv->validate_next].pos;
922 if (pos == validate_pos) {
923 if (FFABS(dts - flv->validate_index[flv->validate_next].dts) <=
924 VALIDATE_INDEX_TS_THRESH) {
925 flv->validate_next++;
927 clear_index_entries(s, validate_pos);
928 flv->validate_count = 0;
930 } else if (pos > validate_pos) {
931 clear_index_entries(s, validate_pos);
932 flv->validate_count = 0;
941 next = size + avio_tell(s->pb);
943 if (type == FLV_TAG_TYPE_AUDIO) {
944 stream_type = FLV_STREAM_TYPE_AUDIO;
945 flags = avio_r8(s->pb);
947 } else if (type == FLV_TAG_TYPE_VIDEO) {
948 stream_type = FLV_STREAM_TYPE_VIDEO;
949 flags = avio_r8(s->pb);
951 if ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_VIDEO_INFO_CMD)
953 } else if (type == FLV_TAG_TYPE_META) {
954 stream_type=FLV_STREAM_TYPE_DATA;
955 if (size > 13 + 1 + 4) { // Header-type metadata stuff
957 meta_pos = avio_tell(s->pb);
958 type = flv_read_metabody(s, next);
959 if (type == 0 && dts == 0 || type < 0 || type == TYPE_UNKNOWN) {
960 if (type < 0 && flv->validate_count &&
961 flv->validate_index[0].pos > next &&
962 flv->validate_index[0].pos - 4 < next
964 av_log(s, AV_LOG_WARNING, "Adjusting next position due to index mismatch\n");
965 next = flv->validate_index[0].pos - 4;
968 } else if (type == TYPE_ONTEXTDATA) {
969 avpriv_request_sample(s, "OnTextData packet");
970 return flv_data_packet(s, pkt, dts, next);
971 } else if (type == TYPE_ONCAPTION) {
972 return flv_data_packet(s, pkt, dts, next);
974 avio_seek(s->pb, meta_pos, SEEK_SET);
977 av_log(s, AV_LOG_DEBUG,
978 "Skipping flv packet: type %d, size %d, flags %d.\n",
981 avio_seek(s->pb, next, SEEK_SET);
986 /* skip empty data packets */
992 /* now find stream */
993 for (i = 0; i < s->nb_streams; i++) {
995 if (stream_type == FLV_STREAM_TYPE_AUDIO) {
996 if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO &&
997 (s->audio_codec_id || flv_same_audio_codec(st->codecpar, flags)))
999 } else if (stream_type == FLV_STREAM_TYPE_VIDEO) {
1000 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
1001 (s->video_codec_id || flv_same_video_codec(st->codecpar, flags)))
1003 } else if (stream_type == FLV_STREAM_TYPE_DATA) {
1004 if (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE)
1008 if (i == s->nb_streams) {
1009 static const enum AVMediaType stream_types[] = {AVMEDIA_TYPE_VIDEO, AVMEDIA_TYPE_AUDIO, AVMEDIA_TYPE_SUBTITLE};
1010 av_log(s, AV_LOG_WARNING, "%s stream discovered after head already parsed\n", av_get_media_type_string(stream_types[stream_type]));
1011 st = create_stream(s, stream_types[stream_type]);
1013 return AVERROR(ENOMEM);
1016 av_log(s, AV_LOG_TRACE, "%d %X %d \n", stream_type, flags, st->discard);
1018 if (s->pb->seekable &&
1019 ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY ||
1020 stream_type == FLV_STREAM_TYPE_AUDIO))
1021 av_add_index_entry(st, pos, dts, size, 0, AVINDEX_KEYFRAME);
1023 if ( (st->discard >= AVDISCARD_NONKEY && !((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY || (stream_type == FLV_STREAM_TYPE_AUDIO)))
1024 ||(st->discard >= AVDISCARD_BIDIR && ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_DISP_INTER && (stream_type == FLV_STREAM_TYPE_VIDEO)))
1025 || st->discard >= AVDISCARD_ALL
1027 avio_seek(s->pb, next, SEEK_SET);
1032 // if not streamed and no duration from metadata then seek to end to find
1033 // the duration from the timestamps
1034 if (s->pb->seekable && (!s->duration || s->duration == AV_NOPTS_VALUE) &&
1035 !flv->searched_for_end) {
1037 const int64_t pos = avio_tell(s->pb);
1038 // Read the last 4 bytes of the file, this should be the size of the
1039 // previous FLV tag. Use the timestamp of its payload as duration.
1040 int64_t fsize = avio_size(s->pb);
1042 avio_seek(s->pb, fsize - 4, SEEK_SET);
1043 size = avio_rb32(s->pb);
1044 if (size > 0 && size < fsize) {
1045 // Seek to the start of the last FLV tag at position (fsize - 4 - size)
1046 // but skip the byte indicating the type.
1047 avio_seek(s->pb, fsize - 3 - size, SEEK_SET);
1048 if (size == avio_rb24(s->pb) + 11) {
1049 uint32_t ts = avio_rb24(s->pb);
1050 ts |= avio_r8(s->pb) << 24;
1052 s->duration = ts * (int64_t)AV_TIME_BASE / 1000;
1053 else if (fsize >= 8 && fsize - 8 >= size) {
1055 goto retry_duration;
1060 avio_seek(s->pb, pos, SEEK_SET);
1061 flv->searched_for_end = 1;
1064 if (stream_type == FLV_STREAM_TYPE_AUDIO) {
1065 int bits_per_coded_sample;
1066 channels = (flags & FLV_AUDIO_CHANNEL_MASK) == FLV_STEREO ? 2 : 1;
1067 sample_rate = 44100 << ((flags & FLV_AUDIO_SAMPLERATE_MASK) >>
1068 FLV_AUDIO_SAMPLERATE_OFFSET) >> 3;
1069 bits_per_coded_sample = (flags & FLV_AUDIO_SAMPLESIZE_MASK) ? 16 : 8;
1070 if (!st->codecpar->channels || !st->codecpar->sample_rate ||
1071 !st->codecpar->bits_per_coded_sample) {
1072 st->codecpar->channels = channels;
1073 st->codecpar->channel_layout = channels == 1
1075 : AV_CH_LAYOUT_STEREO;
1076 st->codecpar->sample_rate = sample_rate;
1077 st->codecpar->bits_per_coded_sample = bits_per_coded_sample;
1079 if (!st->codecpar->codec_id) {
1080 flv_set_audio_codec(s, st, st->codecpar,
1081 flags & FLV_AUDIO_CODECID_MASK);
1082 flv->last_sample_rate =
1083 sample_rate = st->codecpar->sample_rate;
1084 flv->last_channels =
1085 channels = st->codecpar->channels;
1087 AVCodecParameters *par = avcodec_parameters_alloc();
1089 ret = AVERROR(ENOMEM);
1092 par->sample_rate = sample_rate;
1093 par->bits_per_coded_sample = bits_per_coded_sample;
1094 flv_set_audio_codec(s, st, par, flags & FLV_AUDIO_CODECID_MASK);
1095 sample_rate = par->sample_rate;
1096 avcodec_parameters_free(&par);
1098 } else if (stream_type == FLV_STREAM_TYPE_VIDEO) {
1099 size -= flv_set_video_codec(s, st, flags & FLV_VIDEO_CODECID_MASK, 1);
1100 } else if (stream_type == FLV_STREAM_TYPE_DATA) {
1101 st->codecpar->codec_id = AV_CODEC_ID_TEXT;
1104 if (st->codecpar->codec_id == AV_CODEC_ID_AAC ||
1105 st->codecpar->codec_id == AV_CODEC_ID_H264 ||
1106 st->codecpar->codec_id == AV_CODEC_ID_MPEG4) {
1107 int type = avio_r8(s->pb);
1109 if (st->codecpar->codec_id == AV_CODEC_ID_H264 || st->codecpar->codec_id == AV_CODEC_ID_MPEG4) {
1111 int32_t cts = (avio_rb24(s->pb) + 0xff800000) ^ 0xff800000;
1113 if (cts < 0) { // dts might be wrong
1114 if (!flv->wrong_dts)
1115 av_log(s, AV_LOG_WARNING,
1116 "Negative cts, previous timestamps might be wrong.\n");
1118 } else if (FFABS(dts - pts) > 1000*60*15) {
1119 av_log(s, AV_LOG_WARNING,
1120 "invalid timestamps %"PRId64" %"PRId64"\n", dts, pts);
1121 dts = pts = AV_NOPTS_VALUE;
1124 if (type == 0 && (!st->codecpar->extradata || st->codecpar->codec_id == AV_CODEC_ID_AAC ||
1125 st->codecpar->codec_id == AV_CODEC_ID_H264)) {
1126 AVDictionaryEntry *t;
1128 if (st->codecpar->extradata) {
1129 if ((ret = flv_queue_extradata(flv, s->pb, stream_type, size)) < 0)
1134 if ((ret = flv_get_extradata(s, st, size)) < 0)
1137 /* Workaround for buggy Omnia A/XE encoder */
1138 t = av_dict_get(s->metadata, "Encoder", NULL, 0);
1139 if (st->codecpar->codec_id == AV_CODEC_ID_AAC && t && !strcmp(t->value, "Omnia A/XE"))
1140 st->codecpar->extradata_size = 2;
1142 if (st->codecpar->codec_id == AV_CODEC_ID_AAC && 0) {
1143 MPEG4AudioConfig cfg;
1145 if (avpriv_mpeg4audio_get_config(&cfg, st->codecpar->extradata,
1146 st->codecpar->extradata_size * 8, 1) >= 0) {
1147 st->codecpar->channels = cfg.channels;
1148 st->codecpar->channel_layout = 0;
1149 if (cfg.ext_sample_rate)
1150 st->codecpar->sample_rate = cfg.ext_sample_rate;
1152 st->codecpar->sample_rate = cfg.sample_rate;
1153 av_log(s, AV_LOG_TRACE, "mp4a config channels %d sample rate %d\n",
1154 st->codecpar->channels, st->codecpar->sample_rate);
1163 /* skip empty data packets */
1169 ret = av_get_packet(s->pb, pkt, size);
1173 pkt->pts = pts == AV_NOPTS_VALUE ? dts : pts;
1174 pkt->stream_index = st->index;
1176 if (flv->new_extradata[stream_type]) {
1177 uint8_t *side = av_packet_new_side_data(pkt, AV_PKT_DATA_NEW_EXTRADATA,
1178 flv->new_extradata_size[stream_type]);
1180 memcpy(side, flv->new_extradata[stream_type],
1181 flv->new_extradata_size[stream_type]);
1182 av_freep(&flv->new_extradata[stream_type]);
1183 flv->new_extradata_size[stream_type] = 0;
1186 if (stream_type == FLV_STREAM_TYPE_AUDIO &&
1187 (sample_rate != flv->last_sample_rate ||
1188 channels != flv->last_channels)) {
1189 flv->last_sample_rate = sample_rate;
1190 flv->last_channels = channels;
1191 ff_add_param_change(pkt, channels, 0, sample_rate, 0, 0);
1194 if ( stream_type == FLV_STREAM_TYPE_AUDIO ||
1195 ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY) ||
1196 stream_type == FLV_STREAM_TYPE_DATA)
1197 pkt->flags |= AV_PKT_FLAG_KEY;
1200 last = avio_rb32(s->pb);
1201 if (last != orig_size + 11 && last != orig_size + 10 &&
1202 !avio_feof(s->pb) &&
1203 (last != orig_size || !last) && last != flv->sum_flv_tag_size &&
1204 !flv->broken_sizes) {
1205 av_log(s, AV_LOG_ERROR, "Packet mismatch %d %d %d\n", last, orig_size + 11, flv->sum_flv_tag_size);
1206 avio_seek(s->pb, pos + 1, SEEK_SET);
1208 av_packet_unref(pkt);
1216 static int flv_read_seek(AVFormatContext *s, int stream_index,
1217 int64_t ts, int flags)
1219 FLVContext *flv = s->priv_data;
1220 flv->validate_count = 0;
1221 return avio_seek_time(s->pb, stream_index, ts, flags);
1224 #define OFFSET(x) offsetof(FLVContext, x)
1225 #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
1226 static const AVOption options[] = {
1227 { "flv_metadata", "Allocate streams according to the onMetaData array", OFFSET(trust_metadata), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VD },
1228 { "missing_streams", "", OFFSET(missing_streams), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 0xFF, VD | AV_OPT_FLAG_EXPORT | AV_OPT_FLAG_READONLY },
1232 static const AVClass flv_class = {
1233 .class_name = "flvdec",
1234 .item_name = av_default_item_name,
1236 .version = LIBAVUTIL_VERSION_INT,
1239 AVInputFormat ff_flv_demuxer = {
1241 .long_name = NULL_IF_CONFIG_SMALL("FLV (Flash Video)"),
1242 .priv_data_size = sizeof(FLVContext),
1243 .read_probe = flv_probe,
1244 .read_header = flv_read_header,
1245 .read_packet = flv_read_packet,
1246 .read_seek = flv_read_seek,
1247 .read_close = flv_read_close,
1248 .extensions = "flv",
1249 .priv_class = &flv_class,
1252 static const AVClass live_flv_class = {
1253 .class_name = "live_flvdec",
1254 .item_name = av_default_item_name,
1256 .version = LIBAVUTIL_VERSION_INT,
1259 AVInputFormat ff_live_flv_demuxer = {
1261 .long_name = NULL_IF_CONFIG_SMALL("live RTMP FLV (Flash Video)"),
1262 .priv_data_size = sizeof(FLVContext),
1263 .read_probe = live_flv_probe,
1264 .read_header = flv_read_header,
1265 .read_packet = flv_read_packet,
1266 .read_seek = flv_read_seek,
1267 .read_close = flv_read_close,
1268 .extensions = "flv",
1269 .priv_class = &live_flv_class,
1270 .flags = AVFMT_TS_DISCONT