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