Add scale filter.
[ffmpeg-lucabe.git] / libavformat / utils.c
bloba9d07fa64578cd5f8c4db6a008d81f09d99a7cfa
1 /*
2 * various utility functions for use within FFmpeg
3 * Copyright (c) 2000, 2001, 2002 Fabrice Bellard
5 * This file is part of FFmpeg.
7 * FFmpeg is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * FFmpeg is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with FFmpeg; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21 #include "avformat.h"
22 #include "internal.h"
23 #include "libavcodec/opt.h"
24 #include "metadata.h"
25 #include "libavutil/avstring.h"
26 #include "riff.h"
27 #include <sys/time.h>
28 #include <time.h>
29 #include <strings.h>
31 #undef NDEBUG
32 #include <assert.h>
34 /**
35 * @file libavformat/utils.c
36 * various utility functions for use within FFmpeg
39 unsigned avformat_version(void)
41 return LIBAVFORMAT_VERSION_INT;
44 /* fraction handling */
46 /**
47 * f = val + (num / den) + 0.5.
49 * 'num' is normalized so that it is such as 0 <= num < den.
51 * @param f fractional number
52 * @param val integer value
53 * @param num must be >= 0
54 * @param den must be >= 1
56 static void av_frac_init(AVFrac *f, int64_t val, int64_t num, int64_t den)
58 num += (den >> 1);
59 if (num >= den) {
60 val += num / den;
61 num = num % den;
63 f->val = val;
64 f->num = num;
65 f->den = den;
68 /**
69 * Fractional addition to f: f = f + (incr / f->den).
71 * @param f fractional number
72 * @param incr increment, can be positive or negative
74 static void av_frac_add(AVFrac *f, int64_t incr)
76 int64_t num, den;
78 num = f->num + incr;
79 den = f->den;
80 if (num < 0) {
81 f->val += num / den;
82 num = num % den;
83 if (num < 0) {
84 num += den;
85 f->val--;
87 } else if (num >= den) {
88 f->val += num / den;
89 num = num % den;
91 f->num = num;
94 /** head of registered input format linked list */
95 AVInputFormat *first_iformat = NULL;
96 /** head of registered output format linked list */
97 AVOutputFormat *first_oformat = NULL;
99 AVInputFormat *av_iformat_next(AVInputFormat *f)
101 if(f) return f->next;
102 else return first_iformat;
105 AVOutputFormat *av_oformat_next(AVOutputFormat *f)
107 if(f) return f->next;
108 else return first_oformat;
111 void av_register_input_format(AVInputFormat *format)
113 AVInputFormat **p;
114 p = &first_iformat;
115 while (*p != NULL) p = &(*p)->next;
116 *p = format;
117 format->next = NULL;
120 void av_register_output_format(AVOutputFormat *format)
122 AVOutputFormat **p;
123 p = &first_oformat;
124 while (*p != NULL) p = &(*p)->next;
125 *p = format;
126 format->next = NULL;
129 int match_ext(const char *filename, const char *extensions)
131 const char *ext, *p;
132 char ext1[32], *q;
134 if(!filename)
135 return 0;
137 ext = strrchr(filename, '.');
138 if (ext) {
139 ext++;
140 p = extensions;
141 for(;;) {
142 q = ext1;
143 while (*p != '\0' && *p != ',' && q-ext1<sizeof(ext1)-1)
144 *q++ = *p++;
145 *q = '\0';
146 if (!strcasecmp(ext1, ext))
147 return 1;
148 if (*p == '\0')
149 break;
150 p++;
153 return 0;
156 static int match_format(const char *name, const char *names)
158 const char *p;
159 int len, namelen;
161 if (!name || !names)
162 return 0;
164 namelen = strlen(name);
165 while ((p = strchr(names, ','))) {
166 len = FFMAX(p - names, namelen);
167 if (!strncasecmp(name, names, len))
168 return 1;
169 names = p+1;
171 return !strcasecmp(name, names);
174 AVOutputFormat *guess_format(const char *short_name, const char *filename,
175 const char *mime_type)
177 AVOutputFormat *fmt, *fmt_found;
178 int score_max, score;
180 /* specific test for image sequences */
181 #if CONFIG_IMAGE2_MUXER
182 if (!short_name && filename &&
183 av_filename_number_test(filename) &&
184 av_guess_image2_codec(filename) != CODEC_ID_NONE) {
185 return guess_format("image2", NULL, NULL);
187 #endif
188 /* Find the proper file type. */
189 fmt_found = NULL;
190 score_max = 0;
191 fmt = first_oformat;
192 while (fmt != NULL) {
193 score = 0;
194 if (fmt->name && short_name && !strcmp(fmt->name, short_name))
195 score += 100;
196 if (fmt->mime_type && mime_type && !strcmp(fmt->mime_type, mime_type))
197 score += 10;
198 if (filename && fmt->extensions &&
199 match_ext(filename, fmt->extensions)) {
200 score += 5;
202 if (score > score_max) {
203 score_max = score;
204 fmt_found = fmt;
206 fmt = fmt->next;
208 return fmt_found;
211 AVOutputFormat *guess_stream_format(const char *short_name, const char *filename,
212 const char *mime_type)
214 AVOutputFormat *fmt = guess_format(short_name, filename, mime_type);
216 if (fmt) {
217 AVOutputFormat *stream_fmt;
218 char stream_format_name[64];
220 snprintf(stream_format_name, sizeof(stream_format_name), "%s_stream", fmt->name);
221 stream_fmt = guess_format(stream_format_name, NULL, NULL);
223 if (stream_fmt)
224 fmt = stream_fmt;
227 return fmt;
230 enum CodecID av_guess_codec(AVOutputFormat *fmt, const char *short_name,
231 const char *filename, const char *mime_type, enum CodecType type){
232 if(type == CODEC_TYPE_VIDEO){
233 enum CodecID codec_id= CODEC_ID_NONE;
235 #if CONFIG_IMAGE2_MUXER
236 if(!strcmp(fmt->name, "image2") || !strcmp(fmt->name, "image2pipe")){
237 codec_id= av_guess_image2_codec(filename);
239 #endif
240 if(codec_id == CODEC_ID_NONE)
241 codec_id= fmt->video_codec;
242 return codec_id;
243 }else if(type == CODEC_TYPE_AUDIO)
244 return fmt->audio_codec;
245 else
246 return CODEC_ID_NONE;
249 AVInputFormat *av_find_input_format(const char *short_name)
251 AVInputFormat *fmt;
252 for(fmt = first_iformat; fmt != NULL; fmt = fmt->next) {
253 if (match_format(short_name, fmt->name))
254 return fmt;
256 return NULL;
259 /* memory handling */
262 int av_get_packet(ByteIOContext *s, AVPacket *pkt, int size)
264 int ret= av_new_packet(pkt, size);
266 if(ret<0)
267 return ret;
269 pkt->pos= url_ftell(s);
271 ret= get_buffer(s, pkt->data, size);
272 if(ret<=0)
273 av_free_packet(pkt);
274 else
275 av_shrink_packet(pkt, ret);
277 return ret;
281 int av_filename_number_test(const char *filename)
283 char buf[1024];
284 return filename && (av_get_frame_filename(buf, sizeof(buf), filename, 1)>=0);
287 static AVInputFormat *av_probe_input_format2(AVProbeData *pd, int is_opened, int *score_max)
289 AVInputFormat *fmt1, *fmt;
290 int score;
292 fmt = NULL;
293 for(fmt1 = first_iformat; fmt1 != NULL; fmt1 = fmt1->next) {
294 if (!is_opened == !(fmt1->flags & AVFMT_NOFILE))
295 continue;
296 score = 0;
297 if (fmt1->read_probe) {
298 score = fmt1->read_probe(pd);
299 } else if (fmt1->extensions) {
300 if (match_ext(pd->filename, fmt1->extensions)) {
301 score = 50;
304 if (score > *score_max) {
305 *score_max = score;
306 fmt = fmt1;
307 }else if (score == *score_max)
308 fmt = NULL;
310 return fmt;
313 AVInputFormat *av_probe_input_format(AVProbeData *pd, int is_opened){
314 int score=0;
315 return av_probe_input_format2(pd, is_opened, &score);
318 static int set_codec_from_probe_data(AVFormatContext *s, AVStream *st, AVProbeData *pd, int score)
320 AVInputFormat *fmt;
321 fmt = av_probe_input_format2(pd, 1, &score);
323 if (fmt) {
324 av_log(s, AV_LOG_DEBUG, "Probe with size=%d, packets=%d detected %s with score=%d\n",
325 pd->buf_size, MAX_PROBE_PACKETS - st->probe_packets, fmt->name, score);
326 if (!strcmp(fmt->name, "mp3")) {
327 st->codec->codec_id = CODEC_ID_MP3;
328 st->codec->codec_type = CODEC_TYPE_AUDIO;
329 } else if (!strcmp(fmt->name, "ac3")) {
330 st->codec->codec_id = CODEC_ID_AC3;
331 st->codec->codec_type = CODEC_TYPE_AUDIO;
332 } else if (!strcmp(fmt->name, "eac3")) {
333 st->codec->codec_id = CODEC_ID_EAC3;
334 st->codec->codec_type = CODEC_TYPE_AUDIO;
335 } else if (!strcmp(fmt->name, "mpegvideo")) {
336 st->codec->codec_id = CODEC_ID_MPEG2VIDEO;
337 st->codec->codec_type = CODEC_TYPE_VIDEO;
338 } else if (!strcmp(fmt->name, "m4v")) {
339 st->codec->codec_id = CODEC_ID_MPEG4;
340 st->codec->codec_type = CODEC_TYPE_VIDEO;
341 } else if (!strcmp(fmt->name, "h264")) {
342 st->codec->codec_id = CODEC_ID_H264;
343 st->codec->codec_type = CODEC_TYPE_VIDEO;
344 } else if (!strcmp(fmt->name, "dts")) {
345 st->codec->codec_id = CODEC_ID_DTS;
346 st->codec->codec_type = CODEC_TYPE_AUDIO;
349 return !!fmt;
352 /************************************************************/
353 /* input media file */
356 * Open a media file from an IO stream. 'fmt' must be specified.
358 int av_open_input_stream(AVFormatContext **ic_ptr,
359 ByteIOContext *pb, const char *filename,
360 AVInputFormat *fmt, AVFormatParameters *ap)
362 int err;
363 AVFormatContext *ic;
364 AVFormatParameters default_ap;
366 if(!ap){
367 ap=&default_ap;
368 memset(ap, 0, sizeof(default_ap));
371 if(!ap->prealloced_context)
372 ic = avformat_alloc_context();
373 else
374 ic = *ic_ptr;
375 if (!ic) {
376 err = AVERROR(ENOMEM);
377 goto fail;
379 ic->iformat = fmt;
380 ic->pb = pb;
381 ic->duration = AV_NOPTS_VALUE;
382 ic->start_time = AV_NOPTS_VALUE;
383 av_strlcpy(ic->filename, filename, sizeof(ic->filename));
385 /* allocate private data */
386 if (fmt->priv_data_size > 0) {
387 ic->priv_data = av_mallocz(fmt->priv_data_size);
388 if (!ic->priv_data) {
389 err = AVERROR(ENOMEM);
390 goto fail;
392 } else {
393 ic->priv_data = NULL;
396 if (ic->iformat->read_header) {
397 err = ic->iformat->read_header(ic, ap);
398 if (err < 0)
399 goto fail;
402 if (pb && !ic->data_offset)
403 ic->data_offset = url_ftell(ic->pb);
405 #if LIBAVFORMAT_VERSION_MAJOR < 53
406 ff_metadata_demux_compat(ic);
407 #endif
409 ic->raw_packet_buffer_remaining_size = RAW_PACKET_BUFFER_SIZE;
411 *ic_ptr = ic;
412 return 0;
413 fail:
414 if (ic) {
415 int i;
416 av_freep(&ic->priv_data);
417 for(i=0;i<ic->nb_streams;i++) {
418 AVStream *st = ic->streams[i];
419 if (st) {
420 av_free(st->priv_data);
421 av_free(st->codec->extradata);
423 av_free(st);
426 av_free(ic);
427 *ic_ptr = NULL;
428 return err;
431 /** size of probe buffer, for guessing file type from file contents */
432 #define PROBE_BUF_MIN 2048
433 #define PROBE_BUF_MAX (1<<20)
435 int av_open_input_file(AVFormatContext **ic_ptr, const char *filename,
436 AVInputFormat *fmt,
437 int buf_size,
438 AVFormatParameters *ap)
440 int err, probe_size;
441 AVProbeData probe_data, *pd = &probe_data;
442 ByteIOContext *pb = NULL;
443 void *logctx= ap && ap->prealloced_context ? *ic_ptr : NULL;
445 pd->filename = "";
446 if (filename)
447 pd->filename = filename;
448 pd->buf = NULL;
449 pd->buf_size = 0;
451 if (!fmt) {
452 /* guess format if no file can be opened */
453 fmt = av_probe_input_format(pd, 0);
456 /* Do not open file if the format does not need it. XXX: specific
457 hack needed to handle RTSP/TCP */
458 if (!fmt || !(fmt->flags & AVFMT_NOFILE)) {
459 /* if no file needed do not try to open one */
460 if ((err=url_fopen(&pb, filename, URL_RDONLY)) < 0) {
461 goto fail;
463 if (buf_size > 0) {
464 url_setbufsize(pb, buf_size);
467 for(probe_size= PROBE_BUF_MIN; probe_size<=PROBE_BUF_MAX && !fmt; probe_size<<=1){
468 int score= probe_size < PROBE_BUF_MAX ? AVPROBE_SCORE_MAX/4 : 0;
469 /* read probe data */
470 pd->buf= av_realloc(pd->buf, probe_size + AVPROBE_PADDING_SIZE);
471 pd->buf_size = get_buffer(pb, pd->buf, probe_size);
473 if ((int)pd->buf_size < 0) {
474 err = pd->buf_size;
475 goto fail;
478 memset(pd->buf+pd->buf_size, 0, AVPROBE_PADDING_SIZE);
479 if (url_fseek(pb, 0, SEEK_SET) < 0) {
480 url_fclose(pb);
481 if (url_fopen(&pb, filename, URL_RDONLY) < 0) {
482 pb = NULL;
483 err = AVERROR(EIO);
484 goto fail;
487 /* guess file format */
488 fmt = av_probe_input_format2(pd, 1, &score);
489 if(fmt){
490 if(score <= AVPROBE_SCORE_MAX/4){ //this can only be true in the last iteration
491 av_log(logctx, AV_LOG_WARNING, "Format detected only with low score of %d, misdetection possible!\n", score);
492 }else
493 av_log(logctx, AV_LOG_DEBUG, "Probed with size=%d and score=%d\n", probe_size, score);
496 av_freep(&pd->buf);
499 /* if still no format found, error */
500 if (!fmt) {
501 err = AVERROR_NOFMT;
502 goto fail;
505 /* check filename in case an image number is expected */
506 if (fmt->flags & AVFMT_NEEDNUMBER) {
507 if (!av_filename_number_test(filename)) {
508 err = AVERROR_NUMEXPECTED;
509 goto fail;
512 err = av_open_input_stream(ic_ptr, pb, filename, fmt, ap);
513 if (err)
514 goto fail;
515 return 0;
516 fail:
517 av_freep(&pd->buf);
518 if (pb)
519 url_fclose(pb);
520 if (ap && ap->prealloced_context)
521 av_free(*ic_ptr);
522 *ic_ptr = NULL;
523 return err;
527 /*******************************************************/
529 static AVPacket *add_to_pktbuf(AVPacketList **packet_buffer, AVPacket *pkt,
530 AVPacketList **plast_pktl){
531 AVPacketList *pktl = av_mallocz(sizeof(AVPacketList));
532 if (!pktl)
533 return NULL;
535 if (*packet_buffer)
536 (*plast_pktl)->next = pktl;
537 else
538 *packet_buffer = pktl;
540 /* add the packet in the buffered packet list */
541 *plast_pktl = pktl;
542 pktl->pkt= *pkt;
543 return &pktl->pkt;
546 int av_read_packet(AVFormatContext *s, AVPacket *pkt)
548 int ret, i;
549 AVStream *st;
551 for(;;){
552 AVPacketList *pktl = s->raw_packet_buffer;
554 if (pktl) {
555 *pkt = pktl->pkt;
556 if(s->streams[pkt->stream_index]->codec->codec_id != CODEC_ID_PROBE ||
557 !s->streams[pkt->stream_index]->probe_packets ||
558 s->raw_packet_buffer_remaining_size < pkt->size){
559 AVProbeData *pd = &s->streams[pkt->stream_index]->probe_data;
560 av_freep(&pd->buf);
561 pd->buf_size = 0;
562 s->raw_packet_buffer = pktl->next;
563 s->raw_packet_buffer_remaining_size += pkt->size;
564 av_free(pktl);
565 return 0;
569 av_init_packet(pkt);
570 ret= s->iformat->read_packet(s, pkt);
571 if (ret < 0) {
572 if (!pktl || ret == AVERROR(EAGAIN))
573 return ret;
574 for (i = 0; i < s->nb_streams; i++)
575 s->streams[i]->probe_packets = 0;
576 continue;
578 st= s->streams[pkt->stream_index];
580 switch(st->codec->codec_type){
581 case CODEC_TYPE_VIDEO:
582 if(s->video_codec_id) st->codec->codec_id= s->video_codec_id;
583 break;
584 case CODEC_TYPE_AUDIO:
585 if(s->audio_codec_id) st->codec->codec_id= s->audio_codec_id;
586 break;
587 case CODEC_TYPE_SUBTITLE:
588 if(s->subtitle_codec_id)st->codec->codec_id= s->subtitle_codec_id;
589 break;
592 if(!pktl && (st->codec->codec_id != CODEC_ID_PROBE ||
593 !st->probe_packets))
594 return ret;
596 add_to_pktbuf(&s->raw_packet_buffer, pkt, &s->raw_packet_buffer_end);
597 s->raw_packet_buffer_remaining_size -= pkt->size;
599 if(st->codec->codec_id == CODEC_ID_PROBE){
600 AVProbeData *pd = &st->probe_data;
602 --st->probe_packets;
604 pd->buf = av_realloc(pd->buf, pd->buf_size+pkt->size+AVPROBE_PADDING_SIZE);
605 memcpy(pd->buf+pd->buf_size, pkt->data, pkt->size);
606 pd->buf_size += pkt->size;
607 memset(pd->buf+pd->buf_size, 0, AVPROBE_PADDING_SIZE);
609 if(av_log2(pd->buf_size) != av_log2(pd->buf_size - pkt->size)){
610 set_codec_from_probe_data(s, st, pd, 1);
611 if(st->codec->codec_id != CODEC_ID_PROBE){
612 pd->buf_size=0;
613 av_freep(&pd->buf);
620 /**********************************************************/
623 * Get the number of samples of an audio frame. Return -1 on error.
625 static int get_audio_frame_size(AVCodecContext *enc, int size)
627 int frame_size;
629 if(enc->codec_id == CODEC_ID_VORBIS)
630 return -1;
632 if (enc->frame_size <= 1) {
633 int bits_per_sample = av_get_bits_per_sample(enc->codec_id);
635 if (bits_per_sample) {
636 if (enc->channels == 0)
637 return -1;
638 frame_size = (size << 3) / (bits_per_sample * enc->channels);
639 } else {
640 /* used for example by ADPCM codecs */
641 if (enc->bit_rate == 0)
642 return -1;
643 frame_size = ((int64_t)size * 8 * enc->sample_rate) / enc->bit_rate;
645 } else {
646 frame_size = enc->frame_size;
648 return frame_size;
653 * Return the frame duration in seconds. Return 0 if not available.
655 static void compute_frame_duration(int *pnum, int *pden, AVStream *st,
656 AVCodecParserContext *pc, AVPacket *pkt)
658 int frame_size;
660 *pnum = 0;
661 *pden = 0;
662 switch(st->codec->codec_type) {
663 case CODEC_TYPE_VIDEO:
664 if(st->time_base.num*1000LL > st->time_base.den){
665 *pnum = st->time_base.num;
666 *pden = st->time_base.den;
667 }else if(st->codec->time_base.num*1000LL > st->codec->time_base.den){
668 *pnum = st->codec->time_base.num;
669 *pden = st->codec->time_base.den;
670 if (pc && pc->repeat_pict) {
671 *pnum = (*pnum) * (1 + pc->repeat_pict);
674 break;
675 case CODEC_TYPE_AUDIO:
676 frame_size = get_audio_frame_size(st->codec, pkt->size);
677 if (frame_size < 0)
678 break;
679 *pnum = frame_size;
680 *pden = st->codec->sample_rate;
681 break;
682 default:
683 break;
687 static int is_intra_only(AVCodecContext *enc){
688 if(enc->codec_type == CODEC_TYPE_AUDIO){
689 return 1;
690 }else if(enc->codec_type == CODEC_TYPE_VIDEO){
691 switch(enc->codec_id){
692 case CODEC_ID_MJPEG:
693 case CODEC_ID_MJPEGB:
694 case CODEC_ID_LJPEG:
695 case CODEC_ID_RAWVIDEO:
696 case CODEC_ID_DVVIDEO:
697 case CODEC_ID_HUFFYUV:
698 case CODEC_ID_FFVHUFF:
699 case CODEC_ID_ASV1:
700 case CODEC_ID_ASV2:
701 case CODEC_ID_VCR1:
702 case CODEC_ID_DNXHD:
703 case CODEC_ID_JPEG2000:
704 return 1;
705 default: break;
708 return 0;
711 static void update_initial_timestamps(AVFormatContext *s, int stream_index,
712 int64_t dts, int64_t pts)
714 AVStream *st= s->streams[stream_index];
715 AVPacketList *pktl= s->packet_buffer;
717 if(st->first_dts != AV_NOPTS_VALUE || dts == AV_NOPTS_VALUE || st->cur_dts == AV_NOPTS_VALUE)
718 return;
720 st->first_dts= dts - st->cur_dts;
721 st->cur_dts= dts;
723 for(; pktl; pktl= pktl->next){
724 if(pktl->pkt.stream_index != stream_index)
725 continue;
726 //FIXME think more about this check
727 if(pktl->pkt.pts != AV_NOPTS_VALUE && pktl->pkt.pts == pktl->pkt.dts)
728 pktl->pkt.pts += st->first_dts;
730 if(pktl->pkt.dts != AV_NOPTS_VALUE)
731 pktl->pkt.dts += st->first_dts;
733 if(st->start_time == AV_NOPTS_VALUE && pktl->pkt.pts != AV_NOPTS_VALUE)
734 st->start_time= pktl->pkt.pts;
736 if (st->start_time == AV_NOPTS_VALUE)
737 st->start_time = pts;
740 static void update_initial_durations(AVFormatContext *s, AVStream *st, AVPacket *pkt)
742 AVPacketList *pktl= s->packet_buffer;
743 int64_t cur_dts= 0;
745 if(st->first_dts != AV_NOPTS_VALUE){
746 cur_dts= st->first_dts;
747 for(; pktl; pktl= pktl->next){
748 if(pktl->pkt.stream_index == pkt->stream_index){
749 if(pktl->pkt.pts != pktl->pkt.dts || pktl->pkt.dts != AV_NOPTS_VALUE || pktl->pkt.duration)
750 break;
751 cur_dts -= pkt->duration;
754 pktl= s->packet_buffer;
755 st->first_dts = cur_dts;
756 }else if(st->cur_dts)
757 return;
759 for(; pktl; pktl= pktl->next){
760 if(pktl->pkt.stream_index != pkt->stream_index)
761 continue;
762 if(pktl->pkt.pts == pktl->pkt.dts && pktl->pkt.dts == AV_NOPTS_VALUE
763 && !pktl->pkt.duration){
764 pktl->pkt.dts= cur_dts;
765 if(!st->codec->has_b_frames)
766 pktl->pkt.pts= cur_dts;
767 cur_dts += pkt->duration;
768 pktl->pkt.duration= pkt->duration;
769 }else
770 break;
772 if(st->first_dts == AV_NOPTS_VALUE)
773 st->cur_dts= cur_dts;
776 static void compute_pkt_fields(AVFormatContext *s, AVStream *st,
777 AVCodecParserContext *pc, AVPacket *pkt)
779 int num, den, presentation_delayed, delay, i;
780 int64_t offset;
782 if (st->codec->codec_id != CODEC_ID_H264 && pc && pc->pict_type == FF_B_TYPE)
783 //FIXME Set low_delay = 0 when has_b_frames = 1
784 st->codec->has_b_frames = 1;
786 /* do we have a video B-frame ? */
787 delay= st->codec->has_b_frames;
788 presentation_delayed = 0;
789 /* XXX: need has_b_frame, but cannot get it if the codec is
790 not initialized */
791 if (delay &&
792 pc && pc->pict_type != FF_B_TYPE)
793 presentation_delayed = 1;
795 if(pkt->pts != AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE && pkt->dts > pkt->pts && st->pts_wrap_bits<63
796 /*&& pkt->dts-(1LL<<st->pts_wrap_bits) < pkt->pts*/){
797 pkt->dts -= 1LL<<st->pts_wrap_bits;
800 // some mpeg2 in mpeg-ps lack dts (issue171 / input_file.mpg)
801 // we take the conservative approach and discard both
802 // Note, if this is misbehaving for a H.264 file then possibly presentation_delayed is not set correctly.
803 if(delay==1 && pkt->dts == pkt->pts && pkt->dts != AV_NOPTS_VALUE && presentation_delayed){
804 av_log(s, AV_LOG_WARNING, "invalid dts/pts combination\n");
805 pkt->dts= pkt->pts= AV_NOPTS_VALUE;
808 if (pkt->duration == 0) {
809 compute_frame_duration(&num, &den, st, pc, pkt);
810 if (den && num) {
811 pkt->duration = av_rescale(1, num * (int64_t)st->time_base.den, den * (int64_t)st->time_base.num);
813 if(pkt->duration != 0 && s->packet_buffer)
814 update_initial_durations(s, st, pkt);
818 /* correct timestamps with byte offset if demuxers only have timestamps
819 on packet boundaries */
820 if(pc && st->need_parsing == AVSTREAM_PARSE_TIMESTAMPS && pkt->size){
821 /* this will estimate bitrate based on this frame's duration and size */
822 offset = av_rescale(pc->offset, pkt->duration, pkt->size);
823 if(pkt->pts != AV_NOPTS_VALUE)
824 pkt->pts += offset;
825 if(pkt->dts != AV_NOPTS_VALUE)
826 pkt->dts += offset;
829 if (pc && pc->dts_sync_point >= 0) {
830 // we have synchronization info from the parser
831 int64_t den = st->codec->time_base.den * (int64_t) st->time_base.num;
832 if (den > 0) {
833 int64_t num = st->codec->time_base.num * (int64_t) st->time_base.den;
834 if (pkt->dts != AV_NOPTS_VALUE) {
835 // got DTS from the stream, update reference timestamp
836 st->reference_dts = pkt->dts - pc->dts_ref_dts_delta * num / den;
837 pkt->pts = pkt->dts + pc->pts_dts_delta * num / den;
838 } else if (st->reference_dts != AV_NOPTS_VALUE) {
839 // compute DTS based on reference timestamp
840 pkt->dts = st->reference_dts + pc->dts_ref_dts_delta * num / den;
841 pkt->pts = pkt->dts + pc->pts_dts_delta * num / den;
843 if (pc->dts_sync_point > 0)
844 st->reference_dts = pkt->dts; // new reference
848 /* This may be redundant, but it should not hurt. */
849 if(pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE && pkt->pts > pkt->dts)
850 presentation_delayed = 1;
852 // av_log(NULL, AV_LOG_DEBUG, "IN delayed:%d pts:%"PRId64", dts:%"PRId64" cur_dts:%"PRId64" st:%d pc:%p\n", presentation_delayed, pkt->pts, pkt->dts, st->cur_dts, pkt->stream_index, pc);
853 /* interpolate PTS and DTS if they are not present */
854 //We skip H264 currently because delay and has_b_frames are not reliably set
855 if((delay==0 || (delay==1 && pc)) && st->codec->codec_id != CODEC_ID_H264){
856 if (presentation_delayed) {
857 /* DTS = decompression timestamp */
858 /* PTS = presentation timestamp */
859 if (pkt->dts == AV_NOPTS_VALUE)
860 pkt->dts = st->last_IP_pts;
861 update_initial_timestamps(s, pkt->stream_index, pkt->dts, pkt->pts);
862 if (pkt->dts == AV_NOPTS_VALUE)
863 pkt->dts = st->cur_dts;
865 /* this is tricky: the dts must be incremented by the duration
866 of the frame we are displaying, i.e. the last I- or P-frame */
867 if (st->last_IP_duration == 0)
868 st->last_IP_duration = pkt->duration;
869 if(pkt->dts != AV_NOPTS_VALUE)
870 st->cur_dts = pkt->dts + st->last_IP_duration;
871 st->last_IP_duration = pkt->duration;
872 st->last_IP_pts= pkt->pts;
873 /* cannot compute PTS if not present (we can compute it only
874 by knowing the future */
875 } else if(pkt->pts != AV_NOPTS_VALUE || pkt->dts != AV_NOPTS_VALUE || pkt->duration){
876 if(pkt->pts != AV_NOPTS_VALUE && pkt->duration){
877 int64_t old_diff= FFABS(st->cur_dts - pkt->duration - pkt->pts);
878 int64_t new_diff= FFABS(st->cur_dts - pkt->pts);
879 if(old_diff < new_diff && old_diff < (pkt->duration>>3)){
880 pkt->pts += pkt->duration;
881 // av_log(NULL, AV_LOG_DEBUG, "id:%d old:%"PRId64" new:%"PRId64" dur:%d cur:%"PRId64" size:%d\n", pkt->stream_index, old_diff, new_diff, pkt->duration, st->cur_dts, pkt->size);
885 /* presentation is not delayed : PTS and DTS are the same */
886 if(pkt->pts == AV_NOPTS_VALUE)
887 pkt->pts = pkt->dts;
888 update_initial_timestamps(s, pkt->stream_index, pkt->pts, pkt->pts);
889 if(pkt->pts == AV_NOPTS_VALUE)
890 pkt->pts = st->cur_dts;
891 pkt->dts = pkt->pts;
892 if(pkt->pts != AV_NOPTS_VALUE)
893 st->cur_dts = pkt->pts + pkt->duration;
897 if(pkt->pts != AV_NOPTS_VALUE && delay <= MAX_REORDER_DELAY){
898 st->pts_buffer[0]= pkt->pts;
899 for(i=0; i<delay && st->pts_buffer[i] > st->pts_buffer[i+1]; i++)
900 FFSWAP(int64_t, st->pts_buffer[i], st->pts_buffer[i+1]);
901 if(pkt->dts == AV_NOPTS_VALUE)
902 pkt->dts= st->pts_buffer[0];
903 if(st->codec->codec_id == CODEC_ID_H264){ //we skiped it above so we try here
904 update_initial_timestamps(s, pkt->stream_index, pkt->dts, pkt->pts); // this should happen on the first packet
906 if(pkt->dts > st->cur_dts)
907 st->cur_dts = pkt->dts;
910 // av_log(NULL, AV_LOG_ERROR, "OUTdelayed:%d/%d pts:%"PRId64", dts:%"PRId64" cur_dts:%"PRId64"\n", presentation_delayed, delay, pkt->pts, pkt->dts, st->cur_dts);
912 /* update flags */
913 if(is_intra_only(st->codec))
914 pkt->flags |= PKT_FLAG_KEY;
915 else if (pc) {
916 pkt->flags = 0;
917 /* keyframe computation */
918 if (pc->key_frame == 1)
919 pkt->flags |= PKT_FLAG_KEY;
920 else if (pc->key_frame == -1 && pc->pict_type == FF_I_TYPE)
921 pkt->flags |= PKT_FLAG_KEY;
923 if (pc)
924 pkt->convergence_duration = pc->convergence_duration;
928 static int av_read_frame_internal(AVFormatContext *s, AVPacket *pkt)
930 AVStream *st;
931 int len, ret, i;
933 av_init_packet(pkt);
935 for(;;) {
936 /* select current input stream component */
937 st = s->cur_st;
938 if (st) {
939 if (!st->need_parsing || !st->parser) {
940 /* no parsing needed: we just output the packet as is */
941 /* raw data support */
942 *pkt = st->cur_pkt; st->cur_pkt.data= NULL;
943 compute_pkt_fields(s, st, NULL, pkt);
944 s->cur_st = NULL;
945 if ((s->iformat->flags & AVFMT_GENERIC_INDEX) &&
946 (pkt->flags & PKT_FLAG_KEY) && pkt->dts != AV_NOPTS_VALUE) {
947 ff_reduce_index(s, st->index);
948 av_add_index_entry(st, pkt->pos, pkt->dts, 0, 0, AVINDEX_KEYFRAME);
950 break;
951 } else if (st->cur_len > 0 && st->discard < AVDISCARD_ALL) {
952 len = av_parser_parse2(st->parser, st->codec, &pkt->data, &pkt->size,
953 st->cur_ptr, st->cur_len,
954 st->cur_pkt.pts, st->cur_pkt.dts,
955 st->cur_pkt.pos);
956 st->cur_pkt.pts = AV_NOPTS_VALUE;
957 st->cur_pkt.dts = AV_NOPTS_VALUE;
958 /* increment read pointer */
959 st->cur_ptr += len;
960 st->cur_len -= len;
962 /* return packet if any */
963 if (pkt->size) {
964 got_packet:
965 pkt->duration = 0;
966 pkt->stream_index = st->index;
967 pkt->pts = st->parser->pts;
968 pkt->dts = st->parser->dts;
969 pkt->pos = st->parser->pos;
970 pkt->destruct = NULL;
971 compute_pkt_fields(s, st, st->parser, pkt);
973 if((s->iformat->flags & AVFMT_GENERIC_INDEX) && pkt->flags & PKT_FLAG_KEY){
974 ff_reduce_index(s, st->index);
975 av_add_index_entry(st, st->parser->frame_offset, pkt->dts,
976 0, 0, AVINDEX_KEYFRAME);
979 break;
981 } else {
982 /* free packet */
983 av_free_packet(&st->cur_pkt);
984 s->cur_st = NULL;
986 } else {
987 AVPacket cur_pkt;
988 /* read next packet */
989 ret = av_read_packet(s, &cur_pkt);
990 if (ret < 0) {
991 if (ret == AVERROR(EAGAIN))
992 return ret;
993 /* return the last frames, if any */
994 for(i = 0; i < s->nb_streams; i++) {
995 st = s->streams[i];
996 if (st->parser && st->need_parsing) {
997 av_parser_parse2(st->parser, st->codec,
998 &pkt->data, &pkt->size,
999 NULL, 0,
1000 AV_NOPTS_VALUE, AV_NOPTS_VALUE,
1001 AV_NOPTS_VALUE);
1002 if (pkt->size)
1003 goto got_packet;
1006 /* no more packets: really terminate parsing */
1007 return ret;
1009 st = s->streams[cur_pkt.stream_index];
1010 st->cur_pkt= cur_pkt;
1012 if(st->cur_pkt.pts != AV_NOPTS_VALUE &&
1013 st->cur_pkt.dts != AV_NOPTS_VALUE &&
1014 st->cur_pkt.pts < st->cur_pkt.dts){
1015 av_log(s, AV_LOG_WARNING, "Invalid timestamps stream=%d, pts=%"PRId64", dts=%"PRId64", size=%d\n",
1016 st->cur_pkt.stream_index,
1017 st->cur_pkt.pts,
1018 st->cur_pkt.dts,
1019 st->cur_pkt.size);
1020 // av_free_packet(&st->cur_pkt);
1021 // return -1;
1024 if(s->debug & FF_FDEBUG_TS)
1025 av_log(s, AV_LOG_DEBUG, "av_read_packet stream=%d, pts=%"PRId64", dts=%"PRId64", size=%d, duration=%d, flags=%d\n",
1026 st->cur_pkt.stream_index,
1027 st->cur_pkt.pts,
1028 st->cur_pkt.dts,
1029 st->cur_pkt.size,
1030 st->cur_pkt.duration,
1031 st->cur_pkt.flags);
1033 s->cur_st = st;
1034 st->cur_ptr = st->cur_pkt.data;
1035 st->cur_len = st->cur_pkt.size;
1036 if (st->need_parsing && !st->parser) {
1037 st->parser = av_parser_init(st->codec->codec_id);
1038 if (!st->parser) {
1039 /* no parser available: just output the raw packets */
1040 st->need_parsing = AVSTREAM_PARSE_NONE;
1041 }else if(st->need_parsing == AVSTREAM_PARSE_HEADERS){
1042 st->parser->flags |= PARSER_FLAG_COMPLETE_FRAMES;
1044 if(st->parser && (s->iformat->flags & AVFMT_GENERIC_INDEX)){
1045 st->parser->next_frame_offset=
1046 st->parser->cur_offset= st->cur_pkt.pos;
1051 if(s->debug & FF_FDEBUG_TS)
1052 av_log(s, AV_LOG_DEBUG, "av_read_frame_internal stream=%d, pts=%"PRId64", dts=%"PRId64", size=%d, duration=%d, flags=%d\n",
1053 pkt->stream_index,
1054 pkt->pts,
1055 pkt->dts,
1056 pkt->size,
1057 pkt->duration,
1058 pkt->flags);
1060 return 0;
1063 int av_read_frame(AVFormatContext *s, AVPacket *pkt)
1065 AVPacketList *pktl;
1066 int eof=0;
1067 const int genpts= s->flags & AVFMT_FLAG_GENPTS;
1069 for(;;){
1070 pktl = s->packet_buffer;
1071 if (pktl) {
1072 AVPacket *next_pkt= &pktl->pkt;
1074 if(genpts && next_pkt->dts != AV_NOPTS_VALUE){
1075 while(pktl && next_pkt->pts == AV_NOPTS_VALUE){
1076 if( pktl->pkt.stream_index == next_pkt->stream_index
1077 && next_pkt->dts < pktl->pkt.dts
1078 && pktl->pkt.pts != pktl->pkt.dts //not b frame
1079 /*&& pktl->pkt.dts != AV_NOPTS_VALUE*/){
1080 next_pkt->pts= pktl->pkt.dts;
1082 pktl= pktl->next;
1084 pktl = s->packet_buffer;
1087 if( next_pkt->pts != AV_NOPTS_VALUE
1088 || next_pkt->dts == AV_NOPTS_VALUE
1089 || !genpts || eof){
1090 /* read packet from packet buffer, if there is data */
1091 *pkt = *next_pkt;
1092 s->packet_buffer = pktl->next;
1093 av_free(pktl);
1094 return 0;
1097 if(genpts){
1098 int ret= av_read_frame_internal(s, pkt);
1099 if(ret<0){
1100 if(pktl && ret != AVERROR(EAGAIN)){
1101 eof=1;
1102 continue;
1103 }else
1104 return ret;
1107 if(av_dup_packet(add_to_pktbuf(&s->packet_buffer, pkt,
1108 &s->packet_buffer_end)) < 0)
1109 return AVERROR(ENOMEM);
1110 }else{
1111 assert(!s->packet_buffer);
1112 return av_read_frame_internal(s, pkt);
1117 /* XXX: suppress the packet queue */
1118 static void flush_packet_queue(AVFormatContext *s)
1120 AVPacketList *pktl;
1122 for(;;) {
1123 pktl = s->packet_buffer;
1124 if (!pktl)
1125 break;
1126 s->packet_buffer = pktl->next;
1127 av_free_packet(&pktl->pkt);
1128 av_free(pktl);
1130 while(s->raw_packet_buffer){
1131 pktl = s->raw_packet_buffer;
1132 s->raw_packet_buffer = pktl->next;
1133 av_free_packet(&pktl->pkt);
1134 av_free(pktl);
1136 s->packet_buffer_end=
1137 s->raw_packet_buffer_end= NULL;
1138 s->raw_packet_buffer_remaining_size = RAW_PACKET_BUFFER_SIZE;
1141 /*******************************************************/
1142 /* seek support */
1144 int av_find_default_stream_index(AVFormatContext *s)
1146 int first_audio_index = -1;
1147 int i;
1148 AVStream *st;
1150 if (s->nb_streams <= 0)
1151 return -1;
1152 for(i = 0; i < s->nb_streams; i++) {
1153 st = s->streams[i];
1154 if (st->codec->codec_type == CODEC_TYPE_VIDEO) {
1155 return i;
1157 if (first_audio_index < 0 && st->codec->codec_type == CODEC_TYPE_AUDIO)
1158 first_audio_index = i;
1160 return first_audio_index >= 0 ? first_audio_index : 0;
1164 * Flush the frame reader.
1166 void av_read_frame_flush(AVFormatContext *s)
1168 AVStream *st;
1169 int i;
1171 flush_packet_queue(s);
1173 s->cur_st = NULL;
1175 /* for each stream, reset read state */
1176 for(i = 0; i < s->nb_streams; i++) {
1177 st = s->streams[i];
1179 if (st->parser) {
1180 av_parser_close(st->parser);
1181 st->parser = NULL;
1182 av_free_packet(&st->cur_pkt);
1184 st->last_IP_pts = AV_NOPTS_VALUE;
1185 st->cur_dts = AV_NOPTS_VALUE; /* we set the current DTS to an unspecified origin */
1186 st->reference_dts = AV_NOPTS_VALUE;
1187 /* fail safe */
1188 st->cur_ptr = NULL;
1189 st->cur_len = 0;
1191 st->probe_packets = MAX_PROBE_PACKETS;
1195 void av_update_cur_dts(AVFormatContext *s, AVStream *ref_st, int64_t timestamp){
1196 int i;
1198 for(i = 0; i < s->nb_streams; i++) {
1199 AVStream *st = s->streams[i];
1201 st->cur_dts = av_rescale(timestamp,
1202 st->time_base.den * (int64_t)ref_st->time_base.num,
1203 st->time_base.num * (int64_t)ref_st->time_base.den);
1207 void ff_reduce_index(AVFormatContext *s, int stream_index)
1209 AVStream *st= s->streams[stream_index];
1210 unsigned int max_entries= s->max_index_size / sizeof(AVIndexEntry);
1212 if((unsigned)st->nb_index_entries >= max_entries){
1213 int i;
1214 for(i=0; 2*i<st->nb_index_entries; i++)
1215 st->index_entries[i]= st->index_entries[2*i];
1216 st->nb_index_entries= i;
1220 int av_add_index_entry(AVStream *st,
1221 int64_t pos, int64_t timestamp, int size, int distance, int flags)
1223 AVIndexEntry *entries, *ie;
1224 int index;
1226 if((unsigned)st->nb_index_entries + 1 >= UINT_MAX / sizeof(AVIndexEntry))
1227 return -1;
1229 entries = av_fast_realloc(st->index_entries,
1230 &st->index_entries_allocated_size,
1231 (st->nb_index_entries + 1) *
1232 sizeof(AVIndexEntry));
1233 if(!entries)
1234 return -1;
1236 st->index_entries= entries;
1238 index= av_index_search_timestamp(st, timestamp, AVSEEK_FLAG_ANY);
1240 if(index<0){
1241 index= st->nb_index_entries++;
1242 ie= &entries[index];
1243 assert(index==0 || ie[-1].timestamp < timestamp);
1244 }else{
1245 ie= &entries[index];
1246 if(ie->timestamp != timestamp){
1247 if(ie->timestamp <= timestamp)
1248 return -1;
1249 memmove(entries + index + 1, entries + index, sizeof(AVIndexEntry)*(st->nb_index_entries - index));
1250 st->nb_index_entries++;
1251 }else if(ie->pos == pos && distance < ie->min_distance) //do not reduce the distance
1252 distance= ie->min_distance;
1255 ie->pos = pos;
1256 ie->timestamp = timestamp;
1257 ie->min_distance= distance;
1258 ie->size= size;
1259 ie->flags = flags;
1261 return index;
1264 int av_index_search_timestamp(AVStream *st, int64_t wanted_timestamp,
1265 int flags)
1267 AVIndexEntry *entries= st->index_entries;
1268 int nb_entries= st->nb_index_entries;
1269 int a, b, m;
1270 int64_t timestamp;
1272 a = - 1;
1273 b = nb_entries;
1275 while (b - a > 1) {
1276 m = (a + b) >> 1;
1277 timestamp = entries[m].timestamp;
1278 if(timestamp >= wanted_timestamp)
1279 b = m;
1280 if(timestamp <= wanted_timestamp)
1281 a = m;
1283 m= (flags & AVSEEK_FLAG_BACKWARD) ? a : b;
1285 if(!(flags & AVSEEK_FLAG_ANY)){
1286 while(m>=0 && m<nb_entries && !(entries[m].flags & AVINDEX_KEYFRAME)){
1287 m += (flags & AVSEEK_FLAG_BACKWARD) ? -1 : 1;
1291 if(m == nb_entries)
1292 return -1;
1293 return m;
1296 #define DEBUG_SEEK
1298 int av_seek_frame_binary(AVFormatContext *s, int stream_index, int64_t target_ts, int flags){
1299 AVInputFormat *avif= s->iformat;
1300 int64_t av_uninit(pos_min), av_uninit(pos_max), pos, pos_limit;
1301 int64_t ts_min, ts_max, ts;
1302 int index;
1303 AVStream *st;
1305 if (stream_index < 0)
1306 return -1;
1308 #ifdef DEBUG_SEEK
1309 av_log(s, AV_LOG_DEBUG, "read_seek: %d %"PRId64"\n", stream_index, target_ts);
1310 #endif
1312 ts_max=
1313 ts_min= AV_NOPTS_VALUE;
1314 pos_limit= -1; //gcc falsely says it may be uninitialized
1316 st= s->streams[stream_index];
1317 if(st->index_entries){
1318 AVIndexEntry *e;
1320 index= av_index_search_timestamp(st, target_ts, flags | AVSEEK_FLAG_BACKWARD); //FIXME whole func must be checked for non-keyframe entries in index case, especially read_timestamp()
1321 index= FFMAX(index, 0);
1322 e= &st->index_entries[index];
1324 if(e->timestamp <= target_ts || e->pos == e->min_distance){
1325 pos_min= e->pos;
1326 ts_min= e->timestamp;
1327 #ifdef DEBUG_SEEK
1328 av_log(s, AV_LOG_DEBUG, "using cached pos_min=0x%"PRIx64" dts_min=%"PRId64"\n",
1329 pos_min,ts_min);
1330 #endif
1331 }else{
1332 assert(index==0);
1335 index= av_index_search_timestamp(st, target_ts, flags & ~AVSEEK_FLAG_BACKWARD);
1336 assert(index < st->nb_index_entries);
1337 if(index >= 0){
1338 e= &st->index_entries[index];
1339 assert(e->timestamp >= target_ts);
1340 pos_max= e->pos;
1341 ts_max= e->timestamp;
1342 pos_limit= pos_max - e->min_distance;
1343 #ifdef DEBUG_SEEK
1344 av_log(s, AV_LOG_DEBUG, "using cached pos_max=0x%"PRIx64" pos_limit=0x%"PRIx64" dts_max=%"PRId64"\n",
1345 pos_max,pos_limit, ts_max);
1346 #endif
1350 pos= av_gen_search(s, stream_index, target_ts, pos_min, pos_max, pos_limit, ts_min, ts_max, flags, &ts, avif->read_timestamp);
1351 if(pos<0)
1352 return -1;
1354 /* do the seek */
1355 url_fseek(s->pb, pos, SEEK_SET);
1357 av_update_cur_dts(s, st, ts);
1359 return 0;
1362 int64_t av_gen_search(AVFormatContext *s, int stream_index, int64_t target_ts, int64_t pos_min, int64_t pos_max, int64_t pos_limit, int64_t ts_min, int64_t ts_max, int flags, int64_t *ts_ret, int64_t (*read_timestamp)(struct AVFormatContext *, int , int64_t *, int64_t )){
1363 int64_t pos, ts;
1364 int64_t start_pos, filesize;
1365 int no_change;
1367 #ifdef DEBUG_SEEK
1368 av_log(s, AV_LOG_DEBUG, "gen_seek: %d %"PRId64"\n", stream_index, target_ts);
1369 #endif
1371 if(ts_min == AV_NOPTS_VALUE){
1372 pos_min = s->data_offset;
1373 ts_min = read_timestamp(s, stream_index, &pos_min, INT64_MAX);
1374 if (ts_min == AV_NOPTS_VALUE)
1375 return -1;
1378 if(ts_max == AV_NOPTS_VALUE){
1379 int step= 1024;
1380 filesize = url_fsize(s->pb);
1381 pos_max = filesize - 1;
1383 pos_max -= step;
1384 ts_max = read_timestamp(s, stream_index, &pos_max, pos_max + step);
1385 step += step;
1386 }while(ts_max == AV_NOPTS_VALUE && pos_max >= step);
1387 if (ts_max == AV_NOPTS_VALUE)
1388 return -1;
1390 for(;;){
1391 int64_t tmp_pos= pos_max + 1;
1392 int64_t tmp_ts= read_timestamp(s, stream_index, &tmp_pos, INT64_MAX);
1393 if(tmp_ts == AV_NOPTS_VALUE)
1394 break;
1395 ts_max= tmp_ts;
1396 pos_max= tmp_pos;
1397 if(tmp_pos >= filesize)
1398 break;
1400 pos_limit= pos_max;
1403 if(ts_min > ts_max){
1404 return -1;
1405 }else if(ts_min == ts_max){
1406 pos_limit= pos_min;
1409 no_change=0;
1410 while (pos_min < pos_limit) {
1411 #ifdef DEBUG_SEEK
1412 av_log(s, AV_LOG_DEBUG, "pos_min=0x%"PRIx64" pos_max=0x%"PRIx64" dts_min=%"PRId64" dts_max=%"PRId64"\n",
1413 pos_min, pos_max,
1414 ts_min, ts_max);
1415 #endif
1416 assert(pos_limit <= pos_max);
1418 if(no_change==0){
1419 int64_t approximate_keyframe_distance= pos_max - pos_limit;
1420 // interpolate position (better than dichotomy)
1421 pos = av_rescale(target_ts - ts_min, pos_max - pos_min, ts_max - ts_min)
1422 + pos_min - approximate_keyframe_distance;
1423 }else if(no_change==1){
1424 // bisection, if interpolation failed to change min or max pos last time
1425 pos = (pos_min + pos_limit)>>1;
1426 }else{
1427 /* linear search if bisection failed, can only happen if there
1428 are very few or no keyframes between min/max */
1429 pos=pos_min;
1431 if(pos <= pos_min)
1432 pos= pos_min + 1;
1433 else if(pos > pos_limit)
1434 pos= pos_limit;
1435 start_pos= pos;
1437 ts = read_timestamp(s, stream_index, &pos, INT64_MAX); //may pass pos_limit instead of -1
1438 if(pos == pos_max)
1439 no_change++;
1440 else
1441 no_change=0;
1442 #ifdef DEBUG_SEEK
1443 av_log(s, AV_LOG_DEBUG, "%"PRId64" %"PRId64" %"PRId64" / %"PRId64" %"PRId64" %"PRId64" target:%"PRId64" limit:%"PRId64" start:%"PRId64" noc:%d\n",
1444 pos_min, pos, pos_max, ts_min, ts, ts_max, target_ts, pos_limit,
1445 start_pos, no_change);
1446 #endif
1447 if(ts == AV_NOPTS_VALUE){
1448 av_log(s, AV_LOG_ERROR, "read_timestamp() failed in the middle\n");
1449 return -1;
1451 assert(ts != AV_NOPTS_VALUE);
1452 if (target_ts <= ts) {
1453 pos_limit = start_pos - 1;
1454 pos_max = pos;
1455 ts_max = ts;
1457 if (target_ts >= ts) {
1458 pos_min = pos;
1459 ts_min = ts;
1463 pos = (flags & AVSEEK_FLAG_BACKWARD) ? pos_min : pos_max;
1464 ts = (flags & AVSEEK_FLAG_BACKWARD) ? ts_min : ts_max;
1465 #ifdef DEBUG_SEEK
1466 pos_min = pos;
1467 ts_min = read_timestamp(s, stream_index, &pos_min, INT64_MAX);
1468 pos_min++;
1469 ts_max = read_timestamp(s, stream_index, &pos_min, INT64_MAX);
1470 av_log(s, AV_LOG_DEBUG, "pos=0x%"PRIx64" %"PRId64"<=%"PRId64"<=%"PRId64"\n",
1471 pos, ts_min, target_ts, ts_max);
1472 #endif
1473 *ts_ret= ts;
1474 return pos;
1477 static int av_seek_frame_byte(AVFormatContext *s, int stream_index, int64_t pos, int flags){
1478 int64_t pos_min, pos_max;
1479 #if 0
1480 AVStream *st;
1482 if (stream_index < 0)
1483 return -1;
1485 st= s->streams[stream_index];
1486 #endif
1488 pos_min = s->data_offset;
1489 pos_max = url_fsize(s->pb) - 1;
1491 if (pos < pos_min) pos= pos_min;
1492 else if(pos > pos_max) pos= pos_max;
1494 url_fseek(s->pb, pos, SEEK_SET);
1496 #if 0
1497 av_update_cur_dts(s, st, ts);
1498 #endif
1499 return 0;
1502 static int av_seek_frame_generic(AVFormatContext *s,
1503 int stream_index, int64_t timestamp, int flags)
1505 int index, ret;
1506 AVStream *st;
1507 AVIndexEntry *ie;
1509 st = s->streams[stream_index];
1511 index = av_index_search_timestamp(st, timestamp, flags);
1513 if(index < 0 || index==st->nb_index_entries-1){
1514 int i;
1515 AVPacket pkt;
1517 if(st->nb_index_entries){
1518 assert(st->index_entries);
1519 ie= &st->index_entries[st->nb_index_entries-1];
1520 if ((ret = url_fseek(s->pb, ie->pos, SEEK_SET)) < 0)
1521 return ret;
1522 av_update_cur_dts(s, st, ie->timestamp);
1523 }else{
1524 if ((ret = url_fseek(s->pb, s->data_offset, SEEK_SET)) < 0)
1525 return ret;
1527 for(i=0;; i++) {
1528 int ret;
1530 ret = av_read_frame(s, &pkt);
1531 }while(ret == AVERROR(EAGAIN));
1532 if(ret<0)
1533 break;
1534 av_free_packet(&pkt);
1535 if(stream_index == pkt.stream_index){
1536 if((pkt.flags & PKT_FLAG_KEY) && pkt.dts > timestamp)
1537 break;
1540 index = av_index_search_timestamp(st, timestamp, flags);
1542 if (index < 0)
1543 return -1;
1545 av_read_frame_flush(s);
1546 if (s->iformat->read_seek){
1547 if(s->iformat->read_seek(s, stream_index, timestamp, flags) >= 0)
1548 return 0;
1550 ie = &st->index_entries[index];
1551 if ((ret = url_fseek(s->pb, ie->pos, SEEK_SET)) < 0)
1552 return ret;
1553 av_update_cur_dts(s, st, ie->timestamp);
1555 return 0;
1558 int av_seek_frame(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
1560 int ret;
1561 AVStream *st;
1563 av_read_frame_flush(s);
1565 if(flags & AVSEEK_FLAG_BYTE)
1566 return av_seek_frame_byte(s, stream_index, timestamp, flags);
1568 if(stream_index < 0){
1569 stream_index= av_find_default_stream_index(s);
1570 if(stream_index < 0)
1571 return -1;
1573 st= s->streams[stream_index];
1574 /* timestamp for default must be expressed in AV_TIME_BASE units */
1575 timestamp = av_rescale(timestamp, st->time_base.den, AV_TIME_BASE * (int64_t)st->time_base.num);
1578 /* first, we try the format specific seek */
1579 if (s->iformat->read_seek)
1580 ret = s->iformat->read_seek(s, stream_index, timestamp, flags);
1581 else
1582 ret = -1;
1583 if (ret >= 0) {
1584 return 0;
1587 if(s->iformat->read_timestamp)
1588 return av_seek_frame_binary(s, stream_index, timestamp, flags);
1589 else
1590 return av_seek_frame_generic(s, stream_index, timestamp, flags);
1593 int avformat_seek_file(AVFormatContext *s, int stream_index, int64_t min_ts, int64_t ts, int64_t max_ts, int flags)
1595 if(min_ts > ts || max_ts < ts)
1596 return -1;
1598 av_read_frame_flush(s);
1600 if (s->iformat->read_seek2)
1601 return s->iformat->read_seek2(s, stream_index, min_ts, ts, max_ts, flags);
1603 if(s->iformat->read_timestamp){
1604 //try to seek via read_timestamp()
1607 //Fallback to old API if new is not implemented but old is
1608 //Note the old has somewat different sematics
1609 if(s->iformat->read_seek || 1)
1610 return av_seek_frame(s, stream_index, ts, flags | (ts - min_ts > (uint64_t)(max_ts - ts) ? AVSEEK_FLAG_BACKWARD : 0));
1612 // try some generic seek like av_seek_frame_generic() but with new ts semantics
1615 /*******************************************************/
1618 * Returns TRUE if the stream has accurate duration in any stream.
1620 * @return TRUE if the stream has accurate duration for at least one component.
1622 static int av_has_duration(AVFormatContext *ic)
1624 int i;
1625 AVStream *st;
1627 for(i = 0;i < ic->nb_streams; i++) {
1628 st = ic->streams[i];
1629 if (st->duration != AV_NOPTS_VALUE)
1630 return 1;
1632 return 0;
1636 * Estimate the stream timings from the one of each components.
1638 * Also computes the global bitrate if possible.
1640 static void av_update_stream_timings(AVFormatContext *ic)
1642 int64_t start_time, start_time1, end_time, end_time1;
1643 int64_t duration, duration1;
1644 int i;
1645 AVStream *st;
1647 start_time = INT64_MAX;
1648 end_time = INT64_MIN;
1649 duration = INT64_MIN;
1650 for(i = 0;i < ic->nb_streams; i++) {
1651 st = ic->streams[i];
1652 if (st->start_time != AV_NOPTS_VALUE && st->time_base.den) {
1653 start_time1= av_rescale_q(st->start_time, st->time_base, AV_TIME_BASE_Q);
1654 if (start_time1 < start_time)
1655 start_time = start_time1;
1656 if (st->duration != AV_NOPTS_VALUE) {
1657 end_time1 = start_time1
1658 + av_rescale_q(st->duration, st->time_base, AV_TIME_BASE_Q);
1659 if (end_time1 > end_time)
1660 end_time = end_time1;
1663 if (st->duration != AV_NOPTS_VALUE) {
1664 duration1 = av_rescale_q(st->duration, st->time_base, AV_TIME_BASE_Q);
1665 if (duration1 > duration)
1666 duration = duration1;
1669 if (start_time != INT64_MAX) {
1670 ic->start_time = start_time;
1671 if (end_time != INT64_MIN) {
1672 if (end_time - start_time > duration)
1673 duration = end_time - start_time;
1676 if (duration != INT64_MIN) {
1677 ic->duration = duration;
1678 if (ic->file_size > 0) {
1679 /* compute the bitrate */
1680 ic->bit_rate = (double)ic->file_size * 8.0 * AV_TIME_BASE /
1681 (double)ic->duration;
1686 static void fill_all_stream_timings(AVFormatContext *ic)
1688 int i;
1689 AVStream *st;
1691 av_update_stream_timings(ic);
1692 for(i = 0;i < ic->nb_streams; i++) {
1693 st = ic->streams[i];
1694 if (st->start_time == AV_NOPTS_VALUE) {
1695 if(ic->start_time != AV_NOPTS_VALUE)
1696 st->start_time = av_rescale_q(ic->start_time, AV_TIME_BASE_Q, st->time_base);
1697 if(ic->duration != AV_NOPTS_VALUE)
1698 st->duration = av_rescale_q(ic->duration, AV_TIME_BASE_Q, st->time_base);
1703 static void av_estimate_timings_from_bit_rate(AVFormatContext *ic)
1705 int64_t filesize, duration;
1706 int bit_rate, i;
1707 AVStream *st;
1709 /* if bit_rate is already set, we believe it */
1710 if (ic->bit_rate == 0) {
1711 bit_rate = 0;
1712 for(i=0;i<ic->nb_streams;i++) {
1713 st = ic->streams[i];
1714 bit_rate += st->codec->bit_rate;
1716 ic->bit_rate = bit_rate;
1719 /* if duration is already set, we believe it */
1720 if (ic->duration == AV_NOPTS_VALUE &&
1721 ic->bit_rate != 0 &&
1722 ic->file_size != 0) {
1723 filesize = ic->file_size;
1724 if (filesize > 0) {
1725 for(i = 0; i < ic->nb_streams; i++) {
1726 st = ic->streams[i];
1727 duration= av_rescale(8*filesize, st->time_base.den, ic->bit_rate*(int64_t)st->time_base.num);
1728 if (st->duration == AV_NOPTS_VALUE)
1729 st->duration = duration;
1735 #define DURATION_MAX_READ_SIZE 250000
1737 /* only usable for MPEG-PS streams */
1738 static void av_estimate_timings_from_pts(AVFormatContext *ic, int64_t old_offset)
1740 AVPacket pkt1, *pkt = &pkt1;
1741 AVStream *st;
1742 int read_size, i, ret;
1743 int64_t end_time;
1744 int64_t filesize, offset, duration;
1746 ic->cur_st = NULL;
1748 /* flush packet queue */
1749 flush_packet_queue(ic);
1751 for(i=0;i<ic->nb_streams;i++) {
1752 st = ic->streams[i];
1753 if (st->parser) {
1754 av_parser_close(st->parser);
1755 st->parser= NULL;
1756 av_free_packet(&st->cur_pkt);
1760 /* we read the first packets to get the first PTS (not fully
1761 accurate, but it is enough now) */
1762 url_fseek(ic->pb, 0, SEEK_SET);
1763 read_size = 0;
1764 for(;;) {
1765 if (read_size >= DURATION_MAX_READ_SIZE)
1766 break;
1767 /* if all info is available, we can stop */
1768 for(i = 0;i < ic->nb_streams; i++) {
1769 st = ic->streams[i];
1770 if (st->start_time == AV_NOPTS_VALUE)
1771 break;
1773 if (i == ic->nb_streams)
1774 break;
1777 ret = av_read_packet(ic, pkt);
1778 }while(ret == AVERROR(EAGAIN));
1779 if (ret != 0)
1780 break;
1781 read_size += pkt->size;
1782 st = ic->streams[pkt->stream_index];
1783 if (pkt->pts != AV_NOPTS_VALUE) {
1784 if (st->start_time == AV_NOPTS_VALUE)
1785 st->start_time = pkt->pts;
1787 av_free_packet(pkt);
1790 /* estimate the end time (duration) */
1791 /* XXX: may need to support wrapping */
1792 filesize = ic->file_size;
1793 offset = filesize - DURATION_MAX_READ_SIZE;
1794 if (offset < 0)
1795 offset = 0;
1797 url_fseek(ic->pb, offset, SEEK_SET);
1798 read_size = 0;
1799 for(;;) {
1800 if (read_size >= DURATION_MAX_READ_SIZE)
1801 break;
1804 ret = av_read_packet(ic, pkt);
1805 }while(ret == AVERROR(EAGAIN));
1806 if (ret != 0)
1807 break;
1808 read_size += pkt->size;
1809 st = ic->streams[pkt->stream_index];
1810 if (pkt->pts != AV_NOPTS_VALUE &&
1811 st->start_time != AV_NOPTS_VALUE) {
1812 end_time = pkt->pts;
1813 duration = end_time - st->start_time;
1814 if (duration > 0) {
1815 if (st->duration == AV_NOPTS_VALUE ||
1816 st->duration < duration)
1817 st->duration = duration;
1820 av_free_packet(pkt);
1823 fill_all_stream_timings(ic);
1825 url_fseek(ic->pb, old_offset, SEEK_SET);
1826 for(i=0; i<ic->nb_streams; i++){
1827 st= ic->streams[i];
1828 st->cur_dts= st->first_dts;
1829 st->last_IP_pts = AV_NOPTS_VALUE;
1833 static void av_estimate_timings(AVFormatContext *ic, int64_t old_offset)
1835 int64_t file_size;
1837 /* get the file size, if possible */
1838 if (ic->iformat->flags & AVFMT_NOFILE) {
1839 file_size = 0;
1840 } else {
1841 file_size = url_fsize(ic->pb);
1842 if (file_size < 0)
1843 file_size = 0;
1845 ic->file_size = file_size;
1847 if ((!strcmp(ic->iformat->name, "mpeg") ||
1848 !strcmp(ic->iformat->name, "mpegts")) &&
1849 file_size && !url_is_streamed(ic->pb)) {
1850 /* get accurate estimate from the PTSes */
1851 av_estimate_timings_from_pts(ic, old_offset);
1852 } else if (av_has_duration(ic)) {
1853 /* at least one component has timings - we use them for all
1854 the components */
1855 fill_all_stream_timings(ic);
1856 } else {
1857 /* less precise: use bitrate info */
1858 av_estimate_timings_from_bit_rate(ic);
1860 av_update_stream_timings(ic);
1862 #if 0
1864 int i;
1865 AVStream *st;
1866 for(i = 0;i < ic->nb_streams; i++) {
1867 st = ic->streams[i];
1868 printf("%d: start_time: %0.3f duration: %0.3f\n",
1869 i, (double)st->start_time / AV_TIME_BASE,
1870 (double)st->duration / AV_TIME_BASE);
1872 printf("stream: start_time: %0.3f duration: %0.3f bitrate=%d kb/s\n",
1873 (double)ic->start_time / AV_TIME_BASE,
1874 (double)ic->duration / AV_TIME_BASE,
1875 ic->bit_rate / 1000);
1877 #endif
1880 static int has_codec_parameters(AVCodecContext *enc)
1882 int val;
1883 switch(enc->codec_type) {
1884 case CODEC_TYPE_AUDIO:
1885 val = enc->sample_rate && enc->channels && enc->sample_fmt != SAMPLE_FMT_NONE;
1886 if(!enc->frame_size &&
1887 (enc->codec_id == CODEC_ID_VORBIS ||
1888 enc->codec_id == CODEC_ID_AAC ||
1889 enc->codec_id == CODEC_ID_MP3 ||
1890 enc->codec_id == CODEC_ID_SPEEX))
1891 return 0;
1892 break;
1893 case CODEC_TYPE_VIDEO:
1894 val = enc->width && enc->pix_fmt != PIX_FMT_NONE;
1895 break;
1896 default:
1897 val = 1;
1898 break;
1900 return enc->codec_id != CODEC_ID_NONE && val != 0;
1903 static int try_decode_frame(AVStream *st, AVPacket *avpkt)
1905 int16_t *samples;
1906 AVCodec *codec;
1907 int got_picture, data_size, ret=0;
1908 AVFrame picture;
1910 if(!st->codec->codec){
1911 codec = avcodec_find_decoder(st->codec->codec_id);
1912 if (!codec)
1913 return -1;
1914 ret = avcodec_open(st->codec, codec);
1915 if (ret < 0)
1916 return ret;
1919 if(!has_codec_parameters(st->codec)){
1920 switch(st->codec->codec_type) {
1921 case CODEC_TYPE_VIDEO:
1922 avcodec_get_frame_defaults(&picture);
1923 ret = avcodec_decode_video2(st->codec, &picture,
1924 &got_picture, avpkt);
1925 break;
1926 case CODEC_TYPE_AUDIO:
1927 data_size = FFMAX(avpkt->size, AVCODEC_MAX_AUDIO_FRAME_SIZE);
1928 samples = av_malloc(data_size);
1929 if (!samples)
1930 goto fail;
1931 ret = avcodec_decode_audio3(st->codec, samples,
1932 &data_size, avpkt);
1933 av_free(samples);
1934 break;
1935 default:
1936 break;
1939 fail:
1940 return ret;
1943 unsigned int ff_codec_get_tag(const AVCodecTag *tags, int id)
1945 while (tags->id != CODEC_ID_NONE) {
1946 if (tags->id == id)
1947 return tags->tag;
1948 tags++;
1950 return 0;
1953 enum CodecID ff_codec_get_id(const AVCodecTag *tags, unsigned int tag)
1955 int i;
1956 for(i=0; tags[i].id != CODEC_ID_NONE;i++) {
1957 if(tag == tags[i].tag)
1958 return tags[i].id;
1960 for(i=0; tags[i].id != CODEC_ID_NONE; i++) {
1961 if( toupper((tag >> 0)&0xFF) == toupper((tags[i].tag >> 0)&0xFF)
1962 && toupper((tag >> 8)&0xFF) == toupper((tags[i].tag >> 8)&0xFF)
1963 && toupper((tag >>16)&0xFF) == toupper((tags[i].tag >>16)&0xFF)
1964 && toupper((tag >>24)&0xFF) == toupper((tags[i].tag >>24)&0xFF))
1965 return tags[i].id;
1967 return CODEC_ID_NONE;
1970 unsigned int av_codec_get_tag(const AVCodecTag * const *tags, enum CodecID id)
1972 int i;
1973 for(i=0; tags && tags[i]; i++){
1974 int tag= ff_codec_get_tag(tags[i], id);
1975 if(tag) return tag;
1977 return 0;
1980 enum CodecID av_codec_get_id(const AVCodecTag * const *tags, unsigned int tag)
1982 int i;
1983 for(i=0; tags && tags[i]; i++){
1984 enum CodecID id= ff_codec_get_id(tags[i], tag);
1985 if(id!=CODEC_ID_NONE) return id;
1987 return CODEC_ID_NONE;
1990 static void compute_chapters_end(AVFormatContext *s)
1992 unsigned int i;
1994 for (i=0; i+1<s->nb_chapters; i++)
1995 if (s->chapters[i]->end == AV_NOPTS_VALUE) {
1996 assert(s->chapters[i]->start <= s->chapters[i+1]->start);
1997 assert(!av_cmp_q(s->chapters[i]->time_base, s->chapters[i+1]->time_base));
1998 s->chapters[i]->end = s->chapters[i+1]->start;
2001 if (s->nb_chapters && s->chapters[i]->end == AV_NOPTS_VALUE) {
2002 assert(s->start_time != AV_NOPTS_VALUE);
2003 assert(s->duration > 0);
2004 s->chapters[i]->end = av_rescale_q(s->start_time + s->duration,
2005 AV_TIME_BASE_Q,
2006 s->chapters[i]->time_base);
2010 #define MAX_STD_TIMEBASES (60*12+5)
2011 static int get_std_framerate(int i){
2012 if(i<60*12) return i*1001;
2013 else return ((const int[]){24,30,60,12,15})[i-60*12]*1000*12;
2017 * Is the time base unreliable.
2018 * This is a heuristic to balance between quick acceptance of the values in
2019 * the headers vs. some extra checks.
2020 * Old DivX and Xvid often have nonsense timebases like 1fps or 2fps.
2021 * MPEG-2 commonly misuses field repeat flags to store different framerates.
2022 * And there are "variable" fps files this needs to detect as well.
2024 static int tb_unreliable(AVCodecContext *c){
2025 if( c->time_base.den >= 101L*c->time_base.num
2026 || c->time_base.den < 5L*c->time_base.num
2027 /* || c->codec_tag == AV_RL32("DIVX")
2028 || c->codec_tag == AV_RL32("XVID")*/
2029 || c->codec_id == CODEC_ID_MPEG2VIDEO
2030 || c->codec_id == CODEC_ID_H264
2032 return 1;
2033 return 0;
2036 int av_find_stream_info(AVFormatContext *ic)
2038 int i, count, ret, read_size, j;
2039 AVStream *st;
2040 AVPacket pkt1, *pkt;
2041 int64_t last_dts[MAX_STREAMS];
2042 int64_t duration_gcd[MAX_STREAMS]={0};
2043 int duration_count[MAX_STREAMS]={0};
2044 double (*duration_error)[MAX_STD_TIMEBASES];
2045 int64_t old_offset = url_ftell(ic->pb);
2046 int64_t codec_info_duration[MAX_STREAMS]={0};
2047 int codec_info_nb_frames[MAX_STREAMS]={0};
2049 duration_error = av_mallocz(MAX_STREAMS * sizeof(*duration_error));
2050 if (!duration_error) return AVERROR(ENOMEM);
2052 for(i=0;i<ic->nb_streams;i++) {
2053 st = ic->streams[i];
2054 if(st->codec->codec_type == CODEC_TYPE_VIDEO){
2055 /* if(!st->time_base.num)
2056 st->time_base= */
2057 if(!st->codec->time_base.num)
2058 st->codec->time_base= st->time_base;
2060 //only for the split stuff
2061 if (!st->parser) {
2062 st->parser = av_parser_init(st->codec->codec_id);
2063 if(st->need_parsing == AVSTREAM_PARSE_HEADERS && st->parser){
2064 st->parser->flags |= PARSER_FLAG_COMPLETE_FRAMES;
2069 for(i=0;i<MAX_STREAMS;i++){
2070 last_dts[i]= AV_NOPTS_VALUE;
2073 count = 0;
2074 read_size = 0;
2075 for(;;) {
2076 if(url_interrupt_cb()){
2077 ret= AVERROR(EINTR);
2078 av_log(ic, AV_LOG_DEBUG, "interrupted\n");
2079 break;
2082 /* check if one codec still needs to be handled */
2083 for(i=0;i<ic->nb_streams;i++) {
2084 st = ic->streams[i];
2085 if (!has_codec_parameters(st->codec))
2086 break;
2087 /* variable fps and no guess at the real fps */
2088 if( tb_unreliable(st->codec)
2089 && duration_count[i]<20 && st->codec->codec_type == CODEC_TYPE_VIDEO)
2090 break;
2091 if(st->parser && st->parser->parser->split && !st->codec->extradata)
2092 break;
2093 if(st->first_dts == AV_NOPTS_VALUE)
2094 break;
2096 if (i == ic->nb_streams) {
2097 /* NOTE: if the format has no header, then we need to read
2098 some packets to get most of the streams, so we cannot
2099 stop here */
2100 if (!(ic->ctx_flags & AVFMTCTX_NOHEADER)) {
2101 /* if we found the info for all the codecs, we can stop */
2102 ret = count;
2103 av_log(ic, AV_LOG_DEBUG, "All info found\n");
2104 break;
2107 /* we did not get all the codec info, but we read too much data */
2108 if (read_size >= ic->probesize) {
2109 ret = count;
2110 av_log(ic, AV_LOG_WARNING, "MAX_READ_SIZE:%d reached\n", ic->probesize);
2111 break;
2114 /* NOTE: a new stream can be added there if no header in file
2115 (AVFMTCTX_NOHEADER) */
2116 ret = av_read_frame_internal(ic, &pkt1);
2117 if(ret == AVERROR(EAGAIN))
2118 continue;
2119 if (ret < 0) {
2120 /* EOF or error */
2121 ret = -1; /* we could not have all the codec parameters before EOF */
2122 for(i=0;i<ic->nb_streams;i++) {
2123 st = ic->streams[i];
2124 if (!has_codec_parameters(st->codec)){
2125 char buf[256];
2126 avcodec_string(buf, sizeof(buf), st->codec, 0);
2127 av_log(ic, AV_LOG_WARNING, "Could not find codec parameters (%s)\n", buf);
2128 } else {
2129 ret = 0;
2132 break;
2135 pkt= add_to_pktbuf(&ic->packet_buffer, &pkt1, &ic->packet_buffer_end);
2136 if(av_dup_packet(pkt) < 0) {
2137 av_free(duration_error);
2138 return AVERROR(ENOMEM);
2141 read_size += pkt->size;
2143 st = ic->streams[pkt->stream_index];
2144 if(codec_info_nb_frames[st->index]>1) {
2145 if (st->time_base.den > 0 && av_rescale_q(codec_info_duration[st->index], st->time_base, AV_TIME_BASE_Q) >= ic->max_analyze_duration){
2146 av_log(ic, AV_LOG_WARNING, "max_analyze_duration reached\n");
2147 break;
2149 codec_info_duration[st->index] += pkt->duration;
2151 if (pkt->duration != 0)
2152 codec_info_nb_frames[st->index]++;
2155 int index= pkt->stream_index;
2156 int64_t last= last_dts[index];
2157 int64_t duration= pkt->dts - last;
2159 if(pkt->dts != AV_NOPTS_VALUE && last != AV_NOPTS_VALUE && duration>0){
2160 double dur= duration * av_q2d(st->time_base);
2162 // if(st->codec->codec_type == CODEC_TYPE_VIDEO)
2163 // av_log(NULL, AV_LOG_ERROR, "%f\n", dur);
2164 if(duration_count[index] < 2)
2165 memset(duration_error[index], 0, sizeof(*duration_error));
2166 for(i=1; i<MAX_STD_TIMEBASES; i++){
2167 int framerate= get_std_framerate(i);
2168 int ticks= lrintf(dur*framerate/(1001*12));
2169 double error= dur - ticks*1001*12/(double)framerate;
2170 duration_error[index][i] += error*error;
2172 duration_count[index]++;
2173 // ignore the first 4 values, they might have some random jitter
2174 if (duration_count[index] > 3)
2175 duration_gcd[index] = av_gcd(duration_gcd[index], duration);
2177 if(last == AV_NOPTS_VALUE || duration_count[index]<=1)
2178 last_dts[pkt->stream_index]= pkt->dts;
2180 if(st->parser && st->parser->parser->split && !st->codec->extradata){
2181 int i= st->parser->parser->split(st->codec, pkt->data, pkt->size);
2182 if(i){
2183 st->codec->extradata_size= i;
2184 st->codec->extradata= av_malloc(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
2185 memcpy(st->codec->extradata, pkt->data, st->codec->extradata_size);
2186 memset(st->codec->extradata + i, 0, FF_INPUT_BUFFER_PADDING_SIZE);
2190 /* if still no information, we try to open the codec and to
2191 decompress the frame. We try to avoid that in most cases as
2192 it takes longer and uses more memory. For MPEG-4, we need to
2193 decompress for QuickTime. */
2194 if (!has_codec_parameters(st->codec) /*&&
2195 (st->codec->codec_id == CODEC_ID_FLV1 ||
2196 st->codec->codec_id == CODEC_ID_H264 ||
2197 st->codec->codec_id == CODEC_ID_H263 ||
2198 st->codec->codec_id == CODEC_ID_H261 ||
2199 st->codec->codec_id == CODEC_ID_VORBIS ||
2200 st->codec->codec_id == CODEC_ID_MJPEG ||
2201 st->codec->codec_id == CODEC_ID_PNG ||
2202 st->codec->codec_id == CODEC_ID_PAM ||
2203 st->codec->codec_id == CODEC_ID_PGM ||
2204 st->codec->codec_id == CODEC_ID_PGMYUV ||
2205 st->codec->codec_id == CODEC_ID_PBM ||
2206 st->codec->codec_id == CODEC_ID_PPM ||
2207 st->codec->codec_id == CODEC_ID_SHORTEN ||
2208 (st->codec->codec_id == CODEC_ID_MPEG4 && !st->need_parsing))*/)
2209 try_decode_frame(st, pkt);
2211 count++;
2214 // close codecs which were opened in try_decode_frame()
2215 for(i=0;i<ic->nb_streams;i++) {
2216 st = ic->streams[i];
2217 if(st->codec->codec)
2218 avcodec_close(st->codec);
2220 for(i=0;i<ic->nb_streams;i++) {
2221 st = ic->streams[i];
2222 if (st->codec->codec_type == CODEC_TYPE_VIDEO) {
2223 if(st->codec->codec_id == CODEC_ID_RAWVIDEO && !st->codec->codec_tag && !st->codec->bits_per_coded_sample)
2224 st->codec->codec_tag= avcodec_pix_fmt_to_codec_tag(st->codec->pix_fmt);
2226 // the check for tb_unreliable() is not completely correct, since this is not about handling
2227 // a unreliable/inexact time base, but a time base that is finer than necessary, as e.g.
2228 // ipmovie.c produces.
2229 if (tb_unreliable(st->codec) && duration_count[i] > 15 && duration_gcd[i] > 1)
2230 av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den, st->time_base.den, st->time_base.num * duration_gcd[i], INT_MAX);
2231 if(duration_count[i]
2232 && tb_unreliable(st->codec) /*&&
2233 //FIXME we should not special-case MPEG-2, but this needs testing with non-MPEG-2 ...
2234 st->time_base.num*duration_sum[i]/duration_count[i]*101LL > st->time_base.den*/){
2235 int num = 0;
2236 double best_error= 2*av_q2d(st->time_base);
2237 best_error= best_error*best_error*duration_count[i]*1000*12*30;
2239 for(j=1; j<MAX_STD_TIMEBASES; j++){
2240 double error= duration_error[i][j] * get_std_framerate(j);
2241 // if(st->codec->codec_type == CODEC_TYPE_VIDEO)
2242 // av_log(NULL, AV_LOG_ERROR, "%f %f\n", get_std_framerate(j) / 12.0/1001, error);
2243 if(error < best_error){
2244 best_error= error;
2245 num = get_std_framerate(j);
2248 // do not increase frame rate by more than 1 % in order to match a standard rate.
2249 if (num && (!st->r_frame_rate.num || (double)num/(12*1001) < 1.01 * av_q2d(st->r_frame_rate)))
2250 av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den, num, 12*1001, INT_MAX);
2253 if (!st->r_frame_rate.num){
2254 if( st->codec->time_base.den * (int64_t)st->time_base.num
2255 <= st->codec->time_base.num * st->codec->ticks_per_frame * (int64_t)st->time_base.den){
2256 st->r_frame_rate.num = st->codec->time_base.den;
2257 st->r_frame_rate.den = st->codec->time_base.num * st->codec->ticks_per_frame;
2258 }else{
2259 st->r_frame_rate.num = st->time_base.den;
2260 st->r_frame_rate.den = st->time_base.num;
2263 }else if(st->codec->codec_type == CODEC_TYPE_AUDIO) {
2264 if(!st->codec->bits_per_coded_sample)
2265 st->codec->bits_per_coded_sample= av_get_bits_per_sample(st->codec->codec_id);
2269 av_estimate_timings(ic, old_offset);
2271 compute_chapters_end(ic);
2273 #if 0
2274 /* correct DTS for B-frame streams with no timestamps */
2275 for(i=0;i<ic->nb_streams;i++) {
2276 st = ic->streams[i];
2277 if (st->codec->codec_type == CODEC_TYPE_VIDEO) {
2278 if(b-frames){
2279 ppktl = &ic->packet_buffer;
2280 while(ppkt1){
2281 if(ppkt1->stream_index != i)
2282 continue;
2283 if(ppkt1->pkt->dts < 0)
2284 break;
2285 if(ppkt1->pkt->pts != AV_NOPTS_VALUE)
2286 break;
2287 ppkt1->pkt->dts -= delta;
2288 ppkt1= ppkt1->next;
2290 if(ppkt1)
2291 continue;
2292 st->cur_dts -= delta;
2296 #endif
2298 av_free(duration_error);
2300 return ret;
2303 /*******************************************************/
2305 int av_read_play(AVFormatContext *s)
2307 if (s->iformat->read_play)
2308 return s->iformat->read_play(s);
2309 if (s->pb)
2310 return av_url_read_fpause(s->pb, 0);
2311 return AVERROR(ENOSYS);
2314 int av_read_pause(AVFormatContext *s)
2316 if (s->iformat->read_pause)
2317 return s->iformat->read_pause(s);
2318 if (s->pb)
2319 return av_url_read_fpause(s->pb, 1);
2320 return AVERROR(ENOSYS);
2323 void av_close_input_stream(AVFormatContext *s)
2325 int i;
2326 AVStream *st;
2328 if (s->iformat->read_close)
2329 s->iformat->read_close(s);
2330 for(i=0;i<s->nb_streams;i++) {
2331 /* free all data in a stream component */
2332 st = s->streams[i];
2333 if (st->parser) {
2334 av_parser_close(st->parser);
2335 av_free_packet(&st->cur_pkt);
2337 av_metadata_free(&st->metadata);
2338 av_free(st->index_entries);
2339 av_free(st->codec->extradata);
2340 av_free(st->codec);
2341 #if LIBAVFORMAT_VERSION_INT < (53<<16)
2342 av_free(st->filename);
2343 #endif
2344 av_free(st->priv_data);
2345 av_free(st);
2347 for(i=s->nb_programs-1; i>=0; i--) {
2348 #if LIBAVFORMAT_VERSION_INT < (53<<16)
2349 av_freep(&s->programs[i]->provider_name);
2350 av_freep(&s->programs[i]->name);
2351 #endif
2352 av_metadata_free(&s->programs[i]->metadata);
2353 av_freep(&s->programs[i]->stream_index);
2354 av_freep(&s->programs[i]);
2356 av_freep(&s->programs);
2357 flush_packet_queue(s);
2358 av_freep(&s->priv_data);
2359 while(s->nb_chapters--) {
2360 #if LIBAVFORMAT_VERSION_INT < (53<<16)
2361 av_free(s->chapters[s->nb_chapters]->title);
2362 #endif
2363 av_metadata_free(&s->chapters[s->nb_chapters]->metadata);
2364 av_free(s->chapters[s->nb_chapters]);
2366 av_freep(&s->chapters);
2367 av_metadata_free(&s->metadata);
2368 av_free(s);
2371 void av_close_input_file(AVFormatContext *s)
2373 ByteIOContext *pb = s->iformat->flags & AVFMT_NOFILE ? NULL : s->pb;
2374 av_close_input_stream(s);
2375 if (pb)
2376 url_fclose(pb);
2379 AVStream *av_new_stream(AVFormatContext *s, int id)
2381 AVStream *st;
2382 int i;
2384 if (s->nb_streams >= MAX_STREAMS)
2385 return NULL;
2387 st = av_mallocz(sizeof(AVStream));
2388 if (!st)
2389 return NULL;
2391 st->codec= avcodec_alloc_context();
2392 if (s->iformat) {
2393 /* no default bitrate if decoding */
2394 st->codec->bit_rate = 0;
2396 st->index = s->nb_streams;
2397 st->id = id;
2398 st->start_time = AV_NOPTS_VALUE;
2399 st->duration = AV_NOPTS_VALUE;
2400 /* we set the current DTS to 0 so that formats without any timestamps
2401 but durations get some timestamps, formats with some unknown
2402 timestamps have their first few packets buffered and the
2403 timestamps corrected before they are returned to the user */
2404 st->cur_dts = 0;
2405 st->first_dts = AV_NOPTS_VALUE;
2406 st->probe_packets = MAX_PROBE_PACKETS;
2408 /* default pts setting is MPEG-like */
2409 av_set_pts_info(st, 33, 1, 90000);
2410 st->last_IP_pts = AV_NOPTS_VALUE;
2411 for(i=0; i<MAX_REORDER_DELAY+1; i++)
2412 st->pts_buffer[i]= AV_NOPTS_VALUE;
2413 st->reference_dts = AV_NOPTS_VALUE;
2415 st->sample_aspect_ratio = (AVRational){0,1};
2417 s->streams[s->nb_streams++] = st;
2418 return st;
2421 AVProgram *av_new_program(AVFormatContext *ac, int id)
2423 AVProgram *program=NULL;
2424 int i;
2426 #ifdef DEBUG_SI
2427 av_log(ac, AV_LOG_DEBUG, "new_program: id=0x%04x\n", id);
2428 #endif
2430 for(i=0; i<ac->nb_programs; i++)
2431 if(ac->programs[i]->id == id)
2432 program = ac->programs[i];
2434 if(!program){
2435 program = av_mallocz(sizeof(AVProgram));
2436 if (!program)
2437 return NULL;
2438 dynarray_add(&ac->programs, &ac->nb_programs, program);
2439 program->discard = AVDISCARD_NONE;
2441 program->id = id;
2443 return program;
2446 AVChapter *ff_new_chapter(AVFormatContext *s, int id, AVRational time_base, int64_t start, int64_t end, const char *title)
2448 AVChapter *chapter = NULL;
2449 int i;
2451 for(i=0; i<s->nb_chapters; i++)
2452 if(s->chapters[i]->id == id)
2453 chapter = s->chapters[i];
2455 if(!chapter){
2456 chapter= av_mallocz(sizeof(AVChapter));
2457 if(!chapter)
2458 return NULL;
2459 dynarray_add(&s->chapters, &s->nb_chapters, chapter);
2461 #if LIBAVFORMAT_VERSION_INT < (53<<16)
2462 av_free(chapter->title);
2463 #endif
2464 av_metadata_set(&chapter->metadata, "title", title);
2465 chapter->id = id;
2466 chapter->time_base= time_base;
2467 chapter->start = start;
2468 chapter->end = end;
2470 return chapter;
2473 /************************************************************/
2474 /* output media file */
2476 int av_set_parameters(AVFormatContext *s, AVFormatParameters *ap)
2478 int ret;
2480 if (s->oformat->priv_data_size > 0) {
2481 s->priv_data = av_mallocz(s->oformat->priv_data_size);
2482 if (!s->priv_data)
2483 return AVERROR(ENOMEM);
2484 } else
2485 s->priv_data = NULL;
2487 if (s->oformat->set_parameters) {
2488 ret = s->oformat->set_parameters(s, ap);
2489 if (ret < 0)
2490 return ret;
2492 return 0;
2495 int av_write_header(AVFormatContext *s)
2497 int ret, i;
2498 AVStream *st;
2500 // some sanity checks
2501 for(i=0;i<s->nb_streams;i++) {
2502 st = s->streams[i];
2504 switch (st->codec->codec_type) {
2505 case CODEC_TYPE_AUDIO:
2506 if(st->codec->sample_rate<=0){
2507 av_log(s, AV_LOG_ERROR, "sample rate not set\n");
2508 return -1;
2510 if(!st->codec->block_align)
2511 st->codec->block_align = st->codec->channels *
2512 av_get_bits_per_sample(st->codec->codec_id) >> 3;
2513 break;
2514 case CODEC_TYPE_VIDEO:
2515 if(st->codec->time_base.num<=0 || st->codec->time_base.den<=0){ //FIXME audio too?
2516 av_log(s, AV_LOG_ERROR, "time base not set\n");
2517 return -1;
2519 if(st->codec->width<=0 || st->codec->height<=0){
2520 av_log(s, AV_LOG_ERROR, "dimensions not set\n");
2521 return -1;
2523 if(av_cmp_q(st->sample_aspect_ratio, st->codec->sample_aspect_ratio)){
2524 av_log(s, AV_LOG_ERROR, "Aspect ratio mismatch between encoder and muxer layer\n");
2525 return -1;
2527 break;
2530 if(s->oformat->codec_tag){
2531 if(st->codec->codec_tag){
2532 //FIXME
2533 //check that tag + id is in the table
2534 //if neither is in the table -> OK
2535 //if tag is in the table with another id -> FAIL
2536 //if id is in the table with another tag -> FAIL unless strict < ?
2537 }else
2538 st->codec->codec_tag= av_codec_get_tag(s->oformat->codec_tag, st->codec->codec_id);
2541 if(s->oformat->flags & AVFMT_GLOBALHEADER &&
2542 !(st->codec->flags & CODEC_FLAG_GLOBAL_HEADER))
2543 av_log(s, AV_LOG_WARNING, "Codec for stream %d does not use global headers but container format requires global headers\n", i);
2546 if (!s->priv_data && s->oformat->priv_data_size > 0) {
2547 s->priv_data = av_mallocz(s->oformat->priv_data_size);
2548 if (!s->priv_data)
2549 return AVERROR(ENOMEM);
2552 #if LIBAVFORMAT_VERSION_MAJOR < 53
2553 ff_metadata_mux_compat(s);
2554 #endif
2556 if(s->oformat->write_header){
2557 ret = s->oformat->write_header(s);
2558 if (ret < 0)
2559 return ret;
2562 /* init PTS generation */
2563 for(i=0;i<s->nb_streams;i++) {
2564 int64_t den = AV_NOPTS_VALUE;
2565 st = s->streams[i];
2567 switch (st->codec->codec_type) {
2568 case CODEC_TYPE_AUDIO:
2569 den = (int64_t)st->time_base.num * st->codec->sample_rate;
2570 break;
2571 case CODEC_TYPE_VIDEO:
2572 den = (int64_t)st->time_base.num * st->codec->time_base.den;
2573 break;
2574 default:
2575 break;
2577 if (den != AV_NOPTS_VALUE) {
2578 if (den <= 0)
2579 return AVERROR_INVALIDDATA;
2580 av_frac_init(&st->pts, 0, 0, den);
2583 return 0;
2586 //FIXME merge with compute_pkt_fields
2587 static int compute_pkt_fields2(AVStream *st, AVPacket *pkt){
2588 int delay = FFMAX(st->codec->has_b_frames, !!st->codec->max_b_frames);
2589 int num, den, frame_size, i;
2591 // av_log(st->codec, AV_LOG_DEBUG, "av_write_frame: pts:%"PRId64" dts:%"PRId64" cur_dts:%"PRId64" b:%d size:%d st:%d\n", pkt->pts, pkt->dts, st->cur_dts, delay, pkt->size, pkt->stream_index);
2593 /* if(pkt->pts == AV_NOPTS_VALUE && pkt->dts == AV_NOPTS_VALUE)
2594 return -1;*/
2596 /* duration field */
2597 if (pkt->duration == 0) {
2598 compute_frame_duration(&num, &den, st, NULL, pkt);
2599 if (den && num) {
2600 pkt->duration = av_rescale(1, num * (int64_t)st->time_base.den * st->codec->ticks_per_frame, den * (int64_t)st->time_base.num);
2604 if(pkt->pts == AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE && delay==0)
2605 pkt->pts= pkt->dts;
2607 //XXX/FIXME this is a temporary hack until all encoders output pts
2608 if((pkt->pts == 0 || pkt->pts == AV_NOPTS_VALUE) && pkt->dts == AV_NOPTS_VALUE && !delay){
2609 pkt->dts=
2610 // pkt->pts= st->cur_dts;
2611 pkt->pts= st->pts.val;
2614 //calculate dts from pts
2615 if(pkt->pts != AV_NOPTS_VALUE && pkt->dts == AV_NOPTS_VALUE && delay <= MAX_REORDER_DELAY){
2616 st->pts_buffer[0]= pkt->pts;
2617 for(i=1; i<delay+1 && st->pts_buffer[i] == AV_NOPTS_VALUE; i++)
2618 st->pts_buffer[i]= (i-delay-1) * pkt->duration;
2619 for(i=0; i<delay && st->pts_buffer[i] > st->pts_buffer[i+1]; i++)
2620 FFSWAP(int64_t, st->pts_buffer[i], st->pts_buffer[i+1]);
2622 pkt->dts= st->pts_buffer[0];
2625 if(st->cur_dts && st->cur_dts != AV_NOPTS_VALUE && st->cur_dts >= pkt->dts){
2626 av_log(st->codec, AV_LOG_ERROR, "error, non monotone timestamps %"PRId64" >= %"PRId64"\n", st->cur_dts, pkt->dts);
2627 return -1;
2629 if(pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE && pkt->pts < pkt->dts){
2630 av_log(st->codec, AV_LOG_ERROR, "error, pts < dts\n");
2631 return -1;
2634 // av_log(NULL, AV_LOG_DEBUG, "av_write_frame: pts2:%"PRId64" dts2:%"PRId64"\n", pkt->pts, pkt->dts);
2635 st->cur_dts= pkt->dts;
2636 st->pts.val= pkt->dts;
2638 /* update pts */
2639 switch (st->codec->codec_type) {
2640 case CODEC_TYPE_AUDIO:
2641 frame_size = get_audio_frame_size(st->codec, pkt->size);
2643 /* HACK/FIXME, we skip the initial 0 size packets as they are most
2644 likely equal to the encoder delay, but it would be better if we
2645 had the real timestamps from the encoder */
2646 if (frame_size >= 0 && (pkt->size || st->pts.num!=st->pts.den>>1 || st->pts.val)) {
2647 av_frac_add(&st->pts, (int64_t)st->time_base.den * frame_size);
2649 break;
2650 case CODEC_TYPE_VIDEO:
2651 av_frac_add(&st->pts, (int64_t)st->time_base.den * st->codec->time_base.num);
2652 break;
2653 default:
2654 break;
2656 return 0;
2659 int av_write_frame(AVFormatContext *s, AVPacket *pkt)
2661 int ret = compute_pkt_fields2(s->streams[pkt->stream_index], pkt);
2663 if(ret<0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
2664 return ret;
2666 ret= s->oformat->write_packet(s, pkt);
2667 if(!ret)
2668 ret= url_ferror(s->pb);
2669 return ret;
2672 void ff_interleave_add_packet(AVFormatContext *s, AVPacket *pkt,
2673 int (*compare)(AVFormatContext *, AVPacket *, AVPacket *))
2675 AVPacketList **next_point, *this_pktl;
2677 this_pktl = av_mallocz(sizeof(AVPacketList));
2678 this_pktl->pkt= *pkt;
2679 pkt->destruct= NULL; // do not free original but only the copy
2680 av_dup_packet(&this_pktl->pkt); // duplicate the packet if it uses non-alloced memory
2682 if(s->streams[pkt->stream_index]->last_in_packet_buffer){
2683 next_point = &(s->streams[pkt->stream_index]->last_in_packet_buffer->next);
2684 }else
2685 next_point = &s->packet_buffer;
2687 if(*next_point){
2688 if(compare(s, &s->packet_buffer_end->pkt, pkt)){
2689 while(!compare(s, &(*next_point)->pkt, pkt)){
2690 next_point= &(*next_point)->next;
2692 goto next_non_null;
2693 }else{
2694 next_point = &(s->packet_buffer_end->next);
2697 assert(!*next_point);
2699 s->packet_buffer_end= this_pktl;
2700 next_non_null:
2702 this_pktl->next= *next_point;
2704 s->streams[pkt->stream_index]->last_in_packet_buffer=
2705 *next_point= this_pktl;
2708 int ff_interleave_compare_dts(AVFormatContext *s, AVPacket *next, AVPacket *pkt)
2710 AVStream *st = s->streams[ pkt ->stream_index];
2711 AVStream *st2= s->streams[ next->stream_index];
2712 int64_t left = st2->time_base.num * (int64_t)st ->time_base.den;
2713 int64_t right= st ->time_base.num * (int64_t)st2->time_base.den;
2715 if (pkt->dts == AV_NOPTS_VALUE)
2716 return 0;
2718 return next->dts * left > pkt->dts * right; //FIXME this can overflow
2721 int av_interleave_packet_per_dts(AVFormatContext *s, AVPacket *out, AVPacket *pkt, int flush){
2722 AVPacketList *pktl;
2723 int stream_count=0;
2724 int i;
2726 if(pkt){
2727 ff_interleave_add_packet(s, pkt, ff_interleave_compare_dts);
2730 for(i=0; i < s->nb_streams; i++)
2731 stream_count+= !!s->streams[i]->last_in_packet_buffer;
2733 if(stream_count && (s->nb_streams == stream_count || flush)){
2734 pktl= s->packet_buffer;
2735 *out= pktl->pkt;
2737 s->packet_buffer= pktl->next;
2738 if(!s->packet_buffer)
2739 s->packet_buffer_end= NULL;
2741 if(s->streams[out->stream_index]->last_in_packet_buffer == pktl)
2742 s->streams[out->stream_index]->last_in_packet_buffer= NULL;
2743 av_freep(&pktl);
2744 return 1;
2745 }else{
2746 av_init_packet(out);
2747 return 0;
2752 * Interleaves an AVPacket correctly so it can be muxed.
2753 * @param out the interleaved packet will be output here
2754 * @param in the input packet
2755 * @param flush 1 if no further packets are available as input and all
2756 * remaining packets should be output
2757 * @return 1 if a packet was output, 0 if no packet could be output,
2758 * < 0 if an error occurred
2760 static int av_interleave_packet(AVFormatContext *s, AVPacket *out, AVPacket *in, int flush){
2761 if(s->oformat->interleave_packet)
2762 return s->oformat->interleave_packet(s, out, in, flush);
2763 else
2764 return av_interleave_packet_per_dts(s, out, in, flush);
2767 int av_interleaved_write_frame(AVFormatContext *s, AVPacket *pkt){
2768 AVStream *st= s->streams[ pkt->stream_index];
2770 //FIXME/XXX/HACK drop zero sized packets
2771 if(st->codec->codec_type == CODEC_TYPE_AUDIO && pkt->size==0)
2772 return 0;
2774 //av_log(NULL, AV_LOG_DEBUG, "av_interleaved_write_frame %d %"PRId64" %"PRId64"\n", pkt->size, pkt->dts, pkt->pts);
2775 if(compute_pkt_fields2(st, pkt) < 0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
2776 return -1;
2778 if(pkt->dts == AV_NOPTS_VALUE && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
2779 return -1;
2781 for(;;){
2782 AVPacket opkt;
2783 int ret= av_interleave_packet(s, &opkt, pkt, 0);
2784 if(ret<=0) //FIXME cleanup needed for ret<0 ?
2785 return ret;
2787 ret= s->oformat->write_packet(s, &opkt);
2789 av_free_packet(&opkt);
2790 pkt= NULL;
2792 if(ret<0)
2793 return ret;
2794 if(url_ferror(s->pb))
2795 return url_ferror(s->pb);
2799 int av_write_trailer(AVFormatContext *s)
2801 int ret, i;
2803 for(;;){
2804 AVPacket pkt;
2805 ret= av_interleave_packet(s, &pkt, NULL, 1);
2806 if(ret<0) //FIXME cleanup needed for ret<0 ?
2807 goto fail;
2808 if(!ret)
2809 break;
2811 ret= s->oformat->write_packet(s, &pkt);
2813 av_free_packet(&pkt);
2815 if(ret<0)
2816 goto fail;
2817 if(url_ferror(s->pb))
2818 goto fail;
2821 if(s->oformat->write_trailer)
2822 ret = s->oformat->write_trailer(s);
2823 fail:
2824 if(ret == 0)
2825 ret=url_ferror(s->pb);
2826 for(i=0;i<s->nb_streams;i++)
2827 av_freep(&s->streams[i]->priv_data);
2828 av_freep(&s->priv_data);
2829 return ret;
2832 void av_program_add_stream_index(AVFormatContext *ac, int progid, unsigned int idx)
2834 int i, j;
2835 AVProgram *program=NULL;
2836 void *tmp;
2838 if (idx >= ac->nb_streams) {
2839 av_log(ac, AV_LOG_ERROR, "stream index %d is not valid\n", idx);
2840 return;
2843 for(i=0; i<ac->nb_programs; i++){
2844 if(ac->programs[i]->id != progid)
2845 continue;
2846 program = ac->programs[i];
2847 for(j=0; j<program->nb_stream_indexes; j++)
2848 if(program->stream_index[j] == idx)
2849 return;
2851 tmp = av_realloc(program->stream_index, sizeof(unsigned int)*(program->nb_stream_indexes+1));
2852 if(!tmp)
2853 return;
2854 program->stream_index = tmp;
2855 program->stream_index[program->nb_stream_indexes++] = idx;
2856 return;
2860 static void print_fps(double d, const char *postfix){
2861 uint64_t v= lrintf(d*100);
2862 if (v% 100 ) av_log(NULL, AV_LOG_INFO, ", %3.2f %s", d, postfix);
2863 else if(v%(100*1000)) av_log(NULL, AV_LOG_INFO, ", %1.0f %s", d, postfix);
2864 else av_log(NULL, AV_LOG_INFO, ", %1.0fk %s", d/1000, postfix);
2867 /* "user interface" functions */
2868 static void dump_stream_format(AVFormatContext *ic, int i, int index, int is_output)
2870 char buf[256];
2871 int flags = (is_output ? ic->oformat->flags : ic->iformat->flags);
2872 AVStream *st = ic->streams[i];
2873 int g = av_gcd(st->time_base.num, st->time_base.den);
2874 AVMetadataTag *lang = av_metadata_get(st->metadata, "language", NULL, 0);
2875 avcodec_string(buf, sizeof(buf), st->codec, is_output);
2876 av_log(NULL, AV_LOG_INFO, " Stream #%d.%d", index, i);
2877 /* the pid is an important information, so we display it */
2878 /* XXX: add a generic system */
2879 if (flags & AVFMT_SHOW_IDS)
2880 av_log(NULL, AV_LOG_INFO, "[0x%x]", st->id);
2881 if (lang)
2882 av_log(NULL, AV_LOG_INFO, "(%s)", lang->value);
2883 av_log(NULL, AV_LOG_DEBUG, ", %d/%d", st->time_base.num/g, st->time_base.den/g);
2884 av_log(NULL, AV_LOG_INFO, ": %s", buf);
2885 if (st->sample_aspect_ratio.num && // default
2886 av_cmp_q(st->sample_aspect_ratio, st->codec->sample_aspect_ratio)) {
2887 AVRational display_aspect_ratio;
2888 av_reduce(&display_aspect_ratio.num, &display_aspect_ratio.den,
2889 st->codec->width*st->sample_aspect_ratio.num,
2890 st->codec->height*st->sample_aspect_ratio.den,
2891 1024*1024);
2892 av_log(NULL, AV_LOG_INFO, ", PAR %d:%d DAR %d:%d",
2893 st->sample_aspect_ratio.num, st->sample_aspect_ratio.den,
2894 display_aspect_ratio.num, display_aspect_ratio.den);
2896 if(st->codec->codec_type == CODEC_TYPE_VIDEO){
2897 if(st->r_frame_rate.den && st->r_frame_rate.num)
2898 print_fps(av_q2d(st->r_frame_rate), "tbr");
2899 if(st->time_base.den && st->time_base.num)
2900 print_fps(1/av_q2d(st->time_base), "tbn");
2901 if(st->codec->time_base.den && st->codec->time_base.num)
2902 print_fps(1/av_q2d(st->codec->time_base), "tbc");
2904 av_log(NULL, AV_LOG_INFO, "\n");
2907 void dump_format(AVFormatContext *ic,
2908 int index,
2909 const char *url,
2910 int is_output)
2912 int i;
2913 uint8_t *printed = av_mallocz(ic->nb_streams);
2914 if (ic->nb_streams && !printed)
2915 return;
2917 av_log(NULL, AV_LOG_INFO, "%s #%d, %s, %s '%s':\n",
2918 is_output ? "Output" : "Input",
2919 index,
2920 is_output ? ic->oformat->name : ic->iformat->name,
2921 is_output ? "to" : "from", url);
2922 if (!is_output) {
2923 av_log(NULL, AV_LOG_INFO, " Duration: ");
2924 if (ic->duration != AV_NOPTS_VALUE) {
2925 int hours, mins, secs, us;
2926 secs = ic->duration / AV_TIME_BASE;
2927 us = ic->duration % AV_TIME_BASE;
2928 mins = secs / 60;
2929 secs %= 60;
2930 hours = mins / 60;
2931 mins %= 60;
2932 av_log(NULL, AV_LOG_INFO, "%02d:%02d:%02d.%02d", hours, mins, secs,
2933 (100 * us) / AV_TIME_BASE);
2934 } else {
2935 av_log(NULL, AV_LOG_INFO, "N/A");
2937 if (ic->start_time != AV_NOPTS_VALUE) {
2938 int secs, us;
2939 av_log(NULL, AV_LOG_INFO, ", start: ");
2940 secs = ic->start_time / AV_TIME_BASE;
2941 us = ic->start_time % AV_TIME_BASE;
2942 av_log(NULL, AV_LOG_INFO, "%d.%06d",
2943 secs, (int)av_rescale(us, 1000000, AV_TIME_BASE));
2945 av_log(NULL, AV_LOG_INFO, ", bitrate: ");
2946 if (ic->bit_rate) {
2947 av_log(NULL, AV_LOG_INFO,"%d kb/s", ic->bit_rate / 1000);
2948 } else {
2949 av_log(NULL, AV_LOG_INFO, "N/A");
2951 av_log(NULL, AV_LOG_INFO, "\n");
2953 if(ic->nb_programs) {
2954 int j, k, total = 0;
2955 for(j=0; j<ic->nb_programs; j++) {
2956 AVMetadataTag *name = av_metadata_get(ic->programs[j]->metadata,
2957 "name", NULL, 0);
2958 av_log(NULL, AV_LOG_INFO, " Program %d %s\n", ic->programs[j]->id,
2959 name ? name->value : "");
2960 for(k=0; k<ic->programs[j]->nb_stream_indexes; k++) {
2961 dump_stream_format(ic, ic->programs[j]->stream_index[k], index, is_output);
2962 printed[ic->programs[j]->stream_index[k]] = 1;
2964 total += ic->programs[j]->nb_stream_indexes;
2966 if (total < ic->nb_streams)
2967 av_log(NULL, AV_LOG_INFO, " No Program\n");
2969 for(i=0;i<ic->nb_streams;i++)
2970 if (!printed[i])
2971 dump_stream_format(ic, i, index, is_output);
2973 if (ic->metadata) {
2974 AVMetadataTag *tag=NULL;
2975 av_log(NULL, AV_LOG_INFO, " Metadata\n");
2976 while((tag=av_metadata_get(ic->metadata, "", tag, AV_METADATA_IGNORE_SUFFIX))) {
2977 av_log(NULL, AV_LOG_INFO, " %-16s: %s\n", tag->key, tag->value);
2980 av_free(printed);
2983 #if LIBAVFORMAT_VERSION_MAJOR < 53
2984 int parse_image_size(int *width_ptr, int *height_ptr, const char *str)
2986 return av_parse_video_frame_size(width_ptr, height_ptr, str);
2989 int parse_frame_rate(int *frame_rate_num, int *frame_rate_den, const char *arg)
2991 AVRational frame_rate;
2992 int ret = av_parse_video_frame_rate(&frame_rate, arg);
2993 *frame_rate_num= frame_rate.num;
2994 *frame_rate_den= frame_rate.den;
2995 return ret;
2997 #endif
2999 int64_t av_gettime(void)
3001 struct timeval tv;
3002 gettimeofday(&tv,NULL);
3003 return (int64_t)tv.tv_sec * 1000000 + tv.tv_usec;
3006 int64_t parse_date(const char *datestr, int duration)
3008 const char *p;
3009 int64_t t;
3010 struct tm dt;
3011 int i;
3012 static const char * const date_fmt[] = {
3013 "%Y-%m-%d",
3014 "%Y%m%d",
3016 static const char * const time_fmt[] = {
3017 "%H:%M:%S",
3018 "%H%M%S",
3020 const char *q;
3021 int is_utc, len;
3022 char lastch;
3023 int negative = 0;
3025 #undef time
3026 time_t now = time(0);
3028 len = strlen(datestr);
3029 if (len > 0)
3030 lastch = datestr[len - 1];
3031 else
3032 lastch = '\0';
3033 is_utc = (lastch == 'z' || lastch == 'Z');
3035 memset(&dt, 0, sizeof(dt));
3037 p = datestr;
3038 q = NULL;
3039 if (!duration) {
3040 if (!strncasecmp(datestr, "now", len))
3041 return (int64_t) now * 1000000;
3043 /* parse the year-month-day part */
3044 for (i = 0; i < FF_ARRAY_ELEMS(date_fmt); i++) {
3045 q = small_strptime(p, date_fmt[i], &dt);
3046 if (q) {
3047 break;
3051 /* if the year-month-day part is missing, then take the
3052 * current year-month-day time */
3053 if (!q) {
3054 if (is_utc) {
3055 dt = *gmtime(&now);
3056 } else {
3057 dt = *localtime(&now);
3059 dt.tm_hour = dt.tm_min = dt.tm_sec = 0;
3060 } else {
3061 p = q;
3064 if (*p == 'T' || *p == 't' || *p == ' ')
3065 p++;
3067 /* parse the hour-minute-second part */
3068 for (i = 0; i < FF_ARRAY_ELEMS(time_fmt); i++) {
3069 q = small_strptime(p, time_fmt[i], &dt);
3070 if (q) {
3071 break;
3074 } else {
3075 /* parse datestr as a duration */
3076 if (p[0] == '-') {
3077 negative = 1;
3078 ++p;
3080 /* parse datestr as HH:MM:SS */
3081 q = small_strptime(p, time_fmt[0], &dt);
3082 if (!q) {
3083 /* parse datestr as S+ */
3084 dt.tm_sec = strtol(p, (char **)&q, 10);
3085 if (q == p)
3086 /* the parsing didn't succeed */
3087 return INT64_MIN;
3088 dt.tm_min = 0;
3089 dt.tm_hour = 0;
3093 /* Now we have all the fields that we can get */
3094 if (!q) {
3095 return INT64_MIN;
3098 if (duration) {
3099 t = dt.tm_hour * 3600 + dt.tm_min * 60 + dt.tm_sec;
3100 } else {
3101 dt.tm_isdst = -1; /* unknown */
3102 if (is_utc) {
3103 t = mktimegm(&dt);
3104 } else {
3105 t = mktime(&dt);
3109 t *= 1000000;
3111 /* parse the .m... part */
3112 if (*q == '.') {
3113 int val, n;
3114 q++;
3115 for (val = 0, n = 100000; n >= 1; n /= 10, q++) {
3116 if (!isdigit(*q))
3117 break;
3118 val += n * (*q - '0');
3120 t += val;
3122 return negative ? -t : t;
3125 int find_info_tag(char *arg, int arg_size, const char *tag1, const char *info)
3127 const char *p;
3128 char tag[128], *q;
3130 p = info;
3131 if (*p == '?')
3132 p++;
3133 for(;;) {
3134 q = tag;
3135 while (*p != '\0' && *p != '=' && *p != '&') {
3136 if ((q - tag) < sizeof(tag) - 1)
3137 *q++ = *p;
3138 p++;
3140 *q = '\0';
3141 q = arg;
3142 if (*p == '=') {
3143 p++;
3144 while (*p != '&' && *p != '\0') {
3145 if ((q - arg) < arg_size - 1) {
3146 if (*p == '+')
3147 *q++ = ' ';
3148 else
3149 *q++ = *p;
3151 p++;
3153 *q = '\0';
3155 if (!strcmp(tag, tag1))
3156 return 1;
3157 if (*p != '&')
3158 break;
3159 p++;
3161 return 0;
3164 int av_get_frame_filename(char *buf, int buf_size,
3165 const char *path, int number)
3167 const char *p;
3168 char *q, buf1[20], c;
3169 int nd, len, percentd_found;
3171 q = buf;
3172 p = path;
3173 percentd_found = 0;
3174 for(;;) {
3175 c = *p++;
3176 if (c == '\0')
3177 break;
3178 if (c == '%') {
3179 do {
3180 nd = 0;
3181 while (isdigit(*p)) {
3182 nd = nd * 10 + *p++ - '0';
3184 c = *p++;
3185 } while (isdigit(c));
3187 switch(c) {
3188 case '%':
3189 goto addchar;
3190 case 'd':
3191 if (percentd_found)
3192 goto fail;
3193 percentd_found = 1;
3194 snprintf(buf1, sizeof(buf1), "%0*d", nd, number);
3195 len = strlen(buf1);
3196 if ((q - buf + len) > buf_size - 1)
3197 goto fail;
3198 memcpy(q, buf1, len);
3199 q += len;
3200 break;
3201 default:
3202 goto fail;
3204 } else {
3205 addchar:
3206 if ((q - buf) < buf_size - 1)
3207 *q++ = c;
3210 if (!percentd_found)
3211 goto fail;
3212 *q = '\0';
3213 return 0;
3214 fail:
3215 *q = '\0';
3216 return -1;
3219 static void hex_dump_internal(void *avcl, FILE *f, int level, uint8_t *buf, int size)
3221 int len, i, j, c;
3222 #undef fprintf
3223 #define PRINT(...) do { if (!f) av_log(avcl, level, __VA_ARGS__); else fprintf(f, __VA_ARGS__); } while(0)
3225 for(i=0;i<size;i+=16) {
3226 len = size - i;
3227 if (len > 16)
3228 len = 16;
3229 PRINT("%08x ", i);
3230 for(j=0;j<16;j++) {
3231 if (j < len)
3232 PRINT(" %02x", buf[i+j]);
3233 else
3234 PRINT(" ");
3236 PRINT(" ");
3237 for(j=0;j<len;j++) {
3238 c = buf[i+j];
3239 if (c < ' ' || c > '~')
3240 c = '.';
3241 PRINT("%c", c);
3243 PRINT("\n");
3245 #undef PRINT
3248 void av_hex_dump(FILE *f, uint8_t *buf, int size)
3250 hex_dump_internal(NULL, f, 0, buf, size);
3253 void av_hex_dump_log(void *avcl, int level, uint8_t *buf, int size)
3255 hex_dump_internal(avcl, NULL, level, buf, size);
3258 //FIXME needs to know the time_base
3259 static void pkt_dump_internal(void *avcl, FILE *f, int level, AVPacket *pkt, int dump_payload)
3261 #undef fprintf
3262 #define PRINT(...) do { if (!f) av_log(avcl, level, __VA_ARGS__); else fprintf(f, __VA_ARGS__); } while(0)
3263 PRINT("stream #%d:\n", pkt->stream_index);
3264 PRINT(" keyframe=%d\n", ((pkt->flags & PKT_FLAG_KEY) != 0));
3265 PRINT(" duration=%0.3f\n", (double)pkt->duration / AV_TIME_BASE);
3266 /* DTS is _always_ valid after av_read_frame() */
3267 PRINT(" dts=");
3268 if (pkt->dts == AV_NOPTS_VALUE)
3269 PRINT("N/A");
3270 else
3271 PRINT("%0.3f", (double)pkt->dts / AV_TIME_BASE);
3272 /* PTS may not be known if B-frames are present. */
3273 PRINT(" pts=");
3274 if (pkt->pts == AV_NOPTS_VALUE)
3275 PRINT("N/A");
3276 else
3277 PRINT("%0.3f", (double)pkt->pts / AV_TIME_BASE);
3278 PRINT("\n");
3279 PRINT(" size=%d\n", pkt->size);
3280 #undef PRINT
3281 if (dump_payload)
3282 av_hex_dump(f, pkt->data, pkt->size);
3285 void av_pkt_dump(FILE *f, AVPacket *pkt, int dump_payload)
3287 pkt_dump_internal(NULL, f, 0, pkt, dump_payload);
3290 void av_pkt_dump_log(void *avcl, int level, AVPacket *pkt, int dump_payload)
3292 pkt_dump_internal(avcl, NULL, level, pkt, dump_payload);
3295 void url_split(char *proto, int proto_size,
3296 char *authorization, int authorization_size,
3297 char *hostname, int hostname_size,
3298 int *port_ptr,
3299 char *path, int path_size,
3300 const char *url)
3302 const char *p, *ls, *at, *col, *brk;
3304 if (port_ptr) *port_ptr = -1;
3305 if (proto_size > 0) proto[0] = 0;
3306 if (authorization_size > 0) authorization[0] = 0;
3307 if (hostname_size > 0) hostname[0] = 0;
3308 if (path_size > 0) path[0] = 0;
3310 /* parse protocol */
3311 if ((p = strchr(url, ':'))) {
3312 av_strlcpy(proto, url, FFMIN(proto_size, p + 1 - url));
3313 p++; /* skip ':' */
3314 if (*p == '/') p++;
3315 if (*p == '/') p++;
3316 } else {
3317 /* no protocol means plain filename */
3318 av_strlcpy(path, url, path_size);
3319 return;
3322 /* separate path from hostname */
3323 ls = strchr(p, '/');
3324 if(!ls)
3325 ls = strchr(p, '?');
3326 if(ls)
3327 av_strlcpy(path, ls, path_size);
3328 else
3329 ls = &p[strlen(p)]; // XXX
3331 /* the rest is hostname, use that to parse auth/port */
3332 if (ls != p) {
3333 /* authorization (user[:pass]@hostname) */
3334 if ((at = strchr(p, '@')) && at < ls) {
3335 av_strlcpy(authorization, p,
3336 FFMIN(authorization_size, at + 1 - p));
3337 p = at + 1; /* skip '@' */
3340 if (*p == '[' && (brk = strchr(p, ']')) && brk < ls) {
3341 /* [host]:port */
3342 av_strlcpy(hostname, p + 1,
3343 FFMIN(hostname_size, brk - p));
3344 if (brk[1] == ':' && port_ptr)
3345 *port_ptr = atoi(brk + 2);
3346 } else if ((col = strchr(p, ':')) && col < ls) {
3347 av_strlcpy(hostname, p,
3348 FFMIN(col + 1 - p, hostname_size));
3349 if (port_ptr) *port_ptr = atoi(col + 1);
3350 } else
3351 av_strlcpy(hostname, p,
3352 FFMIN(ls + 1 - p, hostname_size));
3356 char *ff_data_to_hex(char *buff, const uint8_t *src, int s)
3358 int i;
3359 static const char hex_table[16] = { '0', '1', '2', '3',
3360 '4', '5', '6', '7',
3361 '8', '9', 'A', 'B',
3362 'C', 'D', 'E', 'F' };
3364 for(i = 0; i < s; i++) {
3365 buff[i * 2] = hex_table[src[i] >> 4];
3366 buff[i * 2 + 1] = hex_table[src[i] & 0xF];
3369 return buff;
3372 void av_set_pts_info(AVStream *s, int pts_wrap_bits,
3373 unsigned int pts_num, unsigned int pts_den)
3375 s->pts_wrap_bits = pts_wrap_bits;
3377 if(av_reduce(&s->time_base.num, &s->time_base.den, pts_num, pts_den, INT_MAX)){
3378 if(s->time_base.num != pts_num)
3379 av_log(NULL, AV_LOG_DEBUG, "st:%d removing common factor %d from timebase\n", s->index, pts_num/s->time_base.num);
3380 }else
3381 av_log(NULL, AV_LOG_WARNING, "st:%d has too large timebase, reducing\n", s->index);
3383 if(!s->time_base.num || !s->time_base.den)
3384 s->time_base.num= s->time_base.den= 0;