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

Generated on Fri Feb 22 2013 07:24:29 for FFmpeg by  doxygen 1.7.1