Skip to content
Snippets Groups Projects
utils.c 46 KiB
Newer Older
  • Learn to ignore specific revisions
  • Fabrice Bellard's avatar
    Fabrice Bellard committed
    /*
     * Various utilities for ffmpeg system
    
     * Copyright (c) 2000, 2001, 2002 Fabrice Bellard
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
     *
    
     * 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
     *
    
     * This library is distributed in the hope that it will be useful,
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
     * but WITHOUT ANY WARRANTY; without even the implied warranty of
    
     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
     * Lesser General Public License for more details.
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
     *
    
     * 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
     */
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
    #include "avformat.h"
    
    AVInputFormat *first_iformat;
    AVOutputFormat *first_oformat;
    
    AVImageFormat *first_image_format;
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
    
    
    void av_register_input_format(AVInputFormat *format)
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
    {
    
        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
        while (*p != NULL) p = &(*p)->next;
        *p = format;
        format->next = NULL;
    }
    
    
    int match_ext(const char *filename, const char *extensions)
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
    {
        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;
    }
    
    
    AVOutputFormat *guess_format(const char *short_name, const char *filename, 
                                 const char *mime_type)
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
    {
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
        int score_max, score;
    
    
        /* specific test for image sequences */
    
        if (!short_name && filename && 
            filename_number_test(filename) >= 0 &&
            guess_image_format(filename)) {
    
            return guess_format("image", NULL, NULL);
        }
    
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
        /* find the proper file type */
        fmt_found = NULL;
        score_max = 0;
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
        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;
    }   
    
    
    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;
    }
    
    
    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
    /* memory handling */
    
    
    /**
     * Default packet destructor 
     */
    static void av_destruct_packet(AVPacket *pkt)
    {
        av_free(pkt->data);
        pkt->data = NULL; pkt->size = 0;
    }
    
    
    /**
     * 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
    int av_new_packet(AVPacket *pkt, int size)
    {
    
        void *data = av_malloc(size + FF_INPUT_BUFFER_PADDING_SIZE);
        if (!data)
    
        memset(data + size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
    
        av_init_packet(pkt);
        pkt->data = data; 
        pkt->size = size;
        pkt->destruct = av_destruct_packet;
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
        return 0;
    }
    
    /* fifo handling */
    
    int fifo_init(FifoBuffer *f, int size)
    {
    
        f->buffer = av_malloc(size);
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
        if (!f->buffer)
            return -1;
        f->end = f->buffer + size;
        f->wptr = f->rptr = f->buffer;
        return 0;
    }
    
    void fifo_free(FifoBuffer *f)
    {
    
        av_free(f->buffer);
    
    int fifo_size(FifoBuffer *f, uint8_t *rptr)
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
    {
        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) */
    
    int fifo_read(FifoBuffer *f, uint8_t *buf, int buf_size, uint8_t **rptr_ptr)
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
    {
    
        uint8_t *rptr = *rptr_ptr;
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
        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;
    }
    
    
    void fifo_write(FifoBuffer *f, uint8_t *buf, int size, uint8_t **wptr_ptr)
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
    {
        int len;
    
        uint8_t *wptr;
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
        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;
    }
    
    
    int filename_number_test(const char *filename)
    {
        char buf[1024];
        return get_frame_filename(buf, sizeof(buf), filename, 1);
    }
    
    /* guess file format */
    
    AVInputFormat *av_probe_input_format(AVProbeData *pd, int is_opened)
    
    {
        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;
    
            if (fmt1->read_probe) {
                score = fmt1->read_probe(pd);
            } else if (fmt1->extensions) {
    
                if (match_ext(pd->filename, fmt1->extensions)) {
                    score = 50;
                }
    
            if (score > score_max) {
                score_max = score;
                fmt = fmt1;
            }
        }
        return fmt;
    }
    
    /************************************************************/
    /* input media file */
    
    #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
    {
        AVFormatContext *ic = NULL;
    
        int err, must_open_file;
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
    
        ic = av_mallocz(sizeof(AVFormatContext));
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
            goto fail;
        }
    
        ic->duration = AV_NOPTS_VALUE;
        ic->start_time = AV_NOPTS_VALUE;
    
        pstrcpy(ic->filename, sizeof(ic->filename), filename);
        pd->filename = ic->filename;
        pd->buf = buf;
        pd->buf_size = 0;
    
        if (!fmt) {
            /* guess format if no file can be opened  */
    
            fmt = av_probe_input_format(pd, 0);
    
        /* do not open file if the format does not need it. XXX: specific
           hack needed to handle RTSP/TCP */
        must_open_file = 1;
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
        if ((fmt && (fmt->flags & AVFMT_NOFILE)) 
    #ifdef CONFIG_NETWORK
            || (fmt == &rtp_demux && !strcmp(filename, "null"))
    #endif
            ) {
    
            must_open_file = 0;
        }
    
        if (!fmt || must_open_file) {
    
            /* if no file needed do not try to open one */
    
            if (url_fopen(&ic->pb, filename, URL_RDONLY) < 0) {
                err = AVERROR_IO;
    
            if (buf_size > 0) {
                url_setbufsize(&ic->pb, buf_size);
            }
    
            if (!fmt) {
                /* read probe data */
                pd->buf_size = get_buffer(&ic->pb, buf, PROBE_BUF_SIZE);
                url_fseek(&ic->pb, 0, SEEK_SET);
            }
    
            fmt = av_probe_input_format(pd, 1);
    
        }
    
        /* if still no format found, error */
        if (!fmt) {
            err = AVERROR_NOFMT;
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
        }
    
        /* XXX: suppress this hack for redirectors */
    
        if (fmt == &redir_demux) {
            err = redir_open(ic_ptr, &ic->pb);
            url_fclose(&ic->pb);
            av_free(ic);
            return err;
        }
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
    
    
        /* check filename in case of an image number is expected */
        if (ic->iformat->flags & AVFMT_NEEDNUMBER) {
            if (filename_number_test(ic->filename) < 0) { 
                err = AVERROR_NUMEXPECTED;
                goto fail1;
            }
        }
        
    
        if (fmt->priv_data_size > 0) {
            ic->priv_data = av_mallocz(fmt->priv_data_size);
            if (!ic->priv_data) {
                err = AVERROR_NOMEM;
    
            }
        } else
            ic->priv_data = NULL;
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
        /* 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 fail1;
        *ic_ptr = ic;
        return 0;
     fail1:
    
        if (!fmt || must_open_file) {
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
     fail:
    
        av_free(ic);
    
    /**
     * Read a packet from a media file
     * @param s media file handle
     * @param pkt is filled 
     * @return 0 if OK. AVERROR_xxx if error.
     */
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
    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;
    
            av_free(pktl);
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
            return 0;
        } else {
    
    
    /* 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;
    
            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);
    
    
        /* 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
    }
    
    
    /* 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;
    
        AVFrame picture;
    
        AVPacketList *pktl=NULL, **ppktl;
        short samples[AVCODEC_MAX_AUDIO_FRAME_SIZE / 2];
    
        uint8_t *ptr;
    
        int min_read_size, max_read_size;
    
        /* typical mpeg ts rate is 40 Mbits. DVD rate is about 10
    
           Mbits. We read at most 0.2 second of file to find all streams */
    
    
        /* 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 */
    
    
        /* 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 */
                if (!(ic->iformat->flags & AVFMT_NOHEADER) ||
                    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
               (AVFMT_NOHEADER) */
            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 */
                if ((ic->iformat->flags & AVFMT_NOHEADER) &&
                    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) {
    
                        if(codec->capabilities & CODEC_CAP_TRUNCATED)
                            st->codec.flags |= CODEC_FLAG_TRUNCATED;
    
    
                        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++;
    
                            st->codec_info_nb_repeat_frames += st->codec.coded_frame->repeat_pict;
    
    #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) {
    
                                av_reduce(
                                    &st->r_frame_rate,
                                    &st->r_frame_rate_base,
                                    (int64_t)st->codec.frame_rate * st->codec_info_nb_real_frames,
    
                                    (st->codec_info_nb_real_frames + (st->codec_info_nb_repeat_frames >> 1)) * st->codec.frame_rate_base,
    
                                goto close_codec;
                            }
                        } else {
                        close_codec:
                            st->codec_info_state = CSTATE_FOUND;
                            avcodec_close(&st->codec);
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
                            break;
    
                        }
                    }
                    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) {
    
                if (!st->r_frame_rate){
                    st->r_frame_rate      = st->codec.frame_rate;
                    st->r_frame_rate_base = st->codec.frame_rate_base;
                }
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
        }
    
    /**
     * Close a media file (but not its codecs)
     *
     * @param s media file handle
     */
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
    void av_close_input_file(AVFormatContext *s)
    {
    
        int i, must_open_file;
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
    
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
        for(i=0;i<s->nb_streams;i++) {
    
            av_free(s->streams[i]);
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
        }
        if (s->packet_buffer) {
            AVPacketList *p, *p1;
            p = s->packet_buffer;
            while (p != NULL) {
                p1 = p->next;
                av_free_packet(&p->pkt);
    
                av_free(p);
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
                p = p1;
            }
            s->packet_buffer = NULL;
        }
    
        must_open_file = 1;
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
        if ((s->iformat->flags & AVFMT_NOFILE)
    #ifdef CONFIG_NETWORK
            || (s->iformat == &rtp_demux && !strcmp(s->filename, "null"))
    #endif
            ) {
    
            must_open_file = 0;
        }
        if (must_open_file) {
    
            url_fclose(&s->pb);
        }
    
        av_free(s);
    
    /**
     * Add a new stream to a media file. Can only be called in the
     * read_header function. If the flag AVFMT_NOHEADER is in the format
     * description, then new streams can be added in read_packet too.
     *
     *
     * @param s media file handle
     * @param id file format dependent stream id
     */
    AVStream *av_new_stream(AVFormatContext *s, int id)
    {
        AVStream *st;
    
        if (s->nb_streams >= MAX_STREAMS)
            return NULL;