comparison Plugins/Input/wma/libffwma/futils.c @ 137:b8d4c1faa6d7 trunk

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