2 * various utility functions for use within FFmpeg
3 * Copyright (c) 2000, 2001, 2002 Fabrice Bellard
5 * This file is part of FFmpeg.
7 * FFmpeg 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 * FFmpeg 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 FFmpeg; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
23 #include "libavcodec/opt.h"
25 #include "libavutil/avstring.h"
35 * @file libavformat/utils.c
36 * various utility functions for use within FFmpeg
39 unsigned avformat_version(void)
41 return LIBAVFORMAT_VERSION_INT
;
44 /* fraction handling */
47 * f = val + (num / den) + 0.5.
49 * 'num' is normalized so that it is such as 0 <= num < den.
51 * @param f fractional number
52 * @param val integer value
53 * @param num must be >= 0
54 * @param den must be >= 1
56 static void av_frac_init(AVFrac
*f
, int64_t val
, int64_t num
, int64_t den
)
69 * Fractional addition to f: f = f + (incr / f->den).
71 * @param f fractional number
72 * @param incr increment, can be positive or negative
74 static void av_frac_add(AVFrac
*f
, int64_t incr
)
87 } else if (num
>= den
) {
94 /** head of registered input format linked list */
95 AVInputFormat
*first_iformat
= NULL
;
96 /** head of registered output format linked list */
97 AVOutputFormat
*first_oformat
= NULL
;
99 AVInputFormat
*av_iformat_next(AVInputFormat
*f
)
101 if(f
) return f
->next
;
102 else return first_iformat
;
105 AVOutputFormat
*av_oformat_next(AVOutputFormat
*f
)
107 if(f
) return f
->next
;
108 else return first_oformat
;
111 void av_register_input_format(AVInputFormat
*format
)
115 while (*p
!= NULL
) p
= &(*p
)->next
;
120 void av_register_output_format(AVOutputFormat
*format
)
124 while (*p
!= NULL
) p
= &(*p
)->next
;
129 int match_ext(const char *filename
, const char *extensions
)
137 ext
= strrchr(filename
, '.');
143 while (*p
!= '\0' && *p
!= ',' && q
-ext1
<sizeof(ext1
)-1)
146 if (!strcasecmp(ext1
, ext
))
156 static int match_format(const char *name
, const char *names
)
164 namelen
= strlen(name
);
165 while ((p
= strchr(names
, ','))) {
166 len
= FFMAX(p
- names
, namelen
);
167 if (!strncasecmp(name
, names
, len
))
171 return !strcasecmp(name
, names
);
174 AVOutputFormat
*guess_format(const char *short_name
, const char *filename
,
175 const char *mime_type
)
177 AVOutputFormat
*fmt
, *fmt_found
;
178 int score_max
, score
;
180 /* specific test for image sequences */
181 #if CONFIG_IMAGE2_MUXER
182 if (!short_name
&& filename
&&
183 av_filename_number_test(filename
) &&
184 av_guess_image2_codec(filename
) != CODEC_ID_NONE
) {
185 return guess_format("image2", NULL
, NULL
);
188 /* Find the proper file type. */
192 while (fmt
!= NULL
) {
194 if (fmt
->name
&& short_name
&& !strcmp(fmt
->name
, short_name
))
196 if (fmt
->mime_type
&& mime_type
&& !strcmp(fmt
->mime_type
, mime_type
))
198 if (filename
&& fmt
->extensions
&&
199 match_ext(filename
, fmt
->extensions
)) {
202 if (score
> score_max
) {
211 AVOutputFormat
*guess_stream_format(const char *short_name
, const char *filename
,
212 const char *mime_type
)
214 AVOutputFormat
*fmt
= guess_format(short_name
, filename
, mime_type
);
217 AVOutputFormat
*stream_fmt
;
218 char stream_format_name
[64];
220 snprintf(stream_format_name
, sizeof(stream_format_name
), "%s_stream", fmt
->name
);
221 stream_fmt
= guess_format(stream_format_name
, NULL
, NULL
);
230 enum CodecID
av_guess_codec(AVOutputFormat
*fmt
, const char *short_name
,
231 const char *filename
, const char *mime_type
, enum CodecType type
){
232 if(type
== CODEC_TYPE_VIDEO
){
233 enum CodecID codec_id
= CODEC_ID_NONE
;
235 #if CONFIG_IMAGE2_MUXER
236 if(!strcmp(fmt
->name
, "image2") || !strcmp(fmt
->name
, "image2pipe")){
237 codec_id
= av_guess_image2_codec(filename
);
240 if(codec_id
== CODEC_ID_NONE
)
241 codec_id
= fmt
->video_codec
;
243 }else if(type
== CODEC_TYPE_AUDIO
)
244 return fmt
->audio_codec
;
246 return CODEC_ID_NONE
;
249 AVInputFormat
*av_find_input_format(const char *short_name
)
252 for(fmt
= first_iformat
; fmt
!= NULL
; fmt
= fmt
->next
) {
253 if (match_format(short_name
, fmt
->name
))
259 /* memory handling */
262 int av_get_packet(ByteIOContext
*s
, AVPacket
*pkt
, int size
)
264 int ret
= av_new_packet(pkt
, size
);
269 pkt
->pos
= url_ftell(s
);
271 ret
= get_buffer(s
, pkt
->data
, size
);
275 av_shrink_packet(pkt
, ret
);
281 int av_filename_number_test(const char *filename
)
284 return filename
&& (av_get_frame_filename(buf
, sizeof(buf
), filename
, 1)>=0);
287 static AVInputFormat
*av_probe_input_format2(AVProbeData
*pd
, int is_opened
, int *score_max
)
289 AVInputFormat
*fmt1
, *fmt
;
293 for(fmt1
= first_iformat
; fmt1
!= NULL
; fmt1
= fmt1
->next
) {
294 if (!is_opened
== !(fmt1
->flags
& AVFMT_NOFILE
))
297 if (fmt1
->read_probe
) {
298 score
= fmt1
->read_probe(pd
);
299 } else if (fmt1
->extensions
) {
300 if (match_ext(pd
->filename
, fmt1
->extensions
)) {
304 if (score
> *score_max
) {
307 }else if (score
== *score_max
)
313 AVInputFormat
*av_probe_input_format(AVProbeData
*pd
, int is_opened
){
315 return av_probe_input_format2(pd
, is_opened
, &score
);
318 static int set_codec_from_probe_data(AVFormatContext
*s
, AVStream
*st
, AVProbeData
*pd
, int score
)
321 fmt
= av_probe_input_format2(pd
, 1, &score
);
324 av_log(s
, AV_LOG_DEBUG
, "Probe with size=%d, packets=%d detected %s with score=%d\n",
325 pd
->buf_size
, MAX_PROBE_PACKETS
- st
->probe_packets
, fmt
->name
, score
);
326 if (!strcmp(fmt
->name
, "mp3")) {
327 st
->codec
->codec_id
= CODEC_ID_MP3
;
328 st
->codec
->codec_type
= CODEC_TYPE_AUDIO
;
329 } else if (!strcmp(fmt
->name
, "ac3")) {
330 st
->codec
->codec_id
= CODEC_ID_AC3
;
331 st
->codec
->codec_type
= CODEC_TYPE_AUDIO
;
332 } else if (!strcmp(fmt
->name
, "eac3")) {
333 st
->codec
->codec_id
= CODEC_ID_EAC3
;
334 st
->codec
->codec_type
= CODEC_TYPE_AUDIO
;
335 } else if (!strcmp(fmt
->name
, "mpegvideo")) {
336 st
->codec
->codec_id
= CODEC_ID_MPEG2VIDEO
;
337 st
->codec
->codec_type
= CODEC_TYPE_VIDEO
;
338 } else if (!strcmp(fmt
->name
, "m4v")) {
339 st
->codec
->codec_id
= CODEC_ID_MPEG4
;
340 st
->codec
->codec_type
= CODEC_TYPE_VIDEO
;
341 } else if (!strcmp(fmt
->name
, "h264")) {
342 st
->codec
->codec_id
= CODEC_ID_H264
;
343 st
->codec
->codec_type
= CODEC_TYPE_VIDEO
;
344 } else if (!strcmp(fmt
->name
, "dts")) {
345 st
->codec
->codec_id
= CODEC_ID_DTS
;
346 st
->codec
->codec_type
= CODEC_TYPE_AUDIO
;
352 /************************************************************/
353 /* input media file */
356 * Open a media file from an IO stream. 'fmt' must be specified.
358 int av_open_input_stream(AVFormatContext
**ic_ptr
,
359 ByteIOContext
*pb
, const char *filename
,
360 AVInputFormat
*fmt
, AVFormatParameters
*ap
)
364 AVFormatParameters default_ap
;
368 memset(ap
, 0, sizeof(default_ap
));
371 if(!ap
->prealloced_context
)
372 ic
= avformat_alloc_context();
376 err
= AVERROR(ENOMEM
);
381 ic
->duration
= AV_NOPTS_VALUE
;
382 ic
->start_time
= AV_NOPTS_VALUE
;
383 av_strlcpy(ic
->filename
, filename
, sizeof(ic
->filename
));
385 /* allocate private data */
386 if (fmt
->priv_data_size
> 0) {
387 ic
->priv_data
= av_mallocz(fmt
->priv_data_size
);
388 if (!ic
->priv_data
) {
389 err
= AVERROR(ENOMEM
);
393 ic
->priv_data
= NULL
;
396 if (ic
->iformat
->read_header
) {
397 err
= ic
->iformat
->read_header(ic
, ap
);
402 if (pb
&& !ic
->data_offset
)
403 ic
->data_offset
= url_ftell(ic
->pb
);
405 #if LIBAVFORMAT_VERSION_MAJOR < 53
406 ff_metadata_demux_compat(ic
);
409 ic
->raw_packet_buffer_remaining_size
= RAW_PACKET_BUFFER_SIZE
;
416 av_freep(&ic
->priv_data
);
417 for(i
=0;i
<ic
->nb_streams
;i
++) {
418 AVStream
*st
= ic
->streams
[i
];
420 av_free(st
->priv_data
);
421 av_free(st
->codec
->extradata
);
431 /** size of probe buffer, for guessing file type from file contents */
432 #define PROBE_BUF_MIN 2048
433 #define PROBE_BUF_MAX (1<<20)
435 int av_open_input_file(AVFormatContext
**ic_ptr
, const char *filename
,
438 AVFormatParameters
*ap
)
441 AVProbeData probe_data
, *pd
= &probe_data
;
442 ByteIOContext
*pb
= NULL
;
443 void *logctx
= ap
&& ap
->prealloced_context
? *ic_ptr
: NULL
;
447 pd
->filename
= filename
;
452 /* guess format if no file can be opened */
453 fmt
= av_probe_input_format(pd
, 0);
456 /* Do not open file if the format does not need it. XXX: specific
457 hack needed to handle RTSP/TCP */
458 if (!fmt
|| !(fmt
->flags
& AVFMT_NOFILE
)) {
459 /* if no file needed do not try to open one */
460 if ((err
=url_fopen(&pb
, filename
, URL_RDONLY
)) < 0) {
464 url_setbufsize(pb
, buf_size
);
467 for(probe_size
= PROBE_BUF_MIN
; probe_size
<=PROBE_BUF_MAX
&& !fmt
; probe_size
<<=1){
468 int score
= probe_size
< PROBE_BUF_MAX
? AVPROBE_SCORE_MAX
/4 : 0;
469 /* read probe data */
470 pd
->buf
= av_realloc(pd
->buf
, probe_size
+ AVPROBE_PADDING_SIZE
);
471 pd
->buf_size
= get_buffer(pb
, pd
->buf
, probe_size
);
473 if ((int)pd
->buf_size
< 0) {
478 memset(pd
->buf
+pd
->buf_size
, 0, AVPROBE_PADDING_SIZE
);
479 if (url_fseek(pb
, 0, SEEK_SET
) < 0) {
481 if (url_fopen(&pb
, filename
, URL_RDONLY
) < 0) {
487 /* guess file format */
488 fmt
= av_probe_input_format2(pd
, 1, &score
);
490 if(score
<= AVPROBE_SCORE_MAX
/4){ //this can only be true in the last iteration
491 av_log(logctx
, AV_LOG_WARNING
, "Format detected only with low score of %d, misdetection possible!\n", score
);
493 av_log(logctx
, AV_LOG_DEBUG
, "Probed with size=%d and score=%d\n", probe_size
, score
);
499 /* if still no format found, error */
505 /* check filename in case an image number is expected */
506 if (fmt
->flags
& AVFMT_NEEDNUMBER
) {
507 if (!av_filename_number_test(filename
)) {
508 err
= AVERROR_NUMEXPECTED
;
512 err
= av_open_input_stream(ic_ptr
, pb
, filename
, fmt
, ap
);
520 if (ap
&& ap
->prealloced_context
)
527 /*******************************************************/
529 static AVPacket
*add_to_pktbuf(AVPacketList
**packet_buffer
, AVPacket
*pkt
,
530 AVPacketList
**plast_pktl
){
531 AVPacketList
*pktl
= av_mallocz(sizeof(AVPacketList
));
536 (*plast_pktl
)->next
= pktl
;
538 *packet_buffer
= pktl
;
540 /* add the packet in the buffered packet list */
546 int av_read_packet(AVFormatContext
*s
, AVPacket
*pkt
)
552 AVPacketList
*pktl
= s
->raw_packet_buffer
;
556 if(s
->streams
[pkt
->stream_index
]->codec
->codec_id
!= CODEC_ID_PROBE
||
557 !s
->streams
[pkt
->stream_index
]->probe_packets
||
558 s
->raw_packet_buffer_remaining_size
< pkt
->size
){
559 AVProbeData
*pd
= &s
->streams
[pkt
->stream_index
]->probe_data
;
562 s
->raw_packet_buffer
= pktl
->next
;
563 s
->raw_packet_buffer_remaining_size
+= pkt
->size
;
570 ret
= s
->iformat
->read_packet(s
, pkt
);
572 if (!pktl
|| ret
== AVERROR(EAGAIN
))
574 for (i
= 0; i
< s
->nb_streams
; i
++)
575 s
->streams
[i
]->probe_packets
= 0;
578 st
= s
->streams
[pkt
->stream_index
];
580 switch(st
->codec
->codec_type
){
581 case CODEC_TYPE_VIDEO
:
582 if(s
->video_codec_id
) st
->codec
->codec_id
= s
->video_codec_id
;
584 case CODEC_TYPE_AUDIO
:
585 if(s
->audio_codec_id
) st
->codec
->codec_id
= s
->audio_codec_id
;
587 case CODEC_TYPE_SUBTITLE
:
588 if(s
->subtitle_codec_id
)st
->codec
->codec_id
= s
->subtitle_codec_id
;
592 if(!pktl
&& (st
->codec
->codec_id
!= CODEC_ID_PROBE
||
596 add_to_pktbuf(&s
->raw_packet_buffer
, pkt
, &s
->raw_packet_buffer_end
);
597 s
->raw_packet_buffer_remaining_size
-= pkt
->size
;
599 if(st
->codec
->codec_id
== CODEC_ID_PROBE
){
600 AVProbeData
*pd
= &st
->probe_data
;
604 pd
->buf
= av_realloc(pd
->buf
, pd
->buf_size
+pkt
->size
+AVPROBE_PADDING_SIZE
);
605 memcpy(pd
->buf
+pd
->buf_size
, pkt
->data
, pkt
->size
);
606 pd
->buf_size
+= pkt
->size
;
607 memset(pd
->buf
+pd
->buf_size
, 0, AVPROBE_PADDING_SIZE
);
609 if(av_log2(pd
->buf_size
) != av_log2(pd
->buf_size
- pkt
->size
)){
610 set_codec_from_probe_data(s
, st
, pd
, 1);
611 if(st
->codec
->codec_id
!= CODEC_ID_PROBE
){
620 /**********************************************************/
623 * Get the number of samples of an audio frame. Return -1 on error.
625 static int get_audio_frame_size(AVCodecContext
*enc
, int size
)
629 if(enc
->codec_id
== CODEC_ID_VORBIS
)
632 if (enc
->frame_size
<= 1) {
633 int bits_per_sample
= av_get_bits_per_sample(enc
->codec_id
);
635 if (bits_per_sample
) {
636 if (enc
->channels
== 0)
638 frame_size
= (size
<< 3) / (bits_per_sample
* enc
->channels
);
640 /* used for example by ADPCM codecs */
641 if (enc
->bit_rate
== 0)
643 frame_size
= ((int64_t)size
* 8 * enc
->sample_rate
) / enc
->bit_rate
;
646 frame_size
= enc
->frame_size
;
653 * Return the frame duration in seconds. Return 0 if not available.
655 static void compute_frame_duration(int *pnum
, int *pden
, AVStream
*st
,
656 AVCodecParserContext
*pc
, AVPacket
*pkt
)
662 switch(st
->codec
->codec_type
) {
663 case CODEC_TYPE_VIDEO
:
664 if(st
->time_base
.num
*1000LL > st
->time_base
.den
){
665 *pnum
= st
->time_base
.num
;
666 *pden
= st
->time_base
.den
;
667 }else if(st
->codec
->time_base
.num
*1000LL > st
->codec
->time_base
.den
){
668 *pnum
= st
->codec
->time_base
.num
;
669 *pden
= st
->codec
->time_base
.den
;
670 if (pc
&& pc
->repeat_pict
) {
671 *pnum
= (*pnum
) * (1 + pc
->repeat_pict
);
675 case CODEC_TYPE_AUDIO
:
676 frame_size
= get_audio_frame_size(st
->codec
, pkt
->size
);
680 *pden
= st
->codec
->sample_rate
;
687 static int is_intra_only(AVCodecContext
*enc
){
688 if(enc
->codec_type
== CODEC_TYPE_AUDIO
){
690 }else if(enc
->codec_type
== CODEC_TYPE_VIDEO
){
691 switch(enc
->codec_id
){
693 case CODEC_ID_MJPEGB
:
695 case CODEC_ID_RAWVIDEO
:
696 case CODEC_ID_DVVIDEO
:
697 case CODEC_ID_HUFFYUV
:
698 case CODEC_ID_FFVHUFF
:
703 case CODEC_ID_JPEG2000
:
711 static void update_initial_timestamps(AVFormatContext
*s
, int stream_index
,
712 int64_t dts
, int64_t pts
)
714 AVStream
*st
= s
->streams
[stream_index
];
715 AVPacketList
*pktl
= s
->packet_buffer
;
717 if(st
->first_dts
!= AV_NOPTS_VALUE
|| dts
== AV_NOPTS_VALUE
|| st
->cur_dts
== AV_NOPTS_VALUE
)
720 st
->first_dts
= dts
- st
->cur_dts
;
723 for(; pktl
; pktl
= pktl
->next
){
724 if(pktl
->pkt
.stream_index
!= stream_index
)
726 //FIXME think more about this check
727 if(pktl
->pkt
.pts
!= AV_NOPTS_VALUE
&& pktl
->pkt
.pts
== pktl
->pkt
.dts
)
728 pktl
->pkt
.pts
+= st
->first_dts
;
730 if(pktl
->pkt
.dts
!= AV_NOPTS_VALUE
)
731 pktl
->pkt
.dts
+= st
->first_dts
;
733 if(st
->start_time
== AV_NOPTS_VALUE
&& pktl
->pkt
.pts
!= AV_NOPTS_VALUE
)
734 st
->start_time
= pktl
->pkt
.pts
;
736 if (st
->start_time
== AV_NOPTS_VALUE
)
737 st
->start_time
= pts
;
740 static void update_initial_durations(AVFormatContext
*s
, AVStream
*st
, AVPacket
*pkt
)
742 AVPacketList
*pktl
= s
->packet_buffer
;
745 if(st
->first_dts
!= AV_NOPTS_VALUE
){
746 cur_dts
= st
->first_dts
;
747 for(; pktl
; pktl
= pktl
->next
){
748 if(pktl
->pkt
.stream_index
== pkt
->stream_index
){
749 if(pktl
->pkt
.pts
!= pktl
->pkt
.dts
|| pktl
->pkt
.dts
!= AV_NOPTS_VALUE
|| pktl
->pkt
.duration
)
751 cur_dts
-= pkt
->duration
;
754 pktl
= s
->packet_buffer
;
755 st
->first_dts
= cur_dts
;
756 }else if(st
->cur_dts
)
759 for(; pktl
; pktl
= pktl
->next
){
760 if(pktl
->pkt
.stream_index
!= pkt
->stream_index
)
762 if(pktl
->pkt
.pts
== pktl
->pkt
.dts
&& pktl
->pkt
.dts
== AV_NOPTS_VALUE
763 && !pktl
->pkt
.duration
){
764 pktl
->pkt
.dts
= cur_dts
;
765 if(!st
->codec
->has_b_frames
)
766 pktl
->pkt
.pts
= cur_dts
;
767 cur_dts
+= pkt
->duration
;
768 pktl
->pkt
.duration
= pkt
->duration
;
772 if(st
->first_dts
== AV_NOPTS_VALUE
)
773 st
->cur_dts
= cur_dts
;
776 static void compute_pkt_fields(AVFormatContext
*s
, AVStream
*st
,
777 AVCodecParserContext
*pc
, AVPacket
*pkt
)
779 int num
, den
, presentation_delayed
, delay
, i
;
782 if (st
->codec
->codec_id
!= CODEC_ID_H264
&& pc
&& pc
->pict_type
== FF_B_TYPE
)
783 //FIXME Set low_delay = 0 when has_b_frames = 1
784 st
->codec
->has_b_frames
= 1;
786 /* do we have a video B-frame ? */
787 delay
= st
->codec
->has_b_frames
;
788 presentation_delayed
= 0;
789 /* XXX: need has_b_frame, but cannot get it if the codec is
792 pc
&& pc
->pict_type
!= FF_B_TYPE
)
793 presentation_delayed
= 1;
795 if(pkt
->pts
!= AV_NOPTS_VALUE
&& pkt
->dts
!= AV_NOPTS_VALUE
&& pkt
->dts
> pkt
->pts
&& st
->pts_wrap_bits
<63
796 /*&& pkt->dts-(1LL<<st->pts_wrap_bits) < pkt->pts*/){
797 pkt
->dts
-= 1LL<<st
->pts_wrap_bits
;
800 // some mpeg2 in mpeg-ps lack dts (issue171 / input_file.mpg)
801 // we take the conservative approach and discard both
802 // Note, if this is misbehaving for a H.264 file then possibly presentation_delayed is not set correctly.
803 if(delay
==1 && pkt
->dts
== pkt
->pts
&& pkt
->dts
!= AV_NOPTS_VALUE
&& presentation_delayed
){
804 av_log(s
, AV_LOG_WARNING
, "invalid dts/pts combination\n");
805 pkt
->dts
= pkt
->pts
= AV_NOPTS_VALUE
;
808 if (pkt
->duration
== 0) {
809 compute_frame_duration(&num
, &den
, st
, pc
, pkt
);
811 pkt
->duration
= av_rescale(1, num
* (int64_t)st
->time_base
.den
, den
* (int64_t)st
->time_base
.num
);
813 if(pkt
->duration
!= 0 && s
->packet_buffer
)
814 update_initial_durations(s
, st
, pkt
);
818 /* correct timestamps with byte offset if demuxers only have timestamps
819 on packet boundaries */
820 if(pc
&& st
->need_parsing
== AVSTREAM_PARSE_TIMESTAMPS
&& pkt
->size
){
821 /* this will estimate bitrate based on this frame's duration and size */
822 offset
= av_rescale(pc
->offset
, pkt
->duration
, pkt
->size
);
823 if(pkt
->pts
!= AV_NOPTS_VALUE
)
825 if(pkt
->dts
!= AV_NOPTS_VALUE
)
829 if (pc
&& pc
->dts_sync_point
>= 0) {
830 // we have synchronization info from the parser
831 int64_t den
= st
->codec
->time_base
.den
* (int64_t) st
->time_base
.num
;
833 int64_t num
= st
->codec
->time_base
.num
* (int64_t) st
->time_base
.den
;
834 if (pkt
->dts
!= AV_NOPTS_VALUE
) {
835 // got DTS from the stream, update reference timestamp
836 st
->reference_dts
= pkt
->dts
- pc
->dts_ref_dts_delta
* num
/ den
;
837 pkt
->pts
= pkt
->dts
+ pc
->pts_dts_delta
* num
/ den
;
838 } else if (st
->reference_dts
!= AV_NOPTS_VALUE
) {
839 // compute DTS based on reference timestamp
840 pkt
->dts
= st
->reference_dts
+ pc
->dts_ref_dts_delta
* num
/ den
;
841 pkt
->pts
= pkt
->dts
+ pc
->pts_dts_delta
* num
/ den
;
843 if (pc
->dts_sync_point
> 0)
844 st
->reference_dts
= pkt
->dts
; // new reference
848 /* This may be redundant, but it should not hurt. */
849 if(pkt
->dts
!= AV_NOPTS_VALUE
&& pkt
->pts
!= AV_NOPTS_VALUE
&& pkt
->pts
> pkt
->dts
)
850 presentation_delayed
= 1;
852 // 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);
853 /* interpolate PTS and DTS if they are not present */
854 //We skip H264 currently because delay and has_b_frames are not reliably set
855 if((delay
==0 || (delay
==1 && pc
)) && st
->codec
->codec_id
!= CODEC_ID_H264
){
856 if (presentation_delayed
) {
857 /* DTS = decompression timestamp */
858 /* PTS = presentation timestamp */
859 if (pkt
->dts
== AV_NOPTS_VALUE
)
860 pkt
->dts
= st
->last_IP_pts
;
861 update_initial_timestamps(s
, pkt
->stream_index
, pkt
->dts
, pkt
->pts
);
862 if (pkt
->dts
== AV_NOPTS_VALUE
)
863 pkt
->dts
= st
->cur_dts
;
865 /* this is tricky: the dts must be incremented by the duration
866 of the frame we are displaying, i.e. the last I- or P-frame */
867 if (st
->last_IP_duration
== 0)
868 st
->last_IP_duration
= pkt
->duration
;
869 if(pkt
->dts
!= AV_NOPTS_VALUE
)
870 st
->cur_dts
= pkt
->dts
+ st
->last_IP_duration
;
871 st
->last_IP_duration
= pkt
->duration
;
872 st
->last_IP_pts
= pkt
->pts
;
873 /* cannot compute PTS if not present (we can compute it only
874 by knowing the future */
875 } else if(pkt
->pts
!= AV_NOPTS_VALUE
|| pkt
->dts
!= AV_NOPTS_VALUE
|| pkt
->duration
){
876 if(pkt
->pts
!= AV_NOPTS_VALUE
&& pkt
->duration
){
877 int64_t old_diff
= FFABS(st
->cur_dts
- pkt
->duration
- pkt
->pts
);
878 int64_t new_diff
= FFABS(st
->cur_dts
- pkt
->pts
);
879 if(old_diff
< new_diff
&& old_diff
< (pkt
->duration
>>3)){
880 pkt
->pts
+= pkt
->duration
;
881 // 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);
885 /* presentation is not delayed : PTS and DTS are the same */
886 if(pkt
->pts
== AV_NOPTS_VALUE
)
888 update_initial_timestamps(s
, pkt
->stream_index
, pkt
->pts
, pkt
->pts
);
889 if(pkt
->pts
== AV_NOPTS_VALUE
)
890 pkt
->pts
= st
->cur_dts
;
892 if(pkt
->pts
!= AV_NOPTS_VALUE
)
893 st
->cur_dts
= pkt
->pts
+ pkt
->duration
;
897 if(pkt
->pts
!= AV_NOPTS_VALUE
&& delay
<= MAX_REORDER_DELAY
){
898 st
->pts_buffer
[0]= pkt
->pts
;
899 for(i
=0; i
<delay
&& st
->pts_buffer
[i
] > st
->pts_buffer
[i
+1]; i
++)
900 FFSWAP(int64_t, st
->pts_buffer
[i
], st
->pts_buffer
[i
+1]);
901 if(pkt
->dts
== AV_NOPTS_VALUE
)
902 pkt
->dts
= st
->pts_buffer
[0];
903 if(st
->codec
->codec_id
== CODEC_ID_H264
){ //we skiped it above so we try here
904 update_initial_timestamps(s
, pkt
->stream_index
, pkt
->dts
, pkt
->pts
); // this should happen on the first packet
906 if(pkt
->dts
> st
->cur_dts
)
907 st
->cur_dts
= pkt
->dts
;
910 // 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);
913 if(is_intra_only(st
->codec
))
914 pkt
->flags
|= PKT_FLAG_KEY
;
917 /* keyframe computation */
918 if (pc
->key_frame
== 1)
919 pkt
->flags
|= PKT_FLAG_KEY
;
920 else if (pc
->key_frame
== -1 && pc
->pict_type
== FF_I_TYPE
)
921 pkt
->flags
|= PKT_FLAG_KEY
;
924 pkt
->convergence_duration
= pc
->convergence_duration
;
928 static int av_read_frame_internal(AVFormatContext
*s
, AVPacket
*pkt
)
936 /* select current input stream component */
939 if (!st
->need_parsing
|| !st
->parser
) {
940 /* no parsing needed: we just output the packet as is */
941 /* raw data support */
942 *pkt
= st
->cur_pkt
; st
->cur_pkt
.data
= NULL
;
943 compute_pkt_fields(s
, st
, NULL
, pkt
);
945 if ((s
->iformat
->flags
& AVFMT_GENERIC_INDEX
) &&
946 (pkt
->flags
& PKT_FLAG_KEY
) && pkt
->dts
!= AV_NOPTS_VALUE
) {
947 ff_reduce_index(s
, st
->index
);
948 av_add_index_entry(st
, pkt
->pos
, pkt
->dts
, 0, 0, AVINDEX_KEYFRAME
);
951 } else if (st
->cur_len
> 0 && st
->discard
< AVDISCARD_ALL
) {
952 len
= av_parser_parse2(st
->parser
, st
->codec
, &pkt
->data
, &pkt
->size
,
953 st
->cur_ptr
, st
->cur_len
,
954 st
->cur_pkt
.pts
, st
->cur_pkt
.dts
,
956 st
->cur_pkt
.pts
= AV_NOPTS_VALUE
;
957 st
->cur_pkt
.dts
= AV_NOPTS_VALUE
;
958 /* increment read pointer */
962 /* return packet if any */
966 pkt
->stream_index
= st
->index
;
967 pkt
->pts
= st
->parser
->pts
;
968 pkt
->dts
= st
->parser
->dts
;
969 pkt
->pos
= st
->parser
->pos
;
970 pkt
->destruct
= NULL
;
971 compute_pkt_fields(s
, st
, st
->parser
, pkt
);
973 if((s
->iformat
->flags
& AVFMT_GENERIC_INDEX
) && pkt
->flags
& PKT_FLAG_KEY
){
974 ff_reduce_index(s
, st
->index
);
975 av_add_index_entry(st
, st
->parser
->frame_offset
, pkt
->dts
,
976 0, 0, AVINDEX_KEYFRAME
);
983 av_free_packet(&st
->cur_pkt
);
988 /* read next packet */
989 ret
= av_read_packet(s
, &cur_pkt
);
991 if (ret
== AVERROR(EAGAIN
))
993 /* return the last frames, if any */
994 for(i
= 0; i
< s
->nb_streams
; i
++) {
996 if (st
->parser
&& st
->need_parsing
) {
997 av_parser_parse2(st
->parser
, st
->codec
,
998 &pkt
->data
, &pkt
->size
,
1000 AV_NOPTS_VALUE
, AV_NOPTS_VALUE
,
1006 /* no more packets: really terminate parsing */
1009 st
= s
->streams
[cur_pkt
.stream_index
];
1010 st
->cur_pkt
= cur_pkt
;
1012 if(st
->cur_pkt
.pts
!= AV_NOPTS_VALUE
&&
1013 st
->cur_pkt
.dts
!= AV_NOPTS_VALUE
&&
1014 st
->cur_pkt
.pts
< st
->cur_pkt
.dts
){
1015 av_log(s
, AV_LOG_WARNING
, "Invalid timestamps stream=%d, pts=%"PRId64
", dts=%"PRId64
", size=%d\n",
1016 st
->cur_pkt
.stream_index
,
1020 // av_free_packet(&st->cur_pkt);
1024 if(s
->debug
& FF_FDEBUG_TS
)
1025 av_log(s
, AV_LOG_DEBUG
, "av_read_packet stream=%d, pts=%"PRId64
", dts=%"PRId64
", size=%d, duration=%d, flags=%d\n",
1026 st
->cur_pkt
.stream_index
,
1030 st
->cur_pkt
.duration
,
1034 st
->cur_ptr
= st
->cur_pkt
.data
;
1035 st
->cur_len
= st
->cur_pkt
.size
;
1036 if (st
->need_parsing
&& !st
->parser
) {
1037 st
->parser
= av_parser_init(st
->codec
->codec_id
);
1039 /* no parser available: just output the raw packets */
1040 st
->need_parsing
= AVSTREAM_PARSE_NONE
;
1041 }else if(st
->need_parsing
== AVSTREAM_PARSE_HEADERS
){
1042 st
->parser
->flags
|= PARSER_FLAG_COMPLETE_FRAMES
;
1044 if(st
->parser
&& (s
->iformat
->flags
& AVFMT_GENERIC_INDEX
)){
1045 st
->parser
->next_frame_offset
=
1046 st
->parser
->cur_offset
= st
->cur_pkt
.pos
;
1051 if(s
->debug
& FF_FDEBUG_TS
)
1052 av_log(s
, AV_LOG_DEBUG
, "av_read_frame_internal stream=%d, pts=%"PRId64
", dts=%"PRId64
", size=%d, duration=%d, flags=%d\n",
1063 int av_read_frame(AVFormatContext
*s
, AVPacket
*pkt
)
1067 const int genpts
= s
->flags
& AVFMT_FLAG_GENPTS
;
1070 pktl
= s
->packet_buffer
;
1072 AVPacket
*next_pkt
= &pktl
->pkt
;
1074 if(genpts
&& next_pkt
->dts
!= AV_NOPTS_VALUE
){
1075 while(pktl
&& next_pkt
->pts
== AV_NOPTS_VALUE
){
1076 if( pktl
->pkt
.stream_index
== next_pkt
->stream_index
1077 && next_pkt
->dts
< pktl
->pkt
.dts
1078 && pktl
->pkt
.pts
!= pktl
->pkt
.dts
//not b frame
1079 /*&& pktl->pkt.dts != AV_NOPTS_VALUE*/){
1080 next_pkt
->pts
= pktl
->pkt
.dts
;
1084 pktl
= s
->packet_buffer
;
1087 if( next_pkt
->pts
!= AV_NOPTS_VALUE
1088 || next_pkt
->dts
== AV_NOPTS_VALUE
1090 /* read packet from packet buffer, if there is data */
1092 s
->packet_buffer
= pktl
->next
;
1098 int ret
= av_read_frame_internal(s
, pkt
);
1100 if(pktl
&& ret
!= AVERROR(EAGAIN
)){
1107 if(av_dup_packet(add_to_pktbuf(&s
->packet_buffer
, pkt
,
1108 &s
->packet_buffer_end
)) < 0)
1109 return AVERROR(ENOMEM
);
1111 assert(!s
->packet_buffer
);
1112 return av_read_frame_internal(s
, pkt
);
1117 /* XXX: suppress the packet queue */
1118 static void flush_packet_queue(AVFormatContext
*s
)
1123 pktl
= s
->packet_buffer
;
1126 s
->packet_buffer
= pktl
->next
;
1127 av_free_packet(&pktl
->pkt
);
1130 while(s
->raw_packet_buffer
){
1131 pktl
= s
->raw_packet_buffer
;
1132 s
->raw_packet_buffer
= pktl
->next
;
1133 av_free_packet(&pktl
->pkt
);
1136 s
->packet_buffer_end
=
1137 s
->raw_packet_buffer_end
= NULL
;
1138 s
->raw_packet_buffer_remaining_size
= RAW_PACKET_BUFFER_SIZE
;
1141 /*******************************************************/
1144 int av_find_default_stream_index(AVFormatContext
*s
)
1146 int first_audio_index
= -1;
1150 if (s
->nb_streams
<= 0)
1152 for(i
= 0; i
< s
->nb_streams
; i
++) {
1154 if (st
->codec
->codec_type
== CODEC_TYPE_VIDEO
) {
1157 if (first_audio_index
< 0 && st
->codec
->codec_type
== CODEC_TYPE_AUDIO
)
1158 first_audio_index
= i
;
1160 return first_audio_index
>= 0 ? first_audio_index
: 0;
1164 * Flush the frame reader.
1166 void av_read_frame_flush(AVFormatContext
*s
)
1171 flush_packet_queue(s
);
1175 /* for each stream, reset read state */
1176 for(i
= 0; i
< s
->nb_streams
; i
++) {
1180 av_parser_close(st
->parser
);
1182 av_free_packet(&st
->cur_pkt
);
1184 st
->last_IP_pts
= AV_NOPTS_VALUE
;
1185 st
->cur_dts
= AV_NOPTS_VALUE
; /* we set the current DTS to an unspecified origin */
1186 st
->reference_dts
= AV_NOPTS_VALUE
;
1191 st
->probe_packets
= MAX_PROBE_PACKETS
;
1195 void av_update_cur_dts(AVFormatContext
*s
, AVStream
*ref_st
, int64_t timestamp
){
1198 for(i
= 0; i
< s
->nb_streams
; i
++) {
1199 AVStream
*st
= s
->streams
[i
];
1201 st
->cur_dts
= av_rescale(timestamp
,
1202 st
->time_base
.den
* (int64_t)ref_st
->time_base
.num
,
1203 st
->time_base
.num
* (int64_t)ref_st
->time_base
.den
);
1207 void ff_reduce_index(AVFormatContext
*s
, int stream_index
)
1209 AVStream
*st
= s
->streams
[stream_index
];
1210 unsigned int max_entries
= s
->max_index_size
/ sizeof(AVIndexEntry
);
1212 if((unsigned)st
->nb_index_entries
>= max_entries
){
1214 for(i
=0; 2*i
<st
->nb_index_entries
; i
++)
1215 st
->index_entries
[i
]= st
->index_entries
[2*i
];
1216 st
->nb_index_entries
= i
;
1220 int av_add_index_entry(AVStream
*st
,
1221 int64_t pos
, int64_t timestamp
, int size
, int distance
, int flags
)
1223 AVIndexEntry
*entries
, *ie
;
1226 if((unsigned)st
->nb_index_entries
+ 1 >= UINT_MAX
/ sizeof(AVIndexEntry
))
1229 entries
= av_fast_realloc(st
->index_entries
,
1230 &st
->index_entries_allocated_size
,
1231 (st
->nb_index_entries
+ 1) *
1232 sizeof(AVIndexEntry
));
1236 st
->index_entries
= entries
;
1238 index
= av_index_search_timestamp(st
, timestamp
, AVSEEK_FLAG_ANY
);
1241 index
= st
->nb_index_entries
++;
1242 ie
= &entries
[index
];
1243 assert(index
==0 || ie
[-1].timestamp
< timestamp
);
1245 ie
= &entries
[index
];
1246 if(ie
->timestamp
!= timestamp
){
1247 if(ie
->timestamp
<= timestamp
)
1249 memmove(entries
+ index
+ 1, entries
+ index
, sizeof(AVIndexEntry
)*(st
->nb_index_entries
- index
));
1250 st
->nb_index_entries
++;
1251 }else if(ie
->pos
== pos
&& distance
< ie
->min_distance
) //do not reduce the distance
1252 distance
= ie
->min_distance
;
1256 ie
->timestamp
= timestamp
;
1257 ie
->min_distance
= distance
;
1264 int av_index_search_timestamp(AVStream
*st
, int64_t wanted_timestamp
,
1267 AVIndexEntry
*entries
= st
->index_entries
;
1268 int nb_entries
= st
->nb_index_entries
;
1277 timestamp
= entries
[m
].timestamp
;
1278 if(timestamp
>= wanted_timestamp
)
1280 if(timestamp
<= wanted_timestamp
)
1283 m
= (flags
& AVSEEK_FLAG_BACKWARD
) ? a
: b
;
1285 if(!(flags
& AVSEEK_FLAG_ANY
)){
1286 while(m
>=0 && m
<nb_entries
&& !(entries
[m
].flags
& AVINDEX_KEYFRAME
)){
1287 m
+= (flags
& AVSEEK_FLAG_BACKWARD
) ? -1 : 1;
1298 int av_seek_frame_binary(AVFormatContext
*s
, int stream_index
, int64_t target_ts
, int flags
){
1299 AVInputFormat
*avif
= s
->iformat
;
1300 int64_t av_uninit(pos_min
), av_uninit(pos_max
), pos
, pos_limit
;
1301 int64_t ts_min
, ts_max
, ts
;
1305 if (stream_index
< 0)
1309 av_log(s
, AV_LOG_DEBUG
, "read_seek: %d %"PRId64
"\n", stream_index
, target_ts
);
1313 ts_min
= AV_NOPTS_VALUE
;
1314 pos_limit
= -1; //gcc falsely says it may be uninitialized
1316 st
= s
->streams
[stream_index
];
1317 if(st
->index_entries
){
1320 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()
1321 index
= FFMAX(index
, 0);
1322 e
= &st
->index_entries
[index
];
1324 if(e
->timestamp
<= target_ts
|| e
->pos
== e
->min_distance
){
1326 ts_min
= e
->timestamp
;
1328 av_log(s
, AV_LOG_DEBUG
, "using cached pos_min=0x%"PRIx64
" dts_min=%"PRId64
"\n",
1335 index
= av_index_search_timestamp(st
, target_ts
, flags
& ~AVSEEK_FLAG_BACKWARD
);
1336 assert(index
< st
->nb_index_entries
);
1338 e
= &st
->index_entries
[index
];
1339 assert(e
->timestamp
>= target_ts
);
1341 ts_max
= e
->timestamp
;
1342 pos_limit
= pos_max
- e
->min_distance
;
1344 av_log(s
, AV_LOG_DEBUG
, "using cached pos_max=0x%"PRIx64
" pos_limit=0x%"PRIx64
" dts_max=%"PRId64
"\n",
1345 pos_max
,pos_limit
, ts_max
);
1350 pos
= av_gen_search(s
, stream_index
, target_ts
, pos_min
, pos_max
, pos_limit
, ts_min
, ts_max
, flags
, &ts
, avif
->read_timestamp
);
1355 url_fseek(s
->pb
, pos
, SEEK_SET
);
1357 av_update_cur_dts(s
, st
, ts
);
1362 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 )){
1364 int64_t start_pos
, filesize
;
1368 av_log(s
, AV_LOG_DEBUG
, "gen_seek: %d %"PRId64
"\n", stream_index
, target_ts
);
1371 if(ts_min
== AV_NOPTS_VALUE
){
1372 pos_min
= s
->data_offset
;
1373 ts_min
= read_timestamp(s
, stream_index
, &pos_min
, INT64_MAX
);
1374 if (ts_min
== AV_NOPTS_VALUE
)
1378 if(ts_max
== AV_NOPTS_VALUE
){
1380 filesize
= url_fsize(s
->pb
);
1381 pos_max
= filesize
- 1;
1384 ts_max
= read_timestamp(s
, stream_index
, &pos_max
, pos_max
+ step
);
1386 }while(ts_max
== AV_NOPTS_VALUE
&& pos_max
>= step
);
1387 if (ts_max
== AV_NOPTS_VALUE
)
1391 int64_t tmp_pos
= pos_max
+ 1;
1392 int64_t tmp_ts
= read_timestamp(s
, stream_index
, &tmp_pos
, INT64_MAX
);
1393 if(tmp_ts
== AV_NOPTS_VALUE
)
1397 if(tmp_pos
>= filesize
)
1403 if(ts_min
> ts_max
){
1405 }else if(ts_min
== ts_max
){
1410 while (pos_min
< pos_limit
) {
1412 av_log(s
, AV_LOG_DEBUG
, "pos_min=0x%"PRIx64
" pos_max=0x%"PRIx64
" dts_min=%"PRId64
" dts_max=%"PRId64
"\n",
1416 assert(pos_limit
<= pos_max
);
1419 int64_t approximate_keyframe_distance
= pos_max
- pos_limit
;
1420 // interpolate position (better than dichotomy)
1421 pos
= av_rescale(target_ts
- ts_min
, pos_max
- pos_min
, ts_max
- ts_min
)
1422 + pos_min
- approximate_keyframe_distance
;
1423 }else if(no_change
==1){
1424 // bisection, if interpolation failed to change min or max pos last time
1425 pos
= (pos_min
+ pos_limit
)>>1;
1427 /* linear search if bisection failed, can only happen if there
1428 are very few or no keyframes between min/max */
1433 else if(pos
> pos_limit
)
1437 ts
= read_timestamp(s
, stream_index
, &pos
, INT64_MAX
); //may pass pos_limit instead of -1
1443 av_log(s
, AV_LOG_DEBUG
, "%"PRId64
" %"PRId64
" %"PRId64
" / %"PRId64
" %"PRId64
" %"PRId64
" target:%"PRId64
" limit:%"PRId64
" start:%"PRId64
" noc:%d\n",
1444 pos_min
, pos
, pos_max
, ts_min
, ts
, ts_max
, target_ts
, pos_limit
,
1445 start_pos
, no_change
);
1447 if(ts
== AV_NOPTS_VALUE
){
1448 av_log(s
, AV_LOG_ERROR
, "read_timestamp() failed in the middle\n");
1451 assert(ts
!= AV_NOPTS_VALUE
);
1452 if (target_ts
<= ts
) {
1453 pos_limit
= start_pos
- 1;
1457 if (target_ts
>= ts
) {
1463 pos
= (flags
& AVSEEK_FLAG_BACKWARD
) ? pos_min
: pos_max
;
1464 ts
= (flags
& AVSEEK_FLAG_BACKWARD
) ? ts_min
: ts_max
;
1467 ts_min
= read_timestamp(s
, stream_index
, &pos_min
, INT64_MAX
);
1469 ts_max
= read_timestamp(s
, stream_index
, &pos_min
, INT64_MAX
);
1470 av_log(s
, AV_LOG_DEBUG
, "pos=0x%"PRIx64
" %"PRId64
"<=%"PRId64
"<=%"PRId64
"\n",
1471 pos
, ts_min
, target_ts
, ts_max
);
1477 static int av_seek_frame_byte(AVFormatContext
*s
, int stream_index
, int64_t pos
, int flags
){
1478 int64_t pos_min
, pos_max
;
1482 if (stream_index
< 0)
1485 st
= s
->streams
[stream_index
];
1488 pos_min
= s
->data_offset
;
1489 pos_max
= url_fsize(s
->pb
) - 1;
1491 if (pos
< pos_min
) pos
= pos_min
;
1492 else if(pos
> pos_max
) pos
= pos_max
;
1494 url_fseek(s
->pb
, pos
, SEEK_SET
);
1497 av_update_cur_dts(s
, st
, ts
);
1502 static int av_seek_frame_generic(AVFormatContext
*s
,
1503 int stream_index
, int64_t timestamp
, int flags
)
1509 st
= s
->streams
[stream_index
];
1511 index
= av_index_search_timestamp(st
, timestamp
, flags
);
1513 if(index
< 0 || index
==st
->nb_index_entries
-1){
1517 if(st
->nb_index_entries
){
1518 assert(st
->index_entries
);
1519 ie
= &st
->index_entries
[st
->nb_index_entries
-1];
1520 if ((ret
= url_fseek(s
->pb
, ie
->pos
, SEEK_SET
)) < 0)
1522 av_update_cur_dts(s
, st
, ie
->timestamp
);
1524 if ((ret
= url_fseek(s
->pb
, s
->data_offset
, SEEK_SET
)) < 0)
1530 ret
= av_read_frame(s
, &pkt
);
1531 }while(ret
== AVERROR(EAGAIN
));
1534 av_free_packet(&pkt
);
1535 if(stream_index
== pkt
.stream_index
){
1536 if((pkt
.flags
& PKT_FLAG_KEY
) && pkt
.dts
> timestamp
)
1540 index
= av_index_search_timestamp(st
, timestamp
, flags
);
1545 av_read_frame_flush(s
);
1546 if (s
->iformat
->read_seek
){
1547 if(s
->iformat
->read_seek(s
, stream_index
, timestamp
, flags
) >= 0)
1550 ie
= &st
->index_entries
[index
];
1551 if ((ret
= url_fseek(s
->pb
, ie
->pos
, SEEK_SET
)) < 0)
1553 av_update_cur_dts(s
, st
, ie
->timestamp
);
1558 int av_seek_frame(AVFormatContext
*s
, int stream_index
, int64_t timestamp
, int flags
)
1563 av_read_frame_flush(s
);
1565 if(flags
& AVSEEK_FLAG_BYTE
)
1566 return av_seek_frame_byte(s
, stream_index
, timestamp
, flags
);
1568 if(stream_index
< 0){
1569 stream_index
= av_find_default_stream_index(s
);
1570 if(stream_index
< 0)
1573 st
= s
->streams
[stream_index
];
1574 /* timestamp for default must be expressed in AV_TIME_BASE units */
1575 timestamp
= av_rescale(timestamp
, st
->time_base
.den
, AV_TIME_BASE
* (int64_t)st
->time_base
.num
);
1578 /* first, we try the format specific seek */
1579 if (s
->iformat
->read_seek
)
1580 ret
= s
->iformat
->read_seek(s
, stream_index
, timestamp
, flags
);
1587 if(s
->iformat
->read_timestamp
)
1588 return av_seek_frame_binary(s
, stream_index
, timestamp
, flags
);
1590 return av_seek_frame_generic(s
, stream_index
, timestamp
, flags
);
1593 int avformat_seek_file(AVFormatContext
*s
, int stream_index
, int64_t min_ts
, int64_t ts
, int64_t max_ts
, int flags
)
1595 if(min_ts
> ts
|| max_ts
< ts
)
1598 av_read_frame_flush(s
);
1600 if (s
->iformat
->read_seek2
)
1601 return s
->iformat
->read_seek2(s
, stream_index
, min_ts
, ts
, max_ts
, flags
);
1603 if(s
->iformat
->read_timestamp
){
1604 //try to seek via read_timestamp()
1607 //Fallback to old API if new is not implemented but old is
1608 //Note the old has somewat different sematics
1609 if(s
->iformat
->read_seek
|| 1)
1610 return av_seek_frame(s
, stream_index
, ts
, flags
| (ts
- min_ts
> (uint64_t)(max_ts
- ts
) ? AVSEEK_FLAG_BACKWARD
: 0));
1612 // try some generic seek like av_seek_frame_generic() but with new ts semantics
1615 /*******************************************************/
1618 * Returns TRUE if the stream has accurate duration in any stream.
1620 * @return TRUE if the stream has accurate duration for at least one component.
1622 static int av_has_duration(AVFormatContext
*ic
)
1627 for(i
= 0;i
< ic
->nb_streams
; i
++) {
1628 st
= ic
->streams
[i
];
1629 if (st
->duration
!= AV_NOPTS_VALUE
)
1636 * Estimate the stream timings from the one of each components.
1638 * Also computes the global bitrate if possible.
1640 static void av_update_stream_timings(AVFormatContext
*ic
)
1642 int64_t start_time
, start_time1
, end_time
, end_time1
;
1643 int64_t duration
, duration1
;
1647 start_time
= INT64_MAX
;
1648 end_time
= INT64_MIN
;
1649 duration
= INT64_MIN
;
1650 for(i
= 0;i
< ic
->nb_streams
; i
++) {
1651 st
= ic
->streams
[i
];
1652 if (st
->start_time
!= AV_NOPTS_VALUE
&& st
->time_base
.den
) {
1653 start_time1
= av_rescale_q(st
->start_time
, st
->time_base
, AV_TIME_BASE_Q
);
1654 if (start_time1
< start_time
)
1655 start_time
= start_time1
;
1656 if (st
->duration
!= AV_NOPTS_VALUE
) {
1657 end_time1
= start_time1
1658 + av_rescale_q(st
->duration
, st
->time_base
, AV_TIME_BASE_Q
);
1659 if (end_time1
> end_time
)
1660 end_time
= end_time1
;
1663 if (st
->duration
!= AV_NOPTS_VALUE
) {
1664 duration1
= av_rescale_q(st
->duration
, st
->time_base
, AV_TIME_BASE_Q
);
1665 if (duration1
> duration
)
1666 duration
= duration1
;
1669 if (start_time
!= INT64_MAX
) {
1670 ic
->start_time
= start_time
;
1671 if (end_time
!= INT64_MIN
) {
1672 if (end_time
- start_time
> duration
)
1673 duration
= end_time
- start_time
;
1676 if (duration
!= INT64_MIN
) {
1677 ic
->duration
= duration
;
1678 if (ic
->file_size
> 0) {
1679 /* compute the bitrate */
1680 ic
->bit_rate
= (double)ic
->file_size
* 8.0 * AV_TIME_BASE
/
1681 (double)ic
->duration
;
1686 static void fill_all_stream_timings(AVFormatContext
*ic
)
1691 av_update_stream_timings(ic
);
1692 for(i
= 0;i
< ic
->nb_streams
; i
++) {
1693 st
= ic
->streams
[i
];
1694 if (st
->start_time
== AV_NOPTS_VALUE
) {
1695 if(ic
->start_time
!= AV_NOPTS_VALUE
)
1696 st
->start_time
= av_rescale_q(ic
->start_time
, AV_TIME_BASE_Q
, st
->time_base
);
1697 if(ic
->duration
!= AV_NOPTS_VALUE
)
1698 st
->duration
= av_rescale_q(ic
->duration
, AV_TIME_BASE_Q
, st
->time_base
);
1703 static void av_estimate_timings_from_bit_rate(AVFormatContext
*ic
)
1705 int64_t filesize
, duration
;
1709 /* if bit_rate is already set, we believe it */
1710 if (ic
->bit_rate
== 0) {
1712 for(i
=0;i
<ic
->nb_streams
;i
++) {
1713 st
= ic
->streams
[i
];
1714 bit_rate
+= st
->codec
->bit_rate
;
1716 ic
->bit_rate
= bit_rate
;
1719 /* if duration is already set, we believe it */
1720 if (ic
->duration
== AV_NOPTS_VALUE
&&
1721 ic
->bit_rate
!= 0 &&
1722 ic
->file_size
!= 0) {
1723 filesize
= ic
->file_size
;
1725 for(i
= 0; i
< ic
->nb_streams
; i
++) {
1726 st
= ic
->streams
[i
];
1727 duration
= av_rescale(8*filesize
, st
->time_base
.den
, ic
->bit_rate
*(int64_t)st
->time_base
.num
);
1728 if (st
->duration
== AV_NOPTS_VALUE
)
1729 st
->duration
= duration
;
1735 #define DURATION_MAX_READ_SIZE 250000
1737 /* only usable for MPEG-PS streams */
1738 static void av_estimate_timings_from_pts(AVFormatContext
*ic
, int64_t old_offset
)
1740 AVPacket pkt1
, *pkt
= &pkt1
;
1742 int read_size
, i
, ret
;
1744 int64_t filesize
, offset
, duration
;
1748 /* flush packet queue */
1749 flush_packet_queue(ic
);
1751 for(i
=0;i
<ic
->nb_streams
;i
++) {
1752 st
= ic
->streams
[i
];
1754 av_parser_close(st
->parser
);
1756 av_free_packet(&st
->cur_pkt
);
1760 /* we read the first packets to get the first PTS (not fully
1761 accurate, but it is enough now) */
1762 url_fseek(ic
->pb
, 0, SEEK_SET
);
1765 if (read_size
>= DURATION_MAX_READ_SIZE
)
1767 /* if all info is available, we can stop */
1768 for(i
= 0;i
< ic
->nb_streams
; i
++) {
1769 st
= ic
->streams
[i
];
1770 if (st
->start_time
== AV_NOPTS_VALUE
)
1773 if (i
== ic
->nb_streams
)
1777 ret
= av_read_packet(ic
, pkt
);
1778 }while(ret
== AVERROR(EAGAIN
));
1781 read_size
+= pkt
->size
;
1782 st
= ic
->streams
[pkt
->stream_index
];
1783 if (pkt
->pts
!= AV_NOPTS_VALUE
) {
1784 if (st
->start_time
== AV_NOPTS_VALUE
)
1785 st
->start_time
= pkt
->pts
;
1787 av_free_packet(pkt
);
1790 /* estimate the end time (duration) */
1791 /* XXX: may need to support wrapping */
1792 filesize
= ic
->file_size
;
1793 offset
= filesize
- DURATION_MAX_READ_SIZE
;
1797 url_fseek(ic
->pb
, offset
, SEEK_SET
);
1800 if (read_size
>= DURATION_MAX_READ_SIZE
)
1804 ret
= av_read_packet(ic
, pkt
);
1805 }while(ret
== AVERROR(EAGAIN
));
1808 read_size
+= pkt
->size
;
1809 st
= ic
->streams
[pkt
->stream_index
];
1810 if (pkt
->pts
!= AV_NOPTS_VALUE
&&
1811 st
->start_time
!= AV_NOPTS_VALUE
) {
1812 end_time
= pkt
->pts
;
1813 duration
= end_time
- st
->start_time
;
1815 if (st
->duration
== AV_NOPTS_VALUE
||
1816 st
->duration
< duration
)
1817 st
->duration
= duration
;
1820 av_free_packet(pkt
);
1823 fill_all_stream_timings(ic
);
1825 url_fseek(ic
->pb
, old_offset
, SEEK_SET
);
1826 for(i
=0; i
<ic
->nb_streams
; i
++){
1828 st
->cur_dts
= st
->first_dts
;
1829 st
->last_IP_pts
= AV_NOPTS_VALUE
;
1833 static void av_estimate_timings(AVFormatContext
*ic
, int64_t old_offset
)
1837 /* get the file size, if possible */
1838 if (ic
->iformat
->flags
& AVFMT_NOFILE
) {
1841 file_size
= url_fsize(ic
->pb
);
1845 ic
->file_size
= file_size
;
1847 if ((!strcmp(ic
->iformat
->name
, "mpeg") ||
1848 !strcmp(ic
->iformat
->name
, "mpegts")) &&
1849 file_size
&& !url_is_streamed(ic
->pb
)) {
1850 /* get accurate estimate from the PTSes */
1851 av_estimate_timings_from_pts(ic
, old_offset
);
1852 } else if (av_has_duration(ic
)) {
1853 /* at least one component has timings - we use them for all
1855 fill_all_stream_timings(ic
);
1857 /* less precise: use bitrate info */
1858 av_estimate_timings_from_bit_rate(ic
);
1860 av_update_stream_timings(ic
);
1866 for(i
= 0;i
< ic
->nb_streams
; i
++) {
1867 st
= ic
->streams
[i
];
1868 printf("%d: start_time: %0.3f duration: %0.3f\n",
1869 i
, (double)st
->start_time
/ AV_TIME_BASE
,
1870 (double)st
->duration
/ AV_TIME_BASE
);
1872 printf("stream: start_time: %0.3f duration: %0.3f bitrate=%d kb/s\n",
1873 (double)ic
->start_time
/ AV_TIME_BASE
,
1874 (double)ic
->duration
/ AV_TIME_BASE
,
1875 ic
->bit_rate
/ 1000);
1880 static int has_codec_parameters(AVCodecContext
*enc
)
1883 switch(enc
->codec_type
) {
1884 case CODEC_TYPE_AUDIO
:
1885 val
= enc
->sample_rate
&& enc
->channels
&& enc
->sample_fmt
!= SAMPLE_FMT_NONE
;
1886 if(!enc
->frame_size
&&
1887 (enc
->codec_id
== CODEC_ID_VORBIS
||
1888 enc
->codec_id
== CODEC_ID_AAC
||
1889 enc
->codec_id
== CODEC_ID_MP3
||
1890 enc
->codec_id
== CODEC_ID_SPEEX
))
1893 case CODEC_TYPE_VIDEO
:
1894 val
= enc
->width
&& enc
->pix_fmt
!= PIX_FMT_NONE
;
1900 return enc
->codec_id
!= CODEC_ID_NONE
&& val
!= 0;
1903 static int try_decode_frame(AVStream
*st
, AVPacket
*avpkt
)
1907 int got_picture
, data_size
, ret
=0;
1910 if(!st
->codec
->codec
){
1911 codec
= avcodec_find_decoder(st
->codec
->codec_id
);
1914 ret
= avcodec_open(st
->codec
, codec
);
1919 if(!has_codec_parameters(st
->codec
)){
1920 switch(st
->codec
->codec_type
) {
1921 case CODEC_TYPE_VIDEO
:
1922 avcodec_get_frame_defaults(&picture
);
1923 ret
= avcodec_decode_video2(st
->codec
, &picture
,
1924 &got_picture
, avpkt
);
1926 case CODEC_TYPE_AUDIO
:
1927 data_size
= FFMAX(avpkt
->size
, AVCODEC_MAX_AUDIO_FRAME_SIZE
);
1928 samples
= av_malloc(data_size
);
1931 ret
= avcodec_decode_audio3(st
->codec
, samples
,
1943 unsigned int ff_codec_get_tag(const AVCodecTag
*tags
, int id
)
1945 while (tags
->id
!= CODEC_ID_NONE
) {
1953 enum CodecID
ff_codec_get_id(const AVCodecTag
*tags
, unsigned int tag
)
1956 for(i
=0; tags
[i
].id
!= CODEC_ID_NONE
;i
++) {
1957 if(tag
== tags
[i
].tag
)
1960 for(i
=0; tags
[i
].id
!= CODEC_ID_NONE
; i
++) {
1961 if( toupper((tag
>> 0)&0xFF) == toupper((tags
[i
].tag
>> 0)&0xFF)
1962 && toupper((tag
>> 8)&0xFF) == toupper((tags
[i
].tag
>> 8)&0xFF)
1963 && toupper((tag
>>16)&0xFF) == toupper((tags
[i
].tag
>>16)&0xFF)
1964 && toupper((tag
>>24)&0xFF) == toupper((tags
[i
].tag
>>24)&0xFF))
1967 return CODEC_ID_NONE
;
1970 unsigned int av_codec_get_tag(const AVCodecTag
* const *tags
, enum CodecID id
)
1973 for(i
=0; tags
&& tags
[i
]; i
++){
1974 int tag
= ff_codec_get_tag(tags
[i
], id
);
1980 enum CodecID
av_codec_get_id(const AVCodecTag
* const *tags
, unsigned int tag
)
1983 for(i
=0; tags
&& tags
[i
]; i
++){
1984 enum CodecID id
= ff_codec_get_id(tags
[i
], tag
);
1985 if(id
!=CODEC_ID_NONE
) return id
;
1987 return CODEC_ID_NONE
;
1990 static void compute_chapters_end(AVFormatContext
*s
)
1994 for (i
=0; i
+1<s
->nb_chapters
; i
++)
1995 if (s
->chapters
[i
]->end
== AV_NOPTS_VALUE
) {
1996 assert(s
->chapters
[i
]->start
<= s
->chapters
[i
+1]->start
);
1997 assert(!av_cmp_q(s
->chapters
[i
]->time_base
, s
->chapters
[i
+1]->time_base
));
1998 s
->chapters
[i
]->end
= s
->chapters
[i
+1]->start
;
2001 if (s
->nb_chapters
&& s
->chapters
[i
]->end
== AV_NOPTS_VALUE
) {
2002 assert(s
->start_time
!= AV_NOPTS_VALUE
);
2003 assert(s
->duration
> 0);
2004 s
->chapters
[i
]->end
= av_rescale_q(s
->start_time
+ s
->duration
,
2006 s
->chapters
[i
]->time_base
);
2010 #define MAX_STD_TIMEBASES (60*12+5)
2011 static int get_std_framerate(int i
){
2012 if(i
<60*12) return i
*1001;
2013 else return ((const int[]){24,30,60,12,15})[i
-60*12]*1000*12;
2017 * Is the time base unreliable.
2018 * This is a heuristic to balance between quick acceptance of the values in
2019 * the headers vs. some extra checks.
2020 * Old DivX and Xvid often have nonsense timebases like 1fps or 2fps.
2021 * MPEG-2 commonly misuses field repeat flags to store different framerates.
2022 * And there are "variable" fps files this needs to detect as well.
2024 static int tb_unreliable(AVCodecContext
*c
){
2025 if( c
->time_base
.den
>= 101L*c
->time_base
.num
2026 || c
->time_base
.den
< 5L*c
->time_base
.num
2027 /* || c->codec_tag == AV_RL32("DIVX")
2028 || c->codec_tag == AV_RL32("XVID")*/
2029 || c
->codec_id
== CODEC_ID_MPEG2VIDEO
2030 || c
->codec_id
== CODEC_ID_H264
2036 int av_find_stream_info(AVFormatContext
*ic
)
2038 int i
, count
, ret
, read_size
, j
;
2040 AVPacket pkt1
, *pkt
;
2041 int64_t last_dts
[MAX_STREAMS
];
2042 int64_t duration_gcd
[MAX_STREAMS
]={0};
2043 int duration_count
[MAX_STREAMS
]={0};
2044 double (*duration_error
)[MAX_STD_TIMEBASES
];
2045 int64_t old_offset
= url_ftell(ic
->pb
);
2046 int64_t codec_info_duration
[MAX_STREAMS
]={0};
2047 int codec_info_nb_frames
[MAX_STREAMS
]={0};
2049 duration_error
= av_mallocz(MAX_STREAMS
* sizeof(*duration_error
));
2050 if (!duration_error
) return AVERROR(ENOMEM
);
2052 for(i
=0;i
<ic
->nb_streams
;i
++) {
2053 st
= ic
->streams
[i
];
2054 if(st
->codec
->codec_type
== CODEC_TYPE_VIDEO
){
2055 /* if(!st->time_base.num)
2057 if(!st
->codec
->time_base
.num
)
2058 st
->codec
->time_base
= st
->time_base
;
2060 //only for the split stuff
2062 st
->parser
= av_parser_init(st
->codec
->codec_id
);
2063 if(st
->need_parsing
== AVSTREAM_PARSE_HEADERS
&& st
->parser
){
2064 st
->parser
->flags
|= PARSER_FLAG_COMPLETE_FRAMES
;
2069 for(i
=0;i
<MAX_STREAMS
;i
++){
2070 last_dts
[i
]= AV_NOPTS_VALUE
;
2076 if(url_interrupt_cb()){
2077 ret
= AVERROR(EINTR
);
2078 av_log(ic
, AV_LOG_DEBUG
, "interrupted\n");
2082 /* check if one codec still needs to be handled */
2083 for(i
=0;i
<ic
->nb_streams
;i
++) {
2084 st
= ic
->streams
[i
];
2085 if (!has_codec_parameters(st
->codec
))
2087 /* variable fps and no guess at the real fps */
2088 if( tb_unreliable(st
->codec
)
2089 && duration_count
[i
]<20 && st
->codec
->codec_type
== CODEC_TYPE_VIDEO
)
2091 if(st
->parser
&& st
->parser
->parser
->split
&& !st
->codec
->extradata
)
2093 if(st
->first_dts
== AV_NOPTS_VALUE
)
2096 if (i
== ic
->nb_streams
) {
2097 /* NOTE: if the format has no header, then we need to read
2098 some packets to get most of the streams, so we cannot
2100 if (!(ic
->ctx_flags
& AVFMTCTX_NOHEADER
)) {
2101 /* if we found the info for all the codecs, we can stop */
2103 av_log(ic
, AV_LOG_DEBUG
, "All info found\n");
2107 /* we did not get all the codec info, but we read too much data */
2108 if (read_size
>= ic
->probesize
) {
2110 av_log(ic
, AV_LOG_WARNING
, "MAX_READ_SIZE:%d reached\n", ic
->probesize
);
2114 /* NOTE: a new stream can be added there if no header in file
2115 (AVFMTCTX_NOHEADER) */
2116 ret
= av_read_frame_internal(ic
, &pkt1
);
2117 if(ret
== AVERROR(EAGAIN
))
2121 ret
= -1; /* we could not have all the codec parameters before EOF */
2122 for(i
=0;i
<ic
->nb_streams
;i
++) {
2123 st
= ic
->streams
[i
];
2124 if (!has_codec_parameters(st
->codec
)){
2126 avcodec_string(buf
, sizeof(buf
), st
->codec
, 0);
2127 av_log(ic
, AV_LOG_WARNING
, "Could not find codec parameters (%s)\n", buf
);
2135 pkt
= add_to_pktbuf(&ic
->packet_buffer
, &pkt1
, &ic
->packet_buffer_end
);
2136 if(av_dup_packet(pkt
) < 0) {
2137 av_free(duration_error
);
2138 return AVERROR(ENOMEM
);
2141 read_size
+= pkt
->size
;
2143 st
= ic
->streams
[pkt
->stream_index
];
2144 if(codec_info_nb_frames
[st
->index
]>1) {
2145 if (st
->time_base
.den
> 0 && av_rescale_q(codec_info_duration
[st
->index
], st
->time_base
, AV_TIME_BASE_Q
) >= ic
->max_analyze_duration
){
2146 av_log(ic
, AV_LOG_WARNING
, "max_analyze_duration reached\n");
2149 codec_info_duration
[st
->index
] += pkt
->duration
;
2151 if (pkt
->duration
!= 0)
2152 codec_info_nb_frames
[st
->index
]++;
2155 int index
= pkt
->stream_index
;
2156 int64_t last
= last_dts
[index
];
2157 int64_t duration
= pkt
->dts
- last
;
2159 if(pkt
->dts
!= AV_NOPTS_VALUE
&& last
!= AV_NOPTS_VALUE
&& duration
>0){
2160 double dur
= duration
* av_q2d(st
->time_base
);
2162 // if(st->codec->codec_type == CODEC_TYPE_VIDEO)
2163 // av_log(NULL, AV_LOG_ERROR, "%f\n", dur);
2164 if(duration_count
[index
] < 2)
2165 memset(duration_error
[index
], 0, sizeof(*duration_error
));
2166 for(i
=1; i
<MAX_STD_TIMEBASES
; i
++){
2167 int framerate
= get_std_framerate(i
);
2168 int ticks
= lrintf(dur
*framerate
/(1001*12));
2169 double error
= dur
- ticks
*1001*12/(double)framerate
;
2170 duration_error
[index
][i
] += error
*error
;
2172 duration_count
[index
]++;
2173 // ignore the first 4 values, they might have some random jitter
2174 if (duration_count
[index
] > 3)
2175 duration_gcd
[index
] = av_gcd(duration_gcd
[index
], duration
);
2177 if(last
== AV_NOPTS_VALUE
|| duration_count
[index
]<=1)
2178 last_dts
[pkt
->stream_index
]= pkt
->dts
;
2180 if(st
->parser
&& st
->parser
->parser
->split
&& !st
->codec
->extradata
){
2181 int i
= st
->parser
->parser
->split(st
->codec
, pkt
->data
, pkt
->size
);
2183 st
->codec
->extradata_size
= i
;
2184 st
->codec
->extradata
= av_malloc(st
->codec
->extradata_size
+ FF_INPUT_BUFFER_PADDING_SIZE
);
2185 memcpy(st
->codec
->extradata
, pkt
->data
, st
->codec
->extradata_size
);
2186 memset(st
->codec
->extradata
+ i
, 0, FF_INPUT_BUFFER_PADDING_SIZE
);
2190 /* if still no information, we try to open the codec and to
2191 decompress the frame. We try to avoid that in most cases as
2192 it takes longer and uses more memory. For MPEG-4, we need to
2193 decompress for QuickTime. */
2194 if (!has_codec_parameters(st
->codec
) /*&&
2195 (st->codec->codec_id == CODEC_ID_FLV1 ||
2196 st->codec->codec_id == CODEC_ID_H264 ||
2197 st->codec->codec_id == CODEC_ID_H263 ||
2198 st->codec->codec_id == CODEC_ID_H261 ||
2199 st->codec->codec_id == CODEC_ID_VORBIS ||
2200 st->codec->codec_id == CODEC_ID_MJPEG ||
2201 st->codec->codec_id == CODEC_ID_PNG ||
2202 st->codec->codec_id == CODEC_ID_PAM ||
2203 st->codec->codec_id == CODEC_ID_PGM ||
2204 st->codec->codec_id == CODEC_ID_PGMYUV ||
2205 st->codec->codec_id == CODEC_ID_PBM ||
2206 st->codec->codec_id == CODEC_ID_PPM ||
2207 st->codec->codec_id == CODEC_ID_SHORTEN ||
2208 (st->codec->codec_id == CODEC_ID_MPEG4 && !st->need_parsing))*/)
2209 try_decode_frame(st
, pkt
);
2214 // close codecs which were opened in try_decode_frame()
2215 for(i
=0;i
<ic
->nb_streams
;i
++) {
2216 st
= ic
->streams
[i
];
2217 if(st
->codec
->codec
)
2218 avcodec_close(st
->codec
);
2220 for(i
=0;i
<ic
->nb_streams
;i
++) {
2221 st
= ic
->streams
[i
];
2222 if (st
->codec
->codec_type
== CODEC_TYPE_VIDEO
) {
2223 if(st
->codec
->codec_id
== CODEC_ID_RAWVIDEO
&& !st
->codec
->codec_tag
&& !st
->codec
->bits_per_coded_sample
)
2224 st
->codec
->codec_tag
= avcodec_pix_fmt_to_codec_tag(st
->codec
->pix_fmt
);
2226 // the check for tb_unreliable() is not completely correct, since this is not about handling
2227 // a unreliable/inexact time base, but a time base that is finer than necessary, as e.g.
2228 // ipmovie.c produces.
2229 if (tb_unreliable(st
->codec
) && duration_count
[i
] > 15 && duration_gcd
[i
] > 1)
2230 av_reduce(&st
->r_frame_rate
.num
, &st
->r_frame_rate
.den
, st
->time_base
.den
, st
->time_base
.num
* duration_gcd
[i
], INT_MAX
);
2231 if(duration_count
[i
]
2232 && tb_unreliable(st
->codec
) /*&&
2233 //FIXME we should not special-case MPEG-2, but this needs testing with non-MPEG-2 ...
2234 st->time_base.num*duration_sum[i]/duration_count[i]*101LL > st->time_base.den*/){
2236 double best_error
= 2*av_q2d(st
->time_base
);
2237 best_error
= best_error
*best_error
*duration_count
[i
]*1000*12*30;
2239 for(j
=1; j
<MAX_STD_TIMEBASES
; j
++){
2240 double error
= duration_error
[i
][j
] * get_std_framerate(j
);
2241 // if(st->codec->codec_type == CODEC_TYPE_VIDEO)
2242 // av_log(NULL, AV_LOG_ERROR, "%f %f\n", get_std_framerate(j) / 12.0/1001, error);
2243 if(error
< best_error
){
2245 num
= get_std_framerate(j
);
2248 // do not increase frame rate by more than 1 % in order to match a standard rate.
2249 if (num
&& (!st
->r_frame_rate
.num
|| (double)num
/(12*1001) < 1.01 * av_q2d(st
->r_frame_rate
)))
2250 av_reduce(&st
->r_frame_rate
.num
, &st
->r_frame_rate
.den
, num
, 12*1001, INT_MAX
);
2253 if (!st
->r_frame_rate
.num
){
2254 if( st
->codec
->time_base
.den
* (int64_t)st
->time_base
.num
2255 <= st
->codec
->time_base
.num
* st
->codec
->ticks_per_frame
* (int64_t)st
->time_base
.den
){
2256 st
->r_frame_rate
.num
= st
->codec
->time_base
.den
;
2257 st
->r_frame_rate
.den
= st
->codec
->time_base
.num
* st
->codec
->ticks_per_frame
;
2259 st
->r_frame_rate
.num
= st
->time_base
.den
;
2260 st
->r_frame_rate
.den
= st
->time_base
.num
;
2263 }else if(st
->codec
->codec_type
== CODEC_TYPE_AUDIO
) {
2264 if(!st
->codec
->bits_per_coded_sample
)
2265 st
->codec
->bits_per_coded_sample
= av_get_bits_per_sample(st
->codec
->codec_id
);
2269 av_estimate_timings(ic
, old_offset
);
2271 compute_chapters_end(ic
);
2274 /* correct DTS for B-frame streams with no timestamps */
2275 for(i
=0;i
<ic
->nb_streams
;i
++) {
2276 st
= ic
->streams
[i
];
2277 if (st
->codec
->codec_type
== CODEC_TYPE_VIDEO
) {
2279 ppktl
= &ic
->packet_buffer
;
2281 if(ppkt1
->stream_index
!= i
)
2283 if(ppkt1
->pkt
->dts
< 0)
2285 if(ppkt1
->pkt
->pts
!= AV_NOPTS_VALUE
)
2287 ppkt1
->pkt
->dts
-= delta
;
2292 st
->cur_dts
-= delta
;
2298 av_free(duration_error
);
2303 /*******************************************************/
2305 int av_read_play(AVFormatContext
*s
)
2307 if (s
->iformat
->read_play
)
2308 return s
->iformat
->read_play(s
);
2310 return av_url_read_fpause(s
->pb
, 0);
2311 return AVERROR(ENOSYS
);
2314 int av_read_pause(AVFormatContext
*s
)
2316 if (s
->iformat
->read_pause
)
2317 return s
->iformat
->read_pause(s
);
2319 return av_url_read_fpause(s
->pb
, 1);
2320 return AVERROR(ENOSYS
);
2323 void av_close_input_stream(AVFormatContext
*s
)
2328 if (s
->iformat
->read_close
)
2329 s
->iformat
->read_close(s
);
2330 for(i
=0;i
<s
->nb_streams
;i
++) {
2331 /* free all data in a stream component */
2334 av_parser_close(st
->parser
);
2335 av_free_packet(&st
->cur_pkt
);
2337 av_metadata_free(&st
->metadata
);
2338 av_free(st
->index_entries
);
2339 av_free(st
->codec
->extradata
);
2341 #if LIBAVFORMAT_VERSION_INT < (53<<16)
2342 av_free(st
->filename
);
2344 av_free(st
->priv_data
);
2347 for(i
=s
->nb_programs
-1; i
>=0; i
--) {
2348 #if LIBAVFORMAT_VERSION_INT < (53<<16)
2349 av_freep(&s
->programs
[i
]->provider_name
);
2350 av_freep(&s
->programs
[i
]->name
);
2352 av_metadata_free(&s
->programs
[i
]->metadata
);
2353 av_freep(&s
->programs
[i
]->stream_index
);
2354 av_freep(&s
->programs
[i
]);
2356 av_freep(&s
->programs
);
2357 flush_packet_queue(s
);
2358 av_freep(&s
->priv_data
);
2359 while(s
->nb_chapters
--) {
2360 #if LIBAVFORMAT_VERSION_INT < (53<<16)
2361 av_free(s
->chapters
[s
->nb_chapters
]->title
);
2363 av_metadata_free(&s
->chapters
[s
->nb_chapters
]->metadata
);
2364 av_free(s
->chapters
[s
->nb_chapters
]);
2366 av_freep(&s
->chapters
);
2367 av_metadata_free(&s
->metadata
);
2371 void av_close_input_file(AVFormatContext
*s
)
2373 ByteIOContext
*pb
= s
->iformat
->flags
& AVFMT_NOFILE
? NULL
: s
->pb
;
2374 av_close_input_stream(s
);
2379 AVStream
*av_new_stream(AVFormatContext
*s
, int id
)
2384 if (s
->nb_streams
>= MAX_STREAMS
)
2387 st
= av_mallocz(sizeof(AVStream
));
2391 st
->codec
= avcodec_alloc_context();
2393 /* no default bitrate if decoding */
2394 st
->codec
->bit_rate
= 0;
2396 st
->index
= s
->nb_streams
;
2398 st
->start_time
= AV_NOPTS_VALUE
;
2399 st
->duration
= AV_NOPTS_VALUE
;
2400 /* we set the current DTS to 0 so that formats without any timestamps
2401 but durations get some timestamps, formats with some unknown
2402 timestamps have their first few packets buffered and the
2403 timestamps corrected before they are returned to the user */
2405 st
->first_dts
= AV_NOPTS_VALUE
;
2406 st
->probe_packets
= MAX_PROBE_PACKETS
;
2408 /* default pts setting is MPEG-like */
2409 av_set_pts_info(st
, 33, 1, 90000);
2410 st
->last_IP_pts
= AV_NOPTS_VALUE
;
2411 for(i
=0; i
<MAX_REORDER_DELAY
+1; i
++)
2412 st
->pts_buffer
[i
]= AV_NOPTS_VALUE
;
2413 st
->reference_dts
= AV_NOPTS_VALUE
;
2415 st
->sample_aspect_ratio
= (AVRational
){0,1};
2417 s
->streams
[s
->nb_streams
++] = st
;
2421 AVProgram
*av_new_program(AVFormatContext
*ac
, int id
)
2423 AVProgram
*program
=NULL
;
2427 av_log(ac
, AV_LOG_DEBUG
, "new_program: id=0x%04x\n", id
);
2430 for(i
=0; i
<ac
->nb_programs
; i
++)
2431 if(ac
->programs
[i
]->id
== id
)
2432 program
= ac
->programs
[i
];
2435 program
= av_mallocz(sizeof(AVProgram
));
2438 dynarray_add(&ac
->programs
, &ac
->nb_programs
, program
);
2439 program
->discard
= AVDISCARD_NONE
;
2446 AVChapter
*ff_new_chapter(AVFormatContext
*s
, int id
, AVRational time_base
, int64_t start
, int64_t end
, const char *title
)
2448 AVChapter
*chapter
= NULL
;
2451 for(i
=0; i
<s
->nb_chapters
; i
++)
2452 if(s
->chapters
[i
]->id
== id
)
2453 chapter
= s
->chapters
[i
];
2456 chapter
= av_mallocz(sizeof(AVChapter
));
2459 dynarray_add(&s
->chapters
, &s
->nb_chapters
, chapter
);
2461 #if LIBAVFORMAT_VERSION_INT < (53<<16)
2462 av_free(chapter
->title
);
2464 av_metadata_set(&chapter
->metadata
, "title", title
);
2466 chapter
->time_base
= time_base
;
2467 chapter
->start
= start
;
2473 /************************************************************/
2474 /* output media file */
2476 int av_set_parameters(AVFormatContext
*s
, AVFormatParameters
*ap
)
2480 if (s
->oformat
->priv_data_size
> 0) {
2481 s
->priv_data
= av_mallocz(s
->oformat
->priv_data_size
);
2483 return AVERROR(ENOMEM
);
2485 s
->priv_data
= NULL
;
2487 if (s
->oformat
->set_parameters
) {
2488 ret
= s
->oformat
->set_parameters(s
, ap
);
2495 int av_write_header(AVFormatContext
*s
)
2500 // some sanity checks
2501 for(i
=0;i
<s
->nb_streams
;i
++) {
2504 switch (st
->codec
->codec_type
) {
2505 case CODEC_TYPE_AUDIO
:
2506 if(st
->codec
->sample_rate
<=0){
2507 av_log(s
, AV_LOG_ERROR
, "sample rate not set\n");
2510 if(!st
->codec
->block_align
)
2511 st
->codec
->block_align
= st
->codec
->channels
*
2512 av_get_bits_per_sample(st
->codec
->codec_id
) >> 3;
2514 case CODEC_TYPE_VIDEO
:
2515 if(st
->codec
->time_base
.num
<=0 || st
->codec
->time_base
.den
<=0){ //FIXME audio too?
2516 av_log(s
, AV_LOG_ERROR
, "time base not set\n");
2519 if(st
->codec
->width
<=0 || st
->codec
->height
<=0){
2520 av_log(s
, AV_LOG_ERROR
, "dimensions not set\n");
2523 if(av_cmp_q(st
->sample_aspect_ratio
, st
->codec
->sample_aspect_ratio
)){
2524 av_log(s
, AV_LOG_ERROR
, "Aspect ratio mismatch between encoder and muxer layer\n");
2530 if(s
->oformat
->codec_tag
){
2531 if(st
->codec
->codec_tag
){
2533 //check that tag + id is in the table
2534 //if neither is in the table -> OK
2535 //if tag is in the table with another id -> FAIL
2536 //if id is in the table with another tag -> FAIL unless strict < ?
2538 st
->codec
->codec_tag
= av_codec_get_tag(s
->oformat
->codec_tag
, st
->codec
->codec_id
);
2541 if(s
->oformat
->flags
& AVFMT_GLOBALHEADER
&&
2542 !(st
->codec
->flags
& CODEC_FLAG_GLOBAL_HEADER
))
2543 av_log(s
, AV_LOG_WARNING
, "Codec for stream %d does not use global headers but container format requires global headers\n", i
);
2546 if (!s
->priv_data
&& s
->oformat
->priv_data_size
> 0) {
2547 s
->priv_data
= av_mallocz(s
->oformat
->priv_data_size
);
2549 return AVERROR(ENOMEM
);
2552 #if LIBAVFORMAT_VERSION_MAJOR < 53
2553 ff_metadata_mux_compat(s
);
2556 if(s
->oformat
->write_header
){
2557 ret
= s
->oformat
->write_header(s
);
2562 /* init PTS generation */
2563 for(i
=0;i
<s
->nb_streams
;i
++) {
2564 int64_t den
= AV_NOPTS_VALUE
;
2567 switch (st
->codec
->codec_type
) {
2568 case CODEC_TYPE_AUDIO
:
2569 den
= (int64_t)st
->time_base
.num
* st
->codec
->sample_rate
;
2571 case CODEC_TYPE_VIDEO
:
2572 den
= (int64_t)st
->time_base
.num
* st
->codec
->time_base
.den
;
2577 if (den
!= AV_NOPTS_VALUE
) {
2579 return AVERROR_INVALIDDATA
;
2580 av_frac_init(&st
->pts
, 0, 0, den
);
2586 //FIXME merge with compute_pkt_fields
2587 static int compute_pkt_fields2(AVStream
*st
, AVPacket
*pkt
){
2588 int delay
= FFMAX(st
->codec
->has_b_frames
, !!st
->codec
->max_b_frames
);
2589 int num
, den
, frame_size
, i
;
2591 // av_log(st->codec, AV_LOG_DEBUG, "av_write_frame: pts:%"PRId64" dts:%"PRId64" cur_dts:%"PRId64" b:%d size:%d st:%d\n", pkt->pts, pkt->dts, st->cur_dts, delay, pkt->size, pkt->stream_index);
2593 /* if(pkt->pts == AV_NOPTS_VALUE && pkt->dts == AV_NOPTS_VALUE)
2596 /* duration field */
2597 if (pkt
->duration
== 0) {
2598 compute_frame_duration(&num
, &den
, st
, NULL
, pkt
);
2600 pkt
->duration
= av_rescale(1, num
* (int64_t)st
->time_base
.den
* st
->codec
->ticks_per_frame
, den
* (int64_t)st
->time_base
.num
);
2604 if(pkt
->pts
== AV_NOPTS_VALUE
&& pkt
->dts
!= AV_NOPTS_VALUE
&& delay
==0)
2607 //XXX/FIXME this is a temporary hack until all encoders output pts
2608 if((pkt
->pts
== 0 || pkt
->pts
== AV_NOPTS_VALUE
) && pkt
->dts
== AV_NOPTS_VALUE
&& !delay
){
2610 // pkt->pts= st->cur_dts;
2611 pkt
->pts
= st
->pts
.val
;
2614 //calculate dts from pts
2615 if(pkt
->pts
!= AV_NOPTS_VALUE
&& pkt
->dts
== AV_NOPTS_VALUE
&& delay
<= MAX_REORDER_DELAY
){
2616 st
->pts_buffer
[0]= pkt
->pts
;
2617 for(i
=1; i
<delay
+1 && st
->pts_buffer
[i
] == AV_NOPTS_VALUE
; i
++)
2618 st
->pts_buffer
[i
]= (i
-delay
-1) * pkt
->duration
;
2619 for(i
=0; i
<delay
&& st
->pts_buffer
[i
] > st
->pts_buffer
[i
+1]; i
++)
2620 FFSWAP(int64_t, st
->pts_buffer
[i
], st
->pts_buffer
[i
+1]);
2622 pkt
->dts
= st
->pts_buffer
[0];
2625 if(st
->cur_dts
&& st
->cur_dts
!= AV_NOPTS_VALUE
&& st
->cur_dts
>= pkt
->dts
){
2626 av_log(st
->codec
, AV_LOG_ERROR
, "error, non monotone timestamps %"PRId64
" >= %"PRId64
"\n", st
->cur_dts
, pkt
->dts
);
2629 if(pkt
->dts
!= AV_NOPTS_VALUE
&& pkt
->pts
!= AV_NOPTS_VALUE
&& pkt
->pts
< pkt
->dts
){
2630 av_log(st
->codec
, AV_LOG_ERROR
, "error, pts < dts\n");
2634 // av_log(NULL, AV_LOG_DEBUG, "av_write_frame: pts2:%"PRId64" dts2:%"PRId64"\n", pkt->pts, pkt->dts);
2635 st
->cur_dts
= pkt
->dts
;
2636 st
->pts
.val
= pkt
->dts
;
2639 switch (st
->codec
->codec_type
) {
2640 case CODEC_TYPE_AUDIO
:
2641 frame_size
= get_audio_frame_size(st
->codec
, pkt
->size
);
2643 /* HACK/FIXME, we skip the initial 0 size packets as they are most
2644 likely equal to the encoder delay, but it would be better if we
2645 had the real timestamps from the encoder */
2646 if (frame_size
>= 0 && (pkt
->size
|| st
->pts
.num
!=st
->pts
.den
>>1 || st
->pts
.val
)) {
2647 av_frac_add(&st
->pts
, (int64_t)st
->time_base
.den
* frame_size
);
2650 case CODEC_TYPE_VIDEO
:
2651 av_frac_add(&st
->pts
, (int64_t)st
->time_base
.den
* st
->codec
->time_base
.num
);
2659 int av_write_frame(AVFormatContext
*s
, AVPacket
*pkt
)
2661 int ret
= compute_pkt_fields2(s
->streams
[pkt
->stream_index
], pkt
);
2663 if(ret
<0 && !(s
->oformat
->flags
& AVFMT_NOTIMESTAMPS
))
2666 ret
= s
->oformat
->write_packet(s
, pkt
);
2668 ret
= url_ferror(s
->pb
);
2672 void ff_interleave_add_packet(AVFormatContext
*s
, AVPacket
*pkt
,
2673 int (*compare
)(AVFormatContext
*, AVPacket
*, AVPacket
*))
2675 AVPacketList
**next_point
, *this_pktl
;
2677 this_pktl
= av_mallocz(sizeof(AVPacketList
));
2678 this_pktl
->pkt
= *pkt
;
2679 pkt
->destruct
= NULL
; // do not free original but only the copy
2680 av_dup_packet(&this_pktl
->pkt
); // duplicate the packet if it uses non-alloced memory
2682 if(s
->streams
[pkt
->stream_index
]->last_in_packet_buffer
){
2683 next_point
= &(s
->streams
[pkt
->stream_index
]->last_in_packet_buffer
->next
);
2685 next_point
= &s
->packet_buffer
;
2688 if(compare(s
, &s
->packet_buffer_end
->pkt
, pkt
)){
2689 while(!compare(s
, &(*next_point
)->pkt
, pkt
)){
2690 next_point
= &(*next_point
)->next
;
2694 next_point
= &(s
->packet_buffer_end
->next
);
2697 assert(!*next_point
);
2699 s
->packet_buffer_end
= this_pktl
;
2702 this_pktl
->next
= *next_point
;
2704 s
->streams
[pkt
->stream_index
]->last_in_packet_buffer
=
2705 *next_point
= this_pktl
;
2708 int ff_interleave_compare_dts(AVFormatContext
*s
, AVPacket
*next
, AVPacket
*pkt
)
2710 AVStream
*st
= s
->streams
[ pkt
->stream_index
];
2711 AVStream
*st2
= s
->streams
[ next
->stream_index
];
2712 int64_t left
= st2
->time_base
.num
* (int64_t)st
->time_base
.den
;
2713 int64_t right
= st
->time_base
.num
* (int64_t)st2
->time_base
.den
;
2715 if (pkt
->dts
== AV_NOPTS_VALUE
)
2718 return next
->dts
* left
> pkt
->dts
* right
; //FIXME this can overflow
2721 int av_interleave_packet_per_dts(AVFormatContext
*s
, AVPacket
*out
, AVPacket
*pkt
, int flush
){
2727 ff_interleave_add_packet(s
, pkt
, ff_interleave_compare_dts
);
2730 for(i
=0; i
< s
->nb_streams
; i
++)
2731 stream_count
+= !!s
->streams
[i
]->last_in_packet_buffer
;
2733 if(stream_count
&& (s
->nb_streams
== stream_count
|| flush
)){
2734 pktl
= s
->packet_buffer
;
2737 s
->packet_buffer
= pktl
->next
;
2738 if(!s
->packet_buffer
)
2739 s
->packet_buffer_end
= NULL
;
2741 if(s
->streams
[out
->stream_index
]->last_in_packet_buffer
== pktl
)
2742 s
->streams
[out
->stream_index
]->last_in_packet_buffer
= NULL
;
2746 av_init_packet(out
);
2752 * Interleaves an AVPacket correctly so it can be muxed.
2753 * @param out the interleaved packet will be output here
2754 * @param in the input packet
2755 * @param flush 1 if no further packets are available as input and all
2756 * remaining packets should be output
2757 * @return 1 if a packet was output, 0 if no packet could be output,
2758 * < 0 if an error occurred
2760 static int av_interleave_packet(AVFormatContext
*s
, AVPacket
*out
, AVPacket
*in
, int flush
){
2761 if(s
->oformat
->interleave_packet
)
2762 return s
->oformat
->interleave_packet(s
, out
, in
, flush
);
2764 return av_interleave_packet_per_dts(s
, out
, in
, flush
);
2767 int av_interleaved_write_frame(AVFormatContext
*s
, AVPacket
*pkt
){
2768 AVStream
*st
= s
->streams
[ pkt
->stream_index
];
2770 //FIXME/XXX/HACK drop zero sized packets
2771 if(st
->codec
->codec_type
== CODEC_TYPE_AUDIO
&& pkt
->size
==0)
2774 //av_log(NULL, AV_LOG_DEBUG, "av_interleaved_write_frame %d %"PRId64" %"PRId64"\n", pkt->size, pkt->dts, pkt->pts);
2775 if(compute_pkt_fields2(st
, pkt
) < 0 && !(s
->oformat
->flags
& AVFMT_NOTIMESTAMPS
))
2778 if(pkt
->dts
== AV_NOPTS_VALUE
&& !(s
->oformat
->flags
& AVFMT_NOTIMESTAMPS
))
2783 int ret
= av_interleave_packet(s
, &opkt
, pkt
, 0);
2784 if(ret
<=0) //FIXME cleanup needed for ret<0 ?
2787 ret
= s
->oformat
->write_packet(s
, &opkt
);
2789 av_free_packet(&opkt
);
2794 if(url_ferror(s
->pb
))
2795 return url_ferror(s
->pb
);
2799 int av_write_trailer(AVFormatContext
*s
)
2805 ret
= av_interleave_packet(s
, &pkt
, NULL
, 1);
2806 if(ret
<0) //FIXME cleanup needed for ret<0 ?
2811 ret
= s
->oformat
->write_packet(s
, &pkt
);
2813 av_free_packet(&pkt
);
2817 if(url_ferror(s
->pb
))
2821 if(s
->oformat
->write_trailer
)
2822 ret
= s
->oformat
->write_trailer(s
);
2825 ret
=url_ferror(s
->pb
);
2826 for(i
=0;i
<s
->nb_streams
;i
++)
2827 av_freep(&s
->streams
[i
]->priv_data
);
2828 av_freep(&s
->priv_data
);
2832 void av_program_add_stream_index(AVFormatContext
*ac
, int progid
, unsigned int idx
)
2835 AVProgram
*program
=NULL
;
2838 if (idx
>= ac
->nb_streams
) {
2839 av_log(ac
, AV_LOG_ERROR
, "stream index %d is not valid\n", idx
);
2843 for(i
=0; i
<ac
->nb_programs
; i
++){
2844 if(ac
->programs
[i
]->id
!= progid
)
2846 program
= ac
->programs
[i
];
2847 for(j
=0; j
<program
->nb_stream_indexes
; j
++)
2848 if(program
->stream_index
[j
] == idx
)
2851 tmp
= av_realloc(program
->stream_index
, sizeof(unsigned int)*(program
->nb_stream_indexes
+1));
2854 program
->stream_index
= tmp
;
2855 program
->stream_index
[program
->nb_stream_indexes
++] = idx
;
2860 static void print_fps(double d
, const char *postfix
){
2861 uint64_t v
= lrintf(d
*100);
2862 if (v
% 100 ) av_log(NULL
, AV_LOG_INFO
, ", %3.2f %s", d
, postfix
);
2863 else if(v
%(100*1000)) av_log(NULL
, AV_LOG_INFO
, ", %1.0f %s", d
, postfix
);
2864 else av_log(NULL
, AV_LOG_INFO
, ", %1.0fk %s", d
/1000, postfix
);
2867 /* "user interface" functions */
2868 static void dump_stream_format(AVFormatContext
*ic
, int i
, int index
, int is_output
)
2871 int flags
= (is_output
? ic
->oformat
->flags
: ic
->iformat
->flags
);
2872 AVStream
*st
= ic
->streams
[i
];
2873 int g
= av_gcd(st
->time_base
.num
, st
->time_base
.den
);
2874 AVMetadataTag
*lang
= av_metadata_get(st
->metadata
, "language", NULL
, 0);
2875 avcodec_string(buf
, sizeof(buf
), st
->codec
, is_output
);
2876 av_log(NULL
, AV_LOG_INFO
, " Stream #%d.%d", index
, i
);
2877 /* the pid is an important information, so we display it */
2878 /* XXX: add a generic system */
2879 if (flags
& AVFMT_SHOW_IDS
)
2880 av_log(NULL
, AV_LOG_INFO
, "[0x%x]", st
->id
);
2882 av_log(NULL
, AV_LOG_INFO
, "(%s)", lang
->value
);
2883 av_log(NULL
, AV_LOG_DEBUG
, ", %d/%d", st
->time_base
.num
/g
, st
->time_base
.den
/g
);
2884 av_log(NULL
, AV_LOG_INFO
, ": %s", buf
);
2885 if (st
->sample_aspect_ratio
.num
&& // default
2886 av_cmp_q(st
->sample_aspect_ratio
, st
->codec
->sample_aspect_ratio
)) {
2887 AVRational display_aspect_ratio
;
2888 av_reduce(&display_aspect_ratio
.num
, &display_aspect_ratio
.den
,
2889 st
->codec
->width
*st
->sample_aspect_ratio
.num
,
2890 st
->codec
->height
*st
->sample_aspect_ratio
.den
,
2892 av_log(NULL
, AV_LOG_INFO
, ", PAR %d:%d DAR %d:%d",
2893 st
->sample_aspect_ratio
.num
, st
->sample_aspect_ratio
.den
,
2894 display_aspect_ratio
.num
, display_aspect_ratio
.den
);
2896 if(st
->codec
->codec_type
== CODEC_TYPE_VIDEO
){
2897 if(st
->r_frame_rate
.den
&& st
->r_frame_rate
.num
)
2898 print_fps(av_q2d(st
->r_frame_rate
), "tbr");
2899 if(st
->time_base
.den
&& st
->time_base
.num
)
2900 print_fps(1/av_q2d(st
->time_base
), "tbn");
2901 if(st
->codec
->time_base
.den
&& st
->codec
->time_base
.num
)
2902 print_fps(1/av_q2d(st
->codec
->time_base
), "tbc");
2904 av_log(NULL
, AV_LOG_INFO
, "\n");
2907 void dump_format(AVFormatContext
*ic
,
2913 uint8_t *printed
= av_mallocz(ic
->nb_streams
);
2914 if (ic
->nb_streams
&& !printed
)
2917 av_log(NULL
, AV_LOG_INFO
, "%s #%d, %s, %s '%s':\n",
2918 is_output
? "Output" : "Input",
2920 is_output
? ic
->oformat
->name
: ic
->iformat
->name
,
2921 is_output
? "to" : "from", url
);
2923 av_log(NULL
, AV_LOG_INFO
, " Duration: ");
2924 if (ic
->duration
!= AV_NOPTS_VALUE
) {
2925 int hours
, mins
, secs
, us
;
2926 secs
= ic
->duration
/ AV_TIME_BASE
;
2927 us
= ic
->duration
% AV_TIME_BASE
;
2932 av_log(NULL
, AV_LOG_INFO
, "%02d:%02d:%02d.%02d", hours
, mins
, secs
,
2933 (100 * us
) / AV_TIME_BASE
);
2935 av_log(NULL
, AV_LOG_INFO
, "N/A");
2937 if (ic
->start_time
!= AV_NOPTS_VALUE
) {
2939 av_log(NULL
, AV_LOG_INFO
, ", start: ");
2940 secs
= ic
->start_time
/ AV_TIME_BASE
;
2941 us
= ic
->start_time
% AV_TIME_BASE
;
2942 av_log(NULL
, AV_LOG_INFO
, "%d.%06d",
2943 secs
, (int)av_rescale(us
, 1000000, AV_TIME_BASE
));
2945 av_log(NULL
, AV_LOG_INFO
, ", bitrate: ");
2947 av_log(NULL
, AV_LOG_INFO
,"%d kb/s", ic
->bit_rate
/ 1000);
2949 av_log(NULL
, AV_LOG_INFO
, "N/A");
2951 av_log(NULL
, AV_LOG_INFO
, "\n");
2953 if(ic
->nb_programs
) {
2954 int j
, k
, total
= 0;
2955 for(j
=0; j
<ic
->nb_programs
; j
++) {
2956 AVMetadataTag
*name
= av_metadata_get(ic
->programs
[j
]->metadata
,
2958 av_log(NULL
, AV_LOG_INFO
, " Program %d %s\n", ic
->programs
[j
]->id
,
2959 name
? name
->value
: "");
2960 for(k
=0; k
<ic
->programs
[j
]->nb_stream_indexes
; k
++) {
2961 dump_stream_format(ic
, ic
->programs
[j
]->stream_index
[k
], index
, is_output
);
2962 printed
[ic
->programs
[j
]->stream_index
[k
]] = 1;
2964 total
+= ic
->programs
[j
]->nb_stream_indexes
;
2966 if (total
< ic
->nb_streams
)
2967 av_log(NULL
, AV_LOG_INFO
, " No Program\n");
2969 for(i
=0;i
<ic
->nb_streams
;i
++)
2971 dump_stream_format(ic
, i
, index
, is_output
);
2974 AVMetadataTag
*tag
=NULL
;
2975 av_log(NULL
, AV_LOG_INFO
, " Metadata\n");
2976 while((tag
=av_metadata_get(ic
->metadata
, "", tag
, AV_METADATA_IGNORE_SUFFIX
))) {
2977 av_log(NULL
, AV_LOG_INFO
, " %-16s: %s\n", tag
->key
, tag
->value
);
2983 #if LIBAVFORMAT_VERSION_MAJOR < 53
2984 int parse_image_size(int *width_ptr
, int *height_ptr
, const char *str
)
2986 return av_parse_video_frame_size(width_ptr
, height_ptr
, str
);
2989 int parse_frame_rate(int *frame_rate_num
, int *frame_rate_den
, const char *arg
)
2991 AVRational frame_rate
;
2992 int ret
= av_parse_video_frame_rate(&frame_rate
, arg
);
2993 *frame_rate_num
= frame_rate
.num
;
2994 *frame_rate_den
= frame_rate
.den
;
2999 int64_t av_gettime(void)
3002 gettimeofday(&tv
,NULL
);
3003 return (int64_t)tv
.tv_sec
* 1000000 + tv
.tv_usec
;
3006 int64_t parse_date(const char *datestr
, int duration
)
3012 static const char * const date_fmt
[] = {
3016 static const char * const time_fmt
[] = {
3026 time_t now
= time(0);
3028 len
= strlen(datestr
);
3030 lastch
= datestr
[len
- 1];
3033 is_utc
= (lastch
== 'z' || lastch
== 'Z');
3035 memset(&dt
, 0, sizeof(dt
));
3040 if (!strncasecmp(datestr
, "now", len
))
3041 return (int64_t) now
* 1000000;
3043 /* parse the year-month-day part */
3044 for (i
= 0; i
< FF_ARRAY_ELEMS(date_fmt
); i
++) {
3045 q
= small_strptime(p
, date_fmt
[i
], &dt
);
3051 /* if the year-month-day part is missing, then take the
3052 * current year-month-day time */
3057 dt
= *localtime(&now
);
3059 dt
.tm_hour
= dt
.tm_min
= dt
.tm_sec
= 0;
3064 if (*p
== 'T' || *p
== 't' || *p
== ' ')
3067 /* parse the hour-minute-second part */
3068 for (i
= 0; i
< FF_ARRAY_ELEMS(time_fmt
); i
++) {
3069 q
= small_strptime(p
, time_fmt
[i
], &dt
);
3075 /* parse datestr as a duration */
3080 /* parse datestr as HH:MM:SS */
3081 q
= small_strptime(p
, time_fmt
[0], &dt
);
3083 /* parse datestr as S+ */
3084 dt
.tm_sec
= strtol(p
, (char **)&q
, 10);
3086 /* the parsing didn't succeed */
3093 /* Now we have all the fields that we can get */
3099 t
= dt
.tm_hour
* 3600 + dt
.tm_min
* 60 + dt
.tm_sec
;
3101 dt
.tm_isdst
= -1; /* unknown */
3111 /* parse the .m... part */
3115 for (val
= 0, n
= 100000; n
>= 1; n
/= 10, q
++) {
3118 val
+= n
* (*q
- '0');
3122 return negative
? -t
: t
;
3125 int find_info_tag(char *arg
, int arg_size
, const char *tag1
, const char *info
)
3135 while (*p
!= '\0' && *p
!= '=' && *p
!= '&') {
3136 if ((q
- tag
) < sizeof(tag
) - 1)
3144 while (*p
!= '&' && *p
!= '\0') {
3145 if ((q
- arg
) < arg_size
- 1) {
3155 if (!strcmp(tag
, tag1
))
3164 int av_get_frame_filename(char *buf
, int buf_size
,
3165 const char *path
, int number
)
3168 char *q
, buf1
[20], c
;
3169 int nd
, len
, percentd_found
;
3181 while (isdigit(*p
)) {
3182 nd
= nd
* 10 + *p
++ - '0';
3185 } while (isdigit(c
));
3194 snprintf(buf1
, sizeof(buf1
), "%0*d", nd
, number
);
3196 if ((q
- buf
+ len
) > buf_size
- 1)
3198 memcpy(q
, buf1
, len
);
3206 if ((q
- buf
) < buf_size
- 1)
3210 if (!percentd_found
)
3219 static void hex_dump_internal(void *avcl
, FILE *f
, int level
, uint8_t *buf
, int size
)
3223 #define PRINT(...) do { if (!f) av_log(avcl, level, __VA_ARGS__); else fprintf(f, __VA_ARGS__); } while(0)
3225 for(i
=0;i
<size
;i
+=16) {
3232 PRINT(" %02x", buf
[i
+j
]);
3237 for(j
=0;j
<len
;j
++) {
3239 if (c
< ' ' || c
> '~')
3248 void av_hex_dump(FILE *f
, uint8_t *buf
, int size
)
3250 hex_dump_internal(NULL
, f
, 0, buf
, size
);
3253 void av_hex_dump_log(void *avcl
, int level
, uint8_t *buf
, int size
)
3255 hex_dump_internal(avcl
, NULL
, level
, buf
, size
);
3258 //FIXME needs to know the time_base
3259 static void pkt_dump_internal(void *avcl
, FILE *f
, int level
, AVPacket
*pkt
, int dump_payload
)
3262 #define PRINT(...) do { if (!f) av_log(avcl, level, __VA_ARGS__); else fprintf(f, __VA_ARGS__); } while(0)
3263 PRINT("stream #%d:\n", pkt
->stream_index
);
3264 PRINT(" keyframe=%d\n", ((pkt
->flags
& PKT_FLAG_KEY
) != 0));
3265 PRINT(" duration=%0.3f\n", (double)pkt
->duration
/ AV_TIME_BASE
);
3266 /* DTS is _always_ valid after av_read_frame() */
3268 if (pkt
->dts
== AV_NOPTS_VALUE
)
3271 PRINT("%0.3f", (double)pkt
->dts
/ AV_TIME_BASE
);
3272 /* PTS may not be known if B-frames are present. */
3274 if (pkt
->pts
== AV_NOPTS_VALUE
)
3277 PRINT("%0.3f", (double)pkt
->pts
/ AV_TIME_BASE
);
3279 PRINT(" size=%d\n", pkt
->size
);
3282 av_hex_dump(f
, pkt
->data
, pkt
->size
);
3285 void av_pkt_dump(FILE *f
, AVPacket
*pkt
, int dump_payload
)
3287 pkt_dump_internal(NULL
, f
, 0, pkt
, dump_payload
);
3290 void av_pkt_dump_log(void *avcl
, int level
, AVPacket
*pkt
, int dump_payload
)
3292 pkt_dump_internal(avcl
, NULL
, level
, pkt
, dump_payload
);
3295 void url_split(char *proto
, int proto_size
,
3296 char *authorization
, int authorization_size
,
3297 char *hostname
, int hostname_size
,
3299 char *path
, int path_size
,
3302 const char *p
, *ls
, *at
, *col
, *brk
;
3304 if (port_ptr
) *port_ptr
= -1;
3305 if (proto_size
> 0) proto
[0] = 0;
3306 if (authorization_size
> 0) authorization
[0] = 0;
3307 if (hostname_size
> 0) hostname
[0] = 0;
3308 if (path_size
> 0) path
[0] = 0;
3310 /* parse protocol */
3311 if ((p
= strchr(url
, ':'))) {
3312 av_strlcpy(proto
, url
, FFMIN(proto_size
, p
+ 1 - url
));
3317 /* no protocol means plain filename */
3318 av_strlcpy(path
, url
, path_size
);
3322 /* separate path from hostname */
3323 ls
= strchr(p
, '/');
3325 ls
= strchr(p
, '?');
3327 av_strlcpy(path
, ls
, path_size
);
3329 ls
= &p
[strlen(p
)]; // XXX
3331 /* the rest is hostname, use that to parse auth/port */
3333 /* authorization (user[:pass]@hostname) */
3334 if ((at
= strchr(p
, '@')) && at
< ls
) {
3335 av_strlcpy(authorization
, p
,
3336 FFMIN(authorization_size
, at
+ 1 - p
));
3337 p
= at
+ 1; /* skip '@' */
3340 if (*p
== '[' && (brk
= strchr(p
, ']')) && brk
< ls
) {
3342 av_strlcpy(hostname
, p
+ 1,
3343 FFMIN(hostname_size
, brk
- p
));
3344 if (brk
[1] == ':' && port_ptr
)
3345 *port_ptr
= atoi(brk
+ 2);
3346 } else if ((col
= strchr(p
, ':')) && col
< ls
) {
3347 av_strlcpy(hostname
, p
,
3348 FFMIN(col
+ 1 - p
, hostname_size
));
3349 if (port_ptr
) *port_ptr
= atoi(col
+ 1);
3351 av_strlcpy(hostname
, p
,
3352 FFMIN(ls
+ 1 - p
, hostname_size
));
3356 char *ff_data_to_hex(char *buff
, const uint8_t *src
, int s
)
3359 static const char hex_table
[16] = { '0', '1', '2', '3',
3362 'C', 'D', 'E', 'F' };
3364 for(i
= 0; i
< s
; i
++) {
3365 buff
[i
* 2] = hex_table
[src
[i
] >> 4];
3366 buff
[i
* 2 + 1] = hex_table
[src
[i
] & 0xF];
3372 void av_set_pts_info(AVStream
*s
, int pts_wrap_bits
,
3373 unsigned int pts_num
, unsigned int pts_den
)
3375 s
->pts_wrap_bits
= pts_wrap_bits
;
3377 if(av_reduce(&s
->time_base
.num
, &s
->time_base
.den
, pts_num
, pts_den
, INT_MAX
)){
3378 if(s
->time_base
.num
!= pts_num
)
3379 av_log(NULL
, AV_LOG_DEBUG
, "st:%d removing common factor %d from timebase\n", s
->index
, pts_num
/s
->time_base
.num
);
3381 av_log(NULL
, AV_LOG_WARNING
, "st:%d has too large timebase, reducing\n", s
->index
);
3383 if(!s
->time_base
.num
|| !s
->time_base
.den
)
3384 s
->time_base
.num
= s
->time_base
.den
= 0;