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
: "" };
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;
267 /* read probe data */
268 if ((ret
= av_reallocp(&buf
, probe_size
+ AVPROBE_PADDING_SIZE
)) < 0)
270 if ((ret
= avio_read(pb
, buf
+ pd
.buf_size
, probe_size
- pd
.buf_size
)) < 0) {
271 /* fail if error was not end of file, otherwise, lower score */
272 if (ret
!= AVERROR_EOF
) {
277 ret
= 0; /* error was end of file, nothing read */
282 memset(pd
.buf
+ pd
.buf_size
, 0, AVPROBE_PADDING_SIZE
);
284 /* guess file format */
285 *fmt
= av_probe_input_format2(&pd
, 1, &score
);
287 if(score
<= AVPROBE_SCORE_MAX
/4){ //this can only be true in the last iteration
288 av_log(logctx
, AV_LOG_WARNING
, "Format detected only with low score of %d, misdetection possible!\n", score
);
290 av_log(logctx
, AV_LOG_DEBUG
, "Probed with size=%d and score=%d\n", probe_size
, score
);
296 return AVERROR_INVALIDDATA
;
299 /* rewind. reuse probe buffer to avoid seeking */
300 if ((ret
= ffio_rewind_with_probe_data(pb
, buf
, pd
.buf_size
)) < 0)
306 /* open input file and probe the format if necessary */
307 static int init_input(AVFormatContext
*s
, const char *filename
, AVDictionary
**options
)
310 AVProbeData pd
= {filename
, NULL
, 0};
313 s
->flags
|= AVFMT_FLAG_CUSTOM_IO
;
315 return av_probe_input_buffer(s
->pb
, &s
->iformat
, filename
, s
, 0, s
->probesize
);
316 else if (s
->iformat
->flags
& AVFMT_NOFILE
)
317 return AVERROR(EINVAL
);
321 if ( (s
->iformat
&& s
->iformat
->flags
& AVFMT_NOFILE
) ||
322 (!s
->iformat
&& (s
->iformat
= av_probe_input_format(&pd
, 0))))
325 if ((ret
= avio_open2(&s
->pb
, filename
, AVIO_FLAG_READ
,
326 &s
->interrupt_callback
, options
)) < 0)
330 return av_probe_input_buffer(s
->pb
, &s
->iformat
, filename
, s
, 0, s
->probesize
);
333 static AVPacket
*add_to_pktbuf(AVPacketList
**packet_buffer
, AVPacket
*pkt
,
334 AVPacketList
**plast_pktl
){
335 AVPacketList
*pktl
= av_mallocz(sizeof(AVPacketList
));
340 (*plast_pktl
)->next
= pktl
;
342 *packet_buffer
= pktl
;
344 /* add the packet in the buffered packet list */
350 static int queue_attached_pictures(AVFormatContext
*s
)
353 for (i
= 0; i
< s
->nb_streams
; i
++)
354 if (s
->streams
[i
]->disposition
& AV_DISPOSITION_ATTACHED_PIC
&&
355 s
->streams
[i
]->discard
< AVDISCARD_ALL
) {
356 AVPacket copy
= s
->streams
[i
]->attached_pic
;
357 copy
.buf
= av_buffer_ref(copy
.buf
);
359 return AVERROR(ENOMEM
);
361 add_to_pktbuf(&s
->raw_packet_buffer
, ©
, &s
->raw_packet_buffer_end
);
366 int avformat_open_input(AVFormatContext
**ps
, const char *filename
, AVInputFormat
*fmt
, AVDictionary
**options
)
368 AVFormatContext
*s
= *ps
;
370 AVDictionary
*tmp
= NULL
;
371 ID3v2ExtraMeta
*id3v2_extra_meta
= NULL
;
373 if (!s
&& !(s
= avformat_alloc_context()))
374 return AVERROR(ENOMEM
);
379 av_dict_copy(&tmp
, *options
, 0);
381 if ((ret
= av_opt_set_dict(s
, &tmp
)) < 0)
384 if ((ret
= init_input(s
, filename
, &tmp
)) < 0)
387 /* check filename in case an image number is expected */
388 if (s
->iformat
->flags
& AVFMT_NEEDNUMBER
) {
389 if (!av_filename_number_test(filename
)) {
390 ret
= AVERROR(EINVAL
);
395 s
->duration
= s
->start_time
= AV_NOPTS_VALUE
;
396 av_strlcpy(s
->filename
, filename ? filename
: "", sizeof(s
->filename
));
398 /* allocate private data */
399 if (s
->iformat
->priv_data_size
> 0) {
400 if (!(s
->priv_data
= av_mallocz(s
->iformat
->priv_data_size
))) {
401 ret
= AVERROR(ENOMEM
);
404 if (s
->iformat
->priv_class
) {
405 *(const AVClass
**)s
->priv_data
= s
->iformat
->priv_class
;
406 av_opt_set_defaults(s
->priv_data
);
407 if ((ret
= av_opt_set_dict(s
->priv_data
, &tmp
)) < 0)
412 /* e.g. AVFMT_NOFILE formats will not have a AVIOContext */
414 ff_id3v2_read(s
, ID3v2_DEFAULT_MAGIC
, &id3v2_extra_meta
);
416 if (s
->iformat
->read_header
)
417 if ((ret
= s
->iformat
->read_header(s
)) < 0)
420 if (id3v2_extra_meta
&&
421 (ret
= ff_id3v2_parse_apic(s
, &id3v2_extra_meta
)) < 0)
423 ff_id3v2_free_extra_meta(&id3v2_extra_meta
);
425 if ((ret
= queue_attached_pictures(s
)) < 0)
428 if (s
->pb
&& !s
->data_offset
)
429 s
->data_offset
= avio_tell(s
->pb
);
431 s
->raw_packet_buffer_remaining_size
= RAW_PACKET_BUFFER_SIZE
;
434 av_dict_free(options
);
441 ff_id3v2_free_extra_meta(&id3v2_extra_meta
);
443 if (s
->pb
&& !(s
->flags
& AVFMT_FLAG_CUSTOM_IO
))
445 avformat_free_context(s
);
450 /*******************************************************/
452 static int probe_codec(AVFormatContext
*s
, AVStream
*st
, const AVPacket
*pkt
)
454 if(st
->codec
->codec_id
== AV_CODEC_ID_PROBE
){
455 AVProbeData
*pd
= &st
->probe_data
;
456 av_log(s
, AV_LOG_DEBUG
, "probing stream %d\n", st
->index
);
461 if ((err
= av_reallocp(&pd
->buf
, pd
->buf_size
+ pkt
->size
+
462 AVPROBE_PADDING_SIZE
)) < 0)
464 memcpy(pd
->buf
+pd
->buf_size
, pkt
->data
, pkt
->size
);
465 pd
->buf_size
+= pkt
->size
;
466 memset(pd
->buf
+pd
->buf_size
, 0, AVPROBE_PADDING_SIZE
);
468 st
->probe_packets
= 0;
470 av_log(s
, AV_LOG_ERROR
, "nothing to probe for stream %d\n",
476 if (!st
->probe_packets
||
477 av_log2(pd
->buf_size
) != av_log2(pd
->buf_size
- pkt
->size
)) {
478 set_codec_from_probe_data(s
, st
, pd
, st
->probe_packets
> 0 ? AVPROBE_SCORE_MAX
/4 : 0);
479 if(st
->codec
->codec_id
!= AV_CODEC_ID_PROBE
){
482 av_log(s
, AV_LOG_DEBUG
, "probed stream %d\n", st
->index
);
489 int ff_read_packet(AVFormatContext
*s
, AVPacket
*pkt
)
495 AVPacketList
*pktl
= s
->raw_packet_buffer
;
499 st
= s
->streams
[pkt
->stream_index
];
500 if (st
->codec
->codec_id
!= AV_CODEC_ID_PROBE
|| !st
->probe_packets
||
501 s
->raw_packet_buffer_remaining_size
< pkt
->size
) {
503 if (st
->probe_packets
) {
504 if ((err
= probe_codec(s
, st
, NULL
)) < 0)
507 pd
= &st
->probe_data
;
510 s
->raw_packet_buffer
= pktl
->next
;
511 s
->raw_packet_buffer_remaining_size
+= pkt
->size
;
520 ret
= s
->iformat
->read_packet(s
, pkt
);
522 if (!pktl
|| ret
== AVERROR(EAGAIN
))
524 for (i
= 0; i
< s
->nb_streams
; i
++) {
526 if (st
->probe_packets
) {
527 if ((err
= probe_codec(s
, st
, NULL
)) < 0)
534 if ((s
->flags
& AVFMT_FLAG_DISCARD_CORRUPT
) &&
535 (pkt
->flags
& AV_PKT_FLAG_CORRUPT
)) {
536 av_log(s
, AV_LOG_WARNING
,
537 "Dropped corrupted packet (stream = %d)\n",
543 st
= s
->streams
[pkt
->stream_index
];
545 switch(st
->codec
->codec_type
){
546 case AVMEDIA_TYPE_VIDEO
:
547 if(s
->video_codec_id
) st
->codec
->codec_id
= s
->video_codec_id
;
549 case AVMEDIA_TYPE_AUDIO
:
550 if(s
->audio_codec_id
) st
->codec
->codec_id
= s
->audio_codec_id
;
552 case AVMEDIA_TYPE_SUBTITLE
:
553 if(s
->subtitle_codec_id
)st
->codec
->codec_id
= s
->subtitle_codec_id
;
557 if(!pktl
&& (st
->codec
->codec_id
!= AV_CODEC_ID_PROBE
||
561 add_to_pktbuf(&s
->raw_packet_buffer
, pkt
, &s
->raw_packet_buffer_end
);
562 s
->raw_packet_buffer_remaining_size
-= pkt
->size
;
564 if ((err
= probe_codec(s
, st
, pkt
)) < 0)
569 /**********************************************************/
572 * Get the number of samples of an audio frame. Return -1 on error.
574 int ff_get_audio_frame_size(AVCodecContext
*enc
, int size
, int mux
)
578 /* give frame_size priority if demuxing */
579 if (!mux
&& enc
->frame_size
> 1)
580 return enc
->frame_size
;
582 if ((frame_size
= av_get_audio_frame_duration(enc
, size
)) > 0)
585 /* Fall back on using frame_size if muxing. */
586 if (enc
->frame_size
> 1)
587 return enc
->frame_size
;
594 * Return the frame duration in seconds. Return 0 if not available.
596 void ff_compute_frame_duration(int *pnum
, int *pden
, AVStream
*st
,
597 AVCodecParserContext
*pc
, AVPacket
*pkt
)
603 switch(st
->codec
->codec_type
) {
604 case AVMEDIA_TYPE_VIDEO
:
605 if (st
->avg_frame_rate
.num
) {
606 *pnum
= st
->avg_frame_rate
.den
;
607 *pden
= st
->avg_frame_rate
.num
;
608 } else if(st
->time_base
.num
*1000LL > st
->time_base
.den
) {
609 *pnum
= st
->time_base
.num
;
610 *pden
= st
->time_base
.den
;
611 }else if(st
->codec
->time_base
.num
*1000LL > st
->codec
->time_base
.den
){
612 *pnum
= st
->codec
->time_base
.num
;
613 *pden
= st
->codec
->time_base
.den
;
614 if (pc
&& pc
->repeat_pict
) {
615 if (*pnum
> INT_MAX
/ (1 + pc
->repeat_pict
))
616 *pden
/= 1 + pc
->repeat_pict
;
618 *pnum
*= 1 + pc
->repeat_pict
;
620 //If this codec can be interlaced or progressive then we need a parser to compute duration of a packet
621 //Thus if we have no parser in such case leave duration undefined.
622 if(st
->codec
->ticks_per_frame
>1 && !pc
){
627 case AVMEDIA_TYPE_AUDIO
:
628 frame_size
= ff_get_audio_frame_size(st
->codec
, pkt
->size
, 0);
629 if (frame_size
<= 0 || st
->codec
->sample_rate
<= 0)
632 *pden
= st
->codec
->sample_rate
;
639 static int is_intra_only(enum AVCodecID id
)
641 const AVCodecDescriptor
*d
= avcodec_descriptor_get(id
);
644 if (d
->type
== AVMEDIA_TYPE_VIDEO
&& !(d
->props
& AV_CODEC_PROP_INTRA_ONLY
))
649 static void update_initial_timestamps(AVFormatContext
*s
, int stream_index
,
650 int64_t dts
, int64_t pts
)
652 AVStream
*st
= s
->streams
[stream_index
];
653 AVPacketList
*pktl
= s
->packet_buffer
;
655 if(st
->first_dts
!= AV_NOPTS_VALUE
|| dts
== AV_NOPTS_VALUE
|| st
->cur_dts
== AV_NOPTS_VALUE
)
658 st
->first_dts
= dts
- st
->cur_dts
;
661 for(; pktl
; pktl
= pktl
->next
){
662 if(pktl
->pkt
.stream_index
!= stream_index
)
664 //FIXME think more about this check
665 if(pktl
->pkt
.pts
!= AV_NOPTS_VALUE
&& pktl
->pkt
.pts
== pktl
->pkt
.dts
)
666 pktl
->pkt
.pts
+= st
->first_dts
;
668 if(pktl
->pkt
.dts
!= AV_NOPTS_VALUE
)
669 pktl
->pkt
.dts
+= st
->first_dts
;
671 if(st
->start_time
== AV_NOPTS_VALUE
&& pktl
->pkt
.pts
!= AV_NOPTS_VALUE
)
672 st
->start_time
= pktl
->pkt
.pts
;
674 if (st
->start_time
== AV_NOPTS_VALUE
)
675 st
->start_time
= pts
;
678 static void update_initial_durations(AVFormatContext
*s
, AVStream
*st
,
679 int stream_index
, int duration
)
681 AVPacketList
*pktl
= s
->packet_buffer
;
684 if(st
->first_dts
!= AV_NOPTS_VALUE
){
685 cur_dts
= st
->first_dts
;
686 for(; pktl
; pktl
= pktl
->next
){
687 if(pktl
->pkt
.stream_index
== stream_index
){
688 if(pktl
->pkt
.pts
!= pktl
->pkt
.dts
|| pktl
->pkt
.dts
!= AV_NOPTS_VALUE
|| pktl
->pkt
.duration
)
693 pktl
= s
->packet_buffer
;
694 st
->first_dts
= cur_dts
;
695 }else if(st
->cur_dts
)
698 for(; pktl
; pktl
= pktl
->next
){
699 if(pktl
->pkt
.stream_index
!= stream_index
)
701 if(pktl
->pkt
.pts
== pktl
->pkt
.dts
&& pktl
->pkt
.dts
== AV_NOPTS_VALUE
702 && !pktl
->pkt
.duration
){
703 pktl
->pkt
.dts
= cur_dts
;
704 if(!st
->codec
->has_b_frames
)
705 pktl
->pkt
.pts
= cur_dts
;
707 if (st
->codec
->codec_type
!= AVMEDIA_TYPE_AUDIO
)
708 pktl
->pkt
.duration
= duration
;
712 if(st
->first_dts
== AV_NOPTS_VALUE
)
713 st
->cur_dts
= cur_dts
;
716 static void compute_pkt_fields(AVFormatContext
*s
, AVStream
*st
,
717 AVCodecParserContext
*pc
, AVPacket
*pkt
)
719 int num
, den
, presentation_delayed
, delay
, i
;
722 if (s
->flags
& AVFMT_FLAG_NOFILLIN
)
725 if((s
->flags
& AVFMT_FLAG_IGNDTS
) && pkt
->pts
!= AV_NOPTS_VALUE
)
726 pkt
->dts
= AV_NOPTS_VALUE
;
728 /* do we have a video B-frame ? */
729 delay
= st
->codec
->has_b_frames
;
730 presentation_delayed
= 0;
732 /* XXX: need has_b_frame, but cannot get it if the codec is
735 pc
&& pc
->pict_type
!= AV_PICTURE_TYPE_B
)
736 presentation_delayed
= 1;
738 if (pkt
->pts
!= AV_NOPTS_VALUE
&& pkt
->dts
!= AV_NOPTS_VALUE
&&
739 st
->pts_wrap_bits
< 63 &&
740 pkt
->dts
- (1LL << (st
->pts_wrap_bits
- 1)) > pkt
->pts
) {
741 pkt
->dts
-= 1LL<<st
->pts_wrap_bits
;
744 // some mpeg2 in mpeg-ps lack dts (issue171 / input_file.mpg)
745 // we take the conservative approach and discard both
746 // Note, if this is misbehaving for a H.264 file then possibly presentation_delayed is not set correctly.
747 if(delay
==1 && pkt
->dts
== pkt
->pts
&& pkt
->dts
!= AV_NOPTS_VALUE
&& presentation_delayed
){
748 av_log(s
, AV_LOG_DEBUG
, "invalid dts/pts combination\n");
749 pkt
->dts
= pkt
->pts
= AV_NOPTS_VALUE
;
752 if (pkt
->duration
== 0 && st
->codec
->codec_type
!= AVMEDIA_TYPE_AUDIO
) {
753 ff_compute_frame_duration(&num
, &den
, st
, pc
, pkt
);
755 pkt
->duration
= av_rescale_rnd(1, num
* (int64_t)st
->time_base
.den
, den
* (int64_t)st
->time_base
.num
, AV_ROUND_DOWN
);
757 if(pkt
->duration
!= 0 && s
->packet_buffer
)
758 update_initial_durations(s
, st
, pkt
->stream_index
, pkt
->duration
);
762 /* correct timestamps with byte offset if demuxers only have timestamps
763 on packet boundaries */
764 if(pc
&& st
->need_parsing
== AVSTREAM_PARSE_TIMESTAMPS
&& pkt
->size
){
765 /* this will estimate bitrate based on this frame's duration and size */
766 offset
= av_rescale(pc
->offset
, pkt
->duration
, pkt
->size
);
767 if(pkt
->pts
!= AV_NOPTS_VALUE
)
769 if(pkt
->dts
!= AV_NOPTS_VALUE
)
773 /* This may be redundant, but it should not hurt. */
774 if(pkt
->dts
!= AV_NOPTS_VALUE
&& pkt
->pts
!= AV_NOPTS_VALUE
&& pkt
->pts
> pkt
->dts
)
775 presentation_delayed
= 1;
778 "IN delayed:%d pts:%"PRId64
", dts:%"PRId64
" cur_dts:%"PRId64
" st:%d pc:%p\n",
779 presentation_delayed
, pkt
->pts
, pkt
->dts
, st
->cur_dts
,
780 pkt
->stream_index
, pc
);
781 /* interpolate PTS and DTS if they are not present */
782 //We skip H264 currently because delay and has_b_frames are not reliably set
783 if((delay
==0 || (delay
==1 && pc
)) && st
->codec
->codec_id
!= AV_CODEC_ID_H264
){
784 if (presentation_delayed
) {
785 /* DTS = decompression timestamp */
786 /* PTS = presentation timestamp */
787 if (pkt
->dts
== AV_NOPTS_VALUE
)
788 pkt
->dts
= st
->last_IP_pts
;
789 update_initial_timestamps(s
, pkt
->stream_index
, pkt
->dts
, pkt
->pts
);
790 if (pkt
->dts
== AV_NOPTS_VALUE
)
791 pkt
->dts
= st
->cur_dts
;
793 /* this is tricky: the dts must be incremented by the duration
794 of the frame we are displaying, i.e. the last I- or P-frame */
795 if (st
->last_IP_duration
== 0)
796 st
->last_IP_duration
= pkt
->duration
;
797 if(pkt
->dts
!= AV_NOPTS_VALUE
)
798 st
->cur_dts
= pkt
->dts
+ st
->last_IP_duration
;
799 st
->last_IP_duration
= pkt
->duration
;
800 st
->last_IP_pts
= pkt
->pts
;
801 /* cannot compute PTS if not present (we can compute it only
802 by knowing the future */
803 } else if (pkt
->pts
!= AV_NOPTS_VALUE
||
804 pkt
->dts
!= AV_NOPTS_VALUE
||
806 st
->codec
->codec_type
== AVMEDIA_TYPE_AUDIO
) {
807 int duration
= pkt
->duration
;
808 if (!duration
&& st
->codec
->codec_type
== AVMEDIA_TYPE_AUDIO
) {
809 ff_compute_frame_duration(&num
, &den
, st
, pc
, pkt
);
811 duration
= av_rescale_rnd(1, num
* (int64_t)st
->time_base
.den
,
812 den
* (int64_t)st
->time_base
.num
,
814 if (duration
!= 0 && s
->packet_buffer
) {
815 update_initial_durations(s
, st
, pkt
->stream_index
,
821 if (pkt
->pts
!= AV_NOPTS_VALUE
|| pkt
->dts
!= AV_NOPTS_VALUE
||
823 /* presentation is not delayed : PTS and DTS are the same */
824 if (pkt
->pts
== AV_NOPTS_VALUE
)
826 update_initial_timestamps(s
, pkt
->stream_index
, pkt
->pts
,
828 if (pkt
->pts
== AV_NOPTS_VALUE
)
829 pkt
->pts
= st
->cur_dts
;
831 if (pkt
->pts
!= AV_NOPTS_VALUE
)
832 st
->cur_dts
= pkt
->pts
+ duration
;
837 if(pkt
->pts
!= AV_NOPTS_VALUE
&& delay
<= MAX_REORDER_DELAY
){
838 st
->pts_buffer
[0]= pkt
->pts
;
839 for(i
=0; i
<delay
&& st
->pts_buffer
[i
] > st
->pts_buffer
[i
+1]; i
++)
840 FFSWAP(int64_t, st
->pts_buffer
[i
], st
->pts_buffer
[i
+1]);
841 if(pkt
->dts
== AV_NOPTS_VALUE
)
842 pkt
->dts
= st
->pts_buffer
[0];
843 if(st
->codec
->codec_id
== AV_CODEC_ID_H264
){ // we skipped it above so we try here
844 update_initial_timestamps(s
, pkt
->stream_index
, pkt
->dts
, pkt
->pts
); // this should happen on the first packet
846 if(pkt
->dts
> st
->cur_dts
)
847 st
->cur_dts
= pkt
->dts
;
851 "OUTdelayed:%d/%d pts:%"PRId64
", dts:%"PRId64
" cur_dts:%"PRId64
"\n",
852 presentation_delayed
, delay
, pkt
->pts
, pkt
->dts
, st
->cur_dts
);
855 if (is_intra_only(st
->codec
->codec_id
))
856 pkt
->flags
|= AV_PKT_FLAG_KEY
;
858 pkt
->convergence_duration
= pc
->convergence_duration
;
861 static void free_packet_buffer(AVPacketList
**pkt_buf
, AVPacketList
**pkt_buf_end
)
864 AVPacketList
*pktl
= *pkt_buf
;
865 *pkt_buf
= pktl
->next
;
866 av_free_packet(&pktl
->pkt
);
873 * Parse a packet, add all split parts to parse_queue
875 * @param pkt packet to parse, NULL when flushing the parser at end of stream
877 static int parse_packet(AVFormatContext
*s
, AVPacket
*pkt
, int stream_index
)
879 AVPacket out_pkt
= { 0 }, flush_pkt
= { 0 };
880 AVStream
*st
= s
->streams
[stream_index
];
881 uint8_t *data
= pkt ? pkt
->data
: NULL
;
882 int size
= pkt ? pkt
->size
: 0;
883 int ret
= 0, got_output
= 0;
886 av_init_packet(&flush_pkt
);
891 while (size
> 0 || (pkt
== &flush_pkt
&& got_output
)) {
894 av_init_packet(&out_pkt
);
895 len
= av_parser_parse2(st
->parser
, st
->codec
,
896 &out_pkt
.data
, &out_pkt
.size
, data
, size
,
897 pkt
->pts
, pkt
->dts
, pkt
->pos
);
899 pkt
->pts
= pkt
->dts
= AV_NOPTS_VALUE
;
900 /* increment read pointer */
904 got_output
= !!out_pkt
.size
;
909 if (pkt
->side_data
) {
910 out_pkt
.side_data
= pkt
->side_data
;
911 out_pkt
.side_data_elems
= pkt
->side_data_elems
;
912 pkt
->side_data
= NULL
;
913 pkt
->side_data_elems
= 0;
916 /* set the duration */
917 out_pkt
.duration
= 0;
918 if (st
->codec
->codec_type
== AVMEDIA_TYPE_AUDIO
) {
919 if (st
->codec
->sample_rate
> 0) {
920 out_pkt
.duration
= av_rescale_q_rnd(st
->parser
->duration
,
921 (AVRational
){ 1, st
->codec
->sample_rate
},
925 } else if (st
->codec
->time_base
.num
!= 0 &&
926 st
->codec
->time_base
.den
!= 0) {
927 out_pkt
.duration
= av_rescale_q_rnd(st
->parser
->duration
,
928 st
->codec
->time_base
,
933 out_pkt
.stream_index
= st
->index
;
934 out_pkt
.pts
= st
->parser
->pts
;
935 out_pkt
.dts
= st
->parser
->dts
;
936 out_pkt
.pos
= st
->parser
->pos
;
938 if (st
->parser
->key_frame
== 1 ||
939 (st
->parser
->key_frame
== -1 &&
940 st
->parser
->pict_type
== AV_PICTURE_TYPE_I
))
941 out_pkt
.flags
|= AV_PKT_FLAG_KEY
;
943 compute_pkt_fields(s
, st
, st
->parser
, &out_pkt
);
945 if ((s
->iformat
->flags
& AVFMT_GENERIC_INDEX
) &&
946 out_pkt
.flags
& AV_PKT_FLAG_KEY
) {
947 ff_reduce_index(s
, st
->index
);
948 av_add_index_entry(st
, st
->parser
->frame_offset
, out_pkt
.dts
,
949 0, 0, AVINDEX_KEYFRAME
);
952 if (out_pkt
.data
== pkt
->data
&& out_pkt
.size
== pkt
->size
) {
953 out_pkt
.buf
= pkt
->buf
;
955 #if FF_API_DESTRUCT_PACKET
956 FF_DISABLE_DEPRECATION_WARNINGS
957 out_pkt
.destruct
= pkt
->destruct
;
958 pkt
->destruct
= NULL
;
959 FF_ENABLE_DEPRECATION_WARNINGS
962 if ((ret
= av_dup_packet(&out_pkt
)) < 0)
965 if (!add_to_pktbuf(&s
->parse_queue
, &out_pkt
, &s
->parse_queue_end
)) {
966 av_free_packet(&out_pkt
);
967 ret
= AVERROR(ENOMEM
);
973 /* end of the stream => close and free the parser */
974 if (pkt
== &flush_pkt
) {
975 av_parser_close(st
->parser
);
984 static int read_from_packet_buffer(AVPacketList
**pkt_buffer
,
985 AVPacketList
**pkt_buffer_end
,
989 av_assert0(*pkt_buffer
);
992 *pkt_buffer
= pktl
->next
;
994 *pkt_buffer_end
= NULL
;
999 static int read_frame_internal(AVFormatContext
*s
, AVPacket
*pkt
)
1001 int ret
= 0, i
, got_packet
= 0;
1003 av_init_packet(pkt
);
1005 while (!got_packet
&& !s
->parse_queue
) {
1009 /* read next packet */
1010 ret
= ff_read_packet(s
, &cur_pkt
);
1012 if (ret
== AVERROR(EAGAIN
))
1014 /* flush the parsers */
1015 for(i
= 0; i
< s
->nb_streams
; i
++) {
1017 if (st
->parser
&& st
->need_parsing
)
1018 parse_packet(s
, NULL
, st
->index
);
1020 /* all remaining packets are now in parse_queue =>
1021 * really terminate parsing */
1025 st
= s
->streams
[cur_pkt
.stream_index
];
1027 if (cur_pkt
.pts
!= AV_NOPTS_VALUE
&&
1028 cur_pkt
.dts
!= AV_NOPTS_VALUE
&&
1029 cur_pkt
.pts
< cur_pkt
.dts
) {
1030 av_log(s
, AV_LOG_WARNING
, "Invalid timestamps stream=%d, pts=%"PRId64
", dts=%"PRId64
", size=%d\n",
1031 cur_pkt
.stream_index
,
1036 if (s
->debug
& FF_FDEBUG_TS
)
1037 av_log(s
, AV_LOG_DEBUG
, "ff_read_packet stream=%d, pts=%"PRId64
", dts=%"PRId64
", size=%d, duration=%d, flags=%d\n",
1038 cur_pkt
.stream_index
,
1045 if (st
->need_parsing
&& !st
->parser
&& !(s
->flags
& AVFMT_FLAG_NOPARSE
)) {
1046 st
->parser
= av_parser_init(st
->codec
->codec_id
);
1048 /* no parser available: just output the raw packets */
1049 st
->need_parsing
= AVSTREAM_PARSE_NONE
;
1050 } else if(st
->need_parsing
== AVSTREAM_PARSE_HEADERS
) {
1051 st
->parser
->flags
|= PARSER_FLAG_COMPLETE_FRAMES
;
1052 } else if(st
->need_parsing
== AVSTREAM_PARSE_FULL_ONCE
) {
1053 st
->parser
->flags
|= PARSER_FLAG_ONCE
;
1057 if (!st
->need_parsing
|| !st
->parser
) {
1058 /* no parsing needed: we just output the packet as is */
1060 compute_pkt_fields(s
, st
, NULL
, pkt
);
1061 if ((s
->iformat
->flags
& AVFMT_GENERIC_INDEX
) &&
1062 (pkt
->flags
& AV_PKT_FLAG_KEY
) && pkt
->dts
!= AV_NOPTS_VALUE
) {
1063 ff_reduce_index(s
, st
->index
);
1064 av_add_index_entry(st
, pkt
->pos
, pkt
->dts
, 0, 0, AVINDEX_KEYFRAME
);
1067 } else if (st
->discard
< AVDISCARD_ALL
) {
1068 if ((ret
= parse_packet(s
, &cur_pkt
, cur_pkt
.stream_index
)) < 0)
1072 av_free_packet(&cur_pkt
);
1076 if (!got_packet
&& s
->parse_queue
)
1077 ret
= read_from_packet_buffer(&s
->parse_queue
, &s
->parse_queue_end
, pkt
);
1079 if(s
->debug
& FF_FDEBUG_TS
)
1080 av_log(s
, AV_LOG_DEBUG
, "read_frame_internal stream=%d, pts=%"PRId64
", dts=%"PRId64
", size=%d, duration=%d, flags=%d\n",
1091 int av_read_frame(AVFormatContext
*s
, AVPacket
*pkt
)
1093 const int genpts
= s
->flags
& AVFMT_FLAG_GENPTS
;
1097 return s
->packet_buffer ?
read_from_packet_buffer(&s
->packet_buffer
,
1098 &s
->packet_buffer_end
,
1100 read_frame_internal(s
, pkt
);
1104 AVPacketList
*pktl
= s
->packet_buffer
;
1107 AVPacket
*next_pkt
= &pktl
->pkt
;
1109 if (next_pkt
->dts
!= AV_NOPTS_VALUE
) {
1110 int wrap_bits
= s
->streams
[next_pkt
->stream_index
]->pts_wrap_bits
;
1111 while (pktl
&& next_pkt
->pts
== AV_NOPTS_VALUE
) {
1112 if (pktl
->pkt
.stream_index
== next_pkt
->stream_index
&&
1113 (av_compare_mod(next_pkt
->dts
, pktl
->pkt
.dts
, 2LL << (wrap_bits
- 1)) < 0) &&
1114 av_compare_mod(pktl
->pkt
.pts
, pktl
->pkt
.dts
, 2LL << (wrap_bits
- 1))) { //not b frame
1115 next_pkt
->pts
= pktl
->pkt
.dts
;
1119 pktl
= s
->packet_buffer
;
1122 /* read packet from packet buffer, if there is data */
1123 if (!(next_pkt
->pts
== AV_NOPTS_VALUE
&&
1124 next_pkt
->dts
!= AV_NOPTS_VALUE
&& !eof
))
1125 return read_from_packet_buffer(&s
->packet_buffer
,
1126 &s
->packet_buffer_end
, pkt
);
1129 ret
= read_frame_internal(s
, pkt
);
1131 if (pktl
&& ret
!= AVERROR(EAGAIN
)) {
1138 if (av_dup_packet(add_to_pktbuf(&s
->packet_buffer
, pkt
,
1139 &s
->packet_buffer_end
)) < 0)
1140 return AVERROR(ENOMEM
);
1144 /* XXX: suppress the packet queue */
1145 static void flush_packet_queue(AVFormatContext
*s
)
1147 free_packet_buffer(&s
->parse_queue
, &s
->parse_queue_end
);
1148 free_packet_buffer(&s
->packet_buffer
, &s
->packet_buffer_end
);
1149 free_packet_buffer(&s
->raw_packet_buffer
, &s
->raw_packet_buffer_end
);
1151 s
->raw_packet_buffer_remaining_size
= RAW_PACKET_BUFFER_SIZE
;
1154 /*******************************************************/
1157 int av_find_default_stream_index(AVFormatContext
*s
)
1159 int first_audio_index
= -1;
1163 if (s
->nb_streams
<= 0)
1165 for(i
= 0; i
< s
->nb_streams
; i
++) {
1167 if (st
->codec
->codec_type
== AVMEDIA_TYPE_VIDEO
&&
1168 !(st
->disposition
& AV_DISPOSITION_ATTACHED_PIC
)) {
1171 if (first_audio_index
< 0 && st
->codec
->codec_type
== AVMEDIA_TYPE_AUDIO
)
1172 first_audio_index
= i
;
1174 return first_audio_index
>= 0 ? first_audio_index
: 0;
1178 * Flush the frame reader.
1180 void ff_read_frame_flush(AVFormatContext
*s
)
1185 flush_packet_queue(s
);
1187 /* for each stream, reset read state */
1188 for(i
= 0; i
< s
->nb_streams
; i
++) {
1192 av_parser_close(st
->parser
);
1195 st
->last_IP_pts
= AV_NOPTS_VALUE
;
1196 st
->cur_dts
= AV_NOPTS_VALUE
; /* we set the current DTS to an unspecified origin */
1198 st
->probe_packets
= MAX_PROBE_PACKETS
;
1200 for(j
=0; j
<MAX_REORDER_DELAY
+1; j
++)
1201 st
->pts_buffer
[j
]= AV_NOPTS_VALUE
;
1205 void ff_update_cur_dts(AVFormatContext
*s
, AVStream
*ref_st
, int64_t timestamp
)
1209 for(i
= 0; i
< s
->nb_streams
; i
++) {
1210 AVStream
*st
= s
->streams
[i
];
1212 st
->cur_dts
= av_rescale(timestamp
,
1213 st
->time_base
.den
* (int64_t)ref_st
->time_base
.num
,
1214 st
->time_base
.num
* (int64_t)ref_st
->time_base
.den
);
1218 void ff_reduce_index(AVFormatContext
*s
, int stream_index
)
1220 AVStream
*st
= s
->streams
[stream_index
];
1221 unsigned int max_entries
= s
->max_index_size
/ sizeof(AVIndexEntry
);
1223 if((unsigned)st
->nb_index_entries
>= max_entries
){
1225 for(i
=0; 2*i
<st
->nb_index_entries
; i
++)
1226 st
->index_entries
[i
]= st
->index_entries
[2*i
];
1227 st
->nb_index_entries
= i
;
1231 int ff_add_index_entry(AVIndexEntry
**index_entries
,
1232 int *nb_index_entries
,
1233 unsigned int *index_entries_allocated_size
,
1234 int64_t pos
, int64_t timestamp
, int size
, int distance
, int flags
)
1236 AVIndexEntry
*entries
, *ie
;
1239 if((unsigned)*nb_index_entries
+ 1 >= UINT_MAX
/ sizeof(AVIndexEntry
))
1242 entries
= av_fast_realloc(*index_entries
,
1243 index_entries_allocated_size
,
1244 (*nb_index_entries
+ 1) *
1245 sizeof(AVIndexEntry
));
1249 *index_entries
= entries
;
1251 index
= ff_index_search_timestamp(*index_entries
, *nb_index_entries
, timestamp
, AVSEEK_FLAG_ANY
);
1254 index
= (*nb_index_entries
)++;
1255 ie
= &entries
[index
];
1256 assert(index
==0 || ie
[-1].timestamp
< timestamp
);
1258 ie
= &entries
[index
];
1259 if(ie
->timestamp
!= timestamp
){
1260 if(ie
->timestamp
<= timestamp
)
1262 memmove(entries
+ index
+ 1, entries
+ index
, sizeof(AVIndexEntry
)*(*nb_index_entries
- index
));
1263 (*nb_index_entries
)++;
1264 }else if(ie
->pos
== pos
&& distance
< ie
->min_distance
) //do not reduce the distance
1265 distance
= ie
->min_distance
;
1269 ie
->timestamp
= timestamp
;
1270 ie
->min_distance
= distance
;
1277 int av_add_index_entry(AVStream
*st
,
1278 int64_t pos
, int64_t timestamp
, int size
, int distance
, int flags
)
1280 return ff_add_index_entry(&st
->index_entries
, &st
->nb_index_entries
,
1281 &st
->index_entries_allocated_size
, pos
,
1282 timestamp
, size
, distance
, flags
);
1285 int ff_index_search_timestamp(const AVIndexEntry
*entries
, int nb_entries
,
1286 int64_t wanted_timestamp
, int flags
)
1294 //optimize appending index entries at the end
1295 if(b
&& entries
[b
-1].timestamp
< wanted_timestamp
)
1300 timestamp
= entries
[m
].timestamp
;
1301 if(timestamp
>= wanted_timestamp
)
1303 if(timestamp
<= wanted_timestamp
)
1306 m
= (flags
& AVSEEK_FLAG_BACKWARD
) ? a
: b
;
1308 if(!(flags
& AVSEEK_FLAG_ANY
)){
1309 while(m
>=0 && m
<nb_entries
&& !(entries
[m
].flags
& AVINDEX_KEYFRAME
)){
1310 m
+= (flags
& AVSEEK_FLAG_BACKWARD
) ?
-1 : 1;
1319 int av_index_search_timestamp(AVStream
*st
, int64_t wanted_timestamp
,
1322 return ff_index_search_timestamp(st
->index_entries
, st
->nb_index_entries
,
1323 wanted_timestamp
, flags
);
1326 int ff_seek_frame_binary(AVFormatContext
*s
, int stream_index
, int64_t target_ts
, int flags
)
1328 AVInputFormat
*avif
= s
->iformat
;
1329 int64_t av_uninit(pos_min
), av_uninit(pos_max
), pos
, pos_limit
;
1330 int64_t ts_min
, ts_max
, ts
;
1335 if (stream_index
< 0)
1338 av_dlog(s
, "read_seek: %d %"PRId64
"\n", stream_index
, target_ts
);
1341 ts_min
= AV_NOPTS_VALUE
;
1342 pos_limit
= -1; //gcc falsely says it may be uninitialized
1344 st
= s
->streams
[stream_index
];
1345 if(st
->index_entries
){
1348 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()
1349 index
= FFMAX(index
, 0);
1350 e
= &st
->index_entries
[index
];
1352 if(e
->timestamp
<= target_ts
|| e
->pos
== e
->min_distance
){
1354 ts_min
= e
->timestamp
;
1355 av_dlog(s
, "using cached pos_min=0x%"PRIx64
" dts_min=%"PRId64
"\n",
1361 index
= av_index_search_timestamp(st
, target_ts
, flags
& ~AVSEEK_FLAG_BACKWARD
);
1362 assert(index
< st
->nb_index_entries
);
1364 e
= &st
->index_entries
[index
];
1365 assert(e
->timestamp
>= target_ts
);
1367 ts_max
= e
->timestamp
;
1368 pos_limit
= pos_max
- e
->min_distance
;
1369 av_dlog(s
, "using cached pos_max=0x%"PRIx64
" pos_limit=0x%"PRIx64
" dts_max=%"PRId64
"\n",
1370 pos_max
,pos_limit
, ts_max
);
1374 pos
= ff_gen_search(s
, stream_index
, target_ts
, pos_min
, pos_max
, pos_limit
, ts_min
, ts_max
, flags
, &ts
, avif
->read_timestamp
);
1379 if ((ret
= avio_seek(s
->pb
, pos
, SEEK_SET
)) < 0)
1382 ff_update_cur_dts(s
, st
, ts
);
1387 int64_t ff_gen_search(AVFormatContext
*s
, int stream_index
, int64_t target_ts
,
1388 int64_t pos_min
, int64_t pos_max
, int64_t pos_limit
,
1389 int64_t ts_min
, int64_t ts_max
, int flags
, int64_t *ts_ret
,
1390 int64_t (*read_timestamp
)(struct AVFormatContext
*, int , int64_t *, int64_t ))
1393 int64_t start_pos
, filesize
;
1396 av_dlog(s
, "gen_seek: %d %"PRId64
"\n", stream_index
, target_ts
);
1398 if(ts_min
== AV_NOPTS_VALUE
){
1399 pos_min
= s
->data_offset
;
1400 ts_min
= read_timestamp(s
, stream_index
, &pos_min
, INT64_MAX
);
1401 if (ts_min
== AV_NOPTS_VALUE
)
1405 if(ts_max
== AV_NOPTS_VALUE
){
1407 filesize
= avio_size(s
->pb
);
1408 pos_max
= filesize
- 1;
1411 ts_max
= read_timestamp(s
, stream_index
, &pos_max
, pos_max
+ step
);
1413 }while(ts_max
== AV_NOPTS_VALUE
&& pos_max
>= step
);
1414 if (ts_max
== AV_NOPTS_VALUE
)
1418 int64_t tmp_pos
= pos_max
+ 1;
1419 int64_t tmp_ts
= read_timestamp(s
, stream_index
, &tmp_pos
, INT64_MAX
);
1420 if(tmp_ts
== AV_NOPTS_VALUE
)
1424 if(tmp_pos
>= filesize
)
1430 if(ts_min
> ts_max
){
1432 }else if(ts_min
== ts_max
){
1437 while (pos_min
< pos_limit
) {
1438 av_dlog(s
, "pos_min=0x%"PRIx64
" pos_max=0x%"PRIx64
" dts_min=%"PRId64
" dts_max=%"PRId64
"\n",
1439 pos_min
, pos_max
, ts_min
, ts_max
);
1440 assert(pos_limit
<= pos_max
);
1443 int64_t approximate_keyframe_distance
= pos_max
- pos_limit
;
1444 // interpolate position (better than dichotomy)
1445 pos
= av_rescale(target_ts
- ts_min
, pos_max
- pos_min
, ts_max
- ts_min
)
1446 + pos_min
- approximate_keyframe_distance
;
1447 }else if(no_change
==1){
1448 // bisection, if interpolation failed to change min or max pos last time
1449 pos
= (pos_min
+ pos_limit
)>>1;
1451 /* linear search if bisection failed, can only happen if there
1452 are very few or no keyframes between min/max */
1457 else if(pos
> pos_limit
)
1461 ts
= read_timestamp(s
, stream_index
, &pos
, INT64_MAX
); //may pass pos_limit instead of -1
1466 av_dlog(s
, "%"PRId64
" %"PRId64
" %"PRId64
" / %"PRId64
" %"PRId64
" %"PRId64
" target:%"PRId64
" limit:%"PRId64
" start:%"PRId64
" noc:%d\n",
1467 pos_min
, pos
, pos_max
, ts_min
, ts
, ts_max
, target_ts
,
1468 pos_limit
, start_pos
, no_change
);
1469 if(ts
== AV_NOPTS_VALUE
){
1470 av_log(s
, AV_LOG_ERROR
, "read_timestamp() failed in the middle\n");
1473 assert(ts
!= AV_NOPTS_VALUE
);
1474 if (target_ts
<= ts
) {
1475 pos_limit
= start_pos
- 1;
1479 if (target_ts
>= ts
) {
1485 pos
= (flags
& AVSEEK_FLAG_BACKWARD
) ? pos_min
: pos_max
;
1486 ts
= (flags
& AVSEEK_FLAG_BACKWARD
) ? ts_min
: ts_max
;
1488 ts_min
= read_timestamp(s
, stream_index
, &pos_min
, INT64_MAX
);
1490 ts_max
= read_timestamp(s
, stream_index
, &pos_min
, INT64_MAX
);
1491 av_dlog(s
, "pos=0x%"PRIx64
" %"PRId64
"<=%"PRId64
"<=%"PRId64
"\n",
1492 pos
, ts_min
, target_ts
, ts_max
);
1497 static int seek_frame_byte(AVFormatContext
*s
, int stream_index
, int64_t pos
, int flags
){
1498 int64_t pos_min
, pos_max
;
1500 pos_min
= s
->data_offset
;
1501 pos_max
= avio_size(s
->pb
) - 1;
1503 if (pos
< pos_min
) pos
= pos_min
;
1504 else if(pos
> pos_max
) pos
= pos_max
;
1506 avio_seek(s
->pb
, pos
, SEEK_SET
);
1511 static int seek_frame_generic(AVFormatContext
*s
,
1512 int stream_index
, int64_t timestamp
, int flags
)
1519 st
= s
->streams
[stream_index
];
1521 index
= av_index_search_timestamp(st
, timestamp
, flags
);
1523 if(index
< 0 && st
->nb_index_entries
&& timestamp
< st
->index_entries
[0].timestamp
)
1526 if(index
< 0 || index
==st
->nb_index_entries
-1){
1529 if(st
->nb_index_entries
){
1530 assert(st
->index_entries
);
1531 ie
= &st
->index_entries
[st
->nb_index_entries
-1];
1532 if ((ret
= avio_seek(s
->pb
, ie
->pos
, SEEK_SET
)) < 0)
1534 ff_update_cur_dts(s
, st
, ie
->timestamp
);
1536 if ((ret
= avio_seek(s
->pb
, s
->data_offset
, SEEK_SET
)) < 0)
1542 read_status
= av_read_frame(s
, &pkt
);
1543 } while (read_status
== AVERROR(EAGAIN
));
1544 if (read_status
< 0)
1546 av_free_packet(&pkt
);
1547 if(stream_index
== pkt
.stream_index
){
1548 if((pkt
.flags
& AV_PKT_FLAG_KEY
) && pkt
.dts
> timestamp
)
1552 index
= av_index_search_timestamp(st
, timestamp
, flags
);
1557 ff_read_frame_flush(s
);
1558 if (s
->iformat
->read_seek
){
1559 if(s
->iformat
->read_seek(s
, stream_index
, timestamp
, flags
) >= 0)
1562 ie
= &st
->index_entries
[index
];
1563 if ((ret
= avio_seek(s
->pb
, ie
->pos
, SEEK_SET
)) < 0)
1565 ff_update_cur_dts(s
, st
, ie
->timestamp
);
1570 static int seek_frame_internal(AVFormatContext
*s
, int stream_index
,
1571 int64_t timestamp
, int flags
)
1576 if (flags
& AVSEEK_FLAG_BYTE
) {
1577 if (s
->iformat
->flags
& AVFMT_NO_BYTE_SEEK
)
1579 ff_read_frame_flush(s
);
1580 return seek_frame_byte(s
, stream_index
, timestamp
, flags
);
1583 if(stream_index
< 0){
1584 stream_index
= av_find_default_stream_index(s
);
1585 if(stream_index
< 0)
1588 st
= s
->streams
[stream_index
];
1589 /* timestamp for default must be expressed in AV_TIME_BASE units */
1590 timestamp
= av_rescale(timestamp
, st
->time_base
.den
, AV_TIME_BASE
* (int64_t)st
->time_base
.num
);
1593 /* first, we try the format specific seek */
1594 if (s
->iformat
->read_seek
) {
1595 ff_read_frame_flush(s
);
1596 ret
= s
->iformat
->read_seek(s
, stream_index
, timestamp
, flags
);
1603 if (s
->iformat
->read_timestamp
&& !(s
->iformat
->flags
& AVFMT_NOBINSEARCH
)) {
1604 ff_read_frame_flush(s
);
1605 return ff_seek_frame_binary(s
, stream_index
, timestamp
, flags
);
1606 } else if (!(s
->iformat
->flags
& AVFMT_NOGENSEARCH
)) {
1607 ff_read_frame_flush(s
);
1608 return seek_frame_generic(s
, stream_index
, timestamp
, flags
);
1614 int av_seek_frame(AVFormatContext
*s
, int stream_index
, int64_t timestamp
, int flags
)
1616 int ret
= seek_frame_internal(s
, stream_index
, timestamp
, flags
);
1619 ret
= queue_attached_pictures(s
);
1624 int avformat_seek_file(AVFormatContext
*s
, int stream_index
, int64_t min_ts
, int64_t ts
, int64_t max_ts
, int flags
)
1626 if(min_ts
> ts
|| max_ts
< ts
)
1629 if (s
->iformat
->read_seek2
) {
1631 ff_read_frame_flush(s
);
1632 ret
= s
->iformat
->read_seek2(s
, stream_index
, min_ts
, ts
, max_ts
, flags
);
1635 ret
= queue_attached_pictures(s
);
1639 if(s
->iformat
->read_timestamp
){
1640 //try to seek via read_timestamp()
1643 // Fall back on old API if new is not implemented but old is.
1644 // Note the old API has somewhat different semantics.
1645 if(s
->iformat
->read_seek
|| 1)
1646 return av_seek_frame(s
, stream_index
, ts
, flags
| ((uint64_t)ts
- min_ts
> (uint64_t)max_ts
- ts ? AVSEEK_FLAG_BACKWARD
: 0));
1648 // try some generic seek like seek_frame_generic() but with new ts semantics
1651 /*******************************************************/
1654 * Return TRUE if the stream has accurate duration in any stream.
1656 * @return TRUE if the stream has accurate duration for at least one component.
1658 static int has_duration(AVFormatContext
*ic
)
1663 for(i
= 0;i
< ic
->nb_streams
; i
++) {
1664 st
= ic
->streams
[i
];
1665 if (st
->duration
!= AV_NOPTS_VALUE
)
1668 if (ic
->duration
!= AV_NOPTS_VALUE
)
1674 * Estimate the stream timings from the one of each components.
1676 * Also computes the global bitrate if possible.
1678 static void update_stream_timings(AVFormatContext
*ic
)
1680 int64_t start_time
, start_time1
, end_time
, end_time1
;
1681 int64_t duration
, duration1
, filesize
;
1685 start_time
= INT64_MAX
;
1686 end_time
= INT64_MIN
;
1687 duration
= INT64_MIN
;
1688 for(i
= 0;i
< ic
->nb_streams
; i
++) {
1689 st
= ic
->streams
[i
];
1690 if (st
->start_time
!= AV_NOPTS_VALUE
&& st
->time_base
.den
) {
1691 start_time1
= av_rescale_q(st
->start_time
, st
->time_base
, AV_TIME_BASE_Q
);
1692 start_time
= FFMIN(start_time
, start_time1
);
1693 if (st
->duration
!= AV_NOPTS_VALUE
) {
1694 end_time1
= start_time1
1695 + av_rescale_q(st
->duration
, st
->time_base
, AV_TIME_BASE_Q
);
1696 end_time
= FFMAX(end_time
, end_time1
);
1699 if (st
->duration
!= AV_NOPTS_VALUE
) {
1700 duration1
= av_rescale_q(st
->duration
, st
->time_base
, AV_TIME_BASE_Q
);
1701 duration
= FFMAX(duration
, duration1
);
1704 if (start_time
!= INT64_MAX
) {
1705 ic
->start_time
= start_time
;
1706 if (end_time
!= INT64_MIN
)
1707 duration
= FFMAX(duration
, end_time
- start_time
);
1709 if (duration
!= INT64_MIN
) {
1710 ic
->duration
= duration
;
1711 if (ic
->pb
&& (filesize
= avio_size(ic
->pb
)) > 0) {
1712 /* compute the bitrate */
1713 ic
->bit_rate
= (double)filesize
* 8.0 * AV_TIME_BASE
/
1714 (double)ic
->duration
;
1719 static void fill_all_stream_timings(AVFormatContext
*ic
)
1724 update_stream_timings(ic
);
1725 for(i
= 0;i
< ic
->nb_streams
; i
++) {
1726 st
= ic
->streams
[i
];
1727 if (st
->start_time
== AV_NOPTS_VALUE
) {
1728 if(ic
->start_time
!= AV_NOPTS_VALUE
)
1729 st
->start_time
= av_rescale_q(ic
->start_time
, AV_TIME_BASE_Q
, st
->time_base
);
1730 if(ic
->duration
!= AV_NOPTS_VALUE
)
1731 st
->duration
= av_rescale_q(ic
->duration
, AV_TIME_BASE_Q
, st
->time_base
);
1736 static void estimate_timings_from_bit_rate(AVFormatContext
*ic
)
1738 int64_t filesize
, duration
;
1742 /* if bit_rate is already set, we believe it */
1743 if (ic
->bit_rate
<= 0) {
1745 for(i
=0;i
<ic
->nb_streams
;i
++) {
1746 st
= ic
->streams
[i
];
1747 if (st
->codec
->bit_rate
> 0) {
1748 if (INT_MAX
- st
->codec
->bit_rate
< bit_rate
) {
1752 bit_rate
+= st
->codec
->bit_rate
;
1755 ic
->bit_rate
= bit_rate
;
1758 /* if duration is already set, we believe it */
1759 if (ic
->duration
== AV_NOPTS_VALUE
&&
1760 ic
->bit_rate
!= 0) {
1761 filesize
= ic
->pb ?
avio_size(ic
->pb
) : 0;
1763 for(i
= 0; i
< ic
->nb_streams
; i
++) {
1764 st
= ic
->streams
[i
];
1765 duration
= av_rescale(8*filesize
, st
->time_base
.den
, ic
->bit_rate
*(int64_t)st
->time_base
.num
);
1766 if (st
->duration
== AV_NOPTS_VALUE
)
1767 st
->duration
= duration
;
1773 #define DURATION_MAX_READ_SIZE 250000
1774 #define DURATION_MAX_RETRY 3
1776 /* only usable for MPEG-PS streams */
1777 static void estimate_timings_from_pts(AVFormatContext
*ic
, int64_t old_offset
)
1779 AVPacket pkt1
, *pkt
= &pkt1
;
1781 int read_size
, i
, ret
;
1783 int64_t filesize
, offset
, duration
;
1786 /* flush packet queue */
1787 flush_packet_queue(ic
);
1789 for (i
=0; i
<ic
->nb_streams
; i
++) {
1790 st
= ic
->streams
[i
];
1791 if (st
->start_time
== AV_NOPTS_VALUE
&& st
->first_dts
== AV_NOPTS_VALUE
)
1792 av_log(st
->codec
, AV_LOG_WARNING
, "start time is not set in estimate_timings_from_pts\n");
1795 av_parser_close(st
->parser
);
1800 /* estimate the end time (duration) */
1801 /* XXX: may need to support wrapping */
1802 filesize
= ic
->pb ?
avio_size(ic
->pb
) : 0;
1803 end_time
= AV_NOPTS_VALUE
;
1805 offset
= filesize
- (DURATION_MAX_READ_SIZE
<<retry
);
1809 avio_seek(ic
->pb
, offset
, SEEK_SET
);
1812 if (read_size
>= DURATION_MAX_READ_SIZE
<<(FFMAX(retry
-1,0)))
1816 ret
= ff_read_packet(ic
, pkt
);
1817 } while(ret
== AVERROR(EAGAIN
));
1820 read_size
+= pkt
->size
;
1821 st
= ic
->streams
[pkt
->stream_index
];
1822 if (pkt
->pts
!= AV_NOPTS_VALUE
&&
1823 (st
->start_time
!= AV_NOPTS_VALUE
||
1824 st
->first_dts
!= AV_NOPTS_VALUE
)) {
1825 duration
= end_time
= pkt
->pts
;
1826 if (st
->start_time
!= AV_NOPTS_VALUE
)
1827 duration
-= st
->start_time
;
1829 duration
-= st
->first_dts
;
1831 duration
+= 1LL<<st
->pts_wrap_bits
;
1833 if (st
->duration
== AV_NOPTS_VALUE
|| st
->duration
< duration
)
1834 st
->duration
= duration
;
1837 av_free_packet(pkt
);
1839 }while( end_time
==AV_NOPTS_VALUE
1840 && filesize
> (DURATION_MAX_READ_SIZE
<<retry
)
1841 && ++retry
<= DURATION_MAX_RETRY
);
1843 fill_all_stream_timings(ic
);
1845 avio_seek(ic
->pb
, old_offset
, SEEK_SET
);
1846 for (i
=0; i
<ic
->nb_streams
; i
++) {
1848 st
->cur_dts
= st
->first_dts
;
1849 st
->last_IP_pts
= AV_NOPTS_VALUE
;
1853 static void estimate_timings(AVFormatContext
*ic
, int64_t old_offset
)
1857 /* get the file size, if possible */
1858 if (ic
->iformat
->flags
& AVFMT_NOFILE
) {
1861 file_size
= avio_size(ic
->pb
);
1862 file_size
= FFMAX(0, file_size
);
1865 if ((!strcmp(ic
->iformat
->name
, "mpeg") ||
1866 !strcmp(ic
->iformat
->name
, "mpegts")) &&
1867 file_size
&& ic
->pb
->seekable
) {
1868 /* get accurate estimate from the PTSes */
1869 estimate_timings_from_pts(ic
, old_offset
);
1870 } else if (has_duration(ic
)) {
1871 /* at least one component has timings - we use them for all
1873 fill_all_stream_timings(ic
);
1875 av_log(ic
, AV_LOG_WARNING
, "Estimating duration from bitrate, this may be inaccurate\n");
1876 /* less precise: use bitrate info */
1877 estimate_timings_from_bit_rate(ic
);
1879 update_stream_timings(ic
);
1883 AVStream av_unused
*st
;
1884 for(i
= 0;i
< ic
->nb_streams
; i
++) {
1885 st
= ic
->streams
[i
];
1886 av_dlog(ic
, "%d: start_time: %0.3f duration: %0.3f\n", i
,
1887 (double) st
->start_time
/ AV_TIME_BASE
,
1888 (double) st
->duration
/ AV_TIME_BASE
);
1890 av_dlog(ic
, "stream: start_time: %0.3f duration: %0.3f bitrate=%d kb/s\n",
1891 (double) ic
->start_time
/ AV_TIME_BASE
,
1892 (double) ic
->duration
/ AV_TIME_BASE
,
1893 ic
->bit_rate
/ 1000);
1897 static int has_codec_parameters(AVStream
*st
)
1899 AVCodecContext
*avctx
= st
->codec
;
1901 switch (avctx
->codec_type
) {
1902 case AVMEDIA_TYPE_AUDIO
:
1903 val
= avctx
->sample_rate
&& avctx
->channels
;
1904 if (st
->info
->found_decoder
>= 0 && avctx
->sample_fmt
== AV_SAMPLE_FMT_NONE
)
1907 case AVMEDIA_TYPE_VIDEO
:
1909 if (st
->info
->found_decoder
>= 0 && avctx
->pix_fmt
== AV_PIX_FMT_NONE
)
1916 return avctx
->codec_id
!= AV_CODEC_ID_NONE
&& val
!= 0;
1919 static int has_decode_delay_been_guessed(AVStream
*st
)
1921 return st
->codec
->codec_id
!= AV_CODEC_ID_H264
||
1922 st
->info
->nb_decoded_frames
>= 6;
1925 /* returns 1 or 0 if or if not decoded data was returned, or a negative error */
1926 static int try_decode_frame(AVStream
*st
, AVPacket
*avpkt
, AVDictionary
**options
)
1928 const AVCodec
*codec
;
1929 int got_picture
= 1, ret
= 0;
1930 AVFrame
*frame
= av_frame_alloc();
1931 AVPacket pkt
= *avpkt
;
1934 return AVERROR(ENOMEM
);
1936 if (!avcodec_is_open(st
->codec
) && !st
->info
->found_decoder
) {
1937 AVDictionary
*thread_opt
= NULL
;
1939 codec
= st
->codec
->codec ? st
->codec
->codec
:
1940 avcodec_find_decoder(st
->codec
->codec_id
);
1943 st
->info
->found_decoder
= -1;
1948 /* force thread count to 1 since the h264 decoder will not extract SPS
1949 * and PPS to extradata during multi-threaded decoding */
1950 av_dict_set(options ? options
: &thread_opt
, "threads", "1", 0);
1951 ret
= avcodec_open2(st
->codec
, codec
, options ? options
: &thread_opt
);
1953 av_dict_free(&thread_opt
);
1955 st
->info
->found_decoder
= -1;
1958 st
->info
->found_decoder
= 1;
1959 } else if (!st
->info
->found_decoder
)
1960 st
->info
->found_decoder
= 1;
1962 if (st
->info
->found_decoder
< 0) {
1967 while ((pkt
.size
> 0 || (!pkt
.data
&& got_picture
)) &&
1969 (!has_codec_parameters(st
) ||
1970 !has_decode_delay_been_guessed(st
) ||
1971 (!st
->codec_info_nb_frames
&& st
->codec
->codec
->capabilities
& CODEC_CAP_CHANNEL_CONF
))) {
1973 switch(st
->codec
->codec_type
) {
1974 case AVMEDIA_TYPE_VIDEO
:
1975 ret
= avcodec_decode_video2(st
->codec
, frame
,
1976 &got_picture
, &pkt
);
1978 case AVMEDIA_TYPE_AUDIO
:
1979 ret
= avcodec_decode_audio4(st
->codec
, frame
, &got_picture
, &pkt
);
1986 st
->info
->nb_decoded_frames
++;
1994 av_frame_free(&frame
);
1998 unsigned int ff_codec_get_tag(const AVCodecTag
*tags
, enum AVCodecID id
)
2000 while (tags
->id
!= AV_CODEC_ID_NONE
) {
2008 enum AVCodecID
ff_codec_get_id(const AVCodecTag
*tags
, unsigned int tag
)
2011 for(i
=0; tags
[i
].id
!= AV_CODEC_ID_NONE
;i
++) {
2012 if(tag
== tags
[i
].tag
)
2015 for(i
=0; tags
[i
].id
!= AV_CODEC_ID_NONE
; i
++) {
2016 if (avpriv_toupper4(tag
) == avpriv_toupper4(tags
[i
].tag
))
2019 return AV_CODEC_ID_NONE
;
2022 enum AVCodecID
ff_get_pcm_codec_id(int bps
, int flt
, int be
, int sflags
)
2026 case 32: return be ? AV_CODEC_ID_PCM_F32BE
: AV_CODEC_ID_PCM_F32LE
;
2027 case 64: return be ? AV_CODEC_ID_PCM_F64BE
: AV_CODEC_ID_PCM_F64LE
;
2028 default: return AV_CODEC_ID_NONE
;
2032 if (sflags
& (1 << (bps
- 1))) {
2034 case 1: return AV_CODEC_ID_PCM_S8
;
2035 case 2: return be ? AV_CODEC_ID_PCM_S16BE
: AV_CODEC_ID_PCM_S16LE
;
2036 case 3: return be ? AV_CODEC_ID_PCM_S24BE
: AV_CODEC_ID_PCM_S24LE
;
2037 case 4: return be ? AV_CODEC_ID_PCM_S32BE
: AV_CODEC_ID_PCM_S32LE
;
2038 default: return AV_CODEC_ID_NONE
;
2042 case 1: return AV_CODEC_ID_PCM_U8
;
2043 case 2: return be ? AV_CODEC_ID_PCM_U16BE
: AV_CODEC_ID_PCM_U16LE
;
2044 case 3: return be ? AV_CODEC_ID_PCM_U24BE
: AV_CODEC_ID_PCM_U24LE
;
2045 case 4: return be ? AV_CODEC_ID_PCM_U32BE
: AV_CODEC_ID_PCM_U32LE
;
2046 default: return AV_CODEC_ID_NONE
;
2052 unsigned int av_codec_get_tag(const AVCodecTag
* const *tags
, enum AVCodecID id
)
2055 for(i
=0; tags
&& tags
[i
]; i
++){
2056 int tag
= ff_codec_get_tag(tags
[i
], id
);
2062 enum AVCodecID
av_codec_get_id(const AVCodecTag
* const *tags
, unsigned int tag
)
2065 for(i
=0; tags
&& tags
[i
]; i
++){
2066 enum AVCodecID id
= ff_codec_get_id(tags
[i
], tag
);
2067 if(id
!=AV_CODEC_ID_NONE
) return id
;
2069 return AV_CODEC_ID_NONE
;
2072 static void compute_chapters_end(AVFormatContext
*s
)
2075 int64_t max_time
= s
->duration
+ ((s
->start_time
== AV_NOPTS_VALUE
) ?
0 : s
->start_time
);
2077 for (i
= 0; i
< s
->nb_chapters
; i
++)
2078 if (s
->chapters
[i
]->end
== AV_NOPTS_VALUE
) {
2079 AVChapter
*ch
= s
->chapters
[i
];
2080 int64_t end
= max_time ?
av_rescale_q(max_time
, AV_TIME_BASE_Q
, ch
->time_base
)
2083 for (j
= 0; j
< s
->nb_chapters
; j
++) {
2084 AVChapter
*ch1
= s
->chapters
[j
];
2085 int64_t next_start
= av_rescale_q(ch1
->start
, ch1
->time_base
, ch
->time_base
);
2086 if (j
!= i
&& next_start
> ch
->start
&& next_start
< end
)
2089 ch
->end
= (end
== INT64_MAX
) ? ch
->start
: end
;
2093 static int get_std_framerate(int i
){
2094 if(i
<60*12) return i
*1001;
2095 else return ((const int[]){24,30,60,12,15})[i
-60*12]*1000*12;
2099 * Is the time base unreliable.
2100 * This is a heuristic to balance between quick acceptance of the values in
2101 * the headers vs. some extra checks.
2102 * Old DivX and Xvid often have nonsense timebases like 1fps or 2fps.
2103 * MPEG-2 commonly misuses field repeat flags to store different framerates.
2104 * And there are "variable" fps files this needs to detect as well.
2106 static int tb_unreliable(AVCodecContext
*c
){
2107 if( c
->time_base
.den
>= 101L*c
->time_base
.num
2108 || c
->time_base
.den
< 5L*c
->time_base
.num
2109 /* || c->codec_tag == AV_RL32("DIVX")
2110 || c->codec_tag == AV_RL32("XVID")*/
2111 || c
->codec_id
== AV_CODEC_ID_MPEG2VIDEO
2112 || c
->codec_id
== AV_CODEC_ID_H264
2118 int avformat_find_stream_info(AVFormatContext
*ic
, AVDictionary
**options
)
2120 int i
, count
, ret
, read_size
, j
;
2122 AVPacket pkt1
, *pkt
;
2123 int64_t old_offset
= avio_tell(ic
->pb
);
2124 int orig_nb_streams
= ic
->nb_streams
; // new streams might appear, no options for those
2126 for(i
=0;i
<ic
->nb_streams
;i
++) {
2127 const AVCodec
*codec
;
2128 AVDictionary
*thread_opt
= NULL
;
2129 st
= ic
->streams
[i
];
2131 //only for the split stuff
2132 if (!st
->parser
&& !(ic
->flags
& AVFMT_FLAG_NOPARSE
)) {
2133 st
->parser
= av_parser_init(st
->codec
->codec_id
);
2134 if(st
->need_parsing
== AVSTREAM_PARSE_HEADERS
&& st
->parser
){
2135 st
->parser
->flags
|= PARSER_FLAG_COMPLETE_FRAMES
;
2138 codec
= st
->codec
->codec ? st
->codec
->codec
:
2139 avcodec_find_decoder(st
->codec
->codec_id
);
2141 /* force thread count to 1 since the h264 decoder will not extract SPS
2142 * and PPS to extradata during multi-threaded decoding */
2143 av_dict_set(options ?
&options
[i
] : &thread_opt
, "threads", "1", 0);
2145 /* Ensure that subtitle_header is properly set. */
2146 if (st
->codec
->codec_type
== AVMEDIA_TYPE_SUBTITLE
2147 && codec
&& !st
->codec
->codec
)
2148 avcodec_open2(st
->codec
, codec
, options ?
&options
[i
]
2151 //try to just open decoders, in case this is enough to get parameters
2152 if (!has_codec_parameters(st
)) {
2153 if (codec
&& !st
->codec
->codec
)
2154 avcodec_open2(st
->codec
, codec
, options ?
&options
[i
]
2158 av_dict_free(&thread_opt
);
2161 for (i
=0; i
<ic
->nb_streams
; i
++) {
2162 ic
->streams
[i
]->info
->fps_first_dts
= AV_NOPTS_VALUE
;
2163 ic
->streams
[i
]->info
->fps_last_dts
= AV_NOPTS_VALUE
;
2169 if (ff_check_interrupt(&ic
->interrupt_callback
)){
2171 av_log(ic
, AV_LOG_DEBUG
, "interrupted\n");
2175 /* check if one codec still needs to be handled */
2176 for(i
=0;i
<ic
->nb_streams
;i
++) {
2177 int fps_analyze_framecount
= 20;
2179 st
= ic
->streams
[i
];
2180 if (!has_codec_parameters(st
))
2182 /* if the timebase is coarse (like the usual millisecond precision
2183 of mkv), we need to analyze more frames to reliably arrive at
2185 if (av_q2d(st
->time_base
) > 0.0005)
2186 fps_analyze_framecount
*= 2;
2187 if (ic
->fps_probe_size
>= 0)
2188 fps_analyze_framecount
= ic
->fps_probe_size
;
2189 /* variable fps and no guess at the real fps */
2190 if( tb_unreliable(st
->codec
) && !st
->avg_frame_rate
.num
2191 && st
->codec_info_nb_frames
< fps_analyze_framecount
2192 && st
->codec
->codec_type
== AVMEDIA_TYPE_VIDEO
)
2194 if(st
->parser
&& st
->parser
->parser
->split
&& !st
->codec
->extradata
)
2196 if (st
->first_dts
== AV_NOPTS_VALUE
&&
2197 (st
->codec
->codec_type
== AVMEDIA_TYPE_VIDEO
||
2198 st
->codec
->codec_type
== AVMEDIA_TYPE_AUDIO
))
2201 if (i
== ic
->nb_streams
) {
2202 /* NOTE: if the format has no header, then we need to read
2203 some packets to get most of the streams, so we cannot
2205 if (!(ic
->ctx_flags
& AVFMTCTX_NOHEADER
)) {
2206 /* if we found the info for all the codecs, we can stop */
2208 av_log(ic
, AV_LOG_DEBUG
, "All info found\n");
2212 /* we did not get all the codec info, but we read too much data */
2213 if (read_size
>= ic
->probesize
) {
2215 av_log(ic
, AV_LOG_DEBUG
, "Probe buffer size limit %d reached\n", ic
->probesize
);
2219 /* NOTE: a new stream can be added there if no header in file
2220 (AVFMTCTX_NOHEADER) */
2221 ret
= read_frame_internal(ic
, &pkt1
);
2222 if (ret
== AVERROR(EAGAIN
))
2227 AVPacket empty_pkt
= { 0 };
2229 av_init_packet(&empty_pkt
);
2231 ret
= -1; /* we could not have all the codec parameters before EOF */
2232 for(i
=0;i
<ic
->nb_streams
;i
++) {
2233 st
= ic
->streams
[i
];
2235 /* flush the decoders */
2236 if (st
->info
->found_decoder
== 1) {
2238 err
= try_decode_frame(st
, &empty_pkt
,
2239 (options
&& i
< orig_nb_streams
) ?
2240 &options
[i
] : NULL
);
2241 } while (err
> 0 && !has_codec_parameters(st
));
2245 av_log(ic
, AV_LOG_WARNING
,
2246 "decoding for stream %d failed\n", st
->index
);
2247 } else if (!has_codec_parameters(st
)) {
2249 avcodec_string(buf
, sizeof(buf
), st
->codec
, 0);
2250 av_log(ic
, AV_LOG_WARNING
,
2251 "Could not find codec parameters (%s)\n", buf
);
2259 if (ic
->flags
& AVFMT_FLAG_NOBUFFER
) {
2262 pkt
= add_to_pktbuf(&ic
->packet_buffer
, &pkt1
,
2263 &ic
->packet_buffer_end
);
2264 if ((ret
= av_dup_packet(pkt
)) < 0)
2265 goto find_stream_info_err
;
2268 read_size
+= pkt
->size
;
2270 st
= ic
->streams
[pkt
->stream_index
];
2271 if (pkt
->dts
!= AV_NOPTS_VALUE
&& st
->codec_info_nb_frames
> 1) {
2272 /* check for non-increasing dts */
2273 if (st
->info
->fps_last_dts
!= AV_NOPTS_VALUE
&&
2274 st
->info
->fps_last_dts
>= pkt
->dts
) {
2275 av_log(ic
, AV_LOG_WARNING
, "Non-increasing DTS in stream %d: "
2276 "packet %d with DTS %"PRId64
", packet %d with DTS "
2277 "%"PRId64
"\n", st
->index
, st
->info
->fps_last_dts_idx
,
2278 st
->info
->fps_last_dts
, st
->codec_info_nb_frames
, pkt
->dts
);
2279 st
->info
->fps_first_dts
= st
->info
->fps_last_dts
= AV_NOPTS_VALUE
;
2281 /* check for a discontinuity in dts - if the difference in dts
2282 * is more than 1000 times the average packet duration in the sequence,
2283 * we treat it as a discontinuity */
2284 if (st
->info
->fps_last_dts
!= AV_NOPTS_VALUE
&&
2285 st
->info
->fps_last_dts_idx
> st
->info
->fps_first_dts_idx
&&
2286 (pkt
->dts
- st
->info
->fps_last_dts
) / 1000 >
2287 (st
->info
->fps_last_dts
- st
->info
->fps_first_dts
) / (st
->info
->fps_last_dts_idx
- st
->info
->fps_first_dts_idx
)) {
2288 av_log(ic
, AV_LOG_WARNING
, "DTS discontinuity in stream %d: "
2289 "packet %d with DTS %"PRId64
", packet %d with DTS "
2290 "%"PRId64
"\n", st
->index
, st
->info
->fps_last_dts_idx
,
2291 st
->info
->fps_last_dts
, st
->codec_info_nb_frames
, pkt
->dts
);
2292 st
->info
->fps_first_dts
= st
->info
->fps_last_dts
= AV_NOPTS_VALUE
;
2295 /* update stored dts values */
2296 if (st
->info
->fps_first_dts
== AV_NOPTS_VALUE
) {
2297 st
->info
->fps_first_dts
= pkt
->dts
;
2298 st
->info
->fps_first_dts_idx
= st
->codec_info_nb_frames
;
2300 st
->info
->fps_last_dts
= pkt
->dts
;
2301 st
->info
->fps_last_dts_idx
= st
->codec_info_nb_frames
;
2303 /* check max_analyze_duration */
2304 if (av_rescale_q(pkt
->dts
- st
->info
->fps_first_dts
, st
->time_base
,
2305 AV_TIME_BASE_Q
) >= ic
->max_analyze_duration
) {
2306 av_log(ic
, AV_LOG_WARNING
, "max_analyze_duration reached\n");
2310 if(st
->parser
&& st
->parser
->parser
->split
&& !st
->codec
->extradata
){
2311 int i
= st
->parser
->parser
->split(st
->codec
, pkt
->data
, pkt
->size
);
2312 if (i
> 0 && i
< FF_MAX_EXTRADATA_SIZE
) {
2313 st
->codec
->extradata_size
= i
;
2314 st
->codec
->extradata
= av_malloc(st
->codec
->extradata_size
+ FF_INPUT_BUFFER_PADDING_SIZE
);
2315 if (!st
->codec
->extradata
)
2316 return AVERROR(ENOMEM
);
2317 memcpy(st
->codec
->extradata
, pkt
->data
, st
->codec
->extradata_size
);
2318 memset(st
->codec
->extradata
+ i
, 0, FF_INPUT_BUFFER_PADDING_SIZE
);
2322 /* if still no information, we try to open the codec and to
2323 decompress the frame. We try to avoid that in most cases as
2324 it takes longer and uses more memory. For MPEG-4, we need to
2325 decompress for QuickTime.
2327 If CODEC_CAP_CHANNEL_CONF is set this will force decoding of at
2328 least one frame of codec data, this makes sure the codec initializes
2329 the channel configuration and does not only trust the values from the container.
2331 try_decode_frame(st
, pkt
, (options
&& i
< orig_nb_streams
) ?
&options
[i
] : NULL
);
2333 st
->codec_info_nb_frames
++;
2337 // close codecs which were opened in try_decode_frame()
2338 for(i
=0;i
<ic
->nb_streams
;i
++) {
2339 st
= ic
->streams
[i
];
2340 avcodec_close(st
->codec
);
2342 for(i
=0;i
<ic
->nb_streams
;i
++) {
2343 st
= ic
->streams
[i
];
2344 if (st
->codec
->codec_type
== AVMEDIA_TYPE_VIDEO
) {
2345 /* estimate average framerate if not set by demuxer */
2346 if (!st
->avg_frame_rate
.num
&& st
->info
->fps_last_dts
!= st
->info
->fps_first_dts
) {
2347 int64_t delta_dts
= st
->info
->fps_last_dts
- st
->info
->fps_first_dts
;
2348 int delta_packets
= st
->info
->fps_last_dts_idx
- st
->info
->fps_first_dts_idx
;
2350 double best_error
= 0.01;
2352 if (delta_dts
>= INT64_MAX
/ st
->time_base
.num
||
2353 delta_packets
>= INT64_MAX
/ st
->time_base
.den
||
2356 av_reduce(&st
->avg_frame_rate
.num
, &st
->avg_frame_rate
.den
,
2357 delta_packets
*(int64_t)st
->time_base
.den
,
2358 delta_dts
*(int64_t)st
->time_base
.num
, 60000);
2360 /* round guessed framerate to a "standard" framerate if it's
2361 * within 1% of the original estimate*/
2362 for (j
= 1; j
< MAX_STD_TIMEBASES
; j
++) {
2363 AVRational std_fps
= { get_std_framerate(j
), 12*1001 };
2364 double error
= fabs(av_q2d(st
->avg_frame_rate
) / av_q2d(std_fps
) - 1);
2366 if (error
< best_error
) {
2368 best_fps
= std_fps
.num
;
2372 av_reduce(&st
->avg_frame_rate
.num
, &st
->avg_frame_rate
.den
,
2373 best_fps
, 12*1001, INT_MAX
);
2376 }else if(st
->codec
->codec_type
== AVMEDIA_TYPE_AUDIO
) {
2377 if(!st
->codec
->bits_per_coded_sample
)
2378 st
->codec
->bits_per_coded_sample
= av_get_bits_per_sample(st
->codec
->codec_id
);
2379 // set stream disposition based on audio service type
2380 switch (st
->codec
->audio_service_type
) {
2381 case AV_AUDIO_SERVICE_TYPE_EFFECTS
:
2382 st
->disposition
= AV_DISPOSITION_CLEAN_EFFECTS
; break;
2383 case AV_AUDIO_SERVICE_TYPE_VISUALLY_IMPAIRED
:
2384 st
->disposition
= AV_DISPOSITION_VISUAL_IMPAIRED
; break;
2385 case AV_AUDIO_SERVICE_TYPE_HEARING_IMPAIRED
:
2386 st
->disposition
= AV_DISPOSITION_HEARING_IMPAIRED
; break;
2387 case AV_AUDIO_SERVICE_TYPE_COMMENTARY
:
2388 st
->disposition
= AV_DISPOSITION_COMMENT
; break;
2389 case AV_AUDIO_SERVICE_TYPE_KARAOKE
:
2390 st
->disposition
= AV_DISPOSITION_KARAOKE
; break;
2395 estimate_timings(ic
, old_offset
);
2397 compute_chapters_end(ic
);
2399 find_stream_info_err
:
2400 for (i
=0; i
< ic
->nb_streams
; i
++) {
2401 ic
->streams
[i
]->codec
->thread_count
= 0;
2402 av_freep(&ic
->streams
[i
]->info
);
2407 static AVProgram
*find_program_from_stream(AVFormatContext
*ic
, int s
)
2411 for (i
= 0; i
< ic
->nb_programs
; i
++)
2412 for (j
= 0; j
< ic
->programs
[i
]->nb_stream_indexes
; j
++)
2413 if (ic
->programs
[i
]->stream_index
[j
] == s
)
2414 return ic
->programs
[i
];
2418 int av_find_best_stream(AVFormatContext
*ic
,
2419 enum AVMediaType type
,
2420 int wanted_stream_nb
,
2422 AVCodec
**decoder_ret
,
2425 int i
, nb_streams
= ic
->nb_streams
;
2426 int ret
= AVERROR_STREAM_NOT_FOUND
, best_count
= -1;
2427 unsigned *program
= NULL
;
2428 AVCodec
*decoder
= NULL
, *best_decoder
= NULL
;
2430 if (related_stream
>= 0 && wanted_stream_nb
< 0) {
2431 AVProgram
*p
= find_program_from_stream(ic
, related_stream
);
2433 program
= p
->stream_index
;
2434 nb_streams
= p
->nb_stream_indexes
;
2437 for (i
= 0; i
< nb_streams
; i
++) {
2438 int real_stream_index
= program ? program
[i
] : i
;
2439 AVStream
*st
= ic
->streams
[real_stream_index
];
2440 AVCodecContext
*avctx
= st
->codec
;
2441 if (avctx
->codec_type
!= type
)
2443 if (wanted_stream_nb
>= 0 && real_stream_index
!= wanted_stream_nb
)
2445 if (st
->disposition
& (AV_DISPOSITION_HEARING_IMPAIRED
|AV_DISPOSITION_VISUAL_IMPAIRED
))
2448 decoder
= avcodec_find_decoder(st
->codec
->codec_id
);
2451 ret
= AVERROR_DECODER_NOT_FOUND
;
2455 if (best_count
>= st
->codec_info_nb_frames
)
2457 best_count
= st
->codec_info_nb_frames
;
2458 ret
= real_stream_index
;
2459 best_decoder
= decoder
;
2460 if (program
&& i
== nb_streams
- 1 && ret
< 0) {
2462 nb_streams
= ic
->nb_streams
;
2463 i
= 0; /* no related stream found, try again with everything */
2467 *decoder_ret
= best_decoder
;
2471 /*******************************************************/
2473 int av_read_play(AVFormatContext
*s
)
2475 if (s
->iformat
->read_play
)
2476 return s
->iformat
->read_play(s
);
2478 return avio_pause(s
->pb
, 0);
2479 return AVERROR(ENOSYS
);
2482 int av_read_pause(AVFormatContext
*s
)
2484 if (s
->iformat
->read_pause
)
2485 return s
->iformat
->read_pause(s
);
2487 return avio_pause(s
->pb
, 1);
2488 return AVERROR(ENOSYS
);
2491 void avformat_free_context(AVFormatContext
*s
)
2497 if (s
->iformat
&& s
->iformat
->priv_class
&& s
->priv_data
)
2498 av_opt_free(s
->priv_data
);
2500 for(i
=0;i
<s
->nb_streams
;i
++) {
2501 /* free all data in a stream component */
2504 av_parser_close(st
->parser
);
2506 if (st
->attached_pic
.data
)
2507 av_free_packet(&st
->attached_pic
);
2508 av_dict_free(&st
->metadata
);
2509 av_freep(&st
->probe_data
.buf
);
2510 av_free(st
->index_entries
);
2511 av_free(st
->codec
->extradata
);
2512 av_free(st
->codec
->subtitle_header
);
2514 av_free(st
->priv_data
);
2518 for(i
=s
->nb_programs
-1; i
>=0; i
--) {
2519 av_dict_free(&s
->programs
[i
]->metadata
);
2520 av_freep(&s
->programs
[i
]->stream_index
);
2521 av_freep(&s
->programs
[i
]);
2523 av_freep(&s
->programs
);
2524 av_freep(&s
->priv_data
);
2525 while(s
->nb_chapters
--) {
2526 av_dict_free(&s
->chapters
[s
->nb_chapters
]->metadata
);
2527 av_free(s
->chapters
[s
->nb_chapters
]);
2529 av_freep(&s
->chapters
);
2530 av_dict_free(&s
->metadata
);
2531 av_freep(&s
->streams
);
2535 void avformat_close_input(AVFormatContext
**ps
)
2537 AVFormatContext
*s
= *ps
;
2538 AVIOContext
*pb
= s
->pb
;
2540 if ((s
->iformat
&& s
->iformat
->flags
& AVFMT_NOFILE
) ||
2541 (s
->flags
& AVFMT_FLAG_CUSTOM_IO
))
2544 flush_packet_queue(s
);
2547 if (s
->iformat
->read_close
)
2548 s
->iformat
->read_close(s
);
2551 avformat_free_context(s
);
2558 AVStream
*avformat_new_stream(AVFormatContext
*s
, AVCodec
*c
)
2563 if (av_reallocp_array(&s
->streams
, s
->nb_streams
+ 1, sizeof(*s
->streams
)) < 0) {
2568 st
= av_mallocz(sizeof(AVStream
));
2571 if (!(st
->info
= av_mallocz(sizeof(*st
->info
)))) {
2576 st
->codec
= avcodec_alloc_context3(c
);
2578 /* no default bitrate if decoding */
2579 st
->codec
->bit_rate
= 0;
2581 st
->index
= s
->nb_streams
;
2582 st
->start_time
= AV_NOPTS_VALUE
;
2583 st
->duration
= AV_NOPTS_VALUE
;
2584 /* we set the current DTS to 0 so that formats without any timestamps
2585 but durations get some timestamps, formats with some unknown
2586 timestamps have their first few packets buffered and the
2587 timestamps corrected before they are returned to the user */
2589 st
->first_dts
= AV_NOPTS_VALUE
;
2590 st
->probe_packets
= MAX_PROBE_PACKETS
;
2592 /* default pts setting is MPEG-like */
2593 avpriv_set_pts_info(st
, 33, 1, 90000);
2594 st
->last_IP_pts
= AV_NOPTS_VALUE
;
2595 for(i
=0; i
<MAX_REORDER_DELAY
+1; i
++)
2596 st
->pts_buffer
[i
]= AV_NOPTS_VALUE
;
2598 st
->sample_aspect_ratio
= (AVRational
){0,1};
2600 st
->info
->fps_first_dts
= AV_NOPTS_VALUE
;
2601 st
->info
->fps_last_dts
= AV_NOPTS_VALUE
;
2603 s
->streams
[s
->nb_streams
++] = st
;
2607 AVProgram
*av_new_program(AVFormatContext
*ac
, int id
)
2609 AVProgram
*program
=NULL
;
2612 av_dlog(ac
, "new_program: id=0x%04x\n", id
);
2614 for(i
=0; i
<ac
->nb_programs
; i
++)
2615 if(ac
->programs
[i
]->id
== id
)
2616 program
= ac
->programs
[i
];
2619 program
= av_mallocz(sizeof(AVProgram
));
2622 dynarray_add(&ac
->programs
, &ac
->nb_programs
, program
);
2623 program
->discard
= AVDISCARD_NONE
;
2630 AVChapter
*avpriv_new_chapter(AVFormatContext
*s
, int id
, AVRational time_base
, int64_t start
, int64_t end
, const char *title
)
2632 AVChapter
*chapter
= NULL
;
2635 for(i
=0; i
<s
->nb_chapters
; i
++)
2636 if(s
->chapters
[i
]->id
== id
)
2637 chapter
= s
->chapters
[i
];
2640 chapter
= av_mallocz(sizeof(AVChapter
));
2643 dynarray_add(&s
->chapters
, &s
->nb_chapters
, chapter
);
2645 av_dict_set(&chapter
->metadata
, "title", title
, 0);
2647 chapter
->time_base
= time_base
;
2648 chapter
->start
= start
;
2654 void ff_program_add_stream_index(AVFormatContext
*ac
, int progid
, unsigned int idx
)
2657 AVProgram
*program
=NULL
;
2659 if (idx
>= ac
->nb_streams
) {
2660 av_log(ac
, AV_LOG_ERROR
, "stream index %d is not valid\n", idx
);
2664 for(i
=0; i
<ac
->nb_programs
; i
++){
2665 if(ac
->programs
[i
]->id
!= progid
)
2667 program
= ac
->programs
[i
];
2668 for(j
=0; j
<program
->nb_stream_indexes
; j
++)
2669 if(program
->stream_index
[j
] == idx
)
2672 if (av_reallocp_array(&program
->stream_index
,
2673 program
->nb_stream_indexes
+ 1,
2674 sizeof(*program
->stream_index
)) < 0) {
2675 program
->nb_stream_indexes
= 0;
2678 program
->stream_index
[program
->nb_stream_indexes
++] = idx
;
2683 static void print_fps(double d
, const char *postfix
){
2684 uint64_t v
= lrintf(d
*100);
2685 if (v
% 100 ) av_log(NULL
, AV_LOG_INFO
, ", %3.2f %s", d
, postfix
);
2686 else if(v
%(100*1000)) av_log(NULL
, AV_LOG_INFO
, ", %1.0f %s", d
, postfix
);
2687 else av_log(NULL
, AV_LOG_INFO
, ", %1.0fk %s", d
/1000, postfix
);
2690 static void dump_metadata(void *ctx
, AVDictionary
*m
, const char *indent
)
2692 if(m
&& !(av_dict_count(m
) == 1 && av_dict_get(m
, "language", NULL
, 0))){
2693 AVDictionaryEntry
*tag
=NULL
;
2695 av_log(ctx
, AV_LOG_INFO
, "%sMetadata:\n", indent
);
2696 while((tag
=av_dict_get(m
, "", tag
, AV_DICT_IGNORE_SUFFIX
))) {
2697 if(strcmp("language", tag
->key
))
2698 av_log(ctx
, AV_LOG_INFO
, "%s %-16s: %s\n", indent
, tag
->key
, tag
->value
);
2703 /* "user interface" functions */
2704 static void dump_stream_format(AVFormatContext
*ic
, int i
, int index
, int is_output
)
2707 int flags
= (is_output ? ic
->oformat
->flags
: ic
->iformat
->flags
);
2708 AVStream
*st
= ic
->streams
[i
];
2709 int g
= av_gcd(st
->time_base
.num
, st
->time_base
.den
);
2710 AVDictionaryEntry
*lang
= av_dict_get(st
->metadata
, "language", NULL
, 0);
2711 avcodec_string(buf
, sizeof(buf
), st
->codec
, is_output
);
2712 av_log(NULL
, AV_LOG_INFO
, " Stream #%d.%d", index
, i
);
2713 /* the pid is an important information, so we display it */
2714 /* XXX: add a generic system */
2715 if (flags
& AVFMT_SHOW_IDS
)
2716 av_log(NULL
, AV_LOG_INFO
, "[0x%x]", st
->id
);
2718 av_log(NULL
, AV_LOG_INFO
, "(%s)", lang
->value
);
2719 av_log(NULL
, AV_LOG_DEBUG
, ", %d, %d/%d", st
->codec_info_nb_frames
, st
->time_base
.num
/g
, st
->time_base
.den
/g
);
2720 av_log(NULL
, AV_LOG_INFO
, ": %s", buf
);
2721 if (st
->sample_aspect_ratio
.num
&& // default
2722 av_cmp_q(st
->sample_aspect_ratio
, st
->codec
->sample_aspect_ratio
)) {
2723 AVRational display_aspect_ratio
;
2724 av_reduce(&display_aspect_ratio
.num
, &display_aspect_ratio
.den
,
2725 st
->codec
->width
*st
->sample_aspect_ratio
.num
,
2726 st
->codec
->height
*st
->sample_aspect_ratio
.den
,
2728 av_log(NULL
, AV_LOG_INFO
, ", PAR %d:%d DAR %d:%d",
2729 st
->sample_aspect_ratio
.num
, st
->sample_aspect_ratio
.den
,
2730 display_aspect_ratio
.num
, display_aspect_ratio
.den
);
2732 if(st
->codec
->codec_type
== AVMEDIA_TYPE_VIDEO
){
2733 if(st
->avg_frame_rate
.den
&& st
->avg_frame_rate
.num
)
2734 print_fps(av_q2d(st
->avg_frame_rate
), "fps");
2735 if(st
->time_base
.den
&& st
->time_base
.num
)
2736 print_fps(1/av_q2d(st
->time_base
), "tbn");
2737 if(st
->codec
->time_base
.den
&& st
->codec
->time_base
.num
)
2738 print_fps(1/av_q2d(st
->codec
->time_base
), "tbc");
2740 if (st
->disposition
& AV_DISPOSITION_DEFAULT
)
2741 av_log(NULL
, AV_LOG_INFO
, " (default)");
2742 if (st
->disposition
& AV_DISPOSITION_DUB
)
2743 av_log(NULL
, AV_LOG_INFO
, " (dub)");
2744 if (st
->disposition
& AV_DISPOSITION_ORIGINAL
)
2745 av_log(NULL
, AV_LOG_INFO
, " (original)");
2746 if (st
->disposition
& AV_DISPOSITION_COMMENT
)
2747 av_log(NULL
, AV_LOG_INFO
, " (comment)");
2748 if (st
->disposition
& AV_DISPOSITION_LYRICS
)
2749 av_log(NULL
, AV_LOG_INFO
, " (lyrics)");
2750 if (st
->disposition
& AV_DISPOSITION_KARAOKE
)
2751 av_log(NULL
, AV_LOG_INFO
, " (karaoke)");
2752 if (st
->disposition
& AV_DISPOSITION_FORCED
)
2753 av_log(NULL
, AV_LOG_INFO
, " (forced)");
2754 if (st
->disposition
& AV_DISPOSITION_HEARING_IMPAIRED
)
2755 av_log(NULL
, AV_LOG_INFO
, " (hearing impaired)");
2756 if (st
->disposition
& AV_DISPOSITION_VISUAL_IMPAIRED
)
2757 av_log(NULL
, AV_LOG_INFO
, " (visual impaired)");
2758 if (st
->disposition
& AV_DISPOSITION_CLEAN_EFFECTS
)
2759 av_log(NULL
, AV_LOG_INFO
, " (clean effects)");
2760 av_log(NULL
, AV_LOG_INFO
, "\n");
2761 dump_metadata(NULL
, st
->metadata
, " ");
2764 void av_dump_format(AVFormatContext
*ic
,
2770 uint8_t *printed
= ic
->nb_streams ?
av_mallocz(ic
->nb_streams
) : NULL
;
2771 if (ic
->nb_streams
&& !printed
)
2774 av_log(NULL
, AV_LOG_INFO
, "%s #%d, %s, %s '%s':\n",
2775 is_output ?
"Output" : "Input",
2777 is_output ? ic
->oformat
->name
: ic
->iformat
->name
,
2778 is_output ?
"to" : "from", url
);
2779 dump_metadata(NULL
, ic
->metadata
, " ");
2781 av_log(NULL
, AV_LOG_INFO
, " Duration: ");
2782 if (ic
->duration
!= AV_NOPTS_VALUE
) {
2783 int hours
, mins
, secs
, us
;
2784 secs
= ic
->duration
/ AV_TIME_BASE
;
2785 us
= ic
->duration
% AV_TIME_BASE
;
2790 av_log(NULL
, AV_LOG_INFO
, "%02d:%02d:%02d.%02d", hours
, mins
, secs
,
2791 (100 * us
) / AV_TIME_BASE
);
2793 av_log(NULL
, AV_LOG_INFO
, "N/A");
2795 if (ic
->start_time
!= AV_NOPTS_VALUE
) {
2797 av_log(NULL
, AV_LOG_INFO
, ", start: ");
2798 secs
= ic
->start_time
/ AV_TIME_BASE
;
2799 us
= abs(ic
->start_time
% AV_TIME_BASE
);
2800 av_log(NULL
, AV_LOG_INFO
, "%d.%06d",
2801 secs
, (int)av_rescale(us
, 1000000, AV_TIME_BASE
));
2803 av_log(NULL
, AV_LOG_INFO
, ", bitrate: ");
2805 av_log(NULL
, AV_LOG_INFO
,"%d kb/s", ic
->bit_rate
/ 1000);
2807 av_log(NULL
, AV_LOG_INFO
, "N/A");
2809 av_log(NULL
, AV_LOG_INFO
, "\n");
2811 for (i
= 0; i
< ic
->nb_chapters
; i
++) {
2812 AVChapter
*ch
= ic
->chapters
[i
];
2813 av_log(NULL
, AV_LOG_INFO
, " Chapter #%d.%d: ", index
, i
);
2814 av_log(NULL
, AV_LOG_INFO
, "start %f, ", ch
->start
* av_q2d(ch
->time_base
));
2815 av_log(NULL
, AV_LOG_INFO
, "end %f\n", ch
->end
* av_q2d(ch
->time_base
));
2817 dump_metadata(NULL
, ch
->metadata
, " ");
2819 if(ic
->nb_programs
) {
2820 int j
, k
, total
= 0;
2821 for(j
=0; j
<ic
->nb_programs
; j
++) {
2822 AVDictionaryEntry
*name
= av_dict_get(ic
->programs
[j
]->metadata
,
2824 av_log(NULL
, AV_LOG_INFO
, " Program %d %s\n", ic
->programs
[j
]->id
,
2825 name ? name
->value
: "");
2826 dump_metadata(NULL
, ic
->programs
[j
]->metadata
, " ");
2827 for(k
=0; k
<ic
->programs
[j
]->nb_stream_indexes
; k
++) {
2828 dump_stream_format(ic
, ic
->programs
[j
]->stream_index
[k
], index
, is_output
);
2829 printed
[ic
->programs
[j
]->stream_index
[k
]] = 1;
2831 total
+= ic
->programs
[j
]->nb_stream_indexes
;
2833 if (total
< ic
->nb_streams
)
2834 av_log(NULL
, AV_LOG_INFO
, " No Program\n");
2836 for(i
=0;i
<ic
->nb_streams
;i
++)
2838 dump_stream_format(ic
, i
, index
, is_output
);
2843 uint64_t ff_ntp_time(void)
2845 return (av_gettime() / 1000) * 1000 + NTP_OFFSET_US
;
2848 int av_get_frame_filename(char *buf
, int buf_size
,
2849 const char *path
, int number
)
2852 char *q
, buf1
[20], c
;
2853 int nd
, len
, percentd_found
;
2865 while (av_isdigit(*p
)) {
2866 nd
= nd
* 10 + *p
++ - '0';
2869 } while (av_isdigit(c
));
2878 snprintf(buf1
, sizeof(buf1
), "%0*d", nd
, number
);
2880 if ((q
- buf
+ len
) > buf_size
- 1)
2882 memcpy(q
, buf1
, len
);
2890 if ((q
- buf
) < buf_size
- 1)
2894 if (!percentd_found
)
2903 static void hex_dump_internal(void *avcl
, FILE *f
, int level
,
2904 const uint8_t *buf
, int size
)
2907 #define PRINT(...) do { if (!f) av_log(avcl, level, __VA_ARGS__); else fprintf(f, __VA_ARGS__); } while(0)
2909 for(i
=0;i
<size
;i
+=16) {
2916 PRINT(" %02x", buf
[i
+j
]);
2921 for(j
=0;j
<len
;j
++) {
2923 if (c
< ' ' || c
> '~')
2932 void av_hex_dump(FILE *f
, const uint8_t *buf
, int size
)
2934 hex_dump_internal(NULL
, f
, 0, buf
, size
);
2937 void av_hex_dump_log(void *avcl
, int level
, const uint8_t *buf
, int size
)
2939 hex_dump_internal(avcl
, NULL
, level
, buf
, size
);
2942 static void pkt_dump_internal(void *avcl
, FILE *f
, int level
, AVPacket
*pkt
, int dump_payload
, AVRational time_base
)
2944 #define PRINT(...) do { if (!f) av_log(avcl, level, __VA_ARGS__); else fprintf(f, __VA_ARGS__); } while(0)
2945 PRINT("stream #%d:\n", pkt
->stream_index
);
2946 PRINT(" keyframe=%d\n", ((pkt
->flags
& AV_PKT_FLAG_KEY
) != 0));
2947 PRINT(" duration=%0.3f\n", pkt
->duration
* av_q2d(time_base
));
2948 /* DTS is _always_ valid after av_read_frame() */
2950 if (pkt
->dts
== AV_NOPTS_VALUE
)
2953 PRINT("%0.3f", pkt
->dts
* av_q2d(time_base
));
2954 /* PTS may not be known if B-frames are present. */
2956 if (pkt
->pts
== AV_NOPTS_VALUE
)
2959 PRINT("%0.3f", pkt
->pts
* av_q2d(time_base
));
2961 PRINT(" size=%d\n", pkt
->size
);
2964 av_hex_dump(f
, pkt
->data
, pkt
->size
);
2967 void av_pkt_dump2(FILE *f
, AVPacket
*pkt
, int dump_payload
, AVStream
*st
)
2969 pkt_dump_internal(NULL
, f
, 0, pkt
, dump_payload
, st
->time_base
);
2972 void av_pkt_dump_log2(void *avcl
, int level
, AVPacket
*pkt
, int dump_payload
,
2975 pkt_dump_internal(avcl
, NULL
, level
, pkt
, dump_payload
, st
->time_base
);
2978 void av_url_split(char *proto
, int proto_size
,
2979 char *authorization
, int authorization_size
,
2980 char *hostname
, int hostname_size
,
2982 char *path
, int path_size
,
2985 const char *p
, *ls
, *at
, *col
, *brk
;
2987 if (port_ptr
) *port_ptr
= -1;
2988 if (proto_size
> 0) proto
[0] = 0;
2989 if (authorization_size
> 0) authorization
[0] = 0;
2990 if (hostname_size
> 0) hostname
[0] = 0;
2991 if (path_size
> 0) path
[0] = 0;
2993 /* parse protocol */
2994 if ((p
= strchr(url
, ':'))) {
2995 av_strlcpy(proto
, url
, FFMIN(proto_size
, p
+ 1 - url
));
3000 /* no protocol means plain filename */
3001 av_strlcpy(path
, url
, path_size
);
3005 /* separate path from hostname */
3006 ls
= strchr(p
, '/');
3008 ls
= strchr(p
, '?');
3010 av_strlcpy(path
, ls
, path_size
);
3012 ls
= &p
[strlen(p
)]; // XXX
3014 /* the rest is hostname, use that to parse auth/port */
3016 /* authorization (user[:pass]@hostname) */
3017 if ((at
= strchr(p
, '@')) && at
< ls
) {
3018 av_strlcpy(authorization
, p
,
3019 FFMIN(authorization_size
, at
+ 1 - p
));
3020 p
= at
+ 1; /* skip '@' */
3023 if (*p
== '[' && (brk
= strchr(p
, ']')) && brk
< ls
) {
3025 av_strlcpy(hostname
, p
+ 1,
3026 FFMIN(hostname_size
, brk
- p
));
3027 if (brk
[1] == ':' && port_ptr
)
3028 *port_ptr
= atoi(brk
+ 2);
3029 } else if ((col
= strchr(p
, ':')) && col
< ls
) {
3030 av_strlcpy(hostname
, p
,
3031 FFMIN(col
+ 1 - p
, hostname_size
));
3032 if (port_ptr
) *port_ptr
= atoi(col
+ 1);
3034 av_strlcpy(hostname
, p
,
3035 FFMIN(ls
+ 1 - p
, hostname_size
));
3039 char *ff_data_to_hex(char *buff
, const uint8_t *src
, int s
, int lowercase
)
3042 static const char hex_table_uc
[16] = { '0', '1', '2', '3',
3045 'C', 'D', 'E', 'F' };
3046 static const char hex_table_lc
[16] = { '0', '1', '2', '3',
3049 'c', 'd', 'e', 'f' };
3050 const char *hex_table
= lowercase ? hex_table_lc
: hex_table_uc
;
3052 for(i
= 0; i
< s
; i
++) {
3053 buff
[i
* 2] = hex_table
[src
[i
] >> 4];
3054 buff
[i
* 2 + 1] = hex_table
[src
[i
] & 0xF];
3060 int ff_hex_to_data(uint8_t *data
, const char *p
)
3067 p
+= strspn(p
, SPACE_CHARS
);