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 "libavutil/opt.h"
31 #include "libavutil/avstring.h"
33 #include "audiointerleave.h"
48 * various utility functions for use within Libav
51 unsigned avformat_version(void)
53 return LIBAVFORMAT_VERSION_INT;
56 const char *avformat_configuration(void)
58 return LIBAV_CONFIGURATION;
61 const char *avformat_license(void)
63 #define LICENSE_PREFIX "libavformat license: "
64 return LICENSE_PREFIX LIBAV_LICENSE + sizeof(LICENSE_PREFIX) - 1;
67 /* fraction handling */
70 * f = val + (num / den) + 0.5.
72 * 'num' is normalized so that it is such as 0 <= num < den.
74 * @param f fractional number
75 * @param val integer value
76 * @param num must be >= 0
77 * @param den must be >= 1
79 static void av_frac_init(AVFrac *f, int64_t val, int64_t num, int64_t den)
92 * Fractional addition to f: f = f + (incr / f->den).
94 * @param f fractional number
95 * @param incr increment, can be positive or negative
97 static void av_frac_add(AVFrac *f, int64_t incr)
110 } else if (num >= den) {
117 /** head of registered input format linked list */
118 #if !FF_API_FIRST_FORMAT
121 AVInputFormat *first_iformat = NULL;
122 /** head of registered output format linked list */
123 #if !FF_API_FIRST_FORMAT
126 AVOutputFormat *first_oformat = NULL;
128 AVInputFormat *av_iformat_next(AVInputFormat *f)
130 if(f) return f->next;
131 else return first_iformat;
134 AVOutputFormat *av_oformat_next(AVOutputFormat *f)
136 if(f) return f->next;
137 else return first_oformat;
140 void av_register_input_format(AVInputFormat *format)
144 while (*p != NULL) p = &(*p)->next;
149 void av_register_output_format(AVOutputFormat *format)
153 while (*p != NULL) p = &(*p)->next;
158 int av_match_ext(const char *filename, const char *extensions)
166 ext = strrchr(filename, '.');
172 while (*p != '\0' && *p != ',' && q-ext1<sizeof(ext1)-1)
175 if (!strcasecmp(ext1, ext))
185 static int match_format(const char *name, const char *names)
193 namelen = strlen(name);
194 while ((p = strchr(names, ','))) {
195 len = FFMAX(p - names, namelen);
196 if (!strncasecmp(name, names, len))
200 return !strcasecmp(name, names);
203 #if FF_API_GUESS_FORMAT
204 AVOutputFormat *guess_format(const char *short_name, const char *filename,
205 const char *mime_type)
207 return av_guess_format(short_name, filename, mime_type);
211 AVOutputFormat *av_guess_format(const char *short_name, const char *filename,
212 const char *mime_type)
214 AVOutputFormat *fmt = NULL, *fmt_found;
215 int score_max, score;
217 /* specific test for image sequences */
218 #if CONFIG_IMAGE2_MUXER
219 if (!short_name && filename &&
220 av_filename_number_test(filename) &&
221 ff_guess_image2_codec(filename) != CODEC_ID_NONE) {
222 return av_guess_format("image2", NULL, NULL);
225 /* Find the proper file type. */
228 while ((fmt = av_oformat_next(fmt))) {
230 if (fmt->name && short_name && !strcmp(fmt->name, short_name))
232 if (fmt->mime_type && mime_type && !strcmp(fmt->mime_type, mime_type))
234 if (filename && fmt->extensions &&
235 av_match_ext(filename, fmt->extensions)) {
238 if (score > score_max) {
246 #if FF_API_GUESS_FORMAT
247 AVOutputFormat *guess_stream_format(const char *short_name, const char *filename,
248 const char *mime_type)
250 AVOutputFormat *fmt = av_guess_format(short_name, filename, mime_type);
253 AVOutputFormat *stream_fmt;
254 char stream_format_name[64];
256 snprintf(stream_format_name, sizeof(stream_format_name), "%s_stream", fmt->name);
257 stream_fmt = av_guess_format(stream_format_name, NULL, NULL);
267 enum CodecID av_guess_codec(AVOutputFormat *fmt, const char *short_name,
268 const char *filename, const char *mime_type, enum AVMediaType type){
269 if(type == AVMEDIA_TYPE_VIDEO){
270 enum CodecID codec_id= CODEC_ID_NONE;
272 #if CONFIG_IMAGE2_MUXER
273 if(!strcmp(fmt->name, "image2") || !strcmp(fmt->name, "image2pipe")){
274 codec_id= ff_guess_image2_codec(filename);
277 if(codec_id == CODEC_ID_NONE)
278 codec_id= fmt->video_codec;
280 }else if(type == AVMEDIA_TYPE_AUDIO)
281 return fmt->audio_codec;
282 else if (type == AVMEDIA_TYPE_SUBTITLE)
283 return fmt->subtitle_codec;
285 return CODEC_ID_NONE;
288 AVInputFormat *av_find_input_format(const char *short_name)
290 AVInputFormat *fmt = NULL;
291 while ((fmt = av_iformat_next(fmt))) {
292 if (match_format(short_name, fmt->name))
298 #if FF_API_SYMVER && CONFIG_SHARED && HAVE_SYMVER
299 FF_SYMVER(void, av_destruct_packet_nofree, (AVPacket *pkt), "LIBAVFORMAT_52")
301 av_destruct_packet_nofree(pkt);
304 FF_SYMVER(void, av_destruct_packet, (AVPacket *pkt), "LIBAVFORMAT_52")
306 av_destruct_packet(pkt);
309 FF_SYMVER(int, av_new_packet, (AVPacket *pkt, int size), "LIBAVFORMAT_52")
311 return av_new_packet(pkt, size);
314 FF_SYMVER(int, av_dup_packet, (AVPacket *pkt), "LIBAVFORMAT_52")
316 return av_dup_packet(pkt);
319 FF_SYMVER(void, av_free_packet, (AVPacket *pkt), "LIBAVFORMAT_52")
324 FF_SYMVER(void, av_init_packet, (AVPacket *pkt), "LIBAVFORMAT_52")
326 av_log(NULL, AV_LOG_WARNING, "Diverting av_*_packet function calls to libavcodec. Recompile to improve performance\n");
331 int av_get_packet(AVIOContext *s, AVPacket *pkt, int size)
333 int ret= av_new_packet(pkt, size);
338 pkt->pos= avio_tell(s);
340 ret= avio_read(s, pkt->data, size);
344 av_shrink_packet(pkt, ret);
349 int av_append_packet(AVIOContext *s, AVPacket *pkt, int size)
354 return av_get_packet(s, pkt, size);
355 old_size = pkt->size;
356 ret = av_grow_packet(pkt, size);
359 ret = avio_read(s, pkt->data + old_size, size);
360 av_shrink_packet(pkt, old_size + FFMAX(ret, 0));
365 int av_filename_number_test(const char *filename)
368 return filename && (av_get_frame_filename(buf, sizeof(buf), filename, 1)>=0);
371 AVInputFormat *av_probe_input_format2(AVProbeData *pd, int is_opened, int *score_max)
373 AVProbeData lpd = *pd;
374 AVInputFormat *fmt1 = NULL, *fmt;
377 if (lpd.buf_size > 10 && ff_id3v2_match(lpd.buf, ID3v2_DEFAULT_MAGIC)) {
378 int id3len = ff_id3v2_tag_len(lpd.buf);
379 if (lpd.buf_size > id3len + 16) {
381 lpd.buf_size -= id3len;
387 while ((fmt1 = av_iformat_next(fmt1))) {
388 if (!is_opened == !(fmt1->flags & AVFMT_NOFILE))
391 if (fmt1->read_probe) {
392 score = fmt1->read_probe(&lpd);
393 } else if (fmt1->extensions) {
394 if (av_match_ext(lpd.filename, fmt1->extensions)) {
398 if (score > *score_max) {
401 }else if (score == *score_max)
405 /* a hack for files with huge id3v2 tags -- try to guess by file extension. */
406 if (!fmt && id3 && *score_max < AVPROBE_SCORE_MAX/4) {
407 while ((fmt = av_iformat_next(fmt)))
408 if (fmt->extensions && av_match_ext(lpd.filename, fmt->extensions)) {
409 *score_max = AVPROBE_SCORE_MAX/4;
417 AVInputFormat *av_probe_input_format(AVProbeData *pd, int is_opened){
419 return av_probe_input_format2(pd, is_opened, &score);
422 static int set_codec_from_probe_data(AVFormatContext *s, AVStream *st, AVProbeData *pd, int score)
424 static const struct {
425 const char *name; enum CodecID id; enum AVMediaType type;
427 { "aac" , CODEC_ID_AAC , AVMEDIA_TYPE_AUDIO },
428 { "ac3" , CODEC_ID_AC3 , AVMEDIA_TYPE_AUDIO },
429 { "dts" , CODEC_ID_DTS , AVMEDIA_TYPE_AUDIO },
430 { "eac3" , CODEC_ID_EAC3 , AVMEDIA_TYPE_AUDIO },
431 { "h264" , CODEC_ID_H264 , AVMEDIA_TYPE_VIDEO },
432 { "m4v" , CODEC_ID_MPEG4 , AVMEDIA_TYPE_VIDEO },
433 { "mp3" , CODEC_ID_MP3 , AVMEDIA_TYPE_AUDIO },
434 { "mpegvideo", CODEC_ID_MPEG2VIDEO, AVMEDIA_TYPE_VIDEO },
437 AVInputFormat *fmt = av_probe_input_format2(pd, 1, &score);
441 av_log(s, AV_LOG_DEBUG, "Probe with size=%d, packets=%d detected %s with score=%d\n",
442 pd->buf_size, MAX_PROBE_PACKETS - st->probe_packets, fmt->name, score);
443 for (i = 0; fmt_id_type[i].name; i++) {
444 if (!strcmp(fmt->name, fmt_id_type[i].name)) {
445 st->codec->codec_id = fmt_id_type[i].id;
446 st->codec->codec_type = fmt_id_type[i].type;
454 /************************************************************/
455 /* input media file */
458 * Open a media file from an IO stream. 'fmt' must be specified.
460 int av_open_input_stream(AVFormatContext **ic_ptr,
461 AVIOContext *pb, const char *filename,
462 AVInputFormat *fmt, AVFormatParameters *ap)
466 AVFormatParameters default_ap;
470 memset(ap, 0, sizeof(default_ap));
473 if(!ap->prealloced_context)
474 ic = avformat_alloc_context();
478 err = AVERROR(ENOMEM);
483 ic->duration = AV_NOPTS_VALUE;
484 ic->start_time = AV_NOPTS_VALUE;
485 av_strlcpy(ic->filename, filename, sizeof(ic->filename));
487 /* allocate private data */
488 if (fmt->priv_data_size > 0) {
489 ic->priv_data = av_mallocz(fmt->priv_data_size);
490 if (!ic->priv_data) {
491 err = AVERROR(ENOMEM);
495 ic->priv_data = NULL;
498 // e.g. AVFMT_NOFILE formats will not have a AVIOContext
500 ff_id3v2_read(ic, ID3v2_DEFAULT_MAGIC);
502 if (ic->iformat->read_header) {
503 err = ic->iformat->read_header(ic, ap);
508 if (pb && !ic->data_offset)
509 ic->data_offset = avio_tell(ic->pb);
511 #if FF_API_OLD_METADATA
512 ff_metadata_demux_compat(ic);
515 ic->raw_packet_buffer_remaining_size = RAW_PACKET_BUFFER_SIZE;
522 av_freep(&ic->priv_data);
523 for(i=0;i<ic->nb_streams;i++) {
524 AVStream *st = ic->streams[i];
526 av_free(st->priv_data);
527 av_free(st->codec->extradata);
539 /** size of probe buffer, for guessing file type from file contents */
540 #define PROBE_BUF_MIN 2048
541 #define PROBE_BUF_MAX (1<<20)
543 int av_probe_input_buffer(AVIOContext *pb, AVInputFormat **fmt,
544 const char *filename, void *logctx,
545 unsigned int offset, unsigned int max_probe_size)
547 AVProbeData pd = { filename ? filename : "", NULL, -offset };
548 unsigned char *buf = NULL;
549 int ret = 0, probe_size;
551 if (!max_probe_size) {
552 max_probe_size = PROBE_BUF_MAX;
553 } else if (max_probe_size > PROBE_BUF_MAX) {
554 max_probe_size = PROBE_BUF_MAX;
555 } else if (max_probe_size < PROBE_BUF_MIN) {
556 return AVERROR(EINVAL);
559 if (offset >= max_probe_size) {
560 return AVERROR(EINVAL);
563 for(probe_size= PROBE_BUF_MIN; probe_size<=max_probe_size && !*fmt && ret >= 0;
564 probe_size = FFMIN(probe_size<<1, FFMAX(max_probe_size, probe_size+1))) {
565 int ret, score = probe_size < max_probe_size ? AVPROBE_SCORE_MAX/4 : 0;
566 int buf_offset = (probe_size == PROBE_BUF_MIN) ? 0 : probe_size>>1;
568 if (probe_size < offset) {
572 /* read probe data */
573 buf = av_realloc(buf, probe_size + AVPROBE_PADDING_SIZE);
574 if ((ret = avio_read(pb, buf + buf_offset, probe_size - buf_offset)) < 0) {
575 /* fail if error was not end of file, otherwise, lower score */
576 if (ret != AVERROR_EOF) {
581 ret = 0; /* error was end of file, nothing read */
584 pd.buf = &buf[offset];
586 memset(pd.buf + pd.buf_size, 0, AVPROBE_PADDING_SIZE);
588 /* guess file format */
589 *fmt = av_probe_input_format2(&pd, 1, &score);
591 if(score <= AVPROBE_SCORE_MAX/4){ //this can only be true in the last iteration
592 av_log(logctx, AV_LOG_WARNING, "Format detected only with low score of %d, misdetection possible!\n", score);
594 av_log(logctx, AV_LOG_DEBUG, "Probed with size=%d and score=%d\n", probe_size, score);
600 return AVERROR_INVALIDDATA;
603 /* rewind. reuse probe buffer to avoid seeking */
604 if ((ret = ffio_rewind_with_probe_data(pb, buf, pd.buf_size)) < 0)
610 int av_open_input_file(AVFormatContext **ic_ptr, const char *filename,
613 AVFormatParameters *ap)
616 AVProbeData probe_data, *pd = &probe_data;
617 AVIOContext *pb = NULL;
618 void *logctx= ap && ap->prealloced_context ? *ic_ptr : NULL;
622 pd->filename = filename;
627 /* guess format if no file can be opened */
628 fmt = av_probe_input_format(pd, 0);
631 /* Do not open file if the format does not need it. XXX: specific
632 hack needed to handle RTSP/TCP */
633 if (!fmt || !(fmt->flags & AVFMT_NOFILE)) {
634 /* if no file needed do not try to open one */
635 if ((err=avio_open(&pb, filename, AVIO_RDONLY)) < 0) {
639 ffio_set_buf_size(pb, buf_size);
641 if (!fmt && (err = av_probe_input_buffer(pb, &fmt, filename, logctx, 0, logctx ? (*ic_ptr)->probesize : 0)) < 0) {
646 /* if still no format found, error */
648 err = AVERROR_INVALIDDATA;
652 /* check filename in case an image number is expected */
653 if (fmt->flags & AVFMT_NEEDNUMBER) {
654 if (!av_filename_number_test(filename)) {
655 err = AVERROR_NUMEXPECTED;
659 err = av_open_input_stream(ic_ptr, pb, filename, fmt, ap);
667 if (ap && ap->prealloced_context)
674 /*******************************************************/
676 static AVPacket *add_to_pktbuf(AVPacketList **packet_buffer, AVPacket *pkt,
677 AVPacketList **plast_pktl){
678 AVPacketList *pktl = av_mallocz(sizeof(AVPacketList));
683 (*plast_pktl)->next = pktl;
685 *packet_buffer = pktl;
687 /* add the packet in the buffered packet list */
693 int av_read_packet(AVFormatContext *s, AVPacket *pkt)
699 AVPacketList *pktl = s->raw_packet_buffer;
703 if(s->streams[pkt->stream_index]->codec->codec_id != CODEC_ID_PROBE ||
704 !s->streams[pkt->stream_index]->probe_packets ||
705 s->raw_packet_buffer_remaining_size < pkt->size){
706 AVProbeData *pd = &s->streams[pkt->stream_index]->probe_data;
709 s->raw_packet_buffer = pktl->next;
710 s->raw_packet_buffer_remaining_size += pkt->size;
717 ret= s->iformat->read_packet(s, pkt);
719 if (!pktl || ret == AVERROR(EAGAIN))
721 for (i = 0; i < s->nb_streams; i++)
722 s->streams[i]->probe_packets = 0;
725 st= s->streams[pkt->stream_index];
727 switch(st->codec->codec_type){
728 case AVMEDIA_TYPE_VIDEO:
729 if(s->video_codec_id) st->codec->codec_id= s->video_codec_id;
731 case AVMEDIA_TYPE_AUDIO:
732 if(s->audio_codec_id) st->codec->codec_id= s->audio_codec_id;
734 case AVMEDIA_TYPE_SUBTITLE:
735 if(s->subtitle_codec_id)st->codec->codec_id= s->subtitle_codec_id;
739 if(!pktl && (st->codec->codec_id != CODEC_ID_PROBE ||
743 add_to_pktbuf(&s->raw_packet_buffer, pkt, &s->raw_packet_buffer_end);
744 s->raw_packet_buffer_remaining_size -= pkt->size;
746 if(st->codec->codec_id == CODEC_ID_PROBE){
747 AVProbeData *pd = &st->probe_data;
748 av_log(s, AV_LOG_DEBUG, "probing stream %d\n", st->index);
751 pd->buf = av_realloc(pd->buf, pd->buf_size+pkt->size+AVPROBE_PADDING_SIZE);
752 memcpy(pd->buf+pd->buf_size, pkt->data, pkt->size);
753 pd->buf_size += pkt->size;
754 memset(pd->buf+pd->buf_size, 0, AVPROBE_PADDING_SIZE);
756 if(av_log2(pd->buf_size) != av_log2(pd->buf_size - pkt->size)){
757 //FIXME we dont reduce score to 0 for the case of running out of buffer space in bytes
758 set_codec_from_probe_data(s, st, pd, st->probe_packets > 0 ? AVPROBE_SCORE_MAX/4 : 0);
759 if(st->codec->codec_id != CODEC_ID_PROBE){
762 av_log(s, AV_LOG_DEBUG, "probed stream %d\n", st->index);
769 /**********************************************************/
772 * Get the number of samples of an audio frame. Return -1 on error.
774 static int get_audio_frame_size(AVCodecContext *enc, int size)
778 if(enc->codec_id == CODEC_ID_VORBIS)
781 if (enc->frame_size <= 1) {
782 int bits_per_sample = av_get_bits_per_sample(enc->codec_id);
784 if (bits_per_sample) {
785 if (enc->channels == 0)
787 frame_size = (size << 3) / (bits_per_sample * enc->channels);
789 /* used for example by ADPCM codecs */
790 if (enc->bit_rate == 0)
792 frame_size = ((int64_t)size * 8 * enc->sample_rate) / enc->bit_rate;
795 frame_size = enc->frame_size;
802 * Return the frame duration in seconds. Return 0 if not available.
804 static void compute_frame_duration(int *pnum, int *pden, AVStream *st,
805 AVCodecParserContext *pc, AVPacket *pkt)
811 switch(st->codec->codec_type) {
812 case AVMEDIA_TYPE_VIDEO:
813 if(st->time_base.num*1000LL > st->time_base.den){
814 *pnum = st->time_base.num;
815 *pden = st->time_base.den;
816 }else if(st->codec->time_base.num*1000LL > st->codec->time_base.den){
817 *pnum = st->codec->time_base.num;
818 *pden = st->codec->time_base.den;
819 if (pc && pc->repeat_pict) {
820 *pnum = (*pnum) * (1 + pc->repeat_pict);
822 //If this codec can be interlaced or progressive then we need a parser to compute duration of a packet
823 //Thus if we have no parser in such case leave duration undefined.
824 if(st->codec->ticks_per_frame>1 && !pc){
829 case AVMEDIA_TYPE_AUDIO:
830 frame_size = get_audio_frame_size(st->codec, pkt->size);
831 if (frame_size <= 0 || st->codec->sample_rate <= 0)
834 *pden = st->codec->sample_rate;
841 static int is_intra_only(AVCodecContext *enc){
842 if(enc->codec_type == AVMEDIA_TYPE_AUDIO){
844 }else if(enc->codec_type == AVMEDIA_TYPE_VIDEO){
845 switch(enc->codec_id){
847 case CODEC_ID_MJPEGB:
849 case CODEC_ID_RAWVIDEO:
850 case CODEC_ID_DVVIDEO:
851 case CODEC_ID_HUFFYUV:
852 case CODEC_ID_FFVHUFF:
857 case CODEC_ID_JPEG2000:
865 static void update_initial_timestamps(AVFormatContext *s, int stream_index,
866 int64_t dts, int64_t pts)
868 AVStream *st= s->streams[stream_index];
869 AVPacketList *pktl= s->packet_buffer;
871 if(st->first_dts != AV_NOPTS_VALUE || dts == AV_NOPTS_VALUE || st->cur_dts == AV_NOPTS_VALUE)
874 st->first_dts= dts - st->cur_dts;
877 for(; pktl; pktl= pktl->next){
878 if(pktl->pkt.stream_index != stream_index)
880 //FIXME think more about this check
881 if(pktl->pkt.pts != AV_NOPTS_VALUE && pktl->pkt.pts == pktl->pkt.dts)
882 pktl->pkt.pts += st->first_dts;
884 if(pktl->pkt.dts != AV_NOPTS_VALUE)
885 pktl->pkt.dts += st->first_dts;
887 if(st->start_time == AV_NOPTS_VALUE && pktl->pkt.pts != AV_NOPTS_VALUE)
888 st->start_time= pktl->pkt.pts;
890 if (st->start_time == AV_NOPTS_VALUE)
891 st->start_time = pts;
894 static void update_initial_durations(AVFormatContext *s, AVStream *st, AVPacket *pkt)
896 AVPacketList *pktl= s->packet_buffer;
899 if(st->first_dts != AV_NOPTS_VALUE){
900 cur_dts= st->first_dts;
901 for(; pktl; pktl= pktl->next){
902 if(pktl->pkt.stream_index == pkt->stream_index){
903 if(pktl->pkt.pts != pktl->pkt.dts || pktl->pkt.dts != AV_NOPTS_VALUE || pktl->pkt.duration)
905 cur_dts -= pkt->duration;
908 pktl= s->packet_buffer;
909 st->first_dts = cur_dts;
910 }else if(st->cur_dts)
913 for(; pktl; pktl= pktl->next){
914 if(pktl->pkt.stream_index != pkt->stream_index)
916 if(pktl->pkt.pts == pktl->pkt.dts && pktl->pkt.dts == AV_NOPTS_VALUE
917 && !pktl->pkt.duration){
918 pktl->pkt.dts= cur_dts;
919 if(!st->codec->has_b_frames)
920 pktl->pkt.pts= cur_dts;
921 cur_dts += pkt->duration;
922 pktl->pkt.duration= pkt->duration;
926 if(st->first_dts == AV_NOPTS_VALUE)
927 st->cur_dts= cur_dts;
930 static void compute_pkt_fields(AVFormatContext *s, AVStream *st,
931 AVCodecParserContext *pc, AVPacket *pkt)
933 int num, den, presentation_delayed, delay, i;
936 if (s->flags & AVFMT_FLAG_NOFILLIN)
939 if((s->flags & AVFMT_FLAG_IGNDTS) && pkt->pts != AV_NOPTS_VALUE)
940 pkt->dts= AV_NOPTS_VALUE;
942 if (st->codec->codec_id != CODEC_ID_H264 && pc && pc->pict_type == FF_B_TYPE)
943 //FIXME Set low_delay = 0 when has_b_frames = 1
944 st->codec->has_b_frames = 1;
946 /* do we have a video B-frame ? */
947 delay= st->codec->has_b_frames;
948 presentation_delayed = 0;
950 // ignore delay caused by frame threading so that the mpeg2-without-dts
951 // warning will not trigger
952 if (delay && st->codec->active_thread_type&FF_THREAD_FRAME)
953 delay -= st->codec->thread_count-1;
955 /* XXX: need has_b_frame, but cannot get it if the codec is
958 pc && pc->pict_type != FF_B_TYPE)
959 presentation_delayed = 1;
961 if(pkt->pts != AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE && pkt->dts > pkt->pts && st->pts_wrap_bits<63
962 /*&& pkt->dts-(1LL<<st->pts_wrap_bits) < pkt->pts*/){
963 pkt->dts -= 1LL<<st->pts_wrap_bits;
966 // some mpeg2 in mpeg-ps lack dts (issue171 / input_file.mpg)
967 // we take the conservative approach and discard both
968 // Note, if this is misbehaving for a H.264 file then possibly presentation_delayed is not set correctly.
969 if(delay==1 && pkt->dts == pkt->pts && pkt->dts != AV_NOPTS_VALUE && presentation_delayed){
970 av_log(s, AV_LOG_DEBUG, "invalid dts/pts combination\n");
971 pkt->dts= pkt->pts= AV_NOPTS_VALUE;
974 if (pkt->duration == 0) {
975 compute_frame_duration(&num, &den, st, pc, pkt);
977 pkt->duration = av_rescale_rnd(1, num * (int64_t)st->time_base.den, den * (int64_t)st->time_base.num, AV_ROUND_DOWN);
979 if(pkt->duration != 0 && s->packet_buffer)
980 update_initial_durations(s, st, pkt);
984 /* correct timestamps with byte offset if demuxers only have timestamps
985 on packet boundaries */
986 if(pc && st->need_parsing == AVSTREAM_PARSE_TIMESTAMPS && pkt->size){
987 /* this will estimate bitrate based on this frame's duration and size */
988 offset = av_rescale(pc->offset, pkt->duration, pkt->size);
989 if(pkt->pts != AV_NOPTS_VALUE)
991 if(pkt->dts != AV_NOPTS_VALUE)
995 if (pc && pc->dts_sync_point >= 0) {
996 // we have synchronization info from the parser
997 int64_t den = st->codec->time_base.den * (int64_t) st->time_base.num;
999 int64_t num = st->codec->time_base.num * (int64_t) st->time_base.den;
1000 if (pkt->dts != AV_NOPTS_VALUE) {
1001 // got DTS from the stream, update reference timestamp
1002 st->reference_dts = pkt->dts - pc->dts_ref_dts_delta * num / den;
1003 pkt->pts = pkt->dts + pc->pts_dts_delta * num / den;
1004 } else if (st->reference_dts != AV_NOPTS_VALUE) {
1005 // compute DTS based on reference timestamp
1006 pkt->dts = st->reference_dts + pc->dts_ref_dts_delta * num / den;
1007 pkt->pts = pkt->dts + pc->pts_dts_delta * num / den;
1009 if (pc->dts_sync_point > 0)
1010 st->reference_dts = pkt->dts; // new reference
1014 /* This may be redundant, but it should not hurt. */
1015 if(pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE && pkt->pts > pkt->dts)
1016 presentation_delayed = 1;
1018 // av_log(NULL, AV_LOG_DEBUG, "IN delayed:%d pts:%"PRId64", dts:%"PRId64" cur_dts:%"PRId64" st:%d pc:%p\n", presentation_delayed, pkt->pts, pkt->dts, st->cur_dts, pkt->stream_index, pc);
1019 /* interpolate PTS and DTS if they are not present */
1020 //We skip H264 currently because delay and has_b_frames are not reliably set
1021 if((delay==0 || (delay==1 && pc)) && st->codec->codec_id != CODEC_ID_H264){
1022 if (presentation_delayed) {
1023 /* DTS = decompression timestamp */
1024 /* PTS = presentation timestamp */
1025 if (pkt->dts == AV_NOPTS_VALUE)
1026 pkt->dts = st->last_IP_pts;
1027 update_initial_timestamps(s, pkt->stream_index, pkt->dts, pkt->pts);
1028 if (pkt->dts == AV_NOPTS_VALUE)
1029 pkt->dts = st->cur_dts;
1031 /* this is tricky: the dts must be incremented by the duration
1032 of the frame we are displaying, i.e. the last I- or P-frame */
1033 if (st->last_IP_duration == 0)
1034 st->last_IP_duration = pkt->duration;
1035 if(pkt->dts != AV_NOPTS_VALUE)
1036 st->cur_dts = pkt->dts + st->last_IP_duration;
1037 st->last_IP_duration = pkt->duration;
1038 st->last_IP_pts= pkt->pts;
1039 /* cannot compute PTS if not present (we can compute it only
1040 by knowing the future */
1041 } else if(pkt->pts != AV_NOPTS_VALUE || pkt->dts != AV_NOPTS_VALUE || pkt->duration){
1042 if(pkt->pts != AV_NOPTS_VALUE && pkt->duration){
1043 int64_t old_diff= FFABS(st->cur_dts - pkt->duration - pkt->pts);
1044 int64_t new_diff= FFABS(st->cur_dts - pkt->pts);
1045 if(old_diff < new_diff && old_diff < (pkt->duration>>3)){
1046 pkt->pts += pkt->duration;
1047 // av_log(NULL, AV_LOG_DEBUG, "id:%d old:%"PRId64" new:%"PRId64" dur:%d cur:%"PRId64" size:%d\n", pkt->stream_index, old_diff, new_diff, pkt->duration, st->cur_dts, pkt->size);
1051 /* presentation is not delayed : PTS and DTS are the same */
1052 if(pkt->pts == AV_NOPTS_VALUE)
1053 pkt->pts = pkt->dts;
1054 update_initial_timestamps(s, pkt->stream_index, pkt->pts, pkt->pts);
1055 if(pkt->pts == AV_NOPTS_VALUE)
1056 pkt->pts = st->cur_dts;
1057 pkt->dts = pkt->pts;
1058 if(pkt->pts != AV_NOPTS_VALUE)
1059 st->cur_dts = pkt->pts + pkt->duration;
1063 if(pkt->pts != AV_NOPTS_VALUE && delay <= MAX_REORDER_DELAY){
1064 st->pts_buffer[0]= pkt->pts;
1065 for(i=0; i<delay && st->pts_buffer[i] > st->pts_buffer[i+1]; i++)
1066 FFSWAP(int64_t, st->pts_buffer[i], st->pts_buffer[i+1]);
1067 if(pkt->dts == AV_NOPTS_VALUE)
1068 pkt->dts= st->pts_buffer[0];
1069 if(st->codec->codec_id == CODEC_ID_H264){ //we skiped it above so we try here
1070 update_initial_timestamps(s, pkt->stream_index, pkt->dts, pkt->pts); // this should happen on the first packet
1072 if(pkt->dts > st->cur_dts)
1073 st->cur_dts = pkt->dts;
1076 // av_log(NULL, AV_LOG_ERROR, "OUTdelayed:%d/%d pts:%"PRId64", dts:%"PRId64" cur_dts:%"PRId64"\n", presentation_delayed, delay, pkt->pts, pkt->dts, st->cur_dts);
1079 if(is_intra_only(st->codec))
1080 pkt->flags |= AV_PKT_FLAG_KEY;
1083 /* keyframe computation */
1084 if (pc->key_frame == 1)
1085 pkt->flags |= AV_PKT_FLAG_KEY;
1086 else if (pc->key_frame == -1 && pc->pict_type == FF_I_TYPE)
1087 pkt->flags |= AV_PKT_FLAG_KEY;
1090 pkt->convergence_duration = pc->convergence_duration;
1094 static int av_read_frame_internal(AVFormatContext *s, AVPacket *pkt)
1099 av_init_packet(pkt);
1102 /* select current input stream component */
1105 if (!st->need_parsing || !st->parser) {
1106 /* no parsing needed: we just output the packet as is */
1107 /* raw data support */
1108 *pkt = st->cur_pkt; st->cur_pkt.data= NULL;
1109 compute_pkt_fields(s, st, NULL, pkt);
1111 if ((s->iformat->flags & AVFMT_GENERIC_INDEX) &&
1112 (pkt->flags & AV_PKT_FLAG_KEY) && pkt->dts != AV_NOPTS_VALUE) {
1113 ff_reduce_index(s, st->index);
1114 av_add_index_entry(st, pkt->pos, pkt->dts, 0, 0, AVINDEX_KEYFRAME);
1117 } else if (st->cur_len > 0 && st->discard < AVDISCARD_ALL) {
1118 len = av_parser_parse2(st->parser, st->codec, &pkt->data, &pkt->size,
1119 st->cur_ptr, st->cur_len,
1120 st->cur_pkt.pts, st->cur_pkt.dts,
1122 st->cur_pkt.pts = AV_NOPTS_VALUE;
1123 st->cur_pkt.dts = AV_NOPTS_VALUE;
1124 /* increment read pointer */
1128 /* return packet if any */
1132 pkt->stream_index = st->index;
1133 pkt->pts = st->parser->pts;
1134 pkt->dts = st->parser->dts;
1135 pkt->pos = st->parser->pos;
1136 if(pkt->data == st->cur_pkt.data && pkt->size == st->cur_pkt.size){
1138 pkt->destruct= st->cur_pkt.destruct;
1139 st->cur_pkt.destruct= NULL;
1140 st->cur_pkt.data = NULL;
1141 assert(st->cur_len == 0);
1143 pkt->destruct = NULL;
1145 compute_pkt_fields(s, st, st->parser, pkt);
1147 if((s->iformat->flags & AVFMT_GENERIC_INDEX) && pkt->flags & AV_PKT_FLAG_KEY){
1148 ff_reduce_index(s, st->index);
1149 av_add_index_entry(st, st->parser->frame_offset, pkt->dts,
1150 0, 0, AVINDEX_KEYFRAME);
1157 av_free_packet(&st->cur_pkt);
1162 /* read next packet */
1163 ret = av_read_packet(s, &cur_pkt);
1165 if (ret == AVERROR(EAGAIN))
1167 /* return the last frames, if any */
1168 for(i = 0; i < s->nb_streams; i++) {
1170 if (st->parser && st->need_parsing) {
1171 av_parser_parse2(st->parser, st->codec,
1172 &pkt->data, &pkt->size,
1174 AV_NOPTS_VALUE, AV_NOPTS_VALUE,
1180 /* no more packets: really terminate parsing */
1183 st = s->streams[cur_pkt.stream_index];
1184 st->cur_pkt= cur_pkt;
1186 if(st->cur_pkt.pts != AV_NOPTS_VALUE &&
1187 st->cur_pkt.dts != AV_NOPTS_VALUE &&
1188 st->cur_pkt.pts < st->cur_pkt.dts){
1189 av_log(s, AV_LOG_WARNING, "Invalid timestamps stream=%d, pts=%"PRId64", dts=%"PRId64", size=%d\n",
1190 st->cur_pkt.stream_index,
1194 // av_free_packet(&st->cur_pkt);
1198 if(s->debug & FF_FDEBUG_TS)
1199 av_log(s, AV_LOG_DEBUG, "av_read_packet stream=%d, pts=%"PRId64", dts=%"PRId64", size=%d, duration=%d, flags=%d\n",
1200 st->cur_pkt.stream_index,
1204 st->cur_pkt.duration,
1208 st->cur_ptr = st->cur_pkt.data;
1209 st->cur_len = st->cur_pkt.size;
1210 if (st->need_parsing && !st->parser && !(s->flags & AVFMT_FLAG_NOPARSE)) {
1211 st->parser = av_parser_init(st->codec->codec_id);
1213 /* no parser available: just output the raw packets */
1214 st->need_parsing = AVSTREAM_PARSE_NONE;
1215 }else if(st->need_parsing == AVSTREAM_PARSE_HEADERS){
1216 st->parser->flags |= PARSER_FLAG_COMPLETE_FRAMES;
1217 }else if(st->need_parsing == AVSTREAM_PARSE_FULL_ONCE){
1218 st->parser->flags |= PARSER_FLAG_ONCE;
1223 if(s->debug & FF_FDEBUG_TS)
1224 av_log(s, AV_LOG_DEBUG, "av_read_frame_internal stream=%d, pts=%"PRId64", dts=%"PRId64", size=%d, duration=%d, flags=%d\n",
1235 int av_read_frame(AVFormatContext *s, AVPacket *pkt)
1239 const int genpts= s->flags & AVFMT_FLAG_GENPTS;
1242 pktl = s->packet_buffer;
1244 AVPacket *next_pkt= &pktl->pkt;
1246 if(genpts && next_pkt->dts != AV_NOPTS_VALUE){
1247 int wrap_bits = s->streams[next_pkt->stream_index]->pts_wrap_bits;
1248 while(pktl && next_pkt->pts == AV_NOPTS_VALUE){
1249 if( pktl->pkt.stream_index == next_pkt->stream_index
1250 && (0 > av_compare_mod(next_pkt->dts, pktl->pkt.dts, 2LL << (wrap_bits - 1)))
1251 && av_compare_mod(pktl->pkt.pts, pktl->pkt.dts, 2LL << (wrap_bits - 1))) { //not b frame
1252 next_pkt->pts= pktl->pkt.dts;
1256 pktl = s->packet_buffer;
1259 if( next_pkt->pts != AV_NOPTS_VALUE
1260 || next_pkt->dts == AV_NOPTS_VALUE
1262 /* read packet from packet buffer, if there is data */
1264 s->packet_buffer = pktl->next;
1270 int ret= av_read_frame_internal(s, pkt);
1272 if(pktl && ret != AVERROR(EAGAIN)){
1279 if(av_dup_packet(add_to_pktbuf(&s->packet_buffer, pkt,
1280 &s->packet_buffer_end)) < 0)
1281 return AVERROR(ENOMEM);
1283 assert(!s->packet_buffer);
1284 return av_read_frame_internal(s, pkt);
1289 /* XXX: suppress the packet queue */
1290 static void flush_packet_queue(AVFormatContext *s)
1295 pktl = s->packet_buffer;
1298 s->packet_buffer = pktl->next;
1299 av_free_packet(&pktl->pkt);
1302 while(s->raw_packet_buffer){
1303 pktl = s->raw_packet_buffer;
1304 s->raw_packet_buffer = pktl->next;
1305 av_free_packet(&pktl->pkt);
1308 s->packet_buffer_end=
1309 s->raw_packet_buffer_end= NULL;
1310 s->raw_packet_buffer_remaining_size = RAW_PACKET_BUFFER_SIZE;
1313 /*******************************************************/
1316 int av_find_default_stream_index(AVFormatContext *s)
1318 int first_audio_index = -1;
1322 if (s->nb_streams <= 0)
1324 for(i = 0; i < s->nb_streams; i++) {
1326 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
1329 if (first_audio_index < 0 && st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
1330 first_audio_index = i;
1332 return first_audio_index >= 0 ? first_audio_index : 0;
1336 * Flush the frame reader.
1338 void ff_read_frame_flush(AVFormatContext *s)
1343 flush_packet_queue(s);
1347 /* for each stream, reset read state */
1348 for(i = 0; i < s->nb_streams; i++) {
1352 av_parser_close(st->parser);
1354 av_free_packet(&st->cur_pkt);
1356 st->last_IP_pts = AV_NOPTS_VALUE;
1357 st->cur_dts = AV_NOPTS_VALUE; /* we set the current DTS to an unspecified origin */
1358 st->reference_dts = AV_NOPTS_VALUE;
1363 st->probe_packets = MAX_PROBE_PACKETS;
1365 for(j=0; j<MAX_REORDER_DELAY+1; j++)
1366 st->pts_buffer[j]= AV_NOPTS_VALUE;
1370 void av_update_cur_dts(AVFormatContext *s, AVStream *ref_st, int64_t timestamp){
1373 for(i = 0; i < s->nb_streams; i++) {
1374 AVStream *st = s->streams[i];
1376 st->cur_dts = av_rescale(timestamp,
1377 st->time_base.den * (int64_t)ref_st->time_base.num,
1378 st->time_base.num * (int64_t)ref_st->time_base.den);
1382 void ff_reduce_index(AVFormatContext *s, int stream_index)
1384 AVStream *st= s->streams[stream_index];
1385 unsigned int max_entries= s->max_index_size / sizeof(AVIndexEntry);
1387 if((unsigned)st->nb_index_entries >= max_entries){
1389 for(i=0; 2*i<st->nb_index_entries; i++)
1390 st->index_entries[i]= st->index_entries[2*i];
1391 st->nb_index_entries= i;
1395 int ff_add_index_entry(AVIndexEntry **index_entries,
1396 int *nb_index_entries,
1397 unsigned int *index_entries_allocated_size,
1398 int64_t pos, int64_t timestamp, int size, int distance, int flags)
1400 AVIndexEntry *entries, *ie;
1403 if((unsigned)*nb_index_entries + 1 >= UINT_MAX / sizeof(AVIndexEntry))
1406 entries = av_fast_realloc(*index_entries,
1407 index_entries_allocated_size,
1408 (*nb_index_entries + 1) *
1409 sizeof(AVIndexEntry));
1413 *index_entries= entries;
1415 index= ff_index_search_timestamp(*index_entries, *nb_index_entries, timestamp, AVSEEK_FLAG_ANY);
1418 index= (*nb_index_entries)++;
1419 ie= &entries[index];
1420 assert(index==0 || ie[-1].timestamp < timestamp);
1422 ie= &entries[index];
1423 if(ie->timestamp != timestamp){
1424 if(ie->timestamp <= timestamp)
1426 memmove(entries + index + 1, entries + index, sizeof(AVIndexEntry)*(*nb_index_entries - index));
1427 (*nb_index_entries)++;
1428 }else if(ie->pos == pos && distance < ie->min_distance) //do not reduce the distance
1429 distance= ie->min_distance;
1433 ie->timestamp = timestamp;
1434 ie->min_distance= distance;
1441 int av_add_index_entry(AVStream *st,
1442 int64_t pos, int64_t timestamp, int size, int distance, int flags)
1444 return ff_add_index_entry(&st->index_entries, &st->nb_index_entries,
1445 &st->index_entries_allocated_size, pos,
1446 timestamp, size, distance, flags);
1449 int ff_index_search_timestamp(const AVIndexEntry *entries, int nb_entries,
1450 int64_t wanted_timestamp, int flags)
1458 //optimize appending index entries at the end
1459 if(b && entries[b-1].timestamp < wanted_timestamp)
1464 timestamp = entries[m].timestamp;
1465 if(timestamp >= wanted_timestamp)
1467 if(timestamp <= wanted_timestamp)
1470 m= (flags & AVSEEK_FLAG_BACKWARD) ? a : b;
1472 if(!(flags & AVSEEK_FLAG_ANY)){
1473 while(m>=0 && m<nb_entries && !(entries[m].flags & AVINDEX_KEYFRAME)){
1474 m += (flags & AVSEEK_FLAG_BACKWARD) ? -1 : 1;
1483 int av_index_search_timestamp(AVStream *st, int64_t wanted_timestamp,
1486 return ff_index_search_timestamp(st->index_entries, st->nb_index_entries,
1487 wanted_timestamp, flags);
1492 int av_seek_frame_binary(AVFormatContext *s, int stream_index, int64_t target_ts, int flags){
1493 AVInputFormat *avif= s->iformat;
1494 int64_t av_uninit(pos_min), av_uninit(pos_max), pos, pos_limit;
1495 int64_t ts_min, ts_max, ts;
1500 if (stream_index < 0)
1504 av_log(s, AV_LOG_DEBUG, "read_seek: %d %"PRId64"\n", stream_index, target_ts);
1508 ts_min= AV_NOPTS_VALUE;
1509 pos_limit= -1; //gcc falsely says it may be uninitialized
1511 st= s->streams[stream_index];
1512 if(st->index_entries){
1515 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()
1516 index= FFMAX(index, 0);
1517 e= &st->index_entries[index];
1519 if(e->timestamp <= target_ts || e->pos == e->min_distance){
1521 ts_min= e->timestamp;
1523 av_log(s, AV_LOG_DEBUG, "using cached pos_min=0x%"PRIx64" dts_min=%"PRId64"\n",
1530 index= av_index_search_timestamp(st, target_ts, flags & ~AVSEEK_FLAG_BACKWARD);
1531 assert(index < st->nb_index_entries);
1533 e= &st->index_entries[index];
1534 assert(e->timestamp >= target_ts);
1536 ts_max= e->timestamp;
1537 pos_limit= pos_max - e->min_distance;
1539 av_log(s, AV_LOG_DEBUG, "using cached pos_max=0x%"PRIx64" pos_limit=0x%"PRIx64" dts_max=%"PRId64"\n",
1540 pos_max,pos_limit, ts_max);
1545 pos= av_gen_search(s, stream_index, target_ts, pos_min, pos_max, pos_limit, ts_min, ts_max, flags, &ts, avif->read_timestamp);
1550 if ((ret = avio_seek(s->pb, pos, SEEK_SET)) < 0)
1553 av_update_cur_dts(s, st, ts);
1558 int64_t av_gen_search(AVFormatContext *s, int stream_index, int64_t target_ts, int64_t pos_min, int64_t pos_max, int64_t pos_limit, int64_t ts_min, int64_t ts_max, int flags, int64_t *ts_ret, int64_t (*read_timestamp)(struct AVFormatContext *, int , int64_t *, int64_t )){
1560 int64_t start_pos, filesize;
1564 av_log(s, AV_LOG_DEBUG, "gen_seek: %d %"PRId64"\n", stream_index, target_ts);
1567 if(ts_min == AV_NOPTS_VALUE){
1568 pos_min = s->data_offset;
1569 ts_min = read_timestamp(s, stream_index, &pos_min, INT64_MAX);
1570 if (ts_min == AV_NOPTS_VALUE)
1574 if(ts_max == AV_NOPTS_VALUE){
1576 filesize = avio_size(s->pb);
1577 pos_max = filesize - 1;
1580 ts_max = read_timestamp(s, stream_index, &pos_max, pos_max + step);
1582 }while(ts_max == AV_NOPTS_VALUE && pos_max >= step);
1583 if (ts_max == AV_NOPTS_VALUE)
1587 int64_t tmp_pos= pos_max + 1;
1588 int64_t tmp_ts= read_timestamp(s, stream_index, &tmp_pos, INT64_MAX);
1589 if(tmp_ts == AV_NOPTS_VALUE)
1593 if(tmp_pos >= filesize)
1599 if(ts_min > ts_max){
1601 }else if(ts_min == ts_max){
1606 while (pos_min < pos_limit) {
1608 av_log(s, AV_LOG_DEBUG, "pos_min=0x%"PRIx64" pos_max=0x%"PRIx64" dts_min=%"PRId64" dts_max=%"PRId64"\n",
1612 assert(pos_limit <= pos_max);
1615 int64_t approximate_keyframe_distance= pos_max - pos_limit;
1616 // interpolate position (better than dichotomy)
1617 pos = av_rescale(target_ts - ts_min, pos_max - pos_min, ts_max - ts_min)
1618 + pos_min - approximate_keyframe_distance;
1619 }else if(no_change==1){
1620 // bisection, if interpolation failed to change min or max pos last time
1621 pos = (pos_min + pos_limit)>>1;
1623 /* linear search if bisection failed, can only happen if there
1624 are very few or no keyframes between min/max */
1629 else if(pos > pos_limit)
1633 ts = read_timestamp(s, stream_index, &pos, INT64_MAX); //may pass pos_limit instead of -1
1639 av_log(s, AV_LOG_DEBUG, "%"PRId64" %"PRId64" %"PRId64" / %"PRId64" %"PRId64" %"PRId64" target:%"PRId64" limit:%"PRId64" start:%"PRId64" noc:%d\n",
1640 pos_min, pos, pos_max, ts_min, ts, ts_max, target_ts, pos_limit,
1641 start_pos, no_change);
1643 if(ts == AV_NOPTS_VALUE){
1644 av_log(s, AV_LOG_ERROR, "read_timestamp() failed in the middle\n");
1647 assert(ts != AV_NOPTS_VALUE);
1648 if (target_ts <= ts) {
1649 pos_limit = start_pos - 1;
1653 if (target_ts >= ts) {
1659 pos = (flags & AVSEEK_FLAG_BACKWARD) ? pos_min : pos_max;
1660 ts = (flags & AVSEEK_FLAG_BACKWARD) ? ts_min : ts_max;
1663 ts_min = read_timestamp(s, stream_index, &pos_min, INT64_MAX);
1665 ts_max = read_timestamp(s, stream_index, &pos_min, INT64_MAX);
1666 av_log(s, AV_LOG_DEBUG, "pos=0x%"PRIx64" %"PRId64"<=%"PRId64"<=%"PRId64"\n",
1667 pos, ts_min, target_ts, ts_max);
1673 static int av_seek_frame_byte(AVFormatContext *s, int stream_index, int64_t pos, int flags){
1674 int64_t pos_min, pos_max;
1678 if (stream_index < 0)
1681 st= s->streams[stream_index];
1684 pos_min = s->data_offset;
1685 pos_max = avio_size(s->pb) - 1;
1687 if (pos < pos_min) pos= pos_min;
1688 else if(pos > pos_max) pos= pos_max;
1690 avio_seek(s->pb, pos, SEEK_SET);
1693 av_update_cur_dts(s, st, ts);
1698 static int av_seek_frame_generic(AVFormatContext *s,
1699 int stream_index, int64_t timestamp, int flags)
1706 st = s->streams[stream_index];
1708 index = av_index_search_timestamp(st, timestamp, flags);
1710 if(index < 0 && st->nb_index_entries && timestamp < st->index_entries[0].timestamp)
1713 if(index < 0 || index==st->nb_index_entries-1){
1717 if(st->nb_index_entries){
1718 assert(st->index_entries);
1719 ie= &st->index_entries[st->nb_index_entries-1];
1720 if ((ret = avio_seek(s->pb, ie->pos, SEEK_SET)) < 0)
1722 av_update_cur_dts(s, st, ie->timestamp);
1724 if ((ret = avio_seek(s->pb, s->data_offset, SEEK_SET)) < 0)
1730 ret = av_read_frame(s, &pkt);
1731 }while(ret == AVERROR(EAGAIN));
1734 av_free_packet(&pkt);
1735 if(stream_index == pkt.stream_index){
1736 if((pkt.flags & AV_PKT_FLAG_KEY) && pkt.dts > timestamp)
1740 index = av_index_search_timestamp(st, timestamp, flags);
1745 ff_read_frame_flush(s);
1746 if (s->iformat->read_seek){
1747 if(s->iformat->read_seek(s, stream_index, timestamp, flags) >= 0)
1750 ie = &st->index_entries[index];
1751 if ((ret = avio_seek(s->pb, ie->pos, SEEK_SET)) < 0)
1753 av_update_cur_dts(s, st, ie->timestamp);
1758 int av_seek_frame(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
1763 ff_read_frame_flush(s);
1765 if(flags & AVSEEK_FLAG_BYTE)
1766 return av_seek_frame_byte(s, stream_index, timestamp, flags);
1768 if(stream_index < 0){
1769 stream_index= av_find_default_stream_index(s);
1770 if(stream_index < 0)
1773 st= s->streams[stream_index];
1774 /* timestamp for default must be expressed in AV_TIME_BASE units */
1775 timestamp = av_rescale(timestamp, st->time_base.den, AV_TIME_BASE * (int64_t)st->time_base.num);
1778 /* first, we try the format specific seek */
1779 if (s->iformat->read_seek)
1780 ret = s->iformat->read_seek(s, stream_index, timestamp, flags);
1787 if(s->iformat->read_timestamp)
1788 return av_seek_frame_binary(s, stream_index, timestamp, flags);
1790 return av_seek_frame_generic(s, stream_index, timestamp, flags);
1793 int avformat_seek_file(AVFormatContext *s, int stream_index, int64_t min_ts, int64_t ts, int64_t max_ts, int flags)
1795 if(min_ts > ts || max_ts < ts)
1798 ff_read_frame_flush(s);
1800 if (s->iformat->read_seek2)
1801 return s->iformat->read_seek2(s, stream_index, min_ts, ts, max_ts, flags);
1803 if(s->iformat->read_timestamp){
1804 //try to seek via read_timestamp()
1807 //Fallback to old API if new is not implemented but old is
1808 //Note the old has somewat different sematics
1809 if(s->iformat->read_seek || 1)
1810 return av_seek_frame(s, stream_index, ts, flags | (ts - min_ts > (uint64_t)(max_ts - ts) ? AVSEEK_FLAG_BACKWARD : 0));
1812 // try some generic seek like av_seek_frame_generic() but with new ts semantics
1815 /*******************************************************/
1818 * Return TRUE if the stream has accurate duration in any stream.
1820 * @return TRUE if the stream has accurate duration for at least one component.
1822 static int av_has_duration(AVFormatContext *ic)
1827 for(i = 0;i < ic->nb_streams; i++) {
1828 st = ic->streams[i];
1829 if (st->duration != AV_NOPTS_VALUE)
1836 * Estimate the stream timings from the one of each components.
1838 * Also computes the global bitrate if possible.
1840 static void av_update_stream_timings(AVFormatContext *ic)
1842 int64_t start_time, start_time1, end_time, end_time1;
1843 int64_t duration, duration1;
1847 start_time = INT64_MAX;
1848 end_time = INT64_MIN;
1849 duration = INT64_MIN;
1850 for(i = 0;i < ic->nb_streams; i++) {
1851 st = ic->streams[i];
1852 if (st->start_time != AV_NOPTS_VALUE && st->time_base.den) {
1853 start_time1= av_rescale_q(st->start_time, st->time_base, AV_TIME_BASE_Q);
1854 if (start_time1 < start_time)
1855 start_time = start_time1;
1856 if (st->duration != AV_NOPTS_VALUE) {
1857 end_time1 = start_time1
1858 + av_rescale_q(st->duration, st->time_base, AV_TIME_BASE_Q);
1859 if (end_time1 > end_time)
1860 end_time = end_time1;
1863 if (st->duration != AV_NOPTS_VALUE) {
1864 duration1 = av_rescale_q(st->duration, st->time_base, AV_TIME_BASE_Q);
1865 if (duration1 > duration)
1866 duration = duration1;
1869 if (start_time != INT64_MAX) {
1870 ic->start_time = start_time;
1871 if (end_time != INT64_MIN) {
1872 if (end_time - start_time > duration)
1873 duration = end_time - start_time;
1876 if (duration != INT64_MIN) {
1877 ic->duration = duration;
1878 if (ic->file_size > 0) {
1879 /* compute the bitrate */
1880 ic->bit_rate = (double)ic->file_size * 8.0 * AV_TIME_BASE /
1881 (double)ic->duration;
1886 static void fill_all_stream_timings(AVFormatContext *ic)
1891 av_update_stream_timings(ic);
1892 for(i = 0;i < ic->nb_streams; i++) {
1893 st = ic->streams[i];
1894 if (st->start_time == AV_NOPTS_VALUE) {
1895 if(ic->start_time != AV_NOPTS_VALUE)
1896 st->start_time = av_rescale_q(ic->start_time, AV_TIME_BASE_Q, st->time_base);
1897 if(ic->duration != AV_NOPTS_VALUE)
1898 st->duration = av_rescale_q(ic->duration, AV_TIME_BASE_Q, st->time_base);
1903 static void av_estimate_timings_from_bit_rate(AVFormatContext *ic)
1905 int64_t filesize, duration;
1909 /* if bit_rate is already set, we believe it */
1910 if (ic->bit_rate <= 0) {
1912 for(i=0;i<ic->nb_streams;i++) {
1913 st = ic->streams[i];
1914 if (st->codec->bit_rate > 0)
1915 bit_rate += st->codec->bit_rate;
1917 ic->bit_rate = bit_rate;
1920 /* if duration is already set, we believe it */
1921 if (ic->duration == AV_NOPTS_VALUE &&
1922 ic->bit_rate != 0 &&
1923 ic->file_size != 0) {
1924 filesize = ic->file_size;
1926 for(i = 0; i < ic->nb_streams; i++) {
1927 st = ic->streams[i];
1928 duration= av_rescale(8*filesize, st->time_base.den, ic->bit_rate*(int64_t)st->time_base.num);
1929 if (st->duration == AV_NOPTS_VALUE)
1930 st->duration = duration;
1936 #define DURATION_MAX_READ_SIZE 250000
1937 #define DURATION_MAX_RETRY 3
1939 /* only usable for MPEG-PS streams */
1940 static void av_estimate_timings_from_pts(AVFormatContext *ic, int64_t old_offset)
1942 AVPacket pkt1, *pkt = &pkt1;
1944 int read_size, i, ret;
1946 int64_t filesize, offset, duration;
1951 /* flush packet queue */
1952 flush_packet_queue(ic);
1954 for (i=0; i<ic->nb_streams; i++) {
1955 st = ic->streams[i];
1956 if (st->start_time == AV_NOPTS_VALUE && st->first_dts == AV_NOPTS_VALUE)
1957 av_log(st->codec, AV_LOG_WARNING, "start time is not set in av_estimate_timings_from_pts\n");
1960 av_parser_close(st->parser);
1962 av_free_packet(&st->cur_pkt);
1966 /* estimate the end time (duration) */
1967 /* XXX: may need to support wrapping */
1968 filesize = ic->file_size;
1969 end_time = AV_NOPTS_VALUE;
1971 offset = filesize - (DURATION_MAX_READ_SIZE<<retry);
1975 avio_seek(ic->pb, offset, SEEK_SET);
1978 if (read_size >= DURATION_MAX_READ_SIZE<<(FFMAX(retry-1,0)))
1982 ret = av_read_packet(ic, pkt);
1983 }while(ret == AVERROR(EAGAIN));
1986 read_size += pkt->size;
1987 st = ic->streams[pkt->stream_index];
1988 if (pkt->pts != AV_NOPTS_VALUE &&
1989 (st->start_time != AV_NOPTS_VALUE ||
1990 st->first_dts != AV_NOPTS_VALUE)) {
1991 duration = end_time = pkt->pts;
1992 if (st->start_time != AV_NOPTS_VALUE) duration -= st->start_time;
1993 else duration -= st->first_dts;
1995 duration += 1LL<<st->pts_wrap_bits;
1997 if (st->duration == AV_NOPTS_VALUE ||
1998 st->duration < duration)
1999 st->duration = duration;
2002 av_free_packet(pkt);
2004 }while( end_time==AV_NOPTS_VALUE
2005 && filesize > (DURATION_MAX_READ_SIZE<<retry)
2006 && ++retry <= DURATION_MAX_RETRY);
2008 fill_all_stream_timings(ic);
2010 avio_seek(ic->pb, old_offset, SEEK_SET);
2011 for (i=0; i<ic->nb_streams; i++) {
2013 st->cur_dts= st->first_dts;
2014 st->last_IP_pts = AV_NOPTS_VALUE;
2018 static void av_estimate_timings(AVFormatContext *ic, int64_t old_offset)
2022 /* get the file size, if possible */
2023 if (ic->iformat->flags & AVFMT_NOFILE) {
2026 file_size = avio_size(ic->pb);
2030 ic->file_size = file_size;
2032 if ((!strcmp(ic->iformat->name, "mpeg") ||
2033 !strcmp(ic->iformat->name, "mpegts")) &&
2034 file_size && ic->pb->seekable) {
2035 /* get accurate estimate from the PTSes */
2036 av_estimate_timings_from_pts(ic, old_offset);
2037 } else if (av_has_duration(ic)) {
2038 /* at least one component has timings - we use them for all
2040 fill_all_stream_timings(ic);
2042 av_log(ic, AV_LOG_WARNING, "Estimating duration from bitrate, this may be inaccurate\n");
2043 /* less precise: use bitrate info */
2044 av_estimate_timings_from_bit_rate(ic);
2046 av_update_stream_timings(ic);
2052 for(i = 0;i < ic->nb_streams; i++) {
2053 st = ic->streams[i];
2054 printf("%d: start_time: %0.3f duration: %0.3f\n",
2055 i, (double)st->start_time / AV_TIME_BASE,
2056 (double)st->duration / AV_TIME_BASE);
2058 printf("stream: start_time: %0.3f duration: %0.3f bitrate=%d kb/s\n",
2059 (double)ic->start_time / AV_TIME_BASE,
2060 (double)ic->duration / AV_TIME_BASE,
2061 ic->bit_rate / 1000);
2066 static int has_codec_parameters(AVCodecContext *enc)
2069 switch(enc->codec_type) {
2070 case AVMEDIA_TYPE_AUDIO:
2071 val = enc->sample_rate && enc->channels && enc->sample_fmt != AV_SAMPLE_FMT_NONE;
2072 if(!enc->frame_size &&
2073 (enc->codec_id == CODEC_ID_VORBIS ||
2074 enc->codec_id == CODEC_ID_AAC ||
2075 enc->codec_id == CODEC_ID_MP1 ||
2076 enc->codec_id == CODEC_ID_MP2 ||
2077 enc->codec_id == CODEC_ID_MP3 ||
2078 enc->codec_id == CODEC_ID_SPEEX))
2081 case AVMEDIA_TYPE_VIDEO:
2082 val = enc->width && enc->pix_fmt != PIX_FMT_NONE;
2088 return enc->codec_id != CODEC_ID_NONE && val != 0;
2091 static int has_decode_delay_been_guessed(AVStream *st)
2093 return st->codec->codec_id != CODEC_ID_H264 ||
2094 st->codec_info_nb_frames >= 6 + st->codec->has_b_frames;
2097 static int try_decode_frame(AVStream *st, AVPacket *avpkt)
2101 int got_picture, data_size, ret=0;
2104 if(!st->codec->codec){
2105 codec = avcodec_find_decoder(st->codec->codec_id);
2108 ret = avcodec_open(st->codec, codec);
2113 if(!has_codec_parameters(st->codec) || !has_decode_delay_been_guessed(st)){
2114 switch(st->codec->codec_type) {
2115 case AVMEDIA_TYPE_VIDEO:
2116 avcodec_get_frame_defaults(&picture);
2117 ret = avcodec_decode_video2(st->codec, &picture,
2118 &got_picture, avpkt);
2120 case AVMEDIA_TYPE_AUDIO:
2121 data_size = FFMAX(avpkt->size, AVCODEC_MAX_AUDIO_FRAME_SIZE);
2122 samples = av_malloc(data_size);
2125 ret = avcodec_decode_audio3(st->codec, samples,
2137 unsigned int ff_codec_get_tag(const AVCodecTag *tags, enum CodecID id)
2139 while (tags->id != CODEC_ID_NONE) {
2147 enum CodecID ff_codec_get_id(const AVCodecTag *tags, unsigned int tag)
2150 for(i=0; tags[i].id != CODEC_ID_NONE;i++) {
2151 if(tag == tags[i].tag)
2154 for(i=0; tags[i].id != CODEC_ID_NONE; i++) {
2155 if (ff_toupper4(tag) == ff_toupper4(tags[i].tag))
2158 return CODEC_ID_NONE;
2161 unsigned int av_codec_get_tag(const AVCodecTag * const *tags, enum CodecID id)
2164 for(i=0; tags && tags[i]; i++){
2165 int tag= ff_codec_get_tag(tags[i], id);
2171 enum CodecID av_codec_get_id(const AVCodecTag * const *tags, unsigned int tag)
2174 for(i=0; tags && tags[i]; i++){
2175 enum CodecID id= ff_codec_get_id(tags[i], tag);
2176 if(id!=CODEC_ID_NONE) return id;
2178 return CODEC_ID_NONE;
2181 static void compute_chapters_end(AVFormatContext *s)
2184 int64_t max_time = s->duration + (s->start_time == AV_NOPTS_VALUE) ? 0 : s->start_time;
2186 for (i = 0; i < s->nb_chapters; i++)
2187 if (s->chapters[i]->end == AV_NOPTS_VALUE) {
2188 AVChapter *ch = s->chapters[i];
2189 int64_t end = max_time ? av_rescale_q(max_time, AV_TIME_BASE_Q, ch->time_base)
2192 for (j = 0; j < s->nb_chapters; j++) {
2193 AVChapter *ch1 = s->chapters[j];
2194 int64_t next_start = av_rescale_q(ch1->start, ch1->time_base, ch->time_base);
2195 if (j != i && next_start > ch->start && next_start < end)
2198 ch->end = (end == INT64_MAX) ? ch->start : end;
2202 static int get_std_framerate(int i){
2203 if(i<60*12) return i*1001;
2204 else return ((const int[]){24,30,60,12,15})[i-60*12]*1000*12;
2208 * Is the time base unreliable.
2209 * This is a heuristic to balance between quick acceptance of the values in
2210 * the headers vs. some extra checks.
2211 * Old DivX and Xvid often have nonsense timebases like 1fps or 2fps.
2212 * MPEG-2 commonly misuses field repeat flags to store different framerates.
2213 * And there are "variable" fps files this needs to detect as well.
2215 static int tb_unreliable(AVCodecContext *c){
2216 if( c->time_base.den >= 101L*c->time_base.num
2217 || c->time_base.den < 5L*c->time_base.num
2218 /* || c->codec_tag == AV_RL32("DIVX")
2219 || c->codec_tag == AV_RL32("XVID")*/
2220 || c->codec_id == CODEC_ID_MPEG2VIDEO
2221 || c->codec_id == CODEC_ID_H264
2227 int av_find_stream_info(AVFormatContext *ic)
2229 int i, count, ret, read_size, j;
2231 AVPacket pkt1, *pkt;
2232 int64_t old_offset = avio_tell(ic->pb);
2234 for(i=0;i<ic->nb_streams;i++) {
2236 st = ic->streams[i];
2237 if (st->codec->codec_id == CODEC_ID_AAC) {
2238 st->codec->sample_rate = 0;
2239 st->codec->frame_size = 0;
2240 st->codec->channels = 0;
2242 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO ||
2243 st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
2244 /* if(!st->time_base.num)
2246 if(!st->codec->time_base.num)
2247 st->codec->time_base= st->time_base;
2249 //only for the split stuff
2250 if (!st->parser && !(ic->flags & AVFMT_FLAG_NOPARSE)) {
2251 st->parser = av_parser_init(st->codec->codec_id);
2252 if(st->need_parsing == AVSTREAM_PARSE_HEADERS && st->parser){
2253 st->parser->flags |= PARSER_FLAG_COMPLETE_FRAMES;
2256 assert(!st->codec->codec);
2257 codec = avcodec_find_decoder(st->codec->codec_id);
2259 /* Force decoding of at least one frame of codec data
2260 * this makes sure the codec initializes the channel configuration
2261 * and does not trust the values from the container.
2263 if (codec && codec->capabilities & CODEC_CAP_CHANNEL_CONF)
2264 st->codec->channels = 0;
2266 /* Ensure that subtitle_header is properly set. */
2267 if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE
2268 && codec && !st->codec->codec)
2269 avcodec_open(st->codec, codec);
2271 //try to just open decoders, in case this is enough to get parameters
2272 if(!has_codec_parameters(st->codec)){
2273 if (codec && !st->codec->codec)
2274 avcodec_open(st->codec, codec);
2278 for (i=0; i<ic->nb_streams; i++) {
2279 ic->streams[i]->info->last_dts = AV_NOPTS_VALUE;
2285 if(url_interrupt_cb()){
2287 av_log(ic, AV_LOG_DEBUG, "interrupted\n");
2291 /* check if one codec still needs to be handled */
2292 for(i=0;i<ic->nb_streams;i++) {
2293 st = ic->streams[i];
2294 if (!has_codec_parameters(st->codec))
2296 /* variable fps and no guess at the real fps */
2297 if( tb_unreliable(st->codec) && !(st->r_frame_rate.num && st->avg_frame_rate.num)
2298 && st->info->duration_count<20 && st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
2300 if(st->parser && st->parser->parser->split && !st->codec->extradata)
2302 if(st->first_dts == AV_NOPTS_VALUE)
2305 if (i == ic->nb_streams) {
2306 /* NOTE: if the format has no header, then we need to read
2307 some packets to get most of the streams, so we cannot
2309 if (!(ic->ctx_flags & AVFMTCTX_NOHEADER)) {
2310 /* if we found the info for all the codecs, we can stop */
2312 av_log(ic, AV_LOG_DEBUG, "All info found\n");
2316 /* we did not get all the codec info, but we read too much data */
2317 if (read_size >= ic->probesize) {
2319 av_log(ic, AV_LOG_DEBUG, "Probe buffer size limit %d reached\n", ic->probesize);
2323 /* NOTE: a new stream can be added there if no header in file
2324 (AVFMTCTX_NOHEADER) */
2325 ret = av_read_frame_internal(ic, &pkt1);
2326 if (ret < 0 && ret != AVERROR(EAGAIN)) {
2328 ret = -1; /* we could not have all the codec parameters before EOF */
2329 for(i=0;i<ic->nb_streams;i++) {
2330 st = ic->streams[i];
2331 if (!has_codec_parameters(st->codec)){
2333 avcodec_string(buf, sizeof(buf), st->codec, 0);
2334 av_log(ic, AV_LOG_WARNING, "Could not find codec parameters (%s)\n", buf);
2342 if (ret == AVERROR(EAGAIN))
2345 pkt= add_to_pktbuf(&ic->packet_buffer, &pkt1, &ic->packet_buffer_end);
2346 if ((ret = av_dup_packet(pkt)) < 0)
2347 goto find_stream_info_err;
2349 read_size += pkt->size;
2351 st = ic->streams[pkt->stream_index];
2352 if (st->codec_info_nb_frames>1) {
2353 if (st->time_base.den > 0 && av_rescale_q(st->info->codec_info_duration, st->time_base, AV_TIME_BASE_Q) >= ic->max_analyze_duration) {
2354 av_log(ic, AV_LOG_WARNING, "max_analyze_duration reached\n");
2357 st->info->codec_info_duration += pkt->duration;
2360 int64_t last = st->info->last_dts;
2361 int64_t duration= pkt->dts - last;
2363 if(pkt->dts != AV_NOPTS_VALUE && last != AV_NOPTS_VALUE && duration>0){
2364 double dur= duration * av_q2d(st->time_base);
2366 // if(st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
2367 // av_log(NULL, AV_LOG_ERROR, "%f\n", dur);
2368 if (st->info->duration_count < 2)
2369 memset(st->info->duration_error, 0, sizeof(st->info->duration_error));
2370 for (i=1; i<FF_ARRAY_ELEMS(st->info->duration_error); i++) {
2371 int framerate= get_std_framerate(i);
2372 int ticks= lrintf(dur*framerate/(1001*12));
2373 double error= dur - ticks*1001*12/(double)framerate;
2374 st->info->duration_error[i] += error*error;
2376 st->info->duration_count++;
2377 // ignore the first 4 values, they might have some random jitter
2378 if (st->info->duration_count > 3)
2379 st->info->duration_gcd = av_gcd(st->info->duration_gcd, duration);
2381 if (last == AV_NOPTS_VALUE || st->info->duration_count <= 1)
2382 st->info->last_dts = pkt->dts;
2384 if(st->parser && st->parser->parser->split && !st->codec->extradata){
2385 int i= st->parser->parser->split(st->codec, pkt->data, pkt->size);
2387 st->codec->extradata_size= i;
2388 st->codec->extradata= av_malloc(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
2389 memcpy(st->codec->extradata, pkt->data, st->codec->extradata_size);
2390 memset(st->codec->extradata + i, 0, FF_INPUT_BUFFER_PADDING_SIZE);
2394 /* if still no information, we try to open the codec and to
2395 decompress the frame. We try to avoid that in most cases as
2396 it takes longer and uses more memory. For MPEG-4, we need to
2397 decompress for QuickTime. */
2398 if (!has_codec_parameters(st->codec) || !has_decode_delay_been_guessed(st))
2399 try_decode_frame(st, pkt);
2401 st->codec_info_nb_frames++;
2405 // close codecs which were opened in try_decode_frame()
2406 for(i=0;i<ic->nb_streams;i++) {
2407 st = ic->streams[i];
2408 if(st->codec->codec)
2409 avcodec_close(st->codec);
2411 for(i=0;i<ic->nb_streams;i++) {
2412 st = ic->streams[i];
2413 if (st->codec_info_nb_frames>2 && !st->avg_frame_rate.num && st->info->codec_info_duration)
2414 av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
2415 (st->codec_info_nb_frames-2)*(int64_t)st->time_base.den,
2416 st->info->codec_info_duration*(int64_t)st->time_base.num, 60000);
2417 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
2418 if(st->codec->codec_id == CODEC_ID_RAWVIDEO && !st->codec->codec_tag && !st->codec->bits_per_coded_sample)
2419 st->codec->codec_tag= avcodec_pix_fmt_to_codec_tag(st->codec->pix_fmt);
2421 // the check for tb_unreliable() is not completely correct, since this is not about handling
2422 // a unreliable/inexact time base, but a time base that is finer than necessary, as e.g.
2423 // ipmovie.c produces.
2424 if (tb_unreliable(st->codec) && st->info->duration_count > 15 && st->info->duration_gcd > 1 && !st->r_frame_rate.num)
2425 av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den, st->time_base.den, st->time_base.num * st->info->duration_gcd, INT_MAX);
2426 if (st->info->duration_count && !st->r_frame_rate.num
2427 && tb_unreliable(st->codec) /*&&
2428 //FIXME we should not special-case MPEG-2, but this needs testing with non-MPEG-2 ...
2429 st->time_base.num*duration_sum[i]/st->info->duration_count*101LL > st->time_base.den*/){
2431 double best_error= 2*av_q2d(st->time_base);
2432 best_error = best_error*best_error*st->info->duration_count*1000*12*30;
2434 for (j=1; j<FF_ARRAY_ELEMS(st->info->duration_error); j++) {
2435 double error = st->info->duration_error[j] * get_std_framerate(j);
2436 // if(st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
2437 // av_log(NULL, AV_LOG_ERROR, "%f %f\n", get_std_framerate(j) / 12.0/1001, error);
2438 if(error < best_error){
2440 num = get_std_framerate(j);
2443 // do not increase frame rate by more than 1 % in order to match a standard rate.
2444 if (num && (!st->r_frame_rate.num || (double)num/(12*1001) < 1.01 * av_q2d(st->r_frame_rate)))
2445 av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den, num, 12*1001, INT_MAX);
2448 if (!st->r_frame_rate.num){
2449 if( st->codec->time_base.den * (int64_t)st->time_base.num
2450 <= st->codec->time_base.num * st->codec->ticks_per_frame * (int64_t)st->time_base.den){
2451 st->r_frame_rate.num = st->codec->time_base.den;
2452 st->r_frame_rate.den = st->codec->time_base.num * st->codec->ticks_per_frame;
2454 st->r_frame_rate.num = st->time_base.den;
2455 st->r_frame_rate.den = st->time_base.num;
2458 }else if(st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
2459 if(!st->codec->bits_per_coded_sample)
2460 st->codec->bits_per_coded_sample= av_get_bits_per_sample(st->codec->codec_id);
2461 // set stream disposition based on audio service type
2462 switch (st->codec->audio_service_type) {
2463 case AV_AUDIO_SERVICE_TYPE_EFFECTS:
2464 st->disposition = AV_DISPOSITION_CLEAN_EFFECTS; break;
2465 case AV_AUDIO_SERVICE_TYPE_VISUALLY_IMPAIRED:
2466 st->disposition = AV_DISPOSITION_VISUAL_IMPAIRED; break;
2467 case AV_AUDIO_SERVICE_TYPE_HEARING_IMPAIRED:
2468 st->disposition = AV_DISPOSITION_HEARING_IMPAIRED; break;
2469 case AV_AUDIO_SERVICE_TYPE_COMMENTARY:
2470 st->disposition = AV_DISPOSITION_COMMENT; break;
2471 case AV_AUDIO_SERVICE_TYPE_KARAOKE:
2472 st->disposition = AV_DISPOSITION_KARAOKE; break;
2477 av_estimate_timings(ic, old_offset);
2479 compute_chapters_end(ic);
2482 /* correct DTS for B-frame streams with no timestamps */
2483 for(i=0;i<ic->nb_streams;i++) {
2484 st = ic->streams[i];
2485 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
2487 ppktl = &ic->packet_buffer;
2489 if(ppkt1->stream_index != i)
2491 if(ppkt1->pkt->dts < 0)
2493 if(ppkt1->pkt->pts != AV_NOPTS_VALUE)
2495 ppkt1->pkt->dts -= delta;
2500 st->cur_dts -= delta;
2506 find_stream_info_err:
2507 for (i=0; i < ic->nb_streams; i++)
2508 av_freep(&ic->streams[i]->info);
2512 static AVProgram *find_program_from_stream(AVFormatContext *ic, int s)
2516 for (i = 0; i < ic->nb_programs; i++)
2517 for (j = 0; j < ic->programs[i]->nb_stream_indexes; j++)
2518 if (ic->programs[i]->stream_index[j] == s)
2519 return ic->programs[i];
2523 int av_find_best_stream(AVFormatContext *ic,
2524 enum AVMediaType type,
2525 int wanted_stream_nb,
2527 AVCodec **decoder_ret,
2530 int i, nb_streams = ic->nb_streams, stream_number = 0;
2531 int ret = AVERROR_STREAM_NOT_FOUND, best_count = -1;
2532 unsigned *program = NULL;
2533 AVCodec *decoder = NULL, *best_decoder = NULL;
2535 if (related_stream >= 0 && wanted_stream_nb < 0) {
2536 AVProgram *p = find_program_from_stream(ic, related_stream);
2538 program = p->stream_index;
2539 nb_streams = p->nb_stream_indexes;
2542 for (i = 0; i < nb_streams; i++) {
2543 AVStream *st = ic->streams[program ? program[i] : i];
2544 AVCodecContext *avctx = st->codec;
2545 if (avctx->codec_type != type)
2547 if (wanted_stream_nb >= 0 && stream_number++ != wanted_stream_nb)
2549 if (st->disposition & (AV_DISPOSITION_HEARING_IMPAIRED|AV_DISPOSITION_VISUAL_IMPAIRED))
2552 decoder = avcodec_find_decoder(ic->streams[i]->codec->codec_id);
2555 ret = AVERROR_DECODER_NOT_FOUND;
2559 if (best_count >= st->codec_info_nb_frames)
2561 best_count = st->codec_info_nb_frames;
2562 ret = program ? program[i] : i;
2563 best_decoder = decoder;
2564 if (program && i == nb_streams - 1 && ret < 0) {
2566 nb_streams = ic->nb_streams;
2567 i = 0; /* no related stream found, try again with everything */
2571 *decoder_ret = best_decoder;
2575 /*******************************************************/
2577 int av_read_play(AVFormatContext *s)
2579 if (s->iformat->read_play)
2580 return s->iformat->read_play(s);
2582 return avio_pause(s->pb, 0);
2583 return AVERROR(ENOSYS);
2586 int av_read_pause(AVFormatContext *s)
2588 if (s->iformat->read_pause)
2589 return s->iformat->read_pause(s);
2591 return avio_pause(s->pb, 1);
2592 return AVERROR(ENOSYS);
2595 void av_close_input_stream(AVFormatContext *s)
2597 flush_packet_queue(s);
2598 if (s->iformat->read_close)
2599 s->iformat->read_close(s);
2600 avformat_free_context(s);
2603 void avformat_free_context(AVFormatContext *s)
2608 for(i=0;i<s->nb_streams;i++) {
2609 /* free all data in a stream component */
2612 av_parser_close(st->parser);
2613 av_free_packet(&st->cur_pkt);
2615 av_metadata_free(&st->metadata);
2616 av_free(st->index_entries);
2617 av_free(st->codec->extradata);
2618 av_free(st->codec->subtitle_header);
2620 #if FF_API_OLD_METADATA
2621 av_free(st->filename);
2623 av_free(st->priv_data);
2627 for(i=s->nb_programs-1; i>=0; i--) {
2628 #if FF_API_OLD_METADATA
2629 av_freep(&s->programs[i]->provider_name);
2630 av_freep(&s->programs[i]->name);
2632 av_metadata_free(&s->programs[i]->metadata);
2633 av_freep(&s->programs[i]->stream_index);
2634 av_freep(&s->programs[i]);
2636 av_freep(&s->programs);
2637 av_freep(&s->priv_data);
2638 while(s->nb_chapters--) {
2639 #if FF_API_OLD_METADATA
2640 av_free(s->chapters[s->nb_chapters]->title);
2642 av_metadata_free(&s->chapters[s->nb_chapters]->metadata);
2643 av_free(s->chapters[s->nb_chapters]);
2645 av_freep(&s->chapters);
2646 av_metadata_free(&s->metadata);
2651 void av_close_input_file(AVFormatContext *s)
2653 AVIOContext *pb = s->iformat->flags & AVFMT_NOFILE ? NULL : s->pb;
2654 av_close_input_stream(s);
2659 AVStream *av_new_stream(AVFormatContext *s, int id)
2664 #if FF_API_MAX_STREAMS
2665 if (s->nb_streams >= MAX_STREAMS){
2666 av_log(s, AV_LOG_ERROR, "Too many streams\n");
2672 if (s->nb_streams >= INT_MAX/sizeof(*streams))
2674 streams = av_realloc(s->streams, (s->nb_streams + 1) * sizeof(*streams));
2677 s->streams = streams;
2680 st = av_mallocz(sizeof(AVStream));
2683 if (!(st->info = av_mallocz(sizeof(*st->info)))) {
2688 st->codec= avcodec_alloc_context();
2690 /* no default bitrate if decoding */
2691 st->codec->bit_rate = 0;
2693 st->index = s->nb_streams;
2695 st->start_time = AV_NOPTS_VALUE;
2696 st->duration = AV_NOPTS_VALUE;
2697 /* we set the current DTS to 0 so that formats without any timestamps
2698 but durations get some timestamps, formats with some unknown
2699 timestamps have their first few packets buffered and the
2700 timestamps corrected before they are returned to the user */
2702 st->first_dts = AV_NOPTS_VALUE;
2703 st->probe_packets = MAX_PROBE_PACKETS;
2705 /* default pts setting is MPEG-like */
2706 av_set_pts_info(st, 33, 1, 90000);
2707 st->last_IP_pts = AV_NOPTS_VALUE;
2708 for(i=0; i<MAX_REORDER_DELAY+1; i++)
2709 st->pts_buffer[i]= AV_NOPTS_VALUE;
2710 st->reference_dts = AV_NOPTS_VALUE;
2712 st->sample_aspect_ratio = (AVRational){0,1};
2714 s->streams[s->nb_streams++] = st;
2718 AVProgram *av_new_program(AVFormatContext *ac, int id)
2720 AVProgram *program=NULL;
2724 av_log(ac, AV_LOG_DEBUG, "new_program: id=0x%04x\n", id);
2727 for(i=0; i<ac->nb_programs; i++)
2728 if(ac->programs[i]->id == id)
2729 program = ac->programs[i];
2732 program = av_mallocz(sizeof(AVProgram));
2735 dynarray_add(&ac->programs, &ac->nb_programs, program);
2736 program->discard = AVDISCARD_NONE;
2743 AVChapter *ff_new_chapter(AVFormatContext *s, int id, AVRational time_base, int64_t start, int64_t end, const char *title)
2745 AVChapter *chapter = NULL;
2748 for(i=0; i<s->nb_chapters; i++)
2749 if(s->chapters[i]->id == id)
2750 chapter = s->chapters[i];
2753 chapter= av_mallocz(sizeof(AVChapter));
2756 dynarray_add(&s->chapters, &s->nb_chapters, chapter);
2758 #if FF_API_OLD_METADATA
2759 av_free(chapter->title);
2761 av_metadata_set2(&chapter->metadata, "title", title, 0);
2763 chapter->time_base= time_base;
2764 chapter->start = start;
2770 /************************************************************/
2771 /* output media file */
2773 int av_set_parameters(AVFormatContext *s, AVFormatParameters *ap)
2777 if (s->oformat->priv_data_size > 0) {
2778 s->priv_data = av_mallocz(s->oformat->priv_data_size);
2780 return AVERROR(ENOMEM);
2781 if (s->oformat->priv_class) {
2782 *(const AVClass**)s->priv_data= s->oformat->priv_class;
2783 av_opt_set_defaults(s->priv_data);
2786 s->priv_data = NULL;
2788 if (s->oformat->set_parameters) {
2789 ret = s->oformat->set_parameters(s, ap);
2796 static int validate_codec_tag(AVFormatContext *s, AVStream *st)
2798 const AVCodecTag *avctag;
2800 enum CodecID id = CODEC_ID_NONE;
2801 unsigned int tag = 0;
2804 * Check that tag + id is in the table
2805 * If neither is in the table -> OK
2806 * If tag is in the table with another id -> FAIL
2807 * If id is in the table with another tag -> FAIL unless strict < normal
2809 for (n = 0; s->oformat->codec_tag[n]; n++) {
2810 avctag = s->oformat->codec_tag[n];
2811 while (avctag->id != CODEC_ID_NONE) {
2812 if (ff_toupper4(avctag->tag) == ff_toupper4(st->codec->codec_tag)) {
2814 if (id == st->codec->codec_id)
2817 if (avctag->id == st->codec->codec_id)
2822 if (id != CODEC_ID_NONE)
2824 if (tag && (st->codec->strict_std_compliance >= FF_COMPLIANCE_NORMAL))
2829 int av_write_header(AVFormatContext *s)
2834 // some sanity checks
2835 if (s->nb_streams == 0 && !(s->oformat->flags & AVFMT_NOSTREAMS)) {
2836 av_log(s, AV_LOG_ERROR, "no streams\n");
2837 return AVERROR(EINVAL);
2840 for(i=0;i<s->nb_streams;i++) {
2843 switch (st->codec->codec_type) {
2844 case AVMEDIA_TYPE_AUDIO:
2845 if(st->codec->sample_rate<=0){
2846 av_log(s, AV_LOG_ERROR, "sample rate not set\n");
2847 return AVERROR(EINVAL);
2849 if(!st->codec->block_align)
2850 st->codec->block_align = st->codec->channels *
2851 av_get_bits_per_sample(st->codec->codec_id) >> 3;
2853 case AVMEDIA_TYPE_VIDEO:
2854 if(st->codec->time_base.num<=0 || st->codec->time_base.den<=0){ //FIXME audio too?
2855 av_log(s, AV_LOG_ERROR, "time base not set\n");
2856 return AVERROR(EINVAL);
2858 if((st->codec->width<=0 || st->codec->height<=0) && !(s->oformat->flags & AVFMT_NODIMENSIONS)){
2859 av_log(s, AV_LOG_ERROR, "dimensions not set\n");
2860 return AVERROR(EINVAL);
2862 if(av_cmp_q(st->sample_aspect_ratio, st->codec->sample_aspect_ratio)){
2863 av_log(s, AV_LOG_ERROR, "Aspect ratio mismatch between encoder and muxer layer\n");
2864 return AVERROR(EINVAL);
2869 if(s->oformat->codec_tag){
2870 if(st->codec->codec_tag && st->codec->codec_id == CODEC_ID_RAWVIDEO && av_codec_get_tag(s->oformat->codec_tag, st->codec->codec_id) == 0 && !validate_codec_tag(s, st)){
2871 //the current rawvideo encoding system ends up setting the wrong codec_tag for avi, we override it here
2872 st->codec->codec_tag= 0;
2874 if(st->codec->codec_tag){
2875 if (!validate_codec_tag(s, st)) {
2877 av_get_codec_tag_string(tagbuf, sizeof(tagbuf), st->codec->codec_tag);
2878 av_log(s, AV_LOG_ERROR,
2879 "Tag %s/0x%08x incompatible with output codec id '%d'\n",
2880 tagbuf, st->codec->codec_tag, st->codec->codec_id);
2881 return AVERROR_INVALIDDATA;
2884 st->codec->codec_tag= av_codec_get_tag(s->oformat->codec_tag, st->codec->codec_id);
2887 if(s->oformat->flags & AVFMT_GLOBALHEADER &&
2888 !(st->codec->flags & CODEC_FLAG_GLOBAL_HEADER))
2889 av_log(s, AV_LOG_WARNING, "Codec for stream %d does not use global headers but container format requires global headers\n", i);
2892 if (!s->priv_data && s->oformat->priv_data_size > 0) {
2893 s->priv_data = av_mallocz(s->oformat->priv_data_size);
2895 return AVERROR(ENOMEM);
2898 #if FF_API_OLD_METADATA
2899 ff_metadata_mux_compat(s);
2902 /* set muxer identification string */
2903 if (s->nb_streams && !(s->streams[0]->codec->flags & CODEC_FLAG_BITEXACT)) {
2904 av_metadata_set2(&s->metadata, "encoder", LIBAVFORMAT_IDENT, 0);
2907 if(s->oformat->write_header){
2908 ret = s->oformat->write_header(s);
2913 /* init PTS generation */
2914 for(i=0;i<s->nb_streams;i++) {
2915 int64_t den = AV_NOPTS_VALUE;
2918 switch (st->codec->codec_type) {
2919 case AVMEDIA_TYPE_AUDIO:
2920 den = (int64_t)st->time_base.num * st->codec->sample_rate;
2922 case AVMEDIA_TYPE_VIDEO:
2923 den = (int64_t)st->time_base.num * st->codec->time_base.den;
2928 if (den != AV_NOPTS_VALUE) {
2930 return AVERROR_INVALIDDATA;
2931 av_frac_init(&st->pts, 0, 0, den);
2937 //FIXME merge with compute_pkt_fields
2938 static int compute_pkt_fields2(AVFormatContext *s, AVStream *st, AVPacket *pkt){
2939 int delay = FFMAX(st->codec->has_b_frames, !!st->codec->max_b_frames);
2940 int num, den, frame_size, i;
2942 av_dlog(s, "av_write_frame: pts:%"PRId64" dts:%"PRId64" cur_dts:%"PRId64" b:%d size:%d st:%d\n",
2943 pkt->pts, pkt->dts, st->cur_dts, delay, pkt->size, pkt->stream_index);
2945 /* if(pkt->pts == AV_NOPTS_VALUE && pkt->dts == AV_NOPTS_VALUE)
2948 /* duration field */
2949 if (pkt->duration == 0) {
2950 compute_frame_duration(&num, &den, st, NULL, pkt);
2952 pkt->duration = av_rescale(1, num * (int64_t)st->time_base.den * st->codec->ticks_per_frame, den * (int64_t)st->time_base.num);
2956 if(pkt->pts == AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE && delay==0)
2959 //XXX/FIXME this is a temporary hack until all encoders output pts
2960 if((pkt->pts == 0 || pkt->pts == AV_NOPTS_VALUE) && pkt->dts == AV_NOPTS_VALUE && !delay){
2962 // pkt->pts= st->cur_dts;
2963 pkt->pts= st->pts.val;
2966 //calculate dts from pts
2967 if(pkt->pts != AV_NOPTS_VALUE && pkt->dts == AV_NOPTS_VALUE && delay <= MAX_REORDER_DELAY){
2968 st->pts_buffer[0]= pkt->pts;
2969 for(i=1; i<delay+1 && st->pts_buffer[i] == AV_NOPTS_VALUE; i++)
2970 st->pts_buffer[i]= pkt->pts + (i-delay-1) * pkt->duration;
2971 for(i=0; i<delay && st->pts_buffer[i] > st->pts_buffer[i+1]; i++)
2972 FFSWAP(int64_t, st->pts_buffer[i], st->pts_buffer[i+1]);
2974 pkt->dts= st->pts_buffer[0];
2977 if(st->cur_dts && st->cur_dts != AV_NOPTS_VALUE && st->cur_dts >= pkt->dts){
2978 av_log(s, AV_LOG_ERROR,
2979 "Application provided invalid, non monotonically increasing dts to muxer in stream %d: %"PRId64" >= %"PRId64"\n",
2980 st->index, st->cur_dts, pkt->dts);
2983 if(pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE && pkt->pts < pkt->dts){
2984 av_log(s, AV_LOG_ERROR, "pts < dts in stream %d\n", st->index);
2988 // av_log(s, AV_LOG_DEBUG, "av_write_frame: pts2:%"PRId64" dts2:%"PRId64"\n", pkt->pts, pkt->dts);
2989 st->cur_dts= pkt->dts;
2990 st->pts.val= pkt->dts;
2993 switch (st->codec->codec_type) {
2994 case AVMEDIA_TYPE_AUDIO:
2995 frame_size = get_audio_frame_size(st->codec, pkt->size);
2997 /* HACK/FIXME, we skip the initial 0 size packets as they are most
2998 likely equal to the encoder delay, but it would be better if we
2999 had the real timestamps from the encoder */
3000 if (frame_size >= 0 && (pkt->size || st->pts.num!=st->pts.den>>1 || st->pts.val)) {
3001 av_frac_add(&st->pts, (int64_t)st->time_base.den * frame_size);
3004 case AVMEDIA_TYPE_VIDEO:
3005 av_frac_add(&st->pts, (int64_t)st->time_base.den * st->codec->time_base.num);
3013 int av_write_frame(AVFormatContext *s, AVPacket *pkt)
3015 int ret = compute_pkt_fields2(s, s->streams[pkt->stream_index], pkt);
3017 if(ret<0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
3020 ret= s->oformat->write_packet(s, pkt);
3024 void ff_interleave_add_packet(AVFormatContext *s, AVPacket *pkt,
3025 int (*compare)(AVFormatContext *, AVPacket *, AVPacket *))
3027 AVPacketList **next_point, *this_pktl;
3029 this_pktl = av_mallocz(sizeof(AVPacketList));
3030 this_pktl->pkt= *pkt;
3031 pkt->destruct= NULL; // do not free original but only the copy
3032 av_dup_packet(&this_pktl->pkt); // duplicate the packet if it uses non-alloced memory
3034 if(s->streams[pkt->stream_index]->last_in_packet_buffer){
3035 next_point = &(s->streams[pkt->stream_index]->last_in_packet_buffer->next);
3037 next_point = &s->packet_buffer;
3040 if(compare(s, &s->packet_buffer_end->pkt, pkt)){
3041 while(!compare(s, &(*next_point)->pkt, pkt)){
3042 next_point= &(*next_point)->next;
3046 next_point = &(s->packet_buffer_end->next);
3049 assert(!*next_point);
3051 s->packet_buffer_end= this_pktl;
3054 this_pktl->next= *next_point;
3056 s->streams[pkt->stream_index]->last_in_packet_buffer=
3057 *next_point= this_pktl;
3060 static int ff_interleave_compare_dts(AVFormatContext *s, AVPacket *next, AVPacket *pkt)
3062 AVStream *st = s->streams[ pkt ->stream_index];
3063 AVStream *st2= s->streams[ next->stream_index];
3064 int64_t a= st2->time_base.num * (int64_t)st ->time_base.den;
3065 int64_t b= st ->time_base.num * (int64_t)st2->time_base.den;
3066 int64_t dts1 = av_rescale_rnd(pkt->dts, b, a, AV_ROUND_DOWN);
3067 if (dts1 == next->dts)
3068 return pkt->stream_index < next->stream_index;
3069 return dts1 < next->dts;
3072 int av_interleave_packet_per_dts(AVFormatContext *s, AVPacket *out, AVPacket *pkt, int flush){
3078 ff_interleave_add_packet(s, pkt, ff_interleave_compare_dts);
3081 for(i=0; i < s->nb_streams; i++)
3082 stream_count+= !!s->streams[i]->last_in_packet_buffer;
3084 if(stream_count && (s->nb_streams == stream_count || flush)){
3085 pktl= s->packet_buffer;
3088 s->packet_buffer= pktl->next;
3089 if(!s->packet_buffer)
3090 s->packet_buffer_end= NULL;
3092 if(s->streams[out->stream_index]->last_in_packet_buffer == pktl)
3093 s->streams[out->stream_index]->last_in_packet_buffer= NULL;
3097 av_init_packet(out);
3103 * Interleave an AVPacket correctly so it can be muxed.
3104 * @param out the interleaved packet will be output here
3105 * @param in the input packet
3106 * @param flush 1 if no further packets are available as input and all
3107 * remaining packets should be output
3108 * @return 1 if a packet was output, 0 if no packet could be output,
3109 * < 0 if an error occurred
3111 static int av_interleave_packet(AVFormatContext *s, AVPacket *out, AVPacket *in, int flush){
3112 if(s->oformat->interleave_packet)
3113 return s->oformat->interleave_packet(s, out, in, flush);
3115 return av_interleave_packet_per_dts(s, out, in, flush);
3118 int av_interleaved_write_frame(AVFormatContext *s, AVPacket *pkt){
3119 AVStream *st= s->streams[ pkt->stream_index];
3122 //FIXME/XXX/HACK drop zero sized packets
3123 if(st->codec->codec_type == AVMEDIA_TYPE_AUDIO && pkt->size==0)
3126 av_dlog(s, "av_interleaved_write_frame size:%d dts:%"PRId64" pts:%"PRId64"\n",
3127 pkt->size, pkt->dts, pkt->pts);
3128 if((ret = compute_pkt_fields2(s, st, pkt)) < 0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
3131 if(pkt->dts == AV_NOPTS_VALUE && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
3132 return AVERROR(EINVAL);
3136 int ret= av_interleave_packet(s, &opkt, pkt, 0);
3137 if(ret<=0) //FIXME cleanup needed for ret<0 ?
3140 ret= s->oformat->write_packet(s, &opkt);
3142 av_free_packet(&opkt);
3150 int av_write_trailer(AVFormatContext *s)
3156 ret= av_interleave_packet(s, &pkt, NULL, 1);
3157 if(ret<0) //FIXME cleanup needed for ret<0 ?
3162 ret= s->oformat->write_packet(s, &pkt);
3164 av_free_packet(&pkt);
3170 if(s->oformat->write_trailer)
3171 ret = s->oformat->write_trailer(s);
3173 for(i=0;i<s->nb_streams;i++) {
3174 av_freep(&s->streams[i]->priv_data);
3175 av_freep(&s->streams[i]->index_entries);
3177 av_freep(&s->priv_data);
3181 void ff_program_add_stream_index(AVFormatContext *ac, int progid, unsigned int idx)
3184 AVProgram *program=NULL;
3187 if (idx >= ac->nb_streams) {
3188 av_log(ac, AV_LOG_ERROR, "stream index %d is not valid\n", idx);
3192 for(i=0; i<ac->nb_programs; i++){
3193 if(ac->programs[i]->id != progid)
3195 program = ac->programs[i];
3196 for(j=0; j<program->nb_stream_indexes; j++)
3197 if(program->stream_index[j] == idx)
3200 tmp = av_realloc(program->stream_index, sizeof(unsigned int)*(program->nb_stream_indexes+1));
3203 program->stream_index = tmp;
3204 program->stream_index[program->nb_stream_indexes++] = idx;
3209 static void print_fps(double d, const char *postfix){
3210 uint64_t v= lrintf(d*100);
3211 if (v% 100 ) av_log(NULL, AV_LOG_INFO, ", %3.2f %s", d, postfix);
3212 else if(v%(100*1000)) av_log(NULL, AV_LOG_INFO, ", %1.0f %s", d, postfix);
3213 else av_log(NULL, AV_LOG_INFO, ", %1.0fk %s", d/1000, postfix);
3216 static void dump_metadata(void *ctx, AVMetadata *m, const char *indent)
3218 if(m && !(m->count == 1 && av_metadata_get(m, "language", NULL, 0))){
3219 AVMetadataTag *tag=NULL;
3221 av_log(ctx, AV_LOG_INFO, "%sMetadata:\n", indent);
3222 while((tag=av_metadata_get(m, "", tag, AV_METADATA_IGNORE_SUFFIX))) {
3223 if(strcmp("language", tag->key))
3224 av_log(ctx, AV_LOG_INFO, "%s %-16s: %s\n", indent, tag->key, tag->value);
3229 /* "user interface" functions */
3230 static void dump_stream_format(AVFormatContext *ic, int i, int index, int is_output)
3233 int flags = (is_output ? ic->oformat->flags : ic->iformat->flags);
3234 AVStream *st = ic->streams[i];
3235 int g = av_gcd(st->time_base.num, st->time_base.den);
3236 AVMetadataTag *lang = av_metadata_get(st->metadata, "language", NULL, 0);
3237 avcodec_string(buf, sizeof(buf), st->codec, is_output);
3238 av_log(NULL, AV_LOG_INFO, " Stream #%d.%d", index, i);
3239 /* the pid is an important information, so we display it */
3240 /* XXX: add a generic system */
3241 if (flags & AVFMT_SHOW_IDS)
3242 av_log(NULL, AV_LOG_INFO, "[0x%x]", st->id);
3244 av_log(NULL, AV_LOG_INFO, "(%s)", lang->value);
3245 av_log(NULL, AV_LOG_DEBUG, ", %d, %d/%d", st->codec_info_nb_frames, st->time_base.num/g, st->time_base.den/g);
3246 av_log(NULL, AV_LOG_INFO, ": %s", buf);
3247 if (st->sample_aspect_ratio.num && // default
3248 av_cmp_q(st->sample_aspect_ratio, st->codec->sample_aspect_ratio)) {
3249 AVRational display_aspect_ratio;
3250 av_reduce(&display_aspect_ratio.num, &display_aspect_ratio.den,
3251 st->codec->width*st->sample_aspect_ratio.num,
3252 st->codec->height*st->sample_aspect_ratio.den,
3254 av_log(NULL, AV_LOG_INFO, ", PAR %d:%d DAR %d:%d",
3255 st->sample_aspect_ratio.num, st->sample_aspect_ratio.den,
3256 display_aspect_ratio.num, display_aspect_ratio.den);
3258 if(st->codec->codec_type == AVMEDIA_TYPE_VIDEO){
3259 if(st->avg_frame_rate.den && st->avg_frame_rate.num)
3260 print_fps(av_q2d(st->avg_frame_rate), "fps");
3261 if(st->r_frame_rate.den && st->r_frame_rate.num)
3262 print_fps(av_q2d(st->r_frame_rate), "tbr");
3263 if(st->time_base.den && st->time_base.num)
3264 print_fps(1/av_q2d(st->time_base), "tbn");
3265 if(st->codec->time_base.den && st->codec->time_base.num)
3266 print_fps(1/av_q2d(st->codec->time_base), "tbc");
3268 if (st->disposition & AV_DISPOSITION_DEFAULT)
3269 av_log(NULL, AV_LOG_INFO, " (default)");
3270 if (st->disposition & AV_DISPOSITION_DUB)
3271 av_log(NULL, AV_LOG_INFO, " (dub)");
3272 if (st->disposition & AV_DISPOSITION_ORIGINAL)
3273 av_log(NULL, AV_LOG_INFO, " (original)");
3274 if (st->disposition & AV_DISPOSITION_COMMENT)
3275 av_log(NULL, AV_LOG_INFO, " (comment)");
3276 if (st->disposition & AV_DISPOSITION_LYRICS)
3277 av_log(NULL, AV_LOG_INFO, " (lyrics)");
3278 if (st->disposition & AV_DISPOSITION_KARAOKE)
3279 av_log(NULL, AV_LOG_INFO, " (karaoke)");
3280 if (st->disposition & AV_DISPOSITION_FORCED)
3281 av_log(NULL, AV_LOG_INFO, " (forced)");
3282 if (st->disposition & AV_DISPOSITION_HEARING_IMPAIRED)
3283 av_log(NULL, AV_LOG_INFO, " (hearing impaired)");
3284 if (st->disposition & AV_DISPOSITION_VISUAL_IMPAIRED)
3285 av_log(NULL, AV_LOG_INFO, " (visual impaired)");
3286 if (st->disposition & AV_DISPOSITION_CLEAN_EFFECTS)
3287 av_log(NULL, AV_LOG_INFO, " (clean effects)");
3288 av_log(NULL, AV_LOG_INFO, "\n");
3289 dump_metadata(NULL, st->metadata, " ");
3292 #if FF_API_DUMP_FORMAT
3293 void dump_format(AVFormatContext *ic,
3298 av_dump_format(ic, index, url, is_output);
3302 void av_dump_format(AVFormatContext *ic,
3308 uint8_t *printed = av_mallocz(ic->nb_streams);
3309 if (ic->nb_streams && !printed)
3312 av_log(NULL, AV_LOG_INFO, "%s #%d, %s, %s '%s':\n",
3313 is_output ? "Output" : "Input",
3315 is_output ? ic->oformat->name : ic->iformat->name,
3316 is_output ? "to" : "from", url);
3317 dump_metadata(NULL, ic->metadata, " ");
3319 av_log(NULL, AV_LOG_INFO, " Duration: ");
3320 if (ic->duration != AV_NOPTS_VALUE) {
3321 int hours, mins, secs, us;
3322 secs = ic->duration / AV_TIME_BASE;
3323 us = ic->duration % AV_TIME_BASE;
3328 av_log(NULL, AV_LOG_INFO, "%02d:%02d:%02d.%02d", hours, mins, secs,
3329 (100 * us) / AV_TIME_BASE);
3331 av_log(NULL, AV_LOG_INFO, "N/A");
3333 if (ic->start_time != AV_NOPTS_VALUE) {
3335 av_log(NULL, AV_LOG_INFO, ", start: ");
3336 secs = ic->start_time / AV_TIME_BASE;
3337 us = abs(ic->start_time % AV_TIME_BASE);
3338 av_log(NULL, AV_LOG_INFO, "%d.%06d",
3339 secs, (int)av_rescale(us, 1000000, AV_TIME_BASE));
3341 av_log(NULL, AV_LOG_INFO, ", bitrate: ");
3343 av_log(NULL, AV_LOG_INFO,"%d kb/s", ic->bit_rate / 1000);
3345 av_log(NULL, AV_LOG_INFO, "N/A");
3347 av_log(NULL, AV_LOG_INFO, "\n");
3349 for (i = 0; i < ic->nb_chapters; i++) {
3350 AVChapter *ch = ic->chapters[i];
3351 av_log(NULL, AV_LOG_INFO, " Chapter #%d.%d: ", index, i);
3352 av_log(NULL, AV_LOG_INFO, "start %f, ", ch->start * av_q2d(ch->time_base));
3353 av_log(NULL, AV_LOG_INFO, "end %f\n", ch->end * av_q2d(ch->time_base));
3355 dump_metadata(NULL, ch->metadata, " ");
3357 if(ic->nb_programs) {
3358 int j, k, total = 0;
3359 for(j=0; j<ic->nb_programs; j++) {
3360 AVMetadataTag *name = av_metadata_get(ic->programs[j]->metadata,
3362 av_log(NULL, AV_LOG_INFO, " Program %d %s\n", ic->programs[j]->id,
3363 name ? name->value : "");
3364 dump_metadata(NULL, ic->programs[j]->metadata, " ");
3365 for(k=0; k<ic->programs[j]->nb_stream_indexes; k++) {
3366 dump_stream_format(ic, ic->programs[j]->stream_index[k], index, is_output);
3367 printed[ic->programs[j]->stream_index[k]] = 1;
3369 total += ic->programs[j]->nb_stream_indexes;
3371 if (total < ic->nb_streams)
3372 av_log(NULL, AV_LOG_INFO, " No Program\n");
3374 for(i=0;i<ic->nb_streams;i++)
3376 dump_stream_format(ic, i, index, is_output);
3381 #if FF_API_PARSE_FRAME_PARAM
3382 #include "libavutil/parseutils.h"
3384 int parse_image_size(int *width_ptr, int *height_ptr, const char *str)
3386 return av_parse_video_size(width_ptr, height_ptr, str);
3389 int parse_frame_rate(int *frame_rate_num, int *frame_rate_den, const char *arg)
3391 AVRational frame_rate;
3392 int ret = av_parse_video_rate(&frame_rate, arg);
3393 *frame_rate_num= frame_rate.num;
3394 *frame_rate_den= frame_rate.den;
3399 int64_t av_gettime(void)
3402 gettimeofday(&tv,NULL);
3403 return (int64_t)tv.tv_sec * 1000000 + tv.tv_usec;
3406 uint64_t ff_ntp_time(void)
3408 return (av_gettime() / 1000) * 1000 + NTP_OFFSET_US;
3411 #if FF_API_PARSE_DATE
3412 #include "libavutil/parseutils.h"
3414 int64_t parse_date(const char *timestr, int duration)
3417 av_parse_time(&timeval, timestr, duration);
3422 #if FF_API_FIND_INFO_TAG
3423 #include "libavutil/parseutils.h"
3425 int find_info_tag(char *arg, int arg_size, const char *tag1, const char *info)
3427 return av_find_info_tag(arg, arg_size, tag1, info);
3431 int av_get_frame_filename(char *buf, int buf_size,
3432 const char *path, int number)
3435 char *q, buf1[20], c;
3436 int nd, len, percentd_found;
3448 while (isdigit(*p)) {
3449 nd = nd * 10 + *p++ - '0';
3452 } while (isdigit(c));
3461 snprintf(buf1, sizeof(buf1), "%0*d", nd, number);
3463 if ((q - buf + len) > buf_size - 1)
3465 memcpy(q, buf1, len);
3473 if ((q - buf) < buf_size - 1)
3477 if (!percentd_found)
3486 static void hex_dump_internal(void *avcl, FILE *f, int level, uint8_t *buf, int size)
3490 #define PRINT(...) do { if (!f) av_log(avcl, level, __VA_ARGS__); else fprintf(f, __VA_ARGS__); } while(0)
3492 for(i=0;i<size;i+=16) {
3499 PRINT(" %02x", buf[i+j]);
3504 for(j=0;j<len;j++) {
3506 if (c < ' ' || c > '~')
3515 void av_hex_dump(FILE *f, uint8_t *buf, int size)
3517 hex_dump_internal(NULL, f, 0, buf, size);
3520 void av_hex_dump_log(void *avcl, int level, uint8_t *buf, int size)
3522 hex_dump_internal(avcl, NULL, level, buf, size);
3525 static void pkt_dump_internal(void *avcl, FILE *f, int level, AVPacket *pkt, int dump_payload, AVRational time_base)
3528 #define PRINT(...) do { if (!f) av_log(avcl, level, __VA_ARGS__); else fprintf(f, __VA_ARGS__); } while(0)
3529 PRINT("stream #%d:\n", pkt->stream_index);
3530 PRINT(" keyframe=%d\n", ((pkt->flags & AV_PKT_FLAG_KEY) != 0));
3531 PRINT(" duration=%0.3f\n", pkt->duration * av_q2d(time_base));
3532 /* DTS is _always_ valid after av_read_frame() */
3534 if (pkt->dts == AV_NOPTS_VALUE)
3537 PRINT("%0.3f", pkt->dts * av_q2d(time_base));
3538 /* PTS may not be known if B-frames are present. */
3540 if (pkt->pts == AV_NOPTS_VALUE)
3543 PRINT("%0.3f", pkt->pts * av_q2d(time_base));
3545 PRINT(" size=%d\n", pkt->size);
3548 av_hex_dump(f, pkt->data, pkt->size);
3552 void av_pkt_dump(FILE *f, AVPacket *pkt, int dump_payload)
3554 AVRational tb = { 1, AV_TIME_BASE };
3555 pkt_dump_internal(NULL, f, 0, pkt, dump_payload, tb);
3559 void av_pkt_dump2(FILE *f, AVPacket *pkt, int dump_payload, AVStream *st)
3561 pkt_dump_internal(NULL, f, 0, pkt, dump_payload, st->time_base);
3565 void av_pkt_dump_log(void *avcl, int level, AVPacket *pkt, int dump_payload)
3567 AVRational tb = { 1, AV_TIME_BASE };
3568 pkt_dump_internal(avcl, NULL, level, pkt, dump_payload, tb);
3572 void av_pkt_dump_log2(void *avcl, int level, AVPacket *pkt, int dump_payload,
3575 pkt_dump_internal(avcl, NULL, level, pkt, dump_payload, st->time_base);
3578 #if FF_API_URL_SPLIT
3579 attribute_deprecated
3580 void ff_url_split(char *proto, int proto_size,
3581 char *authorization, int authorization_size,
3582 char *hostname, int hostname_size,
3584 char *path, int path_size,
3587 av_url_split(proto, proto_size,
3588 authorization, authorization_size,
3589 hostname, hostname_size,
3596 void av_url_split(char *proto, int proto_size,
3597 char *authorization, int authorization_size,
3598 char *hostname, int hostname_size,
3600 char *path, int path_size,
3603 const char *p, *ls, *at, *col, *brk;
3605 if (port_ptr) *port_ptr = -1;
3606 if (proto_size > 0) proto[0] = 0;
3607 if (authorization_size > 0) authorization[0] = 0;
3608 if (hostname_size > 0) hostname[0] = 0;
3609 if (path_size > 0) path[0] = 0;
3611 /* parse protocol */
3612 if ((p = strchr(url, ':'))) {
3613 av_strlcpy(proto, url, FFMIN(proto_size, p + 1 - url));
3618 /* no protocol means plain filename */
3619 av_strlcpy(path, url, path_size);
3623 /* separate path from hostname */
3624 ls = strchr(p, '/');
3626 ls = strchr(p, '?');
3628 av_strlcpy(path, ls, path_size);
3630 ls = &p[strlen(p)]; // XXX
3632 /* the rest is hostname, use that to parse auth/port */
3634 /* authorization (user[:pass]@hostname) */
3635 if ((at = strchr(p, '@')) && at < ls) {
3636 av_strlcpy(authorization, p,
3637 FFMIN(authorization_size, at + 1 - p));
3638 p = at + 1; /* skip '@' */
3641 if (*p == '[' && (brk = strchr(p, ']')) && brk < ls) {
3643 av_strlcpy(hostname, p + 1,
3644 FFMIN(hostname_size, brk - p));
3645 if (brk[1] == ':' && port_ptr)
3646 *port_ptr = atoi(brk + 2);
3647 } else if ((col = strchr(p, ':')) && col < ls) {
3648 av_strlcpy(hostname, p,
3649 FFMIN(col + 1 - p, hostname_size));
3650 if (port_ptr) *port_ptr = atoi(col + 1);
3652 av_strlcpy(hostname, p,
3653 FFMIN(ls + 1 - p, hostname_size));
3657 char *ff_data_to_hex(char *buff, const uint8_t *src, int s, int lowercase)
3660 static const char hex_table_uc[16] = { '0', '1', '2', '3',
3663 'C', 'D', 'E', 'F' };
3664 static const char hex_table_lc[16] = { '0', '1', '2', '3',
3667 'c', 'd', 'e', 'f' };
3668 const char *hex_table = lowercase ? hex_table_lc : hex_table_uc;
3670 for(i = 0; i < s; i++) {
3671 buff[i * 2] = hex_table[src[i] >> 4];
3672 buff[i * 2 + 1] = hex_table[src[i] & 0xF];
3678 int ff_hex_to_data(uint8_t *data, const char *p)
3685 p += strspn(p, SPACE_CHARS);
3688 c = toupper((unsigned char) *p++);
3689 if (c >= '0' && c <= '9')
3691 else if (c >= 'A' && c <= 'F')
3706 void av_set_pts_info(AVStream *s, int pts_wrap_bits,
3707 unsigned int pts_num, unsigned int pts_den)
3710 if(av_reduce(&new_tb.num, &new_tb.den, pts_num, pts_den, INT_MAX)){
3711 if(new_tb.num != pts_num)
3712 av_log(NULL, AV_LOG_DEBUG, "st:%d removing common factor %d from timebase\n", s->index, pts_num/new_tb.num);
3714 av_log(NULL, AV_LOG_WARNING, "st:%d has too large timebase, reducing\n", s->index);
3716 if(new_tb.num <= 0 || new_tb.den <= 0) {
3717 av_log(NULL, AV_LOG_ERROR, "Ignoring attempt to set invalid timebase for st:%d\n", s->index);
3720 s->time_base = new_tb;
3721 s->pts_wrap_bits = pts_wrap_bits;
3724 int ff_url_join(char *str, int size, const char *proto,
3725 const char *authorization, const char *hostname,
3726 int port, const char *fmt, ...)
3729 struct addrinfo hints, *ai;
3734 av_strlcatf(str, size, "%s://", proto);
3735 if (authorization && authorization[0])
3736 av_strlcatf(str, size, "%s@", authorization);
3737 #if CONFIG_NETWORK && defined(AF_INET6)
3738 /* Determine if hostname is a numerical IPv6 address,
3739 * properly escape it within [] in that case. */
3740 memset(&hints, 0, sizeof(hints));
3741 hints.ai_flags = AI_NUMERICHOST;
3742 if (!getaddrinfo(hostname, NULL, &hints, &ai)) {
3743 if (ai->ai_family == AF_INET6) {
3744 av_strlcat(str, "[", size);
3745 av_strlcat(str, hostname, size);
3746 av_strlcat(str, "]", size);
3748 av_strlcat(str, hostname, size);
3753 /* Not an IPv6 address, just output the plain string. */
3754 av_strlcat(str, hostname, size);
3757 av_strlcatf(str, size, ":%d", port);
3760 int len = strlen(str);
3763 vsnprintf(str + len, size > len ? size - len : 0, fmt, vl);
3769 int ff_write_chained(AVFormatContext *dst, int dst_stream, AVPacket *pkt,
3770 AVFormatContext *src)
3775 local_pkt.stream_index = dst_stream;
3776 if (pkt->pts != AV_NOPTS_VALUE)
3777 local_pkt.pts = av_rescale_q(pkt->pts,
3778 src->streams[pkt->stream_index]->time_base,
3779 dst->streams[dst_stream]->time_base);
3780 if (pkt->dts != AV_NOPTS_VALUE)
3781 local_pkt.dts = av_rescale_q(pkt->dts,
3782 src->streams[pkt->stream_index]->time_base,
3783 dst->streams[dst_stream]->time_base);
3784 return av_write_frame(dst, &local_pkt);
3787 void ff_parse_key_value(const char *str, ff_parse_key_val_cb callback_get_buf,
3790 const char *ptr = str;
3792 /* Parse key=value pairs. */
3795 char *dest = NULL, *dest_end;
3796 int key_len, dest_len = 0;
3798 /* Skip whitespace and potential commas. */
3799 while (*ptr && (isspace(*ptr) || *ptr == ','))
3806 if (!(ptr = strchr(key, '=')))
3809 key_len = ptr - key;
3811 callback_get_buf(context, key, key_len, &dest, &dest_len);
3812 dest_end = dest + dest_len - 1;
3816 while (*ptr && *ptr != '\"') {
3820 if (dest && dest < dest_end)
3824 if (dest && dest < dest_end)
3832 for (; *ptr && !(isspace(*ptr) || *ptr == ','); ptr++)
3833 if (dest && dest < dest_end)
3841 int ff_find_stream_index(AVFormatContext *s, int id)
3844 for (i = 0; i < s->nb_streams; i++) {
3845 if (s->streams[i]->id == id)
3851 void ff_make_absolute_url(char *buf, int size, const char *base,
3855 /* Absolute path, relative to the current server */
3856 if (base && strstr(base, "://") && rel[0] == '/') {
3858 av_strlcpy(buf, base, size);
3859 sep = strstr(buf, "://");
3862 sep = strchr(sep, '/');
3866 av_strlcat(buf, rel, size);
3869 /* If rel actually is an absolute url, just copy it */
3870 if (!base || strstr(rel, "://") || rel[0] == '/') {
3871 av_strlcpy(buf, rel, size);
3875 av_strlcpy(buf, base, size);
3876 /* Remove the file name from the base url */
3877 sep = strrchr(buf, '/');
3882 while (av_strstart(rel, "../", NULL) && sep) {
3883 /* Remove the path delimiter at the end */
3885 sep = strrchr(buf, '/');
3886 /* If the next directory name to pop off is "..", break here */
3887 if (!strcmp(sep ? &sep[1] : buf, "..")) {
3888 /* Readd the slash we just removed */
3889 av_strlcat(buf, "/", size);
3892 /* Cut off the directory name */
3899 av_strlcat(buf, rel, size);