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 compute_pkt_fields(s, st, st->parser, &out_pkt);
01211
01212 if ((s->iformat->flags & AVFMT_GENERIC_INDEX) &&
01213 out_pkt.flags & AV_PKT_FLAG_KEY) {
01214 int64_t pos= (st->parser->flags & PARSER_FLAG_COMPLETE_FRAMES) ? out_pkt.pos : st->parser->frame_offset;
01215 ff_reduce_index(s, st->index);
01216 av_add_index_entry(st, pos, out_pkt.dts,
01217 0, 0, AVINDEX_KEYFRAME);
01218 }
01219
01220 if (out_pkt.data == pkt->data && out_pkt.size == pkt->size) {
01221 out_pkt.destruct = pkt->destruct;
01222 pkt->destruct = NULL;
01223 }
01224 if ((ret = av_dup_packet(&out_pkt)) < 0)
01225 goto fail;
01226
01227 if (!add_to_pktbuf(&s->parse_queue, &out_pkt, &s->parse_queue_end)) {
01228 av_free_packet(&out_pkt);
01229 ret = AVERROR(ENOMEM);
01230 goto fail;
01231 }
01232 }
01233
01234
01235
01236 if (pkt == &flush_pkt) {
01237 av_parser_close(st->parser);
01238 st->parser = NULL;
01239 }
01240
01241 fail:
01242 av_free_packet(pkt);
01243 return ret;
01244 }
01245
01246 static int read_from_packet_buffer(AVPacketList **pkt_buffer,
01247 AVPacketList **pkt_buffer_end,
01248 AVPacket *pkt)
01249 {
01250 AVPacketList *pktl;
01251 av_assert0(*pkt_buffer);
01252 pktl = *pkt_buffer;
01253 *pkt = pktl->pkt;
01254 *pkt_buffer = pktl->next;
01255 if (!pktl->next)
01256 *pkt_buffer_end = NULL;
01257 av_freep(&pktl);
01258 return 0;
01259 }
01260
01261 static int read_frame_internal(AVFormatContext *s, AVPacket *pkt)
01262 {
01263 int ret = 0, i, got_packet = 0;
01264
01265 av_init_packet(pkt);
01266
01267 while (!got_packet && !s->parse_queue) {
01268 AVStream *st;
01269 AVPacket cur_pkt;
01270
01271
01272 ret = ff_read_packet(s, &cur_pkt);
01273 if (ret < 0) {
01274 if (ret == AVERROR(EAGAIN))
01275 return ret;
01276
01277 for(i = 0; i < s->nb_streams; i++) {
01278 st = s->streams[i];
01279 if (st->parser && st->need_parsing)
01280 parse_packet(s, NULL, st->index);
01281 }
01282
01283
01284 break;
01285 }
01286 ret = 0;
01287 st = s->streams[cur_pkt.stream_index];
01288
01289 if (cur_pkt.pts != AV_NOPTS_VALUE &&
01290 cur_pkt.dts != AV_NOPTS_VALUE &&
01291 cur_pkt.pts < cur_pkt.dts) {
01292 av_log(s, AV_LOG_WARNING, "Invalid timestamps stream=%d, pts=%s, dts=%s, size=%d\n",
01293 cur_pkt.stream_index,
01294 av_ts2str(cur_pkt.pts),
01295 av_ts2str(cur_pkt.dts),
01296 cur_pkt.size);
01297 }
01298 if (s->debug & FF_FDEBUG_TS)
01299 av_log(s, AV_LOG_DEBUG, "ff_read_packet stream=%d, pts=%s, dts=%s, size=%d, duration=%d, flags=%d\n",
01300 cur_pkt.stream_index,
01301 av_ts2str(cur_pkt.pts),
01302 av_ts2str(cur_pkt.dts),
01303 cur_pkt.size,
01304 cur_pkt.duration,
01305 cur_pkt.flags);
01306
01307 if (st->need_parsing && !st->parser && !(s->flags & AVFMT_FLAG_NOPARSE)) {
01308 st->parser = av_parser_init(st->codec->codec_id);
01309 if (!st->parser) {
01310 av_log(s, AV_LOG_VERBOSE, "parser not found for codec "
01311 "%s, packets or times may be invalid.\n",
01312 avcodec_get_name(st->codec->codec_id));
01313
01314 st->need_parsing = AVSTREAM_PARSE_NONE;
01315 } else if(st->need_parsing == AVSTREAM_PARSE_HEADERS) {
01316 st->parser->flags |= PARSER_FLAG_COMPLETE_FRAMES;
01317 } else if(st->need_parsing == AVSTREAM_PARSE_FULL_ONCE) {
01318 st->parser->flags |= PARSER_FLAG_ONCE;
01319 } else if(st->need_parsing == AVSTREAM_PARSE_FULL_RAW) {
01320 st->parser->flags |= PARSER_FLAG_USE_CODEC_TS;
01321 }
01322 }
01323
01324 if (!st->need_parsing || !st->parser) {
01325
01326 *pkt = cur_pkt;
01327 compute_pkt_fields(s, st, NULL, pkt);
01328 if ((s->iformat->flags & AVFMT_GENERIC_INDEX) &&
01329 (pkt->flags & AV_PKT_FLAG_KEY) && pkt->dts != AV_NOPTS_VALUE) {
01330 ff_reduce_index(s, st->index);
01331 av_add_index_entry(st, pkt->pos, pkt->dts, 0, 0, AVINDEX_KEYFRAME);
01332 }
01333 got_packet = 1;
01334 } else if (st->discard < AVDISCARD_ALL) {
01335 if ((ret = parse_packet(s, &cur_pkt, cur_pkt.stream_index)) < 0)
01336 return ret;
01337 } else {
01338
01339 av_free_packet(&cur_pkt);
01340 }
01341 if (pkt->flags & AV_PKT_FLAG_KEY)
01342 st->skip_to_keyframe = 0;
01343 if (st->skip_to_keyframe) {
01344 av_free_packet(&cur_pkt);
01345 got_packet = 0;
01346 }
01347 }
01348
01349 if (!got_packet && s->parse_queue)
01350 ret = read_from_packet_buffer(&s->parse_queue, &s->parse_queue_end, pkt);
01351
01352 if(s->debug & FF_FDEBUG_TS)
01353 av_log(s, AV_LOG_DEBUG, "read_frame_internal stream=%d, pts=%s, dts=%s, size=%d, duration=%d, flags=%d\n",
01354 pkt->stream_index,
01355 av_ts2str(pkt->pts),
01356 av_ts2str(pkt->dts),
01357 pkt->size,
01358 pkt->duration,
01359 pkt->flags);
01360
01361 return ret;
01362 }
01363
01364 int av_read_frame(AVFormatContext *s, AVPacket *pkt)
01365 {
01366 const int genpts = s->flags & AVFMT_FLAG_GENPTS;
01367 int eof = 0;
01368 int ret;
01369
01370 if (!genpts) {
01371 ret = s->packet_buffer ? read_from_packet_buffer(&s->packet_buffer,
01372 &s->packet_buffer_end,
01373 pkt) :
01374 read_frame_internal(s, pkt);
01375 goto return_packet;
01376 }
01377
01378 for (;;) {
01379 AVPacketList *pktl = s->packet_buffer;
01380
01381 if (pktl) {
01382 AVPacket *next_pkt = &pktl->pkt;
01383
01384 if (next_pkt->dts != AV_NOPTS_VALUE) {
01385 int wrap_bits = s->streams[next_pkt->stream_index]->pts_wrap_bits;
01386
01387
01388 int64_t last_dts = next_pkt->dts;
01389 while (pktl && next_pkt->pts == AV_NOPTS_VALUE) {
01390 if (pktl->pkt.stream_index == next_pkt->stream_index &&
01391 (av_compare_mod(next_pkt->dts, pktl->pkt.dts, 2LL << (wrap_bits - 1)) < 0)) {
01392 if (av_compare_mod(pktl->pkt.pts, pktl->pkt.dts, 2LL << (wrap_bits - 1))) {
01393 next_pkt->pts = pktl->pkt.dts;
01394 }
01395 if (last_dts != AV_NOPTS_VALUE) {
01396
01397 last_dts = pktl->pkt.dts;
01398 }
01399 }
01400 pktl = pktl->next;
01401 }
01402 if (eof && next_pkt->pts == AV_NOPTS_VALUE && last_dts != AV_NOPTS_VALUE) {
01403
01404
01405
01406
01407
01408 next_pkt->pts = last_dts + next_pkt->duration;
01409 }
01410 pktl = s->packet_buffer;
01411 }
01412
01413
01414 if (!(next_pkt->pts == AV_NOPTS_VALUE &&
01415 next_pkt->dts != AV_NOPTS_VALUE && !eof)) {
01416 ret = read_from_packet_buffer(&s->packet_buffer,
01417 &s->packet_buffer_end, pkt);
01418 goto return_packet;
01419 }
01420 }
01421
01422 ret = read_frame_internal(s, pkt);
01423 if (ret < 0) {
01424 if (pktl && ret != AVERROR(EAGAIN)) {
01425 eof = 1;
01426 continue;
01427 } else
01428 return ret;
01429 }
01430
01431 if (av_dup_packet(add_to_pktbuf(&s->packet_buffer, pkt,
01432 &s->packet_buffer_end)) < 0)
01433 return AVERROR(ENOMEM);
01434 }
01435
01436 return_packet:
01437 if (is_relative(pkt->dts))
01438 pkt->dts -= RELATIVE_TS_BASE;
01439 if (is_relative(pkt->pts))
01440 pkt->pts -= RELATIVE_TS_BASE;
01441 return ret;
01442 }
01443
01444
01445 static void flush_packet_queue(AVFormatContext *s)
01446 {
01447 free_packet_buffer(&s->parse_queue, &s->parse_queue_end);
01448 free_packet_buffer(&s->packet_buffer, &s->packet_buffer_end);
01449 free_packet_buffer(&s->raw_packet_buffer, &s->raw_packet_buffer_end);
01450
01451 s->raw_packet_buffer_remaining_size = RAW_PACKET_BUFFER_SIZE;
01452 }
01453
01454
01455
01456
01457 int av_find_default_stream_index(AVFormatContext *s)
01458 {
01459 int first_audio_index = -1;
01460 int i;
01461 AVStream *st;
01462
01463 if (s->nb_streams <= 0)
01464 return -1;
01465 for(i = 0; i < s->nb_streams; i++) {
01466 st = s->streams[i];
01467 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
01468 !(st->disposition & AV_DISPOSITION_ATTACHED_PIC)) {
01469 return i;
01470 }
01471 if (first_audio_index < 0 && st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
01472 first_audio_index = i;
01473 }
01474 return first_audio_index >= 0 ? first_audio_index : 0;
01475 }
01476
01480 void ff_read_frame_flush(AVFormatContext *s)
01481 {
01482 AVStream *st;
01483 int i, j;
01484
01485 flush_packet_queue(s);
01486
01487
01488 for(i = 0; i < s->nb_streams; i++) {
01489 st = s->streams[i];
01490
01491 if (st->parser) {
01492 av_parser_close(st->parser);
01493 st->parser = NULL;
01494 }
01495 st->last_IP_pts = AV_NOPTS_VALUE;
01496 if(st->first_dts == AV_NOPTS_VALUE) st->cur_dts = RELATIVE_TS_BASE;
01497 else st->cur_dts = AV_NOPTS_VALUE;
01498 st->reference_dts = AV_NOPTS_VALUE;
01499
01500 st->probe_packets = MAX_PROBE_PACKETS;
01501
01502 for(j=0; j<MAX_REORDER_DELAY+1; j++)
01503 st->pts_buffer[j]= AV_NOPTS_VALUE;
01504 }
01505 }
01506
01507 void ff_update_cur_dts(AVFormatContext *s, AVStream *ref_st, int64_t timestamp)
01508 {
01509 int i;
01510
01511 for(i = 0; i < s->nb_streams; i++) {
01512 AVStream *st = s->streams[i];
01513
01514 st->cur_dts = av_rescale(timestamp,
01515 st->time_base.den * (int64_t)ref_st->time_base.num,
01516 st->time_base.num * (int64_t)ref_st->time_base.den);
01517 }
01518 }
01519
01520 void ff_reduce_index(AVFormatContext *s, int stream_index)
01521 {
01522 AVStream *st= s->streams[stream_index];
01523 unsigned int max_entries= s->max_index_size / sizeof(AVIndexEntry);
01524
01525 if((unsigned)st->nb_index_entries >= max_entries){
01526 int i;
01527 for(i=0; 2*i<st->nb_index_entries; i++)
01528 st->index_entries[i]= st->index_entries[2*i];
01529 st->nb_index_entries= i;
01530 }
01531 }
01532
01533 int ff_add_index_entry(AVIndexEntry **index_entries,
01534 int *nb_index_entries,
01535 unsigned int *index_entries_allocated_size,
01536 int64_t pos, int64_t timestamp, int size, int distance, int flags)
01537 {
01538 AVIndexEntry *entries, *ie;
01539 int index;
01540
01541 if((unsigned)*nb_index_entries + 1 >= UINT_MAX / sizeof(AVIndexEntry))
01542 return -1;
01543
01544 if (is_relative(timestamp))
01545 timestamp -= RELATIVE_TS_BASE;
01546
01547 entries = av_fast_realloc(*index_entries,
01548 index_entries_allocated_size,
01549 (*nb_index_entries + 1) *
01550 sizeof(AVIndexEntry));
01551 if(!entries)
01552 return -1;
01553
01554 *index_entries= entries;
01555
01556 index= ff_index_search_timestamp(*index_entries, *nb_index_entries, timestamp, AVSEEK_FLAG_ANY);
01557
01558 if(index<0){
01559 index= (*nb_index_entries)++;
01560 ie= &entries[index];
01561 assert(index==0 || ie[-1].timestamp < timestamp);
01562 }else{
01563 ie= &entries[index];
01564 if(ie->timestamp != timestamp){
01565 if(ie->timestamp <= timestamp)
01566 return -1;
01567 memmove(entries + index + 1, entries + index, sizeof(AVIndexEntry)*(*nb_index_entries - index));
01568 (*nb_index_entries)++;
01569 }else if(ie->pos == pos && distance < ie->min_distance)
01570 distance= ie->min_distance;
01571 }
01572
01573 ie->pos = pos;
01574 ie->timestamp = timestamp;
01575 ie->min_distance= distance;
01576 ie->size= size;
01577 ie->flags = flags;
01578
01579 return index;
01580 }
01581
01582 int av_add_index_entry(AVStream *st,
01583 int64_t pos, int64_t timestamp, int size, int distance, int flags)
01584 {
01585 return ff_add_index_entry(&st->index_entries, &st->nb_index_entries,
01586 &st->index_entries_allocated_size, pos,
01587 timestamp, size, distance, flags);
01588 }
01589
01590 int ff_index_search_timestamp(const AVIndexEntry *entries, int nb_entries,
01591 int64_t wanted_timestamp, int flags)
01592 {
01593 int a, b, m;
01594 int64_t timestamp;
01595
01596 a = - 1;
01597 b = nb_entries;
01598
01599
01600 if(b && entries[b-1].timestamp < wanted_timestamp)
01601 a= b-1;
01602
01603 while (b - a > 1) {
01604 m = (a + b) >> 1;
01605 timestamp = entries[m].timestamp;
01606 if(timestamp >= wanted_timestamp)
01607 b = m;
01608 if(timestamp <= wanted_timestamp)
01609 a = m;
01610 }
01611 m= (flags & AVSEEK_FLAG_BACKWARD) ? a : b;
01612
01613 if(!(flags & AVSEEK_FLAG_ANY)){
01614 while(m>=0 && m<nb_entries && !(entries[m].flags & AVINDEX_KEYFRAME)){
01615 m += (flags & AVSEEK_FLAG_BACKWARD) ? -1 : 1;
01616 }
01617 }
01618
01619 if(m == nb_entries)
01620 return -1;
01621 return m;
01622 }
01623
01624 int av_index_search_timestamp(AVStream *st, int64_t wanted_timestamp,
01625 int flags)
01626 {
01627 return ff_index_search_timestamp(st->index_entries, st->nb_index_entries,
01628 wanted_timestamp, flags);
01629 }
01630
01631 int ff_seek_frame_binary(AVFormatContext *s, int stream_index, int64_t target_ts, int flags)
01632 {
01633 AVInputFormat *avif= s->iformat;
01634 int64_t av_uninit(pos_min), av_uninit(pos_max), pos, pos_limit;
01635 int64_t ts_min, ts_max, ts;
01636 int index;
01637 int64_t ret;
01638 AVStream *st;
01639
01640 if (stream_index < 0)
01641 return -1;
01642
01643 av_dlog(s, "read_seek: %d %s\n", stream_index, av_ts2str(target_ts));
01644
01645 ts_max=
01646 ts_min= AV_NOPTS_VALUE;
01647 pos_limit= -1;
01648
01649 st= s->streams[stream_index];
01650 if(st->index_entries){
01651 AVIndexEntry *e;
01652
01653 index= av_index_search_timestamp(st, target_ts, flags | AVSEEK_FLAG_BACKWARD);
01654 index= FFMAX(index, 0);
01655 e= &st->index_entries[index];
01656
01657 if(e->timestamp <= target_ts || e->pos == e->min_distance){
01658 pos_min= e->pos;
01659 ts_min= e->timestamp;
01660 av_dlog(s, "using cached pos_min=0x%"PRIx64" dts_min=%s\n",
01661 pos_min, av_ts2str(ts_min));
01662 }else{
01663 assert(index==0);
01664 }
01665
01666 index= av_index_search_timestamp(st, target_ts, flags & ~AVSEEK_FLAG_BACKWARD);
01667 assert(index < st->nb_index_entries);
01668 if(index >= 0){
01669 e= &st->index_entries[index];
01670 assert(e->timestamp >= target_ts);
01671 pos_max= e->pos;
01672 ts_max= e->timestamp;
01673 pos_limit= pos_max - e->min_distance;
01674 av_dlog(s, "using cached pos_max=0x%"PRIx64" pos_limit=0x%"PRIx64" dts_max=%s\n",
01675 pos_max, pos_limit, av_ts2str(ts_max));
01676 }
01677 }
01678
01679 pos= ff_gen_search(s, stream_index, target_ts, pos_min, pos_max, pos_limit, ts_min, ts_max, flags, &ts, avif->read_timestamp);
01680 if(pos<0)
01681 return -1;
01682
01683
01684 if ((ret = avio_seek(s->pb, pos, SEEK_SET)) < 0)
01685 return ret;
01686
01687 ff_read_frame_flush(s);
01688 ff_update_cur_dts(s, st, ts);
01689
01690 return 0;
01691 }
01692
01693 int64_t ff_gen_search(AVFormatContext *s, int stream_index, int64_t target_ts,
01694 int64_t pos_min, int64_t pos_max, int64_t pos_limit,
01695 int64_t ts_min, int64_t ts_max, int flags, int64_t *ts_ret,
01696 int64_t (*read_timestamp)(struct AVFormatContext *, int , int64_t *, int64_t ))
01697 {
01698 int64_t pos, ts;
01699 int64_t start_pos, filesize;
01700 int no_change;
01701
01702 av_dlog(s, "gen_seek: %d %s\n", stream_index, av_ts2str(target_ts));
01703
01704 if(ts_min == AV_NOPTS_VALUE){
01705 pos_min = s->data_offset;
01706 ts_min = read_timestamp(s, stream_index, &pos_min, INT64_MAX);
01707 if (ts_min == AV_NOPTS_VALUE)
01708 return -1;
01709 }
01710
01711 if(ts_min >= target_ts){
01712 *ts_ret= ts_min;
01713 return pos_min;
01714 }
01715
01716 if(ts_max == AV_NOPTS_VALUE){
01717 int step= 1024;
01718 filesize = avio_size(s->pb);
01719 pos_max = filesize - 1;
01720 do{
01721 pos_max -= step;
01722 ts_max = read_timestamp(s, stream_index, &pos_max, pos_max + step);
01723 step += step;
01724 }while(ts_max == AV_NOPTS_VALUE && pos_max >= step);
01725 if (ts_max == AV_NOPTS_VALUE)
01726 return -1;
01727
01728 for(;;){
01729 int64_t tmp_pos= pos_max + 1;
01730 int64_t tmp_ts= read_timestamp(s, stream_index, &tmp_pos, INT64_MAX);
01731 if(tmp_ts == AV_NOPTS_VALUE)
01732 break;
01733 ts_max= tmp_ts;
01734 pos_max= tmp_pos;
01735 if(tmp_pos >= filesize)
01736 break;
01737 }
01738 pos_limit= pos_max;
01739 }
01740
01741 if(ts_max <= target_ts){
01742 *ts_ret= ts_max;
01743 return pos_max;
01744 }
01745
01746 if(ts_min > ts_max){
01747 return -1;
01748 }else if(ts_min == ts_max){
01749 pos_limit= pos_min;
01750 }
01751
01752 no_change=0;
01753 while (pos_min < pos_limit) {
01754 av_dlog(s, "pos_min=0x%"PRIx64" pos_max=0x%"PRIx64" dts_min=%s dts_max=%s\n",
01755 pos_min, pos_max, av_ts2str(ts_min), av_ts2str(ts_max));
01756 assert(pos_limit <= pos_max);
01757
01758 if(no_change==0){
01759 int64_t approximate_keyframe_distance= pos_max - pos_limit;
01760
01761 pos = av_rescale(target_ts - ts_min, pos_max - pos_min, ts_max - ts_min)
01762 + pos_min - approximate_keyframe_distance;
01763 }else if(no_change==1){
01764
01765 pos = (pos_min + pos_limit)>>1;
01766 }else{
01767
01768
01769 pos=pos_min;
01770 }
01771 if(pos <= pos_min)
01772 pos= pos_min + 1;
01773 else if(pos > pos_limit)
01774 pos= pos_limit;
01775 start_pos= pos;
01776
01777 ts = read_timestamp(s, stream_index, &pos, INT64_MAX);
01778 if(pos == pos_max)
01779 no_change++;
01780 else
01781 no_change=0;
01782 av_dlog(s, "%"PRId64" %"PRId64" %"PRId64" / %s %s %s target:%s limit:%"PRId64" start:%"PRId64" noc:%d\n",
01783 pos_min, pos, pos_max,
01784 av_ts2str(ts_min), av_ts2str(ts), av_ts2str(ts_max), av_ts2str(target_ts),
01785 pos_limit, start_pos, no_change);
01786 if(ts == AV_NOPTS_VALUE){
01787 av_log(s, AV_LOG_ERROR, "read_timestamp() failed in the middle\n");
01788 return -1;
01789 }
01790 assert(ts != AV_NOPTS_VALUE);
01791 if (target_ts <= ts) {
01792 pos_limit = start_pos - 1;
01793 pos_max = pos;
01794 ts_max = ts;
01795 }
01796 if (target_ts >= ts) {
01797 pos_min = pos;
01798 ts_min = ts;
01799 }
01800 }
01801
01802 pos = (flags & AVSEEK_FLAG_BACKWARD) ? pos_min : pos_max;
01803 ts = (flags & AVSEEK_FLAG_BACKWARD) ? ts_min : ts_max;
01804 #if 0
01805 pos_min = pos;
01806 ts_min = read_timestamp(s, stream_index, &pos_min, INT64_MAX);
01807 pos_min++;
01808 ts_max = read_timestamp(s, stream_index, &pos_min, INT64_MAX);
01809 av_dlog(s, "pos=0x%"PRIx64" %s<=%s<=%s\n",
01810 pos, av_ts2str(ts_min), av_ts2str(target_ts), av_ts2str(ts_max));
01811 #endif
01812 *ts_ret= ts;
01813 return pos;
01814 }
01815
01816 static int seek_frame_byte(AVFormatContext *s, int stream_index, int64_t pos, int flags){
01817 int64_t pos_min, pos_max;
01818
01819 pos_min = s->data_offset;
01820 pos_max = avio_size(s->pb) - 1;
01821
01822 if (pos < pos_min) pos= pos_min;
01823 else if(pos > pos_max) pos= pos_max;
01824
01825 avio_seek(s->pb, pos, SEEK_SET);
01826
01827 return 0;
01828 }
01829
01830 static int seek_frame_generic(AVFormatContext *s,
01831 int stream_index, int64_t timestamp, int flags)
01832 {
01833 int index;
01834 int64_t ret;
01835 AVStream *st;
01836 AVIndexEntry *ie;
01837
01838 st = s->streams[stream_index];
01839
01840 index = av_index_search_timestamp(st, timestamp, flags);
01841
01842 if(index < 0 && st->nb_index_entries && timestamp < st->index_entries[0].timestamp)
01843 return -1;
01844
01845 if(index < 0 || index==st->nb_index_entries-1){
01846 AVPacket pkt;
01847 int nonkey=0;
01848
01849 if(st->nb_index_entries){
01850 assert(st->index_entries);
01851 ie= &st->index_entries[st->nb_index_entries-1];
01852 if ((ret = avio_seek(s->pb, ie->pos, SEEK_SET)) < 0)
01853 return ret;
01854 ff_update_cur_dts(s, st, ie->timestamp);
01855 }else{
01856 if ((ret = avio_seek(s->pb, s->data_offset, SEEK_SET)) < 0)
01857 return ret;
01858 }
01859 for (;;) {
01860 int read_status;
01861 do{
01862 read_status = av_read_frame(s, &pkt);
01863 } while (read_status == AVERROR(EAGAIN));
01864 if (read_status < 0)
01865 break;
01866 av_free_packet(&pkt);
01867 if(stream_index == pkt.stream_index && pkt.dts > timestamp){
01868 if(pkt.flags & AV_PKT_FLAG_KEY)
01869 break;
01870 if(nonkey++ > 1000 && st->codec->codec_id != CODEC_ID_CDGRAPHICS){
01871 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);
01872 break;
01873 }
01874 }
01875 }
01876 index = av_index_search_timestamp(st, timestamp, flags);
01877 }
01878 if (index < 0)
01879 return -1;
01880
01881 ff_read_frame_flush(s);
01882 AV_NOWARN_DEPRECATED(
01883 if (s->iformat->read_seek){
01884 if(s->iformat->read_seek(s, stream_index, timestamp, flags) >= 0)
01885 return 0;
01886 }
01887 )
01888 ie = &st->index_entries[index];
01889 if ((ret = avio_seek(s->pb, ie->pos, SEEK_SET)) < 0)
01890 return ret;
01891 ff_update_cur_dts(s, st, ie->timestamp);
01892
01893 return 0;
01894 }
01895
01896 static int seek_frame_internal(AVFormatContext *s, int stream_index,
01897 int64_t timestamp, int flags)
01898 {
01899 int ret;
01900 AVStream *st;
01901
01902 if (flags & AVSEEK_FLAG_BYTE) {
01903 if (s->iformat->flags & AVFMT_NO_BYTE_SEEK)
01904 return -1;
01905 ff_read_frame_flush(s);
01906 return seek_frame_byte(s, stream_index, timestamp, flags);
01907 }
01908
01909 if(stream_index < 0){
01910 stream_index= av_find_default_stream_index(s);
01911 if(stream_index < 0)
01912 return -1;
01913
01914 st= s->streams[stream_index];
01915
01916 timestamp = av_rescale(timestamp, st->time_base.den, AV_TIME_BASE * (int64_t)st->time_base.num);
01917 }
01918
01919
01920 AV_NOWARN_DEPRECATED(
01921 if (s->iformat->read_seek) {
01922 ff_read_frame_flush(s);
01923 ret = s->iformat->read_seek(s, stream_index, timestamp, flags);
01924 } else
01925 ret = -1;
01926 )
01927 if (ret >= 0) {
01928 return 0;
01929 }
01930
01931 if (s->iformat->read_timestamp && !(s->iformat->flags & AVFMT_NOBINSEARCH)) {
01932 ff_read_frame_flush(s);
01933 return ff_seek_frame_binary(s, stream_index, timestamp, flags);
01934 } else if (!(s->iformat->flags & AVFMT_NOGENSEARCH)) {
01935 ff_read_frame_flush(s);
01936 return seek_frame_generic(s, stream_index, timestamp, flags);
01937 }
01938 else
01939 return -1;
01940 }
01941
01942 int av_seek_frame(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
01943 {
01944 int ret = seek_frame_internal(s, stream_index, timestamp, flags);
01945
01946 if (ret >= 0)
01947 queue_attached_pictures(s);
01948
01949 return ret;
01950 }
01951
01952 int avformat_seek_file(AVFormatContext *s, int stream_index, int64_t min_ts, int64_t ts, int64_t max_ts, int flags)
01953 {
01954 if(min_ts > ts || max_ts < ts)
01955 return -1;
01956
01957 if (s->iformat->read_seek2) {
01958 int ret;
01959 ff_read_frame_flush(s);
01960 ret = s->iformat->read_seek2(s, stream_index, min_ts, ts, max_ts, flags);
01961
01962 if (ret >= 0)
01963 queue_attached_pictures(s);
01964 return ret;
01965 }
01966
01967 if(s->iformat->read_timestamp){
01968
01969 }
01970
01971
01972
01973 AV_NOWARN_DEPRECATED(
01974 if (s->iformat->read_seek || 1) {
01975 int dir = (ts - min_ts > (uint64_t)(max_ts - ts) ? AVSEEK_FLAG_BACKWARD : 0);
01976 int ret = av_seek_frame(s, stream_index, ts, flags | dir);
01977 if (ret<0 && ts != min_ts && max_ts != ts) {
01978 ret = av_seek_frame(s, stream_index, dir ? max_ts : min_ts, flags | dir);
01979 if (ret >= 0)
01980 ret = av_seek_frame(s, stream_index, ts, flags | (dir^AVSEEK_FLAG_BACKWARD));
01981 }
01982 return ret;
01983 }
01984 )
01985
01986
01987 }
01988
01989
01990
01996 static int has_duration(AVFormatContext *ic)
01997 {
01998 int i;
01999 AVStream *st;
02000
02001 for(i = 0;i < ic->nb_streams; i++) {
02002 st = ic->streams[i];
02003 if (st->duration != AV_NOPTS_VALUE)
02004 return 1;
02005 }
02006 if (ic->duration != AV_NOPTS_VALUE)
02007 return 1;
02008 return 0;
02009 }
02010
02016 static void update_stream_timings(AVFormatContext *ic)
02017 {
02018 int64_t start_time, start_time1, start_time_text, end_time, end_time1;
02019 int64_t duration, duration1, filesize;
02020 int i;
02021 AVStream *st;
02022
02023 start_time = INT64_MAX;
02024 start_time_text = INT64_MAX;
02025 end_time = INT64_MIN;
02026 duration = INT64_MIN;
02027 for(i = 0;i < ic->nb_streams; i++) {
02028 st = ic->streams[i];
02029 if (st->start_time != AV_NOPTS_VALUE && st->time_base.den) {
02030 start_time1= av_rescale_q(st->start_time, st->time_base, AV_TIME_BASE_Q);
02031 if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
02032 if (start_time1 < start_time_text)
02033 start_time_text = start_time1;
02034 } else
02035 start_time = FFMIN(start_time, start_time1);
02036 if (st->duration != AV_NOPTS_VALUE) {
02037 end_time1 = start_time1
02038 + av_rescale_q(st->duration, st->time_base, AV_TIME_BASE_Q);
02039 end_time = FFMAX(end_time, end_time1);
02040 }
02041 }
02042 if (st->duration != AV_NOPTS_VALUE) {
02043 duration1 = av_rescale_q(st->duration, st->time_base, AV_TIME_BASE_Q);
02044 duration = FFMAX(duration, duration1);
02045 }
02046 }
02047 if (start_time == INT64_MAX || (start_time > start_time_text && start_time - start_time_text < AV_TIME_BASE))
02048 start_time = start_time_text;
02049 if (start_time != INT64_MAX) {
02050 ic->start_time = start_time;
02051 if (end_time != INT64_MIN)
02052 duration = FFMAX(duration, end_time - start_time);
02053 }
02054 if (duration != INT64_MIN && ic->duration == AV_NOPTS_VALUE) {
02055 ic->duration = duration;
02056 }
02057 if (ic->pb && (filesize = avio_size(ic->pb)) > 0 && ic->duration != AV_NOPTS_VALUE) {
02058
02059 ic->bit_rate = (double)filesize * 8.0 * AV_TIME_BASE /
02060 (double)ic->duration;
02061 }
02062 }
02063
02064 static void fill_all_stream_timings(AVFormatContext *ic)
02065 {
02066 int i;
02067 AVStream *st;
02068
02069 update_stream_timings(ic);
02070 for(i = 0;i < ic->nb_streams; i++) {
02071 st = ic->streams[i];
02072 if (st->start_time == AV_NOPTS_VALUE) {
02073 if(ic->start_time != AV_NOPTS_VALUE)
02074 st->start_time = av_rescale_q(ic->start_time, AV_TIME_BASE_Q, st->time_base);
02075 if(ic->duration != AV_NOPTS_VALUE)
02076 st->duration = av_rescale_q(ic->duration, AV_TIME_BASE_Q, st->time_base);
02077 }
02078 }
02079 }
02080
02081 static void estimate_timings_from_bit_rate(AVFormatContext *ic)
02082 {
02083 int64_t filesize, duration;
02084 int bit_rate, i;
02085 AVStream *st;
02086
02087
02088 if (ic->bit_rate <= 0) {
02089 bit_rate = 0;
02090 for(i=0;i<ic->nb_streams;i++) {
02091 st = ic->streams[i];
02092 if (st->codec->bit_rate > 0)
02093 bit_rate += st->codec->bit_rate;
02094 }
02095 ic->bit_rate = bit_rate;
02096 }
02097
02098
02099 if (ic->duration == AV_NOPTS_VALUE &&
02100 ic->bit_rate != 0) {
02101 filesize = ic->pb ? avio_size(ic->pb) : 0;
02102 if (filesize > 0) {
02103 for(i = 0; i < ic->nb_streams; i++) {
02104 st = ic->streams[i];
02105 duration= av_rescale(8*filesize, st->time_base.den, ic->bit_rate*(int64_t)st->time_base.num);
02106 if (st->duration == AV_NOPTS_VALUE)
02107 st->duration = duration;
02108 }
02109 }
02110 }
02111 }
02112
02113 #define DURATION_MAX_READ_SIZE 250000
02114 #define DURATION_MAX_RETRY 3
02115
02116
02117 static void estimate_timings_from_pts(AVFormatContext *ic, int64_t old_offset)
02118 {
02119 AVPacket pkt1, *pkt = &pkt1;
02120 AVStream *st;
02121 int read_size, i, ret;
02122 int64_t end_time;
02123 int64_t filesize, offset, duration;
02124 int retry=0;
02125
02126
02127 flush_packet_queue(ic);
02128
02129 for (i=0; i<ic->nb_streams; i++) {
02130 st = ic->streams[i];
02131 if (st->start_time == AV_NOPTS_VALUE && st->first_dts == AV_NOPTS_VALUE)
02132 av_log(st->codec, AV_LOG_WARNING, "start time is not set in estimate_timings_from_pts\n");
02133
02134 if (st->parser) {
02135 av_parser_close(st->parser);
02136 st->parser= NULL;
02137 }
02138 }
02139
02140
02141
02142 filesize = ic->pb ? avio_size(ic->pb) : 0;
02143 end_time = AV_NOPTS_VALUE;
02144 do{
02145 offset = filesize - (DURATION_MAX_READ_SIZE<<retry);
02146 if (offset < 0)
02147 offset = 0;
02148
02149 avio_seek(ic->pb, offset, SEEK_SET);
02150 read_size = 0;
02151 for(;;) {
02152 if (read_size >= DURATION_MAX_READ_SIZE<<(FFMAX(retry-1,0)))
02153 break;
02154
02155 do {
02156 ret = ff_read_packet(ic, pkt);
02157 } while(ret == AVERROR(EAGAIN));
02158 if (ret != 0)
02159 break;
02160 read_size += pkt->size;
02161 st = ic->streams[pkt->stream_index];
02162 if (pkt->pts != AV_NOPTS_VALUE &&
02163 (st->start_time != AV_NOPTS_VALUE ||
02164 st->first_dts != AV_NOPTS_VALUE)) {
02165 duration = end_time = pkt->pts;
02166 if (st->start_time != AV_NOPTS_VALUE)
02167 duration -= st->start_time;
02168 else
02169 duration -= st->first_dts;
02170 if (duration < 0)
02171 duration += 1LL<<st->pts_wrap_bits;
02172 if (duration > 0) {
02173 if (st->duration == AV_NOPTS_VALUE || st->duration < duration)
02174 st->duration = duration;
02175 }
02176 }
02177 av_free_packet(pkt);
02178 }
02179 }while( end_time==AV_NOPTS_VALUE
02180 && filesize > (DURATION_MAX_READ_SIZE<<retry)
02181 && ++retry <= DURATION_MAX_RETRY);
02182
02183 fill_all_stream_timings(ic);
02184
02185 avio_seek(ic->pb, old_offset, SEEK_SET);
02186 for (i=0; i<ic->nb_streams; i++) {
02187 st= ic->streams[i];
02188 st->cur_dts= st->first_dts;
02189 st->last_IP_pts = AV_NOPTS_VALUE;
02190 st->reference_dts = AV_NOPTS_VALUE;
02191 }
02192 }
02193
02194 static void estimate_timings(AVFormatContext *ic, int64_t old_offset)
02195 {
02196 int64_t file_size;
02197
02198
02199 if (ic->iformat->flags & AVFMT_NOFILE) {
02200 file_size = 0;
02201 } else {
02202 file_size = avio_size(ic->pb);
02203 file_size = FFMAX(0, file_size);
02204 }
02205
02206 if ((!strcmp(ic->iformat->name, "mpeg") ||
02207 !strcmp(ic->iformat->name, "mpegts")) &&
02208 file_size && ic->pb->seekable) {
02209
02210 estimate_timings_from_pts(ic, old_offset);
02211 } else if (has_duration(ic)) {
02212
02213
02214 fill_all_stream_timings(ic);
02215 } else {
02216 av_log(ic, AV_LOG_WARNING, "Estimating duration from bitrate, this may be inaccurate\n");
02217
02218 estimate_timings_from_bit_rate(ic);
02219 }
02220 update_stream_timings(ic);
02221
02222 {
02223 int i;
02224 AVStream av_unused *st;
02225 for(i = 0;i < ic->nb_streams; i++) {
02226 st = ic->streams[i];
02227 av_dlog(ic, "%d: start_time: %0.3f duration: %0.3f\n", i,
02228 (double) st->start_time / AV_TIME_BASE,
02229 (double) st->duration / AV_TIME_BASE);
02230 }
02231 av_dlog(ic, "stream: start_time: %0.3f duration: %0.3f bitrate=%d kb/s\n",
02232 (double) ic->start_time / AV_TIME_BASE,
02233 (double) ic->duration / AV_TIME_BASE,
02234 ic->bit_rate / 1000);
02235 }
02236 }
02237
02238 static int has_codec_parameters(AVStream *st)
02239 {
02240 AVCodecContext *avctx = st->codec;
02241 int val;
02242 switch (avctx->codec_type) {
02243 case AVMEDIA_TYPE_AUDIO:
02244 val = avctx->sample_rate && avctx->channels;
02245 if (!avctx->frame_size && determinable_frame_size(avctx))
02246 return 0;
02247 if (st->info->found_decoder >= 0 && avctx->sample_fmt == AV_SAMPLE_FMT_NONE)
02248 return 0;
02249 break;
02250 case AVMEDIA_TYPE_VIDEO:
02251 val = avctx->width;
02252 if (st->info->found_decoder >= 0 && avctx->pix_fmt == PIX_FMT_NONE)
02253 return 0;
02254 break;
02255 case AVMEDIA_TYPE_DATA:
02256 if(avctx->codec_id == CODEC_ID_NONE) return 1;
02257 default:
02258 val = 1;
02259 break;
02260 }
02261 return avctx->codec_id != CODEC_ID_NONE && val != 0;
02262 }
02263
02264 static int has_decode_delay_been_guessed(AVStream *st)
02265 {
02266 return st->codec->codec_id != CODEC_ID_H264 ||
02267 st->info->nb_decoded_frames >= 6;
02268 }
02269
02270
02271 static int try_decode_frame(AVStream *st, AVPacket *avpkt, AVDictionary **options)
02272 {
02273 AVCodec *codec;
02274 int got_picture = 1, ret = 0;
02275 AVFrame picture;
02276 AVPacket pkt = *avpkt;
02277
02278 if (!avcodec_is_open(st->codec) && !st->info->found_decoder) {
02279 AVDictionary *thread_opt = NULL;
02280
02281 codec = st->codec->codec ? st->codec->codec :
02282 avcodec_find_decoder(st->codec->codec_id);
02283
02284 if (!codec) {
02285 st->info->found_decoder = -1;
02286 return -1;
02287 }
02288
02289
02290
02291 av_dict_set(options ? options : &thread_opt, "threads", "1", 0);
02292 ret = avcodec_open2(st->codec, codec, options ? options : &thread_opt);
02293 if (!options)
02294 av_dict_free(&thread_opt);
02295 if (ret < 0) {
02296 st->info->found_decoder = -1;
02297 return ret;
02298 }
02299 st->info->found_decoder = 1;
02300 } else if (!st->info->found_decoder)
02301 st->info->found_decoder = 1;
02302
02303 if (st->info->found_decoder < 0)
02304 return -1;
02305
02306 while ((pkt.size > 0 || (!pkt.data && got_picture)) &&
02307 ret >= 0 &&
02308 (!has_codec_parameters(st) ||
02309 !has_decode_delay_been_guessed(st) ||
02310 (!st->codec_info_nb_frames && st->codec->codec->capabilities & CODEC_CAP_CHANNEL_CONF))) {
02311 got_picture = 0;
02312 avcodec_get_frame_defaults(&picture);
02313 switch(st->codec->codec_type) {
02314 case AVMEDIA_TYPE_VIDEO:
02315 ret = avcodec_decode_video2(st->codec, &picture,
02316 &got_picture, &pkt);
02317 break;
02318 case AVMEDIA_TYPE_AUDIO:
02319 ret = avcodec_decode_audio4(st->codec, &picture, &got_picture, &pkt);
02320 break;
02321 default:
02322 break;
02323 }
02324 if (ret >= 0) {
02325 if (got_picture)
02326 st->info->nb_decoded_frames++;
02327 pkt.data += ret;
02328 pkt.size -= ret;
02329 ret = got_picture;
02330 }
02331 }
02332 if(!pkt.data && !got_picture)
02333 return -1;
02334 return ret;
02335 }
02336
02337 unsigned int ff_codec_get_tag(const AVCodecTag *tags, enum CodecID id)
02338 {
02339 while (tags->id != CODEC_ID_NONE) {
02340 if (tags->id == id)
02341 return tags->tag;
02342 tags++;
02343 }
02344 return 0;
02345 }
02346
02347 enum CodecID ff_codec_get_id(const AVCodecTag *tags, unsigned int tag)
02348 {
02349 int i;
02350 for(i=0; tags[i].id != CODEC_ID_NONE;i++) {
02351 if(tag == tags[i].tag)
02352 return tags[i].id;
02353 }
02354 for(i=0; tags[i].id != CODEC_ID_NONE; i++) {
02355 if (avpriv_toupper4(tag) == avpriv_toupper4(tags[i].tag))
02356 return tags[i].id;
02357 }
02358 return CODEC_ID_NONE;
02359 }
02360
02361 unsigned int av_codec_get_tag(const AVCodecTag * const *tags, enum CodecID id)
02362 {
02363 int i;
02364 for(i=0; tags && tags[i]; i++){
02365 int tag= ff_codec_get_tag(tags[i], id);
02366 if(tag) return tag;
02367 }
02368 return 0;
02369 }
02370
02371 enum CodecID av_codec_get_id(const AVCodecTag * const *tags, unsigned int tag)
02372 {
02373 int i;
02374 for(i=0; tags && tags[i]; i++){
02375 enum CodecID id= ff_codec_get_id(tags[i], tag);
02376 if(id!=CODEC_ID_NONE) return id;
02377 }
02378 return CODEC_ID_NONE;
02379 }
02380
02381 static void compute_chapters_end(AVFormatContext *s)
02382 {
02383 unsigned int i, j;
02384 int64_t max_time = s->duration + ((s->start_time == AV_NOPTS_VALUE) ? 0 : s->start_time);
02385
02386 for (i = 0; i < s->nb_chapters; i++)
02387 if (s->chapters[i]->end == AV_NOPTS_VALUE) {
02388 AVChapter *ch = s->chapters[i];
02389 int64_t end = max_time ? av_rescale_q(max_time, AV_TIME_BASE_Q, ch->time_base)
02390 : INT64_MAX;
02391
02392 for (j = 0; j < s->nb_chapters; j++) {
02393 AVChapter *ch1 = s->chapters[j];
02394 int64_t next_start = av_rescale_q(ch1->start, ch1->time_base, ch->time_base);
02395 if (j != i && next_start > ch->start && next_start < end)
02396 end = next_start;
02397 }
02398 ch->end = (end == INT64_MAX) ? ch->start : end;
02399 }
02400 }
02401
02402 static int get_std_framerate(int i){
02403 if(i<60*12) return i*1001;
02404 else return ((const int[]){24,30,60,12,15})[i-60*12]*1000*12;
02405 }
02406
02407
02408
02409
02410
02411
02412
02413
02414
02415 static int tb_unreliable(AVCodecContext *c){
02416 if( c->time_base.den >= 101L*c->time_base.num
02417 || c->time_base.den < 5L*c->time_base.num
02418
02419
02420 || c->codec_id == CODEC_ID_MPEG2VIDEO
02421 || c->codec_id == CODEC_ID_H264
02422 )
02423 return 1;
02424 return 0;
02425 }
02426
02427 #if FF_API_FORMAT_PARAMETERS
02428 int av_find_stream_info(AVFormatContext *ic)
02429 {
02430 return avformat_find_stream_info(ic, NULL);
02431 }
02432 #endif
02433
02434 int avformat_find_stream_info(AVFormatContext *ic, AVDictionary **options)
02435 {
02436 int i, count, ret, read_size, j;
02437 AVStream *st;
02438 AVPacket pkt1, *pkt;
02439 int64_t old_offset = avio_tell(ic->pb);
02440 int orig_nb_streams = ic->nb_streams;
02441 int flush_codecs = 1;
02442
02443 if(ic->pb)
02444 av_log(ic, AV_LOG_DEBUG, "File position before avformat_find_stream_info() is %"PRId64"\n", avio_tell(ic->pb));
02445
02446 for(i=0;i<ic->nb_streams;i++) {
02447 AVCodec *codec;
02448 AVDictionary *thread_opt = NULL;
02449 st = ic->streams[i];
02450
02451 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO ||
02452 st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
02453
02454
02455 if(!st->codec->time_base.num)
02456 st->codec->time_base= st->time_base;
02457 }
02458
02459 if (!st->parser && !(ic->flags & AVFMT_FLAG_NOPARSE)) {
02460 st->parser = av_parser_init(st->codec->codec_id);
02461 if(st->parser){
02462 if(st->need_parsing == AVSTREAM_PARSE_HEADERS){
02463 st->parser->flags |= PARSER_FLAG_COMPLETE_FRAMES;
02464 } else if(st->need_parsing == AVSTREAM_PARSE_FULL_RAW) {
02465 st->parser->flags |= PARSER_FLAG_USE_CODEC_TS;
02466 }
02467 }
02468 }
02469 codec = st->codec->codec ? st->codec->codec :
02470 avcodec_find_decoder(st->codec->codec_id);
02471
02472
02473
02474 av_dict_set(options ? &options[i] : &thread_opt, "threads", "1", 0);
02475
02476
02477 if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE
02478 && codec && !st->codec->codec)
02479 avcodec_open2(st->codec, codec, options ? &options[i]
02480 : &thread_opt);
02481
02482
02483 if (!has_codec_parameters(st)) {
02484 if (codec && !st->codec->codec)
02485 avcodec_open2(st->codec, codec, options ? &options[i]
02486 : &thread_opt);
02487 }
02488 if (!options)
02489 av_dict_free(&thread_opt);
02490 }
02491
02492 for (i=0; i<ic->nb_streams; i++) {
02493 ic->streams[i]->info->last_dts = AV_NOPTS_VALUE;
02494 }
02495
02496 count = 0;
02497 read_size = 0;
02498 for(;;) {
02499 if (ff_check_interrupt(&ic->interrupt_callback)){
02500 ret= AVERROR_EXIT;
02501 av_log(ic, AV_LOG_DEBUG, "interrupted\n");
02502 break;
02503 }
02504
02505
02506 for(i=0;i<ic->nb_streams;i++) {
02507 int fps_analyze_framecount = 20;
02508
02509 st = ic->streams[i];
02510 if (!has_codec_parameters(st))
02511 break;
02512
02513
02514
02515 if (av_q2d(st->time_base) > 0.0005)
02516 fps_analyze_framecount *= 2;
02517 if (ic->fps_probe_size >= 0)
02518 fps_analyze_framecount = ic->fps_probe_size;
02519
02520 if( tb_unreliable(st->codec) && !(st->r_frame_rate.num && st->avg_frame_rate.num)
02521 && st->info->duration_count < fps_analyze_framecount
02522 && st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
02523 break;
02524 if(st->parser && st->parser->parser->split && !st->codec->extradata)
02525 break;
02526 if (st->first_dts == AV_NOPTS_VALUE &&
02527 (st->codec->codec_type == AVMEDIA_TYPE_VIDEO ||
02528 st->codec->codec_type == AVMEDIA_TYPE_AUDIO))
02529 break;
02530 }
02531 if (i == ic->nb_streams) {
02532
02533
02534
02535 if (!(ic->ctx_flags & AVFMTCTX_NOHEADER)) {
02536
02537 ret = count;
02538 av_log(ic, AV_LOG_DEBUG, "All info found\n");
02539 flush_codecs = 0;
02540 break;
02541 }
02542 }
02543
02544 if (read_size >= ic->probesize) {
02545 ret = count;
02546 av_log(ic, AV_LOG_DEBUG, "Probe buffer size limit %d reached\n", ic->probesize);
02547 for (i = 0; i < ic->nb_streams; i++)
02548 if (!ic->streams[i]->r_frame_rate.num &&
02549 ic->streams[i]->info->duration_count <= 1)
02550 av_log(ic, AV_LOG_WARNING,
02551 "Stream #%d: not enough frames to estimate rate; "
02552 "consider increasing probesize\n", i);
02553 break;
02554 }
02555
02556
02557
02558 ret = read_frame_internal(ic, &pkt1);
02559 if (ret == AVERROR(EAGAIN))
02560 continue;
02561
02562 if (ret < 0) {
02563
02564 break;
02565 }
02566
02567 pkt= add_to_pktbuf(&ic->packet_buffer, &pkt1, &ic->packet_buffer_end);
02568 if ((ret = av_dup_packet(pkt)) < 0)
02569 goto find_stream_info_err;
02570
02571 read_size += pkt->size;
02572
02573 st = ic->streams[pkt->stream_index];
02574 if (st->codec_info_nb_frames>1) {
02575 int64_t t=0;
02576 if (st->time_base.den > 0)
02577 t = av_rescale_q(st->info->codec_info_duration, st->time_base, AV_TIME_BASE_Q);
02578 if (st->avg_frame_rate.num > 0)
02579 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));
02580
02581 if (t >= ic->max_analyze_duration) {
02582 av_log(ic, AV_LOG_WARNING, "max_analyze_duration %d reached at %"PRId64"\n", ic->max_analyze_duration, t);
02583 break;
02584 }
02585 st->info->codec_info_duration += pkt->duration;
02586 }
02587 {
02588 int64_t last = st->info->last_dts;
02589
02590 if(pkt->dts != AV_NOPTS_VALUE && last != AV_NOPTS_VALUE && pkt->dts > last){
02591 double dts= (is_relative(pkt->dts) ? pkt->dts - RELATIVE_TS_BASE : pkt->dts) * av_q2d(st->time_base);
02592 int64_t duration= pkt->dts - last;
02593
02594
02595
02596 for (i=1; i<FF_ARRAY_ELEMS(st->info->duration_error[0][0]); i++) {
02597 int framerate= get_std_framerate(i);
02598 double sdts= dts*framerate/(1001*12);
02599 for(j=0; j<2; j++){
02600 int ticks= lrintf(sdts+j*0.5);
02601 double error= sdts - ticks + j*0.5;
02602 st->info->duration_error[j][0][i] += error;
02603 st->info->duration_error[j][1][i] += error*error;
02604 }
02605 }
02606 st->info->duration_count++;
02607
02608 if (st->info->duration_count > 3)
02609 st->info->duration_gcd = av_gcd(st->info->duration_gcd, duration);
02610 }
02611 if (last == AV_NOPTS_VALUE || st->info->duration_count <= 1)
02612 st->info->last_dts = pkt->dts;
02613 }
02614 if(st->parser && st->parser->parser->split && !st->codec->extradata){
02615 int i= st->parser->parser->split(st->codec, pkt->data, pkt->size);
02616 if (i > 0 && i < FF_MAX_EXTRADATA_SIZE) {
02617 st->codec->extradata_size= i;
02618 st->codec->extradata= av_malloc(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
02619 if (!st->codec->extradata)
02620 return AVERROR(ENOMEM);
02621 memcpy(st->codec->extradata, pkt->data, st->codec->extradata_size);
02622 memset(st->codec->extradata + i, 0, FF_INPUT_BUFFER_PADDING_SIZE);
02623 }
02624 }
02625
02626
02627
02628
02629
02630
02631
02632
02633
02634
02635 try_decode_frame(st, pkt, (options && i < orig_nb_streams ) ? &options[i] : NULL);
02636
02637 st->codec_info_nb_frames++;
02638 count++;
02639 }
02640
02641 if (flush_codecs) {
02642 AVPacket empty_pkt = { 0 };
02643 int err = 0;
02644 av_init_packet(&empty_pkt);
02645
02646 ret = -1;
02647 for(i=0;i<ic->nb_streams;i++) {
02648 st = ic->streams[i];
02649
02650
02651 if (st->info->found_decoder == 1) {
02652 do {
02653 err = try_decode_frame(st, &empty_pkt,
02654 (options && i < orig_nb_streams) ?
02655 &options[i] : NULL);
02656 } while (err > 0 && !has_codec_parameters(st));
02657
02658 if (err < 0) {
02659 av_log(ic, AV_LOG_INFO,
02660 "decoding for stream %d failed\n", st->index);
02661 }
02662 }
02663
02664 if (!has_codec_parameters(st)){
02665 char buf[256];
02666 avcodec_string(buf, sizeof(buf), st->codec, 0);
02667 av_log(ic, AV_LOG_WARNING,
02668 "Could not find codec parameters (%s)\n", buf);
02669 } else {
02670 ret = 0;
02671 }
02672 }
02673 }
02674
02675
02676 for(i=0;i<ic->nb_streams;i++) {
02677 st = ic->streams[i];
02678 avcodec_close(st->codec);
02679 }
02680 for(i=0;i<ic->nb_streams;i++) {
02681 st = ic->streams[i];
02682 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
02683 if(st->codec->codec_id == CODEC_ID_RAWVIDEO && !st->codec->codec_tag && !st->codec->bits_per_coded_sample){
02684 uint32_t tag= avcodec_pix_fmt_to_codec_tag(st->codec->pix_fmt);
02685 if(ff_find_pix_fmt(ff_raw_pix_fmt_tags, tag) == st->codec->pix_fmt)
02686 st->codec->codec_tag= tag;
02687 }
02688
02689 if (st->codec_info_nb_frames>2 && !st->avg_frame_rate.num && st->info->codec_info_duration)
02690 av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
02691 (st->codec_info_nb_frames-2)*(int64_t)st->time_base.den,
02692 st->info->codec_info_duration*(int64_t)st->time_base.num, 60000);
02693
02694
02695
02696 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)
02697 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);
02698 if (st->info->duration_count && !st->r_frame_rate.num
02699 && tb_unreliable(st->codec)
02700
02701 ){
02702 int num = 0;
02703 double best_error= 0.01;
02704
02705 for (j=1; j<FF_ARRAY_ELEMS(st->info->duration_error[0][0]); j++) {
02706 int k;
02707
02708 if(st->info->codec_info_duration && st->info->codec_info_duration*av_q2d(st->time_base) < (1001*12.0)/get_std_framerate(j))
02709 continue;
02710 if(!st->info->codec_info_duration && 1.0 < (1001*12.0)/get_std_framerate(j))
02711 continue;
02712 for(k=0; k<2; k++){
02713 int n= st->info->duration_count;
02714 double a= st->info->duration_error[k][0][j] / n;
02715 double error= st->info->duration_error[k][1][j]/n - a*a;
02716
02717 if(error < best_error && best_error> 0.000000001){
02718 best_error= error;
02719 num = get_std_framerate(j);
02720 }
02721 if(error < 0.02)
02722 av_log(NULL, AV_LOG_DEBUG, "rfps: %f %f\n", get_std_framerate(j) / 12.0/1001, error);
02723 }
02724 }
02725
02726 if (num && (!st->r_frame_rate.num || (double)num/(12*1001) < 1.01 * av_q2d(st->r_frame_rate)))
02727 av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den, num, 12*1001, INT_MAX);
02728 }
02729
02730 if (!st->r_frame_rate.num){
02731 if( st->codec->time_base.den * (int64_t)st->time_base.num
02732 <= st->codec->time_base.num * st->codec->ticks_per_frame * (int64_t)st->time_base.den){
02733 st->r_frame_rate.num = st->codec->time_base.den;
02734 st->r_frame_rate.den = st->codec->time_base.num * st->codec->ticks_per_frame;
02735 }else{
02736 st->r_frame_rate.num = st->time_base.den;
02737 st->r_frame_rate.den = st->time_base.num;
02738 }
02739 }
02740 }else if(st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
02741 if(!st->codec->bits_per_coded_sample)
02742 st->codec->bits_per_coded_sample= av_get_bits_per_sample(st->codec->codec_id);
02743
02744 switch (st->codec->audio_service_type) {
02745 case AV_AUDIO_SERVICE_TYPE_EFFECTS:
02746 st->disposition = AV_DISPOSITION_CLEAN_EFFECTS; break;
02747 case AV_AUDIO_SERVICE_TYPE_VISUALLY_IMPAIRED:
02748 st->disposition = AV_DISPOSITION_VISUAL_IMPAIRED; break;
02749 case AV_AUDIO_SERVICE_TYPE_HEARING_IMPAIRED:
02750 st->disposition = AV_DISPOSITION_HEARING_IMPAIRED; break;
02751 case AV_AUDIO_SERVICE_TYPE_COMMENTARY:
02752 st->disposition = AV_DISPOSITION_COMMENT; break;
02753 case AV_AUDIO_SERVICE_TYPE_KARAOKE:
02754 st->disposition = AV_DISPOSITION_KARAOKE; break;
02755 }
02756 }
02757 }
02758
02759 estimate_timings(ic, old_offset);
02760
02761 compute_chapters_end(ic);
02762
02763 find_stream_info_err:
02764 for (i=0; i < ic->nb_streams; i++) {
02765 if (ic->streams[i]->codec)
02766 ic->streams[i]->codec->thread_count = 0;
02767 av_freep(&ic->streams[i]->info);
02768 }
02769 if(ic->pb)
02770 av_log(ic, AV_LOG_DEBUG, "File position after avformat_find_stream_info() is %"PRId64"\n", avio_tell(ic->pb));
02771 return ret;
02772 }
02773
02774 AVProgram *av_find_program_from_stream(AVFormatContext *ic, AVProgram *last, int s)
02775 {
02776 int i, j;
02777
02778 for (i = 0; i < ic->nb_programs; i++) {
02779 if (ic->programs[i] == last) {
02780 last = NULL;
02781 } else {
02782 if (!last)
02783 for (j = 0; j < ic->programs[i]->nb_stream_indexes; j++)
02784 if (ic->programs[i]->stream_index[j] == s)
02785 return ic->programs[i];
02786 }
02787 }
02788 return NULL;
02789 }
02790
02791 int av_find_best_stream(AVFormatContext *ic,
02792 enum AVMediaType type,
02793 int wanted_stream_nb,
02794 int related_stream,
02795 AVCodec **decoder_ret,
02796 int flags)
02797 {
02798 int i, nb_streams = ic->nb_streams;
02799 int ret = AVERROR_STREAM_NOT_FOUND, best_count = -1;
02800 unsigned *program = NULL;
02801 AVCodec *decoder = NULL, *best_decoder = NULL;
02802
02803 if (related_stream >= 0 && wanted_stream_nb < 0) {
02804 AVProgram *p = av_find_program_from_stream(ic, NULL, related_stream);
02805 if (p) {
02806 program = p->stream_index;
02807 nb_streams = p->nb_stream_indexes;
02808 }
02809 }
02810 for (i = 0; i < nb_streams; i++) {
02811 int real_stream_index = program ? program[i] : i;
02812 AVStream *st = ic->streams[real_stream_index];
02813 AVCodecContext *avctx = st->codec;
02814 if (avctx->codec_type != type)
02815 continue;
02816 if (wanted_stream_nb >= 0 && real_stream_index != wanted_stream_nb)
02817 continue;
02818 if (st->disposition & (AV_DISPOSITION_HEARING_IMPAIRED|AV_DISPOSITION_VISUAL_IMPAIRED))
02819 continue;
02820 if (decoder_ret) {
02821 decoder = avcodec_find_decoder(st->codec->codec_id);
02822 if (!decoder) {
02823 if (ret < 0)
02824 ret = AVERROR_DECODER_NOT_FOUND;
02825 continue;
02826 }
02827 }
02828 if (best_count >= st->codec_info_nb_frames)
02829 continue;
02830 best_count = st->codec_info_nb_frames;
02831 ret = real_stream_index;
02832 best_decoder = decoder;
02833 if (program && i == nb_streams - 1 && ret < 0) {
02834 program = NULL;
02835 nb_streams = ic->nb_streams;
02836 i = 0;
02837 }
02838 }
02839 if (decoder_ret)
02840 *decoder_ret = best_decoder;
02841 return ret;
02842 }
02843
02844
02845
02846 int av_read_play(AVFormatContext *s)
02847 {
02848 if (s->iformat->read_play)
02849 return s->iformat->read_play(s);
02850 if (s->pb)
02851 return avio_pause(s->pb, 0);
02852 return AVERROR(ENOSYS);
02853 }
02854
02855 int av_read_pause(AVFormatContext *s)
02856 {
02857 if (s->iformat->read_pause)
02858 return s->iformat->read_pause(s);
02859 if (s->pb)
02860 return avio_pause(s->pb, 1);
02861 return AVERROR(ENOSYS);
02862 }
02863
02864 void avformat_free_context(AVFormatContext *s)
02865 {
02866 int i;
02867 AVStream *st;
02868
02869 av_opt_free(s);
02870 if (s->iformat && s->iformat->priv_class && s->priv_data)
02871 av_opt_free(s->priv_data);
02872
02873 for(i=0;i<s->nb_streams;i++) {
02874
02875 st = s->streams[i];
02876 if (st->parser) {
02877 av_parser_close(st->parser);
02878 }
02879 if (st->attached_pic.data)
02880 av_free_packet(&st->attached_pic);
02881 av_dict_free(&st->metadata);
02882 av_freep(&st->index_entries);
02883 av_freep(&st->codec->extradata);
02884 av_freep(&st->codec->subtitle_header);
02885 av_freep(&st->codec);
02886 av_freep(&st->priv_data);
02887 av_freep(&st->info);
02888 av_freep(&st);
02889 }
02890 for(i=s->nb_programs-1; i>=0; i--) {
02891 av_dict_free(&s->programs[i]->metadata);
02892 av_freep(&s->programs[i]->stream_index);
02893 av_freep(&s->programs[i]);
02894 }
02895 av_freep(&s->programs);
02896 av_freep(&s->priv_data);
02897 while(s->nb_chapters--) {
02898 av_dict_free(&s->chapters[s->nb_chapters]->metadata);
02899 av_freep(&s->chapters[s->nb_chapters]);
02900 }
02901 av_freep(&s->chapters);
02902 av_dict_free(&s->metadata);
02903 av_freep(&s->streams);
02904 av_free(s);
02905 }
02906
02907 #if FF_API_CLOSE_INPUT_FILE
02908 void av_close_input_file(AVFormatContext *s)
02909 {
02910 avformat_close_input(&s);
02911 }
02912 #endif
02913
02914 void avformat_close_input(AVFormatContext **ps)
02915 {
02916 AVFormatContext *s = *ps;
02917 AVIOContext *pb = (s->iformat && (s->iformat->flags & AVFMT_NOFILE)) || (s->flags & AVFMT_FLAG_CUSTOM_IO) ?
02918 NULL : s->pb;
02919 flush_packet_queue(s);
02920 if (s->iformat && (s->iformat->read_close))
02921 s->iformat->read_close(s);
02922 avformat_free_context(s);
02923 *ps = NULL;
02924 if (pb)
02925 avio_close(pb);
02926 }
02927
02928 #if FF_API_NEW_STREAM
02929 AVStream *av_new_stream(AVFormatContext *s, int id)
02930 {
02931 AVStream *st = avformat_new_stream(s, NULL);
02932 if (st)
02933 st->id = id;
02934 return st;
02935 }
02936 #endif
02937
02938 AVStream *avformat_new_stream(AVFormatContext *s, AVCodec *c)
02939 {
02940 AVStream *st;
02941 int i;
02942 AVStream **streams;
02943
02944 if (s->nb_streams >= INT_MAX/sizeof(*streams))
02945 return NULL;
02946 streams = av_realloc(s->streams, (s->nb_streams + 1) * sizeof(*streams));
02947 if (!streams)
02948 return NULL;
02949 s->streams = streams;
02950
02951 st = av_mallocz(sizeof(AVStream));
02952 if (!st)
02953 return NULL;
02954 if (!(st->info = av_mallocz(sizeof(*st->info)))) {
02955 av_free(st);
02956 return NULL;
02957 }
02958 st->info->last_dts = AV_NOPTS_VALUE;
02959
02960 st->codec = avcodec_alloc_context3(c);
02961 if (s->iformat) {
02962
02963 st->codec->bit_rate = 0;
02964 }
02965 st->index = s->nb_streams;
02966 st->start_time = AV_NOPTS_VALUE;
02967 st->duration = AV_NOPTS_VALUE;
02968
02969
02970
02971
02972 st->cur_dts = s->iformat ? RELATIVE_TS_BASE : 0;
02973 st->first_dts = AV_NOPTS_VALUE;
02974 st->probe_packets = MAX_PROBE_PACKETS;
02975
02976
02977 avpriv_set_pts_info(st, 33, 1, 90000);
02978 st->last_IP_pts = AV_NOPTS_VALUE;
02979 for(i=0; i<MAX_REORDER_DELAY+1; i++)
02980 st->pts_buffer[i]= AV_NOPTS_VALUE;
02981 st->reference_dts = AV_NOPTS_VALUE;
02982
02983 st->sample_aspect_ratio = (AVRational){0,1};
02984
02985 s->streams[s->nb_streams++] = st;
02986 return st;
02987 }
02988
02989 AVProgram *av_new_program(AVFormatContext *ac, int id)
02990 {
02991 AVProgram *program=NULL;
02992 int i;
02993
02994 av_dlog(ac, "new_program: id=0x%04x\n", id);
02995
02996 for(i=0; i<ac->nb_programs; i++)
02997 if(ac->programs[i]->id == id)
02998 program = ac->programs[i];
02999
03000 if(!program){
03001 program = av_mallocz(sizeof(AVProgram));
03002 if (!program)
03003 return NULL;
03004 dynarray_add(&ac->programs, &ac->nb_programs, program);
03005 program->discard = AVDISCARD_NONE;
03006 }
03007 program->id = id;
03008
03009 return program;
03010 }
03011
03012 AVChapter *avpriv_new_chapter(AVFormatContext *s, int id, AVRational time_base, int64_t start, int64_t end, const char *title)
03013 {
03014 AVChapter *chapter = NULL;
03015 int i;
03016
03017 for(i=0; i<s->nb_chapters; i++)
03018 if(s->chapters[i]->id == id)
03019 chapter = s->chapters[i];
03020
03021 if(!chapter){
03022 chapter= av_mallocz(sizeof(AVChapter));
03023 if(!chapter)
03024 return NULL;
03025 dynarray_add(&s->chapters, &s->nb_chapters, chapter);
03026 }
03027 av_dict_set(&chapter->metadata, "title", title, 0);
03028 chapter->id = id;
03029 chapter->time_base= time_base;
03030 chapter->start = start;
03031 chapter->end = end;
03032
03033 return chapter;
03034 }
03035
03036
03037
03038
03039 int avformat_alloc_output_context2(AVFormatContext **avctx, AVOutputFormat *oformat,
03040 const char *format, const char *filename)
03041 {
03042 AVFormatContext *s = avformat_alloc_context();
03043 int ret = 0;
03044
03045 *avctx = NULL;
03046 if (!s)
03047 goto nomem;
03048
03049 if (!oformat) {
03050 if (format) {
03051 oformat = av_guess_format(format, NULL, NULL);
03052 if (!oformat) {
03053 av_log(s, AV_LOG_ERROR, "Requested output format '%s' is not a suitable output format\n", format);
03054 ret = AVERROR(EINVAL);
03055 goto error;
03056 }
03057 } else {
03058 oformat = av_guess_format(NULL, filename, NULL);
03059 if (!oformat) {
03060 ret = AVERROR(EINVAL);
03061 av_log(s, AV_LOG_ERROR, "Unable to find a suitable output format for '%s'\n",
03062 filename);
03063 goto error;
03064 }
03065 }
03066 }
03067
03068 s->oformat = oformat;
03069 if (s->oformat->priv_data_size > 0) {
03070 s->priv_data = av_mallocz(s->oformat->priv_data_size);
03071 if (!s->priv_data)
03072 goto nomem;
03073 if (s->oformat->priv_class) {
03074 *(const AVClass**)s->priv_data= s->oformat->priv_class;
03075 av_opt_set_defaults(s->priv_data);
03076 }
03077 } else
03078 s->priv_data = NULL;
03079
03080 if (filename)
03081 av_strlcpy(s->filename, filename, sizeof(s->filename));
03082 *avctx = s;
03083 return 0;
03084 nomem:
03085 av_log(s, AV_LOG_ERROR, "Out of memory\n");
03086 ret = AVERROR(ENOMEM);
03087 error:
03088 avformat_free_context(s);
03089 return ret;
03090 }
03091
03092 #if FF_API_ALLOC_OUTPUT_CONTEXT
03093 AVFormatContext *avformat_alloc_output_context(const char *format,
03094 AVOutputFormat *oformat, const char *filename)
03095 {
03096 AVFormatContext *avctx;
03097 int ret = avformat_alloc_output_context2(&avctx, oformat, format, filename);
03098 return ret < 0 ? NULL : avctx;
03099 }
03100 #endif
03101
03102 static int validate_codec_tag(AVFormatContext *s, AVStream *st)
03103 {
03104 const AVCodecTag *avctag;
03105 int n;
03106 enum CodecID id = CODEC_ID_NONE;
03107 unsigned int tag = 0;
03108
03115 for (n = 0; s->oformat->codec_tag[n]; n++) {
03116 avctag = s->oformat->codec_tag[n];
03117 while (avctag->id != CODEC_ID_NONE) {
03118 if (avpriv_toupper4(avctag->tag) == avpriv_toupper4(st->codec->codec_tag)) {
03119 id = avctag->id;
03120 if (id == st->codec->codec_id)
03121 return 1;
03122 }
03123 if (avctag->id == st->codec->codec_id)
03124 tag = avctag->tag;
03125 avctag++;
03126 }
03127 }
03128 if (id != CODEC_ID_NONE)
03129 return 0;
03130 if (tag && (st->codec->strict_std_compliance >= FF_COMPLIANCE_NORMAL))
03131 return 0;
03132 return 1;
03133 }
03134
03135 int avformat_write_header(AVFormatContext *s, AVDictionary **options)
03136 {
03137 int ret = 0, i;
03138 AVStream *st;
03139 AVDictionary *tmp = NULL;
03140
03141 if (options)
03142 av_dict_copy(&tmp, *options, 0);
03143 if ((ret = av_opt_set_dict(s, &tmp)) < 0)
03144 goto fail;
03145 if (s->priv_data && s->oformat->priv_class && *(const AVClass**)s->priv_data==s->oformat->priv_class &&
03146 (ret = av_opt_set_dict(s->priv_data, &tmp)) < 0)
03147 goto fail;
03148
03149
03150 if (s->nb_streams == 0 && !(s->oformat->flags & AVFMT_NOSTREAMS)) {
03151 av_log(s, AV_LOG_ERROR, "no streams\n");
03152 ret = AVERROR(EINVAL);
03153 goto fail;
03154 }
03155
03156 for(i=0;i<s->nb_streams;i++) {
03157 st = s->streams[i];
03158
03159 switch (st->codec->codec_type) {
03160 case AVMEDIA_TYPE_AUDIO:
03161 if(st->codec->sample_rate<=0){
03162 av_log(s, AV_LOG_ERROR, "sample rate not set\n");
03163 ret = AVERROR(EINVAL);
03164 goto fail;
03165 }
03166 if(!st->codec->block_align)
03167 st->codec->block_align = st->codec->channels *
03168 av_get_bits_per_sample(st->codec->codec_id) >> 3;
03169 break;
03170 case AVMEDIA_TYPE_VIDEO:
03171 if(st->codec->time_base.num<=0 || st->codec->time_base.den<=0){
03172 av_log(s, AV_LOG_ERROR, "time base not set\n");
03173 ret = AVERROR(EINVAL);
03174 goto fail;
03175 }
03176 if((st->codec->width<=0 || st->codec->height<=0) && !(s->oformat->flags & AVFMT_NODIMENSIONS)){
03177 av_log(s, AV_LOG_ERROR, "dimensions not set\n");
03178 ret = AVERROR(EINVAL);
03179 goto fail;
03180 }
03181 if(av_cmp_q(st->sample_aspect_ratio, st->codec->sample_aspect_ratio)
03182 && FFABS(av_q2d(st->sample_aspect_ratio) - av_q2d(st->codec->sample_aspect_ratio)) > 0.004*av_q2d(st->sample_aspect_ratio)
03183 ){
03184 av_log(s, AV_LOG_ERROR, "Aspect ratio mismatch between muxer "
03185 "(%d/%d) and encoder layer (%d/%d)\n",
03186 st->sample_aspect_ratio.num, st->sample_aspect_ratio.den,
03187 st->codec->sample_aspect_ratio.num,
03188 st->codec->sample_aspect_ratio.den);
03189 ret = AVERROR(EINVAL);
03190 goto fail;
03191 }
03192 break;
03193 }
03194
03195 if(s->oformat->codec_tag){
03196 if( st->codec->codec_tag
03197 && st->codec->codec_id == CODEC_ID_RAWVIDEO
03198 && (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', ' '))
03199 && !validate_codec_tag(s, st)){
03200
03201 st->codec->codec_tag= 0;
03202 }
03203 if(st->codec->codec_tag){
03204 if (!validate_codec_tag(s, st)) {
03205 char tagbuf[32], cortag[32];
03206 av_get_codec_tag_string(tagbuf, sizeof(tagbuf), st->codec->codec_tag);
03207 av_get_codec_tag_string(cortag, sizeof(cortag), av_codec_get_tag(s->oformat->codec_tag, st->codec->codec_id));
03208 av_log(s, AV_LOG_ERROR,
03209 "Tag %s/0x%08x incompatible with output codec id '%d' (%s)\n",
03210 tagbuf, st->codec->codec_tag, st->codec->codec_id, cortag);
03211 ret = AVERROR_INVALIDDATA;
03212 goto fail;
03213 }
03214 }else
03215 st->codec->codec_tag= av_codec_get_tag(s->oformat->codec_tag, st->codec->codec_id);
03216 }
03217
03218 if(s->oformat->flags & AVFMT_GLOBALHEADER &&
03219 !(st->codec->flags & CODEC_FLAG_GLOBAL_HEADER))
03220 av_log(s, AV_LOG_WARNING, "Codec for stream %d does not use global headers but container format requires global headers\n", i);
03221 }
03222
03223 if (!s->priv_data && s->oformat->priv_data_size > 0) {
03224 s->priv_data = av_mallocz(s->oformat->priv_data_size);
03225 if (!s->priv_data) {
03226 ret = AVERROR(ENOMEM);
03227 goto fail;
03228 }
03229 if (s->oformat->priv_class) {
03230 *(const AVClass**)s->priv_data= s->oformat->priv_class;
03231 av_opt_set_defaults(s->priv_data);
03232 if ((ret = av_opt_set_dict(s->priv_data, &tmp)) < 0)
03233 goto fail;
03234 }
03235 }
03236
03237
03238 if (s->nb_streams && !(s->streams[0]->codec->flags & CODEC_FLAG_BITEXACT)) {
03239 av_dict_set(&s->metadata, "encoder", LIBAVFORMAT_IDENT, 0);
03240 }
03241
03242 if(s->oformat->write_header){
03243 ret = s->oformat->write_header(s);
03244 if (ret < 0)
03245 goto fail;
03246 }
03247
03248
03249 for(i=0;i<s->nb_streams;i++) {
03250 int64_t den = AV_NOPTS_VALUE;
03251 st = s->streams[i];
03252
03253 switch (st->codec->codec_type) {
03254 case AVMEDIA_TYPE_AUDIO:
03255 den = (int64_t)st->time_base.num * st->codec->sample_rate;
03256 break;
03257 case AVMEDIA_TYPE_VIDEO:
03258 den = (int64_t)st->time_base.num * st->codec->time_base.den;
03259 break;
03260 default:
03261 break;
03262 }
03263 if (den != AV_NOPTS_VALUE) {
03264 if (den <= 0) {
03265 ret = AVERROR_INVALIDDATA;
03266 goto fail;
03267 }
03268 frac_init(&st->pts, 0, 0, den);
03269 }
03270 }
03271
03272 if (options) {
03273 av_dict_free(options);
03274 *options = tmp;
03275 }
03276 return 0;
03277 fail:
03278 av_dict_free(&tmp);
03279 return ret;
03280 }
03281
03282
03283 static int compute_pkt_fields2(AVFormatContext *s, AVStream *st, AVPacket *pkt){
03284 int delay = FFMAX(st->codec->has_b_frames, !!st->codec->max_b_frames);
03285 int num, den, frame_size, i;
03286
03287 av_dlog(s, "compute_pkt_fields2: pts:%s dts:%s cur_dts:%s b:%d size:%d st:%d\n",
03288 av_ts2str(pkt->pts), av_ts2str(pkt->dts), av_ts2str(st->cur_dts), delay, pkt->size, pkt->stream_index);
03289
03290
03291 if (pkt->duration == 0) {
03292 compute_frame_duration(&num, &den, st, NULL, pkt);
03293 if (den && num) {
03294 pkt->duration = av_rescale(1, num * (int64_t)st->time_base.den * st->codec->ticks_per_frame, den * (int64_t)st->time_base.num);
03295 }
03296 }
03297
03298 if(pkt->pts == AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE && delay==0)
03299 pkt->pts= pkt->dts;
03300
03301
03302 if((pkt->pts == 0 || pkt->pts == AV_NOPTS_VALUE) && pkt->dts == AV_NOPTS_VALUE && !delay){
03303 static int warned;
03304 if (!warned) {
03305 av_log(s, AV_LOG_WARNING, "Encoder did not produce proper pts, making some up.\n");
03306 warned = 1;
03307 }
03308 pkt->dts=
03309
03310 pkt->pts= st->pts.val;
03311 }
03312
03313
03314 if(pkt->pts != AV_NOPTS_VALUE && pkt->dts == AV_NOPTS_VALUE && delay <= MAX_REORDER_DELAY){
03315 st->pts_buffer[0]= pkt->pts;
03316 for(i=1; i<delay+1 && st->pts_buffer[i] == AV_NOPTS_VALUE; i++)
03317 st->pts_buffer[i]= pkt->pts + (i-delay-1) * pkt->duration;
03318 for(i=0; i<delay && st->pts_buffer[i] > st->pts_buffer[i+1]; i++)
03319 FFSWAP(int64_t, st->pts_buffer[i], st->pts_buffer[i+1]);
03320
03321 pkt->dts= st->pts_buffer[0];
03322 }
03323
03324 if (st->cur_dts && st->cur_dts != AV_NOPTS_VALUE &&
03325 ((!(s->oformat->flags & AVFMT_TS_NONSTRICT) &&
03326 st->cur_dts >= pkt->dts) || st->cur_dts > pkt->dts)) {
03327 av_log(s, AV_LOG_ERROR,
03328 "Application provided invalid, non monotonically increasing dts to muxer in stream %d: %s >= %s\n",
03329 st->index, av_ts2str(st->cur_dts), av_ts2str(pkt->dts));
03330 return AVERROR(EINVAL);
03331 }
03332 if(pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE && pkt->pts < pkt->dts){
03333 av_log(s, AV_LOG_ERROR, "pts (%s) < dts (%s) in stream %d\n",
03334 av_ts2str(pkt->pts), av_ts2str(pkt->dts), st->index);
03335 return AVERROR(EINVAL);
03336 }
03337
03338
03339 st->cur_dts= pkt->dts;
03340 st->pts.val= pkt->dts;
03341
03342
03343 switch (st->codec->codec_type) {
03344 case AVMEDIA_TYPE_AUDIO:
03345 frame_size = get_audio_frame_size(st->codec, pkt->size, 1);
03346
03347
03348
03349
03350 if (frame_size >= 0 && (pkt->size || st->pts.num!=st->pts.den>>1 || st->pts.val)) {
03351 frac_add(&st->pts, (int64_t)st->time_base.den * frame_size);
03352 }
03353 break;
03354 case AVMEDIA_TYPE_VIDEO:
03355 frac_add(&st->pts, (int64_t)st->time_base.den * st->codec->time_base.num);
03356 break;
03357 default:
03358 break;
03359 }
03360 return 0;
03361 }
03362
03363 int av_write_frame(AVFormatContext *s, AVPacket *pkt)
03364 {
03365 int ret;
03366
03367 if (!pkt) {
03368 if (s->oformat->flags & AVFMT_ALLOW_FLUSH)
03369 return s->oformat->write_packet(s, pkt);
03370 return 1;
03371 }
03372
03373 ret = compute_pkt_fields2(s, s->streams[pkt->stream_index], pkt);
03374
03375 if(ret<0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
03376 return ret;
03377
03378 ret= s->oformat->write_packet(s, pkt);
03379
03380 if (ret >= 0)
03381 s->streams[pkt->stream_index]->nb_frames++;
03382 return ret;
03383 }
03384
03385 #define CHUNK_START 0x1000
03386
03387 int ff_interleave_add_packet(AVFormatContext *s, AVPacket *pkt,
03388 int (*compare)(AVFormatContext *, AVPacket *, AVPacket *))
03389 {
03390 AVPacketList **next_point, *this_pktl;
03391 AVStream *st= s->streams[pkt->stream_index];
03392 int chunked= s->max_chunk_size || s->max_chunk_duration;
03393
03394 this_pktl = av_mallocz(sizeof(AVPacketList));
03395 if (!this_pktl)
03396 return AVERROR(ENOMEM);
03397 this_pktl->pkt= *pkt;
03398 pkt->destruct= NULL;
03399 av_dup_packet(&this_pktl->pkt);
03400
03401 if(s->streams[pkt->stream_index]->last_in_packet_buffer){
03402 next_point = &(st->last_in_packet_buffer->next);
03403 }else{
03404 next_point = &s->packet_buffer;
03405 }
03406
03407 if(*next_point){
03408 if(chunked){
03409 uint64_t max= av_rescale_q(s->max_chunk_duration, AV_TIME_BASE_Q, st->time_base);
03410 if( st->interleaver_chunk_size + pkt->size <= s->max_chunk_size-1U
03411 && st->interleaver_chunk_duration + pkt->duration <= max-1U){
03412 st->interleaver_chunk_size += pkt->size;
03413 st->interleaver_chunk_duration += pkt->duration;
03414 goto next_non_null;
03415 }else{
03416 st->interleaver_chunk_size =
03417 st->interleaver_chunk_duration = 0;
03418 this_pktl->pkt.flags |= CHUNK_START;
03419 }
03420 }
03421
03422 if(compare(s, &s->packet_buffer_end->pkt, pkt)){
03423 while( *next_point
03424 && ((chunked && !((*next_point)->pkt.flags&CHUNK_START))
03425 || !compare(s, &(*next_point)->pkt, pkt))){
03426 next_point= &(*next_point)->next;
03427 }
03428 if(*next_point)
03429 goto next_non_null;
03430 }else{
03431 next_point = &(s->packet_buffer_end->next);
03432 }
03433 }
03434 assert(!*next_point);
03435
03436 s->packet_buffer_end= this_pktl;
03437 next_non_null:
03438
03439 this_pktl->next= *next_point;
03440
03441 s->streams[pkt->stream_index]->last_in_packet_buffer=
03442 *next_point= this_pktl;
03443 return 0;
03444 }
03445
03446 static int ff_interleave_compare_dts(AVFormatContext *s, AVPacket *next, AVPacket *pkt)
03447 {
03448 AVStream *st = s->streams[ pkt ->stream_index];
03449 AVStream *st2= s->streams[ next->stream_index];
03450 int comp = av_compare_ts(next->dts, st2->time_base, pkt->dts,
03451 st->time_base);
03452 if(s->audio_preload && ((st->codec->codec_type == AVMEDIA_TYPE_AUDIO) != (st2->codec->codec_type == AVMEDIA_TYPE_AUDIO))){
03453 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);
03454 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);
03455 if(ts == ts2){
03456 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
03457 -( 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;
03458 ts2=0;
03459 }
03460 comp= (ts>ts2) - (ts<ts2);
03461 }
03462
03463 if (comp == 0)
03464 return pkt->stream_index < next->stream_index;
03465 return comp > 0;
03466 }
03467
03468 int ff_interleave_packet_per_dts(AVFormatContext *s, AVPacket *out,
03469 AVPacket *pkt, int flush)
03470 {
03471 AVPacketList *pktl;
03472 int stream_count=0, noninterleaved_count=0;
03473 int64_t delta_dts_max = 0;
03474 int i, ret;
03475
03476 if(pkt){
03477 ret = ff_interleave_add_packet(s, pkt, ff_interleave_compare_dts);
03478 if (ret < 0)
03479 return ret;
03480 }
03481
03482 for(i=0; i < s->nb_streams; i++) {
03483 if (s->streams[i]->last_in_packet_buffer) {
03484 ++stream_count;
03485 } else if(s->streams[i]->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
03486 ++noninterleaved_count;
03487 }
03488 }
03489
03490 if (s->nb_streams == stream_count) {
03491 flush = 1;
03492 } else if (!flush){
03493 for(i=0; i < s->nb_streams; i++) {
03494 if (s->streams[i]->last_in_packet_buffer) {
03495 int64_t delta_dts =
03496 av_rescale_q(s->streams[i]->last_in_packet_buffer->pkt.dts,
03497 s->streams[i]->time_base,
03498 AV_TIME_BASE_Q) -
03499 av_rescale_q(s->packet_buffer->pkt.dts,
03500 s->streams[s->packet_buffer->pkt.stream_index]->time_base,
03501 AV_TIME_BASE_Q);
03502 delta_dts_max= FFMAX(delta_dts_max, delta_dts);
03503 }
03504 }
03505 if(s->nb_streams == stream_count+noninterleaved_count &&
03506 delta_dts_max > 20*AV_TIME_BASE) {
03507 av_log(s, AV_LOG_DEBUG, "flushing with %d noninterleaved\n", noninterleaved_count);
03508 flush = 1;
03509 }
03510 }
03511 if(stream_count && flush){
03512 pktl= s->packet_buffer;
03513 *out= pktl->pkt;
03514
03515 s->packet_buffer= pktl->next;
03516 if(!s->packet_buffer)
03517 s->packet_buffer_end= NULL;
03518
03519 if(s->streams[out->stream_index]->last_in_packet_buffer == pktl)
03520 s->streams[out->stream_index]->last_in_packet_buffer= NULL;
03521 av_freep(&pktl);
03522 return 1;
03523 }else{
03524 av_init_packet(out);
03525 return 0;
03526 }
03527 }
03528
03529 #if FF_API_INTERLEAVE_PACKET
03530 int av_interleave_packet_per_dts(AVFormatContext *s, AVPacket *out,
03531 AVPacket *pkt, int flush)
03532 {
03533 return ff_interleave_packet_per_dts(s, out, pkt, flush);
03534 }
03535 #endif
03536
03546 static int interleave_packet(AVFormatContext *s, AVPacket *out, AVPacket *in, int flush){
03547 if (s->oformat->interleave_packet) {
03548 int ret = s->oformat->interleave_packet(s, out, in, flush);
03549 if (in)
03550 av_free_packet(in);
03551 return ret;
03552 } else
03553 return ff_interleave_packet_per_dts(s, out, in, flush);
03554 }
03555
03556 int av_interleaved_write_frame(AVFormatContext *s, AVPacket *pkt){
03557 int ret, flush = 0;
03558
03559 if (pkt) {
03560 AVStream *st= s->streams[ pkt->stream_index];
03561
03562
03563 if(st->codec->codec_type == AVMEDIA_TYPE_AUDIO && pkt->size==0)
03564 return 0;
03565
03566 av_dlog(s, "av_interleaved_write_frame size:%d dts:%s pts:%s\n",
03567 pkt->size, av_ts2str(pkt->dts), av_ts2str(pkt->pts));
03568 if((ret = compute_pkt_fields2(s, st, pkt)) < 0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
03569 return ret;
03570
03571 if(pkt->dts == AV_NOPTS_VALUE && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
03572 return AVERROR(EINVAL);
03573 } else {
03574 av_dlog(s, "av_interleaved_write_frame FLUSH\n");
03575 flush = 1;
03576 }
03577
03578 for(;;){
03579 AVPacket opkt;
03580 int ret= interleave_packet(s, &opkt, pkt, flush);
03581 if(ret<=0)
03582 return ret;
03583
03584 ret= s->oformat->write_packet(s, &opkt);
03585 if (ret >= 0)
03586 s->streams[opkt.stream_index]->nb_frames++;
03587
03588 av_free_packet(&opkt);
03589 pkt= NULL;
03590
03591 if(ret<0)
03592 return ret;
03593 if(s->pb && s->pb->error)
03594 return s->pb->error;
03595 }
03596 }
03597
03598 int av_write_trailer(AVFormatContext *s)
03599 {
03600 int ret, i;
03601
03602 for(;;){
03603 AVPacket pkt;
03604 ret= interleave_packet(s, &pkt, NULL, 1);
03605 if(ret<0)
03606 goto fail;
03607 if(!ret)
03608 break;
03609
03610 ret= s->oformat->write_packet(s, &pkt);
03611 if (ret >= 0)
03612 s->streams[pkt.stream_index]->nb_frames++;
03613
03614 av_free_packet(&pkt);
03615
03616 if(ret<0)
03617 goto fail;
03618 if(s->pb && s->pb->error)
03619 goto fail;
03620 }
03621
03622 if(s->oformat->write_trailer)
03623 ret = s->oformat->write_trailer(s);
03624 fail:
03625 if (s->pb)
03626 avio_flush(s->pb);
03627 if(ret == 0)
03628 ret = s->pb ? s->pb->error : 0;
03629 for(i=0;i<s->nb_streams;i++) {
03630 av_freep(&s->streams[i]->priv_data);
03631 av_freep(&s->streams[i]->index_entries);
03632 }
03633 if (s->oformat->priv_class)
03634 av_opt_free(s->priv_data);
03635 av_freep(&s->priv_data);
03636 return ret;
03637 }
03638
03639 int av_get_output_timestamp(struct AVFormatContext *s, int stream,
03640 int64_t *dts, int64_t *wall)
03641 {
03642 if (!s->oformat || !s->oformat->get_output_timestamp)
03643 return AVERROR(ENOSYS);
03644 s->oformat->get_output_timestamp(s, stream, dts, wall);
03645 return 0;
03646 }
03647
03648 void ff_program_add_stream_index(AVFormatContext *ac, int progid, unsigned int idx)
03649 {
03650 int i, j;
03651 AVProgram *program=NULL;
03652 void *tmp;
03653
03654 if (idx >= ac->nb_streams) {
03655 av_log(ac, AV_LOG_ERROR, "stream index %d is not valid\n", idx);
03656 return;
03657 }
03658
03659 for(i=0; i<ac->nb_programs; i++){
03660 if(ac->programs[i]->id != progid)
03661 continue;
03662 program = ac->programs[i];
03663 for(j=0; j<program->nb_stream_indexes; j++)
03664 if(program->stream_index[j] == idx)
03665 return;
03666
03667 tmp = av_realloc(program->stream_index, sizeof(unsigned int)*(program->nb_stream_indexes+1));
03668 if(!tmp)
03669 return;
03670 program->stream_index = tmp;
03671 program->stream_index[program->nb_stream_indexes++] = idx;
03672 return;
03673 }
03674 }
03675
03676 static void print_fps(double d, const char *postfix){
03677 uint64_t v= lrintf(d*100);
03678 if (v% 100 ) av_log(NULL, AV_LOG_INFO, ", %3.2f %s", d, postfix);
03679 else if(v%(100*1000)) av_log(NULL, AV_LOG_INFO, ", %1.0f %s", d, postfix);
03680 else av_log(NULL, AV_LOG_INFO, ", %1.0fk %s", d/1000, postfix);
03681 }
03682
03683 static void dump_metadata(void *ctx, AVDictionary *m, const char *indent)
03684 {
03685 if(m && !(m->count == 1 && av_dict_get(m, "language", NULL, 0))){
03686 AVDictionaryEntry *tag=NULL;
03687
03688 av_log(ctx, AV_LOG_INFO, "%sMetadata:\n", indent);
03689 while((tag=av_dict_get(m, "", tag, AV_DICT_IGNORE_SUFFIX))) {
03690 if(strcmp("language", tag->key)){
03691 const char *p = tag->value;
03692 av_log(ctx, AV_LOG_INFO, "%s %-16s: ", indent, tag->key);
03693 while(*p) {
03694 char tmp[256];
03695 size_t len = strcspn(p, "\xd\xa");
03696 av_strlcpy(tmp, p, FFMIN(sizeof(tmp), len+1));
03697 av_log(ctx, AV_LOG_INFO, "%s", tmp);
03698 p += len;
03699 if (*p == 0xd) av_log(ctx, AV_LOG_INFO, " ");
03700 if (*p == 0xa) av_log(ctx, AV_LOG_INFO, "\n%s %-16s: ", indent, "");
03701 if (*p) p++;
03702 }
03703 av_log(ctx, AV_LOG_INFO, "\n");
03704 }
03705 }
03706 }
03707 }
03708
03709
03710 static void dump_stream_format(AVFormatContext *ic, int i, int index, int is_output)
03711 {
03712 char buf[256];
03713 int flags = (is_output ? ic->oformat->flags : ic->iformat->flags);
03714 AVStream *st = ic->streams[i];
03715 int g = av_gcd(st->time_base.num, st->time_base.den);
03716 AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL, 0);
03717 avcodec_string(buf, sizeof(buf), st->codec, is_output);
03718 av_log(NULL, AV_LOG_INFO, " Stream #%d:%d", index, i);
03719
03720
03721 if (flags & AVFMT_SHOW_IDS)
03722 av_log(NULL, AV_LOG_INFO, "[0x%x]", st->id);
03723 if (lang)
03724 av_log(NULL, AV_LOG_INFO, "(%s)", lang->value);
03725 av_log(NULL, AV_LOG_DEBUG, ", %d, %d/%d", st->codec_info_nb_frames, st->time_base.num/g, st->time_base.den/g);
03726 av_log(NULL, AV_LOG_INFO, ": %s", buf);
03727 if (st->sample_aspect_ratio.num &&
03728 av_cmp_q(st->sample_aspect_ratio, st->codec->sample_aspect_ratio)) {
03729 AVRational display_aspect_ratio;
03730 av_reduce(&display_aspect_ratio.num, &display_aspect_ratio.den,
03731 st->codec->width*st->sample_aspect_ratio.num,
03732 st->codec->height*st->sample_aspect_ratio.den,
03733 1024*1024);
03734 av_log(NULL, AV_LOG_INFO, ", SAR %d:%d DAR %d:%d",
03735 st->sample_aspect_ratio.num, st->sample_aspect_ratio.den,
03736 display_aspect_ratio.num, display_aspect_ratio.den);
03737 }
03738 if(st->codec->codec_type == AVMEDIA_TYPE_VIDEO){
03739 if(st->avg_frame_rate.den && st->avg_frame_rate.num)
03740 print_fps(av_q2d(st->avg_frame_rate), "fps");
03741 if(st->r_frame_rate.den && st->r_frame_rate.num)
03742 print_fps(av_q2d(st->r_frame_rate), "tbr");
03743 if(st->time_base.den && st->time_base.num)
03744 print_fps(1/av_q2d(st->time_base), "tbn");
03745 if(st->codec->time_base.den && st->codec->time_base.num)
03746 print_fps(1/av_q2d(st->codec->time_base), "tbc");
03747 }
03748 if (st->disposition & AV_DISPOSITION_DEFAULT)
03749 av_log(NULL, AV_LOG_INFO, " (default)");
03750 if (st->disposition & AV_DISPOSITION_DUB)
03751 av_log(NULL, AV_LOG_INFO, " (dub)");
03752 if (st->disposition & AV_DISPOSITION_ORIGINAL)
03753 av_log(NULL, AV_LOG_INFO, " (original)");
03754 if (st->disposition & AV_DISPOSITION_COMMENT)
03755 av_log(NULL, AV_LOG_INFO, " (comment)");
03756 if (st->disposition & AV_DISPOSITION_LYRICS)
03757 av_log(NULL, AV_LOG_INFO, " (lyrics)");
03758 if (st->disposition & AV_DISPOSITION_KARAOKE)
03759 av_log(NULL, AV_LOG_INFO, " (karaoke)");
03760 if (st->disposition & AV_DISPOSITION_FORCED)
03761 av_log(NULL, AV_LOG_INFO, " (forced)");
03762 if (st->disposition & AV_DISPOSITION_HEARING_IMPAIRED)
03763 av_log(NULL, AV_LOG_INFO, " (hearing impaired)");
03764 if (st->disposition & AV_DISPOSITION_VISUAL_IMPAIRED)
03765 av_log(NULL, AV_LOG_INFO, " (visual impaired)");
03766 if (st->disposition & AV_DISPOSITION_CLEAN_EFFECTS)
03767 av_log(NULL, AV_LOG_INFO, " (clean effects)");
03768 av_log(NULL, AV_LOG_INFO, "\n");
03769 dump_metadata(NULL, st->metadata, " ");
03770 }
03771
03772 void av_dump_format(AVFormatContext *ic,
03773 int index,
03774 const char *url,
03775 int is_output)
03776 {
03777 int i;
03778 uint8_t *printed = ic->nb_streams ? av_mallocz(ic->nb_streams) : NULL;
03779 if (ic->nb_streams && !printed)
03780 return;
03781
03782 av_log(NULL, AV_LOG_INFO, "%s #%d, %s, %s '%s':\n",
03783 is_output ? "Output" : "Input",
03784 index,
03785 is_output ? ic->oformat->name : ic->iformat->name,
03786 is_output ? "to" : "from", url);
03787 dump_metadata(NULL, ic->metadata, " ");
03788 if (!is_output) {
03789 av_log(NULL, AV_LOG_INFO, " Duration: ");
03790 if (ic->duration != AV_NOPTS_VALUE) {
03791 int hours, mins, secs, us;
03792 secs = ic->duration / AV_TIME_BASE;
03793 us = ic->duration % AV_TIME_BASE;
03794 mins = secs / 60;
03795 secs %= 60;
03796 hours = mins / 60;
03797 mins %= 60;
03798 av_log(NULL, AV_LOG_INFO, "%02d:%02d:%02d.%02d", hours, mins, secs,
03799 (100 * us) / AV_TIME_BASE);
03800 } else {
03801 av_log(NULL, AV_LOG_INFO, "N/A");
03802 }
03803 if (ic->start_time != AV_NOPTS_VALUE) {
03804 int secs, us;
03805 av_log(NULL, AV_LOG_INFO, ", start: ");
03806 secs = ic->start_time / AV_TIME_BASE;
03807 us = abs(ic->start_time % AV_TIME_BASE);
03808 av_log(NULL, AV_LOG_INFO, "%d.%06d",
03809 secs, (int)av_rescale(us, 1000000, AV_TIME_BASE));
03810 }
03811 av_log(NULL, AV_LOG_INFO, ", bitrate: ");
03812 if (ic->bit_rate) {
03813 av_log(NULL, AV_LOG_INFO,"%d kb/s", ic->bit_rate / 1000);
03814 } else {
03815 av_log(NULL, AV_LOG_INFO, "N/A");
03816 }
03817 av_log(NULL, AV_LOG_INFO, "\n");
03818 }
03819 for (i = 0; i < ic->nb_chapters; i++) {
03820 AVChapter *ch = ic->chapters[i];
03821 av_log(NULL, AV_LOG_INFO, " Chapter #%d.%d: ", index, i);
03822 av_log(NULL, AV_LOG_INFO, "start %f, ", ch->start * av_q2d(ch->time_base));
03823 av_log(NULL, AV_LOG_INFO, "end %f\n", ch->end * av_q2d(ch->time_base));
03824
03825 dump_metadata(NULL, ch->metadata, " ");
03826 }
03827 if(ic->nb_programs) {
03828 int j, k, total = 0;
03829 for(j=0; j<ic->nb_programs; j++) {
03830 AVDictionaryEntry *name = av_dict_get(ic->programs[j]->metadata,
03831 "name", NULL, 0);
03832 av_log(NULL, AV_LOG_INFO, " Program %d %s\n", ic->programs[j]->id,
03833 name ? name->value : "");
03834 dump_metadata(NULL, ic->programs[j]->metadata, " ");
03835 for(k=0; k<ic->programs[j]->nb_stream_indexes; k++) {
03836 dump_stream_format(ic, ic->programs[j]->stream_index[k], index, is_output);
03837 printed[ic->programs[j]->stream_index[k]] = 1;
03838 }
03839 total += ic->programs[j]->nb_stream_indexes;
03840 }
03841 if (total < ic->nb_streams)
03842 av_log(NULL, AV_LOG_INFO, " No Program\n");
03843 }
03844 for(i=0;i<ic->nb_streams;i++)
03845 if (!printed[i])
03846 dump_stream_format(ic, i, index, is_output);
03847
03848 av_free(printed);
03849 }
03850
03851 int64_t av_gettime(void)
03852 {
03853 struct timeval tv;
03854 gettimeofday(&tv,NULL);
03855 return (int64_t)tv.tv_sec * 1000000 + tv.tv_usec;
03856 }
03857
03858 uint64_t ff_ntp_time(void)
03859 {
03860 return (av_gettime() / 1000) * 1000 + NTP_OFFSET_US;
03861 }
03862
03863 int av_get_frame_filename(char *buf, int buf_size,
03864 const char *path, int number)
03865 {
03866 const char *p;
03867 char *q, buf1[20], c;
03868 int nd, len, percentd_found;
03869
03870 q = buf;
03871 p = path;
03872 percentd_found = 0;
03873 for(;;) {
03874 c = *p++;
03875 if (c == '\0')
03876 break;
03877 if (c == '%') {
03878 do {
03879 nd = 0;
03880 while (isdigit(*p)) {
03881 nd = nd * 10 + *p++ - '0';
03882 }
03883 c = *p++;
03884 } while (isdigit(c));
03885
03886 switch(c) {
03887 case '%':
03888 goto addchar;
03889 case 'd':
03890 if (percentd_found)
03891 goto fail;
03892 percentd_found = 1;
03893 snprintf(buf1, sizeof(buf1), "%0*d", nd, number);
03894 len = strlen(buf1);
03895 if ((q - buf + len) > buf_size - 1)
03896 goto fail;
03897 memcpy(q, buf1, len);
03898 q += len;
03899 break;
03900 default:
03901 goto fail;
03902 }
03903 } else {
03904 addchar:
03905 if ((q - buf) < buf_size - 1)
03906 *q++ = c;
03907 }
03908 }
03909 if (!percentd_found)
03910 goto fail;
03911 *q = '\0';
03912 return 0;
03913 fail:
03914 *q = '\0';
03915 return -1;
03916 }
03917
03918 static void hex_dump_internal(void *avcl, FILE *f, int level, uint8_t *buf, int size)
03919 {
03920 int len, i, j, c;
03921 #undef fprintf
03922 #define PRINT(...) do { if (!f) av_log(avcl, level, __VA_ARGS__); else fprintf(f, __VA_ARGS__); } while(0)
03923
03924 for(i=0;i<size;i+=16) {
03925 len = size - i;
03926 if (len > 16)
03927 len = 16;
03928 PRINT("%08x ", i);
03929 for(j=0;j<16;j++) {
03930 if (j < len)
03931 PRINT(" %02x", buf[i+j]);
03932 else
03933 PRINT(" ");
03934 }
03935 PRINT(" ");
03936 for(j=0;j<len;j++) {
03937 c = buf[i+j];
03938 if (c < ' ' || c > '~')
03939 c = '.';
03940 PRINT("%c", c);
03941 }
03942 PRINT("\n");
03943 }
03944 #undef PRINT
03945 }
03946
03947 void av_hex_dump(FILE *f, uint8_t *buf, int size)
03948 {
03949 hex_dump_internal(NULL, f, 0, buf, size);
03950 }
03951
03952 void av_hex_dump_log(void *avcl, int level, uint8_t *buf, int size)
03953 {
03954 hex_dump_internal(avcl, NULL, level, buf, size);
03955 }
03956
03957 static void pkt_dump_internal(void *avcl, FILE *f, int level, AVPacket *pkt, int dump_payload, AVRational time_base)
03958 {
03959 #undef fprintf
03960 #define PRINT(...) do { if (!f) av_log(avcl, level, __VA_ARGS__); else fprintf(f, __VA_ARGS__); } while(0)
03961 PRINT("stream #%d:\n", pkt->stream_index);
03962 PRINT(" keyframe=%d\n", ((pkt->flags & AV_PKT_FLAG_KEY) != 0));
03963 PRINT(" duration=%0.3f\n", pkt->duration * av_q2d(time_base));
03964
03965 PRINT(" dts=");
03966 if (pkt->dts == AV_NOPTS_VALUE)
03967 PRINT("N/A");
03968 else
03969 PRINT("%0.3f", pkt->dts * av_q2d(time_base));
03970
03971 PRINT(" pts=");
03972 if (pkt->pts == AV_NOPTS_VALUE)
03973 PRINT("N/A");
03974 else
03975 PRINT("%0.3f", pkt->pts * av_q2d(time_base));
03976 PRINT("\n");
03977 PRINT(" size=%d\n", pkt->size);
03978 #undef PRINT
03979 if (dump_payload)
03980 av_hex_dump(f, pkt->data, pkt->size);
03981 }
03982
03983 #if FF_API_PKT_DUMP
03984 void av_pkt_dump(FILE *f, AVPacket *pkt, int dump_payload)
03985 {
03986 AVRational tb = { 1, AV_TIME_BASE };
03987 pkt_dump_internal(NULL, f, 0, pkt, dump_payload, tb);
03988 }
03989 #endif
03990
03991 void av_pkt_dump2(FILE *f, AVPacket *pkt, int dump_payload, AVStream *st)
03992 {
03993 pkt_dump_internal(NULL, f, 0, pkt, dump_payload, st->time_base);
03994 }
03995
03996 #if FF_API_PKT_DUMP
03997 void av_pkt_dump_log(void *avcl, int level, AVPacket *pkt, int dump_payload)
03998 {
03999 AVRational tb = { 1, AV_TIME_BASE };
04000 pkt_dump_internal(avcl, NULL, level, pkt, dump_payload, tb);
04001 }
04002 #endif
04003
04004 void av_pkt_dump_log2(void *avcl, int level, AVPacket *pkt, int dump_payload,
04005 AVStream *st)
04006 {
04007 pkt_dump_internal(avcl, NULL, level, pkt, dump_payload, st->time_base);
04008 }
04009
04010 void av_url_split(char *proto, int proto_size,
04011 char *authorization, int authorization_size,
04012 char *hostname, int hostname_size,
04013 int *port_ptr,
04014 char *path, int path_size,
04015 const char *url)
04016 {
04017 const char *p, *ls, *at, *col, *brk;
04018
04019 if (port_ptr) *port_ptr = -1;
04020 if (proto_size > 0) proto[0] = 0;
04021 if (authorization_size > 0) authorization[0] = 0;
04022 if (hostname_size > 0) hostname[0] = 0;
04023 if (path_size > 0) path[0] = 0;
04024
04025
04026 if ((p = strchr(url, ':'))) {
04027 av_strlcpy(proto, url, FFMIN(proto_size, p + 1 - url));
04028 p++;
04029 if (*p == '/') p++;
04030 if (*p == '/') p++;
04031 } else {
04032
04033 av_strlcpy(path, url, path_size);
04034 return;
04035 }
04036
04037
04038 ls = strchr(p, '/');
04039 if(!ls)
04040 ls = strchr(p, '?');
04041 if(ls)
04042 av_strlcpy(path, ls, path_size);
04043 else
04044 ls = &p[strlen(p)];
04045
04046
04047 if (ls != p) {
04048
04049 if ((at = strchr(p, '@')) && at < ls) {
04050 av_strlcpy(authorization, p,
04051 FFMIN(authorization_size, at + 1 - p));
04052 p = at + 1;
04053 }
04054
04055 if (*p == '[' && (brk = strchr(p, ']')) && brk < ls) {
04056
04057 av_strlcpy(hostname, p + 1,
04058 FFMIN(hostname_size, brk - p));
04059 if (brk[1] == ':' && port_ptr)
04060 *port_ptr = atoi(brk + 2);
04061 } else if ((col = strchr(p, ':')) && col < ls) {
04062 av_strlcpy(hostname, p,
04063 FFMIN(col + 1 - p, hostname_size));
04064 if (port_ptr) *port_ptr = atoi(col + 1);
04065 } else
04066 av_strlcpy(hostname, p,
04067 FFMIN(ls + 1 - p, hostname_size));
04068 }
04069 }
04070
04071 char *ff_data_to_hex(char *buff, const uint8_t *src, int s, int lowercase)
04072 {
04073 int i;
04074 static const char hex_table_uc[16] = { '0', '1', '2', '3',
04075 '4', '5', '6', '7',
04076 '8', '9', 'A', 'B',
04077 'C', 'D', 'E', 'F' };
04078 static const char hex_table_lc[16] = { '0', '1', '2', '3',
04079 '4', '5', '6', '7',
04080 '8', '9', 'a', 'b',
04081 'c', 'd', 'e', 'f' };
04082 const char *hex_table = lowercase ? hex_table_lc : hex_table_uc;
04083
04084 for(i = 0; i < s; i++) {
04085 buff[i * 2] = hex_table[src[i] >> 4];
04086 buff[i * 2 + 1] = hex_table[src[i] & 0xF];
04087 }
04088
04089 return buff;
04090 }
04091
04092 int ff_hex_to_data(uint8_t *data, const char *p)
04093 {
04094 int c, len, v;
04095
04096 len = 0;
04097 v = 1;
04098 for (;;) {
04099 p += strspn(p, SPACE_CHARS);
04100 if (*p == '\0')
04101 break;
04102 c = toupper((unsigned char) *p++);
04103 if (c >= '0' && c <= '9')
04104 c = c - '0';
04105 else if (c >= 'A' && c <= 'F')
04106 c = c - 'A' + 10;
04107 else
04108 break;
04109 v = (v << 4) | c;
04110 if (v & 0x100) {
04111 if (data)
04112 data[len] = v;
04113 len++;
04114 v = 1;
04115 }
04116 }
04117 return len;
04118 }
04119
04120 #if FF_API_SET_PTS_INFO
04121 void av_set_pts_info(AVStream *s, int pts_wrap_bits,
04122 unsigned int pts_num, unsigned int pts_den)
04123 {
04124 avpriv_set_pts_info(s, pts_wrap_bits, pts_num, pts_den);
04125 }
04126 #endif
04127
04128 void avpriv_set_pts_info(AVStream *s, int pts_wrap_bits,
04129 unsigned int pts_num, unsigned int pts_den)
04130 {
04131 AVRational new_tb;
04132 if(av_reduce(&new_tb.num, &new_tb.den, pts_num, pts_den, INT_MAX)){
04133 if(new_tb.num != pts_num)
04134 av_log(NULL, AV_LOG_DEBUG, "st:%d removing common factor %d from timebase\n", s->index, pts_num/new_tb.num);
04135 }else
04136 av_log(NULL, AV_LOG_WARNING, "st:%d has too large timebase, reducing\n", s->index);
04137
04138 if(new_tb.num <= 0 || new_tb.den <= 0) {
04139 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);
04140 return;
04141 }
04142 s->time_base = new_tb;
04143 s->pts_wrap_bits = pts_wrap_bits;
04144 }
04145
04146 int ff_url_join(char *str, int size, const char *proto,
04147 const char *authorization, const char *hostname,
04148 int port, const char *fmt, ...)
04149 {
04150 #if CONFIG_NETWORK
04151 struct addrinfo hints = { 0 }, *ai;
04152 #endif
04153
04154 str[0] = '\0';
04155 if (proto)
04156 av_strlcatf(str, size, "%s://", proto);
04157 if (authorization && authorization[0])
04158 av_strlcatf(str, size, "%s@", authorization);
04159 #if CONFIG_NETWORK && defined(AF_INET6)
04160
04161
04162 hints.ai_flags = AI_NUMERICHOST;
04163 if (!getaddrinfo(hostname, NULL, &hints, &ai)) {
04164 if (ai->ai_family == AF_INET6) {
04165 av_strlcat(str, "[", size);
04166 av_strlcat(str, hostname, size);
04167 av_strlcat(str, "]", size);
04168 } else {
04169 av_strlcat(str, hostname, size);
04170 }
04171 freeaddrinfo(ai);
04172 } else
04173 #endif
04174
04175 av_strlcat(str, hostname, size);
04176
04177 if (port >= 0)
04178 av_strlcatf(str, size, ":%d", port);
04179 if (fmt) {
04180 va_list vl;
04181 int len = strlen(str);
04182
04183 va_start(vl, fmt);
04184 vsnprintf(str + len, size > len ? size - len : 0, fmt, vl);
04185 va_end(vl);
04186 }
04187 return strlen(str);
04188 }
04189
04190 int ff_write_chained(AVFormatContext *dst, int dst_stream, AVPacket *pkt,
04191 AVFormatContext *src)
04192 {
04193 AVPacket local_pkt;
04194
04195 local_pkt = *pkt;
04196 local_pkt.stream_index = dst_stream;
04197 if (pkt->pts != AV_NOPTS_VALUE)
04198 local_pkt.pts = av_rescale_q(pkt->pts,
04199 src->streams[pkt->stream_index]->time_base,
04200 dst->streams[dst_stream]->time_base);
04201 if (pkt->dts != AV_NOPTS_VALUE)
04202 local_pkt.dts = av_rescale_q(pkt->dts,
04203 src->streams[pkt->stream_index]->time_base,
04204 dst->streams[dst_stream]->time_base);
04205 return av_write_frame(dst, &local_pkt);
04206 }
04207
04208 void ff_parse_key_value(const char *str, ff_parse_key_val_cb callback_get_buf,
04209 void *context)
04210 {
04211 const char *ptr = str;
04212
04213
04214 for (;;) {
04215 const char *key;
04216 char *dest = NULL, *dest_end;
04217 int key_len, dest_len = 0;
04218
04219
04220 while (*ptr && (isspace(*ptr) || *ptr == ','))
04221 ptr++;
04222 if (!*ptr)
04223 break;
04224
04225 key = ptr;
04226
04227 if (!(ptr = strchr(key, '=')))
04228 break;
04229 ptr++;
04230 key_len = ptr - key;
04231
04232 callback_get_buf(context, key, key_len, &dest, &dest_len);
04233 dest_end = dest + dest_len - 1;
04234
04235 if (*ptr == '\"') {
04236 ptr++;
04237 while (*ptr && *ptr != '\"') {
04238 if (*ptr == '\\') {
04239 if (!ptr[1])
04240 break;
04241 if (dest && dest < dest_end)
04242 *dest++ = ptr[1];
04243 ptr += 2;
04244 } else {
04245 if (dest && dest < dest_end)
04246 *dest++ = *ptr;
04247 ptr++;
04248 }
04249 }
04250 if (*ptr == '\"')
04251 ptr++;
04252 } else {
04253 for (; *ptr && !(isspace(*ptr) || *ptr == ','); ptr++)
04254 if (dest && dest < dest_end)
04255 *dest++ = *ptr;
04256 }
04257 if (dest)
04258 *dest = 0;
04259 }
04260 }
04261
04262 int ff_find_stream_index(AVFormatContext *s, int id)
04263 {
04264 int i;
04265 for (i = 0; i < s->nb_streams; i++) {
04266 if (s->streams[i]->id == id)
04267 return i;
04268 }
04269 return -1;
04270 }
04271
04272 void ff_make_absolute_url(char *buf, int size, const char *base,
04273 const char *rel)
04274 {
04275 char *sep;
04276
04277 if (base && strstr(base, "://") && rel[0] == '/') {
04278 if (base != buf)
04279 av_strlcpy(buf, base, size);
04280 sep = strstr(buf, "://");
04281 if (sep) {
04282 sep += 3;
04283 sep = strchr(sep, '/');
04284 if (sep)
04285 *sep = '\0';
04286 }
04287 av_strlcat(buf, rel, size);
04288 return;
04289 }
04290
04291 if (!base || strstr(rel, "://") || rel[0] == '/') {
04292 av_strlcpy(buf, rel, size);
04293 return;
04294 }
04295 if (base != buf)
04296 av_strlcpy(buf, base, size);
04297
04298 sep = strrchr(buf, '/');
04299 if (sep)
04300 sep[1] = '\0';
04301 else
04302 buf[0] = '\0';
04303 while (av_strstart(rel, "../", NULL) && sep) {
04304
04305 sep[0] = '\0';
04306 sep = strrchr(buf, '/');
04307
04308 if (!strcmp(sep ? &sep[1] : buf, "..")) {
04309
04310 av_strlcat(buf, "/", size);
04311 break;
04312 }
04313
04314 if (sep)
04315 sep[1] = '\0';
04316 else
04317 buf[0] = '\0';
04318 rel += 3;
04319 }
04320 av_strlcat(buf, rel, size);
04321 }
04322
04323 int64_t ff_iso8601_to_unix_time(const char *datestr)
04324 {
04325 #if HAVE_STRPTIME
04326 struct tm time1 = {0}, time2 = {0};
04327 char *ret1, *ret2;
04328 ret1 = strptime(datestr, "%Y - %m - %d %T", &time1);
04329 ret2 = strptime(datestr, "%Y - %m - %dT%T", &time2);
04330 if (ret2 && !ret1)
04331 return av_timegm(&time2);
04332 else
04333 return av_timegm(&time1);
04334 #else
04335 av_log(NULL, AV_LOG_WARNING, "strptime() unavailable on this system, cannot convert "
04336 "the date string.\n");
04337 return 0;
04338 #endif
04339 }
04340
04341 int avformat_query_codec(AVOutputFormat *ofmt, enum CodecID codec_id, int std_compliance)
04342 {
04343 if (ofmt) {
04344 if (ofmt->query_codec)
04345 return ofmt->query_codec(codec_id, std_compliance);
04346 else if (ofmt->codec_tag)
04347 return !!av_codec_get_tag(ofmt->codec_tag, codec_id);
04348 else if (codec_id == ofmt->video_codec || codec_id == ofmt->audio_codec ||
04349 codec_id == ofmt->subtitle_codec)
04350 return 1;
04351 }
04352 return AVERROR_PATCHWELCOME;
04353 }
04354
04355 int avformat_network_init(void)
04356 {
04357 #if CONFIG_NETWORK
04358 int ret;
04359 ff_network_inited_globally = 1;
04360 if ((ret = ff_network_init()) < 0)
04361 return ret;
04362 ff_tls_init();
04363 #endif
04364 return 0;
04365 }
04366
04367 int avformat_network_deinit(void)
04368 {
04369 #if CONFIG_NETWORK
04370 ff_network_close();
04371 ff_tls_deinit();
04372 #endif
04373 return 0;
04374 }
04375
04376 int ff_add_param_change(AVPacket *pkt, int32_t channels,
04377 uint64_t channel_layout, int32_t sample_rate,
04378 int32_t width, int32_t height)
04379 {
04380 uint32_t flags = 0;
04381 int size = 4;
04382 uint8_t *data;
04383 if (!pkt)
04384 return AVERROR(EINVAL);
04385 if (channels) {
04386 size += 4;
04387 flags |= AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_COUNT;
04388 }
04389 if (channel_layout) {
04390 size += 8;
04391 flags |= AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_LAYOUT;
04392 }
04393 if (sample_rate) {
04394 size += 4;
04395 flags |= AV_SIDE_DATA_PARAM_CHANGE_SAMPLE_RATE;
04396 }
04397 if (width || height) {
04398 size += 8;
04399 flags |= AV_SIDE_DATA_PARAM_CHANGE_DIMENSIONS;
04400 }
04401 data = av_packet_new_side_data(pkt, AV_PKT_DATA_PARAM_CHANGE, size);
04402 if (!data)
04403 return AVERROR(ENOMEM);
04404 bytestream_put_le32(&data, flags);
04405 if (channels)
04406 bytestream_put_le32(&data, channels);
04407 if (channel_layout)
04408 bytestream_put_le64(&data, channel_layout);
04409 if (sample_rate)
04410 bytestream_put_le32(&data, sample_rate);
04411 if (width || height) {
04412 bytestream_put_le32(&data, width);
04413 bytestream_put_le32(&data, height);
04414 }
04415 return 0;
04416 }
04417
04418 const struct AVCodecTag *avformat_get_riff_video_tags(void)
04419 {
04420 return ff_codec_bmp_tags;
04421 }
04422 const struct AVCodecTag *avformat_get_riff_audio_tags(void)
04423 {
04424 return ff_codec_wav_tags;
04425 }
04426
04427 AVRational av_guess_sample_aspect_ratio(AVFormatContext *format, AVStream *stream, AVFrame *frame)
04428 {
04429 AVRational undef = {0, 1};
04430 AVRational stream_sample_aspect_ratio = stream ? stream->sample_aspect_ratio : undef;
04431 AVRational codec_sample_aspect_ratio = stream && stream->codec ? stream->codec->sample_aspect_ratio : undef;
04432 AVRational frame_sample_aspect_ratio = frame ? frame->sample_aspect_ratio : codec_sample_aspect_ratio;
04433
04434 av_reduce(&stream_sample_aspect_ratio.num, &stream_sample_aspect_ratio.den,
04435 stream_sample_aspect_ratio.num, stream_sample_aspect_ratio.den, INT_MAX);
04436 if (stream_sample_aspect_ratio.num <= 0 || stream_sample_aspect_ratio.den <= 0)
04437 stream_sample_aspect_ratio = undef;
04438
04439 av_reduce(&frame_sample_aspect_ratio.num, &frame_sample_aspect_ratio.den,
04440 frame_sample_aspect_ratio.num, frame_sample_aspect_ratio.den, INT_MAX);
04441 if (frame_sample_aspect_ratio.num <= 0 || frame_sample_aspect_ratio.den <= 0)
04442 frame_sample_aspect_ratio = undef;
04443
04444 if (stream_sample_aspect_ratio.num)
04445 return stream_sample_aspect_ratio;
04446 else
04447 return frame_sample_aspect_ratio;
04448 }