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

libavformat/utils.c

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