Statistics
| Branch: | Revision:

ffmpeg / libavformat / utils.c @ 5aa0a644

History | View | Annotate | Download (46 KB)

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
#include "avformat.h"
20

    
21
AVInputFormat *first_iformat;
22
AVOutputFormat *first_oformat;
23
AVImageFormat *first_image_format;
24

    
25
void av_register_input_format(AVInputFormat *format)
26
{
27
    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
    while (*p != NULL) p = &(*p)->next;
39
    *p = format;
40
    format->next = NULL;
41
}
42

    
43
int match_ext(const char *filename, const char *extensions)
44
{
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
AVOutputFormat *guess_format(const char *short_name, const char *filename, 
68
                             const char *mime_type)
69
{
70
    AVOutputFormat *fmt, *fmt_found;
71
    int score_max, score;
72

    
73
    /* specific test for image sequences */
74
    if (!short_name && filename && 
75
        filename_number_test(filename) >= 0 &&
76
        guess_image_format(filename)) {
77
        return guess_format("image", NULL, NULL);
78
    }
79

    
80
    /* find the proper file type */
81
    fmt_found = NULL;
82
    score_max = 0;
83
    fmt = first_oformat;
84
    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
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
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
/* memory handling */
133

    
134
/**
135
 * 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
 * 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
int av_new_packet(AVPacket *pkt, int size)
151
{
152
    void *data = av_malloc(size + FF_INPUT_BUFFER_PADDING_SIZE);
153
    if (!data)
154
        return AVERROR_NOMEM;
155
    memset(data + size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
156

    
157
    av_init_packet(pkt);
158
    pkt->data = data; 
159
    pkt->size = size;
160
    pkt->destruct = av_destruct_packet;
161
    return 0;
162
}
163

    
164
/* fifo handling */
165

    
166
int fifo_init(FifoBuffer *f, int size)
167
{
168
    f->buffer = av_malloc(size);
169
    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
    av_free(f->buffer);
179
}
180

    
181
int fifo_size(FifoBuffer *f, uint8_t *rptr)
182
{
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
int fifo_read(FifoBuffer *f, uint8_t *buf, int buf_size, uint8_t **rptr_ptr)
195
{
196
    uint8_t *rptr = *rptr_ptr;
197
    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
void fifo_write(FifoBuffer *f, uint8_t *buf, int size, uint8_t **wptr_ptr)
223
{
224
    int len;
225
    uint8_t *wptr;
226
    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
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
AVInputFormat *av_probe_input_format(AVProbeData *pd, int is_opened)
249
{
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
        if (fmt1->read_probe) {
260
            score = fmt1->read_probe(pd);
261
        } else if (fmt1->extensions) {
262
            if (match_ext(pd->filename, fmt1->extensions)) {
263
                score = 50;
264
            }
265
        } 
266
        if (score > score_max) {
267
            score_max = score;
268
            fmt = fmt1;
269
        }
270
    }
271
    return fmt;
272
}
273

    
274
/************************************************************/
275
/* input media file */
276

    
277
#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
{
295
    AVFormatContext *ic = NULL;
296
    int err, must_open_file;
297
    char buf[PROBE_BUF_SIZE];
298
    AVProbeData probe_data, *pd = &probe_data;
299

    
300
    ic = av_mallocz(sizeof(AVFormatContext));
301
    if (!ic) {
302
        err = AVERROR_NOMEM;
303
        goto fail;
304
    }
305
    ic->duration = AV_NOPTS_VALUE;
306
    ic->start_time = AV_NOPTS_VALUE;
307
    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
        fmt = av_probe_input_format(pd, 0);
315
    }
316

    
317
    /* 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
    if ((fmt && (fmt->flags & AVFMT_NOFILE)) 
321
#ifdef CONFIG_NETWORK
322
        || (fmt == &rtp_demux && !strcmp(filename, "null"))
323
#endif
324
        ) {
325
        must_open_file = 0;
326
    }
327

    
328
    if (!fmt || must_open_file) {
329
        /* if no file needed do not try to open one */
330
        if (url_fopen(&ic->pb, filename, URL_RDONLY) < 0) {
331
            err = AVERROR_IO;
332
            goto fail;
333
        }
334
        if (buf_size > 0) {
335
            url_setbufsize(&ic->pb, buf_size);
336
        }
337
        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
    }
343
    
344
    /* guess file format */
345
    if (!fmt) {
346
        fmt = av_probe_input_format(pd, 1);
347
    }
348

    
349
    /* if still no format found, error */
350
    if (!fmt) {
351
        err = AVERROR_NOFMT;
352
        goto fail1;
353
    }
354
        
355
    /* XXX: suppress this hack for redirectors */
356
#ifdef CONFIG_NETWORK
357
    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
#endif
364

    
365
    ic->iformat = fmt;
366

    
367
    /* 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
    /* allocate private data */
376
    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
        goto fail1;
381
        }
382
    } else
383
        ic->priv_data = NULL;
384

    
385
    /* default pts settings is MPEG like */
386
    av_set_pts_info(ic, 33, 1, 90000);
387

    
388
    err = ic->iformat->read_header(ic, ap);
389
    if (err < 0)
390
        goto fail1;
391
    *ic_ptr = ic;
392
    return 0;
393
 fail1:
394
    if (!fmt || must_open_file) {
395
        url_fclose(&ic->pb);
396
    }
397
 fail:
398
    if (ic) {
399
        av_freep(&ic->priv_data);
400
    }
401
    av_free(ic);
402
    *ic_ptr = NULL;
403
    return err;
404
}
405

    
406
/**
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
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
        av_free(pktl);
422
        return 0;
423
    } else {
424
        return s->iformat->read_packet(s, pkt);
425
    }
426
}
427

    
428

    
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
        av_free_packet(&pktl->pkt);
540
        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
        }
580
        av_free_packet(pkt);
581
    }
582

    
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
/* 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
    AVFrame picture;
755
    AVPacketList *pktl=NULL, **ppktl;
756
    short samples[AVCODEC_MAX_AUDIO_FRAME_SIZE / 2];
757
    uint8_t *ptr;
758
    int min_read_size, max_read_size;
759

    
760
    /* typical mpeg ts rate is 40 Mbits. DVD rate is about 10
761
       Mbits. We read at most 0.2 second of file to find all streams */
762

    
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
        min_read_size = 6000000;
768
    } else {
769
        min_read_size = 250000;
770
    }
771
    /* max read size is 2 seconds of video max */
772
    max_read_size = min_read_size * 10;
773

    
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
                    if(codec->capabilities & CODEC_CAP_TRUNCATED)
845
                        st->codec.flags |= CODEC_FLAG_TRUNCATED;
846

    
847
                    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
                        st->codec_info_nb_repeat_frames += st->codec.coded_frame->repeat_pict;
892
#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
                            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
                                (st->codec_info_nb_real_frames + (st->codec_info_nb_repeat_frames >> 1)) * st->codec.frame_rate_base,
905
                                1<<30);
906
                            goto close_codec;
907
                        }
908
                    } else {
909
                    close_codec:
910
                        st->codec_info_state = CSTATE_FOUND;
911
                        avcodec_close(&st->codec);
912
                        break;
913
                    }
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
            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
        }
938
    }
939

    
940

    
941
    av_estimate_timings(ic);
942
    return ret;
943
}
944

    
945
/**
946
 * Close a media file (but not its codecs)
947
 *
948
 * @param s media file handle
949
 */
950
void av_close_input_file(AVFormatContext *s)
951
{
952
    int i, must_open_file;
953

    
954
    if (s->iformat->read_close)
955
        s->iformat->read_close(s);
956
    for(i=0;i<s->nb_streams;i++) {
957
        av_free(s->streams[i]);
958
    }
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
            av_free(p);
966
            p = p1;
967
        }
968
        s->packet_buffer = NULL;
969
    }
970
    must_open_file = 1;
971
    if ((s->iformat->flags & AVFMT_NOFILE)
972
#ifdef CONFIG_NETWORK
973
        || (s->iformat == &rtp_demux && !strcmp(s->filename, "null"))
974
#endif
975
        ) {
976
        must_open_file = 0;
977
    }
978
    if (must_open_file) {
979
        url_fclose(&s->pb);
980
    }
981
    av_freep(&s->priv_data);
982
    av_free(s);
983
}
984

    
985
/**
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
    avcodec_get_context_defaults(&st->codec);
1005
    if (s->iformat) {
1006
        /* no default bitrate if decoding */
1007
        st->codec.bit_rate = 0;
1008
    }
1009
    st->index = s->nb_streams;
1010
    st->id = id;
1011
    st->start_time = AV_NOPTS_VALUE;
1012
    st->duration = AV_NOPTS_VALUE;
1013
    s->streams[s->nb_streams++] = st;
1014
    return st;
1015
}
1016

    
1017
/************************************************************/
1018
/* output media file */
1019

    
1020
int av_set_parameters(AVFormatContext *s, AVFormatParameters *ap)
1021
{
1022
    int ret;
1023
    
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
    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
/**
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
    int ret, i;
1049
    AVStream *st;
1050

    
1051
    /* default pts settings is MPEG like */
1052
    av_set_pts_info(s, 33, 1, 90000);
1053
    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
                         (int64_t)s->pts_num * st->codec.sample_rate);
1065
            break;
1066
        case CODEC_TYPE_VIDEO:
1067
            av_frac_init(&st->pts, 0, 0, 
1068
                         (int64_t)s->pts_num * st->codec.frame_rate);
1069
            break;
1070
        default:
1071
            break;
1072
        }
1073
    }
1074
    return 0;
1075
}
1076

    
1077
/**
1078
 * Write a packet to an output media file. The packet shall contain
1079
 * one audio or video frame.
1080
 *
1081
 * @param s media file handle
1082
 * @param stream_index stream index
1083
 * @param buf buffer containing the frame data
1084
 * @param size size of buffer
1085
 * @return < 0 if error, = 0 if OK, 1 if end of stream wanted.
1086
 */
1087
int av_write_frame(AVFormatContext *s, int stream_index, const uint8_t *buf, 
1088
                   int size)
1089
{
1090
    AVStream *st;
1091
    int64_t pts_mask;
1092
    int ret, frame_size;
1093

    
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
        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
            switch(st->codec.codec_id) {
1108
            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
        av_frac_add(&st->pts, 
1121
                    (int64_t)s->pts_den * frame_size);
1122
        break;
1123
    case CODEC_TYPE_VIDEO:
1124
        av_frac_add(&st->pts, 
1125
                    (int64_t)s->pts_den * st->codec.frame_rate_base);
1126
        break;
1127
    default:
1128
        break;
1129
    }
1130
    return ret;
1131
}
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
}
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
    int i, flags;
1155
    char buf[256];
1156

    
1157
    fprintf(stderr, "%s #%d, %s, %s '%s':\n", 
1158
            is_output ? "Output" : "Input",
1159
            index, 
1160
            is_output ? ic->oformat->name : ic->iformat->name, 
1161
            is_output ? "to" : "from", url);
1162
    if (!is_output) {
1163
        fprintf(stderr, "  Duration: ");
1164
        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
            fprintf(stderr, "%02d:%02d:%02d.%01d", hours, mins, secs, 
1173
                   (10 * us) / AV_TIME_BASE);
1174
        } else {
1175
            fprintf(stderr, "N/A");
1176
        }
1177
        fprintf(stderr, ", bitrate: ");
1178
        if (ic->bit_rate) {
1179
            fprintf(stderr,"%d kb/s", ic->bit_rate / 1000);
1180
        } else {
1181
            fprintf(stderr, "N/A");
1182
        }
1183
        fprintf(stderr, "\n");
1184
    }
1185
    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
        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
    }
1200
}
1201

    
1202
typedef struct {
1203
    const char *abv;
1204
    int width, height;
1205
    int frame_rate, frame_rate_base;
1206
} AbvEntry;
1207

    
1208
static AbvEntry frame_abvs[] = {
1209
    { "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
    { "sntsc",     640, 480, 30000, 1001 }, /* square pixel ntsc */
1214
    { "spal",      768, 576,    25,    1 }, /* square pixel pal */
1215
    { "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
};
1222

    
1223
int parse_image_size(int *width_ptr, int *height_ptr, const char *str)
1224
{
1225
    int i;
1226
    int n = sizeof(frame_abvs) / sizeof(AbvEntry);
1227
    const char *p;
1228
    int frame_width = 0, frame_height = 0;
1229

    
1230
    for(i=0;i<n;i++) {
1231
        if (!strcmp(frame_abvs[i].abv, str)) {
1232
            frame_width = frame_abvs[i].width;
1233
            frame_height = frame_abvs[i].height;
1234
            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
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
/* Syntax:
1286
 * - If not a duration:
1287
 *  [{YYYY-MM-DD|YYYYMMDD}]{T| }{HH[:MM[:SS[.m...]]][Z]|HH[MM[SS[.m...]]][Z]}
1288
 * Time is localtime unless Z is suffixed to the end. In this case GMT
1289
 * Return the date in micro seconds since 1970 
1290
 * - If duration:
1291
 *  HH[:MM[:SS[.m...]]]
1292
 *  S+[.m...]
1293
 */
1294
int64_t parse_date(const char *datestr, int duration)
1295
{
1296
    const char *p;
1297
    int64_t t;
1298
    struct tm dt;
1299
    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
    int is_utc, len;
1310
    char lastch;
1311
    time_t now = time(0);
1312

    
1313
    len = strlen(datestr);
1314
    if (len > 0)
1315
        lastch = datestr[len - 1];
1316
    else
1317
        lastch = '\0';
1318
    is_utc = (lastch == 'z' || lastch == 'Z');
1319

    
1320
    memset(&dt, 0, sizeof(dt));
1321

    
1322
    p = datestr;
1323
    q = NULL;
1324
    if (!duration) {
1325
        for (i = 0; i < sizeof(date_fmt) / sizeof(date_fmt[0]); i++) {
1326
            q = small_strptime(p, date_fmt[i], &dt);
1327
            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
        } else {
1340
            p = q;
1341
        }
1342

    
1343
        if (*p == 'T' || *p == 't' || *p == ' ')
1344
            p++;
1345

    
1346
        for (i = 0; i < sizeof(time_fmt) / sizeof(time_fmt[0]); i++) {
1347
            q = small_strptime(p, time_fmt[i], &dt);
1348
            if (q) {
1349
                break;
1350
            }
1351
        }
1352
    } else {
1353
        q = small_strptime(p, time_fmt[0], &dt);
1354
        if (!q) {
1355
            dt.tm_sec = strtol(p, (char **)&q, 10);
1356
            dt.tm_min = 0;
1357
            dt.tm_hour = 0;
1358
        }
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
            return now * int64_t_C(1000000);
1367
    }
1368

    
1369
    if (duration) {
1370
        t = dt.tm_hour * 3600 + dt.tm_min * 60 + dt.tm_sec;
1371
    } else {
1372
        dt.tm_isdst = -1;       /* unknown */
1373
        if (is_utc) {
1374
            t = mktimegm(&dt);
1375
        } else {
1376
            t = mktime(&dt);
1377
        }
1378
    }
1379

    
1380
    t *= 1000000;
1381

    
1382
    if (*q == '.') {
1383
        int val, n;
1384
        q++;
1385
        for (val = 0, n = 100000; n >= 1; n /= 10, q++) {
1386
            if (!isdigit(*q)) 
1387
                break;
1388
            val += n * (*q - '0');
1389
        }
1390
        t += val;
1391
    }
1392
    return t;
1393
}
1394

    
1395
/* syntax: '?tag1=val1&tag2=val2...'. Little URL decoding is done. Return
1396
   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
                if ((q - arg) < arg_size - 1) {
1418
                    if (*p == '+')
1419
                        *q++ = ' ';
1420
                    else
1421
                        *q++ = *p;
1422
                }
1423
                p++;
1424
            }
1425
            *q = '\0';
1426
        }
1427
        if (!strcmp(tag, tag1)) 
1428
            return 1;
1429
        if (*p != '&')
1430
            break;
1431
        p++;
1432
    }
1433
    return 0;
1434
}
1435

    
1436
/* 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
            do {
1455
                nd = 0;
1456
                while (isdigit(*p)) {
1457
                    nd = nd * 10 + *p++ - '0';
1458
                }
1459
                c = *p++;
1460
            } while (isdigit(c));
1461

    
1462
            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
/**
1495
 *
1496
 * Print on stdout a nice hexa dump of a buffer
1497
 * @param buf buffer
1498
 * @param size buffer size
1499
 */
1500
void av_hex_dump(uint8_t *buf, int size)
1501
{
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
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
/**
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
void av_frac_init(AVFrac *f, int64_t val, int64_t num, int64_t den)
1605
{
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
void av_frac_set(AVFrac *f, int64_t val)
1618
{
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
void av_frac_add(AVFrac *f, int64_t incr)
1630
{
1631
    int64_t num, den;
1632

    
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

    
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
        pd->filename = filename;
1710
        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
}
1732