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