utils.c 46.6 KB
Newer Older
Fabrice Bellard's avatar
Fabrice Bellard committed
1 2
/*
 * Various utilities for ffmpeg system
3
 * Copyright (c) 2000, 2001, 2002 Fabrice Bellard
Fabrice Bellard's avatar
Fabrice Bellard committed
4
 *
5 6 7 8
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
Fabrice Bellard's avatar
Fabrice Bellard committed
9
 *
10
 * This library is distributed in the hope that it will be useful,
Fabrice Bellard's avatar
Fabrice Bellard committed
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
Fabrice Bellard's avatar
Fabrice Bellard committed
14
 *
15 16 17
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
Fabrice Bellard's avatar
Fabrice Bellard committed
18
 */
Fabrice Bellard's avatar
Fabrice Bellard committed
19
#include "avformat.h"
20

21 22
AVInputFormat *first_iformat;
AVOutputFormat *first_oformat;
23
AVImageFormat *first_image_format;
Fabrice Bellard's avatar
Fabrice Bellard committed
24

25
void av_register_input_format(AVInputFormat *format)
Fabrice Bellard's avatar
Fabrice Bellard committed
26
{
27 28 29 30 31 32 33 34 35 36 37
    AVInputFormat **p;
    p = &first_iformat;
    while (*p != NULL) p = &(*p)->next;
    *p = format;
    format->next = NULL;
}

void av_register_output_format(AVOutputFormat *format)
{
    AVOutputFormat **p;
    p = &first_oformat;
Fabrice Bellard's avatar
Fabrice Bellard committed
38 39 40 41 42
    while (*p != NULL) p = &(*p)->next;
    *p = format;
    format->next = NULL;
}

43
int match_ext(const char *filename, const char *extensions)
Fabrice Bellard's avatar
Fabrice Bellard committed
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
{
    const char *ext, *p;
    char ext1[32], *q;

    ext = strrchr(filename, '.');
    if (ext) {
        ext++;
        p = extensions;
        for(;;) {
            q = ext1;
            while (*p != '\0' && *p != ',') 
                *q++ = *p++;
            *q = '\0';
            if (!strcasecmp(ext1, ext)) 
                return 1;
            if (*p == '\0') 
                break;
            p++;
        }
    }
    return 0;
}

67 68
AVOutputFormat *guess_format(const char *short_name, const char *filename, 
                             const char *mime_type)
Fabrice Bellard's avatar
Fabrice Bellard committed
69
{
70
    AVOutputFormat *fmt, *fmt_found;
Fabrice Bellard's avatar
Fabrice Bellard committed
71 72
    int score_max, score;

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

Fabrice Bellard's avatar
Fabrice Bellard committed
80 81 82
    /* find the proper file type */
    fmt_found = NULL;
    score_max = 0;
83
    fmt = first_oformat;
Fabrice Bellard's avatar
Fabrice Bellard committed
84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
    while (fmt != NULL) {
        score = 0;
        if (fmt->name && short_name && !strcmp(fmt->name, short_name))
            score += 100;
        if (fmt->mime_type && mime_type && !strcmp(fmt->mime_type, mime_type))
            score += 10;
        if (filename && fmt->extensions && 
            match_ext(filename, fmt->extensions)) {
            score += 5;
        }
        if (score > score_max) {
            score_max = score;
            fmt_found = fmt;
        }
        fmt = fmt->next;
    }
    return fmt_found;
}   

103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
AVOutputFormat *guess_stream_format(const char *short_name, const char *filename, 
                             const char *mime_type)
{
    AVOutputFormat *fmt = guess_format(short_name, filename, mime_type);

    if (fmt) {
        AVOutputFormat *stream_fmt;
        char stream_format_name[64];

        snprintf(stream_format_name, sizeof(stream_format_name), "%s_stream", fmt->name);
        stream_fmt = guess_format(stream_format_name, NULL, NULL);

        if (stream_fmt)
            fmt = stream_fmt;
    }

    return fmt;
}

122 123 124 125 126 127 128 129 130 131
AVInputFormat *av_find_input_format(const char *short_name)
{
    AVInputFormat *fmt;
    for(fmt = first_iformat; fmt != NULL; fmt = fmt->next) {
        if (!strcmp(fmt->name, short_name))
            return fmt;
    }
    return NULL;
}

Fabrice Bellard's avatar
Fabrice Bellard committed
132 133
/* memory handling */

134 135 136 137 138 139 140 141 142
/**
 * Default packet destructor 
 */
static void av_destruct_packet(AVPacket *pkt)
{
    av_free(pkt->data);
    pkt->data = NULL; pkt->size = 0;
}

143 144 145 146 147 148 149
/**
 * Allocate the payload of a packet and intialized its fields to default values.
 *
 * @param pkt packet
 * @param size wanted payload size
 * @return 0 if OK. AVERROR_xxx otherwise.
 */
Fabrice Bellard's avatar
Fabrice Bellard committed
150 151
int av_new_packet(AVPacket *pkt, int size)
{
152 153
    void *data = av_malloc(size + FF_INPUT_BUFFER_PADDING_SIZE);
    if (!data)
154
        return AVERROR_NOMEM;
155
    memset(data + size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
156

157 158 159 160
    av_init_packet(pkt);
    pkt->data = data; 
    pkt->size = size;
    pkt->destruct = av_destruct_packet;
Fabrice Bellard's avatar
Fabrice Bellard committed
161 162 163 164 165 166 167
    return 0;
}

/* fifo handling */

int fifo_init(FifoBuffer *f, int size)
{
168
    f->buffer = av_malloc(size);
Fabrice Bellard's avatar
Fabrice Bellard committed
169 170 171 172 173 174 175 176 177
    if (!f->buffer)
        return -1;
    f->end = f->buffer + size;
    f->wptr = f->rptr = f->buffer;
    return 0;
}

void fifo_free(FifoBuffer *f)
{
178
    av_free(f->buffer);
Fabrice Bellard's avatar
Fabrice Bellard committed
179 180
}

181
int fifo_size(FifoBuffer *f, uint8_t *rptr)
Fabrice Bellard's avatar
Fabrice Bellard committed
182 183 184 185 186 187 188 189 190 191 192 193
{
    int size;

    if (f->wptr >= rptr) {
        size = f->wptr - rptr;
    } else {
        size = (f->end - rptr) + (f->wptr - f->buffer);
    }
    return size;
}

/* 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)
Fabrice Bellard's avatar
Fabrice Bellard committed
195
{
196
    uint8_t *rptr = *rptr_ptr;
Fabrice Bellard's avatar
Fabrice Bellard committed
197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
    int size, len;

    if (f->wptr >= rptr) {
        size = f->wptr - rptr;
    } else {
        size = (f->end - rptr) + (f->wptr - f->buffer);
    }
    
    if (size < buf_size)
        return -1;
    while (buf_size > 0) {
        len = f->end - rptr;
        if (len > buf_size)
            len = buf_size;
        memcpy(buf, rptr, len);
        buf += len;
        rptr += len;
        if (rptr >= f->end)
            rptr = f->buffer;
        buf_size -= len;
    }
    *rptr_ptr = rptr;
    return 0;
}

222
void fifo_write(FifoBuffer *f, uint8_t *buf, int size, uint8_t **wptr_ptr)
Fabrice Bellard's avatar
Fabrice Bellard committed
223 224
{
    int len;
225
    uint8_t *wptr;
Fabrice Bellard's avatar
Fabrice Bellard committed
226 227 228 229 230 231 232 233 234 235 236 237 238 239 240
    wptr = *wptr_ptr;
    while (size > 0) {
        len = f->end - wptr;
        if (len > size)
            len = size;
        memcpy(wptr, buf, len);
        wptr += len;
        if (wptr >= f->end)
            wptr = f->buffer;
        buf += len;
        size -= len;
    }
    *wptr_ptr = wptr;
}

241 242 243 244 245 246 247
int filename_number_test(const char *filename)
{
    char buf[1024];
    return get_frame_filename(buf, sizeof(buf), filename, 1);
}

/* guess file format */
248
AVInputFormat *av_probe_input_format(AVProbeData *pd, int is_opened)
249 250 251 252 253 254 255 256 257 258
{
    AVInputFormat *fmt1, *fmt;
    int score, score_max;

    fmt = NULL;
    score_max = 0;
    for(fmt1 = first_iformat; fmt1 != NULL; fmt1 = fmt1->next) {
        if (!is_opened && !(fmt1->flags & AVFMT_NOFILE))
            continue;
        score = 0;
259 260 261
        if (fmt1->read_probe) {
            score = fmt1->read_probe(pd);
        } else if (fmt1->extensions) {
262 263 264
            if (match_ext(pd->filename, fmt1->extensions)) {
                score = 50;
            }
265
        } 
266 267 268 269 270 271 272 273 274 275
        if (score > score_max) {
            score_max = score;
            fmt = fmt1;
        }
    }
    return fmt;
}

/************************************************************/
/* input media file */
276

277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326
/**
 * open a media file from an IO stream. 'fmt' must be specified.
 */
int av_open_input_stream(AVFormatContext **ic_ptr, 
                         ByteIOContext *pb, const char *filename, 
                         AVInputFormat *fmt, AVFormatParameters *ap)
{
    int err;
    AVFormatContext *ic;

    ic = av_mallocz(sizeof(AVFormatContext));
    if (!ic) {
        err = AVERROR_NOMEM;
        goto fail;
    }
    ic->iformat = fmt;
    if (pb)
        ic->pb = *pb;
    ic->duration = AV_NOPTS_VALUE;
    ic->start_time = AV_NOPTS_VALUE;
    pstrcpy(ic->filename, sizeof(ic->filename), filename);

    /* allocate private data */
    if (fmt->priv_data_size > 0) {
        ic->priv_data = av_mallocz(fmt->priv_data_size);
        if (!ic->priv_data) {
            err = AVERROR_NOMEM;
            goto fail;
        }
    } else {
        ic->priv_data = NULL;
    }

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

    err = ic->iformat->read_header(ic, ap);
    if (err < 0)
        goto fail;
    *ic_ptr = ic;
    return 0;
 fail:
    if (ic) {
        av_freep(&ic->priv_data);
    }
    av_free(ic);
    *ic_ptr = NULL;
    return err;
}

327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343
#define PROBE_BUF_SIZE 2048

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

    if (!fmt) {
        /* guess format if no file can be opened  */
359
        fmt = av_probe_input_format(pd, 0);
Fabrice Bellard's avatar
Fabrice Bellard committed
360 361
    }

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

    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 380
        if (!fmt) {
            /* read probe data */
381 382
            pd->buf_size = get_buffer(pb, buf, PROBE_BUF_SIZE);
            url_fseek(pb, 0, SEEK_SET);
383
        }
384 385
    }
    
386 387
    /* guess file format */
    if (!fmt) {
388
        fmt = av_probe_input_format(pd, 1);
389 390 391 392 393
    }

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

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

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

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

    pktl = s->packet_buffer;
    if (pktl) {
        /* read packet from packet buffer, if there is data */
        *pkt = pktl->pkt;
        s->packet_buffer = pktl->next;
444
        av_free(pktl);
Fabrice Bellard's avatar
Fabrice Bellard committed
445 446
        return 0;
    } else {
447 448 449 450
        return s->iformat->read_packet(s, pkt);
    }
}

451
/*******************************************************/
452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562

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

    for(i = 0;i < ic->nb_streams; i++) {
        st = ic->streams[i];
        if (st->start_time != AV_NOPTS_VALUE &&
            st->duration != AV_NOPTS_VALUE)
            return 1;
    }
    return 0;
}

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

    start_time = MAXINT64;
    end_time = MININT64;
    for(i = 0;i < ic->nb_streams; i++) {
        st = ic->streams[i];
        if (st->start_time != AV_NOPTS_VALUE) {
            if (st->start_time < start_time)
                start_time = st->start_time;
            if (st->duration != AV_NOPTS_VALUE) {
                end_time1 = st->start_time + st->duration;
                if (end_time1 > end_time)
                    end_time = end_time1;
            }
        }
    }
    if (start_time != MAXINT64) {
        ic->start_time = start_time;
        if (end_time != MAXINT64) {
            ic->duration = end_time - start_time;
            if (ic->file_size > 0) {
                /* compute the bit rate */
                ic->bit_rate = (double)ic->file_size * 8.0 * AV_TIME_BASE / 
                    (double)ic->duration;
            }
        }
    }

}

static void fill_all_stream_timings(AVFormatContext *ic)
{
    int i;
    AVStream *st;

    av_update_stream_timings(ic);
    for(i = 0;i < ic->nb_streams; i++) {
        st = ic->streams[i];
        if (st->start_time == AV_NOPTS_VALUE) {
            st->start_time = ic->start_time;
            st->duration = ic->duration;
        }
    }
}

static void av_estimate_timings_from_bit_rate(AVFormatContext *ic)
{
    int64_t filesize, duration;
    int bit_rate, i;
    AVStream *st;

    /* if bit_rate is already set, we believe it */
    if (ic->bit_rate == 0) {
        bit_rate = 0;
        for(i=0;i<ic->nb_streams;i++) {
            st = ic->streams[i];
            bit_rate += st->codec.bit_rate;
        }
        ic->bit_rate = bit_rate;
    }

    /* if duration is already set, we believe it */
    if (ic->duration == AV_NOPTS_VALUE && 
        ic->bit_rate != 0 && 
        ic->file_size != 0)  {
        filesize = ic->file_size;
        if (filesize > 0) {
            duration = (int64_t)((8 * AV_TIME_BASE * (double)filesize) / (double)ic->bit_rate);
            for(i = 0; i < ic->nb_streams; i++) {
                st = ic->streams[i];
                if (st->start_time == AV_NOPTS_VALUE ||
                    st->duration == AV_NOPTS_VALUE) {
                    st->start_time = 0;
                    st->duration = duration;
                }
            }
        }
    }
}

static void flush_packet_queue(AVFormatContext *s)
{
    AVPacketList *pktl;

    for(;;) {
        pktl = s->packet_buffer;
        if (!pktl) 
            break;
        s->packet_buffer = pktl->next;
563
        av_free_packet(&pktl->pkt);
564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602
        av_free(pktl);
    }
}

#define DURATION_MAX_READ_SIZE 250000

/* only usable for MPEG-PS streams */
static void av_estimate_timings_from_pts(AVFormatContext *ic)
{
    AVPacket pkt1, *pkt = &pkt1;
    AVStream *st;
    int read_size, i, ret;
    int64_t start_time, end_time, end_time1;
    int64_t filesize, offset, duration;
    
    /* we read the first packets to get the first PTS (not fully
       accurate, but it is enough now) */
    url_fseek(&ic->pb, 0, SEEK_SET);
    read_size = 0;
    for(;;) {
        if (read_size >= DURATION_MAX_READ_SIZE)
            break;
        /* if all info is available, we can stop */
        for(i = 0;i < ic->nb_streams; i++) {
            st = ic->streams[i];
            if (st->start_time == AV_NOPTS_VALUE)
                break;
        }
        if (i == ic->nb_streams)
            break;

        ret = av_read_packet(ic, pkt);
        if (ret != 0)
            break;
        read_size += pkt->size;
        st = ic->streams[pkt->stream_index];
        if (pkt->pts != AV_NOPTS_VALUE) {
            if (st->start_time == AV_NOPTS_VALUE)
                st->start_time = (int64_t)((double)pkt->pts * ic->pts_num * (double)AV_TIME_BASE / ic->pts_den);
603 604 605
        }
        av_free_packet(pkt);
    }
606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740

    /* we compute the minimum start_time and use it as default */
    start_time = MAXINT64;
    for(i = 0; i < ic->nb_streams; i++) {
        st = ic->streams[i];
        if (st->start_time != AV_NOPTS_VALUE &&
            st->start_time < start_time)
            start_time = st->start_time;
    }
    if (start_time != MAXINT64)
        ic->start_time = start_time;
    
    /* estimate the end time (duration) */
    /* XXX: may need to support wrapping */
    filesize = ic->file_size;
    offset = filesize - DURATION_MAX_READ_SIZE;
    if (offset < 0)
        offset = 0;

    /* flush packet queue */
    flush_packet_queue(ic);

    url_fseek(&ic->pb, offset, SEEK_SET);
    read_size = 0;
    for(;;) {
        if (read_size >= DURATION_MAX_READ_SIZE)
            break;
        /* if all info is available, we can stop */
        for(i = 0;i < ic->nb_streams; i++) {
            st = ic->streams[i];
            if (st->duration == AV_NOPTS_VALUE)
                break;
        }
        if (i == ic->nb_streams)
            break;
        
        ret = av_read_packet(ic, pkt);
        if (ret != 0)
            break;
        read_size += pkt->size;
        st = ic->streams[pkt->stream_index];
        if (pkt->pts != AV_NOPTS_VALUE) {
            end_time = (int64_t)((double)pkt->pts * ic->pts_num * (double)AV_TIME_BASE / ic->pts_den);
            duration = end_time - st->start_time;
            if (duration > 0) {
                if (st->duration == AV_NOPTS_VALUE ||
                    st->duration < duration)
                    st->duration = duration;
            }
        }
        av_free_packet(pkt);
    }
    
    /* estimate total duration */
    end_time = MININT64;
    for(i = 0;i < ic->nb_streams; i++) {
        st = ic->streams[i];
        if (st->duration != AV_NOPTS_VALUE) {
            end_time1 = st->start_time + st->duration;
            if (end_time1 > end_time)
                end_time = end_time1;
        }
    }
    
    /* update start_time (new stream may have been created, so we do
       it at the end */
    if (ic->start_time != AV_NOPTS_VALUE) {
        for(i = 0; i < ic->nb_streams; i++) {
            st = ic->streams[i];
            if (st->start_time == AV_NOPTS_VALUE)
                st->start_time = ic->start_time;
        }
    }

    if (end_time != MININT64) {
        /* put dummy values for duration if needed */
        for(i = 0;i < ic->nb_streams; i++) {
            st = ic->streams[i];
            if (st->duration == AV_NOPTS_VALUE && 
                st->start_time != AV_NOPTS_VALUE)
                st->duration = end_time - st->start_time;
        }
        ic->duration = end_time - ic->start_time;
    }

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

static void av_estimate_timings(AVFormatContext *ic)
{
    URLContext *h;
    int64_t file_size;

    /* get the file size, if possible */
    if (ic->iformat->flags & AVFMT_NOFILE) {
        file_size = 0;
    } else {
        h = url_fileno(&ic->pb);
        file_size = url_filesize(h);
        if (file_size < 0)
            file_size = 0;
    }
    ic->file_size = file_size;

    if (ic->iformat == &mpegps_demux) {
        /* get accurate estimate from the PTSes */
        av_estimate_timings_from_pts(ic);
    } else if (av_has_timings(ic)) {
        /* at least one components has timings - we use them for all
           the components */
        fill_all_stream_timings(ic);
    } else {
        /* less precise: use bit rate info */
        av_estimate_timings_from_bit_rate(ic);
    }
    av_update_stream_timings(ic);

#if 0
    {
        int i;
        AVStream *st;
        for(i = 0;i < ic->nb_streams; i++) {
            st = ic->streams[i];
        printf("%d: start_time: %0.3f duration: %0.3f\n", 
               i, (double)st->start_time / AV_TIME_BASE, 
               (double)st->duration / AV_TIME_BASE);
        }
        printf("stream: start_time: %0.3f duration: %0.3f bitrate=%d kb/s\n", 
               (double)ic->start_time / AV_TIME_BASE, 
               (double)ic->duration / AV_TIME_BASE,
               ic->bit_rate / 1000);
    }
#endif
}

741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777
/* state for codec information */
#define CSTATE_NOTFOUND    0
#define CSTATE_DECODING    1
#define CSTATE_FOUND       2

static int has_codec_parameters(AVCodecContext *enc)
{
    int val;
    switch(enc->codec_type) {
    case CODEC_TYPE_AUDIO:
        val = enc->sample_rate;
        break;
    case CODEC_TYPE_VIDEO:
        val = enc->width;
        break;
    default:
        val = 1;
        break;
    }
    return (val != 0);
}

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

    /* 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 788 789 790

    /* XXX: base it on stream bitrate when possible */
    if (ic->iformat == &mpegts_demux) {
        /* maximum number of bytes we accept to read to find all the streams
           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 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822

    /* set initial codec state */
    for(i=0;i<ic->nb_streams;i++) {
        st = ic->streams[i];
        if (has_codec_parameters(&st->codec))
            st->codec_info_state = CSTATE_FOUND;
        else
            st->codec_info_state = CSTATE_NOTFOUND;
        st->codec_info_nb_repeat_frames = 0;
        st->codec_info_nb_real_frames = 0;
    }

    count = 0;
    read_size = 0;
    ppktl = &ic->packet_buffer;
    for(;;) {
        /* check if one codec still needs to be handled */
        for(i=0;i<ic->nb_streams;i++) {
            st = ic->streams[i];
            if (st->codec_info_state != CSTATE_FOUND)
                break;
        }
        if (i == ic->nb_streams) {
            /* NOTE: if the format has no header, then we need to read
               some packets to get most of the streams, so we cannot
               stop here */
823
            if (!(ic->ctx_flags & AVFMTCTX_NOHEADER) ||
824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847
                read_size >= min_read_size) {
                /* if we found the info for all the codecs, we can stop */
                ret = count;
                break;
            }
        } else {
            /* we did not get all the codec info, but we read too much data */
            if (read_size >= max_read_size) {
                ret = count;
                break;
            }
        }

        pktl = av_mallocz(sizeof(AVPacketList));
        if (!pktl) {
            ret = AVERROR_NOMEM;
            break;
        }

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

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

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

871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914
                    ret = avcodec_open(&st->codec, codec);
                    if (ret >= 0)
                        st->codec_info_state = CSTATE_DECODING;
                }
            }
        }

        st = ic->streams[pkt->stream_index];
        if (st->codec_info_state == CSTATE_DECODING) {
            /* decode the data and update codec parameters */
            ptr = pkt->data;
            size = pkt->size;
            while (size > 0) {
                switch(st->codec.codec_type) {
                case CODEC_TYPE_VIDEO:
                    ret = avcodec_decode_video(&st->codec, &picture, 
                                               &got_picture, ptr, size);
                    break;
                case CODEC_TYPE_AUDIO:
                    ret = avcodec_decode_audio(&st->codec, samples, 
                                               &got_picture, ptr, size);
                    break;
                default:
                    ret = -1;
                    break;
                }
                if (ret < 0) {
                    /* if error, simply ignore because another packet
                       may be OK */
                    break;
                }
                if (got_picture) {
                    /* we got the parameters - now we can stop
                       examining this stream */
                    /* XXX: add a codec info so that we can decide if
                       the codec can repeat frames */
                    if (st->codec.codec_id == CODEC_ID_MPEG1VIDEO && 
                        ic->iformat != &mpegts_demux &&
                        st->codec.sub_id == 2) {
                        /* for mpeg2 video, we want to know the real
                           frame rate, so we decode 40 frames. In mpeg
                           TS case we do not do it because it would be
                           too long */
                        st->codec_info_nb_real_frames++;
915
                        st->codec_info_nb_repeat_frames += st->codec.coded_frame->repeat_pict;
916 917 918 919 920 921 922 923
#if 0
                        /* XXX: testing */
                        if ((st->codec_info_nb_real_frames % 24) == 23) {
                            st->codec_info_nb_repeat_frames += 2;
                        }
#endif
                        /* stop after 40 frames */
                        if (st->codec_info_nb_real_frames >= 40) {
924 925 926 927
                            av_reduce(
                                &st->r_frame_rate,
                                &st->r_frame_rate_base,
                                (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 931 932 933 934 935
                            goto close_codec;
                        }
                    } else {
                    close_codec:
                        st->codec_info_state = CSTATE_FOUND;
                        avcodec_close(&st->codec);
Fabrice Bellard's avatar
Fabrice Bellard committed
936
                        break;
937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956
                    }
                }
                ptr += ret;
                size -= ret;
            }
        }
        count++;
    }

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

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

964 965

    av_estimate_timings(ic);
966
    return ret;
Fabrice Bellard's avatar
Fabrice Bellard committed
967 968
}

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

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

1008 1009
/**
 * Add a new stream to a media file. Can only be called in the
1010 1011
 * read_header function. If the flag AVFMTCTX_NOHEADER is in the
 * 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 1018 1019 1020 1021 1022 1023 1024 1025 1026
 */
AVStream *av_new_stream(AVFormatContext *s, int id)
{
    AVStream *st;

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

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

/************************************************************/
/* output media file */
Fabrice Bellard's avatar
Fabrice Bellard committed
1042

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

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

Fabrice Bellard's avatar
Fabrice Bellard committed
1074 1075
    /* default pts settings is MPEG like */
    av_set_pts_info(s, 33, 1, 90000);
1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086
    ret = s->oformat->write_header(s);
    if (ret < 0)
        return ret;

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

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

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

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

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

/**
 * write the stream trailer to an output media file and and free the
 * file private data.
 *
 * @param s media file handle
 * @return 0 if OK. AVERROR_xxx if error.  */
int av_write_trailer(AVFormatContext *s)
{
    int ret;
    ret = s->oformat->write_trailer(s);
    av_freep(&s->priv_data);
    return ret;
Fabrice Bellard's avatar
Fabrice Bellard committed
1168 1169 1170 1171 1172 1173 1174 1175 1176
}

/* "user interface" functions */

void dump_format(AVFormatContext *ic,
                 int index, 
                 const char *url,
                 int is_output)
{
1177
    int i, flags;
Fabrice Bellard's avatar
Fabrice Bellard committed
1178 1179 1180 1181
    char buf[256];

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

typedef struct {
1226
    const char *abv;
Fabrice Bellard's avatar
Fabrice Bellard committed
1227
    int width, height;
1228 1229 1230 1231
    int frame_rate, frame_rate_base;
} AbvEntry;

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

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

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

1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307
int parse_frame_rate(int *frame_rate, int *frame_rate_base, const char *arg)
{
    int i;
    char* cp;
   
    /* First, we check our abbreviation table */
    for (i = 0; i < sizeof(frame_abvs)/sizeof(*frame_abvs); ++i)
         if (!strcmp(frame_abvs[i].abv, arg)) {
	     *frame_rate = frame_abvs[i].frame_rate;
	     *frame_rate_base = frame_abvs[i].frame_rate_base;
	     return 0;
	 }

    /* Then, we try to parse it as fraction */
    cp = strchr(arg, '/');
    if (cp) {
        char* cpp;
	*frame_rate = strtol(arg, &cpp, 10);
	if (cpp != arg || cpp == cp) 
	    *frame_rate_base = strtol(cp+1, &cpp, 10);
	else
	   *frame_rate = 0;
    } 
    else {
        /* Finally we give up and parse it as double */
        *frame_rate_base = DEFAULT_FRAME_RATE_BASE;
        *frame_rate = (int)(strtod(arg, 0) * (*frame_rate_base) + 0.5);
    }
    if (!*frame_rate || !*frame_rate_base)
        return -1;
    else
        return 0;
}

Fabrice Bellard's avatar
Fabrice Bellard committed
1308 1309 1310
/* Syntax:
 * - If not a duration:
 *  [{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
Fabrice Bellard's avatar
Fabrice Bellard committed
1312 1313 1314 1315 1316
 * Return the date in micro seconds since 1970 
 * - If duration:
 *  HH[:MM[:SS[.m...]]]
 *  S+[.m...]
 */
1317
int64_t parse_date(const char *datestr, int duration)
Fabrice Bellard's avatar
Fabrice Bellard committed
1318 1319
{
    const char *p;
1320
    int64_t t;
1321
    struct tm dt;
1322 1323 1324 1325 1326 1327 1328 1329 1330 1331
    int i;
    static const char *date_fmt[] = {
        "%Y-%m-%d",
        "%Y%m%d",
    };
    static const char *time_fmt[] = {
        "%H:%M:%S",
        "%H%M%S",
    };
    const char *q;
Fabrice Bellard's avatar
Fabrice Bellard committed
1332
    int is_utc, len;
1333 1334 1335
    char lastch;
    time_t now = time(0);

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

    memset(&dt, 0, sizeof(dt));
Fabrice Bellard's avatar
Fabrice Bellard committed
1344 1345

    p = datestr;
Fabrice Bellard's avatar
Fabrice Bellard committed
1346
    q = NULL;
Fabrice Bellard's avatar
Fabrice Bellard committed
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 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361
            if (q) {
                break;
            }
        }

        if (!q) {
            if (is_utc) {
                dt = *gmtime(&now);
            } else {
                dt = *localtime(&now);
            }
            dt.tm_hour = dt.tm_min = dt.tm_sec = 0;
Fabrice Bellard's avatar
Fabrice Bellard committed
1362
        } else {
1363
            p = q;
Fabrice Bellard's avatar
Fabrice Bellard committed
1364
        }
1365 1366 1367 1368

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

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

    /* Now we have all the fields that we can get */
    if (!q) {
        if (duration)
            return 0;
        else
1389
            return now * int64_t_C(1000000);
Fabrice Bellard's avatar
Fabrice Bellard committed
1390
    }
1391 1392

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

1403 1404 1405
    t *= 1000000;

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

1418
/* syntax: '?tag1=val1&tag2=val2...'. Little URL decoding is done. Return
Fabrice Bellard's avatar
Fabrice Bellard committed
1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439
   1 if found */
int find_info_tag(char *arg, int arg_size, const char *tag1, const char *info)
{
    const char *p;
    char tag[128], *q;

    p = info;
    if (*p == '?')
        p++;
    for(;;) {
        q = tag;
        while (*p != '\0' && *p != '=' && *p != '&') {
            if ((q - tag) < sizeof(tag) - 1)
                *q++ = *p;
            p++;
        }
        *q = '\0';
        q = arg;
        if (*p == '=') {
            p++;
            while (*p != '&' && *p != '\0') {
1440 1441 1442 1443 1444 1445
                if ((q - arg) < arg_size - 1) {
                    if (*p == '+')
                        *q++ = ' ';
                    else
                        *q++ = *p;
                }
Fabrice Bellard's avatar
Fabrice Bellard committed
1446 1447 1448 1449 1450 1451 1452 1453
                p++;
            }
            *q = '\0';
        }
        if (!strcmp(tag, tag1)) 
            return 1;
        if (*p != '&')
            break;
1454
        p++;
Fabrice Bellard's avatar
Fabrice Bellard committed
1455 1456 1457 1458
    }
    return 0;
}

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

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

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

1517 1518 1519 1520 1521 1522
/**
 *
 * Print on stdout a nice hexa dump of a buffer
 * @param buf buffer
 * @param size buffer size
 */
1523
void av_hex_dump(uint8_t *buf, int size)
1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548
{
    int len, i, j, c;

    for(i=0;i<size;i+=16) {
        len = size - i;
        if (len > 16)
            len = 16;
        printf("%08x ", i);
        for(j=0;j<16;j++) {
            if (j < len)
                printf(" %02x", buf[i+j]);
            else
                printf("   ");
        }
        printf(" ");
        for(j=0;j<len;j++) {
            c = buf[i+j];
            if (c < ' ' || c > '~')
                c = '.';
            printf("%c", c);
        }
        printf("\n");
    }
}

Fabrice Bellard's avatar
Fabrice Bellard committed
1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599
void url_split(char *proto, int proto_size,
               char *hostname, int hostname_size,
               int *port_ptr,
               char *path, int path_size,
               const char *url)
{
    const char *p;
    char *q;
    int port;

    port = -1;

    p = url;
    q = proto;
    while (*p != ':' && *p != '\0') {
        if ((q - proto) < proto_size - 1)
            *q++ = *p;
        p++;
    }
    if (proto_size > 0)
        *q = '\0';
    if (*p == '\0') {
        if (proto_size > 0)
            proto[0] = '\0';
        if (hostname_size > 0)
            hostname[0] = '\0';
        p = url;
    } else {
        p++;
        if (*p == '/')
            p++;
        if (*p == '/')
            p++;
        q = hostname;
        while (*p != ':' && *p != '/' && *p != '?' && *p != '\0') {
            if ((q - hostname) < hostname_size - 1)
                *q++ = *p;
            p++;
        }
        if (hostname_size > 0)
            *q = '\0';
        if (*p == ':') {
            p++;
            port = strtoul(p, (char **)&p, 10);
        }
    }
    if (port_ptr)
        *port_ptr = port;
    pstrcpy(path, path_size, p);
}

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

/* fraction handling */

/**
 * f = val + (num / den) + 0.5. 'num' is normalized so that it is such
 * as 0 <= num < den.
 *
 * @param f fractional number
 * @param val integer value
 * @param num must be >= 0
 * @param den must be >= 1 
 */
1627
void av_frac_init(AVFrac *f, int64_t val, int64_t num, int64_t den)
Fabrice Bellard's avatar
Fabrice Bellard committed
1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639
{
    num += (den >> 1);
    if (num >= den) {
        val += num / den;
        num = num % den;
    }
    f->val = val;
    f->num = num;
    f->den = den;
}

/* set f to (val + 0.5) */
1640
void av_frac_set(AVFrac *f, int64_t val)
Fabrice Bellard's avatar
Fabrice Bellard committed
1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651
{
    f->val = val;
    f->num = f->den >> 1;
}

/**
 * Fractionnal addition to f: f = f + (incr / f->den)
 *
 * @param f fractional number
 * @param incr increment, can be positive or negative
 */
1652
void av_frac_add(AVFrac *f, int64_t incr)
Fabrice Bellard's avatar
Fabrice Bellard committed
1653
{
1654
    int64_t num, den;
Fabrice Bellard's avatar
Fabrice Bellard committed
1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670

    num = f->num + incr;
    den = f->den;
    if (num < 0) {
        f->val += num / den;
        num = num % den;
        if (num < 0) {
            num += den;
            f->val--;
        }
    } else if (num >= den) {
        f->val += num / den;
        num = num % den;
    }
    f->num = num;
}
1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731

/**
 * register a new image format
 * @param img_fmt Image format descriptor
 */
void av_register_image_format(AVImageFormat *img_fmt)
{
    AVImageFormat **p;

    p = &first_image_format;
    while (*p != NULL) p = &(*p)->next;
    *p = img_fmt;
    img_fmt->next = NULL;
}

/* guess image format */
AVImageFormat *av_probe_image_format(AVProbeData *pd)
{
    AVImageFormat *fmt1, *fmt;
    int score, score_max;

    fmt = NULL;
    score_max = 0;
    for(fmt1 = first_image_format; fmt1 != NULL; fmt1 = fmt1->next) {
        if (fmt1->img_probe) {
            score = fmt1->img_probe(pd);
            if (score > score_max) {
                score_max = score;
                fmt = fmt1;
            }
        }
    }
    return fmt;
}

AVImageFormat *guess_image_format(const char *filename)
{
    AVImageFormat *fmt1;

    for(fmt1 = first_image_format; fmt1 != NULL; fmt1 = fmt1->next) {
        if (fmt1->extensions && match_ext(filename, fmt1->extensions))
            return fmt1;
    }
    return NULL;
}

/**
 * Read an image from a stream. 
 * @param gb byte stream containing the image
 * @param fmt image format, NULL if probing is required
 */
int av_read_image(ByteIOContext *pb, const char *filename,
                  AVImageFormat *fmt,
                  int (*alloc_cb)(void *, AVImageInfo *info), void *opaque)
{
    char buf[PROBE_BUF_SIZE];
    AVProbeData probe_data, *pd = &probe_data;
    offset_t pos;
    int ret;

    if (!fmt) {
1732
        pd->filename = filename;
1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755
        pd->buf = buf;
        pos = url_ftell(pb);
        pd->buf_size = get_buffer(pb, buf, PROBE_BUF_SIZE);
        url_fseek(pb, pos, SEEK_SET);
        fmt = av_probe_image_format(pd);
    }
    if (!fmt)
        return AVERROR_NOFMT;
    ret = fmt->img_read(pb, alloc_cb, opaque);
    return ret;
}

/**
 * Write an image to a stream.
 * @param pb byte stream for the image output
 * @param fmt image format
 * @param img image data and informations
 */
int av_write_image(ByteIOContext *pb, AVImageFormat *fmt, AVImageInfo *img)
{
    return fmt->img_write(pb, img);
}