• Main Page
  • Related Pages
  • Modules
  • Data Structures
  • Files

libavformat/utils.c

Go to the documentation of this file.
00001 /*
00002  * various utility functions for use within FFmpeg
00003  * Copyright (c) 2000, 2001, 2002 Fabrice Bellard
00004  *
00005  * This file is part of FFmpeg.
00006  *
00007  * FFmpeg is free software; you can redistribute it and/or
00008  * modify it under the terms of the GNU Lesser General Public
00009  * License as published by the Free Software Foundation; either
00010  * version 2.1 of the License, or (at your option) any later version.
00011  *
00012  * FFmpeg is distributed in the hope that it will be useful,
00013  * but WITHOUT ANY WARRANTY; without even the implied warranty of
00014  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00015  * Lesser General Public License for more details.
00016  *
00017  * You should have received a copy of the GNU Lesser General Public
00018  * License along with FFmpeg; if not, write to the Free Software
00019  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
00020  */
00021 #include "avformat.h"
00022 #include "internal.h"
00023 #include "libavcodec/internal.h"
00024 #include "libavutil/opt.h"
00025 #include "metadata.h"
00026 #include "id3v2.h"
00027 #include "libavutil/avstring.h"
00028 #include "riff.h"
00029 #include "audiointerleave.h"
00030 #include <sys/time.h>
00031 #include <time.h>
00032 #include <strings.h>
00033 #include <stdarg.h>
00034 #if CONFIG_NETWORK
00035 #include "network.h"
00036 #endif
00037 
00038 #undef NDEBUG
00039 #include <assert.h>
00040 
00046 unsigned avformat_version(void)
00047 {
00048     return LIBAVFORMAT_VERSION_INT;
00049 }
00050 
00051 const char *avformat_configuration(void)
00052 {
00053     return FFMPEG_CONFIGURATION;
00054 }
00055 
00056 const char *avformat_license(void)
00057 {
00058 #define LICENSE_PREFIX "libavformat license: "
00059     return LICENSE_PREFIX FFMPEG_LICENSE + sizeof(LICENSE_PREFIX) - 1;
00060 }
00061 
00062 /* fraction handling */
00063 
00074 static void av_frac_init(AVFrac *f, int64_t val, int64_t num, int64_t den)
00075 {
00076     num += (den >> 1);
00077     if (num >= den) {
00078         val += num / den;
00079         num = num % den;
00080     }
00081     f->val = val;
00082     f->num = num;
00083     f->den = den;
00084 }
00085 
00092 static void av_frac_add(AVFrac *f, int64_t incr)
00093 {
00094     int64_t num, den;
00095 
00096     num = f->num + incr;
00097     den = f->den;
00098     if (num < 0) {
00099         f->val += num / den;
00100         num = num % den;
00101         if (num < 0) {
00102             num += den;
00103             f->val--;
00104         }
00105     } else if (num >= den) {
00106         f->val += num / den;
00107         num = num % den;
00108     }
00109     f->num = num;
00110 }
00111 
00113 #if !FF_API_FIRST_FORMAT
00114 static
00115 #endif
00116 AVInputFormat *first_iformat = NULL;
00118 #if !FF_API_FIRST_FORMAT
00119 static
00120 #endif
00121 AVOutputFormat *first_oformat = NULL;
00122 
00123 AVInputFormat  *av_iformat_next(AVInputFormat  *f)
00124 {
00125     if(f) return f->next;
00126     else  return first_iformat;
00127 }
00128 
00129 AVOutputFormat *av_oformat_next(AVOutputFormat *f)
00130 {
00131     if(f) return f->next;
00132     else  return first_oformat;
00133 }
00134 
00135 void av_register_input_format(AVInputFormat *format)
00136 {
00137     AVInputFormat **p;
00138     p = &first_iformat;
00139     while (*p != NULL) p = &(*p)->next;
00140     *p = format;
00141     format->next = NULL;
00142 }
00143 
00144 void av_register_output_format(AVOutputFormat *format)
00145 {
00146     AVOutputFormat **p;
00147     p = &first_oformat;
00148     while (*p != NULL) p = &(*p)->next;
00149     *p = format;
00150     format->next = NULL;
00151 }
00152 
00153 int av_match_ext(const char *filename, const char *extensions)
00154 {
00155     const char *ext, *p;
00156     char ext1[32], *q;
00157 
00158     if(!filename)
00159         return 0;
00160 
00161     ext = strrchr(filename, '.');
00162     if (ext) {
00163         ext++;
00164         p = extensions;
00165         for(;;) {
00166             q = ext1;
00167             while (*p != '\0' && *p != ',' && q-ext1<sizeof(ext1)-1)
00168                 *q++ = *p++;
00169             *q = '\0';
00170             if (!strcasecmp(ext1, ext))
00171                 return 1;
00172             if (*p == '\0')
00173                 break;
00174             p++;
00175         }
00176     }
00177     return 0;
00178 }
00179 
00180 static int match_format(const char *name, const char *names)
00181 {
00182     const char *p;
00183     int len, namelen;
00184 
00185     if (!name || !names)
00186         return 0;
00187 
00188     namelen = strlen(name);
00189     while ((p = strchr(names, ','))) {
00190         len = FFMAX(p - names, namelen);
00191         if (!strncasecmp(name, names, len))
00192             return 1;
00193         names = p+1;
00194     }
00195     return !strcasecmp(name, names);
00196 }
00197 
00198 #if FF_API_GUESS_FORMAT
00199 AVOutputFormat *guess_format(const char *short_name, const char *filename,
00200                              const char *mime_type)
00201 {
00202     return av_guess_format(short_name, filename, mime_type);
00203 }
00204 #endif
00205 
00206 AVOutputFormat *av_guess_format(const char *short_name, const char *filename,
00207                                 const char *mime_type)
00208 {
00209     AVOutputFormat *fmt = NULL, *fmt_found;
00210     int score_max, score;
00211 
00212     /* specific test for image sequences */
00213 #if CONFIG_IMAGE2_MUXER
00214     if (!short_name && filename &&
00215         av_filename_number_test(filename) &&
00216         av_guess_image2_codec(filename) != CODEC_ID_NONE) {
00217         return av_guess_format("image2", NULL, NULL);
00218     }
00219 #endif
00220     /* Find the proper file type. */
00221     fmt_found = NULL;
00222     score_max = 0;
00223     while ((fmt = av_oformat_next(fmt))) {
00224         score = 0;
00225         if (fmt->name && short_name && !strcmp(fmt->name, short_name))
00226             score += 100;
00227         if (fmt->mime_type && mime_type && !strcmp(fmt->mime_type, mime_type))
00228             score += 10;
00229         if (filename && fmt->extensions &&
00230             av_match_ext(filename, fmt->extensions)) {
00231             score += 5;
00232         }
00233         if (score > score_max) {
00234             score_max = score;
00235             fmt_found = fmt;
00236         }
00237     }
00238     return fmt_found;
00239 }
00240 
00241 #if FF_API_GUESS_FORMAT
00242 AVOutputFormat *guess_stream_format(const char *short_name, const char *filename,
00243                              const char *mime_type)
00244 {
00245     AVOutputFormat *fmt = av_guess_format(short_name, filename, mime_type);
00246 
00247     if (fmt) {
00248         AVOutputFormat *stream_fmt;
00249         char stream_format_name[64];
00250 
00251         snprintf(stream_format_name, sizeof(stream_format_name), "%s_stream", fmt->name);
00252         stream_fmt = av_guess_format(stream_format_name, NULL, NULL);
00253 
00254         if (stream_fmt)
00255             fmt = stream_fmt;
00256     }
00257 
00258     return fmt;
00259 }
00260 #endif
00261 
00262 enum CodecID av_guess_codec(AVOutputFormat *fmt, const char *short_name,
00263                             const char *filename, const char *mime_type, enum AVMediaType type){
00264     if(type == AVMEDIA_TYPE_VIDEO){
00265         enum CodecID codec_id= CODEC_ID_NONE;
00266 
00267 #if CONFIG_IMAGE2_MUXER
00268         if(!strcmp(fmt->name, "image2") || !strcmp(fmt->name, "image2pipe")){
00269             codec_id= av_guess_image2_codec(filename);
00270         }
00271 #endif
00272         if(codec_id == CODEC_ID_NONE)
00273             codec_id= fmt->video_codec;
00274         return codec_id;
00275     }else if(type == AVMEDIA_TYPE_AUDIO)
00276         return fmt->audio_codec;
00277     else if (type == AVMEDIA_TYPE_SUBTITLE)
00278         return fmt->subtitle_codec;
00279     else
00280         return CODEC_ID_NONE;
00281 }
00282 
00283 AVInputFormat *av_find_input_format(const char *short_name)
00284 {
00285     AVInputFormat *fmt = NULL;
00286     while ((fmt = av_iformat_next(fmt))) {
00287         if (match_format(short_name, fmt->name))
00288             return fmt;
00289     }
00290     return NULL;
00291 }
00292 
00293 #if FF_API_SYMVER && CONFIG_SHARED && HAVE_SYMVER
00294 FF_SYMVER(void, av_destruct_packet_nofree, (AVPacket *pkt), "LIBAVFORMAT_52")
00295 {
00296     av_destruct_packet_nofree(pkt);
00297 }
00298 
00299 FF_SYMVER(void, av_destruct_packet, (AVPacket *pkt), "LIBAVFORMAT_52")
00300 {
00301     av_destruct_packet(pkt);
00302 }
00303 
00304 FF_SYMVER(int, av_new_packet, (AVPacket *pkt, int size), "LIBAVFORMAT_52")
00305 {
00306     return av_new_packet(pkt, size);
00307 }
00308 
00309 FF_SYMVER(int, av_dup_packet, (AVPacket *pkt), "LIBAVFORMAT_52")
00310 {
00311     return av_dup_packet(pkt);
00312 }
00313 
00314 FF_SYMVER(void, av_free_packet, (AVPacket *pkt), "LIBAVFORMAT_52")
00315 {
00316     av_free_packet(pkt);
00317 }
00318 
00319 FF_SYMVER(void, av_init_packet, (AVPacket *pkt), "LIBAVFORMAT_52")
00320 {
00321     av_log(NULL, AV_LOG_WARNING, "Diverting av_*_packet function calls to libavcodec. Recompile to improve performance\n");
00322     av_init_packet(pkt);
00323 }
00324 #endif
00325 
00326 int av_get_packet(ByteIOContext *s, AVPacket *pkt, int size)
00327 {
00328     int ret= av_new_packet(pkt, size);
00329 
00330     if(ret<0)
00331         return ret;
00332 
00333     pkt->pos= url_ftell(s);
00334 
00335     ret= get_buffer(s, pkt->data, size);
00336     if(ret<=0)
00337         av_free_packet(pkt);
00338     else
00339         av_shrink_packet(pkt, ret);
00340 
00341     return ret;
00342 }
00343 
00344 int av_append_packet(ByteIOContext *s, AVPacket *pkt, int size)
00345 {
00346     int ret;
00347     int old_size;
00348     if (!pkt->size)
00349         return av_get_packet(s, pkt, size);
00350     old_size = pkt->size;
00351     ret = av_grow_packet(pkt, size);
00352     if (ret < 0)
00353         return ret;
00354     ret = get_buffer(s, pkt->data + old_size, size);
00355     av_shrink_packet(pkt, old_size + FFMAX(ret, 0));
00356     return ret;
00357 }
00358 
00359 
00360 int av_filename_number_test(const char *filename)
00361 {
00362     char buf[1024];
00363     return filename && (av_get_frame_filename(buf, sizeof(buf), filename, 1)>=0);
00364 }
00365 
00366 AVInputFormat *av_probe_input_format2(AVProbeData *pd, int is_opened, int *score_max)
00367 {
00368     AVProbeData lpd = *pd;
00369     AVInputFormat *fmt1 = NULL, *fmt;
00370     int score;
00371 
00372     if (lpd.buf_size > 10 && ff_id3v2_match(lpd.buf, ID3v2_DEFAULT_MAGIC)) {
00373         int id3len = ff_id3v2_tag_len(lpd.buf);
00374         if (lpd.buf_size > id3len + 16) {
00375             lpd.buf += id3len;
00376             lpd.buf_size -= id3len;
00377         }
00378     }
00379 
00380     fmt = NULL;
00381     while ((fmt1 = av_iformat_next(fmt1))) {
00382         if (!is_opened == !(fmt1->flags & AVFMT_NOFILE))
00383             continue;
00384         score = 0;
00385         if (fmt1->read_probe) {
00386             score = fmt1->read_probe(&lpd);
00387         } else if (fmt1->extensions) {
00388             if (av_match_ext(lpd.filename, fmt1->extensions)) {
00389                 score = 50;
00390             }
00391         }
00392         if (score > *score_max) {
00393             *score_max = score;
00394             fmt = fmt1;
00395         }else if (score == *score_max)
00396             fmt = NULL;
00397     }
00398     return fmt;
00399 }
00400 
00401 AVInputFormat *av_probe_input_format(AVProbeData *pd, int is_opened){
00402     int score=0;
00403     return av_probe_input_format2(pd, is_opened, &score);
00404 }
00405 
00406 static int set_codec_from_probe_data(AVFormatContext *s, AVStream *st, AVProbeData *pd, int score)
00407 {
00408     static const struct {
00409         const char *name; enum CodecID id; enum AVMediaType type;
00410     } fmt_id_type[] = {
00411         { "aac"      , CODEC_ID_AAC       , AVMEDIA_TYPE_AUDIO },
00412         { "ac3"      , CODEC_ID_AC3       , AVMEDIA_TYPE_AUDIO },
00413         { "dts"      , CODEC_ID_DTS       , AVMEDIA_TYPE_AUDIO },
00414         { "eac3"     , CODEC_ID_EAC3      , AVMEDIA_TYPE_AUDIO },
00415         { "h264"     , CODEC_ID_H264      , AVMEDIA_TYPE_VIDEO },
00416         { "m4v"      , CODEC_ID_MPEG4     , AVMEDIA_TYPE_VIDEO },
00417         { "mp3"      , CODEC_ID_MP3       , AVMEDIA_TYPE_AUDIO },
00418         { "mpegvideo", CODEC_ID_MPEG2VIDEO, AVMEDIA_TYPE_VIDEO },
00419         { 0 }
00420     };
00421     AVInputFormat *fmt = av_probe_input_format2(pd, 1, &score);
00422 
00423     if (fmt) {
00424         int i;
00425         av_log(s, AV_LOG_DEBUG, "Probe with size=%d, packets=%d detected %s with score=%d\n",
00426                pd->buf_size, MAX_PROBE_PACKETS - st->probe_packets, fmt->name, score);
00427         for (i = 0; fmt_id_type[i].name; i++) {
00428             if (!strcmp(fmt->name, fmt_id_type[i].name)) {
00429                 st->codec->codec_id   = fmt_id_type[i].id;
00430                 st->codec->codec_type = fmt_id_type[i].type;
00431                 break;
00432             }
00433         }
00434     }
00435     return !!fmt;
00436 }
00437 
00438 /************************************************************/
00439 /* input media file */
00440 
00444 int av_open_input_stream(AVFormatContext **ic_ptr,
00445                          ByteIOContext *pb, const char *filename,
00446                          AVInputFormat *fmt, AVFormatParameters *ap)
00447 {
00448     int err;
00449     AVFormatContext *ic;
00450     AVFormatParameters default_ap;
00451 
00452     if(!ap){
00453         ap=&default_ap;
00454         memset(ap, 0, sizeof(default_ap));
00455     }
00456 
00457     if(!ap->prealloced_context)
00458         ic = avformat_alloc_context();
00459     else
00460         ic = *ic_ptr;
00461     if (!ic) {
00462         err = AVERROR(ENOMEM);
00463         goto fail;
00464     }
00465     ic->iformat = fmt;
00466     ic->pb = pb;
00467     ic->duration = AV_NOPTS_VALUE;
00468     ic->start_time = AV_NOPTS_VALUE;
00469     av_strlcpy(ic->filename, filename, sizeof(ic->filename));
00470 
00471     /* allocate private data */
00472     if (fmt->priv_data_size > 0) {
00473         ic->priv_data = av_mallocz(fmt->priv_data_size);
00474         if (!ic->priv_data) {
00475             err = AVERROR(ENOMEM);
00476             goto fail;
00477         }
00478     } else {
00479         ic->priv_data = NULL;
00480     }
00481 
00482     // e.g. AVFMT_NOFILE formats will not have a ByteIOContext
00483     if (ic->pb)
00484         ff_id3v2_read(ic, ID3v2_DEFAULT_MAGIC);
00485 
00486     if (ic->iformat->read_header) {
00487         err = ic->iformat->read_header(ic, ap);
00488         if (err < 0)
00489             goto fail;
00490     }
00491 
00492     if (pb && !ic->data_offset)
00493         ic->data_offset = url_ftell(ic->pb);
00494 
00495 #if FF_API_OLD_METADATA
00496     ff_metadata_demux_compat(ic);
00497 #endif
00498 
00499     ic->raw_packet_buffer_remaining_size = RAW_PACKET_BUFFER_SIZE;
00500 
00501     *ic_ptr = ic;
00502     return 0;
00503  fail:
00504     if (ic) {
00505         int i;
00506         av_freep(&ic->priv_data);
00507         for(i=0;i<ic->nb_streams;i++) {
00508             AVStream *st = ic->streams[i];
00509             if (st) {
00510                 av_free(st->priv_data);
00511                 av_free(st->codec->extradata);
00512                 av_free(st->codec);
00513                 av_free(st->info);
00514             }
00515             av_free(st);
00516         }
00517     }
00518     av_free(ic);
00519     *ic_ptr = NULL;
00520     return err;
00521 }
00522 
00524 #define PROBE_BUF_MIN 2048
00525 #define PROBE_BUF_MAX (1<<20)
00526 
00527 int ff_probe_input_buffer(ByteIOContext **pb, AVInputFormat **fmt,
00528                           const char *filename, void *logctx,
00529                           unsigned int offset, unsigned int max_probe_size)
00530 {
00531     AVProbeData pd = { filename ? filename : "", NULL, -offset };
00532     unsigned char *buf = NULL;
00533     int ret = 0, probe_size;
00534 
00535     if (!max_probe_size) {
00536         max_probe_size = PROBE_BUF_MAX;
00537     } else if (max_probe_size > PROBE_BUF_MAX) {
00538         max_probe_size = PROBE_BUF_MAX;
00539     } else if (max_probe_size < PROBE_BUF_MIN) {
00540         return AVERROR(EINVAL);
00541     }
00542 
00543     if (offset >= max_probe_size) {
00544         return AVERROR(EINVAL);
00545     }
00546 
00547     for(probe_size= PROBE_BUF_MIN; probe_size<=max_probe_size && !*fmt && ret >= 0;
00548         probe_size = FFMIN(probe_size<<1, FFMAX(max_probe_size, probe_size+1))) {
00549         int ret, score = probe_size < max_probe_size ? AVPROBE_SCORE_MAX/4 : 0;
00550         int buf_offset = (probe_size == PROBE_BUF_MIN) ? 0 : probe_size>>1;
00551 
00552         if (probe_size < offset) {
00553             continue;
00554         }
00555 
00556         /* read probe data */
00557         buf = av_realloc(buf, probe_size + AVPROBE_PADDING_SIZE);
00558         if ((ret = get_buffer(*pb, buf + buf_offset, probe_size - buf_offset)) < 0) {
00559             /* fail if error was not end of file, otherwise, lower score */
00560             if (ret != AVERROR_EOF) {
00561                 av_free(buf);
00562                 return ret;
00563             }
00564             score = 0;
00565             ret = 0;            /* error was end of file, nothing read */
00566         }
00567         pd.buf_size += ret;
00568         pd.buf = &buf[offset];
00569 
00570         memset(pd.buf + pd.buf_size, 0, AVPROBE_PADDING_SIZE);
00571 
00572         /* guess file format */
00573         *fmt = av_probe_input_format2(&pd, 1, &score);
00574         if(*fmt){
00575             if(score <= AVPROBE_SCORE_MAX/4){ //this can only be true in the last iteration
00576                 av_log(logctx, AV_LOG_WARNING, "Format detected only with low score of %d, misdetection possible!\n", score);
00577             }else
00578                 av_log(logctx, AV_LOG_DEBUG, "Probed with size=%d and score=%d\n", probe_size, score);
00579         }
00580     }
00581 
00582     if (!*fmt) {
00583         av_free(buf);
00584         return AVERROR_INVALIDDATA;
00585     }
00586 
00587     /* rewind. reuse probe buffer to avoid seeking */
00588     if ((ret = ff_rewind_with_probe_data(*pb, buf, pd.buf_size)) < 0)
00589         av_free(buf);
00590 
00591     return ret;
00592 }
00593 
00594 int av_open_input_file(AVFormatContext **ic_ptr, const char *filename,
00595                        AVInputFormat *fmt,
00596                        int buf_size,
00597                        AVFormatParameters *ap)
00598 {
00599     int err;
00600     AVProbeData probe_data, *pd = &probe_data;
00601     ByteIOContext *pb = NULL;
00602     void *logctx= ap && ap->prealloced_context ? *ic_ptr : NULL;
00603 
00604     pd->filename = "";
00605     if (filename)
00606         pd->filename = filename;
00607     pd->buf = NULL;
00608     pd->buf_size = 0;
00609 
00610     if (!fmt) {
00611         /* guess format if no file can be opened */
00612         fmt = av_probe_input_format(pd, 0);
00613     }
00614 
00615     /* Do not open file if the format does not need it. XXX: specific
00616        hack needed to handle RTSP/TCP */
00617     if (!fmt || !(fmt->flags & AVFMT_NOFILE)) {
00618         /* if no file needed do not try to open one */
00619         if ((err=url_fopen(&pb, filename, URL_RDONLY)) < 0) {
00620             goto fail;
00621         }
00622         if (buf_size > 0) {
00623             url_setbufsize(pb, buf_size);
00624         }
00625         if (!fmt && (err = ff_probe_input_buffer(&pb, &fmt, filename, logctx, 0, logctx ? (*ic_ptr)->probesize : 0)) < 0) {
00626             goto fail;
00627         }
00628     }
00629 
00630     /* if still no format found, error */
00631     if (!fmt) {
00632         err = AVERROR_INVALIDDATA;
00633         goto fail;
00634     }
00635 
00636     /* check filename in case an image number is expected */
00637     if (fmt->flags & AVFMT_NEEDNUMBER) {
00638         if (!av_filename_number_test(filename)) {
00639             err = AVERROR_NUMEXPECTED;
00640             goto fail;
00641         }
00642     }
00643     err = av_open_input_stream(ic_ptr, pb, filename, fmt, ap);
00644     if (err)
00645         goto fail;
00646     return 0;
00647  fail:
00648     av_freep(&pd->buf);
00649     if (pb)
00650         url_fclose(pb);
00651     if (ap && ap->prealloced_context)
00652         av_free(*ic_ptr);
00653     *ic_ptr = NULL;
00654     return err;
00655 
00656 }
00657 
00658 /*******************************************************/
00659 
00660 static AVPacket *add_to_pktbuf(AVPacketList **packet_buffer, AVPacket *pkt,
00661                                AVPacketList **plast_pktl){
00662     AVPacketList *pktl = av_mallocz(sizeof(AVPacketList));
00663     if (!pktl)
00664         return NULL;
00665 
00666     if (*packet_buffer)
00667         (*plast_pktl)->next = pktl;
00668     else
00669         *packet_buffer = pktl;
00670 
00671     /* add the packet in the buffered packet list */
00672     *plast_pktl = pktl;
00673     pktl->pkt= *pkt;
00674     return &pktl->pkt;
00675 }
00676 
00677 int av_read_packet(AVFormatContext *s, AVPacket *pkt)
00678 {
00679     int ret, i;
00680     AVStream *st;
00681 
00682     for(;;){
00683         AVPacketList *pktl = s->raw_packet_buffer;
00684 
00685         if (pktl) {
00686             *pkt = pktl->pkt;
00687             if(s->streams[pkt->stream_index]->codec->codec_id != CODEC_ID_PROBE ||
00688                !s->streams[pkt->stream_index]->probe_packets ||
00689                s->raw_packet_buffer_remaining_size < pkt->size){
00690                 AVProbeData *pd = &s->streams[pkt->stream_index]->probe_data;
00691                 av_freep(&pd->buf);
00692                 pd->buf_size = 0;
00693                 s->raw_packet_buffer = pktl->next;
00694                 s->raw_packet_buffer_remaining_size += pkt->size;
00695                 av_free(pktl);
00696                 return 0;
00697             }
00698         }
00699 
00700         av_init_packet(pkt);
00701         ret= s->iformat->read_packet(s, pkt);
00702         if (ret < 0) {
00703             if (!pktl || ret == AVERROR(EAGAIN))
00704                 return ret;
00705             for (i = 0; i < s->nb_streams; i++)
00706                 s->streams[i]->probe_packets = 0;
00707             continue;
00708         }
00709         st= s->streams[pkt->stream_index];
00710 
00711         switch(st->codec->codec_type){
00712         case AVMEDIA_TYPE_VIDEO:
00713             if(s->video_codec_id)   st->codec->codec_id= s->video_codec_id;
00714             break;
00715         case AVMEDIA_TYPE_AUDIO:
00716             if(s->audio_codec_id)   st->codec->codec_id= s->audio_codec_id;
00717             break;
00718         case AVMEDIA_TYPE_SUBTITLE:
00719             if(s->subtitle_codec_id)st->codec->codec_id= s->subtitle_codec_id;
00720             break;
00721         }
00722 
00723         if(!pktl && (st->codec->codec_id != CODEC_ID_PROBE ||
00724                      !st->probe_packets))
00725             return ret;
00726 
00727         add_to_pktbuf(&s->raw_packet_buffer, pkt, &s->raw_packet_buffer_end);
00728         s->raw_packet_buffer_remaining_size -= pkt->size;
00729 
00730         if(st->codec->codec_id == CODEC_ID_PROBE){
00731             AVProbeData *pd = &st->probe_data;
00732             av_log(s, AV_LOG_DEBUG, "probing stream %d\n", st->index);
00733             --st->probe_packets;
00734 
00735             pd->buf = av_realloc(pd->buf, pd->buf_size+pkt->size+AVPROBE_PADDING_SIZE);
00736             memcpy(pd->buf+pd->buf_size, pkt->data, pkt->size);
00737             pd->buf_size += pkt->size;
00738             memset(pd->buf+pd->buf_size, 0, AVPROBE_PADDING_SIZE);
00739 
00740             if(av_log2(pd->buf_size) != av_log2(pd->buf_size - pkt->size)){
00741                 //FIXME we dont reduce score to 0 for the case of running out of buffer space in bytes
00742                 set_codec_from_probe_data(s, st, pd, st->probe_packets > 0 ? AVPROBE_SCORE_MAX/4 : 0);
00743                 if(st->codec->codec_id != CODEC_ID_PROBE){
00744                     pd->buf_size=0;
00745                     av_freep(&pd->buf);
00746                     av_log(s, AV_LOG_DEBUG, "probed stream %d\n", st->index);
00747                 }
00748             }
00749         }
00750     }
00751 }
00752 
00753 /**********************************************************/
00754 
00758 static int get_audio_frame_size(AVCodecContext *enc, int size)
00759 {
00760     int frame_size;
00761 
00762     if(enc->codec_id == CODEC_ID_VORBIS)
00763         return -1;
00764 
00765     if (enc->frame_size <= 1) {
00766         int bits_per_sample = av_get_bits_per_sample(enc->codec_id);
00767 
00768         if (bits_per_sample) {
00769             if (enc->channels == 0)
00770                 return -1;
00771             frame_size = (size << 3) / (bits_per_sample * enc->channels);
00772         } else {
00773             /* used for example by ADPCM codecs */
00774             if (enc->bit_rate == 0)
00775                 return -1;
00776             frame_size = ((int64_t)size * 8 * enc->sample_rate) / enc->bit_rate;
00777         }
00778     } else {
00779         frame_size = enc->frame_size;
00780     }
00781     return frame_size;
00782 }
00783 
00784 
00788 static void compute_frame_duration(int *pnum, int *pden, AVStream *st,
00789                                    AVCodecParserContext *pc, AVPacket *pkt)
00790 {
00791     int frame_size;
00792 
00793     *pnum = 0;
00794     *pden = 0;
00795     switch(st->codec->codec_type) {
00796     case AVMEDIA_TYPE_VIDEO:
00797         if(st->time_base.num*1000LL > st->time_base.den){
00798             *pnum = st->time_base.num;
00799             *pden = st->time_base.den;
00800         }else if(st->codec->time_base.num*1000LL > st->codec->time_base.den){
00801             *pnum = st->codec->time_base.num;
00802             *pden = st->codec->time_base.den;
00803             if (pc && pc->repeat_pict) {
00804                 *pnum = (*pnum) * (1 + pc->repeat_pict);
00805             }
00806             //If this codec can be interlaced or progressive then we need a parser to compute duration of a packet
00807             //Thus if we have no parser in such case leave duration undefined.
00808             if(st->codec->ticks_per_frame>1 && !pc){
00809                 *pnum = *pden = 0;
00810             }
00811         }
00812         break;
00813     case AVMEDIA_TYPE_AUDIO:
00814         frame_size = get_audio_frame_size(st->codec, pkt->size);
00815         if (frame_size <= 0 || st->codec->sample_rate <= 0)
00816             break;
00817         *pnum = frame_size;
00818         *pden = st->codec->sample_rate;
00819         break;
00820     default:
00821         break;
00822     }
00823 }
00824 
00825 static int is_intra_only(AVCodecContext *enc){
00826     if(enc->codec_type == AVMEDIA_TYPE_AUDIO){
00827         return 1;
00828     }else if(enc->codec_type == AVMEDIA_TYPE_VIDEO){
00829         switch(enc->codec_id){
00830         case CODEC_ID_MJPEG:
00831         case CODEC_ID_MJPEGB:
00832         case CODEC_ID_LJPEG:
00833         case CODEC_ID_RAWVIDEO:
00834         case CODEC_ID_DVVIDEO:
00835         case CODEC_ID_HUFFYUV:
00836         case CODEC_ID_FFVHUFF:
00837         case CODEC_ID_ASV1:
00838         case CODEC_ID_ASV2:
00839         case CODEC_ID_VCR1:
00840         case CODEC_ID_DNXHD:
00841         case CODEC_ID_JPEG2000:
00842             return 1;
00843         default: break;
00844         }
00845     }
00846     return 0;
00847 }
00848 
00849 static void update_initial_timestamps(AVFormatContext *s, int stream_index,
00850                                       int64_t dts, int64_t pts)
00851 {
00852     AVStream *st= s->streams[stream_index];
00853     AVPacketList *pktl= s->packet_buffer;
00854 
00855     if(st->first_dts != AV_NOPTS_VALUE || dts == AV_NOPTS_VALUE || st->cur_dts == AV_NOPTS_VALUE)
00856         return;
00857 
00858     st->first_dts= dts - st->cur_dts;
00859     st->cur_dts= dts;
00860 
00861     for(; pktl; pktl= pktl->next){
00862         if(pktl->pkt.stream_index != stream_index)
00863             continue;
00864         //FIXME think more about this check
00865         if(pktl->pkt.pts != AV_NOPTS_VALUE && pktl->pkt.pts == pktl->pkt.dts)
00866             pktl->pkt.pts += st->first_dts;
00867 
00868         if(pktl->pkt.dts != AV_NOPTS_VALUE)
00869             pktl->pkt.dts += st->first_dts;
00870 
00871         if(st->start_time == AV_NOPTS_VALUE && pktl->pkt.pts != AV_NOPTS_VALUE)
00872             st->start_time= pktl->pkt.pts;
00873     }
00874     if (st->start_time == AV_NOPTS_VALUE)
00875         st->start_time = pts;
00876 }
00877 
00878 static void update_initial_durations(AVFormatContext *s, AVStream *st, AVPacket *pkt)
00879 {
00880     AVPacketList *pktl= s->packet_buffer;
00881     int64_t cur_dts= 0;
00882 
00883     if(st->first_dts != AV_NOPTS_VALUE){
00884         cur_dts= st->first_dts;
00885         for(; pktl; pktl= pktl->next){
00886             if(pktl->pkt.stream_index == pkt->stream_index){
00887                 if(pktl->pkt.pts != pktl->pkt.dts || pktl->pkt.dts != AV_NOPTS_VALUE || pktl->pkt.duration)
00888                     break;
00889                 cur_dts -= pkt->duration;
00890             }
00891         }
00892         pktl= s->packet_buffer;
00893         st->first_dts = cur_dts;
00894     }else if(st->cur_dts)
00895         return;
00896 
00897     for(; pktl; pktl= pktl->next){
00898         if(pktl->pkt.stream_index != pkt->stream_index)
00899             continue;
00900         if(pktl->pkt.pts == pktl->pkt.dts && pktl->pkt.dts == AV_NOPTS_VALUE
00901            && !pktl->pkt.duration){
00902             pktl->pkt.dts= cur_dts;
00903             if(!st->codec->has_b_frames)
00904                 pktl->pkt.pts= cur_dts;
00905             cur_dts += pkt->duration;
00906             pktl->pkt.duration= pkt->duration;
00907         }else
00908             break;
00909     }
00910     if(st->first_dts == AV_NOPTS_VALUE)
00911         st->cur_dts= cur_dts;
00912 }
00913 
00914 static void compute_pkt_fields(AVFormatContext *s, AVStream *st,
00915                                AVCodecParserContext *pc, AVPacket *pkt)
00916 {
00917     int num, den, presentation_delayed, delay, i;
00918     int64_t offset;
00919 
00920     if (s->flags & AVFMT_FLAG_NOFILLIN)
00921         return;
00922 
00923     if((s->flags & AVFMT_FLAG_IGNDTS) && pkt->pts != AV_NOPTS_VALUE)
00924         pkt->dts= AV_NOPTS_VALUE;
00925 
00926     if (st->codec->codec_id != CODEC_ID_H264 && pc && pc->pict_type == FF_B_TYPE)
00927         //FIXME Set low_delay = 0 when has_b_frames = 1
00928         st->codec->has_b_frames = 1;
00929 
00930     /* do we have a video B-frame ? */
00931     delay= st->codec->has_b_frames;
00932     presentation_delayed = 0;
00933     /* XXX: need has_b_frame, but cannot get it if the codec is
00934         not initialized */
00935     if (delay &&
00936         pc && pc->pict_type != FF_B_TYPE)
00937         presentation_delayed = 1;
00938 
00939     if(pkt->pts != AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE && pkt->dts > pkt->pts && st->pts_wrap_bits<63
00940        /*&& pkt->dts-(1LL<<st->pts_wrap_bits) < pkt->pts*/){
00941         pkt->dts -= 1LL<<st->pts_wrap_bits;
00942     }
00943 
00944     // some mpeg2 in mpeg-ps lack dts (issue171 / input_file.mpg)
00945     // we take the conservative approach and discard both
00946     // Note, if this is misbehaving for a H.264 file then possibly presentation_delayed is not set correctly.
00947     if(delay==1 && pkt->dts == pkt->pts && pkt->dts != AV_NOPTS_VALUE && presentation_delayed){
00948         av_log(s, AV_LOG_DEBUG, "invalid dts/pts combination\n");
00949         pkt->dts= pkt->pts= AV_NOPTS_VALUE;
00950     }
00951 
00952     if (pkt->duration == 0) {
00953         compute_frame_duration(&num, &den, st, pc, pkt);
00954         if (den && num) {
00955             pkt->duration = av_rescale_rnd(1, num * (int64_t)st->time_base.den, den * (int64_t)st->time_base.num, AV_ROUND_DOWN);
00956 
00957             if(pkt->duration != 0 && s->packet_buffer)
00958                 update_initial_durations(s, st, pkt);
00959         }
00960     }
00961 
00962     /* correct timestamps with byte offset if demuxers only have timestamps
00963        on packet boundaries */
00964     if(pc && st->need_parsing == AVSTREAM_PARSE_TIMESTAMPS && pkt->size){
00965         /* this will estimate bitrate based on this frame's duration and size */
00966         offset = av_rescale(pc->offset, pkt->duration, pkt->size);
00967         if(pkt->pts != AV_NOPTS_VALUE)
00968             pkt->pts += offset;
00969         if(pkt->dts != AV_NOPTS_VALUE)
00970             pkt->dts += offset;
00971     }
00972 
00973     if (pc && pc->dts_sync_point >= 0) {
00974         // we have synchronization info from the parser
00975         int64_t den = st->codec->time_base.den * (int64_t) st->time_base.num;
00976         if (den > 0) {
00977             int64_t num = st->codec->time_base.num * (int64_t) st->time_base.den;
00978             if (pkt->dts != AV_NOPTS_VALUE) {
00979                 // got DTS from the stream, update reference timestamp
00980                 st->reference_dts = pkt->dts - pc->dts_ref_dts_delta * num / den;
00981                 pkt->pts = pkt->dts + pc->pts_dts_delta * num / den;
00982             } else if (st->reference_dts != AV_NOPTS_VALUE) {
00983                 // compute DTS based on reference timestamp
00984                 pkt->dts = st->reference_dts + pc->dts_ref_dts_delta * num / den;
00985                 pkt->pts = pkt->dts + pc->pts_dts_delta * num / den;
00986             }
00987             if (pc->dts_sync_point > 0)
00988                 st->reference_dts = pkt->dts; // new reference
00989         }
00990     }
00991 
00992     /* This may be redundant, but it should not hurt. */
00993     if(pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE && pkt->pts > pkt->dts)
00994         presentation_delayed = 1;
00995 
00996 //    av_log(NULL, AV_LOG_DEBUG, "IN delayed:%d pts:%"PRId64", dts:%"PRId64" cur_dts:%"PRId64" st:%d pc:%p\n", presentation_delayed, pkt->pts, pkt->dts, st->cur_dts, pkt->stream_index, pc);
00997     /* interpolate PTS and DTS if they are not present */
00998     //We skip H264 currently because delay and has_b_frames are not reliably set
00999     if((delay==0 || (delay==1 && pc)) && st->codec->codec_id != CODEC_ID_H264){
01000         if (presentation_delayed) {
01001             /* DTS = decompression timestamp */
01002             /* PTS = presentation timestamp */
01003             if (pkt->dts == AV_NOPTS_VALUE)
01004                 pkt->dts = st->last_IP_pts;
01005             update_initial_timestamps(s, pkt->stream_index, pkt->dts, pkt->pts);
01006             if (pkt->dts == AV_NOPTS_VALUE)
01007                 pkt->dts = st->cur_dts;
01008 
01009             /* this is tricky: the dts must be incremented by the duration
01010             of the frame we are displaying, i.e. the last I- or P-frame */
01011             if (st->last_IP_duration == 0)
01012                 st->last_IP_duration = pkt->duration;
01013             if(pkt->dts != AV_NOPTS_VALUE)
01014                 st->cur_dts = pkt->dts + st->last_IP_duration;
01015             st->last_IP_duration  = pkt->duration;
01016             st->last_IP_pts= pkt->pts;
01017             /* cannot compute PTS if not present (we can compute it only
01018             by knowing the future */
01019         } else if(pkt->pts != AV_NOPTS_VALUE || pkt->dts != AV_NOPTS_VALUE || pkt->duration){
01020             if(pkt->pts != AV_NOPTS_VALUE && pkt->duration){
01021                 int64_t old_diff= FFABS(st->cur_dts - pkt->duration - pkt->pts);
01022                 int64_t new_diff= FFABS(st->cur_dts - pkt->pts);
01023                 if(old_diff < new_diff && old_diff < (pkt->duration>>3)){
01024                     pkt->pts += pkt->duration;
01025     //                av_log(NULL, AV_LOG_DEBUG, "id:%d old:%"PRId64" new:%"PRId64" dur:%d cur:%"PRId64" size:%d\n", pkt->stream_index, old_diff, new_diff, pkt->duration, st->cur_dts, pkt->size);
01026                 }
01027             }
01028 
01029             /* presentation is not delayed : PTS and DTS are the same */
01030             if(pkt->pts == AV_NOPTS_VALUE)
01031                 pkt->pts = pkt->dts;
01032             update_initial_timestamps(s, pkt->stream_index, pkt->pts, pkt->pts);
01033             if(pkt->pts == AV_NOPTS_VALUE)
01034                 pkt->pts = st->cur_dts;
01035             pkt->dts = pkt->pts;
01036             if(pkt->pts != AV_NOPTS_VALUE)
01037                 st->cur_dts = pkt->pts + pkt->duration;
01038         }
01039     }
01040 
01041     if(pkt->pts != AV_NOPTS_VALUE && delay <= MAX_REORDER_DELAY){
01042         st->pts_buffer[0]= pkt->pts;
01043         for(i=0; i<delay && st->pts_buffer[i] > st->pts_buffer[i+1]; i++)
01044             FFSWAP(int64_t, st->pts_buffer[i], st->pts_buffer[i+1]);
01045         if(pkt->dts == AV_NOPTS_VALUE)
01046             pkt->dts= st->pts_buffer[0];
01047         if(st->codec->codec_id == CODEC_ID_H264){ //we skiped it above so we try here
01048             update_initial_timestamps(s, pkt->stream_index, pkt->dts, pkt->pts); // this should happen on the first packet
01049         }
01050         if(pkt->dts > st->cur_dts)
01051             st->cur_dts = pkt->dts;
01052     }
01053 
01054 //    av_log(NULL, AV_LOG_ERROR, "OUTdelayed:%d/%d pts:%"PRId64", dts:%"PRId64" cur_dts:%"PRId64"\n", presentation_delayed, delay, pkt->pts, pkt->dts, st->cur_dts);
01055 
01056     /* update flags */
01057     if(is_intra_only(st->codec))
01058         pkt->flags |= AV_PKT_FLAG_KEY;
01059     else if (pc) {
01060         pkt->flags = 0;
01061         /* keyframe computation */
01062         if (pc->key_frame == 1)
01063             pkt->flags |= AV_PKT_FLAG_KEY;
01064         else if (pc->key_frame == -1 && pc->pict_type == FF_I_TYPE)
01065             pkt->flags |= AV_PKT_FLAG_KEY;
01066     }
01067     if (pc)
01068         pkt->convergence_duration = pc->convergence_duration;
01069 }
01070 
01071 
01072 static int av_read_frame_internal(AVFormatContext *s, AVPacket *pkt)
01073 {
01074     AVStream *st;
01075     int len, ret, i;
01076 
01077     av_init_packet(pkt);
01078 
01079     for(;;) {
01080         /* select current input stream component */
01081         st = s->cur_st;
01082         if (st) {
01083             if (!st->need_parsing || !st->parser) {
01084                 /* no parsing needed: we just output the packet as is */
01085                 /* raw data support */
01086                 *pkt = st->cur_pkt; st->cur_pkt.data= NULL;
01087                 compute_pkt_fields(s, st, NULL, pkt);
01088                 s->cur_st = NULL;
01089                 if ((s->iformat->flags & AVFMT_GENERIC_INDEX) &&
01090                     (pkt->flags & AV_PKT_FLAG_KEY) && pkt->dts != AV_NOPTS_VALUE) {
01091                     ff_reduce_index(s, st->index);
01092                     av_add_index_entry(st, pkt->pos, pkt->dts, 0, 0, AVINDEX_KEYFRAME);
01093                 }
01094                 break;
01095             } else if (st->cur_len > 0 && st->discard < AVDISCARD_ALL) {
01096                 len = av_parser_parse2(st->parser, st->codec, &pkt->data, &pkt->size,
01097                                        st->cur_ptr, st->cur_len,
01098                                        st->cur_pkt.pts, st->cur_pkt.dts,
01099                                        st->cur_pkt.pos);
01100                 st->cur_pkt.pts = AV_NOPTS_VALUE;
01101                 st->cur_pkt.dts = AV_NOPTS_VALUE;
01102                 /* increment read pointer */
01103                 st->cur_ptr += len;
01104                 st->cur_len -= len;
01105 
01106                 /* return packet if any */
01107                 if (pkt->size) {
01108                 got_packet:
01109                     pkt->duration = 0;
01110                     pkt->stream_index = st->index;
01111                     pkt->pts = st->parser->pts;
01112                     pkt->dts = st->parser->dts;
01113                     pkt->pos = st->parser->pos;
01114                     if(pkt->data == st->cur_pkt.data && pkt->size == st->cur_pkt.size){
01115                         s->cur_st = NULL;
01116                         pkt->destruct= st->cur_pkt.destruct;
01117                         st->cur_pkt.destruct= NULL;
01118                         st->cur_pkt.data    = NULL;
01119                         assert(st->cur_len == 0);
01120                     }else{
01121                     pkt->destruct = NULL;
01122                     }
01123                     compute_pkt_fields(s, st, st->parser, pkt);
01124 
01125                     if((s->iformat->flags & AVFMT_GENERIC_INDEX) && pkt->flags & AV_PKT_FLAG_KEY){
01126                         ff_reduce_index(s, st->index);
01127                         av_add_index_entry(st, st->parser->frame_offset, pkt->dts,
01128                                            0, 0, AVINDEX_KEYFRAME);
01129                     }
01130 
01131                     break;
01132                 }
01133             } else {
01134                 /* free packet */
01135                 av_free_packet(&st->cur_pkt);
01136                 s->cur_st = NULL;
01137             }
01138         } else {
01139             AVPacket cur_pkt;
01140             /* read next packet */
01141             ret = av_read_packet(s, &cur_pkt);
01142             if (ret < 0) {
01143                 if (ret == AVERROR(EAGAIN))
01144                     return ret;
01145                 /* return the last frames, if any */
01146                 for(i = 0; i < s->nb_streams; i++) {
01147                     st = s->streams[i];
01148                     if (st->parser && st->need_parsing) {
01149                         av_parser_parse2(st->parser, st->codec,
01150                                         &pkt->data, &pkt->size,
01151                                         NULL, 0,
01152                                         AV_NOPTS_VALUE, AV_NOPTS_VALUE,
01153                                         AV_NOPTS_VALUE);
01154                         if (pkt->size)
01155                             goto got_packet;
01156                     }
01157                 }
01158                 /* no more packets: really terminate parsing */
01159                 return ret;
01160             }
01161             st = s->streams[cur_pkt.stream_index];
01162             st->cur_pkt= cur_pkt;
01163 
01164             if(st->cur_pkt.pts != AV_NOPTS_VALUE &&
01165                st->cur_pkt.dts != AV_NOPTS_VALUE &&
01166                st->cur_pkt.pts < st->cur_pkt.dts){
01167                 av_log(s, AV_LOG_WARNING, "Invalid timestamps stream=%d, pts=%"PRId64", dts=%"PRId64", size=%d\n",
01168                     st->cur_pkt.stream_index,
01169                     st->cur_pkt.pts,
01170                     st->cur_pkt.dts,
01171                     st->cur_pkt.size);
01172 //                av_free_packet(&st->cur_pkt);
01173 //                return -1;
01174             }
01175 
01176             if(s->debug & FF_FDEBUG_TS)
01177                 av_log(s, AV_LOG_DEBUG, "av_read_packet stream=%d, pts=%"PRId64", dts=%"PRId64", size=%d, duration=%d, flags=%d\n",
01178                     st->cur_pkt.stream_index,
01179                     st->cur_pkt.pts,
01180                     st->cur_pkt.dts,
01181                     st->cur_pkt.size,
01182                     st->cur_pkt.duration,
01183                     st->cur_pkt.flags);
01184 
01185             s->cur_st = st;
01186             st->cur_ptr = st->cur_pkt.data;
01187             st->cur_len = st->cur_pkt.size;
01188             if (st->need_parsing && !st->parser && !(s->flags & AVFMT_FLAG_NOPARSE)) {
01189                 st->parser = av_parser_init(st->codec->codec_id);
01190                 if (!st->parser) {
01191                     /* no parser available: just output the raw packets */
01192                     st->need_parsing = AVSTREAM_PARSE_NONE;
01193                 }else if(st->need_parsing == AVSTREAM_PARSE_HEADERS){
01194                     st->parser->flags |= PARSER_FLAG_COMPLETE_FRAMES;
01195                 }else if(st->need_parsing == AVSTREAM_PARSE_FULL_ONCE){
01196                     st->parser->flags |= PARSER_FLAG_ONCE;
01197                 }
01198             }
01199         }
01200     }
01201     if(s->debug & FF_FDEBUG_TS)
01202         av_log(s, AV_LOG_DEBUG, "av_read_frame_internal stream=%d, pts=%"PRId64", dts=%"PRId64", size=%d, duration=%d, flags=%d\n",
01203             pkt->stream_index,
01204             pkt->pts,
01205             pkt->dts,
01206             pkt->size,
01207             pkt->duration,
01208             pkt->flags);
01209 
01210     return 0;
01211 }
01212 
01213 int av_read_frame(AVFormatContext *s, AVPacket *pkt)
01214 {
01215     AVPacketList *pktl;
01216     int eof=0;
01217     const int genpts= s->flags & AVFMT_FLAG_GENPTS;
01218 
01219     for(;;){
01220         pktl = s->packet_buffer;
01221         if (pktl) {
01222             AVPacket *next_pkt= &pktl->pkt;
01223 
01224             if(genpts && next_pkt->dts != AV_NOPTS_VALUE){
01225                 int wrap_bits = s->streams[next_pkt->stream_index]->pts_wrap_bits;
01226                 while(pktl && next_pkt->pts == AV_NOPTS_VALUE){
01227                     if(   pktl->pkt.stream_index == next_pkt->stream_index
01228                        && (0 > av_compare_mod(next_pkt->dts, pktl->pkt.dts, 2LL << (wrap_bits - 1)))
01229                        && av_compare_mod(pktl->pkt.pts, pktl->pkt.dts, 2LL << (wrap_bits - 1))) { //not b frame
01230                         next_pkt->pts= pktl->pkt.dts;
01231                     }
01232                     pktl= pktl->next;
01233                 }
01234                 pktl = s->packet_buffer;
01235             }
01236 
01237             if(   next_pkt->pts != AV_NOPTS_VALUE
01238                || next_pkt->dts == AV_NOPTS_VALUE
01239                || !genpts || eof){
01240                 /* read packet from packet buffer, if there is data */
01241                 *pkt = *next_pkt;
01242                 s->packet_buffer = pktl->next;
01243                 av_free(pktl);
01244                 return 0;
01245             }
01246         }
01247         if(genpts){
01248             int ret= av_read_frame_internal(s, pkt);
01249             if(ret<0){
01250                 if(pktl && ret != AVERROR(EAGAIN)){
01251                     eof=1;
01252                     continue;
01253                 }else
01254                     return ret;
01255             }
01256 
01257             if(av_dup_packet(add_to_pktbuf(&s->packet_buffer, pkt,
01258                                            &s->packet_buffer_end)) < 0)
01259                 return AVERROR(ENOMEM);
01260         }else{
01261             assert(!s->packet_buffer);
01262             return av_read_frame_internal(s, pkt);
01263         }
01264     }
01265 }
01266 
01267 /* XXX: suppress the packet queue */
01268 static void flush_packet_queue(AVFormatContext *s)
01269 {
01270     AVPacketList *pktl;
01271 
01272     for(;;) {
01273         pktl = s->packet_buffer;
01274         if (!pktl)
01275             break;
01276         s->packet_buffer = pktl->next;
01277         av_free_packet(&pktl->pkt);
01278         av_free(pktl);
01279     }
01280     while(s->raw_packet_buffer){
01281         pktl = s->raw_packet_buffer;
01282         s->raw_packet_buffer = pktl->next;
01283         av_free_packet(&pktl->pkt);
01284         av_free(pktl);
01285     }
01286     s->packet_buffer_end=
01287     s->raw_packet_buffer_end= NULL;
01288     s->raw_packet_buffer_remaining_size = RAW_PACKET_BUFFER_SIZE;
01289 }
01290 
01291 /*******************************************************/
01292 /* seek support */
01293 
01294 int av_find_default_stream_index(AVFormatContext *s)
01295 {
01296     int first_audio_index = -1;
01297     int i;
01298     AVStream *st;
01299 
01300     if (s->nb_streams <= 0)
01301         return -1;
01302     for(i = 0; i < s->nb_streams; i++) {
01303         st = s->streams[i];
01304         if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
01305             return i;
01306         }
01307         if (first_audio_index < 0 && st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
01308             first_audio_index = i;
01309     }
01310     return first_audio_index >= 0 ? first_audio_index : 0;
01311 }
01312 
01316 void ff_read_frame_flush(AVFormatContext *s)
01317 {
01318     AVStream *st;
01319     int i, j;
01320 
01321     flush_packet_queue(s);
01322 
01323     s->cur_st = NULL;
01324 
01325     /* for each stream, reset read state */
01326     for(i = 0; i < s->nb_streams; i++) {
01327         st = s->streams[i];
01328 
01329         if (st->parser) {
01330             av_parser_close(st->parser);
01331             st->parser = NULL;
01332             av_free_packet(&st->cur_pkt);
01333         }
01334         st->last_IP_pts = AV_NOPTS_VALUE;
01335         st->cur_dts = AV_NOPTS_VALUE; /* we set the current DTS to an unspecified origin */
01336         st->reference_dts = AV_NOPTS_VALUE;
01337         /* fail safe */
01338         st->cur_ptr = NULL;
01339         st->cur_len = 0;
01340 
01341         st->probe_packets = MAX_PROBE_PACKETS;
01342 
01343         for(j=0; j<MAX_REORDER_DELAY+1; j++)
01344             st->pts_buffer[j]= AV_NOPTS_VALUE;
01345     }
01346 }
01347 
01348 void av_update_cur_dts(AVFormatContext *s, AVStream *ref_st, int64_t timestamp){
01349     int i;
01350 
01351     for(i = 0; i < s->nb_streams; i++) {
01352         AVStream *st = s->streams[i];
01353 
01354         st->cur_dts = av_rescale(timestamp,
01355                                  st->time_base.den * (int64_t)ref_st->time_base.num,
01356                                  st->time_base.num * (int64_t)ref_st->time_base.den);
01357     }
01358 }
01359 
01360 void ff_reduce_index(AVFormatContext *s, int stream_index)
01361 {
01362     AVStream *st= s->streams[stream_index];
01363     unsigned int max_entries= s->max_index_size / sizeof(AVIndexEntry);
01364 
01365     if((unsigned)st->nb_index_entries >= max_entries){
01366         int i;
01367         for(i=0; 2*i<st->nb_index_entries; i++)
01368             st->index_entries[i]= st->index_entries[2*i];
01369         st->nb_index_entries= i;
01370     }
01371 }
01372 
01373 int av_add_index_entry(AVStream *st,
01374                             int64_t pos, int64_t timestamp, int size, int distance, int flags)
01375 {
01376     AVIndexEntry *entries, *ie;
01377     int index;
01378 
01379     if((unsigned)st->nb_index_entries + 1 >= UINT_MAX / sizeof(AVIndexEntry))
01380         return -1;
01381 
01382     entries = av_fast_realloc(st->index_entries,
01383                               &st->index_entries_allocated_size,
01384                               (st->nb_index_entries + 1) *
01385                               sizeof(AVIndexEntry));
01386     if(!entries)
01387         return -1;
01388 
01389     st->index_entries= entries;
01390 
01391     index= av_index_search_timestamp(st, timestamp, AVSEEK_FLAG_ANY);
01392 
01393     if(index<0){
01394         index= st->nb_index_entries++;
01395         ie= &entries[index];
01396         assert(index==0 || ie[-1].timestamp < timestamp);
01397     }else{
01398         ie= &entries[index];
01399         if(ie->timestamp != timestamp){
01400             if(ie->timestamp <= timestamp)
01401                 return -1;
01402             memmove(entries + index + 1, entries + index, sizeof(AVIndexEntry)*(st->nb_index_entries - index));
01403             st->nb_index_entries++;
01404         }else if(ie->pos == pos && distance < ie->min_distance) //do not reduce the distance
01405             distance= ie->min_distance;
01406     }
01407 
01408     ie->pos = pos;
01409     ie->timestamp = timestamp;
01410     ie->min_distance= distance;
01411     ie->size= size;
01412     ie->flags = flags;
01413 
01414     return index;
01415 }
01416 
01417 int av_index_search_timestamp(AVStream *st, int64_t wanted_timestamp,
01418                               int flags)
01419 {
01420     AVIndexEntry *entries= st->index_entries;
01421     int nb_entries= st->nb_index_entries;
01422     int a, b, m;
01423     int64_t timestamp;
01424 
01425     a = - 1;
01426     b = nb_entries;
01427 
01428     //optimize appending index entries at the end
01429     if(b && entries[b-1].timestamp < wanted_timestamp)
01430         a= b-1;
01431 
01432     while (b - a > 1) {
01433         m = (a + b) >> 1;
01434         timestamp = entries[m].timestamp;
01435         if(timestamp >= wanted_timestamp)
01436             b = m;
01437         if(timestamp <= wanted_timestamp)
01438             a = m;
01439     }
01440     m= (flags & AVSEEK_FLAG_BACKWARD) ? a : b;
01441 
01442     if(!(flags & AVSEEK_FLAG_ANY)){
01443         while(m>=0 && m<nb_entries && !(entries[m].flags & AVINDEX_KEYFRAME)){
01444             m += (flags & AVSEEK_FLAG_BACKWARD) ? -1 : 1;
01445         }
01446     }
01447 
01448     if(m == nb_entries)
01449         return -1;
01450     return  m;
01451 }
01452 
01453 #define DEBUG_SEEK
01454 
01455 int av_seek_frame_binary(AVFormatContext *s, int stream_index, int64_t target_ts, int flags){
01456     AVInputFormat *avif= s->iformat;
01457     int64_t av_uninit(pos_min), av_uninit(pos_max), pos, pos_limit;
01458     int64_t ts_min, ts_max, ts;
01459     int index;
01460     int64_t ret;
01461     AVStream *st;
01462 
01463     if (stream_index < 0)
01464         return -1;
01465 
01466 #ifdef DEBUG_SEEK
01467     av_log(s, AV_LOG_DEBUG, "read_seek: %d %"PRId64"\n", stream_index, target_ts);
01468 #endif
01469 
01470     ts_max=
01471     ts_min= AV_NOPTS_VALUE;
01472     pos_limit= -1; //gcc falsely says it may be uninitialized
01473 
01474     st= s->streams[stream_index];
01475     if(st->index_entries){
01476         AVIndexEntry *e;
01477 
01478         index= av_index_search_timestamp(st, target_ts, flags | AVSEEK_FLAG_BACKWARD); //FIXME whole func must be checked for non-keyframe entries in index case, especially read_timestamp()
01479         index= FFMAX(index, 0);
01480         e= &st->index_entries[index];
01481 
01482         if(e->timestamp <= target_ts || e->pos == e->min_distance){
01483             pos_min= e->pos;
01484             ts_min= e->timestamp;
01485 #ifdef DEBUG_SEEK
01486             av_log(s, AV_LOG_DEBUG, "using cached pos_min=0x%"PRIx64" dts_min=%"PRId64"\n",
01487                    pos_min,ts_min);
01488 #endif
01489         }else{
01490             assert(index==0);
01491         }
01492 
01493         index= av_index_search_timestamp(st, target_ts, flags & ~AVSEEK_FLAG_BACKWARD);
01494         assert(index < st->nb_index_entries);
01495         if(index >= 0){
01496             e= &st->index_entries[index];
01497             assert(e->timestamp >= target_ts);
01498             pos_max= e->pos;
01499             ts_max= e->timestamp;
01500             pos_limit= pos_max - e->min_distance;
01501 #ifdef DEBUG_SEEK
01502             av_log(s, AV_LOG_DEBUG, "using cached pos_max=0x%"PRIx64" pos_limit=0x%"PRIx64" dts_max=%"PRId64"\n",
01503                    pos_max,pos_limit, ts_max);
01504 #endif
01505         }
01506     }
01507 
01508     pos= av_gen_search(s, stream_index, target_ts, pos_min, pos_max, pos_limit, ts_min, ts_max, flags, &ts, avif->read_timestamp);
01509     if(pos<0)
01510         return -1;
01511 
01512     /* do the seek */
01513     if ((ret = url_fseek(s->pb, pos, SEEK_SET)) < 0)
01514         return ret;
01515 
01516     av_update_cur_dts(s, st, ts);
01517 
01518     return 0;
01519 }
01520 
01521 int64_t av_gen_search(AVFormatContext *s, int stream_index, int64_t target_ts, int64_t pos_min, int64_t pos_max, int64_t pos_limit, int64_t ts_min, int64_t ts_max, int flags, int64_t *ts_ret, int64_t (*read_timestamp)(struct AVFormatContext *, int , int64_t *, int64_t )){
01522     int64_t pos, ts;
01523     int64_t start_pos, filesize;
01524     int no_change;
01525 
01526 #ifdef DEBUG_SEEK
01527     av_log(s, AV_LOG_DEBUG, "gen_seek: %d %"PRId64"\n", stream_index, target_ts);
01528 #endif
01529 
01530     if(ts_min == AV_NOPTS_VALUE){
01531         pos_min = s->data_offset;
01532         ts_min = read_timestamp(s, stream_index, &pos_min, INT64_MAX);
01533         if (ts_min == AV_NOPTS_VALUE)
01534             return -1;
01535     }
01536 
01537     if(ts_max == AV_NOPTS_VALUE){
01538         int step= 1024;
01539         filesize = url_fsize(s->pb);
01540         pos_max = filesize - 1;
01541         do{
01542             pos_max -= step;
01543             ts_max = read_timestamp(s, stream_index, &pos_max, pos_max + step);
01544             step += step;
01545         }while(ts_max == AV_NOPTS_VALUE && pos_max >= step);
01546         if (ts_max == AV_NOPTS_VALUE)
01547             return -1;
01548 
01549         for(;;){
01550             int64_t tmp_pos= pos_max + 1;
01551             int64_t tmp_ts= read_timestamp(s, stream_index, &tmp_pos, INT64_MAX);
01552             if(tmp_ts == AV_NOPTS_VALUE)
01553                 break;
01554             ts_max= tmp_ts;
01555             pos_max= tmp_pos;
01556             if(tmp_pos >= filesize)
01557                 break;
01558         }
01559         pos_limit= pos_max;
01560     }
01561 
01562     if(ts_min > ts_max){
01563         return -1;
01564     }else if(ts_min == ts_max){
01565         pos_limit= pos_min;
01566     }
01567 
01568     no_change=0;
01569     while (pos_min < pos_limit) {
01570 #ifdef DEBUG_SEEK
01571         av_log(s, AV_LOG_DEBUG, "pos_min=0x%"PRIx64" pos_max=0x%"PRIx64" dts_min=%"PRId64" dts_max=%"PRId64"\n",
01572                pos_min, pos_max,
01573                ts_min, ts_max);
01574 #endif
01575         assert(pos_limit <= pos_max);
01576 
01577         if(no_change==0){
01578             int64_t approximate_keyframe_distance= pos_max - pos_limit;
01579             // interpolate position (better than dichotomy)
01580             pos = av_rescale(target_ts - ts_min, pos_max - pos_min, ts_max - ts_min)
01581                 + pos_min - approximate_keyframe_distance;
01582         }else if(no_change==1){
01583             // bisection, if interpolation failed to change min or max pos last time
01584             pos = (pos_min + pos_limit)>>1;
01585         }else{
01586             /* linear search if bisection failed, can only happen if there
01587                are very few or no keyframes between min/max */
01588             pos=pos_min;
01589         }
01590         if(pos <= pos_min)
01591             pos= pos_min + 1;
01592         else if(pos > pos_limit)
01593             pos= pos_limit;
01594         start_pos= pos;
01595 
01596         ts = read_timestamp(s, stream_index, &pos, INT64_MAX); //may pass pos_limit instead of -1
01597         if(pos == pos_max)
01598             no_change++;
01599         else
01600             no_change=0;
01601 #ifdef DEBUG_SEEK
01602         av_log(s, AV_LOG_DEBUG, "%"PRId64" %"PRId64" %"PRId64" / %"PRId64" %"PRId64" %"PRId64" target:%"PRId64" limit:%"PRId64" start:%"PRId64" noc:%d\n",
01603                pos_min, pos, pos_max, ts_min, ts, ts_max, target_ts, pos_limit,
01604                start_pos, no_change);
01605 #endif
01606         if(ts == AV_NOPTS_VALUE){
01607             av_log(s, AV_LOG_ERROR, "read_timestamp() failed in the middle\n");
01608             return -1;
01609         }
01610         assert(ts != AV_NOPTS_VALUE);
01611         if (target_ts <= ts) {
01612             pos_limit = start_pos - 1;
01613             pos_max = pos;
01614             ts_max = ts;
01615         }
01616         if (target_ts >= ts) {
01617             pos_min = pos;
01618             ts_min = ts;
01619         }
01620     }
01621 
01622     pos = (flags & AVSEEK_FLAG_BACKWARD) ? pos_min : pos_max;
01623     ts  = (flags & AVSEEK_FLAG_BACKWARD) ?  ts_min :  ts_max;
01624 #ifdef DEBUG_SEEK
01625     pos_min = pos;
01626     ts_min = read_timestamp(s, stream_index, &pos_min, INT64_MAX);
01627     pos_min++;
01628     ts_max = read_timestamp(s, stream_index, &pos_min, INT64_MAX);
01629     av_log(s, AV_LOG_DEBUG, "pos=0x%"PRIx64" %"PRId64"<=%"PRId64"<=%"PRId64"\n",
01630            pos, ts_min, target_ts, ts_max);
01631 #endif
01632     *ts_ret= ts;
01633     return pos;
01634 }
01635 
01636 static int av_seek_frame_byte(AVFormatContext *s, int stream_index, int64_t pos, int flags){
01637     int64_t pos_min, pos_max;
01638 #if 0
01639     AVStream *st;
01640 
01641     if (stream_index < 0)
01642         return -1;
01643 
01644     st= s->streams[stream_index];
01645 #endif
01646 
01647     pos_min = s->data_offset;
01648     pos_max = url_fsize(s->pb) - 1;
01649 
01650     if     (pos < pos_min) pos= pos_min;
01651     else if(pos > pos_max) pos= pos_max;
01652 
01653     url_fseek(s->pb, pos, SEEK_SET);
01654 
01655 #if 0
01656     av_update_cur_dts(s, st, ts);
01657 #endif
01658     return 0;
01659 }
01660 
01661 static int av_seek_frame_generic(AVFormatContext *s,
01662                                  int stream_index, int64_t timestamp, int flags)
01663 {
01664     int index;
01665     int64_t ret;
01666     AVStream *st;
01667     AVIndexEntry *ie;
01668 
01669     st = s->streams[stream_index];
01670 
01671     index = av_index_search_timestamp(st, timestamp, flags);
01672 
01673     if(index < 0 && st->nb_index_entries && timestamp < st->index_entries[0].timestamp)
01674         return -1;
01675 
01676     if(index < 0 || index==st->nb_index_entries-1){
01677         int i;
01678         AVPacket pkt;
01679 
01680         if(st->nb_index_entries){
01681             assert(st->index_entries);
01682             ie= &st->index_entries[st->nb_index_entries-1];
01683             if ((ret = url_fseek(s->pb, ie->pos, SEEK_SET)) < 0)
01684                 return ret;
01685             av_update_cur_dts(s, st, ie->timestamp);
01686         }else{
01687             if ((ret = url_fseek(s->pb, s->data_offset, SEEK_SET)) < 0)
01688                 return ret;
01689         }
01690         for(i=0;; i++) {
01691             int ret;
01692             do{
01693                 ret = av_read_frame(s, &pkt);
01694             }while(ret == AVERROR(EAGAIN));
01695             if(ret<0)
01696                 break;
01697             av_free_packet(&pkt);
01698             if(stream_index == pkt.stream_index){
01699                 if((pkt.flags & AV_PKT_FLAG_KEY) && pkt.dts > timestamp)
01700                     break;
01701             }
01702         }
01703         index = av_index_search_timestamp(st, timestamp, flags);
01704     }
01705     if (index < 0)
01706         return -1;
01707 
01708     ff_read_frame_flush(s);
01709     if (s->iformat->read_seek){
01710         if(s->iformat->read_seek(s, stream_index, timestamp, flags) >= 0)
01711             return 0;
01712     }
01713     ie = &st->index_entries[index];
01714     if ((ret = url_fseek(s->pb, ie->pos, SEEK_SET)) < 0)
01715         return ret;
01716     av_update_cur_dts(s, st, ie->timestamp);
01717 
01718     return 0;
01719 }
01720 
01721 int av_seek_frame(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
01722 {
01723     int ret;
01724     AVStream *st;
01725 
01726     ff_read_frame_flush(s);
01727 
01728     if(flags & AVSEEK_FLAG_BYTE)
01729         return av_seek_frame_byte(s, stream_index, timestamp, flags);
01730 
01731     if(stream_index < 0){
01732         stream_index= av_find_default_stream_index(s);
01733         if(stream_index < 0)
01734             return -1;
01735 
01736         st= s->streams[stream_index];
01737        /* timestamp for default must be expressed in AV_TIME_BASE units */
01738         timestamp = av_rescale(timestamp, st->time_base.den, AV_TIME_BASE * (int64_t)st->time_base.num);
01739     }
01740 
01741     /* first, we try the format specific seek */
01742     if (s->iformat->read_seek)
01743         ret = s->iformat->read_seek(s, stream_index, timestamp, flags);
01744     else
01745         ret = -1;
01746     if (ret >= 0) {
01747         return 0;
01748     }
01749 
01750     if(s->iformat->read_timestamp)
01751         return av_seek_frame_binary(s, stream_index, timestamp, flags);
01752     else
01753         return av_seek_frame_generic(s, stream_index, timestamp, flags);
01754 }
01755 
01756 int avformat_seek_file(AVFormatContext *s, int stream_index, int64_t min_ts, int64_t ts, int64_t max_ts, int flags)
01757 {
01758     if(min_ts > ts || max_ts < ts)
01759         return -1;
01760 
01761     ff_read_frame_flush(s);
01762 
01763     if (s->iformat->read_seek2)
01764         return s->iformat->read_seek2(s, stream_index, min_ts, ts, max_ts, flags);
01765 
01766     if(s->iformat->read_timestamp){
01767         //try to seek via read_timestamp()
01768     }
01769 
01770     //Fallback to old API if new is not implemented but old is
01771     //Note the old has somewat different sematics
01772     if(s->iformat->read_seek || 1)
01773         return av_seek_frame(s, stream_index, ts, flags | (ts - min_ts > (uint64_t)(max_ts - ts) ? AVSEEK_FLAG_BACKWARD : 0));
01774 
01775     // try some generic seek like av_seek_frame_generic() but with new ts semantics
01776 }
01777 
01778 /*******************************************************/
01779 
01785 static int av_has_duration(AVFormatContext *ic)
01786 {
01787     int i;
01788     AVStream *st;
01789 
01790     for(i = 0;i < ic->nb_streams; i++) {
01791         st = ic->streams[i];
01792         if (st->duration != AV_NOPTS_VALUE)
01793             return 1;
01794     }
01795     return 0;
01796 }
01797 
01803 static void av_update_stream_timings(AVFormatContext *ic)
01804 {
01805     int64_t start_time, start_time1, end_time, end_time1;
01806     int64_t duration, duration1;
01807     int i;
01808     AVStream *st;
01809 
01810     start_time = INT64_MAX;
01811     end_time = INT64_MIN;
01812     duration = INT64_MIN;
01813     for(i = 0;i < ic->nb_streams; i++) {
01814         st = ic->streams[i];
01815         if (st->start_time != AV_NOPTS_VALUE && st->time_base.den) {
01816             start_time1= av_rescale_q(st->start_time, st->time_base, AV_TIME_BASE_Q);
01817             if (start_time1 < start_time)
01818                 start_time = start_time1;
01819             if (st->duration != AV_NOPTS_VALUE) {
01820                 end_time1 = start_time1
01821                           + av_rescale_q(st->duration, st->time_base, AV_TIME_BASE_Q);
01822                 if (end_time1 > end_time)
01823                     end_time = end_time1;
01824             }
01825         }
01826         if (st->duration != AV_NOPTS_VALUE) {
01827             duration1 = av_rescale_q(st->duration, st->time_base, AV_TIME_BASE_Q);
01828             if (duration1 > duration)
01829                 duration = duration1;
01830         }
01831     }
01832     if (start_time != INT64_MAX) {
01833         ic->start_time = start_time;
01834         if (end_time != INT64_MIN) {
01835             if (end_time - start_time > duration)
01836                 duration = end_time - start_time;
01837         }
01838     }
01839     if (duration != INT64_MIN) {
01840         ic->duration = duration;
01841         if (ic->file_size > 0) {
01842             /* compute the bitrate */
01843             ic->bit_rate = (double)ic->file_size * 8.0 * AV_TIME_BASE /
01844                 (double)ic->duration;
01845         }
01846     }
01847 }
01848 
01849 static void fill_all_stream_timings(AVFormatContext *ic)
01850 {
01851     int i;
01852     AVStream *st;
01853 
01854     av_update_stream_timings(ic);
01855     for(i = 0;i < ic->nb_streams; i++) {
01856         st = ic->streams[i];
01857         if (st->start_time == AV_NOPTS_VALUE) {
01858             if(ic->start_time != AV_NOPTS_VALUE)
01859                 st->start_time = av_rescale_q(ic->start_time, AV_TIME_BASE_Q, st->time_base);
01860             if(ic->duration != AV_NOPTS_VALUE)
01861                 st->duration = av_rescale_q(ic->duration, AV_TIME_BASE_Q, st->time_base);
01862         }
01863     }
01864 }
01865 
01866 static void av_estimate_timings_from_bit_rate(AVFormatContext *ic)
01867 {
01868     int64_t filesize, duration;
01869     int bit_rate, i;
01870     AVStream *st;
01871 
01872     /* if bit_rate is already set, we believe it */
01873     if (ic->bit_rate <= 0) {
01874         bit_rate = 0;
01875         for(i=0;i<ic->nb_streams;i++) {
01876             st = ic->streams[i];
01877             if (st->codec->bit_rate > 0)
01878             bit_rate += st->codec->bit_rate;
01879         }
01880         ic->bit_rate = bit_rate;
01881     }
01882 
01883     /* if duration is already set, we believe it */
01884     if (ic->duration == AV_NOPTS_VALUE &&
01885         ic->bit_rate != 0 &&
01886         ic->file_size != 0)  {
01887         filesize = ic->file_size;
01888         if (filesize > 0) {
01889             for(i = 0; i < ic->nb_streams; i++) {
01890                 st = ic->streams[i];
01891                 duration= av_rescale(8*filesize, st->time_base.den, ic->bit_rate*(int64_t)st->time_base.num);
01892                 if (st->duration == AV_NOPTS_VALUE)
01893                     st->duration = duration;
01894             }
01895         }
01896     }
01897 }
01898 
01899 #define DURATION_MAX_READ_SIZE 250000
01900 #define DURATION_MAX_RETRY 3
01901 
01902 /* only usable for MPEG-PS streams */
01903 static void av_estimate_timings_from_pts(AVFormatContext *ic, int64_t old_offset)
01904 {
01905     AVPacket pkt1, *pkt = &pkt1;
01906     AVStream *st;
01907     int read_size, i, ret;
01908     int64_t end_time;
01909     int64_t filesize, offset, duration;
01910     int retry=0;
01911 
01912     ic->cur_st = NULL;
01913 
01914     /* flush packet queue */
01915     flush_packet_queue(ic);
01916 
01917     for (i=0; i<ic->nb_streams; i++) {
01918         st = ic->streams[i];
01919         if (st->start_time == AV_NOPTS_VALUE && st->first_dts == AV_NOPTS_VALUE)
01920             av_log(st->codec, AV_LOG_WARNING, "start time is not set in av_estimate_timings_from_pts\n");
01921 
01922         if (st->parser) {
01923             av_parser_close(st->parser);
01924             st->parser= NULL;
01925             av_free_packet(&st->cur_pkt);
01926         }
01927     }
01928 
01929     /* estimate the end time (duration) */
01930     /* XXX: may need to support wrapping */
01931     filesize = ic->file_size;
01932     end_time = AV_NOPTS_VALUE;
01933     do{
01934     offset = filesize - (DURATION_MAX_READ_SIZE<<retry);
01935     if (offset < 0)
01936         offset = 0;
01937 
01938     url_fseek(ic->pb, offset, SEEK_SET);
01939     read_size = 0;
01940     for(;;) {
01941         if (read_size >= DURATION_MAX_READ_SIZE<<(FFMAX(retry-1,0)))
01942             break;
01943 
01944         do{
01945             ret = av_read_packet(ic, pkt);
01946         }while(ret == AVERROR(EAGAIN));
01947         if (ret != 0)
01948             break;
01949         read_size += pkt->size;
01950         st = ic->streams[pkt->stream_index];
01951         if (pkt->pts != AV_NOPTS_VALUE &&
01952             (st->start_time != AV_NOPTS_VALUE ||
01953              st->first_dts  != AV_NOPTS_VALUE)) {
01954             duration = end_time = pkt->pts;
01955             if (st->start_time != AV_NOPTS_VALUE)  duration -= st->start_time;
01956             else                                   duration -= st->first_dts;
01957             if (duration < 0)
01958                 duration += 1LL<<st->pts_wrap_bits;
01959             if (duration > 0) {
01960                 if (st->duration == AV_NOPTS_VALUE ||
01961                     st->duration < duration)
01962                     st->duration = duration;
01963             }
01964         }
01965         av_free_packet(pkt);
01966     }
01967     }while(   end_time==AV_NOPTS_VALUE
01968            && filesize > (DURATION_MAX_READ_SIZE<<retry)
01969            && ++retry <= DURATION_MAX_RETRY);
01970 
01971     fill_all_stream_timings(ic);
01972 
01973     url_fseek(ic->pb, old_offset, SEEK_SET);
01974     for (i=0; i<ic->nb_streams; i++) {
01975         st= ic->streams[i];
01976         st->cur_dts= st->first_dts;
01977         st->last_IP_pts = AV_NOPTS_VALUE;
01978     }
01979 }
01980 
01981 static void av_estimate_timings(AVFormatContext *ic, int64_t old_offset)
01982 {
01983     int64_t file_size;
01984 
01985     /* get the file size, if possible */
01986     if (ic->iformat->flags & AVFMT_NOFILE) {
01987         file_size = 0;
01988     } else {
01989         file_size = url_fsize(ic->pb);
01990         if (file_size < 0)
01991             file_size = 0;
01992     }
01993     ic->file_size = file_size;
01994 
01995     if ((!strcmp(ic->iformat->name, "mpeg") ||
01996          !strcmp(ic->iformat->name, "mpegts")) &&
01997         file_size && !url_is_streamed(ic->pb)) {
01998         /* get accurate estimate from the PTSes */
01999         av_estimate_timings_from_pts(ic, old_offset);
02000     } else if (av_has_duration(ic)) {
02001         /* at least one component has timings - we use them for all
02002            the components */
02003         fill_all_stream_timings(ic);
02004     } else {
02005         av_log(ic, AV_LOG_WARNING, "Estimating duration from bitrate, this may be inaccurate\n");
02006         /* less precise: use bitrate info */
02007         av_estimate_timings_from_bit_rate(ic);
02008     }
02009     av_update_stream_timings(ic);
02010 
02011 #if 0
02012     {
02013         int i;
02014         AVStream *st;
02015         for(i = 0;i < ic->nb_streams; i++) {
02016             st = ic->streams[i];
02017         printf("%d: start_time: %0.3f duration: %0.3f\n",
02018                i, (double)st->start_time / AV_TIME_BASE,
02019                (double)st->duration / AV_TIME_BASE);
02020         }
02021         printf("stream: start_time: %0.3f duration: %0.3f bitrate=%d kb/s\n",
02022                (double)ic->start_time / AV_TIME_BASE,
02023                (double)ic->duration / AV_TIME_BASE,
02024                ic->bit_rate / 1000);
02025     }
02026 #endif
02027 }
02028 
02029 static int has_codec_parameters(AVCodecContext *enc)
02030 {
02031     int val;
02032     switch(enc->codec_type) {
02033     case AVMEDIA_TYPE_AUDIO:
02034         val = enc->sample_rate && enc->channels && enc->sample_fmt != AV_SAMPLE_FMT_NONE;
02035         if(!enc->frame_size &&
02036            (enc->codec_id == CODEC_ID_VORBIS ||
02037             enc->codec_id == CODEC_ID_AAC ||
02038             enc->codec_id == CODEC_ID_MP1 ||
02039             enc->codec_id == CODEC_ID_MP2 ||
02040             enc->codec_id == CODEC_ID_MP3 ||
02041             enc->codec_id == CODEC_ID_SPEEX))
02042             return 0;
02043         break;
02044     case AVMEDIA_TYPE_VIDEO:
02045         val = enc->width && enc->pix_fmt != PIX_FMT_NONE;
02046         break;
02047     default:
02048         val = 1;
02049         break;
02050     }
02051     return enc->codec_id != CODEC_ID_NONE && val != 0;
02052 }
02053 
02054 static int has_decode_delay_been_guessed(AVStream *st)
02055 {
02056     return st->codec->codec_id != CODEC_ID_H264 ||
02057         st->codec_info_nb_frames >= 6 + st->codec->has_b_frames;
02058 }
02059 
02060 static int try_decode_frame(AVStream *st, AVPacket *avpkt)
02061 {
02062     int16_t *samples;
02063     AVCodec *codec;
02064     int got_picture, data_size, ret=0;
02065     AVFrame picture;
02066 
02067     if(!st->codec->codec){
02068         codec = avcodec_find_decoder(st->codec->codec_id);
02069         if (!codec)
02070             return -1;
02071         ret = avcodec_open(st->codec, codec);
02072         if (ret < 0)
02073             return ret;
02074     }
02075 
02076     if(!has_codec_parameters(st->codec) || !has_decode_delay_been_guessed(st)){
02077         switch(st->codec->codec_type) {
02078         case AVMEDIA_TYPE_VIDEO:
02079             avcodec_get_frame_defaults(&picture);
02080             ret = avcodec_decode_video2(st->codec, &picture,
02081                                         &got_picture, avpkt);
02082             break;
02083         case AVMEDIA_TYPE_AUDIO:
02084             data_size = FFMAX(avpkt->size, AVCODEC_MAX_AUDIO_FRAME_SIZE);
02085             samples = av_malloc(data_size);
02086             if (!samples)
02087                 goto fail;
02088             ret = avcodec_decode_audio3(st->codec, samples,
02089                                         &data_size, avpkt);
02090             av_free(samples);
02091             break;
02092         default:
02093             break;
02094         }
02095     }
02096  fail:
02097     return ret;
02098 }
02099 
02100 unsigned int ff_codec_get_tag(const AVCodecTag *tags, enum CodecID id)
02101 {
02102     while (tags->id != CODEC_ID_NONE) {
02103         if (tags->id == id)
02104             return tags->tag;
02105         tags++;
02106     }
02107     return 0;
02108 }
02109 
02110 enum CodecID ff_codec_get_id(const AVCodecTag *tags, unsigned int tag)
02111 {
02112     int i;
02113     for(i=0; tags[i].id != CODEC_ID_NONE;i++) {
02114         if(tag == tags[i].tag)
02115             return tags[i].id;
02116     }
02117     for(i=0; tags[i].id != CODEC_ID_NONE; i++) {
02118         if (ff_toupper4(tag) == ff_toupper4(tags[i].tag))
02119             return tags[i].id;
02120     }
02121     return CODEC_ID_NONE;
02122 }
02123 
02124 unsigned int av_codec_get_tag(const AVCodecTag * const *tags, enum CodecID id)
02125 {
02126     int i;
02127     for(i=0; tags && tags[i]; i++){
02128         int tag= ff_codec_get_tag(tags[i], id);
02129         if(tag) return tag;
02130     }
02131     return 0;
02132 }
02133 
02134 enum CodecID av_codec_get_id(const AVCodecTag * const *tags, unsigned int tag)
02135 {
02136     int i;
02137     for(i=0; tags && tags[i]; i++){
02138         enum CodecID id= ff_codec_get_id(tags[i], tag);
02139         if(id!=CODEC_ID_NONE) return id;
02140     }
02141     return CODEC_ID_NONE;
02142 }
02143 
02144 static void compute_chapters_end(AVFormatContext *s)
02145 {
02146     unsigned int i;
02147 
02148     for (i=0; i+1<s->nb_chapters; i++)
02149         if (s->chapters[i]->end == AV_NOPTS_VALUE) {
02150             assert(s->chapters[i]->start <= s->chapters[i+1]->start);
02151             assert(!av_cmp_q(s->chapters[i]->time_base, s->chapters[i+1]->time_base));
02152             s->chapters[i]->end = s->chapters[i+1]->start;
02153         }
02154 
02155     if (s->nb_chapters && s->chapters[i]->end == AV_NOPTS_VALUE) {
02156         assert(s->start_time != AV_NOPTS_VALUE);
02157         assert(s->duration > 0);
02158         s->chapters[i]->end = av_rescale_q(s->start_time + s->duration,
02159                                            AV_TIME_BASE_Q,
02160                                            s->chapters[i]->time_base);
02161     }
02162 }
02163 
02164 static int get_std_framerate(int i){
02165     if(i<60*12) return i*1001;
02166     else        return ((const int[]){24,30,60,12,15})[i-60*12]*1000*12;
02167 }
02168 
02169 /*
02170  * Is the time base unreliable.
02171  * This is a heuristic to balance between quick acceptance of the values in
02172  * the headers vs. some extra checks.
02173  * Old DivX and Xvid often have nonsense timebases like 1fps or 2fps.
02174  * MPEG-2 commonly misuses field repeat flags to store different framerates.
02175  * And there are "variable" fps files this needs to detect as well.
02176  */
02177 static int tb_unreliable(AVCodecContext *c){
02178     if(   c->time_base.den >= 101L*c->time_base.num
02179        || c->time_base.den <    5L*c->time_base.num
02180 /*       || c->codec_tag == AV_RL32("DIVX")
02181        || c->codec_tag == AV_RL32("XVID")*/
02182        || c->codec_id == CODEC_ID_MPEG2VIDEO
02183        || c->codec_id == CODEC_ID_H264
02184        )
02185         return 1;
02186     return 0;
02187 }
02188 
02189 int av_find_stream_info(AVFormatContext *ic)
02190 {
02191     int i, count, ret, read_size, j;
02192     AVStream *st;
02193     AVPacket pkt1, *pkt;
02194     int64_t old_offset = url_ftell(ic->pb);
02195 
02196     for(i=0;i<ic->nb_streams;i++) {
02197         AVCodec *codec;
02198         st = ic->streams[i];
02199         if (st->codec->codec_id == CODEC_ID_AAC) {
02200             st->codec->sample_rate = 0;
02201             st->codec->frame_size = 0;
02202             st->codec->channels = 0;
02203         }
02204         if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO ||
02205             st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
02206 /*            if(!st->time_base.num)
02207                 st->time_base= */
02208             if(!st->codec->time_base.num)
02209                 st->codec->time_base= st->time_base;
02210         }
02211         //only for the split stuff
02212         if (!st->parser && !(ic->flags & AVFMT_FLAG_NOPARSE)) {
02213             st->parser = av_parser_init(st->codec->codec_id);
02214             if(st->need_parsing == AVSTREAM_PARSE_HEADERS && st->parser){
02215                 st->parser->flags |= PARSER_FLAG_COMPLETE_FRAMES;
02216             }
02217         }
02218         assert(!st->codec->codec);
02219         codec = avcodec_find_decoder(st->codec->codec_id);
02220 
02221         /* Force decoding of at least one frame of codec data
02222          * this makes sure the codec initializes the channel configuration
02223          * and does not trust the values from the container.
02224          */
02225         if (codec && codec->capabilities & CODEC_CAP_CHANNEL_CONF)
02226             st->codec->channels = 0;
02227 
02228         /* Ensure that subtitle_header is properly set. */
02229         if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE
02230             && codec && !st->codec->codec)
02231             avcodec_open(st->codec, codec);
02232 
02233         //try to just open decoders, in case this is enough to get parameters
02234         if(!has_codec_parameters(st->codec)){
02235             if (codec && !st->codec->codec)
02236                 avcodec_open(st->codec, codec);
02237         }
02238     }
02239 
02240     for (i=0; i<ic->nb_streams; i++) {
02241         ic->streams[i]->info->last_dts = AV_NOPTS_VALUE;
02242     }
02243 
02244     count = 0;
02245     read_size = 0;
02246     for(;;) {
02247         if(url_interrupt_cb()){
02248             ret= AVERROR(EINTR);
02249             av_log(ic, AV_LOG_DEBUG, "interrupted\n");
02250             break;
02251         }
02252 
02253         /* check if one codec still needs to be handled */
02254         for(i=0;i<ic->nb_streams;i++) {
02255             st = ic->streams[i];
02256             if (!has_codec_parameters(st->codec))
02257                 break;
02258             /* variable fps and no guess at the real fps */
02259             if(   tb_unreliable(st->codec) && !(st->r_frame_rate.num && st->avg_frame_rate.num)
02260                && st->info->duration_count<20 && st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
02261                 break;
02262             if(st->parser && st->parser->parser->split && !st->codec->extradata)
02263                 break;
02264             if(st->first_dts == AV_NOPTS_VALUE)
02265                 break;
02266         }
02267         if (i == ic->nb_streams) {
02268             /* NOTE: if the format has no header, then we need to read
02269                some packets to get most of the streams, so we cannot
02270                stop here */
02271             if (!(ic->ctx_flags & AVFMTCTX_NOHEADER)) {
02272                 /* if we found the info for all the codecs, we can stop */
02273                 ret = count;
02274                 av_log(ic, AV_LOG_DEBUG, "All info found\n");
02275                 break;
02276             }
02277         }
02278         /* we did not get all the codec info, but we read too much data */
02279         if (read_size >= ic->probesize) {
02280             ret = count;
02281             av_log(ic, AV_LOG_DEBUG, "Probe buffer size limit %d reached\n", ic->probesize);
02282             break;
02283         }
02284 
02285         /* NOTE: a new stream can be added there if no header in file
02286            (AVFMTCTX_NOHEADER) */
02287         ret = av_read_frame_internal(ic, &pkt1);
02288         if (ret < 0 && ret != AVERROR(EAGAIN)) {
02289             /* EOF or error */
02290             ret = -1; /* we could not have all the codec parameters before EOF */
02291             for(i=0;i<ic->nb_streams;i++) {
02292                 st = ic->streams[i];
02293                 if (!has_codec_parameters(st->codec)){
02294                     char buf[256];
02295                     avcodec_string(buf, sizeof(buf), st->codec, 0);
02296                     av_log(ic, AV_LOG_WARNING, "Could not find codec parameters (%s)\n", buf);
02297                 } else {
02298                     ret = 0;
02299                 }
02300             }
02301             break;
02302         }
02303 
02304         if (ret == AVERROR(EAGAIN))
02305             continue;
02306 
02307         pkt= add_to_pktbuf(&ic->packet_buffer, &pkt1, &ic->packet_buffer_end);
02308         if ((ret = av_dup_packet(pkt)) < 0)
02309             goto find_stream_info_err;
02310 
02311         read_size += pkt->size;
02312 
02313         st = ic->streams[pkt->stream_index];
02314         if (st->codec_info_nb_frames>1) {
02315             if (st->time_base.den > 0 && av_rescale_q(st->info->codec_info_duration, st->time_base, AV_TIME_BASE_Q) >= ic->max_analyze_duration) {
02316                 av_log(ic, AV_LOG_WARNING, "max_analyze_duration reached\n");
02317                 break;
02318             }
02319             st->info->codec_info_duration += pkt->duration;
02320         }
02321         {
02322             int64_t last = st->info->last_dts;
02323             int64_t duration= pkt->dts - last;
02324 
02325             if(pkt->dts != AV_NOPTS_VALUE && last != AV_NOPTS_VALUE && duration>0){
02326                 double dur= duration * av_q2d(st->time_base);
02327 
02328 //                if(st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
02329 //                    av_log(NULL, AV_LOG_ERROR, "%f\n", dur);
02330                 if (st->info->duration_count < 2)
02331                     memset(st->info->duration_error, 0, sizeof(st->info->duration_error));
02332                 for (i=1; i<FF_ARRAY_ELEMS(st->info->duration_error); i++) {
02333                     int framerate= get_std_framerate(i);
02334                     int ticks= lrintf(dur*framerate/(1001*12));
02335                     double error= dur - ticks*1001*12/(double)framerate;
02336                     st->info->duration_error[i] += error*error;
02337                 }
02338                 st->info->duration_count++;
02339                 // ignore the first 4 values, they might have some random jitter
02340                 if (st->info->duration_count > 3)
02341                     st->info->duration_gcd = av_gcd(st->info->duration_gcd, duration);
02342             }
02343             if (last == AV_NOPTS_VALUE || st->info->duration_count <= 1)
02344                 st->info->last_dts = pkt->dts;
02345         }
02346         if(st->parser && st->parser->parser->split && !st->codec->extradata){
02347             int i= st->parser->parser->split(st->codec, pkt->data, pkt->size);
02348             if(i){
02349                 st->codec->extradata_size= i;
02350                 st->codec->extradata= av_malloc(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
02351                 memcpy(st->codec->extradata, pkt->data, st->codec->extradata_size);
02352                 memset(st->codec->extradata + i, 0, FF_INPUT_BUFFER_PADDING_SIZE);
02353             }
02354         }
02355 
02356         /* if still no information, we try to open the codec and to
02357            decompress the frame. We try to avoid that in most cases as
02358            it takes longer and uses more memory. For MPEG-4, we need to
02359            decompress for QuickTime. */
02360         if (!has_codec_parameters(st->codec) || !has_decode_delay_been_guessed(st))
02361             try_decode_frame(st, pkt);
02362 
02363         st->codec_info_nb_frames++;
02364         count++;
02365     }
02366 
02367     // close codecs which were opened in try_decode_frame()
02368     for(i=0;i<ic->nb_streams;i++) {
02369         st = ic->streams[i];
02370         if(st->codec->codec)
02371             avcodec_close(st->codec);
02372     }
02373     for(i=0;i<ic->nb_streams;i++) {
02374         st = ic->streams[i];
02375         if (st->codec_info_nb_frames>2 && !st->avg_frame_rate.num && st->info->codec_info_duration)
02376             av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
02377                      (st->codec_info_nb_frames-2)*(int64_t)st->time_base.den,
02378                       st->info->codec_info_duration*(int64_t)st->time_base.num, 60000);
02379         if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
02380             if(st->codec->codec_id == CODEC_ID_RAWVIDEO && !st->codec->codec_tag && !st->codec->bits_per_coded_sample)
02381                 st->codec->codec_tag= avcodec_pix_fmt_to_codec_tag(st->codec->pix_fmt);
02382 
02383             // the check for tb_unreliable() is not completely correct, since this is not about handling
02384             // a unreliable/inexact time base, but a time base that is finer than necessary, as e.g.
02385             // ipmovie.c produces.
02386             if (tb_unreliable(st->codec) && st->info->duration_count > 15 && st->info->duration_gcd > 1 && !st->r_frame_rate.num)
02387                 av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den, st->time_base.den, st->time_base.num * st->info->duration_gcd, INT_MAX);
02388             if (st->info->duration_count && !st->r_frame_rate.num
02389                && tb_unreliable(st->codec) /*&&
02390                //FIXME we should not special-case MPEG-2, but this needs testing with non-MPEG-2 ...
02391                st->time_base.num*duration_sum[i]/st->info->duration_count*101LL > st->time_base.den*/){
02392                 int num = 0;
02393                 double best_error= 2*av_q2d(st->time_base);
02394                 best_error = best_error*best_error*st->info->duration_count*1000*12*30;
02395 
02396                 for (j=1; j<FF_ARRAY_ELEMS(st->info->duration_error); j++) {
02397                     double error = st->info->duration_error[j] * get_std_framerate(j);
02398 //                    if(st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
02399 //                        av_log(NULL, AV_LOG_ERROR, "%f %f\n", get_std_framerate(j) / 12.0/1001, error);
02400                     if(error < best_error){
02401                         best_error= error;
02402                         num = get_std_framerate(j);
02403                     }
02404                 }
02405                 // do not increase frame rate by more than 1 % in order to match a standard rate.
02406                 if (num && (!st->r_frame_rate.num || (double)num/(12*1001) < 1.01 * av_q2d(st->r_frame_rate)))
02407                     av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den, num, 12*1001, INT_MAX);
02408             }
02409 
02410             if (!st->r_frame_rate.num){
02411                 if(    st->codec->time_base.den * (int64_t)st->time_base.num
02412                     <= st->codec->time_base.num * st->codec->ticks_per_frame * (int64_t)st->time_base.den){
02413                     st->r_frame_rate.num = st->codec->time_base.den;
02414                     st->r_frame_rate.den = st->codec->time_base.num * st->codec->ticks_per_frame;
02415                 }else{
02416                     st->r_frame_rate.num = st->time_base.den;
02417                     st->r_frame_rate.den = st->time_base.num;
02418                 }
02419             }
02420         }else if(st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
02421             if(!st->codec->bits_per_coded_sample)
02422                 st->codec->bits_per_coded_sample= av_get_bits_per_sample(st->codec->codec_id);
02423         }
02424     }
02425 
02426     av_estimate_timings(ic, old_offset);
02427 
02428     compute_chapters_end(ic);
02429 
02430 #if 0
02431     /* correct DTS for B-frame streams with no timestamps */
02432     for(i=0;i<ic->nb_streams;i++) {
02433         st = ic->streams[i];
02434         if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
02435             if(b-frames){
02436                 ppktl = &ic->packet_buffer;
02437                 while(ppkt1){
02438                     if(ppkt1->stream_index != i)
02439                         continue;
02440                     if(ppkt1->pkt->dts < 0)
02441                         break;
02442                     if(ppkt1->pkt->pts != AV_NOPTS_VALUE)
02443                         break;
02444                     ppkt1->pkt->dts -= delta;
02445                     ppkt1= ppkt1->next;
02446                 }
02447                 if(ppkt1)
02448                     continue;
02449                 st->cur_dts -= delta;
02450             }
02451         }
02452     }
02453 #endif
02454 
02455  find_stream_info_err:
02456     for (i=0; i < ic->nb_streams; i++)
02457         av_freep(&ic->streams[i]->info);
02458     return ret;
02459 }
02460 
02461 static AVProgram *find_program_from_stream(AVFormatContext *ic, int s)
02462 {
02463     int i, j;
02464 
02465     for (i = 0; i < ic->nb_programs; i++)
02466         for (j = 0; j < ic->programs[i]->nb_stream_indexes; j++)
02467             if (ic->programs[i]->stream_index[j] == s)
02468                 return ic->programs[i];
02469     return NULL;
02470 }
02471 
02472 int av_find_best_stream(AVFormatContext *ic,
02473                         enum AVMediaType type,
02474                         int wanted_stream_nb,
02475                         int related_stream,
02476                         AVCodec **decoder_ret,
02477                         int flags)
02478 {
02479     int i, nb_streams = ic->nb_streams, stream_number = 0;
02480     int ret = AVERROR_STREAM_NOT_FOUND, best_count = -1;
02481     unsigned *program = NULL;
02482     AVCodec *decoder = NULL, *best_decoder = NULL;
02483 
02484     if (related_stream >= 0 && wanted_stream_nb < 0) {
02485         AVProgram *p = find_program_from_stream(ic, related_stream);
02486         if (p) {
02487             program = p->stream_index;
02488             nb_streams = p->nb_stream_indexes;
02489         }
02490     }
02491     for (i = 0; i < nb_streams; i++) {
02492         AVStream *st = ic->streams[program ? program[i] : i];
02493         AVCodecContext *avctx = st->codec;
02494         if (avctx->codec_type != type)
02495             continue;
02496         if (wanted_stream_nb >= 0 && stream_number++ != wanted_stream_nb)
02497             continue;
02498         if (decoder_ret) {
02499             decoder = avcodec_find_decoder(ic->streams[i]->codec->codec_id);
02500             if (!decoder) {
02501                 if (ret < 0)
02502                     ret = AVERROR_DECODER_NOT_FOUND;
02503                 continue;
02504             }
02505         }
02506         if (best_count >= st->codec_info_nb_frames)
02507             continue;
02508         best_count = st->codec_info_nb_frames;
02509         ret = i;
02510         best_decoder = decoder;
02511         if (program && i == nb_streams - 1 && ret < 0) {
02512             program = NULL;
02513             nb_streams = ic->nb_streams;
02514             i = 0; /* no related stream found, try again with everything */
02515         }
02516     }
02517     if (decoder_ret)
02518         *decoder_ret = best_decoder;
02519     return ret;
02520 }
02521 
02522 /*******************************************************/
02523 
02524 int av_read_play(AVFormatContext *s)
02525 {
02526     if (s->iformat->read_play)
02527         return s->iformat->read_play(s);
02528     if (s->pb)
02529         return av_url_read_fpause(s->pb, 0);
02530     return AVERROR(ENOSYS);
02531 }
02532 
02533 int av_read_pause(AVFormatContext *s)
02534 {
02535     if (s->iformat->read_pause)
02536         return s->iformat->read_pause(s);
02537     if (s->pb)
02538         return av_url_read_fpause(s->pb, 1);
02539     return AVERROR(ENOSYS);
02540 }
02541 
02542 void av_close_input_stream(AVFormatContext *s)
02543 {
02544     int i;
02545     AVStream *st;
02546 
02547     flush_packet_queue(s);
02548     if (s->iformat->read_close)
02549         s->iformat->read_close(s);
02550     for(i=0;i<s->nb_streams;i++) {
02551         /* free all data in a stream component */
02552         st = s->streams[i];
02553         if (st->parser) {
02554             av_parser_close(st->parser);
02555             av_free_packet(&st->cur_pkt);
02556         }
02557         av_metadata_free(&st->metadata);
02558         av_free(st->index_entries);
02559         av_free(st->codec->extradata);
02560         av_free(st->codec->subtitle_header);
02561         av_free(st->codec);
02562 #if FF_API_OLD_METADATA
02563         av_free(st->filename);
02564 #endif
02565         av_free(st->priv_data);
02566         av_free(st->info);
02567         av_free(st);
02568     }
02569     for(i=s->nb_programs-1; i>=0; i--) {
02570 #if FF_API_OLD_METADATA
02571         av_freep(&s->programs[i]->provider_name);
02572         av_freep(&s->programs[i]->name);
02573 #endif
02574         av_metadata_free(&s->programs[i]->metadata);
02575         av_freep(&s->programs[i]->stream_index);
02576         av_freep(&s->programs[i]);
02577     }
02578     av_freep(&s->programs);
02579     av_freep(&s->priv_data);
02580     while(s->nb_chapters--) {
02581 #if FF_API_OLD_METADATA
02582         av_free(s->chapters[s->nb_chapters]->title);
02583 #endif
02584         av_metadata_free(&s->chapters[s->nb_chapters]->metadata);
02585         av_free(s->chapters[s->nb_chapters]);
02586     }
02587     av_freep(&s->chapters);
02588     av_metadata_free(&s->metadata);
02589     av_freep(&s->key);
02590     av_free(s);
02591 }
02592 
02593 void av_close_input_file(AVFormatContext *s)
02594 {
02595     ByteIOContext *pb = s->iformat->flags & AVFMT_NOFILE ? NULL : s->pb;
02596     av_close_input_stream(s);
02597     if (pb)
02598         url_fclose(pb);
02599 }
02600 
02601 AVStream *av_new_stream(AVFormatContext *s, int id)
02602 {
02603     AVStream *st;
02604     int i;
02605 
02606 #if FF_API_MAX_STREAMS
02607     if (s->nb_streams >= MAX_STREAMS){
02608         av_log(s, AV_LOG_ERROR, "Too many streams\n");
02609         return NULL;
02610     }
02611 #else
02612     AVStream **streams;
02613 
02614     if (s->nb_streams >= INT_MAX/sizeof(*streams))
02615         return NULL;
02616     streams = av_realloc(s->streams, (s->nb_streams + 1) * sizeof(*streams));
02617     if (!streams)
02618         return NULL;
02619     s->streams = streams;
02620 #endif
02621 
02622     st = av_mallocz(sizeof(AVStream));
02623     if (!st)
02624         return NULL;
02625     if (!(st->info = av_mallocz(sizeof(*st->info)))) {
02626         av_free(st);
02627         return NULL;
02628     }
02629 
02630     st->codec= avcodec_alloc_context();
02631     if (s->iformat) {
02632         /* no default bitrate if decoding */
02633         st->codec->bit_rate = 0;
02634     }
02635     st->index = s->nb_streams;
02636     st->id = id;
02637     st->start_time = AV_NOPTS_VALUE;
02638     st->duration = AV_NOPTS_VALUE;
02639         /* we set the current DTS to 0 so that formats without any timestamps
02640            but durations get some timestamps, formats with some unknown
02641            timestamps have their first few packets buffered and the
02642            timestamps corrected before they are returned to the user */
02643     st->cur_dts = 0;
02644     st->first_dts = AV_NOPTS_VALUE;
02645     st->probe_packets = MAX_PROBE_PACKETS;
02646 
02647     /* default pts setting is MPEG-like */
02648     av_set_pts_info(st, 33, 1, 90000);
02649     st->last_IP_pts = AV_NOPTS_VALUE;
02650     for(i=0; i<MAX_REORDER_DELAY+1; i++)
02651         st->pts_buffer[i]= AV_NOPTS_VALUE;
02652     st->reference_dts = AV_NOPTS_VALUE;
02653 
02654     st->sample_aspect_ratio = (AVRational){0,1};
02655 
02656     s->streams[s->nb_streams++] = st;
02657     return st;
02658 }
02659 
02660 AVProgram *av_new_program(AVFormatContext *ac, int id)
02661 {
02662     AVProgram *program=NULL;
02663     int i;
02664 
02665 #ifdef DEBUG_SI
02666     av_log(ac, AV_LOG_DEBUG, "new_program: id=0x%04x\n", id);
02667 #endif
02668 
02669     for(i=0; i<ac->nb_programs; i++)
02670         if(ac->programs[i]->id == id)
02671             program = ac->programs[i];
02672 
02673     if(!program){
02674         program = av_mallocz(sizeof(AVProgram));
02675         if (!program)
02676             return NULL;
02677         dynarray_add(&ac->programs, &ac->nb_programs, program);
02678         program->discard = AVDISCARD_NONE;
02679     }
02680     program->id = id;
02681 
02682     return program;
02683 }
02684 
02685 AVChapter *ff_new_chapter(AVFormatContext *s, int id, AVRational time_base, int64_t start, int64_t end, const char *title)
02686 {
02687     AVChapter *chapter = NULL;
02688     int i;
02689 
02690     for(i=0; i<s->nb_chapters; i++)
02691         if(s->chapters[i]->id == id)
02692             chapter = s->chapters[i];
02693 
02694     if(!chapter){
02695         chapter= av_mallocz(sizeof(AVChapter));
02696         if(!chapter)
02697             return NULL;
02698         dynarray_add(&s->chapters, &s->nb_chapters, chapter);
02699     }
02700 #if FF_API_OLD_METADATA
02701     av_free(chapter->title);
02702 #endif
02703     av_metadata_set2(&chapter->metadata, "title", title, 0);
02704     chapter->id    = id;
02705     chapter->time_base= time_base;
02706     chapter->start = start;
02707     chapter->end   = end;
02708 
02709     return chapter;
02710 }
02711 
02712 /************************************************************/
02713 /* output media file */
02714 
02715 int av_set_parameters(AVFormatContext *s, AVFormatParameters *ap)
02716 {
02717     int ret;
02718 
02719     if (s->oformat->priv_data_size > 0) {
02720         s->priv_data = av_mallocz(s->oformat->priv_data_size);
02721         if (!s->priv_data)
02722             return AVERROR(ENOMEM);
02723         if (s->oformat->priv_class) {
02724             *(const AVClass**)s->priv_data= s->oformat->priv_class;
02725             av_opt_set_defaults(s->priv_data);
02726         }
02727     } else
02728         s->priv_data = NULL;
02729 
02730     if (s->oformat->set_parameters) {
02731         ret = s->oformat->set_parameters(s, ap);
02732         if (ret < 0)
02733             return ret;
02734     }
02735     return 0;
02736 }
02737 
02738 static int validate_codec_tag(AVFormatContext *s, AVStream *st)
02739 {
02740     const AVCodecTag *avctag;
02741     int n;
02742     enum CodecID id = CODEC_ID_NONE;
02743     unsigned int tag = 0;
02744 
02751     for (n = 0; s->oformat->codec_tag[n]; n++) {
02752         avctag = s->oformat->codec_tag[n];
02753         while (avctag->id != CODEC_ID_NONE) {
02754             if (ff_toupper4(avctag->tag) == ff_toupper4(st->codec->codec_tag)) {
02755                 id = avctag->id;
02756                 if (id == st->codec->codec_id)
02757                     return 1;
02758             }
02759             if (avctag->id == st->codec->codec_id)
02760                 tag = avctag->tag;
02761             avctag++;
02762         }
02763     }
02764     if (id != CODEC_ID_NONE)
02765         return 0;
02766     if (tag && (st->codec->strict_std_compliance >= FF_COMPLIANCE_NORMAL))
02767         return 0;
02768     return 1;
02769 }
02770 
02771 int av_write_header(AVFormatContext *s)
02772 {
02773     int ret, i;
02774     AVStream *st;
02775 
02776     // some sanity checks
02777     if (s->nb_streams == 0 && !(s->oformat->flags & AVFMT_NOSTREAMS)) {
02778         av_log(s, AV_LOG_ERROR, "no streams\n");
02779         return AVERROR(EINVAL);
02780     }
02781 
02782     for(i=0;i<s->nb_streams;i++) {
02783         st = s->streams[i];
02784 
02785         switch (st->codec->codec_type) {
02786         case AVMEDIA_TYPE_AUDIO:
02787             if(st->codec->sample_rate<=0){
02788                 av_log(s, AV_LOG_ERROR, "sample rate not set\n");
02789                 return AVERROR(EINVAL);
02790             }
02791             if(!st->codec->block_align)
02792                 st->codec->block_align = st->codec->channels *
02793                     av_get_bits_per_sample(st->codec->codec_id) >> 3;
02794             break;
02795         case AVMEDIA_TYPE_VIDEO:
02796             if(st->codec->time_base.num<=0 || st->codec->time_base.den<=0){ //FIXME audio too?
02797                 av_log(s, AV_LOG_ERROR, "time base not set\n");
02798                 return AVERROR(EINVAL);
02799             }
02800             if((st->codec->width<=0 || st->codec->height<=0) && !(s->oformat->flags & AVFMT_NODIMENSIONS)){
02801                 av_log(s, AV_LOG_ERROR, "dimensions not set\n");
02802                 return AVERROR(EINVAL);
02803             }
02804             if(av_cmp_q(st->sample_aspect_ratio, st->codec->sample_aspect_ratio)){
02805                 av_log(s, AV_LOG_ERROR, "Aspect ratio mismatch between encoder and muxer layer\n");
02806                 return AVERROR(EINVAL);
02807             }
02808             break;
02809         }
02810 
02811         if(s->oformat->codec_tag){
02812             if(st->codec->codec_tag && st->codec->codec_id == CODEC_ID_RAWVIDEO && av_codec_get_tag(s->oformat->codec_tag, st->codec->codec_id) == 0 && !validate_codec_tag(s, st)){
02813                 //the current rawvideo encoding system ends up setting the wrong codec_tag for avi, we override it here
02814                 st->codec->codec_tag= 0;
02815             }
02816             if(st->codec->codec_tag){
02817                 if (!validate_codec_tag(s, st)) {
02818                     char tagbuf[32];
02819                     av_get_codec_tag_string(tagbuf, sizeof(tagbuf), st->codec->codec_tag);
02820                     av_log(s, AV_LOG_ERROR,
02821                            "Tag %s/0x%08x incompatible with output codec id '%d'\n",
02822                            tagbuf, st->codec->codec_tag, st->codec->codec_id);
02823                     return AVERROR_INVALIDDATA;
02824                 }
02825             }else
02826                 st->codec->codec_tag= av_codec_get_tag(s->oformat->codec_tag, st->codec->codec_id);
02827         }
02828 
02829         if(s->oformat->flags & AVFMT_GLOBALHEADER &&
02830             !(st->codec->flags & CODEC_FLAG_GLOBAL_HEADER))
02831           av_log(s, AV_LOG_WARNING, "Codec for stream %d does not use global headers but container format requires global headers\n", i);
02832     }
02833 
02834     if (!s->priv_data && s->oformat->priv_data_size > 0) {
02835         s->priv_data = av_mallocz(s->oformat->priv_data_size);
02836         if (!s->priv_data)
02837             return AVERROR(ENOMEM);
02838     }
02839 
02840 #if FF_API_OLD_METADATA
02841     ff_metadata_mux_compat(s);
02842 #endif
02843 
02844     /* set muxer identification string */
02845     if (s->nb_streams && !(s->streams[0]->codec->flags & CODEC_FLAG_BITEXACT)) {
02846         av_metadata_set2(&s->metadata, "encoder", LIBAVFORMAT_IDENT, 0);
02847     }
02848 
02849     if(s->oformat->write_header){
02850         ret = s->oformat->write_header(s);
02851         if (ret < 0)
02852             return ret;
02853     }
02854 
02855     /* init PTS generation */
02856     for(i=0;i<s->nb_streams;i++) {
02857         int64_t den = AV_NOPTS_VALUE;
02858         st = s->streams[i];
02859 
02860         switch (st->codec->codec_type) {
02861         case AVMEDIA_TYPE_AUDIO:
02862             den = (int64_t)st->time_base.num * st->codec->sample_rate;
02863             break;
02864         case AVMEDIA_TYPE_VIDEO:
02865             den = (int64_t)st->time_base.num * st->codec->time_base.den;
02866             break;
02867         default:
02868             break;
02869         }
02870         if (den != AV_NOPTS_VALUE) {
02871             if (den <= 0)
02872                 return AVERROR_INVALIDDATA;
02873             av_frac_init(&st->pts, 0, 0, den);
02874         }
02875     }
02876     return 0;
02877 }
02878 
02879 //FIXME merge with compute_pkt_fields
02880 static int compute_pkt_fields2(AVFormatContext *s, AVStream *st, AVPacket *pkt){
02881     int delay = FFMAX(st->codec->has_b_frames, !!st->codec->max_b_frames);
02882     int num, den, frame_size, i;
02883 
02884 //    av_log(s, AV_LOG_DEBUG, "av_write_frame: pts:%"PRId64" dts:%"PRId64" cur_dts:%"PRId64" b:%d size:%d st:%d\n", pkt->pts, pkt->dts, st->cur_dts, delay, pkt->size, pkt->stream_index);
02885 
02886 /*    if(pkt->pts == AV_NOPTS_VALUE && pkt->dts == AV_NOPTS_VALUE)
02887         return -1;*/
02888 
02889     /* duration field */
02890     if (pkt->duration == 0) {
02891         compute_frame_duration(&num, &den, st, NULL, pkt);
02892         if (den && num) {
02893             pkt->duration = av_rescale(1, num * (int64_t)st->time_base.den * st->codec->ticks_per_frame, den * (int64_t)st->time_base.num);
02894         }
02895     }
02896 
02897     if(pkt->pts == AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE && delay==0)
02898         pkt->pts= pkt->dts;
02899 
02900     //XXX/FIXME this is a temporary hack until all encoders output pts
02901     if((pkt->pts == 0 || pkt->pts == AV_NOPTS_VALUE) && pkt->dts == AV_NOPTS_VALUE && !delay){
02902         pkt->dts=
02903 //        pkt->pts= st->cur_dts;
02904         pkt->pts= st->pts.val;
02905     }
02906 
02907     //calculate dts from pts
02908     if(pkt->pts != AV_NOPTS_VALUE && pkt->dts == AV_NOPTS_VALUE && delay <= MAX_REORDER_DELAY){
02909         st->pts_buffer[0]= pkt->pts;
02910         for(i=1; i<delay+1 && st->pts_buffer[i] == AV_NOPTS_VALUE; i++)
02911             st->pts_buffer[i]= pkt->pts + (i-delay-1) * pkt->duration;
02912         for(i=0; i<delay && st->pts_buffer[i] > st->pts_buffer[i+1]; i++)
02913             FFSWAP(int64_t, st->pts_buffer[i], st->pts_buffer[i+1]);
02914 
02915         pkt->dts= st->pts_buffer[0];
02916     }
02917 
02918     if(st->cur_dts && st->cur_dts != AV_NOPTS_VALUE && st->cur_dts >= pkt->dts){
02919         av_log(s, AV_LOG_ERROR,
02920                "Application provided invalid, non monotonically increasing dts to muxer in stream %d: %"PRId64" >= %"PRId64"\n",
02921                st->index, st->cur_dts, pkt->dts);
02922         return -1;
02923     }
02924     if(pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE && pkt->pts < pkt->dts){
02925         av_log(s, AV_LOG_ERROR, "pts < dts in stream %d\n", st->