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