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