extradata may be used as bitstream reader input so allocate with padding
[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 + FF_INPUT_BUFFER_PADDING_SIZE);
1999 memcpy(st->codec->extradata, pkt->data, st->codec->extradata_size);
2000 memset(st->codec->extradata + i, 0, FF_INPUT_BUFFER_PADDING_SIZE);
2001 }
2002 }
2003
2004 /* if still no information, we try to open the codec and to
2005 decompress the frame. We try to avoid that in most cases as
2006 it takes longer and uses more memory. For MPEG4, we need to
2007 decompress for Quicktime. */
2008 if (!has_codec_parameters(st->codec) /*&&
2009 (st->codec->codec_id == CODEC_ID_FLV1 ||
2010 st->codec->codec_id == CODEC_ID_H264 ||
2011 st->codec->codec_id == CODEC_ID_H263 ||
2012 st->codec->codec_id == CODEC_ID_H261 ||
2013 st->codec->codec_id == CODEC_ID_VORBIS ||
2014 st->codec->codec_id == CODEC_ID_MJPEG ||
2015 st->codec->codec_id == CODEC_ID_PNG ||
2016 st->codec->codec_id == CODEC_ID_PAM ||
2017 st->codec->codec_id == CODEC_ID_PGM ||
2018 st->codec->codec_id == CODEC_ID_PGMYUV ||
2019 st->codec->codec_id == CODEC_ID_PBM ||
2020 st->codec->codec_id == CODEC_ID_PPM ||
2021 st->codec->codec_id == CODEC_ID_SHORTEN ||
2022 (st->codec->codec_id == CODEC_ID_MPEG4 && !st->need_parsing))*/)
2023 try_decode_frame(st, pkt->data, pkt->size);
2024
2025 if (av_rescale_q(st->codec_info_duration, st->time_base, AV_TIME_BASE_Q) >= MAX_STREAM_DURATION) {
2026 break;
2027 }
2028 count++;
2029 }
2030
2031 // close codecs which where opened in try_decode_frame()
2032 for(i=0;i<ic->nb_streams;i++) {
2033 st = ic->streams[i];
2034 if(st->codec->codec)
2035 avcodec_close(st->codec);
2036 }
2037 for(i=0;i<ic->nb_streams;i++) {
2038 st = ic->streams[i];
2039 if (st->codec->codec_type == CODEC_TYPE_VIDEO) {
2040 if(st->codec->codec_id == CODEC_ID_RAWVIDEO && !st->codec->codec_tag && !st->codec->bits_per_sample)
2041 st->codec->codec_tag= avcodec_pix_fmt_to_codec_tag(st->codec->pix_fmt);
2042
2043 if(duration_count[i] && st->codec->time_base.num*101LL <= st->codec->time_base.den &&
2044 st->time_base.num*duration_sum[i]/duration_count[i]*101LL > st->time_base.den){
2045 int64_t num, den, error, best_error;
2046
2047 num= st->time_base.den*duration_count[i];
2048 den= st->time_base.num*duration_sum[i];
2049
2050 best_error= INT64_MAX;
2051 for(j=1; j<60*12; j++){
2052 error= ABS(1001*12*num - 1001*j*den);
2053 if(error < best_error){
2054 best_error= error;
2055 av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den, j, 12, INT_MAX);
2056 }
2057 }
2058 for(j=24; j<=30; j+=6){
2059 error= ABS(1001*12*num - 1000*12*j*den);
2060 if(error < best_error){
2061 best_error= error;
2062 av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den, j*1000, 1001, INT_MAX);
2063 }
2064 }
2065 }
2066
2067 /* set real frame rate info */
2068 /* compute the real frame rate for telecine */
2069 if ((st->codec->codec_id == CODEC_ID_MPEG1VIDEO ||
2070 st->codec->codec_id == CODEC_ID_MPEG2VIDEO) &&
2071 st->codec->sub_id == 2) {
2072 if (st->codec_info_nb_frames >= 20) {
2073 float coded_frame_rate, est_frame_rate;
2074 est_frame_rate = ((double)st->codec_info_nb_frames * AV_TIME_BASE) /
2075 (double)st->codec_info_duration ;
2076 coded_frame_rate = 1.0/av_q2d(st->codec->time_base);
2077 #if 0
2078 printf("telecine: coded_frame_rate=%0.3f est_frame_rate=%0.3f\n",
2079 coded_frame_rate, est_frame_rate);
2080 #endif
2081 /* if we detect that it could be a telecine, we
2082 signal it. It would be better to do it at a
2083 higher level as it can change in a film */
2084 if (coded_frame_rate >= 24.97 &&
2085 (est_frame_rate >= 23.5 && est_frame_rate < 24.5)) {
2086 st->r_frame_rate = (AVRational){24000, 1001};
2087 }
2088 }
2089 }
2090 /* if no real frame rate, use the codec one */
2091 if (!st->r_frame_rate.num){
2092 st->r_frame_rate.num = st->codec->time_base.den;
2093 st->r_frame_rate.den = st->codec->time_base.num;
2094 }
2095 }
2096 }
2097
2098 av_estimate_timings(ic);
2099 #if 0
2100 /* correct DTS for b frame streams with no timestamps */
2101 for(i=0;i<ic->nb_streams;i++) {
2102 st = ic->streams[i];
2103 if (st->codec->codec_type == CODEC_TYPE_VIDEO) {
2104 if(b-frames){
2105 ppktl = &ic->packet_buffer;
2106 while(ppkt1){
2107 if(ppkt1->stream_index != i)
2108 continue;
2109 if(ppkt1->pkt->dts < 0)
2110 break;
2111 if(ppkt1->pkt->pts != AV_NOPTS_VALUE)
2112 break;
2113 ppkt1->pkt->dts -= delta;
2114 ppkt1= ppkt1->next;
2115 }
2116 if(ppkt1)
2117 continue;
2118 st->cur_dts -= delta;
2119 }
2120 }
2121 }
2122 #endif
2123 return ret;
2124 }
2125
2126 /*******************************************************/
2127
2128 /**
2129 * start playing a network based stream (e.g. RTSP stream) at the
2130 * current position
2131 */
2132 int av_read_play(AVFormatContext *s)
2133 {
2134 if (!s->iformat->read_play)
2135 return AVERROR_NOTSUPP;
2136 return s->iformat->read_play(s);
2137 }
2138
2139 /**
2140 * Pause a network based stream (e.g. RTSP stream).
2141 *
2142 * Use av_read_play() to resume it.
2143 */
2144 int av_read_pause(AVFormatContext *s)
2145 {
2146 if (!s->iformat->read_pause)
2147 return AVERROR_NOTSUPP;
2148 return s->iformat->read_pause(s);
2149 }
2150
2151 /**
2152 * Close a media file (but not its codecs).
2153 *
2154 * @param s media file handle
2155 */
2156 void av_close_input_file(AVFormatContext *s)
2157 {
2158 int i, must_open_file;
2159 AVStream *st;
2160
2161 /* free previous packet */
2162 if (s->cur_st && s->cur_st->parser)
2163 av_free_packet(&s->cur_pkt);
2164
2165 if (s->iformat->read_close)
2166 s->iformat->read_close(s);
2167 for(i=0;i<s->nb_streams;i++) {
2168 /* free all data in a stream component */
2169 st = s->streams[i];
2170 if (st->parser) {
2171 av_parser_close(st->parser);
2172 }
2173 av_free(st->index_entries);
2174 av_free(st->codec->extradata);
2175 av_free(st->codec);
2176 av_free(st);
2177 }
2178 flush_packet_queue(s);
2179 must_open_file = 1;
2180 if (s->iformat->flags & AVFMT_NOFILE) {
2181 must_open_file = 0;
2182 }
2183 if (must_open_file) {
2184 url_fclose(&s->pb);
2185 }
2186 av_freep(&s->priv_data);
2187 av_free(s);
2188 }
2189
2190 /**
2191 * Add a new stream to a media file.
2192 *
2193 * Can only be called in the read_header() function. If the flag
2194 * AVFMTCTX_NOHEADER is in the format context, then new streams
2195 * can be added in read_packet too.
2196 *
2197 * @param s media file handle
2198 * @param id file format dependent stream id
2199 */
2200 AVStream *av_new_stream(AVFormatContext *s, int id)
2201 {
2202 AVStream *st;
2203
2204 if (s->nb_streams >= MAX_STREAMS)
2205 return NULL;
2206
2207 st = av_mallocz(sizeof(AVStream));
2208 if (!st)
2209 return NULL;
2210
2211 st->codec= avcodec_alloc_context();
2212 if (s->iformat) {
2213 /* no default bitrate if decoding */
2214 st->codec->bit_rate = 0;
2215 }
2216 st->index = s->nb_streams;
2217 st->id = id;
2218 st->start_time = AV_NOPTS_VALUE;
2219 st->duration = AV_NOPTS_VALUE;
2220 st->cur_dts = AV_NOPTS_VALUE;
2221
2222 /* default pts settings is MPEG like */
2223 av_set_pts_info(st, 33, 1, 90000);
2224 st->last_IP_pts = AV_NOPTS_VALUE;
2225
2226 s->streams[s->nb_streams++] = st;
2227 return st;
2228 }
2229
2230 /************************************************************/
2231 /* output media file */
2232
2233 int av_set_parameters(AVFormatContext *s, AVFormatParameters *ap)
2234 {
2235 int ret;
2236
2237 if (s->oformat->priv_data_size > 0) {
2238 s->priv_data = av_mallocz(s->oformat->priv_data_size);
2239 if (!s->priv_data)
2240 return AVERROR_NOMEM;
2241 } else
2242 s->priv_data = NULL;
2243
2244 if (s->oformat->set_parameters) {
2245 ret = s->oformat->set_parameters(s, ap);
2246 if (ret < 0)
2247 return ret;
2248 }
2249 return 0;
2250 }
2251
2252 /**
2253 * allocate the stream private data and write the stream header to an
2254 * output media file
2255 *
2256 * @param s media file handle
2257 * @return 0 if OK. AVERROR_xxx if error.
2258 */
2259 int av_write_header(AVFormatContext *s)
2260 {
2261 int ret, i;
2262 AVStream *st;
2263
2264 // some sanity checks
2265 for(i=0;i<s->nb_streams;i++) {
2266 st = s->streams[i];
2267
2268 switch (st->codec->codec_type) {
2269 case CODEC_TYPE_AUDIO:
2270 if(st->codec->sample_rate<=0){
2271 av_log(s, AV_LOG_ERROR, "sample rate not set\n");
2272 return -1;
2273 }
2274 break;
2275 case CODEC_TYPE_VIDEO:
2276 if(st->codec->time_base.num<=0 || st->codec->time_base.den<=0){ //FIXME audio too?
2277 av_log(s, AV_LOG_ERROR, "time base not set\n");
2278 return -1;
2279 }
2280 if(st->codec->width<=0 || st->codec->height<=0){
2281 av_log(s, AV_LOG_ERROR, "dimensions not set\n");
2282 return -1;
2283 }
2284 break;
2285 }
2286 }
2287
2288 if(s->oformat->write_header){
2289 ret = s->oformat->write_header(s);
2290 if (ret < 0)
2291 return ret;
2292 }
2293
2294 /* init PTS generation */
2295 for(i=0;i<s->nb_streams;i++) {
2296 int64_t den = AV_NOPTS_VALUE;
2297 st = s->streams[i];
2298
2299 switch (st->codec->codec_type) {
2300 case CODEC_TYPE_AUDIO:
2301 den = (int64_t)st->time_base.num * st->codec->sample_rate;
2302 break;
2303 case CODEC_TYPE_VIDEO:
2304 den = (int64_t)st->time_base.num * st->codec->time_base.den;
2305 break;
2306 default:
2307 break;
2308 }
2309 if (den != AV_NOPTS_VALUE) {
2310 if (den <= 0)
2311 return AVERROR_INVALIDDATA;
2312 av_frac_init(&st->pts, 0, 0, den);
2313 }
2314 }
2315 return 0;
2316 }
2317
2318 //FIXME merge with compute_pkt_fields
2319 static int compute_pkt_fields2(AVStream *st, AVPacket *pkt){
2320 int b_frames = FFMAX(st->codec->has_b_frames, st->codec->max_b_frames);
2321 int num, den, frame_size;
2322
2323 // 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);
2324
2325 /* if(pkt->pts == AV_NOPTS_VALUE && pkt->dts == AV_NOPTS_VALUE)
2326 return -1;*/
2327
2328 /* duration field */
2329 if (pkt->duration == 0) {
2330 compute_frame_duration(&num, &den, st, NULL, pkt);
2331 if (den && num) {
2332 pkt->duration = av_rescale(1, num * (int64_t)st->time_base.den, den * (int64_t)st->time_base.num);
2333 }
2334 }
2335
2336 //XXX/FIXME this is a temporary hack until all encoders output pts
2337 if((pkt->pts == 0 || pkt->pts == AV_NOPTS_VALUE) && pkt->dts == AV_NOPTS_VALUE && !b_frames){
2338 pkt->dts=
2339 // pkt->pts= st->cur_dts;
2340 pkt->pts= st->pts.val;
2341 }
2342
2343 //calculate dts from pts
2344 if(pkt->pts != AV_NOPTS_VALUE && pkt->dts == AV_NOPTS_VALUE){
2345 if(b_frames){
2346 if(st->last_IP_pts == AV_NOPTS_VALUE){
2347 st->last_IP_pts= -pkt->duration;
2348 }
2349 if(st->last_IP_pts < pkt->pts){
2350 pkt->dts= st->last_IP_pts;
2351 st->last_IP_pts= pkt->pts;
2352 }else
2353 pkt->dts= pkt->pts;
2354 }else
2355 pkt->dts= pkt->pts;
2356 }
2357
2358 if(st->cur_dts && st->cur_dts != AV_NOPTS_VALUE && st->cur_dts >= pkt->dts){
2359 av_log(NULL, AV_LOG_ERROR, "error, non monotone timestamps %"PRId64" >= %"PRId64"\n", st->cur_dts, pkt->dts);
2360 return -1;
2361 }
2362 if(pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE && pkt->pts < pkt->dts){
2363 av_log(NULL, AV_LOG_ERROR, "error, pts < dts\n");
2364 return -1;
2365 }
2366
2367 // av_log(NULL, AV_LOG_DEBUG, "av_write_frame: pts2:%lld dts2:%lld\n", pkt->pts, pkt->dts);
2368 st->cur_dts= pkt->dts;
2369 st->pts.val= pkt->dts;
2370
2371 /* update pts */
2372 switch (st->codec->codec_type) {
2373 case CODEC_TYPE_AUDIO:
2374 frame_size = get_audio_frame_size(st->codec, pkt->size);
2375
2376 /* HACK/FIXME, we skip the initial 0-size packets as they are most likely equal to the encoder delay,
2377 but it would be better if we had the real timestamps from the encoder */
2378 if (frame_size >= 0 && (pkt->size || st->pts.num!=st->pts.den>>1 || st->pts.val)) {
2379 av_frac_add(&st->pts, (int64_t)st->time_base.den * frame_size);
2380 }
2381 break;
2382 case CODEC_TYPE_VIDEO:
2383 av_frac_add(&st->pts, (int64_t)st->time_base.den * st->codec->time_base.num);
2384 break;
2385 default:
2386 break;
2387 }
2388 return 0;
2389 }
2390
2391 static void truncate_ts(AVStream *st, AVPacket *pkt){
2392 int64_t pts_mask = (2LL << (st->pts_wrap_bits-1)) - 1;
2393
2394 // if(pkt->dts < 0)
2395 // pkt->dts= 0; //this happens for low_delay=0 and b frames, FIXME, needs further invstigation about what we should do here
2396
2397 pkt->pts &= pts_mask;
2398 pkt->dts &= pts_mask;
2399 }
2400
2401 /**
2402 * Write a packet to an output media file.
2403 *
2404 * The packet shall contain one audio or video frame.
2405 *
2406 * @param s media file handle
2407 * @param pkt the packet, which contains the stream_index, buf/buf_size, dts/pts, ...
2408 * @return < 0 if error, = 0 if OK, 1 if end of stream wanted.
2409 */
2410 int av_write_frame(AVFormatContext *s, AVPacket *pkt)
2411 {
2412 int ret;
2413
2414 ret=compute_pkt_fields2(s->streams[pkt->stream_index], pkt);
2415 if(ret<0)
2416 return ret;
2417
2418 truncate_ts(s->streams[pkt->stream_index], pkt);
2419
2420 ret= s->oformat->write_packet(s, pkt);
2421 if(!ret)
2422 ret= url_ferror(&s->pb);
2423 return ret;
2424 }
2425
2426 /**
2427 * interleave_packet implementation which will interleave per DTS.
2428 * packets with pkt->destruct == av_destruct_packet will be freed inside this function.
2429 * so they cannot be used after it, note calling av_free_packet() on them is still safe
2430 */
2431 static int av_interleave_packet_per_dts(AVFormatContext *s, AVPacket *out, AVPacket *pkt, int flush){
2432 AVPacketList *pktl, **next_point, *this_pktl;
2433 int stream_count=0;
2434 int streams[MAX_STREAMS];
2435
2436 if(pkt){
2437 AVStream *st= s->streams[ pkt->stream_index];
2438
2439 // assert(pkt->destruct != av_destruct_packet); //FIXME
2440
2441 this_pktl = av_mallocz(sizeof(AVPacketList));
2442 this_pktl->pkt= *pkt;
2443 if(pkt->destruct == av_destruct_packet)
2444 pkt->destruct= NULL; // non shared -> must keep original from being freed
2445 else
2446 av_dup_packet(&this_pktl->pkt); //shared -> must dup
2447
2448 next_point = &s->packet_buffer;
2449 while(*next_point){
2450 AVStream *st2= s->streams[ (*next_point)->pkt.stream_index];
2451 int64_t left= st2->time_base.num * (int64_t)st ->time_base.den;
2452 int64_t right= st ->time_base.num * (int64_t)st2->time_base.den;
2453 if((*next_point)->pkt.dts * left > pkt->dts * right) //FIXME this can overflow
2454 break;
2455 next_point= &(*next_point)->next;
2456 }
2457 this_pktl->next= *next_point;
2458 *next_point= this_pktl;
2459 }
2460
2461 memset(streams, 0, sizeof(streams));
2462 pktl= s->packet_buffer;
2463 while(pktl){
2464 //av_log(s, AV_LOG_DEBUG, "show st:%d dts:%lld\n", pktl->pkt.stream_index, pktl->pkt.dts);
2465 if(streams[ pktl->pkt.stream_index ] == 0)
2466 stream_count++;
2467 streams[ pktl->pkt.stream_index ]++;
2468 pktl= pktl->next;
2469 }
2470
2471 if(s->nb_streams == stream_count || (flush && stream_count)){
2472 pktl= s->packet_buffer;
2473 *out= pktl->pkt;
2474
2475 s->packet_buffer= pktl->next;
2476 av_freep(&pktl);
2477 return 1;
2478 }else{
2479 av_init_packet(out);
2480 return 0;
2481 }
2482 }
2483
2484 /**
2485 * Interleaves a AVPacket correctly so it can be muxed.
2486 * @param out the interleaved packet will be output here
2487 * @param in the input packet
2488 * @param flush 1 if no further packets are available as input and all
2489 * remaining packets should be output
2490 * @return 1 if a packet was output, 0 if no packet could be output,
2491 * < 0 if an error occured
2492 */
2493 static int av_interleave_packet(AVFormatContext *s, AVPacket *out, AVPacket *in, int flush){
2494 if(s->oformat->interleave_packet)
2495 return s->oformat->interleave_packet(s, out, in, flush);
2496 else
2497 return av_interleave_packet_per_dts(s, out, in, flush);
2498 }
2499
2500 /**
2501 * Writes a packet to an output media file ensuring correct interleaving.
2502 *
2503 * The packet must contain one audio or video frame.
2504 * If the packets are already correctly interleaved the application should
2505 * call av_write_frame() instead as its slightly faster, its also important
2506 * to keep in mind that completly non interleaved input will need huge amounts
2507 * of memory to interleave with this, so its prefereable to interleave at the
2508 * demuxer level
2509 *
2510 * @param s media file handle
2511 * @param pkt the packet, which contains the stream_index, buf/buf_size, dts/pts, ...
2512 * @return < 0 if error, = 0 if OK, 1 if end of stream wanted.
2513 */
2514 int av_interleaved_write_frame(AVFormatContext *s, AVPacket *pkt){
2515 AVStream *st= s->streams[ pkt->stream_index];
2516
2517 //FIXME/XXX/HACK drop zero sized packets
2518 if(st->codec->codec_type == CODEC_TYPE_AUDIO && pkt->size==0)
2519 return 0;
2520
2521 //av_log(NULL, AV_LOG_DEBUG, "av_interleaved_write_frame %d %Ld %Ld\n", pkt->size, pkt->dts, pkt->pts);
2522 if(compute_pkt_fields2(st, pkt) < 0)
2523 return -1;
2524
2525 if(pkt->dts == AV_NOPTS_VALUE)
2526 return -1;
2527
2528 for(;;){
2529 AVPacket opkt;
2530 int ret= av_interleave_packet(s, &opkt, pkt, 0);
2531 if(ret<=0) //FIXME cleanup needed for ret<0 ?
2532 return ret;
2533
2534 truncate_ts(s->streams[opkt.stream_index], &opkt);
2535 ret= s->oformat->write_packet(s, &opkt);
2536
2537 av_free_packet(&opkt);
2538 pkt= NULL;
2539
2540 if(ret<0)
2541 return ret;
2542 if(url_ferror(&s->pb))
2543 return url_ferror(&s->pb);
2544 }
2545 }
2546
2547 /**
2548 * @brief Write the stream trailer to an output media file and
2549 * free the file private data.
2550 *
2551 * @param s media file handle
2552 * @return 0 if OK. AVERROR_xxx if error.
2553 */
2554 int av_write_trailer(AVFormatContext *s)
2555 {
2556 int ret, i;
2557
2558 for(;;){
2559 AVPacket pkt;
2560 ret= av_interleave_packet(s, &pkt, NULL, 1);
2561 if(ret<0) //FIXME cleanup needed for ret<0 ?
2562 goto fail;
2563 if(!ret)
2564 break;
2565
2566 truncate_ts(s->streams[pkt.stream_index], &pkt);
2567 ret= s->oformat->write_packet(s, &pkt);
2568
2569 av_free_packet(&pkt);
2570
2571 if(ret<0)
2572 goto fail;
2573 if(url_ferror(&s->pb))
2574 goto fail;
2575 }
2576
2577 if(s->oformat->write_trailer)
2578 ret = s->oformat->write_trailer(s);
2579 fail:
2580 if(ret == 0)
2581 ret=url_ferror(&s->pb);
2582 for(i=0;i<s->nb_streams;i++)
2583 av_freep(&s->streams[i]->priv_data);
2584 av_freep(&s->priv_data);
2585 return ret;
2586 }
2587
2588 /* "user interface" functions */
2589
2590 void dump_format(AVFormatContext *ic,
2591 int index,
2592 const char *url,
2593 int is_output)
2594 {
2595 int i, flags;
2596 char buf[256];
2597
2598 av_log(NULL, AV_LOG_INFO, "%s #%d, %s, %s '%s':\n",
2599 is_output ? "Output" : "Input",
2600 index,
2601 is_output ? ic->oformat->name : ic->iformat->name,
2602 is_output ? "to" : "from", url);
2603 if (!is_output) {
2604 av_log(NULL, AV_LOG_INFO, " Duration: ");
2605 if (ic->duration != AV_NOPTS_VALUE) {
2606 int hours, mins, secs, us;
2607 secs = ic->duration / AV_TIME_BASE;
2608 us = ic->duration % AV_TIME_BASE;
2609 mins = secs / 60;
2610 secs %= 60;
2611 hours = mins / 60;
2612 mins %= 60;
2613 av_log(NULL, AV_LOG_INFO, "%02d:%02d:%02d.%01d", hours, mins, secs,
2614 (10 * us) / AV_TIME_BASE);
2615 } else {
2616 av_log(NULL, AV_LOG_INFO, "N/A");
2617 }
2618 if (ic->start_time != AV_NOPTS_VALUE) {
2619 int secs, us;
2620 av_log(NULL, AV_LOG_INFO, ", start: ");
2621 secs = ic->start_time / AV_TIME_BASE;
2622 us = ic->start_time % AV_TIME_BASE;
2623 av_log(NULL, AV_LOG_INFO, "%d.%06d",
2624 secs, (int)av_rescale(us, 1000000, AV_TIME_BASE));
2625 }
2626 av_log(NULL, AV_LOG_INFO, ", bitrate: ");
2627 if (ic->bit_rate) {
2628 av_log(NULL, AV_LOG_INFO,"%d kb/s", ic->bit_rate / 1000);
2629 } else {
2630 av_log(NULL, AV_LOG_INFO, "N/A");
2631 }
2632 av_log(NULL, AV_LOG_INFO, "\n");
2633 }
2634 for(i=0;i<ic->nb_streams;i++) {
2635 AVStream *st = ic->streams[i];
2636 int g= ff_gcd(st->time_base.num, st->time_base.den);
2637 avcodec_string(buf, sizeof(buf), st->codec, is_output);
2638 av_log(NULL, AV_LOG_INFO, " Stream #%d.%d", index, i);
2639 /* the pid is an important information, so we display it */
2640 /* XXX: add a generic system */
2641 if (is_output)
2642 flags = ic->oformat->flags;
2643 else
2644 flags = ic->iformat->flags;
2645 if (flags & AVFMT_SHOW_IDS) {
2646 av_log(NULL, AV_LOG_INFO, "[0x%x]", st->id);
2647 }
2648 if (strlen(st->language) > 0) {
2649 av_log(NULL, AV_LOG_INFO, "(%s)", st->language);
2650 }
2651 av_log(NULL, AV_LOG_DEBUG, ", %d/%d", st->time_base.num/g, st->time_base.den/g);
2652 av_log(NULL, AV_LOG_INFO, ": %s", buf);
2653 if(st->codec->codec_type == CODEC_TYPE_VIDEO){
2654 if(st->r_frame_rate.den && st->r_frame_rate.num)
2655 av_log(NULL, AV_LOG_INFO, ", %5.2f fps(r)", av_q2d(st->r_frame_rate));
2656 /* else if(st->time_base.den && st->time_base.num)
2657 av_log(NULL, AV_LOG_INFO, ", %5.2f fps(m)", 1/av_q2d(st->time_base));*/
2658 else
2659 av_log(NULL, AV_LOG_INFO, ", %5.2f fps(c)", 1/av_q2d(st->codec->time_base));
2660 }
2661 av_log(NULL, AV_LOG_INFO, "\n");
2662 }
2663 }
2664
2665 typedef struct {
2666 const char *abv;
2667 int width, height;
2668 int frame_rate, frame_rate_base;
2669 } AbvEntry;
2670
2671 static AbvEntry frame_abvs[] = {
2672 { "ntsc", 720, 480, 30000, 1001 },
2673 { "pal", 720, 576, 25, 1 },
2674 { "qntsc", 352, 240, 30000, 1001 }, /* VCD compliant ntsc */
2675 { "qpal", 352, 288, 25, 1 }, /* VCD compliant pal */
2676 { "sntsc", 640, 480, 30000, 1001 }, /* square pixel ntsc */
2677 { "spal", 768, 576, 25, 1 }, /* square pixel pal */
2678 { "film", 352, 240, 24, 1 },
2679 { "ntsc-film", 352, 240, 24000, 1001 },
2680 { "sqcif", 128, 96, 0, 0 },
2681 { "qcif", 176, 144, 0, 0 },
2682 { "cif", 352, 288, 0, 0 },
2683 { "4cif", 704, 576, 0, 0 },
2684 };
2685
2686 /**
2687 * parses width and height out of string str.
2688 */
2689 int parse_image_size(int *width_ptr, int *height_ptr, const char *str)
2690 {
2691 int i;
2692 int n = sizeof(frame_abvs) / sizeof(AbvEntry);
2693 const char *p;
2694 int frame_width = 0, frame_height = 0;
2695
2696 for(i=0;i<n;i++) {
2697 if (!strcmp(frame_abvs[i].abv, str)) {
2698 frame_width = frame_abvs[i].width;
2699 frame_height = frame_abvs[i].height;
2700 break;
2701 }
2702 }
2703 if (i == n) {
2704 p = str;
2705 frame_width = strtol(p, (char **)&p, 10);
2706 if (*p)
2707 p++;
2708 frame_height = strtol(p, (char **)&p, 10);
2709 }
2710 if (frame_width <= 0 || frame_height <= 0)
2711 return -1;
2712 *width_ptr = frame_width;
2713 *height_ptr = frame_height;
2714 return 0;
2715 }
2716
2717 /**
2718 * Converts frame rate from string to a fraction.
2719 *
2720 * First we try to get an exact integer or fractional frame rate.
2721 * If this fails we convert the frame rate to a double and return
2722 * an approximate fraction using the DEFAULT_FRAME_RATE_BASE.
2723 */
2724 int parse_frame_rate(int *frame_rate, int *frame_rate_base, const char *arg)
2725 {
2726 int i;
2727 char* cp;
2728
2729 /* First, we check our abbreviation table */
2730 for (i = 0; i < sizeof(frame_abvs)/sizeof(*frame_abvs); ++i)
2731 if (!strcmp(frame_abvs[i].abv, arg)) {
2732 *frame_rate = frame_abvs[i].frame_rate;
2733 *frame_rate_base = frame_abvs[i].frame_rate_base;
2734 return 0;
2735 }
2736
2737 /* Then, we try to parse it as fraction */
2738 cp = strchr(arg, '/');
2739 if (!cp)
2740 cp = strchr(arg, ':');
2741 if (cp) {
2742 char* cpp;
2743 *frame_rate = strtol(arg, &cpp, 10);
2744 if (cpp != arg || cpp == cp)
2745 *frame_rate_base = strtol(cp+1, &cpp, 10);
2746 else
2747 *frame_rate = 0;
2748 }
2749 else {
2750 /* Finally we give up and parse it as double */
2751 AVRational time_base = av_d2q(strtod(arg, 0), DEFAULT_FRAME_RATE_BASE);
2752 *frame_rate_base = time_base.den;
2753 *frame_rate = time_base.num;
2754 }
2755 if (!*frame_rate || !*frame_rate_base)
2756 return -1;
2757 else
2758 return 0;
2759 }
2760
2761 /**
2762 * Converts date string to number of seconds since Jan 1st, 1970.
2763 *
2764 * @code
2765 * Syntax:
2766 * - If not a duration:
2767 * [{YYYY-MM-DD|YYYYMMDD}]{T| }{HH[:MM[:SS[.m...]]][Z]|HH[MM[SS[.m...]]][Z]}
2768 * Time is localtime unless Z is suffixed to the end. In this case GMT
2769 * Return the date in micro seconds since 1970
2770 *
2771 * - If a duration:
2772 * HH[:MM[:SS[.m...]]]
2773 * S+[.m...]
2774 * @endcode
2775 */
2776 #ifndef CONFIG_WINCE
2777 int64_t parse_date(const char *datestr, int duration)
2778 {
2779 const char *p;
2780 int64_t t;
2781 struct tm dt;
2782 int i;
2783 static const char *date_fmt[] = {
2784 "%Y-%m-%d",
2785 "%Y%m%d",
2786 };
2787 static const char *time_fmt[] = {
2788 "%H:%M:%S",
2789 "%H%M%S",
2790 };
2791 const char *q;
2792 int is_utc, len;
2793 char lastch;
2794 int negative = 0;
2795
2796 #undef time
2797 time_t now = time(0);
2798
2799 len = strlen(datestr);
2800 if (len > 0)
2801 lastch = datestr[len - 1];
2802 else
2803 lastch = '\0';
2804 is_utc = (lastch == 'z' || lastch == 'Z');
2805
2806 memset(&dt, 0, sizeof(dt));
2807
2808 p = datestr;
2809 q = NULL;
2810 if (!duration) {
2811 for (i = 0; i < sizeof(date_fmt) / sizeof(date_fmt[0]); i++) {
2812 q = small_strptime(p, date_fmt[i], &dt);
2813 if (q) {
2814 break;
2815 }
2816 }
2817
2818 if (!q) {
2819 if (is_utc) {
2820 dt = *gmtime(&now);
2821 } else {
2822 dt = *localtime(&now);
2823 }
2824 dt.tm_hour = dt.tm_min = dt.tm_sec = 0;
2825 } else {
2826 p = q;
2827 }
2828
2829 if (*p == 'T' || *p == 't' || *p == ' ')
2830 p++;
2831
2832 for (i = 0; i < sizeof(time_fmt) / sizeof(time_fmt[0]); i++) {
2833 q = small_strptime(p, time_fmt[i], &dt);
2834 if (q) {
2835 break;
2836 }
2837 }
2838 } else {
2839 if (p[0] == '-') {
2840 negative = 1;
2841 ++p;
2842 }
2843 q = small_strptime(p, time_fmt[0], &dt);
2844 if (!q) {
2845 dt.tm_sec = strtol(p, (char **)&q, 10);
2846 dt.tm_min = 0;
2847 dt.tm_hour = 0;
2848 }
2849 }
2850
2851 /* Now we have all the fields that we can get */
2852 if (!q) {
2853 if (duration)
2854 return 0;
2855 else
2856 return now * int64_t_C(1000000);
2857 }
2858
2859 if (duration) {
2860 t = dt.tm_hour * 3600 + dt.tm_min * 60 + dt.tm_sec;
2861 } else {
2862 dt.tm_isdst = -1; /* unknown */
2863 if (is_utc) {
2864 t = mktimegm(&dt);
2865 } else {
2866 t = mktime(&dt);
2867 }
2868 }
2869
2870 t *= 1000000;
2871
2872 if (*q == '.') {
2873 int val, n;
2874 q++;
2875 for (val = 0, n = 100000; n >= 1; n /= 10, q++) {
2876 if (!isdigit(*q))
2877 break;
2878 val += n * (*q - '0');
2879 }
2880 t += val;
2881 }
2882 return negative ? -t : t;
2883 }
2884 #endif /* CONFIG_WINCE */
2885
2886 /**
2887 * Attempts to find a specific tag in a URL.
2888 *
2889 * syntax: '?tag1=val1&tag2=val2...'. Little URL decoding is done.
2890 * Return 1 if found.
2891 */
2892 int find_info_tag(char *arg, int arg_size, const char *tag1, const char *info)
2893 {
2894 const char *p;
2895 char tag[128], *q;
2896
2897 p = info;
2898 if (*p == '?')
2899 p++;
2900 for(;;) {
2901 q = tag;
2902 while (*p != '\0' && *p != '=' && *p != '&') {
2903 if ((q - tag) < sizeof(tag) - 1)
2904 *q++ = *p;
2905 p++;
2906 }
2907 *q = '\0';
2908 q = arg;
2909 if (*p == '=') {
2910 p++;
2911 while (*p != '&' && *p != '\0') {
2912 if ((q - arg) < arg_size - 1) {
2913 if (*p == '+')
2914 *q++ = ' ';
2915 else
2916 *q++ = *p;
2917 }
2918 p++;
2919 }
2920 *q = '\0';
2921 }
2922 if (!strcmp(tag, tag1))
2923 return 1;
2924 if (*p != '&')
2925 break;
2926 p++;
2927 }
2928 return 0;
2929 }
2930
2931 /**
2932 * Returns in 'buf' the path with '%d' replaced by number.
2933 *
2934 * Also handles the '%0nd' format where 'n' is the total number
2935 * of digits and '%%'. Return 0 if OK, and -1 if format error.
2936 */
2937 int get_frame_filename(char *buf, int buf_size,
2938 const char *path, int number)
2939 {
2940 const char *p;
2941 char *q, buf1[20], c;
2942 int nd, len, percentd_found;
2943
2944 q = buf;
2945 p = path;
2946 percentd_found = 0;
2947 for(;;) {
2948 c = *p++;
2949 if (c == '\0')
2950 break;
2951 if (c == '%') {
2952 do {
2953 nd = 0;
2954 while (isdigit(*p)) {
2955 nd = nd * 10 + *p++ - '0';
2956 }
2957 c = *p++;
2958 } while (isdigit(c));
2959
2960 switch(c) {
2961 case '%':
2962 goto addchar;
2963 case 'd':
2964 if (percentd_found)
2965 goto fail;
2966 percentd_found = 1;
2967 snprintf(buf1, sizeof(buf1), "%0*d", nd, number);
2968 len = strlen(buf1);
2969 if ((q - buf + len) > buf_size - 1)
2970 goto fail;
2971 memcpy(q, buf1, len);
2972 q += len;
2973 break;
2974 default:
2975 goto fail;
2976 }
2977 } else {
2978 addchar:
2979 if ((q - buf) < buf_size - 1)
2980 *q++ = c;
2981 }
2982 }
2983 if (!percentd_found)
2984 goto fail;
2985 *q = '\0';
2986 return 0;
2987 fail:
2988 *q = '\0';
2989 return -1;
2990 }
2991
2992 /**
2993 * Print nice hexa dump of a buffer
2994 * @param f stream for output
2995 * @param buf buffer
2996 * @param size buffer size
2997 */
2998 void av_hex_dump(FILE *f, uint8_t *buf, int size)
2999 {
3000 int len, i, j, c;
3001
3002 for(i=0;i<size;i+=16) {
3003 len = size - i;
3004 if (len > 16)
3005 len = 16;
3006 fprintf(f, "%08x ", i);
3007 for(j=0;j<16;j++) {
3008 if (j < len)
3009 fprintf(f, " %02x", buf[i+j]);
3010 else
3011 fprintf(f, " ");
3012 }
3013 fprintf(f, " ");
3014 for(j=0;j<len;j++) {
3015 c = buf[i+j];
3016 if (c < ' ' || c > '~')
3017 c = '.';
3018 fprintf(f, "%c", c);
3019 }
3020 fprintf(f, "\n");
3021 }
3022 }
3023
3024 /**
3025 * Print on 'f' a nice dump of a packet
3026 * @param f stream for output
3027 * @param pkt packet to dump
3028 * @param dump_payload true if the payload must be displayed too
3029 */
3030 //FIXME needs to know the time_base
3031 void av_pkt_dump(FILE *f, AVPacket *pkt, int dump_payload)
3032 {
3033 fprintf(f, "stream #%d:\n", pkt->stream_index);
3034 fprintf(f, " keyframe=%d\n", ((pkt->flags & PKT_FLAG_KEY) != 0));
3035 fprintf(f, " duration=%0.3f\n", (double)pkt->duration / AV_TIME_BASE);
3036 /* DTS is _always_ valid after av_read_frame() */
3037 fprintf(f, " dts=");
3038 if (pkt->dts == AV_NOPTS_VALUE)
3039 fprintf(f, "N/A");
3040 else
3041 fprintf(f, "%0.3f", (double)pkt->dts / AV_TIME_BASE);
3042 /* PTS may be not known if B frames are present */
3043 fprintf(f, " pts=");
3044 if (pkt->pts == AV_NOPTS_VALUE)
3045 fprintf(f, "N/A");
3046 else
3047 fprintf(f, "%0.3f", (double)pkt->pts / AV_TIME_BASE);
3048 fprintf(f, "\n");
3049 fprintf(f, " size=%d\n", pkt->size);
3050 if (dump_payload)
3051 av_hex_dump(f, pkt->data, pkt->size);
3052 }
3053
3054 void url_split(char *proto, int proto_size,
3055 char *authorization, int authorization_size,
3056 char *hostname, int hostname_size,
3057 int *port_ptr,
3058 char *path, int path_size,
3059 const char *url)
3060 {
3061 const char *p;
3062 char *q;
3063 int port;
3064
3065 port = -1;
3066
3067 p = url;
3068 q = proto;
3069 while (*p != ':' && *p != '\0') {
3070 if ((q - proto) < proto_size - 1)
3071 *q++ = *p;
3072 p++;
3073 }
3074 if (proto_size > 0)
3075 *q = '\0';
3076 if (authorization_size > 0)
3077 authorization[0] = '\0';
3078 if (*p == '\0') {
3079 if (proto_size > 0)
3080 proto[0] = '\0';
3081 if (hostname_size > 0)
3082 hostname[0] = '\0';
3083 p = url;
3084 } else {
3085 char *at,*slash; // PETR: position of '@' character and '/' character
3086
3087 p++;
3088 if (*p == '/')
3089 p++;
3090 if (*p == '/')
3091 p++;
3092 at = strchr(p,'@'); // PETR: get the position of '@'
3093 slash = strchr(p,'/'); // PETR: get position of '/' - end of hostname
3094 if (at && slash && at > slash) at = NULL; // PETR: not interested in '@' behind '/'
3095
3096 q = at ? authorization : hostname; // PETR: if '@' exists starting with auth.
3097
3098 while ((at || *p != ':') && *p != '/' && *p != '?' && *p != '\0') { // PETR:
3099 if (*p == '@') { // PETR: passed '@'
3100 if (authorization_size > 0)
3101 *q = '\0';
3102 q = hostname;
3103 at = NULL;
3104 } else if (!at) { // PETR: hostname
3105 if ((q - hostname) < hostname_size - 1)
3106 *q++ = *p;
3107 } else {
3108 if ((q - authorization) < authorization_size - 1)
3109 *q++ = *p;
3110 }
3111 p++;
3112 }
3113 if (hostname_size > 0)
3114 *q = '\0';
3115 if (*p == ':') {
3116 p++;
3117 port = strtoul(p, (char **)&p, 10);
3118 }
3119 }
3120 if (port_ptr)
3121 *port_ptr = port;
3122 pstrcpy(path, path_size, p);
3123 }
3124
3125 /**
3126 * Set the pts for a given stream.
3127 *
3128 * @param s stream
3129 * @param pts_wrap_bits number of bits effectively used by the pts
3130 * (used for wrap control, 33 is the value for MPEG)
3131 * @param pts_num numerator to convert to seconds (MPEG: 1)
3132 * @param pts_den denominator to convert to seconds (MPEG: 90000)
3133 */
3134 void av_set_pts_info(AVStream *s, int pts_wrap_bits,
3135 int pts_num, int pts_den)
3136 {
3137 s->pts_wrap_bits = pts_wrap_bits;
3138 s->time_base.num = pts_num;
3139 s->time_base.den = pts_den;
3140 }
3141
3142 /* fraction handling */
3143
3144 /**
3145 * f = val + (num / den) + 0.5.
3146 *
3147 * 'num' is normalized so that it is such as 0 <= num < den.
3148 *
3149 * @param f fractional number
3150 * @param val integer value
3151 * @param num must be >= 0
3152 * @param den must be >= 1
3153 */
3154 static void av_frac_init(AVFrac *f, int64_t val, int64_t num, int64_t den)
3155 {
3156 num += (den >> 1);
3157 if (num >= den) {
3158 val += num / den;
3159 num = num % den;
3160 }
3161 f->val = val;
3162 f->num = num;
3163 f->den = den;
3164 }
3165
3166 /**
3167 * Set f to (val + 0.5).
3168 */
3169 static void av_frac_set(AVFrac *f, int64_t val)
3170 {
3171 f->val = val;
3172 f->num = f->den >> 1;
3173 }
3174
3175 /**
3176 * Fractionnal addition to f: f = f + (incr / f->den).
3177 *
3178 * @param f fractional number
3179 * @param incr increment, can be positive or negative
3180 */
3181 static void av_frac_add(AVFrac *f, int64_t incr)
3182 {
3183 int64_t num, den;
3184
3185 num = f->num + incr;
3186 den = f->den;
3187 if (num < 0) {
3188 f->val += num / den;
3189 num = num % den;
3190 if (num < 0) {
3191 num += den;
3192 f->val--;
3193 }
3194 } else if (num >= den) {
3195 f->val += num / den;
3196 num = num % den;
3197 }
3198 f->num = num;
3199 }
3200
3201 /**
3202 * register a new image format
3203 * @param img_fmt Image format descriptor
3204 */
3205 void av_register_image_format(AVImageFormat *img_fmt)
3206 {
3207 AVImageFormat **p;
3208
3209 p = &first_image_format;
3210 while (*p != NULL) p = &(*p)->next;
3211 *p = img_fmt;
3212 img_fmt->next = NULL;
3213 }
3214
3215 /**
3216 * Guesses image format based on data in the image.
3217 */
3218 AVImageFormat *av_probe_image_format(AVProbeData *pd)
3219 {
3220 AVImageFormat *fmt1, *fmt;
3221 int score, score_max;
3222
3223 fmt = NULL;
3224 score_max = 0;
3225 for(fmt1 = first_image_format; fmt1 != NULL; fmt1 = fmt1->next) {
3226 if (fmt1->img_probe) {
3227 score = fmt1->img_probe(pd);
3228 if (score > score_max) {
3229 score_max = score;
3230 fmt = fmt1;
3231 }
3232 }
3233 }
3234 return fmt;
3235 }
3236
3237 /**
3238 * Guesses image format based on file name extensions.
3239 */
3240 AVImageFormat *guess_image_format(const char *filename)
3241 {
3242 AVImageFormat *fmt1;
3243
3244 for(fmt1 = first_image_format; fmt1 != NULL; fmt1 = fmt1->next) {
3245 if (fmt1->extensions && match_ext(filename, fmt1->extensions))
3246 return fmt1;
3247 }
3248 return NULL;
3249 }
3250
3251 /**
3252 * Read an image from a stream.
3253 * @param gb byte stream containing the image
3254 * @param fmt image format, NULL if probing is required
3255 */
3256 int av_read_image(ByteIOContext *pb, const char *filename,
3257 AVImageFormat *fmt,
3258 int (*alloc_cb)(void *, AVImageInfo *info), void *opaque)
3259 {
3260 uint8_t buf[PROBE_BUF_MIN];
3261 AVProbeData probe_data, *pd = &probe_data;
3262 offset_t pos;
3263 int ret;
3264
3265 if (!fmt) {
3266 pd->filename = filename;
3267 pd->buf = buf;
3268 pos = url_ftell(