2 * various utility functions for use within Libav
3 * Copyright (c) 2000, 2001, 2002 Fabrice Bellard
5 * This file is part of Libav.
7 * Libav is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * Libav is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with Libav; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
25 #include "avio_internal.h"
27 #include "libavcodec/internal.h"
28 #include "libavcodec/bytestream.h"
29 #include "libavutil/opt.h"
30 #include "libavutil/dict.h"
31 #include "libavutil/internal.h"
32 #include "libavutil/pixdesc.h"
35 #include "libavutil/avassert.h"
36 #include "libavutil/avstring.h"
37 #include "libavutil/mathematics.h"
38 #include "libavutil/parseutils.h"
39 #include "libavutil/time.h"
41 #include "audiointerleave.h"
53 * various utility functions for use within Libav
56 unsigned avformat_version(void)
58 return LIBAVFORMAT_VERSION_INT
;
61 const char *avformat_configuration(void)
63 return LIBAV_CONFIGURATION
;
66 const char *avformat_license(void)
68 #define LICENSE_PREFIX "libavformat license: "
69 return LICENSE_PREFIX LIBAV_LICENSE
+ sizeof(LICENSE_PREFIX
) - 1;
72 /* an arbitrarily chosen "sane" max packet size -- 50M */
73 #define SANE_CHUNK_SIZE (50000000)
76 * Read the data in sane-sized chunks and append to pkt.
77 * Return the number of bytes read or an error.
79 static int append_packet_chunked(AVIOContext
*s
, AVPacket
*pkt
, int size
)
81 int64_t chunk_size
= size
;
82 int64_t orig_pos
= pkt
->pos
; // av_grow_packet might reset pos
83 int orig_size
= pkt
->size
;
87 int prev_size
= pkt
->size
;
91 * When the caller requests a lot of data, limit it to the amount left
92 * in file or SANE_CHUNK_SIZE when it is not known
94 if (size
> SANE_CHUNK_SIZE
) {
95 int64_t filesize
= avio_size(s
) - avio_tell(s
);
96 chunk_size
= FFMAX(filesize
, SANE_CHUNK_SIZE
);
98 read_size
= FFMIN(size
, chunk_size
);
100 ret
= av_grow_packet(pkt
, read_size
);
104 ret
= avio_read(s
, pkt
->data
+ prev_size
, read_size
);
105 if (ret
!= read_size
) {
106 av_shrink_packet(pkt
, prev_size
+ FFMAX(ret
, 0));
116 return pkt
->size
> orig_size ? pkt
->size
- orig_size
: ret
;
119 int av_get_packet(AVIOContext
*s
, AVPacket
*pkt
, int size
)
124 pkt
->pos
= avio_tell(s
);
126 return append_packet_chunked(s
, pkt
, size
);
129 int av_append_packet(AVIOContext
*s
, AVPacket
*pkt
, int size
)
132 return av_get_packet(s
, pkt
, size
);
133 return append_packet_chunked(s
, pkt
, size
);
137 int av_filename_number_test(const char *filename
)
140 return filename
&& (av_get_frame_filename(buf
, sizeof(buf
), filename
, 1)>=0);
143 AVInputFormat
*av_probe_input_format2(AVProbeData
*pd
, int is_opened
, int *score_max
)
145 AVProbeData lpd
= *pd
;
146 AVInputFormat
*fmt1
= NULL
, *fmt
;
149 if (lpd
.buf_size
> 10 && ff_id3v2_match(lpd
.buf
, ID3v2_DEFAULT_MAGIC
)) {
150 int id3len
= ff_id3v2_tag_len(lpd
.buf
);
151 if (lpd
.buf_size
> id3len
+ 16) {
153 lpd
.buf_size
-= id3len
;
159 while ((fmt1
= av_iformat_next(fmt1
))) {
160 if (!is_opened
== !(fmt1
->flags
& AVFMT_NOFILE
))
163 if (fmt1
->read_probe
) {
164 score
= fmt1
->read_probe(&lpd
);
165 } else if (fmt1
->extensions
) {
166 if (av_match_ext(lpd
.filename
, fmt1
->extensions
)) {
167 score
= AVPROBE_SCORE_EXTENSION
;
170 if (score
> *score_max
) {
173 }else if (score
== *score_max
)
177 /* a hack for files with huge id3v2 tags -- try to guess by file extension. */
178 if (!fmt
&& is_opened
&& *score_max
< AVPROBE_SCORE_EXTENSION
/ 2) {
179 while ((fmt
= av_iformat_next(fmt
)))
180 if (fmt
->extensions
&& av_match_ext(lpd
.filename
, fmt
->extensions
)) {
181 *score_max
= AVPROBE_SCORE_EXTENSION
/ 2;
186 if (!fmt
&& id3
&& *score_max
< AVPROBE_SCORE_EXTENSION
/ 2 - 1) {
187 while ((fmt
= av_iformat_next(fmt
)))
188 if (fmt
->extensions
&& av_match_ext("mp3", fmt
->extensions
)) {
189 *score_max
= AVPROBE_SCORE_EXTENSION
/ 2 - 1;
197 AVInputFormat
*av_probe_input_format(AVProbeData
*pd
, int is_opened
){
199 return av_probe_input_format2(pd
, is_opened
, &score
);
202 static int set_codec_from_probe_data(AVFormatContext
*s
, AVStream
*st
, AVProbeData
*pd
, int score
)
204 static const struct {
205 const char *name
; enum AVCodecID id
; enum AVMediaType type
;
207 { "aac" , AV_CODEC_ID_AAC
, AVMEDIA_TYPE_AUDIO
},
208 { "ac3" , AV_CODEC_ID_AC3
, AVMEDIA_TYPE_AUDIO
},
209 { "dts" , AV_CODEC_ID_DTS
, AVMEDIA_TYPE_AUDIO
},
210 { "eac3" , AV_CODEC_ID_EAC3
, AVMEDIA_TYPE_AUDIO
},
211 { "h264" , AV_CODEC_ID_H264
, AVMEDIA_TYPE_VIDEO
},
212 { "m4v" , AV_CODEC_ID_MPEG4
, AVMEDIA_TYPE_VIDEO
},
213 { "mp3" , AV_CODEC_ID_MP3
, AVMEDIA_TYPE_AUDIO
},
214 { "mpegvideo", AV_CODEC_ID_MPEG2VIDEO
, AVMEDIA_TYPE_VIDEO
},
217 AVInputFormat
*fmt
= av_probe_input_format2(pd
, 1, &score
);
221 av_log(s
, AV_LOG_DEBUG
, "Probe with size=%d, packets=%d detected %s with score=%d\n",
222 pd
->buf_size
, MAX_PROBE_PACKETS
- st
->probe_packets
, fmt
->name
, score
);
223 for (i
= 0; fmt_id_type
[i
].name
; i
++) {
224 if (!strcmp(fmt
->name
, fmt_id_type
[i
].name
)) {
225 st
->codec
->codec_id
= fmt_id_type
[i
].id
;
226 st
->codec
->codec_type
= fmt_id_type
[i
].type
;
234 /************************************************************/
235 /* input media file */
237 /** size of probe buffer, for guessing file type from file contents */
238 #define PROBE_BUF_MIN 2048
239 #define PROBE_BUF_MAX (1<<20)
241 int av_probe_input_buffer(AVIOContext
*pb
, AVInputFormat
**fmt
,
242 const char *filename
, void *logctx
,
243 unsigned int offset
, unsigned int max_probe_size
)
245 AVProbeData pd
= { filename ? filename
: "", NULL
, -offset
};
246 unsigned char *buf
= NULL
;
247 int ret
= 0, probe_size
;
249 if (!max_probe_size
) {
250 max_probe_size
= PROBE_BUF_MAX
;
251 } else if (max_probe_size
> PROBE_BUF_MAX
) {
252 max_probe_size
= PROBE_BUF_MAX
;
253 } else if (max_probe_size
< PROBE_BUF_MIN
) {
254 return AVERROR(EINVAL
);
257 if (offset
>= max_probe_size
) {
258 return AVERROR(EINVAL
);
261 for(probe_size
= PROBE_BUF_MIN
; probe_size
<=max_probe_size
&& !*fmt
;
262 probe_size
= FFMIN(probe_size
<<1, FFMAX(max_probe_size
, probe_size
+1))) {
263 int score
= probe_size
< max_probe_size ? AVPROBE_SCORE_MAX
/4 : 0;
264 int buf_offset
= (probe_size
== PROBE_BUF_MIN
) ?
0 : probe_size
>>1;
266 if (probe_size
< offset
) {
270 /* read probe data */
271 if ((ret
= av_reallocp(&buf
, probe_size
+ AVPROBE_PADDING_SIZE
)) < 0)
273 if ((ret
= avio_read(pb
, buf
+ buf_offset
, probe_size
- buf_offset
)) < 0) {
274 /* fail if error was not end of file, otherwise, lower score */
275 if (ret
!= AVERROR_EOF
) {
280 ret
= 0; /* error was end of file, nothing read */
283 pd
.buf
= &buf
[offset
];
285 memset(pd
.buf
+ pd
.buf_size
, 0, AVPROBE_PADDING_SIZE
);
287 /* guess file format */
288 *fmt
= av_probe_input_format2(&pd
, 1, &score
);
290 if(score
<= AVPROBE_SCORE_MAX
/4){ //this can only be true in the last iteration
291 av_log(logctx
, AV_LOG_WARNING
, "Format detected only with low score of %d, misdetection possible!\n", score
);
293 av_log(logctx
, AV_LOG_DEBUG
, "Probed with size=%d and score=%d\n", probe_size
, score
);
299 return AVERROR_INVALIDDATA
;
302 /* rewind. reuse probe buffer to avoid seeking */
303 if ((ret
= ffio_rewind_with_probe_data(pb
, buf
, pd
.buf_size
)) < 0)
309 /* open input file and probe the format if necessary */
310 static int init_input(AVFormatContext
*s
, const char *filename
, AVDictionary
**options
)
313 AVProbeData pd
= {filename
, NULL
, 0};
316 s
->flags
|= AVFMT_FLAG_CUSTOM_IO
;
318 return av_probe_input_buffer(s
->pb
, &s
->iformat
, filename
, s
, 0, s
->probesize
);
319 else if (s
->iformat
->flags
& AVFMT_NOFILE
)
320 return AVERROR(EINVAL
);
324 if ( (s
->iformat
&& s
->iformat
->flags
& AVFMT_NOFILE
) ||
325 (!s
->iformat
&& (s
->iformat
= av_probe_input_format(&pd
, 0))))
328 if ((ret
= avio_open2(&s
->pb
, filename
, AVIO_FLAG_READ
,
329 &s
->interrupt_callback
, options
)) < 0)
333 return av_probe_input_buffer(s
->pb
, &s
->iformat
, filename
, s
, 0, s
->probesize
);
336 static AVPacket
*add_to_pktbuf(AVPacketList
**packet_buffer
, AVPacket
*pkt
,
337 AVPacketList
**plast_pktl
){
338 AVPacketList
*pktl
= av_mallocz(sizeof(AVPacketList
));
343 (*plast_pktl
)->next
= pktl
;
345 *packet_buffer
= pktl
;
347 /* add the packet in the buffered packet list */
353 static int queue_attached_pictures(AVFormatContext
*s
)
356 for (i
= 0; i
< s
->nb_streams
; i
++)
357 if (s
->streams
[i
]->disposition
& AV_DISPOSITION_ATTACHED_PIC
&&
358 s
->streams
[i
]->discard
< AVDISCARD_ALL
) {
359 AVPacket copy
= s
->streams
[i
]->attached_pic
;
360 copy
.buf
= av_buffer_ref(copy
.buf
);
362 return AVERROR(ENOMEM
);
364 add_to_pktbuf(&s
->raw_packet_buffer
, ©
, &s
->raw_packet_buffer_end
);
369 int avformat_open_input(AVFormatContext
**ps
, const char *filename
, AVInputFormat
*fmt
, AVDictionary
**options
)
371 AVFormatContext
*s
= *ps
;
373 AVDictionary
*tmp
= NULL
;
374 ID3v2ExtraMeta
*id3v2_extra_meta
= NULL
;
376 if (!s
&& !(s
= avformat_alloc_context()))
377 return AVERROR(ENOMEM
);
382 av_dict_copy(&tmp
, *options
, 0);
384 if ((ret
= av_opt_set_dict(s
, &tmp
)) < 0)
387 if ((ret
= init_input(s
, filename
, &tmp
)) < 0)
390 /* check filename in case an image number is expected */
391 if (s
->iformat
->flags
& AVFMT_NEEDNUMBER
) {
392 if (!av_filename_number_test(filename
)) {
393 ret
= AVERROR(EINVAL
);
398 s
->duration
= s
->start_time
= AV_NOPTS_VALUE
;
399 av_strlcpy(s
->filename
, filename ? filename
: "", sizeof(s
->filename
));
401 /* allocate private data */
402 if (s
->iformat
->priv_data_size
> 0) {
403 if (!(s
->priv_data
= av_mallocz(s
->iformat
->priv_data_size
))) {
404 ret
= AVERROR(ENOMEM
);
407 if (s
->iformat
->priv_class
) {
408 *(const AVClass
**)s
->priv_data
= s
->iformat
->priv_class
;
409 av_opt_set_defaults(s
->priv_data
);
410 if ((ret
= av_opt_set_dict(s
->priv_data
, &tmp
)) < 0)
415 /* e.g. AVFMT_NOFILE formats will not have a AVIOContext */
417 ff_id3v2_read(s
, ID3v2_DEFAULT_MAGIC
, &id3v2_extra_meta
);
419 if (s
->iformat
->read_header
)
420 if ((ret
= s
->iformat
->read_header(s
)) < 0)
423 if (id3v2_extra_meta
&&
424 (ret
= ff_id3v2_parse_apic(s
, &id3v2_extra_meta
)) < 0)
426 ff_id3v2_free_extra_meta(&id3v2_extra_meta
);
428 if ((ret
= queue_attached_pictures(s
)) < 0)
431 if (s
->pb
&& !s
->data_offset
)
432 s
->data_offset
= avio_tell(s
->pb
);
434 s
->raw_packet_buffer_remaining_size
= RAW_PACKET_BUFFER_SIZE
;
437 av_dict_free(options
);
444 ff_id3v2_free_extra_meta(&id3v2_extra_meta
);
446 if (s
->pb
&& !(s
->flags
& AVFMT_FLAG_CUSTOM_IO
))
448 avformat_free_context(s
);
453 /*******************************************************/
455 static int probe_codec(AVFormatContext
*s
, AVStream
*st
, const AVPacket
*pkt
)
457 if(st
->codec
->codec_id
== AV_CODEC_ID_PROBE
){
458 AVProbeData
*pd
= &st
->probe_data
;
459 av_log(s
, AV_LOG_DEBUG
, "probing stream %d\n", st
->index
);
464 if ((err
= av_reallocp(&pd
->buf
, pd
->buf_size
+ pkt
->size
+
465 AVPROBE_PADDING_SIZE
)) < 0)
467 memcpy(pd
->buf
+pd
->buf_size
, pkt
->data
, pkt
->size
);
468 pd
->buf_size
+= pkt
->size
;
469 memset(pd
->buf
+pd
->buf_size
, 0, AVPROBE_PADDING_SIZE
);
471 st
->probe_packets
= 0;
473 av_log(s
, AV_LOG_ERROR
, "nothing to probe for stream %d\n",
479 if (!st
->probe_packets
||
480 av_log2(pd
->buf_size
) != av_log2(pd
->buf_size
- pkt
->size
)) {
481 set_codec_from_probe_data(s
, st
, pd
, st
->probe_packets
> 0 ? AVPROBE_SCORE_MAX
/4 : 0);
482 if(st
->codec
->codec_id
!= AV_CODEC_ID_PROBE
){
485 av_log(s
, AV_LOG_DEBUG
, "probed stream %d\n", st
->index
);
492 int ff_read_packet(AVFormatContext
*s
, AVPacket
*pkt
)
498 AVPacketList
*pktl
= s
->raw_packet_buffer
;
502 st
= s
->streams
[pkt
->stream_index
];
503 if (st
->codec
->codec_id
!= AV_CODEC_ID_PROBE
|| !st
->probe_packets
||
504 s
->raw_packet_buffer_remaining_size
< pkt
->size
) {
506 if (st
->probe_packets
) {
507 if ((err
= probe_codec(s
, st
, NULL
)) < 0)
510 pd
= &st
->probe_data
;
513 s
->raw_packet_buffer
= pktl
->next
;
514 s
->raw_packet_buffer_remaining_size
+= pkt
->size
;
523 ret
= s
->iformat
->read_packet(s
, pkt
);
525 if (!pktl
|| ret
== AVERROR(EAGAIN
))
527 for (i
= 0; i
< s
->nb_streams
; i
++) {
529 if (st
->probe_packets
) {
530 if ((err
= probe_codec(s
, st
, NULL
)) < 0)
537 if ((s
->flags
& AVFMT_FLAG_DISCARD_CORRUPT
) &&
538 (pkt
->flags
& AV_PKT_FLAG_CORRUPT
)) {
539 av_log(s
, AV_LOG_WARNING
,
540 "Dropped corrupted packet (stream = %d)\n",
546 st
= s
->streams
[pkt
->stream_index
];
548 switch(st
->codec
->codec_type
){
549 case AVMEDIA_TYPE_VIDEO
:
550 if(s
->video_codec_id
) st
->codec
->codec_id
= s
->video_codec_id
;
552 case AVMEDIA_TYPE_AUDIO
:
553 if(s
->audio_codec_id
) st
->codec
->codec_id
= s
->audio_codec_id
;
555 case AVMEDIA_TYPE_SUBTITLE
:
556 if(s
->subtitle_codec_id
)st
->codec
->codec_id
= s
->subtitle_codec_id
;
560 if(!pktl
&& (st
->codec
->codec_id
!= AV_CODEC_ID_PROBE
||
564 add_to_pktbuf(&s
->raw_packet_buffer
, pkt
, &s
->raw_packet_buffer_end
);
565 s
->raw_packet_buffer_remaining_size
-= pkt
->size
;
567 if ((err
= probe_codec(s
, st
, pkt
)) < 0)
572 /**********************************************************/
575 * Get the number of samples of an audio frame. Return -1 on error.
577 int ff_get_audio_frame_size(AVCodecContext
*enc
, int size
, int mux
)
581 /* give frame_size priority if demuxing */
582 if (!mux
&& enc
->frame_size
> 1)
583 return enc
->frame_size
;
585 if ((frame_size
= av_get_audio_frame_duration(enc
, size
)) > 0)
588 /* Fall back on using frame_size if muxing. */
589 if (enc
->frame_size
> 1)
590 return enc
->frame_size
;
597 * Return the frame duration in seconds. Return 0 if not available.
599 void ff_compute_frame_duration(int *pnum
, int *pden
, AVStream
*st
,
600 AVCodecParserContext
*pc
, AVPacket
*pkt
)
606 switch(st
->codec
->codec_type
) {
607 case AVMEDIA_TYPE_VIDEO
:
608 if (st
->avg_frame_rate
.num
) {
609 *pnum
= st
->avg_frame_rate
.den
;
610 *pden
= st
->avg_frame_rate
.num
;
611 } else if(st
->time_base
.num
*1000LL > st
->time_base
.den
) {
612 *pnum
= st
->time_base
.num
;
613 *pden
= st
->time_base
.den
;
614 }else if(st
->codec
->time_base
.num
*1000LL > st
->codec
->time_base
.den
){
615 *pnum
= st
->codec
->time_base
.num
;
616 *pden
= st
->codec
->time_base
.den
;
617 if (pc
&& pc
->repeat_pict
) {
618 if (*pnum
> INT_MAX
/ (1 + pc
->repeat_pict
))
619 *pden
/= 1 + pc
->repeat_pict
;
621 *pnum
*= 1 + pc
->repeat_pict
;
623 //If this codec can be interlaced or progressive then we need a parser to compute duration of a packet
624 //Thus if we have no parser in such case leave duration undefined.
625 if(st
->codec
->ticks_per_frame
>1 && !pc
){
630 case AVMEDIA_TYPE_AUDIO
:
631 frame_size
= ff_get_audio_frame_size(st
->codec
, pkt
->size
, 0);
632 if (frame_size
<= 0 || st
->codec
->sample_rate
<= 0)
635 *pden
= st
->codec
->sample_rate
;
642 static int is_intra_only(enum AVCodecID id
)
644 const AVCodecDescriptor
*d
= avcodec_descriptor_get(id
);
647 if (d
->type
== AVMEDIA_TYPE_VIDEO
&& !(d
->props
& AV_CODEC_PROP_INTRA_ONLY
))
652 static void update_initial_timestamps(AVFormatContext
*s
, int stream_index
,
653 int64_t dts
, int64_t pts
)
655 AVStream
*st
= s
->streams
[stream_index
];
656 AVPacketList
*pktl
= s
->packet_buffer
;
658 if(st
->first_dts
!= AV_NOPTS_VALUE
|| dts
== AV_NOPTS_VALUE
|| st
->cur_dts
== AV_NOPTS_VALUE
)
661 st
->first_dts
= dts
- st
->cur_dts
;
664 for(; pktl
; pktl
= pktl
->next
){
665 if(pktl
->pkt
.stream_index
!= stream_index
)
667 //FIXME think more about this check
668 if(pktl
->pkt
.pts
!= AV_NOPTS_VALUE
&& pktl
->pkt
.pts
== pktl
->pkt
.dts
)
669 pktl
->pkt
.pts
+= st
->first_dts
;
671 if(pktl
->pkt
.dts
!= AV_NOPTS_VALUE
)
672 pktl
->pkt
.dts
+= st
->first_dts
;
674 if(st
->start_time
== AV_NOPTS_VALUE
&& pktl
->pkt
.pts
!= AV_NOPTS_VALUE
)
675 st
->start_time
= pktl
->pkt
.pts
;
677 if (st
->start_time
== AV_NOPTS_VALUE
)
678 st
->start_time
= pts
;
681 static void update_initial_durations(AVFormatContext
*s
, AVStream
*st
,
682 int stream_index
, int duration
)
684 AVPacketList
*pktl
= s
->packet_buffer
;
687 if(st
->first_dts
!= AV_NOPTS_VALUE
){
688 cur_dts
= st
->first_dts
;
689 for(; pktl
; pktl
= pktl
->next
){
690 if(pktl
->pkt
.stream_index
== stream_index
){
691 if(pktl
->pkt
.pts
!= pktl
->pkt
.dts
|| pktl
->pkt
.dts
!= AV_NOPTS_VALUE
|| pktl
->pkt
.duration
)
696 pktl
= s
->packet_buffer
;
697 st
->first_dts
= cur_dts
;
698 }else if(st
->cur_dts
)
701 for(; pktl
; pktl
= pktl
->next
){
702 if(pktl
->pkt
.stream_index
!= stream_index
)
704 if(pktl
->pkt
.pts
== pktl
->pkt
.dts
&& pktl
->pkt
.dts
== AV_NOPTS_VALUE
705 && !pktl
->pkt
.duration
){
706 pktl
->pkt
.dts
= cur_dts
;
707 if(!st
->codec
->has_b_frames
)
708 pktl
->pkt
.pts
= cur_dts
;
710 if (st
->codec
->codec_type
!= AVMEDIA_TYPE_AUDIO
)
711 pktl
->pkt
.duration
= duration
;
715 if(st
->first_dts
== AV_NOPTS_VALUE
)
716 st
->cur_dts
= cur_dts
;
719 static void compute_pkt_fields(AVFormatContext
*s
, AVStream
*st
,
720 AVCodecParserContext
*pc
, AVPacket
*pkt
)
722 int num
, den
, presentation_delayed
, delay
, i
;
725 if (s
->flags
& AVFMT_FLAG_NOFILLIN
)
728 if((s
->flags
& AVFMT_FLAG_IGNDTS
) && pkt
->pts
!= AV_NOPTS_VALUE
)
729 pkt
->dts
= AV_NOPTS_VALUE
;
731 /* do we have a video B-frame ? */
732 delay
= st
->codec
->has_b_frames
;
733 presentation_delayed
= 0;
735 /* XXX: need has_b_frame, but cannot get it if the codec is
738 pc
&& pc
->pict_type
!= AV_PICTURE_TYPE_B
)
739 presentation_delayed
= 1;
741 if (pkt
->pts
!= AV_NOPTS_VALUE
&& pkt
->dts
!= AV_NOPTS_VALUE
&&
742 st
->pts_wrap_bits
< 63 &&
743 pkt
->dts
- (1LL << (st
->pts_wrap_bits
- 1)) > pkt
->pts
) {
744 pkt
->dts
-= 1LL<<st
->pts_wrap_bits
;
747 // some mpeg2 in mpeg-ps lack dts (issue171 / input_file.mpg)
748 // we take the conservative approach and discard both
749 // Note, if this is misbehaving for a H.264 file then possibly presentation_delayed is not set correctly.
750 if(delay
==1 && pkt
->dts
== pkt
->pts
&& pkt
->dts
!= AV_NOPTS_VALUE
&& presentation_delayed
){
751 av_log(s
, AV_LOG_DEBUG
, "invalid dts/pts combination\n");
752 pkt
->dts
= pkt
->pts
= AV_NOPTS_VALUE
;
755 if (pkt
->duration
== 0 && st
->codec
->codec_type
!= AVMEDIA_TYPE_AUDIO
) {
756 ff_compute_frame_duration(&num
, &den
, st
, pc
, pkt
);
758 pkt
->duration
= av_rescale_rnd(1, num
* (int64_t)st
->time_base
.den
, den
* (int64_t)st
->time_base
.num
, AV_ROUND_DOWN
);
760 if(pkt
->duration
!= 0 && s
->packet_buffer
)
761 update_initial_durations(s
, st
, pkt
->stream_index
, pkt
->duration
);
765 /* correct timestamps with byte offset if demuxers only have timestamps
766 on packet boundaries */
767 if(pc
&& st
->need_parsing
== AVSTREAM_PARSE_TIMESTAMPS
&& pkt
->size
){
768 /* this will estimate bitrate based on this frame's duration and size */
769 offset
= av_rescale(pc
->offset
, pkt
->duration
, pkt
->size
);
770 if(pkt
->pts
!= AV_NOPTS_VALUE
)
772 if(pkt
->dts
!= AV_NOPTS_VALUE
)
776 /* This may be redundant, but it should not hurt. */
777 if(pkt
->dts
!= AV_NOPTS_VALUE
&& pkt
->pts
!= AV_NOPTS_VALUE
&& pkt
->pts
> pkt
->dts
)
778 presentation_delayed
= 1;
781 "IN delayed:%d pts:%"PRId64
", dts:%"PRId64
" cur_dts:%"PRId64
" st:%d pc:%p\n",
782 presentation_delayed
, pkt
->pts
, pkt
->dts
, st
->cur_dts
,
783 pkt
->stream_index
, pc
);
784 /* interpolate PTS and DTS if they are not present */
785 //We skip H264 currently because delay and has_b_frames are not reliably set
786 if((delay
==0 || (delay
==1 && pc
)) && st
->codec
->codec_id
!= AV_CODEC_ID_H264
){
787 if (presentation_delayed
) {
788 /* DTS = decompression timestamp */
789 /* PTS = presentation timestamp */
790 if (pkt
->dts
== AV_NOPTS_VALUE
)
791 pkt
->dts
= st
->last_IP_pts
;
792 update_initial_timestamps(s
, pkt
->stream_index
, pkt
->dts
, pkt
->pts
);
793 if (pkt
->dts
== AV_NOPTS_VALUE
)
794 pkt
->dts
= st
->cur_dts
;
796 /* this is tricky: the dts must be incremented by the duration
797 of the frame we are displaying, i.e. the last I- or P-frame */
798 if (st
->last_IP_duration
== 0)
799 st
->last_IP_duration
= pkt
->duration
;
800 if(pkt
->dts
!= AV_NOPTS_VALUE
)
801 st
->cur_dts
= pkt
->dts
+ st
->last_IP_duration
;
802 st
->last_IP_duration
= pkt
->duration
;
803 st
->last_IP_pts
= pkt
->pts
;
804 /* cannot compute PTS if not present (we can compute it only
805 by knowing the future */
806 } else if (pkt
->pts
!= AV_NOPTS_VALUE
||
807 pkt
->dts
!= AV_NOPTS_VALUE
||
809 st
->codec
->codec_type
== AVMEDIA_TYPE_AUDIO
) {
810 int duration
= pkt
->duration
;
811 if (!duration
&& st
->codec
->codec_type
== AVMEDIA_TYPE_AUDIO
) {
812 ff_compute_frame_duration(&num
, &den
, st
, pc
, pkt
);
814 duration
= av_rescale_rnd(1, num
* (int64_t)st
->time_base
.den
,
815 den
* (int64_t)st
->time_base
.num
,
817 if (duration
!= 0 && s
->packet_buffer
) {
818 update_initial_durations(s
, st
, pkt
->stream_index
,
824 if (pkt
->pts
!= AV_NOPTS_VALUE
|| pkt
->dts
!= AV_NOPTS_VALUE
||
826 /* presentation is not delayed : PTS and DTS are the same */
827 if (pkt
->pts
== AV_NOPTS_VALUE
)
829 update_initial_timestamps(s
, pkt
->stream_index
, pkt
->pts
,
831 if (pkt
->pts
== AV_NOPTS_VALUE
)
832 pkt
->pts
= st
->cur_dts
;
834 if (pkt
->pts
!= AV_NOPTS_VALUE
)
835 st
->cur_dts
= pkt
->pts
+ duration
;
840 if(pkt
->pts
!= AV_NOPTS_VALUE
&& delay
<= MAX_REORDER_DELAY
){
841 st
->pts_buffer
[0]= pkt
->pts
;
842 for(i
=0; i
<delay
&& st
->pts_buffer
[i
] > st
->pts_buffer
[i
+1]; i
++)
843 FFSWAP(int64_t, st
->pts_buffer
[i
], st
->pts_buffer
[i
+1]);
844 if(pkt
->dts
== AV_NOPTS_VALUE
)
845 pkt
->dts
= st
->pts_buffer
[0];
846 if(st
->codec
->codec_id
== AV_CODEC_ID_H264
){ // we skipped it above so we try here
847 update_initial_timestamps(s
, pkt
->stream_index
, pkt
->dts
, pkt
->pts
); // this should happen on the first packet
849 if(pkt
->dts
> st
->cur_dts
)
850 st
->cur_dts
= pkt
->dts
;
854 "OUTdelayed:%d/%d pts:%"PRId64
", dts:%"PRId64
" cur_dts:%"PRId64
"\n",
855 presentation_delayed
, delay
, pkt
->pts
, pkt
->dts
, st
->cur_dts
);
858 if (is_intra_only(st
->codec
->codec_id
))
859 pkt
->flags
|= AV_PKT_FLAG_KEY
;
861 pkt
->convergence_duration
= pc
->convergence_duration
;
864 static void free_packet_buffer(AVPacketList
**pkt_buf
, AVPacketList
**pkt_buf_end
)
867 AVPacketList
*pktl
= *pkt_buf
;
868 *pkt_buf
= pktl
->next
;
869 av_free_packet(&pktl
->pkt
);
876 * Parse a packet, add all split parts to parse_queue
878 * @param pkt packet to parse, NULL when flushing the parser at end of stream
880 static int parse_packet(AVFormatContext
*s
, AVPacket
*pkt
, int stream_index
)
882 AVPacket out_pkt
= { 0 }, flush_pkt
= { 0 };
883 AVStream
*st
= s
->streams
[stream_index
];
884 uint8_t *data
= pkt ? pkt
->data
: NULL
;
885 int size
= pkt ? pkt
->size
: 0;
886 int ret
= 0, got_output
= 0;
889 av_init_packet(&flush_pkt
);
894 while (size
> 0 || (pkt
== &flush_pkt
&& got_output
)) {
897 av_init_packet(&out_pkt
);
898 len
= av_parser_parse2(st
->parser
, st
->codec
,
899 &out_pkt
.data
, &out_pkt
.size
, data
, size
,
900 pkt
->pts
, pkt
->dts
, pkt
->pos
);
902 pkt
->pts
= pkt
->dts
= AV_NOPTS_VALUE
;
903 /* increment read pointer */
907 got_output
= !!out_pkt
.size
;
912 if (pkt
->side_data
) {
913 out_pkt
.side_data
= pkt
->side_data
;
914 out_pkt
.side_data_elems
= pkt
->side_data_elems
;
915 pkt
->side_data
= NULL
;
916 pkt
->side_data_elems
= 0;
919 /* set the duration */
920 out_pkt
.duration
= 0;
921 if (st
->codec
->codec_type
== AVMEDIA_TYPE_AUDIO
) {
922 if (st
->codec
->sample_rate
> 0) {
923 out_pkt
.duration
= av_rescale_q_rnd(st
->parser
->duration
,
924 (AVRational
){ 1, st
->codec
->sample_rate
},
928 } else if (st
->codec
->time_base
.num
!= 0 &&
929 st
->codec
->time_base
.den
!= 0) {
930 out_pkt
.duration
= av_rescale_q_rnd(st
->parser
->duration
,
931 st
->codec
->time_base
,
936 out_pkt
.stream_index
= st
->index
;
937 out_pkt
.pts
= st
->parser
->pts
;
938 out_pkt
.dts
= st
->parser
->dts
;
939 out_pkt
.pos
= st
->parser
->pos
;
941 if (st
->parser
->key_frame
== 1 ||
942 (st
->parser
->key_frame
== -1 &&
943 st
->parser
->pict_type
== AV_PICTURE_TYPE_I
))
944 out_pkt
.flags
|= AV_PKT_FLAG_KEY
;
946 compute_pkt_fields(s
, st
, st
->parser
, &out_pkt
);
948 if ((s
->iformat
->flags
& AVFMT_GENERIC_INDEX
) &&
949 out_pkt
.flags
& AV_PKT_FLAG_KEY
) {
950 ff_reduce_index(s
, st
->index
);
951 av_add_index_entry(st
, st
->parser
->frame_offset
, out_pkt
.dts
,
952 0, 0, AVINDEX_KEYFRAME
);
955 if (out_pkt
.data
== pkt
->data
&& out_pkt
.size
== pkt
->size
) {
956 out_pkt
.buf
= pkt
->buf
;
958 #if FF_API_DESTRUCT_PACKET
959 FF_DISABLE_DEPRECATION_WARNINGS
960 out_pkt
.destruct
= pkt
->destruct
;
961 pkt
->destruct
= NULL
;
962 FF_ENABLE_DEPRECATION_WARNINGS
965 if ((ret
= av_dup_packet(&out_pkt
)) < 0)
968 if (!add_to_pktbuf(&s
->parse_queue
, &out_pkt
, &s
->parse_queue_end
)) {
969 av_free_packet(&out_pkt
);
970 ret
= AVERROR(ENOMEM
);
976 /* end of the stream => close and free the parser */
977 if (pkt
== &flush_pkt
) {
978 av_parser_close(st
->parser
);
987 static int read_from_packet_buffer(AVPacketList
**pkt_buffer
,
988 AVPacketList
**pkt_buffer_end
,
992 av_assert0(*pkt_buffer
);
995 *pkt_buffer
= pktl
->next
;
997 *pkt_buffer_end
= NULL
;
1002 static int read_frame_internal(AVFormatContext
*s
, AVPacket
*pkt
)
1004 int ret
= 0, i
, got_packet
= 0;
1006 av_init_packet(pkt
);
1008 while (!got_packet
&& !s
->parse_queue
) {
1012 /* read next packet */
1013 ret
= ff_read_packet(s
, &cur_pkt
);
1015 if (ret
== AVERROR(EAGAIN
))
1017 /* flush the parsers */
1018 for(i
= 0; i
< s
->nb_streams
; i
++) {
1020 if (st
->parser
&& st
->need_parsing
)
1021 parse_packet(s
, NULL
, st
->index
);
1023 /* all remaining packets are now in parse_queue =>
1024 * really terminate parsing */
1028 st
= s
->streams
[cur_pkt
.stream_index
];
1030 if (cur_pkt
.pts
!= AV_NOPTS_VALUE
&&
1031 cur_pkt
.dts
!= AV_NOPTS_VALUE
&&
1032 cur_pkt
.pts
< cur_pkt
.dts
) {
1033 av_log(s
, AV_LOG_WARNING
, "Invalid timestamps stream=%d, pts=%"PRId64
", dts=%"PRId64
", size=%d\n",
1034 cur_pkt
.stream_index
,
1039 if (s
->debug
& FF_FDEBUG_TS
)
1040 av_log(s
, AV_LOG_DEBUG
, "ff_read_packet stream=%d, pts=%"PRId64
", dts=%"PRId64
", size=%d, duration=%d, flags=%d\n",
1041 cur_pkt
.stream_index
,
1048 if (st
->need_parsing
&& !st
->parser
&& !(s
->flags
& AVFMT_FLAG_NOPARSE
)) {
1049 st
->parser
= av_parser_init(st
->codec
->codec_id
);
1051 /* no parser available: just output the raw packets */
1052 st
->need_parsing
= AVSTREAM_PARSE_NONE
;
1053 } else if(st
->need_parsing
== AVSTREAM_PARSE_HEADERS
) {
1054 st
->parser
->flags
|= PARSER_FLAG_COMPLETE_FRAMES
;
1055 } else if(st
->need_parsing
== AVSTREAM_PARSE_FULL_ONCE
) {
1056 st
->parser
->flags
|= PARSER_FLAG_ONCE
;
1060 if (!st
->need_parsing
|| !st
->parser
) {
1061 /* no parsing needed: we just output the packet as is */
1063 compute_pkt_fields(s
, st
, NULL
, pkt
);
1064 if ((s
->iformat
->flags
& AVFMT_GENERIC_INDEX
) &&
1065 (pkt
->flags
& AV_PKT_FLAG_KEY
) && pkt
->dts
!= AV_NOPTS_VALUE
) {
1066 ff_reduce_index(s
, st
->index
);
1067 av_add_index_entry(st
, pkt
->pos
, pkt
->dts
, 0, 0, AVINDEX_KEYFRAME
);
1070 } else if (st
->discard
< AVDISCARD_ALL
) {
1071 if ((ret
= parse_packet(s
, &cur_pkt
, cur_pkt
.stream_index
)) < 0)
1075 av_free_packet(&cur_pkt
);
1079 if (!got_packet
&& s
->parse_queue
)
1080 ret
= read_from_packet_buffer(&s
->parse_queue
, &s
->parse_queue_end
, pkt
);
1082 if(s
->debug
& FF_FDEBUG_TS
)
1083 av_log(s
, AV_LOG_DEBUG
, "read_frame_internal stream=%d, pts=%"PRId64
", dts=%"PRId64
", size=%d, duration=%d, flags=%d\n",
1094 int av_read_frame(AVFormatContext
*s
, AVPacket
*pkt
)
1096 const int genpts
= s
->flags
& AVFMT_FLAG_GENPTS
;
1100 return s
->packet_buffer ?
read_from_packet_buffer(&s
->packet_buffer
,
1101 &s
->packet_buffer_end
,
1103 read_frame_internal(s
, pkt
);
1107 AVPacketList
*pktl
= s
->packet_buffer
;
1110 AVPacket
*next_pkt
= &pktl
->pkt
;
1112 if (next_pkt
->dts
!= AV_NOPTS_VALUE
) {
1113 int wrap_bits
= s
->streams
[next_pkt
->stream_index
]->pts_wrap_bits
;
1114 while (pktl
&& next_pkt
->pts
== AV_NOPTS_VALUE
) {
1115 if (pktl
->pkt
.stream_index
== next_pkt
->stream_index
&&
1116 (av_compare_mod(next_pkt
->dts
, pktl
->pkt
.dts
, 2LL << (wrap_bits
- 1)) < 0) &&
1117 av_compare_mod(pktl
->pkt
.pts
, pktl
->pkt
.dts
, 2LL << (wrap_bits
- 1))) { //not b frame
1118 next_pkt
->pts
= pktl
->pkt
.dts
;
1122 pktl
= s
->packet_buffer
;
1125 /* read packet from packet buffer, if there is data */
1126 if (!(next_pkt
->pts
== AV_NOPTS_VALUE
&&
1127 next_pkt
->dts
!= AV_NOPTS_VALUE
&& !eof
))
1128 return read_from_packet_buffer(&s
->packet_buffer
,
1129 &s
->packet_buffer_end
, pkt
);
1132 ret
= read_frame_internal(s
, pkt
);
1134 if (pktl
&& ret
!= AVERROR(EAGAIN
)) {
1141 if (av_dup_packet(add_to_pktbuf(&s
->packet_buffer
, pkt
,
1142 &s
->packet_buffer_end
)) < 0)
1143 return AVERROR(ENOMEM
);
1147 /* XXX: suppress the packet queue */
1148 static void flush_packet_queue(AVFormatContext
*s
)
1150 free_packet_buffer(&s
->parse_queue
, &s
->parse_queue_end
);
1151 free_packet_buffer(&s
->packet_buffer
, &s
->packet_buffer_end
);
1152 free_packet_buffer(&s
->raw_packet_buffer
, &s
->raw_packet_buffer_end
);
1154 s
->raw_packet_buffer_remaining_size
= RAW_PACKET_BUFFER_SIZE
;
1157 /*******************************************************/
1160 int av_find_default_stream_index(AVFormatContext
*s
)
1162 int first_audio_index
= -1;
1166 if (s
->nb_streams
<= 0)
1168 for(i
= 0; i
< s
->nb_streams
; i
++) {
1170 if (st
->codec
->codec_type
== AVMEDIA_TYPE_VIDEO
&&
1171 !(st
->disposition
& AV_DISPOSITION_ATTACHED_PIC
)) {
1174 if (first_audio_index
< 0 && st
->codec
->codec_type
== AVMEDIA_TYPE_AUDIO
)
1175 first_audio_index
= i
;
1177 return first_audio_index
>= 0 ? first_audio_index
: 0;
1181 * Flush the frame reader.
1183 void ff_read_frame_flush(AVFormatContext
*s
)
1188 flush_packet_queue(s
);
1190 /* for each stream, reset read state */
1191 for(i
= 0; i
< s
->nb_streams
; i
++) {
1195 av_parser_close(st
->parser
);
1198 st
->last_IP_pts
= AV_NOPTS_VALUE
;
1199 st
->cur_dts
= AV_NOPTS_VALUE
; /* we set the current DTS to an unspecified origin */
1201 st
->probe_packets
= MAX_PROBE_PACKETS
;
1203 for(j
=0; j
<MAX_REORDER_DELAY
+1; j
++)
1204 st
->pts_buffer
[j
]= AV_NOPTS_VALUE
;
1208 void ff_update_cur_dts(AVFormatContext
*s
, AVStream
*ref_st
, int64_t timestamp
)
1212 for(i
= 0; i
< s
->nb_streams
; i
++) {
1213 AVStream
*st
= s
->streams
[i
];
1215 st
->cur_dts
= av_rescale(timestamp
,
1216 st
->time_base
.den
* (int64_t)ref_st
->time_base
.num
,
1217 st
->time_base
.num
* (int64_t)ref_st
->time_base
.den
);
1221 void ff_reduce_index(AVFormatContext
*s
, int stream_index
)
1223 AVStream
*st
= s
->streams
[stream_index
];
1224 unsigned int max_entries
= s
->max_index_size
/ sizeof(AVIndexEntry
);
1226 if((unsigned)st
->nb_index_entries
>= max_entries
){
1228 for(i
=0; 2*i
<st
->nb_index_entries
; i
++)
1229 st
->index_entries
[i
]= st
->index_entries
[2*i
];
1230 st
->nb_index_entries
= i
;
1234 int ff_add_index_entry(AVIndexEntry
**index_entries
,
1235 int *nb_index_entries
,
1236 unsigned int *index_entries_allocated_size
,
1237 int64_t pos
, int64_t timestamp
, int size
, int distance
, int flags
)
1239 AVIndexEntry
*entries
, *ie
;
1242 if((unsigned)*nb_index_entries
+ 1 >= UINT_MAX
/ sizeof(AVIndexEntry
))
1245 entries
= av_fast_realloc(*index_entries
,
1246 index_entries_allocated_size
,
1247 (*nb_index_entries
+ 1) *
1248 sizeof(AVIndexEntry
));
1252 *index_entries
= entries
;
1254 index
= ff_index_search_timestamp(*index_entries
, *nb_index_entries
, timestamp
, AVSEEK_FLAG_ANY
);
1257 index
= (*nb_index_entries
)++;
1258 ie
= &entries
[index
];
1259 assert(index
==0 || ie
[-1].timestamp
< timestamp
);
1261 ie
= &entries
[index
];
1262 if(ie
->timestamp
!= timestamp
){
1263 if(ie
->timestamp
<= timestamp
)
1265 memmove(entries
+ index
+ 1, entries
+ index
, sizeof(AVIndexEntry
)*(*nb_index_entries
- index
));
1266 (*nb_index_entries
)++;
1267 }else if(ie
->pos
== pos
&& distance
< ie
->min_distance
) //do not reduce the distance
1268 distance
= ie
->min_distance
;
1272 ie
->timestamp
= timestamp
;
1273 ie
->min_distance
= distance
;
1280 int av_add_index_entry(AVStream
*st
,
1281 int64_t pos
, int64_t timestamp
, int size
, int distance
, int flags
)
1283 return ff_add_index_entry(&st
->index_entries
, &st
->nb_index_entries
,
1284 &st
->index_entries_allocated_size
, pos
,
1285 timestamp
, size
, distance
, flags
);
1288 int ff_index_search_timestamp(const AVIndexEntry
*entries
, int nb_entries
,
1289 int64_t wanted_timestamp
, int flags
)
1297 //optimize appending index entries at the end
1298 if(b
&& entries
[b
-1].timestamp
< wanted_timestamp
)
1303 timestamp
= entries
[m
].timestamp
;
1304 if(timestamp
>= wanted_timestamp
)
1306 if(timestamp
<= wanted_timestamp
)
1309 m
= (flags
& AVSEEK_FLAG_BACKWARD
) ? a
: b
;
1311 if(!(flags
& AVSEEK_FLAG_ANY
)){
1312 while(m
>=0 && m
<nb_entries
&& !(entries
[m
].flags
& AVINDEX_KEYFRAME
)){
1313 m
+= (flags
& AVSEEK_FLAG_BACKWARD
) ?
-1 : 1;
1322 int av_index_search_timestamp(AVStream
*st
, int64_t wanted_timestamp
,
1325 return ff_index_search_timestamp(st
->index_entries
, st
->nb_index_entries
,
1326 wanted_timestamp
, flags
);
1329 int ff_seek_frame_binary(AVFormatContext
*s
, int stream_index
, int64_t target_ts
, int flags
)
1331 AVInputFormat
*avif
= s
->iformat
;
1332 int64_t av_uninit(pos_min
), av_uninit(pos_max
), pos
, pos_limit
;
1333 int64_t ts_min
, ts_max
, ts
;
1338 if (stream_index
< 0)
1341 av_dlog(s
, "read_seek: %d %"PRId64
"\n", stream_index
, target_ts
);
1344 ts_min
= AV_NOPTS_VALUE
;
1345 pos_limit
= -1; //gcc falsely says it may be uninitialized
1347 st
= s
->streams
[stream_index
];
1348 if(st
->index_entries
){
1351 index
= av_index_search_timestamp(st
, target_ts
, flags
| AVSEEK_FLAG_BACKWARD
); //FIXME whole func must be checked for non-keyframe entries in index case, especially read_timestamp()
1352 index
= FFMAX(index
, 0);
1353 e
= &st
->index_entries
[index
];
1355 if(e
->timestamp
<= target_ts
|| e
->pos
== e
->min_distance
){
1357 ts_min
= e
->timestamp
;
1358 av_dlog(s
, "using cached pos_min=0x%"PRIx64
" dts_min=%"PRId64
"\n",
1364 index
= av_index_search_timestamp(st
, target_ts
, flags
& ~AVSEEK_FLAG_BACKWARD
);
1365 assert(index
< st
->nb_index_entries
);
1367 e
= &st
->index_entries
[index
];
1368 assert(e
->timestamp
>= target_ts
);
1370 ts_max
= e
->timestamp
;
1371 pos_limit
= pos_max
- e
->min_distance
;
1372 av_dlog(s
, "using cached pos_max=0x%"PRIx64
" pos_limit=0x%"PRIx64
" dts_max=%"PRId64
"\n",
1373 pos_max
,pos_limit
, ts_max
);
1377 pos
= ff_gen_search(s
, stream_index
, target_ts
, pos_min
, pos_max
, pos_limit
, ts_min
, ts_max
, flags
, &ts
, avif
->read_timestamp
);
1382 if ((ret
= avio_seek(s
->pb
, pos
, SEEK_SET
)) < 0)
1385 ff_update_cur_dts(s
, st
, ts
);
1390 int64_t ff_gen_search(AVFormatContext
*s
, int stream_index
, int64_t target_ts
,
1391 int64_t pos_min
, int64_t pos_max
, int64_t pos_limit
,
1392 int64_t ts_min
, int64_t ts_max
, int flags
, int64_t *ts_ret
,
1393 int64_t (*read_timestamp
)(struct AVFormatContext
*, int , int64_t *, int64_t ))
1396 int64_t start_pos
, filesize
;
1399 av_dlog(s
, "gen_seek: %d %"PRId64
"\n", stream_index
, target_ts
);
1401 if(ts_min
== AV_NOPTS_VALUE
){
1402 pos_min
= s
->data_offset
;
1403 ts_min
= read_timestamp(s
, stream_index
, &pos_min
, INT64_MAX
);
1404 if (ts_min
== AV_NOPTS_VALUE
)
1408 if(ts_max
== AV_NOPTS_VALUE
){
1410 filesize
= avio_size(s
->pb
);
1411 pos_max
= filesize
- 1;
1414 ts_max
= read_timestamp(s
, stream_index
, &pos_max
, pos_max
+ step
);
1416 }while(ts_max
== AV_NOPTS_VALUE
&& pos_max
>= step
);
1417 if (ts_max
== AV_NOPTS_VALUE
)
1421 int64_t tmp_pos
= pos_max
+ 1;
1422 int64_t tmp_ts
= read_timestamp(s
, stream_index
, &tmp_pos
, INT64_MAX
);
1423 if(tmp_ts
== AV_NOPTS_VALUE
)
1427 if(tmp_pos
>= filesize
)
1433 if(ts_min
> ts_max
){
1435 }else if(ts_min
== ts_max
){
1440 while (pos_min
< pos_limit
) {
1441 av_dlog(s
, "pos_min=0x%"PRIx64
" pos_max=0x%"PRIx64
" dts_min=%"PRId64
" dts_max=%"PRId64
"\n",
1442 pos_min
, pos_max
, ts_min
, ts_max
);
1443 assert(pos_limit
<= pos_max
);
1446 int64_t approximate_keyframe_distance
= pos_max
- pos_limit
;
1447 // interpolate position (better than dichotomy)
1448 pos
= av_rescale(target_ts
- ts_min
, pos_max
- pos_min
, ts_max
- ts_min
)
1449 + pos_min
- approximate_keyframe_distance
;
1450 }else if(no_change
==1){
1451 // bisection, if interpolation failed to change min or max pos last time
1452 pos
= (pos_min
+ pos_limit
)>>1;
1454 /* linear search if bisection failed, can only happen if there
1455 are very few or no keyframes between min/max */
1460 else if(pos
> pos_limit
)
1464 ts
= read_timestamp(s
, stream_index
, &pos
, INT64_MAX
); //may pass pos_limit instead of -1
1469 av_dlog(s
, "%"PRId64
" %"PRId64
" %"PRId64
" / %"PRId64
" %"PRId64
" %"PRId64
" target:%"PRId64
" limit:%"PRId64
" start:%"PRId64
" noc:%d\n",
1470 pos_min
, pos
, pos_max
, ts_min
, ts
, ts_max
, target_ts
,
1471 pos_limit
, start_pos
, no_change
);
1472 if(ts
== AV_NOPTS_VALUE
){
1473 av_log(s
, AV_LOG_ERROR
, "read_timestamp() failed in the middle\n");
1476 assert(ts
!= AV_NOPTS_VALUE
);
1477 if (target_ts
<= ts
) {
1478 pos_limit
= start_pos
- 1;
1482 if (target_ts
>= ts
) {
1488 pos
= (flags
& AVSEEK_FLAG_BACKWARD
) ? pos_min
: pos_max
;
1489 ts
= (flags
& AVSEEK_FLAG_BACKWARD
) ? ts_min
: ts_max
;
1491 ts_min
= read_timestamp(s
, stream_index
, &pos_min
, INT64_MAX
);
1493 ts_max
= read_timestamp(s
, stream_index
, &pos_min
, INT64_MAX
);
1494 av_dlog(s
, "pos=0x%"PRIx64
" %"PRId64
"<=%"PRId64
"<=%"PRId64
"\n",
1495 pos
, ts_min
, target_ts
, ts_max
);
1500 static int seek_frame_byte(AVFormatContext
*s
, int stream_index
, int64_t pos
, int flags
){
1501 int64_t pos_min
, pos_max
;
1503 pos_min
= s
->data_offset
;
1504 pos_max
= avio_size(s
->pb
) - 1;
1506 if (pos
< pos_min
) pos
= pos_min
;
1507 else if(pos
> pos_max
) pos
= pos_max
;
1509 avio_seek(s
->pb
, pos
, SEEK_SET
);
1514 static int seek_frame_generic(AVFormatContext
*s
,
1515 int stream_index
, int64_t timestamp
, int flags
)
1522 st
= s
->streams
[stream_index
];
1524 index
= av_index_search_timestamp(st
, timestamp
, flags
);
1526 if(index
< 0 && st
->nb_index_entries
&& timestamp
< st
->index_entries
[0].timestamp
)
1529 if(index
< 0 || index
==st
->nb_index_entries
-1){
1532 if(st
->nb_index_entries
){
1533 assert(st
->index_entries
);
1534 ie
= &st
->index_entries
[st
->nb_index_entries
-1];
1535 if ((ret
= avio_seek(s
->pb
, ie
->pos
, SEEK_SET
)) < 0)
1537 ff_update_cur_dts(s
, st
, ie
->timestamp
);
1539 if ((ret
= avio_seek(s
->pb
, s
->data_offset
, SEEK_SET
)) < 0)
1545 read_status
= av_read_frame(s
, &pkt
);
1546 } while (read_status
== AVERROR(EAGAIN
));
1547 if (read_status
< 0)
1549 av_free_packet(&pkt
);
1550 if(stream_index
== pkt
.stream_index
){
1551 if((pkt
.flags
& AV_PKT_FLAG_KEY
) && pkt
.dts
> timestamp
)
1555 index
= av_index_search_timestamp(st
, timestamp
, flags
);
1560 ff_read_frame_flush(s
);
1561 if (s
->iformat
->read_seek
){
1562 if(s
->iformat
->read_seek(s
, stream_index
, timestamp
, flags
) >= 0)
1565 ie
= &st
->index_entries
[index
];
1566 if ((ret
= avio_seek(s
->pb
, ie
->pos
, SEEK_SET
)) < 0)
1568 ff_update_cur_dts(s
, st
, ie
->timestamp
);
1573 static int seek_frame_internal(AVFormatContext
*s
, int stream_index
,
1574 int64_t timestamp
, int flags
)
1579 if (flags
& AVSEEK_FLAG_BYTE
) {
1580 if (s
->iformat
->flags
& AVFMT_NO_BYTE_SEEK
)
1582 ff_read_frame_flush(s
);
1583 return seek_frame_byte(s
, stream_index
, timestamp
, flags
);
1586 if(stream_index
< 0){
1587 stream_index
= av_find_default_stream_index(s
);
1588 if(stream_index
< 0)
1591 st
= s
->streams
[stream_index
];
1592 /* timestamp for default must be expressed in AV_TIME_BASE units */
1593 timestamp
= av_rescale(timestamp
, st
->time_base
.den
, AV_TIME_BASE
* (int64_t)st
->time_base
.num
);
1596 /* first, we try the format specific seek */
1597 if (s
->iformat
->read_seek
) {
1598 ff_read_frame_flush(s
);
1599 ret
= s
->iformat
->read_seek(s
, stream_index
, timestamp
, flags
);
1606 if (s
->iformat
->read_timestamp
&& !(s
->iformat
->flags
& AVFMT_NOBINSEARCH
)) {
1607 ff_read_frame_flush(s
);
1608 return ff_seek_frame_binary(s
, stream_index
, timestamp
, flags
);
1609 } else if (!(s
->iformat
->flags
& AVFMT_NOGENSEARCH
)) {
1610 ff_read_frame_flush(s
);
1611 return seek_frame_generic(s
, stream_index
, timestamp
, flags
);
1617 int av_seek_frame(AVFormatContext
*s
, int stream_index
, int64_t timestamp
, int flags
)
1619 int ret
= seek_frame_internal(s
, stream_index
, timestamp
, flags
);
1622 ret
= queue_attached_pictures(s
);
1627 int avformat_seek_file(AVFormatContext
*s
, int stream_index
, int64_t min_ts
, int64_t ts
, int64_t max_ts
, int flags
)
1629 if(min_ts
> ts
|| max_ts
< ts
)
1632 if (s
->iformat
->read_seek2
) {
1634 ff_read_frame_flush(s
);
1635 ret
= s
->iformat
->read_seek2(s
, stream_index
, min_ts
, ts
, max_ts
, flags
);
1638 ret
= queue_attached_pictures(s
);
1642 if(s
->iformat
->read_timestamp
){
1643 //try to seek via read_timestamp()
1646 // Fall back on old API if new is not implemented but old is.
1647 // Note the old API has somewhat different semantics.
1648 if(s
->iformat
->read_seek
|| 1)
1649 return av_seek_frame(s
, stream_index
, ts
, flags
| ((uint64_t)ts
- min_ts
> (uint64_t)max_ts
- ts ? AVSEEK_FLAG_BACKWARD
: 0));
1651 // try some generic seek like seek_frame_generic() but with new ts semantics
1654 /*******************************************************/
1657 * Return TRUE if the stream has accurate duration in any stream.
1659 * @return TRUE if the stream has accurate duration for at least one component.
1661 static int has_duration(AVFormatContext
*ic
)
1666 for(i
= 0;i
< ic
->nb_streams
; i
++) {
1667 st
= ic
->streams
[i
];
1668 if (st
->duration
!= AV_NOPTS_VALUE
)
1671 if (ic
->duration
!= AV_NOPTS_VALUE
)
1677 * Estimate the stream timings from the one of each components.
1679 * Also computes the global bitrate if possible.
1681 static void update_stream_timings(AVFormatContext
*ic
)
1683 int64_t start_time
, start_time1
, end_time
, end_time1
;
1684 int64_t duration
, duration1
, filesize
;
1688 start_time
= INT64_MAX
;
1689 end_time
= INT64_MIN
;
1690 duration
= INT64_MIN
;
1691 for(i
= 0;i
< ic
->nb_streams
; i
++) {
1692 st
= ic
->streams
[i
];
1693 if (st
->start_time
!= AV_NOPTS_VALUE
&& st
->time_base
.den
) {
1694 start_time1
= av_rescale_q(st
->start_time
, st
->time_base
, AV_TIME_BASE_Q
);
1695 start_time
= FFMIN(start_time
, start_time1
);
1696 if (st
->duration
!= AV_NOPTS_VALUE
) {
1697 end_time1
= start_time1
1698 + av_rescale_q(st
->duration
, st
->time_base
, AV_TIME_BASE_Q
);
1699 end_time
= FFMAX(end_time
, end_time1
);
1702 if (st
->duration
!= AV_NOPTS_VALUE
) {
1703 duration1
= av_rescale_q(st
->duration
, st
->time_base
, AV_TIME_BASE_Q
);
1704 duration
= FFMAX(duration
, duration1
);
1707 if (start_time
!= INT64_MAX
) {
1708 ic
->start_time
= start_time
;
1709 if (end_time
!= INT64_MIN
)
1710 duration
= FFMAX(duration
, end_time
- start_time
);
1712 if (duration
!= INT64_MIN
) {
1713 ic
->duration
= duration
;
1714 if (ic
->pb
&& (filesize
= avio_size(ic
->pb
)) > 0) {
1715 /* compute the bitrate */
1716 ic
->bit_rate
= (double)filesize
* 8.0 * AV_TIME_BASE
/
1717 (double)ic
->duration
;
1722 static void fill_all_stream_timings(AVFormatContext
*ic
)
1727 update_stream_timings(ic
);
1728 for(i
= 0;i
< ic
->nb_streams
; i
++) {
1729 st
= ic
->streams
[i
];
1730 if (st
->start_time
== AV_NOPTS_VALUE
) {
1731 if(ic
->start_time
!= AV_NOPTS_VALUE
)
1732 st
->start_time
= av_rescale_q(ic
->start_time
, AV_TIME_BASE_Q
, st
->time_base
);
1733 if(ic
->duration
!= AV_NOPTS_VALUE
)
1734 st
->duration
= av_rescale_q(ic
->duration
, AV_TIME_BASE_Q
, st
->time_base
);
1739 static void estimate_timings_from_bit_rate(AVFormatContext
*ic
)
1741 int64_t filesize
, duration
;
1745 /* if bit_rate is already set, we believe it */
1746 if (ic
->bit_rate
<= 0) {
1748 for(i
=0;i
<ic
->nb_streams
;i
++) {
1749 st
= ic
->streams
[i
];
1750 if (st
->codec
->bit_rate
> 0) {
1751 if (INT_MAX
- st
->codec
->bit_rate
< bit_rate
) {
1755 bit_rate
+= st
->codec
->bit_rate
;
1758 ic
->bit_rate
= bit_rate
;
1761 /* if duration is already set, we believe it */
1762 if (ic
->duration
== AV_NOPTS_VALUE
&&
1763 ic
->bit_rate
!= 0) {
1764 filesize
= ic
->pb ?
avio_size(ic
->pb
) : 0;
1766 for(i
= 0; i
< ic
->nb_streams
; i
++) {
1767 st
= ic
->streams
[i
];
1768 duration
= av_rescale(8*filesize
, st
->time_base
.den
, ic
->bit_rate
*(int64_t)st
->time_base
.num
);
1769 if (st
->duration
== AV_NOPTS_VALUE
)
1770 st
->duration
= duration
;
1776 #define DURATION_MAX_READ_SIZE 250000
1777 #define DURATION_MAX_RETRY 3
1779 /* only usable for MPEG-PS streams */
1780 static void estimate_timings_from_pts(AVFormatContext
*ic
, int64_t old_offset
)
1782 AVPacket pkt1
, *pkt
= &pkt1
;
1784 int read_size
, i
, ret
;
1786 int64_t filesize
, offset
, duration
;
1789 /* flush packet queue */
1790 flush_packet_queue(ic
);
1792 for (i
=0; i
<ic
->nb_streams
; i
++) {
1793 st
= ic
->streams
[i
];
1794 if (st
->start_time
== AV_NOPTS_VALUE
&& st
->first_dts
== AV_NOPTS_VALUE
)
1795 av_log(st
->codec
, AV_LOG_WARNING
, "start time is not set in estimate_timings_from_pts\n");
1798 av_parser_close(st
->parser
);
1803 /* estimate the end time (duration) */
1804 /* XXX: may need to support wrapping */
1805 filesize
= ic
->pb ?
avio_size(ic
->pb
) : 0;
1806 end_time
= AV_NOPTS_VALUE
;
1808 offset
= filesize
- (DURATION_MAX_READ_SIZE
<<retry
);
1812 avio_seek(ic
->pb
, offset
, SEEK_SET
);
1815 if (read_size
>= DURATION_MAX_READ_SIZE
<<(FFMAX(retry
-1,0)))
1819 ret
= ff_read_packet(ic
, pkt
);
1820 } while(ret
== AVERROR(EAGAIN
));
1823 read_size
+= pkt
->size
;
1824 st
= ic
->streams
[pkt
->stream_index
];
1825 if (pkt
->pts
!= AV_NOPTS_VALUE
&&
1826 (st
->start_time
!= AV_NOPTS_VALUE
||
1827 st
->first_dts
!= AV_NOPTS_VALUE
)) {
1828 duration
= end_time
= pkt
->pts
;
1829 if (st
->start_time
!= AV_NOPTS_VALUE
)
1830 duration
-= st
->start_time
;
1832 duration
-= st
->first_dts
;
1834 duration
+= 1LL<<st
->pts_wrap_bits
;
1836 if (st
->duration
== AV_NOPTS_VALUE
|| st
->duration
< duration
)
1837 st
->duration
= duration
;
1840 av_free_packet(pkt
);
1842 }while( end_time
==AV_NOPTS_VALUE
1843 && filesize
> (DURATION_MAX_READ_SIZE
<<retry
)
1844 && ++retry
<= DURATION_MAX_RETRY
);
1846 fill_all_stream_timings(ic
);
1848 avio_seek(ic
->pb
, old_offset
, SEEK_SET
);
1849 for (i
=0; i
<ic
->nb_streams
; i
++) {
1851 st
->cur_dts
= st
->first_dts
;
1852 st
->last_IP_pts
= AV_NOPTS_VALUE
;
1856 static void estimate_timings(AVFormatContext
*ic
, int64_t old_offset
)
1860 /* get the file size, if possible */
1861 if (ic
->iformat
->flags
& AVFMT_NOFILE
) {
1864 file_size
= avio_size(ic
->pb
);
1865 file_size
= FFMAX(0, file_size
);
1868 if ((!strcmp(ic
->iformat
->name
, "mpeg") ||
1869 !strcmp(ic
->iformat
->name
, "mpegts")) &&
1870 file_size
&& ic
->pb
->seekable
) {
1871 /* get accurate estimate from the PTSes */
1872 estimate_timings_from_pts(ic
, old_offset
);
1873 } else if (has_duration(ic
)) {
1874 /* at least one component has timings - we use them for all
1876 fill_all_stream_timings(ic
);
1878 av_log(ic
, AV_LOG_WARNING
, "Estimating duration from bitrate, this may be inaccurate\n");
1879 /* less precise: use bitrate info */
1880 estimate_timings_from_bit_rate(ic
);
1882 update_stream_timings(ic
);
1886 AVStream av_unused
*st
;
1887 for(i
= 0;i
< ic
->nb_streams
; i
++) {
1888 st
= ic
->streams
[i
];
1889 av_dlog(ic
, "%d: start_time: %0.3f duration: %0.3f\n", i
,
1890 (double) st
->start_time
/ AV_TIME_BASE
,
1891 (double) st
->duration
/ AV_TIME_BASE
);
1893 av_dlog(ic
, "stream: start_time: %0.3f duration: %0.3f bitrate=%d kb/s\n",
1894 (double) ic
->start_time
/ AV_TIME_BASE
,
1895 (double) ic
->duration
/ AV_TIME_BASE
,
1896 ic
->bit_rate
/ 1000);
1900 static int has_codec_parameters(AVStream
*st
)
1902 AVCodecContext
*avctx
= st
->codec
;
1904 switch (avctx
->codec_type
) {
1905 case AVMEDIA_TYPE_AUDIO
:
1906 val
= avctx
->sample_rate
&& avctx
->channels
;
1907 if (st
->info
->found_decoder
>= 0 && avctx
->sample_fmt
== AV_SAMPLE_FMT_NONE
)
1910 case AVMEDIA_TYPE_VIDEO
:
1912 if (st
->info
->found_decoder
>= 0 && avctx
->pix_fmt
== AV_PIX_FMT_NONE
)
1919 return avctx
->codec_id
!= AV_CODEC_ID_NONE
&& val
!= 0;
1922 static int has_decode_delay_been_guessed(AVStream
*st
)
1924 return st
->codec
->codec_id
!= AV_CODEC_ID_H264
||
1925 st
->info
->nb_decoded_frames
>= 6;
1928 /* returns 1 or 0 if or if not decoded data was returned, or a negative error */
1929 static int try_decode_frame(AVStream
*st
, AVPacket
*avpkt
, AVDictionary
**options
)
1931 const AVCodec
*codec
;
1932 int got_picture
= 1, ret
= 0;
1933 AVFrame
*frame
= av_frame_alloc();
1934 AVPacket pkt
= *avpkt
;
1937 return AVERROR(ENOMEM
);
1939 if (!avcodec_is_open(st
->codec
) && !st
->info
->found_decoder
) {
1940 AVDictionary
*thread_opt
= NULL
;
1942 codec
= st
->codec
->codec ? st
->codec
->codec
:
1943 avcodec_find_decoder(st
->codec
->codec_id
);
1946 st
->info
->found_decoder
= -1;
1951 /* force thread count to 1 since the h264 decoder will not extract SPS
1952 * and PPS to extradata during multi-threaded decoding */
1953 av_dict_set(options ? options
: &thread_opt
, "threads", "1", 0);
1954 ret
= avcodec_open2(st
->codec
, codec
, options ? options
: &thread_opt
);
1956 av_dict_free(&thread_opt
);
1958 st
->info
->found_decoder
= -1;
1961 st
->info
->found_decoder
= 1;
1962 } else if (!st
->info
->found_decoder
)
1963 st
->info
->found_decoder
= 1;
1965 if (st
->info
->found_decoder
< 0) {
1970 while ((pkt
.size
> 0 || (!pkt
.data
&& got_picture
)) &&
1972 (!has_codec_parameters(st
) ||
1973 !has_decode_delay_been_guessed(st
) ||
1974 (!st
->codec_info_nb_frames
&& st
->codec
->codec
->capabilities
& CODEC_CAP_CHANNEL_CONF
))) {
1976 switch(st
->codec
->codec_type
) {
1977 case AVMEDIA_TYPE_VIDEO
:
1978 ret
= avcodec_decode_video2(st
->codec
, frame
,
1979 &got_picture
, &pkt
);
1981 case AVMEDIA_TYPE_AUDIO
:
1982 ret
= avcodec_decode_audio4(st
->codec
, frame
, &got_picture
, &pkt
);
1989 st
->info
->nb_decoded_frames
++;
1997 av_frame_free(&frame
);
2001 unsigned int ff_codec_get_tag(const AVCodecTag
*tags
, enum AVCodecID id
)
2003 while (tags
->id
!= AV_CODEC_ID_NONE
) {
2011 enum AVCodecID
ff_codec_get_id(const AVCodecTag
*tags
, unsigned int tag
)
2014 for(i
=0; tags
[i
].id
!= AV_CODEC_ID_NONE
;i
++) {
2015 if(tag
== tags
[i
].tag
)
2018 for(i
=0; tags
[i
].id
!= AV_CODEC_ID_NONE
; i
++) {
2019 if (avpriv_toupper4(tag
) == avpriv_toupper4(tags
[i
].tag
))
2022 return AV_CODEC_ID_NONE
;
2025 enum AVCodecID
ff_get_pcm_codec_id(int bps
, int flt
, int be
, int sflags
)
2029 case 32: return be ? AV_CODEC_ID_PCM_F32BE
: AV_CODEC_ID_PCM_F32LE
;
2030 case 64: return be ? AV_CODEC_ID_PCM_F64BE
: AV_CODEC_ID_PCM_F64LE
;
2031 default: return AV_CODEC_ID_NONE
;
2035 if (sflags
& (1 << (bps
- 1))) {
2037 case 1: return AV_CODEC_ID_PCM_S8
;
2038 case 2: return be ? AV_CODEC_ID_PCM_S16BE
: AV_CODEC_ID_PCM_S16LE
;
2039 case 3: return be ? AV_CODEC_ID_PCM_S24BE
: AV_CODEC_ID_PCM_S24LE
;
2040 case 4: return be ? AV_CODEC_ID_PCM_S32BE
: AV_CODEC_ID_PCM_S32LE
;
2041 default: return AV_CODEC_ID_NONE
;
2045 case 1: return AV_CODEC_ID_PCM_U8
;
2046 case 2: return be ? AV_CODEC_ID_PCM_U16BE
: AV_CODEC_ID_PCM_U16LE
;
2047 case 3: return be ? AV_CODEC_ID_PCM_U24BE
: AV_CODEC_ID_PCM_U24LE
;
2048 case 4: return be ? AV_CODEC_ID_PCM_U32BE
: AV_CODEC_ID_PCM_U32LE
;
2049 default: return AV_CODEC_ID_NONE
;
2055 unsigned int av_codec_get_tag(const AVCodecTag
* const *tags
, enum AVCodecID id
)
2058 for(i
=0; tags
&& tags
[i
]; i
++){
2059 int tag
= ff_codec_get_tag(tags
[i
], id
);
2065 enum AVCodecID
av_codec_get_id(const AVCodecTag
* const *tags
, unsigned int tag
)
2068 for(i
=0; tags
&& tags
[i
]; i
++){
2069 enum AVCodecID id
= ff_codec_get_id(tags
[i
], tag
);
2070 if(id
!=AV_CODEC_ID_NONE
) return id
;
2072 return AV_CODEC_ID_NONE
;
2075 static void compute_chapters_end(AVFormatContext
*s
)
2078 int64_t max_time
= s
->duration
+ ((s
->start_time
== AV_NOPTS_VALUE
) ?
0 : s
->start_time
);
2080 for (i
= 0; i
< s
->nb_chapters
; i
++)
2081 if (s
->chapters
[i
]->end
== AV_NOPTS_VALUE
) {
2082 AVChapter
*ch
= s
->chapters
[i
];
2083 int64_t end
= max_time ?
av_rescale_q(max_time
, AV_TIME_BASE_Q
, ch
->time_base
)
2086 for (j
= 0; j
< s
->nb_chapters
; j
++) {
2087 AVChapter
*ch1
= s
->chapters
[j
];
2088 int64_t next_start
= av_rescale_q(ch1
->start
, ch1
->time_base
, ch
->time_base
);
2089 if (j
!= i
&& next_start
> ch
->start
&& next_start
< end
)
2092 ch
->end
= (end
== INT64_MAX
) ? ch
->start
: end
;
2096 static int get_std_framerate(int i
){
2097 if(i
<60*12) return i
*1001;
2098 else return ((const int[]){24,30,60,12,15})[i
-60*12]*1000*12;
2102 * Is the time base unreliable.
2103 * This is a heuristic to balance between quick acceptance of the values in
2104 * the headers vs. some extra checks.
2105 * Old DivX and Xvid often have nonsense timebases like 1fps or 2fps.
2106 * MPEG-2 commonly misuses field repeat flags to store different framerates.
2107 * And there are "variable" fps files this needs to detect as well.
2109 static int tb_unreliable(AVCodecContext
*c
){
2110 if( c
->time_base
.den
>= 101L*c
->time_base
.num
2111 || c
->time_base
.den
< 5L*c
->time_base
.num
2112 /* || c->codec_tag == AV_RL32("DIVX")
2113 || c->codec_tag == AV_RL32("XVID")*/
2114 || c
->codec_id
== AV_CODEC_ID_MPEG2VIDEO
2115 || c
->codec_id
== AV_CODEC_ID_H264
2121 int avformat_find_stream_info(AVFormatContext
*ic
, AVDictionary
**options
)
2123 int i
, count
, ret
, read_size
, j
;
2125 AVPacket pkt1
, *pkt
;
2126 int64_t old_offset
= avio_tell(ic
->pb
);
2127 int orig_nb_streams
= ic
->nb_streams
; // new streams might appear, no options for those
2129 for(i
=0;i
<ic
->nb_streams
;i
++) {
2130 const AVCodec
*codec
;
2131 AVDictionary
*thread_opt
= NULL
;
2132 st
= ic
->streams
[i
];
2134 //only for the split stuff
2135 if (!st
->parser
&& !(ic
->flags
& AVFMT_FLAG_NOPARSE
)) {
2136 st
->parser
= av_parser_init(st
->codec
->codec_id
);
2137 if(st
->need_parsing
== AVSTREAM_PARSE_HEADERS
&& st
->parser
){
2138 st
->parser
->flags
|= PARSER_FLAG_COMPLETE_FRAMES
;
2141 codec
= st
->codec
->codec ? st
->codec
->codec
:
2142 avcodec_find_decoder(st
->codec
->codec_id
);
2144 /* force thread count to 1 since the h264 decoder will not extract SPS
2145 * and PPS to extradata during multi-threaded decoding */
2146 av_dict_set(options ?
&options
[i
] : &thread_opt
, "threads", "1", 0);
2148 /* Ensure that subtitle_header is properly set. */
2149 if (st
->codec
->codec_type
== AVMEDIA_TYPE_SUBTITLE
2150 && codec
&& !st
->codec
->codec
)
2151 avcodec_open2(st
->codec
, codec
, options ?
&options
[i
]
2154 //try to just open decoders, in case this is enough to get parameters
2155 if (!has_codec_parameters(st
)) {
2156 if (codec
&& !st
->codec
->codec
)
2157 avcodec_open2(st
->codec
, codec
, options ?
&options
[i
]
2161 av_dict_free(&thread_opt
);
2164 for (i
=0; i
<ic
->nb_streams
; i
++) {
2165 ic
->streams
[i
]->info
->fps_first_dts
= AV_NOPTS_VALUE
;
2166 ic
->streams
[i
]->info
->fps_last_dts
= AV_NOPTS_VALUE
;
2172 if (ff_check_interrupt(&ic
->interrupt_callback
)){
2174 av_log(ic
, AV_LOG_DEBUG
, "interrupted\n");
2178 /* check if one codec still needs to be handled */
2179 for(i
=0;i
<ic
->nb_streams
;i
++) {
2180 int fps_analyze_framecount
= 20;
2182 st
= ic
->streams
[i
];
2183 if (!has_codec_parameters(st
))
2185 /* if the timebase is coarse (like the usual millisecond precision
2186 of mkv), we need to analyze more frames to reliably arrive at
2188 if (av_q2d(st
->time_base
) > 0.0005)
2189 fps_analyze_framecount
*= 2;
2190 if (ic
->fps_probe_size
>= 0)
2191 fps_analyze_framecount
= ic
->fps_probe_size
;
2192 /* variable fps and no guess at the real fps */
2193 if( tb_unreliable(st
->codec
) && !st
->avg_frame_rate
.num
2194 && st
->codec_info_nb_frames
< fps_analyze_framecount
2195 && st
->codec
->codec_type
== AVMEDIA_TYPE_VIDEO
)
2197 if(st
->parser
&& st
->parser
->parser
->split
&& !st
->codec
->extradata
)
2199 if (st
->first_dts
== AV_NOPTS_VALUE
&&
2200 (st
->codec
->codec_type
== AVMEDIA_TYPE_VIDEO
||
2201 st
->codec
->codec_type
== AVMEDIA_TYPE_AUDIO
))
2204 if (i
== ic
->nb_streams
) {
2205 /* NOTE: if the format has no header, then we need to read
2206 some packets to get most of the streams, so we cannot
2208 if (!(ic
->ctx_flags
& AVFMTCTX_NOHEADER
)) {
2209 /* if we found the info for all the codecs, we can stop */
2211 av_log(ic
, AV_LOG_DEBUG
, "All info found\n");
2215 /* we did not get all the codec info, but we read too much data */
2216 if (read_size
>= ic
->probesize
) {
2218 av_log(ic
, AV_LOG_DEBUG
, "Probe buffer size limit %d reached\n", ic
->probesize
);
2222 /* NOTE: a new stream can be added there if no header in file
2223 (AVFMTCTX_NOHEADER) */
2224 ret
= read_frame_internal(ic
, &pkt1
);
2225 if (ret
== AVERROR(EAGAIN
))
2230 AVPacket empty_pkt
= { 0 };
2232 av_init_packet(&empty_pkt
);
2234 ret
= -1; /* we could not have all the codec parameters before EOF */
2235 for(i
=0;i
<ic
->nb_streams
;i
++) {
2236 st
= ic
->streams
[i
];
2238 /* flush the decoders */
2239 if (st
->info
->found_decoder
== 1) {
2241 err
= try_decode_frame(st
, &empty_pkt
,
2242 (options
&& i
< orig_nb_streams
) ?
2243 &options
[i
] : NULL
);
2244 } while (err
> 0 && !has_codec_parameters(st
));
2248 av_log(ic
, AV_LOG_WARNING
,
2249 "decoding for stream %d failed\n", st
->index
);
2250 } else if (!has_codec_parameters(st
)) {
2252 avcodec_string(buf
, sizeof(buf
), st
->codec
, 0);
2253 av_log(ic
, AV_LOG_WARNING
,
2254 "Could not find codec parameters (%s)\n", buf
);
2262 if (ic
->flags
& AVFMT_FLAG_NOBUFFER
) {
2265 pkt
= add_to_pktbuf(&ic
->packet_buffer
, &pkt1
,
2266 &ic
->packet_buffer_end
);
2267 if ((ret
= av_dup_packet(pkt
)) < 0)
2268 goto find_stream_info_err
;
2271 read_size
+= pkt
->size
;
2273 st
= ic
->streams
[pkt
->stream_index
];
2274 if (pkt
->dts
!= AV_NOPTS_VALUE
&& st
->codec_info_nb_frames
> 1) {
2275 /* check for non-increasing dts */
2276 if (st
->info
->fps_last_dts
!= AV_NOPTS_VALUE
&&
2277 st
->info
->fps_last_dts
>= pkt
->dts
) {
2278 av_log(ic
, AV_LOG_WARNING
, "Non-increasing DTS in stream %d: "
2279 "packet %d with DTS %"PRId64
", packet %d with DTS "
2280 "%"PRId64
"\n", st
->index
, st
->info
->fps_last_dts_idx
,
2281 st
->info
->fps_last_dts
, st
->codec_info_nb_frames
, pkt
->dts
);
2282 st
->info
->fps_first_dts
= st
->info
->fps_last_dts
= AV_NOPTS_VALUE
;
2284 /* check for a discontinuity in dts - if the difference in dts
2285 * is more than 1000 times the average packet duration in the sequence,
2286 * we treat it as a discontinuity */
2287 if (st
->info
->fps_last_dts
!= AV_NOPTS_VALUE
&&
2288 st
->info
->fps_last_dts_idx
> st
->info
->fps_first_dts_idx
&&
2289 (pkt
->dts
- st
->info
->fps_last_dts
) / 1000 >
2290 (st
->info
->fps_last_dts
- st
->info
->fps_first_dts
) / (st
->info
->fps_last_dts_idx
- st
->info
->fps_first_dts_idx
)) {
2291 av_log(ic
, AV_LOG_WARNING
, "DTS discontinuity in stream %d: "
2292 "packet %d with DTS %"PRId64
", packet %d with DTS "
2293 "%"PRId64
"\n", st
->index
, st
->info
->fps_last_dts_idx
,
2294 st
->info
->fps_last_dts
, st
->codec_info_nb_frames
, pkt
->dts
);
2295 st
->info
->fps_first_dts
= st
->info
->fps_last_dts
= AV_NOPTS_VALUE
;
2298 /* update stored dts values */
2299 if (st
->info
->fps_first_dts
== AV_NOPTS_VALUE
) {
2300 st
->info
->fps_first_dts
= pkt
->dts
;
2301 st
->info
->fps_first_dts_idx
= st
->codec_info_nb_frames
;
2303 st
->info
->fps_last_dts
= pkt
->dts
;
2304 st
->info
->fps_last_dts_idx
= st
->codec_info_nb_frames
;
2306 /* check max_analyze_duration */
2307 if (av_rescale_q(pkt
->dts
- st
->info
->fps_first_dts
, st
->time_base
,
2308 AV_TIME_BASE_Q
) >= ic
->max_analyze_duration
) {
2309 av_log(ic
, AV_LOG_WARNING
, "max_analyze_duration reached\n");
2313 if(st
->parser
&& st
->parser
->parser
->split
&& !st
->codec
->extradata
){
2314 int i
= st
->parser
->parser
->split(st
->codec
, pkt
->data
, pkt
->size
);
2315 if (i
> 0 && i
< FF_MAX_EXTRADATA_SIZE
) {
2316 st
->codec
->extradata_size
= i
;
2317 st
->codec
->extradata
= av_malloc(st
->codec
->extradata_size
+ FF_INPUT_BUFFER_PADDING_SIZE
);
2318 if (!st
->codec
->extradata
)
2319 return AVERROR(ENOMEM
);
2320 memcpy(st
->codec
->extradata
, pkt
->data
, st
->codec
->extradata_size
);
2321 memset(st
->codec
->extradata
+ i
, 0, FF_INPUT_BUFFER_PADDING_SIZE
);
2325 /* if still no information, we try to open the codec and to
2326 decompress the frame. We try to avoid that in most cases as
2327 it takes longer and uses more memory. For MPEG-4, we need to
2328 decompress for QuickTime.
2330 If CODEC_CAP_CHANNEL_CONF is set this will force decoding of at
2331 least one frame of codec data, this makes sure the codec initializes
2332 the channel configuration and does not only trust the values from the container.
2334 try_decode_frame(st
, pkt
, (options
&& i
< orig_nb_streams
) ?
&options
[i
] : NULL
);
2336 st
->codec_info_nb_frames
++;
2340 // close codecs which were opened in try_decode_frame()
2341 for(i
=0;i
<ic
->nb_streams
;i
++) {
2342 st
= ic
->streams
[i
];
2343 avcodec_close(st
->codec
);
2345 for(i
=0;i
<ic
->nb_streams
;i
++) {
2346 st
= ic
->streams
[i
];
2347 if (st
->codec
->codec_type
== AVMEDIA_TYPE_VIDEO
) {
2348 /* estimate average framerate if not set by demuxer */
2349 if (!st
->avg_frame_rate
.num
&& st
->info
->fps_last_dts
!= st
->info
->fps_first_dts
) {
2350 int64_t delta_dts
= st
->info
->fps_last_dts
- st
->info
->fps_first_dts
;
2351 int delta_packets
= st
->info
->fps_last_dts_idx
- st
->info
->fps_first_dts_idx
;
2353 double best_error
= 0.01;
2355 if (delta_dts
>= INT64_MAX
/ st
->time_base
.num
||
2356 delta_packets
>= INT64_MAX
/ st
->time_base
.den
||
2359 av_reduce(&st
->avg_frame_rate
.num
, &st
->avg_frame_rate
.den
,
2360 delta_packets
*(int64_t)st
->time_base
.den
,
2361 delta_dts
*(int64_t)st
->time_base
.num
, 60000);
2363 /* round guessed framerate to a "standard" framerate if it's
2364 * within 1% of the original estimate*/
2365 for (j
= 1; j
< MAX_STD_TIMEBASES
; j
++) {
2366 AVRational std_fps
= { get_std_framerate(j
), 12*1001 };
2367 double error
= fabs(av_q2d(st
->avg_frame_rate
) / av_q2d(std_fps
) - 1);
2369 if (error
< best_error
) {
2371 best_fps
= std_fps
.num
;
2375 av_reduce(&st
->avg_frame_rate
.num
, &st
->avg_frame_rate
.den
,
2376 best_fps
, 12*1001, INT_MAX
);
2379 }else if(st
->codec
->codec_type
== AVMEDIA_TYPE_AUDIO
) {
2380 if(!st
->codec
->bits_per_coded_sample
)
2381 st
->codec
->bits_per_coded_sample
= av_get_bits_per_sample(st
->codec
->codec_id
);
2382 // set stream disposition based on audio service type
2383 switch (st
->codec
->audio_service_type
) {
2384 case AV_AUDIO_SERVICE_TYPE_EFFECTS
:
2385 st
->disposition
= AV_DISPOSITION_CLEAN_EFFECTS
; break;
2386 case AV_AUDIO_SERVICE_TYPE_VISUALLY_IMPAIRED
:
2387 st
->disposition
= AV_DISPOSITION_VISUAL_IMPAIRED
; break;
2388 case AV_AUDIO_SERVICE_TYPE_HEARING_IMPAIRED
:
2389 st
->disposition
= AV_DISPOSITION_HEARING_IMPAIRED
; break;
2390 case AV_AUDIO_SERVICE_TYPE_COMMENTARY
:
2391 st
->disposition
= AV_DISPOSITION_COMMENT
; break;
2392 case AV_AUDIO_SERVICE_TYPE_KARAOKE
:
2393 st
->disposition
= AV_DISPOSITION_KARAOKE
; break;
2398 estimate_timings(ic
, old_offset
);
2400 compute_chapters_end(ic
);
2402 find_stream_info_err
:
2403 for (i
=0; i
< ic
->nb_streams
; i
++) {
2404 ic
->streams
[i
]->codec
->thread_count
= 0;
2405 av_freep(&ic
->streams
[i
]->info
);
2410 static AVProgram
*find_program_from_stream(AVFormatContext
*ic
, int s
)
2414 for (i
= 0; i
< ic
->nb_programs
; i
++)
2415 for (j
= 0; j
< ic
->programs
[i
]->nb_stream_indexes
; j
++)
2416 if (ic
->programs
[i
]->stream_index
[j
] == s
)
2417 return ic
->programs
[i
];
2421 int av_find_best_stream(AVFormatContext
*ic
,
2422 enum AVMediaType type
,
2423 int wanted_stream_nb
,
2425 AVCodec
**decoder_ret
,
2428 int i
, nb_streams
= ic
->nb_streams
;
2429 int ret
= AVERROR_STREAM_NOT_FOUND
, best_count
= -1;
2430 unsigned *program
= NULL
;
2431 AVCodec
*decoder
= NULL
, *best_decoder
= NULL
;
2433 if (related_stream
>= 0 && wanted_stream_nb
< 0) {
2434 AVProgram
*p
= find_program_from_stream(ic
, related_stream
);
2436 program
= p
->stream_index
;
2437 nb_streams
= p
->nb_stream_indexes
;
2440 for (i
= 0; i
< nb_streams
; i
++) {
2441 int real_stream_index
= program ? program
[i
] : i
;
2442 AVStream
*st
= ic
->streams
[real_stream_index
];
2443 AVCodecContext
*avctx
= st
->codec
;
2444 if (avctx
->codec_type
!= type
)
2446 if (wanted_stream_nb
>= 0 && real_stream_index
!= wanted_stream_nb
)
2448 if (st
->disposition
& (AV_DISPOSITION_HEARING_IMPAIRED
|AV_DISPOSITION_VISUAL_IMPAIRED
))
2451 decoder
= avcodec_find_decoder(st
->codec
->codec_id
);
2454 ret
= AVERROR_DECODER_NOT_FOUND
;
2458 if (best_count
>= st
->codec_info_nb_frames
)
2460 best_count
= st
->codec_info_nb_frames
;
2461 ret
= real_stream_index
;
2462 best_decoder
= decoder
;
2463 if (program
&& i
== nb_streams
- 1 && ret
< 0) {
2465 nb_streams
= ic
->nb_streams
;
2466 i
= 0; /* no related stream found, try again with everything */
2470 *decoder_ret
= best_decoder
;
2474 /*******************************************************/
2476 int av_read_play(AVFormatContext
*s
)
2478 if (s
->iformat
->read_play
)
2479 return s
->iformat
->read_play(s
);
2481 return avio_pause(s
->pb
, 0);
2482 return AVERROR(ENOSYS
);
2485 int av_read_pause(AVFormatContext
*s
)
2487 if (s
->iformat
->read_pause
)
2488 return s
->iformat
->read_pause(s
);
2490 return avio_pause(s
->pb
, 1);
2491 return AVERROR(ENOSYS
);
2494 void avformat_free_context(AVFormatContext
*s
)
2500 if (s
->iformat
&& s
->iformat
->priv_class
&& s
->priv_data
)
2501 av_opt_free(s
->priv_data
);
2503 for(i
=0;i
<s
->nb_streams
;i
++) {
2504 /* free all data in a stream component */
2507 av_parser_close(st
->parser
);
2509 if (st
->attached_pic
.data
)
2510 av_free_packet(&st
->attached_pic
);
2511 av_dict_free(&st
->metadata
);
2512 av_freep(&st
->probe_data
.buf
);
2513 av_free(st
->index_entries
);
2514 av_free(st
->codec
->extradata
);
2515 av_free(st
->codec
->subtitle_header
);
2517 av_free(st
->priv_data
);
2521 for(i
=s
->nb_programs
-1; i
>=0; i
--) {
2522 av_dict_free(&s
->programs
[i
]->metadata
);
2523 av_freep(&s
->programs
[i
]->stream_index
);
2524 av_freep(&s
->programs
[i
]);
2526 av_freep(&s
->programs
);
2527 av_freep(&s
->priv_data
);
2528 while(s
->nb_chapters
--) {
2529 av_dict_free(&s
->chapters
[s
->nb_chapters
]->metadata
);
2530 av_free(s
->chapters
[s
->nb_chapters
]);
2532 av_freep(&s
->chapters
);
2533 av_dict_free(&s
->metadata
);
2534 av_freep(&s
->streams
);
2538 void avformat_close_input(AVFormatContext
**ps
)
2540 AVFormatContext
*s
= *ps
;
2541 AVIOContext
*pb
= s
->pb
;
2543 if ((s
->iformat
&& s
->iformat
->flags
& AVFMT_NOFILE
) ||
2544 (s
->flags
& AVFMT_FLAG_CUSTOM_IO
))
2547 flush_packet_queue(s
);
2550 if (s
->iformat
->read_close
)
2551 s
->iformat
->read_close(s
);
2554 avformat_free_context(s
);
2561 AVStream
*avformat_new_stream(AVFormatContext
*s
, AVCodec
*c
)
2566 if (av_reallocp_array(&s
->streams
, s
->nb_streams
+ 1, sizeof(*s
->streams
)) < 0) {
2571 st
= av_mallocz(sizeof(AVStream
));
2574 if (!(st
->info
= av_mallocz(sizeof(*st
->info
)))) {
2579 st
->codec
= avcodec_alloc_context3(c
);
2581 /* no default bitrate if decoding */
2582 st
->codec
->bit_rate
= 0;
2584 st
->index
= s
->nb_streams
;
2585 st
->start_time
= AV_NOPTS_VALUE
;
2586 st
->duration
= AV_NOPTS_VALUE
;
2587 /* we set the current DTS to 0 so that formats without any timestamps
2588 but durations get some timestamps, formats with some unknown
2589 timestamps have their first few packets buffered and the
2590 timestamps corrected before they are returned to the user */
2592 st
->first_dts
= AV_NOPTS_VALUE
;
2593 st
->probe_packets
= MAX_PROBE_PACKETS
;
2595 /* default pts setting is MPEG-like */
2596 avpriv_set_pts_info(st
, 33, 1, 90000);
2597 st
->last_IP_pts
= AV_NOPTS_VALUE
;
2598 for(i
=0; i
<MAX_REORDER_DELAY
+1; i
++)
2599 st
->pts_buffer
[i
]= AV_NOPTS_VALUE
;
2601 st
->sample_aspect_ratio
= (AVRational
){0,1};
2603 st
->info
->fps_first_dts
= AV_NOPTS_VALUE
;
2604 st
->info
->fps_last_dts
= AV_NOPTS_VALUE
;
2606 s
->streams
[s
->nb_streams
++] = st
;
2610 AVProgram
*av_new_program(AVFormatContext
*ac
, int id
)
2612 AVProgram
*program
=NULL
;
2615 av_dlog(ac
, "new_program: id=0x%04x\n", id
);
2617 for(i
=0; i
<ac
->nb_programs
; i
++)
2618 if(ac
->programs
[i
]->id
== id
)
2619 program
= ac
->programs
[i
];
2622 program
= av_mallocz(sizeof(AVProgram
));
2625 dynarray_add(&ac
->programs
, &ac
->nb_programs
, program
);
2626 program
->discard
= AVDISCARD_NONE
;
2633 AVChapter
*avpriv_new_chapter(AVFormatContext
*s
, int id
, AVRational time_base
, int64_t start
, int64_t end
, const char *title
)
2635 AVChapter
*chapter
= NULL
;
2638 for(i
=0; i
<s
->nb_chapters
; i
++)
2639 if(s
->chapters
[i
]->id
== id
)
2640 chapter
= s
->chapters
[i
];
2643 chapter
= av_mallocz(sizeof(AVChapter
));
2646 dynarray_add(&s
->chapters
, &s
->nb_chapters
, chapter
);
2648 av_dict_set(&chapter
->metadata
, "title", title
, 0);
2650 chapter
->time_base
= time_base
;
2651 chapter
->start
= start
;
2657 void ff_program_add_stream_index(AVFormatContext
*ac
, int progid
, unsigned int idx
)
2660 AVProgram
*program
=NULL
;
2662 if (idx
>= ac
->nb_streams
) {
2663 av_log(ac
, AV_LOG_ERROR
, "stream index %d is not valid\n", idx
);
2667 for(i
=0; i
<ac
->nb_programs
; i
++){
2668 if(ac
->programs
[i
]->id
!= progid
)
2670 program
= ac
->programs
[i
];
2671 for(j
=0; j
<program
->nb_stream_indexes
; j
++)
2672 if(program
->stream_index
[j
] == idx
)
2675 if (av_reallocp_array(&program
->stream_index
,
2676 program
->nb_stream_indexes
+ 1,
2677 sizeof(*program
->stream_index
)) < 0) {
2678 program
->nb_stream_indexes
= 0;
2681 program
->stream_index
[program
->nb_stream_indexes
++] = idx
;
2686 static void print_fps(double d
, const char *postfix
){
2687 uint64_t v
= lrintf(d
*100);
2688 if (v
% 100 ) av_log(NULL
, AV_LOG_INFO
, ", %3.2f %s", d
, postfix
);
2689 else if(v
%(100*1000)) av_log(NULL
, AV_LOG_INFO
, ", %1.0f %s", d
, postfix
);
2690 else av_log(NULL
, AV_LOG_INFO
, ", %1.0fk %s", d
/1000, postfix
);
2693 static void dump_metadata(void *ctx
, AVDictionary
*m
, const char *indent
)
2695 if(m
&& !(av_dict_count(m
) == 1 && av_dict_get(m
, "language", NULL
, 0))){
2696 AVDictionaryEntry
*tag
=NULL
;
2698 av_log(ctx
, AV_LOG_INFO
, "%sMetadata:\n", indent
);
2699 while((tag
=av_dict_get(m
, "", tag
, AV_DICT_IGNORE_SUFFIX
))) {
2700 if(strcmp("language", tag
->key
))
2701 av_log(ctx
, AV_LOG_INFO
, "%s %-16s: %s\n", indent
, tag
->key
, tag
->value
);
2706 /* "user interface" functions */
2707 static void dump_stream_format(AVFormatContext
*ic
, int i
, int index
, int is_output
)
2710 int flags
= (is_output ? ic
->oformat
->flags
: ic
->iformat
->flags
);
2711 AVStream
*st
= ic
->streams
[i
];
2712 int g
= av_gcd(st
->time_base
.num
, st
->time_base
.den
);
2713 AVDictionaryEntry
*lang
= av_dict_get(st
->metadata
, "language", NULL
, 0);
2714 avcodec_string(buf
, sizeof(buf
), st
->codec
, is_output
);
2715 av_log(NULL
, AV_LOG_INFO
, " Stream #%d.%d", index
, i
);
2716 /* the pid is an important information, so we display it */
2717 /* XXX: add a generic system */
2718 if (flags
& AVFMT_SHOW_IDS
)
2719 av_log(NULL
, AV_LOG_INFO
, "[0x%x]", st
->id
);
2721 av_log(NULL
, AV_LOG_INFO
, "(%s)", lang
->value
);
2722 av_log(NULL
, AV_LOG_DEBUG
, ", %d, %d/%d", st
->codec_info_nb_frames
, st
->time_base
.num
/g
, st
->time_base
.den
/g
);
2723 av_log(NULL
, AV_LOG_INFO
, ": %s", buf
);
2724 if (st
->sample_aspect_ratio
.num
&& // default
2725 av_cmp_q(st
->sample_aspect_ratio
, st
->codec
->sample_aspect_ratio
)) {
2726 AVRational display_aspect_ratio
;
2727 av_reduce(&display_aspect_ratio
.num
, &display_aspect_ratio
.den
,
2728 st
->codec
->width
*st
->sample_aspect_ratio
.num
,
2729 st
->codec
->height
*st
->sample_aspect_ratio
.den
,
2731 av_log(NULL
, AV_LOG_INFO
, ", PAR %d:%d DAR %d:%d",
2732 st
->sample_aspect_ratio
.num
, st
->sample_aspect_ratio
.den
,
2733 display_aspect_ratio
.num
, display_aspect_ratio
.den
);
2735 if(st
->codec
->codec_type
== AVMEDIA_TYPE_VIDEO
){
2736 if(st
->avg_frame_rate
.den
&& st
->avg_frame_rate
.num
)
2737 print_fps(av_q2d(st
->avg_frame_rate
), "fps");
2738 if(st
->time_base
.den
&& st
->time_base
.num
)
2739 print_fps(1/av_q2d(st
->time_base
), "tbn");
2740 if(st
->codec
->time_base
.den
&& st
->codec
->time_base
.num
)
2741 print_fps(1/av_q2d(st
->codec
->time_base
), "tbc");
2743 if (st
->disposition
& AV_DISPOSITION_DEFAULT
)
2744 av_log(NULL
, AV_LOG_INFO
, " (default)");
2745 if (st
->disposition
& AV_DISPOSITION_DUB
)
2746 av_log(NULL
, AV_LOG_INFO
, " (dub)");
2747 if (st
->disposition
& AV_DISPOSITION_ORIGINAL
)
2748 av_log(NULL
, AV_LOG_INFO
, " (original)");
2749 if (st
->disposition
& AV_DISPOSITION_COMMENT
)
2750 av_log(NULL
, AV_LOG_INFO
, " (comment)");
2751 if (st
->disposition
& AV_DISPOSITION_LYRICS
)
2752 av_log(NULL
, AV_LOG_INFO
, " (lyrics)");
2753 if (st
->disposition
& AV_DISPOSITION_KARAOKE
)
2754 av_log(NULL
, AV_LOG_INFO
, " (karaoke)");
2755 if (st
->disposition
& AV_DISPOSITION_FORCED
)
2756 av_log(NULL
, AV_LOG_INFO
, " (forced)");
2757 if (st
->disposition
& AV_DISPOSITION_HEARING_IMPAIRED
)
2758 av_log(NULL
, AV_LOG_INFO
, " (hearing impaired)");
2759 if (st
->disposition
& AV_DISPOSITION_VISUAL_IMPAIRED
)
2760 av_log(NULL
, AV_LOG_INFO
, " (visual impaired)");
2761 if (st
->disposition
& AV_DISPOSITION_CLEAN_EFFECTS
)
2762 av_log(NULL
, AV_LOG_INFO
, " (clean effects)");
2763 av_log(NULL
, AV_LOG_INFO
, "\n");
2764 dump_metadata(NULL
, st
->metadata
, " ");
2767 void av_dump_format(AVFormatContext
*ic
,
2773 uint8_t *printed
= ic
->nb_streams ?
av_mallocz(ic
->nb_streams
) : NULL
;
2774 if (ic
->nb_streams
&& !printed
)
2777 av_log(NULL
, AV_LOG_INFO
, "%s #%d, %s, %s '%s':\n",
2778 is_output ?
"Output" : "Input",
2780 is_output ? ic
->oformat
->name
: ic
->iformat
->name
,
2781 is_output ?
"to" : "from", url
);
2782 dump_metadata(NULL
, ic
->metadata
, " ");
2784 av_log(NULL
, AV_LOG_INFO
, " Duration: ");
2785 if (ic
->duration
!= AV_NOPTS_VALUE
) {
2786 int hours
, mins
, secs
, us
;
2787 secs
= ic
->duration
/ AV_TIME_BASE
;
2788 us
= ic
->duration
% AV_TIME_BASE
;
2793 av_log(NULL
, AV_LOG_INFO
, "%02d:%02d:%02d.%02d", hours
, mins
, secs
,
2794 (100 * us
) / AV_TIME_BASE
);
2796 av_log(NULL
, AV_LOG_INFO
, "N/A");
2798 if (ic
->start_time
!= AV_NOPTS_VALUE
) {
2800 av_log(NULL
, AV_LOG_INFO
, ", start: ");
2801 secs
= ic
->start_time
/ AV_TIME_BASE
;
2802 us
= abs(ic
->start_time
% AV_TIME_BASE
);
2803 av_log(NULL
, AV_LOG_INFO
, "%d.%06d",
2804 secs
, (int)av_rescale(us
, 1000000, AV_TIME_BASE
));
2806 av_log(NULL
, AV_LOG_INFO
, ", bitrate: ");
2808 av_log(NULL
, AV_LOG_INFO
,"%d kb/s", ic
->bit_rate
/ 1000);
2810 av_log(NULL
, AV_LOG_INFO
, "N/A");
2812 av_log(NULL
, AV_LOG_INFO
, "\n");
2814 for (i
= 0; i
< ic
->nb_chapters
; i
++) {
2815 AVChapter
*ch
= ic
->chapters
[i
];
2816 av_log(NULL
, AV_LOG_INFO
, " Chapter #%d.%d: ", index
, i
);
2817 av_log(NULL
, AV_LOG_INFO
, "start %f, ", ch
->start
* av_q2d(ch
->time_base
));
2818 av_log(NULL
, AV_LOG_INFO
, "end %f\n", ch
->end
* av_q2d(ch
->time_base
));
2820 dump_metadata(NULL
, ch
->metadata
, " ");
2822 if(ic
->nb_programs
) {
2823 int j
, k
, total
= 0;
2824 for(j
=0; j
<ic
->nb_programs
; j
++) {
2825 AVDictionaryEntry
*name
= av_dict_get(ic
->programs
[j
]->metadata
,
2827 av_log(NULL
, AV_LOG_INFO
, " Program %d %s\n", ic
->programs
[j
]->id
,
2828 name ? name
->value
: "");
2829 dump_metadata(NULL
, ic
->programs
[j
]->metadata
, " ");
2830 for(k
=0; k
<ic
->programs
[j
]->nb_stream_indexes
; k
++) {
2831 dump_stream_format(ic
, ic
->programs
[j
]->stream_index
[k
], index
, is_output
);
2832 printed
[ic
->programs
[j
]->stream_index
[k
]] = 1;
2834 total
+= ic
->programs
[j
]->nb_stream_indexes
;
2836 if (total
< ic
->nb_streams
)
2837 av_log(NULL
, AV_LOG_INFO
, " No Program\n");
2839 for(i
=0;i
<ic
->nb_streams
;i
++)
2841 dump_stream_format(ic
, i
, index
, is_output
);
2846 uint64_t ff_ntp_time(void)
2848 return (av_gettime() / 1000) * 1000 + NTP_OFFSET_US
;
2851 int av_get_frame_filename(char *buf
, int buf_size
,
2852 const char *path
, int number
)
2855 char *q
, buf1
[20], c
;
2856 int nd
, len
, percentd_found
;
2868 while (av_isdigit(*p
)) {
2869 nd
= nd
* 10 + *p
++ - '0';
2872 } while (av_isdigit(c
));
2881 snprintf(buf1
, sizeof(buf1
), "%0*d", nd
, number
);
2883 if ((q
- buf
+ len
) > buf_size
- 1)
2885 memcpy(q
, buf1
, len
);
2893 if ((q
- buf
) < buf_size
- 1)
2897 if (!percentd_found
)
2906 static void hex_dump_internal(void *avcl
, FILE *f
, int level
,
2907 const uint8_t *buf
, int size
)
2910 #define PRINT(...) do { if (!f) av_log(avcl, level, __VA_ARGS__); else fprintf(f, __VA_ARGS__); } while(0)
2912 for(i
=0;i
<size
;i
+=16) {
2919 PRINT(" %02x", buf
[i
+j
]);
2924 for(j
=0;j
<len
;j
++) {
2926 if (c
< ' ' || c
> '~')
2935 void av_hex_dump(FILE *f
, const uint8_t *buf
, int size
)
2937 hex_dump_internal(NULL
, f
, 0, buf
, size
);
2940 void av_hex_dump_log(void *avcl
, int level
, const uint8_t *buf
, int size
)
2942 hex_dump_internal(avcl
, NULL
, level
, buf
, size
);
2945 static void pkt_dump_internal(void *avcl
, FILE *f
, int level
, AVPacket
*pkt
, int dump_payload
, AVRational time_base
)
2947 #define PRINT(...) do { if (!f) av_log(avcl, level, __VA_ARGS__); else fprintf(f, __VA_ARGS__); } while(0)
2948 PRINT("stream #%d:\n", pkt
->stream_index
);
2949 PRINT(" keyframe=%d\n", ((pkt
->flags
& AV_PKT_FLAG_KEY
) != 0));
2950 PRINT(" duration=%0.3f\n", pkt
->duration
* av_q2d(time_base
));
2951 /* DTS is _always_ valid after av_read_frame() */
2953 if (pkt
->dts
== AV_NOPTS_VALUE
)
2956 PRINT("%0.3f", pkt
->dts
* av_q2d(time_base
));
2957 /* PTS may not be known if B-frames are present. */
2959 if (pkt
->pts
== AV_NOPTS_VALUE
)
2962 PRINT("%0.3f", pkt
->pts
* av_q2d(time_base
));
2964 PRINT(" size=%d\n", pkt
->size
);
2967 av_hex_dump(f
, pkt
->data
, pkt
->size
);
2970 void av_pkt_dump2(FILE *f
, AVPacket
*pkt
, int dump_payload
, AVStream
*st
)
2972 pkt_dump_internal(NULL
, f
, 0, pkt
, dump_payload
, st
->time_base
);
2975 void av_pkt_dump_log2(void *avcl
, int level
, AVPacket
*pkt
, int dump_payload
,
2978 pkt_dump_internal(avcl
, NULL
, level
, pkt
, dump_payload
, st
->time_base
);
2981 void av_url_split(char *proto
, int proto_size
,
2982 char *authorization
, int authorization_size
,
2983 char *hostname
, int hostname_size
,
2985 char *path
, int path_size
,
2988 const char *p
, *ls
, *at
, *col
, *brk
;
2990 if (port_ptr
) *port_ptr
= -1;
2991 if (proto_size
> 0) proto
[0] = 0;
2992 if (authorization_size
> 0) authorization
[0] = 0;
2993 if (hostname_size
> 0) hostname
[0] = 0;
2994 if (path_size
> 0) path
[0] = 0;
2996 /* parse protocol */
2997 if ((p
= strchr(url
, ':'))) {
2998 av_strlcpy(proto
, url
, FFMIN(proto_size
, p
+ 1 - url
));
3003 /* no protocol means plain filename */
3004 av_strlcpy(path
, url
, path_size
);
3008 /* separate path from hostname */
3009 ls
= strchr(p
, '/');
3011 ls
= strchr(p
, '?');
3013 av_strlcpy(path
, ls
, path_size
);
3015 ls
= &p
[strlen(p
)]; // XXX
3017 /* the rest is hostname, use that to parse auth/port */
3019 /* authorization (user[:pass]@hostname) */
3020 if ((at
= strchr(p
, '@')) && at
< ls
) {
3021 av_strlcpy(authorization
, p
,
3022 FFMIN(authorization_size
, at
+ 1 - p
));
3023 p
= at
+ 1; /* skip '@' */
3026 if (*p
== '[' && (brk
= strchr(p
, ']')) && brk
< ls
) {
3028 av_strlcpy(hostname
, p
+ 1,
3029 FFMIN(hostname_size
, brk
- p
));
3030 if (brk
[1] == ':' && port_ptr
)
3031 *port_ptr
= atoi(brk
+ 2);
3032 } else if ((col
= strchr(p
, ':')) && col
< ls
) {
3033 av_strlcpy(hostname
, p
,
3034 FFMIN(col
+ 1 - p
, hostname_size
));
3035 if (port_ptr
) *port_ptr
= atoi(col
+ 1);
3037 av_strlcpy(hostname
, p
,
3038 FFMIN(ls
+ 1 - p
, hostname_size
));
3042 char *ff_data_to_hex(char *buff
, const uint8_t *src
, int s
, int lowercase
)
3045 static const char hex_table_uc
[16] = { '0', '1', '2', '3',
3048 'C', 'D', 'E', 'F' };
3049 static const char hex_table_lc
[16] = { '0', '1', '2', '3',
3052 'c', 'd', 'e', 'f' };
3053 const char *hex_table
= lowercase ? hex_table_lc
: hex_table_uc
;
3055 for(i
= 0; i
< s
; i
++) {
3056 buff
[i
* 2] = hex_table
[src
[i
] >> 4];
3057 buff
[i
* 2 + 1] = hex_table
[src
[i
] & 0xF];
3063 int ff_hex_to_data(uint8_t *data
, const char *p
)
3070 p
+= strspn(p
, SPACE_CHARS
);