• Main Page
  • Related Pages
  • Modules
  • Data Structures
  • Files
  • Examples
  • File List
  • Globals

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 
00022 /* #define DEBUG */
00023 
00024 #include "avformat.h"
00025 #include "avio_internal.h"
00026 #include "internal.h"
00027 #include "libavcodec/internal.h"
00028 #include "libavcodec/raw.h"
00029 #include "libavutil/opt.h"
00030 #include "libavutil/dict.h"
00031 #include "libavutil/pixdesc.h"
00032 #include "metadata.h"
00033 #include "id3v2.h"
00034 #include "libavutil/avstring.h"
00035 #include "riff.h"
00036 #include "audiointerleave.h"
00037 #include "url.h"
00038 #include <sys/time.h>
00039 #include <time.h>
00040 #include <strings.h>
00041 #include <stdarg.h>
00042 #if CONFIG_NETWORK
00043 #include "network.h"
00044 #endif
00045 
00046 #undef NDEBUG
00047 #include <assert.h>
00048 
00054 unsigned avformat_version(void)
00055 {
00056     return LIBAVFORMAT_VERSION_INT;
00057 }
00058 
00059 const char *avformat_configuration(void)
00060 {
00061     return FFMPEG_CONFIGURATION;
00062 }
00063 
00064 const char *avformat_license(void)
00065 {
00066 #define LICENSE_PREFIX "libavformat license: "
00067     return LICENSE_PREFIX FFMPEG_LICENSE + sizeof(LICENSE_PREFIX) - 1;
00068 }
00069 
00070 /* fraction handling */
00071 
00082 static void av_frac_init(AVFrac *f, int64_t val, int64_t num, int64_t den)
00083 {
00084     num += (den >> 1);
00085     if (num >= den) {
00086         val += num / den;
00087         num = num % den;
00088     }
00089     f->val = val;
00090     f->num = num;
00091     f->den = den;
00092 }
00093 
00100 static void av_frac_add(AVFrac *f, int64_t incr)
00101 {
00102     int64_t num, den;
00103 
00104     num = f->num + incr;
00105     den = f->den;
00106     if (num < 0) {
00107         f->val += num / den;
00108         num = num % den;
00109         if (num < 0) {
00110             num += den;
00111             f->val--;
00112         }
00113     } else if (num >= den) {
00114         f->val += num / den;
00115         num = num % den;
00116     }
00117     f->num = num;
00118 }
00119 
00121 #if !FF_API_FIRST_FORMAT
00122 static
00123 #endif
00124 AVInputFormat *first_iformat = NULL;
00126 #if !FF_API_FIRST_FORMAT
00127 static
00128 #endif
00129 AVOutputFormat *first_oformat = NULL;
00130 
00131 AVInputFormat  *av_iformat_next(AVInputFormat  *f)
00132 {
00133     if(f) return f->next;
00134     else  return first_iformat;
00135 }
00136 
00137 AVOutputFormat *av_oformat_next(AVOutputFormat *f)
00138 {
00139     if(f) return f->next;
00140     else  return first_oformat;
00141 }
00142 
00143 void av_register_input_format(AVInputFormat *format)
00144 {
00145     AVInputFormat **p;
00146     p = &first_iformat;
00147     while (*p != NULL) p = &(*p)->next;
00148     *p = format;
00149     format->next = NULL;
00150 }
00151 
00152 void av_register_output_format(AVOutputFormat *format)
00153 {
00154     AVOutputFormat **p;
00155     p = &first_oformat;
00156     while (*p != NULL) p = &(*p)->next;
00157     *p = format;
00158     format->next = NULL;
00159 }
00160 
00161 int av_match_ext(const char *filename, const char *extensions)
00162 {
00163     const char *ext, *p;
00164     char ext1[32], *q;
00165 
00166     if(!filename)
00167         return 0;
00168 
00169     ext = strrchr(filename, '.');
00170     if (ext) {
00171         ext++;
00172         p = extensions;
00173         for(;;) {
00174             q = ext1;
00175             while (*p != '\0' && *p != ',' && q-ext1<sizeof(ext1)-1)
00176                 *q++ = *p++;
00177             *q = '\0';
00178             if (!strcasecmp(ext1, ext))
00179                 return 1;
00180             if (*p == '\0')
00181                 break;
00182             p++;
00183         }
00184     }
00185     return 0;
00186 }
00187 
00188 static int match_format(const char *name, const char *names)
00189 {
00190     const char *p;
00191     int len, namelen;
00192 
00193     if (!name || !names)
00194         return 0;
00195 
00196     namelen = strlen(name);
00197     while ((p = strchr(names, ','))) {
00198         len = FFMAX(p - names, namelen);
00199         if (!strncasecmp(name, names, len))
00200             return 1;
00201         names = p+1;
00202     }
00203     return !strcasecmp(name, names);
00204 }
00205 
00206 #if FF_API_GUESS_FORMAT
00207 AVOutputFormat *guess_format(const char *short_name, const char *filename,
00208                              const char *mime_type)
00209 {
00210     return av_guess_format(short_name, filename, mime_type);
00211 }
00212 #endif
00213 
00214 AVOutputFormat *av_guess_format(const char *short_name, const char *filename,
00215                                 const char *mime_type)
00216 {
00217     AVOutputFormat *fmt = NULL, *fmt_found;
00218     int score_max, score;
00219 
00220     /* specific test for image sequences */
00221 #if CONFIG_IMAGE2_MUXER
00222     if (!short_name && filename &&
00223         av_filename_number_test(filename) &&
00224         ff_guess_image2_codec(filename) != CODEC_ID_NONE) {
00225         return av_guess_format("image2", NULL, NULL);
00226     }
00227 #endif
00228     /* Find the proper file type. */
00229     fmt_found = NULL;
00230     score_max = 0;
00231     while ((fmt = av_oformat_next(fmt))) {
00232         score = 0;
00233         if (fmt->name && short_name && !strcmp(fmt->name, short_name))
00234             score += 100;
00235         if (fmt->mime_type && mime_type && !strcmp(fmt->mime_type, mime_type))
00236             score += 10;
00237         if (filename && fmt->extensions &&
00238             av_match_ext(filename, fmt->extensions)) {
00239             score += 5;
00240         }
00241         if (score > score_max) {
00242             score_max = score;
00243             fmt_found = fmt;
00244         }
00245     }
00246     return fmt_found;
00247 }
00248 
00249 #if FF_API_GUESS_FORMAT
00250 AVOutputFormat *guess_stream_format(const char *short_name, const char *filename,
00251                              const char *mime_type)
00252 {
00253     AVOutputFormat *fmt = av_guess_format(short_name, filename, mime_type);
00254 
00255     if (fmt) {
00256         AVOutputFormat *stream_fmt;
00257         char stream_format_name[64];
00258 
00259         snprintf(stream_format_name, sizeof(stream_format_name), "%s_stream", fmt->name);
00260         stream_fmt = av_guess_format(stream_format_name, NULL, NULL);
00261 
00262         if (stream_fmt)
00263             fmt = stream_fmt;
00264     }
00265 
00266     return fmt;
00267 }
00268 #endif
00269 
00270 enum CodecID av_guess_codec(AVOutputFormat *fmt, const char *short_name,
00271                             const char *filename, const char *mime_type, enum AVMediaType type){
00272     if(type == AVMEDIA_TYPE_VIDEO){
00273         enum CodecID codec_id= CODEC_ID_NONE;
00274 
00275 #if CONFIG_IMAGE2_MUXER
00276         if(!strcmp(fmt->name, "image2") || !strcmp(fmt->name, "image2pipe")){
00277             codec_id= ff_guess_image2_codec(filename);
00278         }
00279 #endif
00280         if(codec_id == CODEC_ID_NONE)
00281             codec_id= fmt->video_codec;
00282         return codec_id;
00283     }else if(type == AVMEDIA_TYPE_AUDIO)
00284         return fmt->audio_codec;
00285     else if (type == AVMEDIA_TYPE_SUBTITLE)
00286         return fmt->subtitle_codec;
00287     else
00288         return CODEC_ID_NONE;
00289 }
00290 
00291 AVInputFormat *av_find_input_format(const char *short_name)
00292 {
00293     AVInputFormat *fmt = NULL;
00294     while ((fmt = av_iformat_next(fmt))) {
00295         if (match_format(short_name, fmt->name))
00296             return fmt;
00297     }
00298     return NULL;
00299 }
00300 
00301 #if FF_API_SYMVER && CONFIG_SHARED && HAVE_SYMVER
00302 FF_SYMVER(void, av_destruct_packet_nofree, (AVPacket *pkt), "LIBAVFORMAT_52")
00303 {
00304     av_destruct_packet_nofree(pkt);
00305 }
00306 
00307 FF_SYMVER(void, av_destruct_packet, (AVPacket *pkt), "LIBAVFORMAT_52")
00308 {
00309     av_destruct_packet(pkt);
00310 }
00311 
00312 FF_SYMVER(int, av_new_packet, (AVPacket *pkt, int size), "LIBAVFORMAT_52")
00313 {
00314     return av_new_packet(pkt, size);
00315 }
00316 
00317 FF_SYMVER(int, av_dup_packet, (AVPacket *pkt), "LIBAVFORMAT_52")
00318 {
00319     return av_dup_packet(pkt);
00320 }
00321 
00322 FF_SYMVER(void, av_free_packet, (AVPacket *pkt), "LIBAVFORMAT_52")
00323 {
00324     av_free_packet(pkt);
00325 }
00326 
00327 FF_SYMVER(void, av_init_packet, (AVPacket *pkt), "LIBAVFORMAT_52")
00328 {
00329     av_log(NULL, AV_LOG_WARNING, "Diverting av_*_packet function calls to libavcodec. Recompile to improve performance\n");
00330     av_init_packet(pkt);
00331 }
00332 #endif
00333 
00334 int av_get_packet(AVIOContext *s, AVPacket *pkt, int size)
00335 {
00336     int ret= av_new_packet(pkt, size);
00337 
00338     if(ret<0)
00339         return ret;
00340 
00341     pkt->pos= avio_tell(s);
00342 
00343     ret= avio_read(s, pkt->data, size);
00344     if(ret<=0)
00345         av_free_packet(pkt);
00346     else
00347         av_shrink_packet(pkt, ret);
00348 
00349     return ret;
00350 }
00351 
00352 int av_append_packet(AVIOContext *s, AVPacket *pkt, int size)
00353 {
00354     int ret;
00355     int old_size;
00356     if (!pkt->size)
00357         return av_get_packet(s, pkt, size);
00358     old_size = pkt->size;
00359     ret = av_grow_packet(pkt, size);
00360     if (ret < 0)
00361         return ret;
00362     ret = avio_read(s, pkt->data + old_size, size);
00363     av_shrink_packet(pkt, old_size + FFMAX(ret, 0));
00364     return ret;
00365 }
00366 
00367 
00368 int av_filename_number_test(const char *filename)
00369 {
00370     char buf[1024];
00371     return filename && (av_get_frame_filename(buf, sizeof(buf), filename, 1)>=0);
00372 }
00373 
00374 AVInputFormat *av_probe_input_format3(AVProbeData *pd, int is_opened, int *score_ret)
00375 {
00376     AVProbeData lpd = *pd;
00377     AVInputFormat *fmt1 = NULL, *fmt;
00378     int score, score_max=0;
00379 
00380     if (lpd.buf_size > 10 && ff_id3v2_match(lpd.buf, ID3v2_DEFAULT_MAGIC)) {
00381         int id3len = ff_id3v2_tag_len(lpd.buf);
00382         if (lpd.buf_size > id3len + 16) {
00383             lpd.buf += id3len;
00384             lpd.buf_size -= id3len;
00385         }
00386     }
00387 
00388     fmt = NULL;
00389     while ((fmt1 = av_iformat_next(fmt1))) {
00390         if (!is_opened == !(fmt1->flags & AVFMT_NOFILE))
00391             continue;
00392         score = 0;
00393         if (fmt1->read_probe) {
00394             score = fmt1->read_probe(&lpd);
00395             if(!score && fmt1->extensions && av_match_ext(lpd.filename, fmt1->extensions))
00396                 score = 1;
00397         } else if (fmt1->extensions) {
00398             if (av_match_ext(lpd.filename, fmt1->extensions)) {
00399                 score = 50;
00400             }
00401         }
00402         if (score > score_max) {
00403             score_max = score;
00404             fmt = fmt1;
00405         }else if (score == score_max)
00406             fmt = NULL;
00407     }
00408     *score_ret= score_max;
00409     return fmt;
00410 }
00411 
00412 AVInputFormat *av_probe_input_format2(AVProbeData *pd, int is_opened, int *score_max)
00413 {
00414     int score_ret;
00415     AVInputFormat *fmt= av_probe_input_format3(pd, is_opened, &score_ret);
00416     if(score_ret > *score_max){
00417         *score_max= score_ret;
00418         return fmt;
00419     }else
00420         return NULL;
00421 }
00422 
00423 AVInputFormat *av_probe_input_format(AVProbeData *pd, int is_opened){
00424     int score=0;
00425     return av_probe_input_format2(pd, is_opened, &score);
00426 }
00427 
00428 static int set_codec_from_probe_data(AVFormatContext *s, AVStream *st, AVProbeData *pd)
00429 {
00430     static const struct {
00431         const char *name; enum CodecID id; enum AVMediaType type;
00432     } fmt_id_type[] = {
00433         { "aac"      , CODEC_ID_AAC       , AVMEDIA_TYPE_AUDIO },
00434         { "ac3"      , CODEC_ID_AC3       , AVMEDIA_TYPE_AUDIO },
00435         { "dts"      , CODEC_ID_DTS       , AVMEDIA_TYPE_AUDIO },
00436         { "eac3"     , CODEC_ID_EAC3      , AVMEDIA_TYPE_AUDIO },
00437         { "h264"     , CODEC_ID_H264      , AVMEDIA_TYPE_VIDEO },
00438         { "m4v"      , CODEC_ID_MPEG4     , AVMEDIA_TYPE_VIDEO },
00439         { "mp3"      , CODEC_ID_MP3       , AVMEDIA_TYPE_AUDIO },
00440         { "mpegvideo", CODEC_ID_MPEG2VIDEO, AVMEDIA_TYPE_VIDEO },
00441         { 0 }
00442     };
00443     int score;
00444     AVInputFormat *fmt = av_probe_input_format3(pd, 1, &score);
00445 
00446     if (fmt) {
00447         int i;
00448         av_log(s, AV_LOG_DEBUG, "Probe with size=%d, packets=%d detected %s with score=%d\n",
00449                pd->buf_size, MAX_PROBE_PACKETS - st->probe_packets, fmt->name, score);
00450         for (i = 0; fmt_id_type[i].name; i++) {
00451             if (!strcmp(fmt->name, fmt_id_type[i].name)) {
00452                 st->codec->codec_id   = fmt_id_type[i].id;
00453                 st->codec->codec_type = fmt_id_type[i].type;
00454                 break;
00455             }
00456         }
00457     }
00458     return score;
00459 }
00460 
00461 /************************************************************/
00462 /* input media file */
00463 
00464 #if FF_API_FORMAT_PARAMETERS
00465 static AVDictionary *convert_format_parameters(AVFormatParameters *ap)
00466 {
00467     char buf[1024];
00468     AVDictionary *opts = NULL;
00469 
00470     if (!ap)
00471         return NULL;
00472 
00473     if (ap->time_base.num) {
00474         snprintf(buf, sizeof(buf), "%d/%d", ap->time_base.den, ap->time_base.num);
00475         av_dict_set(&opts, "framerate", buf, 0);
00476     }
00477     if (ap->sample_rate) {
00478         snprintf(buf, sizeof(buf), "%d", ap->sample_rate);
00479         av_dict_set(&opts, "sample_rate", buf, 0);
00480     }
00481     if (ap->channels) {
00482         snprintf(buf, sizeof(buf), "%d", ap->channels);
00483         av_dict_set(&opts, "channels", buf, 0);
00484     }
00485     if (ap->width || ap->height) {
00486         snprintf(buf, sizeof(buf), "%dx%d", ap->width, ap->height);
00487         av_dict_set(&opts, "video_size", buf, 0);
00488     }
00489     if (ap->pix_fmt != PIX_FMT_NONE) {
00490         av_dict_set(&opts, "pixel_format", av_get_pix_fmt_name(ap->pix_fmt), 0);
00491     }
00492     if (ap->channel) {
00493         snprintf(buf, sizeof(buf), "%d", ap->channel);
00494         av_dict_set(&opts, "channel", buf, 0);
00495     }
00496     if (ap->standard) {
00497         av_dict_set(&opts, "standard", ap->standard, 0);
00498     }
00499     if (ap->mpeg2ts_compute_pcr) {
00500         av_dict_set(&opts, "mpeg2ts_compute_pcr", "1", 0);
00501     }
00502     if (ap->initial_pause) {
00503         av_dict_set(&opts, "initial_pause", "1", 0);
00504     }
00505     return opts;
00506 }
00507 
00511 int av_open_input_stream(AVFormatContext **ic_ptr,
00512                          AVIOContext *pb, const char *filename,
00513                          AVInputFormat *fmt, AVFormatParameters *ap)
00514 {
00515     int err;
00516     AVDictionary *opts;
00517     AVFormatContext *ic;
00518     AVFormatParameters default_ap;
00519 
00520     if(!ap){
00521         ap=&default_ap;
00522         memset(ap, 0, sizeof(default_ap));
00523     }
00524     opts = convert_format_parameters(ap);
00525 
00526     if(!ap->prealloced_context)
00527         *ic_ptr = ic = avformat_alloc_context();
00528     else
00529         ic = *ic_ptr;
00530     if (!ic) {
00531         err = AVERROR(ENOMEM);
00532         goto fail;
00533     }
00534     if (pb && fmt && fmt->flags & AVFMT_NOFILE)
00535         av_log(ic, AV_LOG_WARNING, "Custom AVIOContext makes no sense and "
00536                                    "will be ignored with AVFMT_NOFILE format.\n");
00537     else
00538         ic->pb = pb;
00539 
00540     if ((err = avformat_open_input(&ic, filename, fmt, &opts)) < 0)
00541         goto fail;
00542 
00543     *ic_ptr = ic;
00544     ic->pb = ic->pb ? ic->pb : pb; // don't leak custom pb if it wasn't set above
00545 
00546 #if FF_API_OLD_METADATA
00547     ff_metadata_demux_compat(ic);
00548 #endif
00549 fail:
00550     *ic_ptr = ic;
00551     av_dict_free(&opts);
00552     return err;
00553 }
00554 #endif
00555 
00556 int av_demuxer_open(AVFormatContext *ic, AVFormatParameters *ap){
00557     int err;
00558 
00559     if (ic->iformat->read_header) {
00560         err = ic->iformat->read_header(ic, ap);
00561         if (err < 0)
00562             return err;
00563     }
00564 
00565     if (ic->pb && !ic->data_offset)
00566         ic->data_offset = avio_tell(ic->pb);
00567 
00568     return 0;
00569 }
00570 
00571 
00573 #define PROBE_BUF_MIN 2048
00574 #define PROBE_BUF_MAX (1<<20)
00575 
00576 int av_probe_input_buffer(AVIOContext *pb, AVInputFormat **fmt,
00577                           const char *filename, void *logctx,
00578                           unsigned int offset, unsigned int max_probe_size)
00579 {
00580     AVProbeData pd = { filename ? filename : "", NULL, -offset };
00581     unsigned char *buf = NULL;
00582     int ret = 0, probe_size;
00583 
00584     if (!max_probe_size) {
00585         max_probe_size = PROBE_BUF_MAX;
00586     } else if (max_probe_size > PROBE_BUF_MAX) {
00587         max_probe_size = PROBE_BUF_MAX;
00588     } else if (max_probe_size < PROBE_BUF_MIN) {
00589         return AVERROR(EINVAL);
00590     }
00591 
00592     if (offset >= max_probe_size) {
00593         return AVERROR(EINVAL);
00594     }
00595 
00596     for(probe_size= PROBE_BUF_MIN; probe_size<=max_probe_size && !*fmt && ret >= 0;
00597         probe_size = FFMIN(probe_size<<1, FFMAX(max_probe_size, probe_size+1))) {
00598         int ret, score = probe_size < max_probe_size ? AVPROBE_SCORE_MAX/4 : 0;
00599         int buf_offset = (probe_size == PROBE_BUF_MIN) ? 0 : probe_size>>1;
00600         void *buftmp;
00601 
00602         if (probe_size < offset) {
00603             continue;
00604         }
00605 
00606         /* read probe data */
00607         buftmp = av_realloc(buf, probe_size + AVPROBE_PADDING_SIZE);
00608         if(!buftmp){
00609             av_free(buf);
00610             return AVERROR(ENOMEM);
00611         }
00612         buf=buftmp;
00613         if ((ret = avio_read(pb, buf + buf_offset, probe_size - buf_offset)) < 0) {
00614             /* fail if error was not end of file, otherwise, lower score */
00615             if (ret != AVERROR_EOF) {
00616                 av_free(buf);
00617                 return ret;
00618             }
00619             score = 0;
00620             ret = 0;            /* error was end of file, nothing read */
00621         }
00622         pd.buf_size += ret;
00623         pd.buf = &buf[offset];
00624 
00625         memset(pd.buf + pd.buf_size, 0, AVPROBE_PADDING_SIZE);
00626 
00627         /* guess file format */
00628         *fmt = av_probe_input_format2(&pd, 1, &score);
00629         if(*fmt){
00630             if(score <= AVPROBE_SCORE_MAX/4){ //this can only be true in the last iteration
00631                 av_log(logctx, AV_LOG_WARNING, "Format %s detected only with low score of %d, misdetection possible!\n", (*fmt)->name, score);
00632             }else
00633                 av_log(logctx, AV_LOG_DEBUG, "Format %s probed with size=%d and score=%d\n", (*fmt)->name, probe_size, score);
00634         }
00635     }
00636 
00637     if (!*fmt) {
00638         av_free(buf);
00639         return AVERROR_INVALIDDATA;
00640     }
00641 
00642     /* rewind. reuse probe buffer to avoid seeking */
00643     if ((ret = ffio_rewind_with_probe_data(pb, buf, pd.buf_size)) < 0)
00644         av_free(buf);
00645 
00646     return ret;
00647 }
00648 
00649 #if FF_API_FORMAT_PARAMETERS
00650 int av_open_input_file(AVFormatContext **ic_ptr, const char *filename,
00651                        AVInputFormat *fmt,
00652                        int buf_size,
00653                        AVFormatParameters *ap)
00654 {
00655     int err;
00656     AVDictionary *opts = convert_format_parameters(ap);
00657 
00658     if (!ap || !ap->prealloced_context)
00659         *ic_ptr = NULL;
00660 
00661     err = avformat_open_input(ic_ptr, filename, fmt, &opts);
00662 
00663     av_dict_free(&opts);
00664     return err;
00665 }
00666 #endif
00667 
00668 /* open input file and probe the format if necessary */
00669 static int init_input(AVFormatContext *s, const char *filename)
00670 {
00671     int ret;
00672     AVProbeData pd = {filename, NULL, 0};
00673 
00674     if (s->pb) {
00675         s->flags |= AVFMT_FLAG_CUSTOM_IO;
00676         if (!s->iformat)
00677             return av_probe_input_buffer(s->pb, &s->iformat, filename, s, 0, 0);
00678         else if (s->iformat->flags & AVFMT_NOFILE)
00679             av_log(s, AV_LOG_WARNING, "Custom AVIOContext makes no sense and "
00680                                       "will be ignored with AVFMT_NOFILE format.\n");
00681         return 0;
00682     }
00683 
00684     if ( (s->iformat && s->iformat->flags & AVFMT_NOFILE) ||
00685         (!s->iformat && (s->iformat = av_probe_input_format(&pd, 0))))
00686         return 0;
00687 
00688     if ((ret = avio_open(&s->pb, filename, AVIO_RDONLY)) < 0)
00689        return ret;
00690     if (s->iformat)
00691         return 0;
00692     return av_probe_input_buffer(s->pb, &s->iformat, filename, s, 0, 0);
00693 }
00694 
00695 int avformat_open_input(AVFormatContext **ps, const char *filename, AVInputFormat *fmt, AVDictionary **options)
00696 {
00697     AVFormatContext *s = *ps;
00698     int ret = 0;
00699     AVFormatParameters ap = { 0 };
00700     AVDictionary *tmp = NULL;
00701 
00702     if (!s && !(s = avformat_alloc_context()))
00703         return AVERROR(ENOMEM);
00704     if (fmt)
00705         s->iformat = fmt;
00706 
00707     if (options)
00708         av_dict_copy(&tmp, *options, 0);
00709 
00710     if ((ret = av_opt_set_dict(s, &tmp)) < 0)
00711         goto fail;
00712 
00713     if ((ret = init_input(s, filename)) < 0)
00714         goto fail;
00715 
00716     /* check filename in case an image number is expected */
00717     if (s->iformat->flags & AVFMT_NEEDNUMBER) {
00718         if (!av_filename_number_test(filename)) {
00719             ret = AVERROR(EINVAL);
00720             goto fail;
00721         }
00722     }
00723 
00724     s->duration = s->start_time = AV_NOPTS_VALUE;
00725     av_strlcpy(s->filename, filename, sizeof(s->filename));
00726 
00727     /* allocate private data */
00728     if (s->iformat->priv_data_size > 0) {
00729         if (!(s->priv_data = av_mallocz(s->iformat->priv_data_size))) {
00730             ret = AVERROR(ENOMEM);
00731             goto fail;
00732         }
00733         if (s->iformat->priv_class) {
00734             *(const AVClass**)s->priv_data = s->iformat->priv_class;
00735             av_opt_set_defaults(s->priv_data);
00736             if ((ret = av_opt_set_dict(s->priv_data, &tmp)) < 0)
00737                 goto fail;
00738         }
00739     }
00740 
00741     /* e.g. AVFMT_NOFILE formats will not have a AVIOContext */
00742     if (s->pb)
00743         ff_id3v2_read(s, ID3v2_DEFAULT_MAGIC);
00744 
00745     if (!(s->flags&AVFMT_FLAG_PRIV_OPT) && s->iformat->read_header)
00746         if ((ret = s->iformat->read_header(s, &ap)) < 0)
00747             goto fail;
00748 
00749     if (!(s->flags&AVFMT_FLAG_PRIV_OPT) && s->pb && !s->data_offset)
00750         s->data_offset = avio_tell(s->pb);
00751 
00752     s->raw_packet_buffer_remaining_size = RAW_PACKET_BUFFER_SIZE;
00753 
00754     if (options) {
00755         av_dict_free(options);
00756         *options = tmp;
00757     }
00758     *ps = s;
00759     return 0;
00760 
00761 fail:
00762     av_dict_free(&tmp);
00763     if (s->pb && !(s->flags & AVFMT_FLAG_CUSTOM_IO))
00764         avio_close(s->pb);
00765     avformat_free_context(s);
00766     *ps = NULL;
00767     return ret;
00768 }
00769 
00770 /*******************************************************/
00771 
00772 static AVPacket *add_to_pktbuf(AVPacketList **packet_buffer, AVPacket *pkt,
00773                                AVPacketList **plast_pktl){
00774     AVPacketList *pktl = av_mallocz(sizeof(AVPacketList));
00775     if (!pktl)
00776         return NULL;
00777 
00778     if (*packet_buffer)
00779         (*plast_pktl)->next = pktl;
00780     else
00781         *packet_buffer = pktl;
00782 
00783     /* add the packet in the buffered packet list */
00784     *plast_pktl = pktl;
00785     pktl->pkt= *pkt;
00786     return &pktl->pkt;
00787 }
00788 
00789 int av_read_packet(AVFormatContext *s, AVPacket *pkt)
00790 {
00791     int ret, i;
00792     AVStream *st;
00793 
00794     for(;;){
00795         AVPacketList *pktl = s->raw_packet_buffer;
00796 
00797         if (pktl) {
00798             *pkt = pktl->pkt;
00799             if(s->streams[pkt->stream_index]->request_probe <= 0){
00800                 s->raw_packet_buffer = pktl->next;
00801                 s->raw_packet_buffer_remaining_size += pkt->size;
00802                 av_free(pktl);
00803                 return 0;
00804             }
00805         }
00806 
00807         av_init_packet(pkt);
00808         ret= s->iformat->read_packet(s, pkt);
00809         if (ret < 0) {
00810             if (!pktl || ret == AVERROR(EAGAIN))
00811                 return ret;
00812             for (i = 0; i < s->nb_streams; i++)
00813                 if(s->streams[i]->request_probe > 0)
00814                     s->streams[i]->request_probe = -1;
00815             continue;
00816         }
00817 
00818         st= s->streams[pkt->stream_index];
00819 
00820         switch(st->codec->codec_type){
00821         case AVMEDIA_TYPE_VIDEO:
00822             if(s->video_codec_id)   st->codec->codec_id= s->video_codec_id;
00823             break;
00824         case AVMEDIA_TYPE_AUDIO:
00825             if(s->audio_codec_id)   st->codec->codec_id= s->audio_codec_id;
00826             break;
00827         case AVMEDIA_TYPE_SUBTITLE:
00828             if(s->subtitle_codec_id)st->codec->codec_id= s->subtitle_codec_id;
00829             break;
00830         }
00831 
00832         if(!pktl && st->request_probe <= 0)
00833             return ret;
00834 
00835         add_to_pktbuf(&s->raw_packet_buffer, pkt, &s->raw_packet_buffer_end);
00836         s->raw_packet_buffer_remaining_size -= pkt->size;
00837 
00838         if(st->request_probe>0){
00839             AVProbeData *pd = &st->probe_data;
00840             int end;
00841             av_log(s, AV_LOG_DEBUG, "probing stream %d pp:%d\n", st->index, st->probe_packets);
00842             --st->probe_packets;
00843 
00844             pd->buf = av_realloc(pd->buf, pd->buf_size+pkt->size+AVPROBE_PADDING_SIZE);
00845             memcpy(pd->buf+pd->buf_size, pkt->data, pkt->size);
00846             pd->buf_size += pkt->size;
00847             memset(pd->buf+pd->buf_size, 0, AVPROBE_PADDING_SIZE);
00848 
00849             end=    s->raw_packet_buffer_remaining_size <= 0
00850                  || st->probe_packets<=0;
00851 
00852             if(end || av_log2(pd->buf_size) != av_log2(pd->buf_size - pkt->size)){
00853                 int score= set_codec_from_probe_data(s, st, pd);
00854                 if(    (st->codec->codec_id != CODEC_ID_NONE && score > AVPROBE_SCORE_MAX/4)
00855                     || end){
00856                     pd->buf_size=0;
00857                     av_freep(&pd->buf);
00858                     st->request_probe= -1;
00859                     if(st->codec->codec_id != CODEC_ID_NONE){
00860                     av_log(s, AV_LOG_DEBUG, "probed stream %d\n", st->index);
00861                     }else
00862                         av_log(s, AV_LOG_WARNING, "probed stream %d failed\n", st->index);
00863                 }
00864             }
00865         }
00866     }
00867 }
00868 
00869 /**********************************************************/
00870 
00874 static int get_audio_frame_size(AVCodecContext *enc, int size)
00875 {
00876     int frame_size;
00877 
00878     if(enc->codec_id == CODEC_ID_VORBIS)
00879         return -1;
00880 
00881     if (enc->frame_size <= 1) {
00882         int bits_per_sample = av_get_bits_per_sample(enc->codec_id);
00883 
00884         if (bits_per_sample) {
00885             if (enc->channels == 0)
00886                 return -1;
00887             frame_size = (size << 3) / (bits_per_sample * enc->channels);
00888         } else {
00889             /* used for example by ADPCM codecs */
00890             if (enc->bit_rate == 0)
00891                 return -1;
00892             frame_size = ((int64_t)size * 8 * enc->sample_rate) / enc->bit_rate;
00893         }
00894     } else {
00895         frame_size = enc->frame_size;
00896     }
00897     return frame_size;
00898 }
00899 
00900 
00904 static void compute_frame_duration(int *pnum, int *pden, AVStream *st,
00905                                    AVCodecParserContext *pc, AVPacket *pkt)
00906 {
00907     int frame_size;
00908 
00909     *pnum = 0;
00910     *pden = 0;
00911     switch(st->codec->codec_type) {
00912     case AVMEDIA_TYPE_VIDEO:
00913         if(st->time_base.num*1000LL > st->time_base.den){
00914             *pnum = st->time_base.num;
00915             *pden = st->time_base.den;
00916         }else if(st->codec->time_base.num*1000LL > st->codec->time_base.den){
00917             *pnum = st->codec->time_base.num;
00918             *pden = st->codec->time_base.den;
00919             if (pc && pc->repeat_pict) {
00920                 *pnum = (*pnum) * (1 + pc->repeat_pict);
00921             }
00922             //If this codec can be interlaced or progressive then we need a parser to compute duration of a packet
00923             //Thus if we have no parser in such case leave duration undefined.
00924             if(st->codec->ticks_per_frame>1 && !pc){
00925                 *pnum = *pden = 0;
00926             }
00927         }
00928         break;
00929     case AVMEDIA_TYPE_AUDIO:
00930         frame_size = get_audio_frame_size(st->codec, pkt->size);
00931         if (frame_size <= 0 || st->codec->sample_rate <= 0)
00932             break;
00933         *pnum = frame_size;
00934         *pden = st->codec->sample_rate;
00935         break;
00936     default:
00937         break;
00938     }
00939 }
00940 
00941 static int is_intra_only(AVCodecContext *enc){
00942     if(enc->codec_type == AVMEDIA_TYPE_AUDIO){
00943         return 1;
00944     }else if(enc->codec_type == AVMEDIA_TYPE_VIDEO){
00945         switch(enc->codec_id){
00946         case CODEC_ID_MJPEG:
00947         case CODEC_ID_MJPEGB:
00948         case CODEC_ID_LJPEG:
00949         case CODEC_ID_RAWVIDEO:
00950         case CODEC_ID_DVVIDEO:
00951         case CODEC_ID_HUFFYUV:
00952         case CODEC_ID_FFVHUFF:
00953         case CODEC_ID_ASV1:
00954         case CODEC_ID_ASV2:
00955         case CODEC_ID_VCR1:
00956         case CODEC_ID_DNXHD:
00957         case CODEC_ID_JPEG2000:
00958             return 1;
00959         default: break;
00960         }
00961     }
00962     return 0;
00963 }
00964 
00965 static void update_initial_timestamps(AVFormatContext *s, int stream_index,
00966                                       int64_t dts, int64_t pts)
00967 {
00968     AVStream *st= s->streams[stream_index];
00969     AVPacketList *pktl= s->packet_buffer;
00970 
00971     if(st->first_dts != AV_NOPTS_VALUE || dts == AV_NOPTS_VALUE || st->cur_dts == AV_NOPTS_VALUE)
00972         return;
00973 
00974     st->first_dts= dts - st->cur_dts;
00975     st->cur_dts= dts;
00976 
00977     for(; pktl; pktl= pktl->next){
00978         if(pktl->pkt.stream_index != stream_index)
00979             continue;
00980         //FIXME think more about this check
00981         if(pktl->pkt.pts != AV_NOPTS_VALUE && pktl->pkt.pts == pktl->pkt.dts)
00982             pktl->pkt.pts += st->first_dts;
00983 
00984         if(pktl->pkt.dts != AV_NOPTS_VALUE)
00985             pktl->pkt.dts += st->first_dts;
00986 
00987         if(st->start_time == AV_NOPTS_VALUE && pktl->pkt.pts != AV_NOPTS_VALUE)
00988             st->start_time= pktl->pkt.pts;
00989     }
00990     if (st->start_time == AV_NOPTS_VALUE)
00991         st->start_time = pts;
00992 }
00993 
00994 static void update_initial_durations(AVFormatContext *s, AVStream *st, AVPacket *pkt)
00995 {
00996     AVPacketList *pktl= s->packet_buffer;
00997     int64_t cur_dts= 0;
00998 
00999     if(st->first_dts != AV_NOPTS_VALUE){
01000         cur_dts= st->first_dts;
01001         for(; pktl; pktl= pktl->next){
01002             if(pktl->pkt.stream_index == pkt->stream_index){
01003                 if(pktl->pkt.pts != pktl->pkt.dts || pktl->pkt.dts != AV_NOPTS_VALUE || pktl->pkt.duration)
01004                     break;
01005                 cur_dts -= pkt->duration;
01006             }
01007         }
01008         pktl= s->packet_buffer;
01009         st->first_dts = cur_dts;
01010     }else if(st->cur_dts)
01011         return;
01012 
01013     for(; pktl; pktl= pktl->next){
01014         if(pktl->pkt.stream_index != pkt->stream_index)
01015             continue;
01016         if(pktl->pkt.pts == pktl->pkt.dts && pktl->pkt.dts == AV_NOPTS_VALUE
01017            && !pktl->pkt.duration){
01018             pktl->pkt.dts= cur_dts;
01019             if(!st->codec->has_b_frames)
01020                 pktl->pkt.pts= cur_dts;
01021             cur_dts += pkt->duration;
01022             pktl->pkt.duration= pkt->duration;
01023         }else
01024             break;
01025     }
01026     if(st->first_dts == AV_NOPTS_VALUE)
01027         st->cur_dts= cur_dts;
01028 }
01029 
01030 static void compute_pkt_fields(AVFormatContext *s, AVStream *st,
01031                                AVCodecParserContext *pc, AVPacket *pkt)
01032 {
01033     int num, den, presentation_delayed, delay, i;
01034     int64_t offset;
01035 
01036     if (s->flags & AVFMT_FLAG_NOFILLIN)
01037         return;
01038 
01039     if((s->flags & AVFMT_FLAG_IGNDTS) && pkt->pts != AV_NOPTS_VALUE)
01040         pkt->dts= AV_NOPTS_VALUE;
01041 
01042     if (st->codec->codec_id != CODEC_ID_H264 && pc && pc->pict_type == AV_PICTURE_TYPE_B)
01043         //FIXME Set low_delay = 0 when has_b_frames = 1
01044         st->codec->has_b_frames = 1;
01045 
01046     /* do we have a video B-frame ? */
01047     delay= st->codec->has_b_frames;
01048     presentation_delayed = 0;
01049 
01050     // ignore delay caused by frame threading so that the mpeg2-without-dts
01051     // warning will not trigger
01052     if (delay && st->codec->active_thread_type&FF_THREAD_FRAME)
01053         delay -= st->codec->thread_count-1;
01054 
01055     /* XXX: need has_b_frame, but cannot get it if the codec is
01056         not initialized */
01057     if (delay &&
01058         pc && pc->pict_type != AV_PICTURE_TYPE_B)
01059         presentation_delayed = 1;
01060 
01061     if(pkt->pts != AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE && pkt->dts > pkt->pts && st->pts_wrap_bits<63
01062        /*&& pkt->dts-(1LL<<st->pts_wrap_bits) < pkt->pts*/){
01063         pkt->dts -= 1LL<<st->pts_wrap_bits;
01064     }
01065 
01066     // some mpeg2 in mpeg-ps lack dts (issue171 / input_file.mpg)
01067     // we take the conservative approach and discard both
01068     // Note, if this is misbehaving for a H.264 file then possibly presentation_delayed is not set correctly.
01069     if(delay==1 && pkt->dts == pkt->pts && pkt->dts != AV_NOPTS_VALUE && presentation_delayed){
01070         av_log(s, AV_LOG_DEBUG, "invalid dts/pts combination %Ld\n", pkt->dts);
01071         pkt->dts= pkt->pts= AV_NOPTS_VALUE;
01072     }
01073 
01074     if (pkt->duration == 0) {
01075         compute_frame_duration(&num, &den, st, pc, pkt);
01076         if (den && num) {
01077             pkt->duration = av_rescale_rnd(1, num * (int64_t)st->time_base.den, den * (int64_t)st->time_base.num, AV_ROUND_DOWN);
01078 
01079             if(pkt->duration != 0 && s->packet_buffer)
01080                 update_initial_durations(s, st, pkt);
01081         }
01082     }
01083 
01084     /* correct timestamps with byte offset if demuxers only have timestamps
01085        on packet boundaries */
01086     if(pc && st->need_parsing == AVSTREAM_PARSE_TIMESTAMPS && pkt->size){
01087         /* this will estimate bitrate based on this frame's duration and size */
01088         offset = av_rescale(pc->offset, pkt->duration, pkt->size);
01089         if(pkt->pts != AV_NOPTS_VALUE)
01090             pkt->pts += offset;
01091         if(pkt->dts != AV_NOPTS_VALUE)
01092             pkt->dts += offset;
01093     }
01094 
01095     if (pc && pc->dts_sync_point >= 0) {
01096         // we have synchronization info from the parser
01097         int64_t den = st->codec->time_base.den * (int64_t) st->time_base.num;
01098         if (den > 0) {
01099             int64_t num = st->codec->time_base.num * (int64_t) st->time_base.den;
01100             if (pkt->dts != AV_NOPTS_VALUE) {
01101                 // got DTS from the stream, update reference timestamp
01102                 st->reference_dts = pkt->dts - pc->dts_ref_dts_delta * num / den;
01103                 pkt->pts = pkt->dts + pc->pts_dts_delta * num / den;
01104             } else if (st->reference_dts != AV_NOPTS_VALUE) {
01105                 // compute DTS based on reference timestamp
01106                 pkt->dts = st->reference_dts + pc->dts_ref_dts_delta * num / den;
01107                 pkt->pts = pkt->dts + pc->pts_dts_delta * num / den;
01108             }
01109             if (pc->dts_sync_point > 0)
01110                 st->reference_dts = pkt->dts; // new reference
01111         }
01112     }
01113 
01114     /* This may be redundant, but it should not hurt. */
01115     if(pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE && pkt->pts > pkt->dts)
01116         presentation_delayed = 1;
01117 
01118 //    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);
01119     /* interpolate PTS and DTS if they are not present */
01120     //We skip H264 currently because delay and has_b_frames are not reliably set
01121     if((delay==0 || (delay==1 && pc)) && st->codec->codec_id != CODEC_ID_H264){
01122         if (presentation_delayed) {
01123             /* DTS = decompression timestamp */
01124             /* PTS = presentation timestamp */
01125             if (pkt->dts == AV_NOPTS_VALUE)
01126                 pkt->dts = st->last_IP_pts;
01127             update_initial_timestamps(s, pkt->stream_index, pkt->dts, pkt->pts);
01128             if (pkt->dts == AV_NOPTS_VALUE)
01129                 pkt->dts = st->cur_dts;
01130 
01131             /* this is tricky: the dts must be incremented by the duration
01132             of the frame we are displaying, i.e. the last I- or P-frame */
01133             if (st->last_IP_duration == 0)
01134                 st->last_IP_duration = pkt->duration;
01135             if(pkt->dts != AV_NOPTS_VALUE)
01136                 st->cur_dts = pkt->dts + st->last_IP_duration;
01137             st->last_IP_duration  = pkt->duration;
01138             st->last_IP_pts= pkt->pts;
01139             /* cannot compute PTS if not present (we can compute it only
01140             by knowing the future */
01141         } else if(pkt->pts != AV_NOPTS_VALUE || pkt->dts != AV_NOPTS_VALUE || pkt->duration){
01142             if(pkt->pts != AV_NOPTS_VALUE && pkt->duration){
01143                 int64_t old_diff= FFABS(st->cur_dts - pkt->duration - pkt->pts);
01144                 int64_t new_diff= FFABS(st->cur_dts - pkt->pts);
01145                 if(old_diff < new_diff && old_diff < (pkt->duration>>3)){
01146                     pkt->pts += pkt->duration;
01147     //                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);
01148                 }
01149             }
01150 
01151             /* presentation is not delayed : PTS and DTS are the same */
01152             if(pkt->pts == AV_NOPTS_VALUE)
01153                 pkt->pts = pkt->dts;
01154             update_initial_timestamps(s, pkt->stream_index, pkt->pts, pkt->pts);
01155             if(pkt->pts == AV_NOPTS_VALUE)
01156                 pkt->pts = st->cur_dts;
01157             pkt->dts = pkt->pts;
01158             if(pkt->pts != AV_NOPTS_VALUE)
01159                 st->cur_dts = pkt->pts + pkt->duration;
01160         }
01161     }
01162 
01163     if(pkt->pts != AV_NOPTS_VALUE && delay <= MAX_REORDER_DELAY){
01164         st->pts_buffer[0]= pkt->pts;
01165         for(i=0; i<delay && st->pts_buffer[i] > st->pts_buffer[i+1]; i++)
01166             FFSWAP(int64_t, st->pts_buffer[i], st->pts_buffer[i+1]);
01167         if(pkt->dts == AV_NOPTS_VALUE)
01168             pkt->dts= st->pts_buffer[0];
01169         if(st->codec->codec_id == CODEC_ID_H264){ //we skiped it above so we try here
01170             update_initial_timestamps(s, pkt->stream_index, pkt->dts, pkt->pts); // this should happen on the first packet
01171         }
01172         if(pkt->dts > st->cur_dts)
01173             st->cur_dts = pkt->dts;
01174     }
01175 
01176 //    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);
01177 
01178     /* update flags */
01179     if(is_intra_only(st->codec))
01180         pkt->flags |= AV_PKT_FLAG_KEY;
01181     else if (pc) {
01182         pkt->flags = 0;
01183         /* keyframe computation */
01184         if (pc->key_frame == 1)
01185             pkt->flags |= AV_PKT_FLAG_KEY;
01186         else if (pc->key_frame == -1 && pc->pict_type == AV_PICTURE_TYPE_I)
01187             pkt->flags |= AV_PKT_FLAG_KEY;
01188     }
01189     if (pc)
01190         pkt->convergence_duration = pc->convergence_duration;
01191 }
01192 
01193 
01194 static int av_read_frame_internal(AVFormatContext *s, AVPacket *pkt)
01195 {
01196     AVStream *st;
01197     int len, ret, i;
01198 
01199     av_init_packet(pkt);
01200 
01201     for(;;) {
01202         /* select current input stream component */
01203         st = s->cur_st;
01204         if (st) {
01205             if (!st->need_parsing || !st->parser) {
01206                 /* no parsing needed: we just output the packet as is */
01207                 /* raw data support */
01208                 *pkt = st->cur_pkt;
01209                 st->cur_pkt.data= NULL;
01210                 compute_pkt_fields(s, st, NULL, pkt);
01211                 s->cur_st = NULL;
01212                 if ((s->iformat->flags & AVFMT_GENERIC_INDEX) &&
01213                     (pkt->flags & AV_PKT_FLAG_KEY) && pkt->dts != AV_NOPTS_VALUE) {
01214                     ff_reduce_index(s, st->index);
01215                     av_add_index_entry(st, pkt->pos, pkt->dts, 0, 0, AVINDEX_KEYFRAME);
01216                 }
01217                 break;
01218             } else if (st->cur_len > 0 && st->discard < AVDISCARD_ALL) {
01219                 len = av_parser_parse2(st->parser, st->codec, &pkt->data, &pkt->size,
01220                                        st->cur_ptr, st->cur_len,
01221                                        st->cur_pkt.pts, st->cur_pkt.dts,
01222                                        st->cur_pkt.pos);
01223                 st->cur_pkt.pts = AV_NOPTS_VALUE;
01224                 st->cur_pkt.dts = AV_NOPTS_VALUE;
01225                 /* increment read pointer */
01226                 st->cur_ptr += len;
01227                 st->cur_len -= len;
01228 
01229                 /* return packet if any */
01230                 if (pkt->size) {
01231                 got_packet:
01232                     pkt->duration = 0;
01233                     pkt->stream_index = st->index;
01234                     pkt->pts = st->parser->pts;
01235                     pkt->dts = st->parser->dts;
01236                     pkt->pos = st->parser->pos;
01237                     if(pkt->data == st->cur_pkt.data && pkt->size == st->cur_pkt.size){
01238                         s->cur_st = NULL;
01239                         pkt->destruct= st->cur_pkt.destruct;
01240                         st->cur_pkt.destruct= NULL;
01241                         st->cur_pkt.data    = NULL;
01242                         assert(st->cur_len == 0);
01243                     }else{
01244                     pkt->destruct = NULL;
01245                     }
01246                     compute_pkt_fields(s, st, st->parser, pkt);
01247 
01248                     if((s->iformat->flags & AVFMT_GENERIC_INDEX) && pkt->flags & AV_PKT_FLAG_KEY){
01249                         int64_t pos= (st->parser->flags & PARSER_FLAG_COMPLETE_FRAMES) ? pkt->pos : st->parser->frame_offset;
01250                         ff_reduce_index(s, st->index);
01251                         av_add_index_entry(st, pos, pkt->dts,
01252                                            0, 0, AVINDEX_KEYFRAME);
01253                     }
01254 
01255                     break;
01256                 }
01257             } else {
01258                 /* free packet */
01259                 av_free_packet(&st->cur_pkt);
01260                 s->cur_st = NULL;
01261             }
01262         } else {
01263             AVPacket cur_pkt;
01264             /* read next packet */
01265             ret = av_read_packet(s, &cur_pkt);
01266             if (ret < 0) {
01267                 if (ret == AVERROR(EAGAIN))
01268                     return ret;
01269                 /* return the last frames, if any */
01270                 for(i = 0; i < s->nb_streams; i++) {
01271                     st = s->streams[i];
01272                     if (st->parser && st->need_parsing) {
01273                         av_parser_parse2(st->parser, st->codec,
01274                                         &pkt->data, &pkt->size,
01275                                         NULL, 0,
01276                                         AV_NOPTS_VALUE, AV_NOPTS_VALUE,
01277                                         AV_NOPTS_VALUE);
01278                         if (pkt->size)
01279                             goto got_packet;
01280                     }
01281                 }
01282                 /* no more packets: really terminate parsing */
01283                 return ret;
01284             }
01285             st = s->streams[cur_pkt.stream_index];
01286             st->cur_pkt= cur_pkt;
01287 
01288             if(st->cur_pkt.pts != AV_NOPTS_VALUE &&
01289                st->cur_pkt.dts != AV_NOPTS_VALUE &&
01290                st->cur_pkt.pts < st->cur_pkt.dts){
01291                 av_log(s, AV_LOG_WARNING, "Invalid timestamps stream=%d, pts=%"PRId64", dts=%"PRId64", size=%d\n",
01292                     st->cur_pkt.stream_index,
01293                     st->cur_pkt.pts,
01294                     st->cur_pkt.dts,
01295                     st->cur_pkt.size);
01296 //                av_free_packet(&st->cur_pkt);
01297 //                return -1;
01298             }
01299 
01300             if(s->debug & FF_FDEBUG_TS)
01301                 av_log(s, AV_LOG_DEBUG, "av_read_packet stream=%d, pts=%"PRId64", dts=%"PRId64", size=%d, duration=%d, flags=%d\n",
01302                     st->cur_pkt.stream_index,
01303                     st->cur_pkt.pts,
01304                     st->cur_pkt.dts,
01305                     st->cur_pkt.size,
01306                     st->cur_pkt.duration,
01307                     st->cur_pkt.flags);
01308 
01309             s->cur_st = st;
01310             st->cur_ptr = st->cur_pkt.data;
01311             st->cur_len = st->cur_pkt.size;
01312             if (st->need_parsing && !st->parser && !(s->flags & AVFMT_FLAG_NOPARSE)) {
01313                 st->parser = av_parser_init(st->codec->codec_id);
01314                 if (!st->parser) {
01315                     /* no parser available: just output the raw packets */
01316                     st->need_parsing = AVSTREAM_PARSE_NONE;
01317                 }else if(st->need_parsing == AVSTREAM_PARSE_HEADERS){
01318                     st->parser->flags |= PARSER_FLAG_COMPLETE_FRAMES;
01319                 }else if(st->need_parsing == AVSTREAM_PARSE_FULL_ONCE){
01320                     st->parser->flags |= PARSER_FLAG_ONCE;
01321                 }
01322             }
01323         }
01324     }
01325     if(s->debug & FF_FDEBUG_TS)
01326         av_log(s, AV_LOG_DEBUG, "av_read_frame_internal stream=%d, pts=%"PRId64", dts=%"PRId64", size=%d, duration=%d, flags=%d\n",
01327             pkt->stream_index,
01328             pkt->pts,
01329             pkt->dts,
01330             pkt->size,
01331             pkt->duration,
01332             pkt->flags);
01333 
01334     return 0;
01335 }
01336 
01337 int av_read_frame(AVFormatContext *s, AVPacket *pkt)
01338 {
01339     AVPacketList *pktl;
01340     int eof=0;
01341     const int genpts= s->flags & AVFMT_FLAG_GENPTS;
01342 
01343     for(;;){
01344         pktl = s->packet_buffer;
01345         if (pktl) {
01346             AVPacket *next_pkt= &pktl->pkt;
01347 
01348             if(genpts && next_pkt->dts != AV_NOPTS_VALUE){
01349                 int wrap_bits = s->streams[next_pkt->stream_index]->pts_wrap_bits;
01350                 while(pktl && next_pkt->pts == AV_NOPTS_VALUE){
01351                     if(   pktl->pkt.stream_index == next_pkt->stream_index
01352                        && (0 > av_compare_mod(next_pkt->dts, pktl->pkt.dts, 2LL << (wrap_bits - 1)))
01353                        && av_compare_mod(pktl->pkt.pts, pktl->pkt.dts, 2LL << (wrap_bits - 1))) { //not b frame
01354                         next_pkt->pts= pktl->pkt.dts;
01355                     }
01356                     pktl= pktl->next;
01357                 }
01358                 pktl = s->packet_buffer;
01359             }
01360 
01361             if(   next_pkt->pts != AV_NOPTS_VALUE
01362                || next_pkt->dts == AV_NOPTS_VALUE
01363                || !genpts || eof){
01364                 /* read packet from packet buffer, if there is data */
01365                 *pkt = *next_pkt;
01366                 s->packet_buffer = pktl->next;
01367                 av_free(pktl);
01368                 return 0;
01369             }
01370         }
01371         if(genpts){
01372             int ret= av_read_frame_internal(s, pkt);
01373             if(ret<0){
01374                 if(pktl && ret != AVERROR(EAGAIN)){
01375                     eof=1;
01376                     continue;
01377                 }else
01378                     return ret;
01379             }
01380 
01381             if(av_dup_packet(add_to_pktbuf(&s->packet_buffer, pkt,
01382                                            &s->packet_buffer_end)) < 0)
01383                 return AVERROR(ENOMEM);
01384         }else{
01385             assert(!s->packet_buffer);
01386             return av_read_frame_internal(s, pkt);
01387         }
01388     }
01389 }
01390 
01391 /* XXX: suppress the packet queue */
01392 static void flush_packet_queue(AVFormatContext *s)
01393 {
01394     AVPacketList *pktl;
01395 
01396     for(;;) {
01397         pktl = s->packet_buffer;
01398         if (!pktl)
01399             break;
01400         s->packet_buffer = pktl->next;
01401         av_free_packet(&pktl->pkt);
01402         av_free(pktl);
01403     }
01404     while(s->raw_packet_buffer){
01405         pktl = s->raw_packet_buffer;
01406         s->raw_packet_buffer = pktl->next;
01407         av_free_packet(&pktl->pkt);
01408         av_free(pktl);
01409     }
01410     s->packet_buffer_end=
01411     s->raw_packet_buffer_end= NULL;
01412     s->raw_packet_buffer_remaining_size = RAW_PACKET_BUFFER_SIZE;
01413 }
01414 
01415 /*******************************************************/
01416 /* seek support */
01417 
01418 int av_find_default_stream_index(AVFormatContext *s)
01419 {
01420     int first_audio_index = -1;
01421     int i;
01422     AVStream *st;
01423 
01424     if (s->nb_streams <= 0)
01425         return -1;
01426     for(i = 0; i < s->nb_streams; i++) {
01427         st = s->streams[i];
01428         if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
01429             return i;
01430         }
01431         if (first_audio_index < 0 && st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
01432             first_audio_index = i;
01433     }
01434     return first_audio_index >= 0 ? first_audio_index : 0;
01435 }
01436 
01440 void ff_read_frame_flush(AVFormatContext *s)
01441 {
01442     AVStream *st;
01443     int i, j;
01444 
01445     flush_packet_queue(s);
01446 
01447     s->cur_st = NULL;
01448 
01449     /* for each stream, reset read state */
01450     for(i = 0; i < s->nb_streams; i++) {
01451         st = s->streams[i];
01452 
01453         if (st->parser) {
01454             av_parser_close(st->parser);
01455             st->parser = NULL;
01456             av_free_packet(&st->cur_pkt);
01457         }
01458         st->last_IP_pts = AV_NOPTS_VALUE;
01459         st->cur_dts = AV_NOPTS_VALUE; /* we set the current DTS to an unspecified origin */
01460         st->reference_dts = AV_NOPTS_VALUE;
01461         /* fail safe */
01462         st->cur_ptr = NULL;
01463         st->cur_len = 0;
01464 
01465         st->probe_packets = MAX_PROBE_PACKETS;
01466 
01467         for(j=0; j<MAX_REORDER_DELAY+1; j++)
01468             st->pts_buffer[j]= AV_NOPTS_VALUE;
01469     }
01470 }
01471 
01472 void av_update_cur_dts(AVFormatContext *s, AVStream *ref_st, int64_t timestamp){
01473     int i;
01474 
01475     for(i = 0; i < s->nb_streams; i++) {
01476         AVStream *st = s->streams[i];
01477 
01478         st->cur_dts = av_rescale(timestamp,
01479                                  st->time_base.den * (int64_t)ref_st->time_base.num,
01480                                  st->time_base.num * (int64_t)ref_st->time_base.den);
01481     }
01482 }
01483 
01484 void ff_reduce_index(AVFormatContext *s, int stream_index)
01485 {
01486     AVStream *st= s->streams[stream_index];
01487     unsigned int max_entries= s->max_index_size / sizeof(AVIndexEntry);
01488 
01489     if((unsigned)st->nb_index_entries >= max_entries){
01490         int i;
01491         for(i=0; 2*i<st->nb_index_entries; i++)
01492             st->index_entries[i]= st->index_entries[2*i];
01493         st->nb_index_entries= i;
01494     }
01495 }
01496 
01497 int ff_add_index_entry(AVIndexEntry **index_entries,
01498                        int *nb_index_entries,
01499                        unsigned int *index_entries_allocated_size,
01500                        int64_t pos, int64_t timestamp, int size, int distance, int flags)
01501 {
01502     AVIndexEntry *entries, *ie;
01503     int index;
01504 
01505     if((unsigned)*nb_index_entries + 1 >= UINT_MAX / sizeof(AVIndexEntry))
01506         return -1;
01507 
01508     entries = av_fast_realloc(*index_entries,
01509                               index_entries_allocated_size,
01510                               (*nb_index_entries + 1) *
01511                               sizeof(AVIndexEntry));
01512     if(!entries)
01513         return -1;
01514 
01515     *index_entries= entries;
01516 
01517     index= ff_index_search_timestamp(*index_entries, *nb_index_entries, timestamp, AVSEEK_FLAG_ANY);
01518 
01519     if(index<0){
01520         index= (*nb_index_entries)++;
01521         ie= &entries[index];
01522         assert(index==0 || ie[-1].timestamp < timestamp);
01523     }else{
01524         ie= &entries[index];
01525         if(ie->timestamp != timestamp){
01526             if(ie->timestamp <= timestamp)
01527                 return -1;
01528             memmove(entries + index + 1, entries + index, sizeof(AVIndexEntry)*(*nb_index_entries - index));
01529             (*nb_index_entries)++;
01530         }else if(ie->pos == pos && distance < ie->min_distance) //do not reduce the distance
01531             distance= ie->min_distance;
01532     }
01533 
01534     ie->pos = pos;
01535     ie->timestamp = timestamp;
01536     ie->min_distance= distance;
01537     ie->size= size;
01538     ie->flags = flags;
01539 
01540     return index;
01541 }
01542 
01543 int av_add_index_entry(AVStream *st,
01544                        int64_t pos, int64_t timestamp, int size, int distance, int flags)
01545 {
01546     return ff_add_index_entry(&st->index_entries, &st->nb_index_entries,
01547                               &st->index_entries_allocated_size, pos,
01548                               timestamp, size, distance, flags);
01549 }
01550 
01551 int ff_index_search_timestamp(const AVIndexEntry *entries, int nb_entries,
01552                               int64_t wanted_timestamp, int flags)
01553 {
01554     int a, b, m;
01555     int64_t timestamp;
01556 
01557     a = - 1;
01558     b = nb_entries;
01559 
01560     //optimize appending index entries at the end
01561     if(b && entries[b-1].timestamp < wanted_timestamp)
01562         a= b-1;
01563 
01564     while (b - a > 1) {
01565         m = (a + b) >> 1;
01566         timestamp = entries[m].timestamp;
01567         if(timestamp >= wanted_timestamp)
01568             b = m;
01569         if(timestamp <= wanted_timestamp)
01570             a = m;
01571     }
01572     m= (flags & AVSEEK_FLAG_BACKWARD) ? a : b;
01573 
01574     if(!(flags & AVSEEK_FLAG_ANY)){
01575         while(m>=0 && m<nb_entries && !(entries[m].flags & AVINDEX_KEYFRAME)){
01576             m += (flags & AVSEEK_FLAG_BACKWARD) ? -1 : 1;
01577         }
01578     }
01579 
01580     if(m == nb_entries)
01581         return -1;
01582     return  m;
01583 }
01584 
01585 int av_index_search_timestamp(AVStream *st, int64_t wanted_timestamp,
01586                               int flags)
01587 {
01588     return ff_index_search_timestamp(st->index_entries, st->nb_index_entries,
01589                                      wanted_timestamp, flags);
01590 }
01591 
01592 int av_seek_frame_binary(AVFormatContext *s, int stream_index, int64_t target_ts, int flags){
01593     AVInputFormat *avif= s->iformat;
01594     int64_t av_uninit(pos_min), av_uninit(pos_max), pos, pos_limit;
01595     int64_t ts_min, ts_max, ts;
01596     int index;
01597     int64_t ret;
01598     AVStream *st;
01599 
01600     if (stream_index < 0)
01601         return -1;
01602 
01603     av_dlog(s, "read_seek: %d %"PRId64"\n", stream_index, target_ts);
01604 
01605     ts_max=
01606     ts_min= AV_NOPTS_VALUE;
01607     pos_limit= -1; //gcc falsely says it may be uninitialized
01608 
01609     st= s->streams[stream_index];
01610     if(st->index_entries){
01611         AVIndexEntry *e;
01612 
01613         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()
01614         index= FFMAX(index, 0);
01615         e= &st->index_entries[index];
01616 
01617         if(e->timestamp <= target_ts || e->pos == e->min_distance){
01618             pos_min= e->pos;
01619             ts_min= e->timestamp;
01620             av_dlog(s, "using cached pos_min=0x%"PRIx64" dts_min=%"PRId64"\n",
01621                     pos_min,ts_min);
01622         }else{
01623             assert(index==0);
01624         }
01625 
01626         index= av_index_search_timestamp(st, target_ts, flags & ~AVSEEK_FLAG_BACKWARD);
01627         assert(index < st->nb_index_entries);
01628         if(index >= 0){
01629             e= &st->index_entries[index];
01630             assert(e->timestamp >= target_ts);
01631             pos_max= e->pos;
01632             ts_max= e->timestamp;
01633             pos_limit= pos_max - e->min_distance;
01634             av_dlog(s, "using cached pos_max=0x%"PRIx64" pos_limit=0x%"PRIx64" dts_max=%"PRId64"\n",
01635                     pos_max,pos_limit, ts_max);
01636         }
01637     }
01638 
01639     pos= av_gen_search(s, stream_index, target_ts, pos_min, pos_max, pos_limit, ts_min, ts_max, flags, &ts, avif->read_timestamp);
01640     if(pos<0)
01641         return -1;
01642 
01643     /* do the seek */
01644     if ((ret = avio_seek(s->pb, pos, SEEK_SET)) < 0)
01645         return ret;
01646 
01647     av_update_cur_dts(s, st, ts);
01648 
01649     return 0;
01650 }
01651 
01652 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 )){
01653     int64_t pos, ts;
01654     int64_t start_pos, filesize;
01655     int no_change;
01656 
01657     av_dlog(s, "gen_seek: %d %"PRId64"\n", stream_index, target_ts);
01658 
01659     if(ts_min == AV_NOPTS_VALUE){
01660         pos_min = s->data_offset;
01661         ts_min = read_timestamp(s, stream_index, &pos_min, INT64_MAX);
01662         if (ts_min == AV_NOPTS_VALUE)
01663             return -1;
01664     }
01665 
01666     if(ts_max == AV_NOPTS_VALUE){
01667         int step= 1024;
01668         filesize = avio_size(s->pb);
01669         pos_max = filesize - 1;
01670         do{
01671             pos_max -= step;
01672             ts_max = read_timestamp(s, stream_index, &pos_max, pos_max + step);
01673             step += step;
01674         }while(ts_max == AV_NOPTS_VALUE && pos_max >= step);
01675         if (ts_max == AV_NOPTS_VALUE)
01676             return -1;
01677 
01678         for(;;){
01679             int64_t tmp_pos= pos_max + 1;
01680             int64_t tmp_ts= read_timestamp(s, stream_index, &tmp_pos, INT64_MAX);
01681             if(tmp_ts == AV_NOPTS_VALUE)
01682                 break;
01683             ts_max= tmp_ts;
01684             pos_max= tmp_pos;
01685             if(tmp_pos >= filesize)
01686                 break;
01687         }
01688         pos_limit= pos_max;
01689     }
01690 
01691     if(ts_min > ts_max){
01692         return -1;
01693     }else if(ts_min == ts_max){
01694         pos_limit= pos_min;
01695     }
01696 
01697     no_change=0;
01698     while (pos_min < pos_limit) {
01699         av_dlog(s, "pos_min=0x%"PRIx64" pos_max=0x%"PRIx64" dts_min=%"PRId64" dts_max=%"PRId64"\n",
01700                 pos_min, pos_max, ts_min, ts_max);
01701         assert(pos_limit <= pos_max);
01702 
01703         if(no_change==0){
01704             int64_t approximate_keyframe_distance= pos_max - pos_limit;
01705             // interpolate position (better than dichotomy)
01706             pos = av_rescale(target_ts - ts_min, pos_max - pos_min, ts_max - ts_min)
01707                 + pos_min - approximate_keyframe_distance;
01708         }else if(no_change==1){
01709             // bisection, if interpolation failed to change min or max pos last time
01710             pos = (pos_min + pos_limit)>>1;
01711         }else{
01712             /* linear search if bisection failed, can only happen if there
01713                are very few or no keyframes between min/max */
01714             pos=pos_min;
01715         }
01716         if(pos <= pos_min)
01717             pos= pos_min + 1;
01718         else if(pos > pos_limit)
01719             pos= pos_limit;
01720         start_pos= pos;
01721 
01722         ts = read_timestamp(s, stream_index, &pos, INT64_MAX); //may pass pos_limit instead of -1
01723         if(pos == pos_max)
01724             no_change++;
01725         else
01726             no_change=0;
01727         av_dlog(s, "%"PRId64" %"PRId64" %"PRId64" / %"PRId64" %"PRId64" %"PRId64" target:%"PRId64" limit:%"PRId64" start:%"PRId64" noc:%d\n",
01728                 pos_min, pos, pos_max, ts_min, ts, ts_max, target_ts,
01729                 pos_limit, start_pos, no_change);
01730         if(ts == AV_NOPTS_VALUE){
01731             av_log(s, AV_LOG_ERROR, "read_timestamp() failed in the middle\n");
01732             return -1;
01733         }
01734         assert(ts != AV_NOPTS_VALUE);
01735         if (target_ts <= ts) {
01736             pos_limit = start_pos - 1;
01737             pos_max = pos;
01738             ts_max = ts;
01739         }
01740         if (target_ts >= ts) {
01741             pos_min = pos;
01742             ts_min = ts;
01743         }
01744     }
01745 
01746     pos = (flags & AVSEEK_FLAG_BACKWARD) ? pos_min : pos_max;
01747     ts  = (flags & AVSEEK_FLAG_BACKWARD) ?  ts_min :  ts_max;
01748     pos_min = pos;
01749     ts_min = read_timestamp(s, stream_index, &pos_min, INT64_MAX);
01750     pos_min++;
01751     ts_max = read_timestamp(s, stream_index, &pos_min, INT64_MAX);
01752     av_dlog(s, "pos=0x%"PRIx64" %"PRId64"<=%"PRId64"<=%"PRId64"\n",
01753             pos, ts_min, target_ts, ts_max);
01754     *ts_ret= ts;
01755     return pos;
01756 }
01757 
01758 static int av_seek_frame_byte(AVFormatContext *s, int stream_index, int64_t pos, int flags){
01759     int64_t pos_min, pos_max;
01760 #if 0
01761     AVStream *st;
01762 
01763     if (stream_index < 0)
01764         return -1;
01765 
01766     st= s->streams[stream_index];
01767 #endif
01768 
01769     pos_min = s->data_offset;
01770     pos_max = avio_size(s->pb) - 1;
01771 
01772     if     (pos < pos_min) pos= pos_min;
01773     else if(pos > pos_max) pos= pos_max;
01774 
01775     avio_seek(s->pb, pos, SEEK_SET);
01776 
01777 #if 0
01778     av_update_cur_dts(s, st, ts);
01779 #endif
01780     return 0;
01781 }
01782 
01783 static int av_seek_frame_generic(AVFormatContext *s,
01784                                  int stream_index, int64_t timestamp, int flags)
01785 {
01786     int index;
01787     int64_t ret;
01788     AVStream *st;
01789     AVIndexEntry *ie;
01790 
01791     st = s->streams[stream_index];
01792 
01793     index = av_index_search_timestamp(st, timestamp, flags);
01794 
01795     if(index < 0 && st->nb_index_entries && timestamp < st->index_entries[0].timestamp)
01796         return -1;
01797 
01798     if(index < 0 || index==st->nb_index_entries-1){
01799         int i;
01800         AVPacket pkt;
01801 
01802         if(st->nb_index_entries){
01803             assert(st->index_entries);
01804             ie= &st->index_entries[st->nb_index_entries-1];
01805             if ((ret = avio_seek(s->pb, ie->pos, SEEK_SET)) < 0)
01806                 return ret;
01807             av_update_cur_dts(s, st, ie->timestamp);
01808         }else{
01809             if ((ret = avio_seek(s->pb, s->data_offset, SEEK_SET)) < 0)
01810                 return ret;
01811         }
01812         for(i=0;; i++) {
01813             int ret;
01814             do{
01815                 ret = av_read_frame(s, &pkt);
01816             }while(ret == AVERROR(EAGAIN));
01817             if(ret<0)
01818                 break;
01819             av_free_packet(&pkt);
01820             if(stream_index == pkt.stream_index){
01821                 if((pkt.flags & AV_PKT_FLAG_KEY) && pkt.dts > timestamp)
01822                     break;
01823             }
01824         }
01825         index = av_index_search_timestamp(st, timestamp, flags);
01826     }
01827     if (index < 0)
01828         return -1;
01829 
01830     ff_read_frame_flush(s);
01831     if (s->iformat->read_seek){
01832         if(s->iformat->read_seek(s, stream_index, timestamp, flags) >= 0)
01833             return 0;
01834     }
01835     ie = &st->index_entries[index];
01836     if ((ret = avio_seek(s->pb, ie->pos, SEEK_SET)) < 0)
01837         return ret;
01838     av_update_cur_dts(s, st, ie->timestamp);
01839 
01840     return 0;
01841 }
01842 
01843 int av_seek_frame(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
01844 {
01845     int ret;
01846     AVStream *st;
01847 
01848     ff_read_frame_flush(s);
01849 
01850     if(flags & AVSEEK_FLAG_BYTE)
01851         return av_seek_frame_byte(s, stream_index, timestamp, flags);
01852 
01853     if(stream_index < 0){
01854         stream_index= av_find_default_stream_index(s);
01855         if(stream_index < 0)
01856             return -1;
01857 
01858         st= s->streams[stream_index];
01859        /* timestamp for default must be expressed in AV_TIME_BASE units */
01860         timestamp = av_rescale(timestamp, st->time_base.den, AV_TIME_BASE * (int64_t)st->time_base.num);
01861     }
01862 
01863     /* first, we try the format specific seek */
01864     if (s->iformat->read_seek)
01865         ret = s->iformat->read_seek(s, stream_index, timestamp, flags);
01866     else
01867         ret = -1;
01868     if (ret >= 0) {
01869         return 0;
01870     }
01871 
01872     if(s->iformat->read_timestamp && !(s->iformat->flags & AVFMT_NOBINSEARCH))
01873         return av_seek_frame_binary(s, stream_index, timestamp, flags);
01874     else if (!(s->iformat->flags & AVFMT_NOGENSEARCH))
01875         return av_seek_frame_generic(s, stream_index, timestamp, flags);
01876     else
01877         return -1;
01878 }
01879 
01880 int avformat_seek_file(AVFormatContext *s, int stream_index, int64_t min_ts, int64_t ts, int64_t max_ts, int flags)
01881 {
01882     if(min_ts > ts || max_ts < ts)
01883         return -1;
01884 
01885     ff_read_frame_flush(s);
01886 
01887     if (s->iformat->read_seek2)
01888         return s->iformat->read_seek2(s, stream_index, min_ts, ts, max_ts, flags);
01889 
01890     if(s->iformat->read_timestamp){
01891         //try to seek via read_timestamp()
01892     }
01893 
01894     //Fallback to old API if new is not implemented but old is
01895     //Note the old has somewat different sematics
01896     if(s->iformat->read_seek || 1)
01897         return av_seek_frame(s, stream_index, ts, flags | (ts - min_ts > (uint64_t)(max_ts - ts) ? AVSEEK_FLAG_BACKWARD : 0));
01898 
01899     // try some generic seek like av_seek_frame_generic() but with new ts semantics
01900 }
01901 
01902 /*******************************************************/
01903 
01909 static int av_has_duration(AVFormatContext *ic)
01910 {
01911     int i;
01912     AVStream *st;
01913 
01914     for(i = 0;i < ic->nb_streams; i++) {
01915         st = ic->streams[i];
01916         if (st->duration != AV_NOPTS_VALUE)
01917             return 1;
01918     }
01919     return 0;
01920 }
01921 
01927 static void av_update_stream_timings(AVFormatContext *ic)
01928 {
01929     int64_t start_time, start_time1, start_time_text, end_time, end_time1;
01930     int64_t duration, duration1;
01931     int i;
01932     AVStream *st;
01933 
01934     start_time = INT64_MAX;
01935     start_time_text = INT64_MAX;
01936     end_time = INT64_MIN;
01937     duration = INT64_MIN;
01938     for(i = 0;i < ic->nb_streams; i++) {
01939         st = ic->streams[i];
01940         if (st->start_time != AV_NOPTS_VALUE && st->time_base.den) {
01941             start_time1= av_rescale_q(st->start_time, st->time_base, AV_TIME_BASE_Q);
01942             if (st->codec->codec_id == CODEC_ID_DVB_TELETEXT) {
01943                 if (start_time1 < start_time_text)
01944                     start_time_text = start_time1;
01945             } else
01946             if (start_time1 < start_time)
01947                 start_time = start_time1;
01948             if (st->duration != AV_NOPTS_VALUE) {
01949                 end_time1 = start_time1
01950                           + av_rescale_q(st->duration, st->time_base, AV_TIME_BASE_Q);
01951                 if (end_time1 > end_time)
01952                     end_time = end_time1;
01953             }
01954         }
01955         if (st->duration != AV_NOPTS_VALUE) {
01956             duration1 = av_rescale_q(st->duration, st->time_base, AV_TIME_BASE_Q);
01957             if (duration1 > duration)
01958                 duration = duration1;
01959         }
01960     }
01961     if (start_time == INT64_MAX || (start_time > start_time_text && start_time - start_time_text < AV_TIME_BASE))
01962         start_time = start_time_text;
01963     if (start_time != INT64_MAX) {
01964         ic->start_time = start_time;
01965         if (end_time != INT64_MIN) {
01966             if (end_time - start_time > duration)
01967                 duration = end_time - start_time;
01968         }
01969     }
01970     if (duration != INT64_MIN) {
01971         ic->duration = duration;
01972         if (ic->file_size > 0) {
01973             /* compute the bitrate */
01974             ic->bit_rate = (double)ic->file_size * 8.0 * AV_TIME_BASE /
01975                 (double)ic->duration;
01976         }
01977     }
01978 }
01979 
01980 static void fill_all_stream_timings(AVFormatContext *ic)
01981 {
01982     int i;
01983     AVStream *st;
01984 
01985     av_update_stream_timings(ic);
01986     for(i = 0;i < ic->nb_streams; i++) {
01987         st = ic->streams[i];
01988         if (st->start_time == AV_NOPTS_VALUE) {
01989             if(ic->start_time != AV_NOPTS_VALUE)
01990                 st->start_time = av_rescale_q(ic->start_time, AV_TIME_BASE_Q, st->time_base);
01991             if(ic->duration != AV_NOPTS_VALUE)
01992                 st->duration = av_rescale_q(ic->duration, AV_TIME_BASE_Q, st->time_base);
01993         }
01994     }
01995 }
01996 
01997 static void av_estimate_timings_from_bit_rate(AVFormatContext *ic)
01998 {
01999     int64_t filesize, duration;
02000     int bit_rate, i;
02001     AVStream *st;
02002 
02003     /* if bit_rate is already set, we believe it */
02004     if (ic->bit_rate <= 0) {
02005         bit_rate = 0;
02006         for(i=0;i<ic->nb_streams;i++) {
02007             st = ic->streams[i];
02008             if (st->codec->bit_rate > 0)
02009             bit_rate += st->codec->bit_rate;
02010         }
02011         ic->bit_rate = bit_rate;
02012     }
02013 
02014     /* if duration is already set, we believe it */
02015     if (ic->duration == AV_NOPTS_VALUE &&
02016         ic->bit_rate != 0 &&
02017         ic->file_size != 0)  {
02018         filesize = ic->file_size;
02019         if (filesize > 0) {
02020             for(i = 0; i < ic->nb_streams; i++) {
02021                 st = ic->streams[i];
02022                 duration= av_rescale(8*filesize, st->time_base.den, ic->bit_rate*(int64_t)st->time_base.num);
02023                 if (st->duration == AV_NOPTS_VALUE)
02024                     st->duration = duration;
02025             }
02026         }
02027     }
02028 }
02029 
02030 #define DURATION_MAX_READ_SIZE 250000
02031 #define DURATION_MAX_RETRY 3
02032 
02033 /* only usable for MPEG-PS streams */
02034 static void av_estimate_timings_from_pts(AVFormatContext *ic, int64_t old_offset)
02035 {
02036     AVPacket pkt1, *pkt = &pkt1;
02037     AVStream *st;
02038     int read_size, i, ret;
02039     int64_t end_time;
02040     int64_t filesize, offset, duration;
02041     int retry=0;
02042 
02043     ic->cur_st = NULL;
02044 
02045     /* flush packet queue */
02046     flush_packet_queue(ic);
02047 
02048     for (i=0; i<ic->nb_streams; i++) {
02049         st = ic->streams[i];
02050         if (st->start_time == AV_NOPTS_VALUE && st->first_dts == AV_NOPTS_VALUE)
02051             av_log(st->codec, AV_LOG_WARNING, "start time is not set in av_estimate_timings_from_pts\n");
02052 
02053         if (st->parser) {
02054             av_parser_close(st->parser);
02055             st->parser= NULL;
02056             av_free_packet(&st->cur_pkt);
02057         }
02058     }
02059 
02060     /* estimate the end time (duration) */
02061     /* XXX: may need to support wrapping */
02062     filesize = ic->file_size;
02063     end_time = AV_NOPTS_VALUE;
02064     do{
02065     offset = filesize - (DURATION_MAX_READ_SIZE<<retry);
02066     if (offset < 0)
02067         offset = 0;
02068 
02069     avio_seek(ic->pb, offset, SEEK_SET);
02070     read_size = 0;
02071     for(;;) {
02072         if (read_size >= DURATION_MAX_READ_SIZE<<(FFMAX(retry-1,0)))
02073             break;
02074 
02075         do{
02076             ret = av_read_packet(ic, pkt);
02077         }while(ret == AVERROR(EAGAIN));
02078         if (ret != 0)
02079             break;
02080         read_size += pkt->size;
02081         st = ic->streams[pkt->stream_index];
02082         if (pkt->pts != AV_NOPTS_VALUE &&
02083             (st->start_time != AV_NOPTS_VALUE ||
02084              st->first_dts  != AV_NOPTS_VALUE)) {
02085             duration = end_time = pkt->pts;
02086             if (st->start_time != AV_NOPTS_VALUE)  duration -= st->start_time;
02087             else                                   duration -= st->first_dts;
02088             if (duration < 0)
02089                 duration += 1LL<<st->pts_wrap_bits;
02090             if (duration > 0) {
02091                 if (st->duration == AV_NOPTS_VALUE ||
02092                     st->duration < duration)
02093                     st->duration = duration;
02094             }
02095         }
02096         av_free_packet(pkt);
02097     }
02098     }while(   end_time==AV_NOPTS_VALUE
02099            && filesize > (DURATION_MAX_READ_SIZE<<retry)
02100            && ++retry <= DURATION_MAX_RETRY);
02101 
02102     fill_all_stream_timings(ic);
02103 
02104     avio_seek(ic->pb, old_offset, SEEK_SET);
02105     for (i=0; i<ic->nb_streams; i++) {
02106         st= ic->streams[i];
02107         st->cur_dts= st->first_dts;
02108         st->last_IP_pts = AV_NOPTS_VALUE;
02109         st->reference_dts = AV_NOPTS_VALUE;
02110     }
02111 }
02112 
02113 static void av_estimate_timings(AVFormatContext *ic, int64_t old_offset)
02114 {
02115     int64_t file_size;
02116 
02117     /* get the file size, if possible */
02118     if (ic->iformat->flags & AVFMT_NOFILE) {
02119         file_size = 0;
02120     } else {
02121         file_size = avio_size(ic->pb);
02122         if (file_size < 0)
02123             file_size = 0;
02124     }
02125     ic->file_size = file_size;
02126 
02127     if ((!strcmp(ic->iformat->name, "mpeg") ||
02128          !strcmp(ic->iformat->name, "mpegts")) &&
02129         file_size && ic->pb->seekable) {
02130         /* get accurate estimate from the PTSes */
02131         av_estimate_timings_from_pts(ic, old_offset);
02132     } else if (av_has_duration(ic)) {
02133         /* at least one component has timings - we use them for all
02134            the components */
02135         fill_all_stream_timings(ic);
02136     } else {
02137         av_log(ic, AV_LOG_WARNING, "Estimating duration from bitrate, this may be inaccurate\n");
02138         /* less precise: use bitrate info */
02139         av_estimate_timings_from_bit_rate(ic);
02140     }
02141     av_update_stream_timings(ic);
02142 
02143 #if 0
02144     {
02145         int i;
02146         AVStream av_unused *st;
02147         for(i = 0;i < ic->nb_streams; i++) {
02148             st = ic->streams[i];
02149         printf("%d: start_time: %0.3f duration: %0.3f\n",
02150                i, (double)st->start_time / AV_TIME_BASE,
02151                (double)st->duration / AV_TIME_BASE);
02152         }
02153         printf("stream: start_time: %0.3f duration: %0.3f bitrate=%d kb/s\n",
02154                (double)ic->start_time / AV_TIME_BASE,
02155                (double)ic->duration / AV_TIME_BASE,
02156                ic->bit_rate / 1000);
02157     }
02158 #endif
02159 }
02160 
02161 static int has_codec_parameters(AVCodecContext *enc)
02162 {
02163     int val;
02164     switch(enc->codec_type) {
02165     case AVMEDIA_TYPE_AUDIO:
02166         val = enc->sample_rate && enc->channels && enc->sample_fmt != AV_SAMPLE_FMT_NONE;
02167         if(!enc->frame_size &&
02168            (enc->codec_id == CODEC_ID_VORBIS ||
02169             enc->codec_id == CODEC_ID_AAC ||
02170             enc->codec_id == CODEC_ID_MP1 ||
02171             enc->codec_id == CODEC_ID_MP2 ||
02172             enc->codec_id == CODEC_ID_MP3 ||
02173             enc->codec_id == CODEC_ID_SPEEX ||
02174             enc->codec_id == CODEC_ID_CELT))
02175             return 0;
02176         break;
02177     case AVMEDIA_TYPE_VIDEO:
02178         val = enc->width && enc->pix_fmt != PIX_FMT_NONE;
02179         break;
02180     default:
02181         val = 1;
02182         break;
02183     }
02184     return enc->codec_id != CODEC_ID_NONE && val != 0;
02185 }
02186 
02187 static int has_decode_delay_been_guessed(AVStream *st)
02188 {
02189     return st->codec->codec_id != CODEC_ID_H264 ||
02190         st->codec_info_nb_frames >= 6 + st->codec->has_b_frames;
02191 }
02192 
02193 static int try_decode_frame(AVStream *st, AVPacket *avpkt, AVDictionary **options)
02194 {
02195     int16_t *samples;
02196     AVCodec *codec;
02197     int got_picture, data_size, ret=0;
02198     AVFrame picture;
02199 
02200     if(!st->codec->codec){
02201         codec = avcodec_find_decoder(st->codec->codec_id);
02202         if (!codec)
02203             return -1;
02204         ret = avcodec_open2(st->codec, codec, options);
02205         if (ret < 0)
02206             return ret;
02207     }
02208 
02209     if(!has_codec_parameters(st->codec) || !has_decode_delay_been_guessed(st)){
02210         switch(st->codec->codec_type) {
02211         case AVMEDIA_TYPE_VIDEO:
02212             avcodec_get_frame_defaults(&picture);
02213             ret = avcodec_decode_video2(st->codec, &picture,
02214                                         &got_picture, avpkt);
02215             break;
02216         case AVMEDIA_TYPE_AUDIO:
02217             data_size = FFMAX(avpkt->size, AVCODEC_MAX_AUDIO_FRAME_SIZE);
02218             samples = av_malloc(data_size);
02219             if (!samples)
02220                 goto fail;
02221             ret = avcodec_decode_audio3(st->codec, samples,
02222                                         &data_size, avpkt);
02223             av_free(samples);
02224             break;
02225         default:
02226             break;
02227         }
02228     }
02229  fail:
02230     return ret;
02231 }
02232 
02233 unsigned int ff_codec_get_tag(const AVCodecTag *tags, enum CodecID id)
02234 {
02235     while (tags->id != CODEC_ID_NONE) {
02236         if (tags->id == id)
02237             return tags->tag;
02238         tags++;
02239     }
02240     return 0;
02241 }
02242 
02243 enum CodecID ff_codec_get_id(const AVCodecTag *tags, unsigned int tag)
02244 {
02245     int i;
02246     for(i=0; tags[i].id != CODEC_ID_NONE;i++) {
02247         if(tag == tags[i].tag)
02248             return tags[i].id;
02249     }
02250     for(i=0; tags[i].id != CODEC_ID_NONE; i++) {
02251         if (ff_toupper4(tag) == ff_toupper4(tags[i].tag))
02252             return tags[i].id;
02253     }
02254     return CODEC_ID_NONE;
02255 }
02256 
02257 unsigned int av_codec_get_tag(const AVCodecTag * const *tags, enum CodecID id)
02258 {
02259     int i;
02260     for(i=0; tags && tags[i]; i++){
02261         int tag= ff_codec_get_tag(tags[i], id);
02262         if(tag) return tag;
02263     }
02264     return 0;
02265 }
02266 
02267 enum CodecID av_codec_get_id(const AVCodecTag * const *tags, unsigned int tag)
02268 {
02269     int i;
02270     for(i=0; tags && tags[i]; i++){
02271         enum CodecID id= ff_codec_get_id(tags[i], tag);
02272         if(id!=CODEC_ID_NONE) return id;
02273     }
02274     return CODEC_ID_NONE;
02275 }
02276 
02277 static void compute_chapters_end(AVFormatContext *s)
02278 {
02279     unsigned int i, j;
02280     int64_t max_time = s->duration + ((s->start_time == AV_NOPTS_VALUE) ? 0 : s->start_time);
02281 
02282     for (i = 0; i < s->nb_chapters; i++)
02283         if (s->chapters[i]->end == AV_NOPTS_VALUE) {
02284             AVChapter *ch = s->chapters[i];
02285             int64_t   end = max_time ? av_rescale_q(max_time, AV_TIME_BASE_Q, ch->time_base)
02286                                      : INT64_MAX;
02287 
02288             for (j = 0; j < s->nb_chapters; j++) {
02289                 AVChapter *ch1 = s->chapters[j];
02290                 int64_t next_start = av_rescale_q(ch1->start, ch1->time_base, ch->time_base);
02291                 if (j != i && next_start > ch->start && next_start < end)
02292                     end = next_start;
02293             }
02294             ch->end = (end == INT64_MAX) ? ch->start : end;
02295         }
02296 }
02297 
02298 static int get_std_framerate(int i){
02299     if(i<60*12) return i*1001;
02300     else        return ((const int[]){24,30,60,12,15})[i-60*12]*1000*12;
02301 }
02302 
02303 /*
02304  * Is the time base unreliable.
02305  * This is a heuristic to balance between quick acceptance of the values in
02306  * the headers vs. some extra checks.
02307  * Old DivX and Xvid often have nonsense timebases like 1fps or 2fps.
02308  * MPEG-2 commonly misuses field repeat flags to store different framerates.
02309  * And there are "variable" fps files this needs to detect as well.
02310  */
02311 static int tb_unreliable(AVCodecContext *c){
02312     if(   c->time_base.den >= 101L*c->time_base.num
02313        || c->time_base.den <    5L*c->time_base.num
02314 /*       || c->codec_tag == AV_RL32("DIVX")
02315        || c->codec_tag == AV_RL32("XVID")*/
02316        || c->codec_id == CODEC_ID_MPEG2VIDEO
02317        || c->codec_id == CODEC_ID_H264
02318        )
02319         return 1;
02320     return 0;
02321 }
02322 
02323 #if FF_API_FORMAT_PARAMETERS
02324 int av_find_stream_info(AVFormatContext *ic)
02325 {
02326     return avformat_find_stream_info(ic, NULL);
02327 }
02328 #endif
02329 
02330 int avformat_find_stream_info(AVFormatContext *ic, AVDictionary **options)
02331 {
02332     int i, count, ret, read_size, j;
02333     AVStream *st;
02334     AVPacket pkt1, *pkt;
02335     int64_t old_offset = avio_tell(ic->pb);
02336     int orig_nb_streams = ic->nb_streams;        // new streams might appear, no options for those
02337 
02338     for(i=0;i<ic->nb_streams;i++) {
02339         AVCodec *codec;
02340         st = ic->streams[i];
02341         if (st->codec->codec_id == CODEC_ID_AAC) {
02342             st->codec->sample_rate = 0;
02343             st->codec->frame_size = 0;
02344             st->codec->channels = 0;
02345         }
02346         if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO ||
02347             st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
02348 /*            if(!st->time_base.num)
02349                 st->time_base= */
02350             if(!st->codec->time_base.num)
02351                 st->codec->time_base= st->time_base;
02352         }
02353         //only for the split stuff
02354         if (!st->parser && !(ic->flags & AVFMT_FLAG_NOPARSE)) {
02355             st->parser = av_parser_init(st->codec->codec_id);
02356             if(st->need_parsing == AVSTREAM_PARSE_HEADERS && st->parser){
02357                 st->parser->flags |= PARSER_FLAG_COMPLETE_FRAMES;
02358             }
02359         }
02360         assert(!st->codec->codec);
02361         codec = avcodec_find_decoder(st->codec->codec_id);
02362 
02363         /* Force decoding of at least one frame of codec data
02364          * this makes sure the codec initializes the channel configuration
02365          * and does not trust the values from the container.
02366          */
02367         if (codec && codec->capabilities & CODEC_CAP_CHANNEL_CONF)
02368             st->codec->channels = 0;
02369 
02370         /* Ensure that subtitle_header is properly set. */
02371         if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE
02372             && codec && !st->codec->codec)
02373             avcodec_open2(st->codec, codec, options ? &options[i] : NULL);
02374 
02375         //try to just open decoders, in case this is enough to get parameters
02376         if(!has_codec_parameters(st->codec)){
02377             if (codec && !st->codec->codec)
02378                 avcodec_open2(st->codec, codec, options ? &options[i] : NULL);
02379         }
02380     }
02381 
02382     for (i=0; i<ic->nb_streams; i++) {
02383         ic->streams[i]->info->last_dts = AV_NOPTS_VALUE;
02384     }
02385 
02386     count = 0;
02387     read_size = 0;
02388     for(;;) {
02389         if(url_interrupt_cb()){
02390             ret= AVERROR_EXIT;
02391             av_log(ic, AV_LOG_DEBUG, "interrupted\n");
02392             break;
02393         }
02394 
02395         /* check if one codec still needs to be handled */
02396         for(i=0;i<ic->nb_streams;i++) {
02397             int fps_analyze_framecount = 20;
02398 
02399             st = ic->streams[i];
02400             if (!has_codec_parameters(st->codec))
02401                 break;
02402             /* if the timebase is coarse (like the usual millisecond precision
02403                of mkv), we need to analyze more frames to reliably arrive at
02404                the correct fps */
02405             if (av_q2d(st->time_base) > 0.0005)
02406                 fps_analyze_framecount *= 2;
02407             if (ic->fps_probe_size >= 0)
02408                 fps_analyze_framecount = ic->fps_probe_size;
02409             /* variable fps and no guess at the real fps */
02410             if(   tb_unreliable(st->codec) && !(st->r_frame_rate.num && st->avg_frame_rate.num)
02411                && st->info->duration_count < fps_analyze_framecount
02412                && st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
02413                 break;
02414             if(st->parser && st->parser->parser->split && !st->codec->extradata)
02415                 break;
02416             if(st->first_dts == AV_NOPTS_VALUE)
02417                 break;
02418         }
02419         if (i == ic->nb_streams) {
02420             /* NOTE: if the format has no header, then we need to read
02421                some packets to get most of the streams, so we cannot
02422                stop here */
02423             if (!(ic->ctx_flags & AVFMTCTX_NOHEADER)) {
02424                 /* if we found the info for all the codecs, we can stop */
02425                 ret = count;
02426                 av_log(ic, AV_LOG_DEBUG, "All info found\n");
02427                 break;
02428             }
02429         }
02430         /* we did not get all the codec info, but we read too much data */
02431         if (read_size >= ic->probesize) {
02432             ret = count;
02433             av_log(ic, AV_LOG_DEBUG, "Probe buffer size limit %d reached\n", ic->probesize);
02434             break;
02435         }
02436 
02437         /* NOTE: a new stream can be added there if no header in file
02438            (AVFMTCTX_NOHEADER) */
02439         ret = av_read_frame_internal(ic, &pkt1);
02440         if (ret < 0 && ret != AVERROR(EAGAIN)) {
02441             /* EOF or error */
02442             ret = -1; /* we could not have all the codec parameters before EOF */
02443             for(i=0;i<ic->nb_streams;i++) {
02444                 st = ic->streams[i];
02445                 if (!has_codec_parameters(st->codec)){
02446                     char buf[256];
02447                     avcodec_string(buf, sizeof(buf), st->codec, 0);
02448                     av_log(ic, AV_LOG_WARNING, "Could not find codec parameters (%s)\n", buf);
02449                 } else {
02450                     ret = 0;
02451                 }
02452             }
02453             break;
02454         }
02455 
02456         if (ret == AVERROR(EAGAIN))
02457             continue;
02458 
02459         pkt= add_to_pktbuf(&ic->packet_buffer, &pkt1, &ic->packet_buffer_end);
02460         if ((ret = av_dup_packet(pkt)) < 0)
02461             goto find_stream_info_err;
02462 
02463         read_size += pkt->size;
02464 
02465         st = ic->streams[pkt->stream_index];
02466         if (st->codec_info_nb_frames>1) {
02467             int64_t t;
02468             if (st->time_base.den > 0 && (t=av_rescale_q(st->info->codec_info_duration, st->time_base, AV_TIME_BASE_Q)) >= ic->max_analyze_duration) {
02469                 av_log(ic, AV_LOG_WARNING, "max_analyze_duration %d reached at %"PRId64"\n", ic->max_analyze_duration, t);
02470                 break;
02471             }
02472             st->info->codec_info_duration += pkt->duration;
02473         }
02474         {
02475             int64_t last = st->info->last_dts;
02476 
02477             if(pkt->dts != AV_NOPTS_VALUE && last != AV_NOPTS_VALUE && pkt->dts > last){
02478                 int64_t duration= pkt->dts - last;
02479                 double dur= duration * av_q2d(st->time_base);
02480 
02481 //                if(st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
02482 //                    av_log(NULL, AV_LOG_ERROR, "%f\n", dur);
02483                 if (st->info->duration_count < 2)
02484                     memset(st->info->duration_error, 0, sizeof(st->info->duration_error));
02485                 for (i=1; i<FF_ARRAY_ELEMS(st->info->duration_error); i++) {
02486                     int framerate= get_std_framerate(i);
02487                     int ticks= lrintf(dur*framerate/(1001*12));
02488                     double error = dur - (double)ticks*1001*12 / framerate;
02489                     st->info->duration_error[i] += error*error;
02490                 }
02491                 st->info->duration_count++;
02492                 // ignore the first 4 values, they might have some random jitter
02493                 if (st->info->duration_count > 3)
02494                     st->info->duration_gcd = av_gcd(st->info->duration_gcd, duration);
02495             }
02496             if (last == AV_NOPTS_VALUE || st->info->duration_count <= 1)
02497                 st->info->last_dts = pkt->dts;
02498         }
02499         if(st->parser && st->parser->parser->split && !st->codec->extradata){
02500             int i= st->parser->parser->split(st->codec, pkt->data, pkt->size);
02501             if(i){
02502                 st->codec->extradata_size= i;
02503                 st->codec->extradata= av_malloc(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
02504                 memcpy(st->codec->extradata, pkt->data, st->codec->extradata_size);
02505                 memset(st->codec->extradata + i, 0, FF_INPUT_BUFFER_PADDING_SIZE);
02506             }
02507         }
02508 
02509         /* if still no information, we try to open the codec and to
02510            decompress the frame. We try to avoid that in most cases as
02511            it takes longer and uses more memory. For MPEG-4, we need to
02512            decompress for QuickTime. */
02513         if (!has_codec_parameters(st->codec) || !has_decode_delay_been_guessed(st))
02514             try_decode_frame(st, pkt, (options && i < orig_nb_streams )? &options[i] : NULL);
02515 
02516         st->codec_info_nb_frames++;
02517         count++;
02518     }
02519 
02520     // close codecs which were opened in try_decode_frame()
02521     for(i=0;i<ic->nb_streams;i++) {
02522         st = ic->streams[i];
02523         if(st->codec->codec)
02524             avcodec_close(st->codec);
02525     }
02526     for(i=0;i<ic->nb_streams;i++) {
02527         st = ic->streams[i];
02528         if (st->codec_info_nb_frames>2 && !st->avg_frame_rate.num && st->info->codec_info_duration)
02529             av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
02530                      (st->codec_info_nb_frames-2)*(int64_t)st->time_base.den,
02531                       st->info->codec_info_duration*(int64_t)st->time_base.num, 60000);
02532         if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
02533             if(st->codec->codec_id == CODEC_ID_RAWVIDEO && !st->codec->codec_tag && !st->codec->bits_per_coded_sample){
02534                 uint32_t tag= avcodec_pix_fmt_to_codec_tag(st->codec->pix_fmt);
02535                 if(ff_find_pix_fmt(ff_raw_pix_fmt_tags, tag) == st->codec->pix_fmt)
02536                     st->codec->codec_tag= tag;
02537             }
02538 
02539             // the check for tb_unreliable() is not completely correct, since this is not about handling
02540             // a unreliable/inexact time base, but a time base that is finer than necessary, as e.g.
02541             // ipmovie.c produces.
02542             if (tb_unreliable(st->codec) && st->info->duration_count > 15 && st->info->duration_gcd > FFMAX(1, st->time_base.den/(500LL*st->time_base.num)) && !st->r_frame_rate.num)
02543                 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);
02544             if (st->info->duration_count && !st->r_frame_rate.num
02545                && tb_unreliable(st->codec) /*&&
02546                //FIXME we should not special-case MPEG-2, but this needs testing with non-MPEG-2 ...
02547                st->time_base.num*duration_sum[i]/st->info->duration_count*101LL > st->time_base.den*/){
02548                 int num = 0;
02549                 double best_error= 2*av_q2d(st->time_base);
02550                 best_error = best_error*best_error*st->info->duration_count*1000*12*30;
02551 
02552                 for (j=1; j<FF_ARRAY_ELEMS(st->info->duration_error); j++) {
02553                     double error = st->info->duration_error[j] * get_std_framerate(j);
02554 //                    if(st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
02555 //                        av_log(NULL, AV_LOG_ERROR, "%f %f\n", get_std_framerate(j) / 12.0/1001, error);
02556                     if(error < best_error){
02557                         best_error= error;
02558                         num = get_std_framerate(j);
02559                     }
02560                 }
02561                 // do not increase frame rate by more than 1 % in order to match a standard rate.
02562                 if (num && (!st->r_frame_rate.num || (double)num/(12*1001) < 1.01 * av_q2d(st->r_frame_rate)))
02563                     av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den, num, 12*1001, INT_MAX);
02564             }
02565 
02566             if (!st->r_frame_rate.num){
02567                 if(    st->codec->time_base.den * (int64_t)st->time_base.num
02568                     <= st->codec->time_base.num * st->codec->ticks_per_frame * (int64_t)st->time_base.den){
02569                     st->r_frame_rate.num = st->codec->time_base.den;
02570                     st->r_frame_rate.den = st->codec->time_base.num * st->codec->ticks_per_frame;
02571                 }else{
02572                     st->r_frame_rate.num = st->time_base.den;
02573                     st->r_frame_rate.den = st->time_base.num;
02574                 }
02575             }
02576         }else if(st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
02577             if(!st->codec->bits_per_coded_sample)
02578                 st->codec->bits_per_coded_sample= av_get_bits_per_sample(st->codec->codec_id);
02579             // set stream disposition based on audio service type
02580             switch (st->codec->audio_service_type) {
02581             case AV_AUDIO_SERVICE_TYPE_EFFECTS:
02582                 st->disposition = AV_DISPOSITION_CLEAN_EFFECTS;    break;
02583             case AV_AUDIO_SERVICE_TYPE_VISUALLY_IMPAIRED:
02584                 st->disposition = AV_DISPOSITION_VISUAL_IMPAIRED;  break;
02585             case AV_AUDIO_SERVICE_TYPE_HEARING_IMPAIRED:
02586                 st->disposition = AV_DISPOSITION_HEARING_IMPAIRED; break;
02587             case AV_AUDIO_SERVICE_TYPE_COMMENTARY:
02588                 st->disposition = AV_DISPOSITION_COMMENT;          break;
02589             case AV_AUDIO_SERVICE_TYPE_KARAOKE:
02590                 st->disposition = AV_DISPOSITION_KARAOKE;          break;
02591             }
02592         }
02593     }
02594 
02595     av_estimate_timings(ic, old_offset);
02596 
02597     compute_chapters_end(ic);
02598 
02599 #if 0
02600     /* correct DTS for B-frame streams with no timestamps */
02601     for(i=0;i<ic->nb_streams;i++) {
02602         st = ic->streams[i];
02603         if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
02604             if(b-frames){
02605                 ppktl = &ic->packet_buffer;
02606                 while(ppkt1){
02607                     if(ppkt1->stream_index != i)
02608                         continue;
02609                     if(ppkt1->pkt->dts < 0)
02610                         break;
02611                     if(ppkt1->pkt->pts != AV_NOPTS_VALUE)
02612                         break;
02613                     ppkt1->pkt->dts -= delta;
02614                     ppkt1= ppkt1->next;
02615                 }
02616                 if(ppkt1)
02617                     continue;
02618                 st->cur_dts -= delta;
02619             }
02620         }
02621     }
02622 #endif
02623 
02624  find_stream_info_err:
02625     for (i=0; i < ic->nb_streams; i++)
02626         av_freep(&ic->streams[i]->info);
02627     return ret;
02628 }
02629 
02630 static AVProgram *find_program_from_stream(AVFormatContext *ic, int s)
02631 {
02632     int i, j;
02633 
02634     for (i = 0; i < ic->nb_programs; i++)
02635         for (j = 0; j < ic->programs[i]->nb_stream_indexes; j++)
02636             if (ic->programs[i]->stream_index[j] == s)
02637                 return ic->programs[i];
02638     return NULL;
02639 }
02640 
02641 int av_find_best_stream(AVFormatContext *ic,
02642                         enum AVMediaType type,
02643                         int wanted_stream_nb,
02644                         int related_stream,
02645                         AVCodec **decoder_ret,
02646                         int flags)
02647 {
02648     int i, nb_streams = ic->nb_streams;
02649     int ret = AVERROR_STREAM_NOT_FOUND, best_count = -1;
02650     unsigned *program = NULL;
02651     AVCodec *decoder = NULL, *best_decoder = NULL;
02652 
02653     if (related_stream >= 0 && wanted_stream_nb < 0) {
02654         AVProgram *p = find_program_from_stream(ic, related_stream);
02655         if (p) {
02656             program = p->stream_index;
02657             nb_streams = p->nb_stream_indexes;
02658         }
02659     }
02660     for (i = 0; i < nb_streams; i++) {
02661         int real_stream_index = program ? program[i] : i;
02662         AVStream *st = ic->streams[real_stream_index];
02663         AVCodecContext *avctx = st->codec;
02664         if (avctx->codec_type != type)
02665             continue;
02666         if (wanted_stream_nb >= 0 && real_stream_index != wanted_stream_nb)
02667             continue;
02668         if (st->disposition & (AV_DISPOSITION_HEARING_IMPAIRED|AV_DISPOSITION_VISUAL_IMPAIRED))
02669             continue;
02670         if (decoder_ret) {
02671             decoder = avcodec_find_decoder(st->codec->codec_id);
02672             if (!decoder) {
02673                 if (ret < 0)
02674                     ret = AVERROR_DECODER_NOT_FOUND;
02675                 continue;
02676             }
02677         }
02678         if (best_count >= st->codec_info_nb_frames)
02679             continue;
02680         best_count = st->codec_info_nb_frames;
02681         ret = real_stream_index;
02682         best_decoder = decoder;
02683         if (program && i == nb_streams - 1 && ret < 0) {
02684             program = NULL;
02685             nb_streams = ic->nb_streams;
02686             i = 0; /* no related stream found, try again with everything */
02687         }
02688     }
02689     if (decoder_ret)
02690         *decoder_ret = best_decoder;
02691     return ret;
02692 }
02693 
02694 /*******************************************************/
02695 
02696 int av_read_play(AVFormatContext *s)
02697 {
02698     if (s->iformat->read_play)
02699         return s->iformat->read_play(s);
02700     if (s->pb)
02701         return avio_pause(s->pb, 0);
02702     return AVERROR(ENOSYS);
02703 }
02704 
02705 int av_read_pause(AVFormatContext *s)
02706 {
02707     if (s->iformat->read_pause)
02708         return s->iformat->read_pause(s);
02709     if (s->pb)
02710         return avio_pause(s->pb, 1);
02711     return AVERROR(ENOSYS);
02712 }
02713 
02714 void av_close_input_stream(AVFormatContext *s)
02715 {
02716     flush_packet_queue(s);
02717     if (s->iformat->read_close)
02718         s->iformat->read_close(s);
02719     avformat_free_context(s);
02720 }
02721 
02722 void avformat_free_context(AVFormatContext *s)
02723 {
02724     int i;
02725     AVStream *st;
02726 
02727     av_opt_free(s);
02728     if (s->iformat && s->iformat->priv_class && s->priv_data)
02729         av_opt_free(s->priv_data);
02730 
02731     for(i=0;i<s->nb_streams;i++) {
02732         /* free all data in a stream component */
02733         st = s->streams[i];
02734         if (st->parser) {
02735             av_parser_close(st->parser);
02736             av_free_packet(&st->cur_pkt);
02737         }
02738         av_dict_free(&st->metadata);
02739         av_freep(&st->index_entries);
02740         av_freep(&st->codec->extradata);
02741         av_freep(&st->codec->subtitle_header);
02742         av_freep(&st->codec);
02743 #if FF_API_OLD_METADATA
02744         av_freep(&st->filename);
02745 #endif
02746         av_freep(&st->priv_data);
02747         av_freep(&st->info);
02748         av_freep(&st);
02749     }
02750     for(i=s->nb_programs-1; i>=0; i--) {
02751 #if FF_API_OLD_METADATA
02752         av_freep(&s->programs[i]->provider_name);
02753         av_freep(&s->programs[i]->name);
02754 #endif
02755         av_metadata_free(&s->programs[i]->metadata);
02756         av_freep(&s->programs[i]->stream_index);
02757         av_freep(&s->programs[i]);
02758     }
02759     av_freep(&s->programs);
02760     av_freep(&s->priv_data);
02761     while(s->nb_chapters--) {
02762 #if FF_API_OLD_METADATA
02763         av_free(s->chapters[s->nb_chapters]->title);
02764 #endif
02765         av_dict_free(&s->chapters[s->nb_chapters]->metadata);
02766         av_freep(&s->chapters[s->nb_chapters]);
02767     }
02768     av_freep(&s->chapters);
02769     av_metadata_free(&s->metadata);
02770 //    av_freep(&s->key);
02771     av_free(s);
02772 }
02773 
02774 void av_close_input_file(AVFormatContext *s)
02775 {
02776     AVIOContext *pb = (s->iformat->flags & AVFMT_NOFILE) || (s->flags & AVFMT_FLAG_CUSTOM_IO) ?
02777                        NULL : s->pb;
02778     av_close_input_stream(s);
02779     if (pb)
02780         avio_close(pb);
02781 }
02782 
02783 AVStream *av_new_stream(AVFormatContext *s, int id)
02784 {
02785     AVStream *st;
02786     int i;
02787 
02788 #if FF_API_MAX_STREAMS
02789     if (s->nb_streams >= MAX_STREAMS){
02790         av_log(s, AV_LOG_ERROR, "Too many streams\n");
02791         return NULL;
02792     }
02793 #else
02794     AVStream **streams;
02795 
02796     if (s->nb_streams >= INT_MAX/sizeof(*streams))
02797         return NULL;
02798     streams = av_realloc(s->streams, (s->nb_streams + 1) * sizeof(*streams));
02799     if (!streams)
02800         return NULL;
02801     s->streams = streams;
02802 #endif
02803 
02804     st = av_mallocz(sizeof(AVStream));
02805     if (!st)
02806         return NULL;
02807     if (!(st->info = av_mallocz(sizeof(*st->info)))) {
02808         av_free(st);
02809         return NULL;
02810     }
02811 
02812     st->codec= avcodec_alloc_context();
02813     if (s->iformat) {
02814         /* no default bitrate if decoding */
02815         st->codec->bit_rate = 0;
02816     }
02817     st->index = s->nb_streams;
02818     st->id = id;
02819     st->start_time = AV_NOPTS_VALUE;
02820     st->duration = AV_NOPTS_VALUE;
02821         /* we set the current DTS to 0 so that formats without any timestamps
02822            but durations get some timestamps, formats with some unknown
02823            timestamps have their first few packets buffered and the
02824            timestamps corrected before they are returned to the user */
02825     st->cur_dts = 0;
02826     st->first_dts = AV_NOPTS_VALUE;
02827     st->probe_packets = MAX_PROBE_PACKETS;
02828 
02829     /* default pts setting is MPEG-like */
02830     av_set_pts_info(st, 33, 1, 90000);
02831     st->last_IP_pts = AV_NOPTS_VALUE;
02832     for(i=0; i<MAX_REORDER_DELAY+1; i++)
02833         st->pts_buffer[i]= AV_NOPTS_VALUE;
02834     st->reference_dts = AV_NOPTS_VALUE;
02835 
02836     st->sample_aspect_ratio = (AVRational){0,1};
02837 
02838     s->streams[s->nb_streams++] = st;
02839     return st;
02840 }
02841 
02842 AVProgram *av_new_program(AVFormatContext *ac, int id)
02843 {
02844     AVProgram *program=NULL;
02845     int i;
02846 
02847     av_dlog(ac, "new_program: id=0x%04x\n", id);
02848 
02849     for(i=0; i<ac->nb_programs; i++)
02850         if(ac->programs[i]->id == id)
02851             program = ac->programs[i];
02852 
02853     if(!program){
02854         program = av_mallocz(sizeof(AVProgram));
02855         if (!program)
02856             return NULL;
02857         dynarray_add(&ac->programs, &ac->nb_programs, program);
02858         program->discard = AVDISCARD_NONE;
02859     }
02860     program->id = id;
02861 
02862     return program;
02863 }
02864 
02865 AVChapter *ff_new_chapter(AVFormatContext *s, int id, AVRational time_base, int64_t start, int64_t end, const char *title)
02866 {
02867     AVChapter *chapter = NULL;
02868     int i;
02869 
02870     for(i=0; i<s->nb_chapters; i++)
02871         if(s->chapters[i]->id == id)
02872             chapter = s->chapters[i];
02873 
02874     if(!chapter){
02875         chapter= av_mallocz(sizeof(AVChapter));
02876         if(!chapter)
02877             return NULL;
02878         dynarray_add(&s->chapters, &s->nb_chapters, chapter);
02879     }
02880 #if FF_API_OLD_METADATA
02881     av_free(chapter->title);
02882 #endif
02883     av_dict_set(&chapter->metadata, "title", title, 0);
02884     chapter->id    = id;
02885     chapter->time_base= time_base;
02886     chapter->start = start;
02887     chapter->end   = end;
02888 
02889     return chapter;
02890 }
02891 
02892 /************************************************************/
02893 /* output media file */
02894 
02895 #if FF_API_FORMAT_PARAMETERS
02896 int av_set_parameters(AVFormatContext *s, AVFormatParameters *ap)
02897 {
02898     if (s->oformat->priv_data_size > 0) {
02899         s->priv_data = av_mallocz(s->oformat->priv_data_size);
02900         if (!s->priv_data)
02901             return AVERROR(ENOMEM);
02902         if (s->oformat->priv_class) {
02903             *(const AVClass**)s->priv_data= s->oformat->priv_class;
02904             av_opt_set_defaults(s->priv_data);
02905         }
02906     } else
02907         s->priv_data = NULL;
02908 
02909     return 0;
02910 }
02911 #endif
02912 
02913 int avformat_alloc_output_context2(AVFormatContext **avctx, AVOutputFormat *oformat,
02914                                    const char *format, const char *filename)
02915 {
02916     AVFormatContext *s = avformat_alloc_context();
02917     int ret = 0;
02918 
02919     *avctx = NULL;
02920     if (!s)
02921         goto nomem;
02922 
02923     if (!oformat) {
02924         if (format) {
02925             oformat = av_guess_format(format, NULL, NULL);
02926             if (!oformat) {
02927                 av_log(s, AV_LOG_ERROR, "Requested output format '%s' is not a suitable output format\n", format);
02928                 ret = AVERROR(EINVAL);
02929                 goto error;
02930             }
02931         } else {
02932             oformat = av_guess_format(NULL, filename, NULL);
02933             if (!oformat) {
02934                 ret = AVERROR(EINVAL);
02935                 av_log(s, AV_LOG_ERROR, "Unable to find a suitable output format for '%s'\n",
02936                        filename);
02937                 goto error;
02938             }
02939         }
02940     }
02941 
02942     s->oformat = oformat;
02943     if (s->oformat->priv_data_size > 0) {
02944         s->priv_data = av_mallocz(s->oformat->priv_data_size);
02945         if (!s->priv_data)
02946             goto nomem;
02947         if (s->oformat->priv_class) {
02948             *(const AVClass**)s->priv_data= s->oformat->priv_class;
02949             av_opt_set_defaults(s->priv_data);
02950         }
02951     } else
02952         s->priv_data = NULL;
02953 
02954     if (filename)
02955         av_strlcpy(s->filename, filename, sizeof(s->filename));
02956     *avctx = s;
02957     return 0;
02958 nomem:
02959     av_log(s, AV_LOG_ERROR, "Out of memory\n");
02960     ret = AVERROR(ENOMEM);
02961 error:
02962     avformat_free_context(s);
02963     return ret;
02964 }
02965 
02966 #if FF_API_ALLOC_OUTPUT_CONTEXT
02967 AVFormatContext *avformat_alloc_output_context(const char *format,
02968                                                AVOutputFormat *oformat, const char *filename)
02969 {
02970     AVFormatContext *avctx;
02971     int ret = avformat_alloc_output_context2(&avctx, oformat, format, filename);
02972     return ret < 0 ? NULL : avctx;
02973 }
02974 #endif
02975 
02976 static int validate_codec_tag(AVFormatContext *s, AVStream *st)
02977 {
02978     const AVCodecTag *avctag;
02979     int n;
02980     enum CodecID id = CODEC_ID_NONE;
02981     unsigned int tag = 0;
02982 
02989     for (n = 0; s->oformat->codec_tag[n]; n++) {
02990         avctag = s->oformat->codec_tag[n];
02991         while (avctag->id != CODEC_ID_NONE) {
02992             if (ff_toupper4(avctag->tag) == ff_toupper4(st->codec->codec_tag)) {
02993                 id = avctag->id;
02994                 if (id == st->codec->codec_id)
02995                     return 1;
02996             }
02997             if (avctag->id == st->codec->codec_id)
02998                 tag = avctag->tag;
02999             avctag++;
03000         }
03001     }
03002     if (id != CODEC_ID_NONE)
03003         return 0;
03004     if (tag && (st->codec->strict_std_compliance >= FF_COMPLIANCE_NORMAL))
03005         return 0;
03006     return 1;
03007 }
03008 
03009 #if FF_API_FORMAT_PARAMETERS
03010 int av_write_header(AVFormatContext *s)
03011 {
03012     return avformat_write_header(s, NULL);
03013 }
03014 #endif
03015 
03016 int avformat_write_header(AVFormatContext *s, AVDictionary **options)
03017 {
03018     int ret = 0, i;
03019     AVStream *st;
03020     AVDictionary *tmp = NULL;
03021 
03022     if (options)
03023         av_dict_copy(&tmp, *options, 0);
03024     if ((ret = av_opt_set_dict(s, &tmp)) < 0)
03025         goto fail;
03026 
03027     // some sanity checks
03028     if (s->nb_streams == 0 && !(s->oformat->flags & AVFMT_NOSTREAMS)) {
03029         av_log(s, AV_LOG_ERROR, "no streams\n");
03030         ret = AVERROR(EINVAL);
03031         goto fail;
03032     }
03033 
03034     for(i=0;i<s->nb_streams;i++) {
03035         st = s->streams[i];
03036 
03037         switch (st->codec->codec_type) {
03038         case AVMEDIA_TYPE_AUDIO:
03039             if(st->codec->sample_rate<=0){
03040                 av_log(s, AV_LOG_ERROR, "sample rate not set\n");
03041                 ret = AVERROR(EINVAL);
03042                 goto fail;
03043             }
03044             if(!st->codec->block_align)
03045                 st->codec->block_align = st->codec->channels *
03046                     av_get_bits_per_sample(st->codec->codec_id) >> 3;
03047             break;
03048         case AVMEDIA_TYPE_VIDEO:
03049             if(st->codec->time_base.num<=0 || st->codec->time_base.den<=0){ //FIXME audio too?
03050                 av_log(s, AV_LOG_ERROR, "time base not set\n");
03051                 ret = AVERROR(EINVAL);
03052                 goto fail;
03053             }
03054             if((st->codec->width<=0 || st->codec->height<=0) && !(s->oformat->flags & AVFMT_NODIMENSIONS)){
03055                 av_log(s, AV_LOG_ERROR, "dimensions not set\n");
03056                 ret = AVERROR(EINVAL);
03057                 goto fail;
03058             }
03059             if(av_cmp_q(st->sample_aspect_ratio, st->codec->sample_aspect_ratio)
03060                && FFABS(av_q2d(st->sample_aspect_ratio) - av_q2d(st->codec->sample_aspect_ratio)) > 0.004*av_q2d(st->sample_aspect_ratio)
03061             ){
03062                 av_log(s, AV_LOG_ERROR, "Aspect ratio mismatch between encoder and muxer layer\n");
03063                 ret = AVERROR(EINVAL);
03064                 goto fail;
03065             }
03066             break;
03067         }
03068 
03069         if(s->oformat->codec_tag){
03070             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)){
03071                 //the current rawvideo encoding system ends up setting the wrong codec_tag for avi, we override it here
03072                 st->codec->codec_tag= 0;
03073             }
03074             if(st->codec->codec_tag){
03075                 if (!validate_codec_tag(s, st)) {
03076                     char tagbuf[32];
03077                     av_get_codec_tag_string(tagbuf, sizeof(tagbuf), st->codec->codec_tag);
03078                     av_log(s, AV_LOG_ERROR,
03079                            "Tag %s/0x%08x incompatible with output codec id '%d'\n",
03080                            tagbuf, st->codec->codec_tag, st->codec->codec_id);
03081                     ret = AVERROR_INVALIDDATA;
03082                     goto fail;
03083                 }
03084             }else
03085                 st->codec->codec_tag= av_codec_get_tag(s->oformat->codec_tag, st->codec->codec_id);
03086         }
03087 
03088         if(s->oformat->flags & AVFMT_GLOBALHEADER &&
03089             !(st->codec->flags & CODEC_FLAG_GLOBAL_HEADER))
03090           av_log(s, AV_LOG_WARNING, "Codec for stream %d does not use global headers but container format requires global headers\n", i);
03091     }
03092 
03093     if (!s->priv_data && s->oformat->priv_data_size > 0) {
03094         s->priv_data = av_mallocz(s->oformat->priv_data_size);
03095         if (!s->priv_data) {
03096             ret = AVERROR(ENOMEM);
03097             goto fail;
03098         }
03099         if (s->oformat->priv_class) {
03100             *(const AVClass**)s->priv_data= s->oformat->priv_class;
03101             av_opt_set_defaults(s->priv_data);
03102             if ((ret = av_opt_set_dict(s->priv_data, &tmp)) < 0)
03103                 goto fail;
03104         }
03105     }
03106 
03107 #if FF_API_OLD_METADATA
03108     ff_metadata_mux_compat(s);
03109 #endif
03110 
03111     /* set muxer identification string */
03112     if (s->nb_streams && !(s->streams[0]->codec->flags & CODEC_FLAG_BITEXACT)) {
03113         av_dict_set(&s->metadata, "encoder", LIBAVFORMAT_IDENT, 0);
03114     }
03115 
03116     if(s->oformat->write_header){
03117         ret = s->oformat->write_header(s);
03118         if (ret < 0)
03119             goto fail;
03120     }
03121 
03122     /* init PTS generation */
03123     for(i=0;i<s->nb_streams;i++) {
03124         int64_t den = AV_NOPTS_VALUE;
03125         st = s->streams[i];
03126 
03127         switch (st->codec->codec_type) {
03128         case AVMEDIA_TYPE_AUDIO:
03129             den = (int64_t)st->time_base.num * st->codec->sample_rate;
03130             break;
03131         case AVMEDIA_TYPE_VIDEO:
03132             den = (int64_t)st->time_base.num * st->codec->time_base.den;
03133             break;
03134         default:
03135             break;
03136         }
03137         if (den != AV_NOPTS_VALUE) {
03138             if (den <= 0) {
03139                 ret = AVERROR_INVALIDDATA;
03140                 goto fail;
03141             }
03142             av_frac_init(&st->pts, 0, 0, den);
03143         }
03144     }
03145 
03146     if (options) {
03147         av_dict_free(options);
03148         *options = tmp;
03149     }
03150     return 0;
03151 fail:
03152     av_dict_free(&tmp);
03153     return ret;
03154 }
03155 
03156 //FIXME merge with compute_pkt_fields
03157 static int compute_pkt_fields2(AVFormatContext *s, AVStream *st, AVPacket *pkt){
03158     int delay = FFMAX(st->codec->has_b_frames, !!st->codec->max_b_frames);
03159     int num, den, frame_size, i;
03160 
03161     av_dlog(s, "compute_pkt_fields2: pts:%"PRId64" dts:%"PRId64" cur_dts:%"PRId64" b:%d size:%d st:%d\n",
03162             pkt->pts, pkt->dts, st->cur_dts, delay, pkt->size, pkt->stream_index);
03163 
03164 /*    if(pkt->pts == AV_NOPTS_VALUE && pkt->dts == AV_NOPTS_VALUE)
03165         return AVERROR(EINVAL);*/
03166 
03167     /* duration field */
03168     if (pkt->duration == 0) {
03169         compute_frame_duration(&num, &den, st, NULL, pkt);
03170         if (den && num) {
03171             pkt->duration = av_rescale(1, num * (int64_t)st->time_base.den * st->codec->ticks_per_frame, den * (int64_t)st->time_base.num);
03172         }
03173     }
03174 
03175     if(pkt->pts == AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE && delay==0)
03176         pkt->pts= pkt->dts;
03177 
03178     //XXX/FIXME this is a temporary hack until all encoders output pts
03179     if((pkt->pts == 0 || pkt->pts == AV_NOPTS_VALUE) && pkt->dts == AV_NOPTS_VALUE && !delay){
03180         pkt->dts=
03181 //        pkt->pts= st->cur_dts;
03182         pkt->pts= st->pts.val;
03183     }
03184 
03185     //calculate dts from pts
03186     if(pkt->pts != AV_NOPTS_VALUE && pkt->dts == AV_NOPTS_VALUE && delay <= MAX_REORDER_DELAY){
03187         st->pts_buffer[0]= pkt->pts;
03188         for(i=1; i<delay+1 && st->pts_buffer[i] == AV_NOPTS_VALUE; i++)
03189             st->pts_buffer[i]= pkt->pts + (i-delay-1) * pkt->duration;
03190         for(i=0; i<delay && st->pts_buffer[i] > st->pts_buffer[i+1]; i++)
03191             FFSWAP(int64_t, st->pts_buffer[i], st->pts_buffer[i+1]);
03192 
03193         pkt->dts= st->pts_buffer[0];
03194     }
03195 
03196     if(st->cur_dts && st->cur_dts != AV_NOPTS_VALUE && ((!(s->oformat->flags & AVFMT_TS_NONSTRICT) && st->cur_dts >= pkt->dts) || st->cur_dts > pkt->dts)){
03197         av_log(s, AV_LOG_ERROR,
03198                "Application provided invalid, non monotonically increasing dts to muxer in stream %d: %"PRId64" >= %"PRId64"\n",
03199                st->index, st->cur_dts, pkt->dts);
03200         return AVERROR(EINVAL);
03201     }
03202     if(pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE && pkt->pts < pkt->dts){
03203         av_log(s, AV_LOG_ERROR, "pts < dts in stream %d\n", st->index);
03204         return AVERROR(EINVAL);
03205     }
03206 
03207 //    av_log(s, AV_LOG_DEBUG, "av_write_frame: pts2:%"PRId64" dts2:%"PRId64"\n", pkt->pts, pkt->dts);
03208     st->cur_dts= pkt->dts;
03209     st->pts.val= pkt->dts;
03210 
03211     /* update pts */
03212     switch (st->codec->codec_type) {
03213     case AVMEDIA_TYPE_AUDIO:
03214         frame_size = get_audio_frame_size(st->codec, pkt->size);
03215 
03216         /* HACK/FIXME, we skip the initial 0 size packets as they are most
03217            likely equal to the encoder delay, but it would be better if we
03218            had the real timestamps from the encoder */
03219         if (frame_size >= 0 && (pkt->size || st->pts.num!=st->pts.den>>1 || st->pts.val)) {
03220             av_frac_add(&st->pts, (int64_t)st->time_base.den * frame_size);
03221         }
03222         break;
03223     case AVMEDIA_TYPE_VIDEO:
03224         av_frac_add(&st->pts, (int64_t)st->time_base.den * st->codec->time_base.num);
03225         break;
03226     default:
03227         break;
03228     }
03229     return 0;
03230 }
03231 
03232 int av_write_frame(AVFormatContext *s, AVPacket *pkt)
03233 {
03234     int ret = compute_pkt_fields2(s, s->streams[pkt->stream_index], pkt);
03235 
03236     if(ret<0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
03237         return ret;
03238 
03239     ret= s->oformat->write_packet(s, pkt);
03240     if(!ret)
03241         ret= url_ferror(s->pb);
03242     return ret;
03243 }
03244 
03245 void ff_interleave_add_packet(AVFormatContext *s, AVPacket *pkt,
03246                               int (*compare)(AVFormatContext *, AVPacket *, AVPacket *))
03247 {
03248     AVPacketList **next_point, *this_pktl;
03249 
03250     this_pktl = av_mallocz(sizeof(AVPacketList));
03251     this_pktl->pkt= *pkt;
03252     pkt->destruct= NULL;             // do not free original but only the copy
03253     av_dup_packet(&this_pktl->pkt);  // duplicate the packet if it uses non-alloced memory
03254 
03255     if(s->streams[pkt->stream_index]->last_in_packet_buffer){
03256         next_point = &(s->streams[pkt->stream_index]->last_in_packet_buffer->next);
03257     }else
03258         next_point = &s->packet_buffer;
03259 
03260     if(*next_point){
03261         if(compare(s, &s->packet_buffer_end->pkt, pkt)){
03262             while(!compare(s, &(*next_point)->pkt, pkt)){
03263                 next_point= &(*next_point)->next;
03264             }
03265             goto next_non_null;
03266         }else{
03267             next_point = &(s->packet_buffer_end->next);
03268         }
03269     }
03270     assert(!*next_point);
03271 
03272     s->packet_buffer_end= this_pktl;
03273 next_non_null:
03274 
03275     this_pktl->next= *next_point;
03276 
03277     s->streams[pkt->stream_index]->last_in_packet_buffer=
03278     *next_point= this_pktl;
03279 }
03280 
03281 static int ff_interleave_compare_dts(AVFormatContext *s, AVPacket *next, AVPacket *pkt)
03282 {
03283     AVStream *st = s->streams[ pkt ->stream_index];
03284     AVStream *st2= s->streams[ next->stream_index];
03285     int comp = av_compare_ts(next->dts, st2->time_base, pkt->dts,
03286                              st->time_base);
03287 
03288     if (comp == 0)
03289         return pkt->stream_index < next->stream_index;
03290     return comp > 0;
03291 }
03292 
03293 int av_interleave_packet_per_dts(AVFormatContext *s, AVPacket *out, AVPacket *pkt, int flush){
03294     AVPacketList *pktl;
03295     int stream_count=0;
03296     int i;
03297 
03298     if(pkt){
03299         ff_interleave_add_packet(s, pkt, ff_interleave_compare_dts);
03300     }
03301 
03302     for(i=0; i < s->nb_streams; i++)
03303         stream_count+= !!s->streams[i]->last_in_packet_buffer;
03304 
03305     if(stream_count && (s->nb_streams == stream_count || flush)){
03306         pktl= s->packet_buffer;
03307         *out= pktl->pkt;
03308 
03309         s->packet_buffer= pktl->next;
03310         if(!s->packet_buffer)
03311             s->packet_buffer_end= NULL;
03312 
03313         if(s->streams[out->stream_index]->last_in_packet_buffer == pktl)
03314             s->streams[out->stream_index]->last_in_packet_buffer= NULL;
03315         av_freep(&pktl);
03316         return 1;
03317     }else{
03318         av_init_packet(out);
03319         return 0;
03320     }
03321 }
03322 
03332 static int av_interleave_packet(AVFormatContext *s, AVPacket *out, AVPacket *in, int flush){
03333     if(s->oformat->interleave_packet)
03334         return s->oformat->interleave_packet(s, out, in, flush);
03335     else
03336         return av_interleave_packet_per_dts(s, out, in, flush);
03337 }
03338 
03339 int av_interleaved_write_frame(AVFormatContext *s, AVPacket *pkt){
03340     AVStream *st= s->streams[ pkt->stream_index];
03341     int ret;
03342 
03343     //FIXME/XXX/HACK drop zero sized packets
03344     if(st->codec->codec_type == AVMEDIA_TYPE_AUDIO && pkt->size==0)
03345         return 0;
03346 
03347     av_dlog(s, "av_interleaved_write_frame size:%d dts:%"PRId64" pts:%"PRId64"\n",
03348             pkt->size, pkt->dts, pkt->pts);
03349     if((ret = compute_pkt_fields2(s, st, pkt)) < 0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
03350         return ret;
03351 
03352     if(pkt->dts == AV_NOPTS_VALUE && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
03353         return AVERROR(EINVAL);
03354 
03355     for(;;){
03356         AVPacket opkt;
03357         int ret= av_interleave_packet(s, &opkt, pkt, 0);
03358         if(ret<=0) //FIXME cleanup needed for ret<0 ?
03359             return ret;
03360 
03361         ret= s->oformat->write_packet(s, &opkt);
03362 
03363         av_free_packet(&opkt);
03364         pkt= NULL;
03365 
03366         if(ret<0)
03367             return ret;
03368         if(url_ferror(s->pb))
03369             return url_ferror(s->pb);
03370     }
03371 }
03372 
03373 int av_write_trailer(AVFormatContext *s)
03374 {
03375     int ret, i;
03376 
03377     for(;;){
03378         AVPacket pkt;
03379         ret= av_interleave_packet(s, &pkt, NULL, 1);
03380         if(ret<0) //FIXME cleanup needed for ret<0 ?
03381             goto fail;
03382         if(!ret)
03383             break;
03384 
03385         ret= s->oformat->write_packet(s, &pkt);
03386 
03387         av_free_packet(&pkt);
03388 
03389         if(ret<0)
03390             goto fail;
03391         if(url_ferror(s->pb))
03392             goto fail;
03393     }
03394 
03395     if(s->oformat->write_trailer)
03396         ret = s->oformat->write_trailer(s);
03397 fail:
03398     if(ret == 0)
03399        ret=url_ferror(s->pb);
03400     for(i=0;i<s->nb_streams;i++) {
03401         av_freep(&s->streams[i]->priv_data);
03402         av_freep(&s->streams[i]->index_entries);
03403     }
03404     if (s->iformat && s->iformat->priv_class)
03405         av_opt_free(s->priv_data);
03406     av_freep(&s->priv_data);
03407     return ret;
03408 }
03409 
03410 void ff_program_add_stream_index(AVFormatContext *ac, int progid, unsigned int idx)
03411 {
03412     int i, j;
03413     AVProgram *program=NULL;
03414     void *tmp;
03415 
03416     if (idx >= ac->nb_streams) {
03417         av_log(ac, AV_LOG_ERROR, "stream index %d is not valid\n", idx);
03418         return;
03419     }
03420 
03421     for(i=0; i<ac->nb_programs; i++){
03422         if(ac->programs[i]->id != progid)
03423             continue;
03424         program = ac->programs[i];
03425         for(j=0; j<program->nb_stream_indexes; j++)
03426             if(program->stream_index[j] == idx)
03427                 return;
03428 
03429         tmp = av_realloc(program->stream_index, sizeof(unsigned int)*(program->nb_stream_indexes+1));
03430         if(!tmp)
03431             return;
03432         program->stream_index = tmp;
03433         program->stream_index[program->nb_stream_indexes++] = idx;
03434         return;
03435     }
03436 }
03437 
03438 static void print_fps(double d, const char *postfix){
03439     uint64_t v= lrintf(d*100);
03440     if     (v% 100      ) av_log(NULL, AV_LOG_INFO, ", %3.2f %s", d, postfix);
03441     else if(v%(100*1000)) av_log(NULL, AV_LOG_INFO, ", %1.0f %s", d, postfix);
03442     else                  av_log(NULL, AV_LOG_INFO, ", %1.0fk %s", d/1000, postfix);
03443 }
03444 
03445 static void dump_metadata(void *ctx, AVDictionary *m, const char *indent)
03446 {
03447     if(m && !(m->count == 1 && av_dict_get(m, "language", NULL, 0))){
03448         AVDictionaryEntry *tag=NULL;
03449 
03450         av_log(ctx, AV_LOG_INFO, "%sMetadata:\n", indent);
03451         while((tag=av_dict_get(m, "", tag, AV_DICT_IGNORE_SUFFIX))) {
03452             if(strcmp("language", tag->key)){
03453                 char tmp[256];
03454                 int i;
03455                 av_strlcpy(tmp, tag->value, sizeof(tmp));
03456                 for(i=0; i<strlen(tmp); i++) if(tmp[i]==0xd) tmp[i]=' ';
03457                 av_log(ctx, AV_LOG_INFO, "%s  %-16s: %s\n", indent, tag->key, tmp);
03458             }
03459         }
03460     }
03461 }
03462 
03463 /* "user interface" functions */
03464 static void dump_stream_format(AVFormatContext *ic, int i, int index, int is_output)
03465 {
03466     char buf[256];
03467     int flags = (is_output ? ic->oformat->flags : ic->iformat->flags);
03468     AVStream *st = ic->streams[i];
03469     int g = av_gcd(st->time_base.num, st->time_base.den);
03470     AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL, 0);
03471     avcodec_string(buf, sizeof(buf), st->codec, is_output);
03472     av_log(NULL, AV_LOG_INFO, "    Stream #%d.%d", index, i);
03473     /* the pid is an important information, so we display it */
03474     /* XXX: add a generic system */
03475     if (flags & AVFMT_SHOW_IDS)
03476         av_log(NULL, AV_LOG_INFO, "[0x%x]", st->id);
03477     if (lang)
03478         av_log(NULL, AV_LOG_INFO, "(%s)", lang->value);
03479     av_log(NULL, AV_LOG_DEBUG, ", %d, %d/%d", st->codec_info_nb_frames, st->time_base.num/g, st->time_base.den/g);
03480     av_log(NULL, AV_LOG_INFO, ": %s", buf);
03481     if (st->sample_aspect_ratio.num && // default
03482         av_cmp_q(st->sample_aspect_ratio, st->codec->sample_aspect_ratio)) {
03483         AVRational display_aspect_ratio;
03484         av_reduce(&display_aspect_ratio.num, &display_aspect_ratio.den,
03485                   st->codec->width*st->sample_aspect_ratio.num,
03486                   st->codec->height*st->sample_aspect_ratio.den,
03487                   1024*1024);
03488         av_log(NULL, AV_LOG_INFO, ", PAR %d:%d DAR %d:%d",
03489                  st->sample_aspect_ratio.num, st->sample_aspect_ratio.den,
03490                  display_aspect_ratio.num, display_aspect_ratio.den);
03491     }
03492     if(st->codec->codec_type == AVMEDIA_TYPE_VIDEO){
03493         if(st->avg_frame_rate.den && st->avg_frame_rate.num)
03494             print_fps(av_q2d(st->avg_frame_rate), "fps");
03495         if(st->r_frame_rate.den && st->r_frame_rate.num)
03496             print_fps(av_q2d(st->r_frame_rate), "tbr");
03497         if(st->time_base.den && st->time_base.num)
03498             print_fps(1/av_q2d(st->time_base), "tbn");
03499         if(st->codec->time_base.den && st->codec->time_base.num)
03500             print_fps(1/av_q2d(st->codec->time_base), "tbc");
03501     }
03502     if (st->disposition & AV_DISPOSITION_DEFAULT)
03503         av_log(NULL, AV_LOG_INFO, " (default)");
03504     if (st->disposition & AV_DISPOSITION_DUB)
03505         av_log(NULL, AV_LOG_INFO, " (dub)");
03506     if (st->disposition & AV_DISPOSITION_ORIGINAL)
03507         av_log(NULL, AV_LOG_INFO, " (original)");
03508     if (st->disposition & AV_DISPOSITION_COMMENT)
03509         av_log(NULL, AV_LOG_INFO, " (comment)");
03510     if (st->disposition & AV_DISPOSITION_LYRICS)
03511         av_log(NULL, AV_LOG_INFO, " (lyrics)");
03512     if (st->disposition & AV_DISPOSITION_KARAOKE)
03513         av_log(NULL, AV_LOG_INFO, " (karaoke)");
03514     if (st->disposition & AV_DISPOSITION_FORCED)
03515         av_log(NULL, AV_LOG_INFO, " (forced)");
03516     if (st->disposition & AV_DISPOSITION_HEARING_IMPAIRED)
03517         av_log(NULL, AV_LOG_INFO, " (hearing impaired)");
03518     if (st->disposition & AV_DISPOSITION_VISUAL_IMPAIRED)
03519         av_log(NULL, AV_LOG_INFO, " (visual impaired)");
03520     if (st->disposition & AV_DISPOSITION_CLEAN_EFFECTS)
03521         av_log(NULL, AV_LOG_INFO, " (clean effects)");
03522     av_log(NULL, AV_LOG_INFO, "\n");
03523     dump_metadata(NULL, st->metadata, "    ");
03524 }
03525 
03526 #if FF_API_DUMP_FORMAT
03527 void dump_format(AVFormatContext *ic,
03528                  int index,
03529                  const char *url,
03530                  int is_output)
03531 {
03532     av_dump_format(ic, index, url, is_output);
03533 }
03534 #endif
03535 
03536 void av_dump_format(AVFormatContext *ic,
03537                     int index,
03538                     const char *url,
03539                     int is_output)
03540 {
03541     int i;
03542     uint8_t *printed = ic->nb_streams ? av_mallocz(ic->nb_streams) : NULL;
03543     if (ic->nb_streams && !printed)
03544         return;
03545 
03546     av_log(NULL, AV_LOG_INFO, "%s #%d, %s, %s '%s':\n",
03547             is_output ? "Output" : "Input",
03548             index,
03549             is_output ? ic->oformat->name : ic->iformat->name,
03550             is_output ? "to" : "from", url);
03551     dump_metadata(NULL, ic->metadata, "  ");
03552     if (!is_output) {
03553         av_log(NULL, AV_LOG_INFO, "  Duration: ");
03554         if (ic->duration != AV_NOPTS_VALUE) {
03555             int hours, mins, secs, us;
03556             secs = ic->duration / AV_TIME_BASE;
03557             us = ic->duration % AV_TIME_BASE;
03558             mins = secs / 60;
03559             secs %= 60;
03560             hours = mins / 60;
03561             mins %= 60;
03562             av_log(NULL, AV_LOG_INFO, "%02d:%02d:%02d.%02d", hours, mins, secs,
03563                    (100 * us) / AV_TIME_BASE);
03564         } else {
03565             av_log(NULL, AV_LOG_INFO, "N/A");
03566         }
03567         if (ic->start_time != AV_NOPTS_VALUE) {
03568             int secs, us;
03569             av_log(NULL, AV_LOG_INFO, ", start: ");
03570             secs = ic->start_time / AV_TIME_BASE;
03571             us = abs(ic->start_time % AV_TIME_BASE);
03572             av_log(NULL, AV_LOG_INFO, "%d.%06d",
03573                    secs, (int)av_rescale(us, 1000000, AV_TIME_BASE));
03574         }
03575         av_log(NULL, AV_LOG_INFO, ", bitrate: ");
03576         if (ic->bit_rate) {
03577             av_log(NULL, AV_LOG_INFO,"%d kb/s", ic->bit_rate / 1000);
03578         } else {
03579             av_log(NULL, AV_LOG_INFO, "N/A");
03580         }
03581         av_log(NULL, AV_LOG_INFO, "\n");
03582     }
03583     for (i = 0; i < ic->nb_chapters; i++) {
03584         AVChapter *ch = ic->chapters[i];
03585         av_log(NULL, AV_LOG_INFO, "    Chapter #%d.%d: ", index, i);
03586         av_log(NULL, AV_LOG_INFO, "start %f, ", ch->start * av_q2d(ch->time_base));
03587         av_log(NULL, AV_LOG_INFO, "end %f\n",   ch->end   * av_q2d(ch->time_base));
03588 
03589         dump_metadata(NULL, ch->metadata, "    ");
03590     }
03591     if(ic->nb_programs) {
03592         int j, k, total = 0;
03593         for(j=0; j<ic->nb_programs; j++) {
03594             AVDictionaryEntry *name = av_dict_get(ic->programs[j]->metadata,
03595                                                   "name", NULL, 0);
03596             av_log(NULL, AV_LOG_INFO, "  Program %d %s\n", ic->programs[j]->id,
03597                    name ? name->value : "");
03598             dump_metadata(NULL, ic->programs[j]->metadata, "    ");
03599             for(k=0; k<ic->programs[j]->nb_stream_indexes; k++) {
03600                 dump_stream_format(ic, ic->programs[j]->stream_index[k], index, is_output);
03601                 printed[ic->programs[j]->stream_index[k]] = 1;
03602             }
03603             total += ic->programs[j]->nb_stream_indexes;
03604         }
03605         if (total < ic->nb_streams)
03606             av_log(NULL, AV_LOG_INFO, "  No Program\n");
03607     }
03608     for(i=0;i<ic->nb_streams;i++)
03609         if (!printed[i])
03610             dump_stream_format(ic, i, index, is_output);
03611 
03612     av_free(printed);
03613 }
03614 
03615 #if FF_API_PARSE_FRAME_PARAM
03616 #include "libavutil/parseutils.h"
03617 
03618 int parse_image_size(int *width_ptr, int *height_ptr, const char *str)
03619 {
03620     return av_parse_video_size(width_ptr, height_ptr, str);
03621 }
03622 
03623 int parse_frame_rate(int *frame_rate_num, int *frame_rate_den, const char *arg)
03624 {
03625     AVRational frame_rate;
03626     int ret = av_parse_video_rate(&frame_rate, arg);
03627     *frame_rate_num= frame_rate.num;
03628     *frame_rate_den= frame_rate.den;
03629     return ret;
03630 }
03631 #endif
03632 
03633 int64_t av_gettime(void)
03634 {
03635     struct timeval tv;
03636     gettimeofday(&tv,NULL);
03637     return (int64_t)tv.tv_sec * 1000000 + tv.tv_usec;
03638 }
03639 
03640 uint64_t ff_ntp_time(void)
03641 {
03642   return (av_gettime() / 1000) * 1000 + NTP_OFFSET_US;
03643 }
03644 
03645 #if FF_API_PARSE_DATE
03646 #include "libavutil/parseutils.h"
03647 
03648 int64_t parse_date(const char *timestr, int duration)
03649 {
03650     int64_t timeval;
03651     av_parse_time(&timeval, timestr, duration);
03652     return timeval;
03653 }
03654 #endif
03655 
03656 #if FF_API_FIND_INFO_TAG
03657 #include "libavutil/parseutils.h"
03658 
03659 int find_info_tag(char *arg, int arg_size, const char *tag1, const char *info)
03660 {
03661     return av_find_info_tag(arg, arg_size, tag1, info);
03662 }
03663 #endif
03664 
03665 int av_get_frame_filename(char *buf, int buf_size,
03666                           const char *path, int number)
03667 {
03668     const char *p;
03669     char *q, buf1[20], c;
03670     int nd, len, percentd_found;
03671 
03672     q = buf;
03673     p = path;
03674     percentd_found = 0;
03675     for(;;) {
03676         c = *p++;
03677         if (c == '\0')
03678             break;
03679         if (c == '%') {
03680             do {
03681                 nd = 0;
03682                 while (isdigit(*p)) {
03683                     nd = nd * 10 + *p++ - '0';
03684                 }
03685                 c = *p++;
03686             } while (isdigit(c));
03687 
03688             switch(c) {
03689             case '%':
03690                 goto addchar;
03691             case 'd':
03692                 if (percentd_found)
03693                     goto fail;
03694                 percentd_found = 1;
03695                 snprintf(buf1, sizeof(buf1), "%0*d", nd, number);
03696                 len = strlen(buf1);
03697                 if ((q - buf + len) > buf_size - 1)
03698                     goto fail;
03699                 memcpy(q, buf1, len);
03700                 q += len;
03701                 break;
03702             default:
03703                 goto fail;
03704             }
03705         } else {
03706         addchar:
03707             if ((q - buf) < buf_size - 1)
03708                 *q++ = c;
03709         }
03710     }
03711     if (!percentd_found)
03712         goto fail;
03713     *q = '\0';
03714     return 0;
03715  fail:
03716     *q = '\0';
03717     return -1;
03718 }
03719 
03720 static void hex_dump_internal(void *avcl, FILE *f, int level, uint8_t *buf, int size)
03721 {
03722     int len, i, j, c;
03723 #undef fprintf
03724 #define PRINT(...) do { if (!f) av_log(avcl, level, __VA_ARGS__); else fprintf(f, __VA_ARGS__); } while(0)
03725 
03726     for(i=0;i<size;i+=16) {
03727         len = size - i;
03728         if (len > 16)
03729             len = 16;
03730         PRINT("%08x ", i);
03731         for(j=0;j<16;j++) {
03732             if (j < len)
03733                 PRINT(" %02x", buf[i+j]);
03734             else
03735                 PRINT("   ");
03736         }
03737         PRINT(" ");
03738         for(j=0;j<len;j++) {
03739             c = buf[i+j];
03740             if (c < ' ' || c > '~')
03741                 c = '.';
03742             PRINT("%c", c);
03743         }
03744         PRINT("\n");
03745     }
03746 #undef PRINT
03747 }
03748 
03749 void av_hex_dump(FILE *f, uint8_t *buf, int size)
03750 {
03751     hex_dump_internal(NULL, f, 0, buf, size);
03752 }
03753 
03754 void av_hex_dump_log(void *avcl, int level, uint8_t *buf, int size)
03755 {
03756     hex_dump_internal(avcl, NULL, level, buf, size);
03757 }
03758 
03759 static void pkt_dump_internal(void *avcl, FILE *f, int level, AVPacket *pkt, int dump_payload, AVRational time_base)
03760 {
03761 #undef fprintf
03762 #define PRINT(...) do { if (!f) av_log(avcl, level, __VA_ARGS__); else fprintf(f, __VA_ARGS__); } while(0)
03763     PRINT("stream #%d:\n", pkt->stream_index);
03764     PRINT("  keyframe=%d\n", ((pkt->flags & AV_PKT_FLAG_KEY) != 0));
03765     PRINT("  duration=%0.3f\n", pkt->duration * av_q2d(time_base));
03766     /* DTS is _always_ valid after av_read_frame() */
03767     PRINT("  dts=");
03768     if (pkt->dts == AV_NOPTS_VALUE)
03769         PRINT("N/A");
03770     else
03771         PRINT("%0.3f", pkt->dts * av_q2d(time_base));
03772     /* PTS may not be known if B-frames are present. */
03773     PRINT("  pts=");
03774     if (pkt->pts == AV_NOPTS_VALUE)
03775         PRINT("N/A");
03776     else
03777         PRINT("%0.3f", pkt->pts * av_q2d(time_base));
03778     PRINT("\n");
03779     PRINT("  size=%d\n", pkt->size);
03780 #undef PRINT
03781     if (dump_payload)
03782         av_hex_dump(f, pkt->data, pkt->size);
03783 }
03784 
03785 #if FF_API_PKT_DUMP
03786 void av_pkt_dump(FILE *f, AVPacket *pkt, int dump_payload)
03787 {
03788     AVRational tb = { 1, AV_TIME_BASE };
03789     pkt_dump_internal(NULL, f, 0, pkt, dump_payload, tb);
03790 }
03791 #endif
03792 
03793 void av_pkt_dump2(FILE *f, AVPacket *pkt, int dump_payload, AVStream *st)
03794 {
03795     pkt_dump_internal(NULL, f, 0, pkt, dump_payload, st->time_base);
03796 }
03797 
03798 #if FF_API_PKT_DUMP
03799 void av_pkt_dump_log(void *avcl, int level, AVPacket *pkt, int dump_payload)
03800 {
03801     AVRational tb = { 1, AV_TIME_BASE };
03802     pkt_dump_internal(avcl, NULL, level, pkt, dump_payload, tb);
03803 }
03804 #endif
03805 
03806 void av_pkt_dump_log2(void *avcl, int level, AVPacket *pkt, int dump_payload,
03807                       AVStream *st)
03808 {
03809     pkt_dump_internal(avcl, NULL, level, pkt, dump_payload, st->time_base);
03810 }
03811 
03812 #if FF_API_URL_SPLIT
03813 attribute_deprecated
03814 void ff_url_split(char *proto, int proto_size,
03815                   char *authorization, int authorization_size,
03816                   char *hostname, int hostname_size,
03817                   int *port_ptr,
03818                   char *path, int path_size,
03819                   const char *url)
03820 {
03821     av_url_split(proto, proto_size,
03822                  authorization, authorization_size,
03823                  hostname, hostname_size,
03824                  port_ptr,
03825                  path, path_size,
03826                  url);
03827 }
03828 #endif
03829 
03830 void av_url_split(char *proto, int proto_size,
03831                   char *authorization, int authorization_size,
03832                   char *hostname, int hostname_size,
03833                   int *port_ptr,
03834                   char *path, int path_size,
03835                   const char *url)
03836 {
03837     const char *p, *ls, *at, *col, *brk;
03838 
03839     if (port_ptr)               *port_ptr = -1;
03840     if (proto_size > 0)         proto[0] = 0;
03841     if (authorization_size > 0) authorization[0] = 0;
03842     if (hostname_size > 0)      hostname[0] = 0;
03843     if (path_size > 0)          path[0] = 0;
03844 
03845     /* parse protocol */
03846     if ((p = strchr(url, ':'))) {
03847         av_strlcpy(proto, url, FFMIN(proto_size, p + 1 - url));
03848         p++; /* skip ':' */
03849         if (*p == '/') p++;
03850         if (*p == '/') p++;
03851     } else {
03852         /* no protocol means plain filename */
03853         av_strlcpy(path, url, path_size);
03854         return;
03855     }
03856 
03857     /* separate path from hostname */
03858     ls = strchr(p, '/');
03859     if(!ls)
03860         ls = strchr(p, '?');
03861     if(ls)
03862         av_strlcpy(path, ls, path_size);
03863     else
03864         ls = &p[strlen(p)]; // XXX
03865 
03866     /* the rest is hostname, use that to parse auth/port */
03867     if (ls != p) {
03868         /* authorization (user[:pass]@hostname) */
03869         if ((at = strchr(p, '@')) && at < ls) {
03870             av_strlcpy(authorization, p,
03871                        FFMIN(authorization_size, at + 1 - p));
03872             p = at + 1; /* skip '@' */
03873         }
03874 
03875         if (*p == '[' && (brk = strchr(p, ']')) && brk < ls) {
03876             /* [host]:port */
03877             av_strlcpy(hostname, p + 1,
03878                        FFMIN(hostname_size, brk - p));
03879             if (brk[1] == ':' && port_ptr)
03880                 *port_ptr = atoi(brk + 2);
03881         } else if ((col = strchr(p, ':')) && col < ls) {
03882             av_strlcpy(hostname, p,
03883                        FFMIN(col + 1 - p, hostname_size));
03884             if (port_ptr) *port_ptr = atoi(col + 1);
03885         } else
03886             av_strlcpy(hostname, p,
03887                        FFMIN(ls + 1 - p, hostname_size));
03888     }
03889 }
03890 
03891 char *ff_data_to_hex(char *buff, const uint8_t *src, int s, int lowercase)
03892 {
03893     int i;
03894     static const char hex_table_uc[16] = { '0', '1', '2', '3',
03895                                            '4', '5', '6', '7',
03896                                            '8', '9', 'A', 'B',
03897                                            'C', 'D', 'E', 'F' };
03898     static const char hex_table_lc[16] = { '0', '1', '2', '3',
03899                                            '4', '5', '6', '7',
03900                                            '8', '9', 'a', 'b',
03901                                            'c', 'd', 'e', 'f' };
03902     const char *hex_table = lowercase ? hex_table_lc : hex_table_uc;
03903 
03904     for(i = 0; i < s; i++) {
03905         buff[i * 2]     = hex_table[src[i] >> 4];
03906         buff[i * 2 + 1] = hex_table[src[i] & 0xF];
03907     }
03908 
03909     return buff;
03910 }
03911 
03912 int ff_hex_to_data(uint8_t *data, const char *p)
03913 {
03914     int c, len, v;
03915 
03916     len = 0;
03917     v = 1;
03918     for (;;) {
03919         p += strspn(p, SPACE_CHARS);
03920         if (*p == '\0')
03921             break;
03922         c = toupper((unsigned char) *p++);
03923         if (c >= '0' && c <= '9')
03924             c = c - '0';
03925         else if (c >= 'A' && c <= 'F')
03926             c = c - 'A' + 10;
03927         else
03928             break;
03929         v = (v << 4) | c;
03930         if (v & 0x100) {
03931             if (data)
03932                 data[len] = v;
03933             len++;
03934             v = 1;
03935         }
03936     }
03937     return len;
03938 }
03939 
03940 void av_set_pts_info(AVStream *s, int pts_wrap_bits,
03941                      unsigned int pts_num, unsigned int pts_den)
03942 {
03943     AVRational new_tb;
03944     if(av_reduce(&new_tb.num, &new_tb.den, pts_num, pts_den, INT_MAX)){
03945         if(new_tb.num != pts_num)
03946             av_log(NULL, AV_LOG_DEBUG, "st:%d removing common factor %d from timebase\n", s->index, pts_num/new_tb.num);
03947     }else
03948         av_log(NULL, AV_LOG_WARNING, "st:%d has too large timebase, reducing\n", s->index);
03949 
03950     if(new_tb.num <= 0 || new_tb.den <= 0) {
03951         av_log(NULL, AV_LOG_ERROR, "Ignoring attempt to set invalid timebase for st:%d\n", s->index);
03952         return;
03953     }
03954     s->time_base = new_tb;
03955     s->pts_wrap_bits = pts_wrap_bits;
03956 }
03957 
03958 int ff_url_join(char *str, int size, const char *proto,
03959                 const char *authorization, const char *hostname,
03960                 int port, const char *fmt, ...)
03961 {
03962 #if CONFIG_NETWORK
03963     struct addrinfo hints, *ai;
03964 #endif
03965 
03966     str[0] = '\0';
03967     if (proto)
03968         av_strlcatf(str, size, "%s://", proto);
03969     if (authorization && authorization[0])
03970         av_strlcatf(str, size, "%s@", authorization);
03971 #if CONFIG_NETWORK && defined(AF_INET6)
03972     /* Determine if hostname is a numerical IPv6 address,
03973      * properly escape it within [] in that case. */
03974     memset(&hints, 0, sizeof(hints));
03975     hints.ai_flags = AI_NUMERICHOST;
03976     if (!getaddrinfo(hostname, NULL, &hints, &ai)) {
03977         if (ai->ai_family == AF_INET6) {
03978             av_strlcat(str, "[", size);
03979             av_strlcat(str, hostname, size);
03980             av_strlcat(str, "]", size);
03981         } else {
03982             av_strlcat(str, hostname, size);
03983         }
03984         freeaddrinfo(ai);
03985     } else
03986 #endif
03987         /* Not an IPv6 address, just output the plain string. */
03988         av_strlcat(str, hostname, size);
03989 
03990     if (port >= 0)
03991         av_strlcatf(str, size, ":%d", port);
03992     if (fmt) {
03993         va_list vl;
03994         int len = strlen(str);
03995 
03996         va_start(vl, fmt);
03997         vsnprintf(str + len, size > len ? size - len : 0, fmt, vl);
03998         va_end(vl);
03999     }
04000     return strlen(str);
04001 }
04002 
04003 int ff_write_chained(AVFormatContext *dst, int dst_stream, AVPacket *pkt,
04004                      AVFormatContext *src)
04005 {
04006     AVPacket local_pkt;
04007 
04008     local_pkt = *pkt;
04009     local_pkt.stream_index = dst_stream;
04010     if (pkt->pts != AV_NOPTS_VALUE)
04011         local_pkt.pts = av_rescale_q(pkt->pts,
04012                                      src->streams[pkt->stream_index]->time_base,
04013                                      dst->streams[dst_stream]->time_base);
04014     if (pkt->dts != AV_NOPTS_VALUE)
04015         local_pkt.dts = av_rescale_q(pkt->dts,
04016                                      src->streams[pkt->stream_index]->time_base,
04017                                      dst->streams[dst_stream]->time_base);
04018     return av_write_frame(dst, &local_pkt);
04019 }
04020 
04021 void ff_parse_key_value(const char *str, ff_parse_key_val_cb callback_get_buf,
04022                         void *context)
04023 {
04024     const char *ptr = str;
04025 
04026     /* Parse key=value pairs. */
04027     for (;;) {
04028         const char *key;
04029         char *dest = NULL, *dest_end;
04030         int key_len, dest_len = 0;
04031 
04032         /* Skip whitespace and potential commas. */
04033         while (*ptr && (isspace(*ptr) || *ptr == ','))
04034             ptr++;
04035         if (!*ptr)
04036             break;
04037 
04038         key = ptr;
04039 
04040         if (!(ptr = strchr(key, '=')))
04041             break;
04042         ptr++;
04043         key_len = ptr - key;
04044 
04045         callback_get_buf(context, key, key_len, &dest, &dest_len);
04046         dest_end = dest + dest_len - 1;
04047 
04048         if (*ptr == '\"') {
04049             ptr++;
04050             while (*ptr && *ptr != '\"') {
04051                 if (*ptr == '\\') {
04052                     if (!ptr[1])
04053                         break;
04054                     if (dest && dest < dest_end)
04055                         *dest++ = ptr[1];
04056                     ptr += 2;
04057                 } else {
04058                     if (dest && dest < dest_end)
04059                         *dest++ = *ptr;
04060                     ptr++;
04061                 }
04062             }
04063             if (*ptr == '\"')
04064                 ptr++;
04065         } else {
04066             for (; *ptr && !(isspace(*ptr) || *ptr == ','); ptr++)
04067                 if (dest && dest < dest_end)
04068                     *dest++ = *ptr;
04069         }
04070         if (dest)
04071             *dest = 0;
04072     }
04073 }
04074 
04075 int ff_find_stream_index(AVFormatContext *s, int id)
04076 {
04077     int i;
04078     for (i = 0; i < s->nb_streams; i++) {
04079         if (s->streams[i]->id == id)
04080             return i;
04081     }
04082     return -1;
04083 }
04084 
04085 void ff_make_absolute_url(char *buf, int size, const char *base,
04086                           const char *rel)
04087 {
04088     char *sep;
04089     /* Absolute path, relative to the current server */
04090     if (base && strstr(base, "://") && rel[0] == '/') {
04091         if (base != buf)
04092             av_strlcpy(buf, base, size);
04093         sep = strstr(buf, "://");
04094         if (sep) {
04095             sep += 3;
04096             sep = strchr(sep, '/');
04097             if (sep)
04098                 *sep = '\0';
04099         }
04100         av_strlcat(buf, rel, size);
04101         return;
04102     }
04103     /* If rel actually is an absolute url, just copy it */
04104     if (!base || strstr(rel, "://") || rel[0] == '/') {
04105         av_strlcpy(buf, rel, size);
04106         return;
04107     }
04108     if (base != buf)
04109         av_strlcpy(buf, base, size);
04110     /* Remove the file name from the base url */
04111     sep = strrchr(buf, '/');
04112     if (sep)
04113         sep[1] = '\0';
04114     else
04115         buf[0] = '\0';
04116     while (av_strstart(rel, "../", NULL) && sep) {
04117         /* Remove the path delimiter at the end */
04118         sep[0] = '\0';
04119         sep = strrchr(buf, '/');
04120         /* If the next directory name to pop off is "..", break here */
04121         if (!strcmp(sep ? &sep[1] : buf, "..")) {
04122             /* Readd the slash we just removed */
04123             av_strlcat(buf, "/", size);
04124             break;
04125         }
04126         /* Cut off the directory name */
04127         if (sep)
04128             sep[1] = '\0';
04129         else
04130             buf[0] = '\0';
04131         rel += 3;
04132     }
04133     av_strlcat(buf, rel, size);
04134 }

Generated on Wed Apr 11 2012 07:31:35 for FFmpeg by  doxygen 1.7.1