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];
66 static int probe(AVProbeData *p, int live)
68 const uint8_t *d = p->buf;
69 unsigned offset = AV_RB32(d + 5);
74 d[3] < 5 && d[5] == 0 &&
75 offset + 100 < p->buf_size &&
77 int is_live = !memcmp(d + offset + 40, "NGINX RTMP", 10);
80 return AVPROBE_SCORE_MAX;
85 static int flv_probe(AVProbeData *p)
90 static int live_flv_probe(AVProbeData *p)
95 static AVStream *create_stream(AVFormatContext *s, int codec_type)
97 AVStream *st = avformat_new_stream(s, NULL);
100 st->codecpar->codec_type = codec_type;
101 if (s->nb_streams>=3 ||( s->nb_streams==2
102 && s->streams[0]->codecpar->codec_type != AVMEDIA_TYPE_SUBTITLE
103 && s->streams[1]->codecpar->codec_type != AVMEDIA_TYPE_SUBTITLE))
104 s->ctx_flags &= ~AVFMTCTX_NOHEADER;
106 avpriv_set_pts_info(st, 32, 1, 1000); /* 32 bit pts in ms */
110 static int flv_same_audio_codec(AVCodecParameters *apar, int flags)
112 int bits_per_coded_sample = (flags & FLV_AUDIO_SAMPLESIZE_MASK) ? 16 : 8;
113 int flv_codecid = flags & FLV_AUDIO_CODECID_MASK;
116 if (!apar->codec_id && !apar->codec_tag)
119 if (apar->bits_per_coded_sample != bits_per_coded_sample)
122 switch (flv_codecid) {
123 // no distinction between S16 and S8 PCM codec flags
124 case FLV_CODECID_PCM:
125 codec_id = bits_per_coded_sample == 8
128 : AV_CODEC_ID_PCM_S16BE;
130 : AV_CODEC_ID_PCM_S16LE;
132 return codec_id == apar->codec_id;
133 case FLV_CODECID_PCM_LE:
134 codec_id = bits_per_coded_sample == 8
136 : AV_CODEC_ID_PCM_S16LE;
137 return codec_id == apar->codec_id;
138 case FLV_CODECID_AAC:
139 return apar->codec_id == AV_CODEC_ID_AAC;
140 case FLV_CODECID_ADPCM:
141 return apar->codec_id == AV_CODEC_ID_ADPCM_SWF;
142 case FLV_CODECID_SPEEX:
143 return apar->codec_id == AV_CODEC_ID_SPEEX;
144 case FLV_CODECID_MP3:
145 return apar->codec_id == AV_CODEC_ID_MP3;
146 case FLV_CODECID_NELLYMOSER_8KHZ_MONO:
147 case FLV_CODECID_NELLYMOSER_16KHZ_MONO:
148 case FLV_CODECID_NELLYMOSER:
149 return apar->codec_id == AV_CODEC_ID_NELLYMOSER;
150 case FLV_CODECID_PCM_MULAW:
151 return apar->sample_rate == 8000 &&
152 apar->codec_id == AV_CODEC_ID_PCM_MULAW;
153 case FLV_CODECID_PCM_ALAW:
154 return apar->sample_rate == 8000 &&
155 apar->codec_id == AV_CODEC_ID_PCM_ALAW;
157 return apar->codec_tag == (flv_codecid >> FLV_AUDIO_CODECID_OFFSET);
161 static void flv_set_audio_codec(AVFormatContext *s, AVStream *astream,
162 AVCodecParameters *apar, int flv_codecid)
164 switch (flv_codecid) {
165 // no distinction between S16 and S8 PCM codec flags
166 case FLV_CODECID_PCM:
167 apar->codec_id = apar->bits_per_coded_sample == 8
170 : AV_CODEC_ID_PCM_S16BE;
172 : AV_CODEC_ID_PCM_S16LE;
175 case FLV_CODECID_PCM_LE:
176 apar->codec_id = apar->bits_per_coded_sample == 8
178 : AV_CODEC_ID_PCM_S16LE;
180 case FLV_CODECID_AAC:
181 apar->codec_id = AV_CODEC_ID_AAC;
183 case FLV_CODECID_ADPCM:
184 apar->codec_id = AV_CODEC_ID_ADPCM_SWF;
186 case FLV_CODECID_SPEEX:
187 apar->codec_id = AV_CODEC_ID_SPEEX;
188 apar->sample_rate = 16000;
190 case FLV_CODECID_MP3:
191 apar->codec_id = AV_CODEC_ID_MP3;
192 astream->need_parsing = AVSTREAM_PARSE_FULL;
194 case FLV_CODECID_NELLYMOSER_8KHZ_MONO:
195 // in case metadata does not otherwise declare samplerate
196 apar->sample_rate = 8000;
197 apar->codec_id = AV_CODEC_ID_NELLYMOSER;
199 case FLV_CODECID_NELLYMOSER_16KHZ_MONO:
200 apar->sample_rate = 16000;
201 apar->codec_id = AV_CODEC_ID_NELLYMOSER;
203 case FLV_CODECID_NELLYMOSER:
204 apar->codec_id = AV_CODEC_ID_NELLYMOSER;
206 case FLV_CODECID_PCM_MULAW:
207 apar->sample_rate = 8000;
208 apar->codec_id = AV_CODEC_ID_PCM_MULAW;
210 case FLV_CODECID_PCM_ALAW:
211 apar->sample_rate = 8000;
212 apar->codec_id = AV_CODEC_ID_PCM_ALAW;
215 avpriv_request_sample(s, "Audio codec (%x)",
216 flv_codecid >> FLV_AUDIO_CODECID_OFFSET);
217 apar->codec_tag = flv_codecid >> FLV_AUDIO_CODECID_OFFSET;
221 static int flv_same_video_codec(AVCodecParameters *vpar, int flags)
223 int flv_codecid = flags & FLV_VIDEO_CODECID_MASK;
225 if (!vpar->codec_id && !vpar->codec_tag)
228 switch (flv_codecid) {
229 case FLV_CODECID_H263:
230 return vpar->codec_id == AV_CODEC_ID_FLV1;
231 case FLV_CODECID_SCREEN:
232 return vpar->codec_id == AV_CODEC_ID_FLASHSV;
233 case FLV_CODECID_SCREEN2:
234 return vpar->codec_id == AV_CODEC_ID_FLASHSV2;
235 case FLV_CODECID_VP6:
236 return vpar->codec_id == AV_CODEC_ID_VP6F;
237 case FLV_CODECID_VP6A:
238 return vpar->codec_id == AV_CODEC_ID_VP6A;
239 case FLV_CODECID_H264:
240 return vpar->codec_id == AV_CODEC_ID_H264;
242 return vpar->codec_tag == flv_codecid;
246 static int flv_set_video_codec(AVFormatContext *s, AVStream *vstream,
247 int flv_codecid, int read)
249 AVCodecParameters *par = vstream->codecpar;
250 switch (flv_codecid) {
251 case FLV_CODECID_H263:
252 par->codec_id = AV_CODEC_ID_FLV1;
254 case FLV_CODECID_REALH263:
255 par->codec_id = AV_CODEC_ID_H263;
256 break; // Really mean it this time
257 case FLV_CODECID_SCREEN:
258 par->codec_id = AV_CODEC_ID_FLASHSV;
260 case FLV_CODECID_SCREEN2:
261 par->codec_id = AV_CODEC_ID_FLASHSV2;
263 case FLV_CODECID_VP6:
264 par->codec_id = AV_CODEC_ID_VP6F;
265 case FLV_CODECID_VP6A:
266 if (flv_codecid == FLV_CODECID_VP6A)
267 par->codec_id = AV_CODEC_ID_VP6A;
269 if (par->extradata_size != 1) {
270 ff_alloc_extradata(par, 1);
273 par->extradata[0] = avio_r8(s->pb);
277 return 1; // 1 byte body size adjustment for flv_read_packet()
278 case FLV_CODECID_H264:
279 par->codec_id = AV_CODEC_ID_H264;
280 vstream->need_parsing = AVSTREAM_PARSE_HEADERS;
281 return 3; // not 4, reading packet type will consume one byte
282 case FLV_CODECID_MPEG4:
283 par->codec_id = AV_CODEC_ID_MPEG4;
286 avpriv_request_sample(s, "Video codec (%x)", flv_codecid);
287 par->codec_tag = flv_codecid;
293 static int amf_get_string(AVIOContext *ioc, char *buffer, int buffsize)
295 int length = avio_rb16(ioc);
296 if (length >= buffsize) {
297 avio_skip(ioc, length);
301 avio_read(ioc, buffer, length);
303 buffer[length] = '\0';
308 static int parse_keyframes_index(AVFormatContext *s, AVIOContext *ioc,
309 AVStream *vstream, int64_t max_pos)
311 FLVContext *flv = s->priv_data;
312 unsigned int timeslen = 0, fileposlen = 0, i;
314 int64_t *times = NULL;
315 int64_t *filepositions = NULL;
316 int ret = AVERROR(ENOSYS);
317 int64_t initial_pos = avio_tell(ioc);
319 if (vstream->nb_index_entries>0) {
320 av_log(s, AV_LOG_WARNING, "Skipping duplicate index\n");
324 if (s->flags & AVFMT_FLAG_IGNIDX)
327 while (avio_tell(ioc) < max_pos - 2 &&
328 amf_get_string(ioc, str_val, sizeof(str_val)) > 0) {
329 int64_t **current_array;
330 unsigned int arraylen;
332 // Expect array object in context
333 if (avio_r8(ioc) != AMF_DATA_TYPE_ARRAY)
336 arraylen = avio_rb32(ioc);
340 if (!strcmp(KEYFRAMES_TIMESTAMP_TAG , str_val) && !times) {
341 current_array = ×
343 } else if (!strcmp(KEYFRAMES_BYTEOFFSET_TAG, str_val) &&
345 current_array = &filepositions;
346 fileposlen = arraylen;
348 // unexpected metatag inside keyframes, will not use such
349 // metadata for indexing
352 if (!(*current_array = av_mallocz(sizeof(**current_array) * arraylen))) {
353 ret = AVERROR(ENOMEM);
357 for (i = 0; i < arraylen && avio_tell(ioc) < max_pos - 1; i++) {
358 if (avio_r8(ioc) != AMF_DATA_TYPE_NUMBER)
360 current_array[0][i] = av_int2double(avio_rb64(ioc));
362 if (times && filepositions) {
363 // All done, exiting at a position allowing amf_parse_object
364 // to finish parsing the object
370 if (timeslen == fileposlen && fileposlen>1 && max_pos <= filepositions[0]) {
371 for (i = 0; i < fileposlen; i++) {
372 av_add_index_entry(vstream, filepositions[i], times[i] * 1000,
373 0, 0, AVINDEX_KEYFRAME);
375 flv->validate_index[i].pos = filepositions[i];
376 flv->validate_index[i].dts = times[i] * 1000;
377 flv->validate_count = i + 1;
382 av_log(s, AV_LOG_WARNING, "Invalid keyframes object, skipping.\n");
387 av_freep(&filepositions);
388 avio_seek(ioc, initial_pos, SEEK_SET);
392 static int amf_parse_object(AVFormatContext *s, AVStream *astream,
393 AVStream *vstream, const char *key,
394 int64_t max_pos, int depth)
396 AVCodecParameters *apar, *vpar;
397 FLVContext *flv = s->priv_data;
399 AMFDataType amf_type;
405 amf_type = avio_r8(ioc);
408 case AMF_DATA_TYPE_NUMBER:
409 num_val = av_int2double(avio_rb64(ioc));
411 case AMF_DATA_TYPE_BOOL:
412 num_val = avio_r8(ioc);
414 case AMF_DATA_TYPE_STRING:
415 if (amf_get_string(ioc, str_val, sizeof(str_val)) < 0) {
416 av_log(s, AV_LOG_ERROR, "AMF_DATA_TYPE_STRING parsing failed\n");
420 case AMF_DATA_TYPE_OBJECT:
421 if ((vstream || astream) && key &&
423 !strcmp(KEYFRAMES_TAG, key) && depth == 1)
424 if (parse_keyframes_index(s, ioc, vstream ? vstream : astream,
426 av_log(s, AV_LOG_ERROR, "Keyframe index parsing failed\n");
428 while (avio_tell(ioc) < max_pos - 2 &&
429 amf_get_string(ioc, str_val, sizeof(str_val)) > 0)
430 if (amf_parse_object(s, astream, vstream, str_val, max_pos,
432 return -1; // if we couldn't skip, bomb out.
433 if (avio_r8(ioc) != AMF_END_OF_OBJECT) {
434 av_log(s, AV_LOG_ERROR, "Missing AMF_END_OF_OBJECT in AMF_DATA_TYPE_OBJECT\n");
438 case AMF_DATA_TYPE_NULL:
439 case AMF_DATA_TYPE_UNDEFINED:
440 case AMF_DATA_TYPE_UNSUPPORTED:
441 break; // these take up no additional space
442 case AMF_DATA_TYPE_MIXEDARRAY:
445 avio_skip(ioc, 4); // skip 32-bit max array index
446 while (avio_tell(ioc) < max_pos - 2 &&
447 amf_get_string(ioc, str_val, sizeof(str_val)) > 0)
448 // this is the only case in which we would want a nested
449 // parse to not skip over the object
450 if (amf_parse_object(s, astream, vstream, str_val, max_pos,
454 if (v != AMF_END_OF_OBJECT) {
455 av_log(s, AV_LOG_ERROR, "Missing AMF_END_OF_OBJECT in AMF_DATA_TYPE_MIXEDARRAY, found %d\n", v);
460 case AMF_DATA_TYPE_ARRAY:
462 unsigned int arraylen, i;
464 arraylen = avio_rb32(ioc);
465 for (i = 0; i < arraylen && avio_tell(ioc) < max_pos - 1; i++)
466 if (amf_parse_object(s, NULL, NULL, NULL, max_pos,
468 return -1; // if we couldn't skip, bomb out.
471 case AMF_DATA_TYPE_DATE:
472 avio_skip(ioc, 8 + 2); // timestamp (double) and UTC offset (int16)
474 default: // unsupported type, we couldn't skip
475 av_log(s, AV_LOG_ERROR, "unsupported amf type %d\n", amf_type);
480 apar = astream ? astream->codecpar : NULL;
481 vpar = vstream ? vstream->codecpar : NULL;
483 // stream info doesn't live any deeper than the first object
485 if (amf_type == AMF_DATA_TYPE_NUMBER ||
486 amf_type == AMF_DATA_TYPE_BOOL) {
487 if (!strcmp(key, "duration"))
488 s->duration = num_val * AV_TIME_BASE;
489 else if (!strcmp(key, "videodatarate") && vpar &&
490 0 <= (int)(num_val * 1024.0))
491 vpar->bit_rate = num_val * 1024.0;
492 else if (!strcmp(key, "audiodatarate") && apar &&
493 0 <= (int)(num_val * 1024.0))
494 apar->bit_rate = num_val * 1024.0;
495 else if (!strcmp(key, "datastream")) {
496 AVStream *st = create_stream(s, AVMEDIA_TYPE_SUBTITLE);
498 return AVERROR(ENOMEM);
499 st->codecpar->codec_id = AV_CODEC_ID_TEXT;
500 } else if (flv->trust_metadata) {
501 if (!strcmp(key, "videocodecid") && vpar) {
502 flv_set_video_codec(s, vstream, num_val, 0);
503 } else if (!strcmp(key, "audiocodecid") && apar) {
504 int id = ((int)num_val) << FLV_AUDIO_CODECID_OFFSET;
505 flv_set_audio_codec(s, astream, apar, id);
506 } else if (!strcmp(key, "audiosamplerate") && apar) {
507 apar->sample_rate = num_val;
508 } else if (!strcmp(key, "audiosamplesize") && apar) {
509 apar->bits_per_coded_sample = num_val;
510 } else if (!strcmp(key, "stereo") && apar) {
511 apar->channels = num_val + 1;
512 apar->channel_layout = apar->channels == 2 ?
513 AV_CH_LAYOUT_STEREO :
515 } else if (!strcmp(key, "width") && vpar) {
516 vpar->width = num_val;
517 } else if (!strcmp(key, "height") && vpar) {
518 vpar->height = num_val;
522 if (amf_type == AMF_DATA_TYPE_STRING) {
523 if (!strcmp(key, "encoder")) {
525 if (1 == sscanf(str_val, "Open Broadcaster Software v0.%d", &version)) {
526 if (version > 0 && version <= 655)
527 flv->broken_sizes = 1;
529 } else if (!strcmp(key, "metadatacreator") && !strcmp(str_val, "MEGA")) {
530 flv->broken_sizes = 1;
535 if (amf_type == AMF_DATA_TYPE_OBJECT && s->nb_streams == 1 &&
536 ((!apar && !strcmp(key, "audiocodecid")) ||
537 (!vpar && !strcmp(key, "videocodecid"))))
538 s->ctx_flags &= ~AVFMTCTX_NOHEADER; //If there is either audio/video missing, codecid will be an empty object
540 if (!strcmp(key, "duration") ||
541 !strcmp(key, "filesize") ||
542 !strcmp(key, "width") ||
543 !strcmp(key, "height") ||
544 !strcmp(key, "videodatarate") ||
545 !strcmp(key, "framerate") ||
546 !strcmp(key, "videocodecid") ||
547 !strcmp(key, "audiodatarate") ||
548 !strcmp(key, "audiosamplerate") ||
549 !strcmp(key, "audiosamplesize") ||
550 !strcmp(key, "stereo") ||
551 !strcmp(key, "audiocodecid") ||
552 !strcmp(key, "datastream"))
555 s->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
556 if (amf_type == AMF_DATA_TYPE_BOOL) {
557 av_strlcpy(str_val, num_val > 0 ? "true" : "false",
559 av_dict_set(&s->metadata, key, str_val, 0);
560 } else if (amf_type == AMF_DATA_TYPE_NUMBER) {
561 snprintf(str_val, sizeof(str_val), "%.f", num_val);
562 av_dict_set(&s->metadata, key, str_val, 0);
563 } else if (amf_type == AMF_DATA_TYPE_STRING)
564 av_dict_set(&s->metadata, key, str_val, 0);
570 #define TYPE_ONTEXTDATA 1
571 #define TYPE_ONCAPTION 2
572 #define TYPE_ONCAPTIONINFO 3
573 #define TYPE_UNKNOWN 9
575 static int flv_read_metabody(AVFormatContext *s, int64_t next_pos)
578 AVStream *stream, *astream, *vstream;
579 AVStream av_unused *dstream;
582 // only needs to hold the string "onMetaData".
583 // Anything longer is something we don't want.
591 // first object needs to be "onMetaData" string
593 if (type != AMF_DATA_TYPE_STRING ||
594 amf_get_string(ioc, buffer, sizeof(buffer)) < 0)
597 if (!strcmp(buffer, "onTextData"))
598 return TYPE_ONTEXTDATA;
600 if (!strcmp(buffer, "onCaption"))
601 return TYPE_ONCAPTION;
603 if (!strcmp(buffer, "onCaptionInfo"))
604 return TYPE_ONCAPTIONINFO;
606 if (strcmp(buffer, "onMetaData") && strcmp(buffer, "onCuePoint")) {
607 av_log(s, AV_LOG_DEBUG, "Unknown type %s\n", buffer);
611 // find the streams now so that amf_parse_object doesn't need to do
612 // the lookup every time it is called.
613 for (i = 0; i < s->nb_streams; i++) {
614 stream = s->streams[i];
615 if (stream->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
617 else if (stream->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)
619 else if (stream->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE)
623 // parse the second object (we want a mixed array)
624 if (amf_parse_object(s, astream, vstream, buffer, next_pos, 0) < 0)
630 static int flv_read_header(AVFormatContext *s)
632 FLVContext *flv = s->priv_data;
636 avio_r8(s->pb); // flags
638 s->ctx_flags |= AVFMTCTX_NOHEADER;
640 offset = avio_rb32(s->pb);
641 avio_seek(s->pb, offset, SEEK_SET);
645 flv->sum_flv_tag_size = 0;
650 static int flv_read_close(AVFormatContext *s)
653 FLVContext *flv = s->priv_data;
654 for (i=0; i<FLV_STREAM_TYPE_NB; i++)
655 av_freep(&flv->new_extradata[i]);
659 static int flv_get_extradata(AVFormatContext *s, AVStream *st, int size)
661 av_freep(&st->codecpar->extradata);
662 if (ff_get_extradata(s, st->codecpar, s->pb, size) < 0)
663 return AVERROR(ENOMEM);
667 static int flv_queue_extradata(FLVContext *flv, AVIOContext *pb, int stream,
670 av_free(flv->new_extradata[stream]);
671 flv->new_extradata[stream] = av_mallocz(size +
672 AV_INPUT_BUFFER_PADDING_SIZE);
673 if (!flv->new_extradata[stream])
674 return AVERROR(ENOMEM);
675 flv->new_extradata_size[stream] = size;
676 avio_read(pb, flv->new_extradata[stream], size);
680 static void clear_index_entries(AVFormatContext *s, int64_t pos)
683 av_log(s, AV_LOG_WARNING,
684 "Found invalid index entries, clearing the index.\n");
685 for (i = 0; i < s->nb_streams; i++) {
686 AVStream *st = s->streams[i];
687 /* Remove all index entries that point to >= pos */
689 for (j = 0; j < st->nb_index_entries; j++)
690 if (st->index_entries[j].pos < pos)
691 st->index_entries[out++] = st->index_entries[j];
692 st->nb_index_entries = out;
696 static int amf_skip_tag(AVIOContext *pb, AMFDataType type)
698 int nb = -1, ret, parse_name = 1;
701 case AMF_DATA_TYPE_NUMBER:
704 case AMF_DATA_TYPE_BOOL:
707 case AMF_DATA_TYPE_STRING:
708 avio_skip(pb, avio_rb16(pb));
710 case AMF_DATA_TYPE_ARRAY:
712 case AMF_DATA_TYPE_MIXEDARRAY:
714 case AMF_DATA_TYPE_OBJECT:
715 while(!pb->eof_reached && (nb-- > 0 || type != AMF_DATA_TYPE_ARRAY)) {
717 int size = avio_rb16(pb);
724 if ((ret = amf_skip_tag(pb, avio_r8(pb))) < 0)
728 case AMF_DATA_TYPE_NULL:
729 case AMF_DATA_TYPE_OBJECT_END:
732 return AVERROR_INVALIDDATA;
737 static int flv_data_packet(AVFormatContext *s, AVPacket *pkt,
738 int64_t dts, int64_t next)
740 AVIOContext *pb = s->pb;
743 int ret = AVERROR_INVALIDDATA;
747 switch (avio_r8(pb)) {
748 case AMF_DATA_TYPE_ARRAY:
750 case AMF_DATA_TYPE_MIXEDARRAY:
751 avio_seek(pb, 4, SEEK_CUR);
752 case AMF_DATA_TYPE_OBJECT:
758 while (array || (ret = amf_get_string(pb, buf, sizeof(buf))) > 0) {
759 AMFDataType type = avio_r8(pb);
760 if (type == AMF_DATA_TYPE_STRING && (array || !strcmp(buf, "text"))) {
761 length = avio_rb16(pb);
762 ret = av_get_packet(pb, pkt, length);
768 if ((ret = amf_skip_tag(pb, type)) < 0)
774 ret = AVERROR_INVALIDDATA;
778 for (i = 0; i < s->nb_streams; i++) {
780 if (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE)
784 if (i == s->nb_streams) {
785 st = create_stream(s, AVMEDIA_TYPE_SUBTITLE);
787 return AVERROR(ENOMEM);
788 st->codecpar->codec_id = AV_CODEC_ID_TEXT;
795 pkt->stream_index = st->index;
796 pkt->flags |= AV_PKT_FLAG_KEY;
799 avio_seek(s->pb, next + 4, SEEK_SET);
804 static int resync(AVFormatContext *s)
806 FLVContext *flv = s->priv_data;
808 int64_t pos = avio_tell(s->pb);
810 for (i=0; !avio_feof(s->pb); i++) {
811 int j = i & (RESYNC_BUFFER_SIZE-1);
812 int j1 = j + RESYNC_BUFFER_SIZE;
813 flv->resync_buffer[j ] =
814 flv->resync_buffer[j1] = avio_r8(s->pb);
817 unsigned lsize2 = AV_RB32(flv->resync_buffer + j1 - 4);
818 if (lsize2 >= 11 && lsize2 + 8LL < FFMIN(i, RESYNC_BUFFER_SIZE)) {
819 unsigned size2 = AV_RB24(flv->resync_buffer + j1 - lsize2 + 1 - 4);
820 unsigned lsize1 = AV_RB32(flv->resync_buffer + j1 - lsize2 - 8);
821 if (lsize1 >= 11 && lsize1 + 8LL + lsize2 < FFMIN(i, RESYNC_BUFFER_SIZE)) {
822 unsigned size1 = AV_RB24(flv->resync_buffer + j1 - lsize1 + 1 - lsize2 - 8);
823 if (size1 == lsize1 - 11 && size2 == lsize2 - 11) {
824 avio_seek(s->pb, pos + i - lsize1 - lsize2 - 8, SEEK_SET);
834 static int flv_read_packet(AVFormatContext *s, AVPacket *pkt)
836 FLVContext *flv = s->priv_data;
837 int ret, i, size, flags;
838 enum FlvTagType type;
840 int64_t next, pos, meta_pos;
841 int64_t dts, pts = AV_NOPTS_VALUE;
842 int av_uninit(channels);
843 int av_uninit(sample_rate);
849 /* pkt size is repeated at end. skip it */
850 pos = avio_tell(s->pb);
851 type = (avio_r8(s->pb) & 0x1F);
853 size = avio_rb24(s->pb);
854 flv->sum_flv_tag_size += size + 11;
855 dts = avio_rb24(s->pb);
856 dts |= (unsigned)avio_r8(s->pb) << 24;
857 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));
858 if (avio_feof(s->pb))
860 avio_skip(s->pb, 3); /* stream id, always 0 */
863 if (flv->validate_next < flv->validate_count) {
864 int64_t validate_pos = flv->validate_index[flv->validate_next].pos;
865 if (pos == validate_pos) {
866 if (FFABS(dts - flv->validate_index[flv->validate_next].dts) <=
867 VALIDATE_INDEX_TS_THRESH) {
868 flv->validate_next++;
870 clear_index_entries(s, validate_pos);
871 flv->validate_count = 0;
873 } else if (pos > validate_pos) {
874 clear_index_entries(s, validate_pos);
875 flv->validate_count = 0;
884 next = size + avio_tell(s->pb);
886 if (type == FLV_TAG_TYPE_AUDIO) {
887 stream_type = FLV_STREAM_TYPE_AUDIO;
888 flags = avio_r8(s->pb);
890 } else if (type == FLV_TAG_TYPE_VIDEO) {
891 stream_type = FLV_STREAM_TYPE_VIDEO;
892 flags = avio_r8(s->pb);
894 if ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_VIDEO_INFO_CMD)
896 } else if (type == FLV_TAG_TYPE_META) {
897 stream_type=FLV_STREAM_TYPE_DATA;
898 if (size > 13 + 1 + 4) { // Header-type metadata stuff
900 meta_pos = avio_tell(s->pb);
901 type = flv_read_metabody(s, next);
902 if (type == 0 && dts == 0 || type < 0 || type == TYPE_UNKNOWN) {
903 if (type < 0 && flv->validate_count &&
904 flv->validate_index[0].pos > next &&
905 flv->validate_index[0].pos - 4 < next
907 av_log(s, AV_LOG_WARNING, "Adjusting next position due to index mismatch\n");
908 next = flv->validate_index[0].pos - 4;
911 } else if (type == TYPE_ONTEXTDATA) {
912 avpriv_request_sample(s, "OnTextData packet");
913 return flv_data_packet(s, pkt, dts, next);
914 } else if (type == TYPE_ONCAPTION) {
915 return flv_data_packet(s, pkt, dts, next);
917 avio_seek(s->pb, meta_pos, SEEK_SET);
920 av_log(s, AV_LOG_DEBUG,
921 "Skipping flv packet: type %d, size %d, flags %d.\n",
924 avio_seek(s->pb, next, SEEK_SET);
929 /* skip empty data packets */
935 /* now find stream */
936 for (i = 0; i < s->nb_streams; i++) {
938 if (stream_type == FLV_STREAM_TYPE_AUDIO) {
939 if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO &&
940 (s->audio_codec_id || flv_same_audio_codec(st->codecpar, flags)))
942 } else if (stream_type == FLV_STREAM_TYPE_VIDEO) {
943 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
944 (s->video_codec_id || flv_same_video_codec(st->codecpar, flags)))
946 } else if (stream_type == FLV_STREAM_TYPE_DATA) {
947 if (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE)
951 if (i == s->nb_streams) {
952 static const enum AVMediaType stream_types[] = {AVMEDIA_TYPE_VIDEO, AVMEDIA_TYPE_AUDIO, AVMEDIA_TYPE_SUBTITLE};
953 av_log(s, AV_LOG_WARNING, "%s stream discovered after head already parsed\n", av_get_media_type_string(stream_types[stream_type]));
954 st = create_stream(s, stream_types[stream_type]);
956 return AVERROR(ENOMEM);
959 av_log(s, AV_LOG_TRACE, "%d %X %d \n", stream_type, flags, st->discard);
961 if (s->pb->seekable &&
962 ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY ||
963 stream_type == FLV_STREAM_TYPE_AUDIO))
964 av_add_index_entry(st, pos, dts, size, 0, AVINDEX_KEYFRAME);
966 if ( (st->discard >= AVDISCARD_NONKEY && !((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY || (stream_type == FLV_STREAM_TYPE_AUDIO)))
967 ||(st->discard >= AVDISCARD_BIDIR && ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_DISP_INTER && (stream_type == FLV_STREAM_TYPE_VIDEO)))
968 || st->discard >= AVDISCARD_ALL
970 avio_seek(s->pb, next, SEEK_SET);
975 // if not streamed and no duration from metadata then seek to end to find
976 // the duration from the timestamps
977 if (s->pb->seekable && (!s->duration || s->duration == AV_NOPTS_VALUE) &&
978 !flv->searched_for_end) {
980 const int64_t pos = avio_tell(s->pb);
981 // Read the last 4 bytes of the file, this should be the size of the
982 // previous FLV tag. Use the timestamp of its payload as duration.
983 int64_t fsize = avio_size(s->pb);
985 avio_seek(s->pb, fsize - 4, SEEK_SET);
986 size = avio_rb32(s->pb);
987 if (size > 0 && size < fsize) {
988 // Seek to the start of the last FLV tag at position (fsize - 4 - size)
989 // but skip the byte indicating the type.
990 avio_seek(s->pb, fsize - 3 - size, SEEK_SET);
991 if (size == avio_rb24(s->pb) + 11) {
992 uint32_t ts = avio_rb24(s->pb);
993 ts |= avio_r8(s->pb) << 24;
995 s->duration = ts * (int64_t)AV_TIME_BASE / 1000;
996 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->codecpar->channels || !st->codecpar->sample_rate ||
1014 !st->codecpar->bits_per_coded_sample) {
1015 st->codecpar->channels = channels;
1016 st->codecpar->channel_layout = channels == 1
1018 : AV_CH_LAYOUT_STEREO;
1019 st->codecpar->sample_rate = sample_rate;
1020 st->codecpar->bits_per_coded_sample = bits_per_coded_sample;
1022 if (!st->codecpar->codec_id) {
1023 flv_set_audio_codec(s, st, st->codecpar,
1024 flags & FLV_AUDIO_CODECID_MASK);
1025 flv->last_sample_rate =
1026 sample_rate = st->codecpar->sample_rate;
1027 flv->last_channels =
1028 channels = st->codecpar->channels;
1030 AVCodecParameters *par = avcodec_parameters_alloc();
1032 ret = AVERROR(ENOMEM);
1035 par->sample_rate = sample_rate;
1036 par->bits_per_coded_sample = bits_per_coded_sample;
1037 flv_set_audio_codec(s, st, par, flags & FLV_AUDIO_CODECID_MASK);
1038 sample_rate = par->sample_rate;
1039 avcodec_parameters_free(&par);
1041 } else if (stream_type == FLV_STREAM_TYPE_VIDEO) {
1042 size -= flv_set_video_codec(s, st, flags & FLV_VIDEO_CODECID_MASK, 1);
1043 } else if (stream_type == FLV_STREAM_TYPE_DATA) {
1044 st->codecpar->codec_id = AV_CODEC_ID_TEXT;
1047 if (st->codecpar->codec_id == AV_CODEC_ID_AAC ||
1048 st->codecpar->codec_id == AV_CODEC_ID_H264 ||
1049 st->codecpar->codec_id == AV_CODEC_ID_MPEG4) {
1050 int type = avio_r8(s->pb);
1052 if (st->codecpar->codec_id == AV_CODEC_ID_H264 || st->codecpar->codec_id == AV_CODEC_ID_MPEG4) {
1054 int32_t cts = (avio_rb24(s->pb) + 0xff800000) ^ 0xff800000;
1056 if (cts < 0) { // dts might be wrong
1057 if (!flv->wrong_dts)
1058 av_log(s, AV_LOG_WARNING,
1059 "Negative cts, previous timestamps might be wrong.\n");
1061 } else if (FFABS(dts - pts) > 1000*60*15) {
1062 av_log(s, AV_LOG_WARNING,
1063 "invalid timestamps %"PRId64" %"PRId64"\n", dts, pts);
1064 dts = pts = AV_NOPTS_VALUE;
1067 if (type == 0 && (!st->codecpar->extradata || st->codecpar->codec_id == AV_CODEC_ID_AAC ||
1068 st->codecpar->codec_id == AV_CODEC_ID_H264)) {
1069 AVDictionaryEntry *t;
1071 if (st->codecpar->extradata) {
1072 if ((ret = flv_queue_extradata(flv, s->pb, stream_type, size)) < 0)
1077 if ((ret = flv_get_extradata(s, st, size)) < 0)
1080 /* Workaround for buggy Omnia A/XE encoder */
1081 t = av_dict_get(s->metadata, "Encoder", NULL, 0);
1082 if (st->codecpar->codec_id == AV_CODEC_ID_AAC && t && !strcmp(t->value, "Omnia A/XE"))
1083 st->codecpar->extradata_size = 2;
1085 if (st->codecpar->codec_id == AV_CODEC_ID_AAC && 0) {
1086 MPEG4AudioConfig cfg;
1088 if (avpriv_mpeg4audio_get_config(&cfg, st->codecpar->extradata,
1089 st->codecpar->extradata_size * 8, 1) >= 0) {
1090 st->codecpar->channels = cfg.channels;
1091 st->codecpar->channel_layout = 0;
1092 if (cfg.ext_sample_rate)
1093 st->codecpar->sample_rate = cfg.ext_sample_rate;
1095 st->codecpar->sample_rate = cfg.sample_rate;
1096 av_log(s, AV_LOG_TRACE, "mp4a config channels %d sample rate %d\n",
1097 st->codecpar->channels, st->codecpar->sample_rate);
1106 /* skip empty data packets */
1112 ret = av_get_packet(s->pb, pkt, size);
1116 pkt->pts = pts == AV_NOPTS_VALUE ? dts : pts;
1117 pkt->stream_index = st->index;
1118 if (flv->new_extradata[stream_type]) {
1119 uint8_t *side = av_packet_new_side_data(pkt, AV_PKT_DATA_NEW_EXTRADATA,
1120 flv->new_extradata_size[stream_type]);
1122 memcpy(side, flv->new_extradata[stream_type],
1123 flv->new_extradata_size[stream_type]);
1124 av_freep(&flv->new_extradata[stream_type]);
1125 flv->new_extradata_size[stream_type] = 0;
1128 if (stream_type == FLV_STREAM_TYPE_AUDIO &&
1129 (sample_rate != flv->last_sample_rate ||
1130 channels != flv->last_channels)) {
1131 flv->last_sample_rate = sample_rate;
1132 flv->last_channels = channels;
1133 ff_add_param_change(pkt, channels, 0, sample_rate, 0, 0);
1136 if ( stream_type == FLV_STREAM_TYPE_AUDIO ||
1137 ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY) ||
1138 stream_type == FLV_STREAM_TYPE_DATA)
1139 pkt->flags |= AV_PKT_FLAG_KEY;
1142 last = avio_rb32(s->pb);
1143 if (last != orig_size + 11 &&
1144 (last != orig_size || !last) && last != flv->sum_flv_tag_size &&
1145 !flv->broken_sizes) {
1146 av_log(s, AV_LOG_ERROR, "Packet mismatch %d %d\n", last, orig_size + 11);
1147 avio_seek(s->pb, pos + 1, SEEK_SET);
1149 av_packet_unref(pkt);
1157 static int flv_read_seek(AVFormatContext *s, int stream_index,
1158 int64_t ts, int flags)
1160 FLVContext *flv = s->priv_data;
1161 flv->validate_count = 0;
1162 return avio_seek_time(s->pb, stream_index, ts, flags);
1165 #define OFFSET(x) offsetof(FLVContext, x)
1166 #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
1167 static const AVOption options[] = {
1168 { "flv_metadata", "Allocate streams according to the onMetaData array", OFFSET(trust_metadata), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VD },
1172 static const AVClass flv_class = {
1173 .class_name = "flvdec",
1174 .item_name = av_default_item_name,
1176 .version = LIBAVUTIL_VERSION_INT,
1179 AVInputFormat ff_flv_demuxer = {
1181 .long_name = NULL_IF_CONFIG_SMALL("FLV (Flash Video)"),
1182 .priv_data_size = sizeof(FLVContext),
1183 .read_probe = flv_probe,
1184 .read_header = flv_read_header,
1185 .read_packet = flv_read_packet,
1186 .read_seek = flv_read_seek,
1187 .read_close = flv_read_close,
1188 .extensions = "flv",
1189 .priv_class = &flv_class,
1192 static const AVClass live_flv_class = {
1193 .class_name = "live_flvdec",
1194 .item_name = av_default_item_name,
1196 .version = LIBAVUTIL_VERSION_INT,
1199 AVInputFormat ff_live_flv_demuxer = {
1201 .long_name = NULL_IF_CONFIG_SMALL("live RTMP FLV (Flash Video)"),
1202 .priv_data_size = sizeof(FLVContext),
1203 .read_probe = live_flv_probe,
1204 .read_header = flv_read_header,
1205 .read_packet = flv_read_packet,
1206 .read_seek = flv_read_seek,
1207 .read_close = flv_read_close,
1208 .extensions = "flv",
1209 .priv_class = &live_flv_class,
1210 .flags = AVFMT_TS_DISCONT