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
: "" };
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
);
260 avio_skip(pb
, offset
);
261 max_probe_size
-= offset
;
263 for(probe_size
= PROBE_BUF_MIN
; probe_size
<=max_probe_size
&& !*fmt
;
264 probe_size
= FFMIN(probe_size
<<1, FFMAX(max_probe_size
, probe_size
+1))) {
265 int score
= probe_size
< max_probe_size ? AVPROBE_SCORE_MAX
/4 : 0;
266 int buf_offset
= (probe_size
== PROBE_BUF_MIN
) ?
0 : probe_size
>>1;
268 /* read probe data */
269 if ((ret
= av_reallocp(&buf
, probe_size
+ AVPROBE_PADDING_SIZE
)) < 0)
271 if ((ret
= avio_read(pb
, buf
+ buf_offset
, probe_size
- buf_offset
)) < 0) {
272 /* fail if error was not end of file, otherwise, lower score */
273 if (ret
!= AVERROR_EOF
) {
278 ret
= 0; /* error was end of file, nothing read */
283 memset(pd
.buf
+ pd
.buf_size
, 0, AVPROBE_PADDING_SIZE
);
285 /* guess file format */
286 *fmt
= av_probe_input_format2(&pd
, 1, &score
);
288 if(score
<= AVPROBE_SCORE_MAX
/4){ //this can only be true in the last iteration
289 av_log(logctx
, AV_LOG_WARNING
, "Format detected only with low score of %d, misdetection possible!\n", score
);
291 av_log(logctx
, AV_LOG_DEBUG
, "Probed with size=%d and score=%d\n", probe_size
, score
);
297 return AVERROR_INVALIDDATA
;
300 /* rewind. reuse probe buffer to avoid seeking */
301 if ((ret
= ffio_rewind_with_probe_data(pb
, buf
, pd
.buf_size
)) < 0)
307 /* open input file and probe the format if necessary */
308 static int init_input(AVFormatContext
*s
, const char *filename
, AVDictionary
**options
)
311 AVProbeData pd
= {filename
, NULL
, 0};
314 s
->flags
|= AVFMT_FLAG_CUSTOM_IO
;
316 return av_probe_input_buffer(s
->pb
, &s
->iformat
, filename
, s
, 0, s
->probesize
);
317 else if (s
->iformat
->flags
& AVFMT_NOFILE
)
318 return AVERROR(EINVAL
);
322 if ( (s
->iformat
&& s
->iformat
->flags
& AVFMT_NOFILE
) ||
323 (!s
->iformat
&& (s
->iformat
= av_probe_input_format(&pd
, 0))))
326 if ((ret
= avio_open2(&s
->pb
, filename
, AVIO_FLAG_READ
,
327 &s
->interrupt_callback
, options
)) < 0)
331 return av_probe_input_buffer(s
->pb
, &s
->iformat
, filename
, s
, 0, s
->probesize
);
334 static AVPacket
*add_to_pktbuf(AVPacketList
**packet_buffer
, AVPacket
*pkt
,
335 AVPacketList
**plast_pktl
){
336 AVPacketList
*pktl
= av_mallocz(sizeof(AVPacketList
));
341 (*plast_pktl
)->next
= pktl
;
343 *packet_buffer
= pktl
;
345 /* add the packet in the buffered packet list */
351 static int queue_attached_pictures(AVFormatContext
*s
)
354 for (i
= 0; i
< s
->nb_streams
; i
++)
355 if (s
->streams
[i
]->disposition
& AV_DISPOSITION_ATTACHED_PIC
&&
356 s
->streams
[i
]->discard
< AVDISCARD_ALL
) {
357 AVPacket copy
= s
->streams
[i
]->attached_pic
;
358 copy
.buf
= av_buffer_ref(copy
.buf
);
360 return AVERROR(ENOMEM
);
362 add_to_pktbuf(&s
->raw_packet_buffer
, ©
, &s
->raw_packet_buffer_end
);
367 int avformat_open_input(AVFormatContext
**ps
, const char *filename
, AVInputFormat
*fmt
, AVDictionary
**options
)
369 AVFormatContext
*s
= *ps
;
371 AVDictionary
*tmp
= NULL
;
372 ID3v2ExtraMeta
*id3v2_extra_meta
= NULL
;
374 if (!s
&& !(s
= avformat_alloc_context()))
375 return AVERROR(ENOMEM
);
380 av_dict_copy(&tmp
, *options
, 0);
382 if ((ret
= av_opt_set_dict(s
, &tmp
)) < 0)
385 if ((ret
= init_input(s
, filename
, &tmp
)) < 0)
388 /* check filename in case an image number is expected */
389 if (s
->iformat
->flags
& AVFMT_NEEDNUMBER
) {
390 if (!av_filename_number_test(filename
)) {
391 ret
= AVERROR(EINVAL
);
396 s
->duration
= s
->start_time
= AV_NOPTS_VALUE
;
397 av_strlcpy(s
->filename
, filename ? filename
: "", sizeof(s
->filename
));
399 /* allocate private data */
400 if (s
->iformat
->priv_data_size
> 0) {
401 if (!(s
->priv_data
= av_mallocz(s
->iformat
->priv_data_size
))) {
402 ret
= AVERROR(ENOMEM
);
405 if (s
->iformat
->priv_class
) {
406 *(const AVClass
**)s
->priv_data
= s
->iformat
->priv_class
;
407 av_opt_set_defaults(s
->priv_data
);
408 if ((ret
= av_opt_set_dict(s
->priv_data
, &tmp
)) < 0)
413 /* e.g. AVFMT_NOFILE formats will not have a AVIOContext */
415 ff_id3v2_read(s
, ID3v2_DEFAULT_MAGIC
, &id3v2_extra_meta
);
417 if (s
->iformat
->read_header
)
418 if ((ret
= s
->iformat
->read_header(s
)) < 0)
421 if (id3v2_extra_meta
&&
422 (ret
= ff_id3v2_parse_apic(s
, &id3v2_extra_meta
)) < 0)
424 ff_id3v2_free_extra_meta(&id3v2_extra_meta
);
426 if ((ret
= queue_attached_pictures(s
)) < 0)
429 if (s
->pb
&& !s
->data_offset
)
430 s
->data_offset
= avio_tell(s
->pb
);
432 s
->raw_packet_buffer_remaining_size
= RAW_PACKET_BUFFER_SIZE
;
435 av_dict_free(options
);
442 ff_id3v2_free_extra_meta(&id3v2_extra_meta
);
444 if (s
->pb
&& !(s
->flags
& AVFMT_FLAG_CUSTOM_IO
))
446 avformat_free_context(s
);
451 /*******************************************************/
453 static int probe_codec(AVFormatContext
*s
, AVStream
*st
, const AVPacket
*pkt
)
455 if(st
->codec
->codec_id
== AV_CODEC_ID_PROBE
){
456 AVProbeData
*pd
= &st
->probe_data
;
457 av_log(s
, AV_LOG_DEBUG
, "probing stream %d\n", st
->index
);
462 if ((err
= av_reallocp(&pd
->buf
, pd
->buf_size
+ pkt
->size
+
463 AVPROBE_PADDING_SIZE
)) < 0)
465 memcpy(pd
->buf
+pd
->buf_size
, pkt
->data
, pkt
->size
);
466 pd
->buf_size
+= pkt
->size
;
467 memset(pd
->buf
+pd
->buf_size
, 0, AVPROBE_PADDING_SIZE
);
469 st
->probe_packets
= 0;
471 av_log(s
, AV_LOG_ERROR
, "nothing to probe for stream %d\n",
477 if (!st
->probe_packets
||
478 av_log2(pd
->buf_size
) != av_log2(pd
->buf_size
- pkt
->size
)) {
479 set_codec_from_probe_data(s
, st
, pd
, st
->probe_packets
> 0 ? AVPROBE_SCORE_MAX
/4 : 0);
480 if(st
->codec
->codec_id
!= AV_CODEC_ID_PROBE
){
483 av_log(s
, AV_LOG_DEBUG
, "probed stream %d\n", st
->index
);
490 int ff_read_packet(AVFormatContext
*s
, AVPacket
*pkt
)
496 AVPacketList
*pktl
= s
->raw_packet_buffer
;
500 st
= s
->streams
[pkt
->stream_index
];
501 if (st
->codec
->codec_id
!= AV_CODEC_ID_PROBE
|| !st
->probe_packets
||
502 s
->raw_packet_buffer_remaining_size
< pkt
->size
) {
504 if (st
->probe_packets
) {
505 if ((err
= probe_codec(s
, st
, NULL
)) < 0)
508 pd
= &st
->probe_data
;
511 s
->raw_packet_buffer
= pktl
->next
;
512 s
->raw_packet_buffer_remaining_size
+= pkt
->size
;
521 ret
= s
->iformat
->read_packet(s
, pkt
);
523 if (!pktl
|| ret
== AVERROR(EAGAIN
))
525 for (i
= 0; i
< s
->nb_streams
; i
++) {
527 if (st
->probe_packets
) {
528 if ((err
= probe_codec(s
, st
, NULL
)) < 0)
535 if ((s
->flags
& AVFMT_FLAG_DISCARD_CORRUPT
) &&
536 (pkt
->flags
& AV_PKT_FLAG_CORRUPT
)) {
537 av_log(s
, AV_LOG_WARNING
,
538 "Dropped corrupted packet (stream = %d)\n",
544 st
= s
->streams
[pkt
->stream_index
];
546 switch(st
->codec
->codec_type
){
547 case AVMEDIA_TYPE_VIDEO
:
548 if(s
->video_codec_id
) st
->codec
->codec_id
= s
->video_codec_id
;
550 case AVMEDIA_TYPE_AUDIO
:
551 if(s
->audio_codec_id
) st
->codec
->codec_id
= s
->audio_codec_id
;
553 case AVMEDIA_TYPE_SUBTITLE
:
554 if(s
->subtitle_codec_id
)st
->codec
->codec_id
= s
->subtitle_codec_id
;
558 if(!pktl
&& (st
->codec
->codec_id
!= AV_CODEC_ID_PROBE
||
562 add_to_pktbuf(&s
->raw_packet_buffer
, pkt
, &s
->raw_packet_buffer_end
);
563 s
->raw_packet_buffer_remaining_size
-= pkt
->size
;
565 if ((err
= probe_codec(s
, st
, pkt
)) < 0)
570 /**********************************************************/
573 * Get the number of samples of an audio frame. Return -1 on error.
575 int ff_get_audio_frame_size(AVCodecContext
*enc
, int size
, int mux
)
579 /* give frame_size priority if demuxing */
580 if (!mux
&& enc
->frame_size
> 1)
581 return enc
->frame_size
;
583 if ((frame_size
= av_get_audio_frame_duration(enc
, size
)) > 0)
586 /* Fall back on using frame_size if muxing. */
587 if (enc
->frame_size
> 1)
588 return enc
->frame_size
;
595 * Return the frame duration in seconds. Return 0 if not available.
597 void ff_compute_frame_duration(int *pnum
, int *pden
, AVStream
*st
,
598 AVCodecParserContext
*pc
, AVPacket
*pkt
)
604 switch(st
->codec
->codec_type
) {
605 case AVMEDIA_TYPE_VIDEO
:
606 if (st
->avg_frame_rate
.num
) {
607 *pnum
= st
->avg_frame_rate
.den
;
608 *pden
= st
->avg_frame_rate
.num
;
609 } else if(st
->time_base
.num
*1000LL > st
->time_base
.den
) {
610 *pnum
= st
->time_base
.num
;
611 *pden
= st
->time_base
.den
;
612 }else if(st
->codec
->time_base
.num
*1000LL > st
->codec
->time_base
.den
){
613 *pnum
= st
->codec
->time_base
.num
;
614 *pden
= st
->codec
->time_base
.den
;
615 if (pc
&& pc
->repeat_pict
) {
616 if (*pnum
> INT_MAX
/ (1 + pc
->repeat_pict
))
617 *pden
/= 1 + pc
->repeat_pict
;
619 *pnum
*= 1 + pc
->repeat_pict
;
621 //If this codec can be interlaced or progressive then we need a parser to compute duration of a packet
622 //Thus if we have no parser in such case leave duration undefined.
623 if(st
->codec
->ticks_per_frame
>1 && !pc
){
628 case AVMEDIA_TYPE_AUDIO
:
629 frame_size
= ff_get_audio_frame_size(st
->codec
, pkt
->size
, 0);
630 if (frame_size
<= 0 || st
->codec
->sample_rate
<= 0)
633 *pden
= st
->codec
->sample_rate
;
640 static int is_intra_only(enum AVCodecID id
)
642 const AVCodecDescriptor
*d
= avcodec_descriptor_get(id
);
645 if (d
->type
== AVMEDIA_TYPE_VIDEO
&& !(d
->props
& AV_CODEC_PROP_INTRA_ONLY
))
650 static void update_initial_timestamps(AVFormatContext
*s
, int stream_index
,
651 int64_t dts
, int64_t pts
)
653 AVStream
*st
= s
->streams
[stream_index
];
654 AVPacketList
*pktl
= s
->packet_buffer
;
656 if(st
->first_dts
!= AV_NOPTS_VALUE
|| dts
== AV_NOPTS_VALUE
|| st
->cur_dts
== AV_NOPTS_VALUE
)
659 st
->first_dts
= dts
- st
->cur_dts
;
662 for(; pktl
; pktl
= pktl
->next
){
663 if(pktl
->pkt
.stream_index
!= stream_index
)
665 //FIXME think more about this check
666 if(pktl
->pkt
.pts
!= AV_NOPTS_VALUE
&& pktl
->pkt
.pts
== pktl
->pkt
.dts
)
667 pktl
->pkt
.pts
+= st
->first_dts
;
669 if(pktl
->pkt
.dts
!= AV_NOPTS_VALUE
)
670 pktl
->pkt
.dts
+= st
->first_dts
;
672 if(st
->start_time
== AV_NOPTS_VALUE
&& pktl
->pkt
.pts
!= AV_NOPTS_VALUE
)
673 st
->start_time
= pktl
->pkt
.pts
;
675 if (st
->start_time
== AV_NOPTS_VALUE
)
676 st
->start_time
= pts
;
679 static void update_initial_durations(AVFormatContext
*s
, AVStream
*st
,
680 int stream_index
, int duration
)
682 AVPacketList
*pktl
= s
->packet_buffer
;
685 if(st
->first_dts
!= AV_NOPTS_VALUE
){
686 cur_dts
= st
->first_dts
;
687 for(; pktl
; pktl
= pktl
->next
){
688 if(pktl
->pkt
.stream_index
== stream_index
){
689 if(pktl
->pkt
.pts
!= pktl
->pkt
.dts
|| pktl
->pkt
.dts
!= AV_NOPTS_VALUE
|| pktl
->pkt
.duration
)
694 pktl
= s
->packet_buffer
;
695 st
->first_dts
= cur_dts
;
696 }else if(st
->cur_dts
)
699 for(; pktl
; pktl
= pktl
->next
){
700 if(pktl
->pkt
.stream_index
!= stream_index
)
702 if(pktl
->pkt
.pts
== pktl
->pkt
.dts
&& pktl
->pkt
.dts
== AV_NOPTS_VALUE
703 && !pktl
->pkt
.duration
){
704 pktl
->pkt
.dts
= cur_dts
;
705 if(!st
->codec
->has_b_frames
)
706 pktl
->pkt
.pts
= cur_dts
;
708 if (st
->codec
->codec_type
!= AVMEDIA_TYPE_AUDIO
)
709 pktl
->pkt
.duration
= duration
;
713 if(st
->first_dts
== AV_NOPTS_VALUE
)
714 st
->cur_dts
= cur_dts
;
717 static void compute_pkt_fields(AVFormatContext
*s
, AVStream
*st
,
718 AVCodecParserContext
*pc
, AVPacket
*pkt
)
720 int num
, den
, presentation_delayed
, delay
, i
;
723 if (s
->flags
& AVFMT_FLAG_NOFILLIN
)
726 if((s
->flags
& AVFMT_FLAG_IGNDTS
) && pkt
->pts
!= AV_NOPTS_VALUE
)
727 pkt
->dts
= AV_NOPTS_VALUE
;
729 /* do we have a video B-frame ? */
730 delay
= st
->codec
->has_b_frames
;
731 presentation_delayed
= 0;
733 /* XXX: need has_b_frame, but cannot get it if the codec is
736 pc
&& pc
->pict_type
!= AV_PICTURE_TYPE_B
)
737 presentation_delayed
= 1;
739 if (pkt
->pts
!= AV_NOPTS_VALUE
&& pkt
->dts
!= AV_NOPTS_VALUE
&&
740 st
->pts_wrap_bits
< 63 &&
741 pkt
->dts
- (1LL << (st
->pts_wrap_bits
- 1)) > pkt
->pts
) {
742 pkt
->dts
-= 1LL<<st
->pts_wrap_bits
;
745 // some mpeg2 in mpeg-ps lack dts (issue171 / input_file.mpg)
746 // we take the conservative approach and discard both
747 // Note, if this is misbehaving for a H.264 file then possibly presentation_delayed is not set correctly.
748 if(delay
==1 && pkt
->dts
== pkt
->pts
&& pkt
->dts
!= AV_NOPTS_VALUE
&& presentation_delayed
){
749 av_log(s
, AV_LOG_DEBUG
, "invalid dts/pts combination\n");
750 pkt
->dts
= pkt
->pts
= AV_NOPTS_VALUE
;
753 if (pkt
->duration
== 0 && st
->codec
->codec_type
!= AVMEDIA_TYPE_AUDIO
) {
754 ff_compute_frame_duration(&num
, &den
, st
, pc
, pkt
);
756 pkt
->duration
= av_rescale_rnd(1, num
* (int64_t)st
->time_base
.den
, den
* (int64_t)st
->time_base
.num
, AV_ROUND_DOWN
);
758 if(pkt
->duration
!= 0 && s
->packet_buffer
)
759 update_initial_durations(s
, st
, pkt
->stream_index
, pkt
->duration
);
763 /* correct timestamps with byte offset if demuxers only have timestamps
764 on packet boundaries */
765 if(pc
&& st
->need_parsing
== AVSTREAM_PARSE_TIMESTAMPS
&& pkt
->size
){
766 /* this will estimate bitrate based on this frame's duration and size */
767 offset
= av_rescale(pc
->offset
, pkt
->duration
, pkt
->size
);
768 if(pkt
->pts
!= AV_NOPTS_VALUE
)
770 if(pkt
->dts
!= AV_NOPTS_VALUE
)
774 /* This may be redundant, but it should not hurt. */
775 if(pkt
->dts
!= AV_NOPTS_VALUE
&& pkt
->pts
!= AV_NOPTS_VALUE
&& pkt
->pts
> pkt
->dts
)
776 presentation_delayed
= 1;
779 "IN delayed:%d pts:%"PRId64
", dts:%"PRId64
" cur_dts:%"PRId64
" st:%d pc:%p\n",
780 presentation_delayed
, pkt
->pts
, pkt
->dts
, st
->cur_dts
,
781 pkt
->stream_index
, pc
);
782 /* interpolate PTS and DTS if they are not present */
783 //We skip H264 currently because delay and has_b_frames are not reliably set
784 if((delay
==0 || (delay
==1 && pc
)) && st
->codec
->codec_id
!= AV_CODEC_ID_H264
){
785 if (presentation_delayed
) {
786 /* DTS = decompression timestamp */
787 /* PTS = presentation timestamp */
788 if (pkt
->dts
== AV_NOPTS_VALUE
)
789 pkt
->dts
= st
->last_IP_pts
;
790 update_initial_timestamps(s
, pkt
->stream_index
, pkt
->dts
, pkt
->pts
);
791 if (pkt
->dts
== AV_NOPTS_VALUE
)
792 pkt
->dts
= st
->cur_dts
;
794 /* this is tricky: the dts must be incremented by the duration
795 of the frame we are displaying, i.e. the last I- or P-frame */
796 if (st
->last_IP_duration
== 0)
797 st
->last_IP_duration
= pkt
->duration
;
798 if(pkt
->dts
!= AV_NOPTS_VALUE
)
799 st
->cur_dts
= pkt
->dts
+ st
->last_IP_duration
;
800 st
->last_IP_duration
= pkt
->duration
;
801 st
->last_IP_pts
= pkt
->pts
;
802 /* cannot compute PTS if not present (we can compute it only
803 by knowing the future */
804 } else if (pkt
->pts
!= AV_NOPTS_VALUE
||
805 pkt
->dts
!= AV_NOPTS_VALUE
||
807 st
->codec
->codec_type
== AVMEDIA_TYPE_AUDIO
) {
808 int duration
= pkt
->duration
;
809 if (!duration
&& st
->codec
->codec_type
== AVMEDIA_TYPE_AUDIO
) {
810 ff_compute_frame_duration(&num
, &den
, st
, pc
, pkt
);
812 duration
= av_rescale_rnd(1, num
* (int64_t)st
->time_base
.den
,
813 den
* (int64_t)st
->time_base
.num
,
815 if (duration
!= 0 && s
->packet_buffer
) {
816 update_initial_durations(s
, st
, pkt
->stream_index
,
822 if (pkt
->pts
!= AV_NOPTS_VALUE
|| pkt
->dts
!= AV_NOPTS_VALUE
||
824 /* presentation is not delayed : PTS and DTS are the same */
825 if (pkt
->pts
== AV_NOPTS_VALUE
)
827 update_initial_timestamps(s
, pkt
->stream_index
, pkt
->pts
,
829 if (pkt
->pts
== AV_NOPTS_VALUE
)
830 pkt
->pts
= st
->cur_dts
;
832 if (pkt
->pts
!= AV_NOPTS_VALUE
)
833 st
->cur_dts
= pkt
->pts
+ duration
;
838 if(pkt
->pts
!= AV_NOPTS_VALUE
&& delay
<= MAX_REORDER_DELAY
){
839 st
->pts_buffer
[0]= pkt
->pts
;
840 for(i
=0; i
<delay
&& st
->pts_buffer
[i
] > st
->pts_buffer
[i
+1]; i
++)
841 FFSWAP(int64_t, st
->pts_buffer
[i
], st
->pts_buffer
[i
+1]);
842 if(pkt
->dts
== AV_NOPTS_VALUE
)
843 pkt
->dts
= st
->pts_buffer
[0];
844 if(st
->codec
->codec_id
== AV_CODEC_ID_H264
){ // we skipped it above so we try here
845 update_initial_timestamps(s
, pkt
->stream_index
, pkt
->dts
, pkt
->pts
); // this should happen on the first packet
847 if(pkt
->dts
> st
->cur_dts
)
848 st
->cur_dts
= pkt
->dts
;
852 "OUTdelayed:%d/%d pts:%"PRId64
", dts:%"PRId64
" cur_dts:%"PRId64
"\n",
853 presentation_delayed
, delay
, pkt
->pts
, pkt
->dts
, st
->cur_dts
);
856 if (is_intra_only(st
->codec
->codec_id
))
857 pkt
->flags
|= AV_PKT_FLAG_KEY
;
859 pkt
->convergence_duration
= pc
->convergence_duration
;
862 static void free_packet_buffer(AVPacketList
**pkt_buf
, AVPacketList
**pkt_buf_end
)
865 AVPacketList
*pktl
= *pkt_buf
;
866 *pkt_buf
= pktl
->next
;
867 av_free_packet(&pktl
->pkt
);
874 * Parse a packet, add all split parts to parse_queue
876 * @param pkt packet to parse, NULL when flushing the parser at end of stream
878 static int parse_packet(AVFormatContext
*s
, AVPacket
*pkt
, int stream_index
)
880 AVPacket out_pkt
= { 0 }, flush_pkt
= { 0 };
881 AVStream
*st
= s
->streams
[stream_index
];
882 uint8_t *data
= pkt ? pkt
->data
: NULL
;
883 int size
= pkt ? pkt
->size
: 0;
884 int ret
= 0, got_output
= 0;
887 av_init_packet(&flush_pkt
);
892 while (size
> 0 || (pkt
== &flush_pkt
&& got_output
)) {
895 av_init_packet(&out_pkt
);
896 len
= av_parser_parse2(st
->parser
, st
->codec
,
897 &out_pkt
.data
, &out_pkt
.size
, data
, size
,
898 pkt
->pts
, pkt
->dts
, pkt
->pos
);
900 pkt
->pts
= pkt
->dts
= AV_NOPTS_VALUE
;
901 /* increment read pointer */
905 got_output
= !!out_pkt
.size
;
910 if (pkt
->side_data
) {
911 out_pkt
.side_data
= pkt
->side_data
;
912 out_pkt
.side_data_elems
= pkt
->side_data_elems
;
913 pkt
->side_data
= NULL
;
914 pkt
->side_data_elems
= 0;
917 /* set the duration */
918 out_pkt
.duration
= 0;
919 if (st
->codec
->codec_type
== AVMEDIA_TYPE_AUDIO
) {
920 if (st
->codec
->sample_rate
> 0) {
921 out_pkt
.duration
= av_rescale_q_rnd(st
->parser
->duration
,
922 (AVRational
){ 1, st
->codec
->sample_rate
},
926 } else if (st
->codec
->time_base
.num
!= 0 &&
927 st
->codec
->time_base
.den
!= 0) {
928 out_pkt
.duration
= av_rescale_q_rnd(st
->parser
->duration
,
929 st
->codec
->time_base
,
934 out_pkt
.stream_index
= st
->index
;
935 out_pkt
.pts
= st
->parser
->pts
;
936 out_pkt
.dts
= st
->parser
->dts
;
937 out_pkt
.pos
= st
->parser
->pos
;
939 if (st
->parser
->key_frame
== 1 ||
940 (st
->parser
->key_frame
== -1 &&
941 st
->parser
->pict_type
== AV_PICTURE_TYPE_I
))
942 out_pkt
.flags
|= AV_PKT_FLAG_KEY
;
944 compute_pkt_fields(s
, st
, st
->parser
, &out_pkt
);
946 if ((s
->iformat
->flags
& AVFMT_GENERIC_INDEX
) &&
947 out_pkt
.flags
& AV_PKT_FLAG_KEY
) {
948 ff_reduce_index(s
, st
->index
);
949 av_add_index_entry(st
, st
->parser
->frame_offset
, out_pkt
.dts
,
950 0, 0, AVINDEX_KEYFRAME
);
953 if (out_pkt
.data
== pkt
->data
&& out_pkt
.size
== pkt
->size
) {
954 out_pkt
.buf
= pkt
->buf
;
956 #if FF_API_DESTRUCT_PACKET
957 FF_DISABLE_DEPRECATION_WARNINGS
958 out_pkt
.destruct
= pkt
->destruct
;
959 pkt
->destruct
= NULL
;
960 FF_ENABLE_DEPRECATION_WARNINGS
963 if ((ret
= av_dup_packet(&out_pkt
)) < 0)
966 if (!add_to_pktbuf(&s
->parse_queue
, &out_pkt
, &s
->parse_queue_end
)) {
967 av_free_packet(&out_pkt
);
968 ret
= AVERROR(ENOMEM
);
974 /* end of the stream => close and free the parser */
975 if (pkt
== &flush_pkt
) {
976 av_parser_close(st
->parser
);
985 static int read_from_packet_buffer(AVPacketList
**pkt_buffer
,
986 AVPacketList
**pkt_buffer_end
,
990 av_assert0(*pkt_buffer
);
993 *pkt_buffer
= pktl
->next
;
995 *pkt_buffer_end
= NULL
;
1000 static int read_frame_internal(AVFormatContext
*s
, AVPacket
*pkt
)
1002 int ret
= 0, i
, got_packet
= 0;
1004 av_init_packet(pkt
);
1006 while (!got_packet
&& !s
->parse_queue
) {
1010 /* read next packet */
1011 ret
= ff_read_packet(s
, &cur_pkt
);
1013 if (ret
== AVERROR(EAGAIN
))
1015 /* flush the parsers */
1016 for(i
= 0; i
< s
->nb_streams
; i
++) {
1018 if (st
->parser
&& st
->need_parsing
)
1019 parse_packet(s
, NULL
, st
->index
);
1021 /* all remaining packets are now in parse_queue =>
1022 * really terminate parsing */
1026 st
= s
->streams
[cur_pkt
.stream_index
];
1028 if (cur_pkt
.pts
!= AV_NOPTS_VALUE
&&
1029 cur_pkt
.dts
!= AV_NOPTS_VALUE
&&
1030 cur_pkt
.pts
< cur_pkt
.dts
) {
1031 av_log(s
, AV_LOG_WARNING
, "Invalid timestamps stream=%d, pts=%"PRId64
", dts=%"PRId64
", size=%d\n",
1032 cur_pkt
.stream_index
,
1037 if (s
->debug
& FF_FDEBUG_TS
)
1038 av_log(s
, AV_LOG_DEBUG
, "ff_read_packet stream=%d, pts=%"PRId64
", dts=%"PRId64
", size=%d, duration=%d, flags=%d\n",
1039 cur_pkt
.stream_index
,
1046 if (st
->need_parsing
&& !st
->parser
&& !(s
->flags
& AVFMT_FLAG_NOPARSE
)) {
1047 st
->parser
= av_parser_init(st
->codec
->codec_id
);
1049 /* no parser available: just output the raw packets */
1050 st
->need_parsing
= AVSTREAM_PARSE_NONE
;
1051 } else if(st
->need_parsing
== AVSTREAM_PARSE_HEADERS
) {
1052 st
->parser
->flags
|= PARSER_FLAG_COMPLETE_FRAMES
;
1053 } else if(st
->need_parsing
== AVSTREAM_PARSE_FULL_ONCE
) {
1054 st
->parser
->flags
|= PARSER_FLAG_ONCE
;
1058 if (!st
->need_parsing
|| !st
->parser
) {
1059 /* no parsing needed: we just output the packet as is */
1061 compute_pkt_fields(s
, st
, NULL
, pkt
);
1062 if ((s
->iformat
->flags
& AVFMT_GENERIC_INDEX
) &&
1063 (pkt
->flags
& AV_PKT_FLAG_KEY
) && pkt
->dts
!= AV_NOPTS_VALUE
) {
1064 ff_reduce_index(s
, st
->index
);
1065 av_add_index_entry(st
, pkt
->pos
, pkt
->dts
, 0, 0, AVINDEX_KEYFRAME
);
1068 } else if (st
->discard
< AVDISCARD_ALL
) {
1069 if ((ret
= parse_packet(s
, &cur_pkt
, cur_pkt
.stream_index
)) < 0)
1073 av_free_packet(&cur_pkt
);
1077 if (!got_packet
&& s
->parse_queue
)
1078 ret
= read_from_packet_buffer(&s
->parse_queue
, &s
->parse_queue_end
, pkt
);
1080 if(s
->debug
& FF_FDEBUG_TS
)
1081 av_log(s
, AV_LOG_DEBUG
, "read_frame_internal stream=%d, pts=%"PRId64
", dts=%"PRId64
", size=%d, duration=%d, flags=%d\n",
1092 int av_read_frame(AVFormatContext
*s
, AVPacket
*pkt
)
1094 const int genpts
= s
->flags
& AVFMT_FLAG_GENPTS
;
1098 return s
->packet_buffer ?
read_from_packet_buffer(&s
->packet_buffer
,
1099 &s
->packet_buffer_end
,
1101 read_frame_internal(s
, pkt
);
1105 AVPacketList
*pktl
= s
->packet_buffer
;
1108 AVPacket
*next_pkt
= &pktl
->pkt
;
1110 if (next_pkt
->dts
!= AV_NOPTS_VALUE
) {
1111 int wrap_bits
= s
->streams
[next_pkt
->stream_index
]->pts_wrap_bits
;
1112 while (pktl
&& next_pkt
->pts
== AV_NOPTS_VALUE
) {
1113 if (pktl
->pkt
.stream_index
== next_pkt
->stream_index
&&
1114 (av_compare_mod(next_pkt
->dts
, pktl
->pkt
.dts
, 2LL << (wrap_bits
- 1)) < 0) &&
1115 av_compare_mod(pktl
->pkt
.pts
, pktl
->pkt
.dts
, 2LL << (wrap_bits
- 1))) { //not b frame
1116 next_pkt
->pts
= pktl
->pkt
.dts
;
1120 pktl
= s
->packet_buffer
;
1123 /* read packet from packet buffer, if there is data */
1124 if (!(next_pkt
->pts
== AV_NOPTS_VALUE
&&
1125 next_pkt
->dts
!= AV_NOPTS_VALUE
&& !eof
))
1126 return read_from_packet_buffer(&s
->packet_buffer
,
1127 &s
->packet_buffer_end
, pkt
);
1130 ret
= read_frame_internal(s
, pkt
);
1132 if (pktl
&& ret
!= AVERROR(EAGAIN
)) {
1139 if (av_dup_packet(add_to_pktbuf(&s
->packet_buffer
, pkt
,
1140 &s
->packet_buffer_end
)) < 0)
1141 return AVERROR(ENOMEM
);
1145 /* XXX: suppress the packet queue */
1146 static void flush_packet_queue(AVFormatContext
*s
)
1148 free_packet_buffer(&s
->parse_queue
, &s
->parse_queue_end
);
1149 free_packet_buffer(&s
->packet_buffer
, &s
->packet_buffer_end
);
1150 free_packet_buffer(&s
->raw_packet_buffer
, &s
->raw_packet_buffer_end
);
1152 s
->raw_packet_buffer_remaining_size
= RAW_PACKET_BUFFER_SIZE
;
1155 /*******************************************************/
1158 int av_find_default_stream_index(AVFormatContext
*s
)
1160 int first_audio_index
= -1;
1164 if (s
->nb_streams
<= 0)
1166 for(i
= 0; i
< s
->nb_streams
; i
++) {
1168 if (st
->codec
->codec_type
== AVMEDIA_TYPE_VIDEO
&&
1169 !(st
->disposition
& AV_DISPOSITION_ATTACHED_PIC
)) {
1172 if (first_audio_index
< 0 && st
->codec
->codec_type
== AVMEDIA_TYPE_AUDIO
)
1173 first_audio_index
= i
;
1175 return first_audio_index
>= 0 ? first_audio_index
: 0;
1179 * Flush the frame reader.
1181 void ff_read_frame_flush(AVFormatContext
*s
)
1186 flush_packet_queue(s
);
1188 /* for each stream, reset read state */
1189 for(i
= 0; i
< s
->nb_streams
; i
++) {
1193 av_parser_close(st
->parser
);
1196 st
->last_IP_pts
= AV_NOPTS_VALUE
;
1197 st
->cur_dts
= AV_NOPTS_VALUE
; /* we set the current DTS to an unspecified origin */
1199 st
->probe_packets
= MAX_PROBE_PACKETS
;
1201 for(j
=0; j
<MAX_REORDER_DELAY
+1; j
++)
1202 st
->pts_buffer
[j
]= AV_NOPTS_VALUE
;
1206 void ff_update_cur_dts(AVFormatContext
*s
, AVStream
*ref_st
, int64_t timestamp
)
1210 for(i
= 0; i
< s
->nb_streams
; i
++) {
1211 AVStream
*st
= s
->streams
[i
];
1213 st
->cur_dts
= av_rescale(timestamp
,
1214 st
->time_base
.den
* (int64_t)ref_st
->time_base
.num
,
1215 st
->time_base
.num
* (int64_t)ref_st
->time_base
.den
);
1219 void ff_reduce_index(AVFormatContext
*s
, int stream_index
)
1221 AVStream
*st
= s
->streams
[stream_index
];
1222 unsigned int max_entries
= s
->max_index_size
/ sizeof(AVIndexEntry
);
1224 if((unsigned)st
->nb_index_entries
>= max_entries
){
1226 for(i
=0; 2*i
<st
->nb_index_entries
; i
++)
1227 st
->index_entries
[i
]= st
->index_entries
[2*i
];
1228 st
->nb_index_entries
= i
;
1232 int ff_add_index_entry(AVIndexEntry
**index_entries
,
1233 int *nb_index_entries
,
1234 unsigned int *index_entries_allocated_size
,
1235 int64_t pos
, int64_t timestamp
, int size
, int distance
, int flags
)
1237 AVIndexEntry
*entries
, *ie
;
1240 if((unsigned)*nb_index_entries
+ 1 >= UINT_MAX
/ sizeof(AVIndexEntry
))
1243 entries
= av_fast_realloc(*index_entries
,
1244 index_entries_allocated_size
,
1245 (*nb_index_entries
+ 1) *
1246 sizeof(AVIndexEntry
));
1250 *index_entries
= entries
;
1252 index
= ff_index_search_timestamp(*index_entries
, *nb_index_entries
, timestamp
, AVSEEK_FLAG_ANY
);
1255 index
= (*nb_index_entries
)++;
1256 ie
= &entries
[index
];
1257 assert(index
==0 || ie
[-1].timestamp
< timestamp
);
1259 ie
= &entries
[index
];
1260 if(ie
->timestamp
!= timestamp
){
1261 if(ie
->timestamp
<= timestamp
)
1263 memmove(entries
+ index
+ 1, entries
+ index
, sizeof(AVIndexEntry
)*(*nb_index_entries
- index
));
1264 (*nb_index_entries
)++;
1265 }else if(ie
->pos
== pos
&& distance
< ie
->min_distance
) //do not reduce the distance
1266 distance
= ie
->min_distance
;
1270 ie
->timestamp
= timestamp
;
1271 ie
->min_distance
= distance
;
1278 int av_add_index_entry(AVStream
*st
,
1279 int64_t pos
, int64_t timestamp
, int size
, int distance
, int flags
)
1281 return ff_add_index_entry(&st
->index_entries
, &st
->nb_index_entries
,
1282 &st
->index_entries_allocated_size
, pos
,
1283 timestamp
, size
, distance
, flags
);
1286 int ff_index_search_timestamp(const AVIndexEntry
*entries
, int nb_entries
,
1287 int64_t wanted_timestamp
, int flags
)
1295 //optimize appending index entries at the end
1296 if(b
&& entries
[b
-1].timestamp
< wanted_timestamp
)
1301 timestamp
= entries
[m
].timestamp
;
1302 if(timestamp
>= wanted_timestamp
)
1304 if(timestamp
<= wanted_timestamp
)
1307 m
= (flags
& AVSEEK_FLAG_BACKWARD
) ? a
: b
;
1309 if(!(flags
& AVSEEK_FLAG_ANY
)){
1310 while(m
>=0 && m
<nb_entries
&& !(entries
[m
].flags
& AVINDEX_KEYFRAME
)){
1311 m
+= (flags
& AVSEEK_FLAG_BACKWARD
) ?
-1 : 1;
1320 int av_index_search_timestamp(AVStream
*st
, int64_t wanted_timestamp
,
1323 return ff_index_search_timestamp(st
->index_entries
, st
->nb_index_entries
,
1324 wanted_timestamp
, flags
);
1327 int ff_seek_frame_binary(AVFormatContext
*s
, int stream_index
, int64_t target_ts
, int flags
)
1329 AVInputFormat
*avif
= s
->iformat
;
1330 int64_t av_uninit(pos_min
), av_uninit(pos_max
), pos
, pos_limit
;
1331 int64_t ts_min
, ts_max
, ts
;
1336 if (stream_index
< 0)
1339 av_dlog(s
, "read_seek: %d %"PRId64
"\n", stream_index
, target_ts
);
1342 ts_min
= AV_NOPTS_VALUE
;
1343 pos_limit
= -1; //gcc falsely says it may be uninitialized
1345 st
= s
->streams
[stream_index
];
1346 if(st
->index_entries
){
1349 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()
1350 index
= FFMAX(index
, 0);
1351 e
= &st
->index_entries
[index
];
1353 if(e
->timestamp
<= target_ts
|| e
->pos
== e
->min_distance
){
1355 ts_min
= e
->timestamp
;
1356 av_dlog(s
, "using cached pos_min=0x%"PRIx64
" dts_min=%"PRId64
"\n",
1362 index
= av_index_search_timestamp(st
, target_ts
, flags
& ~AVSEEK_FLAG_BACKWARD
);
1363 assert(index
< st
->nb_index_entries
);
1365 e
= &st
->index_entries
[index
];
1366 assert(e
->timestamp
>= target_ts
);
1368 ts_max
= e
->timestamp
;
1369 pos_limit
= pos_max
- e
->min_distance
;
1370 av_dlog(s
, "using cached pos_max=0x%"PRIx64
" pos_limit=0x%"PRIx64
" dts_max=%"PRId64
"\n",
1371 pos_max
,pos_limit
, ts_max
);
1375 pos
= ff_gen_search(s
, stream_index
, target_ts
, pos_min
, pos_max
, pos_limit
, ts_min
, ts_max
, flags
, &ts
, avif
->read_timestamp
);
1380 if ((ret
= avio_seek(s
->pb
, pos
, SEEK_SET
)) < 0)
1383 ff_update_cur_dts(s
, st
, ts
);
1388 int64_t ff_gen_search(AVFormatContext
*s
, int stream_index
, int64_t target_ts
,
1389 int64_t pos_min
, int64_t pos_max
, int64_t pos_limit
,
1390 int64_t ts_min
, int64_t ts_max
, int flags
, int64_t *ts_ret
,
1391 int64_t (*read_timestamp
)(struct AVFormatContext
*, int , int64_t *, int64_t ))
1394 int64_t start_pos
, filesize
;
1397 av_dlog(s
, "gen_seek: %d %"PRId64
"\n", stream_index
, target_ts
);
1399 if(ts_min
== AV_NOPTS_VALUE
){
1400 pos_min
= s
->data_offset
;
1401 ts_min
= read_timestamp(s
, stream_index
, &pos_min
, INT64_MAX
);
1402 if (ts_min
== AV_NOPTS_VALUE
)
1406 if(ts_max
== AV_NOPTS_VALUE
){
1408 filesize
= avio_size(s
->pb
);
1409 pos_max
= filesize
- 1;
1412 ts_max
= read_timestamp(s
, stream_index
, &pos_max
, pos_max
+ step
);
1414 }while(ts_max
== AV_NOPTS_VALUE
&& pos_max
>= step
);
1415 if (ts_max
== AV_NOPTS_VALUE
)
1419 int64_t tmp_pos
= pos_max
+ 1;
1420 int64_t tmp_ts
= read_timestamp(s
, stream_index
, &tmp_pos
, INT64_MAX
);
1421 if(tmp_ts
== AV_NOPTS_VALUE
)
1425 if(tmp_pos
>= filesize
)
1431 if(ts_min
> ts_max
){
1433 }else if(ts_min
== ts_max
){
1438 while (pos_min
< pos_limit
) {
1439 av_dlog(s
, "pos_min=0x%"PRIx64
" pos_max=0x%"PRIx64
" dts_min=%"PRId64
" dts_max=%"PRId64
"\n",
1440 pos_min
, pos_max
, ts_min
, ts_max
);
1441 assert(pos_limit
<= pos_max
);
1444 int64_t approximate_keyframe_distance
= pos_max
- pos_limit
;
1445 // interpolate position (better than dichotomy)
1446 pos
= av_rescale(target_ts
- ts_min
, pos_max
- pos_min
, ts_max
- ts_min
)
1447 + pos_min
- approximate_keyframe_distance
;
1448 }else if(no_change
==1){
1449 // bisection, if interpolation failed to change min or max pos last time
1450 pos
= (pos_min
+ pos_limit
)>>1;
1452 /* linear search if bisection failed, can only happen if there
1453 are very few or no keyframes between min/max */
1458 else if(pos
> pos_limit
)
1462 ts
= read_timestamp(s
, stream_index
, &pos
, INT64_MAX
); //may pass pos_limit instead of -1
1467 av_dlog(s
, "%"PRId64
" %"PRId64
" %"PRId64
" / %"PRId64
" %"PRId64
" %"PRId64
" target:%"PRId64
" limit:%"PRId64
" start:%"PRId64
" noc:%d\n",
1468 pos_min
, pos
, pos_max
, ts_min
, ts
, ts_max
, target_ts
,
1469 pos_limit
, start_pos
, no_change
);
1470 if(ts
== AV_NOPTS_VALUE
){
1471 av_log(s
, AV_LOG_ERROR
, "read_timestamp() failed in the middle\n");
1474 assert(ts
!= AV_NOPTS_VALUE
);
1475 if (target_ts
<= ts
) {
1476 pos_limit
= start_pos
- 1;
1480 if (target_ts
>= ts
) {
1486 pos
= (flags
& AVSEEK_FLAG_BACKWARD
) ? pos_min
: pos_max
;
1487 ts
= (flags
& AVSEEK_FLAG_BACKWARD
) ? ts_min
: ts_max
;
1489 ts_min
= read_timestamp(s
, stream_index
, &pos_min
, INT64_MAX
);
1491 ts_max
= read_timestamp(s
, stream_index
, &pos_min
, INT64_MAX
);
1492 av_dlog(s
, "pos=0x%"PRIx64
" %"PRId64
"<=%"PRId64
"<=%"PRId64
"\n",
1493 pos
, ts_min
, target_ts
, ts_max
);
1498 static int seek_frame_byte(AVFormatContext
*s
, int stream_index
, int64_t pos
, int flags
){
1499 int64_t pos_min
, pos_max
;
1501 pos_min
= s
->data_offset
;
1502 pos_max
= avio_size(s
->pb
) - 1;
1504 if (pos
< pos_min
) pos
= pos_min
;
1505 else if(pos
> pos_max
) pos
= pos_max
;
1507 avio_seek(s
->pb
, pos
, SEEK_SET
);
1512 static int seek_frame_generic(AVFormatContext
*s
,
1513 int stream_index
, int64_t timestamp
, int flags
)
1520 st
= s
->streams
[stream_index
];
1522 index
= av_index_search_timestamp(st
, timestamp
, flags
);
1524 if(index
< 0 && st
->nb_index_entries
&& timestamp
< st
->index_entries
[0].timestamp
)
1527 if(index
< 0 || index
==st
->nb_index_entries
-1){
1530 if(st
->nb_index_entries
){
1531 assert(st
->index_entries
);
1532 ie
= &st
->index_entries
[st
->nb_index_entries
-1];
1533 if ((ret
= avio_seek(s
->pb
, ie
->pos
, SEEK_SET
)) < 0)
1535 ff_update_cur_dts(s
, st
, ie
->timestamp
);
1537 if ((ret
= avio_seek(s
->pb
, s
->data_offset
, SEEK_SET
)) < 0)
1543 read_status
= av_read_frame(s
, &pkt
);
1544 } while (read_status
== AVERROR(EAGAIN
));
1545 if (read_status
< 0)
1547 av_free_packet(&pkt
);
1548 if(stream_index
== pkt
.stream_index
){
1549 if((pkt
.flags
& AV_PKT_FLAG_KEY
) && pkt
.dts
> timestamp
)
1553 index
= av_index_search_timestamp(st
, timestamp
, flags
);
1558 ff_read_frame_flush(s
);
1559 if (s
->iformat
->read_seek
){
1560 if(s
->iformat
->read_seek(s
, stream_index
, timestamp
, flags
) >= 0)
1563 ie
= &st
->index_entries
[index
];
1564 if ((ret
= avio_seek(s
->pb
, ie
->pos
, SEEK_SET
)) < 0)
1566 ff_update_cur_dts(s
, st
, ie
->timestamp
);
1571 static int seek_frame_internal(AVFormatContext
*s
, int stream_index
,
1572 int64_t timestamp
, int flags
)
1577 if (flags
& AVSEEK_FLAG_BYTE
) {
1578 if (s
->iformat
->flags
& AVFMT_NO_BYTE_SEEK
)
1580 ff_read_frame_flush(s
);
1581 return seek_frame_byte(s
, stream_index
, timestamp
, flags
);
1584 if(stream_index
< 0){
1585 stream_index
= av_find_default_stream_index(s
);
1586 if(stream_index
< 0)
1589 st
= s
->streams
[stream_index
];
1590 /* timestamp for default must be expressed in AV_TIME_BASE units */
1591 timestamp
= av_rescale(timestamp
, st
->time_base
.den
, AV_TIME_BASE
* (int64_t)st
->time_base
.num
);
1594 /* first, we try the format specific seek */
1595 if (s
->iformat
->read_seek
) {
1596 ff_read_frame_flush(s
);
1597 ret
= s
->iformat
->read_seek(s
, stream_index
, timestamp
, flags
);
1604 if (s
->iformat
->read_timestamp
&& !(s
->iformat
->flags
& AVFMT_NOBINSEARCH
)) {
1605 ff_read_frame_flush(s
);
1606 return ff_seek_frame_binary(s
, stream_index
, timestamp
, flags
);
1607 } else if (!(s
->iformat
->flags
& AVFMT_NOGENSEARCH
)) {
1608 ff_read_frame_flush(s
);
1609 return seek_frame_generic(s
, stream_index
, timestamp
, flags
);
1615 int av_seek_frame(AVFormatContext
*s
, int stream_index
, int64_t timestamp
, int flags
)
1617 int ret
= seek_frame_internal(s
, stream_index
, timestamp
, flags
);
1620 ret
= queue_attached_pictures(s
);
1625 int avformat_seek_file(AVFormatContext
*s
, int stream_index
, int64_t min_ts
, int64_t ts
, int64_t max_ts
, int flags
)
1627 if(min_ts
> ts
|| max_ts
< ts
)
1630 if (s
->iformat
->read_seek2
) {
1632 ff_read_frame_flush(s
);
1633 ret
= s
->iformat
->read_seek2(s
, stream_index
, min_ts
, ts
, max_ts
, flags
);
1636 ret
= queue_attached_pictures(s
);
1640 if(s
->iformat
->read_timestamp
){
1641 //try to seek via read_timestamp()
1644 // Fall back on old API if new is not implemented but old is.
1645 // Note the old API has somewhat different semantics.
1646 if(s
->iformat
->read_seek
|| 1)
1647 return av_seek_frame(s
, stream_index
, ts
, flags
| ((uint64_t)ts
- min_ts
> (uint64_t)max_ts
- ts ? AVSEEK_FLAG_BACKWARD
: 0));
1649 // try some generic seek like seek_frame_generic() but with new ts semantics
1652 /*******************************************************/
1655 * Return TRUE if the stream has accurate duration in any stream.
1657 * @return TRUE if the stream has accurate duration for at least one component.
1659 static int has_duration(AVFormatContext
*ic
)
1664 for(i
= 0;i
< ic
->nb_streams
; i
++) {
1665 st
= ic
->streams
[i
];
1666 if (st
->duration
!= AV_NOPTS_VALUE
)
1669 if (ic
->duration
!= AV_NOPTS_VALUE
)
1675 * Estimate the stream timings from the one of each components.
1677 * Also computes the global bitrate if possible.
1679 static void update_stream_timings(AVFormatContext
*ic
)
1681 int64_t start_time
, start_time1
, end_time
, end_time1
;
1682 int64_t duration
, duration1
, filesize
;
1686 start_time
= INT64_MAX
;
1687 end_time
= INT64_MIN
;
1688 duration
= INT64_MIN
;
1689 for(i
= 0;i
< ic
->nb_streams
; i
++) {
1690 st
= ic
->streams
[i
];
1691 if (st
->start_time
!= AV_NOPTS_VALUE
&& st
->time_base
.den
) {
1692 start_time1
= av_rescale_q(st
->start_time
, st
->time_base
, AV_TIME_BASE_Q
);
1693 start_time
= FFMIN(start_time
, start_time1
);
1694 if (st
->duration
!= AV_NOPTS_VALUE
) {
1695 end_time1
= start_time1
1696 + av_rescale_q(st
->duration
, st
->time_base
, AV_TIME_BASE_Q
);
1697 end_time
= FFMAX(end_time
, end_time1
);
1700 if (st
->duration
!= AV_NOPTS_VALUE
) {
1701 duration1
= av_rescale_q(st
->duration
, st
->time_base
, AV_TIME_BASE_Q
);
1702 duration
= FFMAX(duration
, duration1
);
1705 if (start_time
!= INT64_MAX
) {
1706 ic
->start_time
= start_time
;
1707 if (end_time
!= INT64_MIN
)
1708 duration
= FFMAX(duration
, end_time
- start_time
);
1710 if (duration
!= INT64_MIN
) {
1711 ic
->duration
= duration
;
1712 if (ic
->pb
&& (filesize
= avio_size(ic
->pb
)) > 0) {
1713 /* compute the bitrate */
1714 ic
->bit_rate
= (double)filesize
* 8.0 * AV_TIME_BASE
/
1715 (double)ic
->duration
;
1720 static void fill_all_stream_timings(AVFormatContext
*ic
)
1725 update_stream_timings(ic
);
1726 for(i
= 0;i
< ic
->nb_streams
; i
++) {
1727 st
= ic
->streams
[i
];
1728 if (st
->start_time
== AV_NOPTS_VALUE
) {
1729 if(ic
->start_time
!= AV_NOPTS_VALUE
)
1730 st
->start_time
= av_rescale_q(ic
->start_time
, AV_TIME_BASE_Q
, st
->time_base
);
1731 if(ic
->duration
!= AV_NOPTS_VALUE
)
1732 st
->duration
= av_rescale_q(ic
->duration
, AV_TIME_BASE_Q
, st
->time_base
);
1737 static void estimate_timings_from_bit_rate(AVFormatContext
*ic
)
1739 int64_t filesize
, duration
;
1743 /* if bit_rate is already set, we believe it */
1744 if (ic
->bit_rate
<= 0) {
1746 for(i
=0;i
<ic
->nb_streams
;i
++) {
1747 st
= ic
->streams
[i
];
1748 if (st
->codec
->bit_rate
> 0) {
1749 if (INT_MAX
- st
->codec
->bit_rate
< bit_rate
) {
1753 bit_rate
+= st
->codec
->bit_rate
;
1756 ic
->bit_rate
= bit_rate
;
1759 /* if duration is already set, we believe it */
1760 if (ic
->duration
== AV_NOPTS_VALUE
&&
1761 ic
->bit_rate
!= 0) {
1762 filesize
= ic
->pb ?
avio_size(ic
->pb
) : 0;
1764 for(i
= 0; i
< ic
->nb_streams
; i
++) {
1765 st
= ic
->streams
[i
];
1766 duration
= av_rescale(8*filesize
, st
->time_base
.den
, ic
->bit_rate
*(int64_t)st
->time_base
.num
);
1767 if (st
->duration
== AV_NOPTS_VALUE
)
1768 st
->duration
= duration
;
1774 #define DURATION_MAX_READ_SIZE 250000
1775 #define DURATION_MAX_RETRY 3
1777 /* only usable for MPEG-PS streams */
1778 static void estimate_timings_from_pts(AVFormatContext
*ic
, int64_t old_offset
)
1780 AVPacket pkt1
, *pkt
= &pkt1
;
1782 int read_size
, i
, ret
;
1784 int64_t filesize
, offset
, duration
;
1787 /* flush packet queue */
1788 flush_packet_queue(ic
);
1790 for (i
=0; i
<ic
->nb_streams
; i
++) {
1791 st
= ic
->streams
[i
];
1792 if (st
->start_time
== AV_NOPTS_VALUE
&& st
->first_dts
== AV_NOPTS_VALUE
)
1793 av_log(st
->codec
, AV_LOG_WARNING
, "start time is not set in estimate_timings_from_pts\n");
1796 av_parser_close(st
->parser
);
1801 /* estimate the end time (duration) */
1802 /* XXX: may need to support wrapping */
1803 filesize
= ic
->pb ?
avio_size(ic
->pb
) : 0;
1804 end_time
= AV_NOPTS_VALUE
;
1806 offset
= filesize
- (DURATION_MAX_READ_SIZE
<<retry
);
1810 avio_seek(ic
->pb
, offset
, SEEK_SET
);
1813 if (read_size
>= DURATION_MAX_READ_SIZE
<<(FFMAX(retry
-1,0)))
1817 ret
= ff_read_packet(ic
, pkt
);
1818 } while(ret
== AVERROR(EAGAIN
));
1821 read_size
+= pkt
->size
;
1822 st
= ic
->streams
[pkt
->stream_index
];
1823 if (pkt
->pts
!= AV_NOPTS_VALUE
&&
1824 (st
->start_time
!= AV_NOPTS_VALUE
||
1825 st
->first_dts
!= AV_NOPTS_VALUE
)) {
1826 duration
= end_time
= pkt
->pts
;
1827 if (st
->start_time
!= AV_NOPTS_VALUE
)
1828 duration
-= st
->start_time
;
1830 duration
-= st
->first_dts
;
1832 duration
+= 1LL<<st
->pts_wrap_bits
;
1834 if (st
->duration
== AV_NOPTS_VALUE
|| st
->duration
< duration
)
1835 st
->duration
= duration
;
1838 av_free_packet(pkt
);
1840 }while( end_time
==AV_NOPTS_VALUE
1841 && filesize
> (DURATION_MAX_READ_SIZE
<<retry
)
1842 && ++retry
<= DURATION_MAX_RETRY
);
1844 fill_all_stream_timings(ic
);
1846 avio_seek(ic
->pb
, old_offset
, SEEK_SET
);
1847 for (i
=0; i
<ic
->nb_streams
; i
++) {
1849 st
->cur_dts
= st
->first_dts
;
1850 st
->last_IP_pts
= AV_NOPTS_VALUE
;
1854 static void estimate_timings(AVFormatContext
*ic
, int64_t old_offset
)
1858 /* get the file size, if possible */
1859 if (ic
->iformat
->flags
& AVFMT_NOFILE
) {
1862 file_size
= avio_size(ic
->pb
);
1863 file_size
= FFMAX(0, file_size
);
1866 if ((!strcmp(ic
->iformat
->name
, "mpeg") ||
1867 !strcmp(ic
->iformat
->name
, "mpegts")) &&
1868 file_size
&& ic
->pb
->seekable
) {
1869 /* get accurate estimate from the PTSes */
1870 estimate_timings_from_pts(ic
, old_offset
);
1871 } else if (has_duration(ic
)) {
1872 /* at least one component has timings - we use them for all
1874 fill_all_stream_timings(ic
);
1876 av_log(ic
, AV_LOG_WARNING
, "Estimating duration from bitrate, this may be inaccurate\n");
1877 /* less precise: use bitrate info */
1878 estimate_timings_from_bit_rate(ic
);
1880 update_stream_timings(ic
);
1884 AVStream av_unused
*st
;
1885 for(i
= 0;i
< ic
->nb_streams
; i
++) {
1886 st
= ic
->streams
[i
];
1887 av_dlog(ic
, "%d: start_time: %0.3f duration: %0.3f\n", i
,
1888 (double) st
->start_time
/ AV_TIME_BASE
,
1889 (double) st
->duration
/ AV_TIME_BASE
);
1891 av_dlog(ic
, "stream: start_time: %0.3f duration: %0.3f bitrate=%d kb/s\n",
1892 (double) ic
->start_time
/ AV_TIME_BASE
,
1893 (double) ic
->duration
/ AV_TIME_BASE
,
1894 ic
->bit_rate
/ 1000);
1898 static int has_codec_parameters(AVStream
*st
)
1900 AVCodecContext
*avctx
= st
->codec
;
1902 switch (avctx
->codec_type
) {
1903 case AVMEDIA_TYPE_AUDIO
:
1904 val
= avctx
->sample_rate
&& avctx
->channels
;
1905 if (st
->info
->found_decoder
>= 0 && avctx
->sample_fmt
== AV_SAMPLE_FMT_NONE
)
1908 case AVMEDIA_TYPE_VIDEO
:
1910 if (st
->info
->found_decoder
>= 0 && avctx
->pix_fmt
== AV_PIX_FMT_NONE
)
1917 return avctx
->codec_id
!= AV_CODEC_ID_NONE
&& val
!= 0;
1920 static int has_decode_delay_been_guessed(AVStream
*st
)
1922 return st
->codec
->codec_id
!= AV_CODEC_ID_H264
||
1923 st
->info
->nb_decoded_frames
>= 6;
1926 /* returns 1 or 0 if or if not decoded data was returned, or a negative error */
1927 static int try_decode_frame(AVStream
*st
, AVPacket
*avpkt
, AVDictionary
**options
)
1929 const AVCodec
*codec
;
1930 int got_picture
= 1, ret
= 0;
1931 AVFrame
*frame
= av_frame_alloc();
1932 AVPacket pkt
= *avpkt
;
1935 return AVERROR(ENOMEM
);
1937 if (!avcodec_is_open(st
->codec
) && !st
->info
->found_decoder
) {
1938 AVDictionary
*thread_opt
= NULL
;
1940 codec
= st
->codec
->codec ? st
->codec
->codec
:
1941 avcodec_find_decoder(st
->codec
->codec_id
);
1944 st
->info
->found_decoder
= -1;
1949 /* force thread count to 1 since the h264 decoder will not extract SPS
1950 * and PPS to extradata during multi-threaded decoding */
1951 av_dict_set(options ? options
: &thread_opt
, "threads", "1", 0);
1952 ret
= avcodec_open2(st
->codec
, codec
, options ? options
: &thread_opt
);
1954 av_dict_free(&thread_opt
);
1956 st
->info
->found_decoder
= -1;
1959 st
->info
->found_decoder
= 1;
1960 } else if (!st
->info
->found_decoder
)
1961 st
->info
->found_decoder
= 1;
1963 if (st
->info
->found_decoder
< 0) {
1968 while ((pkt
.size
> 0 || (!pkt
.data
&& got_picture
)) &&
1970 (!has_codec_parameters(st
) ||
1971 !has_decode_delay_been_guessed(st
) ||
1972 (!st
->codec_info_nb_frames
&& st
->codec
->codec
->capabilities
& CODEC_CAP_CHANNEL_CONF
))) {
1974 switch(st
->codec
->codec_type
) {
1975 case AVMEDIA_TYPE_VIDEO
:
1976 ret
= avcodec_decode_video2(st
->codec
, frame
,
1977 &got_picture
, &pkt
);
1979 case AVMEDIA_TYPE_AUDIO
:
1980 ret
= avcodec_decode_audio4(st
->codec
, frame
, &got_picture
, &pkt
);
1987 st
->info
->nb_decoded_frames
++;
1995 av_frame_free(&frame
);
1999 unsigned int ff_codec_get_tag(const AVCodecTag
*tags
, enum AVCodecID id
)
2001 while (tags
->id
!= AV_CODEC_ID_NONE
) {
2009 enum AVCodecID
ff_codec_get_id(const AVCodecTag
*tags
, unsigned int tag
)
2012 for(i
=0; tags
[i
].id
!= AV_CODEC_ID_NONE
;i
++) {
2013 if(tag
== tags
[i
].tag
)
2016 for(i
=0; tags
[i
].id
!= AV_CODEC_ID_NONE
; i
++) {
2017 if (avpriv_toupper4(tag
) == avpriv_toupper4(tags
[i
].tag
))
2020 return AV_CODEC_ID_NONE
;
2023 enum AVCodecID
ff_get_pcm_codec_id(int bps
, int flt
, int be
, int sflags
)
2027 case 32: return be ? AV_CODEC_ID_PCM_F32BE
: AV_CODEC_ID_PCM_F32LE
;
2028 case 64: return be ? AV_CODEC_ID_PCM_F64BE
: AV_CODEC_ID_PCM_F64LE
;
2029 default: return AV_CODEC_ID_NONE
;
2033 if (sflags
& (1 << (bps
- 1))) {
2035 case 1: return AV_CODEC_ID_PCM_S8
;
2036 case 2: return be ? AV_CODEC_ID_PCM_S16BE
: AV_CODEC_ID_PCM_S16LE
;
2037 case 3: return be ? AV_CODEC_ID_PCM_S24BE
: AV_CODEC_ID_PCM_S24LE
;
2038 case 4: return be ? AV_CODEC_ID_PCM_S32BE
: AV_CODEC_ID_PCM_S32LE
;
2039 default: return AV_CODEC_ID_NONE
;
2043 case 1: return AV_CODEC_ID_PCM_U8
;
2044 case 2: return be ? AV_CODEC_ID_PCM_U16BE
: AV_CODEC_ID_PCM_U16LE
;
2045 case 3: return be ? AV_CODEC_ID_PCM_U24BE
: AV_CODEC_ID_PCM_U24LE
;
2046 case 4: return be ? AV_CODEC_ID_PCM_U32BE
: AV_CODEC_ID_PCM_U32LE
;
2047 default: return AV_CODEC_ID_NONE
;
2053 unsigned int av_codec_get_tag(const AVCodecTag
* const *tags
, enum AVCodecID id
)
2056 for(i
=0; tags
&& tags
[i
]; i
++){
2057 int tag
= ff_codec_get_tag(tags
[i
], id
);
2063 enum AVCodecID
av_codec_get_id(const AVCodecTag
* const *tags
, unsigned int tag
)
2066 for(i
=0; tags
&& tags
[i
]; i
++){
2067 enum AVCodecID id
= ff_codec_get_id(tags
[i
], tag
);
2068 if(id
!=AV_CODEC_ID_NONE
) return id
;
2070 return AV_CODEC_ID_NONE
;
2073 static void compute_chapters_end(AVFormatContext
*s
)
2076 int64_t max_time
= s
->duration
+ ((s
->start_time
== AV_NOPTS_VALUE
) ?
0 : s
->start_time
);
2078 for (i
= 0; i
< s
->nb_chapters
; i
++)
2079 if (s
->chapters
[i
]->end
== AV_NOPTS_VALUE
) {
2080 AVChapter
*ch
= s
->chapters
[i
];
2081 int64_t end
= max_time ?
av_rescale_q(max_time
, AV_TIME_BASE_Q
, ch
->time_base
)
2084 for (j
= 0; j
< s
->nb_chapters
; j
++) {
2085 AVChapter
*ch1
= s
->chapters
[j
];
2086 int64_t next_start
= av_rescale_q(ch1
->start
, ch1
->time_base
, ch
->time_base
);
2087 if (j
!= i
&& next_start
> ch
->start
&& next_start
< end
)
2090 ch
->end
= (end
== INT64_MAX
) ? ch
->start
: end
;
2094 static int get_std_framerate(int i
){
2095 if(i
<60*12) return i
*1001;
2096 else return ((const int[]){24,30,60,12,15})[i
-60*12]*1000*12;
2100 * Is the time base unreliable.
2101 * This is a heuristic to balance between quick acceptance of the values in
2102 * the headers vs. some extra checks.
2103 * Old DivX and Xvid often have nonsense timebases like 1fps or 2fps.
2104 * MPEG-2 commonly misuses field repeat flags to store different framerates.
2105 * And there are "variable" fps files this needs to detect as well.
2107 static int tb_unreliable(AVCodecContext
*c
){
2108 if( c
->time_base
.den
>= 101L*c
->time_base
.num
2109 || c
->time_base
.den
< 5L*c
->time_base
.num
2110 /* || c->codec_tag == AV_RL32("DIVX")
2111 || c->codec_tag == AV_RL32("XVID")*/
2112 || c
->codec_id
== AV_CODEC_ID_MPEG2VIDEO
2113 || c
->codec_id
== AV_CODEC_ID_H264
2119 int avformat_find_stream_info(AVFormatContext
*ic
, AVDictionary
**options
)
2121 int i
, count
, ret
, read_size
, j
;
2123 AVPacket pkt1
, *pkt
;
2124 int64_t old_offset
= avio_tell(ic
->pb
);
2125 int orig_nb_streams
= ic
->nb_streams
; // new streams might appear, no options for those
2127 for(i
=0;i
<ic
->nb_streams
;i
++) {
2128 const AVCodec
*codec
;
2129 AVDictionary
*thread_opt
= NULL
;
2130 st
= ic
->streams
[i
];
2132 //only for the split stuff
2133 if (!st
->parser
&& !(ic
->flags
& AVFMT_FLAG_NOPARSE
)) {
2134 st
->parser
= av_parser_init(st
->codec
->codec_id
);
2135 if(st
->need_parsing
== AVSTREAM_PARSE_HEADERS
&& st
->parser
){
2136 st
->parser
->flags
|= PARSER_FLAG_COMPLETE_FRAMES
;
2139 codec
= st
->codec
->codec ? st
->codec
->codec
:
2140 avcodec_find_decoder(st
->codec
->codec_id
);
2142 /* force thread count to 1 since the h264 decoder will not extract SPS
2143 * and PPS to extradata during multi-threaded decoding */
2144 av_dict_set(options ?
&options
[i
] : &thread_opt
, "threads", "1", 0);
2146 /* Ensure that subtitle_header is properly set. */
2147 if (st
->codec
->codec_type
== AVMEDIA_TYPE_SUBTITLE
2148 && codec
&& !st
->codec
->codec
)
2149 avcodec_open2(st
->codec
, codec
, options ?
&options
[i
]
2152 //try to just open decoders, in case this is enough to get parameters
2153 if (!has_codec_parameters(st
)) {
2154 if (codec
&& !st
->codec
->codec
)
2155 avcodec_open2(st
->codec
, codec
, options ?
&options
[i
]
2159 av_dict_free(&thread_opt
);
2162 for (i
=0; i
<ic
->nb_streams
; i
++) {
2163 ic
->streams
[i
]->info
->fps_first_dts
= AV_NOPTS_VALUE
;
2164 ic
->streams
[i
]->info
->fps_last_dts
= AV_NOPTS_VALUE
;
2170 if (ff_check_interrupt(&ic
->interrupt_callback
)){
2172 av_log(ic
, AV_LOG_DEBUG
, "interrupted\n");
2176 /* check if one codec still needs to be handled */
2177 for(i
=0;i
<ic
->nb_streams
;i
++) {
2178 int fps_analyze_framecount
= 20;
2180 st
= ic
->streams
[i
];
2181 if (!has_codec_parameters(st
))
2183 /* if the timebase is coarse (like the usual millisecond precision
2184 of mkv), we need to analyze more frames to reliably arrive at
2186 if (av_q2d(st
->time_base
) > 0.0005)
2187 fps_analyze_framecount
*= 2;
2188 if (ic
->fps_probe_size
>= 0)
2189 fps_analyze_framecount
= ic
->fps_probe_size
;
2190 /* variable fps and no guess at the real fps */
2191 if( tb_unreliable(st
->codec
) && !st
->avg_frame_rate
.num
2192 && st
->codec_info_nb_frames
< fps_analyze_framecount
2193 && st
->codec
->codec_type
== AVMEDIA_TYPE_VIDEO
)
2195 if(st
->parser
&& st
->parser
->parser
->split
&& !st
->codec
->extradata
)
2197 if (st
->first_dts
== AV_NOPTS_VALUE
&&
2198 (st
->codec
->codec_type
== AVMEDIA_TYPE_VIDEO
||
2199 st
->codec
->codec_type
== AVMEDIA_TYPE_AUDIO
))
2202 if (i
== ic
->nb_streams
) {
2203 /* NOTE: if the format has no header, then we need to read
2204 some packets to get most of the streams, so we cannot
2206 if (!(ic
->ctx_flags
& AVFMTCTX_NOHEADER
)) {
2207 /* if we found the info for all the codecs, we can stop */
2209 av_log(ic
, AV_LOG_DEBUG
, "All info found\n");
2213 /* we did not get all the codec info, but we read too much data */
2214 if (read_size
>= ic
->probesize
) {
2216 av_log(ic
, AV_LOG_DEBUG
, "Probe buffer size limit %d reached\n", ic
->probesize
);
2220 /* NOTE: a new stream can be added there if no header in file
2221 (AVFMTCTX_NOHEADER) */
2222 ret
= read_frame_internal(ic
, &pkt1
);
2223 if (ret
== AVERROR(EAGAIN
))
2228 AVPacket empty_pkt
= { 0 };
2230 av_init_packet(&empty_pkt
);
2232 ret
= -1; /* we could not have all the codec parameters before EOF */
2233 for(i
=0;i
<ic
->nb_streams
;i
++) {
2234 st
= ic
->streams
[i
];
2236 /* flush the decoders */
2237 if (st
->info
->found_decoder
== 1) {
2239 err
= try_decode_frame(st
, &empty_pkt
,
2240 (options
&& i
< orig_nb_streams
) ?
2241 &options
[i
] : NULL
);
2242 } while (err
> 0 && !has_codec_parameters(st
));
2246 av_log(ic
, AV_LOG_WARNING
,
2247 "decoding for stream %d failed\n", st
->index
);
2248 } else if (!has_codec_parameters(st
)) {
2250 avcodec_string(buf
, sizeof(buf
), st
->codec
, 0);
2251 av_log(ic
, AV_LOG_WARNING
,
2252 "Could not find codec parameters (%s)\n", buf
);
2260 if (ic
->flags
& AVFMT_FLAG_NOBUFFER
) {
2263 pkt
= add_to_pktbuf(&ic
->packet_buffer
, &pkt1
,
2264 &ic
->packet_buffer_end
);
2265 if ((ret
= av_dup_packet(pkt
)) < 0)
2266 goto find_stream_info_err
;
2269 read_size
+= pkt
->size
;
2271 st
= ic
->streams
[pkt
->stream_index
];
2272 if (pkt
->dts
!= AV_NOPTS_VALUE
&& st
->codec_info_nb_frames
> 1) {
2273 /* check for non-increasing dts */
2274 if (st
->info
->fps_last_dts
!= AV_NOPTS_VALUE
&&
2275 st
->info
->fps_last_dts
>= pkt
->dts
) {
2276 av_log(ic
, AV_LOG_WARNING
, "Non-increasing DTS in stream %d: "
2277 "packet %d with DTS %"PRId64
", packet %d with DTS "
2278 "%"PRId64
"\n", st
->index
, st
->info
->fps_last_dts_idx
,
2279 st
->info
->fps_last_dts
, st
->codec_info_nb_frames
, pkt
->dts
);
2280 st
->info
->fps_first_dts
= st
->info
->fps_last_dts
= AV_NOPTS_VALUE
;
2282 /* check for a discontinuity in dts - if the difference in dts
2283 * is more than 1000 times the average packet duration in the sequence,
2284 * we treat it as a discontinuity */
2285 if (st
->info
->fps_last_dts
!= AV_NOPTS_VALUE
&&
2286 st
->info
->fps_last_dts_idx
> st
->info
->fps_first_dts_idx
&&
2287 (pkt
->dts
- st
->info
->fps_last_dts
) / 1000 >
2288 (st
->info
->fps_last_dts
- st
->info
->fps_first_dts
) / (st
->info
->fps_last_dts_idx
- st
->info
->fps_first_dts_idx
)) {
2289 av_log(ic
, AV_LOG_WARNING
, "DTS discontinuity in stream %d: "
2290 "packet %d with DTS %"PRId64
", packet %d with DTS "
2291 "%"PRId64
"\n", st
->index
, st
->info
->fps_last_dts_idx
,
2292 st
->info
->fps_last_dts
, st
->codec_info_nb_frames
, pkt
->dts
);
2293 st
->info
->fps_first_dts
= st
->info
->fps_last_dts
= AV_NOPTS_VALUE
;
2296 /* update stored dts values */
2297 if (st
->info
->fps_first_dts
== AV_NOPTS_VALUE
) {
2298 st
->info
->fps_first_dts
= pkt
->dts
;
2299 st
->info
->fps_first_dts_idx
= st
->codec_info_nb_frames
;
2301 st
->info
->fps_last_dts
= pkt
->dts
;
2302 st
->info
->fps_last_dts_idx
= st
->codec_info_nb_frames
;
2304 /* check max_analyze_duration */
2305 if (av_rescale_q(pkt
->dts
- st
->info
->fps_first_dts
, st
->time_base
,
2306 AV_TIME_BASE_Q
) >= ic
->max_analyze_duration
) {
2307 av_log(ic
, AV_LOG_WARNING
, "max_analyze_duration reached\n");
2311 if(st
->parser
&& st
->parser
->parser
->split
&& !st
->codec
->extradata
){
2312 int i
= st
->parser
->parser
->split(st
->codec
, pkt
->data
, pkt
->size
);
2313 if (i
> 0 && i
< FF_MAX_EXTRADATA_SIZE
) {
2314 st
->codec
->extradata_size
= i
;
2315 st
->codec
->extradata
= av_malloc(st
->codec
->extradata_size
+ FF_INPUT_BUFFER_PADDING_SIZE
);
2316 if (!st
->codec
->extradata
)
2317 return AVERROR(ENOMEM
);
2318 memcpy(st
->codec
->extradata
, pkt
->data
, st
->codec
->extradata_size
);
2319 memset(st
->codec
->extradata
+ i
, 0, FF_INPUT_BUFFER_PADDING_SIZE
);
2323 /* if still no information, we try to open the codec and to
2324 decompress the frame. We try to avoid that in most cases as
2325 it takes longer and uses more memory. For MPEG-4, we need to
2326 decompress for QuickTime.
2328 If CODEC_CAP_CHANNEL_CONF is set this will force decoding of at
2329 least one frame of codec data, this makes sure the codec initializes
2330 the channel configuration and does not only trust the values from the container.
2332 try_decode_frame(st
, pkt
, (options
&& i
< orig_nb_streams
) ?
&options
[i
] : NULL
);
2334 st
->codec_info_nb_frames
++;
2338 // close codecs which were opened in try_decode_frame()
2339 for(i
=0;i
<ic
->nb_streams
;i
++) {
2340 st
= ic
->streams
[i
];
2341 avcodec_close(st
->codec
);
2343 for(i
=0;i
<ic
->nb_streams
;i
++) {
2344 st
= ic
->streams
[i
];
2345 if (st
->codec
->codec_type
== AVMEDIA_TYPE_VIDEO
) {
2346 /* estimate average framerate if not set by demuxer */
2347 if (!st
->avg_frame_rate
.num
&& st
->info
->fps_last_dts
!= st
->info
->fps_first_dts
) {
2348 int64_t delta_dts
= st
->info
->fps_last_dts
- st
->info
->fps_first_dts
;
2349 int delta_packets
= st
->info
->fps_last_dts_idx
- st
->info
->fps_first_dts_idx
;
2351 double best_error
= 0.01;
2353 if (delta_dts
>= INT64_MAX
/ st
->time_base
.num
||
2354 delta_packets
>= INT64_MAX
/ st
->time_base
.den
||
2357 av_reduce(&st
->avg_frame_rate
.num
, &st
->avg_frame_rate
.den
,
2358 delta_packets
*(int64_t)st
->time_base
.den
,
2359 delta_dts
*(int64_t)st
->time_base
.num
, 60000);
2361 /* round guessed framerate to a "standard" framerate if it's
2362 * within 1% of the original estimate*/
2363 for (j
= 1; j
< MAX_STD_TIMEBASES
; j
++) {
2364 AVRational std_fps
= { get_std_framerate(j
), 12*1001 };
2365 double error
= fabs(av_q2d(st
->avg_frame_rate
) / av_q2d(std_fps
) - 1);
2367 if (error
< best_error
) {
2369 best_fps
= std_fps
.num
;
2373 av_reduce(&st
->avg_frame_rate
.num
, &st
->avg_frame_rate
.den
,
2374 best_fps
, 12*1001, INT_MAX
);
2377 }else if(st
->codec
->codec_type
== AVMEDIA_TYPE_AUDIO
) {
2378 if(!st
->codec
->bits_per_coded_sample
)
2379 st
->codec
->bits_per_coded_sample
= av_get_bits_per_sample(st
->codec
->codec_id
);
2380 // set stream disposition based on audio service type
2381 switch (st
->codec
->audio_service_type
) {
2382 case AV_AUDIO_SERVICE_TYPE_EFFECTS
:
2383 st
->disposition
= AV_DISPOSITION_CLEAN_EFFECTS
; break;
2384 case AV_AUDIO_SERVICE_TYPE_VISUALLY_IMPAIRED
:
2385 st
->disposition
= AV_DISPOSITION_VISUAL_IMPAIRED
; break;
2386 case AV_AUDIO_SERVICE_TYPE_HEARING_IMPAIRED
:
2387 st
->disposition
= AV_DISPOSITION_HEARING_IMPAIRED
; break;
2388 case AV_AUDIO_SERVICE_TYPE_COMMENTARY
:
2389 st
->disposition
= AV_DISPOSITION_COMMENT
; break;
2390 case AV_AUDIO_SERVICE_TYPE_KARAOKE
:
2391 st
->disposition
= AV_DISPOSITION_KARAOKE
; break;
2396 estimate_timings(ic
, old_offset
);
2398 compute_chapters_end(ic
);
2400 find_stream_info_err
:
2401 for (i
=0; i
< ic
->nb_streams
; i
++) {
2402 ic
->streams
[i
]->codec
->thread_count
= 0;
2403 av_freep(&ic
->streams
[i
]->info
);
2408 static AVProgram
*find_program_from_stream(AVFormatContext
*ic
, int s
)
2412 for (i
= 0; i
< ic
->nb_programs
; i
++)
2413 for (j
= 0; j
< ic
->programs
[i
]->nb_stream_indexes
; j
++)
2414 if (ic
->programs
[i
]->stream_index
[j
] == s
)
2415 return ic
->programs
[i
];
2419 int av_find_best_stream(AVFormatContext
*ic
,
2420 enum AVMediaType type
,
2421 int wanted_stream_nb
,
2423 AVCodec
**decoder_ret
,
2426 int i
, nb_streams
= ic
->nb_streams
;
2427 int ret
= AVERROR_STREAM_NOT_FOUND
, best_count
= -1;
2428 unsigned *program
= NULL
;
2429 AVCodec
*decoder
= NULL
, *best_decoder
= NULL
;
2431 if (related_stream
>= 0 && wanted_stream_nb
< 0) {
2432 AVProgram
*p
= find_program_from_stream(ic
, related_stream
);
2434 program
= p
->stream_index
;
2435 nb_streams
= p
->nb_stream_indexes
;
2438 for (i
= 0; i
< nb_streams
; i
++) {
2439 int real_stream_index
= program ? program
[i
] : i
;
2440 AVStream
*st
= ic
->streams
[real_stream_index
];
2441 AVCodecContext
*avctx
= st
->codec
;
2442 if (avctx
->codec_type
!= type
)
2444 if (wanted_stream_nb
>= 0 && real_stream_index
!= wanted_stream_nb
)
2446 if (st
->disposition
& (AV_DISPOSITION_HEARING_IMPAIRED
|AV_DISPOSITION_VISUAL_IMPAIRED
))
2449 decoder
= avcodec_find_decoder(st
->codec
->codec_id
);
2452 ret
= AVERROR_DECODER_NOT_FOUND
;
2456 if (best_count
>= st
->codec_info_nb_frames
)
2458 best_count
= st
->codec_info_nb_frames
;
2459 ret
= real_stream_index
;
2460 best_decoder
= decoder
;
2461 if (program
&& i
== nb_streams
- 1 && ret
< 0) {
2463 nb_streams
= ic
->nb_streams
;
2464 i
= 0; /* no related stream found, try again with everything */
2468 *decoder_ret
= best_decoder
;
2472 /*******************************************************/
2474 int av_read_play(AVFormatContext
*s
)
2476 if (s
->iformat
->read_play
)
2477 return s
->iformat
->read_play(s
);
2479 return avio_pause(s
->pb
, 0);
2480 return AVERROR(ENOSYS
);
2483 int av_read_pause(AVFormatContext
*s
)
2485 if (s
->iformat
->read_pause
)
2486 return s
->iformat
->read_pause(s
);
2488 return avio_pause(s
->pb
, 1);
2489 return AVERROR(ENOSYS
);
2492 void avformat_free_context(AVFormatContext
*s
)
2498 if (s
->iformat
&& s
->iformat
->priv_class
&& s
->priv_data
)
2499 av_opt_free(s
->priv_data
);
2501 for(i
=0;i
<s
->nb_streams
;i
++) {
2502 /* free all data in a stream component */
2505 av_parser_close(st
->parser
);
2507 if (st
->attached_pic
.data
)
2508 av_free_packet(&st
->attached_pic
);
2509 av_dict_free(&st
->metadata
);
2510 av_freep(&st
->probe_data
.buf
);
2511 av_free(st
->index_entries
);
2512 av_free(st
->codec
->extradata
);
2513 av_free(st
->codec
->subtitle_header
);
2515 av_free(st
->priv_data
);
2519 for(i
=s
->nb_programs
-1; i
>=0; i
--) {
2520 av_dict_free(&s
->programs
[i
]->metadata
);
2521 av_freep(&s
->programs
[i
]->stream_index
);
2522 av_freep(&s
->programs
[i
]);
2524 av_freep(&s
->programs
);
2525 av_freep(&s
->priv_data
);
2526 while(s
->nb_chapters
--) {
2527 av_dict_free(&s
->chapters
[s
->nb_chapters
]->metadata
);
2528 av_free(s
->chapters
[s
->nb_chapters
]);
2530 av_freep(&s
->chapters
);
2531 av_dict_free(&s
->metadata
);
2532 av_freep(&s
->streams
);
2536 void avformat_close_input(AVFormatContext
**ps
)
2538 AVFormatContext
*s
= *ps
;
2539 AVIOContext
*pb
= s
->pb
;
2541 if ((s
->iformat
&& s
->iformat
->flags
& AVFMT_NOFILE
) ||
2542 (s
->flags
& AVFMT_FLAG_CUSTOM_IO
))
2545 flush_packet_queue(s
);
2548 if (s
->iformat
->read_close
)
2549 s
->iformat
->read_close(s
);
2552 avformat_free_context(s
);
2559 AVStream
*avformat_new_stream(AVFormatContext
*s
, AVCodec
*c
)
2564 if (av_reallocp_array(&s
->streams
, s
->nb_streams
+ 1, sizeof(*s
->streams
)) < 0) {
2569 st
= av_mallocz(sizeof(AVStream
));
2572 if (!(st
->info
= av_mallocz(sizeof(*st
->info
)))) {
2577 st
->codec
= avcodec_alloc_context3(c
);
2579 /* no default bitrate if decoding */
2580 st
->codec
->bit_rate
= 0;
2582 st
->index
= s
->nb_streams
;
2583 st
->start_time
= AV_NOPTS_VALUE
;
2584 st
->duration
= AV_NOPTS_VALUE
;
2585 /* we set the current DTS to 0 so that formats without any timestamps
2586 but durations get some timestamps, formats with some unknown
2587 timestamps have their first few packets buffered and the
2588 timestamps corrected before they are returned to the user */
2590 st
->first_dts
= AV_NOPTS_VALUE
;
2591 st
->probe_packets
= MAX_PROBE_PACKETS
;
2593 /* default pts setting is MPEG-like */
2594 avpriv_set_pts_info(st
, 33, 1, 90000);
2595 st
->last_IP_pts
= AV_NOPTS_VALUE
;
2596 for(i
=0; i
<MAX_REORDER_DELAY
+1; i
++)
2597 st
->pts_buffer
[i
]= AV_NOPTS_VALUE
;
2599 st
->sample_aspect_ratio
= (AVRational
){0,1};
2601 st
->info
->fps_first_dts
= AV_NOPTS_VALUE
;
2602 st
->info
->fps_last_dts
= AV_NOPTS_VALUE
;
2604 s
->streams
[s
->nb_streams
++] = st
;
2608 AVProgram
*av_new_program(AVFormatContext
*ac
, int id
)
2610 AVProgram
*program
=NULL
;
2613 av_dlog(ac
, "new_program: id=0x%04x\n", id
);
2615 for(i
=0; i
<ac
->nb_programs
; i
++)
2616 if(ac
->programs
[i
]->id
== id
)
2617 program
= ac
->programs
[i
];
2620 program
= av_mallocz(sizeof(AVProgram
));
2623 dynarray_add(&ac
->programs
, &ac
->nb_programs
, program
);
2624 program
->discard
= AVDISCARD_NONE
;
2631 AVChapter
*avpriv_new_chapter(AVFormatContext
*s
, int id
, AVRational time_base
, int64_t start
, int64_t end
, const char *title
)
2633 AVChapter
*chapter
= NULL
;
2636 for(i
=0; i
<s
->nb_chapters
; i
++)
2637 if(s
->chapters
[i
]->id
== id
)
2638 chapter
= s
->chapters
[i
];
2641 chapter
= av_mallocz(sizeof(AVChapter
));
2644 dynarray_add(&s
->chapters
, &s
->nb_chapters
, chapter
);
2646 av_dict_set(&chapter
->metadata
, "title", title
, 0);
2648 chapter
->time_base
= time_base
;
2649 chapter
->start
= start
;
2655 void ff_program_add_stream_index(AVFormatContext
*ac
, int progid
, unsigned int idx
)
2658 AVProgram
*program
=NULL
;
2660 if (idx
>= ac
->nb_streams
) {
2661 av_log(ac
, AV_LOG_ERROR
, "stream index %d is not valid\n", idx
);
2665 for(i
=0; i
<ac
->nb_programs
; i
++){
2666 if(ac
->programs
[i
]->id
!= progid
)
2668 program
= ac
->programs
[i
];
2669 for(j
=0; j
<program
->nb_stream_indexes
; j
++)
2670 if(program
->stream_index
[j
] == idx
)
2673 if (av_reallocp_array(&program
->stream_index
,
2674 program
->nb_stream_indexes
+ 1,
2675 sizeof(*program
->stream_index
)) < 0) {
2676 program
->nb_stream_indexes
= 0;
2679 program
->stream_index
[program
->nb_stream_indexes
++] = idx
;
2684 static void print_fps(double d
, const char *postfix
){
2685 uint64_t v
= lrintf(d
*100);
2686 if (v
% 100 ) av_log(NULL
, AV_LOG_INFO
, ", %3.2f %s", d
, postfix
);
2687 else if(v
%(100*1000)) av_log(NULL
, AV_LOG_INFO
, ", %1.0f %s", d
, postfix
);
2688 else av_log(NULL
, AV_LOG_INFO
, ", %1.0fk %s", d
/1000, postfix
);
2691 static void dump_metadata(void *ctx
, AVDictionary
*m
, const char *indent
)
2693 if(m
&& !(av_dict_count(m
) == 1 && av_dict_get(m
, "language", NULL
, 0))){
2694 AVDictionaryEntry
*tag
=NULL
;
2696 av_log(ctx
, AV_LOG_INFO
, "%sMetadata:\n", indent
);
2697 while((tag
=av_dict_get(m
, "", tag
, AV_DICT_IGNORE_SUFFIX
))) {
2698 if(strcmp("language", tag
->key
))
2699 av_log(ctx
, AV_LOG_INFO
, "%s %-16s: %s\n", indent
, tag
->key
, tag
->value
);
2704 /* "user interface" functions */
2705 static void dump_stream_format(AVFormatContext
*ic
, int i
, int index
, int is_output
)
2708 int flags
= (is_output ? ic
->oformat
->flags
: ic
->iformat
->flags
);
2709 AVStream
*st
= ic
->streams
[i
];
2710 int g
= av_gcd(st
->time_base
.num
, st
->time_base
.den
);
2711 AVDictionaryEntry
*lang
= av_dict_get(st
->metadata
, "language", NULL
, 0);
2712 avcodec_string(buf
, sizeof(buf
), st
->codec
, is_output
);
2713 av_log(NULL
, AV_LOG_INFO
, " Stream #%d.%d", index
, i
);
2714 /* the pid is an important information, so we display it */
2715 /* XXX: add a generic system */
2716 if (flags
& AVFMT_SHOW_IDS
)
2717 av_log(NULL
, AV_LOG_INFO
, "[0x%x]", st
->id
);
2719 av_log(NULL
, AV_LOG_INFO
, "(%s)", lang
->value
);
2720 av_log(NULL
, AV_LOG_DEBUG
, ", %d, %d/%d", st
->codec_info_nb_frames
, st
->time_base
.num
/g
, st
->time_base
.den
/g
);
2721 av_log(NULL
, AV_LOG_INFO
, ": %s", buf
);
2722 if (st
->sample_aspect_ratio
.num
&& // default
2723 av_cmp_q(st
->sample_aspect_ratio
, st
->codec
->sample_aspect_ratio
)) {
2724 AVRational display_aspect_ratio
;
2725 av_reduce(&display_aspect_ratio
.num
, &display_aspect_ratio
.den
,
2726 st
->codec
->width
*st
->sample_aspect_ratio
.num
,
2727 st
->codec
->height
*st
->sample_aspect_ratio
.den
,
2729 av_log(NULL
, AV_LOG_INFO
, ", PAR %d:%d DAR %d:%d",
2730 st
->sample_aspect_ratio
.num
, st
->sample_aspect_ratio
.den
,
2731 display_aspect_ratio
.num
, display_aspect_ratio
.den
);
2733 if(st
->codec
->codec_type
== AVMEDIA_TYPE_VIDEO
){
2734 if(st
->avg_frame_rate
.den
&& st
->avg_frame_rate
.num
)
2735 print_fps(av_q2d(st
->avg_frame_rate
), "fps");
2736 if(st
->time_base
.den
&& st
->time_base
.num
)
2737 print_fps(1/av_q2d(st
->time_base
), "tbn");
2738 if(st
->codec
->time_base
.den
&& st
->codec
->time_base
.num
)
2739 print_fps(1/av_q2d(st
->codec
->time_base
), "tbc");
2741 if (st
->disposition
& AV_DISPOSITION_DEFAULT
)
2742 av_log(NULL
, AV_LOG_INFO
, " (default)");
2743 if (st
->disposition
& AV_DISPOSITION_DUB
)
2744 av_log(NULL
, AV_LOG_INFO
, " (dub)");
2745 if (st
->disposition
& AV_DISPOSITION_ORIGINAL
)
2746 av_log(NULL
, AV_LOG_INFO
, " (original)");
2747 if (st
->disposition
& AV_DISPOSITION_COMMENT
)
2748 av_log(NULL
, AV_LOG_INFO
, " (comment)");
2749 if (st
->disposition
& AV_DISPOSITION_LYRICS
)
2750 av_log(NULL
, AV_LOG_INFO
, " (lyrics)");
2751 if (st
->disposition
& AV_DISPOSITION_KARAOKE
)
2752 av_log(NULL
, AV_LOG_INFO
, " (karaoke)");
2753 if (st
->disposition
& AV_DISPOSITION_FORCED
)
2754 av_log(NULL
, AV_LOG_INFO
, " (forced)");
2755 if (st
->disposition
& AV_DISPOSITION_HEARING_IMPAIRED
)
2756 av_log(NULL
, AV_LOG_INFO
, " (hearing impaired)");
2757 if (st
->disposition
& AV_DISPOSITION_VISUAL_IMPAIRED
)
2758 av_log(NULL
, AV_LOG_INFO
, " (visual impaired)");
2759 if (st
->disposition
& AV_DISPOSITION_CLEAN_EFFECTS
)
2760 av_log(NULL
, AV_LOG_INFO
, " (clean effects)");
2761 av_log(NULL
, AV_LOG_INFO
, "\n");
2762 dump_metadata(NULL
, st
->metadata
, " ");
2765 void av_dump_format(AVFormatContext
*ic
,
2771 uint8_t *printed
= ic
->nb_streams ?
av_mallocz(ic
->nb_streams
) : NULL
;
2772 if (ic
->nb_streams
&& !printed
)
2775 av_log(NULL
, AV_LOG_INFO
, "%s #%d, %s, %s '%s':\n",
2776 is_output ?
"Output" : "Input",
2778 is_output ? ic
->oformat
->name
: ic
->iformat
->name
,
2779 is_output ?
"to" : "from", url
);
2780 dump_metadata(NULL
, ic
->metadata
, " ");
2782 av_log(NULL
, AV_LOG_INFO
, " Duration: ");
2783 if (ic
->duration
!= AV_NOPTS_VALUE
) {
2784 int hours
, mins
, secs
, us
;
2785 secs
= ic
->duration
/ AV_TIME_BASE
;
2786 us
= ic
->duration
% AV_TIME_BASE
;
2791 av_log(NULL
, AV_LOG_INFO
, "%02d:%02d:%02d.%02d", hours
, mins
, secs
,
2792 (100 * us
) / AV_TIME_BASE
);
2794 av_log(NULL
, AV_LOG_INFO
, "N/A");
2796 if (ic
->start_time
!= AV_NOPTS_VALUE
) {
2798 av_log(NULL
, AV_LOG_INFO
, ", start: ");
2799 secs
= ic
->start_time
/ AV_TIME_BASE
;
2800 us
= abs(ic
->start_time
% AV_TIME_BASE
);
2801 av_log(NULL
, AV_LOG_INFO
, "%d.%06d",
2802 secs
, (int)av_rescale(us
, 1000000, AV_TIME_BASE
));
2804 av_log(NULL
, AV_LOG_INFO
, ", bitrate: ");
2806 av_log(NULL
, AV_LOG_INFO
,"%d kb/s", ic
->bit_rate
/ 1000);
2808 av_log(NULL
, AV_LOG_INFO
, "N/A");
2810 av_log(NULL
, AV_LOG_INFO
, "\n");
2812 for (i
= 0; i
< ic
->nb_chapters
; i
++) {
2813 AVChapter
*ch
= ic
->chapters
[i
];
2814 av_log(NULL
, AV_LOG_INFO
, " Chapter #%d.%d: ", index
, i
);
2815 av_log(NULL
, AV_LOG_INFO
, "start %f, ", ch
->start
* av_q2d(ch
->time_base
));
2816 av_log(NULL
, AV_LOG_INFO
, "end %f\n", ch
->end
* av_q2d(ch
->time_base
));
2818 dump_metadata(NULL
, ch
->metadata
, " ");
2820 if(ic
->nb_programs
) {
2821 int j
, k
, total
= 0;
2822 for(j
=0; j
<ic
->nb_programs
; j
++) {
2823 AVDictionaryEntry
*name
= av_dict_get(ic
->programs
[j
]->metadata
,
2825 av_log(NULL
, AV_LOG_INFO
, " Program %d %s\n", ic
->programs
[j
]->id
,
2826 name ? name
->value
: "");
2827 dump_metadata(NULL
, ic
->programs
[j
]->metadata
, " ");
2828 for(k
=0; k
<ic
->programs
[j
]->nb_stream_indexes
; k
++) {
2829 dump_stream_format(ic
, ic
->programs
[j
]->stream_index
[k
], index
, is_output
);
2830 printed
[ic
->programs
[j
]->stream_index
[k
]] = 1;
2832 total
+= ic
->programs
[j
]->nb_stream_indexes
;
2834 if (total
< ic
->nb_streams
)
2835 av_log(NULL
, AV_LOG_INFO
, " No Program\n");
2837 for(i
=0;i
<ic
->nb_streams
;i
++)
2839 dump_stream_format(ic
, i
, index
, is_output
);
2844 uint64_t ff_ntp_time(void)
2846 return (av_gettime() / 1000) * 1000 + NTP_OFFSET_US
;
2849 int av_get_frame_filename(char *buf
, int buf_size
,
2850 const char *path
, int number
)
2853 char *q
, buf1
[20], c
;
2854 int nd
, len
, percentd_found
;
2866 while (av_isdigit(*p
)) {
2867 nd
= nd
* 10 + *p
++ - '0';
2870 } while (av_isdigit(c
));
2879 snprintf(buf1
, sizeof(buf1
), "%0*d", nd
, number
);
2881 if ((q
- buf
+ len
) > buf_size
- 1)
2883 memcpy(q
, buf1
, len
);
2891 if ((q
- buf
) < buf_size
- 1)
2895 if (!percentd_found
)
2904 static void hex_dump_internal(void *avcl
, FILE *f
, int level
,
2905 const uint8_t *buf
, int size
)
2908 #define PRINT(...) do { if (!f) av_log(avcl, level, __VA_ARGS__); else fprintf(f, __VA_ARGS__); } while(0)
2910 for(i
=0;i
<size
;i
+=16) {
2917 PRINT(" %02x", buf
[i
+j
]);
2922 for(j
=0;j
<len
;j
++) {
2924 if (c
< ' ' || c
> '~')
2933 void av_hex_dump(FILE *f
, const uint8_t *buf
, int size
)
2935 hex_dump_internal(NULL
, f
, 0, buf
, size
);
2938 void av_hex_dump_log(void *avcl
, int level
, const uint8_t *buf
, int size
)
2940 hex_dump_internal(avcl
, NULL
, level
, buf
, size
);
2943 static void pkt_dump_internal(void *avcl
, FILE *f
, int level
, AVPacket
*pkt
, int dump_payload
, AVRational time_base
)
2945 #define PRINT(...) do { if (!f) av_log(avcl, level, __VA_ARGS__); else fprintf(f, __VA_ARGS__); } while(0)
2946 PRINT("stream #%d:\n", pkt
->stream_index
);
2947 PRINT(" keyframe=%d\n", ((pkt
->flags
& AV_PKT_FLAG_KEY
) != 0));
2948 PRINT(" duration=%0.3f\n", pkt
->duration
* av_q2d(time_base
));
2949 /* DTS is _always_ valid after av_read_frame() */
2951 if (pkt
->dts
== AV_NOPTS_VALUE
)
2954 PRINT("%0.3f", pkt
->dts
* av_q2d(time_base
));
2955 /* PTS may not be known if B-frames are present. */
2957 if (pkt
->pts
== AV_NOPTS_VALUE
)
2960 PRINT("%0.3f", pkt
->pts
* av_q2d(time_base
));
2962 PRINT(" size=%d\n", pkt
->size
);
2965 av_hex_dump(f
, pkt
->data
, pkt
->size
);
2968 void av_pkt_dump2(FILE *f
, AVPacket
*pkt
, int dump_payload
, AVStream
*st
)
2970 pkt_dump_internal(NULL
, f
, 0, pkt
, dump_payload
, st
->time_base
);
2973 void av_pkt_dump_log2(void *avcl
, int level
, AVPacket
*pkt
, int dump_payload
,
2976 pkt_dump_internal(avcl
, NULL
, level
, pkt
, dump_payload
, st
->time_base
);
2979 void av_url_split(char *proto
, int proto_size
,
2980 char *authorization
, int authorization_size
,
2981 char *hostname
, int hostname_size
,
2983 char *path
, int path_size
,
2986 const char *p
, *ls
, *at
, *col
, *brk
;
2988 if (port_ptr
) *port_ptr
= -1;
2989 if (proto_size
> 0) proto
[0] = 0;
2990 if (authorization_size
> 0) authorization
[0] = 0;
2991 if (hostname_size
> 0) hostname
[0] = 0;
2992 if (path_size
> 0) path
[0] = 0;
2994 /* parse protocol */
2995 if ((p
= strchr(url
, ':'))) {
2996 av_strlcpy(proto
, url
, FFMIN(proto_size
, p
+ 1 - url
));
3001 /* no protocol means plain filename */
3002 av_strlcpy(path
, url
, path_size
);
3006 /* separate path from hostname */
3007 ls
= strchr(p
, '/');
3009 ls
= strchr(p
, '?');
3011 av_strlcpy(path
, ls
, path_size
);
3013 ls
= &p
[strlen(p
)]; // XXX
3015 /* the rest is hostname, use that to parse auth/port */
3017 /* authorization (user[:pass]@hostname) */
3018 if ((at
= strchr(p
, '@')) && at
< ls
) {
3019 av_strlcpy(authorization
, p
,
3020 FFMIN(authorization_size
, at
+ 1 - p
));
3021 p
= at
+ 1; /* skip '@' */
3024 if (*p
== '[' && (brk
= strchr(p
, ']')) && brk
< ls
) {
3026 av_strlcpy(hostname
, p
+ 1,
3027 FFMIN(hostname_size
, brk
- p
));
3028 if (brk
[1] == ':' && port_ptr
)
3029 *port_ptr
= atoi(brk
+ 2);
3030 } else if ((col
= strchr(p
, ':')) && col
< ls
) {
3031 av_strlcpy(hostname
, p
,
3032 FFMIN(col
+ 1 - p
, hostname_size
));
3033 if (port_ptr
) *port_ptr
= atoi(col
+ 1);
3035 av_strlcpy(hostname
, p
,
3036 FFMIN(ls
+ 1 - p
, hostname_size
));
3040 char *ff_data_to_hex(char *buff
, const uint8_t *src
, int s
, int lowercase
)
3043 static const char hex_table_uc
[16] = { '0', '1', '2', '3',
3046 'C', 'D', 'E', 'F' };
3047 static const char hex_table_lc
[16] = { '0', '1', '2', '3',
3050 'c', 'd', 'e', 'f' };
3051 const char *hex_table
= lowercase ? hex_table_lc
: hex_table_uc
;
3053 for(i
= 0; i
< s
; i
++) {
3054 buff
[i
* 2] = hex_table
[src
[i
] >> 4];
3055 buff
[i
* 2 + 1] = hex_table
[src
[i
] & 0xF];
3061 int ff_hex_to_data(uint8_t *data
, const char *p
)