Statistics
| Branch: | Revision:

ffmpeg / libavformat / utils.c @ 5aa0a644

History | View | Annotate | Download (46 KB)

1 de6d9b64 Fabrice Bellard
/*
2
 * Various utilities for ffmpeg system
3 19720f15 Fabrice Bellard
 * Copyright (c) 2000, 2001, 2002 Fabrice Bellard
4 de6d9b64 Fabrice Bellard
 *
5 19720f15 Fabrice Bellard
 * 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 de6d9b64 Fabrice Bellard
 *
10 19720f15 Fabrice Bellard
 * This library is distributed in the hope that it will be useful,
11 de6d9b64 Fabrice Bellard
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 19720f15 Fabrice Bellard
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13
 * Lesser General Public License for more details.
14 de6d9b64 Fabrice Bellard
 *
15 19720f15 Fabrice Bellard
 * 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 de6d9b64 Fabrice Bellard
 */
19 8be1c656 Fabrice Bellard
#include "avformat.h"
20 c5510dd6 Philip Gladstone
21 b9a281db Fabrice Bellard
AVInputFormat *first_iformat;
22
AVOutputFormat *first_oformat;
23 87a0a681 Fabrice Bellard
AVImageFormat *first_image_format;
24 de6d9b64 Fabrice Bellard
25 b9a281db Fabrice Bellard
void av_register_input_format(AVInputFormat *format)
26 de6d9b64 Fabrice Bellard
{
27 b9a281db Fabrice Bellard
    AVInputFormat **p;
28
    p = &first_iformat;
29
    while (*p != NULL) p = &(*p)->next;
30
    *p = format;
31
    format->next = NULL;
32
}
33
34
void av_register_output_format(AVOutputFormat *format)
35
{
36
    AVOutputFormat **p;
37
    p = &first_oformat;
38 de6d9b64 Fabrice Bellard
    while (*p != NULL) p = &(*p)->next;
39
    *p = format;
40
    format->next = NULL;
41
}
42
43 5b25dfa7 Fabrice Bellard
int match_ext(const char *filename, const char *extensions)
44 de6d9b64 Fabrice Bellard
{
45
    const char *ext, *p;
46
    char ext1[32], *q;
47
48
    ext = strrchr(filename, '.');
49
    if (ext) {
50
        ext++;
51
        p = extensions;
52
        for(;;) {
53
            q = ext1;
54
            while (*p != '\0' && *p != ',') 
55
                *q++ = *p++;
56
            *q = '\0';
57
            if (!strcasecmp(ext1, ext)) 
58
                return 1;
59
            if (*p == '\0') 
60
                break;
61
            p++;
62
        }
63
    }
64
    return 0;
65
}
66
67 b9a281db Fabrice Bellard
AVOutputFormat *guess_format(const char *short_name, const char *filename, 
68
                             const char *mime_type)
69 de6d9b64 Fabrice Bellard
{
70 b9a281db Fabrice Bellard
    AVOutputFormat *fmt, *fmt_found;
71 de6d9b64 Fabrice Bellard
    int score_max, score;
72
73 87a0a681 Fabrice Bellard
    /* specific test for image sequences */
74 94d883e8 Fabrice Bellard
    if (!short_name && filename && 
75
        filename_number_test(filename) >= 0 &&
76
        guess_image_format(filename)) {
77 87a0a681 Fabrice Bellard
        return guess_format("image", NULL, NULL);
78
    }
79
80 de6d9b64 Fabrice Bellard
    /* find the proper file type */
81
    fmt_found = NULL;
82
    score_max = 0;
83 b9a281db Fabrice Bellard
    fmt = first_oformat;
84 de6d9b64 Fabrice Bellard
    while (fmt != NULL) {
85
        score = 0;
86
        if (fmt->name && short_name && !strcmp(fmt->name, short_name))
87
            score += 100;
88
        if (fmt->mime_type && mime_type && !strcmp(fmt->mime_type, mime_type))
89
            score += 10;
90
        if (filename && fmt->extensions && 
91
            match_ext(filename, fmt->extensions)) {
92
            score += 5;
93
        }
94
        if (score > score_max) {
95
            score_max = score;
96
            fmt_found = fmt;
97
        }
98
        fmt = fmt->next;
99
    }
100
    return fmt_found;
101
}   
102
103 c5510dd6 Philip Gladstone
AVOutputFormat *guess_stream_format(const char *short_name, const char *filename, 
104
                             const char *mime_type)
105
{
106
    AVOutputFormat *fmt = guess_format(short_name, filename, mime_type);
107
108
    if (fmt) {
109
        AVOutputFormat *stream_fmt;
110
        char stream_format_name[64];
111
112
        snprintf(stream_format_name, sizeof(stream_format_name), "%s_stream", fmt->name);
113
        stream_fmt = guess_format(stream_format_name, NULL, NULL);
114
115
        if (stream_fmt)
116
            fmt = stream_fmt;
117
    }
118
119
    return fmt;
120
}
121
122 b9a281db Fabrice Bellard
AVInputFormat *av_find_input_format(const char *short_name)
123
{
124
    AVInputFormat *fmt;
125
    for(fmt = first_iformat; fmt != NULL; fmt = fmt->next) {
126
        if (!strcmp(fmt->name, short_name))
127
            return fmt;
128
    }
129
    return NULL;
130
}
131
132 de6d9b64 Fabrice Bellard
/* memory handling */
133
134 b9a281db Fabrice Bellard
/**
135 6fa5a56c Fabrice Bellard
 * Default packet destructor 
136
 */
137
static void av_destruct_packet(AVPacket *pkt)
138
{
139
    av_free(pkt->data);
140
    pkt->data = NULL; pkt->size = 0;
141
}
142
143
/**
144 b9a281db Fabrice Bellard
 * Allocate the payload of a packet and intialized its fields to default values.
145
 *
146
 * @param pkt packet
147
 * @param size wanted payload size
148
 * @return 0 if OK. AVERROR_xxx otherwise.
149
 */
150 de6d9b64 Fabrice Bellard
int av_new_packet(AVPacket *pkt, int size)
151
{
152 6fa5a56c Fabrice Bellard
    void *data = av_malloc(size + FF_INPUT_BUFFER_PADDING_SIZE);
153
    if (!data)
154 b9a281db Fabrice Bellard
        return AVERROR_NOMEM;
155 6fa5a56c Fabrice Bellard
    memset(data + size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
156 8cd5be98 Michael Niedermayer
157 6fa5a56c Fabrice Bellard
    av_init_packet(pkt);
158
    pkt->data = data; 
159
    pkt->size = size;
160
    pkt->destruct = av_destruct_packet;
161 de6d9b64 Fabrice Bellard
    return 0;
162
}
163
164
/* fifo handling */
165
166
int fifo_init(FifoBuffer *f, int size)
167
{
168 1ea4f593 Fabrice Bellard
    f->buffer = av_malloc(size);
169 de6d9b64 Fabrice Bellard
    if (!f->buffer)
170
        return -1;
171
    f->end = f->buffer + size;
172
    f->wptr = f->rptr = f->buffer;
173
    return 0;
174
}
175
176
void fifo_free(FifoBuffer *f)
177
{
178 1ea4f593 Fabrice Bellard
    av_free(f->buffer);
179 de6d9b64 Fabrice Bellard
}
180
181 0c1a9eda Zdenek Kabelac
int fifo_size(FifoBuffer *f, uint8_t *rptr)
182 de6d9b64 Fabrice Bellard
{
183
    int size;
184
185
    if (f->wptr >= rptr) {
186
        size = f->wptr - rptr;
187
    } else {
188
        size = (f->end - rptr) + (f->wptr - f->buffer);
189
    }
190
    return size;
191
}
192
193
/* get data from the fifo (return -1 if not enough data) */
194 0c1a9eda Zdenek Kabelac
int fifo_read(FifoBuffer *f, uint8_t *buf, int buf_size, uint8_t **rptr_ptr)
195 de6d9b64 Fabrice Bellard
{
196 0c1a9eda Zdenek Kabelac
    uint8_t *rptr = *rptr_ptr;
197 de6d9b64 Fabrice Bellard
    int size, len;
198
199
    if (f->wptr >= rptr) {
200
        size = f->wptr - rptr;
201
    } else {
202
        size = (f->end - rptr) + (f->wptr - f->buffer);
203
    }
204
    
205
    if (size < buf_size)
206
        return -1;
207
    while (buf_size > 0) {
208
        len = f->end - rptr;
209
        if (len > buf_size)
210
            len = buf_size;
211
        memcpy(buf, rptr, len);
212
        buf += len;
213
        rptr += len;
214
        if (rptr >= f->end)
215
            rptr = f->buffer;
216
        buf_size -= len;
217
    }
218
    *rptr_ptr = rptr;
219
    return 0;
220
}
221
222 0c1a9eda Zdenek Kabelac
void fifo_write(FifoBuffer *f, uint8_t *buf, int size, uint8_t **wptr_ptr)
223 de6d9b64 Fabrice Bellard
{
224
    int len;
225 0c1a9eda Zdenek Kabelac
    uint8_t *wptr;
226 de6d9b64 Fabrice Bellard
    wptr = *wptr_ptr;
227
    while (size > 0) {
228
        len = f->end - wptr;
229
        if (len > size)
230
            len = size;
231
        memcpy(wptr, buf, len);
232
        wptr += len;
233
        if (wptr >= f->end)
234
            wptr = f->buffer;
235
        buf += len;
236
        size -= len;
237
    }
238
    *wptr_ptr = wptr;
239
}
240
241 b9a281db Fabrice Bellard
int filename_number_test(const char *filename)
242
{
243
    char buf[1024];
244
    return get_frame_filename(buf, sizeof(buf), filename, 1);
245
}
246
247
/* guess file format */
248 a25e098d Fabrice Bellard
AVInputFormat *av_probe_input_format(AVProbeData *pd, int is_opened)
249 b9a281db Fabrice Bellard
{
250
    AVInputFormat *fmt1, *fmt;
251
    int score, score_max;
252
253
    fmt = NULL;
254
    score_max = 0;
255
    for(fmt1 = first_iformat; fmt1 != NULL; fmt1 = fmt1->next) {
256
        if (!is_opened && !(fmt1->flags & AVFMT_NOFILE))
257
            continue;
258
        score = 0;
259 a8dbe951 Philip Gladstone
        if (fmt1->read_probe) {
260
            score = fmt1->read_probe(pd);
261
        } else if (fmt1->extensions) {
262 b9a281db Fabrice Bellard
            if (match_ext(pd->filename, fmt1->extensions)) {
263
                score = 50;
264
            }
265 a8dbe951 Philip Gladstone
        } 
266 b9a281db Fabrice Bellard
        if (score > score_max) {
267
            score_max = score;
268
            fmt = fmt1;
269
        }
270
    }
271
    return fmt;
272
}
273
274
/************************************************************/
275
/* input media file */
276 96baaa6a Fabrice Bellard
277 b9a281db Fabrice Bellard
#define PROBE_BUF_SIZE 2048
278
279
/**
280
 * Open a media file as input. The codec are not opened. Only the file
281
 * header (if present) is read.
282
 *
283
 * @param ic_ptr the opened media file handle is put here
284
 * @param filename filename to open.
285
 * @param fmt if non NULL, force the file format to use
286
 * @param buf_size optional buffer size (zero if default is OK)
287
 * @param ap additionnal parameters needed when opening the file (NULL if default)
288
 * @return 0 if OK. AVERROR_xxx otherwise.
289
 */
290
int av_open_input_file(AVFormatContext **ic_ptr, const char *filename, 
291
                       AVInputFormat *fmt,
292
                       int buf_size,
293
                       AVFormatParameters *ap)
294 de6d9b64 Fabrice Bellard
{
295
    AVFormatContext *ic = NULL;
296 b6892136 Fabrice Bellard
    int err, must_open_file;
297 b9a281db Fabrice Bellard
    char buf[PROBE_BUF_SIZE];
298
    AVProbeData probe_data, *pd = &probe_data;
299 de6d9b64 Fabrice Bellard
300
    ic = av_mallocz(sizeof(AVFormatContext));
301 b9a281db Fabrice Bellard
    if (!ic) {
302
        err = AVERROR_NOMEM;
303 de6d9b64 Fabrice Bellard
        goto fail;
304
    }
305 12f996ed Fabrice Bellard
    ic->duration = AV_NOPTS_VALUE;
306
    ic->start_time = AV_NOPTS_VALUE;
307 b9a281db Fabrice Bellard
    pstrcpy(ic->filename, sizeof(ic->filename), filename);
308
    pd->filename = ic->filename;
309
    pd->buf = buf;
310
    pd->buf_size = 0;
311
312
    if (!fmt) {
313
        /* guess format if no file can be opened  */
314 a25e098d Fabrice Bellard
        fmt = av_probe_input_format(pd, 0);
315 de6d9b64 Fabrice Bellard
    }
316
317 b6892136 Fabrice Bellard
    /* do not open file if the format does not need it. XXX: specific
318
       hack needed to handle RTSP/TCP */
319
    must_open_file = 1;
320 00b4fdb7 Fabrice Bellard
    if ((fmt && (fmt->flags & AVFMT_NOFILE)) 
321
#ifdef CONFIG_NETWORK
322
        || (fmt == &rtp_demux && !strcmp(filename, "null"))
323
#endif
324
        ) {
325 b6892136 Fabrice Bellard
        must_open_file = 0;
326
    }
327
328
    if (!fmt || must_open_file) {
329 87a0a681 Fabrice Bellard
        /* if no file needed do not try to open one */
330 b9a281db Fabrice Bellard
        if (url_fopen(&ic->pb, filename, URL_RDONLY) < 0) {
331
            err = AVERROR_IO;
332 96baaa6a Fabrice Bellard
            goto fail;
333 b9a281db Fabrice Bellard
        }
334 96baaa6a Fabrice Bellard
        if (buf_size > 0) {
335
            url_setbufsize(&ic->pb, buf_size);
336
        }
337 5b25dfa7 Fabrice Bellard
        if (!fmt) {
338
            /* read probe data */
339
            pd->buf_size = get_buffer(&ic->pb, buf, PROBE_BUF_SIZE);
340
            url_fseek(&ic->pb, 0, SEEK_SET);
341
        }
342 96baaa6a Fabrice Bellard
    }
343
    
344 b9a281db Fabrice Bellard
    /* guess file format */
345
    if (!fmt) {
346 a25e098d Fabrice Bellard
        fmt = av_probe_input_format(pd, 1);
347 b9a281db Fabrice Bellard
    }
348
349
    /* if still no format found, error */
350
    if (!fmt) {
351
        err = AVERROR_NOFMT;
352 a05c8d71 Michael Niedermayer
        goto fail1;
353 de6d9b64 Fabrice Bellard
    }
354 b9a281db Fabrice Bellard
        
355 67d06418 Fabrice Bellard
    /* XXX: suppress this hack for redirectors */
356 f3ec2d46 Slavik Gnatenko
#ifdef CONFIG_NETWORK
357 67d06418 Fabrice Bellard
    if (fmt == &redir_demux) {
358
        err = redir_open(ic_ptr, &ic->pb);
359
        url_fclose(&ic->pb);
360
        av_free(ic);
361
        return err;
362
    }
363 9b2e001f Bill Eldridge
#endif
364 67d06418 Fabrice Bellard
365 b9a281db Fabrice Bellard
    ic->iformat = fmt;
366 de6d9b64 Fabrice Bellard
367 87a0a681 Fabrice Bellard
    /* check filename in case of an image number is expected */
368
    if (ic->iformat->flags & AVFMT_NEEDNUMBER) {
369
        if (filename_number_test(ic->filename) < 0) { 
370
            err = AVERROR_NUMEXPECTED;
371
            goto fail1;
372
        }
373
    }
374
    
375 b9a281db Fabrice Bellard
    /* allocate private data */
376 98486a6b Roman Shaposhnik
    if (fmt->priv_data_size > 0) {
377
        ic->priv_data = av_mallocz(fmt->priv_data_size);
378
        if (!ic->priv_data) {
379
            err = AVERROR_NOMEM;
380 a05c8d71 Michael Niedermayer
        goto fail1;
381 98486a6b Roman Shaposhnik
        }
382
    } else
383
        ic->priv_data = NULL;
384 b9a281db Fabrice Bellard
385 916c80e9 Fabrice Bellard
    /* default pts settings is MPEG like */
386
    av_set_pts_info(ic, 33, 1, 90000);
387
388 b9a281db Fabrice Bellard
    err = ic->iformat->read_header(ic, ap);
389
    if (err < 0)
390
        goto fail1;
391
    *ic_ptr = ic;
392
    return 0;
393
 fail1:
394 b6892136 Fabrice Bellard
    if (!fmt || must_open_file) {
395 b9a281db Fabrice Bellard
        url_fclose(&ic->pb);
396
    }
397 de6d9b64 Fabrice Bellard
 fail:
398 b9a281db Fabrice Bellard
    if (ic) {
399 a8dbe951 Philip Gladstone
        av_freep(&ic->priv_data);
400 b9a281db Fabrice Bellard
    }
401 1ea4f593 Fabrice Bellard
    av_free(ic);
402 b9a281db Fabrice Bellard
    *ic_ptr = NULL;
403
    return err;
404 de6d9b64 Fabrice Bellard
}
405
406 b9a281db Fabrice Bellard
/**
407
 * Read a packet from a media file
408
 * @param s media file handle
409
 * @param pkt is filled 
410
 * @return 0 if OK. AVERROR_xxx if error.
411
 */
412 de6d9b64 Fabrice Bellard
int av_read_packet(AVFormatContext *s, AVPacket *pkt)
413
{
414
    AVPacketList *pktl;
415
416
    pktl = s->packet_buffer;
417
    if (pktl) {
418
        /* read packet from packet buffer, if there is data */
419
        *pkt = pktl->pkt;
420
        s->packet_buffer = pktl->next;
421 1ea4f593 Fabrice Bellard
        av_free(pktl);
422 de6d9b64 Fabrice Bellard
        return 0;
423
    } else {
424 b9a281db Fabrice Bellard
        return s->iformat->read_packet(s, pkt);
425
    }
426
}
427
428 12f996ed Fabrice Bellard
429
/* return TRUE if the stream has accurate timings for at least one component */
430
static int av_has_timings(AVFormatContext *ic)
431
{
432
    int i;
433
    AVStream *st;
434
435
    for(i = 0;i < ic->nb_streams; i++) {
436
        st = ic->streams[i];
437
        if (st->start_time != AV_NOPTS_VALUE &&
438
            st->duration != AV_NOPTS_VALUE)
439
            return 1;
440
    }
441
    return 0;
442
}
443
444
/* estimate the stream timings from the one of each components. Also
445
   compute the global bitrate if possible */
446
static void av_update_stream_timings(AVFormatContext *ic)
447
{
448
    int64_t start_time, end_time, end_time1;
449
    int i;
450
    AVStream *st;
451
452
    start_time = MAXINT64;
453
    end_time = MININT64;
454
    for(i = 0;i < ic->nb_streams; i++) {
455
        st = ic->streams[i];
456
        if (st->start_time != AV_NOPTS_VALUE) {
457
            if (st->start_time < start_time)
458
                start_time = st->start_time;
459
            if (st->duration != AV_NOPTS_VALUE) {
460
                end_time1 = st->start_time + st->duration;
461
                if (end_time1 > end_time)
462
                    end_time = end_time1;
463
            }
464
        }
465
    }
466
    if (start_time != MAXINT64) {
467
        ic->start_time = start_time;
468
        if (end_time != MAXINT64) {
469
            ic->duration = end_time - start_time;
470
            if (ic->file_size > 0) {
471
                /* compute the bit rate */
472
                ic->bit_rate = (double)ic->file_size * 8.0 * AV_TIME_BASE / 
473
                    (double)ic->duration;
474
            }
475
        }
476
    }
477
478
}
479
480
static void fill_all_stream_timings(AVFormatContext *ic)
481
{
482
    int i;
483
    AVStream *st;
484
485
    av_update_stream_timings(ic);
486
    for(i = 0;i < ic->nb_streams; i++) {
487
        st = ic->streams[i];
488
        if (st->start_time == AV_NOPTS_VALUE) {
489
            st->start_time = ic->start_time;
490
            st->duration = ic->duration;
491
        }
492
    }
493
}
494
495
static void av_estimate_timings_from_bit_rate(AVFormatContext *ic)
496
{
497
    int64_t filesize, duration;
498
    int bit_rate, i;
499
    AVStream *st;
500
501
    /* if bit_rate is already set, we believe it */
502
    if (ic->bit_rate == 0) {
503
        bit_rate = 0;
504
        for(i=0;i<ic->nb_streams;i++) {
505
            st = ic->streams[i];
506
            bit_rate += st->codec.bit_rate;
507
        }
508
        ic->bit_rate = bit_rate;
509
    }
510
511
    /* if duration is already set, we believe it */
512
    if (ic->duration == AV_NOPTS_VALUE && 
513
        ic->bit_rate != 0 && 
514
        ic->file_size != 0)  {
515
        filesize = ic->file_size;
516
        if (filesize > 0) {
517
            duration = (int64_t)((8 * AV_TIME_BASE * (double)filesize) / (double)ic->bit_rate);
518
            for(i = 0; i < ic->nb_streams; i++) {
519
                st = ic->streams[i];
520
                if (st->start_time == AV_NOPTS_VALUE ||
521
                    st->duration == AV_NOPTS_VALUE) {
522
                    st->start_time = 0;
523
                    st->duration = duration;
524
                }
525
            }
526
        }
527
    }
528
}
529
530
static void flush_packet_queue(AVFormatContext *s)
531
{
532
    AVPacketList *pktl;
533
534
    for(;;) {
535
        pktl = s->packet_buffer;
536
        if (!pktl) 
537
            break;
538
        s->packet_buffer = pktl->next;
539 0a5f92a1 Michael Niedermayer
        av_free_packet(&pktl->pkt);
540 12f996ed Fabrice Bellard
        av_free(pktl);
541
    }
542
}
543
544
#define DURATION_MAX_READ_SIZE 250000
545
546
/* only usable for MPEG-PS streams */
547
static void av_estimate_timings_from_pts(AVFormatContext *ic)
548
{
549
    AVPacket pkt1, *pkt = &pkt1;
550
    AVStream *st;
551
    int read_size, i, ret;
552
    int64_t start_time, end_time, end_time1;
553
    int64_t filesize, offset, duration;
554
    
555
    /* we read the first packets to get the first PTS (not fully
556
       accurate, but it is enough now) */
557
    url_fseek(&ic->pb, 0, SEEK_SET);
558
    read_size = 0;
559
    for(;;) {
560
        if (read_size >= DURATION_MAX_READ_SIZE)
561
            break;
562
        /* if all info is available, we can stop */
563
        for(i = 0;i < ic->nb_streams; i++) {
564
            st = ic->streams[i];
565
            if (st->start_time == AV_NOPTS_VALUE)
566
                break;
567
        }
568
        if (i == ic->nb_streams)
569
            break;
570
571
        ret = av_read_packet(ic, pkt);
572
        if (ret != 0)
573
            break;
574
        read_size += pkt->size;
575
        st = ic->streams[pkt->stream_index];
576
        if (pkt->pts != AV_NOPTS_VALUE) {
577
            if (st->start_time == AV_NOPTS_VALUE)
578
                st->start_time = (int64_t)((double)pkt->pts * ic->pts_num * (double)AV_TIME_BASE / ic->pts_den);
579 0a5f92a1 Michael Niedermayer
        }
580
        av_free_packet(pkt);
581
    }
582 12f996ed Fabrice Bellard
583
    /* we compute the minimum start_time and use it as default */
584
    start_time = MAXINT64;
585
    for(i = 0; i < ic->nb_streams; i++) {
586
        st = ic->streams[i];
587
        if (st->start_time != AV_NOPTS_VALUE &&
588
            st->start_time < start_time)
589
            start_time = st->start_time;
590
    }
591
    if (start_time != MAXINT64)
592
        ic->start_time = start_time;
593
    
594
    /* estimate the end time (duration) */
595
    /* XXX: may need to support wrapping */
596
    filesize = ic->file_size;
597
    offset = filesize - DURATION_MAX_READ_SIZE;
598
    if (offset < 0)
599
        offset = 0;
600
601
    /* flush packet queue */
602
    flush_packet_queue(ic);
603
604
    url_fseek(&ic->pb, offset, SEEK_SET);
605
    read_size = 0;
606
    for(;;) {
607
        if (read_size >= DURATION_MAX_READ_SIZE)
608
            break;
609
        /* if all info is available, we can stop */
610
        for(i = 0;i < ic->nb_streams; i++) {
611
            st = ic->streams[i];
612
            if (st->duration == AV_NOPTS_VALUE)
613
                break;
614
        }
615
        if (i == ic->nb_streams)
616
            break;
617
        
618
        ret = av_read_packet(ic, pkt);
619
        if (ret != 0)
620
            break;
621
        read_size += pkt->size;
622
        st = ic->streams[pkt->stream_index];
623
        if (pkt->pts != AV_NOPTS_VALUE) {
624
            end_time = (int64_t)((double)pkt->pts * ic->pts_num * (double)AV_TIME_BASE / ic->pts_den);
625
            duration = end_time - st->start_time;
626
            if (duration > 0) {
627
                if (st->duration == AV_NOPTS_VALUE ||
628
                    st->duration < duration)
629
                    st->duration = duration;
630
            }
631
        }
632
        av_free_packet(pkt);
633
    }
634
    
635
    /* estimate total duration */
636
    end_time = MININT64;
637
    for(i = 0;i < ic->nb_streams; i++) {
638
        st = ic->streams[i];
639
        if (st->duration != AV_NOPTS_VALUE) {
640
            end_time1 = st->start_time + st->duration;
641
            if (end_time1 > end_time)
642
                end_time = end_time1;
643
        }
644
    }
645
    
646
    /* update start_time (new stream may have been created, so we do
647
       it at the end */
648
    if (ic->start_time != AV_NOPTS_VALUE) {
649
        for(i = 0; i < ic->nb_streams; i++) {
650
            st = ic->streams[i];
651
            if (st->start_time == AV_NOPTS_VALUE)
652
                st->start_time = ic->start_time;
653
        }
654
    }
655
656
    if (end_time != MININT64) {
657
        /* put dummy values for duration if needed */
658
        for(i = 0;i < ic->nb_streams; i++) {
659
            st = ic->streams[i];
660
            if (st->duration == AV_NOPTS_VALUE && 
661
                st->start_time != AV_NOPTS_VALUE)
662
                st->duration = end_time - st->start_time;
663
        }
664
        ic->duration = end_time - ic->start_time;
665
    }
666
667
    url_fseek(&ic->pb, 0, SEEK_SET);
668
}
669
670
static void av_estimate_timings(AVFormatContext *ic)
671
{
672
    URLContext *h;
673
    int64_t file_size;
674
675
    /* get the file size, if possible */
676
    if (ic->iformat->flags & AVFMT_NOFILE) {
677
        file_size = 0;
678
    } else {
679
        h = url_fileno(&ic->pb);
680
        file_size = url_filesize(h);
681
        if (file_size < 0)
682
            file_size = 0;
683
    }
684
    ic->file_size = file_size;
685
686
    if (ic->iformat == &mpegps_demux) {
687
        /* get accurate estimate from the PTSes */
688
        av_estimate_timings_from_pts(ic);
689
    } else if (av_has_timings(ic)) {
690
        /* at least one components has timings - we use them for all
691
           the components */
692
        fill_all_stream_timings(ic);
693
    } else {
694
        /* less precise: use bit rate info */
695
        av_estimate_timings_from_bit_rate(ic);
696
    }
697
    av_update_stream_timings(ic);
698
699
#if 0
700
    {
701
        int i;
702
        AVStream *st;
703
        for(i = 0;i < ic->nb_streams; i++) {
704
            st = ic->streams[i];
705
        printf("%d: start_time: %0.3f duration: %0.3f\n", 
706
               i, (double)st->start_time / AV_TIME_BASE, 
707
               (double)st->duration / AV_TIME_BASE);
708
        }
709
        printf("stream: start_time: %0.3f duration: %0.3f bitrate=%d kb/s\n", 
710
               (double)ic->start_time / AV_TIME_BASE, 
711
               (double)ic->duration / AV_TIME_BASE,
712
               ic->bit_rate / 1000);
713
    }
714
#endif
715
}
716
717 b9a281db Fabrice Bellard
/* state for codec information */
718
#define CSTATE_NOTFOUND    0
719
#define CSTATE_DECODING    1
720
#define CSTATE_FOUND       2
721
722
static int has_codec_parameters(AVCodecContext *enc)
723
{
724
    int val;
725
    switch(enc->codec_type) {
726
    case CODEC_TYPE_AUDIO:
727
        val = enc->sample_rate;
728
        break;
729
    case CODEC_TYPE_VIDEO:
730
        val = enc->width;
731
        break;
732
    default:
733
        val = 1;
734
        break;
735
    }
736
    return (val != 0);
737
}
738
739
/**
740
 * Read the beginning of a media file to get stream information. This
741
 * is useful for file formats with no headers such as MPEG. This
742
 * function also compute the real frame rate in case of mpeg2 repeat
743
 * frame mode.
744
 *
745
 * @param ic media file handle
746
 * @return >=0 if OK. AVERROR_xxx if error.  
747
 */
748
int av_find_stream_info(AVFormatContext *ic)
749
{
750
    int i, count, ret, got_picture, size, read_size;
751
    AVCodec *codec;
752
    AVStream *st;
753
    AVPacket *pkt;
754 492cd3a9 Michael Niedermayer
    AVFrame picture;
755 b9a281db Fabrice Bellard
    AVPacketList *pktl=NULL, **ppktl;
756
    short samples[AVCODEC_MAX_AUDIO_FRAME_SIZE / 2];
757 0c1a9eda Zdenek Kabelac
    uint8_t *ptr;
758 b9a281db Fabrice Bellard
    int min_read_size, max_read_size;
759
760
    /* typical mpeg ts rate is 40 Mbits. DVD rate is about 10
761 b530f842 Michael Niedermayer
       Mbits. We read at most 0.2 second of file to find all streams */
762 b9a281db Fabrice Bellard
763
    /* XXX: base it on stream bitrate when possible */
764
    if (ic->iformat == &mpegts_demux) {
765
        /* maximum number of bytes we accept to read to find all the streams
766
           in a file */
767 b530f842 Michael Niedermayer
        min_read_size = 6000000;
768 b9a281db Fabrice Bellard
    } else {
769 b530f842 Michael Niedermayer
        min_read_size = 250000;
770 b9a281db Fabrice Bellard
    }
771
    /* max read size is 2 seconds of video max */
772 b530f842 Michael Niedermayer
    max_read_size = min_read_size * 10;
773 b9a281db Fabrice Bellard
774
    /* set initial codec state */
775
    for(i=0;i<ic->nb_streams;i++) {
776
        st = ic->streams[i];
777
        if (has_codec_parameters(&st->codec))
778
            st->codec_info_state = CSTATE_FOUND;
779
        else
780
            st->codec_info_state = CSTATE_NOTFOUND;
781
        st->codec_info_nb_repeat_frames = 0;
782
        st->codec_info_nb_real_frames = 0;
783
    }
784
785
    count = 0;
786
    read_size = 0;
787
    ppktl = &ic->packet_buffer;
788
    for(;;) {
789
        /* check if one codec still needs to be handled */
790
        for(i=0;i<ic->nb_streams;i++) {
791
            st = ic->streams[i];
792
            if (st->codec_info_state != CSTATE_FOUND)
793
                break;
794
        }
795
        if (i == ic->nb_streams) {
796
            /* NOTE: if the format has no header, then we need to read
797
               some packets to get most of the streams, so we cannot
798
               stop here */
799
            if (!(ic->iformat->flags & AVFMT_NOHEADER) ||
800
                read_size >= min_read_size) {
801
                /* if we found the info for all the codecs, we can stop */
802
                ret = count;
803
                break;
804
            }
805
        } else {
806
            /* we did not get all the codec info, but we read too much data */
807
            if (read_size >= max_read_size) {
808
                ret = count;
809
                break;
810
            }
811
        }
812
813
        pktl = av_mallocz(sizeof(AVPacketList));
814
        if (!pktl) {
815
            ret = AVERROR_NOMEM;
816
            break;
817
        }
818
819
        /* add the packet in the buffered packet list */
820
        *ppktl = pktl;
821
        ppktl = &pktl->next;
822
823
        /* NOTE: a new stream can be added there if no header in file
824
           (AVFMT_NOHEADER) */
825
        pkt = &pktl->pkt;
826
        if (ic->iformat->read_packet(ic, pkt) < 0) {
827
            /* EOF or error */
828
            ret = -1; /* we could not have all the codec parameters before EOF */
829
            if ((ic->iformat->flags & AVFMT_NOHEADER) &&
830
                i == ic->nb_streams)
831
                ret = 0;
832
            break;
833
        }
834
        read_size += pkt->size;
835
836
        /* open new codecs */
837
        for(i=0;i<ic->nb_streams;i++) {
838
            st = ic->streams[i];
839
            if (st->codec_info_state == CSTATE_NOTFOUND) {
840
                /* set to found in case of error */
841
                st->codec_info_state = CSTATE_FOUND; 
842
                codec = avcodec_find_decoder(st->codec.codec_id);
843
                if (codec) {
844 d7425f59 Michael Niedermayer
                    if(codec->capabilities & CODEC_CAP_TRUNCATED)
845
                        st->codec.flags |= CODEC_FLAG_TRUNCATED;
846
847 b9a281db Fabrice Bellard
                    ret = avcodec_open(&st->codec, codec);
848
                    if (ret >= 0)
849
                        st->codec_info_state = CSTATE_DECODING;
850
                }
851
            }
852
        }
853
854
        st = ic->streams[pkt->stream_index];
855
        if (st->codec_info_state == CSTATE_DECODING) {
856
            /* decode the data and update codec parameters */
857
            ptr = pkt->data;
858
            size = pkt->size;
859
            while (size > 0) {
860
                switch(st->codec.codec_type) {
861
                case CODEC_TYPE_VIDEO:
862
                    ret = avcodec_decode_video(&st->codec, &picture, 
863
                                               &got_picture, ptr, size);
864
                    break;
865
                case CODEC_TYPE_AUDIO:
866
                    ret = avcodec_decode_audio(&st->codec, samples, 
867
                                               &got_picture, ptr, size);
868
                    break;
869
                default:
870
                    ret = -1;
871
                    break;
872
                }
873
                if (ret < 0) {
874
                    /* if error, simply ignore because another packet
875
                       may be OK */
876
                    break;
877
                }
878
                if (got_picture) {
879
                    /* we got the parameters - now we can stop
880
                       examining this stream */
881
                    /* XXX: add a codec info so that we can decide if
882
                       the codec can repeat frames */
883
                    if (st->codec.codec_id == CODEC_ID_MPEG1VIDEO && 
884
                        ic->iformat != &mpegts_demux &&
885
                        st->codec.sub_id == 2) {
886
                        /* for mpeg2 video, we want to know the real
887
                           frame rate, so we decode 40 frames. In mpeg
888
                           TS case we do not do it because it would be
889
                           too long */
890
                        st->codec_info_nb_real_frames++;
891 2ec23b6d Michael Niedermayer
                        st->codec_info_nb_repeat_frames += st->codec.coded_frame->repeat_pict;
892 b9a281db Fabrice Bellard
#if 0
893
                        /* XXX: testing */
894
                        if ((st->codec_info_nb_real_frames % 24) == 23) {
895
                            st->codec_info_nb_repeat_frames += 2;
896
                        }
897
#endif
898
                        /* stop after 40 frames */
899
                        if (st->codec_info_nb_real_frames >= 40) {
900 14bea432 Michael Niedermayer
                            av_reduce(
901
                                &st->r_frame_rate,
902
                                &st->r_frame_rate_base,
903
                                (int64_t)st->codec.frame_rate * st->codec_info_nb_real_frames,
904 e71ea8b2 Michael Niedermayer
                                (st->codec_info_nb_real_frames + (st->codec_info_nb_repeat_frames >> 1)) * st->codec.frame_rate_base,
905 14bea432 Michael Niedermayer
                                1<<30);
906 b9a281db Fabrice Bellard
                            goto close_codec;
907
                        }
908
                    } else {
909
                    close_codec:
910
                        st->codec_info_state = CSTATE_FOUND;
911
                        avcodec_close(&st->codec);
912 24f9709b Fabrice Bellard
                        break;
913 b9a281db Fabrice Bellard
                    }
914
                }
915
                ptr += ret;
916
                size -= ret;
917
            }
918
        }
919
        count++;
920
    }
921
922
    /* close each codec if there are opened */
923
    for(i=0;i<ic->nb_streams;i++) {
924
        st = ic->streams[i];
925
        if (st->codec_info_state == CSTATE_DECODING)
926
            avcodec_close(&st->codec);
927
    }
928
929
    /* set real frame rate info */
930
    for(i=0;i<ic->nb_streams;i++) {
931
        st = ic->streams[i];
932
        if (st->codec.codec_type == CODEC_TYPE_VIDEO) {
933 14bea432 Michael Niedermayer
            if (!st->r_frame_rate){
934
                st->r_frame_rate      = st->codec.frame_rate;
935
                st->r_frame_rate_base = st->codec.frame_rate_base;
936
            }
937 b9a281db Fabrice Bellard
        }
938 de6d9b64 Fabrice Bellard
    }
939 b9a281db Fabrice Bellard
940 12f996ed Fabrice Bellard
941
    av_estimate_timings(ic);
942 b9a281db Fabrice Bellard
    return ret;
943 de6d9b64 Fabrice Bellard
}
944
945 b9a281db Fabrice Bellard
/**
946
 * Close a media file (but not its codecs)
947
 *
948
 * @param s media file handle
949
 */
950 de6d9b64 Fabrice Bellard
void av_close_input_file(AVFormatContext *s)
951
{
952 b6892136 Fabrice Bellard
    int i, must_open_file;
953 de6d9b64 Fabrice Bellard
954 b9a281db Fabrice Bellard
    if (s->iformat->read_close)
955
        s->iformat->read_close(s);
956 de6d9b64 Fabrice Bellard
    for(i=0;i<s->nb_streams;i++) {
957 1ea4f593 Fabrice Bellard
        av_free(s->streams[i]);
958 de6d9b64 Fabrice Bellard
    }
959
    if (s->packet_buffer) {
960
        AVPacketList *p, *p1;
961
        p = s->packet_buffer;
962
        while (p != NULL) {
963
            p1 = p->next;
964
            av_free_packet(&p->pkt);
965 1ea4f593 Fabrice Bellard
            av_free(p);
966 de6d9b64 Fabrice Bellard
            p = p1;
967
        }
968
        s->packet_buffer = NULL;
969
    }
970 b6892136 Fabrice Bellard
    must_open_file = 1;
971 00b4fdb7 Fabrice Bellard
    if ((s->iformat->flags & AVFMT_NOFILE)
972
#ifdef CONFIG_NETWORK
973
        || (s->iformat == &rtp_demux && !strcmp(s->filename, "null"))
974
#endif
975
        ) {
976 b6892136 Fabrice Bellard
        must_open_file = 0;
977
    }
978
    if (must_open_file) {
979 96baaa6a Fabrice Bellard
        url_fclose(&s->pb);
980
    }
981 a8dbe951 Philip Gladstone
    av_freep(&s->priv_data);
982 1ea4f593 Fabrice Bellard
    av_free(s);
983 de6d9b64 Fabrice Bellard
}
984
985 b9a281db Fabrice Bellard
/**
986
 * Add a new stream to a media file. Can only be called in the
987
 * read_header function. If the flag AVFMT_NOHEADER is in the format
988
 * description, then new streams can be added in read_packet too.
989
 *
990
 *
991
 * @param s media file handle
992
 * @param id file format dependent stream id
993
 */
994
AVStream *av_new_stream(AVFormatContext *s, int id)
995
{
996
    AVStream *st;
997
998
    if (s->nb_streams >= MAX_STREAMS)
999
        return NULL;
1000
1001
    st = av_mallocz(sizeof(AVStream));
1002
    if (!st)
1003
        return NULL;
1004 1e491e29 Michael Niedermayer
    avcodec_get_context_defaults(&st->codec);
1005 48091512 Fabrice Bellard
    if (s->iformat) {
1006
        /* no default bitrate if decoding */
1007
        st->codec.bit_rate = 0;
1008
    }
1009 b9a281db Fabrice Bellard
    st->index = s->nb_streams;
1010
    st->id = id;
1011 12f996ed Fabrice Bellard
    st->start_time = AV_NOPTS_VALUE;
1012
    st->duration = AV_NOPTS_VALUE;
1013 b9a281db Fabrice Bellard
    s->streams[s->nb_streams++] = st;
1014
    return st;
1015
}
1016
1017
/************************************************************/
1018
/* output media file */
1019 de6d9b64 Fabrice Bellard
1020 87a0a681 Fabrice Bellard
int av_set_parameters(AVFormatContext *s, AVFormatParameters *ap)
1021
{
1022
    int ret;
1023 98486a6b Roman Shaposhnik
    
1024
    if (s->oformat->priv_data_size > 0) {
1025
        s->priv_data = av_mallocz(s->oformat->priv_data_size);
1026
        if (!s->priv_data)
1027
            return AVERROR_NOMEM;
1028
    } else
1029
        s->priv_data = NULL;
1030
        
1031 87a0a681 Fabrice Bellard
    if (s->oformat->set_parameters) {
1032
        ret = s->oformat->set_parameters(s, ap);
1033
        if (ret < 0)
1034
            return ret;
1035
    }
1036
    return 0;
1037
}
1038
1039 b9a281db Fabrice Bellard
/**
1040
 * allocate the stream private data and write the stream header to an
1041
 * output media file
1042
 *
1043
 * @param s media file handle
1044
 * @return 0 if OK. AVERROR_xxx if error.  
1045
 */
1046
int av_write_header(AVFormatContext *s)
1047
{
1048 1e51d801 Fabrice Bellard
    int ret, i;
1049
    AVStream *st;
1050
1051 916c80e9 Fabrice Bellard
    /* default pts settings is MPEG like */
1052
    av_set_pts_info(s, 33, 1, 90000);
1053 1e51d801 Fabrice Bellard
    ret = s->oformat->write_header(s);
1054
    if (ret < 0)
1055
        return ret;
1056
1057
    /* init PTS generation */
1058
    for(i=0;i<s->nb_streams;i++) {
1059
        st = s->streams[i];
1060
1061
        switch (st->codec.codec_type) {
1062
        case CODEC_TYPE_AUDIO:
1063
            av_frac_init(&st->pts, 0, 0, 
1064 0c1a9eda Zdenek Kabelac
                         (int64_t)s->pts_num * st->codec.sample_rate);
1065 1e51d801 Fabrice Bellard
            break;
1066
        case CODEC_TYPE_VIDEO:
1067
            av_frac_init(&st->pts, 0, 0, 
1068 0c1a9eda Zdenek Kabelac
                         (int64_t)s->pts_num * st->codec.frame_rate);
1069 1e51d801 Fabrice Bellard
            break;
1070
        default:
1071
            break;
1072
        }
1073
    }
1074
    return 0;
1075 b9a281db Fabrice Bellard
}
1076
1077
/**
1078 1e51d801 Fabrice Bellard
 * Write a packet to an output media file. The packet shall contain
1079
 * one audio or video frame.
1080 b9a281db Fabrice Bellard
 *
1081
 * @param s media file handle
1082 1e51d801 Fabrice Bellard
 * @param stream_index stream index
1083
 * @param buf buffer containing the frame data
1084
 * @param size size of buffer
1085 d4c0ff91 Fabrice Bellard
 * @return < 0 if error, = 0 if OK, 1 if end of stream wanted.
1086 b9a281db Fabrice Bellard
 */
1087 1e51d801 Fabrice Bellard
int av_write_frame(AVFormatContext *s, int stream_index, const uint8_t *buf, 
1088
                   int size)
1089 de6d9b64 Fabrice Bellard
{
1090 1e51d801 Fabrice Bellard
    AVStream *st;
1091 0c1a9eda Zdenek Kabelac
    int64_t pts_mask;
1092 7feb950a Fabrice Bellard
    int ret, frame_size;
1093 1e51d801 Fabrice Bellard
1094
    st = s->streams[stream_index];
1095
    pts_mask = (1LL << s->pts_wrap_bits) - 1;
1096
    ret = s->oformat->write_packet(s, stream_index, (uint8_t *)buf, size, 
1097
                                   st->pts.val & pts_mask);
1098
    if (ret < 0)
1099
        return ret;
1100
1101
    /* update pts */
1102
    switch (st->codec.codec_type) {
1103
    case CODEC_TYPE_AUDIO:
1104 7feb950a Fabrice Bellard
        if (st->codec.frame_size <= 1) {
1105
            frame_size = size / st->codec.channels;
1106
            /* specific hack for pcm codecs because no frame size is provided */
1107 50d5d129 Fabrice Bellard
            switch(st->codec.codec_id) {
1108 7feb950a Fabrice Bellard
            case CODEC_ID_PCM_S16LE:
1109
            case CODEC_ID_PCM_S16BE:
1110
            case CODEC_ID_PCM_U16LE:
1111
            case CODEC_ID_PCM_U16BE:
1112
                frame_size >>= 1;
1113
                break;
1114
            default:
1115
                break;
1116
            }
1117
        } else {
1118
            frame_size = st->codec.frame_size;
1119
        }
1120 1e51d801 Fabrice Bellard
        av_frac_add(&st->pts, 
1121 0c1a9eda Zdenek Kabelac
                    (int64_t)s->pts_den * frame_size);
1122 1e51d801 Fabrice Bellard
        break;
1123
    case CODEC_TYPE_VIDEO:
1124
        av_frac_add(&st->pts, 
1125 14bea432 Michael Niedermayer
                    (int64_t)s->pts_den * st->codec.frame_rate_base);
1126 1e51d801 Fabrice Bellard
        break;
1127
    default:
1128
        break;
1129
    }
1130 d4c0ff91 Fabrice Bellard
    return ret;
1131 b9a281db Fabrice Bellard
}
1132
1133
/**
1134
 * write the stream trailer to an output media file and and free the
1135
 * file private data.
1136
 *
1137
 * @param s media file handle
1138
 * @return 0 if OK. AVERROR_xxx if error.  */
1139
int av_write_trailer(AVFormatContext *s)
1140
{
1141
    int ret;
1142
    ret = s->oformat->write_trailer(s);
1143
    av_freep(&s->priv_data);
1144
    return ret;
1145 de6d9b64 Fabrice Bellard
}
1146
1147
/* "user interface" functions */
1148
1149
void dump_format(AVFormatContext *ic,
1150
                 int index, 
1151
                 const char *url,
1152
                 int is_output)
1153
{
1154 b9a281db Fabrice Bellard
    int i, flags;
1155 de6d9b64 Fabrice Bellard
    char buf[256];
1156
1157
    fprintf(stderr, "%s #%d, %s, %s '%s':\n", 
1158
            is_output ? "Output" : "Input",
1159 b9a281db Fabrice Bellard
            index, 
1160
            is_output ? ic->oformat->name : ic->iformat->name, 
1161 de6d9b64 Fabrice Bellard
            is_output ? "to" : "from", url);
1162 12f996ed Fabrice Bellard
    if (!is_output) {
1163 c9245417 Roman Shaposhnik
        fprintf(stderr, "  Duration: ");
1164 12f996ed Fabrice Bellard
        if (ic->duration != AV_NOPTS_VALUE) {
1165
            int hours, mins, secs, us;
1166
            secs = ic->duration / AV_TIME_BASE;
1167
            us = ic->duration % AV_TIME_BASE;
1168
            mins = secs / 60;
1169
            secs %= 60;
1170
            hours = mins / 60;
1171
            mins %= 60;
1172 c9245417 Roman Shaposhnik
            fprintf(stderr, "%02d:%02d:%02d.%01d", hours, mins, secs, 
1173 12f996ed Fabrice Bellard
                   (10 * us) / AV_TIME_BASE);
1174
        } else {
1175 c9245417 Roman Shaposhnik
            fprintf(stderr, "N/A");
1176 12f996ed Fabrice Bellard
        }
1177 c9245417 Roman Shaposhnik
        fprintf(stderr, ", bitrate: ");
1178 12f996ed Fabrice Bellard
        if (ic->bit_rate) {
1179 c9245417 Roman Shaposhnik
            fprintf(stderr,"%d kb/s", ic->bit_rate / 1000);
1180 12f996ed Fabrice Bellard
        } else {
1181 c9245417 Roman Shaposhnik
            fprintf(stderr, "N/A");
1182 12f996ed Fabrice Bellard
        }
1183 c9245417 Roman Shaposhnik
        fprintf(stderr, "\n");
1184 12f996ed Fabrice Bellard
    }
1185 de6d9b64 Fabrice Bellard
    for(i=0;i<ic->nb_streams;i++) {
1186
        AVStream *st = ic->streams[i];
1187
        avcodec_string(buf, sizeof(buf), &st->codec, is_output);
1188 b9a281db Fabrice Bellard
        fprintf(stderr, "  Stream #%d.%d", index, i);
1189
        /* the pid is an important information, so we display it */
1190
        /* XXX: add a generic system */
1191
        if (is_output)
1192
            flags = ic->oformat->flags;
1193
        else
1194
            flags = ic->iformat->flags;
1195
        if (flags & AVFMT_SHOW_IDS) {
1196
            fprintf(stderr, "[0x%x]", st->id);
1197
        }
1198
        fprintf(stderr, ": %s\n", buf);
1199 de6d9b64 Fabrice Bellard
    }
1200
}
1201
1202
typedef struct {
1203 445f1b83 Roman Shaposhnik
    const char *abv;
1204 de6d9b64 Fabrice Bellard
    int width, height;
1205 445f1b83 Roman Shaposhnik
    int frame_rate, frame_rate_base;
1206
} AbvEntry;
1207
1208
static AbvEntry frame_abvs[] = {
1209 ba2a8cb4 Roman Shaposhnik
    { "ntsc",      720, 480, 30000, 1001 },
1210
    { "pal",       720, 576,    25,    1 },
1211
    { "qntsc",     352, 240, 30000, 1001 }, /* VCD compliant ntsc */
1212
    { "qpal",      352, 288,    25,    1 }, /* VCD compliant pal */
1213 904736b5 Roman Shaposhnik
    { "sntsc",     640, 480, 30000, 1001 }, /* square pixel ntsc */
1214
    { "spal",      768, 576,    25,    1 }, /* square pixel pal */
1215 445f1b83 Roman Shaposhnik
    { "film",      352, 240,    24,    1 },
1216
    { "ntsc-film", 352, 240, 24000, 1001 },
1217
    { "sqcif",     128,  96,     0,    0 },
1218
    { "qcif",      176, 144,     0,    0 },
1219
    { "cif",       352, 288,     0,    0 },
1220
    { "4cif",      704, 576,     0,    0 },
1221 de6d9b64 Fabrice Bellard
};
1222 445f1b83 Roman Shaposhnik
1223 de6d9b64 Fabrice Bellard
int parse_image_size(int *width_ptr, int *height_ptr, const char *str)
1224
{
1225
    int i;
1226 445f1b83 Roman Shaposhnik
    int n = sizeof(frame_abvs) / sizeof(AbvEntry);
1227 de6d9b64 Fabrice Bellard
    const char *p;
1228
    int frame_width = 0, frame_height = 0;
1229
1230
    for(i=0;i<n;i++) {
1231 445f1b83 Roman Shaposhnik
        if (!strcmp(frame_abvs[i].abv, str)) {
1232
            frame_width = frame_abvs[i].width;
1233
            frame_height = frame_abvs[i].height;
1234 de6d9b64 Fabrice Bellard
            break;
1235
        }
1236
    }
1237
    if (i == n) {
1238
        p = str;
1239
        frame_width = strtol(p, (char **)&p, 10);
1240
        if (*p)
1241
            p++;
1242
        frame_height = strtol(p, (char **)&p, 10);
1243
    }
1244
    if (frame_width <= 0 || frame_height <= 0)
1245
        return -1;
1246
    *width_ptr = frame_width;
1247
    *height_ptr = frame_height;
1248
    return 0;
1249
}
1250
1251 445f1b83 Roman Shaposhnik
int parse_frame_rate(int *frame_rate, int *frame_rate_base, const char *arg)
1252
{
1253
    int i;
1254
    char* cp;
1255
   
1256
    /* First, we check our abbreviation table */
1257
    for (i = 0; i < sizeof(frame_abvs)/sizeof(*frame_abvs); ++i)
1258
         if (!strcmp(frame_abvs[i].abv, arg)) {
1259
             *frame_rate = frame_abvs[i].frame_rate;
1260
             *frame_rate_base = frame_abvs[i].frame_rate_base;
1261
             return 0;
1262
         }
1263
1264
    /* Then, we try to parse it as fraction */
1265
    cp = strchr(arg, '/');
1266
    if (cp) {
1267
        char* cpp;
1268
        *frame_rate = strtol(arg, &cpp, 10);
1269
        if (cpp != arg || cpp == cp) 
1270
            *frame_rate_base = strtol(cp+1, &cpp, 10);
1271
        else
1272
           *frame_rate = 0;
1273
    } 
1274
    else {
1275
        /* Finally we give up and parse it as double */
1276
        *frame_rate_base = DEFAULT_FRAME_RATE_BASE;
1277
        *frame_rate = (int)(strtod(arg, 0) * (*frame_rate_base) + 0.5);
1278
    }
1279
    if (!*frame_rate || !*frame_rate_base)
1280
        return -1;
1281
    else
1282
        return 0;
1283
}
1284
1285 916c80e9 Fabrice Bellard
/* Syntax:
1286
 * - If not a duration:
1287
 *  [{YYYY-MM-DD|YYYYMMDD}]{T| }{HH[:MM[:SS[.m...]]][Z]|HH[MM[SS[.m...]]][Z]}
1288 c5510dd6 Philip Gladstone
 * Time is localtime unless Z is suffixed to the end. In this case GMT
1289 916c80e9 Fabrice Bellard
 * Return the date in micro seconds since 1970 
1290
 * - If duration:
1291
 *  HH[:MM[:SS[.m...]]]
1292
 *  S+[.m...]
1293
 */
1294 0c1a9eda Zdenek Kabelac
int64_t parse_date(const char *datestr, int duration)
1295 de6d9b64 Fabrice Bellard
{
1296
    const char *p;
1297 0c1a9eda Zdenek Kabelac
    int64_t t;
1298 2dbceb9f Philip Gladstone
    struct tm dt;
1299 c5510dd6 Philip Gladstone
    int i;
1300
    static const char *date_fmt[] = {
1301
        "%Y-%m-%d",
1302
        "%Y%m%d",
1303
    };
1304
    static const char *time_fmt[] = {
1305
        "%H:%M:%S",
1306
        "%H%M%S",
1307
    };
1308
    const char *q;
1309 916c80e9 Fabrice Bellard
    int is_utc, len;
1310 c5510dd6 Philip Gladstone
    char lastch;
1311
    time_t now = time(0);
1312
1313 916c80e9 Fabrice Bellard
    len = strlen(datestr);
1314
    if (len > 0)
1315
        lastch = datestr[len - 1];
1316
    else
1317
        lastch = '\0';
1318 c5510dd6 Philip Gladstone
    is_utc = (lastch == 'z' || lastch == 'Z');
1319 2dbceb9f Philip Gladstone
1320
    memset(&dt, 0, sizeof(dt));
1321 de6d9b64 Fabrice Bellard
1322
    p = datestr;
1323 916c80e9 Fabrice Bellard
    q = NULL;
1324 de6d9b64 Fabrice Bellard
    if (!duration) {
1325 c5510dd6 Philip Gladstone
        for (i = 0; i < sizeof(date_fmt) / sizeof(date_fmt[0]); i++) {
1326 f71869a4 Fabrice Bellard
            q = small_strptime(p, date_fmt[i], &dt);
1327 c5510dd6 Philip Gladstone
            if (q) {
1328
                break;
1329
            }
1330
        }
1331
1332
        if (!q) {
1333
            if (is_utc) {
1334
                dt = *gmtime(&now);
1335
            } else {
1336
                dt = *localtime(&now);
1337
            }
1338
            dt.tm_hour = dt.tm_min = dt.tm_sec = 0;
1339 de6d9b64 Fabrice Bellard
        } else {
1340 c5510dd6 Philip Gladstone
            p = q;
1341 de6d9b64 Fabrice Bellard
        }
1342 c5510dd6 Philip Gladstone
1343
        if (*p == 'T' || *p == 't' || *p == ' ')
1344
            p++;
1345
1346 916c80e9 Fabrice Bellard
        for (i = 0; i < sizeof(time_fmt) / sizeof(time_fmt[0]); i++) {
1347 f71869a4 Fabrice Bellard
            q = small_strptime(p, time_fmt[i], &dt);
1348 916c80e9 Fabrice Bellard
            if (q) {
1349
                break;
1350
            }
1351
        }
1352
    } else {
1353 f71869a4 Fabrice Bellard
        q = small_strptime(p, time_fmt[0], &dt);
1354 916c80e9 Fabrice Bellard
        if (!q) {
1355
            dt.tm_sec = strtol(p, (char **)&q, 10);
1356
            dt.tm_min = 0;
1357
            dt.tm_hour = 0;
1358 c5510dd6 Philip Gladstone
        }
1359
    }
1360
1361
    /* Now we have all the fields that we can get */
1362
    if (!q) {
1363
        if (duration)
1364
            return 0;
1365
        else
1366 0c1a9eda Zdenek Kabelac
            return now * int64_t_C(1000000);
1367 de6d9b64 Fabrice Bellard
    }
1368 2dbceb9f Philip Gladstone
1369
    if (duration) {
1370 c5510dd6 Philip Gladstone
        t = dt.tm_hour * 3600 + dt.tm_min * 60 + dt.tm_sec;
1371 2dbceb9f Philip Gladstone
    } else {
1372 c5510dd6 Philip Gladstone
        dt.tm_isdst = -1;       /* unknown */
1373
        if (is_utc) {
1374
            t = mktimegm(&dt);
1375
        } else {
1376
            t = mktime(&dt);
1377
        }
1378 de6d9b64 Fabrice Bellard
    }
1379 2dbceb9f Philip Gladstone
1380 c5510dd6 Philip Gladstone
    t *= 1000000;
1381
1382
    if (*q == '.') {
1383 de6d9b64 Fabrice Bellard
        int val, n;
1384 c5510dd6 Philip Gladstone
        q++;
1385
        for (val = 0, n = 100000; n >= 1; n /= 10, q++) {
1386
            if (!isdigit(*q)) 
1387
                break;
1388
            val += n * (*q - '0');
1389 de6d9b64 Fabrice Bellard
        }
1390
        t += val;
1391
    }
1392
    return t;
1393
}
1394
1395 2dbceb9f Philip Gladstone
/* syntax: '?tag1=val1&tag2=val2...'. Little URL decoding is done. Return
1396 de6d9b64 Fabrice Bellard
   1 if found */
1397
int find_info_tag(char *arg, int arg_size, const char *tag1, const char *info)
1398
{
1399
    const char *p;
1400
    char tag[128], *q;
1401
1402
    p = info;
1403
    if (*p == '?')
1404
        p++;
1405
    for(;;) {
1406
        q = tag;
1407
        while (*p != '\0' && *p != '=' && *p != '&') {
1408
            if ((q - tag) < sizeof(tag) - 1)
1409
                *q++ = *p;
1410
            p++;
1411
        }
1412
        *q = '\0';
1413
        q = arg;
1414
        if (*p == '=') {
1415
            p++;
1416
            while (*p != '&' && *p != '\0') {
1417 2dbceb9f Philip Gladstone
                if ((q - arg) < arg_size - 1) {
1418
                    if (*p == '+')
1419
                        *q++ = ' ';
1420
                    else
1421
                        *q++ = *p;
1422
                }
1423 de6d9b64 Fabrice Bellard
                p++;
1424
            }
1425
            *q = '\0';
1426
        }
1427
        if (!strcmp(tag, tag1)) 
1428
            return 1;
1429
        if (*p != '&')
1430
            break;
1431 8d1335ea Philip Gladstone
        p++;
1432 de6d9b64 Fabrice Bellard
    }
1433
    return 0;
1434
}
1435
1436 9150f42e Fabrice Bellard
/* Return in 'buf' the path with '%d' replaced by number. Also handles
1437
   the '%0nd' format where 'n' is the total number of digits and
1438
   '%%'. Return 0 if OK, and -1 if format error */
1439
int get_frame_filename(char *buf, int buf_size,
1440
                       const char *path, int number)
1441
{
1442
    const char *p;
1443
    char *q, buf1[20];
1444
    int nd, len, c, percentd_found;
1445
1446
    q = buf;
1447
    p = path;
1448
    percentd_found = 0;
1449
    for(;;) {
1450
        c = *p++;
1451
        if (c == '\0')
1452
            break;
1453
        if (c == '%') {
1454 c9646fda Philip Gladstone
            do {
1455
                nd = 0;
1456
                while (isdigit(*p)) {
1457
                    nd = nd * 10 + *p++ - '0';
1458
                }
1459
                c = *p++;
1460
            } while (isdigit(c));
1461
1462 9150f42e Fabrice Bellard
            switch(c) {
1463
            case '%':
1464
                goto addchar;
1465
            case 'd':
1466
                if (percentd_found)
1467
                    goto fail;
1468
                percentd_found = 1;
1469
                snprintf(buf1, sizeof(buf1), "%0*d", nd, number);
1470
                len = strlen(buf1);
1471
                if ((q - buf + len) > buf_size - 1)
1472
                    goto fail;
1473
                memcpy(q, buf1, len);
1474
                q += len;
1475
                break;
1476
            default:
1477
                goto fail;
1478
            }
1479
        } else {
1480
        addchar:
1481
            if ((q - buf) < buf_size - 1)
1482
                *q++ = c;
1483
        }
1484
    }
1485
    if (!percentd_found)
1486
        goto fail;
1487
    *q = '\0';
1488
    return 0;
1489
 fail:
1490
    *q = '\0';
1491
    return -1;
1492
}
1493
1494 b9a281db Fabrice Bellard
/**
1495
 *
1496
 * Print on stdout a nice hexa dump of a buffer
1497
 * @param buf buffer
1498
 * @param size buffer size
1499
 */
1500 0c1a9eda Zdenek Kabelac
void av_hex_dump(uint8_t *buf, int size)
1501 b9a281db Fabrice Bellard
{
1502
    int len, i, j, c;
1503
1504
    for(i=0;i<size;i+=16) {
1505
        len = size - i;
1506
        if (len > 16)
1507
            len = 16;
1508
        printf("%08x ", i);
1509
        for(j=0;j<16;j++) {
1510
            if (j < len)
1511
                printf(" %02x", buf[i+j]);
1512
            else
1513
                printf("   ");
1514
        }
1515
        printf(" ");
1516
        for(j=0;j<len;j++) {
1517
            c = buf[i+j];
1518
            if (c < ' ' || c > '~')
1519
                c = '.';
1520
            printf("%c", c);
1521
        }
1522
        printf("\n");
1523
    }
1524
}
1525
1526 a9a721da Fabrice Bellard
void url_split(char *proto, int proto_size,
1527
               char *hostname, int hostname_size,
1528
               int *port_ptr,
1529
               char *path, int path_size,
1530
               const char *url)
1531
{
1532
    const char *p;
1533
    char *q;
1534
    int port;
1535
1536
    port = -1;
1537
1538
    p = url;
1539
    q = proto;
1540
    while (*p != ':' && *p != '\0') {
1541
        if ((q - proto) < proto_size - 1)
1542
            *q++ = *p;
1543
        p++;
1544
    }
1545
    if (proto_size > 0)
1546
        *q = '\0';
1547
    if (*p == '\0') {
1548
        if (proto_size > 0)
1549
            proto[0] = '\0';
1550
        if (hostname_size > 0)
1551
            hostname[0] = '\0';
1552
        p = url;
1553
    } else {
1554
        p++;
1555
        if (*p == '/')
1556
            p++;
1557
        if (*p == '/')
1558
            p++;
1559
        q = hostname;
1560
        while (*p != ':' && *p != '/' && *p != '?' && *p != '\0') {
1561
            if ((q - hostname) < hostname_size - 1)
1562
                *q++ = *p;
1563
            p++;
1564
        }
1565
        if (hostname_size > 0)
1566
            *q = '\0';
1567
        if (*p == ':') {
1568
            p++;
1569
            port = strtoul(p, (char **)&p, 10);
1570
        }
1571
    }
1572
    if (port_ptr)
1573
        *port_ptr = port;
1574
    pstrcpy(path, path_size, p);
1575
}
1576
1577 916c80e9 Fabrice Bellard
/**
1578
 * Set the pts for a given stream
1579
 * @param s stream 
1580
 * @param pts_wrap_bits number of bits effectively used by the pts
1581
 *        (used for wrap control, 33 is the value for MPEG) 
1582
 * @param pts_num numerator to convert to seconds (MPEG: 1) 
1583
 * @param pts_den denominator to convert to seconds (MPEG: 90000)
1584
 */
1585
void av_set_pts_info(AVFormatContext *s, int pts_wrap_bits,
1586
                     int pts_num, int pts_den)
1587
{
1588
    s->pts_wrap_bits = pts_wrap_bits;
1589
    s->pts_num = pts_num;
1590
    s->pts_den = pts_den;
1591
}
1592
1593
/* fraction handling */
1594
1595
/**
1596
 * f = val + (num / den) + 0.5. 'num' is normalized so that it is such
1597
 * as 0 <= num < den.
1598
 *
1599
 * @param f fractional number
1600
 * @param val integer value
1601
 * @param num must be >= 0
1602
 * @param den must be >= 1 
1603
 */
1604 0c1a9eda Zdenek Kabelac
void av_frac_init(AVFrac *f, int64_t val, int64_t num, int64_t den)
1605 916c80e9 Fabrice Bellard
{
1606
    num += (den >> 1);
1607
    if (num >= den) {
1608
        val += num / den;
1609
        num = num % den;
1610
    }
1611
    f->val = val;
1612
    f->num = num;
1613
    f->den = den;
1614
}
1615
1616
/* set f to (val + 0.5) */
1617 0c1a9eda Zdenek Kabelac
void av_frac_set(AVFrac *f, int64_t val)
1618 916c80e9 Fabrice Bellard
{
1619
    f->val = val;
1620
    f->num = f->den >> 1;
1621
}
1622
1623
/**
1624
 * Fractionnal addition to f: f = f + (incr / f->den)
1625
 *
1626
 * @param f fractional number
1627
 * @param incr increment, can be positive or negative
1628
 */
1629 0c1a9eda Zdenek Kabelac
void av_frac_add(AVFrac *f, int64_t incr)
1630 916c80e9 Fabrice Bellard
{
1631 0c1a9eda Zdenek Kabelac
    int64_t num, den;
1632 916c80e9 Fabrice Bellard
1633
    num = f->num + incr;
1634
    den = f->den;
1635
    if (num < 0) {
1636
        f->val += num / den;
1637
        num = num % den;
1638
        if (num < 0) {
1639
            num += den;
1640
            f->val--;
1641
        }
1642
    } else if (num >= den) {
1643
        f->val += num / den;
1644
        num = num % den;
1645
    }
1646
    f->num = num;
1647
}
1648 87a0a681 Fabrice Bellard
1649
/**
1650
 * register a new image format
1651
 * @param img_fmt Image format descriptor
1652
 */
1653
void av_register_image_format(AVImageFormat *img_fmt)
1654
{
1655
    AVImageFormat **p;
1656
1657
    p = &first_image_format;
1658
    while (*p != NULL) p = &(*p)->next;
1659
    *p = img_fmt;
1660
    img_fmt->next = NULL;
1661
}
1662
1663
/* guess image format */
1664
AVImageFormat *av_probe_image_format(AVProbeData *pd)
1665
{
1666
    AVImageFormat *fmt1, *fmt;
1667
    int score, score_max;
1668
1669
    fmt = NULL;
1670
    score_max = 0;
1671
    for(fmt1 = first_image_format; fmt1 != NULL; fmt1 = fmt1->next) {
1672
        if (fmt1->img_probe) {
1673
            score = fmt1->img_probe(pd);
1674
            if (score > score_max) {
1675
                score_max = score;
1676
                fmt = fmt1;
1677
            }
1678
        }
1679
    }
1680
    return fmt;
1681
}
1682
1683
AVImageFormat *guess_image_format(const char *filename)
1684
{
1685
    AVImageFormat *fmt1;
1686
1687
    for(fmt1 = first_image_format; fmt1 != NULL; fmt1 = fmt1->next) {
1688
        if (fmt1->extensions && match_ext(filename, fmt1->extensions))
1689
            return fmt1;
1690
    }
1691
    return NULL;
1692
}
1693
1694
/**
1695
 * Read an image from a stream. 
1696
 * @param gb byte stream containing the image
1697
 * @param fmt image format, NULL if probing is required
1698
 */
1699
int av_read_image(ByteIOContext *pb, const char *filename,
1700
                  AVImageFormat *fmt,
1701
                  int (*alloc_cb)(void *, AVImageInfo *info), void *opaque)
1702
{
1703
    char buf[PROBE_BUF_SIZE];
1704
    AVProbeData probe_data, *pd = &probe_data;
1705
    offset_t pos;
1706
    int ret;
1707
1708
    if (!fmt) {
1709 5c91a675 Zdenek Kabelac
        pd->filename = filename;
1710 87a0a681 Fabrice Bellard
        pd->buf = buf;
1711
        pos = url_ftell(pb);
1712
        pd->buf_size = get_buffer(pb, buf, PROBE_BUF_SIZE);
1713
        url_fseek(pb, pos, SEEK_SET);
1714
        fmt = av_probe_image_format(pd);
1715
    }
1716
    if (!fmt)
1717
        return AVERROR_NOFMT;
1718
    ret = fmt->img_read(pb, alloc_cb, opaque);
1719
    return ret;
1720
}
1721
1722
/**
1723
 * Write an image to a stream.
1724
 * @param pb byte stream for the image output
1725
 * @param fmt image format
1726
 * @param img image data and informations
1727
 */
1728
int av_write_image(ByteIOContext *pb, AVImageFormat *fmt, AVImageInfo *img)
1729
{
1730
    return fmt->img_write(pb, img);
1731
}