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