Statistics
| Branch: | Revision:

ffmpeg / libavformat / utils.c @ da24c5e3

History | View | Annotate | Download (46.6 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
/**
278
 * open a media file from an IO stream. 'fmt' must be specified.
279
 */
280
int av_open_input_stream(AVFormatContext **ic_ptr, 
281
                         ByteIOContext *pb, const char *filename, 
282
                         AVInputFormat *fmt, AVFormatParameters *ap)
283
{
284
    int err;
285
    AVFormatContext *ic;
286

    
287
    ic = av_mallocz(sizeof(AVFormatContext));
288
    if (!ic) {
289
        err = AVERROR_NOMEM;
290
        goto fail;
291
    }
292
    ic->iformat = fmt;
293
    if (pb)
294
        ic->pb = *pb;
295
    ic->duration = AV_NOPTS_VALUE;
296
    ic->start_time = AV_NOPTS_VALUE;
297
    pstrcpy(ic->filename, sizeof(ic->filename), filename);
298

    
299
    /* allocate private data */
300
    if (fmt->priv_data_size > 0) {
301
        ic->priv_data = av_mallocz(fmt->priv_data_size);
302
        if (!ic->priv_data) {
303
            err = AVERROR_NOMEM;
304
            goto fail;
305
        }
306
    } else {
307
        ic->priv_data = NULL;
308
    }
309

    
310
    /* default pts settings is MPEG like */
311
    av_set_pts_info(ic, 33, 1, 90000);
312

    
313
    err = ic->iformat->read_header(ic, ap);
314
    if (err < 0)
315
        goto fail;
316
    *ic_ptr = ic;
317
    return 0;
318
 fail:
319
    if (ic) {
320
        av_freep(&ic->priv_data);
321
    }
322
    av_free(ic);
323
    *ic_ptr = NULL;
324
    return err;
325
}
326

    
327
#define PROBE_BUF_SIZE 2048
328

    
329
/**
330
 * Open a media file as input. The codec are not opened. Only the file
331
 * header (if present) is read.
332
 *
333
 * @param ic_ptr the opened media file handle is put here
334
 * @param filename filename to open.
335
 * @param fmt if non NULL, force the file format to use
336
 * @param buf_size optional buffer size (zero if default is OK)
337
 * @param ap additionnal parameters needed when opening the file (NULL if default)
338
 * @return 0 if OK. AVERROR_xxx otherwise.
339
 */
340
int av_open_input_file(AVFormatContext **ic_ptr, const char *filename, 
341
                       AVInputFormat *fmt,
342
                       int buf_size,
343
                       AVFormatParameters *ap)
344
{
345
    int err, must_open_file, file_opened;
346
    uint8_t buf[PROBE_BUF_SIZE];
347
    AVProbeData probe_data, *pd = &probe_data;
348
    ByteIOContext pb1, *pb = &pb1;
349
    
350
    file_opened = 0;
351
    pd->filename = "";
352
    if (filename)
353
        pd->filename = filename;
354
    pd->buf = buf;
355
    pd->buf_size = 0;
356

    
357
    if (!fmt) {
358
        /* guess format if no file can be opened  */
359
        fmt = av_probe_input_format(pd, 0);
360
    }
361

    
362
    /* do not open file if the format does not need it. XXX: specific
363
       hack needed to handle RTSP/TCP */
364
    must_open_file = 1;
365
    if (fmt && (fmt->flags & AVFMT_NOFILE)) {
366
        must_open_file = 0;
367
    }
368

    
369
    if (!fmt || must_open_file) {
370
        /* if no file needed do not try to open one */
371
        if (url_fopen(pb, filename, URL_RDONLY) < 0) {
372
            err = AVERROR_IO;
373
            goto fail;
374
        }
375
        file_opened = 1;
376
        if (buf_size > 0) {
377
            url_setbufsize(pb, buf_size);
378
        }
379
        if (!fmt) {
380
            /* read probe data */
381
            pd->buf_size = get_buffer(pb, buf, PROBE_BUF_SIZE);
382
            url_fseek(pb, 0, SEEK_SET);
383
        }
384
    }
385
    
386
    /* guess file format */
387
    if (!fmt) {
388
        fmt = av_probe_input_format(pd, 1);
389
    }
390

    
391
    /* if still no format found, error */
392
    if (!fmt) {
393
        err = AVERROR_NOFMT;
394
        goto fail;
395
    }
396
        
397
    /* XXX: suppress this hack for redirectors */
398
#ifdef CONFIG_NETWORK
399
    if (fmt == &redir_demux) {
400
        err = redir_open(ic_ptr, pb);
401
        url_fclose(pb);
402
        return err;
403
    }
404
#endif
405

    
406
    /* check filename in case of an image number is expected */
407
    if (fmt->flags & AVFMT_NEEDNUMBER) {
408
        if (filename_number_test(filename) < 0) { 
409
            err = AVERROR_NUMEXPECTED;
410
            goto fail;
411
        }
412
    }
413
    err = av_open_input_stream(ic_ptr, pb, filename, fmt, ap);
414
    if (err)
415
        goto fail;
416
    return 0;
417
 fail:
418
    if (file_opened)
419
        url_fclose(pb);
420
    *ic_ptr = NULL;
421
    return err;
422
    
423
}
424

    
425
/*******************************************************/
426

    
427
/**
428
 * Read a packet from a media file. Use it only for low level file
429
 * reading. It is almost always better to use av_read_frame().
430
 * 
431
 * @param s media file handle
432
 * @param pkt is filled 
433
 * @return 0 if OK. AVERROR_xxx if error.  
434
 */
435
int av_read_packet(AVFormatContext *s, AVPacket *pkt)
436
{
437
    AVPacketList *pktl;
438

    
439
    pktl = s->packet_buffer;
440
    if (pktl) {
441
        /* read packet from packet buffer, if there is data */
442
        *pkt = pktl->pkt;
443
        s->packet_buffer = pktl->next;
444
        av_free(pktl);
445
        return 0;
446
    } else {
447
        return s->iformat->read_packet(s, pkt);
448
    }
449
}
450

    
451
/*******************************************************/
452

    
453
/* return TRUE if the stream has accurate timings for at least one component */
454
static int av_has_timings(AVFormatContext *ic)
455
{
456
    int i;
457
    AVStream *st;
458

    
459
    for(i = 0;i < ic->nb_streams; i++) {
460
        st = ic->streams[i];
461
        if (st->start_time != AV_NOPTS_VALUE &&
462
            st->duration != AV_NOPTS_VALUE)
463
            return 1;
464
    }
465
    return 0;
466
}
467

    
468
/* estimate the stream timings from the one of each components. Also
469
   compute the global bitrate if possible */
470
static void av_update_stream_timings(AVFormatContext *ic)
471
{
472
    int64_t start_time, end_time, end_time1;
473
    int i;
474
    AVStream *st;
475

    
476
    start_time = MAXINT64;
477
    end_time = MININT64;
478
    for(i = 0;i < ic->nb_streams; i++) {
479
        st = ic->streams[i];
480
        if (st->start_time != AV_NOPTS_VALUE) {
481
            if (st->start_time < start_time)
482
                start_time = st->start_time;
483
            if (st->duration != AV_NOPTS_VALUE) {
484
                end_time1 = st->start_time + st->duration;
485
                if (end_time1 > end_time)
486
                    end_time = end_time1;
487
            }
488
        }
489
    }
490
    if (start_time != MAXINT64) {
491
        ic->start_time = start_time;
492
        if (end_time != MAXINT64) {
493
            ic->duration = end_time - start_time;
494
            if (ic->file_size > 0) {
495
                /* compute the bit rate */
496
                ic->bit_rate = (double)ic->file_size * 8.0 * AV_TIME_BASE / 
497
                    (double)ic->duration;
498
            }
499
        }
500
    }
501

    
502
}
503

    
504
static void fill_all_stream_timings(AVFormatContext *ic)
505
{
506
    int i;
507
    AVStream *st;
508

    
509
    av_update_stream_timings(ic);
510
    for(i = 0;i < ic->nb_streams; i++) {
511
        st = ic->streams[i];
512
        if (st->start_time == AV_NOPTS_VALUE) {
513
            st->start_time = ic->start_time;
514
            st->duration = ic->duration;
515
        }
516
    }
517
}
518

    
519
static void av_estimate_timings_from_bit_rate(AVFormatContext *ic)
520
{
521
    int64_t filesize, duration;
522
    int bit_rate, i;
523
    AVStream *st;
524

    
525
    /* if bit_rate is already set, we believe it */
526
    if (ic->bit_rate == 0) {
527
        bit_rate = 0;
528
        for(i=0;i<ic->nb_streams;i++) {
529
            st = ic->streams[i];
530
            bit_rate += st->codec.bit_rate;
531
        }
532
        ic->bit_rate = bit_rate;
533
    }
534

    
535
    /* if duration is already set, we believe it */
536
    if (ic->duration == AV_NOPTS_VALUE && 
537
        ic->bit_rate != 0 && 
538
        ic->file_size != 0)  {
539
        filesize = ic->file_size;
540
        if (filesize > 0) {
541
            duration = (int64_t)((8 * AV_TIME_BASE * (double)filesize) / (double)ic->bit_rate);
542
            for(i = 0; i < ic->nb_streams; i++) {
543
                st = ic->streams[i];
544
                if (st->start_time == AV_NOPTS_VALUE ||
545
                    st->duration == AV_NOPTS_VALUE) {
546
                    st->start_time = 0;
547
                    st->duration = duration;
548
                }
549
            }
550
        }
551
    }
552
}
553

    
554
static void flush_packet_queue(AVFormatContext *s)
555
{
556
    AVPacketList *pktl;
557

    
558
    for(;;) {
559
        pktl = s->packet_buffer;
560
        if (!pktl) 
561
            break;
562
        s->packet_buffer = pktl->next;
563
        av_free_packet(&pktl->pkt);
564
        av_free(pktl);
565
    }
566
}
567

    
568
#define DURATION_MAX_READ_SIZE 250000
569

    
570
/* only usable for MPEG-PS streams */
571
static void av_estimate_timings_from_pts(AVFormatContext *ic)
572
{
573
    AVPacket pkt1, *pkt = &pkt1;
574
    AVStream *st;
575
    int read_size, i, ret;
576
    int64_t start_time, end_time, end_time1;
577
    int64_t filesize, offset, duration;
578
    
579
    /* we read the first packets to get the first PTS (not fully
580
       accurate, but it is enough now) */
581
    url_fseek(&ic->pb, 0, SEEK_SET);
582
    read_size = 0;
583
    for(;;) {
584
        if (read_size >= DURATION_MAX_READ_SIZE)
585
            break;
586
        /* if all info is available, we can stop */
587
        for(i = 0;i < ic->nb_streams; i++) {
588
            st = ic->streams[i];
589
            if (st->start_time == AV_NOPTS_VALUE)
590
                break;
591
        }
592
        if (i == ic->nb_streams)
593
            break;
594

    
595
        ret = av_read_packet(ic, pkt);
596
        if (ret != 0)
597
            break;
598
        read_size += pkt->size;
599
        st = ic->streams[pkt->stream_index];
600
        if (pkt->pts != AV_NOPTS_VALUE) {
601
            if (st->start_time == AV_NOPTS_VALUE)
602
                st->start_time = (int64_t)((double)pkt->pts * ic->pts_num * (double)AV_TIME_BASE / ic->pts_den);
603
        }
604
        av_free_packet(pkt);
605
    }
606

    
607
    /* we compute the minimum start_time and use it as default */
608
    start_time = MAXINT64;
609
    for(i = 0; i < ic->nb_streams; i++) {
610
        st = ic->streams[i];
611
        if (st->start_time != AV_NOPTS_VALUE &&
612
            st->start_time < start_time)
613
            start_time = st->start_time;
614
    }
615
    if (start_time != MAXINT64)
616
        ic->start_time = start_time;
617
    
618
    /* estimate the end time (duration) */
619
    /* XXX: may need to support wrapping */
620
    filesize = ic->file_size;
621
    offset = filesize - DURATION_MAX_READ_SIZE;
622
    if (offset < 0)
623
        offset = 0;
624

    
625
    /* flush packet queue */
626
    flush_packet_queue(ic);
627

    
628
    url_fseek(&ic->pb, offset, SEEK_SET);
629
    read_size = 0;
630
    for(;;) {
631
        if (read_size >= DURATION_MAX_READ_SIZE)
632
            break;
633
        /* if all info is available, we can stop */
634
        for(i = 0;i < ic->nb_streams; i++) {
635
            st = ic->streams[i];
636
            if (st->duration == AV_NOPTS_VALUE)
637
                break;
638
        }
639
        if (i == ic->nb_streams)
640
            break;
641
        
642
        ret = av_read_packet(ic, pkt);
643
        if (ret != 0)
644
            break;
645
        read_size += pkt->size;
646
        st = ic->streams[pkt->stream_index];
647
        if (pkt->pts != AV_NOPTS_VALUE) {
648
            end_time = (int64_t)((double)pkt->pts * ic->pts_num * (double)AV_TIME_BASE / ic->pts_den);
649
            duration = end_time - st->start_time;
650
            if (duration > 0) {
651
                if (st->duration == AV_NOPTS_VALUE ||
652
                    st->duration < duration)
653
                    st->duration = duration;
654
            }
655
        }
656
        av_free_packet(pkt);
657
    }
658
    
659
    /* estimate total duration */
660
    end_time = MININT64;
661
    for(i = 0;i < ic->nb_streams; i++) {
662
        st = ic->streams[i];
663
        if (st->duration != AV_NOPTS_VALUE) {
664
            end_time1 = st->start_time + st->duration;
665
            if (end_time1 > end_time)
666
                end_time = end_time1;
667
        }
668
    }
669
    
670
    /* update start_time (new stream may have been created, so we do
671
       it at the end */
672
    if (ic->start_time != AV_NOPTS_VALUE) {
673
        for(i = 0; i < ic->nb_streams; i++) {
674
            st = ic->streams[i];
675
            if (st->start_time == AV_NOPTS_VALUE)
676
                st->start_time = ic->start_time;
677
        }
678
    }
679

    
680
    if (end_time != MININT64) {
681
        /* put dummy values for duration if needed */
682
        for(i = 0;i < ic->nb_streams; i++) {
683
            st = ic->streams[i];
684
            if (st->duration == AV_NOPTS_VALUE && 
685
                st->start_time != AV_NOPTS_VALUE)
686
                st->duration = end_time - st->start_time;
687
        }
688
        ic->duration = end_time - ic->start_time;
689
    }
690

    
691
    url_fseek(&ic->pb, 0, SEEK_SET);
692
}
693

    
694
static void av_estimate_timings(AVFormatContext *ic)
695
{
696
    URLContext *h;
697
    int64_t file_size;
698

    
699
    /* get the file size, if possible */
700
    if (ic->iformat->flags & AVFMT_NOFILE) {
701
        file_size = 0;
702
    } else {
703
        h = url_fileno(&ic->pb);
704
        file_size = url_filesize(h);
705
        if (file_size < 0)
706
            file_size = 0;
707
    }
708
    ic->file_size = file_size;
709

    
710
    if (ic->iformat == &mpegps_demux) {
711
        /* get accurate estimate from the PTSes */
712
        av_estimate_timings_from_pts(ic);
713
    } else if (av_has_timings(ic)) {
714
        /* at least one components has timings - we use them for all
715
           the components */
716
        fill_all_stream_timings(ic);
717
    } else {
718
        /* less precise: use bit rate info */
719
        av_estimate_timings_from_bit_rate(ic);
720
    }
721
    av_update_stream_timings(ic);
722

    
723
#if 0
724
    {
725
        int i;
726
        AVStream *st;
727
        for(i = 0;i < ic->nb_streams; i++) {
728
            st = ic->streams[i];
729
        printf("%d: start_time: %0.3f duration: %0.3f\n", 
730
               i, (double)st->start_time / AV_TIME_BASE, 
731
               (double)st->duration / AV_TIME_BASE);
732
        }
733
        printf("stream: start_time: %0.3f duration: %0.3f bitrate=%d kb/s\n", 
734
               (double)ic->start_time / AV_TIME_BASE, 
735
               (double)ic->duration / AV_TIME_BASE,
736
               ic->bit_rate / 1000);
737
    }
738
#endif
739
}
740

    
741
/* state for codec information */
742
#define CSTATE_NOTFOUND    0
743
#define CSTATE_DECODING    1
744
#define CSTATE_FOUND       2
745

    
746
static int has_codec_parameters(AVCodecContext *enc)
747
{
748
    int val;
749
    switch(enc->codec_type) {
750
    case CODEC_TYPE_AUDIO:
751
        val = enc->sample_rate;
752
        break;
753
    case CODEC_TYPE_VIDEO:
754
        val = enc->width;
755
        break;
756
    default:
757
        val = 1;
758
        break;
759
    }
760
    return (val != 0);
761
}
762

    
763
/**
764
 * Read the beginning of a media file to get stream information. This
765
 * is useful for file formats with no headers such as MPEG. This
766
 * function also compute the real frame rate in case of mpeg2 repeat
767
 * frame mode.
768
 *
769
 * @param ic media file handle
770
 * @return >=0 if OK. AVERROR_xxx if error.  
771
 */
772
int av_find_stream_info(AVFormatContext *ic)
773
{
774
    int i, count, ret, got_picture, size, read_size;
775
    AVCodec *codec;
776
    AVStream *st;
777
    AVPacket *pkt;
778
    AVFrame picture;
779
    AVPacketList *pktl=NULL, **ppktl;
780
    short samples[AVCODEC_MAX_AUDIO_FRAME_SIZE / 2];
781
    uint8_t *ptr;
782
    int min_read_size, max_read_size;
783

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

    
787
    /* XXX: base it on stream bitrate when possible */
788
    if (ic->iformat == &mpegts_demux) {
789
        /* maximum number of bytes we accept to read to find all the streams
790
           in a file */
791
        min_read_size = 6000000;
792
    } else {
793
        min_read_size = 250000;
794
    }
795
    /* max read size is 2 seconds of video max */
796
    max_read_size = min_read_size * 10;
797

    
798
    /* set initial codec state */
799
    for(i=0;i<ic->nb_streams;i++) {
800
        st = ic->streams[i];
801
        if (has_codec_parameters(&st->codec))
802
            st->codec_info_state = CSTATE_FOUND;
803
        else
804
            st->codec_info_state = CSTATE_NOTFOUND;
805
        st->codec_info_nb_repeat_frames = 0;
806
        st->codec_info_nb_real_frames = 0;
807
    }
808

    
809
    count = 0;
810
    read_size = 0;
811
    ppktl = &ic->packet_buffer;
812
    for(;;) {
813
        /* check if one codec still needs to be handled */
814
        for(i=0;i<ic->nb_streams;i++) {
815
            st = ic->streams[i];
816
            if (st->codec_info_state != CSTATE_FOUND)
817
                break;
818
        }
819
        if (i == ic->nb_streams) {
820
            /* NOTE: if the format has no header, then we need to read
821
               some packets to get most of the streams, so we cannot
822
               stop here */
823
            if (!(ic->ctx_flags & AVFMTCTX_NOHEADER) ||
824
                read_size >= min_read_size) {
825
                /* if we found the info for all the codecs, we can stop */
826
                ret = count;
827
                break;
828
            }
829
        } else {
830
            /* we did not get all the codec info, but we read too much data */
831
            if (read_size >= max_read_size) {
832
                ret = count;
833
                break;
834
            }
835
        }
836

    
837
        pktl = av_mallocz(sizeof(AVPacketList));
838
        if (!pktl) {
839
            ret = AVERROR_NOMEM;
840
            break;
841
        }
842

    
843
        /* add the packet in the buffered packet list */
844
        *ppktl = pktl;
845
        ppktl = &pktl->next;
846

    
847
        /* NOTE: a new stream can be added there if no header in file
848
           (AVFMTCTX_NOHEADER) */
849
        pkt = &pktl->pkt;
850
        if (ic->iformat->read_packet(ic, pkt) < 0) {
851
            /* EOF or error */
852
            ret = -1; /* we could not have all the codec parameters before EOF */
853
            if ((ic->ctx_flags & AVFMTCTX_NOHEADER) &&
854
                i == ic->nb_streams)
855
                ret = 0;
856
            break;
857
        }
858
        read_size += pkt->size;
859

    
860
        /* open new codecs */
861
        for(i=0;i<ic->nb_streams;i++) {
862
            st = ic->streams[i];
863
            if (st->codec_info_state == CSTATE_NOTFOUND) {
864
                /* set to found in case of error */
865
                st->codec_info_state = CSTATE_FOUND; 
866
                codec = avcodec_find_decoder(st->codec.codec_id);
867
                if (codec) {
868
                    if(codec->capabilities & CODEC_CAP_TRUNCATED)
869
                        st->codec.flags |= CODEC_FLAG_TRUNCATED;
870

    
871
                    ret = avcodec_open(&st->codec, codec);
872
                    if (ret >= 0)
873
                        st->codec_info_state = CSTATE_DECODING;
874
                }
875
            }
876
        }
877

    
878
        st = ic->streams[pkt->stream_index];
879
        if (st->codec_info_state == CSTATE_DECODING) {
880
            /* decode the data and update codec parameters */
881
            ptr = pkt->data;
882
            size = pkt->size;
883
            while (size > 0) {
884
                switch(st->codec.codec_type) {
885
                case CODEC_TYPE_VIDEO:
886
                    ret = avcodec_decode_video(&st->codec, &picture, 
887
                                               &got_picture, ptr, size);
888
                    break;
889
                case CODEC_TYPE_AUDIO:
890
                    ret = avcodec_decode_audio(&st->codec, samples, 
891
                                               &got_picture, ptr, size);
892
                    break;
893
                default:
894
                    ret = -1;
895
                    break;
896
                }
897
                if (ret < 0) {
898
                    /* if error, simply ignore because another packet
899
                       may be OK */
900
                    break;
901
                }
902
                if (got_picture) {
903
                    /* we got the parameters - now we can stop
904
                       examining this stream */
905
                    /* XXX: add a codec info so that we can decide if
906
                       the codec can repeat frames */
907
                    if (st->codec.codec_id == CODEC_ID_MPEG1VIDEO && 
908
                        ic->iformat != &mpegts_demux &&
909
                        st->codec.sub_id == 2) {
910
                        /* for mpeg2 video, we want to know the real
911
                           frame rate, so we decode 40 frames. In mpeg
912
                           TS case we do not do it because it would be
913
                           too long */
914
                        st->codec_info_nb_real_frames++;
915
                        st->codec_info_nb_repeat_frames += st->codec.coded_frame->repeat_pict;
916
#if 0
917
                        /* XXX: testing */
918
                        if ((st->codec_info_nb_real_frames % 24) == 23) {
919
                            st->codec_info_nb_repeat_frames += 2;
920
                        }
921
#endif
922
                        /* stop after 40 frames */
923
                        if (st->codec_info_nb_real_frames >= 40) {
924
                            av_reduce(
925
                                &st->r_frame_rate,
926
                                &st->r_frame_rate_base,
927
                                (int64_t)st->codec.frame_rate * st->codec_info_nb_real_frames,
928
                                (st->codec_info_nb_real_frames + (st->codec_info_nb_repeat_frames >> 1)) * st->codec.frame_rate_base,
929
                                1<<30);
930
                            goto close_codec;
931
                        }
932
                    } else {
933
                    close_codec:
934
                        st->codec_info_state = CSTATE_FOUND;
935
                        avcodec_close(&st->codec);
936
                        break;
937
                    }
938
                }
939
                ptr += ret;
940
                size -= ret;
941
            }
942
        }
943
        count++;
944
    }
945

    
946
    /* close each codec if there are opened */
947
    for(i=0;i<ic->nb_streams;i++) {
948
        st = ic->streams[i];
949
        if (st->codec_info_state == CSTATE_DECODING)
950
            avcodec_close(&st->codec);
951
    }
952

    
953
    /* set real frame rate info */
954
    for(i=0;i<ic->nb_streams;i++) {
955
        st = ic->streams[i];
956
        if (st->codec.codec_type == CODEC_TYPE_VIDEO) {
957
            if (!st->r_frame_rate){
958
                st->r_frame_rate      = st->codec.frame_rate;
959
                st->r_frame_rate_base = st->codec.frame_rate_base;
960
            }
961
        }
962
    }
963

    
964

    
965
    av_estimate_timings(ic);
966
    return ret;
967
}
968

    
969
/**
970
 * Close a media file (but not its codecs)
971
 *
972
 * @param s media file handle
973
 */
974
void av_close_input_file(AVFormatContext *s)
975
{
976
    int i, must_open_file;
977
    AVStream *st;
978

    
979
    if (s->iformat->read_close)
980
        s->iformat->read_close(s);
981
    for(i=0;i<s->nb_streams;i++) {
982
        /* free all data in a stream component */
983
        st = s->streams[i];
984
        av_free(st);
985
    }
986
    if (s->packet_buffer) {
987
        AVPacketList *p, *p1;
988
        p = s->packet_buffer;
989
        while (p != NULL) {
990
            p1 = p->next;
991
            av_free_packet(&p->pkt);
992
            av_free(p);
993
            p = p1;
994
        }
995
        s->packet_buffer = NULL;
996
    }
997
    must_open_file = 1;
998
    if (s->iformat->flags & AVFMT_NOFILE) {
999
        must_open_file = 0;
1000
    }
1001
    if (must_open_file) {
1002
        url_fclose(&s->pb);
1003
    }
1004
    av_freep(&s->priv_data);
1005
    av_free(s);
1006
}
1007

    
1008
/**
1009
 * Add a new stream to a media file. Can only be called in the
1010
 * read_header function. If the flag AVFMTCTX_NOHEADER is in the
1011
 * format context, then new streams can be added in read_packet too.
1012
 *
1013
 *
1014
 * @param s media file handle
1015
 * @param id file format dependent stream id 
1016
 */
1017
AVStream *av_new_stream(AVFormatContext *s, int id)
1018
{
1019
    AVStream *st;
1020

    
1021
    if (s->nb_streams >= MAX_STREAMS)
1022
        return NULL;
1023

    
1024
    st = av_mallocz(sizeof(AVStream));
1025
    if (!st)
1026
        return NULL;
1027
    avcodec_get_context_defaults(&st->codec);
1028
    if (s->iformat) {
1029
        /* no default bitrate if decoding */
1030
        st->codec.bit_rate = 0;
1031
    }
1032
    st->index = s->nb_streams;
1033
    st->id = id;
1034
    st->start_time = AV_NOPTS_VALUE;
1035
    st->duration = AV_NOPTS_VALUE;
1036
    s->streams[s->nb_streams++] = st;
1037
    return st;
1038
}
1039

    
1040
/************************************************************/
1041
/* output media file */
1042

    
1043
int av_set_parameters(AVFormatContext *s, AVFormatParameters *ap)
1044
{
1045
    int ret;
1046
    
1047
    if (s->oformat->priv_data_size > 0) {
1048
        s->priv_data = av_mallocz(s->oformat->priv_data_size);
1049
        if (!s->priv_data)
1050
            return AVERROR_NOMEM;
1051
    } else
1052
        s->priv_data = NULL;
1053
        
1054
    if (s->oformat->set_parameters) {
1055
        ret = s->oformat->set_parameters(s, ap);
1056
        if (ret < 0)
1057
            return ret;
1058
    }
1059
    return 0;
1060
}
1061

    
1062
/**
1063
 * allocate the stream private data and write the stream header to an
1064
 * output media file
1065
 *
1066
 * @param s media file handle
1067
 * @return 0 if OK. AVERROR_xxx if error.  
1068
 */
1069
int av_write_header(AVFormatContext *s)
1070
{
1071
    int ret, i;
1072
    AVStream *st;
1073

    
1074
    /* default pts settings is MPEG like */
1075
    av_set_pts_info(s, 33, 1, 90000);
1076
    ret = s->oformat->write_header(s);
1077
    if (ret < 0)
1078
        return ret;
1079

    
1080
    /* init PTS generation */
1081
    for(i=0;i<s->nb_streams;i++) {
1082
        st = s->streams[i];
1083

    
1084
        switch (st->codec.codec_type) {
1085
        case CODEC_TYPE_AUDIO:
1086
            av_frac_init(&st->pts, 0, 0, 
1087
                         (int64_t)s->pts_num * st->codec.sample_rate);
1088
            break;
1089
        case CODEC_TYPE_VIDEO:
1090
            av_frac_init(&st->pts, 0, 0, 
1091
                         (int64_t)s->pts_num * st->codec.frame_rate);
1092
            break;
1093
        default:
1094
            break;
1095
        }
1096
    }
1097
    return 0;
1098
}
1099

    
1100
/**
1101
 * Write a packet to an output media file. The packet shall contain
1102
 * one audio or video frame.
1103
 *
1104
 * @param s media file handle
1105
 * @param stream_index stream index
1106
 * @param buf buffer containing the frame data
1107
 * @param size size of buffer
1108
 * @return < 0 if error, = 0 if OK, 1 if end of stream wanted.
1109
 */
1110
int av_write_frame(AVFormatContext *s, int stream_index, const uint8_t *buf, 
1111
                   int size)
1112
{
1113
    AVStream *st;
1114
    int64_t pts_mask;
1115
    int ret, frame_size;
1116

    
1117
    st = s->streams[stream_index];
1118
    pts_mask = (1LL << s->pts_wrap_bits) - 1;
1119
    ret = s->oformat->write_packet(s, stream_index, (uint8_t *)buf, size, 
1120
                                   st->pts.val & pts_mask);
1121
    if (ret < 0)
1122
        return ret;
1123

    
1124
    /* update pts */
1125
    switch (st->codec.codec_type) {
1126
    case CODEC_TYPE_AUDIO:
1127
        if (st->codec.frame_size <= 1) {
1128
            frame_size = size / st->codec.channels;
1129
            /* specific hack for pcm codecs because no frame size is provided */
1130
            switch(st->codec.codec_id) {
1131
            case CODEC_ID_PCM_S16LE:
1132
            case CODEC_ID_PCM_S16BE:
1133
            case CODEC_ID_PCM_U16LE:
1134
            case CODEC_ID_PCM_U16BE:
1135
                frame_size >>= 1;
1136
                break;
1137
            default:
1138
                break;
1139
            }
1140
        } else {
1141
            frame_size = st->codec.frame_size;
1142
        }
1143
        av_frac_add(&st->pts, 
1144
                    (int64_t)s->pts_den * frame_size);
1145
        break;
1146
    case CODEC_TYPE_VIDEO:
1147
        av_frac_add(&st->pts, 
1148
                    (int64_t)s->pts_den * st->codec.frame_rate_base);
1149
        break;
1150
    default:
1151
        break;
1152
    }
1153
    return ret;
1154
}
1155

    
1156
/**
1157
 * write the stream trailer to an output media file and and free the
1158
 * file private data.
1159
 *
1160
 * @param s media file handle
1161
 * @return 0 if OK. AVERROR_xxx if error.  */
1162
int av_write_trailer(AVFormatContext *s)
1163
{
1164
    int ret;
1165
    ret = s->oformat->write_trailer(s);
1166
    av_freep(&s->priv_data);
1167
    return ret;
1168
}
1169

    
1170
/* "user interface" functions */
1171

    
1172
void dump_format(AVFormatContext *ic,
1173
                 int index, 
1174
                 const char *url,
1175
                 int is_output)
1176
{
1177
    int i, flags;
1178
    char buf[256];
1179

    
1180
    fprintf(stderr, "%s #%d, %s, %s '%s':\n", 
1181
            is_output ? "Output" : "Input",
1182
            index, 
1183
            is_output ? ic->oformat->name : ic->iformat->name, 
1184
            is_output ? "to" : "from", url);
1185
    if (!is_output) {
1186
        fprintf(stderr, "  Duration: ");
1187
        if (ic->duration != AV_NOPTS_VALUE) {
1188
            int hours, mins, secs, us;
1189
            secs = ic->duration / AV_TIME_BASE;
1190
            us = ic->duration % AV_TIME_BASE;
1191
            mins = secs / 60;
1192
            secs %= 60;
1193
            hours = mins / 60;
1194
            mins %= 60;
1195
            fprintf(stderr, "%02d:%02d:%02d.%01d", hours, mins, secs, 
1196
                   (10 * us) / AV_TIME_BASE);
1197
        } else {
1198
            fprintf(stderr, "N/A");
1199
        }
1200
        fprintf(stderr, ", bitrate: ");
1201
        if (ic->bit_rate) {
1202
            fprintf(stderr,"%d kb/s", ic->bit_rate / 1000);
1203
        } else {
1204
            fprintf(stderr, "N/A");
1205
        }
1206
        fprintf(stderr, "\n");
1207
    }
1208
    for(i=0;i<ic->nb_streams;i++) {
1209
        AVStream *st = ic->streams[i];
1210
        avcodec_string(buf, sizeof(buf), &st->codec, is_output);
1211
        fprintf(stderr, "  Stream #%d.%d", index, i);
1212
        /* the pid is an important information, so we display it */
1213
        /* XXX: add a generic system */
1214
        if (is_output)
1215
            flags = ic->oformat->flags;
1216
        else
1217
            flags = ic->iformat->flags;
1218
        if (flags & AVFMT_SHOW_IDS) {
1219
            fprintf(stderr, "[0x%x]", st->id);
1220
        }
1221
        fprintf(stderr, ": %s\n", buf);
1222
    }
1223
}
1224

    
1225
typedef struct {
1226
    const char *abv;
1227
    int width, height;
1228
    int frame_rate, frame_rate_base;
1229
} AbvEntry;
1230

    
1231
static AbvEntry frame_abvs[] = {
1232
    { "ntsc",      720, 480, 30000, 1001 },
1233
    { "pal",       720, 576,    25,    1 },
1234
    { "qntsc",     352, 240, 30000, 1001 }, /* VCD compliant ntsc */
1235
    { "qpal",      352, 288,    25,    1 }, /* VCD compliant pal */
1236
    { "sntsc",     640, 480, 30000, 1001 }, /* square pixel ntsc */
1237
    { "spal",      768, 576,    25,    1 }, /* square pixel pal */
1238
    { "film",      352, 240,    24,    1 },
1239
    { "ntsc-film", 352, 240, 24000, 1001 },
1240
    { "sqcif",     128,  96,     0,    0 },
1241
    { "qcif",      176, 144,     0,    0 },
1242
    { "cif",       352, 288,     0,    0 },
1243
    { "4cif",      704, 576,     0,    0 },
1244
};
1245

    
1246
int parse_image_size(int *width_ptr, int *height_ptr, const char *str)
1247
{
1248
    int i;
1249
    int n = sizeof(frame_abvs) / sizeof(AbvEntry);
1250
    const char *p;
1251
    int frame_width = 0, frame_height = 0;
1252

    
1253
    for(i=0;i<n;i++) {
1254
        if (!strcmp(frame_abvs[i].abv, str)) {
1255
            frame_width = frame_abvs[i].width;
1256
            frame_height = frame_abvs[i].height;
1257
            break;
1258
        }
1259
    }
1260
    if (i == n) {
1261
        p = str;
1262
        frame_width = strtol(p, (char **)&p, 10);
1263
        if (*p)
1264
            p++;
1265
        frame_height = strtol(p, (char **)&p, 10);
1266
    }
1267
    if (frame_width <= 0 || frame_height <= 0)
1268
        return -1;
1269
    *width_ptr = frame_width;
1270
    *height_ptr = frame_height;
1271
    return 0;
1272
}
1273

    
1274
int parse_frame_rate(int *frame_rate, int *frame_rate_base, const char *arg)
1275
{
1276
    int i;
1277
    char* cp;
1278
   
1279
    /* First, we check our abbreviation table */
1280
    for (i = 0; i < sizeof(frame_abvs)/sizeof(*frame_abvs); ++i)
1281
         if (!strcmp(frame_abvs[i].abv, arg)) {
1282
             *frame_rate = frame_abvs[i].frame_rate;
1283
             *frame_rate_base = frame_abvs[i].frame_rate_base;
1284
             return 0;
1285
         }
1286

    
1287
    /* Then, we try to parse it as fraction */
1288
    cp = strchr(arg, '/');
1289
    if (cp) {
1290
        char* cpp;
1291
        *frame_rate = strtol(arg, &cpp, 10);
1292
        if (cpp != arg || cpp == cp) 
1293
            *frame_rate_base = strtol(cp+1, &cpp, 10);
1294
        else
1295
           *frame_rate = 0;
1296
    } 
1297
    else {
1298
        /* Finally we give up and parse it as double */
1299
        *frame_rate_base = DEFAULT_FRAME_RATE_BASE;
1300
        *frame_rate = (int)(strtod(arg, 0) * (*frame_rate_base) + 0.5);
1301
    }
1302
    if (!*frame_rate || !*frame_rate_base)
1303
        return -1;
1304
    else
1305
        return 0;
1306
}
1307

    
1308
/* Syntax:
1309
 * - If not a duration:
1310
 *  [{YYYY-MM-DD|YYYYMMDD}]{T| }{HH[:MM[:SS[.m...]]][Z]|HH[MM[SS[.m...]]][Z]}
1311
 * Time is localtime unless Z is suffixed to the end. In this case GMT
1312
 * Return the date in micro seconds since 1970 
1313
 * - If duration:
1314
 *  HH[:MM[:SS[.m...]]]
1315
 *  S+[.m...]
1316
 */
1317
int64_t parse_date(const char *datestr, int duration)
1318
{
1319
    const char *p;
1320
    int64_t t;
1321
    struct tm dt;
1322
    int i;
1323
    static const char *date_fmt[] = {
1324
        "%Y-%m-%d",
1325
        "%Y%m%d",
1326
    };
1327
    static const char *time_fmt[] = {
1328
        "%H:%M:%S",
1329
        "%H%M%S",
1330
    };
1331
    const char *q;
1332
    int is_utc, len;
1333
    char lastch;
1334
    time_t now = time(0);
1335

    
1336
    len = strlen(datestr);
1337
    if (len > 0)
1338
        lastch = datestr[len - 1];
1339
    else
1340
        lastch = '\0';
1341
    is_utc = (lastch == 'z' || lastch == 'Z');
1342

    
1343
    memset(&dt, 0, sizeof(dt));
1344

    
1345
    p = datestr;
1346
    q = NULL;
1347
    if (!duration) {
1348
        for (i = 0; i < sizeof(date_fmt) / sizeof(date_fmt[0]); i++) {
1349
            q = small_strptime(p, date_fmt[i], &dt);
1350
            if (q) {
1351
                break;
1352
            }
1353
        }
1354

    
1355
        if (!q) {
1356
            if (is_utc) {
1357
                dt = *gmtime(&now);
1358
            } else {
1359
                dt = *localtime(&now);
1360
            }
1361
            dt.tm_hour = dt.tm_min = dt.tm_sec = 0;
1362
        } else {
1363
            p = q;
1364
        }
1365

    
1366
        if (*p == 'T' || *p == 't' || *p == ' ')
1367
            p++;
1368

    
1369
        for (i = 0; i < sizeof(time_fmt) / sizeof(time_fmt[0]); i++) {
1370
            q = small_strptime(p, time_fmt[i], &dt);
1371
            if (q) {
1372
                break;
1373
            }
1374
        }
1375
    } else {
1376
        q = small_strptime(p, time_fmt[0], &dt);
1377
        if (!q) {
1378
            dt.tm_sec = strtol(p, (char **)&q, 10);
1379
            dt.tm_min = 0;
1380
            dt.tm_hour = 0;
1381
        }
1382
    }
1383

    
1384
    /* Now we have all the fields that we can get */
1385
    if (!q) {
1386
        if (duration)
1387
            return 0;
1388
        else
1389
            return now * int64_t_C(1000000);
1390
    }
1391

    
1392
    if (duration) {
1393
        t = dt.tm_hour * 3600 + dt.tm_min * 60 + dt.tm_sec;
1394
    } else {
1395
        dt.tm_isdst = -1;       /* unknown */
1396
        if (is_utc) {
1397
            t = mktimegm(&dt);
1398
        } else {
1399
            t = mktime(&dt);
1400
        }
1401
    }
1402

    
1403
    t *= 1000000;
1404

    
1405
    if (*q == '.') {
1406
        int val, n;
1407
        q++;
1408
        for (val = 0, n = 100000; n >= 1; n /= 10, q++) {
1409
            if (!isdigit(*q)) 
1410
                break;
1411
            val += n * (*q - '0');
1412
        }
1413
        t += val;
1414
    }
1415
    return t;
1416
}
1417

    
1418
/* syntax: '?tag1=val1&tag2=val2...'. Little URL decoding is done. Return
1419
   1 if found */
1420
int find_info_tag(char *arg, int arg_size, const char *tag1, const char *info)
1421
{
1422
    const char *p;
1423
    char tag[128], *q;
1424

    
1425
    p = info;
1426
    if (*p == '?')
1427
        p++;
1428
    for(;;) {
1429
        q = tag;
1430
        while (*p != '\0' && *p != '=' && *p != '&') {
1431
            if ((q - tag) < sizeof(tag) - 1)
1432
                *q++ = *p;
1433
            p++;
1434
        }
1435
        *q = '\0';
1436
        q = arg;
1437
        if (*p == '=') {
1438
            p++;
1439
            while (*p != '&' && *p != '\0') {
1440
                if ((q - arg) < arg_size - 1) {
1441
                    if (*p == '+')
1442
                        *q++ = ' ';
1443
                    else
1444
                        *q++ = *p;
1445
                }
1446
                p++;
1447
            }
1448
            *q = '\0';
1449
        }
1450
        if (!strcmp(tag, tag1)) 
1451
            return 1;
1452
        if (*p != '&')
1453
            break;
1454
        p++;
1455
    }
1456
    return 0;
1457
}
1458

    
1459
/* Return in 'buf' the path with '%d' replaced by number. Also handles
1460
   the '%0nd' format where 'n' is the total number of digits and
1461
   '%%'. Return 0 if OK, and -1 if format error */
1462
int get_frame_filename(char *buf, int buf_size,
1463
                       const char *path, int number)
1464
{
1465
    const char *p;
1466
    char *q, buf1[20], c;
1467
    int nd, len, percentd_found;
1468

    
1469
    q = buf;
1470
    p = path;
1471
    percentd_found = 0;
1472
    for(;;) {
1473
        c = *p++;
1474
        if (c == '\0')
1475
            break;
1476
        if (c == '%') {
1477
            do {
1478
                nd = 0;
1479
                while (isdigit(*p)) {
1480
                    nd = nd * 10 + *p++ - '0';
1481
                }
1482
                c = *p++;
1483
            } while (isdigit(c));
1484

    
1485
            switch(c) {
1486
            case '%':
1487
                goto addchar;
1488
            case 'd':
1489
                if (percentd_found)
1490
                    goto fail;
1491
                percentd_found = 1;
1492
                snprintf(buf1, sizeof(buf1), "%0*d", nd, number);
1493
                len = strlen(buf1);
1494
                if ((q - buf + len) > buf_size - 1)
1495
                    goto fail;
1496
                memcpy(q, buf1, len);
1497
                q += len;
1498
                break;
1499
            default:
1500
                goto fail;
1501
            }
1502
        } else {
1503
        addchar:
1504
            if ((q - buf) < buf_size - 1)
1505
                *q++ = c;
1506
        }
1507
    }
1508
    if (!percentd_found)
1509
        goto fail;
1510
    *q = '\0';
1511
    return 0;
1512
 fail:
1513
    *q = '\0';
1514
    return -1;
1515
}
1516

    
1517
/**
1518
 *
1519
 * Print on stdout a nice hexa dump of a buffer
1520
 * @param buf buffer
1521
 * @param size buffer size
1522
 */
1523
void av_hex_dump(uint8_t *buf, int size)
1524
{
1525
    int len, i, j, c;
1526

    
1527
    for(i=0;i<size;i+=16) {
1528
        len = size - i;
1529
        if (len > 16)
1530
            len = 16;
1531
        printf("%08x ", i);
1532
        for(j=0;j<16;j++) {
1533
            if (j < len)
1534
                printf(" %02x", buf[i+j]);
1535
            else
1536
                printf("   ");
1537
        }
1538
        printf(" ");
1539
        for(j=0;j<len;j++) {
1540
            c = buf[i+j];
1541
            if (c < ' ' || c > '~')
1542
                c = '.';
1543
            printf("%c", c);
1544
        }
1545
        printf("\n");
1546
    }
1547
}
1548

    
1549
void url_split(char *proto, int proto_size,
1550
               char *hostname, int hostname_size,
1551
               int *port_ptr,
1552
               char *path, int path_size,
1553
               const char *url)
1554
{
1555
    const char *p;
1556
    char *q;
1557
    int port;
1558

    
1559
    port = -1;
1560

    
1561
    p = url;
1562
    q = proto;
1563
    while (*p != ':' && *p != '\0') {
1564
        if ((q - proto) < proto_size - 1)
1565
            *q++ = *p;
1566
        p++;
1567
    }
1568
    if (proto_size > 0)
1569
        *q = '\0';
1570
    if (*p == '\0') {
1571
        if (proto_size > 0)
1572
            proto[0] = '\0';
1573
        if (hostname_size > 0)
1574
            hostname[0] = '\0';
1575
        p = url;
1576
    } else {
1577
        p++;
1578
        if (*p == '/')
1579
            p++;
1580
        if (*p == '/')
1581
            p++;
1582
        q = hostname;
1583
        while (*p != ':' && *p != '/' && *p != '?' && *p != '\0') {
1584
            if ((q - hostname) < hostname_size - 1)
1585
                *q++ = *p;
1586
            p++;
1587
        }
1588
        if (hostname_size > 0)
1589
            *q = '\0';
1590
        if (*p == ':') {
1591
            p++;
1592
            port = strtoul(p, (char **)&p, 10);
1593
        }
1594
    }
1595
    if (port_ptr)
1596
        *port_ptr = port;
1597
    pstrcpy(path, path_size, p);
1598
}
1599

    
1600
/**
1601
 * Set the pts for a given stream
1602
 * @param s stream 
1603
 * @param pts_wrap_bits number of bits effectively used by the pts
1604
 *        (used for wrap control, 33 is the value for MPEG) 
1605
 * @param pts_num numerator to convert to seconds (MPEG: 1) 
1606
 * @param pts_den denominator to convert to seconds (MPEG: 90000)
1607
 */
1608
void av_set_pts_info(AVFormatContext *s, int pts_wrap_bits,
1609
                     int pts_num, int pts_den)
1610
{
1611
    s->pts_wrap_bits = pts_wrap_bits;
1612
    s->pts_num = pts_num;
1613
    s->pts_den = pts_den;
1614
}
1615

    
1616
/* fraction handling */
1617

    
1618
/**
1619
 * f = val + (num / den) + 0.5. 'num' is normalized so that it is such
1620
 * as 0 <= num < den.
1621
 *
1622
 * @param f fractional number
1623
 * @param val integer value
1624
 * @param num must be >= 0
1625
 * @param den must be >= 1 
1626
 */
1627
void av_frac_init(AVFrac *f, int64_t val, int64_t num, int64_t den)
1628
{
1629
    num += (den >> 1);
1630
    if (num >= den) {
1631
        val += num / den;
1632
        num = num % den;
1633
    }
1634
    f->val = val;
1635
    f->num = num;
1636
    f->den = den;
1637
}
1638

    
1639
/* set f to (val + 0.5) */
1640
void av_frac_set(AVFrac *f, int64_t val)
1641
{
1642
    f->val = val;
1643
    f->num = f->den >> 1;
1644
}
1645

    
1646
/**
1647
 * Fractionnal addition to f: f = f + (incr / f->den)
1648
 *
1649
 * @param f fractional number
1650
 * @param incr increment, can be positive or negative
1651
 */
1652
void av_frac_add(AVFrac *f, int64_t incr)
1653
{
1654
    int64_t num, den;
1655

    
1656
    num = f->num + incr;
1657
    den = f->den;
1658
    if (num < 0) {
1659
        f->val += num / den;
1660
        num = num % den;
1661
        if (num < 0) {
1662
            num += den;
1663
            f->val--;
1664
        }
1665
    } else if (num >= den) {
1666
        f->val += num / den;
1667
        num = num % den;
1668
    }
1669
    f->num = num;
1670
}
1671

    
1672
/**
1673
 * register a new image format
1674
 * @param img_fmt Image format descriptor
1675
 */
1676
void av_register_image_format(AVImageFormat *img_fmt)
1677
{
1678
    AVImageFormat **p;
1679

    
1680
    p = &first_image_format;
1681
    while (*p != NULL) p = &(*p)->next;
1682
    *p = img_fmt;
1683
    img_fmt->next = NULL;
1684
}
1685

    
1686
/* guess image format */
1687
AVImageFormat *av_probe_image_format(AVProbeData *pd)
1688
{
1689
    AVImageFormat *fmt1, *fmt;
1690
    int score, score_max;
1691

    
1692
    fmt = NULL;
1693
    score_max = 0;
1694
    for(fmt1 = first_image_format; fmt1 != NULL; fmt1 = fmt1->next) {
1695
        if (fmt1->img_probe) {
1696
            score = fmt1->img_probe(pd);
1697
            if (score > score_max) {
1698
                score_max = score;
1699
                fmt = fmt1;
1700
            }
1701
        }
1702
    }
1703
    return fmt;
1704
}
1705

    
1706
AVImageFormat *guess_image_format(const char *filename)
1707
{
1708
    AVImageFormat *fmt1;
1709

    
1710
    for(fmt1 = first_image_format; fmt1 != NULL; fmt1 = fmt1->next) {
1711
        if (fmt1->extensions && match_ext(filename, fmt1->extensions))
1712
            return fmt1;
1713
    }
1714
    return NULL;
1715
}
1716

    
1717
/**
1718
 * Read an image from a stream. 
1719
 * @param gb byte stream containing the image
1720
 * @param fmt image format, NULL if probing is required
1721
 */
1722
int av_read_image(ByteIOContext *pb, const char *filename,
1723
                  AVImageFormat *fmt,
1724
                  int (*alloc_cb)(void *, AVImageInfo *info), void *opaque)
1725
{
1726
    char buf[PROBE_BUF_SIZE];
1727
    AVProbeData probe_data, *pd = &probe_data;
1728
    offset_t pos;
1729
    int ret;
1730

    
1731
    if (!fmt) {
1732
        pd->filename = filename;
1733
        pd->buf = buf;
1734
        pos = url_ftell(pb);
1735
        pd->buf_size = get_buffer(pb, buf, PROBE_BUF_SIZE);
1736
        url_fseek(pb, pos, SEEK_SET);
1737
        fmt = av_probe_image_format(pd);
1738
    }
1739
    if (!fmt)
1740
        return AVERROR_NOFMT;
1741
    ret = fmt->img_read(pb, alloc_cb, opaque);
1742
    return ret;
1743
}
1744

    
1745
/**
1746
 * Write an image to a stream.
1747
 * @param pb byte stream for the image output
1748
 * @param fmt image format
1749
 * @param img image data and informations
1750
 */
1751
int av_write_image(ByteIOContext *pb, AVImageFormat *fmt, AVImageInfo *img)
1752
{
1753
    return fmt->img_write(pb, img);
1754
}
1755