added option probesize; at the moment only used by mpegts.c
[libav.git] / libavformat / utils.c
CommitLineData
de6d9b64
FB
1/*
2 * Various utilities for ffmpeg system
19720f15 3 * Copyright (c) 2000, 2001, 2002 Fabrice Bellard
de6d9b64 4 *
19720f15
FB
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public
7 * License as published by the Free Software Foundation; either
8 * version 2 of the License, or (at your option) any later version.
de6d9b64 9 *
19720f15 10 * This library is distributed in the hope that it will be useful,
de6d9b64 11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19720f15
FB
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
de6d9b64 14 *
19720f15
FB
15 * You should have received a copy of the GNU Lesser General Public
16 * License along with this library; if not, write to the Free Software
5509bffa 17 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
de6d9b64 18 */
8be1c656 19#include "avformat.h"
e006c307 20#include "allformats.h"
4eb72c6b 21#include "opt.h"
c5510dd6 22
b754978a
MN
23#undef NDEBUG
24#include <assert.h>
25
e36bdf8b
DK
26/**
27 * @file libavformat/utils.c
28 * Various utility functions for using ffmpeg library.
29 */
30
f3a30e3a
LB
31static void av_frac_init(AVFrac *f, int64_t val, int64_t num, int64_t den);
32static void av_frac_add(AVFrac *f, int64_t incr);
33static void av_frac_set(AVFrac *f, int64_t val);
34
e36bdf8b 35/** head of registered input format linked list. */
8b69867f 36AVInputFormat *first_iformat = NULL;
e36bdf8b 37/** head of registered output format linked list. */
8b69867f 38AVOutputFormat *first_oformat = NULL;
e36bdf8b 39/** head of registered image format linked list. */
8b69867f 40AVImageFormat *first_image_format = NULL;
de6d9b64 41
b9a281db 42void av_register_input_format(AVInputFormat *format)
de6d9b64 43{
b9a281db
FB
44 AVInputFormat **p;
45 p = &first_iformat;
46 while (*p != NULL) p = &(*p)->next;
47 *p = format;
48 format->next = NULL;
49}
50
51void av_register_output_format(AVOutputFormat *format)
52{
53 AVOutputFormat **p;
54 p = &first_oformat;
de6d9b64
FB
55 while (*p != NULL) p = &(*p)->next;
56 *p = format;
57 format->next = NULL;
58}
59
5b25dfa7 60int match_ext(const char *filename, const char *extensions)
de6d9b64
FB
61{
62 const char *ext, *p;
63 char ext1[32], *q;
64
293ed23f
MN
65 if(!filename)
66 return 0;
115329f1 67
de6d9b64
FB
68 ext = strrchr(filename, '.');
69 if (ext) {
70 ext++;
71 p = extensions;
72 for(;;) {
73 q = ext1;
115329f1 74 while (*p != '\0' && *p != ',' && q-ext1<sizeof(ext1)-1)
de6d9b64
FB
75 *q++ = *p++;
76 *q = '\0';
115329f1 77 if (!strcasecmp(ext1, ext))
de6d9b64 78 return 1;
115329f1 79 if (*p == '\0')
de6d9b64
FB
80 break;
81 p++;
82 }
83 }
84 return 0;
85}
86
115329f1 87AVOutputFormat *guess_format(const char *short_name, const char *filename,
b9a281db 88 const char *mime_type)
de6d9b64 89{
b9a281db 90 AVOutputFormat *fmt, *fmt_found;
de6d9b64
FB
91 int score_max, score;
92
87a0a681 93 /* specific test for image sequences */
ff70e601 94#ifdef CONFIG_IMAGE2_MUXER
115329f1 95 if (!short_name && filename &&
94d883e8 96 filename_number_test(filename) >= 0 &&
5b6d5596
MN
97 av_guess_image2_codec(filename) != CODEC_ID_NONE) {
98 return guess_format("image2", NULL, NULL);
99 }
ff70e601 100#endif
115329f1 101 if (!short_name && filename &&
5b6d5596 102 filename_number_test(filename) >= 0 &&
94d883e8 103 guess_image_format(filename)) {
87a0a681
FB
104 return guess_format("image", NULL, NULL);
105 }
106
de6d9b64
FB
107 /* find the proper file type */
108 fmt_found = NULL;
109 score_max = 0;
b9a281db 110 fmt = first_oformat;
de6d9b64
FB
111 while (fmt != NULL) {
112 score = 0;
113 if (fmt->name && short_name && !strcmp(fmt->name, short_name))
114 score += 100;
115 if (fmt->mime_type && mime_type && !strcmp(fmt->mime_type, mime_type))
116 score += 10;
115329f1 117 if (filename && fmt->extensions &&
de6d9b64
FB
118 match_ext(filename, fmt->extensions)) {
119 score += 5;
120 }
121 if (score > score_max) {
122 score_max = score;
123 fmt_found = fmt;
124 }
125 fmt = fmt->next;
126 }
127 return fmt_found;
115329f1 128}
de6d9b64 129
115329f1 130AVOutputFormat *guess_stream_format(const char *short_name, const char *filename,
c5510dd6
PG
131 const char *mime_type)
132{
133 AVOutputFormat *fmt = guess_format(short_name, filename, mime_type);
134
135 if (fmt) {
136 AVOutputFormat *stream_fmt;
137 char stream_format_name[64];
138
139 snprintf(stream_format_name, sizeof(stream_format_name), "%s_stream", fmt->name);
140 stream_fmt = guess_format(stream_format_name, NULL, NULL);
141
142 if (stream_fmt)
143 fmt = stream_fmt;
144 }
145
146 return fmt;
147}
148
5b6d5596 149/**
e36bdf8b 150 * Guesses the codec id based upon muxer and filename.
5b6d5596 151 */
115329f1 152enum CodecID av_guess_codec(AVOutputFormat *fmt, const char *short_name,
5b6d5596
MN
153 const char *filename, const char *mime_type, enum CodecType type){
154 if(type == CODEC_TYPE_VIDEO){
155 enum CodecID codec_id= CODEC_ID_NONE;
156
ff70e601 157#ifdef CONFIG_IMAGE2_MUXER
ae214ac3 158 if(!strcmp(fmt->name, "image2") || !strcmp(fmt->name, "image2pipe")){
5b6d5596
MN
159 codec_id= av_guess_image2_codec(filename);
160 }
ff70e601 161#endif
5b6d5596
MN
162 if(codec_id == CODEC_ID_NONE)
163 codec_id= fmt->video_codec;
164 return codec_id;
165 }else if(type == CODEC_TYPE_AUDIO)
166 return fmt->audio_codec;
167 else
168 return CODEC_ID_NONE;
169}
170
e36bdf8b
DK
171/**
172 * finds AVInputFormat based on input format's short name.
173 */
b9a281db
FB
174AVInputFormat *av_find_input_format(const char *short_name)
175{
176 AVInputFormat *fmt;
177 for(fmt = first_iformat; fmt != NULL; fmt = fmt->next) {
178 if (!strcmp(fmt->name, short_name))
179 return fmt;
180 }
181 return NULL;
182}
183
de6d9b64
FB
184/* memory handling */
185
b9a281db 186/**
e36bdf8b 187 * Default packet destructor.
6fa5a56c 188 */
90ad92b3 189void av_destruct_packet(AVPacket *pkt)
6fa5a56c
FB
190{
191 av_free(pkt->data);
192 pkt->data = NULL; pkt->size = 0;
193}
194
195/**
b9a281db
FB
196 * Allocate the payload of a packet and intialized its fields to default values.
197 *
198 * @param pkt packet
199 * @param size wanted payload size
200 * @return 0 if OK. AVERROR_xxx otherwise.
201 */
de6d9b64
FB
202int av_new_packet(AVPacket *pkt, int size)
203{
568e18b1
MN
204 void *data;
205 if((unsigned)size > (unsigned)size + FF_INPUT_BUFFER_PADDING_SIZE)
115329f1 206 return AVERROR_NOMEM;
568e18b1 207 data = av_malloc(size + FF_INPUT_BUFFER_PADDING_SIZE);
6fa5a56c 208 if (!data)
b9a281db 209 return AVERROR_NOMEM;
6fa5a56c 210 memset(data + size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
8cd5be98 211
6fa5a56c 212 av_init_packet(pkt);
115329f1 213 pkt->data = data;
6fa5a56c
FB
214 pkt->size = size;
215 pkt->destruct = av_destruct_packet;
de6d9b64
FB
216 return 0;
217}
218
2692067a
MN
219/**
220 * Allocate and read the payload of a packet and intialized its fields to default values.
221 *
222 * @param pkt packet
223 * @param size wanted payload size
224 * @return >0 (read size) if OK. AVERROR_xxx otherwise.
225 */
226int av_get_packet(ByteIOContext *s, AVPacket *pkt, int size)
227{
228 int ret= av_new_packet(pkt, size);
229
230 if(ret<0)
231 return ret;
232
233 pkt->pos= url_ftell(s);
234
235 ret= get_buffer(s, pkt->data, size);
236 if(ret<=0)
237 av_free_packet(pkt);
238 else
239 pkt->size= ret;
240
241 return ret;
242}
243
fb2758c8
FB
244/* This is a hack - the packet memory allocation stuff is broken. The
245 packet is allocated if it was not really allocated */
246int av_dup_packet(AVPacket *pkt)
247{
248 if (pkt->destruct != av_destruct_packet) {
249 uint8_t *data;
8a56ac7b
FB
250 /* we duplicate the packet and don't forget to put the padding
251 again */
568e18b1 252 if((unsigned)pkt->size > (unsigned)pkt->size + FF_INPUT_BUFFER_PADDING_SIZE)
115329f1 253 return AVERROR_NOMEM;
8a56ac7b 254 data = av_malloc(pkt->size + FF_INPUT_BUFFER_PADDING_SIZE);
fb2758c8
FB
255 if (!data) {
256 return AVERROR_NOMEM;
257 }
258 memcpy(data, pkt->data, pkt->size);
8a56ac7b 259 memset(data + pkt->size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
fb2758c8
FB
260 pkt->data = data;
261 pkt->destruct = av_destruct_packet;
262 }
263 return 0;
264}
265
de6d9b64
FB
266/* fifo handling */
267
268int fifo_init(FifoBuffer *f, int size)
269{
1ea4f593 270 f->buffer = av_malloc(size);
de6d9b64
FB
271 if (!f->buffer)
272 return -1;
273 f->end = f->buffer + size;
274 f->wptr = f->rptr = f->buffer;
275 return 0;
276}
277
278void fifo_free(FifoBuffer *f)
279{
1ea4f593 280 av_free(f->buffer);
de6d9b64
FB
281}
282
0c1a9eda 283int fifo_size(FifoBuffer *f, uint8_t *rptr)
de6d9b64
FB
284{
285 int size;
115329f1 286
0d712409
MN
287 if(!rptr)
288 rptr= f->rptr;
de6d9b64
FB
289
290 if (f->wptr >= rptr) {
291 size = f->wptr - rptr;
292 } else {
293 size = (f->end - rptr) + (f->wptr - f->buffer);
294 }
295 return size;
296}
297
e36bdf8b
DK
298/**
299 * Get data from the fifo (returns -1 if not enough data).
300 */
0c1a9eda 301int fifo_read(FifoBuffer *f, uint8_t *buf, int buf_size, uint8_t **rptr_ptr)
de6d9b64 302{
0d712409 303 uint8_t *rptr;
de6d9b64
FB
304 int size, len;
305
0d712409
MN
306 if(!rptr_ptr)
307 rptr_ptr= &f->rptr;
308 rptr = *rptr_ptr;
309
de6d9b64
FB
310 if (f->wptr >= rptr) {
311 size = f->wptr - rptr;
312 } else {
313 size = (f->end - rptr) + (f->wptr - f->buffer);
314 }
115329f1 315
de6d9b64
FB
316 if (size < buf_size)
317 return -1;
318 while (buf_size > 0) {
319 len = f->end - rptr;
320 if (len > buf_size)
321 len = buf_size;
322 memcpy(buf, rptr, len);
323 buf += len;
324 rptr += len;
325 if (rptr >= f->end)
326 rptr = f->buffer;
327 buf_size -= len;
328 }
329 *rptr_ptr = rptr;
330 return 0;
331}
332
e36bdf8b
DK
333/**
334 * Resizes a FIFO.
335 */
568e18b1
MN
336void fifo_realloc(FifoBuffer *f, unsigned int new_size){
337 unsigned int old_size= f->end - f->buffer;
115329f1 338
0d712409
MN
339 if(old_size < new_size){
340 uint8_t *old= f->buffer;
341
342 f->buffer= av_realloc(f->buffer, new_size);
343
344 f->rptr += f->buffer - old;
345 f->wptr += f->buffer - old;
346
347 if(f->wptr < f->rptr){
348 memmove(f->rptr + new_size - old_size, f->rptr, f->buffer + old_size - f->rptr);
349 f->rptr += new_size - old_size;
350 }
351 f->end= f->buffer + new_size;
352 }
353}
354
a97c1e93 355void fifo_write(FifoBuffer *f, const uint8_t *buf, int size, uint8_t **wptr_ptr)
de6d9b64
FB
356{
357 int len;
0c1a9eda 358 uint8_t *wptr;
0d712409
MN
359
360 if(!wptr_ptr)
361 wptr_ptr= &f->wptr;
de6d9b64 362 wptr = *wptr_ptr;
0d712409 363
de6d9b64
FB
364 while (size > 0) {
365 len = f->end - wptr;
366 if (len > size)
367 len = size;
368 memcpy(wptr, buf, len);
369 wptr += len;
370 if (wptr >= f->end)
371 wptr = f->buffer;
372 buf += len;
373 size -= len;
374 }
375 *wptr_ptr = wptr;
376}
377
7000a175
MN
378/* get data from the fifo (return -1 if not enough data) */
379int put_fifo(ByteIOContext *pb, FifoBuffer *f, int buf_size, uint8_t **rptr_ptr)
380{
381 uint8_t *rptr = *rptr_ptr;
382 int size, len;
383
384 if (f->wptr >= rptr) {
385 size = f->wptr - rptr;
386 } else {
387 size = (f->end - rptr) + (f->wptr - f->buffer);
388 }
115329f1 389
7000a175
MN
390 if (size < buf_size)
391 return -1;
392 while (buf_size > 0) {
393 len = f->end - rptr;
394 if (len > buf_size)
395 len = buf_size;
396 put_buffer(pb, rptr, len);
397 rptr += len;
398 if (rptr >= f->end)
399 rptr = f->buffer;
400 buf_size -= len;
401 }
402 *rptr_ptr = rptr;
403 return 0;
404}
405
b9a281db
FB
406int filename_number_test(const char *filename)
407{
408 char buf[1024];
293ed23f
MN
409 if(!filename)
410 return -1;
b9a281db
FB
411 return get_frame_filename(buf, sizeof(buf), filename, 1);
412}
413
e36bdf8b
DK
414/**
415 * Guess file format.
416 */
a25e098d 417AVInputFormat *av_probe_input_format(AVProbeData *pd, int is_opened)
b9a281db
FB
418{
419 AVInputFormat *fmt1, *fmt;
420 int score, score_max;
421
422 fmt = NULL;
423 score_max = 0;
424 for(fmt1 = first_iformat; fmt1 != NULL; fmt1 = fmt1->next) {
425 if (!is_opened && !(fmt1->flags & AVFMT_NOFILE))
426 continue;
427 score = 0;
a8dbe951
PG
428 if (fmt1->read_probe) {
429 score = fmt1->read_probe(pd);
430 } else if (fmt1->extensions) {
b9a281db
FB
431 if (match_ext(pd->filename, fmt1->extensions)) {
432 score = 50;
433 }
115329f1 434 }
b9a281db
FB
435 if (score > score_max) {
436 score_max = score;
437 fmt = fmt1;
438 }
439 }
440 return fmt;
441}
442
443/************************************************************/
444/* input media file */
96baaa6a 445
da24c5e3 446/**
e36bdf8b 447 * Open a media file from an IO stream. 'fmt' must be specified.
da24c5e3 448 */
43465395 449static const char* format_to_name(void* ptr)
bc874dae 450{
43465395 451 AVFormatContext* fc = (AVFormatContext*) ptr;
bc874dae
MB
452 if(fc->iformat) return fc->iformat->name;
453 else if(fc->oformat) return fc->oformat->name;
454 else return "NULL";
455}
456
4eb72c6b
NS
457#define OFFSET(x) (int)&((AVFormatContext*)0)->x
458#define DEFAULT 0 //should be NAN but it doesnt work as its not a constant in glibc as required by ANSI/ISO C
459//these names are too long to be readable
460#define E AV_OPT_FLAG_ENCODING_PARAM
461#define D AV_OPT_FLAG_DECODING_PARAM
462
463static const AVOption options[]={
9e6c9470 464{"probesize", NULL, OFFSET(probesize), FF_OPT_TYPE_INT, DEFAULT, 32, INT_MAX, D},
4eb72c6b
NS
465{NULL},
466};
467
468static const AVClass av_format_context_class = { "AVFormatContext", format_to_name, options };
469
470void avformat_get_context_defaults(AVFormatContext *s){
471 memset(s, 0, sizeof(AVFormatContext));
9e6c9470
NS
472
473 /* from mpegts.c: 1.0 second at 24Mbit/s */
474 s->probesize=32000;
4eb72c6b 475}
bc874dae
MB
476
477AVFormatContext *av_alloc_format_context(void)
478{
479 AVFormatContext *ic;
480 ic = av_mallocz(sizeof(AVFormatContext));
481 if (!ic) return ic;
4eb72c6b 482 avformat_get_context_defaults(ic);
43465395 483 ic->av_class = &av_format_context_class;
bc874dae
MB
484 return ic;
485}
486
e36bdf8b
DK
487/**
488 * Allocates all the structures needed to read an input stream.
489 * This does not open the needed codecs for decoding the stream[s].
490 */
115329f1
DB
491int av_open_input_stream(AVFormatContext **ic_ptr,
492 ByteIOContext *pb, const char *filename,
da24c5e3
FB
493 AVInputFormat *fmt, AVFormatParameters *ap)
494{
495 int err;
496 AVFormatContext *ic;
c04c3282
MN
497 AVFormatParameters default_ap;
498
499 if(!ap){
500 ap=&default_ap;
501 memset(ap, 0, sizeof(default_ap));
502 }
da24c5e3 503
4eb72c6b
NS
504 if(!ap->prealloced_context)
505 ic = av_alloc_format_context();
506 else
507 ic = *ic_ptr;
da24c5e3
FB
508 if (!ic) {
509 err = AVERROR_NOMEM;
510 goto fail;
511 }
512 ic->iformat = fmt;
513 if (pb)
514 ic->pb = *pb;
515 ic->duration = AV_NOPTS_VALUE;
516 ic->start_time = AV_NOPTS_VALUE;
517 pstrcpy(ic->filename, sizeof(ic->filename), filename);
518
519 /* allocate private data */
520 if (fmt->priv_data_size > 0) {
521 ic->priv_data = av_mallocz(fmt->priv_data_size);
522 if (!ic->priv_data) {
523 err = AVERROR_NOMEM;
524 goto fail;
525 }
526 } else {
527 ic->priv_data = NULL;
528 }
529
da24c5e3
FB
530 err = ic->iformat->read_header(ic, ap);
531 if (err < 0)
532 goto fail;
fb2758c8
FB
533
534 if (pb)
535 ic->data_offset = url_ftell(&ic->pb);
536
da24c5e3
FB
537 *ic_ptr = ic;
538 return 0;
539 fail:
540 if (ic) {
541 av_freep(&ic->priv_data);
542 }
543 av_free(ic);
544 *ic_ptr = NULL;
545 return err;
546}
547
e36bdf8b 548/** Size of probe buffer, for guessing file type from file contents. */
a877eedc 549#define PROBE_BUF_MIN 2048
329b1e75 550#define PROBE_BUF_MAX (1<<20)
b9a281db
FB
551
552/**
553 * Open a media file as input. The codec are not opened. Only the file
554 * header (if present) is read.
555 *
556 * @param ic_ptr the opened media file handle is put here
557 * @param filename filename to open.
558 * @param fmt if non NULL, force the file format to use
559 * @param buf_size optional buffer size (zero if default is OK)
560 * @param ap additionnal parameters needed when opening the file (NULL if default)
561 * @return 0 if OK. AVERROR_xxx otherwise.
562 */
115329f1 563int av_open_input_file(AVFormatContext **ic_ptr, const char *filename,
b9a281db
FB
564 AVInputFormat *fmt,
565 int buf_size,
566 AVFormatParameters *ap)
de6d9b64 567{
a877eedc 568 int err, must_open_file, file_opened, probe_size;
b9a281db 569 AVProbeData probe_data, *pd = &probe_data;
da24c5e3 570 ByteIOContext pb1, *pb = &pb1;
115329f1 571
da24c5e3
FB
572 file_opened = 0;
573 pd->filename = "";
574 if (filename)
575 pd->filename = filename;
a877eedc 576 pd->buf = NULL;
b9a281db
FB
577 pd->buf_size = 0;
578
579 if (!fmt) {
580 /* guess format if no file can be opened */
a25e098d 581 fmt = av_probe_input_format(pd, 0);
de6d9b64 582 }
de6d9b64 583
b6892136
FB
584 /* do not open file if the format does not need it. XXX: specific
585 hack needed to handle RTSP/TCP */
586 must_open_file = 1;
da24c5e3 587 if (fmt && (fmt->flags & AVFMT_NOFILE)) {
b6892136 588 must_open_file = 0;
63dd1377 589 pb= NULL; //FIXME this or memset(pb, 0, sizeof(ByteIOContext)); otherwise its uninitalized
b6892136
FB
590 }
591
592 if (!fmt || must_open_file) {
87a0a681 593 /* if no file needed do not try to open one */
da24c5e3 594 if (url_fopen(pb, filename, URL_RDONLY) < 0) {
b9a281db 595 err = AVERROR_IO;
96baaa6a 596 goto fail;
b9a281db 597 }
da24c5e3 598 file_opened = 1;
96baaa6a 599 if (buf_size > 0) {
da24c5e3 600 url_setbufsize(pb, buf_size);
96baaa6a 601 }
a877eedc
MN
602
603 for(probe_size= PROBE_BUF_MIN; probe_size<=PROBE_BUF_MAX && !fmt; probe_size<<=1){
5b25dfa7 604 /* read probe data */
a877eedc
MN
605 pd->buf= av_realloc(pd->buf, probe_size);
606 pd->buf_size = get_buffer(pb, pd->buf, probe_size);
53e2f9ca
MN
607 if (url_fseek(pb, 0, SEEK_SET) == (offset_t)-EPIPE) {
608 url_fclose(pb);
609 if (url_fopen(pb, filename, URL_RDONLY) < 0) {
5e43b17e 610 file_opened = 0;
53e2f9ca
MN
611 err = AVERROR_IO;
612 goto fail;
613 }
614 }
a877eedc
MN
615 /* guess file format */
616 fmt = av_probe_input_format(pd, 1);
5b25dfa7 617 }
a877eedc 618 av_freep(&pd->buf);
b9a281db
FB
619 }
620
621 /* if still no format found, error */
622 if (!fmt) {
623 err = AVERROR_NOFMT;
da24c5e3 624 goto fail;
de6d9b64 625 }
115329f1 626
67d06418 627 /* XXX: suppress this hack for redirectors */
f3ec2d46 628#ifdef CONFIG_NETWORK
d2a067d1 629 if (fmt == &redir_demuxer) {
da24c5e3
FB
630 err = redir_open(ic_ptr, pb);
631 url_fclose(pb);
67d06418
FB
632 return err;
633 }
9b2e001f 634#endif
67d06418 635
87a0a681 636 /* check filename in case of an image number is expected */
da24c5e3 637 if (fmt->flags & AVFMT_NEEDNUMBER) {
115329f1 638 if (filename_number_test(filename) < 0) {
87a0a681 639 err = AVERROR_NUMEXPECTED;
da24c5e3 640 goto fail;
87a0a681
FB
641 }
642 }
da24c5e3
FB
643 err = av_open_input_stream(ic_ptr, pb, filename, fmt, ap);
644 if (err)
645 goto fail;
b9a281db 646 return 0;
de6d9b64 647 fail:
a877eedc 648 av_freep(&pd->buf);
da24c5e3
FB
649 if (file_opened)
650 url_fclose(pb);
b9a281db
FB
651 *ic_ptr = NULL;
652 return err;
115329f1 653
de6d9b64
FB
654}
655
da24c5e3
FB
656/*******************************************************/
657
b9a281db 658/**
e36bdf8b
DK
659 * Read a transport packet from a media file.
660 *
661 * This function is absolete and should never be used.
662 * Use av_read_frame() instead.
115329f1 663 *
b9a281db 664 * @param s media file handle
115329f1
DB
665 * @param pkt is filled
666 * @return 0 if OK. AVERROR_xxx if error.
b9a281db 667 */
de6d9b64
FB
668int av_read_packet(AVFormatContext *s, AVPacket *pkt)
669{
fb2758c8
FB
670 return s->iformat->read_packet(s, pkt);
671}
672
673/**********************************************************/
674
e36bdf8b
DK
675/**
676 * Get the number of samples of an audio frame. Return (-1) if error.
677 */
fb2758c8
FB
678static int get_audio_frame_size(AVCodecContext *enc, int size)
679{
680 int frame_size;
681
682 if (enc->frame_size <= 1) {
ac3e1834
BC
683 int bits_per_sample = av_get_bits_per_sample(enc->codec_id);
684
685 if (bits_per_sample) {
fb2758c8
FB
686 if (enc->channels == 0)
687 return -1;
f1b163e0 688 frame_size = (size << 3) / (bits_per_sample * enc->channels);
ac3e1834 689 } else {
fb2758c8
FB
690 /* used for example by ADPCM codecs */
691 if (enc->bit_rate == 0)
692 return -1;
693 frame_size = (size * 8 * enc->sample_rate) / enc->bit_rate;
fb2758c8
FB
694 }
695 } else {
696 frame_size = enc->frame_size;
697 }
698 return frame_size;
699}
700
701
e36bdf8b
DK
702/**
703 * Return the frame duration in seconds, return 0 if not available.
704 */
115329f1 705static void compute_frame_duration(int *pnum, int *pden, AVStream *st,
fb2758c8
FB
706 AVCodecParserContext *pc, AVPacket *pkt)
707{
708 int frame_size;
709
710 *pnum = 0;
711 *pden = 0;
01f4895c 712 switch(st->codec->codec_type) {
fb2758c8 713 case CODEC_TYPE_VIDEO:
1677155d 714 if(st->time_base.num*1000LL > st->time_base.den){
c0df9d75
MN
715 *pnum = st->time_base.num;
716 *pden = st->time_base.den;
01f4895c
MN
717 }else if(st->codec->time_base.num*1000LL > st->codec->time_base.den){
718 *pnum = st->codec->time_base.num;
719 *pden = st->codec->time_base.den;
327c4076
MN
720 if (pc && pc->repeat_pict) {
721 *pden *= 2;
722 *pnum = (*pnum) * (2 + pc->repeat_pict);
723 }
fb2758c8
FB
724 }
725 break;
726 case CODEC_TYPE_AUDIO:
01f4895c 727 frame_size = get_audio_frame_size(st->codec, pkt->size);
fb2758c8
FB
728 if (frame_size < 0)
729 break;
730 *pnum = frame_size;
01f4895c 731 *pden = st->codec->sample_rate;
fb2758c8
FB
732 break;
733 default:
734 break;
735 }
736}
737
5ba7c3d7
MN
738static int is_intra_only(AVCodecContext *enc){
739 if(enc->codec_type == CODEC_TYPE_AUDIO){
740 return 1;
741 }else if(enc->codec_type == CODEC_TYPE_VIDEO){
742 switch(enc->codec_id){
743 case CODEC_ID_MJPEG:
744 case CODEC_ID_MJPEGB:
745 case CODEC_ID_LJPEG:
746 case CODEC_ID_RAWVIDEO:
747 case CODEC_ID_DVVIDEO:
748 case CODEC_ID_HUFFYUV:
f37b9768 749 case CODEC_ID_FFVHUFF:
5ba7c3d7
MN
750 case CODEC_ID_ASV1:
751 case CODEC_ID_ASV2:
752 case CODEC_ID_VCR1:
753 return 1;
754 default: break;
755 }
756 }
757 return 0;
758}
759
77405fc8 760static int64_t lsb2full(int64_t lsb, int64_t last_ts, int lsb_bits){
4fc2c644 761 int64_t mask = lsb_bits < 64 ? (1LL<<lsb_bits)-1 : -1LL;
77405fc8
MN
762 int64_t delta= last_ts - mask/2;
763 return ((lsb - delta)&mask) + delta;
764}
765
115329f1 766static void compute_pkt_fields(AVFormatContext *s, AVStream *st,
fb2758c8
FB
767 AVCodecParserContext *pc, AVPacket *pkt)
768{
769 int num, den, presentation_delayed;
77405fc8 770 /* handle wrapping */
e928649b
MN
771 if(st->cur_dts != AV_NOPTS_VALUE){
772 if(pkt->pts != AV_NOPTS_VALUE)
773 pkt->pts= lsb2full(pkt->pts, st->cur_dts, st->pts_wrap_bits);
774 if(pkt->dts != AV_NOPTS_VALUE)
775 pkt->dts= lsb2full(pkt->dts, st->cur_dts, st->pts_wrap_bits);
776 }
115329f1 777
fb2758c8 778 if (pkt->duration == 0) {
3c895fc0 779 compute_frame_duration(&num, &den, st, pc, pkt);
fb2758c8 780 if (den && num) {
77405fc8 781 pkt->duration = av_rescale(1, num * (int64_t)st->time_base.den, den * (int64_t)st->time_base.num);
fb2758c8
FB
782 }
783 }
784
01f4895c 785 if(is_intra_only(st->codec))
5ba7c3d7
MN
786 pkt->flags |= PKT_FLAG_KEY;
787
fb2758c8
FB
788 /* do we have a video B frame ? */
789 presentation_delayed = 0;
01f4895c 790 if (st->codec->codec_type == CODEC_TYPE_VIDEO) {
fb2758c8
FB
791 /* XXX: need has_b_frame, but cannot get it if the codec is
792 not initialized */
115329f1
DB
793 if (( st->codec->codec_id == CODEC_ID_H264
794 || st->codec->has_b_frames) &&
fb2758c8
FB
795 pc && pc->pict_type != FF_B_TYPE)
796 presentation_delayed = 1;
77405fc8
MN
797 /* this may be redundant, but it shouldnt hurt */
798 if(pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE && pkt->pts > pkt->dts)
799 presentation_delayed = 1;
fb2758c8 800 }
115329f1 801
e928649b
MN
802 if(st->cur_dts == AV_NOPTS_VALUE){
803 if(presentation_delayed) st->cur_dts = -pkt->duration;
804 else st->cur_dts = 0;
805 }
fb2758c8 806
3c895fc0 807// av_log(NULL, AV_LOG_DEBUG, "IN delayed:%d pts:%lld, dts:%lld cur_dts:%lld st:%d pc:%p\n", presentation_delayed, pkt->pts, pkt->dts, st->cur_dts, pkt->stream_index, pc);
fb2758c8
FB
808 /* interpolate PTS and DTS if they are not present */
809 if (presentation_delayed) {
810 /* DTS = decompression time stamp */
811 /* PTS = presentation time stamp */
812 if (pkt->dts == AV_NOPTS_VALUE) {
77405fc8
MN
813 /* if we know the last pts, use it */
814 if(st->last_IP_pts != AV_NOPTS_VALUE)
815 st->cur_dts = pkt->dts = st->last_IP_pts;
816 else
817 pkt->dts = st->cur_dts;
fb2758c8
FB
818 } else {
819 st->cur_dts = pkt->dts;
820 }
821 /* this is tricky: the dts must be incremented by the duration
822 of the frame we are displaying, i.e. the last I or P frame */
823 if (st->last_IP_duration == 0)
824 st->cur_dts += pkt->duration;
825 else
826 st->cur_dts += st->last_IP_duration;
827 st->last_IP_duration = pkt->duration;
77405fc8 828 st->last_IP_pts= pkt->pts;
fb2758c8
FB
829 /* cannot compute PTS if not present (we can compute it only
830 by knowing the futur */
a603bf8d 831 } else if(pkt->pts != AV_NOPTS_VALUE || pkt->dts != AV_NOPTS_VALUE || pkt->duration){
90bb394d
MN
832 if(pkt->pts != AV_NOPTS_VALUE && pkt->duration){
833 int64_t old_diff= ABS(st->cur_dts - pkt->duration - pkt->pts);
834 int64_t new_diff= ABS(st->cur_dts - pkt->pts);
835 if(old_diff < new_diff && old_diff < (pkt->duration>>3)){
836 pkt->pts += pkt->duration;
3e76d1b5 837// av_log(NULL, AV_LOG_DEBUG, "id:%d old:%Ld new:%Ld dur:%d cur:%Ld size:%d\n", pkt->stream_index, old_diff, new_diff, pkt->duration, st->cur_dts, pkt->size);
90bb394d
MN
838 }
839 }
115329f1 840
fb2758c8
FB
841 /* presentation is not delayed : PTS and DTS are the same */
842 if (pkt->pts == AV_NOPTS_VALUE) {
2092bd75
GB
843 if (pkt->dts == AV_NOPTS_VALUE) {
844 pkt->pts = st->cur_dts;
845 pkt->dts = st->cur_dts;
846 }
847 else {
848 st->cur_dts = pkt->dts;
849 pkt->pts = pkt->dts;
850 }
fb2758c8
FB
851 } else {
852 st->cur_dts = pkt->pts;
853 pkt->dts = pkt->pts;
854 }
855 st->cur_dts += pkt->duration;
856 }
e928649b 857// av_log(NULL, AV_LOG_DEBUG, "OUTdelayed:%d pts:%lld, dts:%lld cur_dts:%lld\n", presentation_delayed, pkt->pts, pkt->dts, st->cur_dts);
115329f1 858
fb2758c8
FB
859 /* update flags */
860 if (pc) {
861 pkt->flags = 0;
862 /* key frame computation */
01f4895c 863 switch(st->codec->codec_type) {
fb2758c8
FB
864 case CODEC_TYPE_VIDEO:
865 if (pc->pict_type == FF_I_TYPE)
866 pkt->flags |= PKT_FLAG_KEY;
867 break;
868 case CODEC_TYPE_AUDIO:
869 pkt->flags |= PKT_FLAG_KEY;
870 break;
871 default:
872 break;
873 }
874 }
fb2758c8
FB
875}
876
63dd1377 877void av_destruct_packet_nofree(AVPacket *pkt)
fb2758c8
FB
878{
879 pkt->data = NULL; pkt->size = 0;
880}
881
882static int av_read_frame_internal(AVFormatContext *s, AVPacket *pkt)
883{
884 AVStream *st;
37353960 885 int len, ret, i;
fb2758c8
FB
886
887 for(;;) {
888 /* select current input stream component */
889 st = s->cur_st;
890 if (st) {
90ad92b3 891 if (!st->need_parsing || !st->parser) {
fb2758c8
FB
892 /* no parsing needed: we just output the packet as is */
893 /* raw data support */
894 *pkt = s->cur_pkt;
895 compute_pkt_fields(s, st, NULL, pkt);
896 s->cur_st = NULL;
434cab9e 897 break;
f3356e9c 898 } else if (s->cur_len > 0 && st->discard < AVDISCARD_ALL) {
115329f1 899 len = av_parser_parse(st->parser, st->codec, &pkt->data, &pkt->size,
6ec87caa
FB
900 s->cur_ptr, s->cur_len,
901 s->cur_pkt.pts, s->cur_pkt.dts);
902 s->cur_pkt.pts = AV_NOPTS_VALUE;
903 s->cur_pkt.dts = AV_NOPTS_VALUE;
fb2758c8
FB
904 /* increment read pointer */
905 s->cur_ptr += len;
906 s->cur_len -= len;
115329f1 907
fb2758c8
FB
908 /* return packet if any */
909 if (pkt->size) {
37353960 910 got_packet:
fb2758c8
FB
911 pkt->duration = 0;
912 pkt->stream_index = st->index;
6ec87caa
FB
913 pkt->pts = st->parser->pts;
914 pkt->dts = st->parser->dts;
fb2758c8
FB
915 pkt->destruct = av_destruct_packet_nofree;
916 compute_pkt_fields(s, st, st->parser, pkt);
434cab9e 917 break;
fb2758c8
FB
918 }
919 } else {
bcbecff1 920 /* free packet */
115329f1 921 av_free_packet(&s->cur_pkt);
fb2758c8
FB
922 s->cur_st = NULL;
923 }
924 } else {
fb2758c8
FB
925 /* read next packet */
926 ret = av_read_packet(s, &s->cur_pkt);
37353960
FB
927 if (ret < 0) {
928 if (ret == -EAGAIN)
929 return ret;
930 /* return the last frames, if any */
931 for(i = 0; i < s->nb_streams; i++) {
932 st = s->streams[i];
90ad92b3 933 if (st->parser && st->need_parsing) {
115329f1
DB
934 av_parser_parse(st->parser, st->codec,
935 &pkt->data, &pkt->size,
936 NULL, 0,
6ec87caa 937 AV_NOPTS_VALUE, AV_NOPTS_VALUE);
37353960
FB
938 if (pkt->size)
939 goto got_packet;
940 }
941 }
942 /* no more packets: really terminates parsing */
fb2758c8 943 return ret;
37353960 944 }
115329f1 945
9ee91c2f 946 st = s->streams[s->cur_pkt.stream_index];
434cab9e
MN
947 if(st->codec->debug & FF_DEBUG_PTS)
948 av_log(s, AV_LOG_DEBUG, "av_read_packet stream=%d, pts=%lld, dts=%lld, size=%d\n",
949 s->cur_pkt.stream_index,
950 s->cur_pkt.pts,
951 s->cur_pkt.dts,
952 s->cur_pkt.size);
fb2758c8 953
fb2758c8
FB
954 s->cur_st = st;
955 s->cur_ptr = s->cur_pkt.data;
956 s->cur_len = s->cur_pkt.size;
957 if (st->need_parsing && !st->parser) {
01f4895c 958 st->parser = av_parser_init(st->codec->codec_id);
fb2758c8
FB
959 if (!st->parser) {
960 /* no parser available : just output the raw packets */
961 st->need_parsing = 0;
7cbaa7ba
MN
962 }else if(st->need_parsing == 2){
963 st->parser->flags |= PARSER_FLAG_COMPLETE_FRAMES;
fb2758c8
FB
964 }
965 }
966 }
967 }
434cab9e
MN
968 if(st->codec->debug & FF_DEBUG_PTS)
969 av_log(s, AV_LOG_DEBUG, "av_read_frame_internal stream=%d, pts=%lld, dts=%lld, size=%d\n",
970 pkt->stream_index,
971 pkt->pts,
972 pkt->dts,
973 pkt->size);
974
975 return 0;
fb2758c8
FB
976}
977
978/**
e36bdf8b
DK
979 * Return the next frame of a stream.
980 *
981 * The returned packet is valid
fb2758c8
FB
982 * until the next av_read_frame() or until av_close_input_file() and
983 * must be freed with av_free_packet. For video, the packet contains
984 * exactly one frame. For audio, it contains an integer number of
985 * frames if each frame has a known fixed size (e.g. PCM or ADPCM
986 * data). If the audio frames have a variable size (e.g. MPEG audio),
987 * then it contains one frame.
115329f1 988 *
fb2758c8
FB
989 * pkt->pts, pkt->dts and pkt->duration are always set to correct
990 * values in AV_TIME_BASE unit (and guessed if the format cannot
991 * provided them). pkt->pts can be AV_NOPTS_VALUE if the video format
992 * has B frames, so it is better to rely on pkt->dts if you do not
993 * decompress the payload.
115329f1 994 *
e36bdf8b 995 * @return 0 if OK, < 0 if error or end of file.
fb2758c8
FB
996 */
997int av_read_frame(AVFormatContext *s, AVPacket *pkt)
998{
de6d9b64 999 AVPacketList *pktl;
30bc6613
MN
1000 int eof=0;
1001 const int genpts= s->flags & AVFMT_FLAG_GENPTS;
1002
1003 for(;;){
1004 pktl = s->packet_buffer;
1005 if (pktl) {
1006 AVPacket *next_pkt= &pktl->pkt;
30bc6613
MN
1007
1008 if(genpts && next_pkt->dts != AV_NOPTS_VALUE){
1009 while(pktl && next_pkt->pts == AV_NOPTS_VALUE){
115329f1 1010 if( pktl->pkt.stream_index == next_pkt->stream_index
30bc6613
MN
1011 && next_pkt->dts < pktl->pkt.dts
1012 && pktl->pkt.pts != pktl->pkt.dts //not b frame
1013 /*&& pktl->pkt.dts != AV_NOPTS_VALUE*/){
1014 next_pkt->pts= pktl->pkt.dts;
1015 }
1016 pktl= pktl->next;
1017 }
1018 pktl = s->packet_buffer;
1019 }
115329f1
DB
1020
1021 if( next_pkt->pts != AV_NOPTS_VALUE
1022 || next_pkt->dts == AV_NOPTS_VALUE
30bc6613
MN
1023 || !genpts || eof){
1024 /* read packet from packet buffer, if there is data */
1025 *pkt = *next_pkt;
1026 s->packet_buffer = pktl->next;
1027 av_free(pktl);
1028 return 0;
1029 }
1030 }
1031 if(genpts){
1032 AVPacketList **plast_pktl= &s->packet_buffer;
1033 int ret= av_read_frame_internal(s, pkt);
1034 if(ret<0){
1035 if(pktl && ret != -EAGAIN){
1036 eof=1;
1037 continue;
1038 }else
1039 return ret;
1040 }
115329f1 1041
30bc6613
MN
1042 /* duplicate the packet */
1043 if (av_dup_packet(pkt) < 0)
1044 return AVERROR_NOMEM;
de6d9b64 1045
30bc6613 1046 while(*plast_pktl) plast_pktl= &(*plast_pktl)->next; //FIXME maybe maintain pointer to the last?
115329f1 1047
30bc6613
MN
1048 pktl = av_mallocz(sizeof(AVPacketList));
1049 if (!pktl)
1050 return AVERROR_NOMEM;
115329f1 1051
30bc6613
MN
1052 /* add the packet in the buffered packet list */
1053 *plast_pktl = pktl;
115329f1 1054 pktl->pkt= *pkt;
30bc6613
MN
1055 }else{
1056 assert(!s->packet_buffer);
1057 return av_read_frame_internal(s, pkt);
1058 }
fb2758c8
FB
1059 }
1060}
1061
1062/* XXX: suppress the packet queue */
1063static void flush_packet_queue(AVFormatContext *s)
1064{
1065 AVPacketList *pktl;
1066
1067 for(;;) {
1068 pktl = s->packet_buffer;
115329f1 1069 if (!pktl)
fb2758c8
FB
1070 break;
1071 s->packet_buffer = pktl->next;
1072 av_free_packet(&pktl->pkt);
1073 av_free(pktl);
b9a281db
FB
1074 }
1075}
1076
da24c5e3 1077/*******************************************************/
fb2758c8
FB
1078/* seek support */
1079
b754978a
MN
1080int av_find_default_stream_index(AVFormatContext *s)
1081{
1082 int i;
1083 AVStream *st;
1084
1085 if (s->nb_streams <= 0)
1086 return -1;
1087 for(i = 0; i < s->nb_streams; i++) {
1088 st = s->streams[i];
01f4895c 1089 if (st->codec->codec_type == CODEC_TYPE_VIDEO) {
b754978a
MN
1090 return i;
1091 }
1092 }
1093 return 0;
1094}
1095
e36bdf8b
DK
1096/**
1097 * Flush the frame reader.
1098 */
fb2758c8
FB
1099static void av_read_frame_flush(AVFormatContext *s)
1100{
1101 AVStream *st;
1102 int i;
1103
1104 flush_packet_queue(s);
1105
1106 /* free previous packet */
1107 if (s->cur_st) {
1108 if (s->cur_st->parser)
1109 av_free_packet(&s->cur_pkt);
1110 s->cur_st = NULL;
1111 }
1112 /* fail safe */
1113 s->cur_ptr = NULL;
1114 s->cur_len = 0;
115329f1 1115
fb2758c8
FB
1116 /* for each stream, reset read state */
1117 for(i = 0; i < s->nb_streams; i++) {
1118 st = s->streams[i];
115329f1 1119
fb2758c8
FB
1120 if (st->parser) {
1121 av_parser_close(st->parser);
1122 st->parser = NULL;
1123 }
77405fc8 1124 st->last_IP_pts = AV_NOPTS_VALUE;
fb2758c8
FB
1125 st->cur_dts = 0; /* we set the current DTS to an unspecified origin */
1126 }
1127}
1128
cdd5034f 1129/**
e36bdf8b
DK
1130 * Updates cur_dts of all streams based on given timestamp and AVStream.
1131 *
1132 * Stream ref_st unchanged, others set cur_dts in their native timebase
1a1dc611
NK
1133 * only needed for timestamp wrapping or if (dts not set and pts!=dts)
1134 * @param timestamp new dts expressed in time_base of param ref_st
1135 * @param ref_st reference stream giving time_base of param timestamp
8bcb147f 1136 */
22ffac70 1137void av_update_cur_dts(AVFormatContext *s, AVStream *ref_st, int64_t timestamp){
8bcb147f
MN
1138 int i;
1139
1140 for(i = 0; i < s->nb_streams; i++) {
1a1dc611 1141 AVStream *st = s->streams[i];
8bcb147f 1142
115329f1 1143 st->cur_dts = av_rescale(timestamp,
1a1dc611
NK
1144 st->time_base.den * (int64_t)ref_st->time_base.num,
1145 st->time_base.num * (int64_t)ref_st->time_base.den);
8bcb147f
MN
1146 }
1147}
1148
1149/**
e36bdf8b
DK
1150 * Add a index entry into a sorted list updateing if it is already there.
1151 *
cdd5034f
MN
1152 * @param timestamp timestamp in the timebase of the given stream
1153 */
3e9245a9 1154int av_add_index_entry(AVStream *st,
30a43f2d 1155 int64_t pos, int64_t timestamp, int size, int distance, int flags)
fb2758c8
FB
1156{
1157 AVIndexEntry *entries, *ie;
b754978a 1158 int index;
115329f1 1159
568e18b1
MN
1160 if((unsigned)st->nb_index_entries + 1 >= UINT_MAX / sizeof(AVIndexEntry))
1161 return -1;
115329f1 1162
fb2758c8
FB
1163 entries = av_fast_realloc(st->index_entries,
1164 &st->index_entries_allocated_size,
115329f1 1165 (st->nb_index_entries + 1) *
fb2758c8 1166 sizeof(AVIndexEntry));
568e18b1
MN
1167 if(!entries)
1168 return -1;
1169
b754978a
MN
1170 st->index_entries= entries;
1171
27a5fe5f 1172 index= av_index_search_timestamp(st, timestamp, AVSEEK_FLAG_ANY);
b754978a 1173
3ba1438d 1174 if(index<0){
3e9245a9
MN
1175 index= st->nb_index_entries++;
1176 ie= &entries[index];
3ba1438d
MN
1177 assert(index==0 || ie[-1].timestamp < timestamp);
1178 }else{
1179 ie= &entries[index];
1180 if(ie->timestamp != timestamp){
528c2c73
MN
1181 if(ie->timestamp <= timestamp)
1182 return -1;
3ba1438d
MN
1183 memmove(entries + index + 1, entries + index, sizeof(AVIndexEntry)*(st->nb_index_entries - index));
1184 st->nb_index_entries++;
1185 }else if(ie->pos == pos && distance < ie->min_distance) //dont reduce the distance
1186 distance= ie->min_distance;
3e9245a9 1187 }
3ba1438d 1188
b754978a
MN
1189 ie->pos = pos;
1190 ie->timestamp = timestamp;
3e9245a9 1191 ie->min_distance= distance;
30a43f2d 1192 ie->size= size;
b754978a 1193 ie->flags = flags;
115329f1 1194
3e9245a9 1195 return index;
fb2758c8
FB
1196}
1197
e36bdf8b
DK
1198/**
1199 * build an index for raw streams using a parser.
1200 */
fb2758c8
FB
1201static void av_build_index_raw(AVFormatContext *s)
1202{
1203 AVPacket pkt1, *pkt = &pkt1;
1204 int ret;
1205 AVStream *st;
1206
1207 st = s->streams[0];
1208 av_read_frame_flush(s);
1209 url_fseek(&s->pb, s->data_offset, SEEK_SET);
1210
1211 for(;;) {
1212 ret = av_read_frame(s, pkt);
1213 if (ret < 0)
1214 break;
1215 if (pkt->stream_index == 0 && st->parser &&
1216 (pkt->flags & PKT_FLAG_KEY)) {
115329f1 1217 av_add_index_entry(st, st->parser->frame_offset, pkt->dts,
30a43f2d 1218 0, 0, AVINDEX_KEYFRAME);
fb2758c8
FB
1219 }
1220 av_free_packet(pkt);
1221 }
1222}
1223
e36bdf8b
DK
1224/**
1225 * Returns TRUE if we deal with a raw stream.
1226 *
1227 * Raw codec data and parsing needed.
1228 */
fb2758c8
FB
1229static int is_raw_stream(AVFormatContext *s)
1230{
1231 AVStream *st;
1232
1233 if (s->nb_streams != 1)
1234 return 0;
1235 st = s->streams[0];
1236 if (!st->need_parsing)
1237 return 0;
1238 return 1;
1239}
1240
3ba1438d 1241/**
e36bdf8b 1242 * Gets the index for a specific timestamp.
115329f1
DB
1243 * @param flags if AVSEEK_FLAG_BACKWARD then the returned index will correspond to
1244 * the timestamp which is <= the requested one, if backward is 0
3ba1438d 1245 * then it will be >=
27a5fe5f 1246 * if AVSEEK_FLAG_ANY seek to any frame, only keyframes otherwise
3ba1438d
MN
1247 * @return < 0 if no such timestamp could be found
1248 */
dc56fc38 1249int av_index_search_timestamp(AVStream *st, int64_t wanted_timestamp,
27a5fe5f 1250 int flags)
fb2758c8 1251{
b754978a
MN
1252 AVIndexEntry *entries= st->index_entries;
1253 int nb_entries= st->nb_index_entries;
fb2758c8
FB
1254 int a, b, m;
1255 int64_t timestamp;
1256
3ba1438d
MN
1257 a = - 1;
1258 b = nb_entries;
b754978a 1259
3ba1438d
MN
1260 while (b - a > 1) {
1261 m = (a + b) >> 1;
fb2758c8 1262 timestamp = entries[m].timestamp;
3ba1438d
MN
1263 if(timestamp >= wanted_timestamp)
1264 b = m;
1265 if(timestamp <= wanted_timestamp)
b754978a 1266 a = m;
fb2758c8 1267 }
27a5fe5f 1268 m= (flags & AVSEEK_FLAG_BACKWARD) ? a : b;
115329f1 1269
27a5fe5f
MN
1270 if(!(flags & AVSEEK_FLAG_ANY)){
1271 while(m>=0 && m<nb_entries && !(entries[m].flags & AVINDEX_KEYFRAME)){
1272 m += (flags & AVSEEK_FLAG_BACKWARD) ? -1 : 1;
1273 }
1274 }
3ba1438d 1275
115329f1 1276 if(m == nb_entries)
3ba1438d
MN
1277 return -1;
1278 return m;
fb2758c8
FB
1279}
1280
8d14a25c
MN
1281#define DEBUG_SEEK
1282
cdd5034f
MN
1283/**
1284 * Does a binary search using av_index_search_timestamp() and AVCodec.read_timestamp().
1285 * this isnt supposed to be called directly by a user application, but by demuxers
1286 * @param target_ts target timestamp in the time base of the given stream
1287 * @param stream_index stream number
1288 */
3ba1438d 1289int av_seek_frame_binary(AVFormatContext *s, int stream_index, int64_t target_ts, int flags){
8d14a25c
MN
1290 AVInputFormat *avif= s->iformat;
1291 int64_t pos_min, pos_max, pos, pos_limit;
1292 int64_t ts_min, ts_max, ts;
6fd93ce2 1293 int64_t start_pos, filesize;
8bcb147f 1294 int index, no_change;
8d14a25c
MN
1295 AVStream *st;
1296
cdd5034f
MN
1297 if (stream_index < 0)
1298 return -1;
115329f1 1299
8d14a25c 1300#ifdef DEBUG_SEEK
4733abcb 1301 av_log(s, AV_LOG_DEBUG, "read_seek: %d %"PRId64"\n", stream_index, target_ts);
8d14a25c
MN
1302#endif
1303
1304 ts_max=
1305 ts_min= AV_NOPTS_VALUE;
1306 pos_limit= -1; //gcc falsely says it may be uninitalized
1307
1308 st= s->streams[stream_index];
1309 if(st->index_entries){
1310 AVIndexEntry *e;
1311
27a5fe5f 1312 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()
3ba1438d 1313 index= FFMAX(index, 0);
8d14a25c
MN
1314 e= &st->index_entries[index];
1315
1316 if(e->timestamp <= target_ts || e->pos == e->min_distance){
1317 pos_min= e->pos;
1318 ts_min= e->timestamp;
1319#ifdef DEBUG_SEEK
115329f1 1320 av_log(s, AV_LOG_DEBUG, "using cached pos_min=0x%"PRIx64" dts_min=%"PRId64"\n",
8d14a25c
MN
1321 pos_min,ts_min);
1322#endif
1323 }else{
1324 assert(index==0);
1325 }
115329f1
DB
1326
1327 index= av_index_search_timestamp(st, target_ts, flags & ~AVSEEK_FLAG_BACKWARD);
27a5fe5f
MN
1328 assert(index < st->nb_index_entries);
1329 if(index >= 0){
8d14a25c
MN
1330 e= &st->index_entries[index];
1331 assert(e->timestamp >= target_ts);
1332 pos_max= e->pos;
1333 ts_max= e->timestamp;
1334 pos_limit= pos_max - e->min_distance;
1335#ifdef DEBUG_SEEK
115329f1 1336 av_log(s, AV_LOG_DEBUG, "using cached pos_max=0x%"PRIx64" pos_limit=0x%"PRIx64" dts_max=%"PRId64"\n",
8d14a25c
MN
1337 pos_max,pos_limit, ts_max);
1338#endif
1339 }
1340 }
1341
1342 if(ts_min == AV_NOPTS_VALUE){
1343 pos_min = s->data_offset;
1344 ts_min = avif->read_timestamp(s, stream_index, &pos_min, INT64_MAX);
1345 if (ts_min == AV_NOPTS_VALUE)
1346 return -1;
1347 }
1348
1349 if(ts_max == AV_NOPTS_VALUE){
1350 int step= 1024;
6fd93ce2
KA
1351 filesize = url_fsize(&s->pb);
1352 pos_max = filesize - 1;
8d14a25c
MN
1353 do{
1354 pos_max -= step;
1355 ts_max = avif->read_timestamp(s, stream_index, &pos_max, pos_max + step);
1356 step += step;
1357 }while(ts_max == AV_NOPTS_VALUE && pos_max >= step);
1358 if (ts_max == AV_NOPTS_VALUE)
1359 return -1;
115329f1 1360
8d14a25c
MN
1361 for(;;){
1362 int64_t tmp_pos= pos_max + 1;
1363 int64_t tmp_ts= avif->read_timestamp(s, stream_index, &tmp_pos, INT64_MAX);
1364 if(tmp_ts == AV_NOPTS_VALUE)
1365 break;
1366 ts_max= tmp_ts;
1367 pos_max= tmp_pos;
6fd93ce2
KA
1368 if(tmp_pos >= filesize)
1369 break;
8d14a25c
MN
1370 }
1371 pos_limit= pos_max;
1372 }
1373
53f7c43f
MN
1374 if(ts_min > ts_max){
1375 return -1;
1376 }else if(ts_min == ts_max){
1377 pos_limit= pos_min;
1378 }
1379
8d14a25c
MN
1380 no_change=0;
1381 while (pos_min < pos_limit) {
1382#ifdef DEBUG_SEEK
115329f1 1383 av_log(s, AV_LOG_DEBUG, "pos_min=0x%"PRIx64" pos_max=0x%"PRIx64" dts_min=%"PRId64" dts_max=%"PRId64"\n",
8d14a25c
MN
1384 pos_min, pos_max,
1385 ts_min, ts_max);
1386#endif
1387 assert(pos_limit <= pos_max);
1388
1389 if(no_change==0){
1390 int64_t approximate_keyframe_distance= pos_max - pos_limit;
1391 // interpolate position (better than dichotomy)
3ba1438d
MN
1392 pos = av_rescale(target_ts - ts_min, pos_max - pos_min, ts_max - ts_min)
1393 + pos_min - approximate_keyframe_distance;
8d14a25c
MN
1394 }else if(no_change==1){
1395 // bisection, if interpolation failed to change min or max pos last time
1396 pos = (pos_min + pos_limit)>>1;
1397 }else{
1398 // linear search if bisection failed, can only happen if there are very few or no keframes between min/max
1399 pos=pos_min;
1400 }
1401 if(pos <= pos_min)
1402 pos= pos_min + 1;
1403 else if(pos > pos_limit)
1404 pos= pos_limit;
1405 start_pos= pos;
1406
1407 ts = avif->read_timestamp(s, stream_index, &pos, INT64_MAX); //may pass pos_limit instead of -1
1408 if(pos == pos_max)
1409 no_change++;
1410 else
1411 no_change=0;
1412#ifdef DEBUG_SEEK
4733abcb 1413av_log(s, AV_LOG_DEBUG, "%"PRId64" %"PRId64" %"PRId64" / %"PRId64" %"PRId64" %"PRId64" target:%"PRId64" limit:%"PRId64" start:%"PRId64" noc:%d\n", pos_min, pos, pos_max, ts_min, ts, ts_max, target_ts, pos_limit, start_pos, no_change);
8d14a25c
MN
1414#endif
1415 assert(ts != AV_NOPTS_VALUE);
3ba1438d 1416 if (target_ts <= ts) {
8d14a25c
MN
1417 pos_limit = start_pos - 1;
1418 pos_max = pos;
1419 ts_max = ts;
3ba1438d
MN
1420 }
1421 if (target_ts >= ts) {
8d14a25c
MN
1422 pos_min = pos;
1423 ts_min = ts;
8d14a25c
MN
1424 }
1425 }
115329f1 1426
3ba1438d
MN
1427 pos = (flags & AVSEEK_FLAG_BACKWARD) ? pos_min : pos_max;
1428 ts = (flags & AVSEEK_FLAG_BACKWARD) ? ts_min : ts_max;
8d14a25c
MN
1429#ifdef DEBUG_SEEK
1430 pos_min = pos;
1431 ts_min = avif->read_timestamp(s, stream_index, &pos_min, INT64_MAX);
1432 pos_min++;
1433 ts_max = avif->read_timestamp(s, stream_index, &pos_min, INT64_MAX);
115329f1 1434 av_log(s, AV_LOG_DEBUG, "pos=0x%"PRIx64" %"PRId64"<=%"PRId64"<=%"PRId64"\n",
8d14a25c
MN
1435 pos, ts_min, target_ts, ts_max);
1436#endif
1437 /* do the seek */
1438 url_fseek(&s->pb, pos, SEEK_SET);
cdd5034f 1439
8bcb147f 1440 av_update_cur_dts(s, st, ts);
8d14a25c
MN
1441
1442 return 0;
1443}
1444
3ba1438d 1445static int av_seek_frame_byte(AVFormatContext *s, int stream_index, int64_t pos, int flags){
3ba1438d
MN
1446 int64_t pos_min, pos_max;
1447#if 0
1448 AVStream *st;
1449
1450 if (stream_index < 0)
1451 return -1;
1452
1453 st= s->streams[stream_index];
1454#endif
1455
1456 pos_min = s->data_offset;
a965c478 1457 pos_max = url_fsize(&s->pb) - 1;
3ba1438d
MN
1458
1459 if (pos < pos_min) pos= pos_min;
1460 else if(pos > pos_max) pos= pos_max;
1461
1462 url_fseek(&s->pb, pos, SEEK_SET);
1463
1464#if 0
8bcb147f 1465 av_update_cur_dts(s, st, ts);
3ba1438d
MN
1466#endif
1467 return 0;
1468}
1469
115329f1 1470static int av_seek_frame_generic(AVFormatContext *s,
3ba1438d 1471 int stream_index, int64_t timestamp, int flags)
fb2758c8 1472{
8bcb147f 1473 int index;
fb2758c8
FB
1474 AVStream *st;
1475 AVIndexEntry *ie;
1476
1477 if (!s->index_built) {
1478 if (is_raw_stream(s)) {
1479 av_build_index_raw(s);
1480 } else {
1481 return -1;
1482 }
1483 s->index_built = 1;
1484 }
1485
fb2758c8 1486 st = s->streams[stream_index];
27a5fe5f 1487 index = av_index_search_timestamp(st, timestamp, flags);
fb2758c8
FB
1488 if (index < 0)
1489 return -1;
1490
1491 /* now we have found the index, we can seek */
1492 ie = &st->index_entries[index];
1493 av_read_frame_flush(s);
1494 url_fseek(&s->pb, ie->pos, SEEK_SET);
3ba1438d 1495
8bcb147f 1496 av_update_cur_dts(s, st, ie->timestamp);
cdd5034f 1497
fb2758c8
FB
1498 return 0;
1499}
1500
1501/**
3ba1438d 1502 * Seek to the key frame at timestamp.
cdd5034f
MN
1503 * 'timestamp' in 'stream_index'.
1504 * @param stream_index If stream_index is (-1), a default
115329f1 1505 * stream is selected, and timestamp is automatically converted
eb497825 1506 * from AV_TIME_BASE units to the stream specific time_base.
3ba1438d 1507 * @param timestamp timestamp in AVStream.time_base units
9c98cdbc 1508 * or if there is no stream specified then in AV_TIME_BASE units
3ba1438d 1509 * @param flags flags which select direction and seeking mode
cdd5034f 1510 * @return >= 0 on success
fb2758c8 1511 */
3ba1438d 1512int av_seek_frame(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
fb2758c8
FB
1513{
1514 int ret;
cdd5034f 1515 AVStream *st;
115329f1 1516
fb2758c8 1517 av_read_frame_flush(s);
115329f1 1518
3ba1438d
MN
1519 if(flags & AVSEEK_FLAG_BYTE)
1520 return av_seek_frame_byte(s, stream_index, timestamp, flags);
115329f1 1521
cdd5034f
MN
1522 if(stream_index < 0){
1523 stream_index= av_find_default_stream_index(s);
1524 if(stream_index < 0)
1525 return -1;
115329f1 1526
3ba1438d 1527 st= s->streams[stream_index];
eb497825 1528 /* timestamp for default must be expressed in AV_TIME_BASE units */
3ba1438d 1529 timestamp = av_rescale(timestamp, st->time_base.den, AV_TIME_BASE * (int64_t)st->time_base.num);
cdd5034f
MN
1530 }
1531 st= s->streams[stream_index];
1532
fb2758c8
FB
1533 /* first, we try the format specific seek */
1534 if (s->iformat->read_seek)
3ba1438d 1535 ret = s->iformat->read_seek(s, stream_index, timestamp, flags);
fb2758c8
FB
1536 else
1537 ret = -1;
1538 if (ret >= 0) {
1539 return 0;
1540 }
8d14a25c
MN
1541
1542 if(s->iformat->read_timestamp)
3ba1438d 1543 return av_seek_frame_binary(s, stream_index, timestamp, flags);
8d14a25c 1544 else
3ba1438d 1545 return av_seek_frame_generic(s, stream_index, timestamp, flags);
fb2758c8
FB
1546}
1547
1548/*******************************************************/
12f996ed 1549
e36bdf8b
DK
1550/**
1551 * Returns TRUE if the stream has accurate timings in any stream.
1552 *
1553 * @return TRUE if the stream has accurate timings for at least one component.
1554 */
12f996ed
FB
1555static int av_has_timings(AVFormatContext *ic)
1556{
1557 int i;
1558 AVStream *st;
1559
1560 for(i = 0;i < ic->nb_streams; i++) {
1561 st = ic->streams[i];
1562 if (st->start_time != AV_NOPTS_VALUE &&
1563 st->duration != AV_NOPTS_VALUE)
1564 return 1;
1565 }
1566 return 0;
1567}
1568
e36bdf8b
DK
1569/**
1570 * Estimate the stream timings from the one of each components.
1571 *
1572 * Also computes the global bitrate if possible.
1573 */
12f996ed
FB
1574static void av_update_stream_timings(AVFormatContext *ic)
1575{
c0df9d75 1576 int64_t start_time, start_time1, end_time, end_time1;
12f996ed
FB
1577 int i;
1578 AVStream *st;
1579
1580 start_time = MAXINT64;
1581 end_time = MININT64;
1582 for(i = 0;i < ic->nb_streams; i++) {
1583 st = ic->streams[i];
1584 if (st->start_time != AV_NOPTS_VALUE) {
c0df9d75
MN
1585 start_time1= av_rescale_q(st->start_time, st->time_base, AV_TIME_BASE_Q);
1586 if (start_time1 < start_time)
1587 start_time = start_time1;
12f996ed 1588 if (st->duration != AV_NOPTS_VALUE) {
c0df9d75
MN
1589 end_time1 = start_time1
1590 + av_rescale_q(st->duration, st->time_base, AV_TIME_BASE_Q);
12f996ed
FB
1591 if (end_time1 > end_time)
1592 end_time = end_time1;
1593 }
1594 }
1595 }
1596 if (start_time != MAXINT64) {
1597 ic->start_time = start_time;
69d93a13 1598 if (end_time != MININT64) {
12f996ed
FB
1599 ic->duration = end_time - start_time;
1600 if (ic->file_size > 0) {
1601 /* compute the bit rate */
115329f1 1602 ic->bit_rate = (double)ic->file_size * 8.0 * AV_TIME_BASE /
12f996ed
FB
1603 (double)ic->duration;
1604 }
1605 }
1606 }
1607
1608}
1609
1610static void fill_all_stream_timings(AVFormatContext *ic)
1611{
1612 int i;
1613 AVStream *st;
1614
1615 av_update_stream_timings(ic);
1616 for(i = 0;i < ic->nb_streams; i++) {
1617 st = ic->streams[i];
1618 if (st->start_time == AV_NOPTS_VALUE) {
c0df9d75
MN
1619 if(ic->start_time != AV_NOPTS_VALUE)
1620 st->start_time = av_rescale_q(ic->start_time, AV_TIME_BASE_Q, st->time_base);
1621 if(ic->duration != AV_NOPTS_VALUE)
1622 st->duration = av_rescale_q(ic->duration, AV_TIME_BASE_Q, st->time_base);
12f996ed
FB
1623 }
1624 }
1625}
1626
1627static void av_estimate_timings_from_bit_rate(AVFormatContext *ic)
1628{
1629 int64_t filesize, duration;
1630 int bit_rate, i;
1631 AVStream *st;
1632
1633 /* if bit_rate is already set, we believe it */
1634 if (ic->bit_rate == 0) {
1635 bit_rate = 0;
1636 for(i=0;i<ic->nb_streams;i++) {
1637 st = ic->streams[i];
01f4895c 1638 bit_rate += st->codec->bit_rate;
12f996ed
FB
1639 }
1640 ic->bit_rate = bit_rate;
1641 }
1642
1643 /* if duration is already set, we believe it */
115329f1
DB
1644 if (ic->duration == AV_NOPTS_VALUE &&
1645 ic->bit_rate != 0 &&
12f996ed
FB
1646 ic->file_size != 0) {
1647 filesize = ic->file_size;
1648 if (filesize > 0) {
12f996ed
FB
1649 for(i = 0; i < ic->nb_streams; i++) {
1650 st = ic->streams[i];
c0df9d75 1651 duration= av_rescale(8*filesize, st->time_base.den, ic->bit_rate*(int64_t)st->time_base.num);
12f996ed
FB
1652 if (st->start_time == AV_NOPTS_VALUE ||
1653 st->duration == AV_NOPTS_VALUE) {
1654 st->start_time = 0;
1655 st->duration = duration;
1656 }
1657 }
1658 }
1659 }
1660}
1661
12f996ed
FB
1662#define DURATION_MAX_READ_SIZE 250000
1663
1664/* only usable for MPEG-PS streams */
1665static void av_estimate_timings_from_pts(AVFormatContext *ic)
1666{
1667 AVPacket pkt1, *pkt = &pkt1;
1668 AVStream *st;
1669 int read_size, i, ret;
bf4e3bd2 1670 int64_t end_time;
12f996ed 1671 int64_t filesize, offset, duration;
115329f1 1672
fb2758c8
FB
1673 /* free previous packet */
1674 if (ic->cur_st && ic->cur_st->parser)
115329f1 1675 av_free_packet(&ic->cur_pkt);
fb2758c8
FB
1676 ic->cur_st = NULL;
1677
1678 /* flush packet queue */
1679 flush_packet_queue(ic);
fb2758c8 1680
0ff7199f
MN
1681 for(i=0;i<ic->nb_streams;i++) {
1682 st = ic->streams[i];
1683 if (st->parser) {
1684 av_parser_close(st->parser);
1685 st->parser= NULL;
1686 }
1687 }
115329f1 1688
12f996ed
FB
1689 /* we read the first packets to get the first PTS (not fully
1690 accurate, but it is enough now) */
1691 url_fseek(&ic->pb, 0, SEEK_SET);
1692 read_size = 0;
1693 for(;;) {
1694 if (read_size >= DURATION_MAX_READ_SIZE)
1695 break;
1696 /* if all info is available, we can stop */
1697 for(i = 0;i < ic->nb_streams; i++) {
1698 st = ic->streams[i];
1699 if (st->start_time == AV_NOPTS_VALUE)
1700 break;
1701 }
1702 if (i == ic->nb_streams)
1703 break;
1704
1705 ret = av_read_packet(ic, pkt);
1706 if (ret != 0)
1707 break;
1708 read_size += pkt->size;
1709 st = ic->streams[pkt->stream_index];
1710 if (pkt->pts != AV_NOPTS_VALUE) {
1711 if (st->start_time == AV_NOPTS_VALUE)
c0df9d75 1712 st->start_time = pkt->pts;
0a5f92a1
MN
1713 }
1714 av_free_packet(pkt);
1715 }
12f996ed 1716
12f996ed
FB
1717 /* estimate the end time (duration) */
1718 /* XXX: may need to support wrapping */
1719 filesize = ic->file_size;
1720 offset = filesize - DURATION_MAX_READ_SIZE;
1721 if (offset < 0)
1722 offset = 0;
1723
12f996ed
FB
1724 url_fseek(&ic->pb, offset, SEEK_SET);
1725 read_size = 0;
1726 for(;;) {
1727 if (read_size >= DURATION_MAX_READ_SIZE)
1728 break;
1729 /* if all info is available, we can stop */
1730 for(i = 0;i < ic->nb_streams; i++) {
1731 st = ic->streams[i];
1732 if (st->duration == AV_NOPTS_VALUE)
1733 break;
1734 }
1735 if (i == ic->nb_streams)
1736 break;
115329f1 1737
12f996ed
FB
1738 ret = av_read_packet(ic, pkt);
1739 if (ret != 0)
1740 break;
1741 read_size += pkt->size;
1742 st = ic->streams[pkt->stream_index];
1743 if (pkt->pts != AV_NOPTS_VALUE) {
c0df9d75 1744 end_time = pkt->pts;
12f996ed
FB
1745 duration = end_time - st->start_time;
1746 if (duration > 0) {
1747 if (st->duration == AV_NOPTS_VALUE ||
1748 st->duration < duration)
1749 st->duration = duration;
1750 }
1751 }
1752 av_free_packet(pkt);
1753 }
115329f1 1754
c0df9d75 1755 fill_all_stream_timings(ic);
12f996ed
FB
1756
1757 url_fseek(&ic->pb, 0, SEEK_SET);
1758}
1759
1760static void av_estimate_timings(AVFormatContext *ic)
1761{
12f996ed
FB
1762 int64_t file_size;
1763
1764 /* get the file size, if possible */
1765 if (ic->iformat->flags & AVFMT_NOFILE) {
1766 file_size = 0;
1767 } else {
a965c478 1768 file_size = url_fsize(&ic->pb);
12f996ed
FB
1769 if (file_size < 0)
1770 file_size = 0;
1771 }
1772 ic->file_size = file_size;
1773
ff70e601
MR
1774 if ((!strcmp(ic->iformat->name, "mpeg") ||
1775 !strcmp(ic->iformat->name, "mpegts")) &&
1776 file_size && !ic->pb.is_streamed) {
12f996ed
FB
1777 /* get accurate estimate from the PTSes */
1778 av_estimate_timings_from_pts(ic);
1779 } else if (av_has_timings(ic)) {
1780 /* at least one components has timings - we use them for all
1781 the components */
1782 fill_all_stream_timings(ic);
1783 } else {
1784 /* less precise: use bit rate info */
1785 av_estimate_timings_from_bit_rate(ic);
1786 }
1787 av_update_stream_timings(ic);
1788
1789#if 0
1790 {
1791 int i;
1792 AVStream *st;
1793 for(i = 0;i < ic->nb_streams; i++) {
1794 st = ic->streams[i];
115329f1
DB
1795 printf("%d: start_time: %0.3f duration: %0.3f\n",
1796 i, (double)st->start_time / AV_TIME_BASE,
12f996ed
FB
1797 (double)st->duration / AV_TIME_BASE);
1798 }
115329f1
DB
1799 printf("stream: start_time: %0.3f duration: %0.3f bitrate=%d kb/s\n",
1800 (double)ic->start_time / AV_TIME_BASE,
12f996ed
FB
1801 (double)ic->duration / AV_TIME_BASE,
1802 ic->bit_rate / 1000);
1803 }
1804#endif
1805}
1806
b9a281db
FB
1807static int has_codec_parameters(AVCodecContext *enc)
1808{
1809 int val;
1810 switch(enc->codec_type) {
1811 case CODEC_TYPE_AUDIO:
1812 val = enc->sample_rate;
1813 break;
1814 case CODEC_TYPE_VIDEO:
644a9262 1815 val = enc->width && enc->pix_fmt != PIX_FMT_NONE;
b9a281db
FB
1816 break;
1817 default:
1818 val = 1;
1819 break;
1820 }
1821 return (val != 0);
1822}
1823
fb2758c8
FB
1824static int try_decode_frame(AVStream *st, const uint8_t *data, int size)
1825{
1826 int16_t *samples;
1827 AVCodec *codec;
43c0040a 1828 int got_picture, ret=0;
fb2758c8 1829 AVFrame picture;
115329f1 1830
01f4895c
MN
1831 if(!st->codec->codec){
1832 codec = avcodec_find_decoder(st->codec->codec_id);
fb2758c8
FB
1833 if (!codec)
1834 return -1;
01f4895c 1835 ret = avcodec_open(st->codec, codec);
fb2758c8
FB
1836 if (ret < 0)
1837 return ret;
43c0040a 1838 }
644a9262 1839
01f4895c
MN
1840 if(!has_codec_parameters(st->codec)){
1841 switch(st->codec->codec_type) {
fb2758c8 1842 case CODEC_TYPE_VIDEO:
115329f1 1843 ret = avcodec_decode_video(st->codec, &picture,
fb2758c8
FB
1844 &got_picture, (uint8_t *)data, size);
1845 break;
1846 case CODEC_TYPE_AUDIO:
1847 samples = av_malloc(AVCODEC_MAX_AUDIO_FRAME_SIZE);
1848 if (!samples)
1849 goto fail;
115329f1 1850 ret = avcodec_decode_audio(st->codec, samples,
fb2758c8
FB
1851 &got_picture, (uint8_t *)data, size);
1852 av_free(samples);
1853 break;
1854 default:
1855 break;
1856 }
644a9262 1857 }
fb2758c8 1858 fail:
fb2758c8
FB
1859 return ret;
1860}
1861
1862/* absolute maximum size we read until we abort */
1863#define MAX_READ_SIZE 5000000
1864
1865/* maximum duration until we stop analysing the stream */
c10824ea 1866#define MAX_STREAM_DURATION ((int)(AV_TIME_BASE * 3.0))
fb2758c8 1867
b9a281db
FB
1868/**
1869 * Read the beginning of a media file to get stream information. This
1870 * is useful for file formats with no headers such as MPEG. This
1871 * function also compute the real frame rate in case of mpeg2 repeat
1872 * frame mode.
1873 *
1874 * @param ic media file handle
115329f1 1875 * @return >=0 if OK. AVERROR_xxx if error.
644a9262 1876 * @todo let user decide somehow what information is needed so we dont waste time geting stuff the user doesnt need
b9a281db
FB
1877 */
1878int av_find_stream_info(AVFormatContext *ic)
1879{
9f75260e 1880 int i, count, ret, read_size, j;
b9a281db 1881 AVStream *st;
fb2758c8 1882 AVPacket pkt1, *pkt;
b9a281db 1883 AVPacketList *pktl=NULL, **ppktl;
15bc38e5 1884 int64_t last_dts[MAX_STREAMS];
3c150d16
MN
1885 int64_t duration_sum[MAX_STREAMS];
1886 int duration_count[MAX_STREAMS]={0};
b9a281db 1887
c0df9d75
MN
1888 for(i=0;i<ic->nb_streams;i++) {
1889 st = ic->streams[i];
01f4895c 1890 if(st->codec->codec_type == CODEC_TYPE_VIDEO){
c0df9d75
MN
1891/* if(!st->time_base.num)
1892 st->time_base= */
01f4895c
MN
1893 if(!st->codec->time_base.num)
1894 st->codec->time_base= st->time_base;
c0df9d75 1895 }
90ad92b3
MN
1896 //only for the split stuff
1897 if (!st->parser) {
01f4895c 1898 st->parser = av_parser_init(st->codec->codec_id);
7cbaa7ba
MN
1899 if(st->need_parsing == 2 && st->parser){
1900 st->parser->flags |= PARSER_FLAG_COMPLETE_FRAMES;
1901 }
90ad92b3 1902 }
c0df9d75
MN
1903 }
1904
15bc38e5
MN
1905 for(i=0;i<MAX_STREAMS;i++){
1906 last_dts[i]= AV_NOPTS_VALUE;
3c150d16 1907 duration_sum[i]= INT64_MAX;
15bc38e5 1908 }
115329f1 1909
b9a281db
FB
1910 count = 0;
1911 read_size = 0;
1912 ppktl = &ic->packet_buffer;
1913 for(;;) {
1914 /* check if one codec still needs to be handled */
1915 for(i=0;i<ic->nb_streams;i++) {
1916 st = ic->streams[i];
01f4895c 1917 if (!has_codec_parameters(st->codec))
b9a281db 1918 break;
3e76d1b5 1919 /* variable fps and no guess at the real fps */
9f75260e 1920 if( st->codec->time_base.den >= 101LL*st->codec->time_base.num
01f4895c 1921 && duration_count[i]<20 && st->codec->codec_type == CODEC_TYPE_VIDEO)
3e76d1b5 1922 break;
01f4895c 1923 if(st->parser && st->parser->parser->split && !st->codec->extradata)
90ad92b3 1924 break;
b9a281db
FB
1925 }
1926 if (i == ic->nb_streams) {
1927 /* NOTE: if the format has no header, then we need to read
1928 some packets to get most of the streams, so we cannot
1929 stop here */
fb2758c8 1930 if (!(ic->ctx_flags & AVFMTCTX_NOHEADER)) {
b9a281db
FB
1931 /* if we found the info for all the codecs, we can stop */
1932 ret = count;
1933 break;
1934 }
1935 } else {
1936 /* we did not get all the codec info, but we read too much data */
fb2758c8 1937 if (read_size >= MAX_READ_SIZE) {
b9a281db
FB
1938 ret = count;
1939 break;
1940 }
1941 }
1942
fb2758c8
FB
1943 /* NOTE: a new stream can be added there if no header in file
1944 (AVFMTCTX_NOHEADER) */
1945 ret = av_read_frame_internal(ic, &pkt1);
1946 if (ret < 0) {
1947 /* EOF or error */
1948 ret = -1; /* we could not have all the codec parameters before EOF */
e19456e3
MN
1949 for(i=0;i<ic->nb_streams;i++) {
1950 st = ic->streams[i];
305ee50f
MN
1951 if (!has_codec_parameters(st->codec)){
1952 char buf[256];
1953 avcodec_string(buf, sizeof(buf), st->codec, 0);
1954 av_log(ic, AV_LOG_INFO, "Could not find codec parameters (%s)\n", buf);
344a18c3
MR
1955 } else {
1956 ret = 0;
305ee50f 1957 }
e19456e3 1958 }
fb2758c8
FB
1959 break;
1960 }
1961
b9a281db
FB
1962 pktl = av_mallocz(sizeof(AVPacketList));
1963 if (!pktl) {
1964 ret = AVERROR_NOMEM;
1965 break;
1966 }
1967
1968 /* add the packet in the buffered packet list */
1969 *ppktl = pktl;
1970 ppktl = &pktl->next;
1971
b9a281db 1972 pkt = &pktl->pkt;
fb2758c8 1973 *pkt = pkt1;
115329f1 1974
fb2758c8
FB
1975 /* duplicate the packet */
1976 if (av_dup_packet(pkt) < 0) {
1977 ret = AVERROR_NOMEM;
1978 break;
b9a281db 1979 }
b9a281db 1980
fb2758c8 1981 read_size += pkt->size;
b9a281db
FB
1982
1983 st = ic->streams[pkt->stream_index];
fb2758c8
FB
1984 st->codec_info_duration += pkt->duration;
1985 if (pkt->duration != 0)
1986 st->codec_info_nb_frames++;
1987
cefe0607 1988 {
3c150d16
MN
1989 int index= pkt->stream_index;
1990 int64_t last= last_dts[index];
1991 int64_t duration= pkt->dts - last;
1992
1993 if(pkt->dts != AV_NOPTS_VALUE && last != AV_NOPTS_VALUE && duration>0){
1994 if(duration*duration_count[index]*10/9 < duration_sum[index]){
1995 duration_sum[index]= duration;
1996 duration_count[index]=1;
1997 }else{
1998 int factor= av_rescale(duration, duration_count[index], duration_sum[index]);
1999 duration_sum[index] += duration;
2000 duration_count[index]+= factor;
2001 }
43c0040a 2002 if(st->codec_info_nb_frames == 0 && 0)
cefe0607 2003 st->codec_info_duration += duration;
15bc38e5
MN
2004 }
2005 last_dts[pkt->stream_index]= pkt->dts;
2006 }
01f4895c
MN
2007 if(st->parser && st->parser->parser->split && !st->codec->extradata){
2008 int i= st->parser->parser->split(st->codec, pkt->data, pkt->size);
90ad92b3 2009 if(i){
01f4895c 2010 st->codec->extradata_size= i;
62c52121 2011 st->codec->extradata= av_malloc(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
01f4895c 2012 memcpy(st->codec->extradata, pkt->data, st->codec->extradata_size);
62c52121 2013 memset(st->codec->extradata + i, 0, FF_INPUT_BUFFER_PADDING_SIZE);
90ad92b3
MN
2014 }
2015 }
115329f1 2016
fb2758c8
FB
2017 /* if still no information, we try to open the codec and to
2018 decompress the frame. We try to avoid that in most cases as
2019 it takes longer and uses more memory. For MPEG4, we need to
2020 decompress for Quicktime. */
01f4895c
MN
2021 if (!has_codec_parameters(st->codec) /*&&
2022 (st->codec->codec_id == CODEC_ID_FLV1 ||
2023 st->codec->codec_id == CODEC_ID_H264 ||
2024 st->codec->codec_id == CODEC_ID_H263 ||
2025 st->codec->codec_id == CODEC_ID_H261 ||
2026 st->codec->codec_id == CODEC_ID_VORBIS ||
2027 st->codec->codec_id == CODEC_ID_MJPEG ||
2028 st->codec->codec_id == CODEC_ID_PNG ||
2029 st->codec->codec_id == CODEC_ID_PAM ||
2030 st->codec->codec_id == CODEC_ID_PGM ||
2031 st->codec->codec_id == CODEC_ID_PGMYUV ||
2032 st->codec->codec_id == CODEC_ID_PBM ||
2033 st->codec->codec_id == CODEC_ID_PPM ||
2034 st->codec->codec_id == CODEC_ID_SHORTEN ||
2035 (st->codec->codec_id == CODEC_ID_MPEG4 && !st->need_parsing))*/)
fb2758c8 2036 try_decode_frame(st, pkt->data, pkt->size);
115329f1 2037
cefe0607 2038 if (av_rescale_q(st->codec_info_duration, st->time_base, AV_TIME_BASE_Q) >= MAX_STREAM_DURATION) {
fb2758c8 2039 break;
b9a281db
FB
2040 }
2041 count++;
2042 }
2043
43c0040a
MN
2044 // close codecs which where opened in try_decode_frame()
2045 for(i=0;i<ic->nb_streams;i++) {
2046 st = ic->streams[i];
01f4895c
MN
2047 if(st->codec->codec)
2048 avcodec_close(st->codec);
43c0040a 2049 }
b9a281db
FB
2050 for(i=0;i<ic->nb_streams;i++) {
2051 st = ic->streams[i];
01f4895c
MN
2052 if (st->codec->codec_type == CODEC_TYPE_VIDEO) {
2053 if(st->codec->codec_id == CODEC_ID_RAWVIDEO && !st->codec->codec_tag && !st->codec->bits_per_sample)
2054 st->codec->codec_tag= avcodec_pix_fmt_to_codec_tag(st->codec->pix_fmt);
15bc38e5 2055
9f75260e
MN
2056 if(duration_count[i] && st->codec->time_base.num*101LL <= st->codec->time_base.den &&
2057 st->time_base.num*duration_sum[i]/duration_count[i]*101LL > st->time_base.den){
2058 int64_t num, den, error, best_error;
b3506cb4 2059
3c150d16
MN
2060 num= st->time_base.den*duration_count[i];
2061 den= st->time_base.num*duration_sum[i];
115329f1 2062
9f75260e
MN
2063 best_error= INT64_MAX;
2064 for(j=1; j<60*12; j++){
2065 error= ABS(1001*12*num - 1001*j*den);
2066 if(error < best_error){
2067 best_error= error;
2068 av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den, j, 12, INT_MAX);
2069 }
2070 }
2071 for(j=24; j<=30; j+=6){
2072 error= ABS(1001*12*num - 1000*12*j*den);
2073 if(error < best_error){
2074 best_error= error;
2075 av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den, j*1000, 1001, INT_MAX);
2076 }
3c150d16 2077 }
15bc38e5
MN
2078 }
2079
d07730dd 2080 /* set real frame rate info */
fb2758c8 2081 /* compute the real frame rate for telecine */
01f4895c
MN
2082 if ((st->codec->codec_id == CODEC_ID_MPEG1VIDEO ||
2083 st->codec->codec_id == CODEC_ID_MPEG2VIDEO) &&
2084 st->codec->sub_id == 2) {
fb2758c8
FB
2085 if (st->codec_info_nb_frames >= 20) {
2086 float coded_frame_rate, est_frame_rate;
115329f1 2087 est_frame_rate = ((double)st->codec_info_nb_frames * AV_TIME_BASE) /
fb2758c8 2088 (double)st->codec_info_duration ;
01f4895c 2089 coded_frame_rate = 1.0/av_q2d(st->codec->time_base);
fb2758c8 2090#if 0
115329f1 2091 printf("telecine: coded_frame_rate=%0.3f est_frame_rate=%0.3f\n",
fb2758c8
FB
2092 coded_frame_rate, est_frame_rate);
2093#endif
2094 /* if we detect that it could be a telecine, we
2095 signal it. It would be better to do it at a
2096 higher level as it can change in a film */
115329f1 2097 if (coded_frame_rate >= 24.97 &&
fb2758c8 2098 (est_frame_rate >= 23.5 && est_frame_rate < 24.5)) {
c0df9d75 2099 st->r_frame_rate = (AVRational){24000, 1001};
fb2758c8
FB
2100 }
2101 }
2102 }
2103 /* if no real frame rate, use the codec one */
c0df9d75 2104 if (!st->r_frame_rate.num){
01f4895c
MN
2105 st->r_frame_rate.num = st->codec->time_base.den;
2106 st->r_frame_rate.den = st->codec->time_base.num;
14bea432 2107 }
b9a281db 2108 }
de6d9b64 2109 }
b9a281db 2110
12f996ed 2111 av_estimate_timings(ic);
e928649b
MN
2112#if 0
2113 /* correct DTS for b frame streams with no timestamps */
2114 for(i=0;i<ic->nb_streams;i++) {
2115 st = ic->streams[i];
01f4895c 2116 if (st->codec->codec_type == CODEC_TYPE_VIDEO) {
e928649b
MN
2117 if(b-frames){
2118 ppktl = &ic->packet_buffer;
2119 while(ppkt1){
2120 if(ppkt1->stream_index != i)
2121 continue;
2122 if(ppkt1->pkt->dts < 0)
2123 break;
2124 if(ppkt1->pkt->pts != AV_NOPTS_VALUE)
2125 break;
2126 ppkt1->pkt->dts -= delta;
2127 ppkt1= ppkt1->next;
2128 }
2129 if(ppkt1)
2130 continue;
2131 st->cur_dts -= delta;
2132 }
2133 }
2134 }
2135#endif
b9a281db 2136 return ret;
de6d9b64
FB
2137}
2138
fb2758c8
FB
2139/*******************************************************/
2140
2141/**
2142 * start playing a network based stream (e.g. RTSP stream) at the
115329f1 2143 * current position
fb2758c8
FB
2144 */
2145int av_read_play(AVFormatContext *s)
2146{
2147 if (!s->iformat->read_play)
2148 return AVERROR_NOTSUPP;
2149 return s->iformat->read_play(s);
2150}
2151
2152/**
e36bdf8b
DK
2153 * Pause a network based stream (e.g. RTSP stream).
2154 *
2155 * Use av_read_play() to resume it.
fb2758c8
FB
2156 */
2157int av_read_pause(AVFormatContext *s)
2158{
2159 if (!s->iformat->read_pause)
2160 return AVERROR_NOTSUPP;
2161 return s->iformat->read_pause(s);
2162}
2163
b9a281db 2164/**
e36bdf8b 2165 * Close a media file (but not its codecs).
b9a281db
FB
2166 *
2167 * @param s media file handle
2168 */
de6d9b64
FB
2169void av_close_input_file(AVFormatContext *s)
2170{
b6892136 2171 int i, must_open_file;
da24c5e3 2172 AVStream *st;
de6d9b64 2173
fb2758c8
FB
2174 /* free previous packet */
2175 if (s->cur_st && s->cur_st->parser)
115329f1 2176 av_free_packet(&s->cur_pkt);
fb2758c8 2177
b9a281db
FB
2178 if (s->iformat->read_close)
2179 s->iformat->read_close(s);
de6d9b64 2180 for(i=0;i<s->nb_streams;i++) {
da24c5e3
FB
2181 /* free all data in a stream component */
2182 st = s->streams[i];
fb2758c8
FB
2183 if (st->parser) {
2184 av_parser_close(st->parser);
de6d9b64 2185 }
fb2758c8 2186 av_free(st->index_entries);
a5e9102b 2187 av_free(st->codec->extradata);
01f4895c 2188 av_free(st->codec);
fb2758c8 2189 av_free(st);
de6d9b64 2190 }
fb2758c8 2191 flush_packet_queue(s);
b6892136 2192 must_open_file = 1;
da24c5e3 2193 if (s->iformat->flags & AVFMT_NOFILE) {
b6892136
FB
2194 must_open_file = 0;
2195 }
2196 if (must_open_file) {
96baaa6a
FB
2197 url_fclose(&s->pb);
2198 }
a8dbe951 2199 av_freep(&s->priv_data);
1ea4f593 2200 av_free(s);
de6d9b64
FB
2201}
2202
b9a281db 2203/**
e36bdf8b 2204 * Add a new stream to a media file.
b9a281db 2205 *
e36bdf8b
DK
2206 * Can only be called in the read_header() function. If the flag
2207 * AVFMTCTX_NOHEADER is in the format context, then new streams
2208 * can be added in read_packet too.
b9a281db
FB
2209 *
2210 * @param s media file handle
115329f1 2211 * @param id file format dependent stream id
b9a281db
FB
2212 */
2213AVStream *av_new_stream(AVFormatContext *s, int id)
2214{
2215 AVStream *st;
2216
2217 if (s->nb_streams >= MAX_STREAMS)
2218 return NULL;
2219
2220 st = av_mallocz(sizeof(AVStream));
2221 if (!st)
2222 return NULL;
115329f1 2223
01f4895c 2224 st->codec= avcodec_alloc_context();
48091512
FB
2225 if (s->iformat) {
2226 /* no default bitrate if decoding */
01f4895c 2227 st->codec->bit_rate = 0;
48091512 2228 }
b9a281db
FB
2229 st->index = s->nb_streams;
2230 st->id = id;
12f996ed
FB
2231 st->start_time = AV_NOPTS_VALUE;
2232 st->duration = AV_NOPTS_VALUE;
e928649b 2233 st->cur_dts = AV_NOPTS_VALUE;
9ee91c2f
MN
2234
2235 /* default pts settings is MPEG like */
2236 av_set_pts_info(st, 33, 1, 90000);
77405fc8 2237 st->last_IP_pts = AV_NOPTS_VALUE;
9ee91c2f 2238
b9a281db
FB
2239 s->streams[s->nb_streams++] = st;
2240 return st;
2241}
2242
2243/************************************************************/
2244/* output media file */
de6d9b64 2245
87a0a681
FB
2246int av_set_parameters(AVFormatContext *s, AVFormatParameters *ap)
2247{
2248 int ret;
115329f1 2249
98486a6b
RS
2250 if (s->oformat->priv_data_size > 0) {
2251 s->priv_data = av_mallocz(s->oformat->priv_data_size);
2252 if (!s->priv_data)
2253 return AVERROR_NOMEM;
2254 } else
2255 s->priv_data = NULL;
115329f1 2256
87a0a681
FB
2257 if (s->oformat->set_parameters) {
2258 ret = s->oformat->set_parameters(s, ap);
2259 if (ret < 0)
2260 return ret;
2261 }
2262 return 0;
2263}
2264
b9a281db
FB
2265/**
2266 * allocate the stream private data and write the stream header to an
2267 * output media file
2268 *
2269 * @param s media file handle
115329f1 2270 * @return 0 if OK. AVERROR_xxx if error.
b9a281db
FB
2271 */
2272int av_write_header(AVFormatContext *s)
2273{
1e51d801
FB
2274 int ret, i;
2275 AVStream *st;
2276
9450118b
MN
2277 // some sanity checks
2278 for(i=0;i<s->nb_streams;i++) {
2279 st = s->streams[i];
2280
2281 switch (st->codec->codec_type) {
2282 case CODEC_TYPE_AUDIO:
2283 if(st->codec->sample_rate<=0){
2284 av_log(s, AV_LOG_ERROR, "sample rate not set\n");
2285 return -1;
2286 }
2287 break;
2288 case CODEC_TYPE_VIDEO:
2289 if(st->codec->time_base.num<=0 || st->codec->time_base.den<=0){ //FIXME audio too?
2290 av_log(s, AV_LOG_ERROR, "time base not set\n");
2291 return -1;
2292 }
2293 if(st->codec->width<=0 || st->codec->height<=0){
2294 av_log(s, AV_LOG_ERROR, "dimensions not set\n");
2295 return -1;
2296 }
2297 break;
2298 }
2299 }
2300
31e11451
MN
2301 if(s->oformat->write_header){
2302 ret = s->oformat->write_header(s);
2303 if (ret < 0)
2304 return ret;
2305 }
1e51d801
FB
2306
2307 /* init PTS generation */
2308 for(i=0;i<s->nb_streams;i++) {
f0ff20a1 2309 int64_t den = AV_NOPTS_VALUE;
1e51d801
FB
2310 st = s->streams[i];
2311
01f4895c 2312 switch (st->codec->codec_type) {
1e51d801 2313 case CODEC_TYPE_AUDIO:
f0ff20a1 2314 den = (int64_t)st->time_base.num * st->codec->sample_rate;
1e51d801
FB
2315 break;
2316 case CODEC_TYPE_VIDEO:
f0ff20a1 2317 den = (int64_t)st->time_base.num * st->codec->time_base.den;
1e51d801
FB
2318 break;
2319 default:
2320 break;
2321 }
f0ff20a1
WG
2322 if (den != AV_NOPTS_VALUE) {
2323 if (den <= 0)
2324 return AVERROR_INVALIDDATA;
2325 av_frac_init(&st->pts, 0, 0, den);
2326 }
1e51d801
FB
2327 }
2328 return 0;
b9a281db
FB
2329}
2330
3c895fc0 2331//FIXME merge with compute_pkt_fields
5edea431 2332static int compute_pkt_fields2(AVStream *st, AVPacket *pkt){
01f4895c 2333 int b_frames = FFMAX(st->codec->has_b_frames, st->codec->max_b_frames);
3c895fc0 2334 int num, den, frame_size;
b0c7f5a9 2335
3c895fc0 2336// av_log(NULL, AV_LOG_DEBUG, "av_write_frame: pts:%lld dts:%lld cur_dts:%lld b:%d size:%d st:%d\n", pkt->pts, pkt->dts, st->cur_dts, b_frames, pkt->size, pkt->stream_index);
115329f1 2337
e928649b
MN
2338/* if(pkt->pts == AV_NOPTS_VALUE && pkt->dts == AV_NOPTS_VALUE)
2339 return -1;*/
115329f1 2340
e928649b 2341 /* duration field */
3c895fc0
MN
2342 if (pkt->duration == 0) {
2343 compute_frame_duration(&num, &den, st, NULL, pkt);
2344 if (den && num) {
2345 pkt->duration = av_rescale(1, num * (int64_t)st->time_base.den, den * (int64_t)st->time_base.num);
2346 }
2347 }
e928649b
MN
2348
2349 //XXX/FIXME this is a temporary hack until all encoders output pts
2350 if((pkt->pts == 0 || pkt->pts == AV_NOPTS_VALUE) && pkt->dts == AV_NOPTS_VALUE && !b_frames){
2351 pkt->dts=
2352// pkt->pts= st->cur_dts;
2353 pkt->pts= st->pts.val;
2354 }
2355
115329f1 2356 //calculate dts from pts
e928649b
MN
2357 if(pkt->pts != AV_NOPTS_VALUE && pkt->dts == AV_NOPTS_VALUE){
2358 if(b_frames){
2359 if(st->last_IP_pts == AV_NOPTS_VALUE){
3c895fc0 2360 st->last_IP_pts= -pkt->duration;
e928649b
MN
2361 }
2362 if(st->last_IP_pts < pkt->pts){
2363 pkt->dts= st->last_IP_pts;
2364 st->last_IP_pts= pkt->pts;
2365 }else
2366 pkt->dts= pkt->pts;
2367 }else
2368 pkt->dts= pkt->pts;
2369 }
115329f1 2370
5edea431 2371 if(st->cur_dts && st->cur_dts != AV_NOPTS_VALUE && st->cur_dts >= pkt->dts){
4733abcb 2372 av_log(NULL, AV_LOG_ERROR, "error, non monotone timestamps %"PRId64" >= %"PRId64"\n", st->cur_dts, pkt->dts);
5edea431
MN
2373 return -1;
2374 }
2375 if(pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE && pkt->pts < pkt->dts){
2376 av_log(NULL, AV_LOG_ERROR, "error, pts < dts\n");
2377 return -1;
2378 }
2379
3c895fc0 2380// av_log(NULL, AV_LOG_DEBUG, "av_write_frame: pts2:%lld dts2:%lld\n", pkt->pts, pkt->dts);
e928649b
MN
2381 st->cur_dts= pkt->dts;
2382 st->pts.val= pkt->dts;
2383
1e51d801 2384 /* update pts */
01f4895c 2385 switch (st->codec->codec_type) {
1e51d801 2386 case CODEC_TYPE_AUDIO:
01f4895c 2387 frame_size = get_audio_frame_size(st->codec, pkt->size);
6d8f985e 2388
b0c7f5a9 2389 /* HACK/FIXME, we skip the initial 0-size packets as they are most likely equal to the encoder delay,
6d8f985e 2390 but it would be better if we had the real timestamps from the encoder */
e928649b 2391 if (frame_size >= 0 && (pkt->size || st->pts.num!=st->pts.den>>1 || st->pts.val)) {
9ee91c2f 2392 av_frac_add(&st->pts, (int64_t)st->time_base.den * frame_size);
7feb950a 2393 }
1e51d801
FB
2394 break;
2395 case CODEC_TYPE_VIDEO:
01f4895c 2396 av_frac_add(&st->pts, (int64_t)st->time_base.den * st->codec->time_base.num);
1e51d801
FB
2397 break;
2398 default:
2399 break;
2400 }
5edea431 2401 return 0;
3c895fc0
MN
2402}
2403
2404static void truncate_ts(AVStream *st, AVPacket *pkt){
2405 int64_t pts_mask = (2LL << (st->pts_wrap_bits-1)) - 1;
115329f1 2406
e0c91bc2
MN
2407// if(pkt->dts < 0)
2408// pkt->dts= 0; //this happens for low_delay=0 and b frames, FIXME, needs further invstigation about what we should do here
115329f1 2409
3c895fc0
MN
2410 pkt->pts &= pts_mask;
2411 pkt->dts &= pts_mask;
2412}
2413
2414/**
e36bdf8b
DK
2415 * Write a packet to an output media file.
2416 *
2417 * The packet shall contain one audio or video frame.
3c895fc0
MN
2418 *
2419 * @param s media file handle
2420 * @param pkt the packet, which contains the stream_index, buf/buf_size, dts/pts, ...
2421 * @return < 0 if error, = 0 if OK, 1 if end of stream wanted.
2422 */
2423int av_write_frame(AVFormatContext *s, AVPacket *pkt)
2424{
576ae256
MN
2425 int ret;
2426
5edea431 2427 ret=compute_pkt_fields2(s->streams[pkt->stream_index], pkt);
494bbf58 2428 if(ret<0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
5edea431 2429 return ret;
115329f1 2430
3c895fc0
MN
2431 truncate_ts(s->streams[pkt->stream_index], pkt);
2432
576ae256
MN
2433 ret= s->oformat->write_packet(s, pkt);
2434 if(!ret)
2435 ret= url_ferror(&s->pb);
2436 return ret;
3c895fc0
MN
2437}
2438
2439/**
81f0f938
BC
2440 * Interleave a packet per DTS in an output media file.
2441 *
2442 * Packets with pkt->destruct == av_destruct_packet will be freed inside this function,
2443 * so they cannot be used after it, note calling av_free_packet() on them is still safe.
2444 *
2445 * @param s media file handle
2446 * @param out the interleaved packet will be output here
2447 * @param in the input packet
2448 * @param flush 1 if no further packets are available as input and all
2449 * remaining packets should be output
2450 * @return 1 if a packet was output, 0 if no packet could be output,
2451 * < 0 if an error occured
fe2d6fe2 2452 */
f21c0b4c 2453int av_interleave_packet_per_dts(AVFormatContext *s, AVPacket *out, AVPacket *pkt, int flush){
fe2d6fe2
MN
2454 AVPacketList *pktl, **next_point, *this_pktl;
2455 int stream_count=0;
2456 int streams[MAX_STREAMS];
2457
2458 if(pkt){
2459 AVStream *st= s->streams[ pkt->stream_index];
2460
2577897d 2461// assert(pkt->destruct != av_destruct_packet); //FIXME
fe2d6fe2
MN
2462
2463 this_pktl = av_mallocz(sizeof(AVPacketList));
2464 this_pktl->pkt= *pkt;
2577897d
MN
2465 if(pkt->destruct == av_destruct_packet)
2466 pkt->destruct= NULL; // non shared -> must keep original from being freed
2467 else
2468 av_dup_packet(&this_pktl->pkt); //shared -> must dup
fe2d6fe2
MN
2469
2470 next_point = &s->packet_buffer;
2471 while(*next_point){
2472 AVStream *st2= s->streams[ (*next_point)->pkt.stream_index];
2473 int64_t left= st2->time_base.num * (int64_t)st ->time_base.den;
2474 int64_t right= st ->time_base.num * (int64_t)st2->time_base.den;
2475 if((*next_point)->pkt.dts * left > pkt->dts * right) //FIXME this can overflow
2476 break;
2477 next_point= &(*next_point)->next;
2478 }
2479 this_pktl->next= *next_point;
2480 *next_point= this_pktl;
2481 }
115329f1 2482
fe2d6fe2
MN
2483 memset(streams, 0, sizeof(streams));
2484 pktl= s->packet_buffer;
2485 while(pktl){
2486//av_log(s, AV_LOG_DEBUG, "show st:%d dts:%lld\n", pktl->pkt.stream_index, pktl->pkt.dts);
2487 if(streams[ pktl->pkt.stream_index ] == 0)
2488 stream_count++;
2489 streams[ pktl->pkt.stream_index ]++;
2490 pktl= pktl->next;
2491 }
115329f1 2492
fe2d6fe2
MN
2493 if(s->nb_streams == stream_count || (flush && stream_count)){
2494 pktl= s->packet_buffer;
2495 *out= pktl->pkt;
115329f1
DB
2496
2497 s->packet_buffer= pktl->next;
fe2d6fe2
MN
2498 av_freep(&pktl);
2499 return 1;
2500 }else{
2501 av_init_packet(out);
2502 return 0;
2503 }
2504}
2505
2506/**
2507 * Interleaves a AVPacket correctly so it can be muxed.
2508 * @param out the interleaved packet will be output here
2509 * @param in the input packet
2510 * @param flush 1 if no further packets are available as input and all
2511 * remaining packets should be output
115329f1 2512 * @return 1 if a packet was output, 0 if no packet could be output,
fe2d6fe2
MN
2513 * < 0 if an error occured
2514 */
2515static int av_interleave_packet(AVFormatContext *s, AVPacket *out, AVPacket *in, int flush){
2516 if(s->oformat->interleave_packet)
2517 return s->oformat->interleave_packet(s, out, in, flush);
2518 else
2519 return av_interleave_packet_per_dts(s, out, in, flush);
2520}
2521
2522/**
e36bdf8b
DK
2523 * Writes a packet to an output media file ensuring correct interleaving.
2524 *
2525 * The packet must contain one audio or video frame.
3c895fc0
MN
2526 * If the packets are already correctly interleaved the application should
2527 * call av_write_frame() instead as its slightly faster, its also important
fe2d6fe2 2528 * to keep in mind that completly non interleaved input will need huge amounts
3c895fc0
MN
2529 * of memory to interleave with this, so its prefereable to interleave at the
2530 * demuxer level
2531 *
2532 * @param s media file handle
2533 * @param pkt the packet, which contains the stream_index, buf/buf_size, dts/pts, ...
2534 * @return < 0 if error, = 0 if OK, 1 if end of stream wanted.
2535 */
2536int av_interleaved_write_frame(AVFormatContext *s, AVPacket *pkt){
3c895fc0
MN
2537 AVStream *st= s->streams[ pkt->stream_index];
2538
6f824977 2539 //FIXME/XXX/HACK drop zero sized packets
01f4895c 2540 if(st->codec->codec_type == CODEC_TYPE_AUDIO && pkt->size==0)
6f824977 2541 return 0;
3ce16b30
MN
2542
2543//av_log(NULL, AV_LOG_DEBUG, "av_interleaved_write_frame %d %Ld %Ld\n", pkt->size, pkt->dts, pkt->pts);
494bbf58 2544 if(compute_pkt_fields2(st, pkt) < 0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
3ce16b30 2545 return -1;
115329f1 2546
3c895fc0
MN
2547 if(pkt->dts == AV_NOPTS_VALUE)
2548 return -1;
3c895fc0 2549
fe2d6fe2
MN
2550 for(;;){
2551 AVPacket opkt;
2552 int ret= av_interleave_packet(s, &opkt, pkt, 0);
2553 if(ret<=0) //FIXME cleanup needed for ret<0 ?
2554 return ret;
115329f1 2555
fe2d6fe2
MN
2556 truncate_ts(s->streams[opkt.stream_index], &opkt);
2557 ret= s->oformat->write_packet(s, &opkt);
115329f1 2558
fe2d6fe2
MN
2559 av_free_packet(&opkt);
2560 pkt= NULL;
115329f1 2561
3c895fc0
MN
2562 if(ret<0)
2563 return ret;
576ae256
MN
2564 if(url_ferror(&s->pb))
2565 return url_ferror(&s->pb);
3c895fc0 2566 }
b9a281db
FB
2567}
2568
2569/**
e36bdf8b
DK
2570 * @brief Write the stream trailer to an output media file and
2571 * free the file private data.
b9a281db
FB
2572 *
2573 * @param s media file handle
e36bdf8b
DK
2574 * @return 0 if OK. AVERROR_xxx if error.
2575 */
b9a281db
FB
2576int av_write_trailer(AVFormatContext *s)
2577{
c40a3a42 2578 int ret, i;
115329f1 2579
fe2d6fe2
MN
2580 for(;;){
2581 AVPacket pkt;
2582 ret= av_interleave_packet(s, &pkt, NULL, 1);
2583 if(ret<0) //FIXME cleanup needed for ret<0 ?
c40a3a42 2584 goto fail;
fe2d6fe2
MN
2585 if(!ret)
2586 break;
115329f1 2587
fe2d6fe2
MN
2588 truncate_ts(s->streams[pkt.stream_index], &pkt);
2589 ret= s->oformat->write_packet(s, &pkt);
115329f1 2590
fe2d6fe2 2591 av_free_packet(&pkt);
115329f1 2592
3c895fc0 2593 if(ret<0)
c40a3a42 2594 goto fail;
576ae256
MN
2595 if(url_ferror(&s->pb))
2596 goto fail;
3c895fc0
MN
2597 }
2598
31e11451
MN
2599 if(s->oformat->write_trailer)
2600 ret = s->oformat->write_trailer(s);
c40a3a42 2601fail:
576ae256
MN
2602 if(ret == 0)
2603 ret=url_ferror(&s->pb);
c40a3a42
MN
2604 for(i=0;i<s->nb_streams;i++)
2605 av_freep(&s->streams[i]->priv_data);
b9a281db
FB
2606 av_freep(&s->priv_data);
2607 return ret;
de6d9b64
FB
2608}
2609
2610/* "user interface" functions */
2611
2612void dump_format(AVFormatContext *ic,
115329f1 2613 int index,
de6d9b64
FB
2614 const char *url,
2615 int is_output)
2616{
b9a281db 2617 int i, flags;
de6d9b64
FB
2618 char buf[256];
2619
115329f1 2620 av_log(NULL, AV_LOG_INFO, "%s #%d, %s, %s '%s':\n",
de6d9b64 2621 is_output ? "Output" : "Input",
115329f1
DB
2622 index,
2623 is_output ? ic->oformat->name : ic->iformat->name,
de6d9b64 2624 is_output ? "to" : "from", url);
12f996ed 2625 if (!is_output) {
2143116d 2626 av_log(NULL, AV_LOG_INFO, " Duration: ");
12f996ed
FB
2627 if (ic->duration != AV_NOPTS_VALUE) {
2628 int hours, mins, secs, us;
2629 secs = ic->duration / AV_TIME_BASE;
2630 us = ic->duration % AV_TIME_BASE;
2631 mins = secs / 60;
2632 secs %= 60;
2633 hours = mins / 60;
2634 mins %= 60;
115329f1 2635 av_log(NULL, AV_LOG_INFO, "%02d:%02d:%02d.%01d", hours, mins, secs,
12f996ed
FB
2636 (10 * us) / AV_TIME_BASE);
2637 } else {
2143116d 2638 av_log(NULL, AV_LOG_INFO, "N/A");
12f996ed 2639 }
d0f3f159
WG
2640 if (ic->start_time != AV_NOPTS_VALUE) {
2641 int secs, us;
2143116d 2642 av_log(NULL, AV_LOG_INFO, ", start: ");
d0f3f159
WG
2643 secs = ic->start_time / AV_TIME_BASE;
2644 us = ic->start_time % AV_TIME_BASE;
2143116d 2645 av_log(NULL, AV_LOG_INFO, "%d.%06d",
d0f3f159
WG
2646 secs, (int)av_rescale(us, 1000000, AV_TIME_BASE));
2647 }
2143116d 2648 av_log(NULL, AV_LOG_INFO, ", bitrate: ");
12f996ed 2649 if (ic->bit_rate) {
2143116d 2650 av_log(NULL, AV_LOG_INFO,"%d kb/s", ic->bit_rate / 1000);
12f996ed 2651 } else {
2143116d 2652 av_log(NULL, AV_LOG_INFO, "N/A");
12f996ed 2653 }
2143116d 2654 av_log(NULL, AV_LOG_INFO, "\n");
12f996ed 2655 }
de6d9b64
FB
2656 for(i=0;i<ic->nb_streams;i++) {
2657 AVStream *st = ic->streams[i];
21189011 2658 int g= ff_gcd(st->time_base.num, st->time_base.den);
01f4895c 2659 avcodec_string(buf, sizeof(buf), st->codec, is_output);
2143116d 2660 av_log(NULL, AV_LOG_INFO, " Stream #%d.%d", index, i);
b9a281db
FB
2661 /* the pid is an important information, so we display it */
2662 /* XXX: add a generic system */
2663 if (is_output)
2664 flags = ic->oformat->flags;
2665 else
2666 flags = ic->iformat->flags;
2667 if (flags & AVFMT_SHOW_IDS) {
2143116d 2668 av_log(NULL, AV_LOG_INFO, "[0x%x]", st->id);
b9a281db 2669 }
c6ec28b1
MN
2670 if (strlen(st->language) > 0) {
2671 av_log(NULL, AV_LOG_INFO, "(%s)", st->language);
2672 }
21189011 2673 av_log(NULL, AV_LOG_DEBUG, ", %d/%d", st->time_base.num/g, st->time_base.den/g);
47dd81c7 2674 av_log(NULL, AV_LOG_INFO, ": %s", buf);
21189011 2675 if(st->codec->codec_type == CODEC_TYPE_VIDEO){
780eb1c9
MN
2676 if(st->r_frame_rate.den && st->r_frame_rate.num)
2677 av_log(NULL, AV_LOG_INFO, ", %5.2f fps(r)", av_q2d(st->r_frame_rate));
2678/* else if(st->time_base.den && st->time_base.num)
2679 av_log(NULL, AV_LOG_INFO, ", %5.2f fps(m)", 1/av_q2d(st->time_base));*/
2680 else
2681 av_log(NULL, AV_LOG_INFO, ", %5.2f fps(c)", 1/av_q2d(st->codec->time_base));
21189011 2682 }
47dd81c7 2683 av_log(NULL, AV_LOG_INFO, "\n");
de6d9b64
FB
2684 }
2685}
2686
2687typedef struct {
445f1b83 2688 const char *abv;
de6d9b64 2689 int width, height;
445f1b83
RS
2690 int frame_rate, frame_rate_base;
2691} AbvEntry;
2692
2693static AbvEntry frame_abvs[] = {
ba2a8cb4
RS
2694 { "ntsc", 720, 480, 30000, 1001 },
2695 { "pal", 720, 576, 25, 1 },
2696 { "qntsc", 352, 240, 30000, 1001 }, /* VCD compliant ntsc */
2697 { "qpal", 352, 288, 25, 1 }, /* VCD compliant pal */
904736b5
RS
2698 { "sntsc", 640, 480, 30000, 1001 }, /* square pixel ntsc */
2699 { "spal", 768, 576, 25, 1 }, /* square pixel pal */
445f1b83
RS
2700 { "film", 352, 240, 24, 1 },
2701 { "ntsc-film", 352, 240, 24000, 1001 },
2702 { "sqcif", 128, 96, 0, 0 },
2703 { "qcif", 176, 144, 0, 0 },
2704 { "cif", 352, 288, 0, 0 },
2705 { "4cif", 704, 576, 0, 0 },
de6d9b64 2706};
445f1b83 2707
e36bdf8b
DK
2708/**
2709 * parses width and height out of string str.
2710 */
de6d9b64
FB
2711int parse_image_size(int *width_ptr, int *height_ptr, const char *str)
2712{
2713 int i;
445f1b83 2714 int n = sizeof(frame_abvs) / sizeof(AbvEntry);
de6d9b64
FB
2715 const char *p;
2716 int frame_width = 0, frame_height = 0;
2717
2718 for(i=0;i<n;i++) {
445f1b83
RS
2719 if (!strcmp(frame_abvs[i].abv, str)) {
2720 frame_width = frame_abvs[i].width;
2721 frame_height = frame_abvs[i].height;
de6d9b64
FB
2722 break;
2723 }
2724 }
2725 if (i == n) {
2726 p = str;
2727 frame_width = strtol(p, (char **)&p, 10);
2728 if (*p)
2729 p++;
2730 frame_height = strtol(p, (char **)&p, 10);
2731 }
2732 if (frame_width <= 0 || frame_height <= 0)
2733 return -1;
2734 *width_ptr = frame_width;
2735 *height_ptr = frame_height;
2736 return 0;
2737}
2738
e36bdf8b
DK
2739/**
2740 * Converts frame rate from string to a fraction.
2741 *
2742 * First we try to get an exact integer or fractional frame rate.
2743 * If this fails we convert the frame rate to a double and return
2744 * an approximate fraction using the DEFAULT_FRAME_RATE_BASE.
2745 */
445f1b83
RS
2746int parse_frame_rate(int *frame_rate, int *frame_rate_base, const char *arg)
2747{
2748 int i;
2749 char* cp;
115329f1 2750
445f1b83
RS
2751 /* First, we check our abbreviation table */
2752 for (i = 0; i < sizeof(frame_abvs)/sizeof(*frame_abvs); ++i)
2753 if (!strcmp(frame_abvs[i].abv, arg)) {
bb270c08
DB
2754 *frame_rate = frame_abvs[i].frame_rate;
2755 *frame_rate_base = frame_abvs[i].frame_rate_base;
2756 return 0;
2757 }
445f1b83
RS
2758
2759 /* Then, we try to parse it as fraction */
2760 cp = strchr(arg, '/');
88805317
RG
2761 if (!cp)
2762 cp = strchr(arg, ':');
445f1b83
RS
2763 if (cp) {
2764 char* cpp;
bb270c08
DB
2765 *frame_rate = strtol(arg, &cpp, 10);
2766 if (cpp != arg || cpp == cp)
2767 *frame_rate_base = strtol(cp+1, &cpp, 10);
2768 else
2769 *frame_rate = 0;
115329f1 2770 }
445f1b83
RS
2771 else {
2772 /* Finally we give up and parse it as double */
67dd33f9
BC
2773 AVRational time_base = av_d2q(strtod(arg, 0), DEFAULT_FRAME_RATE_BASE);
2774 *frame_rate_base = time_base.den;
2775 *frame_rate = time_base.num;
445f1b83
RS
2776 }
2777 if (!*frame_rate || !*frame_rate_base)
2778 return -1;
2779 else
2780 return 0;
2781}
2782
e36bdf8b
DK
2783/**
2784 * Converts date string to number of seconds since Jan 1st, 1970.
2785 *
2786 * @code
2787 * Syntax:
916c80e9
FB
2788 * - If not a duration:
2789 * [{YYYY-MM-DD|YYYYMMDD}]{T| }{HH[:MM[:SS[.m...]]][Z]|HH[MM[SS[.m...]]][Z]}
c5510dd6 2790 * Time is localtime unless Z is suffixed to the end. In this case GMT
115329f1 2791 * Return the date in micro seconds since 1970
e36bdf8b
DK
2792 *
2793 * - If a duration:
916c80e9
FB
2794 * HH[:MM[:SS[.m...]]]
2795 * S+[.m...]
e36bdf8b 2796 * @endcode
916c80e9 2797 */
ac44871c 2798#ifndef CONFIG_WINCE
0c1a9eda 2799int64_t parse_date(const char *datestr, int duration)
de6d9b64
FB
2800{
2801 const char *p;
0c1a9eda 2802 int64_t t;
2dbceb9f 2803 struct tm dt;
c5510dd6
PG
2804 int i;
2805 static const char *date_fmt[] = {
2806 "%Y-%m-%d",
2807 "%Y%m%d",
2808 };
2809 static const char *time_fmt[] = {
2810 "%H:%M:%S",
2811 "%H%M%S",
2812 };
2813 const char *q;
916c80e9 2814 int is_utc, len;
c5510dd6 2815 char lastch;
a6a92a9a 2816 int negative = 0;
6d8f985e
MN
2817
2818#undef time
c5510dd6
PG
2819 time_t now = time(0);
2820
916c80e9
FB
2821 len = strlen(datestr);
2822 if (len > 0)
2823 lastch = datestr[len - 1];
2824 else
2825 lastch = '\0';
c5510dd6 2826 is_utc = (lastch == 'z' || lastch == 'Z');
2dbceb9f
PG
2827
2828 memset(&dt, 0, sizeof(dt));
de6d9b64
FB
2829
2830 p = datestr;
916c80e9 2831 q = NULL;
de6d9b64 2832 if (!duration) {
c5510dd6 2833 for (i = 0; i < sizeof(date_fmt) / sizeof(date_fmt[0]); i++) {
f71869a4 2834 q = small_strptime(p, date_fmt[i], &dt);
c5510dd6
PG
2835 if (q) {
2836 break;
2837 }
2838 }
2839
2840 if (!q) {
2841 if (is_utc) {
2842 dt = *gmtime(&now);
2843 } else {
2844 dt = *localtime(&now);
2845 }
2846 dt.tm_hour = dt.tm_min = dt.tm_sec = 0;
de6d9b64 2847 } else {
c5510dd6 2848 p = q;
de6d9b64 2849 }
c5510dd6
PG
2850
2851 if (*p == 'T' || *p == 't' || *p == ' ')
2852 p++;
c5510dd6 2853
916c80e9 2854 for (i = 0; i < sizeof(time_fmt) / sizeof(time_fmt[0]); i++) {
f71869a4 2855 q = small_strptime(p, time_fmt[i], &dt);
916c80e9
FB
2856 if (q) {
2857 break;
2858 }
2859 }
2860 } else {
bb270c08
DB
2861 if (p[0] == '-') {
2862 negative = 1;
2863 ++p;
2864 }
f71869a4 2865 q = small_strptime(p, time_fmt[0], &dt);
916c80e9
FB
2866 if (!q) {
2867 dt.tm_sec = strtol(p, (char **)&q, 10);
2868 dt.tm_min = 0;
2869 dt.tm_hour = 0;
c5510dd6
PG
2870 }
2871 }
2872
2873 /* Now we have all the fields that we can get */
2874 if (!q) {
2875 if (duration)
2876 return 0;
2877 else
0c1a9eda 2878 return now * int64_t_C(1000000);
de6d9b64 2879 }
2dbceb9f
PG
2880
2881 if (duration) {
c5510dd6 2882 t = dt.tm_hour * 3600 + dt.tm_min * 60 + dt.tm_sec;
2dbceb9f 2883 } else {
c5510dd6
PG
2884 dt.tm_isdst = -1; /* unknown */
2885 if (is_utc) {
2886 t = mktimegm(&dt);
2887 } else {
2888 t = mktime(&dt);
2889 }
de6d9b64 2890 }
2dbceb9f 2891
c5510dd6
PG
2892 t *= 1000000;
2893
2894 if (*q == '.') {
de6d9b64 2895 int val, n;
c5510dd6
PG
2896 q++;
2897 for (val = 0, n = 100000; n >= 1; n /= 10, q++) {
115329f1 2898 if (!isdigit(*q))
c5510dd6
PG
2899 break;
2900 val += n * (*q - '0');
de6d9b64
FB
2901 }
2902 t += val;
2903 }
a6a92a9a 2904 return negative ? -t : t;
de6d9b64 2905}
ac44871c 2906#endif /* CONFIG_WINCE */
de6d9b64 2907
e36bdf8b
DK
2908/**
2909 * Attempts to find a specific tag in a URL.
2910 *
2911 * syntax: '?tag1=val1&tag2=val2...'. Little URL decoding is done.
2912 * Return 1 if found.
2913 */
de6d9b64
FB
2914int find_info_tag(char *arg, int arg_size, const char *tag1, const char *info)
2915{
2916 const char *p;
2917 char tag[128], *q;
2918
2919 p = info;
2920 if (*p == '?')
2921 p++;
2922 for(;;) {
2923 q = tag;
2924 while (*p != '\0' && *p != '=' && *p != '&') {
2925 if ((q - tag) < sizeof(tag) - 1)
2926 *q++ = *p;
2927 p++;
2928 }
2929 *q = '\0';
2930 q = arg;
2931 if (*p == '=') {
2932 p++;
2933 while (*p != '&' && *p != '\0') {
2dbceb9f
PG
2934 if ((q - arg) < arg_size - 1) {
2935 if (*p == '+')
2936 *q++ = ' ';
2937 else
2938 *q++ = *p;
2939 }
de6d9b64
FB
2940 p++;
2941 }
2942 *q = '\0';
2943 }
115329f1 2944 if (!strcmp(tag, tag1))
de6d9b64
FB
2945 return 1;
2946 if (*p != '&')
2947 break;
8d1335ea 2948 p++;
de6d9b64
FB
2949 }
2950 return 0;
2951}
2952
e36bdf8b
DK
2953/**
2954 * Returns in 'buf' the path with '%d' replaced by number.
2955 *
2956 * Also handles the '%0nd' format where 'n' is the total number
2957 * of digits and '%%'. Return 0 if OK, and -1 if format error.
2958 */
9150f42e
FB
2959int get_frame_filename(char *buf, int buf_size,
2960 const char *path, int number)
2961{
2962 const char *p;
0bf92f79
PI
2963 char *q, buf1[20], c;
2964 int nd, len, percentd_found;
9150f42e
FB
2965
2966 q = buf;
2967 p = path;
2968 percentd_found = 0;
2969 for(;;) {
2970 c = *p++;
2971 if (c == '\0')
2972 break;
2973 if (c == '%') {
c9646fda
PG
2974 do {
2975 nd = 0;
2976 while (isdigit(*p)) {
2977 nd = nd * 10 + *p++ - '0';
2978 }
2979 c = *p++;
c9646fda
PG
2980 } while (isdigit(c));
2981
9150f42e
FB
2982 switch(c) {
2983 case '%':
2984 goto addchar;
2985 case 'd':
2986 if (percentd_found)
2987 goto fail;
2988 percentd_found = 1;
2989 snprintf(buf1, sizeof(buf1), "%0*d", nd, number);
2990 len = strlen(buf1);
2991 if ((q - buf + len) > buf_size - 1)
2992 goto fail;
2993 memcpy(q, buf1, len);
2994 q += len;
2995 break;
2996 default:
2997 goto fail;
2998 }
2999 } else {
3000 addchar:
3001 if ((q - buf) < buf_size - 1)
3002 *q++ = c;
3003 }
3004 }
3005 if (!percentd_found)
3006 goto fail;
3007 *q = '\0';
3008 return 0;
3009 fail:
3010 *q = '\0';
3011 return -1;
3012}
3013
b9a281db 3014/**
fb2758c8
FB
3015 * Print nice hexa dump of a buffer
3016 * @param f stream for output
b9a281db
FB
3017 * @param buf buffer
3018 * @param size buffer size
3019 */
fb2758c8 3020void av_hex_dump(FILE *f, uint8_t *buf, int size)
b9a281db
FB
3021{
3022 int len, i, j, c;
3023
3024 for(i=0;i<size;i+=16) {
3025 len = size - i;
3026 if (len > 16)
3027 len = 16;
fb2758c8 3028 fprintf(f, "%08x ", i);
b9a281db
FB
3029 for(j=0;j<16;j++) {
3030 if (j < len)
fb2758c8 3031 fprintf(f, " %02x", buf[i+j]);
b9a281db 3032 else
fb2758c8 3033 fprintf(f, " ");
b9a281db 3034 }
fb2758c8 3035 fprintf(f, " ");
b9a281db
FB
3036 for(j=0;j<len;j++) {
3037 c = buf[i+j];
3038 if (c < ' ' || c > '~')
3039 c = '.';
fb2758c8 3040 fprintf(f, "%c", c);
b9a281db 3041 }
fb2758c8 3042 fprintf(f, "\n");
b9a281db
FB
3043 }
3044}
3045
fb2758c8
FB
3046/**
3047 * Print on 'f' a nice dump of a packet
3048 * @param f stream for output
3049 * @param pkt packet to dump
3050 * @param dump_payload true if the payload must be displayed too
3051 */
c0df9d75 3052 //FIXME needs to know the time_base
fb2758c8
FB
3053void av_pkt_dump(FILE *f, AVPacket *pkt, int dump_payload)
3054{
3055 fprintf(f, "stream #%d:\n", pkt->stream_index);
3056 fprintf(f, " keyframe=%d\n", ((pkt->flags & PKT_FLAG_KEY) != 0));
3057 fprintf(f, " duration=%0.3f\n", (double)pkt->duration / AV_TIME_BASE);
37353960
FB
3058 /* DTS is _always_ valid after av_read_frame() */
3059 fprintf(f, " dts=");
3060 if (pkt->dts == AV_NOPTS_VALUE)
3061 fprintf(f, "N/A");
3062 else
3063 fprintf(f, "%0.3f", (double)pkt->dts / AV_TIME_BASE);
fb2758c8
FB
3064 /* PTS may be not known if B frames are present */
3065 fprintf(f, " pts=");
3066 if (pkt->pts == AV_NOPTS_VALUE)
3067 fprintf(f, "N/A");
3068 else
3069 fprintf(f, "%0.3f", (double)pkt->pts / AV_TIME_BASE);
3070 fprintf(f, "\n");
3071 fprintf(f, " size=%d\n", pkt->size);
3072 if (dump_payload)
3073 av_hex_dump(f, pkt->data, pkt->size);
3074}
3075
a9a721da 3076void url_split(char *proto, int proto_size,
6ba5cbc6 3077 char *authorization, int authorization_size,
a9a721da
FB
3078 char *hostname, int hostname_size,
3079 int *port_ptr,
3080 char *path, int path_size,
3081 const char *url)
3082{
3083 const char *p;
3084 char *q;
3085 int port;
3086
3087 port = -1;
3088
3089 p = url;
3090 q = proto;
3091 while (*p != ':' && *p != '\0') {
3092 if ((q - proto) < proto_size - 1)
3093 *q++ = *p;
3094 p++;
3095 }
3096 if (proto_size > 0)
3097 *q = '\0';
6ba5cbc6
PD
3098 if (authorization_size > 0)
3099 authorization[0] = '\0';
a9a721da
FB
3100 if (*p == '\0') {
3101 if (proto_size > 0)
3102 proto[0] = '\0';
3103 if (hostname_size > 0)
3104 hostname[0] = '\0';
3105 p = url;
3106 } else {
6ba5cbc6
PD
3107 char *at,*slash; // PETR: position of '@' character and '/' character
3108
a9a721da
FB
3109 p++;
3110 if (*p == '/')
3111 p++;
3112 if (*p == '/')
3113 p++;
6ba5cbc6
PD
3114 at = strchr(p,'@'); // PETR: get the position of '@'
3115 slash = strchr(p,'/'); // PETR: get position of '/' - end of hostname
3116 if (at && slash && at > slash) at = NULL; // PETR: not interested in '@' behind '/'
3117
3118 q = at ? authorization : hostname; // PETR: if '@' exists starting with auth.
3119
3120 while ((at || *p != ':') && *p != '/' && *p != '?' && *p != '\0') { // PETR:
3121 if (*p == '@') { // PETR: passed '@'
3122 if (authorization_size > 0)
3123 *q = '\0';
3124 q = hostname;
3125 at = NULL;
3126 } else if (!at) { // PETR: hostname
3127 if ((q - hostname) < hostname_size - 1)
3128 *q++ = *p;
3129 } else {
3130 if ((q - authorization) < authorization_size - 1)
a9a721da 3131 *q++ = *p;
6ba5cbc6 3132 }
a9a721da
FB
3133 p++;
3134 }
3135 if (hostname_size > 0)
3136 *q = '\0';
3137 if (*p == ':') {
3138 p++;
3139 port = strtoul(p, (char **)&p, 10);
3140 }
3141 }
3142 if (port_ptr)
3143 *port_ptr = port;
3144 pstrcpy(path, path_size, p);
3145}
3146
916c80e9 3147/**
e36bdf8b
DK
3148 * Set the pts for a given stream.
3149 *
115329f1 3150 * @param s stream
916c80e9 3151 * @param pts_wrap_bits number of bits effectively used by the pts
115329f1
DB
3152 * (used for wrap control, 33 is the value for MPEG)
3153 * @param pts_num numerator to convert to seconds (MPEG: 1)
916c80e9
FB
3154 * @param pts_den denominator to convert to seconds (MPEG: 90000)
3155 */
9ee91c2f 3156void av_set_pts_info(AVStream *s, int pts_wrap_bits,
916c80e9
FB
3157 int pts_num, int pts_den)
3158{
3159 s->pts_wrap_bits = pts_wrap_bits;
9ee91c2f
MN
3160 s->time_base.num = pts_num;
3161 s->time_base.den = pts_den;
916c80e9
FB
3162}
3163
3164/* fraction handling */
3165
3166/**
e36bdf8b
DK
3167 * f = val + (num / den) + 0.5.
3168 *
3169 * 'num' is normalized so that it is such as 0 <= num < den.
916c80e9
FB
3170 *
3171 * @param f fractional number
3172 * @param val integer value
3173 * @param num must be >= 0
115329f1 3174 * @param den must be >= 1
916c80e9 3175 */
f3a30e3a 3176static void av_frac_init(AVFrac *f, int64_t val, int64_t num, int64_t den)
916c80e9
FB
3177{
3178 num += (den >> 1);
3179 if (num >= den) {
3180 val += num / den;
3181 num = num % den;
3182 }
3183 f->val = val;
3184 f->num = num;
3185 f->den = den;
3186}
3187
e36bdf8b
DK
3188/**
3189 * Set f to (val + 0.5).
3190 */
f3a30e3a 3191static void av_frac_set(AVFrac *f, int64_t val)
916c80e9
FB
3192{
3193 f->val = val;
3194 f->num = f->den >> 1;
3195}
3196
3197/**
e36bdf8b 3198 * Fractionnal addition to f: f = f + (incr / f->den).
916c80e9
FB
3199 *
3200 * @param f fractional number
3201 * @param incr increment, can be positive or negative
3202 */
f3a30e3a 3203static void av_frac_add(AVFrac *f, int64_t incr)
916c80e9 3204{
0c1a9eda 3205 int64_t num, den;
916c80e9
FB
3206
3207 num = f->num + incr;
3208 den = f->den;
3209 if (num < 0) {
3210 f->val += num / den;
3211 num = num % den;
3212 if (num < 0) {
3213 num += den;
3214 f->val--;
3215 }
3216 } else if (num >= den) {
3217 f->val += num / den;
3218 num = num % den;
3219 }
3220 f->num = num;
3221}
87a0a681
FB
3222
3223/**
3224 * register a new image format
3225 * @param img_fmt Image format descriptor
3226 */
3227void av_register_image_format(AVImageFormat *img_fmt)
3228{
3229 AVImageFormat **p;
3230
3231 p = &first_image_format;
3232 while (*p != NULL) p = &(*p)->next;
3233 *p = img_fmt;
3234 img_fmt->next = NULL;
3235}
3236
e36bdf8b
DK
3237/**
3238 * Guesses image format based on data in the image.
3239 */
87a0a681
FB
3240AVImageFormat *av_probe_image_format(AVProbeData *pd)
3241{
3242 AVImageFormat *fmt1, *fmt;
3243 int score, score_max;
3244
3245 fmt = NULL;
3246 score_max = 0;
3247 for(fmt1 = first_image_format; fmt1 != NULL; fmt1 = fmt1->next) {
3248 if (fmt1->img_probe) {
3249 score = fmt1->img_probe(pd);
3250 if (score > score_max) {
3251 score_max = score;
3252 fmt = fmt1;
3253 }
3254 }
3255 }
3256 return fmt;
3257}
3258
e36bdf8b
DK
3259/**
3260 * Guesses image format based on file name extensions.
3261 */
87a0a681
FB
3262AVImageFormat *guess_image_format(const char *filename)
3263{
3264 AVImageFormat *fmt1;
3265
3266 for(fmt1 = first_image_format; fmt1 != NULL; fmt1 = fmt1->next) {
3267 if (fmt1->extensions && match_ext(filename, fmt1->extensions))
3268 return fmt1;
3269 }
3270 return NULL;
3271}
3272
3273/**
115329f1 3274 * Read an image from a stream.
87a0a681
FB
3275 * @param gb byte stream containing the image
3276 * @param fmt image format, NULL if probing is required
3277 */
3278int av_read_image(ByteIOContext *pb, const char *filename,
3279 AVImageFormat *fmt,
3280 int (*alloc_cb)(void *, AVImageInfo *info), void *opaque)
3281{
a877eedc 3282 uint8_t buf[PROBE_BUF_MIN];
87a0a681
FB
3283 AVProbeData probe_data, *pd = &probe_data;
3284 offset_t pos;
3285 int ret;
3286
3287 if (!fmt) {
5c91a675 3288 pd->filename = filename;
87a0a681
FB
3289 pd->buf = buf;
3290 pos = url_ftell(pb);
a877eedc 3291 pd->buf_size = get_buffer(pb, buf, PROBE_BUF_MIN);
87a0a681
FB
3292 url_fseek(pb, pos, SEEK_SET);
3293 fmt = av_probe_image_format(pd);
3294 }
3295 if (!fmt)
3296 return AVERROR_NOFMT;
3297 ret = fmt->img_read(pb, alloc_cb, opaque);
3298 return ret;
3299}
3300
3301/**
3302 * Write an image to a stream.
3303 * @param pb byte stream for the image output
3304 * @param fmt image format
3305 * @param img image data and informations
3306 */
3307int av_write_image(ByteIOContext *pb, AVImageFormat *fmt, AVImageInfo *img)
3308{
3309 return fmt->img_write(pb, img);
3310}
3311