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