2 * various utility functions for use within Libav
3 * Copyright (c) 2000, 2001, 2002 Fabrice Bellard
5 * This file is part of Libav.
7 * Libav is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * Libav is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with Libav; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
25 #include "avio_internal.h"
27 #include "libavcodec/internal.h"
28 #include "libavcodec/bytestream.h"
29 #include "libavutil/opt.h"
30 #include "libavutil/dict.h"
31 #include "libavutil/internal.h"
32 #include "libavutil/pixdesc.h"
35 #include "libavutil/avassert.h"
36 #include "libavutil/avstring.h"
37 #include "libavutil/mathematics.h"
38 #include "libavutil/parseutils.h"
39 #include "libavutil/time.h"
41 #include "audiointerleave.h"
53 * various utility functions for use within Libav
56 unsigned avformat_version(void)
58 return LIBAVFORMAT_VERSION_INT;
61 const char *avformat_configuration(void)
63 return LIBAV_CONFIGURATION;
66 const char *avformat_license(void)
68 #define LICENSE_PREFIX "libavformat license: "
69 return LICENSE_PREFIX LIBAV_LICENSE + sizeof(LICENSE_PREFIX) - 1;
72 /* an arbitrarily chosen "sane" max packet size -- 50M */
73 #define SANE_CHUNK_SIZE (50000000)
76 * Read the data in sane-sized chunks and append to pkt.
77 * Return the number of bytes read or an error.
79 static int append_packet_chunked(AVIOContext *s, AVPacket *pkt, int size)
81 int64_t chunk_size = size;
82 int64_t orig_pos = pkt->pos; // av_grow_packet might reset pos
83 int orig_size = pkt->size;
87 int prev_size = pkt->size;
91 * When the caller requests a lot of data, limit it to the amount left
92 * in file or SANE_CHUNK_SIZE when it is not known
94 if (size > SANE_CHUNK_SIZE) {
95 int64_t filesize = avio_size(s) - avio_tell(s);
96 chunk_size = FFMAX(filesize, SANE_CHUNK_SIZE);
98 read_size = FFMIN(size, chunk_size);
100 ret = av_grow_packet(pkt, read_size);
104 ret = avio_read(s, pkt->data + prev_size, read_size);
105 if (ret != read_size) {
106 av_shrink_packet(pkt, prev_size + FFMAX(ret, 0));
116 return pkt->size > orig_size ? pkt->size - orig_size : ret;
119 int av_get_packet(AVIOContext *s, AVPacket *pkt, int size)
124 pkt->pos = avio_tell(s);
126 return append_packet_chunked(s, pkt, size);
129 int av_append_packet(AVIOContext *s, AVPacket *pkt, int size)
132 return av_get_packet(s, pkt, size);
133 return append_packet_chunked(s, pkt, size);
137 int av_filename_number_test(const char *filename)
140 return filename && (av_get_frame_filename(buf, sizeof(buf), filename, 1)>=0);
143 AVInputFormat *av_probe_input_format2(AVProbeData *pd, int is_opened, int *score_max)
145 AVProbeData lpd = *pd;
146 AVInputFormat *fmt1 = NULL, *fmt;
149 if (lpd.buf_size > 10 && ff_id3v2_match(lpd.buf, ID3v2_DEFAULT_MAGIC)) {
150 int id3len = ff_id3v2_tag_len(lpd.buf);
151 if (lpd.buf_size > id3len + 16) {
153 lpd.buf_size -= id3len;
159 while ((fmt1 = av_iformat_next(fmt1))) {
160 if (!is_opened == !(fmt1->flags & AVFMT_NOFILE))
163 if (fmt1->read_probe) {
164 score = fmt1->read_probe(&lpd);
165 } else if (fmt1->extensions) {
166 if (av_match_ext(lpd.filename, fmt1->extensions)) {
167 score = AVPROBE_SCORE_EXTENSION;
170 if (score > *score_max) {
173 }else if (score == *score_max)
177 /* a hack for files with huge id3v2 tags -- try to guess by file extension. */
178 if (!fmt && is_opened && *score_max < AVPROBE_SCORE_EXTENSION / 2) {
179 while ((fmt = av_iformat_next(fmt)))
180 if (fmt->extensions && av_match_ext(lpd.filename, fmt->extensions)) {
181 *score_max = AVPROBE_SCORE_EXTENSION / 2;
186 if (!fmt && id3 && *score_max < AVPROBE_SCORE_EXTENSION / 2 - 1) {
187 while ((fmt = av_iformat_next(fmt)))
188 if (fmt->extensions && av_match_ext("mp3", fmt->extensions)) {
189 *score_max = AVPROBE_SCORE_EXTENSION / 2 - 1;
197 AVInputFormat *av_probe_input_format(AVProbeData *pd, int is_opened){
199 return av_probe_input_format2(pd, is_opened, &score);
202 static int set_codec_from_probe_data(AVFormatContext *s, AVStream *st, AVProbeData *pd, int score)
204 static const struct {
205 const char *name; enum AVCodecID id; enum AVMediaType type;
207 { "aac" , AV_CODEC_ID_AAC , AVMEDIA_TYPE_AUDIO },
208 { "ac3" , AV_CODEC_ID_AC3 , AVMEDIA_TYPE_AUDIO },
209 { "dts" , AV_CODEC_ID_DTS , AVMEDIA_TYPE_AUDIO },
210 { "eac3" , AV_CODEC_ID_EAC3 , AVMEDIA_TYPE_AUDIO },
211 { "h264" , AV_CODEC_ID_H264 , AVMEDIA_TYPE_VIDEO },
212 { "m4v" , AV_CODEC_ID_MPEG4 , AVMEDIA_TYPE_VIDEO },
213 { "mp3" , AV_CODEC_ID_MP3 , AVMEDIA_TYPE_AUDIO },
214 { "mpegvideo", AV_CODEC_ID_MPEG2VIDEO, AVMEDIA_TYPE_VIDEO },
217 AVInputFormat *fmt = av_probe_input_format2(pd, 1, &score);
221 av_log(s, AV_LOG_DEBUG, "Probe with size=%d, packets=%d detected %s with score=%d\n",
222 pd->buf_size, MAX_PROBE_PACKETS - st->probe_packets, fmt->name, score);
223 for (i = 0; fmt_id_type[i].name; i++) {
224 if (!strcmp(fmt->name, fmt_id_type[i].name)) {
225 st->codec->codec_id = fmt_id_type[i].id;
226 st->codec->codec_type = fmt_id_type[i].type;
234 /************************************************************/
235 /* input media file */
237 /** size of probe buffer, for guessing file type from file contents */
238 #define PROBE_BUF_MIN 2048
239 #define PROBE_BUF_MAX (1<<20)
241 int av_probe_input_buffer(AVIOContext *pb, AVInputFormat **fmt,
242 const char *filename, void *logctx,
243 unsigned int offset, unsigned int max_probe_size)
245 AVProbeData pd = { filename ? filename : "", NULL, -offset };
246 unsigned char *buf = NULL;
247 int ret = 0, probe_size;
249 if (!max_probe_size) {
250 max_probe_size = PROBE_BUF_MAX;
251 } else if (max_probe_size > PROBE_BUF_MAX) {
252 max_probe_size = PROBE_BUF_MAX;
253 } else if (max_probe_size < PROBE_BUF_MIN) {
254 return AVERROR(EINVAL);
257 if (offset >= max_probe_size) {
258 return AVERROR(EINVAL);
261 for(probe_size= PROBE_BUF_MIN; probe_size<=max_probe_size && !*fmt;
262 probe_size = FFMIN(probe_size<<1, FFMAX(max_probe_size, probe_size+1))) {
263 int score = probe_size < max_probe_size ? AVPROBE_SCORE_MAX/4 : 0;
264 int buf_offset = (probe_size == PROBE_BUF_MIN) ? 0 : probe_size>>1;
266 if (probe_size < offset) {
270 /* read probe data */
271 if ((ret = av_reallocp(&buf, probe_size + AVPROBE_PADDING_SIZE)) < 0)
273 if ((ret = avio_read(pb, buf + buf_offset, probe_size - buf_offset)) < 0) {
274 /* fail if error was not end of file, otherwise, lower score */
275 if (ret != AVERROR_EOF) {
280 ret = 0; /* error was end of file, nothing read */
283 pd.buf = &buf[offset];
285 memset(pd.buf + pd.buf_size, 0, AVPROBE_PADDING_SIZE);
287 /* guess file format */
288 *fmt = av_probe_input_format2(&pd, 1, &score);
290 if(score <= AVPROBE_SCORE_MAX/4){ //this can only be true in the last iteration
291 av_log(logctx, AV_LOG_WARNING, "Format detected only with low score of %d, misdetection possible!\n", score);
293 av_log(logctx, AV_LOG_DEBUG, "Probed with size=%d and score=%d\n", probe_size, score);
299 return AVERROR_INVALIDDATA;
302 /* rewind. reuse probe buffer to avoid seeking */
303 if ((ret = ffio_rewind_with_probe_data(pb, buf, pd.buf_size)) < 0)
309 /* open input file and probe the format if necessary */
310 static int init_input(AVFormatContext *s, const char *filename, AVDictionary **options)
313 AVProbeData pd = {filename, NULL, 0};
316 s->flags |= AVFMT_FLAG_CUSTOM_IO;
318 return av_probe_input_buffer(s->pb, &s->iformat, filename, s, 0, s->probesize);
319 else if (s->iformat->flags & AVFMT_NOFILE)
320 return AVERROR(EINVAL);
324 if ( (s->iformat && s->iformat->flags & AVFMT_NOFILE) ||
325 (!s->iformat && (s->iformat = av_probe_input_format(&pd, 0))))
328 if ((ret = avio_open2(&s->pb, filename, AVIO_FLAG_READ,
329 &s->interrupt_callback, options)) < 0)
333 return av_probe_input_buffer(s->pb, &s->iformat, filename, s, 0, s->probesize);
336 static AVPacket *add_to_pktbuf(AVPacketList **packet_buffer, AVPacket *pkt,
337 AVPacketList **plast_pktl){
338 AVPacketList *pktl = av_mallocz(sizeof(AVPacketList));
343 (*plast_pktl)->next = pktl;
345 *packet_buffer = pktl;
347 /* add the packet in the buffered packet list */
353 static int queue_attached_pictures(AVFormatContext *s)
356 for (i = 0; i < s->nb_streams; i++)
357 if (s->streams[i]->disposition & AV_DISPOSITION_ATTACHED_PIC &&
358 s->streams[i]->discard < AVDISCARD_ALL) {
359 AVPacket copy = s->streams[i]->attached_pic;
360 copy.buf = av_buffer_ref(copy.buf);
362 return AVERROR(ENOMEM);
364 add_to_pktbuf(&s->raw_packet_buffer, ©, &s->raw_packet_buffer_end);
369 int avformat_open_input(AVFormatContext **ps, const char *filename, AVInputFormat *fmt, AVDictionary **options)
371 AVFormatContext *s = *ps;
373 AVDictionary *tmp = NULL;
374 ID3v2ExtraMeta *id3v2_extra_meta = NULL;
376 if (!s && !(s = avformat_alloc_context()))
377 return AVERROR(ENOMEM);
382 av_dict_copy(&tmp, *options, 0);
384 if ((ret = av_opt_set_dict(s, &tmp)) < 0)
387 if ((ret = init_input(s, filename, &tmp)) < 0)
390 /* check filename in case an image number is expected */
391 if (s->iformat->flags & AVFMT_NEEDNUMBER) {
392 if (!av_filename_number_test(filename)) {
393 ret = AVERROR(EINVAL);
398 s->duration = s->start_time = AV_NOPTS_VALUE;
399 av_strlcpy(s->filename, filename ? filename : "", sizeof(s->filename));
401 /* allocate private data */
402 if (s->iformat->priv_data_size > 0) {
403 if (!(s->priv_data = av_mallocz(s->iformat->priv_data_size))) {
404 ret = AVERROR(ENOMEM);
407 if (s->iformat->priv_class) {
408 *(const AVClass**)s->priv_data = s->iformat->priv_class;
409 av_opt_set_defaults(s->priv_data);
410 if ((ret = av_opt_set_dict(s->priv_data, &tmp)) < 0)
415 /* e.g. AVFMT_NOFILE formats will not have a AVIOContext */
417 ff_id3v2_read(s, ID3v2_DEFAULT_MAGIC, &id3v2_extra_meta);
419 if (s->iformat->read_header)
420 if ((ret = s->iformat->read_header(s)) < 0)
423 if (id3v2_extra_meta &&
424 (ret = ff_id3v2_parse_apic(s, &id3v2_extra_meta)) < 0)
426 ff_id3v2_free_extra_meta(&id3v2_extra_meta);
428 if ((ret = queue_attached_pictures(s)) < 0)
431 if (s->pb && !s->data_offset)
432 s->data_offset = avio_tell(s->pb);
434 s->raw_packet_buffer_remaining_size = RAW_PACKET_BUFFER_SIZE;
437 av_dict_free(options);
444 ff_id3v2_free_extra_meta(&id3v2_extra_meta);
446 if (s->pb && !(s->flags & AVFMT_FLAG_CUSTOM_IO))
448 avformat_free_context(s);
453 /*******************************************************/
455 static int probe_codec(AVFormatContext *s, AVStream *st, const AVPacket *pkt)
457 if(st->codec->codec_id == AV_CODEC_ID_PROBE){
458 AVProbeData *pd = &st->probe_data;
459 av_log(s, AV_LOG_DEBUG, "probing stream %d\n", st->index);
464 if ((err = av_reallocp(&pd->buf, pd->buf_size + pkt->size +
465 AVPROBE_PADDING_SIZE)) < 0)
467 memcpy(pd->buf+pd->buf_size, pkt->data, pkt->size);
468 pd->buf_size += pkt->size;
469 memset(pd->buf+pd->buf_size, 0, AVPROBE_PADDING_SIZE);
471 st->probe_packets = 0;
473 av_log(s, AV_LOG_ERROR, "nothing to probe for stream %d\n",
479 if (!st->probe_packets ||
480 av_log2(pd->buf_size) != av_log2(pd->buf_size - pkt->size)) {
481 set_codec_from_probe_data(s, st, pd, st->probe_packets > 0 ? AVPROBE_SCORE_MAX/4 : 0);
482 if(st->codec->codec_id != AV_CODEC_ID_PROBE){
485 av_log(s, AV_LOG_DEBUG, "probed stream %d\n", st->index);
492 int ff_read_packet(AVFormatContext *s, AVPacket *pkt)
498 AVPacketList *pktl = s->raw_packet_buffer;
502 st = s->streams[pkt->stream_index];
503 if (st->codec->codec_id != AV_CODEC_ID_PROBE || !st->probe_packets ||
504 s->raw_packet_buffer_remaining_size < pkt->size) {
506 if (st->probe_packets) {
507 if ((err = probe_codec(s, st, NULL)) < 0)
510 pd = &st->probe_data;
513 s->raw_packet_buffer = pktl->next;
514 s->raw_packet_buffer_remaining_size += pkt->size;
523 ret= s->iformat->read_packet(s, pkt);
525 if (!pktl || ret == AVERROR(EAGAIN))
527 for (i = 0; i < s->nb_streams; i++) {
529 if (st->probe_packets) {
530 if ((err = probe_codec(s, st, NULL)) < 0)
537 if ((s->flags & AVFMT_FLAG_DISCARD_CORRUPT) &&
538 (pkt->flags & AV_PKT_FLAG_CORRUPT)) {
539 av_log(s, AV_LOG_WARNING,
540 "Dropped corrupted packet (stream = %d)\n",
546 st= s->streams[pkt->stream_index];
548 switch(st->codec->codec_type){
549 case AVMEDIA_TYPE_VIDEO:
550 if(s->video_codec_id) st->codec->codec_id= s->video_codec_id;
552 case AVMEDIA_TYPE_AUDIO:
553 if(s->audio_codec_id) st->codec->codec_id= s->audio_codec_id;
555 case AVMEDIA_TYPE_SUBTITLE:
556 if(s->subtitle_codec_id)st->codec->codec_id= s->subtitle_codec_id;
560 if(!pktl && (st->codec->codec_id != AV_CODEC_ID_PROBE ||
564 add_to_pktbuf(&s->raw_packet_buffer, pkt, &s->raw_packet_buffer_end);
565 s->raw_packet_buffer_remaining_size -= pkt->size;
567 if ((err = probe_codec(s, st, pkt)) < 0)
572 /**********************************************************/
575 * Get the number of samples of an audio frame. Return -1 on error.
577 int ff_get_audio_frame_size(AVCodecContext *enc, int size, int mux)
581 /* give frame_size priority if demuxing */
582 if (!mux && enc->frame_size > 1)
583 return enc->frame_size;
585 if ((frame_size = av_get_audio_frame_duration(enc, size)) > 0)
588 /* Fall back on using frame_size if muxing. */
589 if (enc->frame_size > 1)
590 return enc->frame_size;
597 * Return the frame duration in seconds. Return 0 if not available.
599 void ff_compute_frame_duration(int *pnum, int *pden, AVStream *st,
600 AVCodecParserContext *pc, AVPacket *pkt)
606 switch(st->codec->codec_type) {
607 case AVMEDIA_TYPE_VIDEO:
608 if (st->avg_frame_rate.num) {
609 *pnum = st->avg_frame_rate.den;
610 *pden = st->avg_frame_rate.num;
611 } else if(st->time_base.num*1000LL > st->time_base.den) {
612 *pnum = st->time_base.num;
613 *pden = st->time_base.den;
614 }else if(st->codec->time_base.num*1000LL > st->codec->time_base.den){
615 *pnum = st->codec->time_base.num;
616 *pden = st->codec->time_base.den;
617 if (pc && pc->repeat_pict) {
618 if (*pnum > INT_MAX / (1 + pc->repeat_pict))
619 *pden /= 1 + pc->repeat_pict;
621 *pnum *= 1 + pc->repeat_pict;
623 //If this codec can be interlaced or progressive then we need a parser to compute duration of a packet
624 //Thus if we have no parser in such case leave duration undefined.
625 if(st->codec->ticks_per_frame>1 && !pc){
630 case AVMEDIA_TYPE_AUDIO:
631 frame_size = ff_get_audio_frame_size(st->codec, pkt->size, 0);
632 if (frame_size <= 0 || st->codec->sample_rate <= 0)
635 *pden = st->codec->sample_rate;
642 static int is_intra_only(enum AVCodecID id)
644 const AVCodecDescriptor *d = avcodec_descriptor_get(id);
647 if (d->type == AVMEDIA_TYPE_VIDEO && !(d->props & AV_CODEC_PROP_INTRA_ONLY))
652 static void update_initial_timestamps(AVFormatContext *s, int stream_index,
653 int64_t dts, int64_t pts)
655 AVStream *st= s->streams[stream_index];
656 AVPacketList *pktl= s->packet_buffer;
658 if(st->first_dts != AV_NOPTS_VALUE || dts == AV_NOPTS_VALUE || st->cur_dts == AV_NOPTS_VALUE)
661 st->first_dts= dts - st->cur_dts;
664 for(; pktl; pktl= pktl->next){
665 if(pktl->pkt.stream_index != stream_index)
667 //FIXME think more about this check
668 if(pktl->pkt.pts != AV_NOPTS_VALUE && pktl->pkt.pts == pktl->pkt.dts)
669 pktl->pkt.pts += st->first_dts;
671 if(pktl->pkt.dts != AV_NOPTS_VALUE)
672 pktl->pkt.dts += st->first_dts;
674 if(st->start_time == AV_NOPTS_VALUE && pktl->pkt.pts != AV_NOPTS_VALUE)
675 st->start_time= pktl->pkt.pts;
677 if (st->start_time == AV_NOPTS_VALUE)
678 st->start_time = pts;
681 static void update_initial_durations(AVFormatContext *s, AVStream *st,
682 int stream_index, int duration)
684 AVPacketList *pktl= s->packet_buffer;
687 if(st->first_dts != AV_NOPTS_VALUE){
688 cur_dts= st->first_dts;
689 for(; pktl; pktl= pktl->next){
690 if(pktl->pkt.stream_index == stream_index){
691 if(pktl->pkt.pts != pktl->pkt.dts || pktl->pkt.dts != AV_NOPTS_VALUE || pktl->pkt.duration)
696 pktl= s->packet_buffer;
697 st->first_dts = cur_dts;
698 }else if(st->cur_dts)
701 for(; pktl; pktl= pktl->next){
702 if(pktl->pkt.stream_index != stream_index)
704 if(pktl->pkt.pts == pktl->pkt.dts && pktl->pkt.dts == AV_NOPTS_VALUE
705 && !pktl->pkt.duration){
706 pktl->pkt.dts= cur_dts;
707 if(!st->codec->has_b_frames)
708 pktl->pkt.pts= cur_dts;
710 if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO)
711 pktl->pkt.duration = duration;
715 if(st->first_dts == AV_NOPTS_VALUE)
716 st->cur_dts= cur_dts;
719 static void compute_pkt_fields(AVFormatContext *s, AVStream *st,
720 AVCodecParserContext *pc, AVPacket *pkt)
722 int num, den, presentation_delayed, delay, i;
725 if (s->flags & AVFMT_FLAG_NOFILLIN)
728 if((s->flags & AVFMT_FLAG_IGNDTS) && pkt->pts != AV_NOPTS_VALUE)
729 pkt->dts= AV_NOPTS_VALUE;
731 /* do we have a video B-frame ? */
732 delay= st->codec->has_b_frames;
733 presentation_delayed = 0;
735 /* XXX: need has_b_frame, but cannot get it if the codec is
738 pc && pc->pict_type != AV_PICTURE_TYPE_B)
739 presentation_delayed = 1;
741 if (pkt->pts != AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE &&
742 st->pts_wrap_bits < 63 &&
743 pkt->dts - (1LL << (st->pts_wrap_bits - 1)) > pkt->pts) {
744 pkt->dts -= 1LL<<st->pts_wrap_bits;
747 // some mpeg2 in mpeg-ps lack dts (issue171 / input_file.mpg)
748 // we take the conservative approach and discard both
749 // Note, if this is misbehaving for a H.264 file then possibly presentation_delayed is not set correctly.
750 if(delay==1 && pkt->dts == pkt->pts && pkt->dts != AV_NOPTS_VALUE && presentation_delayed){
751 av_log(s, AV_LOG_DEBUG, "invalid dts/pts combination\n");
752 pkt->dts= pkt->pts= AV_NOPTS_VALUE;
755 if (pkt->duration == 0 && st->codec->codec_type != AVMEDIA_TYPE_AUDIO) {
756 ff_compute_frame_duration(&num, &den, st, pc, pkt);
758 pkt->duration = av_rescale_rnd(1, num * (int64_t)st->time_base.den, den * (int64_t)st->time_base.num, AV_ROUND_DOWN);
760 if(pkt->duration != 0 && s->packet_buffer)
761 update_initial_durations(s, st, pkt->stream_index, pkt->duration);
765 /* correct timestamps with byte offset if demuxers only have timestamps
766 on packet boundaries */
767 if(pc && st->need_parsing == AVSTREAM_PARSE_TIMESTAMPS && pkt->size){
768 /* this will estimate bitrate based on this frame's duration and size */
769 offset = av_rescale(pc->offset, pkt->duration, pkt->size);
770 if(pkt->pts != AV_NOPTS_VALUE)
772 if(pkt->dts != AV_NOPTS_VALUE)
776 /* This may be redundant, but it should not hurt. */
777 if(pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE && pkt->pts > pkt->dts)
778 presentation_delayed = 1;
781 "IN delayed:%d pts:%"PRId64", dts:%"PRId64" cur_dts:%"PRId64" st:%d pc:%p\n",
782 presentation_delayed, pkt->pts, pkt->dts, st->cur_dts,
783 pkt->stream_index, pc);
784 /* interpolate PTS and DTS if they are not present */
785 //We skip H264 currently because delay and has_b_frames are not reliably set
786 if((delay==0 || (delay==1 && pc)) && st->codec->codec_id != AV_CODEC_ID_H264){
787 if (presentation_delayed) {
788 /* DTS = decompression timestamp */
789 /* PTS = presentation timestamp */
790 if (pkt->dts == AV_NOPTS_VALUE)
791 pkt->dts = st->last_IP_pts;
792 update_initial_timestamps(s, pkt->stream_index, pkt->dts, pkt->pts);
793 if (pkt->dts == AV_NOPTS_VALUE)
794 pkt->dts = st->cur_dts;
796 /* this is tricky: the dts must be incremented by the duration
797 of the frame we are displaying, i.e. the last I- or P-frame */
798 if (st->last_IP_duration == 0)
799 st->last_IP_duration = pkt->duration;
800 if(pkt->dts != AV_NOPTS_VALUE)
801 st->cur_dts = pkt->dts + st->last_IP_duration;
802 st->last_IP_duration = pkt->duration;
803 st->last_IP_pts= pkt->pts;
804 /* cannot compute PTS if not present (we can compute it only
805 by knowing the future */
806 } else if (pkt->pts != AV_NOPTS_VALUE ||
807 pkt->dts != AV_NOPTS_VALUE ||
809 st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
810 int duration = pkt->duration;
811 if (!duration && st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
812 ff_compute_frame_duration(&num, &den, st, pc, pkt);
814 duration = av_rescale_rnd(1, num * (int64_t)st->time_base.den,
815 den * (int64_t)st->time_base.num,
817 if (duration != 0 && s->packet_buffer) {
818 update_initial_durations(s, st, pkt->stream_index,
824 if (pkt->pts != AV_NOPTS_VALUE || pkt->dts != AV_NOPTS_VALUE ||
826 /* presentation is not delayed : PTS and DTS are the same */
827 if (pkt->pts == AV_NOPTS_VALUE)
829 update_initial_timestamps(s, pkt->stream_index, pkt->pts,
831 if (pkt->pts == AV_NOPTS_VALUE)
832 pkt->pts = st->cur_dts;
834 if (pkt->pts != AV_NOPTS_VALUE)
835 st->cur_dts = pkt->pts + duration;
840 if(pkt->pts != AV_NOPTS_VALUE && delay <= MAX_REORDER_DELAY){
841 st->pts_buffer[0]= pkt->pts;
842 for(i=0; i<delay && st->pts_buffer[i] > st->pts_buffer[i+1]; i++)
843 FFSWAP(int64_t, st->pts_buffer[i], st->pts_buffer[i+1]);
844 if(pkt->dts == AV_NOPTS_VALUE)
845 pkt->dts= st->pts_buffer[0];
846 if(st->codec->codec_id == AV_CODEC_ID_H264){ // we skipped it above so we try here
847 update_initial_timestamps(s, pkt->stream_index, pkt->dts, pkt->pts); // this should happen on the first packet
849 if(pkt->dts > st->cur_dts)
850 st->cur_dts = pkt->dts;
854 "OUTdelayed:%d/%d pts:%"PRId64", dts:%"PRId64" cur_dts:%"PRId64"\n",
855 presentation_delayed, delay, pkt->pts, pkt->dts, st->cur_dts);
858 if (is_intra_only(st->codec->codec_id))
859 pkt->flags |= AV_PKT_FLAG_KEY;
861 pkt->convergence_duration = pc->convergence_duration;
864 static void free_packet_buffer(AVPacketList **pkt_buf, AVPacketList **pkt_buf_end)
867 AVPacketList *pktl = *pkt_buf;
868 *pkt_buf = pktl->next;
869 av_free_packet(&pktl->pkt);
876 * Parse a packet, add all split parts to parse_queue
878 * @param pkt packet to parse, NULL when flushing the parser at end of stream
880 static int parse_packet(AVFormatContext *s, AVPacket *pkt, int stream_index)
882 AVPacket out_pkt = { 0 }, flush_pkt = { 0 };
883 AVStream *st = s->streams[stream_index];
884 uint8_t *data = pkt ? pkt->data : NULL;
885 int size = pkt ? pkt->size : 0;
886 int ret = 0, got_output = 0;
889 av_init_packet(&flush_pkt);
894 while (size > 0 || (pkt == &flush_pkt && got_output)) {
897 av_init_packet(&out_pkt);
898 len = av_parser_parse2(st->parser, st->codec,
899 &out_pkt.data, &out_pkt.size, data, size,
900 pkt->pts, pkt->dts, pkt->pos);
902 pkt->pts = pkt->dts = AV_NOPTS_VALUE;
903 /* increment read pointer */
907 got_output = !!out_pkt.size;
912 if (pkt->side_data) {
913 out_pkt.side_data = pkt->side_data;
914 out_pkt.side_data_elems = pkt->side_data_elems;
915 pkt->side_data = NULL;
916 pkt->side_data_elems = 0;
919 /* set the duration */
920 out_pkt.duration = 0;
921 if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
922 if (st->codec->sample_rate > 0) {
923 out_pkt.duration = av_rescale_q_rnd(st->parser->duration,
924 (AVRational){ 1, st->codec->sample_rate },
928 } else if (st->codec->time_base.num != 0 &&
929 st->codec->time_base.den != 0) {
930 out_pkt.duration = av_rescale_q_rnd(st->parser->duration,
931 st->codec->time_base,
936 out_pkt.stream_index = st->index;
937 out_pkt.pts = st->parser->pts;
938 out_pkt.dts = st->parser->dts;
939 out_pkt.pos = st->parser->pos;
941 if (st->parser->key_frame == 1 ||
942 (st->parser->key_frame == -1 &&
943 st->parser->pict_type == AV_PICTURE_TYPE_I))
944 out_pkt.flags |= AV_PKT_FLAG_KEY;
946 compute_pkt_fields(s, st, st->parser, &out_pkt);
948 if ((s->iformat->flags & AVFMT_GENERIC_INDEX) &&
949 out_pkt.flags & AV_PKT_FLAG_KEY) {
950 ff_reduce_index(s, st->index);
951 av_add_index_entry(st, st->parser->frame_offset, out_pkt.dts,
952 0, 0, AVINDEX_KEYFRAME);
955 if (out_pkt.data == pkt->data && out_pkt.size == pkt->size) {
956 out_pkt.buf = pkt->buf;
958 #if FF_API_DESTRUCT_PACKET
959 FF_DISABLE_DEPRECATION_WARNINGS
960 out_pkt.destruct = pkt->destruct;
961 pkt->destruct = NULL;
962 FF_ENABLE_DEPRECATION_WARNINGS
965 if ((ret = av_dup_packet(&out_pkt)) < 0)
968 if (!add_to_pktbuf(&s->parse_queue, &out_pkt, &s->parse_queue_end)) {
969 av_free_packet(&out_pkt);
970 ret = AVERROR(ENOMEM);
976 /* end of the stream => close and free the parser */
977 if (pkt == &flush_pkt) {
978 av_parser_close(st->parser);
987 static int read_from_packet_buffer(AVPacketList **pkt_buffer,
988 AVPacketList **pkt_buffer_end,
992 av_assert0(*pkt_buffer);
995 *pkt_buffer = pktl->next;
997 *pkt_buffer_end = NULL;
1002 static int read_frame_internal(AVFormatContext *s, AVPacket *pkt)
1004 int ret = 0, i, got_packet = 0;
1006 av_init_packet(pkt);
1008 while (!got_packet && !s->parse_queue) {
1012 /* read next packet */
1013 ret = ff_read_packet(s, &cur_pkt);
1015 if (ret == AVERROR(EAGAIN))
1017 /* flush the parsers */
1018 for(i = 0; i < s->nb_streams; i++) {
1020 if (st->parser && st->need_parsing)
1021 parse_packet(s, NULL, st->index);
1023 /* all remaining packets are now in parse_queue =>
1024 * really terminate parsing */
1028 st = s->streams[cur_pkt.stream_index];
1030 if (cur_pkt.pts != AV_NOPTS_VALUE &&
1031 cur_pkt.dts != AV_NOPTS_VALUE &&
1032 cur_pkt.pts < cur_pkt.dts) {
1033 av_log(s, AV_LOG_WARNING, "Invalid timestamps stream=%d, pts=%"PRId64", dts=%"PRId64", size=%d\n",
1034 cur_pkt.stream_index,
1039 if (s->debug & FF_FDEBUG_TS)
1040 av_log(s, AV_LOG_DEBUG, "ff_read_packet stream=%d, pts=%"PRId64", dts=%"PRId64", size=%d, duration=%d, flags=%d\n",
1041 cur_pkt.stream_index,
1048 if (st->need_parsing && !st->parser && !(s->flags & AVFMT_FLAG_NOPARSE)) {
1049 st->parser = av_parser_init(st->codec->codec_id);
1051 /* no parser available: just output the raw packets */
1052 st->need_parsing = AVSTREAM_PARSE_NONE;
1053 } else if(st->need_parsing == AVSTREAM_PARSE_HEADERS) {
1054 st->parser->flags |= PARSER_FLAG_COMPLETE_FRAMES;
1055 } else if(st->need_parsing == AVSTREAM_PARSE_FULL_ONCE) {
1056 st->parser->flags |= PARSER_FLAG_ONCE;
1060 if (!st->need_parsing || !st->parser) {
1061 /* no parsing needed: we just output the packet as is */
1063 compute_pkt_fields(s, st, NULL, pkt);
1064 if ((s->iformat->flags & AVFMT_GENERIC_INDEX) &&
1065 (pkt->flags & AV_PKT_FLAG_KEY) && pkt->dts != AV_NOPTS_VALUE) {
1066 ff_reduce_index(s, st->index);
1067 av_add_index_entry(st, pkt->pos, pkt->dts, 0, 0, AVINDEX_KEYFRAME);
1070 } else if (st->discard < AVDISCARD_ALL) {
1071 if ((ret = parse_packet(s, &cur_pkt, cur_pkt.stream_index)) < 0)
1075 av_free_packet(&cur_pkt);
1079 if (!got_packet && s->parse_queue)
1080 ret = read_from_packet_buffer(&s->parse_queue, &s->parse_queue_end, pkt);
1082 if(s->debug & FF_FDEBUG_TS)
1083 av_log(s, AV_LOG_DEBUG, "read_frame_internal stream=%d, pts=%"PRId64", dts=%"PRId64", size=%d, duration=%d, flags=%d\n",
1094 int av_read_frame(AVFormatContext *s, AVPacket *pkt)
1096 const int genpts = s->flags & AVFMT_FLAG_GENPTS;
1100 return s->packet_buffer ? read_from_packet_buffer(&s->packet_buffer,
1101 &s->packet_buffer_end,
1103 read_frame_internal(s, pkt);
1107 AVPacketList *pktl = s->packet_buffer;
1110 AVPacket *next_pkt = &pktl->pkt;
1112 if (next_pkt->dts != AV_NOPTS_VALUE) {
1113 int wrap_bits = s->streams[next_pkt->stream_index]->pts_wrap_bits;
1114 while (pktl && next_pkt->pts == AV_NOPTS_VALUE) {
1115 if (pktl->pkt.stream_index == next_pkt->stream_index &&
1116 (av_compare_mod(next_pkt->dts, pktl->pkt.dts, 2LL << (wrap_bits - 1)) < 0) &&
1117 av_compare_mod(pktl->pkt.pts, pktl->pkt.dts, 2LL << (wrap_bits - 1))) { //not b frame
1118 next_pkt->pts = pktl->pkt.dts;
1122 pktl = s->packet_buffer;
1125 /* read packet from packet buffer, if there is data */
1126 if (!(next_pkt->pts == AV_NOPTS_VALUE &&
1127 next_pkt->dts != AV_NOPTS_VALUE && !eof))
1128 return read_from_packet_buffer(&s->packet_buffer,
1129 &s->packet_buffer_end, pkt);
1132 ret = read_frame_internal(s, pkt);
1134 if (pktl && ret != AVERROR(EAGAIN)) {
1141 if (av_dup_packet(add_to_pktbuf(&s->packet_buffer, pkt,
1142 &s->packet_buffer_end)) < 0)
1143 return AVERROR(ENOMEM);
1147 /* XXX: suppress the packet queue */
1148 static void flush_packet_queue(AVFormatContext *s)
1150 free_packet_buffer(&s->parse_queue, &s->parse_queue_end);
1151 free_packet_buffer(&s->packet_buffer, &s->packet_buffer_end);
1152 free_packet_buffer(&s->raw_packet_buffer, &s->raw_packet_buffer_end);
1154 s->raw_packet_buffer_remaining_size = RAW_PACKET_BUFFER_SIZE;
1157 /*******************************************************/
1160 int av_find_default_stream_index(AVFormatContext *s)
1162 int first_audio_index = -1;
1166 if (s->nb_streams <= 0)
1168 for(i = 0; i < s->nb_streams; i++) {
1170 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
1171 !(st->disposition & AV_DISPOSITION_ATTACHED_PIC)) {
1174 if (first_audio_index < 0 && st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
1175 first_audio_index = i;
1177 return first_audio_index >= 0 ? first_audio_index : 0;
1181 * Flush the frame reader.
1183 void ff_read_frame_flush(AVFormatContext *s)
1188 flush_packet_queue(s);
1190 /* for each stream, reset read state */
1191 for(i = 0; i < s->nb_streams; i++) {
1195 av_parser_close(st->parser);
1198 st->last_IP_pts = AV_NOPTS_VALUE;
1199 st->cur_dts = AV_NOPTS_VALUE; /* we set the current DTS to an unspecified origin */
1201 st->probe_packets = MAX_PROBE_PACKETS;
1203 for(j=0; j<MAX_REORDER_DELAY+1; j++)
1204 st->pts_buffer[j]= AV_NOPTS_VALUE;
1208 void ff_update_cur_dts(AVFormatContext *s, AVStream *ref_st, int64_t timestamp)
1212 for(i = 0; i < s->nb_streams; i++) {
1213 AVStream *st = s->streams[i];
1215 st->cur_dts = av_rescale(timestamp,
1216 st->time_base.den * (int64_t)ref_st->time_base.num,
1217 st->time_base.num * (int64_t)ref_st->time_base.den);
1221 void ff_reduce_index(AVFormatContext *s, int stream_index)
1223 AVStream *st= s->streams[stream_index];
1224 unsigned int max_entries= s->max_index_size / sizeof(AVIndexEntry);
1226 if((unsigned)st->nb_index_entries >= max_entries){
1228 for(i=0; 2*i<st->nb_index_entries; i++)
1229 st->index_entries[i]= st->index_entries[2*i];
1230 st->nb_index_entries= i;
1234 int ff_add_index_entry(AVIndexEntry **index_entries,
1235 int *nb_index_entries,
1236 unsigned int *index_entries_allocated_size,
1237 int64_t pos, int64_t timestamp, int size, int distance, int flags)
1239 AVIndexEntry *entries, *ie;
1242 if((unsigned)*nb_index_entries + 1 >= UINT_MAX / sizeof(AVIndexEntry))
1245 entries = av_fast_realloc(*index_entries,
1246 index_entries_allocated_size,
1247 (*nb_index_entries + 1) *
1248 sizeof(AVIndexEntry));
1252 *index_entries= entries;
1254 index= ff_index_search_timestamp(*index_entries, *nb_index_entries, timestamp, AVSEEK_FLAG_ANY);
1257 index= (*nb_index_entries)++;
1258 ie= &entries[index];
1259 assert(index==0 || ie[-1].timestamp < timestamp);
1261 ie= &entries[index];
1262 if(ie->timestamp != timestamp){
1263 if(ie->timestamp <= timestamp)
1265 memmove(entries + index + 1, entries + index, sizeof(AVIndexEntry)*(*nb_index_entries - index));
1266 (*nb_index_entries)++;
1267 }else if(ie->pos == pos && distance < ie->min_distance) //do not reduce the distance
1268 distance= ie->min_distance;
1272 ie->timestamp = timestamp;
1273 ie->min_distance= distance;
1280 int av_add_index_entry(AVStream *st,
1281 int64_t pos, int64_t timestamp, int size, int distance, int flags)
1283 return ff_add_index_entry(&st->index_entries, &st->nb_index_entries,
1284 &st->index_entries_allocated_size, pos,
1285 timestamp, size, distance, flags);
1288 int ff_index_search_timestamp(const AVIndexEntry *entries, int nb_entries,
1289 int64_t wanted_timestamp, int flags)
1297 //optimize appending index entries at the end
1298 if(b && entries[b-1].timestamp < wanted_timestamp)
1303 timestamp = entries[m].timestamp;
1304 if(timestamp >= wanted_timestamp)
1306 if(timestamp <= wanted_timestamp)
1309 m= (flags & AVSEEK_FLAG_BACKWARD) ? a : b;
1311 if(!(flags & AVSEEK_FLAG_ANY)){
1312 while(m>=0 && m<nb_entries && !(entries[m].flags & AVINDEX_KEYFRAME)){
1313 m += (flags & AVSEEK_FLAG_BACKWARD) ? -1 : 1;
1322 int av_index_search_timestamp(AVStream *st, int64_t wanted_timestamp,
1325 return ff_index_search_timestamp(st->index_entries, st->nb_index_entries,
1326 wanted_timestamp, flags);
1329 int ff_seek_frame_binary(AVFormatContext *s, int stream_index, int64_t target_ts, int flags)
1331 AVInputFormat *avif= s->iformat;
1332 int64_t av_uninit(pos_min), av_uninit(pos_max), pos, pos_limit;
1333 int64_t ts_min, ts_max, ts;
1338 if (stream_index < 0)
1341 av_dlog(s, "read_seek: %d %"PRId64"\n", stream_index, target_ts);
1344 ts_min= AV_NOPTS_VALUE;
1345 pos_limit= -1; //gcc falsely says it may be uninitialized
1347 st= s->streams[stream_index];
1348 if(st->index_entries){
1351 index= av_index_search_timestamp(st, target_ts, flags | AVSEEK_FLAG_BACKWARD); //FIXME whole func must be checked for non-keyframe entries in index case, especially read_timestamp()
1352 index= FFMAX(index, 0);
1353 e= &st->index_entries[index];
1355 if(e->timestamp <= target_ts || e->pos == e->min_distance){
1357 ts_min= e->timestamp;
1358 av_dlog(s, "using cached pos_min=0x%"PRIx64" dts_min=%"PRId64"\n",
1364 index= av_index_search_timestamp(st, target_ts, flags & ~AVSEEK_FLAG_BACKWARD);
1365 assert(index < st->nb_index_entries);
1367 e= &st->index_entries[index];
1368 assert(e->timestamp >= target_ts);
1370 ts_max= e->timestamp;
1371 pos_limit= pos_max - e->min_distance;
1372 av_dlog(s, "using cached pos_max=0x%"PRIx64" pos_limit=0x%"PRIx64" dts_max=%"PRId64"\n",
1373 pos_max,pos_limit, ts_max);
1377 pos= ff_gen_search(s, stream_index, target_ts, pos_min, pos_max, pos_limit, ts_min, ts_max, flags, &ts, avif->read_timestamp);
1382 if ((ret = avio_seek(s->pb, pos, SEEK_SET)) < 0)
1385 ff_update_cur_dts(s, st, ts);
1390 int64_t ff_gen_search(AVFormatContext *s, int stream_index, int64_t target_ts,
1391 int64_t pos_min, int64_t pos_max, int64_t pos_limit,
1392 int64_t ts_min, int64_t ts_max, int flags, int64_t *ts_ret,
1393 int64_t (*read_timestamp)(struct AVFormatContext *, int , int64_t *, int64_t ))
1396 int64_t start_pos, filesize;
1399 av_dlog(s, "gen_seek: %d %"PRId64"\n", stream_index, target_ts);
1401 if(ts_min == AV_NOPTS_VALUE){
1402 pos_min = s->data_offset;
1403 ts_min = read_timestamp(s, stream_index, &pos_min, INT64_MAX);
1404 if (ts_min == AV_NOPTS_VALUE)
1408 if(ts_max == AV_NOPTS_VALUE){
1410 filesize = avio_size(s->pb);
1411 pos_max = filesize - 1;
1414 ts_max = read_timestamp(s, stream_index, &pos_max, pos_max + step);
1416 }while(ts_max == AV_NOPTS_VALUE && pos_max >= step);
1417 if (ts_max == AV_NOPTS_VALUE)
1421 int64_t tmp_pos= pos_max + 1;
1422 int64_t tmp_ts= read_timestamp(s, stream_index, &tmp_pos, INT64_MAX);
1423 if(tmp_ts == AV_NOPTS_VALUE)
1427 if(tmp_pos >= filesize)
1433 if(ts_min > ts_max){
1435 }else if(ts_min == ts_max){
1440 while (pos_min < pos_limit) {
1441 av_dlog(s, "pos_min=0x%"PRIx64" pos_max=0x%"PRIx64" dts_min=%"PRId64" dts_max=%"PRId64"\n",
1442 pos_min, pos_max, ts_min, ts_max);
1443 assert(pos_limit <= pos_max);
1446 int64_t approximate_keyframe_distance= pos_max - pos_limit;
1447 // interpolate position (better than dichotomy)
1448 pos = av_rescale(target_ts - ts_min, pos_max - pos_min, ts_max - ts_min)
1449 + pos_min - approximate_keyframe_distance;
1450 }else if(no_change==1){
1451 // bisection, if interpolation failed to change min or max pos last time
1452 pos = (pos_min + pos_limit)>>1;
1454 /* linear search if bisection failed, can only happen if there
1455 are very few or no keyframes between min/max */
1460 else if(pos > pos_limit)
1464 ts = read_timestamp(s, stream_index, &pos, INT64_MAX); //may pass pos_limit instead of -1
1469 av_dlog(s, "%"PRId64" %"PRId64" %"PRId64" / %"PRId64" %"PRId64" %"PRId64" target:%"PRId64" limit:%"PRId64" start:%"PRId64" noc:%d\n",
1470 pos_min, pos, pos_max, ts_min, ts, ts_max, target_ts,
1471 pos_limit, start_pos, no_change);
1472 if(ts == AV_NOPTS_VALUE){
1473 av_log(s, AV_LOG_ERROR, "read_timestamp() failed in the middle\n");
1476 assert(ts != AV_NOPTS_VALUE);
1477 if (target_ts <= ts) {
1478 pos_limit = start_pos - 1;
1482 if (target_ts >= ts) {
1488 pos = (flags & AVSEEK_FLAG_BACKWARD) ? pos_min : pos_max;
1489 ts = (flags & AVSEEK_FLAG_BACKWARD) ? ts_min : ts_max;
1491 ts_min = read_timestamp(s, stream_index, &pos_min, INT64_MAX);
1493 ts_max = read_timestamp(s, stream_index, &pos_min, INT64_MAX);
1494 av_dlog(s, "pos=0x%"PRIx64" %"PRId64"<=%"PRId64"<=%"PRId64"\n",
1495 pos, ts_min, target_ts, ts_max);
1500 static int seek_frame_byte(AVFormatContext *s, int stream_index, int64_t pos, int flags){
1501 int64_t pos_min, pos_max;
1503 pos_min = s->data_offset;
1504 pos_max = avio_size(s->pb) - 1;
1506 if (pos < pos_min) pos= pos_min;
1507 else if(pos > pos_max) pos= pos_max;
1509 avio_seek(s->pb, pos, SEEK_SET);
1514 static int seek_frame_generic(AVFormatContext *s,
1515 int stream_index, int64_t timestamp, int flags)
1522 st = s->streams[stream_index];
1524 index = av_index_search_timestamp(st, timestamp, flags);
1526 if(index < 0 && st->nb_index_entries && timestamp < st->index_entries[0].timestamp)
1529 if(index < 0 || index==st->nb_index_entries-1){
1532 if(st->nb_index_entries){
1533 assert(st->index_entries);
1534 ie= &st->index_entries[st->nb_index_entries-1];
1535 if ((ret = avio_seek(s->pb, ie->pos, SEEK_SET)) < 0)
1537 ff_update_cur_dts(s, st, ie->timestamp);
1539 if ((ret = avio_seek(s->pb, s->data_offset, SEEK_SET)) < 0)
1545 read_status = av_read_frame(s, &pkt);
1546 } while (read_status == AVERROR(EAGAIN));
1547 if (read_status < 0)
1549 av_free_packet(&pkt);
1550 if(stream_index == pkt.stream_index){
1551 if((pkt.flags & AV_PKT_FLAG_KEY) && pkt.dts > timestamp)
1555 index = av_index_search_timestamp(st, timestamp, flags);
1560 ff_read_frame_flush(s);
1561 if (s->iformat->read_seek){
1562 if(s->iformat->read_seek(s, stream_index, timestamp, flags) >= 0)
1565 ie = &st->index_entries[index];
1566 if ((ret = avio_seek(s->pb, ie->pos, SEEK_SET)) < 0)
1568 ff_update_cur_dts(s, st, ie->timestamp);
1573 static int seek_frame_internal(AVFormatContext *s, int stream_index,
1574 int64_t timestamp, int flags)
1579 if (flags & AVSEEK_FLAG_BYTE) {
1580 if (s->iformat->flags & AVFMT_NO_BYTE_SEEK)
1582 ff_read_frame_flush(s);
1583 return seek_frame_byte(s, stream_index, timestamp, flags);
1586 if(stream_index < 0){
1587 stream_index= av_find_default_stream_index(s);
1588 if(stream_index < 0)
1591 st= s->streams[stream_index];
1592 /* timestamp for default must be expressed in AV_TIME_BASE units */
1593 timestamp = av_rescale(timestamp, st->time_base.den, AV_TIME_BASE * (int64_t)st->time_base.num);
1596 /* first, we try the format specific seek */
1597 if (s->iformat->read_seek) {
1598 ff_read_frame_flush(s);
1599 ret = s->iformat->read_seek(s, stream_index, timestamp, flags);
1606 if (s->iformat->read_timestamp && !(s->iformat->flags & AVFMT_NOBINSEARCH)) {
1607 ff_read_frame_flush(s);
1608 return ff_seek_frame_binary(s, stream_index, timestamp, flags);
1609 } else if (!(s->iformat->flags & AVFMT_NOGENSEARCH)) {
1610 ff_read_frame_flush(s);
1611 return seek_frame_generic(s, stream_index, timestamp, flags);
1617 int av_seek_frame(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
1619 int ret = seek_frame_internal(s, stream_index, timestamp, flags);
1622 ret = queue_attached_pictures(s);
1627 int avformat_seek_file(AVFormatContext *s, int stream_index, int64_t min_ts, int64_t ts, int64_t max_ts, int flags)
1629 if(min_ts > ts || max_ts < ts)
1632 if (s->iformat->read_seek2) {
1634 ff_read_frame_flush(s);
1635 ret = s->iformat->read_seek2(s, stream_index, min_ts, ts, max_ts, flags);
1638 ret = queue_attached_pictures(s);
1642 if(s->iformat->read_timestamp){
1643 //try to seek via read_timestamp()
1646 // Fall back on old API if new is not implemented but old is.
1647 // Note the old API has somewhat different semantics.
1648 if(s->iformat->read_seek || 1)
1649 return av_seek_frame(s, stream_index, ts, flags | ((uint64_t)ts - min_ts > (uint64_t)max_ts - ts ? AVSEEK_FLAG_BACKWARD : 0));
1651 // try some generic seek like seek_frame_generic() but with new ts semantics
1654 /*******************************************************/
1657 * Return TRUE if the stream has accurate duration in any stream.
1659 * @return TRUE if the stream has accurate duration for at least one component.
1661 static int has_duration(AVFormatContext *ic)
1666 for(i = 0;i < ic->nb_streams; i++) {
1667 st = ic->streams[i];
1668 if (st->duration != AV_NOPTS_VALUE)
1671 if (ic->duration != AV_NOPTS_VALUE)
1677 * Estimate the stream timings from the one of each components.
1679 * Also computes the global bitrate if possible.
1681 static void update_stream_timings(AVFormatContext *ic)
1683 int64_t start_time, start_time1, end_time, end_time1;
1684 int64_t duration, duration1, filesize;
1688 start_time = INT64_MAX;
1689 end_time = INT64_MIN;
1690 duration = INT64_MIN;
1691 for(i = 0;i < ic->nb_streams; i++) {
1692 st = ic->streams[i];
1693 if (st->start_time != AV_NOPTS_VALUE && st->time_base.den) {
1694 start_time1= av_rescale_q(st->start_time, st->time_base, AV_TIME_BASE_Q);
1695 start_time = FFMIN(start_time, start_time1);
1696 if (st->duration != AV_NOPTS_VALUE) {
1697 end_time1 = start_time1
1698 + av_rescale_q(st->duration, st->time_base, AV_TIME_BASE_Q);
1699 end_time = FFMAX(end_time, end_time1);
1702 if (st->duration != AV_NOPTS_VALUE) {
1703 duration1 = av_rescale_q(st->duration, st->time_base, AV_TIME_BASE_Q);
1704 duration = FFMAX(duration, duration1);
1707 if (start_time != INT64_MAX) {
1708 ic->start_time = start_time;
1709 if (end_time != INT64_MIN)
1710 duration = FFMAX(duration, end_time - start_time);
1712 if (duration != INT64_MIN) {
1713 ic->duration = duration;
1714 if (ic->pb && (filesize = avio_size(ic->pb)) > 0) {
1715 /* compute the bitrate */
1716 ic->bit_rate = (double)filesize * 8.0 * AV_TIME_BASE /
1717 (double)ic->duration;
1722 static void fill_all_stream_timings(AVFormatContext *ic)
1727 update_stream_timings(ic);
1728 for(i = 0;i < ic->nb_streams; i++) {
1729 st = ic->streams[i];
1730 if (st->start_time == AV_NOPTS_VALUE) {
1731 if(ic->start_time != AV_NOPTS_VALUE)
1732 st->start_time = av_rescale_q(ic->start_time, AV_TIME_BASE_Q, st->time_base);
1733 if(ic->duration != AV_NOPTS_VALUE)
1734 st->duration = av_rescale_q(ic->duration, AV_TIME_BASE_Q, st->time_base);
1739 static void estimate_timings_from_bit_rate(AVFormatContext *ic)
1741 int64_t filesize, duration;
1745 /* if bit_rate is already set, we believe it */
1746 if (ic->bit_rate <= 0) {
1748 for(i=0;i<ic->nb_streams;i++) {
1749 st = ic->streams[i];
1750 if (st->codec->bit_rate > 0) {
1751 if (INT_MAX - st->codec->bit_rate < bit_rate) {
1755 bit_rate += st->codec->bit_rate;
1758 ic->bit_rate = bit_rate;
1761 /* if duration is already set, we believe it */
1762 if (ic->duration == AV_NOPTS_VALUE &&
1763 ic->bit_rate != 0) {
1764 filesize = ic->pb ? avio_size(ic->pb) : 0;
1766 for(i = 0; i < ic->nb_streams; i++) {
1767 st = ic->streams[i];
1768 duration= av_rescale(8*filesize, st->time_base.den, ic->bit_rate*(int64_t)st->time_base.num);
1769 if (st->duration == AV_NOPTS_VALUE)
1770 st->duration = duration;
1776 #define DURATION_MAX_READ_SIZE 250000
1777 #define DURATION_MAX_RETRY 3
1779 /* only usable for MPEG-PS streams */
1780 static void estimate_timings_from_pts(AVFormatContext *ic, int64_t old_offset)
1782 AVPacket pkt1, *pkt = &pkt1;
1784 int read_size, i, ret;
1786 int64_t filesize, offset, duration;
1789 /* flush packet queue */
1790 flush_packet_queue(ic);
1792 for (i=0; i<ic->nb_streams; i++) {
1793 st = ic->streams[i];
1794 if (st->start_time == AV_NOPTS_VALUE && st->first_dts == AV_NOPTS_VALUE)
1795 av_log(st->codec, AV_LOG_WARNING, "start time is not set in estimate_timings_from_pts\n");
1798 av_parser_close(st->parser);
1803 /* estimate the end time (duration) */
1804 /* XXX: may need to support wrapping */
1805 filesize = ic->pb ? avio_size(ic->pb) : 0;
1806 end_time = AV_NOPTS_VALUE;
1808 offset = filesize - (DURATION_MAX_READ_SIZE<<retry);
1812 avio_seek(ic->pb, offset, SEEK_SET);
1815 if (read_size >= DURATION_MAX_READ_SIZE<<(FFMAX(retry-1,0)))
1819 ret = ff_read_packet(ic, pkt);
1820 } while(ret == AVERROR(EAGAIN));
1823 read_size += pkt->size;
1824 st = ic->streams[pkt->stream_index];
1825 if (pkt->pts != AV_NOPTS_VALUE &&
1826 (st->start_time != AV_NOPTS_VALUE ||
1827 st->first_dts != AV_NOPTS_VALUE)) {
1828 duration = end_time = pkt->pts;
1829 if (st->start_time != AV_NOPTS_VALUE)
1830 duration -= st->start_time;
1832 duration -= st->first_dts;
1834 duration += 1LL<<st->pts_wrap_bits;
1836 if (st->duration == AV_NOPTS_VALUE || st->duration < duration)
1837 st->duration = duration;
1840 av_free_packet(pkt);
1842 }while( end_time==AV_NOPTS_VALUE
1843 && filesize > (DURATION_MAX_READ_SIZE<<retry)
1844 && ++retry <= DURATION_MAX_RETRY);
1846 fill_all_stream_timings(ic);
1848 avio_seek(ic->pb, old_offset, SEEK_SET);
1849 for (i=0; i<ic->nb_streams; i++) {
1851 st->cur_dts= st->first_dts;
1852 st->last_IP_pts = AV_NOPTS_VALUE;
1856 static void estimate_timings(AVFormatContext *ic, int64_t old_offset)
1860 /* get the file size, if possible */
1861 if (ic->iformat->flags & AVFMT_NOFILE) {
1864 file_size = avio_size(ic->pb);
1865 file_size = FFMAX(0, file_size);
1868 if ((!strcmp(ic->iformat->name, "mpeg") ||
1869 !strcmp(ic->iformat->name, "mpegts")) &&
1870 file_size && ic->pb->seekable) {
1871 /* get accurate estimate from the PTSes */
1872 estimate_timings_from_pts(ic, old_offset);
1873 } else if (has_duration(ic)) {
1874 /* at least one component has timings - we use them for all
1876 fill_all_stream_timings(ic);
1878 av_log(ic, AV_LOG_WARNING, "Estimating duration from bitrate, this may be inaccurate\n");
1879 /* less precise: use bitrate info */
1880 estimate_timings_from_bit_rate(ic);
1882 update_stream_timings(ic);
1886 AVStream av_unused *st;
1887 for(i = 0;i < ic->nb_streams; i++) {
1888 st = ic->streams[i];
1889 av_dlog(ic, "%d: start_time: %0.3f duration: %0.3f\n", i,
1890 (double) st->start_time / AV_TIME_BASE,
1891 (double) st->duration / AV_TIME_BASE);
1893 av_dlog(ic, "stream: start_time: %0.3f duration: %0.3f bitrate=%d kb/s\n",
1894 (double) ic->start_time / AV_TIME_BASE,
1895 (double) ic->duration / AV_TIME_BASE,
1896 ic->bit_rate / 1000);
1900 static int has_codec_parameters(AVStream *st)
1902 AVCodecContext *avctx = st->codec;
1904 switch (avctx->codec_type) {
1905 case AVMEDIA_TYPE_AUDIO:
1906 val = avctx->sample_rate && avctx->channels;
1907 if (st->info->found_decoder >= 0 && avctx->sample_fmt == AV_SAMPLE_FMT_NONE)
1910 case AVMEDIA_TYPE_VIDEO:
1912 if (st->info->found_decoder >= 0 && avctx->pix_fmt == AV_PIX_FMT_NONE)
1919 return avctx->codec_id != AV_CODEC_ID_NONE && val != 0;
1922 static int has_decode_delay_been_guessed(AVStream *st)
1924 return st->codec->codec_id != AV_CODEC_ID_H264 ||
1925 st->info->nb_decoded_frames >= 6;
1928 /* returns 1 or 0 if or if not decoded data was returned, or a negative error */
1929 static int try_decode_frame(AVStream *st, AVPacket *avpkt, AVDictionary **options)
1931 const AVCodec *codec;
1932 int got_picture = 1, ret = 0;
1933 AVFrame *frame = av_frame_alloc();
1934 AVPacket pkt = *avpkt;
1937 return AVERROR(ENOMEM);
1939 if (!avcodec_is_open(st->codec) && !st->info->found_decoder) {
1940 AVDictionary *thread_opt = NULL;
1942 codec = st->codec->codec ? st->codec->codec :
1943 avcodec_find_decoder(st->codec->codec_id);
1946 st->info->found_decoder = -1;
1951 /* force thread count to 1 since the h264 decoder will not extract SPS
1952 * and PPS to extradata during multi-threaded decoding */
1953 av_dict_set(options ? options : &thread_opt, "threads", "1", 0);
1954 ret = avcodec_open2(st->codec, codec, options ? options : &thread_opt);
1956 av_dict_free(&thread_opt);
1958 st->info->found_decoder = -1;
1961 st->info->found_decoder = 1;
1962 } else if (!st->info->found_decoder)
1963 st->info->found_decoder = 1;
1965 if (st->info->found_decoder < 0) {
1970 while ((pkt.size > 0 || (!pkt.data && got_picture)) &&
1972 (!has_codec_parameters(st) ||
1973 !has_decode_delay_been_guessed(st) ||
1974 (!st->codec_info_nb_frames && st->codec->codec->capabilities & CODEC_CAP_CHANNEL_CONF))) {
1976 avcodec_get_frame_defaults(frame);
1977 switch(st->codec->codec_type) {
1978 case AVMEDIA_TYPE_VIDEO:
1979 ret = avcodec_decode_video2(st->codec, frame,
1980 &got_picture, &pkt);
1982 case AVMEDIA_TYPE_AUDIO:
1983 ret = avcodec_decode_audio4(st->codec, frame, &got_picture, &pkt);
1990 st->info->nb_decoded_frames++;
1998 avcodec_free_frame(&frame);
2002 unsigned int ff_codec_get_tag(const AVCodecTag *tags, enum AVCodecID id)
2004 while (tags->id != AV_CODEC_ID_NONE) {
2012 enum AVCodecID ff_codec_get_id(const AVCodecTag *tags, unsigned int tag)
2015 for(i=0; tags[i].id != AV_CODEC_ID_NONE;i++) {
2016 if(tag == tags[i].tag)
2019 for(i=0; tags[i].id != AV_CODEC_ID_NONE; i++) {
2020 if (avpriv_toupper4(tag) == avpriv_toupper4(tags[i].tag))
2023 return AV_CODEC_ID_NONE;
2026 enum AVCodecID ff_get_pcm_codec_id(int bps, int flt, int be, int sflags)
2030 case 32: return be ? AV_CODEC_ID_PCM_F32BE : AV_CODEC_ID_PCM_F32LE;
2031 case 64: return be ? AV_CODEC_ID_PCM_F64BE : AV_CODEC_ID_PCM_F64LE;
2032 default: return AV_CODEC_ID_NONE;
2036 if (sflags & (1 << (bps - 1))) {
2038 case 1: return AV_CODEC_ID_PCM_S8;
2039 case 2: return be ? AV_CODEC_ID_PCM_S16BE : AV_CODEC_ID_PCM_S16LE;
2040 case 3: return be ? AV_CODEC_ID_PCM_S24BE : AV_CODEC_ID_PCM_S24LE;
2041 case 4: return be ? AV_CODEC_ID_PCM_S32BE : AV_CODEC_ID_PCM_S32LE;
2042 default: return AV_CODEC_ID_NONE;
2046 case 1: return AV_CODEC_ID_PCM_U8;
2047 case 2: return be ? AV_CODEC_ID_PCM_U16BE : AV_CODEC_ID_PCM_U16LE;
2048 case 3: return be ? AV_CODEC_ID_PCM_U24BE : AV_CODEC_ID_PCM_U24LE;
2049 case 4: return be ? AV_CODEC_ID_PCM_U32BE : AV_CODEC_ID_PCM_U32LE;
2050 default: return AV_CODEC_ID_NONE;
2056 unsigned int av_codec_get_tag(const AVCodecTag * const *tags, enum AVCodecID id)
2059 for(i=0; tags && tags[i]; i++){
2060 int tag= ff_codec_get_tag(tags[i], id);
2066 enum AVCodecID av_codec_get_id(const AVCodecTag * const *tags, unsigned int tag)
2069 for(i=0; tags && tags[i]; i++){
2070 enum AVCodecID id= ff_codec_get_id(tags[i], tag);
2071 if(id!=AV_CODEC_ID_NONE) return id;
2073 return AV_CODEC_ID_NONE;
2076 static void compute_chapters_end(AVFormatContext *s)
2079 int64_t max_time = s->duration + ((s->start_time == AV_NOPTS_VALUE) ? 0 : s->start_time);
2081 for (i = 0; i < s->nb_chapters; i++)
2082 if (s->chapters[i]->end == AV_NOPTS_VALUE) {
2083 AVChapter *ch = s->chapters[i];
2084 int64_t end = max_time ? av_rescale_q(max_time, AV_TIME_BASE_Q, ch->time_base)
2087 for (j = 0; j < s->nb_chapters; j++) {
2088 AVChapter *ch1 = s->chapters[j];
2089 int64_t next_start = av_rescale_q(ch1->start, ch1->time_base, ch->time_base);
2090 if (j != i && next_start > ch->start && next_start < end)
2093 ch->end = (end == INT64_MAX) ? ch->start : end;
2097 static int get_std_framerate(int i){
2098 if(i<60*12) return i*1001;
2099 else return ((const int[]){24,30,60,12,15})[i-60*12]*1000*12;
2103 * Is the time base unreliable.
2104 * This is a heuristic to balance between quick acceptance of the values in
2105 * the headers vs. some extra checks.
2106 * Old DivX and Xvid often have nonsense timebases like 1fps or 2fps.
2107 * MPEG-2 commonly misuses field repeat flags to store different framerates.
2108 * And there are "variable" fps files this needs to detect as well.
2110 static int tb_unreliable(AVCodecContext *c){
2111 if( c->time_base.den >= 101L*c->time_base.num
2112 || c->time_base.den < 5L*c->time_base.num
2113 /* || c->codec_tag == AV_RL32("DIVX")
2114 || c->codec_tag == AV_RL32("XVID")*/
2115 || c->codec_id == AV_CODEC_ID_MPEG2VIDEO
2116 || c->codec_id == AV_CODEC_ID_H264
2122 int avformat_find_stream_info(AVFormatContext *ic, AVDictionary **options)
2124 int i, count, ret, read_size, j;
2126 AVPacket pkt1, *pkt;
2127 int64_t old_offset = avio_tell(ic->pb);
2128 int orig_nb_streams = ic->nb_streams; // new streams might appear, no options for those
2130 for(i=0;i<ic->nb_streams;i++) {
2131 const AVCodec *codec;
2132 AVDictionary *thread_opt = NULL;
2133 st = ic->streams[i];
2135 //only for the split stuff
2136 if (!st->parser && !(ic->flags & AVFMT_FLAG_NOPARSE)) {
2137 st->parser = av_parser_init(st->codec->codec_id);
2138 if(st->need_parsing == AVSTREAM_PARSE_HEADERS && st->parser){
2139 st->parser->flags |= PARSER_FLAG_COMPLETE_FRAMES;
2142 codec = st->codec->codec ? st->codec->codec :
2143 avcodec_find_decoder(st->codec->codec_id);
2145 /* force thread count to 1 since the h264 decoder will not extract SPS
2146 * and PPS to extradata during multi-threaded decoding */
2147 av_dict_set(options ? &options[i] : &thread_opt, "threads", "1", 0);
2149 /* Ensure that subtitle_header is properly set. */
2150 if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE
2151 && codec && !st->codec->codec)
2152 avcodec_open2(st->codec, codec, options ? &options[i]
2155 //try to just open decoders, in case this is enough to get parameters
2156 if (!has_codec_parameters(st)) {
2157 if (codec && !st->codec->codec)
2158 avcodec_open2(st->codec, codec, options ? &options[i]
2162 av_dict_free(&thread_opt);
2165 for (i=0; i<ic->nb_streams; i++) {
2166 ic->streams[i]->info->fps_first_dts = AV_NOPTS_VALUE;
2167 ic->streams[i]->info->fps_last_dts = AV_NOPTS_VALUE;
2173 if (ff_check_interrupt(&ic->interrupt_callback)){
2175 av_log(ic, AV_LOG_DEBUG, "interrupted\n");
2179 /* check if one codec still needs to be handled */
2180 for(i=0;i<ic->nb_streams;i++) {
2181 int fps_analyze_framecount = 20;
2183 st = ic->streams[i];
2184 if (!has_codec_parameters(st))
2186 /* if the timebase is coarse (like the usual millisecond precision
2187 of mkv), we need to analyze more frames to reliably arrive at
2189 if (av_q2d(st->time_base) > 0.0005)
2190 fps_analyze_framecount *= 2;
2191 if (ic->fps_probe_size >= 0)
2192 fps_analyze_framecount = ic->fps_probe_size;
2193 /* variable fps and no guess at the real fps */
2194 if( tb_unreliable(st->codec) && !st->avg_frame_rate.num
2195 && st->codec_info_nb_frames < fps_analyze_framecount
2196 && st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
2198 if(st->parser && st->parser->parser->split && !st->codec->extradata)
2200 if (st->first_dts == AV_NOPTS_VALUE &&
2201 (st->codec->codec_type == AVMEDIA_TYPE_VIDEO ||
2202 st->codec->codec_type == AVMEDIA_TYPE_AUDIO))
2205 if (i == ic->nb_streams) {
2206 /* NOTE: if the format has no header, then we need to read
2207 some packets to get most of the streams, so we cannot
2209 if (!(ic->ctx_flags & AVFMTCTX_NOHEADER)) {
2210 /* if we found the info for all the codecs, we can stop */
2212 av_log(ic, AV_LOG_DEBUG, "All info found\n");
2216 /* we did not get all the codec info, but we read too much data */
2217 if (read_size >= ic->probesize) {
2219 av_log(ic, AV_LOG_DEBUG, "Probe buffer size limit %d reached\n", ic->probesize);
2223 /* NOTE: a new stream can be added there if no header in file
2224 (AVFMTCTX_NOHEADER) */
2225 ret = read_frame_internal(ic, &pkt1);
2226 if (ret == AVERROR(EAGAIN))
2231 AVPacket empty_pkt = { 0 };
2233 av_init_packet(&empty_pkt);
2235 ret = -1; /* we could not have all the codec parameters before EOF */
2236 for(i=0;i<ic->nb_streams;i++) {
2237 st = ic->streams[i];
2239 /* flush the decoders */
2240 if (st->info->found_decoder == 1) {
2242 err = try_decode_frame(st, &empty_pkt,
2243 (options && i < orig_nb_streams) ?
2244 &options[i] : NULL);
2245 } while (err > 0 && !has_codec_parameters(st));
2249 av_log(ic, AV_LOG_WARNING,
2250 "decoding for stream %d failed\n", st->index);
2251 } else if (!has_codec_parameters(st)) {
2253 avcodec_string(buf, sizeof(buf), st->codec, 0);
2254 av_log(ic, AV_LOG_WARNING,
2255 "Could not find codec parameters (%s)\n", buf);
2263 if (ic->flags & AVFMT_FLAG_NOBUFFER) {
2266 pkt = add_to_pktbuf(&ic->packet_buffer, &pkt1,
2267 &ic->packet_buffer_end);
2268 if ((ret = av_dup_packet(pkt)) < 0)
2269 goto find_stream_info_err;
2272 read_size += pkt->size;
2274 st = ic->streams[pkt->stream_index];
2275 if (pkt->dts != AV_NOPTS_VALUE && st->codec_info_nb_frames > 1) {
2276 /* check for non-increasing dts */
2277 if (st->info->fps_last_dts != AV_NOPTS_VALUE &&
2278 st->info->fps_last_dts >= pkt->dts) {
2279 av_log(ic, AV_LOG_WARNING, "Non-increasing DTS in stream %d: "
2280 "packet %d with DTS %"PRId64", packet %d with DTS "
2281 "%"PRId64"\n", st->index, st->info->fps_last_dts_idx,
2282 st->info->fps_last_dts, st->codec_info_nb_frames, pkt->dts);
2283 st->info->fps_first_dts = st->info->fps_last_dts = AV_NOPTS_VALUE;
2285 /* check for a discontinuity in dts - if the difference in dts
2286 * is more than 1000 times the average packet duration in the sequence,
2287 * we treat it as a discontinuity */
2288 if (st->info->fps_last_dts != AV_NOPTS_VALUE &&
2289 st->info->fps_last_dts_idx > st->info->fps_first_dts_idx &&
2290 (pkt->dts - st->info->fps_last_dts) / 1000 >
2291 (st->info->fps_last_dts - st->info->fps_first_dts) / (st->info->fps_last_dts_idx - st->info->fps_first_dts_idx)) {
2292 av_log(ic, AV_LOG_WARNING, "DTS discontinuity in stream %d: "
2293 "packet %d with DTS %"PRId64", packet %d with DTS "
2294 "%"PRId64"\n", st->index, st->info->fps_last_dts_idx,
2295 st->info->fps_last_dts, st->codec_info_nb_frames, pkt->dts);
2296 st->info->fps_first_dts = st->info->fps_last_dts = AV_NOPTS_VALUE;
2299 /* update stored dts values */
2300 if (st->info->fps_first_dts == AV_NOPTS_VALUE) {
2301 st->info->fps_first_dts = pkt->dts;
2302 st->info->fps_first_dts_idx = st->codec_info_nb_frames;
2304 st->info->fps_last_dts = pkt->dts;
2305 st->info->fps_last_dts_idx = st->codec_info_nb_frames;
2307 /* check max_analyze_duration */
2308 if (av_rescale_q(pkt->dts - st->info->fps_first_dts, st->time_base,
2309 AV_TIME_BASE_Q) >= ic->max_analyze_duration) {
2310 av_log(ic, AV_LOG_WARNING, "max_analyze_duration reached\n");
2314 if(st->parser && st->parser->parser->split && !st->codec->extradata){
2315 int i= st->parser->parser->split(st->codec, pkt->data, pkt->size);
2316 if (i > 0 && i < FF_MAX_EXTRADATA_SIZE) {
2317 st->codec->extradata_size= i;
2318 st->codec->extradata= av_malloc(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
2319 if (!st->codec->extradata)
2320 return AVERROR(ENOMEM);
2321 memcpy(st->codec->extradata, pkt->data, st->codec->extradata_size);
2322 memset(st->codec->extradata + i, 0, FF_INPUT_BUFFER_PADDING_SIZE);
2326 /* if still no information, we try to open the codec and to
2327 decompress the frame. We try to avoid that in most cases as
2328 it takes longer and uses more memory. For MPEG-4, we need to
2329 decompress for QuickTime.
2331 If CODEC_CAP_CHANNEL_CONF is set this will force decoding of at
2332 least one frame of codec data, this makes sure the codec initializes
2333 the channel configuration and does not only trust the values from the container.
2335 try_decode_frame(st, pkt, (options && i < orig_nb_streams ) ? &options[i] : NULL);
2337 st->codec_info_nb_frames++;
2341 // close codecs which were opened in try_decode_frame()
2342 for(i=0;i<ic->nb_streams;i++) {
2343 st = ic->streams[i];
2344 avcodec_close(st->codec);
2346 for(i=0;i<ic->nb_streams;i++) {
2347 st = ic->streams[i];
2348 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
2349 /* estimate average framerate if not set by demuxer */
2350 if (!st->avg_frame_rate.num && st->info->fps_last_dts != st->info->fps_first_dts) {
2351 int64_t delta_dts = st->info->fps_last_dts - st->info->fps_first_dts;
2352 int delta_packets = st->info->fps_last_dts_idx - st->info->fps_first_dts_idx;
2354 double best_error = 0.01;
2356 if (delta_dts >= INT64_MAX / st->time_base.num ||
2357 delta_packets >= INT64_MAX / st->time_base.den ||
2360 av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
2361 delta_packets*(int64_t)st->time_base.den,
2362 delta_dts*(int64_t)st->time_base.num, 60000);
2364 /* round guessed framerate to a "standard" framerate if it's
2365 * within 1% of the original estimate*/
2366 for (j = 1; j < MAX_STD_TIMEBASES; j++) {
2367 AVRational std_fps = { get_std_framerate(j), 12*1001 };
2368 double error = fabs(av_q2d(st->avg_frame_rate) / av_q2d(std_fps) - 1);
2370 if (error < best_error) {
2372 best_fps = std_fps.num;
2376 av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
2377 best_fps, 12*1001, INT_MAX);
2380 }else if(st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
2381 if(!st->codec->bits_per_coded_sample)
2382 st->codec->bits_per_coded_sample= av_get_bits_per_sample(st->codec->codec_id);
2383 // set stream disposition based on audio service type
2384 switch (st->codec->audio_service_type) {
2385 case AV_AUDIO_SERVICE_TYPE_EFFECTS:
2386 st->disposition = AV_DISPOSITION_CLEAN_EFFECTS; break;
2387 case AV_AUDIO_SERVICE_TYPE_VISUALLY_IMPAIRED:
2388 st->disposition = AV_DISPOSITION_VISUAL_IMPAIRED; break;
2389 case AV_AUDIO_SERVICE_TYPE_HEARING_IMPAIRED:
2390 st->disposition = AV_DISPOSITION_HEARING_IMPAIRED; break;
2391 case AV_AUDIO_SERVICE_TYPE_COMMENTARY:
2392 st->disposition = AV_DISPOSITION_COMMENT; break;
2393 case AV_AUDIO_SERVICE_TYPE_KARAOKE:
2394 st->disposition = AV_DISPOSITION_KARAOKE; break;
2399 estimate_timings(ic, old_offset);
2401 compute_chapters_end(ic);
2403 find_stream_info_err:
2404 for (i=0; i < ic->nb_streams; i++) {
2405 if (ic->streams[i]->codec)
2406 ic->streams[i]->codec->thread_count = 0;
2407 av_freep(&ic->streams[i]->info);
2412 static AVProgram *find_program_from_stream(AVFormatContext *ic, int s)
2416 for (i = 0; i < ic->nb_programs; i++)
2417 for (j = 0; j < ic->programs[i]->nb_stream_indexes; j++)
2418 if (ic->programs[i]->stream_index[j] == s)
2419 return ic->programs[i];
2423 int av_find_best_stream(AVFormatContext *ic,
2424 enum AVMediaType type,
2425 int wanted_stream_nb,
2427 AVCodec **decoder_ret,
2430 int i, nb_streams = ic->nb_streams;
2431 int ret = AVERROR_STREAM_NOT_FOUND, best_count = -1;
2432 unsigned *program = NULL;
2433 AVCodec *decoder = NULL, *best_decoder = NULL;
2435 if (related_stream >= 0 && wanted_stream_nb < 0) {
2436 AVProgram *p = find_program_from_stream(ic, related_stream);
2438 program = p->stream_index;
2439 nb_streams = p->nb_stream_indexes;
2442 for (i = 0; i < nb_streams; i++) {
2443 int real_stream_index = program ? program[i] : i;
2444 AVStream *st = ic->streams[real_stream_index];
2445 AVCodecContext *avctx = st->codec;
2446 if (avctx->codec_type != type)
2448 if (wanted_stream_nb >= 0 && real_stream_index != wanted_stream_nb)
2450 if (st->disposition & (AV_DISPOSITION_HEARING_IMPAIRED|AV_DISPOSITION_VISUAL_IMPAIRED))
2453 decoder = avcodec_find_decoder(st->codec->codec_id);
2456 ret = AVERROR_DECODER_NOT_FOUND;
2460 if (best_count >= st->codec_info_nb_frames)
2462 best_count = st->codec_info_nb_frames;
2463 ret = real_stream_index;
2464 best_decoder = decoder;
2465 if (program && i == nb_streams - 1 && ret < 0) {
2467 nb_streams = ic->nb_streams;
2468 i = 0; /* no related stream found, try again with everything */
2472 *decoder_ret = best_decoder;
2476 /*******************************************************/
2478 int av_read_play(AVFormatContext *s)
2480 if (s->iformat->read_play)
2481 return s->iformat->read_play(s);
2483 return avio_pause(s->pb, 0);
2484 return AVERROR(ENOSYS);
2487 int av_read_pause(AVFormatContext *s)
2489 if (s->iformat->read_pause)
2490 return s->iformat->read_pause(s);
2492 return avio_pause(s->pb, 1);
2493 return AVERROR(ENOSYS);
2496 void avformat_free_context(AVFormatContext *s)
2502 if (s->iformat && s->iformat->priv_class && s->priv_data)
2503 av_opt_free(s->priv_data);
2505 for(i=0;i<s->nb_streams;i++) {
2506 /* free all data in a stream component */
2509 av_parser_close(st->parser);
2511 if (st->attached_pic.data)
2512 av_free_packet(&st->attached_pic);
2513 av_dict_free(&st->metadata);
2514 av_freep(&st->probe_data.buf);
2515 av_free(st->index_entries);
2516 av_free(st->codec->extradata);
2517 av_free(st->codec->subtitle_header);
2519 av_free(st->priv_data);
2523 for(i=s->nb_programs-1; i>=0; i--) {
2524 av_dict_free(&s->programs[i]->metadata);
2525 av_freep(&s->programs[i]->stream_index);
2526 av_freep(&s->programs[i]);
2528 av_freep(&s->programs);
2529 av_freep(&s->priv_data);
2530 while(s->nb_chapters--) {
2531 av_dict_free(&s->chapters[s->nb_chapters]->metadata);
2532 av_free(s->chapters[s->nb_chapters]);
2534 av_freep(&s->chapters);
2535 av_dict_free(&s->metadata);
2536 av_freep(&s->streams);
2540 void avformat_close_input(AVFormatContext **ps)
2542 AVFormatContext *s = *ps;
2543 AVIOContext *pb = s->pb;
2545 if ((s->iformat && s->iformat->flags & AVFMT_NOFILE) ||
2546 (s->flags & AVFMT_FLAG_CUSTOM_IO))
2549 flush_packet_queue(s);
2552 if (s->iformat->read_close)
2553 s->iformat->read_close(s);
2556 avformat_free_context(s);
2563 AVStream *avformat_new_stream(AVFormatContext *s, AVCodec *c)
2568 if (av_reallocp_array(&s->streams, s->nb_streams + 1, sizeof(*s->streams)) < 0) {
2573 st = av_mallocz(sizeof(AVStream));
2576 if (!(st->info = av_mallocz(sizeof(*st->info)))) {
2581 st->codec = avcodec_alloc_context3(c);
2583 /* no default bitrate if decoding */
2584 st->codec->bit_rate = 0;
2586 st->index = s->nb_streams;
2587 st->start_time = AV_NOPTS_VALUE;
2588 st->duration = AV_NOPTS_VALUE;
2589 /* we set the current DTS to 0 so that formats without any timestamps
2590 but durations get some timestamps, formats with some unknown
2591 timestamps have their first few packets buffered and the
2592 timestamps corrected before they are returned to the user */
2594 st->first_dts = AV_NOPTS_VALUE;
2595 st->probe_packets = MAX_PROBE_PACKETS;
2597 /* default pts setting is MPEG-like */
2598 avpriv_set_pts_info(st, 33, 1, 90000);
2599 st->last_IP_pts = AV_NOPTS_VALUE;
2600 for(i=0; i<MAX_REORDER_DELAY+1; i++)
2601 st->pts_buffer[i]= AV_NOPTS_VALUE;
2603 st->sample_aspect_ratio = (AVRational){0,1};
2605 st->info->fps_first_dts = AV_NOPTS_VALUE;
2606 st->info->fps_last_dts = AV_NOPTS_VALUE;
2608 s->streams[s->nb_streams++] = st;
2612 AVProgram *av_new_program(AVFormatContext *ac, int id)
2614 AVProgram *program=NULL;
2617 av_dlog(ac, "new_program: id=0x%04x\n", id);
2619 for(i=0; i<ac->nb_programs; i++)
2620 if(ac->programs[i]->id == id)
2621 program = ac->programs[i];
2624 program = av_mallocz(sizeof(AVProgram));
2627 dynarray_add(&ac->programs, &ac->nb_programs, program);
2628 program->discard = AVDISCARD_NONE;
2635 AVChapter *avpriv_new_chapter(AVFormatContext *s, int id, AVRational time_base, int64_t start, int64_t end, const char *title)
2637 AVChapter *chapter = NULL;
2640 for(i=0; i<s->nb_chapters; i++)
2641 if(s->chapters[i]->id == id)
2642 chapter = s->chapters[i];
2645 chapter= av_mallocz(sizeof(AVChapter));
2648 dynarray_add(&s->chapters, &s->nb_chapters, chapter);
2650 av_dict_set(&chapter->metadata, "title", title, 0);
2652 chapter->time_base= time_base;
2653 chapter->start = start;
2659 void ff_program_add_stream_index(AVFormatContext *ac, int progid, unsigned int idx)
2662 AVProgram *program=NULL;
2664 if (idx >= ac->nb_streams) {
2665 av_log(ac, AV_LOG_ERROR, "stream index %d is not valid\n", idx);
2669 for(i=0; i<ac->nb_programs; i++){
2670 if(ac->programs[i]->id != progid)
2672 program = ac->programs[i];
2673 for(j=0; j<program->nb_stream_indexes; j++)
2674 if(program->stream_index[j] == idx)
2677 if (av_reallocp_array(&program->stream_index,
2678 program->nb_stream_indexes + 1,
2679 sizeof(*program->stream_index)) < 0) {
2680 program->nb_stream_indexes = 0;
2683 program->stream_index[program->nb_stream_indexes++] = idx;
2688 static void print_fps(double d, const char *postfix){
2689 uint64_t v= lrintf(d*100);
2690 if (v% 100 ) av_log(NULL, AV_LOG_INFO, ", %3.2f %s", d, postfix);
2691 else if(v%(100*1000)) av_log(NULL, AV_LOG_INFO, ", %1.0f %s", d, postfix);
2692 else av_log(NULL, AV_LOG_INFO, ", %1.0fk %s", d/1000, postfix);
2695 static void dump_metadata(void *ctx, AVDictionary *m, const char *indent)
2697 if(m && !(av_dict_count(m) == 1 && av_dict_get(m, "language", NULL, 0))){
2698 AVDictionaryEntry *tag=NULL;
2700 av_log(ctx, AV_LOG_INFO, "%sMetadata:\n", indent);
2701 while((tag=av_dict_get(m, "", tag, AV_DICT_IGNORE_SUFFIX))) {
2702 if(strcmp("language", tag->key))
2703 av_log(ctx, AV_LOG_INFO, "%s %-16s: %s\n", indent, tag->key, tag->value);
2708 /* "user interface" functions */
2709 static void dump_stream_format(AVFormatContext *ic, int i, int index, int is_output)
2712 int flags = (is_output ? ic->oformat->flags : ic->iformat->flags);
2713 AVStream *st = ic->streams[i];
2714 int g = av_gcd(st->time_base.num, st->time_base.den);
2715 AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL, 0);
2716 avcodec_string(buf, sizeof(buf), st->codec, is_output);
2717 av_log(NULL, AV_LOG_INFO, " Stream #%d.%d", index, i);
2718 /* the pid is an important information, so we display it */
2719 /* XXX: add a generic system */
2720 if (flags & AVFMT_SHOW_IDS)
2721 av_log(NULL, AV_LOG_INFO, "[0x%x]", st->id);
2723 av_log(NULL, AV_LOG_INFO, "(%s)", lang->value);
2724 av_log(NULL, AV_LOG_DEBUG, ", %d, %d/%d", st->codec_info_nb_frames, st->time_base.num/g, st->time_base.den/g);
2725 av_log(NULL, AV_LOG_INFO, ": %s", buf);
2726 if (st->sample_aspect_ratio.num && // default
2727 av_cmp_q(st->sample_aspect_ratio, st->codec->sample_aspect_ratio)) {
2728 AVRational display_aspect_ratio;
2729 av_reduce(&display_aspect_ratio.num, &display_aspect_ratio.den,
2730 st->codec->width*st->sample_aspect_ratio.num,
2731 st->codec->height*st->sample_aspect_ratio.den,
2733 av_log(NULL, AV_LOG_INFO, ", PAR %d:%d DAR %d:%d",
2734 st->sample_aspect_ratio.num, st->sample_aspect_ratio.den,
2735 display_aspect_ratio.num, display_aspect_ratio.den);
2737 if(st->codec->codec_type == AVMEDIA_TYPE_VIDEO){
2738 if(st->avg_frame_rate.den && st->avg_frame_rate.num)
2739 print_fps(av_q2d(st->avg_frame_rate), "fps");
2740 if(st->time_base.den && st->time_base.num)
2741 print_fps(1/av_q2d(st->time_base), "tbn");
2742 if(st->codec->time_base.den && st->codec->time_base.num)
2743 print_fps(1/av_q2d(st->codec->time_base), "tbc");
2745 if (st->disposition & AV_DISPOSITION_DEFAULT)
2746 av_log(NULL, AV_LOG_INFO, " (default)");
2747 if (st->disposition & AV_DISPOSITION_DUB)
2748 av_log(NULL, AV_LOG_INFO, " (dub)");
2749 if (st->disposition & AV_DISPOSITION_ORIGINAL)
2750 av_log(NULL, AV_LOG_INFO, " (original)");
2751 if (st->disposition & AV_DISPOSITION_COMMENT)
2752 av_log(NULL, AV_LOG_INFO, " (comment)");
2753 if (st->disposition & AV_DISPOSITION_LYRICS)
2754 av_log(NULL, AV_LOG_INFO, " (lyrics)");
2755 if (st->disposition & AV_DISPOSITION_KARAOKE)
2756 av_log(NULL, AV_LOG_INFO, " (karaoke)");
2757 if (st->disposition & AV_DISPOSITION_FORCED)
2758 av_log(NULL, AV_LOG_INFO, " (forced)");
2759 if (st->disposition & AV_DISPOSITION_HEARING_IMPAIRED)
2760 av_log(NULL, AV_LOG_INFO, " (hearing impaired)");
2761 if (st->disposition & AV_DISPOSITION_VISUAL_IMPAIRED)
2762 av_log(NULL, AV_LOG_INFO, " (visual impaired)");
2763 if (st->disposition & AV_DISPOSITION_CLEAN_EFFECTS)
2764 av_log(NULL, AV_LOG_INFO, " (clean effects)");
2765 av_log(NULL, AV_LOG_INFO, "\n");
2766 dump_metadata(NULL, st->metadata, " ");
2769 void av_dump_format(AVFormatContext *ic,
2775 uint8_t *printed = ic->nb_streams ? av_mallocz(ic->nb_streams) : NULL;
2776 if (ic->nb_streams && !printed)
2779 av_log(NULL, AV_LOG_INFO, "%s #%d, %s, %s '%s':\n",
2780 is_output ? "Output" : "Input",
2782 is_output ? ic->oformat->name : ic->iformat->name,
2783 is_output ? "to" : "from", url);
2784 dump_metadata(NULL, ic->metadata, " ");
2786 av_log(NULL, AV_LOG_INFO, " Duration: ");
2787 if (ic->duration != AV_NOPTS_VALUE) {
2788 int hours, mins, secs, us;
2789 secs = ic->duration / AV_TIME_BASE;
2790 us = ic->duration % AV_TIME_BASE;
2795 av_log(NULL, AV_LOG_INFO, "%02d:%02d:%02d.%02d", hours, mins, secs,
2796 (100 * us) / AV_TIME_BASE);
2798 av_log(NULL, AV_LOG_INFO, "N/A");
2800 if (ic->start_time != AV_NOPTS_VALUE) {
2802 av_log(NULL, AV_LOG_INFO, ", start: ");
2803 secs = ic->start_time / AV_TIME_BASE;
2804 us = abs(ic->start_time % AV_TIME_BASE);
2805 av_log(NULL, AV_LOG_INFO, "%d.%06d",
2806 secs, (int)av_rescale(us, 1000000, AV_TIME_BASE));
2808 av_log(NULL, AV_LOG_INFO, ", bitrate: ");
2810 av_log(NULL, AV_LOG_INFO,"%d kb/s", ic->bit_rate / 1000);
2812 av_log(NULL, AV_LOG_INFO, "N/A");
2814 av_log(NULL, AV_LOG_INFO, "\n");
2816 for (i = 0; i < ic->nb_chapters; i++) {
2817 AVChapter *ch = ic->chapters[i];
2818 av_log(NULL, AV_LOG_INFO, " Chapter #%d.%d: ", index, i);
2819 av_log(NULL, AV_LOG_INFO, "start %f, ", ch->start * av_q2d(ch->time_base));
2820 av_log(NULL, AV_LOG_INFO, "end %f\n", ch->end * av_q2d(ch->time_base));
2822 dump_metadata(NULL, ch->metadata, " ");
2824 if(ic->nb_programs) {
2825 int j, k, total = 0;
2826 for(j=0; j<ic->nb_programs; j++) {
2827 AVDictionaryEntry *name = av_dict_get(ic->programs[j]->metadata,
2829 av_log(NULL, AV_LOG_INFO, " Program %d %s\n", ic->programs[j]->id,
2830 name ? name->value : "");
2831 dump_metadata(NULL, ic->programs[j]->metadata, " ");
2832 for(k=0; k<ic->programs[j]->nb_stream_indexes; k++) {
2833 dump_stream_format(ic, ic->programs[j]->stream_index[k], index, is_output);
2834 printed[ic->programs[j]->stream_index[k]] = 1;
2836 total += ic->programs[j]->nb_stream_indexes;
2838 if (total < ic->nb_streams)
2839 av_log(NULL, AV_LOG_INFO, " No Program\n");
2841 for(i=0;i<ic->nb_streams;i++)
2843 dump_stream_format(ic, i, index, is_output);
2848 uint64_t ff_ntp_time(void)
2850 return (av_gettime() / 1000) * 1000 + NTP_OFFSET_US;
2853 int av_get_frame_filename(char *buf, int buf_size,
2854 const char *path, int number)
2857 char *q, buf1[20], c;
2858 int nd, len, percentd_found;
2870 while (av_isdigit(*p)) {
2871 nd = nd * 10 + *p++ - '0';
2874 } while (av_isdigit(c));
2883 snprintf(buf1, sizeof(buf1), "%0*d", nd, number);
2885 if ((q - buf + len) > buf_size - 1)
2887 memcpy(q, buf1, len);
2895 if ((q - buf) < buf_size - 1)
2899 if (!percentd_found)
2908 static void hex_dump_internal(void *avcl, FILE *f, int level,
2909 const uint8_t *buf, int size)
2912 #define PRINT(...) do { if (!f) av_log(avcl, level, __VA_ARGS__); else fprintf(f, __VA_ARGS__); } while(0)
2914 for(i=0;i<size;i+=16) {
2921 PRINT(" %02x", buf[i+j]);
2926 for(j=0;j<len;j++) {
2928 if (c < ' ' || c > '~')
2937 void av_hex_dump(FILE *f, const uint8_t *buf, int size)
2939 hex_dump_internal(NULL, f, 0, buf, size);
2942 void av_hex_dump_log(void *avcl, int level, const uint8_t *buf, int size)
2944 hex_dump_internal(avcl, NULL, level, buf, size);
2947 static void pkt_dump_internal(void *avcl, FILE *f, int level, AVPacket *pkt, int dump_payload, AVRational time_base)
2949 #define PRINT(...) do { if (!f) av_log(avcl, level, __VA_ARGS__); else fprintf(f, __VA_ARGS__); } while(0)
2950 PRINT("stream #%d:\n", pkt->stream_index);
2951 PRINT(" keyframe=%d\n", ((pkt->flags & AV_PKT_FLAG_KEY) != 0));
2952 PRINT(" duration=%0.3f\n", pkt->duration * av_q2d(time_base));
2953 /* DTS is _always_ valid after av_read_frame() */
2955 if (pkt->dts == AV_NOPTS_VALUE)
2958 PRINT("%0.3f", pkt->dts * av_q2d(time_base));
2959 /* PTS may not be known if B-frames are present. */
2961 if (pkt->pts == AV_NOPTS_VALUE)
2964 PRINT("%0.3f", pkt->pts * av_q2d(time_base));
2966 PRINT(" size=%d\n", pkt->size);
2969 av_hex_dump(f, pkt->data, pkt->size);
2972 void av_pkt_dump2(FILE *f, AVPacket *pkt, int dump_payload, AVStream *st)
2974 pkt_dump_internal(NULL, f, 0, pkt, dump_payload, st->time_base);
2977 void av_pkt_dump_log2(void *avcl, int level, AVPacket *pkt, int dump_payload,
2980 pkt_dump_internal(avcl, NULL, level, pkt, dump_payload, st->time_base);
2983 void av_url_split(char *proto, int proto_size,
2984 char *authorization, int authorization_size,
2985 char *hostname, int hostname_size,
2987 char *path, int path_size,
2990 const char *p, *ls, *at, *col, *brk;
2992 if (port_ptr) *port_ptr = -1;
2993 if (proto_size > 0) proto[0] = 0;
2994 if (authorization_size > 0) authorization[0] = 0;
2995 if (hostname_size > 0) hostname[0] = 0;
2996 if (path_size > 0) path[0] = 0;
2998 /* parse protocol */
2999 if ((p = strchr(url, ':'))) {
3000 av_strlcpy(proto, url, FFMIN(proto_size, p + 1 - url));
3005 /* no protocol means plain filename */
3006 av_strlcpy(path, url, path_size);
3010 /* separate path from hostname */
3011 ls = strchr(p, '/');
3013 ls = strchr(p, '?');
3015 av_strlcpy(path, ls, path_size);
3017 ls = &p[strlen(p)]; // XXX
3019 /* the rest is hostname, use that to parse auth/port */
3021 /* authorization (user[:pass]@hostname) */
3022 if ((at = strchr(p, '@')) && at < ls) {
3023 av_strlcpy(authorization, p,
3024 FFMIN(authorization_size, at + 1 - p));
3025 p = at + 1; /* skip '@' */
3028 if (*p == '[' && (brk = strchr(p, ']')) && brk < ls) {
3030 av_strlcpy(hostname, p + 1,
3031 FFMIN(hostname_size, brk - p));
3032 if (brk[1] == ':' && port_ptr)
3033 *port_ptr = atoi(brk + 2);
3034 } else if ((col = strchr(p, ':')) && col < ls) {
3035 av_strlcpy(hostname, p,
3036 FFMIN(col + 1 - p, hostname_size));
3037 if (port_ptr) *port_ptr = atoi(col + 1);
3039 av_strlcpy(hostname, p,
3040 FFMIN(ls + 1 - p, hostname_size));
3044 char *ff_data_to_hex(char *buff, const uint8_t *src, int s, int lowercase)
3047 static const char hex_table_uc[16] = { '0', '1', '2', '3',
3050 'C', 'D', 'E', 'F' };
3051 static const char hex_table_lc[16] = { '0', '1', '2', '3',
3054 'c', 'd', 'e', 'f' };
3055 const char *hex_table = lowercase ? hex_table_lc : hex_table_uc;
3057 for(i = 0; i < s; i++) {
3058 buff[i * 2] = hex_table[src[i] >> 4];
3059 buff[i * 2 + 1] = hex_table[src[i] & 0xF];
3065 int ff_hex_to_data(uint8_t *data, const char *p)
3072 p += strspn(p, SPACE_CHARS);
3075 c = av_toupper((unsigned char) *p++);
3076 if (c >= '0' && c <= '9')
3078 else if (c >= 'A' && c <= 'F')
3093 void avpriv_set_pts_info(AVStream *s, int pts_wrap_bits,
3094 unsigned int pts_num, unsigned int pts_den)
3097 if(av_reduce(&new_tb.num, &new_tb.den, pts_num, pts_den, INT_MAX)){
3098 if(new_tb.num != pts_num)
3099 av_log(NULL, AV_LOG_DEBUG, "st:%d removing common factor %d from timebase\n", s->index, pts_num/new_tb.num);
3101 av_log(NULL, AV_LOG_WARNING, "st:%d has too large timebase, reducing\n", s->index);
3103 if(new_tb.num <= 0 || new_tb.den <= 0) {
3104 av_log(NULL, AV_LOG_ERROR, "Ignoring attempt to set invalid timebase for st:%d\n", s->index);
3107 s->time_base = new_tb;
3108 s->pts_wrap_bits = pts_wrap_bits;
3111 void ff_parse_key_value(const char *str, ff_parse_key_val_cb callback_get_buf,
3114 const char *ptr = str;
3116 /* Parse key=value pairs. */
3119 char *dest = NULL, *dest_end;
3120 int key_len, dest_len = 0;
3122 /* Skip whitespace and potential commas. */
3123 while (*ptr && (av_isspace(*ptr) || *ptr == ','))
3130 if (!(ptr = strchr(key, '=')))
3133 key_len = ptr - key;
3135 callback_get_buf(context, key, key_len, &dest, &dest_len);
3136 dest_end = dest + dest_len - 1;
3140 while (*ptr && *ptr != '\"') {
3144 if (dest && dest < dest_end)
3148 if (dest && dest < dest_end)
3156 for (; *ptr && !(av_isspace(*ptr) || *ptr == ','); ptr++)
3157 if (dest && dest < dest_end)
3165 int ff_find_stream_index(AVFormatContext *s, int id)
3168 for (i = 0; i < s->nb_streams; i++) {
3169 if (s->streams[i]->id == id)
3175 int64_t ff_iso8601_to_unix_time(const char *datestr)
3178 struct tm time1 = {0}, time2 = {0};
3180 ret1 = strptime(datestr, "%Y - %m - %d %T", &time1);
3181 ret2 = strptime(datestr, "%Y - %m - %dT%T", &time2);
3183 return av_timegm(&time2);
3185 return av_timegm(&time1);
3187 av_log(NULL, AV_LOG_WARNING, "strptime() unavailable on this system, cannot convert "
3188 "the date string.\n");
3193 int avformat_query_codec(AVOutputFormat *ofmt, enum AVCodecID codec_id, int std_compliance)
3196 if (ofmt->query_codec)
3197 return ofmt->query_codec(codec_id, std_compliance);
3198 else if (ofmt->codec_tag)
3199 return !!av_codec_get_tag(ofmt->codec_tag, codec_id);
3200 else if (codec_id == ofmt->video_codec || codec_id == ofmt->audio_codec ||
3201 codec_id == ofmt->subtitle_codec)
3204 return AVERROR_PATCHWELCOME;
3207 int avformat_network_init(void)
3211 ff_network_inited_globally = 1;
3212 if ((ret = ff_network_init()) < 0)
3219 int avformat_network_deinit(void)
3228 int ff_add_param_change(AVPacket *pkt, int32_t channels,
3229 uint64_t channel_layout, int32_t sample_rate,
3230 int32_t width, int32_t height)
3236 return AVERROR(EINVAL);
3239 flags |= AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_COUNT;
3241 if (channel_layout) {
3243 flags |= AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_LAYOUT;
3247 flags |= AV_SIDE_DATA_PARAM_CHANGE_SAMPLE_RATE;
3249 if (width || height) {
3251 flags |= AV_SIDE_DATA_PARAM_CHANGE_DIMENSIONS;
3253 data = av_packet_new_side_data(pkt, AV_PKT_DATA_PARAM_CHANGE, size);
3255 return AVERROR(ENOMEM);
3256 bytestream_put_le32(&data, flags);
3258 bytestream_put_le32(&data, channels);
3260 bytestream_put_le64(&data, channel_layout);
3262 bytestream_put_le32(&data, sample_rate);
3263 if (width || height) {
3264 bytestream_put_le32(&data, width);
3265 bytestream_put_le32(&data, height);
3270 int ff_generate_avci_extradata(AVStream *st)
3272 static const uint8_t avci100_1080p_extradata[] = {
3274 0x00, 0x00, 0x00, 0x01, 0x67, 0x7a, 0x10, 0x29,
3275 0xb6, 0xd4, 0x20, 0x22, 0x33, 0x19, 0xc6, 0x63,
3276 0x23, 0x21, 0x01, 0x11, 0x98, 0xce, 0x33, 0x19,
3277 0x18, 0x21, 0x02, 0x56, 0xb9, 0x3d, 0x7d, 0x7e,
3278 0x4f, 0xe3, 0x3f, 0x11, 0xf1, 0x9e, 0x08, 0xb8,
3279 0x8c, 0x54, 0x43, 0xc0, 0x78, 0x02, 0x27, 0xe2,
3280 0x70, 0x1e, 0x30, 0x10, 0x10, 0x14, 0x00, 0x00,
3281 0x03, 0x00, 0x04, 0x00, 0x00, 0x03, 0x00, 0xca,
3282 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
3284 0x00, 0x00, 0x00, 0x01, 0x68, 0xce, 0x33, 0x48,
3287 static const uint8_t avci100_1080i_extradata[] = {
3289 0x00, 0x00, 0x00, 0x01, 0x67, 0x7a, 0x10, 0x29,
3290 0xb6, 0xd4, 0x20, 0x22, 0x33, 0x19, 0xc6, 0x63,
3291 0x23, 0x21, 0x01, 0x11, 0x98, 0xce, 0x33, 0x19,
3292 0x18, 0x21, 0x03, 0x3a, 0x46, 0x65, 0x6a, 0x65,
3293 0x24, 0xad, 0xe9, 0x12, 0x32, 0x14, 0x1a, 0x26,
3294 0x34, 0xad, 0xa4, 0x41, 0x82, 0x23, 0x01, 0x50,
3295 0x2b, 0x1a, 0x24, 0x69, 0x48, 0x30, 0x40, 0x2e,
3296 0x11, 0x12, 0x08, 0xc6, 0x8c, 0x04, 0x41, 0x28,
3297 0x4c, 0x34, 0xf0, 0x1e, 0x01, 0x13, 0xf2, 0xe0,
3298 0x3c, 0x60, 0x20, 0x20, 0x28, 0x00, 0x00, 0x03,
3299 0x00, 0x08, 0x00, 0x00, 0x03, 0x01, 0x94, 0x00,
3301 0x00, 0x00, 0x00, 0x01, 0x68, 0xce, 0x33, 0x48,
3304 static const uint8_t avci50_1080i_extradata[] = {
3306 0x00, 0x00, 0x00, 0x01, 0x67, 0x6e, 0x10, 0x28,
3307 0xa6, 0xd4, 0x20, 0x32, 0x33, 0x0c, 0x71, 0x18,
3308 0x88, 0x62, 0x10, 0x19, 0x19, 0x86, 0x38, 0x8c,
3309 0x44, 0x30, 0x21, 0x02, 0x56, 0x4e, 0x6e, 0x61,
3310 0x87, 0x3e, 0x73, 0x4d, 0x98, 0x0c, 0x03, 0x06,
3311 0x9c, 0x0b, 0x73, 0xe6, 0xc0, 0xb5, 0x18, 0x63,
3312 0x0d, 0x39, 0xe0, 0x5b, 0x02, 0xd4, 0xc6, 0x19,
3313 0x1a, 0x79, 0x8c, 0x32, 0x34, 0x24, 0xf0, 0x16,
3314 0x81, 0x13, 0xf7, 0xff, 0x80, 0x01, 0x80, 0x02,
3315 0x71, 0x80, 0x80, 0x80, 0xa0, 0x00, 0x00, 0x03,
3316 0x00, 0x20, 0x00, 0x00, 0x06, 0x50, 0x80, 0x00,
3318 0x00, 0x00, 0x00, 0x01, 0x68, 0xee, 0x31, 0x12,
3321 static const uint8_t avci100_720p_extradata[] = {
3323 0x00, 0x00, 0x00, 0x01, 0x67, 0x7a, 0x10, 0x29,
3324 0xb6, 0xd4, 0x20, 0x2a, 0x33, 0x1d, 0xc7, 0x62,
3325 0xa1, 0x08, 0x40, 0x54, 0x66, 0x3b, 0x8e, 0xc5,
3326 0x42, 0x02, 0x10, 0x25, 0x64, 0x2c, 0x89, 0xe8,
3327 0x85, 0xe4, 0x21, 0x4b, 0x90, 0x83, 0x06, 0x95,
3328 0xd1, 0x06, 0x46, 0x97, 0x20, 0xc8, 0xd7, 0x43,
3329 0x08, 0x11, 0xc2, 0x1e, 0x4c, 0x91, 0x0f, 0x01,
3330 0x40, 0x16, 0xec, 0x07, 0x8c, 0x04, 0x04, 0x05,
3331 0x00, 0x00, 0x03, 0x00, 0x01, 0x00, 0x00, 0x03,
3332 0x00, 0x64, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00,
3334 0x00, 0x00, 0x00, 0x01, 0x68, 0xce, 0x31, 0x12,
3338 const uint8_t *data = NULL;
3341 if (st->codec->width == 1920) {
3342 if (st->codec->field_order == AV_FIELD_PROGRESSIVE) {
3343 data = avci100_1080p_extradata;
3344 size = sizeof(avci100_1080p_extradata);
3346 data = avci100_1080i_extradata;
3347 size = sizeof(avci100_1080i_extradata);
3349 } else if (st->codec->width == 1440) {
3350 data = avci50_1080i_extradata;
3351 size = sizeof(avci50_1080i_extradata);
3352 } else if (st->codec->width == 1280) {
3353 data = avci100_720p_extradata;
3354 size = sizeof(avci100_720p_extradata);
3360 av_freep(&st->codec->extradata);
3361 st->codec->extradata_size = 0;
3362 st->codec->extradata = av_mallocz(size + FF_INPUT_BUFFER_PADDING_SIZE);
3363 if (!st->codec->extradata)
3364 return AVERROR(ENOMEM);
3366 memcpy(st->codec->extradata, data, size);
3367 st->codec->extradata_size = size;