Minor Patch for shared libs on Mac OSX by (Bill May <wmay at cisco dot com>)
[libav.git] / libavformat / utils.c
1 /*
2 * Various utilities for ffmpeg system
3 * Copyright (c) 2000, 2001, 2002 Fabrice Bellard
4 *
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.
9 *
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
14 *
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
17 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18 */
19 #include "avformat.h"
20
21 #undef NDEBUG
22 #include <assert.h>
23
24 AVInputFormat *first_iformat = NULL;
25 AVOutputFormat *first_oformat = NULL;
26 AVImageFormat *first_image_format = NULL;
27
28 void av_register_input_format(AVInputFormat *format)
29 {
30 AVInputFormat **p;
31 p = &first_iformat;
32 while (*p != NULL) p = &(*p)->next;
33 *p = format;
34 format->next = NULL;
35 }
36
37 void av_register_output_format(AVOutputFormat *format)
38 {
39 AVOutputFormat **p;
40 p = &first_oformat;
41 while (*p != NULL) p = &(*p)->next;
42 *p = format;
43 format->next = NULL;
44 }
45
46 int match_ext(const char *filename, const char *extensions)
47 {
48 const char *ext, *p;
49 char ext1[32], *q;
50
51 if(!filename)
52 return 0;
53
54 ext = strrchr(filename, '.');
55 if (ext) {
56 ext++;
57 p = extensions;
58 for(;;) {
59 q = ext1;
60 while (*p != '\0' && *p != ',')
61 *q++ = *p++;
62 *q = '\0';
63 if (!strcasecmp(ext1, ext))
64 return 1;
65 if (*p == '\0')
66 break;
67 p++;
68 }
69 }
70 return 0;
71 }
72
73 AVOutputFormat *guess_format(const char *short_name, const char *filename,
74 const char *mime_type)
75 {
76 AVOutputFormat *fmt, *fmt_found;
77 int score_max, score;
78
79 /* specific test for image sequences */
80 if (!short_name && filename &&
81 filename_number_test(filename) >= 0 &&
82 guess_image_format(filename)) {
83 return guess_format("image", NULL, NULL);
84 }
85
86 /* find the proper file type */
87 fmt_found = NULL;
88 score_max = 0;
89 fmt = first_oformat;
90 while (fmt != NULL) {
91 score = 0;
92 if (fmt->name && short_name && !strcmp(fmt->name, short_name))
93 score += 100;
94 if (fmt->mime_type && mime_type && !strcmp(fmt->mime_type, mime_type))
95 score += 10;
96 if (filename && fmt->extensions &&
97 match_ext(filename, fmt->extensions)) {
98 score += 5;
99 }
100 if (score > score_max) {
101 score_max = score;
102 fmt_found = fmt;
103 }
104 fmt = fmt->next;
105 }
106 return fmt_found;
107 }
108
109 AVOutputFormat *guess_stream_format(const char *short_name, const char *filename,
110 const char *mime_type)
111 {
112 AVOutputFormat *fmt = guess_format(short_name, filename, mime_type);
113
114 if (fmt) {
115 AVOutputFormat *stream_fmt;
116 char stream_format_name[64];
117
118 snprintf(stream_format_name, sizeof(stream_format_name), "%s_stream", fmt->name);
119 stream_fmt = guess_format(stream_format_name, NULL, NULL);
120
121 if (stream_fmt)
122 fmt = stream_fmt;
123 }
124
125 return fmt;
126 }
127
128 AVInputFormat *av_find_input_format(const char *short_name)
129 {
130 AVInputFormat *fmt;
131 for(fmt = first_iformat; fmt != NULL; fmt = fmt->next) {
132 if (!strcmp(fmt->name, short_name))
133 return fmt;
134 }
135 return NULL;
136 }
137
138 /* memory handling */
139
140 /**
141 * Default packet destructor
142 */
143 static void av_destruct_packet(AVPacket *pkt)
144 {
145 av_free(pkt->data);
146 pkt->data = NULL; pkt->size = 0;
147 }
148
149 /**
150 * Allocate the payload of a packet and intialized its fields to default values.
151 *
152 * @param pkt packet
153 * @param size wanted payload size
154 * @return 0 if OK. AVERROR_xxx otherwise.
155 */
156 int av_new_packet(AVPacket *pkt, int size)
157 {
158 void *data = av_malloc(size + FF_INPUT_BUFFER_PADDING_SIZE);
159 if (!data)
160 return AVERROR_NOMEM;
161 memset(data + size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
162
163 av_init_packet(pkt);
164 pkt->data = data;
165 pkt->size = size;
166 pkt->destruct = av_destruct_packet;
167 return 0;
168 }
169
170 /* This is a hack - the packet memory allocation stuff is broken. The
171 packet is allocated if it was not really allocated */
172 int av_dup_packet(AVPacket *pkt)
173 {
174 if (pkt->destruct != av_destruct_packet) {
175 uint8_t *data;
176 /* we duplicate the packet and don't forget to put the padding
177 again */
178 data = av_malloc(pkt->size + FF_INPUT_BUFFER_PADDING_SIZE);
179 if (!data) {
180 return AVERROR_NOMEM;
181 }
182 memcpy(data, pkt->data, pkt->size);
183 memset(data + pkt->size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
184 pkt->data = data;
185 pkt->destruct = av_destruct_packet;
186 }
187 return 0;
188 }
189
190 /* fifo handling */
191
192 int fifo_init(FifoBuffer *f, int size)
193 {
194 f->buffer = av_malloc(size);
195 if (!f->buffer)
196 return -1;
197 f->end = f->buffer + size;
198 f->wptr = f->rptr = f->buffer;
199 return 0;
200 }
201
202 void fifo_free(FifoBuffer *f)
203 {
204 av_free(f->buffer);
205 }
206
207 int fifo_size(FifoBuffer *f, uint8_t *rptr)
208 {
209 int size;
210
211 if (f->wptr >= rptr) {
212 size = f->wptr - rptr;
213 } else {
214 size = (f->end - rptr) + (f->wptr - f->buffer);
215 }
216 return size;
217 }
218
219 /* get data from the fifo (return -1 if not enough data) */
220 int fifo_read(FifoBuffer *f, uint8_t *buf, int buf_size, uint8_t **rptr_ptr)
221 {
222 uint8_t *rptr = *rptr_ptr;
223 int size, len;
224
225 if (f->wptr >= rptr) {
226 size = f->wptr - rptr;
227 } else {
228 size = (f->end - rptr) + (f->wptr - f->buffer);
229 }
230
231 if (size < buf_size)
232 return -1;
233 while (buf_size > 0) {
234 len = f->end - rptr;
235 if (len > buf_size)
236 len = buf_size;
237 memcpy(buf, rptr, len);
238 buf += len;
239 rptr += len;
240 if (rptr >= f->end)
241 rptr = f->buffer;
242 buf_size -= len;
243 }
244 *rptr_ptr = rptr;
245 return 0;
246 }
247
248 void fifo_write(FifoBuffer *f, uint8_t *buf, int size, uint8_t **wptr_ptr)
249 {
250 int len;
251 uint8_t *wptr;
252 wptr = *wptr_ptr;
253 while (size > 0) {
254 len = f->end - wptr;
255 if (len > size)
256 len = size;
257 memcpy(wptr, buf, len);
258 wptr += len;
259 if (wptr >= f->end)
260 wptr = f->buffer;
261 buf += len;
262 size -= len;
263 }
264 *wptr_ptr = wptr;
265 }
266
267 int filename_number_test(const char *filename)
268 {
269 char buf[1024];
270 if(!filename)
271 return -1;
272 return get_frame_filename(buf, sizeof(buf), filename, 1);
273 }
274
275 /* guess file format */
276 AVInputFormat *av_probe_input_format(AVProbeData *pd, int is_opened)
277 {
278 AVInputFormat *fmt1, *fmt;
279 int score, score_max;
280
281 fmt = NULL;
282 score_max = 0;
283 for(fmt1 = first_iformat; fmt1 != NULL; fmt1 = fmt1->next) {
284 if (!is_opened && !(fmt1->flags & AVFMT_NOFILE))
285 continue;
286 score = 0;
287 if (fmt1->read_probe) {
288 score = fmt1->read_probe(pd);
289 } else if (fmt1->extensions) {
290 if (match_ext(pd->filename, fmt1->extensions)) {
291 score = 50;
292 }
293 }
294 if (score > score_max) {
295 score_max = score;
296 fmt = fmt1;
297 }
298 }
299 return fmt;
300 }
301
302 /************************************************************/
303 /* input media file */
304
305 /**
306 * open a media file from an IO stream. 'fmt' must be specified.
307 */
308
309 static const char* format_to_name(void* ptr)
310 {
311 AVFormatContext* fc = (AVFormatContext*) ptr;
312 if(fc->iformat) return fc->iformat->name;
313 else if(fc->oformat) return fc->oformat->name;
314 else return "NULL";
315 }
316
317 static const AVClass av_format_context_class = { "AVFormatContext", format_to_name };
318
319 AVFormatContext *av_alloc_format_context(void)
320 {
321 AVFormatContext *ic;
322 ic = av_mallocz(sizeof(AVFormatContext));
323 if (!ic) return ic;
324 ic->av_class = &av_format_context_class;
325 return ic;
326 }
327
328 int av_open_input_stream(AVFormatContext **ic_ptr,
329 ByteIOContext *pb, const char *filename,
330 AVInputFormat *fmt, AVFormatParameters *ap)
331 {
332 int err;
333 AVFormatContext *ic;
334
335 ic = av_alloc_format_context();
336 if (!ic) {
337 err = AVERROR_NOMEM;
338 goto fail;
339 }
340 ic->iformat = fmt;
341 if (pb)
342 ic->pb = *pb;
343 ic->duration = AV_NOPTS_VALUE;
344 ic->start_time = AV_NOPTS_VALUE;
345 pstrcpy(ic->filename, sizeof(ic->filename), filename);
346
347 /* allocate private data */
348 if (fmt->priv_data_size > 0) {
349 ic->priv_data = av_mallocz(fmt->priv_data_size);
350 if (!ic->priv_data) {
351 err = AVERROR_NOMEM;
352 goto fail;
353 }
354 } else {
355 ic->priv_data = NULL;
356 }
357
358 err = ic->iformat->read_header(ic, ap);
359 if (err < 0)
360 goto fail;
361
362 if (pb)
363 ic->data_offset = url_ftell(&ic->pb);
364
365 *ic_ptr = ic;
366 return 0;
367 fail:
368 if (ic) {
369 av_freep(&ic->priv_data);
370 }
371 av_free(ic);
372 *ic_ptr = NULL;
373 return err;
374 }
375
376 #define PROBE_BUF_SIZE 2048
377
378 /**
379 * Open a media file as input. The codec are not opened. Only the file
380 * header (if present) is read.
381 *
382 * @param ic_ptr the opened media file handle is put here
383 * @param filename filename to open.
384 * @param fmt if non NULL, force the file format to use
385 * @param buf_size optional buffer size (zero if default is OK)
386 * @param ap additionnal parameters needed when opening the file (NULL if default)
387 * @return 0 if OK. AVERROR_xxx otherwise.
388 */
389 int av_open_input_file(AVFormatContext **ic_ptr, const char *filename,
390 AVInputFormat *fmt,
391 int buf_size,
392 AVFormatParameters *ap)
393 {
394 int err, must_open_file, file_opened;
395 uint8_t buf[PROBE_BUF_SIZE];
396 AVProbeData probe_data, *pd = &probe_data;
397 ByteIOContext pb1, *pb = &pb1;
398
399 file_opened = 0;
400 pd->filename = "";
401 if (filename)
402 pd->filename = filename;
403 pd->buf = buf;
404 pd->buf_size = 0;
405
406 if (!fmt) {
407 /* guess format if no file can be opened */
408 fmt = av_probe_input_format(pd, 0);
409 }
410
411 /* do not open file if the format does not need it. XXX: specific
412 hack needed to handle RTSP/TCP */
413 must_open_file = 1;
414 if (fmt && (fmt->flags & AVFMT_NOFILE)) {
415 must_open_file = 0;
416 }
417
418 if (!fmt || must_open_file) {
419 /* if no file needed do not try to open one */
420 if (url_fopen(pb, filename, URL_RDONLY) < 0) {
421 err = AVERROR_IO;
422 goto fail;
423 }
424 file_opened = 1;
425 if (buf_size > 0) {
426 url_setbufsize(pb, buf_size);
427 }
428 if (!fmt) {
429 /* read probe data */
430 pd->buf_size = get_buffer(pb, buf, PROBE_BUF_SIZE);
431 if (url_fseek(pb, 0, SEEK_SET) == (offset_t)-EPIPE) {
432 url_fclose(pb);
433 if (url_fopen(pb, filename, URL_RDONLY) < 0) {
434 err = AVERROR_IO;
435 goto fail;
436 }
437 }
438 }
439 }
440
441 /* guess file format */
442 if (!fmt) {
443 fmt = av_probe_input_format(pd, 1);
444 }
445
446 /* if still no format found, error */
447 if (!fmt) {
448 err = AVERROR_NOFMT;
449 goto fail;
450 }
451
452 /* XXX: suppress this hack for redirectors */
453 #ifdef CONFIG_NETWORK
454 if (fmt == &redir_demux) {
455 err = redir_open(ic_ptr, pb);
456 url_fclose(pb);
457 return err;
458 }
459 #endif
460
461 /* check filename in case of an image number is expected */
462 if (fmt->flags & AVFMT_NEEDNUMBER) {
463 if (filename_number_test(filename) < 0) {
464 err = AVERROR_NUMEXPECTED;
465 goto fail;
466 }
467 }
468 err = av_open_input_stream(ic_ptr, pb, filename, fmt, ap);
469 if (err)
470 goto fail;
471 return 0;
472 fail:
473 if (file_opened)
474 url_fclose(pb);
475 *ic_ptr = NULL;
476 return err;
477
478 }
479
480 /*******************************************************/
481
482 /**
483 * Read a transport packet from a media file. This function is
484 * absolete and should never be used. Use av_read_frame() instead.
485 *
486 * @param s media file handle
487 * @param pkt is filled
488 * @return 0 if OK. AVERROR_xxx if error.
489 */
490 int av_read_packet(AVFormatContext *s, AVPacket *pkt)
491 {
492 return s->iformat->read_packet(s, pkt);
493 }
494
495 /**********************************************************/
496
497 /* get the number of samples of an audio frame. Return (-1) if error */
498 static int get_audio_frame_size(AVCodecContext *enc, int size)
499 {
500 int frame_size;
501
502 if (enc->frame_size <= 1) {
503 /* specific hack for pcm codecs because no frame size is
504 provided */
505 switch(enc->codec_id) {
506 case CODEC_ID_PCM_S16LE:
507 case CODEC_ID_PCM_S16BE:
508 case CODEC_ID_PCM_U16LE:
509 case CODEC_ID_PCM_U16BE:
510 if (enc->channels == 0)
511 return -1;
512 frame_size = size / (2 * enc->channels);
513 break;
514 case CODEC_ID_PCM_S8:
515 case CODEC_ID_PCM_U8:
516 case CODEC_ID_PCM_MULAW:
517 case CODEC_ID_PCM_ALAW:
518 if (enc->channels == 0)
519 return -1;
520 frame_size = size / (enc->channels);
521 break;
522 default:
523 /* used for example by ADPCM codecs */
524 if (enc->bit_rate == 0)
525 return -1;
526 frame_size = (size * 8 * enc->sample_rate) / enc->bit_rate;
527 break;
528 }
529 } else {
530 frame_size = enc->frame_size;
531 }
532 return frame_size;
533 }
534
535
536 /* return the frame duration in seconds, return 0 if not available */
537 static void compute_frame_duration(int *pnum, int *pden, AVStream *st,
538 AVCodecParserContext *pc, AVPacket *pkt)
539 {
540 int frame_size;
541
542 *pnum = 0;
543 *pden = 0;
544 switch(st->codec.codec_type) {
545 case CODEC_TYPE_VIDEO:
546 *pnum = st->codec.frame_rate_base;
547 *pden = st->codec.frame_rate;
548 if (pc && pc->repeat_pict) {
549 *pden *= 2;
550 *pnum = (*pnum) * (2 + pc->repeat_pict);
551 }
552 break;
553 case CODEC_TYPE_AUDIO:
554 frame_size = get_audio_frame_size(&st->codec, pkt->size);
555 if (frame_size < 0)
556 break;
557 *pnum = frame_size;
558 *pden = st->codec.sample_rate;
559 break;
560 default:
561 break;
562 }
563 }
564
565 static int64_t lsb2full(int64_t lsb, int64_t last_ts, int lsb_bits){
566 int64_t mask = lsb_bits < 64 ? (1LL<<lsb_bits)-1 : -1LL;
567 int64_t delta= last_ts - mask/2;
568 return ((lsb - delta)&mask) + delta;
569 }
570
571 static void compute_pkt_fields(AVFormatContext *s, AVStream *st,
572 AVCodecParserContext *pc, AVPacket *pkt)
573 {
574 int num, den, presentation_delayed;
575
576 /* handle wrapping */
577 if(st->cur_dts != AV_NOPTS_VALUE){
578 if(pkt->pts != AV_NOPTS_VALUE)
579 pkt->pts= lsb2full(pkt->pts, st->cur_dts, st->pts_wrap_bits);
580 if(pkt->dts != AV_NOPTS_VALUE)
581 pkt->dts= lsb2full(pkt->dts, st->cur_dts, st->pts_wrap_bits);
582 }
583
584 if (pkt->duration == 0) {
585 compute_frame_duration(&num, &den, st, pc, pkt);
586 if (den && num) {
587 pkt->duration = av_rescale(1, num * (int64_t)st->time_base.den, den * (int64_t)st->time_base.num);
588 }
589 }
590
591 /* do we have a video B frame ? */
592 presentation_delayed = 0;
593 if (st->codec.codec_type == CODEC_TYPE_VIDEO) {
594 /* XXX: need has_b_frame, but cannot get it if the codec is
595 not initialized */
596 if ((st->codec.codec_id == CODEC_ID_MPEG1VIDEO ||
597 st->codec.codec_id == CODEC_ID_MPEG2VIDEO ||
598 st->codec.codec_id == CODEC_ID_MPEG4 ||
599 st->codec.codec_id == CODEC_ID_H264) &&
600 pc && pc->pict_type != FF_B_TYPE)
601 presentation_delayed = 1;
602 /* this may be redundant, but it shouldnt hurt */
603 if(pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE && pkt->pts > pkt->dts)
604 presentation_delayed = 1;
605 }
606
607 if(st->cur_dts == AV_NOPTS_VALUE){
608 if(presentation_delayed) st->cur_dts = -pkt->duration;
609 else st->cur_dts = 0;
610 }
611
612 // 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);
613 /* interpolate PTS and DTS if they are not present */
614 if (presentation_delayed) {
615 /* DTS = decompression time stamp */
616 /* PTS = presentation time stamp */
617 if (pkt->dts == AV_NOPTS_VALUE) {
618 /* if we know the last pts, use it */
619 if(st->last_IP_pts != AV_NOPTS_VALUE)
620 st->cur_dts = pkt->dts = st->last_IP_pts;
621 else
622 pkt->dts = st->cur_dts;
623 } else {
624 st->cur_dts = pkt->dts;
625 }
626 /* this is tricky: the dts must be incremented by the duration
627 of the frame we are displaying, i.e. the last I or P frame */
628 if (st->last_IP_duration == 0)
629 st->cur_dts += pkt->duration;
630 else
631 st->cur_dts += st->last_IP_duration;
632 st->last_IP_duration = pkt->duration;
633 st->last_IP_pts= pkt->pts;
634 /* cannot compute PTS if not present (we can compute it only
635 by knowing the futur */
636 } else {
637 /* presentation is not delayed : PTS and DTS are the same */
638 if (pkt->pts == AV_NOPTS_VALUE) {
639 if (pkt->dts == AV_NOPTS_VALUE) {
640 pkt->pts = st->cur_dts;
641 pkt->dts = st->cur_dts;
642 }
643 else {
644 st->cur_dts = pkt->dts;
645 pkt->pts = pkt->dts;
646 }
647 } else {
648 st->cur_dts = pkt->pts;
649 pkt->dts = pkt->pts;
650 }
651 st->cur_dts += pkt->duration;
652 }
653 // 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);
654
655 /* update flags */
656 if (pc) {
657 pkt->flags = 0;
658 /* key frame computation */
659 switch(st->codec.codec_type) {
660 case CODEC_TYPE_VIDEO:
661 if (pc->pict_type == FF_I_TYPE)
662 pkt->flags |= PKT_FLAG_KEY;
663 break;
664 case CODEC_TYPE_AUDIO:
665 pkt->flags |= PKT_FLAG_KEY;
666 break;
667 default:
668 break;
669 }
670 }
671
672 /* convert the packet time stamp units */
673 if(pkt->pts != AV_NOPTS_VALUE)
674 pkt->pts = av_rescale(pkt->pts, AV_TIME_BASE * (int64_t)st->time_base.num, st->time_base.den);
675 if(pkt->dts != AV_NOPTS_VALUE)
676 pkt->dts = av_rescale(pkt->dts, AV_TIME_BASE * (int64_t)st->time_base.num, st->time_base.den);
677
678 /* duration field */
679 pkt->duration = av_rescale(pkt->duration, AV_TIME_BASE * (int64_t)st->time_base.num, st->time_base.den);
680 }
681
682 static void av_destruct_packet_nofree(AVPacket *pkt)
683 {
684 pkt->data = NULL; pkt->size = 0;
685 }
686
687 static int av_read_frame_internal(AVFormatContext *s, AVPacket *pkt)
688 {
689 AVStream *st;
690 int len, ret, i;
691
692 for(;;) {
693 /* select current input stream component */
694 st = s->cur_st;
695 if (st) {
696 if (!st->parser) {
697 /* no parsing needed: we just output the packet as is */
698 /* raw data support */
699 *pkt = s->cur_pkt;
700 compute_pkt_fields(s, st, NULL, pkt);
701 s->cur_st = NULL;
702 return 0;
703 } else if (s->cur_len > 0) {
704 len = av_parser_parse(st->parser, &st->codec, &pkt->data, &pkt->size,
705 s->cur_ptr, s->cur_len,
706 s->cur_pkt.pts, s->cur_pkt.dts);
707 s->cur_pkt.pts = AV_NOPTS_VALUE;
708 s->cur_pkt.dts = AV_NOPTS_VALUE;
709 /* increment read pointer */
710 s->cur_ptr += len;
711 s->cur_len -= len;
712
713 /* return packet if any */
714 if (pkt->size) {
715 got_packet:
716 pkt->duration = 0;
717 pkt->stream_index = st->index;
718 pkt->pts = st->parser->pts;
719 pkt->dts = st->parser->dts;
720 pkt->destruct = av_destruct_packet_nofree;
721 compute_pkt_fields(s, st, st->parser, pkt);
722 return 0;
723 }
724 } else {
725 /* free packet */
726 av_free_packet(&s->cur_pkt);
727 s->cur_st = NULL;
728 }
729 } else {
730 /* read next packet */
731 ret = av_read_packet(s, &s->cur_pkt);
732 if (ret < 0) {
733 if (ret == -EAGAIN)
734 return ret;
735 /* return the last frames, if any */
736 for(i = 0; i < s->nb_streams; i++) {
737 st = s->streams[i];
738 if (st->parser) {
739 av_parser_parse(st->parser, &st->codec,
740 &pkt->data, &pkt->size,
741 NULL, 0,
742 AV_NOPTS_VALUE, AV_NOPTS_VALUE);
743 if (pkt->size)
744 goto got_packet;
745 }
746 }
747 /* no more packets: really terminates parsing */
748 return ret;
749 }
750
751 st = s->streams[s->cur_pkt.stream_index];
752
753 s->cur_st = st;
754 s->cur_ptr = s->cur_pkt.data;
755 s->cur_len = s->cur_pkt.size;
756 if (st->need_parsing && !st->parser) {
757 st->parser = av_parser_init(st->codec.codec_id);
758 if (!st->parser) {
759 /* no parser available : just output the raw packets */
760 st->need_parsing = 0;
761 }
762 }
763 }
764 }
765 }
766
767 /**
768 * Return the next frame of a stream. The returned packet is valid
769 * until the next av_read_frame() or until av_close_input_file() and
770 * must be freed with av_free_packet. For video, the packet contains
771 * exactly one frame. For audio, it contains an integer number of
772 * frames if each frame has a known fixed size (e.g. PCM or ADPCM
773 * data). If the audio frames have a variable size (e.g. MPEG audio),
774 * then it contains one frame.
775 *
776 * pkt->pts, pkt->dts and pkt->duration are always set to correct
777 * values in AV_TIME_BASE unit (and guessed if the format cannot
778 * provided them). pkt->pts can be AV_NOPTS_VALUE if the video format
779 * has B frames, so it is better to rely on pkt->dts if you do not
780 * decompress the payload.
781 *
782 * Return 0 if OK, < 0 if error or end of file.
783 */
784 int av_read_frame(AVFormatContext *s, AVPacket *pkt)
785 {
786 AVPacketList *pktl;
787
788 pktl = s->packet_buffer;
789 if (pktl) {
790 /* read packet from packet buffer, if there is data */
791 *pkt = pktl->pkt;
792 s->packet_buffer = pktl->next;
793 av_free(pktl);
794 return 0;
795 } else {
796 return av_read_frame_internal(s, pkt);
797 }
798 }
799
800 /* XXX: suppress the packet queue */
801 static void flush_packet_queue(AVFormatContext *s)
802 {
803 AVPacketList *pktl;
804
805 for(;;) {
806 pktl = s->packet_buffer;
807 if (!pktl)
808 break;
809 s->packet_buffer = pktl->next;
810 av_free_packet(&pktl->pkt);
811 av_free(pktl);
812 }
813 }
814
815 /*******************************************************/
816 /* seek support */
817
818 int av_find_default_stream_index(AVFormatContext *s)
819 {
820 int i;
821 AVStream *st;
822
823 if (s->nb_streams <= 0)
824 return -1;
825 for(i = 0; i < s->nb_streams; i++) {
826 st = s->streams[i];
827 if (st->codec.codec_type == CODEC_TYPE_VIDEO) {
828 return i;
829 }
830 }
831 return 0;
832 }
833
834 /* flush the frame reader */
835 static void av_read_frame_flush(AVFormatContext *s)
836 {
837 AVStream *st;
838 int i;
839
840 flush_packet_queue(s);
841
842 /* free previous packet */
843 if (s->cur_st) {
844 if (s->cur_st->parser)
845 av_free_packet(&s->cur_pkt);
846 s->cur_st = NULL;
847 }
848 /* fail safe */
849 s->cur_ptr = NULL;
850 s->cur_len = 0;
851
852 /* for each stream, reset read state */
853 for(i = 0; i < s->nb_streams; i++) {
854 st = s->streams[i];
855
856 if (st->parser) {
857 av_parser_close(st->parser);
858 st->parser = NULL;
859 }
860 st->last_IP_pts = AV_NOPTS_VALUE;
861 st->cur_dts = 0; /* we set the current DTS to an unspecified origin */
862 }
863 }
864
865 /**
866 * add a index entry into a sorted list updateing if it is already there.
867 * @param timestamp timestamp in the timebase of the given stream
868 */
869 int av_add_index_entry(AVStream *st,
870 int64_t pos, int64_t timestamp, int distance, int flags)
871 {
872 AVIndexEntry *entries, *ie;
873 int index;
874
875 entries = av_fast_realloc(st->index_entries,
876 &st->index_entries_allocated_size,
877 (st->nb_index_entries + 1) *
878 sizeof(AVIndexEntry));
879 st->index_entries= entries;
880
881 if(st->nb_index_entries){
882 index= av_index_search_timestamp(st, timestamp);
883 ie= &entries[index];
884
885 if(ie->timestamp != timestamp){
886 if(ie->timestamp < timestamp){
887 index++; //index points to next instead of previous entry, maybe nonexistant
888 ie= &st->index_entries[index];
889 }else
890 assert(index==0);
891
892 if(index != st->nb_index_entries){
893 assert(index < st->nb_index_entries);
894 memmove(entries + index + 1, entries + index, sizeof(AVIndexEntry)*(st->nb_index_entries - index));
895 }
896 st->nb_index_entries++;
897 }else{
898 if(ie->pos == pos && distance < ie->min_distance) //dont reduce the distance
899 distance= ie->min_distance;
900 }
901 }else{
902 index= st->nb_index_entries++;
903 ie= &entries[index];
904 }
905
906 ie->pos = pos;
907 ie->timestamp = timestamp;
908 ie->min_distance= distance;
909 ie->flags = flags;
910
911 return index;
912 }
913
914 /* build an index for raw streams using a parser */
915 static void av_build_index_raw(AVFormatContext *s)
916 {
917 AVPacket pkt1, *pkt = &pkt1;
918 int ret;
919 AVStream *st;
920
921 st = s->streams[0];
922 av_read_frame_flush(s);
923 url_fseek(&s->pb, s->data_offset, SEEK_SET);
924
925 for(;;) {
926 ret = av_read_frame(s, pkt);
927 if (ret < 0)
928 break;
929 if (pkt->stream_index == 0 && st->parser &&
930 (pkt->flags & PKT_FLAG_KEY)) {
931 int64_t dts= av_rescale(pkt->dts, st->time_base.den, AV_TIME_BASE*(int64_t)st->time_base.num);
932 av_add_index_entry(st, st->parser->frame_offset, dts,
933 0, AVINDEX_KEYFRAME);
934 }
935 av_free_packet(pkt);
936 }
937 }
938
939 /* return TRUE if we deal with a raw stream (raw codec data and
940 parsing needed) */
941 static int is_raw_stream(AVFormatContext *s)
942 {
943 AVStream *st;
944
945 if (s->nb_streams != 1)
946 return 0;
947 st = s->streams[0];
948 if (!st->need_parsing)
949 return 0;
950 return 1;
951 }
952
953 /* return the largest index entry whose timestamp is <=
954 wanted_timestamp */
955 int av_index_search_timestamp(AVStream *st, int wanted_timestamp)
956 {
957 AVIndexEntry *entries= st->index_entries;
958 int nb_entries= st->nb_index_entries;
959 int a, b, m;
960 int64_t timestamp;
961
962 if (nb_entries <= 0)
963 return -1;
964
965 a = 0;
966 b = nb_entries - 1;
967
968 while (a < b) {
969 m = (a + b + 1) >> 1;
970 timestamp = entries[m].timestamp;
971 if (timestamp > wanted_timestamp) {
972 b = m - 1;
973 } else {
974 a = m;
975 }
976 }
977 return a;
978 }
979
980 #define DEBUG_SEEK
981
982 /**
983 * Does a binary search using av_index_search_timestamp() and AVCodec.read_timestamp().
984 * this isnt supposed to be called directly by a user application, but by demuxers
985 * @param target_ts target timestamp in the time base of the given stream
986 * @param stream_index stream number
987 */
988 int av_seek_frame_binary(AVFormatContext *s, int stream_index, int64_t target_ts){
989 AVInputFormat *avif= s->iformat;
990 int64_t pos_min, pos_max, pos, pos_limit;
991 int64_t ts_min, ts_max, ts;
992 int64_t start_pos;
993 int index, no_change, i;
994 AVStream *st;
995
996 if (stream_index < 0)
997 return -1;
998
999 #ifdef DEBUG_SEEK
1000 av_log(s, AV_LOG_DEBUG, "read_seek: %d %lld\n", stream_index, target_ts);
1001 #endif
1002
1003 ts_max=
1004 ts_min= AV_NOPTS_VALUE;
1005 pos_limit= -1; //gcc falsely says it may be uninitalized
1006
1007 st= s->streams[stream_index];
1008 if(st->index_entries){
1009 AVIndexEntry *e;
1010
1011 index= av_index_search_timestamp(st, target_ts);
1012 e= &st->index_entries[index];
1013
1014 if(e->timestamp <= target_ts || e->pos == e->min_distance){
1015 pos_min= e->pos;
1016 ts_min= e->timestamp;
1017 #ifdef DEBUG_SEEK
1018 av_log(s, AV_LOG_DEBUG, "using cached pos_min=0x%llx dts_min=%lld\n",
1019 pos_min,ts_min);
1020 #endif
1021 }else{
1022 assert(index==0);
1023 }
1024 index++;
1025 if(index < st->nb_index_entries){
1026 e= &st->index_entries[index];
1027 assert(e->timestamp >= target_ts);
1028 pos_max= e->pos;
1029 ts_max= e->timestamp;
1030 pos_limit= pos_max - e->min_distance;
1031 #ifdef DEBUG_SEEK
1032 av_log(s, AV_LOG_DEBUG, "using cached pos_max=0x%llx pos_limit=0x%llx dts_max=%lld\n",
1033 pos_max,pos_limit, ts_max);
1034 #endif
1035 }
1036 }
1037
1038 if(ts_min == AV_NOPTS_VALUE){
1039 pos_min = s->data_offset;
1040 ts_min = avif->read_timestamp(s, stream_index, &pos_min, INT64_MAX);
1041 if (ts_min == AV_NOPTS_VALUE)
1042 return -1;
1043 }
1044
1045 if(ts_max == AV_NOPTS_VALUE){
1046 int step= 1024;
1047 pos_max = url_filesize(url_fileno(&s->pb)) - 1;
1048 do{
1049 pos_max -= step;
1050 ts_max = avif->read_timestamp(s, stream_index, &pos_max, pos_max + step);
1051 step += step;
1052 }while(ts_max == AV_NOPTS_VALUE && pos_max >= step);
1053 if (ts_max == AV_NOPTS_VALUE)
1054 return -1;
1055
1056 for(;;){
1057 int64_t tmp_pos= pos_max + 1;
1058 int64_t tmp_ts= avif->read_timestamp(s, stream_index, &tmp_pos, INT64_MAX);
1059 if(tmp_ts == AV_NOPTS_VALUE)
1060 break;
1061 ts_max= tmp_ts;
1062 pos_max= tmp_pos;
1063 }
1064 pos_limit= pos_max;
1065 }
1066
1067 no_change=0;
1068 while (pos_min < pos_limit) {
1069 #ifdef DEBUG_SEEK
1070 av_log(s, AV_LOG_DEBUG, "pos_min=0x%llx pos_max=0x%llx dts_min=%lld dts_max=%lld\n",
1071 pos_min, pos_max,
1072 ts_min, ts_max);
1073 #endif
1074 assert(pos_limit <= pos_max);
1075
1076 if(no_change==0){
1077 int64_t approximate_keyframe_distance= pos_max - pos_limit;
1078 // interpolate position (better than dichotomy)
1079 pos = (int64_t)((double)(pos_max - pos_min) *
1080 (double)(target_ts - ts_min) /
1081 (double)(ts_max - ts_min)) + pos_min - approximate_keyframe_distance;
1082 }else if(no_change==1){
1083 // bisection, if interpolation failed to change min or max pos last time
1084 pos = (pos_min + pos_limit)>>1;
1085 }else{
1086 // linear search if bisection failed, can only happen if there are very few or no keframes between min/max
1087 pos=pos_min;
1088 }
1089 if(pos <= pos_min)
1090 pos= pos_min + 1;
1091 else if(pos > pos_limit)
1092 pos= pos_limit;
1093 start_pos= pos;
1094
1095 ts = avif->read_timestamp(s, stream_index, &pos, INT64_MAX); //may pass pos_limit instead of -1
1096 if(pos == pos_max)
1097 no_change++;
1098 else
1099 no_change=0;
1100 #ifdef DEBUG_SEEK
1101 av_log(s, AV_LOG_DEBUG, "%Ld %Ld %Ld / %Ld %Ld %Ld target:%Ld limit:%Ld start:%Ld noc:%d\n", pos_min, pos, pos_max, ts_min, ts, ts_max, target_ts, pos_limit, start_pos, no_change);
1102 #endif
1103 assert(ts != AV_NOPTS_VALUE);
1104 if (target_ts < ts) {
1105 pos_limit = start_pos - 1;
1106 pos_max = pos;
1107 ts_max = ts;
1108 } else {
1109 pos_min = pos;
1110 ts_min = ts;
1111 /* check if we are lucky */
1112 if (target_ts == ts)
1113 break;
1114 }
1115 }
1116
1117 pos = pos_min;
1118 #ifdef DEBUG_SEEK
1119 pos_min = pos;
1120 ts_min = avif->read_timestamp(s, stream_index, &pos_min, INT64_MAX);
1121 pos_min++;
1122 ts_max = avif->read_timestamp(s, stream_index, &pos_min, INT64_MAX);
1123 av_log(s, AV_LOG_DEBUG, "pos=0x%llx %lld<=%lld<=%lld\n",
1124 pos, ts_min, target_ts, ts_max);
1125 #endif
1126 /* do the seek */
1127 url_fseek(&s->pb, pos, SEEK_SET);
1128
1129 ts= av_rescale(ts_min, AV_TIME_BASE*(int64_t)st->time_base.num, st->time_base.den);
1130 for(i = 0; i < s->nb_streams; i++) {
1131 st = s->streams[i];
1132
1133 st->cur_dts = av_rescale(ts, st->time_base.den, AV_TIME_BASE*(int64_t)st->time_base.num);
1134 }
1135
1136 return 0;
1137 }
1138
1139 static int av_seek_frame_generic(AVFormatContext *s,
1140 int stream_index, int64_t timestamp)
1141 {
1142 int index, i;
1143 AVStream *st;
1144 AVIndexEntry *ie;
1145
1146 if (!s->index_built) {
1147 if (is_raw_stream(s)) {
1148 av_build_index_raw(s);
1149 } else {
1150 return -1;
1151 }
1152 s->index_built = 1;
1153 }
1154
1155 st = s->streams[stream_index];
1156 index = av_index_search_timestamp(st, timestamp);
1157 if (index < 0)
1158 return -1;
1159
1160 /* now we have found the index, we can seek */
1161 ie = &st->index_entries[index];
1162 av_read_frame_flush(s);
1163 url_fseek(&s->pb, ie->pos, SEEK_SET);
1164
1165 timestamp= av_rescale(ie->timestamp, AV_TIME_BASE*(int64_t)st->time_base.num, st->time_base.den);
1166 for(i = 0; i < s->nb_streams; i++) {
1167 st = s->streams[i];
1168
1169 st->cur_dts = av_rescale(timestamp, st->time_base.den, AV_TIME_BASE*(int64_t)st->time_base.num);
1170 }
1171
1172 return 0;
1173 }
1174
1175 /**
1176 * Seek to the key frame just before the frame at timestamp
1177 * 'timestamp' in 'stream_index'.
1178 * @param stream_index If stream_index is (-1), a default
1179 * stream is selected
1180 * @param timestamp timestamp in AV_TIME_BASE units
1181 * @return >= 0 on success
1182 */
1183 int av_seek_frame(AVFormatContext *s, int stream_index, int64_t timestamp)
1184 {
1185 int ret;
1186 AVStream *st;
1187
1188 av_read_frame_flush(s);
1189
1190 if(stream_index < 0){
1191 stream_index= av_find_default_stream_index(s);
1192 if(stream_index < 0)
1193 return -1;
1194 }
1195 st= s->streams[stream_index];
1196
1197 timestamp = av_rescale(timestamp, st->time_base.den, AV_TIME_BASE * (int64_t)st->time_base.num);
1198
1199 /* first, we try the format specific seek */
1200 if (s->iformat->read_seek)
1201 ret = s->iformat->read_seek(s, stream_index, timestamp);
1202 else
1203 ret = -1;
1204 if (ret >= 0) {
1205 return 0;
1206 }
1207
1208 if(s->iformat->read_timestamp)
1209 return av_seek_frame_binary(s, stream_index, timestamp);
1210 else
1211 return av_seek_frame_generic(s, stream_index, timestamp);
1212 }
1213
1214 /*******************************************************/
1215
1216 /* return TRUE if the stream has accurate timings for at least one component */
1217 static int av_has_timings(AVFormatContext *ic)
1218 {
1219 int i;
1220 AVStream *st;
1221
1222 for(i = 0;i < ic->nb_streams; i++) {
1223 st = ic->streams[i];
1224 if (st->start_time != AV_NOPTS_VALUE &&
1225 st->duration != AV_NOPTS_VALUE)
1226 return 1;
1227 }
1228 return 0;
1229 }
1230
1231 /* estimate the stream timings from the one of each components. Also
1232 compute the global bitrate if possible */
1233 static void av_update_stream_timings(AVFormatContext *ic)
1234 {
1235 int64_t start_time, end_time, end_time1;
1236 int i;
1237 AVStream *st;
1238
1239 start_time = MAXINT64;
1240 end_time = MININT64;
1241 for(i = 0;i < ic->nb_streams; i++) {
1242 st = ic->streams[i];
1243 if (st->start_time != AV_NOPTS_VALUE) {
1244 if (st->start_time < start_time)
1245 start_time = st->start_time;
1246 if (st->duration != AV_NOPTS_VALUE) {
1247 end_time1 = st->start_time + st->duration;
1248 if (end_time1 > end_time)
1249 end_time = end_time1;
1250 }
1251 }
1252 }
1253 if (start_time != MAXINT64) {
1254 ic->start_time = start_time;
1255 if (end_time != MAXINT64) {
1256 ic->duration = end_time - start_time;
1257 if (ic->file_size > 0) {
1258 /* compute the bit rate */
1259 ic->bit_rate = (double)ic->file_size * 8.0 * AV_TIME_BASE /
1260 (double)ic->duration;
1261 }
1262 }
1263 }
1264
1265 }
1266
1267 static void fill_all_stream_timings(AVFormatContext *ic)
1268 {
1269 int i;
1270 AVStream *st;
1271
1272 av_update_stream_timings(ic);
1273 for(i = 0;i < ic->nb_streams; i++) {
1274 st = ic->streams[i];
1275 if (st->start_time == AV_NOPTS_VALUE) {
1276 st->start_time = ic->start_time;
1277 st->duration = ic->duration;
1278 }
1279 }
1280 }
1281
1282 static void av_estimate_timings_from_bit_rate(AVFormatContext *ic)
1283 {
1284 int64_t filesize, duration;
1285 int bit_rate, i;
1286 AVStream *st;
1287
1288 /* if bit_rate is already set, we believe it */
1289 if (ic->bit_rate == 0) {
1290 bit_rate = 0;
1291 for(i=0;i<ic->nb_streams;i++) {
1292 st = ic->streams[i];
1293 bit_rate += st->codec.bit_rate;
1294 }
1295 ic->bit_rate = bit_rate;
1296 }
1297
1298 /* if duration is already set, we believe it */
1299 if (ic->duration == AV_NOPTS_VALUE &&
1300 ic->bit_rate != 0 &&
1301 ic->file_size != 0) {
1302 filesize = ic->file_size;
1303 if (filesize > 0) {
1304 duration = (int64_t)((8 * AV_TIME_BASE * (double)filesize) / (double)ic->bit_rate);
1305 for(i = 0; i < ic->nb_streams; i++) {
1306 st = ic->streams[i];
1307 if (st->start_time == AV_NOPTS_VALUE ||
1308 st->duration == AV_NOPTS_VALUE) {
1309 st->start_time = 0;
1310 st->duration = duration;
1311 }
1312 }
1313 }
1314 }
1315 }
1316
1317 #define DURATION_MAX_READ_SIZE 250000
1318
1319 /* only usable for MPEG-PS streams */
1320 static void av_estimate_timings_from_pts(AVFormatContext *ic)
1321 {
1322 AVPacket pkt1, *pkt = &pkt1;
1323 AVStream *st;
1324 int read_size, i, ret;
1325 int64_t start_time, end_time, end_time1;
1326 int64_t filesize, offset, duration;
1327
1328 /* free previous packet */
1329 if (ic->cur_st && ic->cur_st->parser)
1330 av_free_packet(&ic->cur_pkt);
1331 ic->cur_st = NULL;
1332
1333 /* flush packet queue */
1334 flush_packet_queue(ic);
1335
1336 for(i=0;i<ic->nb_streams;i++) {
1337 st = ic->streams[i];
1338 if (st->parser) {
1339 av_parser_close(st->parser);
1340 st->parser= NULL;
1341 }
1342 }
1343
1344 /* we read the first packets to get the first PTS (not fully
1345 accurate, but it is enough now) */
1346 url_fseek(&ic->pb, 0, SEEK_SET);
1347 read_size = 0;
1348 for(;;) {
1349 if (read_size >= DURATION_MAX_READ_SIZE)
1350 break;
1351 /* if all info is available, we can stop */
1352 for(i = 0;i < ic->nb_streams; i++) {
1353 st = ic->streams[i];
1354 if (st->start_time == AV_NOPTS_VALUE)
1355 break;
1356 }
1357 if (i == ic->nb_streams)
1358 break;
1359
1360 ret = av_read_packet(ic, pkt);
1361 if (ret != 0)
1362 break;
1363 read_size += pkt->size;
1364 st = ic->streams[pkt->stream_index];
1365 if (pkt->pts != AV_NOPTS_VALUE) {
1366 if (st->start_time == AV_NOPTS_VALUE)
1367 st->start_time = av_rescale(pkt->pts, st->time_base.num * (int64_t)AV_TIME_BASE, st->time_base.den);
1368 }
1369 av_free_packet(pkt);
1370 }
1371
1372 /* we compute the minimum start_time and use it as default */
1373 start_time = MAXINT64;
1374 for(i = 0; i < ic->nb_streams; i++) {
1375 st = ic->streams[i];
1376 if (st->start_time != AV_NOPTS_VALUE &&
1377 st->start_time < start_time)
1378 start_time = st->start_time;
1379 }
1380 if (start_time != MAXINT64)
1381 ic->start_time = start_time;
1382
1383 /* estimate the end time (duration) */
1384 /* XXX: may need to support wrapping */
1385 filesize = ic->file_size;
1386 offset = filesize - DURATION_MAX_READ_SIZE;
1387 if (offset < 0)
1388 offset = 0;
1389
1390 url_fseek(&ic->pb, offset, SEEK_SET);
1391 read_size = 0;
1392 for(;;) {
1393 if (read_size >= DURATION_MAX_READ_SIZE)
1394 break;
1395 /* if all info is available, we can stop */
1396 for(i = 0;i < ic->nb_streams; i++) {
1397 st = ic->streams[i];
1398 if (st->duration == AV_NOPTS_VALUE)
1399 break;
1400 }
1401 if (i == ic->nb_streams)
1402 break;
1403
1404 ret = av_read_packet(ic, pkt);
1405 if (ret != 0)
1406 break;
1407 read_size += pkt->size;
1408 st = ic->streams[pkt->stream_index];
1409 if (pkt->pts != AV_NOPTS_VALUE) {
1410 end_time = av_rescale(pkt->pts, st->time_base.num * (int64_t)AV_TIME_BASE, st->time_base.den);
1411 duration = end_time - st->start_time;
1412 if (duration > 0) {
1413 if (st->duration == AV_NOPTS_VALUE ||
1414 st->duration < duration)
1415 st->duration = duration;
1416 }
1417 }
1418 av_free_packet(pkt);
1419 }
1420
1421 /* estimate total duration */
1422 end_time = MININT64;
1423 for(i = 0;i < ic->nb_streams; i++) {
1424 st = ic->streams[i];
1425 if (st->duration != AV_NOPTS_VALUE) {
1426 end_time1 = st->start_time + st->duration;
1427 if (end_time1 > end_time)
1428 end_time = end_time1;
1429 }
1430 }
1431
1432 /* update start_time (new stream may have been created, so we do
1433 it at the end */
1434 if (ic->start_time != AV_NOPTS_VALUE) {
1435 for(i = 0; i < ic->nb_streams; i++) {
1436 st = ic->streams[i];
1437 if (st->start_time == AV_NOPTS_VALUE)
1438 st->start_time = ic->start_time;
1439 }
1440 }
1441
1442 if (end_time != MININT64) {
1443 /* put dummy values for duration if needed */
1444 for(i = 0;i < ic->nb_streams; i++) {
1445 st = ic->streams[i];
1446 if (st->duration == AV_NOPTS_VALUE &&
1447 st->start_time != AV_NOPTS_VALUE)
1448 st->duration = end_time - st->start_time;
1449 }
1450 ic->duration = end_time - ic->start_time;
1451 }
1452
1453 url_fseek(&ic->pb, 0, SEEK_SET);
1454 }
1455
1456 static void av_estimate_timings(AVFormatContext *ic)
1457 {
1458 URLContext *h;
1459 int64_t file_size;
1460
1461 /* get the file size, if possible */
1462 if (ic->iformat->flags & AVFMT_NOFILE) {
1463 file_size = 0;
1464 } else {
1465 h = url_fileno(&ic->pb);
1466 file_size = url_filesize(h);
1467 if (file_size < 0)
1468 file_size = 0;
1469 }
1470 ic->file_size = file_size;
1471
1472 if (ic->iformat == &mpegps_demux) {
1473 /* get accurate estimate from the PTSes */
1474 av_estimate_timings_from_pts(ic);
1475 } else if (av_has_timings(ic)) {
1476 /* at least one components has timings - we use them for all
1477 the components */
1478 fill_all_stream_timings(ic);
1479 } else {
1480 /* less precise: use bit rate info */
1481 av_estimate_timings_from_bit_rate(ic);
1482 }
1483 av_update_stream_timings(ic);
1484
1485 #if 0
1486 {
1487 int i;
1488 AVStream *st;
1489 for(i = 0;i < ic->nb_streams; i++) {
1490 st = ic->streams[i];
1491 printf("%d: start_time: %0.3f duration: %0.3f\n",
1492 i, (double)st->start_time / AV_TIME_BASE,
1493 (double)st->duration / AV_TIME_BASE);
1494 }
1495 printf("stream: start_time: %0.3f duration: %0.3f bitrate=%d kb/s\n",
1496 (double)ic->start_time / AV_TIME_BASE,
1497 (double)ic->duration / AV_TIME_BASE,
1498 ic->bit_rate / 1000);
1499 }
1500 #endif
1501 }
1502
1503 static int has_codec_parameters(AVCodecContext *enc)
1504 {
1505 int val;
1506 switch(enc->codec_type) {
1507 case CODEC_TYPE_AUDIO:
1508 val = enc->sample_rate;
1509 break;
1510 case CODEC_TYPE_VIDEO:
1511 val = enc->width;
1512 break;
1513 default:
1514 val = 1;
1515 break;
1516 }
1517 return (val != 0);
1518 }
1519
1520 static int try_decode_frame(AVStream *st, const uint8_t *data, int size)
1521 {
1522 int16_t *samples;
1523 AVCodec *codec;
1524 int got_picture, ret;
1525 AVFrame picture;
1526
1527 codec = avcodec_find_decoder(st->codec.codec_id);
1528 if (!codec)
1529 return -1;
1530 ret = avcodec_open(&st->codec, codec);
1531 if (ret < 0)
1532 return ret;
1533 switch(st->codec.codec_type) {
1534 case CODEC_TYPE_VIDEO:
1535 ret = avcodec_decode_video(&st->codec, &picture,
1536 &got_picture, (uint8_t *)data, size);
1537 break;
1538 case CODEC_TYPE_AUDIO:
1539 samples = av_malloc(AVCODEC_MAX_AUDIO_FRAME_SIZE);
1540 if (!samples)
1541 goto fail;
1542 ret = avcodec_decode_audio(&st->codec, samples,
1543 &got_picture, (uint8_t *)data, size);
1544 av_free(samples);
1545 break;
1546 default:
1547 break;
1548 }
1549 fail:
1550 avcodec_close(&st->codec);
1551 return ret;
1552 }
1553
1554 /* absolute maximum size we read until we abort */
1555 #define MAX_READ_SIZE 5000000
1556
1557 /* maximum duration until we stop analysing the stream */
1558 #define MAX_STREAM_DURATION ((int)(AV_TIME_BASE * 1.0))
1559
1560 /**
1561 * Read the beginning of a media file to get stream information. This
1562 * is useful for file formats with no headers such as MPEG. This
1563 * function also compute the real frame rate in case of mpeg2 repeat
1564 * frame mode.
1565 *
1566 * @param ic media file handle
1567 * @return >=0 if OK. AVERROR_xxx if error.
1568 */
1569 int av_find_stream_info(AVFormatContext *ic)
1570 {
1571 int i, count, ret, read_size;
1572 AVStream *st;
1573 AVPacket pkt1, *pkt;
1574 AVPacketList *pktl=NULL, **ppktl;
1575
1576 count = 0;
1577 read_size = 0;
1578 ppktl = &ic->packet_buffer;
1579 for(;;) {
1580 /* check if one codec still needs to be handled */
1581 for(i=0;i<ic->nb_streams;i++) {
1582 st = ic->streams[i];
1583 if (!has_codec_parameters(&st->codec))
1584 break;
1585 }
1586 if (i == ic->nb_streams) {
1587 /* NOTE: if the format has no header, then we need to read
1588 some packets to get most of the streams, so we cannot
1589 stop here */
1590 if (!(ic->ctx_flags & AVFMTCTX_NOHEADER)) {
1591 /* if we found the info for all the codecs, we can stop */
1592 ret = count;
1593 break;
1594 }
1595 } else {
1596 /* we did not get all the codec info, but we read too much data */
1597 if (read_size >= MAX_READ_SIZE) {
1598 ret = count;
1599 break;
1600 }
1601 }
1602
1603 /* NOTE: a new stream can be added there if no header in file
1604 (AVFMTCTX_NOHEADER) */
1605 ret = av_read_frame_internal(ic, &pkt1);
1606 if (ret < 0) {
1607 /* EOF or error */
1608 ret = -1; /* we could not have all the codec parameters before EOF */
1609 if ((ic->ctx_flags & AVFMTCTX_NOHEADER) &&
1610 i == ic->nb_streams)
1611 ret = 0;
1612 break;
1613 }
1614
1615 pktl = av_mallocz(sizeof(AVPacketList));
1616 if (!pktl) {
1617 ret = AVERROR_NOMEM;
1618 break;
1619 }
1620
1621 /* add the packet in the buffered packet list */
1622 *ppktl = pktl;
1623 ppktl = &pktl->next;
1624
1625 pkt = &pktl->pkt;
1626 *pkt = pkt1;
1627
1628 /* duplicate the packet */
1629 if (av_dup_packet(pkt) < 0) {
1630 ret = AVERROR_NOMEM;
1631 break;
1632 }
1633
1634 read_size += pkt->size;
1635
1636 st = ic->streams[pkt->stream_index];
1637 st->codec_info_duration += pkt->duration;
1638 if (pkt->duration != 0)
1639 st->codec_info_nb_frames++;
1640
1641 /* if still no information, we try to open the codec and to
1642 decompress the frame. We try to avoid that in most cases as
1643 it takes longer and uses more memory. For MPEG4, we need to
1644 decompress for Quicktime. */
1645 if (!has_codec_parameters(&st->codec) &&
1646 (st->codec.codec_id == CODEC_ID_FLV1 ||
1647 st->codec.codec_id == CODEC_ID_H264 ||
1648 st->codec.codec_id == CODEC_ID_H263 ||
1649 st->codec.codec_id == CODEC_ID_VORBIS ||
1650 st->codec.codec_id == CODEC_ID_MJPEG ||
1651 (st->codec.codec_id == CODEC_ID_MPEG4 && !st->need_parsing)))
1652 try_decode_frame(st, pkt->data, pkt->size);
1653
1654 if (st->codec_info_duration >= MAX_STREAM_DURATION) {
1655 break;
1656 }
1657 count++;
1658 }
1659
1660 /* set real frame rate info */
1661 for(i=0;i<ic->nb_streams;i++) {
1662 st = ic->streams[i];
1663 if (st->codec.codec_type == CODEC_TYPE_VIDEO) {
1664 /* compute the real frame rate for telecine */
1665 if ((st->codec.codec_id == CODEC_ID_MPEG1VIDEO ||
1666 st->codec.codec_id == CODEC_ID_MPEG2VIDEO) &&
1667 st->codec.sub_id == 2) {
1668 if (st->codec_info_nb_frames >= 20) {
1669 float coded_frame_rate, est_frame_rate;
1670 est_frame_rate = ((double)st->codec_info_nb_frames * AV_TIME_BASE) /
1671 (double)st->codec_info_duration ;
1672 coded_frame_rate = (double)st->codec.frame_rate /
1673 (double)st->codec.frame_rate_base;
1674 #if 0
1675 printf("telecine: coded_frame_rate=%0.3f est_frame_rate=%0.3f\n",
1676 coded_frame_rate, est_frame_rate);
1677 #endif
1678 /* if we detect that it could be a telecine, we
1679 signal it. It would be better to do it at a
1680 higher level as it can change in a film */
1681 if (coded_frame_rate >= 24.97 &&
1682 (est_frame_rate >= 23.5 && est_frame_rate < 24.5)) {
1683 st->r_frame_rate = 24024;
1684 st->r_frame_rate_base = 1001;
1685 }
1686 }
1687 }
1688 /* if no real frame rate, use the codec one */
1689 if (!st->r_frame_rate){
1690 st->r_frame_rate = st->codec.frame_rate;
1691 st->r_frame_rate_base = st->codec.frame_rate_base;
1692 }
1693 }
1694 }
1695
1696 av_estimate_timings(ic);
1697 #if 0
1698 /* correct DTS for b frame streams with no timestamps */
1699 for(i=0;i<ic->nb_streams;i++) {
1700 st = ic->streams[i];
1701 if (st->codec.codec_type == CODEC_TYPE_VIDEO) {
1702 if(b-frames){
1703 ppktl = &ic->packet_buffer;
1704 while(ppkt1){
1705 if(ppkt1->stream_index != i)
1706 continue;
1707 if(ppkt1->pkt->dts < 0)
1708 break;
1709 if(ppkt1->pkt->pts != AV_NOPTS_VALUE)
1710 break;
1711 ppkt1->pkt->dts -= delta;
1712 ppkt1= ppkt1->next;
1713 }
1714 if(ppkt1)
1715 continue;
1716 st->cur_dts -= delta;
1717 }
1718 }
1719 }
1720 #endif
1721 return ret;
1722 }
1723
1724 /*******************************************************/
1725
1726 /**
1727 * start playing a network based stream (e.g. RTSP stream) at the
1728 * current position
1729 */
1730 int av_read_play(AVFormatContext *s)
1731 {
1732 if (!s->iformat->read_play)
1733 return AVERROR_NOTSUPP;
1734 return s->iformat->read_play(s);
1735 }
1736
1737 /**
1738 * pause a network based stream (e.g. RTSP stream). Use av_read_play()
1739 * to resume it.
1740 */
1741 int av_read_pause(AVFormatContext *s)
1742 {
1743 if (!s->iformat->read_pause)
1744 return AVERROR_NOTSUPP;
1745 return s->iformat->read_pause(s);
1746 }
1747
1748 /**
1749 * Close a media file (but not its codecs)
1750 *
1751 * @param s media file handle
1752 */
1753 void av_close_input_file(AVFormatContext *s)
1754 {
1755 int i, must_open_file;
1756 AVStream *st;
1757
1758 /* free previous packet */
1759 if (s->cur_st && s->cur_st->parser)
1760 av_free_packet(&s->cur_pkt);
1761
1762 if (s->iformat->read_close)
1763 s->iformat->read_close(s);
1764 for(i=0;i<s->nb_streams;i++) {
1765 /* free all data in a stream component */
1766 st = s->streams[i];
1767 if (st->parser) {
1768 av_parser_close(st->parser);
1769 }
1770 av_free(st->index_entries);
1771 av_free(st);
1772 }
1773 flush_packet_queue(s);
1774 must_open_file = 1;
1775 if (s->iformat->flags & AVFMT_NOFILE) {
1776 must_open_file = 0;
1777 }
1778 if (must_open_file) {
1779 url_fclose(&s->pb);
1780 }
1781 av_freep(&s->priv_data);
1782 av_free(s);
1783 }
1784
1785 /**
1786 * Add a new stream to a media file. Can only be called in the
1787 * read_header function. If the flag AVFMTCTX_NOHEADER is in the
1788 * format context, then new streams can be added in read_packet too.
1789 *
1790 *
1791 * @param s media file handle
1792 * @param id file format dependent stream id
1793 */
1794 AVStream *av_new_stream(AVFormatContext *s, int id)
1795 {
1796 AVStream *st;
1797
1798 if (s->nb_streams >= MAX_STREAMS)
1799 return NULL;
1800
1801 st = av_mallocz(sizeof(AVStream));
1802 if (!st)
1803 return NULL;
1804 avcodec_get_context_defaults(&st->codec);
1805 if (s->iformat) {
1806 /* no default bitrate if decoding */
1807 st->codec.bit_rate = 0;
1808 }
1809 st->index = s->nb_streams;
1810 st->id = id;
1811 st->start_time = AV_NOPTS_VALUE;
1812 st->duration = AV_NOPTS_VALUE;
1813 st->cur_dts = AV_NOPTS_VALUE;
1814
1815 /* default pts settings is MPEG like */
1816 av_set_pts_info(st, 33, 1, 90000);
1817 st->last_IP_pts = AV_NOPTS_VALUE;
1818
1819 s->streams[s->nb_streams++] = st;
1820 return st;
1821 }
1822
1823 /************************************************************/
1824 /* output media file */
1825
1826 int av_set_parameters(AVFormatContext *s, AVFormatParameters *ap)
1827 {
1828 int ret;
1829
1830 if (s->oformat->priv_data_size > 0) {
1831 s->priv_data = av_mallocz(s->oformat->priv_data_size);
1832 if (!s->priv_data)
1833 return AVERROR_NOMEM;
1834 } else
1835 s->priv_data = NULL;
1836
1837 if (s->oformat->set_parameters) {
1838 ret = s->oformat->set_parameters(s, ap);
1839 if (ret < 0)
1840 return ret;
1841 }
1842 return 0;
1843 }
1844
1845 /**
1846 * allocate the stream private data and write the stream header to an
1847 * output media file
1848 *
1849 * @param s media file handle
1850 * @return 0 if OK. AVERROR_xxx if error.
1851 */
1852 int av_write_header(AVFormatContext *s)
1853 {
1854 int ret, i;
1855 AVStream *st;
1856
1857 ret = s->oformat->write_header(s);
1858 if (ret < 0)
1859 return ret;
1860
1861 /* init PTS generation */
1862 for(i=0;i<s->nb_streams;i++) {
1863 st = s->streams[i];
1864
1865 switch (st->codec.codec_type) {
1866 case CODEC_TYPE_AUDIO:
1867 av_frac_init(&st->pts, 0, 0,
1868 (int64_t)st->time_base.num * st->codec.sample_rate);
1869 break;
1870 case CODEC_TYPE_VIDEO:
1871 av_frac_init(&st->pts, 0, 0,
1872 (int64_t)st->time_base.num * st->codec.frame_rate);
1873 break;
1874 default:
1875 break;
1876 }
1877 }
1878 return 0;
1879 }
1880
1881 //FIXME merge with compute_pkt_fields
1882 static void compute_pkt_fields2(AVStream *st, AVPacket *pkt){
1883 int b_frames = FFMAX(st->codec.has_b_frames, st->codec.max_b_frames);
1884 int num, den, frame_size;
1885
1886 // 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);
1887
1888 /* if(pkt->pts == AV_NOPTS_VALUE && pkt->dts == AV_NOPTS_VALUE)
1889 return -1;*/
1890
1891 if(pkt->pts != AV_NOPTS_VALUE)
1892 pkt->pts = av_rescale(pkt->pts, st->time_base.den, AV_TIME_BASE * (int64_t)st->time_base.num);
1893 if(pkt->dts != AV_NOPTS_VALUE)
1894 pkt->dts = av_rescale(pkt->dts, st->time_base.den, AV_TIME_BASE * (int64_t)st->time_base.num);
1895
1896 /* duration field */
1897 pkt->duration = av_rescale(pkt->duration, st->time_base.den, AV_TIME_BASE * (int64_t)st->time_base.num);
1898 if (pkt->duration == 0) {
1899 compute_frame_duration(&num, &den, st, NULL, pkt);
1900 if (den && num) {
1901 pkt->duration = av_rescale(1, num * (int64_t)st->time_base.den, den * (int64_t)st->time_base.num);
1902 }
1903 }
1904
1905 //XXX/FIXME this is a temporary hack until all encoders output pts
1906 if((pkt->pts == 0 || pkt->pts == AV_NOPTS_VALUE) && pkt->dts == AV_NOPTS_VALUE && !b_frames){
1907 pkt->dts=
1908 // pkt->pts= st->cur_dts;
1909 pkt->pts= st->pts.val;
1910 }
1911
1912 //calculate dts from pts
1913 if(pkt->pts != AV_NOPTS_VALUE && pkt->dts == AV_NOPTS_VALUE){
1914 if(b_frames){
1915 if(st->last_IP_pts == AV_NOPTS_VALUE){
1916 st->last_IP_pts= -pkt->duration;
1917 }
1918 if(st->last_IP_pts < pkt->pts){
1919 pkt->dts= st->last_IP_pts;
1920 st->last_IP_pts= pkt->pts;
1921 }else
1922 pkt->dts= pkt->pts;
1923 }else
1924 pkt->dts= pkt->pts;
1925 }
1926
1927 // av_log(NULL, AV_LOG_DEBUG, "av_write_frame: pts2:%lld dts2:%lld\n", pkt->pts, pkt->dts);
1928 st->cur_dts= pkt->dts;
1929 st->pts.val= pkt->dts;
1930
1931 /* update pts */
1932 switch (st->codec.codec_type) {
1933 case CODEC_TYPE_AUDIO:
1934 frame_size = get_audio_frame_size(&st->codec, pkt->size);
1935
1936 /* HACK/FIXME, we skip the initial 0-size packets as they are most likely equal to the encoder delay,
1937 but it would be better if we had the real timestamps from the encoder */
1938 if (frame_size >= 0 && (pkt->size || st->pts.num!=st->pts.den>>1 || st->pts.val)) {
1939 av_frac_add(&st->pts, (int64_t)st->time_base.den * frame_size);
1940 }
1941 break;
1942 case CODEC_TYPE_VIDEO:
1943 av_frac_add(&st->pts, (int64_t)st->time_base.den * st->codec.frame_rate_base);
1944 break;
1945 default:
1946 break;
1947 }
1948 }
1949
1950 static void truncate_ts(AVStream *st, AVPacket *pkt){
1951 int64_t pts_mask = (2LL << (st->pts_wrap_bits-1)) - 1;
1952
1953 if(pkt->dts < 0)
1954 pkt->dts= 0; //this happens for low_delay=0 and b frames, FIXME, needs further invstigation about what we should do here
1955
1956 pkt->pts &= pts_mask;
1957 pkt->dts &= pts_mask;
1958 }
1959
1960 /**
1961 * Write a packet to an output media file. The packet shall contain
1962 * one audio or video frame.
1963 *
1964 * @param s media file handle
1965 * @param pkt the packet, which contains the stream_index, buf/buf_size, dts/pts, ...
1966 * @return < 0 if error, = 0 if OK, 1 if end of stream wanted.
1967 */
1968 int av_write_frame(AVFormatContext *s, AVPacket *pkt)
1969 {
1970 compute_pkt_fields2(s->streams[pkt->stream_index], pkt);
1971
1972 truncate_ts(s->streams[pkt->stream_index], pkt);
1973
1974 return s->oformat->write_packet(s, pkt);
1975 }
1976
1977 /**
1978 * Writes a packet to an output media file ensuring correct interleaving.
1979 * The packet shall contain one audio or video frame.
1980 * If the packets are already correctly interleaved the application should
1981 * call av_write_frame() instead as its slightly faster, its also important
1982 * to keep in mind that non interlaved input will need huge amounts
1983 * of memory to interleave with this, so its prefereable to interleave at the
1984 * demuxer level
1985 *
1986 * @param s media file handle
1987 * @param pkt the packet, which contains the stream_index, buf/buf_size, dts/pts, ...
1988 * @return < 0 if error, = 0 if OK, 1 if end of stream wanted.
1989 */
1990 int av_interleaved_write_frame(AVFormatContext *s, AVPacket *pkt){
1991 AVPacketList *pktl, **next_point, *this_pktl;
1992 int stream_count=0;
1993 int streams[MAX_STREAMS];
1994 AVStream *st= s->streams[ pkt->stream_index];
1995
1996 compute_pkt_fields2(st, pkt);
1997
1998 //FIXME/XXX/HACK drop zero sized packets
1999 if(st->codec.codec_type == CODEC_TYPE_AUDIO && pkt->size==0)
2000 return 0;
2001
2002 if(pkt->dts == AV_NOPTS_VALUE)
2003 return -1;
2004
2005 assert(pkt->destruct != av_destruct_packet); //FIXME
2006
2007 this_pktl = av_mallocz(sizeof(AVPacketList));
2008 this_pktl->pkt= *pkt;
2009 av_dup_packet(&this_pktl->pkt);
2010
2011 next_point = &s->packet_buffer;
2012 while(*next_point){
2013 AVStream *st2= s->streams[ (*next_point)->pkt.stream_index];
2014 int64_t left= st2->time_base.num * (int64_t)st ->time_base.den;
2015 int64_t right= st ->time_base.num * (int64_t)st2->time_base.den;
2016 if((*next_point)->pkt.dts * left > pkt->dts * right) //FIXME this can overflow
2017 break;
2018 next_point= &(*next_point)->next;
2019 }
2020 this_pktl->next= *next_point;
2021 *next_point= this_pktl;
2022
2023 memset(streams, 0, sizeof(streams));
2024 pktl= s->packet_buffer;
2025 while(pktl){
2026 //av_log(s, AV_LOG_DEBUG, "show st:%d dts:%lld\n", pktl->pkt.stream_index, pktl->pkt.dts);
2027 if(streams[ pktl->pkt.stream_index ] == 0)
2028 stream_count++;
2029 streams[ pktl->pkt.stream_index ]++;
2030 pktl= pktl->next;
2031 }
2032
2033 while(s->nb_streams == stream_count){
2034 int ret;
2035
2036 pktl= s->packet_buffer;
2037 //av_log(s, AV_LOG_DEBUG, "write st:%d dts:%lld\n", pktl->pkt.stream_index, pktl->pkt.dts);
2038 truncate_ts(s->streams[pktl->pkt.stream_index], &pktl->pkt);
2039 ret= s->oformat->write_packet(s, &pktl->pkt);
2040
2041 s->packet_buffer= pktl->next;
2042 if((--streams[ pktl->pkt.stream_index ]) == 0)
2043 stream_count--;
2044
2045 av_free_packet(&pktl->pkt);
2046 av_freep(&pktl);
2047
2048 if(ret<0)
2049 return ret;
2050 }
2051 return 0;
2052 }
2053
2054 /**
2055 * write the stream trailer to an output media file and and free the
2056 * file private data.
2057 *
2058 * @param s media file handle
2059 * @return 0 if OK. AVERROR_xxx if error. */
2060 int av_write_trailer(AVFormatContext *s)
2061 {
2062 int ret;
2063
2064 while(s->packet_buffer){
2065 int ret;
2066 AVPacketList *pktl= s->packet_buffer;
2067
2068 //av_log(s, AV_LOG_DEBUG, "write_trailer st:%d dts:%lld\n", pktl->pkt.stream_index, pktl->pkt.dts);
2069 truncate_ts(s->streams[pktl->pkt.stream_index], &pktl->pkt);
2070 ret= s->oformat->write_packet(s, &pktl->pkt);
2071
2072 s->packet_buffer= pktl->next;
2073
2074 av_free_packet(&pktl->pkt);
2075 av_freep(&pktl);
2076
2077 if(ret<0)
2078 return ret;
2079 }
2080
2081 ret = s->oformat->write_trailer(s);
2082 av_freep(&s->priv_data);
2083 return ret;
2084 }
2085
2086 /* "user interface" functions */
2087
2088 void dump_format(AVFormatContext *ic,
2089 int index,
2090 const char *url,
2091 int is_output)
2092 {
2093 int i, flags;
2094 char buf[256];
2095
2096 av_log(NULL, AV_LOG_DEBUG, "%s #%d, %s, %s '%s':\n",
2097 is_output ? "Output" : "Input",
2098 index,
2099 is_output ? ic->oformat->name : ic->iformat->name,
2100 is_output ? "to" : "from", url);
2101 if (!is_output) {
2102 av_log(NULL, AV_LOG_DEBUG, " Duration: ");
2103 if (ic->duration != AV_NOPTS_VALUE) {
2104 int hours, mins, secs, us;
2105 secs = ic->duration / AV_TIME_BASE;
2106 us = ic->duration % AV_TIME_BASE;
2107 mins = secs / 60;
2108 secs %= 60;
2109 hours = mins / 60;
2110 mins %= 60;
2111 av_log(NULL, AV_LOG_DEBUG, "%02d:%02d:%02d.%01d", hours, mins, secs,
2112 (10 * us) / AV_TIME_BASE);
2113 } else {
2114 av_log(NULL, AV_LOG_DEBUG, "N/A");
2115 }
2116 av_log(NULL, AV_LOG_DEBUG, ", bitrate: ");
2117 if (ic->bit_rate) {
2118 av_log(NULL, AV_LOG_DEBUG,"%d kb/s", ic->bit_rate / 1000);
2119 } else {
2120 av_log(NULL, AV_LOG_DEBUG, "N/A");
2121 }
2122 av_log(NULL, AV_LOG_DEBUG, "\n");
2123 }
2124 for(i=0;i<ic->nb_streams;i++) {
2125 AVStream *st = ic->streams[i];
2126 avcodec_string(buf, sizeof(buf), &st->codec, is_output);
2127 av_log(NULL, AV_LOG_DEBUG, " Stream #%d.%d", index, i);
2128 /* the pid is an important information, so we display it */
2129 /* XXX: add a generic system */
2130 if (is_output)
2131 flags = ic->oformat->flags;
2132 else
2133 flags = ic->iformat->flags;
2134 if (flags & AVFMT_SHOW_IDS) {
2135 av_log(NULL, AV_LOG_DEBUG, "[0x%x]", st->id);
2136 }
2137 av_log(NULL, AV_LOG_DEBUG, ": %s\n", buf);
2138 }
2139 }
2140
2141 typedef struct {
2142 const char *abv;
2143 int width, height;
2144 int frame_rate, frame_rate_base;
2145 } AbvEntry;
2146
2147 static AbvEntry frame_abvs[] = {
2148 { "ntsc", 720, 480, 30000, 1001 },
2149 { "pal", 720, 576, 25, 1 },
2150 { "qntsc", 352, 240, 30000, 1001 }, /* VCD compliant ntsc */
2151 { "qpal", 352, 288, 25, 1 }, /* VCD compliant pal */
2152 { "sntsc", 640, 480, 30000, 1001 }, /* square pixel ntsc */
2153 { "spal", 768, 576, 25, 1 }, /* square pixel pal */
2154 { "film", 352, 240, 24, 1 },
2155 { "ntsc-film", 352, 240, 24000, 1001 },
2156 { "sqcif", 128, 96, 0, 0 },
2157 { "qcif", 176, 144, 0, 0 },
2158 { "cif", 352, 288, 0, 0 },
2159 { "4cif", 704, 576, 0, 0 },
2160 };
2161
2162 int parse_image_size(int *width_ptr, int *height_ptr, const char *str)
2163 {
2164 int i;
2165 int n = sizeof(frame_abvs) / sizeof(AbvEntry);
2166 const char *p;
2167 int frame_width = 0, frame_height = 0;
2168
2169 for(i=0;i<n;i++) {
2170 if (!strcmp(frame_abvs[i].abv, str)) {
2171 frame_width = frame_abvs[i].width;
2172 frame_height = frame_abvs[i].height;
2173 break;
2174 }
2175 }
2176 if (i == n) {
2177 p = str;
2178 frame_width = strtol(p, (char **)&p, 10);
2179 if (*p)
2180 p++;
2181 frame_height = strtol(p, (char **)&p, 10);
2182 }
2183 if (frame_width <= 0 || frame_height <= 0)
2184 return -1;
2185 *width_ptr = frame_width;
2186 *height_ptr = frame_height;
2187 return 0;
2188 }
2189
2190 int parse_frame_rate(int *frame_rate, int *frame_rate_base, const char *arg)
2191 {
2192 int i;
2193 char* cp;
2194
2195 /* First, we check our abbreviation table */
2196 for (i = 0; i < sizeof(frame_abvs)/sizeof(*frame_abvs); ++i)
2197 if (!strcmp(frame_abvs[i].abv, arg)) {
2198 *frame_rate = frame_abvs[i].frame_rate;
2199 *frame_rate_base = frame_abvs[i].frame_rate_base;
2200 return 0;
2201 }
2202
2203 /* Then, we try to parse it as fraction */
2204 cp = strchr(arg, '/');
2205 if (cp) {
2206 char* cpp;
2207 *frame_rate = strtol(arg, &cpp, 10);
2208 if (cpp != arg || cpp == cp)
2209 *frame_rate_base = strtol(cp+1, &cpp, 10);
2210 else
2211 *frame_rate = 0;
2212 }
2213 else {
2214 /* Finally we give up and parse it as double */
2215 *frame_rate_base = DEFAULT_FRAME_RATE_BASE; //FIXME use av_d2q()
2216 *frame_rate = (int)(strtod(arg, 0) * (*frame_rate_base) + 0.5);
2217 }
2218 if (!*frame_rate || !*frame_rate_base)
2219 return -1;
2220 else
2221 return 0;
2222 }
2223
2224 /* Syntax:
2225 * - If not a duration:
2226 * [{YYYY-MM-DD|YYYYMMDD}]{T| }{HH[:MM[:SS[.m...]]][Z]|HH[MM[SS[.m...]]][Z]}
2227 * Time is localtime unless Z is suffixed to the end. In this case GMT
2228 * Return the date in micro seconds since 1970
2229 * - If duration:
2230 * HH[:MM[:SS[.m...]]]
2231 * S+[.m...]
2232 */
2233 int64_t parse_date(const char *datestr, int duration)
2234 {
2235 const char *p;
2236 int64_t t;
2237 struct tm dt;
2238 int i;
2239 static const char *date_fmt[] = {
2240 "%Y-%m-%d",
2241 "%Y%m%d",
2242 };
2243 static const char *time_fmt[] = {
2244 "%H:%M:%S",
2245 "%H%M%S",
2246 };
2247 const char *q;
2248 int is_utc, len;
2249 char lastch;
2250 int negative = 0;
2251
2252 #undef time
2253 time_t now = time(0);
2254
2255 len = strlen(datestr);
2256 if (len > 0)
2257 lastch = datestr[len - 1];
2258 else
2259 lastch = '\0';
2260 is_utc = (lastch == 'z' || lastch == 'Z');
2261
2262 memset(&dt, 0, sizeof(dt));
2263
2264 p = datestr;
2265 q = NULL;
2266 if (!duration) {
2267 for (i = 0; i < sizeof(date_fmt) / sizeof(date_fmt[0]); i++) {
2268 q = small_strptime(p, date_fmt[i], &dt);
2269 if (q) {
2270 break;
2271 }
2272 }
2273
2274 if (!q) {
2275 if (is_utc) {
2276 dt = *gmtime(&now);
2277 } else {
2278 dt = *localtime(&now);
2279 }
2280 dt.tm_hour = dt.tm_min = dt.tm_sec = 0;
2281 } else {
2282 p = q;
2283 }
2284
2285 if (*p == 'T' || *p == 't' || *p == ' ')
2286 p++;
2287
2288 for (i = 0; i < sizeof(time_fmt) / sizeof(time_fmt[0]); i++) {
2289 q = small_strptime(p, time_fmt[i], &dt);
2290 if (q) {
2291 break;
2292 }
2293 }
2294 } else {
2295 if (p[0] == '-') {
2296 negative = 1;
2297 ++p;
2298 }
2299 q = small_strptime(p, time_fmt[0], &dt);
2300 if (!q) {
2301 dt.tm_sec = strtol(p, (char **)&q, 10);
2302 dt.tm_min = 0;
2303 dt.tm_hour = 0;
2304 }
2305 }
2306
2307 /* Now we have all the fields that we can get */
2308 if (!q) {
2309 if (duration)
2310 return 0;
2311 else
2312 return now * int64_t_C(1000000);
2313 }
2314
2315 if (duration) {
2316 t = dt.tm_hour * 3600 + dt.tm_min * 60 + dt.tm_sec;
2317 } else {
2318 dt.tm_isdst = -1; /* unknown */
2319 if (is_utc) {
2320 t = mktimegm(&dt);
2321 } else {
2322 t = mktime(&dt);
2323 }
2324 }
2325
2326 t *= 1000000;
2327
2328 if (*q == '.') {
2329 int val, n;
2330 q++;
2331 for (val = 0, n = 100000; n >= 1; n /= 10, q++) {
2332 if (!isdigit(*q))
2333 break;
2334 val += n * (*q - '0');
2335 }
2336 t += val;
2337 }
2338 return negative ? -t : t;
2339 }
2340
2341 /* syntax: '?tag1=val1&tag2=val2...'. Little URL decoding is done. Return
2342 1 if found */
2343 int find_info_tag(char *arg, int arg_size, const char *tag1, const char *info)
2344 {
2345 const char *p;
2346 char tag[128], *q;
2347
2348 p = info;
2349 if (*p == '?')
2350 p++;
2351 for(;;) {
2352 q = tag;
2353 while (*p != '\0' && *p != '=' && *p != '&') {
2354 if ((q - tag) < sizeof(tag) - 1)
2355 *q++ = *p;
2356 p++;
2357 }
2358 *q = '\0';
2359 q = arg;
2360 if (*p == '=') {
2361 p++;
2362 while (*p != '&' && *p != '\0') {
2363 if ((q - arg) < arg_size - 1) {
2364 if (*p == '+')
2365 *q++ = ' ';
2366 else
2367 *q++ = *p;
2368 }
2369 p++;
2370 }
2371 *q = '\0';
2372 }
2373 if (!strcmp(tag, tag1))
2374 return 1;
2375 if (*p != '&')
2376 break;
2377 p++;
2378 }
2379 return 0;
2380 }
2381
2382 /* Return in 'buf' the path with '%d' replaced by number. Also handles
2383 the '%0nd' format where 'n' is the total number of digits and
2384 '%%'. Return 0 if OK, and -1 if format error */
2385 int get_frame_filename(char *buf, int buf_size,
2386 const char *path, int number)
2387 {
2388 const char *p;
2389 char *q, buf1[20], c;
2390 int nd, len, percentd_found;
2391
2392 q = buf;
2393 p = path;
2394 percentd_found = 0;
2395 for(;;) {
2396 c = *p++;
2397 if (c == '\0')
2398 break;
2399 if (c == '%') {
2400 do {
2401 nd = 0;
2402 while (isdigit(*p)) {
2403 nd = nd * 10 + *p++ - '0';
2404 }
2405 c = *p++;
2406 } while (isdigit(c));
2407
2408 switch(c) {
2409 case '%':
2410 goto addchar;
2411 case 'd':
2412 if (percentd_found)
2413 goto fail;
2414 percentd_found = 1;
2415 snprintf(buf1, sizeof(buf1), "%0*d", nd, number);
2416 len = strlen(buf1);
2417 if ((q - buf + len) > buf_size - 1)
2418 goto fail;
2419 memcpy(q, buf1, len);
2420 q += len;
2421 break;
2422 default:
2423 goto fail;
2424 }
2425 } else {
2426 addchar:
2427 if ((q - buf) < buf_size - 1)
2428 *q++ = c;
2429 }
2430 }
2431 if (!percentd_found)
2432 goto fail;
2433 *q = '\0';
2434 return 0;
2435 fail:
2436 *q = '\0';
2437 return -1;
2438 }
2439
2440 /**
2441 * Print nice hexa dump of a buffer
2442 * @param f stream for output
2443 * @param buf buffer
2444 * @param size buffer size
2445 */
2446 void av_hex_dump(FILE *f, uint8_t *buf, int size)
2447 {
2448 int len, i, j, c;
2449
2450 for(i=0;i<size;i+=16) {
2451 len = size - i;
2452 if (len > 16)
2453 len = 16;
2454 fprintf(f, "%08x ", i);
2455 for(j=0;j<16;j++) {
2456 if (j < len)
2457 fprintf(f, " %02x", buf[i+j]);
2458 else
2459 fprintf(f, " ");
2460 }
2461 fprintf(f, " ");
2462 for(j=0;j<len;j++) {
2463 c = buf[i+j];
2464 if (c < ' ' || c > '~')
2465 c = '.';
2466 fprintf(f, "%c", c);
2467 }
2468 fprintf(f, "\n");
2469 }
2470 }
2471
2472 /**
2473 * Print on 'f' a nice dump of a packet
2474 * @param f stream for output
2475 * @param pkt packet to dump
2476 * @param dump_payload true if the payload must be displayed too
2477 */
2478 void av_pkt_dump(FILE *f, AVPacket *pkt, int dump_payload)
2479 {
2480 fprintf(f, "stream #%d:\n", pkt->stream_index);
2481 fprintf(f, " keyframe=%d\n", ((pkt->flags & PKT_FLAG_KEY) != 0));
2482 fprintf(f, " duration=%0.3f\n", (double)pkt->duration / AV_TIME_BASE);
2483 /* DTS is _always_ valid after av_read_frame() */
2484 fprintf(f, " dts=");
2485 if (pkt->dts == AV_NOPTS_VALUE)
2486 fprintf(f, "N/A");
2487 else
2488 fprintf(f, "%0.3f", (double)pkt->dts / AV_TIME_BASE);
2489 /* PTS may be not known if B frames are present */
2490 fprintf(f, " pts=");
2491 if (pkt->pts == AV_NOPTS_VALUE)
2492 fprintf(f, "N/A");
2493 else
2494 fprintf(f, "%0.3f", (double)pkt->pts / AV_TIME_BASE);
2495 fprintf(f, "\n");
2496 fprintf(f, " size=%d\n", pkt->size);
2497 if (dump_payload)
2498 av_hex_dump(f, pkt->data, pkt->size);
2499 }
2500
2501 void url_split(char *proto, int proto_size,
2502 char *authorization, int authorization_size,
2503 char *hostname, int hostname_size,
2504 int *port_ptr,
2505 char *path, int path_size,
2506 const char *url)
2507 {
2508 const char *p;
2509 char *q;
2510 int port;
2511
2512 port = -1;
2513
2514 p = url;
2515 q = proto;
2516 while (*p != ':' && *p != '\0') {
2517 if ((q - proto) < proto_size - 1)
2518 *q++ = *p;
2519 p++;
2520 }
2521 if (proto_size > 0)
2522 *q = '\0';
2523 if (authorization_size > 0)
2524 authorization[0] = '\0';
2525 if (*p == '\0') {
2526 if (proto_size > 0)
2527 proto[0] = '\0';
2528 if (hostname_size > 0)
2529 hostname[0] = '\0';
2530 p = url;
2531 } else {
2532 char *at,*slash; // PETR: position of '@' character and '/' character
2533
2534 p++;
2535 if (*p == '/')
2536 p++;
2537 if (*p == '/')
2538 p++;
2539 at = strchr(p,'@'); // PETR: get the position of '@'
2540 slash = strchr(p,'/'); // PETR: get position of '/' - end of hostname
2541 if (at && slash && at > slash) at = NULL; // PETR: not interested in '@' behind '/'
2542
2543 q = at ? authorization : hostname; // PETR: if '@' exists starting with auth.
2544
2545 while ((at || *p != ':') && *p != '/' && *p != '?' && *p != '\0') { // PETR:
2546 if (*p == '@') { // PETR: passed '@'
2547 if (authorization_size > 0)
2548 *q = '\0';
2549 q = hostname;
2550 at = NULL;
2551 } else if (!at) { // PETR: hostname
2552 if ((q - hostname) < hostname_size - 1)
2553 *q++ = *p;
2554 } else {
2555 if ((q - authorization) < authorization_size - 1)
2556 *q++ = *p;
2557 }
2558 p++;
2559 }
2560 if (hostname_size > 0)
2561 *q = '\0';
2562 if (*p == ':') {
2563 p++;
2564 port = strtoul(p, (char **)&p, 10);
2565 }
2566 }
2567 if (port_ptr)
2568 *port_ptr = port;
2569 pstrcpy(path, path_size, p);
2570 }
2571
2572 /**
2573 * Set the pts for a given stream
2574 * @param s stream
2575 * @param pts_wrap_bits number of bits effectively used by the pts
2576 * (used for wrap control, 33 is the value for MPEG)
2577 * @param pts_num numerator to convert to seconds (MPEG: 1)
2578 * @param pts_den denominator to convert to seconds (MPEG: 90000)
2579 */
2580 void av_set_pts_info(AVStream *s, int pts_wrap_bits,
2581 int pts_num, int pts_den)
2582 {
2583 s->pts_wrap_bits = pts_wrap_bits;
2584 s->time_base.num = pts_num;
2585 s->time_base.den = pts_den;
2586 }
2587
2588 /* fraction handling */
2589
2590 /**
2591 * f = val + (num / den) + 0.5. 'num' is normalized so that it is such
2592 * as 0 <= num < den.
2593 *
2594 * @param f fractional number
2595 * @param val integer value
2596 * @param num must be >= 0
2597 * @param den must be >= 1
2598 */
2599 void av_frac_init(AVFrac *f, int64_t val, int64_t num, int64_t den)
2600 {
2601 num += (den >> 1);
2602 if (num >= den) {
2603 val += num / den;
2604 num = num % den;
2605 }
2606 f->val = val;
2607 f->num = num;
2608 f->den = den;
2609 }
2610
2611 /* set f to (val + 0.5) */
2612 void av_frac_set(AVFrac *f, int64_t val)
2613 {
2614 f->val = val;
2615 f->num = f->den >> 1;
2616 }
2617
2618 /**
2619 * Fractionnal addition to f: f = f + (incr / f->den)
2620 *
2621 * @param f fractional number
2622 * @param incr increment, can be positive or negative
2623 */
2624 void av_frac_add(AVFrac *f, int64_t incr)
2625 {
2626 int64_t num, den;
2627
2628 num = f->num + incr;
2629 den = f->den;
2630 if (num < 0) {
2631 f->val += num / den;
2632 num = num % den;
2633 if (num < 0) {
2634 num += den;
2635 f->val--;
2636 }
2637 } else if (num >= den) {
2638 f->val += num / den;
2639 num = num % den;
2640 }
2641 f->num = num;
2642 }
2643
2644 /**
2645 * register a new image format
2646 * @param img_fmt Image format descriptor
2647 */
2648 void av_register_image_format(AVImageFormat *img_fmt)
2649 {
2650 AVImageFormat **p;
2651
2652 p = &first_image_format;
2653 while (*p != NULL) p = &(*p)->next;
2654 *p = img_fmt;
2655 img_fmt->next = NULL;
2656 }
2657
2658 /* guess image format */
2659 AVImageFormat *av_probe_image_format(AVProbeData *pd)
2660 {
2661 AVImageFormat *fmt1, *fmt;
2662 int score, score_max;
2663
2664 fmt = NULL;
2665 score_max = 0;
2666 for(fmt1 = first_image_format; fmt1 != NULL; fmt1 = fmt1->next) {
2667 if (fmt1->img_probe) {
2668 score = fmt1->img_probe(pd);
2669 if (score > score_max) {
2670 score_max = score;
2671 fmt = fmt1;
2672 }
2673 }
2674 }
2675 return fmt;
2676 }
2677
2678 AVImageFormat *guess_image_format(const char *filename)
2679 {
2680 AVImageFormat *fmt1;
2681
2682 for(fmt1 = first_image_format; fmt1 != NULL; fmt1 = fmt1->next) {
2683 if (fmt1->extensions && match_ext(filename, fmt1->extensions))
2684 return fmt1;
2685 }
2686 return NULL;
2687 }
2688
2689 /**
2690 * Read an image from a stream.
2691 * @param gb byte stream containing the image
2692 * @param fmt image format, NULL if probing is required
2693 */
2694 int av_read_image(ByteIOContext *pb, const char *filename,
2695 AVImageFormat *fmt,
2696 int (*alloc_cb)(void *, AVImageInfo *info), void *opaque)
2697 {
2698 char buf[PROBE_BUF_SIZE];
2699 AVProbeData probe_data, *pd = &probe_data;
2700 offset_t pos;
2701 int ret;
2702
2703 if (!fmt) {
2704 pd->filename = filename;
2705 pd->buf = buf;
2706 pos = url_ftell(pb);
2707 pd->buf_size = get_buffer(pb, buf, PROBE_BUF_SIZE);
2708 url_fseek(pb, pos, SEEK_SET);
2709 fmt = av_probe_image_format(pd);
2710 }
2711 if (!fmt)
2712 return AVERROR_NOFMT;
2713 ret = fmt->img_read(pb, alloc_cb, opaque);
2714 return ret;
2715 }
2716
2717 /**
2718 * Write an image to a stream.
2719 * @param pb byte stream for the image output
2720 * @param fmt image format
2721 * @param img image data and informations
2722 */
2723 int av_write_image(ByteIOContext *pb, AVImageFormat *fmt, AVImageInfo *img)
2724 {
2725 return fmt->img_write(pb, img);
2726 }
2727