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