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/pixdesc.h"
34 #include "libavutil/avassert.h"
35 #include "libavutil/avstring.h"
36 #include "libavutil/mathematics.h"
37 #include "libavutil/parseutils.h"
38 #include "libavutil/time.h"
40 #include "audiointerleave.h"
52 * various utility functions for use within Libav
55 unsigned avformat_version(void)
57 return LIBAVFORMAT_VERSION_INT;
60 const char *avformat_configuration(void)
62 return LIBAV_CONFIGURATION;
65 const char *avformat_license(void)
67 #define LICENSE_PREFIX "libavformat license: "
68 return LICENSE_PREFIX LIBAV_LICENSE + sizeof(LICENSE_PREFIX) - 1;
71 /** head of registered input format linked list */
72 static AVInputFormat *first_iformat = NULL;
73 /** head of registered output format linked list */
74 static AVOutputFormat *first_oformat = NULL;
76 AVInputFormat *av_iformat_next(AVInputFormat *f)
79 else return first_iformat;
82 AVOutputFormat *av_oformat_next(AVOutputFormat *f)
85 else return first_oformat;
88 void av_register_input_format(AVInputFormat *format)
92 while (*p != NULL) p = &(*p)->next;
97 void av_register_output_format(AVOutputFormat *format)
101 while (*p != NULL) p = &(*p)->next;
106 int av_match_ext(const char *filename, const char *extensions)
114 ext = strrchr(filename, '.');
120 while (*p != '\0' && *p != ',' && q-ext1<sizeof(ext1)-1)
123 if (!av_strcasecmp(ext1, ext))
133 static int match_format(const char *name, const char *names)
141 namelen = strlen(name);
142 while ((p = strchr(names, ','))) {
143 len = FFMAX(p - names, namelen);
144 if (!av_strncasecmp(name, names, len))
148 return !av_strcasecmp(name, names);
151 AVOutputFormat *av_guess_format(const char *short_name, const char *filename,
152 const char *mime_type)
154 AVOutputFormat *fmt = NULL, *fmt_found;
155 int score_max, score;
157 /* specific test for image sequences */
158 #if CONFIG_IMAGE2_MUXER
159 if (!short_name && filename &&
160 av_filename_number_test(filename) &&
161 ff_guess_image2_codec(filename) != AV_CODEC_ID_NONE) {
162 return av_guess_format("image2", NULL, NULL);
165 /* Find the proper file type. */
168 while ((fmt = av_oformat_next(fmt))) {
170 if (fmt->name && short_name && !av_strcasecmp(fmt->name, short_name))
172 if (fmt->mime_type && mime_type && !strcmp(fmt->mime_type, mime_type))
174 if (filename && fmt->extensions &&
175 av_match_ext(filename, fmt->extensions)) {
178 if (score > score_max) {
186 enum AVCodecID av_guess_codec(AVOutputFormat *fmt, const char *short_name,
187 const char *filename, const char *mime_type, enum AVMediaType type){
188 if(type == AVMEDIA_TYPE_VIDEO){
189 enum AVCodecID codec_id= AV_CODEC_ID_NONE;
191 #if CONFIG_IMAGE2_MUXER
192 if(!strcmp(fmt->name, "image2") || !strcmp(fmt->name, "image2pipe")){
193 codec_id= ff_guess_image2_codec(filename);
196 if(codec_id == AV_CODEC_ID_NONE)
197 codec_id= fmt->video_codec;
199 }else if(type == AVMEDIA_TYPE_AUDIO)
200 return fmt->audio_codec;
201 else if (type == AVMEDIA_TYPE_SUBTITLE)
202 return fmt->subtitle_codec;
204 return AV_CODEC_ID_NONE;
207 AVInputFormat *av_find_input_format(const char *short_name)
209 AVInputFormat *fmt = NULL;
210 while ((fmt = av_iformat_next(fmt))) {
211 if (match_format(short_name, fmt->name))
217 /* an arbitrarily chosen "sane" max packet size -- 50M */
218 #define SANE_CHUNK_SIZE (50000000)
221 * Read the data in sane-sized chunks and append to pkt.
222 * Return the number of bytes read or an error.
224 static int append_packet_chunked(AVIOContext *s, AVPacket *pkt, int size)
226 int64_t chunk_size = size;
227 int orig_pos = pkt->pos; // av_grow_packet might reset pos
228 int orig_size = pkt->size;
232 int prev_size = pkt->size;
236 * When the caller requests a lot of data, limit it to the amount left
237 * in file or SANE_CHUNK_SIZE when it is not known
239 if (size > SANE_CHUNK_SIZE) {
240 int64_t filesize = avio_size(s) - avio_tell(s);
241 chunk_size = FFMAX(filesize, SANE_CHUNK_SIZE);
243 read_size = FFMIN(size, chunk_size);
245 ret = av_grow_packet(pkt, read_size);
249 ret = avio_read(s, pkt->data + prev_size, read_size);
250 if (ret != read_size) {
251 av_shrink_packet(pkt, prev_size + FFMAX(ret, 0));
261 return pkt->size > orig_size ? pkt->size - orig_size : ret;
264 int av_get_packet(AVIOContext *s, AVPacket *pkt, int size)
269 pkt->pos = avio_tell(s);
271 return append_packet_chunked(s, pkt, size);
274 int av_append_packet(AVIOContext *s, AVPacket *pkt, int size)
277 return av_get_packet(s, pkt, size);
278 return append_packet_chunked(s, pkt, size);
282 int av_filename_number_test(const char *filename)
285 return filename && (av_get_frame_filename(buf, sizeof(buf), filename, 1)>=0);
288 AVInputFormat *av_probe_input_format2(AVProbeData *pd, int is_opened, int *score_max)
290 AVProbeData lpd = *pd;
291 AVInputFormat *fmt1 = NULL, *fmt;
294 if (lpd.buf_size > 10 && ff_id3v2_match(lpd.buf, ID3v2_DEFAULT_MAGIC)) {
295 int id3len = ff_id3v2_tag_len(lpd.buf);
296 if (lpd.buf_size > id3len + 16) {
298 lpd.buf_size -= id3len;
304 while ((fmt1 = av_iformat_next(fmt1))) {
305 if (!is_opened == !(fmt1->flags & AVFMT_NOFILE))
308 if (fmt1->read_probe) {
309 score = fmt1->read_probe(&lpd);
310 } else if (fmt1->extensions) {
311 if (av_match_ext(lpd.filename, fmt1->extensions)) {
315 if (score > *score_max) {
318 }else if (score == *score_max)
322 /* a hack for files with huge id3v2 tags -- try to guess by file extension. */
323 if (!fmt && is_opened && *score_max < AVPROBE_SCORE_MAX/4) {
324 while ((fmt = av_iformat_next(fmt)))
325 if (fmt->extensions && av_match_ext(lpd.filename, fmt->extensions)) {
326 *score_max = AVPROBE_SCORE_MAX/4;
331 if (!fmt && id3 && *score_max < AVPROBE_SCORE_MAX/4-1) {
332 while ((fmt = av_iformat_next(fmt)))
333 if (fmt->extensions && av_match_ext("mp3", fmt->extensions)) {
334 *score_max = AVPROBE_SCORE_MAX/4-1;
342 AVInputFormat *av_probe_input_format(AVProbeData *pd, int is_opened){
344 return av_probe_input_format2(pd, is_opened, &score);
347 static int set_codec_from_probe_data(AVFormatContext *s, AVStream *st, AVProbeData *pd, int score)
349 static const struct {
350 const char *name; enum AVCodecID id; enum AVMediaType type;
352 { "aac" , AV_CODEC_ID_AAC , AVMEDIA_TYPE_AUDIO },
353 { "ac3" , AV_CODEC_ID_AC3 , AVMEDIA_TYPE_AUDIO },
354 { "dts" , AV_CODEC_ID_DTS , AVMEDIA_TYPE_AUDIO },
355 { "eac3" , AV_CODEC_ID_EAC3 , AVMEDIA_TYPE_AUDIO },
356 { "h264" , AV_CODEC_ID_H264 , AVMEDIA_TYPE_VIDEO },
357 { "m4v" , AV_CODEC_ID_MPEG4 , AVMEDIA_TYPE_VIDEO },
358 { "mp3" , AV_CODEC_ID_MP3 , AVMEDIA_TYPE_AUDIO },
359 { "mpegvideo", AV_CODEC_ID_MPEG2VIDEO, AVMEDIA_TYPE_VIDEO },
362 AVInputFormat *fmt = av_probe_input_format2(pd, 1, &score);
366 av_log(s, AV_LOG_DEBUG, "Probe with size=%d, packets=%d detected %s with score=%d\n",
367 pd->buf_size, MAX_PROBE_PACKETS - st->probe_packets, fmt->name, score);
368 for (i = 0; fmt_id_type[i].name; i++) {
369 if (!strcmp(fmt->name, fmt_id_type[i].name)) {
370 st->codec->codec_id = fmt_id_type[i].id;
371 st->codec->codec_type = fmt_id_type[i].type;
379 /************************************************************/
380 /* input media file */
382 /** size of probe buffer, for guessing file type from file contents */
383 #define PROBE_BUF_MIN 2048
384 #define PROBE_BUF_MAX (1<<20)
386 int av_probe_input_buffer(AVIOContext *pb, AVInputFormat **fmt,
387 const char *filename, void *logctx,
388 unsigned int offset, unsigned int max_probe_size)
390 AVProbeData pd = { filename ? filename : "", NULL, -offset };
391 unsigned char *buf = NULL;
392 int ret = 0, probe_size;
394 if (!max_probe_size) {
395 max_probe_size = PROBE_BUF_MAX;
396 } else if (max_probe_size > PROBE_BUF_MAX) {
397 max_probe_size = PROBE_BUF_MAX;
398 } else if (max_probe_size < PROBE_BUF_MIN) {
399 return AVERROR(EINVAL);
402 if (offset >= max_probe_size) {
403 return AVERROR(EINVAL);
406 for(probe_size= PROBE_BUF_MIN; probe_size<=max_probe_size && !*fmt;
407 probe_size = FFMIN(probe_size<<1, FFMAX(max_probe_size, probe_size+1))) {
408 int score = probe_size < max_probe_size ? AVPROBE_SCORE_MAX/4 : 0;
409 int buf_offset = (probe_size == PROBE_BUF_MIN) ? 0 : probe_size>>1;
411 if (probe_size < offset) {
415 /* read probe data */
416 buf = av_realloc(buf, probe_size + AVPROBE_PADDING_SIZE);
417 if ((ret = avio_read(pb, buf + buf_offset, probe_size - buf_offset)) < 0) {
418 /* fail if error was not end of file, otherwise, lower score */
419 if (ret != AVERROR_EOF) {
424 ret = 0; /* error was end of file, nothing read */
427 pd.buf = &buf[offset];
429 memset(pd.buf + pd.buf_size, 0, AVPROBE_PADDING_SIZE);
431 /* guess file format */
432 *fmt = av_probe_input_format2(&pd, 1, &score);
434 if(score <= AVPROBE_SCORE_MAX/4){ //this can only be true in the last iteration
435 av_log(logctx, AV_LOG_WARNING, "Format detected only with low score of %d, misdetection possible!\n", score);
437 av_log(logctx, AV_LOG_DEBUG, "Probed with size=%d and score=%d\n", probe_size, score);
443 return AVERROR_INVALIDDATA;
446 /* rewind. reuse probe buffer to avoid seeking */
447 if ((ret = ffio_rewind_with_probe_data(pb, buf, pd.buf_size)) < 0)
453 /* open input file and probe the format if necessary */
454 static int init_input(AVFormatContext *s, const char *filename, AVDictionary **options)
457 AVProbeData pd = {filename, NULL, 0};
460 s->flags |= AVFMT_FLAG_CUSTOM_IO;
462 return av_probe_input_buffer(s->pb, &s->iformat, filename, s, 0, s->probesize);
463 else if (s->iformat->flags & AVFMT_NOFILE)
464 return AVERROR(EINVAL);
468 if ( (s->iformat && s->iformat->flags & AVFMT_NOFILE) ||
469 (!s->iformat && (s->iformat = av_probe_input_format(&pd, 0))))
472 if ((ret = avio_open2(&s->pb, filename, AVIO_FLAG_READ,
473 &s->interrupt_callback, options)) < 0)
477 return av_probe_input_buffer(s->pb, &s->iformat, filename, s, 0, s->probesize);
480 static AVPacket *add_to_pktbuf(AVPacketList **packet_buffer, AVPacket *pkt,
481 AVPacketList **plast_pktl){
482 AVPacketList *pktl = av_mallocz(sizeof(AVPacketList));
487 (*plast_pktl)->next = pktl;
489 *packet_buffer = pktl;
491 /* add the packet in the buffered packet list */
497 static int queue_attached_pictures(AVFormatContext *s)
500 for (i = 0; i < s->nb_streams; i++)
501 if (s->streams[i]->disposition & AV_DISPOSITION_ATTACHED_PIC &&
502 s->streams[i]->discard < AVDISCARD_ALL) {
503 AVPacket copy = s->streams[i]->attached_pic;
504 copy.buf = av_buffer_ref(copy.buf);
506 return AVERROR(ENOMEM);
508 add_to_pktbuf(&s->raw_packet_buffer, ©, &s->raw_packet_buffer_end);
513 int avformat_open_input(AVFormatContext **ps, const char *filename, AVInputFormat *fmt, AVDictionary **options)
515 AVFormatContext *s = *ps;
517 AVDictionary *tmp = NULL;
518 ID3v2ExtraMeta *id3v2_extra_meta = NULL;
520 if (!s && !(s = avformat_alloc_context()))
521 return AVERROR(ENOMEM);
526 av_dict_copy(&tmp, *options, 0);
528 if ((ret = av_opt_set_dict(s, &tmp)) < 0)
531 if ((ret = init_input(s, filename, &tmp)) < 0)
534 /* check filename in case an image number is expected */
535 if (s->iformat->flags & AVFMT_NEEDNUMBER) {
536 if (!av_filename_number_test(filename)) {
537 ret = AVERROR(EINVAL);
542 s->duration = s->start_time = AV_NOPTS_VALUE;
543 av_strlcpy(s->filename, filename ? filename : "", sizeof(s->filename));
545 /* allocate private data */
546 if (s->iformat->priv_data_size > 0) {
547 if (!(s->priv_data = av_mallocz(s->iformat->priv_data_size))) {
548 ret = AVERROR(ENOMEM);
551 if (s->iformat->priv_class) {
552 *(const AVClass**)s->priv_data = s->iformat->priv_class;
553 av_opt_set_defaults(s->priv_data);
554 if ((ret = av_opt_set_dict(s->priv_data, &tmp)) < 0)
559 /* e.g. AVFMT_NOFILE formats will not have a AVIOContext */
561 ff_id3v2_read(s, ID3v2_DEFAULT_MAGIC, &id3v2_extra_meta);
563 if (s->iformat->read_header)
564 if ((ret = s->iformat->read_header(s)) < 0)
567 if (id3v2_extra_meta &&
568 (ret = ff_id3v2_parse_apic(s, &id3v2_extra_meta)) < 0)
570 ff_id3v2_free_extra_meta(&id3v2_extra_meta);
572 if ((ret = queue_attached_pictures(s)) < 0)
575 if (s->pb && !s->data_offset)
576 s->data_offset = avio_tell(s->pb);
578 s->raw_packet_buffer_remaining_size = RAW_PACKET_BUFFER_SIZE;
581 av_dict_free(options);
588 ff_id3v2_free_extra_meta(&id3v2_extra_meta);
590 if (s->pb && !(s->flags & AVFMT_FLAG_CUSTOM_IO))
592 avformat_free_context(s);
597 /*******************************************************/
599 static void probe_codec(AVFormatContext *s, AVStream *st, const AVPacket *pkt)
601 if(st->codec->codec_id == AV_CODEC_ID_PROBE){
602 AVProbeData *pd = &st->probe_data;
603 av_log(s, AV_LOG_DEBUG, "probing stream %d\n", st->index);
607 pd->buf = av_realloc(pd->buf, pd->buf_size+pkt->size+AVPROBE_PADDING_SIZE);
608 memcpy(pd->buf+pd->buf_size, pkt->data, pkt->size);
609 pd->buf_size += pkt->size;
610 memset(pd->buf+pd->buf_size, 0, AVPROBE_PADDING_SIZE);
612 st->probe_packets = 0;
614 av_log(s, AV_LOG_ERROR, "nothing to probe for stream %d\n",
620 if (!st->probe_packets ||
621 av_log2(pd->buf_size) != av_log2(pd->buf_size - pkt->size)) {
622 set_codec_from_probe_data(s, st, pd, st->probe_packets > 0 ? AVPROBE_SCORE_MAX/4 : 0);
623 if(st->codec->codec_id != AV_CODEC_ID_PROBE){
626 av_log(s, AV_LOG_DEBUG, "probed stream %d\n", st->index);
632 int ff_read_packet(AVFormatContext *s, AVPacket *pkt)
638 AVPacketList *pktl = s->raw_packet_buffer;
642 st = s->streams[pkt->stream_index];
643 if (st->codec->codec_id != AV_CODEC_ID_PROBE || !st->probe_packets ||
644 s->raw_packet_buffer_remaining_size < pkt->size) {
646 if (st->probe_packets) {
647 probe_codec(s, st, NULL);
649 pd = &st->probe_data;
652 s->raw_packet_buffer = pktl->next;
653 s->raw_packet_buffer_remaining_size += pkt->size;
662 ret= s->iformat->read_packet(s, pkt);
664 if (!pktl || ret == AVERROR(EAGAIN))
666 for (i = 0; i < s->nb_streams; i++) {
668 if (st->probe_packets) {
669 probe_codec(s, st, NULL);
675 if ((s->flags & AVFMT_FLAG_DISCARD_CORRUPT) &&
676 (pkt->flags & AV_PKT_FLAG_CORRUPT)) {
677 av_log(s, AV_LOG_WARNING,
678 "Dropped corrupted packet (stream = %d)\n",
684 st= s->streams[pkt->stream_index];
686 switch(st->codec->codec_type){
687 case AVMEDIA_TYPE_VIDEO:
688 if(s->video_codec_id) st->codec->codec_id= s->video_codec_id;
690 case AVMEDIA_TYPE_AUDIO:
691 if(s->audio_codec_id) st->codec->codec_id= s->audio_codec_id;
693 case AVMEDIA_TYPE_SUBTITLE:
694 if(s->subtitle_codec_id)st->codec->codec_id= s->subtitle_codec_id;
698 if(!pktl && (st->codec->codec_id != AV_CODEC_ID_PROBE ||
702 add_to_pktbuf(&s->raw_packet_buffer, pkt, &s->raw_packet_buffer_end);
703 s->raw_packet_buffer_remaining_size -= pkt->size;
705 probe_codec(s, st, pkt);
709 /**********************************************************/
712 * Get the number of samples of an audio frame. Return -1 on error.
714 int ff_get_audio_frame_size(AVCodecContext *enc, int size, int mux)
718 /* give frame_size priority if demuxing */
719 if (!mux && enc->frame_size > 1)
720 return enc->frame_size;
722 if ((frame_size = av_get_audio_frame_duration(enc, size)) > 0)
725 /* fallback to using frame_size if muxing */
726 if (enc->frame_size > 1)
727 return enc->frame_size;
734 * Return the frame duration in seconds. Return 0 if not available.
736 void ff_compute_frame_duration(int *pnum, int *pden, AVStream *st,
737 AVCodecParserContext *pc, AVPacket *pkt)
743 switch(st->codec->codec_type) {
744 case AVMEDIA_TYPE_VIDEO:
745 if (st->avg_frame_rate.num) {
746 *pnum = st->avg_frame_rate.den;
747 *pden = st->avg_frame_rate.num;
748 } else if(st->time_base.num*1000LL > st->time_base.den) {
749 *pnum = st->time_base.num;
750 *pden = st->time_base.den;
751 }else if(st->codec->time_base.num*1000LL > st->codec->time_base.den){
752 *pnum = st->codec->time_base.num;
753 *pden = st->codec->time_base.den;
754 if (pc && pc->repeat_pict) {
755 if (*pnum > INT_MAX / (1 + pc->repeat_pict))
756 *pden /= 1 + pc->repeat_pict;
758 *pnum *= 1 + pc->repeat_pict;
760 //If this codec can be interlaced or progressive then we need a parser to compute duration of a packet
761 //Thus if we have no parser in such case leave duration undefined.
762 if(st->codec->ticks_per_frame>1 && !pc){
767 case AVMEDIA_TYPE_AUDIO:
768 frame_size = ff_get_audio_frame_size(st->codec, pkt->size, 0);
769 if (frame_size <= 0 || st->codec->sample_rate <= 0)
772 *pden = st->codec->sample_rate;
779 static int is_intra_only(enum AVCodecID id)
781 const AVCodecDescriptor *d = avcodec_descriptor_get(id);
784 if (d->type == AVMEDIA_TYPE_VIDEO && !(d->props & AV_CODEC_PROP_INTRA_ONLY))
789 static void update_initial_timestamps(AVFormatContext *s, int stream_index,
790 int64_t dts, int64_t pts)
792 AVStream *st= s->streams[stream_index];
793 AVPacketList *pktl= s->packet_buffer;
795 if(st->first_dts != AV_NOPTS_VALUE || dts == AV_NOPTS_VALUE || st->cur_dts == AV_NOPTS_VALUE)
798 st->first_dts= dts - st->cur_dts;
801 for(; pktl; pktl= pktl->next){
802 if(pktl->pkt.stream_index != stream_index)
804 //FIXME think more about this check
805 if(pktl->pkt.pts != AV_NOPTS_VALUE && pktl->pkt.pts == pktl->pkt.dts)
806 pktl->pkt.pts += st->first_dts;
808 if(pktl->pkt.dts != AV_NOPTS_VALUE)
809 pktl->pkt.dts += st->first_dts;
811 if(st->start_time == AV_NOPTS_VALUE && pktl->pkt.pts != AV_NOPTS_VALUE)
812 st->start_time= pktl->pkt.pts;
814 if (st->start_time == AV_NOPTS_VALUE)
815 st->start_time = pts;
818 static void update_initial_durations(AVFormatContext *s, AVStream *st,
819 int stream_index, int duration)
821 AVPacketList *pktl= s->packet_buffer;
824 if(st->first_dts != AV_NOPTS_VALUE){
825 cur_dts= st->first_dts;
826 for(; pktl; pktl= pktl->next){
827 if(pktl->pkt.stream_index == stream_index){
828 if(pktl->pkt.pts != pktl->pkt.dts || pktl->pkt.dts != AV_NOPTS_VALUE || pktl->pkt.duration)
833 pktl= s->packet_buffer;
834 st->first_dts = cur_dts;
835 }else if(st->cur_dts)
838 for(; pktl; pktl= pktl->next){
839 if(pktl->pkt.stream_index != stream_index)
841 if(pktl->pkt.pts == pktl->pkt.dts && pktl->pkt.dts == AV_NOPTS_VALUE
842 && !pktl->pkt.duration){
843 pktl->pkt.dts= cur_dts;
844 if(!st->codec->has_b_frames)
845 pktl->pkt.pts= cur_dts;
847 if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO)
848 pktl->pkt.duration = duration;
852 if(st->first_dts == AV_NOPTS_VALUE)
853 st->cur_dts= cur_dts;
856 static void compute_pkt_fields(AVFormatContext *s, AVStream *st,
857 AVCodecParserContext *pc, AVPacket *pkt)
859 int num, den, presentation_delayed, delay, i;
862 if (s->flags & AVFMT_FLAG_NOFILLIN)
865 if((s->flags & AVFMT_FLAG_IGNDTS) && pkt->pts != AV_NOPTS_VALUE)
866 pkt->dts= AV_NOPTS_VALUE;
868 /* do we have a video B-frame ? */
869 delay= st->codec->has_b_frames;
870 presentation_delayed = 0;
872 /* XXX: need has_b_frame, but cannot get it if the codec is
875 pc && pc->pict_type != AV_PICTURE_TYPE_B)
876 presentation_delayed = 1;
878 if(pkt->pts != AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE && pkt->dts > pkt->pts && st->pts_wrap_bits<63
879 /*&& pkt->dts-(1LL<<st->pts_wrap_bits) < pkt->pts*/){
880 pkt->dts -= 1LL<<st->pts_wrap_bits;
883 // some mpeg2 in mpeg-ps lack dts (issue171 / input_file.mpg)
884 // we take the conservative approach and discard both
885 // Note, if this is misbehaving for a H.264 file then possibly presentation_delayed is not set correctly.
886 if(delay==1 && pkt->dts == pkt->pts && pkt->dts != AV_NOPTS_VALUE && presentation_delayed){
887 av_log(s, AV_LOG_DEBUG, "invalid dts/pts combination\n");
888 pkt->dts= pkt->pts= AV_NOPTS_VALUE;
891 if (pkt->duration == 0 && st->codec->codec_type != AVMEDIA_TYPE_AUDIO) {
892 ff_compute_frame_duration(&num, &den, st, pc, pkt);
894 pkt->duration = av_rescale_rnd(1, num * (int64_t)st->time_base.den, den * (int64_t)st->time_base.num, AV_ROUND_DOWN);
896 if(pkt->duration != 0 && s->packet_buffer)
897 update_initial_durations(s, st, pkt->stream_index, pkt->duration);
901 /* correct timestamps with byte offset if demuxers only have timestamps
902 on packet boundaries */
903 if(pc && st->need_parsing == AVSTREAM_PARSE_TIMESTAMPS && pkt->size){
904 /* this will estimate bitrate based on this frame's duration and size */
905 offset = av_rescale(pc->offset, pkt->duration, pkt->size);
906 if(pkt->pts != AV_NOPTS_VALUE)
908 if(pkt->dts != AV_NOPTS_VALUE)
912 if (pc && pc->dts_sync_point >= 0) {
913 // we have synchronization info from the parser
914 int64_t den = st->codec->time_base.den * (int64_t) st->time_base.num;
916 int64_t num = st->codec->time_base.num * (int64_t) st->time_base.den;
917 if (pkt->dts != AV_NOPTS_VALUE) {
918 // got DTS from the stream, update reference timestamp
919 st->reference_dts = pkt->dts - pc->dts_ref_dts_delta * num / den;
920 pkt->pts = pkt->dts + pc->pts_dts_delta * num / den;
921 } else if (st->reference_dts != AV_NOPTS_VALUE) {
922 // compute DTS based on reference timestamp
923 pkt->dts = st->reference_dts + pc->dts_ref_dts_delta * num / den;
924 pkt->pts = pkt->dts + pc->pts_dts_delta * num / den;
926 if (pc->dts_sync_point > 0)
927 st->reference_dts = pkt->dts; // new reference
931 /* This may be redundant, but it should not hurt. */
932 if(pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE && pkt->pts > pkt->dts)
933 presentation_delayed = 1;
936 "IN delayed:%d pts:%"PRId64", dts:%"PRId64" cur_dts:%"PRId64" st:%d pc:%p\n",
937 presentation_delayed, pkt->pts, pkt->dts, st->cur_dts,
938 pkt->stream_index, pc);
939 /* interpolate PTS and DTS if they are not present */
940 //We skip H264 currently because delay and has_b_frames are not reliably set
941 if((delay==0 || (delay==1 && pc)) && st->codec->codec_id != AV_CODEC_ID_H264){
942 if (presentation_delayed) {
943 /* DTS = decompression timestamp */
944 /* PTS = presentation timestamp */
945 if (pkt->dts == AV_NOPTS_VALUE)
946 pkt->dts = st->last_IP_pts;
947 update_initial_timestamps(s, pkt->stream_index, pkt->dts, pkt->pts);
948 if (pkt->dts == AV_NOPTS_VALUE)
949 pkt->dts = st->cur_dts;
951 /* this is tricky: the dts must be incremented by the duration
952 of the frame we are displaying, i.e. the last I- or P-frame */
953 if (st->last_IP_duration == 0)
954 st->last_IP_duration = pkt->duration;
955 if(pkt->dts != AV_NOPTS_VALUE)
956 st->cur_dts = pkt->dts + st->last_IP_duration;
957 st->last_IP_duration = pkt->duration;
958 st->last_IP_pts= pkt->pts;
959 /* cannot compute PTS if not present (we can compute it only
960 by knowing the future */
961 } else if (pkt->pts != AV_NOPTS_VALUE ||
962 pkt->dts != AV_NOPTS_VALUE ||
964 st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
965 int duration = pkt->duration;
966 if (!duration && st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
967 ff_compute_frame_duration(&num, &den, st, pc, pkt);
969 duration = av_rescale_rnd(1, num * (int64_t)st->time_base.den,
970 den * (int64_t)st->time_base.num,
972 if (duration != 0 && s->packet_buffer) {
973 update_initial_durations(s, st, pkt->stream_index,
979 if (pkt->pts != AV_NOPTS_VALUE || pkt->dts != AV_NOPTS_VALUE ||
981 /* presentation is not delayed : PTS and DTS are the same */
982 if (pkt->pts == AV_NOPTS_VALUE)
984 update_initial_timestamps(s, pkt->stream_index, pkt->pts,
986 if (pkt->pts == AV_NOPTS_VALUE)
987 pkt->pts = st->cur_dts;
989 if (pkt->pts != AV_NOPTS_VALUE)
990 st->cur_dts = pkt->pts + duration;
995 if(pkt->pts != AV_NOPTS_VALUE && delay <= MAX_REORDER_DELAY){
996 st->pts_buffer[0]= pkt->pts;
997 for(i=0; i<delay && st->pts_buffer[i] > st->pts_buffer[i+1]; i++)
998 FFSWAP(int64_t, st->pts_buffer[i], st->pts_buffer[i+1]);
999 if(pkt->dts == AV_NOPTS_VALUE)
1000 pkt->dts= st->pts_buffer[0];
1001 if(st->codec->codec_id == AV_CODEC_ID_H264){ // we skipped it above so we try here
1002 update_initial_timestamps(s, pkt->stream_index, pkt->dts, pkt->pts); // this should happen on the first packet
1004 if(pkt->dts > st->cur_dts)
1005 st->cur_dts = pkt->dts;
1009 "OUTdelayed:%d/%d pts:%"PRId64", dts:%"PRId64" cur_dts:%"PRId64"\n",
1010 presentation_delayed, delay, pkt->pts, pkt->dts, st->cur_dts);
1013 if (is_intra_only(st->codec->codec_id))
1014 pkt->flags |= AV_PKT_FLAG_KEY;
1016 pkt->convergence_duration = pc->convergence_duration;
1019 static void free_packet_buffer(AVPacketList **pkt_buf, AVPacketList **pkt_buf_end)
1022 AVPacketList *pktl = *pkt_buf;
1023 *pkt_buf = pktl->next;
1024 av_free_packet(&pktl->pkt);
1027 *pkt_buf_end = NULL;
1031 * Parse a packet, add all split parts to parse_queue
1033 * @param pkt packet to parse, NULL when flushing the parser at end of stream
1035 static int parse_packet(AVFormatContext *s, AVPacket *pkt, int stream_index)
1037 AVPacket out_pkt = { 0 }, flush_pkt = { 0 };
1038 AVStream *st = s->streams[stream_index];
1039 uint8_t *data = pkt ? pkt->data : NULL;
1040 int size = pkt ? pkt->size : 0;
1041 int ret = 0, got_output = 0;
1044 av_init_packet(&flush_pkt);
1049 while (size > 0 || (pkt == &flush_pkt && got_output)) {
1052 av_init_packet(&out_pkt);
1053 len = av_parser_parse2(st->parser, st->codec,
1054 &out_pkt.data, &out_pkt.size, data, size,
1055 pkt->pts, pkt->dts, pkt->pos);
1057 pkt->pts = pkt->dts = AV_NOPTS_VALUE;
1058 /* increment read pointer */
1062 got_output = !!out_pkt.size;
1067 /* set the duration */
1068 out_pkt.duration = 0;
1069 if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
1070 if (st->codec->sample_rate > 0) {
1071 out_pkt.duration = av_rescale_q_rnd(st->parser->duration,
1072 (AVRational){ 1, st->codec->sample_rate },
1076 } else if (st->codec->time_base.num != 0 &&
1077 st->codec->time_base.den != 0) {
1078 out_pkt.duration = av_rescale_q_rnd(st->parser->duration,
1079 st->codec->time_base,
1084 out_pkt.stream_index = st->index;
1085 out_pkt.pts = st->parser->pts;
1086 out_pkt.dts = st->parser->dts;
1087 out_pkt.pos = st->parser->pos;
1089 if (st->parser->key_frame == 1 ||
1090 (st->parser->key_frame == -1 &&
1091 st->parser->pict_type == AV_PICTURE_TYPE_I))
1092 out_pkt.flags |= AV_PKT_FLAG_KEY;
1094 compute_pkt_fields(s, st, st->parser, &out_pkt);
1096 if ((s->iformat->flags & AVFMT_GENERIC_INDEX) &&
1097 out_pkt.flags & AV_PKT_FLAG_KEY) {
1098 ff_reduce_index(s, st->index);
1099 av_add_index_entry(st, st->parser->frame_offset, out_pkt.dts,
1100 0, 0, AVINDEX_KEYFRAME);
1103 if (out_pkt.data == pkt->data && out_pkt.size == pkt->size) {
1104 out_pkt.buf = pkt->buf;
1106 #if FF_API_DESTRUCT_PACKET
1107 out_pkt.destruct = pkt->destruct;
1108 pkt->destruct = NULL;
1111 if ((ret = av_dup_packet(&out_pkt)) < 0)
1114 if (!add_to_pktbuf(&s->parse_queue, &out_pkt, &s->parse_queue_end)) {
1115 av_free_packet(&out_pkt);
1116 ret = AVERROR(ENOMEM);
1122 /* end of the stream => close and free the parser */
1123 if (pkt == &flush_pkt) {
1124 av_parser_close(st->parser);
1129 av_free_packet(pkt);
1133 static int read_from_packet_buffer(AVPacketList **pkt_buffer,
1134 AVPacketList **pkt_buffer_end,
1138 av_assert0(*pkt_buffer);
1141 *pkt_buffer = pktl->next;
1143 *pkt_buffer_end = NULL;
1148 static int read_frame_internal(AVFormatContext *s, AVPacket *pkt)
1150 int ret = 0, i, got_packet = 0;
1152 av_init_packet(pkt);
1154 while (!got_packet && !s->parse_queue) {
1158 /* read next packet */
1159 ret = ff_read_packet(s, &cur_pkt);
1161 if (ret == AVERROR(EAGAIN))
1163 /* flush the parsers */
1164 for(i = 0; i < s->nb_streams; i++) {
1166 if (st->parser && st->need_parsing)
1167 parse_packet(s, NULL, st->index);
1169 /* all remaining packets are now in parse_queue =>
1170 * really terminate parsing */
1174 st = s->streams[cur_pkt.stream_index];
1176 if (cur_pkt.pts != AV_NOPTS_VALUE &&
1177 cur_pkt.dts != AV_NOPTS_VALUE &&
1178 cur_pkt.pts < cur_pkt.dts) {
1179 av_log(s, AV_LOG_WARNING, "Invalid timestamps stream=%d, pts=%"PRId64", dts=%"PRId64", size=%d\n",
1180 cur_pkt.stream_index,
1185 if (s->debug & FF_FDEBUG_TS)
1186 av_log(s, AV_LOG_DEBUG, "ff_read_packet stream=%d, pts=%"PRId64", dts=%"PRId64", size=%d, duration=%d, flags=%d\n",
1187 cur_pkt.stream_index,
1194 if (st->need_parsing && !st->parser && !(s->flags & AVFMT_FLAG_NOPARSE)) {
1195 st->parser = av_parser_init(st->codec->codec_id);
1197 /* no parser available: just output the raw packets */
1198 st->need_parsing = AVSTREAM_PARSE_NONE;
1199 } else if(st->need_parsing == AVSTREAM_PARSE_HEADERS) {
1200 st->parser->flags |= PARSER_FLAG_COMPLETE_FRAMES;
1201 } else if(st->need_parsing == AVSTREAM_PARSE_FULL_ONCE) {
1202 st->parser->flags |= PARSER_FLAG_ONCE;
1206 if (!st->need_parsing || !st->parser) {
1207 /* no parsing needed: we just output the packet as is */
1209 compute_pkt_fields(s, st, NULL, pkt);
1210 if ((s->iformat->flags & AVFMT_GENERIC_INDEX) &&
1211 (pkt->flags & AV_PKT_FLAG_KEY) && pkt->dts != AV_NOPTS_VALUE) {
1212 ff_reduce_index(s, st->index);
1213 av_add_index_entry(st, pkt->pos, pkt->dts, 0, 0, AVINDEX_KEYFRAME);
1216 } else if (st->discard < AVDISCARD_ALL) {
1217 if ((ret = parse_packet(s, &cur_pkt, cur_pkt.stream_index)) < 0)
1221 av_free_packet(&cur_pkt);
1225 if (!got_packet && s->parse_queue)
1226 ret = read_from_packet_buffer(&s->parse_queue, &s->parse_queue_end, pkt);
1228 if(s->debug & FF_FDEBUG_TS)
1229 av_log(s, AV_LOG_DEBUG, "read_frame_internal stream=%d, pts=%"PRId64", dts=%"PRId64", size=%d, duration=%d, flags=%d\n",
1240 int av_read_frame(AVFormatContext *s, AVPacket *pkt)
1242 const int genpts = s->flags & AVFMT_FLAG_GENPTS;
1246 return s->packet_buffer ? read_from_packet_buffer(&s->packet_buffer,
1247 &s->packet_buffer_end,
1249 read_frame_internal(s, pkt);
1253 AVPacketList *pktl = s->packet_buffer;
1256 AVPacket *next_pkt = &pktl->pkt;
1258 if (next_pkt->dts != AV_NOPTS_VALUE) {
1259 int wrap_bits = s->streams[next_pkt->stream_index]->pts_wrap_bits;
1260 while (pktl && next_pkt->pts == AV_NOPTS_VALUE) {
1261 if (pktl->pkt.stream_index == next_pkt->stream_index &&
1262 (av_compare_mod(next_pkt->dts, pktl->pkt.dts, 2LL << (wrap_bits - 1)) < 0) &&
1263 av_compare_mod(pktl->pkt.pts, pktl->pkt.dts, 2LL << (wrap_bits - 1))) { //not b frame
1264 next_pkt->pts = pktl->pkt.dts;
1268 pktl = s->packet_buffer;
1271 /* read packet from packet buffer, if there is data */
1272 if (!(next_pkt->pts == AV_NOPTS_VALUE &&
1273 next_pkt->dts != AV_NOPTS_VALUE && !eof))
1274 return read_from_packet_buffer(&s->packet_buffer,
1275 &s->packet_buffer_end, pkt);
1278 ret = read_frame_internal(s, pkt);
1280 if (pktl && ret != AVERROR(EAGAIN)) {
1287 if (av_dup_packet(add_to_pktbuf(&s->packet_buffer, pkt,
1288 &s->packet_buffer_end)) < 0)
1289 return AVERROR(ENOMEM);
1293 /* XXX: suppress the packet queue */
1294 static void flush_packet_queue(AVFormatContext *s)
1296 free_packet_buffer(&s->parse_queue, &s->parse_queue_end);
1297 free_packet_buffer(&s->packet_buffer, &s->packet_buffer_end);
1298 free_packet_buffer(&s->raw_packet_buffer, &s->raw_packet_buffer_end);
1300 s->raw_packet_buffer_remaining_size = RAW_PACKET_BUFFER_SIZE;
1303 /*******************************************************/
1306 int av_find_default_stream_index(AVFormatContext *s)
1308 int first_audio_index = -1;
1312 if (s->nb_streams <= 0)
1314 for(i = 0; i < s->nb_streams; i++) {
1316 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
1317 !(st->disposition & AV_DISPOSITION_ATTACHED_PIC)) {
1320 if (first_audio_index < 0 && st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
1321 first_audio_index = i;
1323 return first_audio_index >= 0 ? first_audio_index : 0;
1327 * Flush the frame reader.
1329 void ff_read_frame_flush(AVFormatContext *s)
1334 flush_packet_queue(s);
1336 /* for each stream, reset read state */
1337 for(i = 0; i < s->nb_streams; i++) {
1341 av_parser_close(st->parser);
1344 st->last_IP_pts = AV_NOPTS_VALUE;
1345 st->cur_dts = AV_NOPTS_VALUE; /* we set the current DTS to an unspecified origin */
1346 st->reference_dts = AV_NOPTS_VALUE;
1348 st->probe_packets = MAX_PROBE_PACKETS;
1350 for(j=0; j<MAX_REORDER_DELAY+1; j++)
1351 st->pts_buffer[j]= AV_NOPTS_VALUE;
1355 void ff_update_cur_dts(AVFormatContext *s, AVStream *ref_st, int64_t timestamp)
1359 for(i = 0; i < s->nb_streams; i++) {
1360 AVStream *st = s->streams[i];
1362 st->cur_dts = av_rescale(timestamp,
1363 st->time_base.den * (int64_t)ref_st->time_base.num,
1364 st->time_base.num * (int64_t)ref_st->time_base.den);
1368 void ff_reduce_index(AVFormatContext *s, int stream_index)
1370 AVStream *st= s->streams[stream_index];
1371 unsigned int max_entries= s->max_index_size / sizeof(AVIndexEntry);
1373 if((unsigned)st->nb_index_entries >= max_entries){
1375 for(i=0; 2*i<st->nb_index_entries; i++)
1376 st->index_entries[i]= st->index_entries[2*i];
1377 st->nb_index_entries= i;
1381 int ff_add_index_entry(AVIndexEntry **index_entries,
1382 int *nb_index_entries,
1383 unsigned int *index_entries_allocated_size,
1384 int64_t pos, int64_t timestamp, int size, int distance, int flags)
1386 AVIndexEntry *entries, *ie;
1389 if((unsigned)*nb_index_entries + 1 >= UINT_MAX / sizeof(AVIndexEntry))
1392 entries = av_fast_realloc(*index_entries,
1393 index_entries_allocated_size,
1394 (*nb_index_entries + 1) *
1395 sizeof(AVIndexEntry));
1399 *index_entries= entries;
1401 index= ff_index_search_timestamp(*index_entries, *nb_index_entries, timestamp, AVSEEK_FLAG_ANY);
1404 index= (*nb_index_entries)++;
1405 ie= &entries[index];
1406 assert(index==0 || ie[-1].timestamp < timestamp);
1408 ie= &entries[index];
1409 if(ie->timestamp != timestamp){
1410 if(ie->timestamp <= timestamp)
1412 memmove(entries + index + 1, entries + index, sizeof(AVIndexEntry)*(*nb_index_entries - index));
1413 (*nb_index_entries)++;
1414 }else if(ie->pos == pos && distance < ie->min_distance) //do not reduce the distance
1415 distance= ie->min_distance;
1419 ie->timestamp = timestamp;
1420 ie->min_distance= distance;
1427 int av_add_index_entry(AVStream *st,
1428 int64_t pos, int64_t timestamp, int size, int distance, int flags)
1430 return ff_add_index_entry(&st->index_entries, &st->nb_index_entries,
1431 &st->index_entries_allocated_size, pos,
1432 timestamp, size, distance, flags);
1435 int ff_index_search_timestamp(const AVIndexEntry *entries, int nb_entries,
1436 int64_t wanted_timestamp, int flags)
1444 //optimize appending index entries at the end
1445 if(b && entries[b-1].timestamp < wanted_timestamp)
1450 timestamp = entries[m].timestamp;
1451 if(timestamp >= wanted_timestamp)
1453 if(timestamp <= wanted_timestamp)
1456 m= (flags & AVSEEK_FLAG_BACKWARD) ? a : b;
1458 if(!(flags & AVSEEK_FLAG_ANY)){
1459 while(m>=0 && m<nb_entries && !(entries[m].flags & AVINDEX_KEYFRAME)){
1460 m += (flags & AVSEEK_FLAG_BACKWARD) ? -1 : 1;
1469 int av_index_search_timestamp(AVStream *st, int64_t wanted_timestamp,
1472 return ff_index_search_timestamp(st->index_entries, st->nb_index_entries,
1473 wanted_timestamp, flags);
1476 int ff_seek_frame_binary(AVFormatContext *s, int stream_index, int64_t target_ts, int flags)
1478 AVInputFormat *avif= s->iformat;
1479 int64_t av_uninit(pos_min), av_uninit(pos_max), pos, pos_limit;
1480 int64_t ts_min, ts_max, ts;
1485 if (stream_index < 0)
1488 av_dlog(s, "read_seek: %d %"PRId64"\n", stream_index, target_ts);
1491 ts_min= AV_NOPTS_VALUE;
1492 pos_limit= -1; //gcc falsely says it may be uninitialized
1494 st= s->streams[stream_index];
1495 if(st->index_entries){
1498 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()
1499 index= FFMAX(index, 0);
1500 e= &st->index_entries[index];
1502 if(e->timestamp <= target_ts || e->pos == e->min_distance){
1504 ts_min= e->timestamp;
1505 av_dlog(s, "using cached pos_min=0x%"PRIx64" dts_min=%"PRId64"\n",
1511 index= av_index_search_timestamp(st, target_ts, flags & ~AVSEEK_FLAG_BACKWARD);
1512 assert(index < st->nb_index_entries);
1514 e= &st->index_entries[index];
1515 assert(e->timestamp >= target_ts);
1517 ts_max= e->timestamp;
1518 pos_limit= pos_max - e->min_distance;
1519 av_dlog(s, "using cached pos_max=0x%"PRIx64" pos_limit=0x%"PRIx64" dts_max=%"PRId64"\n",
1520 pos_max,pos_limit, ts_max);
1524 pos= ff_gen_search(s, stream_index, target_ts, pos_min, pos_max, pos_limit, ts_min, ts_max, flags, &ts, avif->read_timestamp);
1529 if ((ret = avio_seek(s->pb, pos, SEEK_SET)) < 0)
1532 ff_update_cur_dts(s, st, ts);
1537 int64_t ff_gen_search(AVFormatContext *s, int stream_index, int64_t target_ts,
1538 int64_t pos_min, int64_t pos_max, int64_t pos_limit,
1539 int64_t ts_min, int64_t ts_max, int flags, int64_t *ts_ret,
1540 int64_t (*read_timestamp)(struct AVFormatContext *, int , int64_t *, int64_t ))
1543 int64_t start_pos, filesize;
1546 av_dlog(s, "gen_seek: %d %"PRId64"\n", stream_index, target_ts);
1548 if(ts_min == AV_NOPTS_VALUE){
1549 pos_min = s->data_offset;
1550 ts_min = read_timestamp(s, stream_index, &pos_min, INT64_MAX);
1551 if (ts_min == AV_NOPTS_VALUE)
1555 if(ts_max == AV_NOPTS_VALUE){
1557 filesize = avio_size(s->pb);
1558 pos_max = filesize - 1;
1561 ts_max = read_timestamp(s, stream_index, &pos_max, pos_max + step);
1563 }while(ts_max == AV_NOPTS_VALUE && pos_max >= step);
1564 if (ts_max == AV_NOPTS_VALUE)
1568 int64_t tmp_pos= pos_max + 1;
1569 int64_t tmp_ts= read_timestamp(s, stream_index, &tmp_pos, INT64_MAX);
1570 if(tmp_ts == AV_NOPTS_VALUE)
1574 if(tmp_pos >= filesize)
1580 if(ts_min > ts_max){
1582 }else if(ts_min == ts_max){
1587 while (pos_min < pos_limit) {
1588 av_dlog(s, "pos_min=0x%"PRIx64" pos_max=0x%"PRIx64" dts_min=%"PRId64" dts_max=%"PRId64"\n",
1589 pos_min, pos_max, ts_min, ts_max);
1590 assert(pos_limit <= pos_max);
1593 int64_t approximate_keyframe_distance= pos_max - pos_limit;
1594 // interpolate position (better than dichotomy)
1595 pos = av_rescale(target_ts - ts_min, pos_max - pos_min, ts_max - ts_min)
1596 + pos_min - approximate_keyframe_distance;
1597 }else if(no_change==1){
1598 // bisection, if interpolation failed to change min or max pos last time
1599 pos = (pos_min + pos_limit)>>1;
1601 /* linear search if bisection failed, can only happen if there
1602 are very few or no keyframes between min/max */
1607 else if(pos > pos_limit)
1611 ts = read_timestamp(s, stream_index, &pos, INT64_MAX); //may pass pos_limit instead of -1
1616 av_dlog(s, "%"PRId64" %"PRId64" %"PRId64" / %"PRId64" %"PRId64" %"PRId64" target:%"PRId64" limit:%"PRId64" start:%"PRId64" noc:%d\n",
1617 pos_min, pos, pos_max, ts_min, ts, ts_max, target_ts,
1618 pos_limit, start_pos, no_change);
1619 if(ts == AV_NOPTS_VALUE){
1620 av_log(s, AV_LOG_ERROR, "read_timestamp() failed in the middle\n");
1623 assert(ts != AV_NOPTS_VALUE);
1624 if (target_ts <= ts) {
1625 pos_limit = start_pos - 1;
1629 if (target_ts >= ts) {
1635 pos = (flags & AVSEEK_FLAG_BACKWARD) ? pos_min : pos_max;
1636 ts = (flags & AVSEEK_FLAG_BACKWARD) ? ts_min : ts_max;
1638 ts_min = read_timestamp(s, stream_index, &pos_min, INT64_MAX);
1640 ts_max = read_timestamp(s, stream_index, &pos_min, INT64_MAX);
1641 av_dlog(s, "pos=0x%"PRIx64" %"PRId64"<=%"PRId64"<=%"PRId64"\n",
1642 pos, ts_min, target_ts, ts_max);
1647 static int seek_frame_byte(AVFormatContext *s, int stream_index, int64_t pos, int flags){
1648 int64_t pos_min, pos_max;
1650 pos_min = s->data_offset;
1651 pos_max = avio_size(s->pb) - 1;
1653 if (pos < pos_min) pos= pos_min;
1654 else if(pos > pos_max) pos= pos_max;
1656 avio_seek(s->pb, pos, SEEK_SET);
1661 static int seek_frame_generic(AVFormatContext *s,
1662 int stream_index, int64_t timestamp, int flags)
1669 st = s->streams[stream_index];
1671 index = av_index_search_timestamp(st, timestamp, flags);
1673 if(index < 0 && st->nb_index_entries && timestamp < st->index_entries[0].timestamp)
1676 if(index < 0 || index==st->nb_index_entries-1){
1679 if(st->nb_index_entries){
1680 assert(st->index_entries);
1681 ie= &st->index_entries[st->nb_index_entries-1];
1682 if ((ret = avio_seek(s->pb, ie->pos, SEEK_SET)) < 0)
1684 ff_update_cur_dts(s, st, ie->timestamp);
1686 if ((ret = avio_seek(s->pb, s->data_offset, SEEK_SET)) < 0)
1692 read_status = av_read_frame(s, &pkt);
1693 } while (read_status == AVERROR(EAGAIN));
1694 if (read_status < 0)
1696 av_free_packet(&pkt);
1697 if(stream_index == pkt.stream_index){
1698 if((pkt.flags & AV_PKT_FLAG_KEY) && pkt.dts > timestamp)
1702 index = av_index_search_timestamp(st, timestamp, flags);
1707 ff_read_frame_flush(s);
1708 if (s->iformat->read_seek){
1709 if(s->iformat->read_seek(s, stream_index, timestamp, flags) >= 0)
1712 ie = &st->index_entries[index];
1713 if ((ret = avio_seek(s->pb, ie->pos, SEEK_SET)) < 0)
1715 ff_update_cur_dts(s, st, ie->timestamp);
1720 static int seek_frame_internal(AVFormatContext *s, int stream_index,
1721 int64_t timestamp, int flags)
1726 if (flags & AVSEEK_FLAG_BYTE) {
1727 if (s->iformat->flags & AVFMT_NO_BYTE_SEEK)
1729 ff_read_frame_flush(s);
1730 return seek_frame_byte(s, stream_index, timestamp, flags);
1733 if(stream_index < 0){
1734 stream_index= av_find_default_stream_index(s);
1735 if(stream_index < 0)
1738 st= s->streams[stream_index];
1739 /* timestamp for default must be expressed in AV_TIME_BASE units */
1740 timestamp = av_rescale(timestamp, st->time_base.den, AV_TIME_BASE * (int64_t)st->time_base.num);
1743 /* first, we try the format specific seek */
1744 if (s->iformat->read_seek) {
1745 ff_read_frame_flush(s);
1746 ret = s->iformat->read_seek(s, stream_index, timestamp, flags);
1753 if (s->iformat->read_timestamp && !(s->iformat->flags & AVFMT_NOBINSEARCH)) {
1754 ff_read_frame_flush(s);
1755 return ff_seek_frame_binary(s, stream_index, timestamp, flags);
1756 } else if (!(s->iformat->flags & AVFMT_NOGENSEARCH)) {
1757 ff_read_frame_flush(s);
1758 return seek_frame_generic(s, stream_index, timestamp, flags);
1764 int av_seek_frame(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
1766 int ret = seek_frame_internal(s, stream_index, timestamp, flags);
1769 ret = queue_attached_pictures(s);
1774 int avformat_seek_file(AVFormatContext *s, int stream_index, int64_t min_ts, int64_t ts, int64_t max_ts, int flags)
1776 if(min_ts > ts || max_ts < ts)
1779 if (s->iformat->read_seek2) {
1781 ff_read_frame_flush(s);
1782 ret = s->iformat->read_seek2(s, stream_index, min_ts, ts, max_ts, flags);
1785 ret = queue_attached_pictures(s);
1789 if(s->iformat->read_timestamp){
1790 //try to seek via read_timestamp()
1793 //Fallback to old API if new is not implemented but old is
1794 //Note the old has somewat different sematics
1795 if(s->iformat->read_seek || 1)
1796 return av_seek_frame(s, stream_index, ts, flags | ((uint64_t)ts - min_ts > (uint64_t)max_ts - ts ? AVSEEK_FLAG_BACKWARD : 0));
1798 // try some generic seek like seek_frame_generic() but with new ts semantics
1801 /*******************************************************/
1804 * Return TRUE if the stream has accurate duration in any stream.
1806 * @return TRUE if the stream has accurate duration for at least one component.
1808 static int has_duration(AVFormatContext *ic)
1813 for(i = 0;i < ic->nb_streams; i++) {
1814 st = ic->streams[i];
1815 if (st->duration != AV_NOPTS_VALUE)
1818 if (ic->duration != AV_NOPTS_VALUE)
1824 * Estimate the stream timings from the one of each components.
1826 * Also computes the global bitrate if possible.
1828 static void update_stream_timings(AVFormatContext *ic)
1830 int64_t start_time, start_time1, end_time, end_time1;
1831 int64_t duration, duration1, filesize;
1835 start_time = INT64_MAX;
1836 end_time = INT64_MIN;
1837 duration = INT64_MIN;
1838 for(i = 0;i < ic->nb_streams; i++) {
1839 st = ic->streams[i];
1840 if (st->start_time != AV_NOPTS_VALUE && st->time_base.den) {
1841 start_time1= av_rescale_q(st->start_time, st->time_base, AV_TIME_BASE_Q);
1842 start_time = FFMIN(start_time, start_time1);
1843 if (st->duration != AV_NOPTS_VALUE) {
1844 end_time1 = start_time1
1845 + av_rescale_q(st->duration, st->time_base, AV_TIME_BASE_Q);
1846 end_time = FFMAX(end_time, end_time1);
1849 if (st->duration != AV_NOPTS_VALUE) {
1850 duration1 = av_rescale_q(st->duration, st->time_base, AV_TIME_BASE_Q);
1851 duration = FFMAX(duration, duration1);
1854 if (start_time != INT64_MAX) {
1855 ic->start_time = start_time;
1856 if (end_time != INT64_MIN)
1857 duration = FFMAX(duration, end_time - start_time);
1859 if (duration != INT64_MIN) {
1860 ic->duration = duration;
1861 if (ic->pb && (filesize = avio_size(ic->pb)) > 0) {
1862 /* compute the bitrate */
1863 ic->bit_rate = (double)filesize * 8.0 * AV_TIME_BASE /
1864 (double)ic->duration;
1869 static void fill_all_stream_timings(AVFormatContext *ic)
1874 update_stream_timings(ic);
1875 for(i = 0;i < ic->nb_streams; i++) {
1876 st = ic->streams[i];
1877 if (st->start_time == AV_NOPTS_VALUE) {
1878 if(ic->start_time != AV_NOPTS_VALUE)
1879 st->start_time = av_rescale_q(ic->start_time, AV_TIME_BASE_Q, st->time_base);
1880 if(ic->duration != AV_NOPTS_VALUE)
1881 st->duration = av_rescale_q(ic->duration, AV_TIME_BASE_Q, st->time_base);
1886 static void estimate_timings_from_bit_rate(AVFormatContext *ic)
1888 int64_t filesize, duration;
1892 /* if bit_rate is already set, we believe it */
1893 if (ic->bit_rate <= 0) {
1895 for(i=0;i<ic->nb_streams;i++) {
1896 st = ic->streams[i];
1897 if (st->codec->bit_rate > 0)
1898 bit_rate += st->codec->bit_rate;
1900 ic->bit_rate = bit_rate;
1903 /* if duration is already set, we believe it */
1904 if (ic->duration == AV_NOPTS_VALUE &&
1905 ic->bit_rate != 0) {
1906 filesize = ic->pb ? avio_size(ic->pb) : 0;
1908 for(i = 0; i < ic->nb_streams; i++) {
1909 st = ic->streams[i];
1910 duration= av_rescale(8*filesize, st->time_base.den, ic->bit_rate*(int64_t)st->time_base.num);
1911 if (st->duration == AV_NOPTS_VALUE)
1912 st->duration = duration;
1918 #define DURATION_MAX_READ_SIZE 250000
1919 #define DURATION_MAX_RETRY 3
1921 /* only usable for MPEG-PS streams */
1922 static void estimate_timings_from_pts(AVFormatContext *ic, int64_t old_offset)
1924 AVPacket pkt1, *pkt = &pkt1;
1926 int read_size, i, ret;
1928 int64_t filesize, offset, duration;
1931 /* flush packet queue */
1932 flush_packet_queue(ic);
1934 for (i=0; i<ic->nb_streams; i++) {
1935 st = ic->streams[i];
1936 if (st->start_time == AV_NOPTS_VALUE && st->first_dts == AV_NOPTS_VALUE)
1937 av_log(st->codec, AV_LOG_WARNING, "start time is not set in estimate_timings_from_pts\n");
1940 av_parser_close(st->parser);
1945 /* estimate the end time (duration) */
1946 /* XXX: may need to support wrapping */
1947 filesize = ic->pb ? avio_size(ic->pb) : 0;
1948 end_time = AV_NOPTS_VALUE;
1950 offset = filesize - (DURATION_MAX_READ_SIZE<<retry);
1954 avio_seek(ic->pb, offset, SEEK_SET);
1957 if (read_size >= DURATION_MAX_READ_SIZE<<(FFMAX(retry-1,0)))
1961 ret = ff_read_packet(ic, pkt);
1962 } while(ret == AVERROR(EAGAIN));
1965 read_size += pkt->size;
1966 st = ic->streams[pkt->stream_index];
1967 if (pkt->pts != AV_NOPTS_VALUE &&
1968 (st->start_time != AV_NOPTS_VALUE ||
1969 st->first_dts != AV_NOPTS_VALUE)) {
1970 duration = end_time = pkt->pts;
1971 if (st->start_time != AV_NOPTS_VALUE)
1972 duration -= st->start_time;
1974 duration -= st->first_dts;
1976 duration += 1LL<<st->pts_wrap_bits;
1978 if (st->duration == AV_NOPTS_VALUE || st->duration < duration)
1979 st->duration = duration;
1982 av_free_packet(pkt);
1984 }while( end_time==AV_NOPTS_VALUE
1985 && filesize > (DURATION_MAX_READ_SIZE<<retry)
1986 && ++retry <= DURATION_MAX_RETRY);
1988 fill_all_stream_timings(ic);
1990 avio_seek(ic->pb, old_offset, SEEK_SET);
1991 for (i=0; i<ic->nb_streams; i++) {
1993 st->cur_dts= st->first_dts;
1994 st->last_IP_pts = AV_NOPTS_VALUE;
1995 st->reference_dts = AV_NOPTS_VALUE;
1999 static void estimate_timings(AVFormatContext *ic, int64_t old_offset)
2003 /* get the file size, if possible */
2004 if (ic->iformat->flags & AVFMT_NOFILE) {
2007 file_size = avio_size(ic->pb);
2008 file_size = FFMAX(0, file_size);
2011 if ((!strcmp(ic->iformat->name, "mpeg") ||
2012 !strcmp(ic->iformat->name, "mpegts")) &&
2013 file_size && ic->pb->seekable) {
2014 /* get accurate estimate from the PTSes */
2015 estimate_timings_from_pts(ic, old_offset);
2016 } else if (has_duration(ic)) {
2017 /* at least one component has timings - we use them for all
2019 fill_all_stream_timings(ic);
2021 av_log(ic, AV_LOG_WARNING, "Estimating duration from bitrate, this may be inaccurate\n");
2022 /* less precise: use bitrate info */
2023 estimate_timings_from_bit_rate(ic);
2025 update_stream_timings(ic);
2029 AVStream av_unused *st;
2030 for(i = 0;i < ic->nb_streams; i++) {
2031 st = ic->streams[i];
2032 av_dlog(ic, "%d: start_time: %0.3f duration: %0.3f\n", i,
2033 (double) st->start_time / AV_TIME_BASE,
2034 (double) st->duration / AV_TIME_BASE);
2036 av_dlog(ic, "stream: start_time: %0.3f duration: %0.3f bitrate=%d kb/s\n",
2037 (double) ic->start_time / AV_TIME_BASE,
2038 (double) ic->duration / AV_TIME_BASE,
2039 ic->bit_rate / 1000);
2043 static int has_codec_parameters(AVStream *st)
2045 AVCodecContext *avctx = st->codec;
2047 switch (avctx->codec_type) {
2048 case AVMEDIA_TYPE_AUDIO:
2049 val = avctx->sample_rate && avctx->channels;
2050 if (st->info->found_decoder >= 0 && avctx->sample_fmt == AV_SAMPLE_FMT_NONE)
2053 case AVMEDIA_TYPE_VIDEO:
2055 if (st->info->found_decoder >= 0 && avctx->pix_fmt == AV_PIX_FMT_NONE)
2062 return avctx->codec_id != AV_CODEC_ID_NONE && val != 0;
2065 static int has_decode_delay_been_guessed(AVStream *st)
2067 return st->codec->codec_id != AV_CODEC_ID_H264 ||
2068 st->info->nb_decoded_frames >= 6;
2071 /* returns 1 or 0 if or if not decoded data was returned, or a negative error */
2072 static int try_decode_frame(AVStream *st, AVPacket *avpkt, AVDictionary **options)
2074 const AVCodec *codec;
2075 int got_picture = 1, ret = 0;
2076 AVFrame *frame = avcodec_alloc_frame();
2077 AVPacket pkt = *avpkt;
2080 return AVERROR(ENOMEM);
2082 if (!avcodec_is_open(st->codec) && !st->info->found_decoder) {
2083 AVDictionary *thread_opt = NULL;
2085 codec = st->codec->codec ? st->codec->codec :
2086 avcodec_find_decoder(st->codec->codec_id);
2089 st->info->found_decoder = -1;
2094 /* force thread count to 1 since the h264 decoder will not extract SPS
2095 * and PPS to extradata during multi-threaded decoding */
2096 av_dict_set(options ? options : &thread_opt, "threads", "1", 0);
2097 ret = avcodec_open2(st->codec, codec, options ? options : &thread_opt);
2099 av_dict_free(&thread_opt);
2101 st->info->found_decoder = -1;
2104 st->info->found_decoder = 1;
2105 } else if (!st->info->found_decoder)
2106 st->info->found_decoder = 1;
2108 if (st->info->found_decoder < 0) {
2113 while ((pkt.size > 0 || (!pkt.data && got_picture)) &&
2115 (!has_codec_parameters(st) ||
2116 !has_decode_delay_been_guessed(st) ||
2117 (!st->codec_info_nb_frames && st->codec->codec->capabilities & CODEC_CAP_CHANNEL_CONF))) {
2119 avcodec_get_frame_defaults(frame);
2120 switch(st->codec->codec_type) {
2121 case AVMEDIA_TYPE_VIDEO:
2122 ret = avcodec_decode_video2(st->codec, frame,
2123 &got_picture, &pkt);
2125 case AVMEDIA_TYPE_AUDIO:
2126 ret = avcodec_decode_audio4(st->codec, frame, &got_picture, &pkt);
2133 st->info->nb_decoded_frames++;
2141 avcodec_free_frame(&frame);
2145 unsigned int ff_codec_get_tag(const AVCodecTag *tags, enum AVCodecID id)
2147 while (tags->id != AV_CODEC_ID_NONE) {
2155 enum AVCodecID ff_codec_get_id(const AVCodecTag *tags, unsigned int tag)
2158 for(i=0; tags[i].id != AV_CODEC_ID_NONE;i++) {
2159 if(tag == tags[i].tag)
2162 for(i=0; tags[i].id != AV_CODEC_ID_NONE; i++) {
2163 if (avpriv_toupper4(tag) == avpriv_toupper4(tags[i].tag))
2166 return AV_CODEC_ID_NONE;
2169 enum AVCodecID ff_get_pcm_codec_id(int bps, int flt, int be, int sflags)
2173 case 32: return be ? AV_CODEC_ID_PCM_F32BE : AV_CODEC_ID_PCM_F32LE;
2174 case 64: return be ? AV_CODEC_ID_PCM_F64BE : AV_CODEC_ID_PCM_F64LE;
2175 default: return AV_CODEC_ID_NONE;
2179 if (sflags & (1 << (bps - 1))) {
2181 case 1: return AV_CODEC_ID_PCM_S8;
2182 case 2: return be ? AV_CODEC_ID_PCM_S16BE : AV_CODEC_ID_PCM_S16LE;
2183 case 3: return be ? AV_CODEC_ID_PCM_S24BE : AV_CODEC_ID_PCM_S24LE;
2184 case 4: return be ? AV_CODEC_ID_PCM_S32BE : AV_CODEC_ID_PCM_S32LE;
2185 default: return AV_CODEC_ID_NONE;
2189 case 1: return AV_CODEC_ID_PCM_U8;
2190 case 2: return be ? AV_CODEC_ID_PCM_U16BE : AV_CODEC_ID_PCM_U16LE;
2191 case 3: return be ? AV_CODEC_ID_PCM_U24BE : AV_CODEC_ID_PCM_U24LE;
2192 case 4: return be ? AV_CODEC_ID_PCM_U32BE : AV_CODEC_ID_PCM_U32LE;
2193 default: return AV_CODEC_ID_NONE;
2199 unsigned int av_codec_get_tag(const AVCodecTag * const *tags, enum AVCodecID id)
2202 for(i=0; tags && tags[i]; i++){
2203 int tag= ff_codec_get_tag(tags[i], id);
2209 enum AVCodecID av_codec_get_id(const AVCodecTag * const *tags, unsigned int tag)
2212 for(i=0; tags && tags[i]; i++){
2213 enum AVCodecID id= ff_codec_get_id(tags[i], tag);
2214 if(id!=AV_CODEC_ID_NONE) return id;
2216 return AV_CODEC_ID_NONE;
2219 static void compute_chapters_end(AVFormatContext *s)
2222 int64_t max_time = s->duration + ((s->start_time == AV_NOPTS_VALUE) ? 0 : s->start_time);
2224 for (i = 0; i < s->nb_chapters; i++)
2225 if (s->chapters[i]->end == AV_NOPTS_VALUE) {
2226 AVChapter *ch = s->chapters[i];
2227 int64_t end = max_time ? av_rescale_q(max_time, AV_TIME_BASE_Q, ch->time_base)
2230 for (j = 0; j < s->nb_chapters; j++) {
2231 AVChapter *ch1 = s->chapters[j];
2232 int64_t next_start = av_rescale_q(ch1->start, ch1->time_base, ch->time_base);
2233 if (j != i && next_start > ch->start && next_start < end)
2236 ch->end = (end == INT64_MAX) ? ch->start : end;
2240 static int get_std_framerate(int i){
2241 if(i<60*12) return i*1001;
2242 else return ((const int[]){24,30,60,12,15})[i-60*12]*1000*12;
2246 * Is the time base unreliable.
2247 * This is a heuristic to balance between quick acceptance of the values in
2248 * the headers vs. some extra checks.
2249 * Old DivX and Xvid often have nonsense timebases like 1fps or 2fps.
2250 * MPEG-2 commonly misuses field repeat flags to store different framerates.
2251 * And there are "variable" fps files this needs to detect as well.
2253 static int tb_unreliable(AVCodecContext *c){
2254 if( c->time_base.den >= 101L*c->time_base.num
2255 || c->time_base.den < 5L*c->time_base.num
2256 /* || c->codec_tag == AV_RL32("DIVX")
2257 || c->codec_tag == AV_RL32("XVID")*/
2258 || c->codec_id == AV_CODEC_ID_MPEG2VIDEO
2259 || c->codec_id == AV_CODEC_ID_H264
2265 int avformat_find_stream_info(AVFormatContext *ic, AVDictionary **options)
2267 int i, count, ret, read_size, j;
2269 AVPacket pkt1, *pkt;
2270 int64_t old_offset = avio_tell(ic->pb);
2271 int orig_nb_streams = ic->nb_streams; // new streams might appear, no options for those
2273 for(i=0;i<ic->nb_streams;i++) {
2274 const AVCodec *codec;
2275 AVDictionary *thread_opt = NULL;
2276 st = ic->streams[i];
2278 //only for the split stuff
2279 if (!st->parser && !(ic->flags & AVFMT_FLAG_NOPARSE)) {
2280 st->parser = av_parser_init(st->codec->codec_id);
2281 if(st->need_parsing == AVSTREAM_PARSE_HEADERS && st->parser){
2282 st->parser->flags |= PARSER_FLAG_COMPLETE_FRAMES;
2285 codec = st->codec->codec ? st->codec->codec :
2286 avcodec_find_decoder(st->codec->codec_id);
2288 /* force thread count to 1 since the h264 decoder will not extract SPS
2289 * and PPS to extradata during multi-threaded decoding */
2290 av_dict_set(options ? &options[i] : &thread_opt, "threads", "1", 0);
2292 /* Ensure that subtitle_header is properly set. */
2293 if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE
2294 && codec && !st->codec->codec)
2295 avcodec_open2(st->codec, codec, options ? &options[i]
2298 //try to just open decoders, in case this is enough to get parameters
2299 if (!has_codec_parameters(st)) {
2300 if (codec && !st->codec->codec)
2301 avcodec_open2(st->codec, codec, options ? &options[i]
2305 av_dict_free(&thread_opt);
2308 for (i=0; i<ic->nb_streams; i++) {
2309 ic->streams[i]->info->fps_first_dts = AV_NOPTS_VALUE;
2310 ic->streams[i]->info->fps_last_dts = AV_NOPTS_VALUE;
2316 if (ff_check_interrupt(&ic->interrupt_callback)){
2318 av_log(ic, AV_LOG_DEBUG, "interrupted\n");
2322 /* check if one codec still needs to be handled */
2323 for(i=0;i<ic->nb_streams;i++) {
2324 int fps_analyze_framecount = 20;
2326 st = ic->streams[i];
2327 if (!has_codec_parameters(st))
2329 /* if the timebase is coarse (like the usual millisecond precision
2330 of mkv), we need to analyze more frames to reliably arrive at
2332 if (av_q2d(st->time_base) > 0.0005)
2333 fps_analyze_framecount *= 2;
2334 if (ic->fps_probe_size >= 0)
2335 fps_analyze_framecount = ic->fps_probe_size;
2336 /* variable fps and no guess at the real fps */
2337 if( tb_unreliable(st->codec) && !st->avg_frame_rate.num
2338 && st->codec_info_nb_frames < fps_analyze_framecount
2339 && st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
2341 if(st->parser && st->parser->parser->split && !st->codec->extradata)
2343 if (st->first_dts == AV_NOPTS_VALUE &&
2344 (st->codec->codec_type == AVMEDIA_TYPE_VIDEO ||
2345 st->codec->codec_type == AVMEDIA_TYPE_AUDIO))
2348 if (i == ic->nb_streams) {
2349 /* NOTE: if the format has no header, then we need to read
2350 some packets to get most of the streams, so we cannot
2352 if (!(ic->ctx_flags & AVFMTCTX_NOHEADER)) {
2353 /* if we found the info for all the codecs, we can stop */
2355 av_log(ic, AV_LOG_DEBUG, "All info found\n");
2359 /* we did not get all the codec info, but we read too much data */
2360 if (read_size >= ic->probesize) {
2362 av_log(ic, AV_LOG_DEBUG, "Probe buffer size limit %d reached\n", ic->probesize);
2366 /* NOTE: a new stream can be added there if no header in file
2367 (AVFMTCTX_NOHEADER) */
2368 ret = read_frame_internal(ic, &pkt1);
2369 if (ret == AVERROR(EAGAIN))
2374 AVPacket empty_pkt = { 0 };
2376 av_init_packet(&empty_pkt);
2378 ret = -1; /* we could not have all the codec parameters before EOF */
2379 for(i=0;i<ic->nb_streams;i++) {
2380 st = ic->streams[i];
2382 /* flush the decoders */
2383 if (st->info->found_decoder == 1) {
2385 err = try_decode_frame(st, &empty_pkt,
2386 (options && i < orig_nb_streams) ?
2387 &options[i] : NULL);
2388 } while (err > 0 && !has_codec_parameters(st));
2392 av_log(ic, AV_LOG_WARNING,
2393 "decoding for stream %d failed\n", st->index);
2394 } else if (!has_codec_parameters(st)) {
2396 avcodec_string(buf, sizeof(buf), st->codec, 0);
2397 av_log(ic, AV_LOG_WARNING,
2398 "Could not find codec parameters (%s)\n", buf);
2406 if (ic->flags & AVFMT_FLAG_NOBUFFER) {
2409 pkt = add_to_pktbuf(&ic->packet_buffer, &pkt1,
2410 &ic->packet_buffer_end);
2411 if ((ret = av_dup_packet(pkt)) < 0)
2412 goto find_stream_info_err;
2415 read_size += pkt->size;
2417 st = ic->streams[pkt->stream_index];
2418 if (pkt->dts != AV_NOPTS_VALUE && st->codec_info_nb_frames > 1) {
2419 /* check for non-increasing dts */
2420 if (st->info->fps_last_dts != AV_NOPTS_VALUE &&
2421 st->info->fps_last_dts >= pkt->dts) {
2422 av_log(ic, AV_LOG_WARNING, "Non-increasing DTS in stream %d: "
2423 "packet %d with DTS %"PRId64", packet %d with DTS "
2424 "%"PRId64"\n", st->index, st->info->fps_last_dts_idx,
2425 st->info->fps_last_dts, st->codec_info_nb_frames, pkt->dts);
2426 st->info->fps_first_dts = st->info->fps_last_dts = AV_NOPTS_VALUE;
2428 /* check for a discontinuity in dts - if the difference in dts
2429 * is more than 1000 times the average packet duration in the sequence,
2430 * we treat it as a discontinuity */
2431 if (st->info->fps_last_dts != AV_NOPTS_VALUE &&
2432 st->info->fps_last_dts_idx > st->info->fps_first_dts_idx &&
2433 (pkt->dts - st->info->fps_last_dts) / 1000 >
2434 (st->info->fps_last_dts - st->info->fps_first_dts) / (st->info->fps_last_dts_idx - st->info->fps_first_dts_idx)) {
2435 av_log(ic, AV_LOG_WARNING, "DTS discontinuity in stream %d: "
2436 "packet %d with DTS %"PRId64", packet %d with DTS "
2437 "%"PRId64"\n", st->index, st->info->fps_last_dts_idx,
2438 st->info->fps_last_dts, st->codec_info_nb_frames, pkt->dts);
2439 st->info->fps_first_dts = st->info->fps_last_dts = AV_NOPTS_VALUE;
2442 /* update stored dts values */
2443 if (st->info->fps_first_dts == AV_NOPTS_VALUE) {
2444 st->info->fps_first_dts = pkt->dts;
2445 st->info->fps_first_dts_idx = st->codec_info_nb_frames;
2447 st->info->fps_last_dts = pkt->dts;
2448 st->info->fps_last_dts_idx = st->codec_info_nb_frames;
2450 /* check max_analyze_duration */
2451 if (av_rescale_q(pkt->dts - st->info->fps_first_dts, st->time_base,
2452 AV_TIME_BASE_Q) >= ic->max_analyze_duration) {
2453 av_log(ic, AV_LOG_WARNING, "max_analyze_duration reached\n");
2457 if(st->parser && st->parser->parser->split && !st->codec->extradata){
2458 int i= st->parser->parser->split(st->codec, pkt->data, pkt->size);
2459 if (i > 0 && i < FF_MAX_EXTRADATA_SIZE) {
2460 st->codec->extradata_size= i;
2461 st->codec->extradata= av_malloc(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
2462 if (!st->codec->extradata)
2463 return AVERROR(ENOMEM);
2464 memcpy(st->codec->extradata, pkt->data, st->codec->extradata_size);
2465 memset(st->codec->extradata + i, 0, FF_INPUT_BUFFER_PADDING_SIZE);
2469 /* if still no information, we try to open the codec and to
2470 decompress the frame. We try to avoid that in most cases as
2471 it takes longer and uses more memory. For MPEG-4, we need to
2472 decompress for QuickTime.
2474 If CODEC_CAP_CHANNEL_CONF is set this will force decoding of at
2475 least one frame of codec data, this makes sure the codec initializes
2476 the channel configuration and does not only trust the values from the container.
2478 try_decode_frame(st, pkt, (options && i < orig_nb_streams ) ? &options[i] : NULL);
2480 st->codec_info_nb_frames++;
2484 // close codecs which were opened in try_decode_frame()
2485 for(i=0;i<ic->nb_streams;i++) {
2486 st = ic->streams[i];
2487 avcodec_close(st->codec);
2489 for(i=0;i<ic->nb_streams;i++) {
2490 st = ic->streams[i];
2491 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
2492 /* estimate average framerate if not set by demuxer */
2493 if (!st->avg_frame_rate.num && st->info->fps_last_dts != st->info->fps_first_dts) {
2494 int64_t delta_dts = st->info->fps_last_dts - st->info->fps_first_dts;
2495 int delta_packets = st->info->fps_last_dts_idx - st->info->fps_first_dts_idx;
2497 double best_error = 0.01;
2499 av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
2500 delta_packets*(int64_t)st->time_base.den,
2501 delta_dts*(int64_t)st->time_base.num, 60000);
2503 /* round guessed framerate to a "standard" framerate if it's
2504 * within 1% of the original estimate*/
2505 for (j = 1; j < MAX_STD_TIMEBASES; j++) {
2506 AVRational std_fps = { get_std_framerate(j), 12*1001 };
2507 double error = fabs(av_q2d(st->avg_frame_rate) / av_q2d(std_fps) - 1);
2509 if (error < best_error) {
2511 best_fps = std_fps.num;
2515 av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
2516 best_fps, 12*1001, INT_MAX);
2519 }else if(st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
2520 if(!st->codec->bits_per_coded_sample)
2521 st->codec->bits_per_coded_sample= av_get_bits_per_sample(st->codec->codec_id);
2522 // set stream disposition based on audio service type
2523 switch (st->codec->audio_service_type) {
2524 case AV_AUDIO_SERVICE_TYPE_EFFECTS:
2525 st->disposition = AV_DISPOSITION_CLEAN_EFFECTS; break;
2526 case AV_AUDIO_SERVICE_TYPE_VISUALLY_IMPAIRED:
2527 st->disposition = AV_DISPOSITION_VISUAL_IMPAIRED; break;
2528 case AV_AUDIO_SERVICE_TYPE_HEARING_IMPAIRED:
2529 st->disposition = AV_DISPOSITION_HEARING_IMPAIRED; break;
2530 case AV_AUDIO_SERVICE_TYPE_COMMENTARY:
2531 st->disposition = AV_DISPOSITION_COMMENT; break;
2532 case AV_AUDIO_SERVICE_TYPE_KARAOKE:
2533 st->disposition = AV_DISPOSITION_KARAOKE; break;
2538 estimate_timings(ic, old_offset);
2540 compute_chapters_end(ic);
2542 find_stream_info_err:
2543 for (i=0; i < ic->nb_streams; i++) {
2544 if (ic->streams[i]->codec)
2545 ic->streams[i]->codec->thread_count = 0;
2546 av_freep(&ic->streams[i]->info);
2551 static AVProgram *find_program_from_stream(AVFormatContext *ic, int s)
2555 for (i = 0; i < ic->nb_programs; i++)
2556 for (j = 0; j < ic->programs[i]->nb_stream_indexes; j++)
2557 if (ic->programs[i]->stream_index[j] == s)
2558 return ic->programs[i];
2562 int av_find_best_stream(AVFormatContext *ic,
2563 enum AVMediaType type,
2564 int wanted_stream_nb,
2566 AVCodec **decoder_ret,
2569 int i, nb_streams = ic->nb_streams;
2570 int ret = AVERROR_STREAM_NOT_FOUND, best_count = -1;
2571 unsigned *program = NULL;
2572 AVCodec *decoder = NULL, *best_decoder = NULL;
2574 if (related_stream >= 0 && wanted_stream_nb < 0) {
2575 AVProgram *p = find_program_from_stream(ic, related_stream);
2577 program = p->stream_index;
2578 nb_streams = p->nb_stream_indexes;
2581 for (i = 0; i < nb_streams; i++) {
2582 int real_stream_index = program ? program[i] : i;
2583 AVStream *st = ic->streams[real_stream_index];
2584 AVCodecContext *avctx = st->codec;
2585 if (avctx->codec_type != type)
2587 if (wanted_stream_nb >= 0 && real_stream_index != wanted_stream_nb)
2589 if (st->disposition & (AV_DISPOSITION_HEARING_IMPAIRED|AV_DISPOSITION_VISUAL_IMPAIRED))
2592 decoder = avcodec_find_decoder(st->codec->codec_id);
2595 ret = AVERROR_DECODER_NOT_FOUND;
2599 if (best_count >= st->codec_info_nb_frames)
2601 best_count = st->codec_info_nb_frames;
2602 ret = real_stream_index;
2603 best_decoder = decoder;
2604 if (program && i == nb_streams - 1 && ret < 0) {
2606 nb_streams = ic->nb_streams;
2607 i = 0; /* no related stream found, try again with everything */
2611 *decoder_ret = best_decoder;
2615 /*******************************************************/
2617 int av_read_play(AVFormatContext *s)
2619 if (s->iformat->read_play)
2620 return s->iformat->read_play(s);
2622 return avio_pause(s->pb, 0);
2623 return AVERROR(ENOSYS);
2626 int av_read_pause(AVFormatContext *s)
2628 if (s->iformat->read_pause)
2629 return s->iformat->read_pause(s);
2631 return avio_pause(s->pb, 1);
2632 return AVERROR(ENOSYS);
2635 void avformat_free_context(AVFormatContext *s)
2641 if (s->iformat && s->iformat->priv_class && s->priv_data)
2642 av_opt_free(s->priv_data);
2644 for(i=0;i<s->nb_streams;i++) {
2645 /* free all data in a stream component */
2648 av_parser_close(st->parser);
2650 if (st->attached_pic.data)
2651 av_free_packet(&st->attached_pic);
2652 av_dict_free(&st->metadata);
2653 av_freep(&st->probe_data.buf);
2654 av_free(st->index_entries);
2655 av_free(st->codec->extradata);
2656 av_free(st->codec->subtitle_header);
2658 av_free(st->priv_data);
2662 for(i=s->nb_programs-1; i>=0; i--) {
2663 av_dict_free(&s->programs[i]->metadata);
2664 av_freep(&s->programs[i]->stream_index);
2665 av_freep(&s->programs[i]);
2667 av_freep(&s->programs);
2668 av_freep(&s->priv_data);
2669 while(s->nb_chapters--) {
2670 av_dict_free(&s->chapters[s->nb_chapters]->metadata);
2671 av_free(s->chapters[s->nb_chapters]);
2673 av_freep(&s->chapters);
2674 av_dict_free(&s->metadata);
2675 av_freep(&s->streams);
2679 void avformat_close_input(AVFormatContext **ps)
2681 AVFormatContext *s = *ps;
2682 AVIOContext *pb = s->pb;
2684 if ((s->iformat && s->iformat->flags & AVFMT_NOFILE) ||
2685 (s->flags & AVFMT_FLAG_CUSTOM_IO))
2688 flush_packet_queue(s);
2691 if (s->iformat->read_close)
2692 s->iformat->read_close(s);
2695 avformat_free_context(s);
2702 AVStream *avformat_new_stream(AVFormatContext *s, AVCodec *c)
2708 if (s->nb_streams >= INT_MAX/sizeof(*streams))
2710 streams = av_realloc(s->streams, (s->nb_streams + 1) * sizeof(*streams));
2713 s->streams = streams;
2715 st = av_mallocz(sizeof(AVStream));
2718 if (!(st->info = av_mallocz(sizeof(*st->info)))) {
2723 st->codec = avcodec_alloc_context3(c);
2725 /* no default bitrate if decoding */
2726 st->codec->bit_rate = 0;
2728 st->index = s->nb_streams;
2729 st->start_time = AV_NOPTS_VALUE;
2730 st->duration = AV_NOPTS_VALUE;
2731 /* we set the current DTS to 0 so that formats without any timestamps
2732 but durations get some timestamps, formats with some unknown
2733 timestamps have their first few packets buffered and the
2734 timestamps corrected before they are returned to the user */
2736 st->first_dts = AV_NOPTS_VALUE;
2737 st->probe_packets = MAX_PROBE_PACKETS;
2739 /* default pts setting is MPEG-like */
2740 avpriv_set_pts_info(st, 33, 1, 90000);
2741 st->last_IP_pts = AV_NOPTS_VALUE;
2742 for(i=0; i<MAX_REORDER_DELAY+1; i++)
2743 st->pts_buffer[i]= AV_NOPTS_VALUE;
2744 st->reference_dts = AV_NOPTS_VALUE;
2746 st->sample_aspect_ratio = (AVRational){0,1};
2748 st->info->fps_first_dts = AV_NOPTS_VALUE;
2749 st->info->fps_last_dts = AV_NOPTS_VALUE;
2751 s->streams[s->nb_streams++] = st;
2755 AVProgram *av_new_program(AVFormatContext *ac, int id)
2757 AVProgram *program=NULL;
2760 av_dlog(ac, "new_program: id=0x%04x\n", id);
2762 for(i=0; i<ac->nb_programs; i++)
2763 if(ac->programs[i]->id == id)
2764 program = ac->programs[i];
2767 program = av_mallocz(sizeof(AVProgram));
2770 dynarray_add(&ac->programs, &ac->nb_programs, program);
2771 program->discard = AVDISCARD_NONE;
2778 AVChapter *avpriv_new_chapter(AVFormatContext *s, int id, AVRational time_base, int64_t start, int64_t end, const char *title)
2780 AVChapter *chapter = NULL;
2783 for(i=0; i<s->nb_chapters; i++)
2784 if(s->chapters[i]->id == id)
2785 chapter = s->chapters[i];
2788 chapter= av_mallocz(sizeof(AVChapter));
2791 dynarray_add(&s->chapters, &s->nb_chapters, chapter);
2793 av_dict_set(&chapter->metadata, "title", title, 0);
2795 chapter->time_base= time_base;
2796 chapter->start = start;
2802 void ff_program_add_stream_index(AVFormatContext *ac, int progid, unsigned int idx)
2805 AVProgram *program=NULL;
2808 if (idx >= ac->nb_streams) {
2809 av_log(ac, AV_LOG_ERROR, "stream index %d is not valid\n", idx);
2813 for(i=0; i<ac->nb_programs; i++){
2814 if(ac->programs[i]->id != progid)
2816 program = ac->programs[i];
2817 for(j=0; j<program->nb_stream_indexes; j++)
2818 if(program->stream_index[j] == idx)
2821 tmp = av_realloc(program->stream_index, sizeof(unsigned int)*(program->nb_stream_indexes+1));
2824 program->stream_index = tmp;
2825 program->stream_index[program->nb_stream_indexes++] = idx;
2830 static void print_fps(double d, const char *postfix){
2831 uint64_t v= lrintf(d*100);
2832 if (v% 100 ) av_log(NULL, AV_LOG_INFO, ", %3.2f %s", d, postfix);
2833 else if(v%(100*1000)) av_log(NULL, AV_LOG_INFO, ", %1.0f %s", d, postfix);
2834 else av_log(NULL, AV_LOG_INFO, ", %1.0fk %s", d/1000, postfix);
2837 static void dump_metadata(void *ctx, AVDictionary *m, const char *indent)
2839 if(m && !(av_dict_count(m) == 1 && av_dict_get(m, "language", NULL, 0))){
2840 AVDictionaryEntry *tag=NULL;
2842 av_log(ctx, AV_LOG_INFO, "%sMetadata:\n", indent);
2843 while((tag=av_dict_get(m, "", tag, AV_DICT_IGNORE_SUFFIX))) {
2844 if(strcmp("language", tag->key))
2845 av_log(ctx, AV_LOG_INFO, "%s %-16s: %s\n", indent, tag->key, tag->value);
2850 /* "user interface" functions */
2851 static void dump_stream_format(AVFormatContext *ic, int i, int index, int is_output)
2854 int flags = (is_output ? ic->oformat->flags : ic->iformat->flags);
2855 AVStream *st = ic->streams[i];
2856 int g = av_gcd(st->time_base.num, st->time_base.den);
2857 AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL, 0);
2858 avcodec_string(buf, sizeof(buf), st->codec, is_output);
2859 av_log(NULL, AV_LOG_INFO, " Stream #%d.%d", index, i);
2860 /* the pid is an important information, so we display it */
2861 /* XXX: add a generic system */
2862 if (flags & AVFMT_SHOW_IDS)
2863 av_log(NULL, AV_LOG_INFO, "[0x%x]", st->id);
2865 av_log(NULL, AV_LOG_INFO, "(%s)", lang->value);
2866 av_log(NULL, AV_LOG_DEBUG, ", %d, %d/%d", st->codec_info_nb_frames, st->time_base.num/g, st->time_base.den/g);
2867 av_log(NULL, AV_LOG_INFO, ": %s", buf);
2868 if (st->sample_aspect_ratio.num && // default
2869 av_cmp_q(st->sample_aspect_ratio, st->codec->sample_aspect_ratio)) {
2870 AVRational display_aspect_ratio;
2871 av_reduce(&display_aspect_ratio.num, &display_aspect_ratio.den,
2872 st->codec->width*st->sample_aspect_ratio.num,
2873 st->codec->height*st->sample_aspect_ratio.den,
2875 av_log(NULL, AV_LOG_INFO, ", PAR %d:%d DAR %d:%d",
2876 st->sample_aspect_ratio.num, st->sample_aspect_ratio.den,
2877 display_aspect_ratio.num, display_aspect_ratio.den);
2879 if(st->codec->codec_type == AVMEDIA_TYPE_VIDEO){
2880 if(st->avg_frame_rate.den && st->avg_frame_rate.num)
2881 print_fps(av_q2d(st->avg_frame_rate), "fps");
2882 if(st->time_base.den && st->time_base.num)
2883 print_fps(1/av_q2d(st->time_base), "tbn");
2884 if(st->codec->time_base.den && st->codec->time_base.num)
2885 print_fps(1/av_q2d(st->codec->time_base), "tbc");
2887 if (st->disposition & AV_DISPOSITION_DEFAULT)
2888 av_log(NULL, AV_LOG_INFO, " (default)");
2889 if (st->disposition & AV_DISPOSITION_DUB)
2890 av_log(NULL, AV_LOG_INFO, " (dub)");
2891 if (st->disposition & AV_DISPOSITION_ORIGINAL)
2892 av_log(NULL, AV_LOG_INFO, " (original)");
2893 if (st->disposition & AV_DISPOSITION_COMMENT)
2894 av_log(NULL, AV_LOG_INFO, " (comment)");
2895 if (st->disposition & AV_DISPOSITION_LYRICS)
2896 av_log(NULL, AV_LOG_INFO, " (lyrics)");
2897 if (st->disposition & AV_DISPOSITION_KARAOKE)
2898 av_log(NULL, AV_LOG_INFO, " (karaoke)");
2899 if (st->disposition & AV_DISPOSITION_FORCED)
2900 av_log(NULL, AV_LOG_INFO, " (forced)");
2901 if (st->disposition & AV_DISPOSITION_HEARING_IMPAIRED)
2902 av_log(NULL, AV_LOG_INFO, " (hearing impaired)");
2903 if (st->disposition & AV_DISPOSITION_VISUAL_IMPAIRED)
2904 av_log(NULL, AV_LOG_INFO, " (visual impaired)");
2905 if (st->disposition & AV_DISPOSITION_CLEAN_EFFECTS)
2906 av_log(NULL, AV_LOG_INFO, " (clean effects)");
2907 av_log(NULL, AV_LOG_INFO, "\n");
2908 dump_metadata(NULL, st->metadata, " ");
2911 void av_dump_format(AVFormatContext *ic,
2917 uint8_t *printed = ic->nb_streams ? av_mallocz(ic->nb_streams) : NULL;
2918 if (ic->nb_streams && !printed)
2921 av_log(NULL, AV_LOG_INFO, "%s #%d, %s, %s '%s':\n",
2922 is_output ? "Output" : "Input",
2924 is_output ? ic->oformat->name : ic->iformat->name,
2925 is_output ? "to" : "from", url);
2926 dump_metadata(NULL, ic->metadata, " ");
2928 av_log(NULL, AV_LOG_INFO, " Duration: ");
2929 if (ic->duration != AV_NOPTS_VALUE) {
2930 int hours, mins, secs, us;
2931 secs = ic->duration / AV_TIME_BASE;
2932 us = ic->duration % AV_TIME_BASE;
2937 av_log(NULL, AV_LOG_INFO, "%02d:%02d:%02d.%02d", hours, mins, secs,
2938 (100 * us) / AV_TIME_BASE);
2940 av_log(NULL, AV_LOG_INFO, "N/A");
2942 if (ic->start_time != AV_NOPTS_VALUE) {
2944 av_log(NULL, AV_LOG_INFO, ", start: ");
2945 secs = ic->start_time / AV_TIME_BASE;
2946 us = abs(ic->start_time % AV_TIME_BASE);
2947 av_log(NULL, AV_LOG_INFO, "%d.%06d",
2948 secs, (int)av_rescale(us, 1000000, AV_TIME_BASE));
2950 av_log(NULL, AV_LOG_INFO, ", bitrate: ");
2952 av_log(NULL, AV_LOG_INFO,"%d kb/s", ic->bit_rate / 1000);
2954 av_log(NULL, AV_LOG_INFO, "N/A");
2956 av_log(NULL, AV_LOG_INFO, "\n");
2958 for (i = 0; i < ic->nb_chapters; i++) {
2959 AVChapter *ch = ic->chapters[i];
2960 av_log(NULL, AV_LOG_INFO, " Chapter #%d.%d: ", index, i);
2961 av_log(NULL, AV_LOG_INFO, "start %f, ", ch->start * av_q2d(ch->time_base));
2962 av_log(NULL, AV_LOG_INFO, "end %f\n", ch->end * av_q2d(ch->time_base));
2964 dump_metadata(NULL, ch->metadata, " ");
2966 if(ic->nb_programs) {
2967 int j, k, total = 0;
2968 for(j=0; j<ic->nb_programs; j++) {
2969 AVDictionaryEntry *name = av_dict_get(ic->programs[j]->metadata,
2971 av_log(NULL, AV_LOG_INFO, " Program %d %s\n", ic->programs[j]->id,
2972 name ? name->value : "");
2973 dump_metadata(NULL, ic->programs[j]->metadata, " ");
2974 for(k=0; k<ic->programs[j]->nb_stream_indexes; k++) {
2975 dump_stream_format(ic, ic->programs[j]->stream_index[k], index, is_output);
2976 printed[ic->programs[j]->stream_index[k]] = 1;
2978 total += ic->programs[j]->nb_stream_indexes;
2980 if (total < ic->nb_streams)
2981 av_log(NULL, AV_LOG_INFO, " No Program\n");
2983 for(i=0;i<ic->nb_streams;i++)
2985 dump_stream_format(ic, i, index, is_output);
2990 uint64_t ff_ntp_time(void)
2992 return (av_gettime() / 1000) * 1000 + NTP_OFFSET_US;
2995 int av_get_frame_filename(char *buf, int buf_size,
2996 const char *path, int number)
2999 char *q, buf1[20], c;
3000 int nd, len, percentd_found;
3012 while (av_isdigit(*p)) {
3013 nd = nd * 10 + *p++ - '0';
3016 } while (av_isdigit(c));
3025 snprintf(buf1, sizeof(buf1), "%0*d", nd, number);
3027 if ((q - buf + len) > buf_size - 1)
3029 memcpy(q, buf1, len);
3037 if ((q - buf) < buf_size - 1)
3041 if (!percentd_found)
3050 static void hex_dump_internal(void *avcl, FILE *f, int level,
3051 const uint8_t *buf, int size)
3054 #define PRINT(...) do { if (!f) av_log(avcl, level, __VA_ARGS__); else fprintf(f, __VA_ARGS__); } while(0)
3056 for(i=0;i<size;i+=16) {
3063 PRINT(" %02x", buf[i+j]);
3068 for(j=0;j<len;j++) {
3070 if (c < ' ' || c > '~')
3079 void av_hex_dump(FILE *f, const uint8_t *buf, int size)
3081 hex_dump_internal(NULL, f, 0, buf, size);
3084 void av_hex_dump_log(void *avcl, int level, const uint8_t *buf, int size)
3086 hex_dump_internal(avcl, NULL, level, buf, size);
3089 static void pkt_dump_internal(void *avcl, FILE *f, int level, AVPacket *pkt, int dump_payload, AVRational time_base)
3091 #define PRINT(...) do { if (!f) av_log(avcl, level, __VA_ARGS__); else fprintf(f, __VA_ARGS__); } while(0)
3092 PRINT("stream #%d:\n", pkt->stream_index);
3093 PRINT(" keyframe=%d\n", ((pkt->flags & AV_PKT_FLAG_KEY) != 0));
3094 PRINT(" duration=%0.3f\n", pkt->duration * av_q2d(time_base));
3095 /* DTS is _always_ valid after av_read_frame() */
3097 if (pkt->dts == AV_NOPTS_VALUE)
3100 PRINT("%0.3f", pkt->dts * av_q2d(time_base));
3101 /* PTS may not be known if B-frames are present. */
3103 if (pkt->pts == AV_NOPTS_VALUE)
3106 PRINT("%0.3f", pkt->pts * av_q2d(time_base));
3108 PRINT(" size=%d\n", pkt->size);
3111 av_hex_dump(f, pkt->data, pkt->size);
3114 void av_pkt_dump2(FILE *f, AVPacket *pkt, int dump_payload, AVStream *st)
3116 pkt_dump_internal(NULL, f, 0, pkt, dump_payload, st->time_base);
3119 void av_pkt_dump_log2(void *avcl, int level, AVPacket *pkt, int dump_payload,
3122 pkt_dump_internal(avcl, NULL, level, pkt, dump_payload, st->time_base);
3125 void av_url_split(char *proto, int proto_size,
3126 char *authorization, int authorization_size,
3127 char *hostname, int hostname_size,
3129 char *path, int path_size,
3132 const char *p, *ls, *at, *col, *brk;
3134 if (port_ptr) *port_ptr = -1;
3135 if (proto_size > 0) proto[0] = 0;
3136 if (authorization_size > 0) authorization[0] = 0;
3137 if (hostname_size > 0) hostname[0] = 0;
3138 if (path_size > 0) path[0] = 0;
3140 /* parse protocol */
3141 if ((p = strchr(url, ':'))) {
3142 av_strlcpy(proto, url, FFMIN(proto_size, p + 1 - url));
3147 /* no protocol means plain filename */
3148 av_strlcpy(path, url, path_size);
3152 /* separate path from hostname */
3153 ls = strchr(p, '/');
3155 ls = strchr(p, '?');
3157 av_strlcpy(path, ls, path_size);
3159 ls = &p[strlen(p)]; // XXX
3161 /* the rest is hostname, use that to parse auth/port */
3163 /* authorization (user[:pass]@hostname) */
3164 if ((at = strchr(p, '@')) && at < ls) {
3165 av_strlcpy(authorization, p,
3166 FFMIN(authorization_size, at + 1 - p));
3167 p = at + 1; /* skip '@' */
3170 if (*p == '[' && (brk = strchr(p, ']')) && brk < ls) {
3172 av_strlcpy(hostname, p + 1,
3173 FFMIN(hostname_size, brk - p));
3174 if (brk[1] == ':' && port_ptr)
3175 *port_ptr = atoi(brk + 2);
3176 } else if ((col = strchr(p, ':')) && col < ls) {
3177 av_strlcpy(hostname, p,
3178 FFMIN(col + 1 - p, hostname_size));
3179 if (port_ptr) *port_ptr = atoi(col + 1);
3181 av_strlcpy(hostname, p,
3182 FFMIN(ls + 1 - p, hostname_size));
3186 char *ff_data_to_hex(char *buff, const uint8_t *src, int s, int lowercase)
3189 static const char hex_table_uc[16] = { '0', '1', '2', '3',
3192 'C', 'D', 'E', 'F' };
3193 static const char hex_table_lc[16] = { '0', '1', '2', '3',
3196 'c', 'd', 'e', 'f' };
3197 const char *hex_table = lowercase ? hex_table_lc : hex_table_uc;
3199 for(i = 0; i < s; i++) {
3200 buff[i * 2] = hex_table[src[i] >> 4];
3201 buff[i * 2 + 1] = hex_table[src[i] & 0xF];
3207 int ff_hex_to_data(uint8_t *data, const char *p)
3214 p += strspn(p, SPACE_CHARS);
3217 c = av_toupper((unsigned char) *p++);
3218 if (c >= '0' && c <= '9')
3220 else if (c >= 'A' && c <= 'F')
3235 void avpriv_set_pts_info(AVStream *s, int pts_wrap_bits,
3236 unsigned int pts_num, unsigned int pts_den)
3239 if(av_reduce(&new_tb.num, &new_tb.den, pts_num, pts_den, INT_MAX)){
3240 if(new_tb.num != pts_num)
3241 av_log(NULL, AV_LOG_DEBUG, "st:%d removing common factor %d from timebase\n", s->index, pts_num/new_tb.num);
3243 av_log(NULL, AV_LOG_WARNING, "st:%d has too large timebase, reducing\n", s->index);
3245 if(new_tb.num <= 0 || new_tb.den <= 0) {
3246 av_log(NULL, AV_LOG_ERROR, "Ignoring attempt to set invalid timebase for st:%d\n", s->index);
3249 s->time_base = new_tb;
3250 s->pts_wrap_bits = pts_wrap_bits;
3253 int ff_url_join(char *str, int size, const char *proto,
3254 const char *authorization, const char *hostname,
3255 int port, const char *fmt, ...)
3258 struct addrinfo hints = { 0 }, *ai;
3263 av_strlcatf(str, size, "%s://", proto);
3264 if (authorization && authorization[0])
3265 av_strlcatf(str, size, "%s@", authorization);
3266 #if CONFIG_NETWORK && defined(AF_INET6)
3267 /* Determine if hostname is a numerical IPv6 address,
3268 * properly escape it within [] in that case. */
3269 hints.ai_flags = AI_NUMERICHOST;
3270 if (!getaddrinfo(hostname, NULL, &hints, &ai)) {
3271 if (ai->ai_family == AF_INET6) {
3272 av_strlcat(str, "[", size);
3273 av_strlcat(str, hostname, size);
3274 av_strlcat(str, "]", size);
3276 av_strlcat(str, hostname, size);
3281 /* Not an IPv6 address, just output the plain string. */
3282 av_strlcat(str, hostname, size);
3285 av_strlcatf(str, size, ":%d", port);
3288 int len = strlen(str);
3291 vsnprintf(str + len, size > len ? size - len : 0, fmt, vl);
3297 int ff_write_chained(AVFormatContext *dst, int dst_stream, AVPacket *pkt,
3298 AVFormatContext *src)
3303 local_pkt.stream_index = dst_stream;
3304 if (pkt->pts != AV_NOPTS_VALUE)
3305 local_pkt.pts = av_rescale_q(pkt->pts,
3306 src->streams[pkt->stream_index]->time_base,
3307 dst->streams[dst_stream]->time_base);
3308 if (pkt->dts != AV_NOPTS_VALUE)
3309 local_pkt.dts = av_rescale_q(pkt->dts,
3310 src->streams[pkt->stream_index]->time_base,
3311 dst->streams[dst_stream]->time_base);
3312 return av_write_frame(dst, &local_pkt);
3315 void ff_parse_key_value(const char *str, ff_parse_key_val_cb callback_get_buf,
3318 const char *ptr = str;
3320 /* Parse key=value pairs. */
3323 char *dest = NULL, *dest_end;
3324 int key_len, dest_len = 0;
3326 /* Skip whitespace and potential commas. */
3327 while (*ptr && (av_isspace(*ptr) || *ptr == ','))
3334 if (!(ptr = strchr(key, '=')))
3337 key_len = ptr - key;
3339 callback_get_buf(context, key, key_len, &dest, &dest_len);
3340 dest_end = dest + dest_len - 1;
3344 while (*ptr && *ptr != '\"') {
3348 if (dest && dest < dest_end)
3352 if (dest && dest < dest_end)
3360 for (; *ptr && !(av_isspace(*ptr) || *ptr == ','); ptr++)
3361 if (dest && dest < dest_end)
3369 int ff_find_stream_index(AVFormatContext *s, int id)
3372 for (i = 0; i < s->nb_streams; i++) {
3373 if (s->streams[i]->id == id)
3379 void ff_make_absolute_url(char *buf, int size, const char *base,
3382 char *sep, *path_query;
3383 /* Absolute path, relative to the current server */
3384 if (base && strstr(base, "://") && rel[0] == '/') {
3386 av_strlcpy(buf, base, size);
3387 sep = strstr(buf, "://");
3389 /* Take scheme from base url */
3390 if (rel[1] == '/') {
3393 /* Take scheme and host from base url */
3395 sep = strchr(sep, '/');
3400 av_strlcat(buf, rel, size);
3403 /* If rel actually is an absolute url, just copy it */
3404 if (!base || strstr(rel, "://") || rel[0] == '/') {
3405 av_strlcpy(buf, rel, size);
3409 av_strlcpy(buf, base, size);
3411 /* Strip off any query string from base */
3412 path_query = strchr(buf, '?');
3413 if (path_query != NULL)
3416 /* Is relative path just a new query part? */
3417 if (rel[0] == '?') {
3418 av_strlcat(buf, rel, size);
3422 /* Remove the file name from the base url */
3423 sep = strrchr(buf, '/');
3428 while (av_strstart(rel, "../", NULL) && sep) {
3429 /* Remove the path delimiter at the end */
3431 sep = strrchr(buf, '/');
3432 /* If the next directory name to pop off is "..", break here */
3433 if (!strcmp(sep ? &sep[1] : buf, "..")) {
3434 /* Readd the slash we just removed */
3435 av_strlcat(buf, "/", size);
3438 /* Cut off the directory name */
3445 av_strlcat(buf, rel, size);
3448 int64_t ff_iso8601_to_unix_time(const char *datestr)
3451 struct tm time1 = {0}, time2 = {0};
3453 ret1 = strptime(datestr, "%Y - %m - %d %T", &time1);
3454 ret2 = strptime(datestr, "%Y - %m - %dT%T", &time2);
3456 return av_timegm(&time2);
3458 return av_timegm(&time1);
3460 av_log(NULL, AV_LOG_WARNING, "strptime() unavailable on this system, cannot convert "
3461 "the date string.\n");
3466 int avformat_query_codec(AVOutputFormat *ofmt, enum AVCodecID codec_id, int std_compliance)
3469 if (ofmt->query_codec)
3470 return ofmt->query_codec(codec_id, std_compliance);
3471 else if (ofmt->codec_tag)
3472 return !!av_codec_get_tag(ofmt->codec_tag, codec_id);
3473 else if (codec_id == ofmt->video_codec || codec_id == ofmt->audio_codec ||
3474 codec_id == ofmt->subtitle_codec)
3477 return AVERROR_PATCHWELCOME;
3480 int avformat_network_init(void)
3484 ff_network_inited_globally = 1;
3485 if ((ret = ff_network_init()) < 0)
3492 int avformat_network_deinit(void)
3501 int ff_add_param_change(AVPacket *pkt, int32_t channels,
3502 uint64_t channel_layout, int32_t sample_rate,
3503 int32_t width, int32_t height)
3509 return AVERROR(EINVAL);
3512 flags |= AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_COUNT;
3514 if (channel_layout) {
3516 flags |= AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_LAYOUT;
3520 flags |= AV_SIDE_DATA_PARAM_CHANGE_SAMPLE_RATE;
3522 if (width || height) {
3524 flags |= AV_SIDE_DATA_PARAM_CHANGE_DIMENSIONS;
3526 data = av_packet_new_side_data(pkt, AV_PKT_DATA_PARAM_CHANGE, size);
3528 return AVERROR(ENOMEM);
3529 bytestream_put_le32(&data, flags);
3531 bytestream_put_le32(&data, channels);
3533 bytestream_put_le64(&data, channel_layout);
3535 bytestream_put_le32(&data, sample_rate);
3536 if (width || height) {
3537 bytestream_put_le32(&data, width);
3538 bytestream_put_le32(&data, height);
3543 const struct AVCodecTag *avformat_get_riff_video_tags(void)
3545 return ff_codec_bmp_tags;
3547 const struct AVCodecTag *avformat_get_riff_audio_tags(void)
3549 return ff_codec_wav_tags;
3552 static int match_host_pattern(const char *pattern, const char *hostname)
3555 if (!strcmp(pattern, "*"))
3557 // Skip a possible *. at the start of the pattern
3558 if (pattern[0] == '*')
3560 if (pattern[0] == '.')
3562 len_p = strlen(pattern);
3563 len_h = strlen(hostname);
3566 // Simply check if the end of hostname is equal to 'pattern'
3567 if (!strcmp(pattern, &hostname[len_h - len_p])) {
3569 return 1; // Exact match
3570 if (hostname[len_h - len_p - 1] == '.')
3571 return 1; // The matched substring is a domain and not just a substring of a domain
3576 int ff_http_match_no_proxy(const char *no_proxy, const char *hostname)
3584 buf = av_strdup(no_proxy);
3589 char *sep, *next = NULL;
3590 start += strspn(start, " ,");
3591 sep = start + strcspn(start, " ,");
3596 if (match_host_pattern(start, hostname)) {