1/* 2 * various utility functions for use within FFmpeg 3 * Copyright (c) 2000, 2001, 2002 Fabrice Bellard 4 * 5 * This file is part of FFmpeg. 6 * 7 * FFmpeg is free software; you can redistribute it and/or 8 * modify it under the terms of the GNU Lesser General Public 9 * License as published by the Free Software Foundation; either 10 * version 2.1 of the License, or (at your option) any later version. 11 * 12 * FFmpeg is distributed in the hope that it will be useful, 13 * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 15 * Lesser General Public License for more details. 16 * 17 * You should have received a copy of the GNU Lesser General Public 18 * License along with FFmpeg; if not, write to the Free Software 19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 20 */ 21#include "avformat.h" 22#include "internal.h" 23#include "libavcodec/opt.h" 24#include "metadata.h" 25#include "libavutil/avstring.h" 26#include "riff.h" 27#include "audiointerleave.h" 28#include <sys/time.h> 29#include <time.h> 30#include <strings.h> 31#include <stdarg.h> 32#if CONFIG_NETWORK 33#include "network.h" 34#endif 35 36#undef NDEBUG 37#include <assert.h> 38 39/** 40 * @file 41 * various utility functions for use within FFmpeg 42 */ 43 44unsigned avformat_version(void) 45{ 46 return LIBAVFORMAT_VERSION_INT; 47} 48 49const char *avformat_configuration(void) 50{ 51 return FFMPEG_CONFIGURATION; 52} 53 54const char *avformat_license(void) 55{ 56#define LICENSE_PREFIX "libavformat license: " 57 return LICENSE_PREFIX FFMPEG_LICENSE + sizeof(LICENSE_PREFIX) - 1; 58} 59 60/* fraction handling */ 61 62/** 63 * f = val + (num / den) + 0.5. 64 * 65 * 'num' is normalized so that it is such as 0 <= num < den. 66 * 67 * @param f fractional number 68 * @param val integer value 69 * @param num must be >= 0 70 * @param den must be >= 1 71 */ 72static void av_frac_init(AVFrac *f, int64_t val, int64_t num, int64_t den) 73{ 74 num += (den >> 1); 75 if (num >= den) { 76 val += num / den; 77 num = num % den; 78 } 79 f->val = val; 80 f->num = num; 81 f->den = den; 82} 83 84/** 85 * Fractional addition to f: f = f + (incr / f->den). 86 * 87 * @param f fractional number 88 * @param incr increment, can be positive or negative 89 */ 90static void av_frac_add(AVFrac *f, int64_t incr) 91{ 92 int64_t num, den; 93 94 num = f->num + incr; 95 den = f->den; 96 if (num < 0) { 97 f->val += num / den; 98 num = num % den; 99 if (num < 0) { 100 num += den; 101 f->val--; 102 } 103 } else if (num >= den) { 104 f->val += num / den; 105 num = num % den; 106 } 107 f->num = num; 108} 109 110/** head of registered input format linked list */ 111AVInputFormat *first_iformat = NULL; 112/** head of registered output format linked list */ 113AVOutputFormat *first_oformat = NULL; 114 115AVInputFormat *av_iformat_next(AVInputFormat *f) 116{ 117 if(f) return f->next; 118 else return first_iformat; 119} 120 121AVOutputFormat *av_oformat_next(AVOutputFormat *f) 122{ 123 if(f) return f->next; 124 else return first_oformat; 125} 126 127void av_register_input_format(AVInputFormat *format) 128{ 129 AVInputFormat **p; 130 p = &first_iformat; 131 while (*p != NULL) p = &(*p)->next; 132 *p = format; 133 format->next = NULL; 134} 135 136void av_register_output_format(AVOutputFormat *format) 137{ 138 AVOutputFormat **p; 139 p = &first_oformat; 140 while (*p != NULL) p = &(*p)->next; 141 *p = format; 142 format->next = NULL; 143} 144 145int av_match_ext(const char *filename, const char *extensions) 146{ 147 const char *ext, *p; 148 char ext1[32], *q; 149 150 if(!filename) 151 return 0; 152 153 ext = strrchr(filename, '.'); 154 if (ext) { 155 ext++; 156 p = extensions; 157 for(;;) { 158 q = ext1; 159 while (*p != '\0' && *p != ',' && q-ext1<sizeof(ext1)-1) 160 *q++ = *p++; 161 *q = '\0'; 162 if (!strcasecmp(ext1, ext)) 163 return 1; 164 if (*p == '\0') 165 break; 166 p++; 167 } 168 } 169 return 0; 170} 171 172static int match_format(const char *name, const char *names) 173{ 174 const char *p; 175 int len, namelen; 176 177 if (!name || !names) 178 return 0; 179 180 namelen = strlen(name); 181 while ((p = strchr(names, ','))) { 182 len = FFMAX(p - names, namelen); 183 if (!strncasecmp(name, names, len)) 184 return 1; 185 names = p+1; 186 } 187 return !strcasecmp(name, names); 188} 189 190#if LIBAVFORMAT_VERSION_MAJOR < 53 191AVOutputFormat *guess_format(const char *short_name, const char *filename, 192 const char *mime_type) 193{ 194 return av_guess_format(short_name, filename, mime_type); 195} 196#endif 197 198AVOutputFormat *av_guess_format(const char *short_name, const char *filename, 199 const char *mime_type) 200{ 201 AVOutputFormat *fmt, *fmt_found; 202 int score_max, score; 203 204 /* specific test for image sequences */ 205#if CONFIG_IMAGE2_MUXER 206 if (!short_name && filename && 207 av_filename_number_test(filename) && 208 av_guess_image2_codec(filename) != CODEC_ID_NONE) { 209 return av_guess_format("image2", NULL, NULL); 210 } 211#endif 212 /* Find the proper file type. */ 213 fmt_found = NULL; 214 score_max = 0; 215 fmt = first_oformat; 216 while (fmt != NULL) { 217 score = 0; 218 if (fmt->name && short_name && !strcmp(fmt->name, short_name)) 219 score += 100; 220 if (fmt->mime_type && mime_type && !strcmp(fmt->mime_type, mime_type)) 221 score += 10; 222 if (filename && fmt->extensions && 223 av_match_ext(filename, fmt->extensions)) { 224 score += 5; 225 } 226 if (score > score_max) { 227 score_max = score; 228 fmt_found = fmt; 229 } 230 fmt = fmt->next; 231 } 232 return fmt_found; 233} 234 235#if LIBAVFORMAT_VERSION_MAJOR < 53 236AVOutputFormat *guess_stream_format(const char *short_name, const char *filename, 237 const char *mime_type) 238{ 239 AVOutputFormat *fmt = av_guess_format(short_name, filename, mime_type); 240 241 if (fmt) { 242 AVOutputFormat *stream_fmt; 243 char stream_format_name[64]; 244 245 snprintf(stream_format_name, sizeof(stream_format_name), "%s_stream", fmt->name); 246 stream_fmt = av_guess_format(stream_format_name, NULL, NULL); 247 248 if (stream_fmt) 249 fmt = stream_fmt; 250 } 251 252 return fmt; 253} 254#endif 255 256enum CodecID av_guess_codec(AVOutputFormat *fmt, const char *short_name, 257 const char *filename, const char *mime_type, enum AVMediaType type){ 258 if(type == AVMEDIA_TYPE_VIDEO){ 259 enum CodecID codec_id= CODEC_ID_NONE; 260 261#if CONFIG_IMAGE2_MUXER 262 if(!strcmp(fmt->name, "image2") || !strcmp(fmt->name, "image2pipe")){ 263 codec_id= av_guess_image2_codec(filename); 264 } 265#endif 266 if(codec_id == CODEC_ID_NONE) 267 codec_id= fmt->video_codec; 268 return codec_id; 269 }else if(type == AVMEDIA_TYPE_AUDIO) 270 return fmt->audio_codec; 271 else 272 return CODEC_ID_NONE; 273} 274 275AVInputFormat *av_find_input_format(const char *short_name) 276{ 277 AVInputFormat *fmt; 278 for(fmt = first_iformat; fmt != NULL; fmt = fmt->next) { 279 if (match_format(short_name, fmt->name)) 280 return fmt; 281 } 282 return NULL; 283} 284 285#if LIBAVFORMAT_VERSION_MAJOR < 53 && CONFIG_SHARED && HAVE_SYMVER 286FF_SYMVER(void, av_destruct_packet_nofree, (AVPacket *pkt), "LIBAVFORMAT_52") 287{ 288 av_destruct_packet_nofree(pkt); 289} 290 291FF_SYMVER(void, av_destruct_packet, (AVPacket *pkt), "LIBAVFORMAT_52") 292{ 293 av_destruct_packet(pkt); 294} 295 296FF_SYMVER(int, av_new_packet, (AVPacket *pkt, int size), "LIBAVFORMAT_52") 297{ 298 return av_new_packet(pkt, size); 299} 300 301FF_SYMVER(int, av_dup_packet, (AVPacket *pkt), "LIBAVFORMAT_52") 302{ 303 return av_dup_packet(pkt); 304} 305 306FF_SYMVER(void, av_free_packet, (AVPacket *pkt), "LIBAVFORMAT_52") 307{ 308 av_free_packet(pkt); 309} 310 311FF_SYMVER(void, av_init_packet, (AVPacket *pkt), "LIBAVFORMAT_52") 312{ 313 av_log(NULL, AV_LOG_WARNING, "Diverting av_*_packet function calls to libavcodec. Recompile to improve performance\n"); 314 av_init_packet(pkt); 315} 316#endif 317 318int av_get_packet(ByteIOContext *s, AVPacket *pkt, int size) 319{ 320 int ret= av_new_packet(pkt, size); 321 322 if(ret<0) 323 return ret; 324 325 pkt->pos= url_ftell(s); 326 327 ret= get_buffer(s, pkt->data, size); 328 if(ret<=0) 329 av_free_packet(pkt); 330 else 331 av_shrink_packet(pkt, ret); 332 333 return ret; 334} 335 336 337int av_filename_number_test(const char *filename) 338{ 339 char buf[1024]; 340 return filename && (av_get_frame_filename(buf, sizeof(buf), filename, 1)>=0); 341} 342 343AVInputFormat *av_probe_input_format2(AVProbeData *pd, int is_opened, int *score_max) 344{ 345 AVInputFormat *fmt1, *fmt; 346 int score; 347 348 fmt = NULL; 349 for(fmt1 = first_iformat; fmt1 != NULL; fmt1 = fmt1->next) { 350 if (!is_opened == !(fmt1->flags & AVFMT_NOFILE)) 351 continue; 352 score = 0; 353 if (fmt1->read_probe) { 354 score = fmt1->read_probe(pd); 355 } else if (fmt1->extensions) { 356 if (av_match_ext(pd->filename, fmt1->extensions)) { 357 score = 50; 358 } 359 } 360 if (score > *score_max) { 361 *score_max = score; 362 fmt = fmt1; 363 }else if (score == *score_max) 364 fmt = NULL; 365 } 366 return fmt; 367} 368 369AVInputFormat *av_probe_input_format(AVProbeData *pd, int is_opened){ 370 int score=0; 371 return av_probe_input_format2(pd, is_opened, &score); 372} 373 374static int set_codec_from_probe_data(AVFormatContext *s, AVStream *st, AVProbeData *pd, int score) 375{ 376 AVInputFormat *fmt; 377 fmt = av_probe_input_format2(pd, 1, &score); 378 379 if (fmt) { 380 av_log(s, AV_LOG_DEBUG, "Probe with size=%d, packets=%d detected %s with score=%d\n", 381 pd->buf_size, MAX_PROBE_PACKETS - st->probe_packets, fmt->name, score); 382 if (!strcmp(fmt->name, "mp3")) { 383 st->codec->codec_id = CODEC_ID_MP3; 384 st->codec->codec_type = AVMEDIA_TYPE_AUDIO; 385 } else if (!strcmp(fmt->name, "ac3")) { 386 st->codec->codec_id = CODEC_ID_AC3; 387 st->codec->codec_type = AVMEDIA_TYPE_AUDIO; 388 } else if (!strcmp(fmt->name, "eac3")) { 389 st->codec->codec_id = CODEC_ID_EAC3; 390 st->codec->codec_type = AVMEDIA_TYPE_AUDIO; 391 } else if (!strcmp(fmt->name, "mpegvideo")) { 392 st->codec->codec_id = CODEC_ID_MPEG2VIDEO; 393 st->codec->codec_type = AVMEDIA_TYPE_VIDEO; 394 } else if (!strcmp(fmt->name, "m4v")) { 395 st->codec->codec_id = CODEC_ID_MPEG4; 396 st->codec->codec_type = AVMEDIA_TYPE_VIDEO; 397 } else if (!strcmp(fmt->name, "h264")) { 398 st->codec->codec_id = CODEC_ID_H264; 399 st->codec->codec_type = AVMEDIA_TYPE_VIDEO; 400 } else if (!strcmp(fmt->name, "dts")) { 401 st->codec->codec_id = CODEC_ID_DTS; 402 st->codec->codec_type = AVMEDIA_TYPE_AUDIO; 403 } else if (!strcmp(fmt->name, "aac")) { 404 st->codec->codec_id = CODEC_ID_AAC; 405 st->codec->codec_type = AVMEDIA_TYPE_AUDIO; 406 } 407 } 408 return !!fmt; 409} 410 411/************************************************************/ 412/* input media file */ 413 414/** 415 * Open a media file from an IO stream. 'fmt' must be specified. 416 */ 417int av_open_input_stream(AVFormatContext **ic_ptr, 418 ByteIOContext *pb, const char *filename, 419 AVInputFormat *fmt, AVFormatParameters *ap) 420{ 421 int err; 422 AVFormatContext *ic; 423 AVFormatParameters default_ap; 424 425 if(!ap){ 426 ap=&default_ap; 427 memset(ap, 0, sizeof(default_ap)); 428 } 429 430 if(!ap->prealloced_context) 431 ic = avformat_alloc_context(); 432 else 433 ic = *ic_ptr; 434 if (!ic) { 435 err = AVERROR(ENOMEM); 436 goto fail; 437 } 438 ic->iformat = fmt; 439 ic->pb = pb; 440 ic->duration = AV_NOPTS_VALUE; 441 ic->start_time = AV_NOPTS_VALUE; 442 av_strlcpy(ic->filename, filename, sizeof(ic->filename)); 443 444 /* allocate private data */ 445 if (fmt->priv_data_size > 0) { 446 ic->priv_data = av_mallocz(fmt->priv_data_size); 447 if (!ic->priv_data) { 448 err = AVERROR(ENOMEM); 449 goto fail; 450 } 451 } else { 452 ic->priv_data = NULL; 453 } 454 455 if (ic->iformat->read_header) { 456 err = ic->iformat->read_header(ic, ap); 457 if (err < 0) 458 goto fail; 459 } 460 461 if (pb && !ic->data_offset) 462 ic->data_offset = url_ftell(ic->pb); 463 464#if LIBAVFORMAT_VERSION_MAJOR < 53 465 ff_metadata_demux_compat(ic); 466#endif 467 468 ic->raw_packet_buffer_remaining_size = RAW_PACKET_BUFFER_SIZE; 469 470 *ic_ptr = ic; 471 return 0; 472 fail: 473 if (ic) { 474 int i; 475 av_freep(&ic->priv_data); 476 for(i=0;i<ic->nb_streams;i++) { 477 AVStream *st = ic->streams[i]; 478 if (st) { 479 av_free(st->priv_data); 480 av_free(st->codec->extradata); 481 } 482 av_free(st); 483 } 484 } 485 av_free(ic); 486 *ic_ptr = NULL; 487 return err; 488} 489 490/** size of probe buffer, for guessing file type from file contents */ 491#define PROBE_BUF_MIN 2048 492#define PROBE_BUF_MAX (1<<20) 493 494int ff_probe_input_buffer(ByteIOContext **pb, AVInputFormat **fmt, 495 const char *filename, void *logctx, 496 unsigned int offset, unsigned int max_probe_size) 497{ 498 AVProbeData pd = { filename ? filename : "", NULL, -offset }; 499 unsigned char *buf = NULL; 500 int ret = 0, probe_size; 501 502 if (!max_probe_size) { 503 max_probe_size = PROBE_BUF_MAX; 504 } else if (max_probe_size > PROBE_BUF_MAX) { 505 max_probe_size = PROBE_BUF_MAX; 506 } else if (max_probe_size < PROBE_BUF_MIN) { 507 return AVERROR(EINVAL); 508 } 509 510 if (offset >= max_probe_size) { 511 return AVERROR(EINVAL); 512 } 513 514 for(probe_size= PROBE_BUF_MIN; probe_size<=max_probe_size && !*fmt && ret >= 0; 515 probe_size = FFMIN(probe_size<<1, FFMAX(max_probe_size, probe_size+1))) { 516 int ret, score = probe_size < max_probe_size ? AVPROBE_SCORE_MAX/4 : 0; 517 int buf_offset = (probe_size == PROBE_BUF_MIN) ? 0 : probe_size>>1; 518 519 if (probe_size < offset) { 520 continue; 521 } 522 523 /* read probe data */ 524 buf = av_realloc(buf, probe_size + AVPROBE_PADDING_SIZE); 525 if ((ret = get_buffer(*pb, buf + buf_offset, probe_size - buf_offset)) < 0) { 526 /* fail if error was not end of file, otherwise, lower score */ 527 if (ret != AVERROR_EOF) { 528 av_free(buf); 529 return ret; 530 } 531 score = 0; 532 ret = 0; /* error was end of file, nothing read */ 533 } 534 pd.buf_size += ret; 535 pd.buf = &buf[offset]; 536 537 memset(pd.buf + pd.buf_size, 0, AVPROBE_PADDING_SIZE); 538 539 /* guess file format */ 540 *fmt = av_probe_input_format2(&pd, 1, &score); 541 if(*fmt){ 542 if(score <= AVPROBE_SCORE_MAX/4){ //this can only be true in the last iteration 543 av_log(logctx, AV_LOG_WARNING, "Format detected only with low score of %d, misdetection possible!\n", score); 544 }else 545 av_log(logctx, AV_LOG_DEBUG, "Probed with size=%d and score=%d\n", probe_size, score); 546 } 547 } 548 549 if (!*fmt) { 550 av_free(buf); 551 return AVERROR_INVALIDDATA; 552 } 553 554 /* rewind. reuse probe buffer to avoid seeking */ 555 if ((ret = ff_rewind_with_probe_data(*pb, buf, pd.buf_size)) < 0) 556 av_free(buf); 557 558 return ret; 559} 560 561int av_open_input_file(AVFormatContext **ic_ptr, const char *filename, 562 AVInputFormat *fmt, 563 int buf_size, 564 AVFormatParameters *ap) 565{ 566 int err; 567 AVProbeData probe_data, *pd = &probe_data; 568 ByteIOContext *pb = NULL; 569 void *logctx= ap && ap->prealloced_context ? *ic_ptr : NULL; 570 571 pd->filename = ""; 572 if (filename) 573 pd->filename = filename; 574 pd->buf = NULL; 575 pd->buf_size = 0; 576 577 if (!fmt) { 578 /* guess format if no file can be opened */ 579 fmt = av_probe_input_format(pd, 0); 580 } 581 582 /* Do not open file if the format does not need it. XXX: specific 583 hack needed to handle RTSP/TCP */ 584 if (!fmt || !(fmt->flags & AVFMT_NOFILE)) { 585 /* if no file needed do not try to open one */ 586 if ((err=url_fopen(&pb, filename, URL_RDONLY)) < 0) { 587 goto fail; 588 } 589 if (buf_size > 0) { 590 url_setbufsize(pb, buf_size); 591 } 592 if (!fmt && (err = ff_probe_input_buffer(&pb, &fmt, filename, logctx, 0, logctx ? (*ic_ptr)->probesize : 0)) < 0) { 593 goto fail; 594 } 595 } 596 597 /* if still no format found, error */ 598 if (!fmt) { 599 err = AVERROR_INVALIDDATA; 600 goto fail; 601 } 602 603 /* check filename in case an image number is expected */ 604 if (fmt->flags & AVFMT_NEEDNUMBER) { 605 if (!av_filename_number_test(filename)) { 606 err = AVERROR_NUMEXPECTED; 607 goto fail; 608 } 609 } 610 err = av_open_input_stream(ic_ptr, pb, filename, fmt, ap); 611 if (err) 612 goto fail; 613 return 0; 614 fail: 615 av_freep(&pd->buf); 616 if (pb) 617 url_fclose(pb); 618 if (ap && ap->prealloced_context) 619 av_free(*ic_ptr); 620 *ic_ptr = NULL; 621 return err; 622 623} 624 625/*******************************************************/ 626 627static AVPacket *add_to_pktbuf(AVPacketList **packet_buffer, AVPacket *pkt, 628 AVPacketList **plast_pktl){ 629 AVPacketList *pktl = av_mallocz(sizeof(AVPacketList)); 630 if (!pktl) 631 return NULL; 632 633 if (*packet_buffer) 634 (*plast_pktl)->next = pktl; 635 else 636 *packet_buffer = pktl; 637 638 /* add the packet in the buffered packet list */ 639 *plast_pktl = pktl; 640 pktl->pkt= *pkt; 641 return &pktl->pkt; 642} 643 644int av_read_packet(AVFormatContext *s, AVPacket *pkt) 645{ 646 int ret, i; 647 AVStream *st; 648 649 for(;;){ 650 AVPacketList *pktl = s->raw_packet_buffer; 651 652 if (pktl) { 653 *pkt = pktl->pkt; 654 if(s->streams[pkt->stream_index]->codec->codec_id != CODEC_ID_PROBE || 655 !s->streams[pkt->stream_index]->probe_packets || 656 s->raw_packet_buffer_remaining_size < pkt->size){ 657 AVProbeData *pd = &s->streams[pkt->stream_index]->probe_data; 658 av_freep(&pd->buf); 659 pd->buf_size = 0; 660 s->raw_packet_buffer = pktl->next; 661 s->raw_packet_buffer_remaining_size += pkt->size; 662 av_free(pktl); 663 return 0; 664 } 665 } 666 667 av_init_packet(pkt); 668 ret= s->iformat->read_packet(s, pkt); 669 if (ret < 0) { 670 if (!pktl || ret == AVERROR(EAGAIN)) 671 return ret; 672 for (i = 0; i < s->nb_streams; i++) 673 s->streams[i]->probe_packets = 0; 674 continue; 675 } 676 st= s->streams[pkt->stream_index]; 677 678 switch(st->codec->codec_type){ 679 case AVMEDIA_TYPE_VIDEO: 680 if(s->video_codec_id) st->codec->codec_id= s->video_codec_id; 681 break; 682 case AVMEDIA_TYPE_AUDIO: 683 if(s->audio_codec_id) st->codec->codec_id= s->audio_codec_id; 684 break; 685 case AVMEDIA_TYPE_SUBTITLE: 686 if(s->subtitle_codec_id)st->codec->codec_id= s->subtitle_codec_id; 687 break; 688 } 689 690 if(!pktl && (st->codec->codec_id != CODEC_ID_PROBE || 691 !st->probe_packets)) 692 return ret; 693 694 add_to_pktbuf(&s->raw_packet_buffer, pkt, &s->raw_packet_buffer_end); 695 s->raw_packet_buffer_remaining_size -= pkt->size; 696 697 if(st->codec->codec_id == CODEC_ID_PROBE){ 698 AVProbeData *pd = &st->probe_data; 699 av_log(s, AV_LOG_DEBUG, "probing stream %d\n", st->index); 700 --st->probe_packets; 701 702 pd->buf = av_realloc(pd->buf, pd->buf_size+pkt->size+AVPROBE_PADDING_SIZE); 703 memcpy(pd->buf+pd->buf_size, pkt->data, pkt->size); 704 pd->buf_size += pkt->size; 705 memset(pd->buf+pd->buf_size, 0, AVPROBE_PADDING_SIZE); 706 707 if(av_log2(pd->buf_size) != av_log2(pd->buf_size - pkt->size)){ 708 //FIXME we dont reduce score to 0 for the case of running out of buffer space in bytes 709 set_codec_from_probe_data(s, st, pd, st->probe_packets > 0 ? AVPROBE_SCORE_MAX/4 : 0); 710 if(st->codec->codec_id != CODEC_ID_PROBE){ 711 pd->buf_size=0; 712 av_freep(&pd->buf); 713 av_log(s, AV_LOG_DEBUG, "probed stream %d\n", st->index); 714 } 715 } 716 } 717 } 718} 719 720/**********************************************************/ 721 722/** 723 * Get the number of samples of an audio frame. Return -1 on error. 724 */ 725static int get_audio_frame_size(AVCodecContext *enc, int size) 726{ 727 int frame_size; 728 729 if(enc->codec_id == CODEC_ID_VORBIS) 730 return -1; 731 732 if (enc->frame_size <= 1) { 733 int bits_per_sample = av_get_bits_per_sample(enc->codec_id); 734 735 if (bits_per_sample) { 736 if (enc->channels == 0) 737 return -1; 738 frame_size = (size << 3) / (bits_per_sample * enc->channels); 739 } else { 740 /* used for example by ADPCM codecs */ 741 if (enc->bit_rate == 0) 742 return -1; 743 frame_size = ((int64_t)size * 8 * enc->sample_rate) / enc->bit_rate; 744 } 745 } else { 746 frame_size = enc->frame_size; 747 } 748 return frame_size; 749} 750 751 752/** 753 * Return the frame duration in seconds. Return 0 if not available. 754 */ 755static void compute_frame_duration(int *pnum, int *pden, AVStream *st, 756 AVCodecParserContext *pc, AVPacket *pkt) 757{ 758 int frame_size; 759 760 *pnum = 0; 761 *pden = 0; 762 switch(st->codec->codec_type) { 763 case AVMEDIA_TYPE_VIDEO: 764 if(st->time_base.num*1000LL > st->time_base.den){ 765 *pnum = st->time_base.num; 766 *pden = st->time_base.den; 767 }else if(st->codec->time_base.num*1000LL > st->codec->time_base.den){ 768 *pnum = st->codec->time_base.num; 769 *pden = st->codec->time_base.den; 770 if (pc && pc->repeat_pict) { 771 *pnum = (*pnum) * (1 + pc->repeat_pict); 772 } 773 //If this codec can be interlaced or progressive then we need a parser to compute duration of a packet 774 //Thus if we have no parser in such case leave duration undefined. 775 if(st->codec->ticks_per_frame>1 && !pc){ 776 *pnum = *pden = 0; 777 } 778 } 779 break; 780 case AVMEDIA_TYPE_AUDIO: 781 frame_size = get_audio_frame_size(st->codec, pkt->size); 782 if (frame_size < 0) 783 break; 784 *pnum = frame_size; 785 *pden = st->codec->sample_rate; 786 break; 787 default: 788 break; 789 } 790} 791 792static int is_intra_only(AVCodecContext *enc){ 793 if(enc->codec_type == AVMEDIA_TYPE_AUDIO){ 794 return 1; 795 }else if(enc->codec_type == AVMEDIA_TYPE_VIDEO){ 796 switch(enc->codec_id){ 797 case CODEC_ID_MJPEG: 798 case CODEC_ID_MJPEGB: 799 case CODEC_ID_LJPEG: 800 case CODEC_ID_RAWVIDEO: 801 case CODEC_ID_DVVIDEO: 802 case CODEC_ID_HUFFYUV: 803 case CODEC_ID_FFVHUFF: 804 case CODEC_ID_ASV1: 805 case CODEC_ID_ASV2: 806 case CODEC_ID_VCR1: 807 case CODEC_ID_DNXHD: 808 case CODEC_ID_JPEG2000: 809 return 1; 810 default: break; 811 } 812 } 813 return 0; 814} 815 816static void update_initial_timestamps(AVFormatContext *s, int stream_index, 817 int64_t dts, int64_t pts) 818{ 819 AVStream *st= s->streams[stream_index]; 820 AVPacketList *pktl= s->packet_buffer; 821 822 if(st->first_dts != AV_NOPTS_VALUE || dts == AV_NOPTS_VALUE || st->cur_dts == AV_NOPTS_VALUE) 823 return; 824 825 st->first_dts= dts - st->cur_dts; 826 st->cur_dts= dts; 827 828 for(; pktl; pktl= pktl->next){ 829 if(pktl->pkt.stream_index != stream_index) 830 continue; 831 //FIXME think more about this check 832 if(pktl->pkt.pts != AV_NOPTS_VALUE && pktl->pkt.pts == pktl->pkt.dts) 833 pktl->pkt.pts += st->first_dts; 834 835 if(pktl->pkt.dts != AV_NOPTS_VALUE) 836 pktl->pkt.dts += st->first_dts; 837 838 if(st->start_time == AV_NOPTS_VALUE && pktl->pkt.pts != AV_NOPTS_VALUE) 839 st->start_time= pktl->pkt.pts; 840 } 841 if (st->start_time == AV_NOPTS_VALUE) 842 st->start_time = pts; 843} 844 845static void update_initial_durations(AVFormatContext *s, AVStream *st, AVPacket *pkt) 846{ 847 AVPacketList *pktl= s->packet_buffer; 848 int64_t cur_dts= 0; 849 850 if(st->first_dts != AV_NOPTS_VALUE){ 851 cur_dts= st->first_dts; 852 for(; pktl; pktl= pktl->next){ 853 if(pktl->pkt.stream_index == pkt->stream_index){ 854 if(pktl->pkt.pts != pktl->pkt.dts || pktl->pkt.dts != AV_NOPTS_VALUE || pktl->pkt.duration) 855 break; 856 cur_dts -= pkt->duration; 857 } 858 } 859 pktl= s->packet_buffer; 860 st->first_dts = cur_dts; 861 }else if(st->cur_dts) 862 return; 863 864 for(; pktl; pktl= pktl->next){ 865 if(pktl->pkt.stream_index != pkt->stream_index) 866 continue; 867 if(pktl->pkt.pts == pktl->pkt.dts && pktl->pkt.dts == AV_NOPTS_VALUE 868 && !pktl->pkt.duration){ 869 pktl->pkt.dts= cur_dts; 870 if(!st->codec->has_b_frames) 871 pktl->pkt.pts= cur_dts; 872 cur_dts += pkt->duration; 873 pktl->pkt.duration= pkt->duration; 874 }else 875 break; 876 } 877 if(st->first_dts == AV_NOPTS_VALUE) 878 st->cur_dts= cur_dts; 879} 880 881static void compute_pkt_fields(AVFormatContext *s, AVStream *st, 882 AVCodecParserContext *pc, AVPacket *pkt) 883{ 884 int num, den, presentation_delayed, delay, i; 885 int64_t offset; 886 887 if (s->flags & AVFMT_FLAG_NOFILLIN) 888 return; 889 890 if((s->flags & AVFMT_FLAG_IGNDTS) && pkt->pts != AV_NOPTS_VALUE) 891 pkt->dts= AV_NOPTS_VALUE; 892 893 if (st->codec->codec_id != CODEC_ID_H264 && pc && pc->pict_type == FF_B_TYPE) 894 //FIXME Set low_delay = 0 when has_b_frames = 1 895 st->codec->has_b_frames = 1; 896 897 /* do we have a video B-frame ? */ 898 delay= st->codec->has_b_frames; 899 presentation_delayed = 0; 900 /* XXX: need has_b_frame, but cannot get it if the codec is 901 not initialized */ 902 if (delay && 903 pc && pc->pict_type != FF_B_TYPE) 904 presentation_delayed = 1; 905 906 if(pkt->pts != AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE && pkt->dts > pkt->pts && st->pts_wrap_bits<63 907 /*&& pkt->dts-(1LL<<st->pts_wrap_bits) < pkt->pts*/){ 908 pkt->dts -= 1LL<<st->pts_wrap_bits; 909 } 910 911 // some mpeg2 in mpeg-ps lack dts (issue171 / input_file.mpg) 912 // we take the conservative approach and discard both 913 // Note, if this is misbehaving for a H.264 file then possibly presentation_delayed is not set correctly. 914 if(delay==1 && pkt->dts == pkt->pts && pkt->dts != AV_NOPTS_VALUE && presentation_delayed){ 915 av_log(s, AV_LOG_WARNING, "invalid dts/pts combination\n"); 916 pkt->dts= pkt->pts= AV_NOPTS_VALUE; 917 } 918 919 if (pkt->duration == 0) { 920 compute_frame_duration(&num, &den, st, pc, pkt); 921 if (den && num) { 922 pkt->duration = av_rescale_rnd(1, num * (int64_t)st->time_base.den, den * (int64_t)st->time_base.num, AV_ROUND_DOWN); 923 924 if(pkt->duration != 0 && s->packet_buffer) 925 update_initial_durations(s, st, pkt); 926 } 927 } 928 929 /* correct timestamps with byte offset if demuxers only have timestamps 930 on packet boundaries */ 931 if(pc && st->need_parsing == AVSTREAM_PARSE_TIMESTAMPS && pkt->size){ 932 /* this will estimate bitrate based on this frame's duration and size */ 933 offset = av_rescale(pc->offset, pkt->duration, pkt->size); 934 if(pkt->pts != AV_NOPTS_VALUE) 935 pkt->pts += offset; 936 if(pkt->dts != AV_NOPTS_VALUE) 937 pkt->dts += offset; 938 } 939 940 if (pc && pc->dts_sync_point >= 0) { 941 // we have synchronization info from the parser 942 int64_t den = st->codec->time_base.den * (int64_t) st->time_base.num; 943 if (den > 0) { 944 int64_t num = st->codec->time_base.num * (int64_t) st->time_base.den; 945 if (pkt->dts != AV_NOPTS_VALUE) { 946 // got DTS from the stream, update reference timestamp 947 st->reference_dts = pkt->dts - pc->dts_ref_dts_delta * num / den; 948 pkt->pts = pkt->dts + pc->pts_dts_delta * num / den; 949 } else if (st->reference_dts != AV_NOPTS_VALUE) { 950 // compute DTS based on reference timestamp 951 pkt->dts = st->reference_dts + pc->dts_ref_dts_delta * num / den; 952 pkt->pts = pkt->dts + pc->pts_dts_delta * num / den; 953 } 954 if (pc->dts_sync_point > 0) 955 st->reference_dts = pkt->dts; // new reference 956 } 957 } 958 959 /* This may be redundant, but it should not hurt. */ 960 if(pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE && pkt->pts > pkt->dts) 961 presentation_delayed = 1; 962 963// av_log(NULL, AV_LOG_DEBUG, "IN delayed:%d pts:%"PRId64", dts:%"PRId64" cur_dts:%"PRId64" st:%d pc:%p\n", presentation_delayed, pkt->pts, pkt->dts, st->cur_dts, pkt->stream_index, pc); 964 /* interpolate PTS and DTS if they are not present */ 965 //We skip H264 currently because delay and has_b_frames are not reliably set 966 if((delay==0 || (delay==1 && pc)) && st->codec->codec_id != CODEC_ID_H264){ 967 if (presentation_delayed) { 968 /* DTS = decompression timestamp */ 969 /* PTS = presentation timestamp */ 970 if (pkt->dts == AV_NOPTS_VALUE) 971 pkt->dts = st->last_IP_pts; 972 update_initial_timestamps(s, pkt->stream_index, pkt->dts, pkt->pts); 973 if (pkt->dts == AV_NOPTS_VALUE) 974 pkt->dts = st->cur_dts; 975 976 /* this is tricky: the dts must be incremented by the duration 977 of the frame we are displaying, i.e. the last I- or P-frame */ 978 if (st->last_IP_duration == 0) 979 st->last_IP_duration = pkt->duration; 980 if(pkt->dts != AV_NOPTS_VALUE) 981 st->cur_dts = pkt->dts + st->last_IP_duration; 982 st->last_IP_duration = pkt->duration; 983 st->last_IP_pts= pkt->pts; 984 /* cannot compute PTS if not present (we can compute it only 985 by knowing the future */ 986 } else if(pkt->pts != AV_NOPTS_VALUE || pkt->dts != AV_NOPTS_VALUE || pkt->duration){ 987 if(pkt->pts != AV_NOPTS_VALUE && pkt->duration){ 988 int64_t old_diff= FFABS(st->cur_dts - pkt->duration - pkt->pts); 989 int64_t new_diff= FFABS(st->cur_dts - pkt->pts); 990 if(old_diff < new_diff && old_diff < (pkt->duration>>3)){ 991 pkt->pts += pkt->duration; 992 // av_log(NULL, AV_LOG_DEBUG, "id:%d old:%"PRId64" new:%"PRId64" dur:%d cur:%"PRId64" size:%d\n", pkt->stream_index, old_diff, new_diff, pkt->duration, st->cur_dts, pkt->size); 993 } 994 } 995 996 /* presentation is not delayed : PTS and DTS are the same */ 997 if(pkt->pts == AV_NOPTS_VALUE) 998 pkt->pts = pkt->dts; 999 update_initial_timestamps(s, pkt->stream_index, pkt->pts, pkt->pts); 1000 if(pkt->pts == AV_NOPTS_VALUE) 1001 pkt->pts = st->cur_dts; 1002 pkt->dts = pkt->pts; 1003 if(pkt->pts != AV_NOPTS_VALUE) 1004 st->cur_dts = pkt->pts + pkt->duration; 1005 } 1006 } 1007 1008 if(pkt->pts != AV_NOPTS_VALUE && delay <= MAX_REORDER_DELAY){ 1009 st->pts_buffer[0]= pkt->pts; 1010 for(i=0; i<delay && st->pts_buffer[i] > st->pts_buffer[i+1]; i++) 1011 FFSWAP(int64_t, st->pts_buffer[i], st->pts_buffer[i+1]); 1012 if(pkt->dts == AV_NOPTS_VALUE) 1013 pkt->dts= st->pts_buffer[0]; 1014 if(st->codec->codec_id == CODEC_ID_H264){ //we skiped it above so we try here 1015 update_initial_timestamps(s, pkt->stream_index, pkt->dts, pkt->pts); // this should happen on the first packet 1016 } 1017 if(pkt->dts > st->cur_dts) 1018 st->cur_dts = pkt->dts; 1019 } 1020 1021// av_log(NULL, AV_LOG_ERROR, "OUTdelayed:%d/%d pts:%"PRId64", dts:%"PRId64" cur_dts:%"PRId64"\n", presentation_delayed, delay, pkt->pts, pkt->dts, st->cur_dts); 1022 1023 /* update flags */ 1024 if(is_intra_only(st->codec)) 1025 pkt->flags |= AV_PKT_FLAG_KEY; 1026 else if (pc) { 1027 pkt->flags = 0; 1028 /* keyframe computation */ 1029 if (pc->key_frame == 1) 1030 pkt->flags |= AV_PKT_FLAG_KEY; 1031 else if (pc->key_frame == -1 && pc->pict_type == FF_I_TYPE) 1032 pkt->flags |= AV_PKT_FLAG_KEY; 1033 } 1034 if (pc) 1035 pkt->convergence_duration = pc->convergence_duration; 1036} 1037 1038 1039static int av_read_frame_internal(AVFormatContext *s, AVPacket *pkt) 1040{ 1041 AVStream *st; 1042 int len, ret, i; 1043 1044 av_init_packet(pkt); 1045 1046 for(;;) { 1047 /* select current input stream component */ 1048 st = s->cur_st; 1049 if (st) { 1050 if (!st->need_parsing || !st->parser) { 1051 /* no parsing needed: we just output the packet as is */ 1052 /* raw data support */ 1053 *pkt = st->cur_pkt; st->cur_pkt.data= NULL; 1054 compute_pkt_fields(s, st, NULL, pkt); 1055 s->cur_st = NULL; 1056 if ((s->iformat->flags & AVFMT_GENERIC_INDEX) && 1057 (pkt->flags & AV_PKT_FLAG_KEY) && pkt->dts != AV_NOPTS_VALUE) { 1058 ff_reduce_index(s, st->index); 1059 av_add_index_entry(st, pkt->pos, pkt->dts, 0, 0, AVINDEX_KEYFRAME); 1060 } 1061 break; 1062 } else if (st->cur_len > 0 && st->discard < AVDISCARD_ALL) { 1063 len = av_parser_parse2(st->parser, st->codec, &pkt->data, &pkt->size, 1064 st->cur_ptr, st->cur_len, 1065 st->cur_pkt.pts, st->cur_pkt.dts, 1066 st->cur_pkt.pos); 1067 st->cur_pkt.pts = AV_NOPTS_VALUE; 1068 st->cur_pkt.dts = AV_NOPTS_VALUE; 1069 /* increment read pointer */ 1070 st->cur_ptr += len; 1071 st->cur_len -= len; 1072 1073 /* return packet if any */ 1074 if (pkt->size) { 1075 got_packet: 1076 pkt->duration = 0; 1077 pkt->stream_index = st->index; 1078 pkt->pts = st->parser->pts; 1079 pkt->dts = st->parser->dts; 1080 pkt->pos = st->parser->pos; 1081 pkt->destruct = NULL; 1082 compute_pkt_fields(s, st, st->parser, pkt); 1083 1084 if((s->iformat->flags & AVFMT_GENERIC_INDEX) && pkt->flags & AV_PKT_FLAG_KEY){ 1085 ff_reduce_index(s, st->index); 1086 av_add_index_entry(st, st->parser->frame_offset, pkt->dts, 1087 0, 0, AVINDEX_KEYFRAME); 1088 } 1089 1090 break; 1091 } 1092 } else { 1093 /* free packet */ 1094 av_free_packet(&st->cur_pkt); 1095 s->cur_st = NULL; 1096 } 1097 } else { 1098 AVPacket cur_pkt; 1099 /* read next packet */ 1100 ret = av_read_packet(s, &cur_pkt); 1101 if (ret < 0) { 1102 if (ret == AVERROR(EAGAIN)) 1103 return ret; 1104 /* return the last frames, if any */ 1105 for(i = 0; i < s->nb_streams; i++) { 1106 st = s->streams[i]; 1107 if (st->parser && st->need_parsing) { 1108 av_parser_parse2(st->parser, st->codec, 1109 &pkt->data, &pkt->size, 1110 NULL, 0, 1111 AV_NOPTS_VALUE, AV_NOPTS_VALUE, 1112 AV_NOPTS_VALUE); 1113 if (pkt->size) 1114 goto got_packet; 1115 } 1116 } 1117 /* no more packets: really terminate parsing */ 1118 return ret; 1119 } 1120 st = s->streams[cur_pkt.stream_index]; 1121 st->cur_pkt= cur_pkt; 1122 1123 if(st->cur_pkt.pts != AV_NOPTS_VALUE && 1124 st->cur_pkt.dts != AV_NOPTS_VALUE && 1125 st->cur_pkt.pts < st->cur_pkt.dts){ 1126 av_log(s, AV_LOG_WARNING, "Invalid timestamps stream=%d, pts=%"PRId64", dts=%"PRId64", size=%d\n", 1127 st->cur_pkt.stream_index, 1128 st->cur_pkt.pts, 1129 st->cur_pkt.dts, 1130 st->cur_pkt.size); 1131// av_free_packet(&st->cur_pkt); 1132// return -1; 1133 } 1134 1135 if(s->debug & FF_FDEBUG_TS) 1136 av_log(s, AV_LOG_DEBUG, "av_read_packet stream=%d, pts=%"PRId64", dts=%"PRId64", size=%d, duration=%d, flags=%d\n", 1137 st->cur_pkt.stream_index, 1138 st->cur_pkt.pts, 1139 st->cur_pkt.dts, 1140 st->cur_pkt.size, 1141 st->cur_pkt.duration, 1142 st->cur_pkt.flags); 1143 1144 s->cur_st = st; 1145 st->cur_ptr = st->cur_pkt.data; 1146 st->cur_len = st->cur_pkt.size; 1147 if (st->need_parsing && !st->parser && !(s->flags & AVFMT_FLAG_NOPARSE)) { 1148 st->parser = av_parser_init(st->codec->codec_id); 1149 if (!st->parser) { 1150 /* no parser available: just output the raw packets */ 1151 st->need_parsing = AVSTREAM_PARSE_NONE; 1152 }else if(st->need_parsing == AVSTREAM_PARSE_HEADERS){ 1153 st->parser->flags |= PARSER_FLAG_COMPLETE_FRAMES; 1154 } 1155 if(st->parser && (s->iformat->flags & AVFMT_GENERIC_INDEX)){ 1156 st->parser->next_frame_offset= 1157 st->parser->cur_offset= st->cur_pkt.pos; 1158 } 1159 } 1160 } 1161 } 1162 if(s->debug & FF_FDEBUG_TS) 1163 av_log(s, AV_LOG_DEBUG, "av_read_frame_internal stream=%d, pts=%"PRId64", dts=%"PRId64", size=%d, duration=%d, flags=%d\n", 1164 pkt->stream_index, 1165 pkt->pts, 1166 pkt->dts, 1167 pkt->size, 1168 pkt->duration, 1169 pkt->flags); 1170 1171 return 0; 1172} 1173 1174int av_read_frame(AVFormatContext *s, AVPacket *pkt) 1175{ 1176 AVPacketList *pktl; 1177 int eof=0; 1178 const int genpts= s->flags & AVFMT_FLAG_GENPTS; 1179 1180 for(;;){ 1181 pktl = s->packet_buffer; 1182 if (pktl) { 1183 AVPacket *next_pkt= &pktl->pkt; 1184 1185 if(genpts && next_pkt->dts != AV_NOPTS_VALUE){ 1186 while(pktl && next_pkt->pts == AV_NOPTS_VALUE){ 1187 if( pktl->pkt.stream_index == next_pkt->stream_index 1188 && next_pkt->dts < pktl->pkt.dts 1189 && pktl->pkt.pts != pktl->pkt.dts //not b frame 1190 /*&& pktl->pkt.dts != AV_NOPTS_VALUE*/){ 1191 next_pkt->pts= pktl->pkt.dts; 1192 } 1193 pktl= pktl->next; 1194 } 1195 pktl = s->packet_buffer; 1196 } 1197 1198 if( next_pkt->pts != AV_NOPTS_VALUE 1199 || next_pkt->dts == AV_NOPTS_VALUE 1200 || !genpts || eof){ 1201 /* read packet from packet buffer, if there is data */ 1202 *pkt = *next_pkt; 1203 s->packet_buffer = pktl->next; 1204 av_free(pktl); 1205 return 0; 1206 } 1207 } 1208 if(genpts){ 1209 int ret= av_read_frame_internal(s, pkt); 1210 if(ret<0){ 1211 if(pktl && ret != AVERROR(EAGAIN)){ 1212 eof=1; 1213 continue; 1214 }else 1215 return ret; 1216 } 1217 1218 if(av_dup_packet(add_to_pktbuf(&s->packet_buffer, pkt, 1219 &s->packet_buffer_end)) < 0) 1220 return AVERROR(ENOMEM); 1221 }else{ 1222 assert(!s->packet_buffer); 1223 return av_read_frame_internal(s, pkt); 1224 } 1225 } 1226} 1227 1228/* XXX: suppress the packet queue */ 1229static void flush_packet_queue(AVFormatContext *s) 1230{ 1231 AVPacketList *pktl; 1232 1233 for(;;) { 1234 pktl = s->packet_buffer; 1235 if (!pktl) 1236 break; 1237 s->packet_buffer = pktl->next; 1238 av_free_packet(&pktl->pkt); 1239 av_free(pktl); 1240 } 1241 while(s->raw_packet_buffer){ 1242 pktl = s->raw_packet_buffer; 1243 s->raw_packet_buffer = pktl->next; 1244 av_free_packet(&pktl->pkt); 1245 av_free(pktl); 1246 } 1247 s->packet_buffer_end= 1248 s->raw_packet_buffer_end= NULL; 1249 s->raw_packet_buffer_remaining_size = RAW_PACKET_BUFFER_SIZE; 1250} 1251 1252/*******************************************************/ 1253/* seek support */ 1254 1255int av_find_default_stream_index(AVFormatContext *s) 1256{ 1257 int first_audio_index = -1; 1258 int i; 1259 AVStream *st; 1260 1261 if (s->nb_streams <= 0) 1262 return -1; 1263 for(i = 0; i < s->nb_streams; i++) { 1264 st = s->streams[i]; 1265 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) { 1266 return i; 1267 } 1268 if (first_audio_index < 0 && st->codec->codec_type == AVMEDIA_TYPE_AUDIO) 1269 first_audio_index = i; 1270 } 1271 return first_audio_index >= 0 ? first_audio_index : 0; 1272} 1273 1274/** 1275 * Flush the frame reader. 1276 */ 1277void ff_read_frame_flush(AVFormatContext *s) 1278{ 1279 AVStream *st; 1280 int i, j; 1281 1282 flush_packet_queue(s); 1283 1284 s->cur_st = NULL; 1285 1286 /* for each stream, reset read state */ 1287 for(i = 0; i < s->nb_streams; i++) { 1288 st = s->streams[i]; 1289 1290 if (st->parser) { 1291 av_parser_close(st->parser); 1292 st->parser = NULL; 1293 av_free_packet(&st->cur_pkt); 1294 } 1295 st->last_IP_pts = AV_NOPTS_VALUE; 1296 st->cur_dts = AV_NOPTS_VALUE; /* we set the current DTS to an unspecified origin */ 1297 st->reference_dts = AV_NOPTS_VALUE; 1298 /* fail safe */ 1299 st->cur_ptr = NULL; 1300 st->cur_len = 0; 1301 1302 st->probe_packets = MAX_PROBE_PACKETS; 1303 1304 for(j=0; j<MAX_REORDER_DELAY+1; j++) 1305 st->pts_buffer[j]= AV_NOPTS_VALUE; 1306 } 1307} 1308 1309void av_update_cur_dts(AVFormatContext *s, AVStream *ref_st, int64_t timestamp){ 1310 int i; 1311 1312 for(i = 0; i < s->nb_streams; i++) { 1313 AVStream *st = s->streams[i]; 1314 1315 st->cur_dts = av_rescale(timestamp, 1316 st->time_base.den * (int64_t)ref_st->time_base.num, 1317 st->time_base.num * (int64_t)ref_st->time_base.den); 1318 } 1319} 1320 1321void ff_reduce_index(AVFormatContext *s, int stream_index) 1322{ 1323 AVStream *st= s->streams[stream_index]; 1324 unsigned int max_entries= s->max_index_size / sizeof(AVIndexEntry); 1325 1326 if((unsigned)st->nb_index_entries >= max_entries){ 1327 int i; 1328 for(i=0; 2*i<st->nb_index_entries; i++) 1329 st->index_entries[i]= st->index_entries[2*i]; 1330 st->nb_index_entries= i; 1331 } 1332} 1333 1334int av_add_index_entry(AVStream *st, 1335 int64_t pos, int64_t timestamp, int size, int distance, int flags) 1336{ 1337 AVIndexEntry *entries, *ie; 1338 int index; 1339 1340 if((unsigned)st->nb_index_entries + 1 >= UINT_MAX / sizeof(AVIndexEntry)) 1341 return -1; 1342 1343 entries = av_fast_realloc(st->index_entries, 1344 &st->index_entries_allocated_size, 1345 (st->nb_index_entries + 1) * 1346 sizeof(AVIndexEntry)); 1347 if(!entries) 1348 return -1; 1349 1350 st->index_entries= entries; 1351 1352 index= av_index_search_timestamp(st, timestamp, AVSEEK_FLAG_ANY); 1353 1354 if(index<0){ 1355 index= st->nb_index_entries++; 1356 ie= &entries[index]; 1357 assert(index==0 || ie[-1].timestamp < timestamp); 1358 }else{ 1359 ie= &entries[index]; 1360 if(ie->timestamp != timestamp){ 1361 if(ie->timestamp <= timestamp) 1362 return -1; 1363 memmove(entries + index + 1, entries + index, sizeof(AVIndexEntry)*(st->nb_index_entries - index)); 1364 st->nb_index_entries++; 1365 }else if(ie->pos == pos && distance < ie->min_distance) //do not reduce the distance 1366 distance= ie->min_distance; 1367 } 1368 1369 ie->pos = pos; 1370 ie->timestamp = timestamp; 1371 ie->min_distance= distance; 1372 ie->size= size; 1373 ie->flags = flags; 1374 1375 return index; 1376} 1377 1378int av_index_search_timestamp(AVStream *st, int64_t wanted_timestamp, 1379 int flags) 1380{ 1381 AVIndexEntry *entries= st->index_entries; 1382 int nb_entries= st->nb_index_entries; 1383 int a, b, m; 1384 int64_t timestamp; 1385 1386 a = - 1; 1387 b = nb_entries; 1388 1389 //optimize appending index entries at the end 1390 if(b && entries[b-1].timestamp < wanted_timestamp) 1391 a= b-1; 1392 1393 while (b - a > 1) { 1394 m = (a + b) >> 1; 1395 timestamp = entries[m].timestamp; 1396 if(timestamp >= wanted_timestamp) 1397 b = m; 1398 if(timestamp <= wanted_timestamp) 1399 a = m; 1400 } 1401 m= (flags & AVSEEK_FLAG_BACKWARD) ? a : b; 1402 1403 if(!(flags & AVSEEK_FLAG_ANY)){ 1404 while(m>=0 && m<nb_entries && !(entries[m].flags & AVINDEX_KEYFRAME)){ 1405 m += (flags & AVSEEK_FLAG_BACKWARD) ? -1 : 1; 1406 } 1407 } 1408 1409 if(m == nb_entries) 1410 return -1; 1411 return m; 1412} 1413 1414#define DEBUG_SEEK 1415 1416int av_seek_frame_binary(AVFormatContext *s, int stream_index, int64_t target_ts, int flags){ 1417 AVInputFormat *avif= s->iformat; 1418 int64_t av_uninit(pos_min), av_uninit(pos_max), pos, pos_limit; 1419 int64_t ts_min, ts_max, ts; 1420 int index; 1421 int64_t ret; 1422 AVStream *st; 1423 1424 if (stream_index < 0) 1425 return -1; 1426 1427#ifdef DEBUG_SEEK 1428 av_log(s, AV_LOG_DEBUG, "read_seek: %d %"PRId64"\n", stream_index, target_ts); 1429#endif 1430 1431 ts_max= 1432 ts_min= AV_NOPTS_VALUE; 1433 pos_limit= -1; //gcc falsely says it may be uninitialized 1434 1435 st= s->streams[stream_index]; 1436 if(st->index_entries){ 1437 AVIndexEntry *e; 1438 1439 index= av_index_search_timestamp(st, target_ts, flags | AVSEEK_FLAG_BACKWARD); //FIXME whole func must be checked for non-keyframe entries in index case, especially read_timestamp() 1440 index= FFMAX(index, 0); 1441 e= &st->index_entries[index]; 1442 1443 if(e->timestamp <= target_ts || e->pos == e->min_distance){ 1444 pos_min= e->pos; 1445 ts_min= e->timestamp; 1446#ifdef DEBUG_SEEK 1447 av_log(s, AV_LOG_DEBUG, "using cached pos_min=0x%"PRIx64" dts_min=%"PRId64"\n", 1448 pos_min,ts_min); 1449#endif 1450 }else{ 1451 assert(index==0); 1452 } 1453 1454 index= av_index_search_timestamp(st, target_ts, flags & ~AVSEEK_FLAG_BACKWARD); 1455 assert(index < st->nb_index_entries); 1456 if(index >= 0){ 1457 e= &st->index_entries[index]; 1458 assert(e->timestamp >= target_ts); 1459 pos_max= e->pos; 1460 ts_max= e->timestamp; 1461 pos_limit= pos_max - e->min_distance; 1462#ifdef DEBUG_SEEK 1463 av_log(s, AV_LOG_DEBUG, "using cached pos_max=0x%"PRIx64" pos_limit=0x%"PRIx64" dts_max=%"PRId64"\n", 1464 pos_max,pos_limit, ts_max); 1465#endif 1466 } 1467 } 1468 1469 pos= av_gen_search(s, stream_index, target_ts, pos_min, pos_max, pos_limit, ts_min, ts_max, flags, &ts, avif->read_timestamp); 1470 if(pos<0) 1471 return -1; 1472 1473 /* do the seek */ 1474 if ((ret = url_fseek(s->pb, pos, SEEK_SET)) < 0) 1475 return ret; 1476 1477 av_update_cur_dts(s, st, ts); 1478 1479 return 0; 1480} 1481 1482int64_t av_gen_search(AVFormatContext *s, int stream_index, int64_t target_ts, int64_t pos_min, int64_t pos_max, int64_t pos_limit, int64_t ts_min, int64_t ts_max, int flags, int64_t *ts_ret, int64_t (*read_timestamp)(struct AVFormatContext *, int , int64_t *, int64_t )){ 1483 int64_t pos, ts; 1484 int64_t start_pos, filesize; 1485 int no_change; 1486 1487#ifdef DEBUG_SEEK 1488 av_log(s, AV_LOG_DEBUG, "gen_seek: %d %"PRId64"\n", stream_index, target_ts); 1489#endif 1490 1491 if(ts_min == AV_NOPTS_VALUE){ 1492 pos_min = s->data_offset; 1493 ts_min = read_timestamp(s, stream_index, &pos_min, INT64_MAX); 1494 if (ts_min == AV_NOPTS_VALUE) 1495 return -1; 1496 } 1497 1498 if(ts_max == AV_NOPTS_VALUE){ 1499 int step= 1024; 1500 filesize = url_fsize(s->pb); 1501 pos_max = filesize - 1; 1502 do{ 1503 pos_max -= step; 1504 ts_max = read_timestamp(s, stream_index, &pos_max, pos_max + step); 1505 step += step; 1506 }while(ts_max == AV_NOPTS_VALUE && pos_max >= step); 1507 if (ts_max == AV_NOPTS_VALUE) 1508 return -1; 1509 1510 for(;;){ 1511 int64_t tmp_pos= pos_max + 1; 1512 int64_t tmp_ts= read_timestamp(s, stream_index, &tmp_pos, INT64_MAX); 1513 if(tmp_ts == AV_NOPTS_VALUE) 1514 break; 1515 ts_max= tmp_ts; 1516 pos_max= tmp_pos; 1517 if(tmp_pos >= filesize) 1518 break; 1519 } 1520 pos_limit= pos_max; 1521 } 1522 1523 if(ts_min > ts_max){ 1524 return -1; 1525 }else if(ts_min == ts_max){ 1526 pos_limit= pos_min; 1527 } 1528 1529 no_change=0; 1530 while (pos_min < pos_limit) { 1531#ifdef DEBUG_SEEK 1532 av_log(s, AV_LOG_DEBUG, "pos_min=0x%"PRIx64" pos_max=0x%"PRIx64" dts_min=%"PRId64" dts_max=%"PRId64"\n", 1533 pos_min, pos_max, 1534 ts_min, ts_max); 1535#endif 1536 assert(pos_limit <= pos_max); 1537 1538 if(no_change==0){ 1539 int64_t approximate_keyframe_distance= pos_max - pos_limit; 1540 // interpolate position (better than dichotomy) 1541 pos = av_rescale(target_ts - ts_min, pos_max - pos_min, ts_max - ts_min) 1542 + pos_min - approximate_keyframe_distance; 1543 }else if(no_change==1){ 1544 // bisection, if interpolation failed to change min or max pos last time 1545 pos = (pos_min + pos_limit)>>1; 1546 }else{ 1547 /* linear search if bisection failed, can only happen if there 1548 are very few or no keyframes between min/max */ 1549 pos=pos_min; 1550 } 1551 if(pos <= pos_min) 1552 pos= pos_min + 1; 1553 else if(pos > pos_limit) 1554 pos= pos_limit; 1555 start_pos= pos; 1556 1557 ts = read_timestamp(s, stream_index, &pos, INT64_MAX); //may pass pos_limit instead of -1 1558 if(pos == pos_max) 1559 no_change++; 1560 else 1561 no_change=0; 1562#ifdef DEBUG_SEEK 1563 av_log(s, AV_LOG_DEBUG, "%"PRId64" %"PRId64" %"PRId64" / %"PRId64" %"PRId64" %"PRId64" target:%"PRId64" limit:%"PRId64" start:%"PRId64" noc:%d\n", 1564 pos_min, pos, pos_max, ts_min, ts, ts_max, target_ts, pos_limit, 1565 start_pos, no_change); 1566#endif 1567 if(ts == AV_NOPTS_VALUE){ 1568 av_log(s, AV_LOG_ERROR, "read_timestamp() failed in the middle\n"); 1569 return -1; 1570 } 1571 assert(ts != AV_NOPTS_VALUE); 1572 if (target_ts <= ts) { 1573 pos_limit = start_pos - 1; 1574 pos_max = pos; 1575 ts_max = ts; 1576 } 1577 if (target_ts >= ts) { 1578 pos_min = pos; 1579 ts_min = ts; 1580 } 1581 } 1582 1583 pos = (flags & AVSEEK_FLAG_BACKWARD) ? pos_min : pos_max; 1584 ts = (flags & AVSEEK_FLAG_BACKWARD) ? ts_min : ts_max; 1585#ifdef DEBUG_SEEK 1586 pos_min = pos; 1587 ts_min = read_timestamp(s, stream_index, &pos_min, INT64_MAX); 1588 pos_min++; 1589 ts_max = read_timestamp(s, stream_index, &pos_min, INT64_MAX); 1590 av_log(s, AV_LOG_DEBUG, "pos=0x%"PRIx64" %"PRId64"<=%"PRId64"<=%"PRId64"\n", 1591 pos, ts_min, target_ts, ts_max); 1592#endif 1593 *ts_ret= ts; 1594 return pos; 1595} 1596 1597static int av_seek_frame_byte(AVFormatContext *s, int stream_index, int64_t pos, int flags){ 1598 int64_t pos_min, pos_max; 1599#if 0 1600 AVStream *st; 1601 1602 if (stream_index < 0) 1603 return -1; 1604 1605 st= s->streams[stream_index]; 1606#endif 1607 1608 pos_min = s->data_offset; 1609 pos_max = url_fsize(s->pb) - 1; 1610 1611 if (pos < pos_min) pos= pos_min; 1612 else if(pos > pos_max) pos= pos_max; 1613 1614 url_fseek(s->pb, pos, SEEK_SET); 1615 1616#if 0 1617 av_update_cur_dts(s, st, ts); 1618#endif 1619 return 0; 1620} 1621 1622static int av_seek_frame_generic(AVFormatContext *s, 1623 int stream_index, int64_t timestamp, int flags) 1624{ 1625 int index; 1626 int64_t ret; 1627 AVStream *st; 1628 AVIndexEntry *ie; 1629 1630 st = s->streams[stream_index]; 1631 1632 index = av_index_search_timestamp(st, timestamp, flags); 1633 1634 if(index < 0 && st->nb_index_entries && timestamp < st->index_entries[0].timestamp) 1635 return -1; 1636 1637 if(index < 0 || index==st->nb_index_entries-1){ 1638 int i; 1639 AVPacket pkt; 1640 1641 if(st->nb_index_entries){ 1642 assert(st->index_entries); 1643 ie= &st->index_entries[st->nb_index_entries-1]; 1644 if ((ret = url_fseek(s->pb, ie->pos, SEEK_SET)) < 0) 1645 return ret; 1646 av_update_cur_dts(s, st, ie->timestamp); 1647 }else{ 1648 if ((ret = url_fseek(s->pb, s->data_offset, SEEK_SET)) < 0) 1649 return ret; 1650 } 1651 for(i=0;; i++) { 1652 int ret; 1653 do{ 1654 ret = av_read_frame(s, &pkt); 1655 }while(ret == AVERROR(EAGAIN)); 1656 if(ret<0) 1657 break; 1658 av_free_packet(&pkt); 1659 if(stream_index == pkt.stream_index){ 1660 if((pkt.flags & AV_PKT_FLAG_KEY) && pkt.dts > timestamp) 1661 break; 1662 } 1663 } 1664 index = av_index_search_timestamp(st, timestamp, flags); 1665 } 1666 if (index < 0) 1667 return -1; 1668 1669 ff_read_frame_flush(s); 1670 if (s->iformat->read_seek){ 1671 if(s->iformat->read_seek(s, stream_index, timestamp, flags) >= 0) 1672 return 0; 1673 } 1674 ie = &st->index_entries[index]; 1675 if ((ret = url_fseek(s->pb, ie->pos, SEEK_SET)) < 0) 1676 return ret; 1677 av_update_cur_dts(s, st, ie->timestamp); 1678 1679 return 0; 1680} 1681 1682int av_seek_frame(AVFormatContext *s, int stream_index, int64_t timestamp, int flags) 1683{ 1684 int ret; 1685 AVStream *st; 1686 1687 ff_read_frame_flush(s); 1688 1689 if(flags & AVSEEK_FLAG_BYTE) 1690 return av_seek_frame_byte(s, stream_index, timestamp, flags); 1691 1692 if(stream_index < 0){ 1693 stream_index= av_find_default_stream_index(s); 1694 if(stream_index < 0) 1695 return -1; 1696 1697 st= s->streams[stream_index]; 1698 /* timestamp for default must be expressed in AV_TIME_BASE units */ 1699 timestamp = av_rescale(timestamp, st->time_base.den, AV_TIME_BASE * (int64_t)st->time_base.num); 1700 } 1701 1702 /* first, we try the format specific seek */ 1703 if (s->iformat->read_seek) 1704 ret = s->iformat->read_seek(s, stream_index, timestamp, flags); 1705 else 1706 ret = -1; 1707 if (ret >= 0) { 1708 return 0; 1709 } 1710 1711 if(s->iformat->read_timestamp) 1712 return av_seek_frame_binary(s, stream_index, timestamp, flags); 1713 else 1714 return av_seek_frame_generic(s, stream_index, timestamp, flags); 1715} 1716 1717int avformat_seek_file(AVFormatContext *s, int stream_index, int64_t min_ts, int64_t ts, int64_t max_ts, int flags) 1718{ 1719 if(min_ts > ts || max_ts < ts) 1720 return -1; 1721 1722 ff_read_frame_flush(s); 1723 1724 if (s->iformat->read_seek2) 1725 return s->iformat->read_seek2(s, stream_index, min_ts, ts, max_ts, flags); 1726 1727 if(s->iformat->read_timestamp){ 1728 //try to seek via read_timestamp() 1729 } 1730 1731 //Fallback to old API if new is not implemented but old is 1732 //Note the old has somewat different sematics 1733 if(s->iformat->read_seek || 1) 1734 return av_seek_frame(s, stream_index, ts, flags | (ts - min_ts > (uint64_t)(max_ts - ts) ? AVSEEK_FLAG_BACKWARD : 0)); 1735 1736 // try some generic seek like av_seek_frame_generic() but with new ts semantics 1737} 1738 1739/*******************************************************/ 1740 1741/** 1742 * Returns TRUE if the stream has accurate duration in any stream. 1743 * 1744 * @return TRUE if the stream has accurate duration for at least one component. 1745 */ 1746static int av_has_duration(AVFormatContext *ic) 1747{ 1748 int i; 1749 AVStream *st; 1750 1751 for(i = 0;i < ic->nb_streams; i++) { 1752 st = ic->streams[i]; 1753 if (st->duration != AV_NOPTS_VALUE) 1754 return 1; 1755 } 1756 return 0; 1757} 1758 1759/** 1760 * Estimate the stream timings from the one of each components. 1761 * 1762 * Also computes the global bitrate if possible. 1763 */ 1764static void av_update_stream_timings(AVFormatContext *ic) 1765{ 1766 int64_t start_time, start_time1, end_time, end_time1; 1767 int64_t duration, duration1; 1768 int i; 1769 AVStream *st; 1770 1771 start_time = INT64_MAX; 1772 end_time = INT64_MIN; 1773 duration = INT64_MIN; 1774 for(i = 0;i < ic->nb_streams; i++) { 1775 st = ic->streams[i]; 1776 if (st->start_time != AV_NOPTS_VALUE && st->time_base.den) { 1777 start_time1= av_rescale_q(st->start_time, st->time_base, AV_TIME_BASE_Q); 1778 if (start_time1 < start_time) 1779 start_time = start_time1; 1780 if (st->duration != AV_NOPTS_VALUE) { 1781 end_time1 = start_time1 1782 + av_rescale_q(st->duration, st->time_base, AV_TIME_BASE_Q); 1783 if (end_time1 > end_time) 1784 end_time = end_time1; 1785 } 1786 } 1787 if (st->duration != AV_NOPTS_VALUE) { 1788 duration1 = av_rescale_q(st->duration, st->time_base, AV_TIME_BASE_Q); 1789 if (duration1 > duration) 1790 duration = duration1; 1791 } 1792 } 1793 if (start_time != INT64_MAX) { 1794 ic->start_time = start_time; 1795 if (end_time != INT64_MIN) { 1796 if (end_time - start_time > duration) 1797 duration = end_time - start_time; 1798 } 1799 } 1800 if (duration != INT64_MIN) { 1801 ic->duration = duration; 1802 if (ic->file_size > 0) { 1803 /* compute the bitrate */ 1804 ic->bit_rate = (double)ic->file_size * 8.0 * AV_TIME_BASE / 1805 (double)ic->duration; 1806 } 1807 } 1808} 1809 1810static void fill_all_stream_timings(AVFormatContext *ic) 1811{ 1812 int i; 1813 AVStream *st; 1814 1815 av_update_stream_timings(ic); 1816 for(i = 0;i < ic->nb_streams; i++) { 1817 st = ic->streams[i]; 1818 if (st->start_time == AV_NOPTS_VALUE) { 1819 if(ic->start_time != AV_NOPTS_VALUE) 1820 st->start_time = av_rescale_q(ic->start_time, AV_TIME_BASE_Q, st->time_base); 1821 if(ic->duration != AV_NOPTS_VALUE) 1822 st->duration = av_rescale_q(ic->duration, AV_TIME_BASE_Q, st->time_base); 1823 } 1824 } 1825} 1826 1827static void av_estimate_timings_from_bit_rate(AVFormatContext *ic) 1828{ 1829 int64_t filesize, duration; 1830 int bit_rate, i; 1831 AVStream *st; 1832 1833 /* if bit_rate is already set, we believe it */ 1834 if (ic->bit_rate == 0) { 1835 bit_rate = 0; 1836 for(i=0;i<ic->nb_streams;i++) { 1837 st = ic->streams[i]; 1838 bit_rate += st->codec->bit_rate; 1839 } 1840 ic->bit_rate = bit_rate; 1841 } 1842 1843 /* if duration is already set, we believe it */ 1844 if (ic->duration == AV_NOPTS_VALUE && 1845 ic->bit_rate != 0 && 1846 ic->file_size != 0) { 1847 filesize = ic->file_size; 1848 if (filesize > 0) { 1849 for(i = 0; i < ic->nb_streams; i++) { 1850 st = ic->streams[i]; 1851 duration= av_rescale(8*filesize, st->time_base.den, ic->bit_rate*(int64_t)st->time_base.num); 1852 if (st->duration == AV_NOPTS_VALUE) 1853 st->duration = duration; 1854 } 1855 } 1856 } 1857} 1858 1859#define DURATION_MAX_READ_SIZE 250000 1860#define DURATION_MAX_RETRY 3 1861 1862/* only usable for MPEG-PS streams */ 1863static void av_estimate_timings_from_pts(AVFormatContext *ic, int64_t old_offset) 1864{ 1865 AVPacket pkt1, *pkt = &pkt1; 1866 AVStream *st; 1867 int read_size, i, ret; 1868 int64_t end_time, start_time[MAX_STREAMS]; 1869 int64_t filesize, offset, duration; 1870 int retry=0; 1871 1872 ic->cur_st = NULL; 1873 1874 /* flush packet queue */ 1875 flush_packet_queue(ic); 1876 1877 for(i=0;i<ic->nb_streams;i++) { 1878 st = ic->streams[i]; 1879 if(st->start_time != AV_NOPTS_VALUE){ 1880 start_time[i]= st->start_time; 1881 }else if(st->first_dts != AV_NOPTS_VALUE){ 1882 start_time[i]= st->first_dts; 1883 }else 1884 av_log(st->codec, AV_LOG_WARNING, "start time is not set in av_estimate_timings_from_pts\n"); 1885 1886 if (st->parser) { 1887 av_parser_close(st->parser); 1888 st->parser= NULL; 1889 av_free_packet(&st->cur_pkt); 1890 } 1891 } 1892 1893 /* estimate the end time (duration) */ 1894 /* XXX: may need to support wrapping */ 1895 filesize = ic->file_size; 1896 end_time = AV_NOPTS_VALUE; 1897 do{ 1898 offset = filesize - (DURATION_MAX_READ_SIZE<<retry); 1899 if (offset < 0) 1900 offset = 0; 1901 1902 url_fseek(ic->pb, offset, SEEK_SET); 1903 read_size = 0; 1904 for(;;) { 1905 if (read_size >= DURATION_MAX_READ_SIZE<<(FFMAX(retry-1,0))) 1906 break; 1907 1908 do{ 1909 ret = av_read_packet(ic, pkt); 1910 }while(ret == AVERROR(EAGAIN)); 1911 if (ret != 0) 1912 break; 1913 read_size += pkt->size; 1914 st = ic->streams[pkt->stream_index]; 1915 if (pkt->pts != AV_NOPTS_VALUE && 1916 start_time[pkt->stream_index] != AV_NOPTS_VALUE) { 1917 end_time = pkt->pts; 1918 duration = end_time - start_time[pkt->stream_index]; 1919 if (duration < 0) 1920 duration += 1LL<<st->pts_wrap_bits; 1921 if (duration > 0) { 1922 if (st->duration == AV_NOPTS_VALUE || 1923 st->duration < duration) 1924 st->duration = duration; 1925 } 1926 } 1927 av_free_packet(pkt); 1928 } 1929 }while( end_time==AV_NOPTS_VALUE 1930 && filesize > (DURATION_MAX_READ_SIZE<<retry) 1931 && ++retry <= DURATION_MAX_RETRY); 1932 1933 fill_all_stream_timings(ic); 1934 1935 url_fseek(ic->pb, old_offset, SEEK_SET); 1936 for(i=0; i<ic->nb_streams; i++){ 1937 st= ic->streams[i]; 1938 st->cur_dts= st->first_dts; 1939 st->last_IP_pts = AV_NOPTS_VALUE; 1940 } 1941} 1942 1943static void av_estimate_timings(AVFormatContext *ic, int64_t old_offset) 1944{ 1945 int64_t file_size; 1946 1947 /* get the file size, if possible */ 1948 if (ic->iformat->flags & AVFMT_NOFILE) { 1949 file_size = 0; 1950 } else { 1951 file_size = url_fsize(ic->pb); 1952 if (file_size < 0) 1953 file_size = 0; 1954 } 1955 ic->file_size = file_size; 1956 1957 if ((!strcmp(ic->iformat->name, "mpeg") || 1958 !strcmp(ic->iformat->name, "mpegts")) && 1959 file_size && !url_is_streamed(ic->pb)) { 1960 /* get accurate estimate from the PTSes */ 1961 av_estimate_timings_from_pts(ic, old_offset); 1962 } else if (av_has_duration(ic)) { 1963 /* at least one component has timings - we use them for all 1964 the components */ 1965 fill_all_stream_timings(ic); 1966 } else { 1967 av_log(ic, AV_LOG_WARNING, "Estimating duration from bitrate, this may be inaccurate\n"); 1968 /* less precise: use bitrate info */ 1969 av_estimate_timings_from_bit_rate(ic); 1970 } 1971 av_update_stream_timings(ic); 1972 1973#if 0 1974 { 1975 int i; 1976 AVStream *st; 1977 for(i = 0;i < ic->nb_streams; i++) { 1978 st = ic->streams[i]; 1979 printf("%d: start_time: %0.3f duration: %0.3f\n", 1980 i, (double)st->start_time / AV_TIME_BASE, 1981 (double)st->duration / AV_TIME_BASE); 1982 } 1983 printf("stream: start_time: %0.3f duration: %0.3f bitrate=%d kb/s\n", 1984 (double)ic->start_time / AV_TIME_BASE, 1985 (double)ic->duration / AV_TIME_BASE, 1986 ic->bit_rate / 1000); 1987 } 1988#endif 1989} 1990 1991static int has_codec_parameters(AVCodecContext *enc) 1992{ 1993 int val; 1994 switch(enc->codec_type) { 1995 case AVMEDIA_TYPE_AUDIO: 1996 val = enc->sample_rate && enc->channels && enc->sample_fmt != SAMPLE_FMT_NONE; 1997 if(!enc->frame_size && 1998 (enc->codec_id == CODEC_ID_VORBIS || 1999 enc->codec_id == CODEC_ID_AAC || 2000 enc->codec_id == CODEC_ID_MP1 || 2001 enc->codec_id == CODEC_ID_MP2 || 2002 enc->codec_id == CODEC_ID_MP3 || 2003 enc->codec_id == CODEC_ID_SPEEX)) 2004 return 0; 2005 break; 2006 case AVMEDIA_TYPE_VIDEO: 2007 val = enc->width && enc->pix_fmt != PIX_FMT_NONE; 2008 break; 2009 default: 2010 val = 1; 2011 break; 2012 } 2013 return enc->codec_id != CODEC_ID_NONE && val != 0; 2014} 2015 2016static int try_decode_frame(AVStream *st, AVPacket *avpkt) 2017{ 2018 int16_t *samples; 2019 AVCodec *codec; 2020 int got_picture, data_size, ret=0; 2021 AVFrame picture; 2022 2023 if(!st->codec->codec){ 2024 codec = avcodec_find_decoder(st->codec->codec_id); 2025 if (!codec) 2026 return -1; 2027 ret = avcodec_open(st->codec, codec); 2028 if (ret < 0) 2029 return ret; 2030 } 2031 2032 if(!has_codec_parameters(st->codec)){ 2033 switch(st->codec->codec_type) { 2034 case AVMEDIA_TYPE_VIDEO: 2035 avcodec_get_frame_defaults(&picture); 2036 ret = avcodec_decode_video2(st->codec, &picture, 2037 &got_picture, avpkt); 2038 break; 2039 case AVMEDIA_TYPE_AUDIO: 2040 data_size = FFMAX(avpkt->size, AVCODEC_MAX_AUDIO_FRAME_SIZE); 2041 samples = av_malloc(data_size); 2042 if (!samples) 2043 goto fail; 2044 ret = avcodec_decode_audio3(st->codec, samples, 2045 &data_size, avpkt); 2046 av_free(samples); 2047 break; 2048 default: 2049 break; 2050 } 2051 } 2052 fail: 2053 return ret; 2054} 2055 2056unsigned int ff_codec_get_tag(const AVCodecTag *tags, int id) 2057{ 2058 while (tags->id != CODEC_ID_NONE) { 2059 if (tags->id == id) 2060 return tags->tag; 2061 tags++; 2062 } 2063 return 0; 2064} 2065 2066enum CodecID ff_codec_get_id(const AVCodecTag *tags, unsigned int tag) 2067{ 2068 int i; 2069 for(i=0; tags[i].id != CODEC_ID_NONE;i++) { 2070 if(tag == tags[i].tag) 2071 return tags[i].id; 2072 } 2073 for(i=0; tags[i].id != CODEC_ID_NONE; i++) { 2074 if( toupper((tag >> 0)&0xFF) == toupper((tags[i].tag >> 0)&0xFF) 2075 && toupper((tag >> 8)&0xFF) == toupper((tags[i].tag >> 8)&0xFF) 2076 && toupper((tag >>16)&0xFF) == toupper((tags[i].tag >>16)&0xFF) 2077 && toupper((tag >>24)&0xFF) == toupper((tags[i].tag >>24)&0xFF)) 2078 return tags[i].id; 2079 } 2080 return CODEC_ID_NONE; 2081} 2082 2083unsigned int av_codec_get_tag(const AVCodecTag * const *tags, enum CodecID id) 2084{ 2085 int i; 2086 for(i=0; tags && tags[i]; i++){ 2087 int tag= ff_codec_get_tag(tags[i], id); 2088 if(tag) return tag; 2089 } 2090 return 0; 2091} 2092 2093enum CodecID av_codec_get_id(const AVCodecTag * const *tags, unsigned int tag) 2094{ 2095 int i; 2096 for(i=0; tags && tags[i]; i++){ 2097 enum CodecID id= ff_codec_get_id(tags[i], tag); 2098 if(id!=CODEC_ID_NONE) return id; 2099 } 2100 return CODEC_ID_NONE; 2101} 2102 2103static void compute_chapters_end(AVFormatContext *s) 2104{ 2105 unsigned int i; 2106 2107 for (i=0; i+1<s->nb_chapters; i++) 2108 if (s->chapters[i]->end == AV_NOPTS_VALUE) { 2109 assert(s->chapters[i]->start <= s->chapters[i+1]->start); 2110 assert(!av_cmp_q(s->chapters[i]->time_base, s->chapters[i+1]->time_base)); 2111 s->chapters[i]->end = s->chapters[i+1]->start; 2112 } 2113 2114 if (s->nb_chapters && s->chapters[i]->end == AV_NOPTS_VALUE) { 2115 assert(s->start_time != AV_NOPTS_VALUE); 2116 assert(s->duration > 0); 2117 s->chapters[i]->end = av_rescale_q(s->start_time + s->duration, 2118 AV_TIME_BASE_Q, 2119 s->chapters[i]->time_base); 2120 } 2121} 2122 2123#define MAX_STD_TIMEBASES (60*12+5) 2124static int get_std_framerate(int i){ 2125 if(i<60*12) return i*1001; 2126 else return ((const int[]){24,30,60,12,15})[i-60*12]*1000*12; 2127} 2128 2129/* 2130 * Is the time base unreliable. 2131 * This is a heuristic to balance between quick acceptance of the values in 2132 * the headers vs. some extra checks. 2133 * Old DivX and Xvid often have nonsense timebases like 1fps or 2fps. 2134 * MPEG-2 commonly misuses field repeat flags to store different framerates. 2135 * And there are "variable" fps files this needs to detect as well. 2136 */ 2137static int tb_unreliable(AVCodecContext *c){ 2138 if( c->time_base.den >= 101L*c->time_base.num 2139 || c->time_base.den < 5L*c->time_base.num 2140/* || c->codec_tag == AV_RL32("DIVX") 2141 || c->codec_tag == AV_RL32("XVID")*/ 2142 || c->codec_id == CODEC_ID_MPEG2VIDEO 2143 || c->codec_id == CODEC_ID_H264 2144 ) 2145 return 1; 2146 return 0; 2147} 2148 2149int av_find_stream_info(AVFormatContext *ic) 2150{ 2151 int i, count, ret, read_size, j; 2152 AVStream *st; 2153 AVPacket pkt1, *pkt; 2154 int64_t last_dts[MAX_STREAMS]; 2155 int64_t duration_gcd[MAX_STREAMS]={0}; 2156 int duration_count[MAX_STREAMS]={0}; 2157 double (*duration_error)[MAX_STD_TIMEBASES]; 2158 int64_t old_offset = url_ftell(ic->pb); 2159 int64_t codec_info_duration[MAX_STREAMS]={0}; 2160 2161 duration_error = av_mallocz(MAX_STREAMS * sizeof(*duration_error)); 2162 if (!duration_error) return AVERROR(ENOMEM); 2163 2164 for(i=0;i<ic->nb_streams;i++) { 2165 st = ic->streams[i]; 2166 if (st->codec->codec_id == CODEC_ID_AAC) { 2167 st->codec->sample_rate = 0; 2168 st->codec->frame_size = 0; 2169 st->codec->channels = 0; 2170 } 2171 if(st->codec->codec_type == AVMEDIA_TYPE_VIDEO){ 2172/* if(!st->time_base.num) 2173 st->time_base= */ 2174 if(!st->codec->time_base.num) 2175 st->codec->time_base= st->time_base; 2176 } 2177 //only for the split stuff 2178 if (!st->parser && !(ic->flags & AVFMT_FLAG_NOPARSE)) { 2179 st->parser = av_parser_init(st->codec->codec_id); 2180 if(st->need_parsing == AVSTREAM_PARSE_HEADERS && st->parser){ 2181 st->parser->flags |= PARSER_FLAG_COMPLETE_FRAMES; 2182 } 2183 } 2184 assert(!st->codec->codec); 2185 //try to just open decoders, in case this is enough to get parameters 2186 if(!has_codec_parameters(st->codec)){ 2187 AVCodec *codec = avcodec_find_decoder(st->codec->codec_id); 2188 if (codec) 2189 avcodec_open(st->codec, codec); 2190 } 2191 } 2192 2193 for(i=0;i<MAX_STREAMS;i++){ 2194 last_dts[i]= AV_NOPTS_VALUE; 2195 } 2196 2197 count = 0; 2198 read_size = 0; 2199 for(;;) { 2200 if(url_interrupt_cb()){ 2201 ret= AVERROR(EINTR); 2202 av_log(ic, AV_LOG_DEBUG, "interrupted\n"); 2203 break; 2204 } 2205 2206 /* check if one codec still needs to be handled */ 2207 for(i=0;i<ic->nb_streams;i++) { 2208 st = ic->streams[i]; 2209 if (!has_codec_parameters(st->codec)) 2210 break; 2211 /* variable fps and no guess at the real fps */ 2212 if( tb_unreliable(st->codec) && !(st->r_frame_rate.num && st->avg_frame_rate.num) 2213 && duration_count[i]<20 && st->codec->codec_type == AVMEDIA_TYPE_VIDEO) 2214 break; 2215 if(st->parser && st->parser->parser->split && !st->codec->extradata) 2216 break; 2217 if(st->first_dts == AV_NOPTS_VALUE) 2218 break; 2219 } 2220 if (i == ic->nb_streams) { 2221 /* NOTE: if the format has no header, then we need to read 2222 some packets to get most of the streams, so we cannot 2223 stop here */ 2224 if (!(ic->ctx_flags & AVFMTCTX_NOHEADER)) { 2225 /* if we found the info for all the codecs, we can stop */ 2226 ret = count; 2227 av_log(ic, AV_LOG_DEBUG, "All info found\n"); 2228 break; 2229 } 2230 } 2231 /* we did not get all the codec info, but we read too much data */ 2232 if (read_size >= ic->probesize) { 2233 ret = count; 2234 av_log(ic, AV_LOG_DEBUG, "Probe buffer size limit %d reached\n", ic->probesize); 2235 break; 2236 } 2237 2238 /* NOTE: a new stream can be added there if no header in file 2239 (AVFMTCTX_NOHEADER) */ 2240 ret = av_read_frame_internal(ic, &pkt1); 2241 if(ret == AVERROR(EAGAIN)) 2242 continue; 2243 if (ret < 0) { 2244 /* EOF or error */ 2245 ret = -1; /* we could not have all the codec parameters before EOF */ 2246 for(i=0;i<ic->nb_streams;i++) { 2247 st = ic->streams[i]; 2248 if (!has_codec_parameters(st->codec)){ 2249 char buf[256]; 2250 avcodec_string(buf, sizeof(buf), st->codec, 0); 2251 av_log(ic, AV_LOG_WARNING, "Could not find codec parameters (%s)\n", buf); 2252 } else { 2253 ret = 0; 2254 } 2255 } 2256 break; 2257 } 2258 2259 pkt= add_to_pktbuf(&ic->packet_buffer, &pkt1, &ic->packet_buffer_end); 2260 if(av_dup_packet(pkt) < 0) { 2261 av_free(duration_error); 2262 return AVERROR(ENOMEM); 2263 } 2264 2265 read_size += pkt->size; 2266 2267 st = ic->streams[pkt->stream_index]; 2268 if(st->codec_info_nb_frames>1) { 2269 if (st->time_base.den > 0 && av_rescale_q(codec_info_duration[st->index], st->time_base, AV_TIME_BASE_Q) >= ic->max_analyze_duration){ 2270 av_log(ic, AV_LOG_WARNING, "max_analyze_duration reached\n"); 2271 break; 2272 } 2273 codec_info_duration[st->index] += pkt->duration; 2274 } 2275 st->codec_info_nb_frames++; 2276 2277 { 2278 int index= pkt->stream_index; 2279 int64_t last= last_dts[index]; 2280 int64_t duration= pkt->dts - last; 2281 2282 if(pkt->dts != AV_NOPTS_VALUE && last != AV_NOPTS_VALUE && duration>0){ 2283 double dur= duration * av_q2d(st->time_base); 2284 2285// if(st->codec->codec_type == AVMEDIA_TYPE_VIDEO) 2286// av_log(NULL, AV_LOG_ERROR, "%f\n", dur); 2287 if(duration_count[index] < 2) 2288 memset(duration_error[index], 0, sizeof(*duration_error)); 2289 for(i=1; i<MAX_STD_TIMEBASES; i++){ 2290 int framerate= get_std_framerate(i); 2291 int ticks= lrintf(dur*framerate/(1001*12)); 2292 double error= dur - ticks*1001*12/(double)framerate; 2293 duration_error[index][i] += error*error; 2294 } 2295 duration_count[index]++; 2296 // ignore the first 4 values, they might have some random jitter 2297 if (duration_count[index] > 3) 2298 duration_gcd[index] = av_gcd(duration_gcd[index], duration); 2299 } 2300 if(last == AV_NOPTS_VALUE || duration_count[index]<=1) 2301 last_dts[pkt->stream_index]= pkt->dts; 2302 } 2303 if(st->parser && st->parser->parser->split && !st->codec->extradata){ 2304 int i= st->parser->parser->split(st->codec, pkt->data, pkt->size); 2305 if(i){ 2306 st->codec->extradata_size= i; 2307 st->codec->extradata= av_malloc(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE); 2308 memcpy(st->codec->extradata, pkt->data, st->codec->extradata_size); 2309 memset(st->codec->extradata + i, 0, FF_INPUT_BUFFER_PADDING_SIZE); 2310 } 2311 } 2312 2313 /* if still no information, we try to open the codec and to 2314 decompress the frame. We try to avoid that in most cases as 2315 it takes longer and uses more memory. For MPEG-4, we need to 2316 decompress for QuickTime. */ 2317 if (!has_codec_parameters(st->codec)) 2318 try_decode_frame(st, pkt); 2319 2320 count++; 2321 } 2322 2323 // close codecs which were opened in try_decode_frame() 2324 for(i=0;i<ic->nb_streams;i++) { 2325 st = ic->streams[i]; 2326 if(st->codec->codec) 2327 avcodec_close(st->codec); 2328 } 2329 for(i=0;i<ic->nb_streams;i++) { 2330 st = ic->streams[i]; 2331 if(st->codec_info_nb_frames>2 && !st->avg_frame_rate.num && codec_info_duration[i]) 2332 av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den, 2333 (st->codec_info_nb_frames-2)*(int64_t)st->time_base.den, 2334 codec_info_duration[i] *(int64_t)st->time_base.num, 60000); 2335 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) { 2336 if(st->codec->codec_id == CODEC_ID_RAWVIDEO && !st->codec->codec_tag && !st->codec->bits_per_coded_sample) 2337 st->codec->codec_tag= avcodec_pix_fmt_to_codec_tag(st->codec->pix_fmt); 2338 2339 // the check for tb_unreliable() is not completely correct, since this is not about handling 2340 // a unreliable/inexact time base, but a time base that is finer than necessary, as e.g. 2341 // ipmovie.c produces. 2342 if (tb_unreliable(st->codec) && duration_count[i] > 15 && duration_gcd[i] > 1 && !st->r_frame_rate.num) 2343 av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den, st->time_base.den, st->time_base.num * duration_gcd[i], INT_MAX); 2344 if(duration_count[i] && !st->r_frame_rate.num 2345 && tb_unreliable(st->codec) /*&& 2346 //FIXME we should not special-case MPEG-2, but this needs testing with non-MPEG-2 ... 2347 st->time_base.num*duration_sum[i]/duration_count[i]*101LL > st->time_base.den*/){ 2348 int num = 0; 2349 double best_error= 2*av_q2d(st->time_base); 2350 best_error= best_error*best_error*duration_count[i]*1000*12*30; 2351 2352 for(j=1; j<MAX_STD_TIMEBASES; j++){ 2353 double error= duration_error[i][j] * get_std_framerate(j); 2354// if(st->codec->codec_type == AVMEDIA_TYPE_VIDEO) 2355// av_log(NULL, AV_LOG_ERROR, "%f %f\n", get_std_framerate(j) / 12.0/1001, error); 2356 if(error < best_error){ 2357 best_error= error; 2358 num = get_std_framerate(j); 2359 } 2360 } 2361 // do not increase frame rate by more than 1 % in order to match a standard rate. 2362 if (num && (!st->r_frame_rate.num || (double)num/(12*1001) < 1.01 * av_q2d(st->r_frame_rate))) 2363 av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den, num, 12*1001, INT_MAX); 2364 } 2365 2366 if (!st->r_frame_rate.num){ 2367 if( st->codec->time_base.den * (int64_t)st->time_base.num 2368 <= st->codec->time_base.num * st->codec->ticks_per_frame * (int64_t)st->time_base.den){ 2369 st->r_frame_rate.num = st->codec->time_base.den; 2370 st->r_frame_rate.den = st->codec->time_base.num * st->codec->ticks_per_frame; 2371 }else{ 2372 st->r_frame_rate.num = st->time_base.den; 2373 st->r_frame_rate.den = st->time_base.num; 2374 } 2375 } 2376 }else if(st->codec->codec_type == AVMEDIA_TYPE_AUDIO) { 2377 if(!st->codec->bits_per_coded_sample) 2378 st->codec->bits_per_coded_sample= av_get_bits_per_sample(st->codec->codec_id); 2379 } 2380 } 2381 2382 av_estimate_timings(ic, old_offset); 2383 2384 compute_chapters_end(ic); 2385 2386#if 0 2387 /* correct DTS for B-frame streams with no timestamps */ 2388 for(i=0;i<ic->nb_streams;i++) { 2389 st = ic->streams[i]; 2390 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) { 2391 if(b-frames){ 2392 ppktl = &ic->packet_buffer; 2393 while(ppkt1){ 2394 if(ppkt1->stream_index != i) 2395 continue; 2396 if(ppkt1->pkt->dts < 0) 2397 break; 2398 if(ppkt1->pkt->pts != AV_NOPTS_VALUE) 2399 break; 2400 ppkt1->pkt->dts -= delta; 2401 ppkt1= ppkt1->next; 2402 } 2403 if(ppkt1) 2404 continue; 2405 st->cur_dts -= delta; 2406 } 2407 } 2408 } 2409#endif 2410 2411 av_free(duration_error); 2412 2413 return ret; 2414} 2415 2416/*******************************************************/ 2417 2418int av_read_play(AVFormatContext *s) 2419{ 2420 if (s->iformat->read_play) 2421 return s->iformat->read_play(s); 2422 if (s->pb) 2423 return av_url_read_fpause(s->pb, 0); 2424 return AVERROR(ENOSYS); 2425} 2426 2427int av_read_pause(AVFormatContext *s) 2428{ 2429 if (s->iformat->read_pause) 2430 return s->iformat->read_pause(s); 2431 if (s->pb) 2432 return av_url_read_fpause(s->pb, 1); 2433 return AVERROR(ENOSYS); 2434} 2435 2436void av_close_input_stream(AVFormatContext *s) 2437{ 2438 int i; 2439 AVStream *st; 2440 2441 if (s->iformat->read_close) 2442 s->iformat->read_close(s); 2443 for(i=0;i<s->nb_streams;i++) { 2444 /* free all data in a stream component */ 2445 st = s->streams[i]; 2446 if (st->parser) { 2447 av_parser_close(st->parser); 2448 av_free_packet(&st->cur_pkt); 2449 } 2450 av_metadata_free(&st->metadata); 2451 av_free(st->index_entries); 2452 av_free(st->codec->extradata); 2453 av_free(st->codec); 2454#if LIBAVFORMAT_VERSION_INT < (53<<16) 2455 av_free(st->filename); 2456#endif 2457 av_free(st->priv_data); 2458 av_free(st); 2459 } 2460 for(i=s->nb_programs-1; i>=0; i--) { 2461#if LIBAVFORMAT_VERSION_INT < (53<<16) 2462 av_freep(&s->programs[i]->provider_name); 2463 av_freep(&s->programs[i]->name); 2464#endif 2465 av_metadata_free(&s->programs[i]->metadata); 2466 av_freep(&s->programs[i]->stream_index); 2467 av_freep(&s->programs[i]); 2468 } 2469 av_freep(&s->programs); 2470 flush_packet_queue(s); 2471 av_freep(&s->priv_data); 2472 while(s->nb_chapters--) { 2473#if LIBAVFORMAT_VERSION_INT < (53<<16) 2474 av_free(s->chapters[s->nb_chapters]->title); 2475#endif 2476 av_metadata_free(&s->chapters[s->nb_chapters]->metadata); 2477 av_free(s->chapters[s->nb_chapters]); 2478 } 2479 av_freep(&s->chapters); 2480 av_metadata_free(&s->metadata); 2481 av_free(s); 2482} 2483 2484void av_close_input_file(AVFormatContext *s) 2485{ 2486 ByteIOContext *pb = s->iformat->flags & AVFMT_NOFILE ? NULL : s->pb; 2487 av_close_input_stream(s); 2488 if (pb) 2489 url_fclose(pb); 2490} 2491 2492AVStream *av_new_stream(AVFormatContext *s, int id) 2493{ 2494 AVStream *st; 2495 int i; 2496 2497 if (s->nb_streams >= MAX_STREAMS) 2498 return NULL; 2499 2500 st = av_mallocz(sizeof(AVStream)); 2501 if (!st) 2502 return NULL; 2503 2504 st->codec= avcodec_alloc_context(); 2505 if (s->iformat) { 2506 /* no default bitrate if decoding */ 2507 st->codec->bit_rate = 0; 2508 } 2509 st->index = s->nb_streams; 2510 st->id = id; 2511 st->start_time = AV_NOPTS_VALUE; 2512 st->duration = AV_NOPTS_VALUE; 2513 /* we set the current DTS to 0 so that formats without any timestamps 2514 but durations get some timestamps, formats with some unknown 2515 timestamps have their first few packets buffered and the 2516 timestamps corrected before they are returned to the user */ 2517 st->cur_dts = 0; 2518 st->first_dts = AV_NOPTS_VALUE; 2519 st->probe_packets = MAX_PROBE_PACKETS; 2520 2521 /* default pts setting is MPEG-like */ 2522 av_set_pts_info(st, 33, 1, 90000); 2523 st->last_IP_pts = AV_NOPTS_VALUE; 2524 for(i=0; i<MAX_REORDER_DELAY+1; i++) 2525 st->pts_buffer[i]= AV_NOPTS_VALUE; 2526 st->reference_dts = AV_NOPTS_VALUE; 2527 2528 st->sample_aspect_ratio = (AVRational){0,1}; 2529 2530 s->streams[s->nb_streams++] = st; 2531 return st; 2532} 2533 2534AVProgram *av_new_program(AVFormatContext *ac, int id) 2535{ 2536 AVProgram *program=NULL; 2537 int i; 2538 2539#ifdef DEBUG_SI 2540 av_log(ac, AV_LOG_DEBUG, "new_program: id=0x%04x\n", id); 2541#endif 2542 2543 for(i=0; i<ac->nb_programs; i++) 2544 if(ac->programs[i]->id == id) 2545 program = ac->programs[i]; 2546 2547 if(!program){ 2548 program = av_mallocz(sizeof(AVProgram)); 2549 if (!program) 2550 return NULL; 2551 dynarray_add(&ac->programs, &ac->nb_programs, program); 2552 program->discard = AVDISCARD_NONE; 2553 } 2554 program->id = id; 2555 2556 return program; 2557} 2558 2559AVChapter *ff_new_chapter(AVFormatContext *s, int id, AVRational time_base, int64_t start, int64_t end, const char *title) 2560{ 2561 AVChapter *chapter = NULL; 2562 int i; 2563 2564 for(i=0; i<s->nb_chapters; i++) 2565 if(s->chapters[i]->id == id) 2566 chapter = s->chapters[i]; 2567 2568 if(!chapter){ 2569 chapter= av_mallocz(sizeof(AVChapter)); 2570 if(!chapter) 2571 return NULL; 2572 dynarray_add(&s->chapters, &s->nb_chapters, chapter); 2573 } 2574#if LIBAVFORMAT_VERSION_INT < (53<<16) 2575 av_free(chapter->title); 2576#endif 2577 av_metadata_set2(&chapter->metadata, "title", title, 0); 2578 chapter->id = id; 2579 chapter->time_base= time_base; 2580 chapter->start = start; 2581 chapter->end = end; 2582 2583 return chapter; 2584} 2585 2586/************************************************************/ 2587/* output media file */ 2588 2589int av_set_parameters(AVFormatContext *s, AVFormatParameters *ap) 2590{ 2591 int ret; 2592 2593 if (s->oformat->priv_data_size > 0) { 2594 s->priv_data = av_mallocz(s->oformat->priv_data_size); 2595 if (!s->priv_data) 2596 return AVERROR(ENOMEM); 2597 } else 2598 s->priv_data = NULL; 2599 2600 if (s->oformat->set_parameters) { 2601 ret = s->oformat->set_parameters(s, ap); 2602 if (ret < 0) 2603 return ret; 2604 } 2605 return 0; 2606} 2607 2608int av_write_header(AVFormatContext *s) 2609{ 2610 int ret, i; 2611 AVStream *st; 2612 2613 // some sanity checks 2614 if (s->nb_streams == 0) { 2615 av_log(s, AV_LOG_ERROR, "no streams\n"); 2616 return -1; 2617 } 2618 2619 for(i=0;i<s->nb_streams;i++) { 2620 st = s->streams[i]; 2621 2622 switch (st->codec->codec_type) { 2623 case AVMEDIA_TYPE_AUDIO: 2624 if(st->codec->sample_rate<=0){ 2625 av_log(s, AV_LOG_ERROR, "sample rate not set\n"); 2626 return -1; 2627 } 2628 if(!st->codec->block_align) 2629 st->codec->block_align = st->codec->channels * 2630 av_get_bits_per_sample(st->codec->codec_id) >> 3; 2631 break; 2632 case AVMEDIA_TYPE_VIDEO: 2633 if(st->codec->time_base.num<=0 || st->codec->time_base.den<=0){ //FIXME audio too? 2634 av_log(s, AV_LOG_ERROR, "time base not set\n"); 2635 return -1; 2636 } 2637 if((st->codec->width<=0 || st->codec->height<=0) && !(s->oformat->flags & AVFMT_NODIMENSIONS)){ 2638 av_log(s, AV_LOG_ERROR, "dimensions not set\n"); 2639 return -1; 2640 } 2641 if(av_cmp_q(st->sample_aspect_ratio, st->codec->sample_aspect_ratio)){ 2642 av_log(s, AV_LOG_ERROR, "Aspect ratio mismatch between encoder and muxer layer\n"); 2643 return -1; 2644 } 2645 break; 2646 } 2647 2648 if(s->oformat->codec_tag){ 2649 if(st->codec->codec_tag){ 2650 //FIXME 2651 //check that tag + id is in the table 2652 //if neither is in the table -> OK 2653 //if tag is in the table with another id -> FAIL 2654 //if id is in the table with another tag -> FAIL unless strict < ? 2655 }else 2656 st->codec->codec_tag= av_codec_get_tag(s->oformat->codec_tag, st->codec->codec_id); 2657 } 2658 2659 if(s->oformat->flags & AVFMT_GLOBALHEADER && 2660 !(st->codec->flags & CODEC_FLAG_GLOBAL_HEADER)) 2661 av_log(s, AV_LOG_WARNING, "Codec for stream %d does not use global headers but container format requires global headers\n", i); 2662 } 2663 2664 if (!s->priv_data && s->oformat->priv_data_size > 0) { 2665 s->priv_data = av_mallocz(s->oformat->priv_data_size); 2666 if (!s->priv_data) 2667 return AVERROR(ENOMEM); 2668 } 2669 2670#if LIBAVFORMAT_VERSION_MAJOR < 53 2671 ff_metadata_mux_compat(s); 2672#endif 2673 2674 /* set muxer identification string */ 2675 if (!(s->streams[0]->codec->flags & CODEC_FLAG_BITEXACT)) { 2676 AVMetadata *m; 2677 AVMetadataTag *t; 2678 2679 if (!(m = av_mallocz(sizeof(AVMetadata)))) 2680 return AVERROR(ENOMEM); 2681 av_metadata_set2(&m, "encoder", LIBAVFORMAT_IDENT, 0); 2682 metadata_conv(&m, s->oformat->metadata_conv, NULL); 2683 if ((t = av_metadata_get(m, "", NULL, AV_METADATA_IGNORE_SUFFIX))) 2684 av_metadata_set2(&s->metadata, t->key, t->value, 0); 2685 av_metadata_free(&m); 2686 } 2687 2688 if(s->oformat->write_header){ 2689 ret = s->oformat->write_header(s); 2690 if (ret < 0) 2691 return ret; 2692 } 2693 2694 /* init PTS generation */ 2695 for(i=0;i<s->nb_streams;i++) { 2696 int64_t den = AV_NOPTS_VALUE; 2697 st = s->streams[i]; 2698 2699 switch (st->codec->codec_type) { 2700 case AVMEDIA_TYPE_AUDIO: 2701 den = (int64_t)st->time_base.num * st->codec->sample_rate; 2702 break; 2703 case AVMEDIA_TYPE_VIDEO: 2704 den = (int64_t)st->time_base.num * st->codec->time_base.den; 2705 break; 2706 default: 2707 break; 2708 } 2709 if (den != AV_NOPTS_VALUE) { 2710 if (den <= 0) 2711 return AVERROR_INVALIDDATA; 2712 av_frac_init(&st->pts, 0, 0, den); 2713 } 2714 } 2715 return 0; 2716} 2717 2718//FIXME merge with compute_pkt_fields 2719static int compute_pkt_fields2(AVFormatContext *s, AVStream *st, AVPacket *pkt){ 2720 int delay = FFMAX(st->codec->has_b_frames, !!st->codec->max_b_frames); 2721 int num, den, frame_size, i; 2722 2723// av_log(s, AV_LOG_DEBUG, "av_write_frame: pts:%"PRId64" dts:%"PRId64" cur_dts:%"PRId64" b:%d size:%d st:%d\n", pkt->pts, pkt->dts, st->cur_dts, delay, pkt->size, pkt->stream_index); 2724 2725/* if(pkt->pts == AV_NOPTS_VALUE && pkt->dts == AV_NOPTS_VALUE) 2726 return -1;*/ 2727 2728 /* duration field */ 2729 if (pkt->duration == 0) { 2730 compute_frame_duration(&num, &den, st, NULL, pkt); 2731 if (den && num) { 2732 pkt->duration = av_rescale(1, num * (int64_t)st->time_base.den * st->codec->ticks_per_frame, den * (int64_t)st->time_base.num); 2733 } 2734 } 2735 2736 if(pkt->pts == AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE && delay==0) 2737 pkt->pts= pkt->dts; 2738 2739 //XXX/FIXME this is a temporary hack until all encoders output pts 2740 if((pkt->pts == 0 || pkt->pts == AV_NOPTS_VALUE) && pkt->dts == AV_NOPTS_VALUE && !delay){ 2741 pkt->dts= 2742// pkt->pts= st->cur_dts; 2743 pkt->pts= st->pts.val; 2744 } 2745 2746 //calculate dts from pts 2747 if(pkt->pts != AV_NOPTS_VALUE && pkt->dts == AV_NOPTS_VALUE && delay <= MAX_REORDER_DELAY){ 2748 st->pts_buffer[0]= pkt->pts; 2749 for(i=1; i<delay+1 && st->pts_buffer[i] == AV_NOPTS_VALUE; i++) 2750 st->pts_buffer[i]= pkt->pts + (i-delay-1) * pkt->duration; 2751 for(i=0; i<delay && st->pts_buffer[i] > st->pts_buffer[i+1]; i++) 2752 FFSWAP(int64_t, st->pts_buffer[i], st->pts_buffer[i+1]); 2753 2754 pkt->dts= st->pts_buffer[0]; 2755 } 2756 2757 if(st->cur_dts && st->cur_dts != AV_NOPTS_VALUE && st->cur_dts >= pkt->dts){ 2758 av_log(s, AV_LOG_ERROR, 2759 "st:%d error, non monotone timestamps %"PRId64" >= %"PRId64"\n", 2760 st->index, st->cur_dts, pkt->dts); 2761 return -1; 2762 } 2763 if(pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE && pkt->pts < pkt->dts){ 2764 av_log(s, AV_LOG_ERROR, "st:%d error, pts < dts\n", st->index); 2765 return -1; 2766 } 2767 2768// av_log(s, AV_LOG_DEBUG, "av_write_frame: pts2:%"PRId64" dts2:%"PRId64"\n", pkt->pts, pkt->dts); 2769 st->cur_dts= pkt->dts; 2770 st->pts.val= pkt->dts; 2771 2772 /* update pts */ 2773 switch (st->codec->codec_type) { 2774 case AVMEDIA_TYPE_AUDIO: 2775 frame_size = get_audio_frame_size(st->codec, pkt->size); 2776 2777 /* HACK/FIXME, we skip the initial 0 size packets as they are most 2778 likely equal to the encoder delay, but it would be better if we 2779 had the real timestamps from the encoder */ 2780 if (frame_size >= 0 && (pkt->size || st->pts.num!=st->pts.den>>1 || st->pts.val)) { 2781 av_frac_add(&st->pts, (int64_t)st->time_base.den * frame_size); 2782 } 2783 break; 2784 case AVMEDIA_TYPE_VIDEO: 2785 av_frac_add(&st->pts, (int64_t)st->time_base.den * st->codec->time_base.num); 2786 break; 2787 default: 2788 break; 2789 } 2790 return 0; 2791} 2792 2793int av_write_frame(AVFormatContext *s, AVPacket *pkt) 2794{ 2795 int ret = compute_pkt_fields2(s, s->streams[pkt->stream_index], pkt); 2796 2797 if(ret<0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS)) 2798 return ret; 2799 2800 ret= s->oformat->write_packet(s, pkt); 2801 if(!ret) 2802 ret= url_ferror(s->pb); 2803 return ret; 2804} 2805 2806void ff_interleave_add_packet(AVFormatContext *s, AVPacket *pkt, 2807 int (*compare)(AVFormatContext *, AVPacket *, AVPacket *)) 2808{ 2809 AVPacketList **next_point, *this_pktl; 2810 2811 this_pktl = av_mallocz(sizeof(AVPacketList)); 2812 this_pktl->pkt= *pkt; 2813 pkt->destruct= NULL; // do not free original but only the copy 2814 av_dup_packet(&this_pktl->pkt); // duplicate the packet if it uses non-alloced memory 2815 2816 if(s->streams[pkt->stream_index]->last_in_packet_buffer){ 2817 next_point = &(s->streams[pkt->stream_index]->last_in_packet_buffer->next); 2818 }else 2819 next_point = &s->packet_buffer; 2820 2821 if(*next_point){ 2822 if(compare(s, &s->packet_buffer_end->pkt, pkt)){ 2823 while(!compare(s, &(*next_point)->pkt, pkt)){ 2824 next_point= &(*next_point)->next; 2825 } 2826 goto next_non_null; 2827 }else{ 2828 next_point = &(s->packet_buffer_end->next); 2829 } 2830 } 2831 assert(!*next_point); 2832 2833 s->packet_buffer_end= this_pktl; 2834next_non_null: 2835 2836 this_pktl->next= *next_point; 2837 2838 s->streams[pkt->stream_index]->last_in_packet_buffer= 2839 *next_point= this_pktl; 2840} 2841 2842int ff_interleave_compare_dts(AVFormatContext *s, AVPacket *next, AVPacket *pkt) 2843{ 2844 AVStream *st = s->streams[ pkt ->stream_index]; 2845 AVStream *st2= s->streams[ next->stream_index]; 2846 int64_t a= st2->time_base.num * (int64_t)st ->time_base.den; 2847 int64_t b= st ->time_base.num * (int64_t)st2->time_base.den; 2848 return av_rescale_rnd(pkt->dts, b, a, AV_ROUND_DOWN) < next->dts; 2849} 2850 2851int av_interleave_packet_per_dts(AVFormatContext *s, AVPacket *out, AVPacket *pkt, int flush){ 2852 AVPacketList *pktl; 2853 int stream_count=0; 2854 int i; 2855 2856 if(pkt){ 2857 ff_interleave_add_packet(s, pkt, ff_interleave_compare_dts); 2858 } 2859 2860 for(i=0; i < s->nb_streams; i++) 2861 stream_count+= !!s->streams[i]->last_in_packet_buffer; 2862 2863 if(stream_count && (s->nb_streams == stream_count || flush)){ 2864 pktl= s->packet_buffer; 2865 *out= pktl->pkt; 2866 2867 s->packet_buffer= pktl->next; 2868 if(!s->packet_buffer) 2869 s->packet_buffer_end= NULL; 2870 2871 if(s->streams[out->stream_index]->last_in_packet_buffer == pktl) 2872 s->streams[out->stream_index]->last_in_packet_buffer= NULL; 2873 av_freep(&pktl); 2874 return 1; 2875 }else{ 2876 av_init_packet(out); 2877 return 0; 2878 } 2879} 2880 2881/** 2882 * Interleaves an AVPacket correctly so it can be muxed. 2883 * @param out the interleaved packet will be output here 2884 * @param in the input packet 2885 * @param flush 1 if no further packets are available as input and all 2886 * remaining packets should be output 2887 * @return 1 if a packet was output, 0 if no packet could be output, 2888 * < 0 if an error occurred 2889 */ 2890static int av_interleave_packet(AVFormatContext *s, AVPacket *out, AVPacket *in, int flush){ 2891 if(s->oformat->interleave_packet) 2892 return s->oformat->interleave_packet(s, out, in, flush); 2893 else 2894 return av_interleave_packet_per_dts(s, out, in, flush); 2895} 2896 2897int av_interleaved_write_frame(AVFormatContext *s, AVPacket *pkt){ 2898 AVStream *st= s->streams[ pkt->stream_index]; 2899 2900 //FIXME/XXX/HACK drop zero sized packets 2901 if(st->codec->codec_type == AVMEDIA_TYPE_AUDIO && pkt->size==0) 2902 return 0; 2903 2904//av_log(NULL, AV_LOG_DEBUG, "av_interleaved_write_frame %d %"PRId64" %"PRId64"\n", pkt->size, pkt->dts, pkt->pts); 2905 if(compute_pkt_fields2(s, st, pkt) < 0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS)) 2906 return -1; 2907 2908 if(pkt->dts == AV_NOPTS_VALUE && !(s->oformat->flags & AVFMT_NOTIMESTAMPS)) 2909 return -1; 2910 2911 for(;;){ 2912 AVPacket opkt; 2913 int ret= av_interleave_packet(s, &opkt, pkt, 0); 2914 if(ret<=0) //FIXME cleanup needed for ret<0 ? 2915 return ret; 2916 2917 ret= s->oformat->write_packet(s, &opkt); 2918 2919 av_free_packet(&opkt); 2920 pkt= NULL; 2921 2922 if(ret<0) 2923 return ret; 2924 if(url_ferror(s->pb)) 2925 return url_ferror(s->pb); 2926 } 2927} 2928 2929int av_write_trailer(AVFormatContext *s) 2930{ 2931 int ret, i; 2932 2933 for(;;){ 2934 AVPacket pkt; 2935 ret= av_interleave_packet(s, &pkt, NULL, 1); 2936 if(ret<0) //FIXME cleanup needed for ret<0 ? 2937 goto fail; 2938 if(!ret) 2939 break; 2940 2941 ret= s->oformat->write_packet(s, &pkt); 2942 2943 av_free_packet(&pkt); 2944 2945 if(ret<0) 2946 goto fail; 2947 if(url_ferror(s->pb)) 2948 goto fail; 2949 } 2950 2951 if(s->oformat->write_trailer) 2952 ret = s->oformat->write_trailer(s); 2953fail: 2954 if(ret == 0) 2955 ret=url_ferror(s->pb); 2956 for(i=0;i<s->nb_streams;i++) { 2957 av_freep(&s->streams[i]->priv_data); 2958 av_freep(&s->streams[i]->index_entries); 2959 } 2960 av_freep(&s->priv_data); 2961 return ret; 2962} 2963 2964void ff_program_add_stream_index(AVFormatContext *ac, int progid, unsigned int idx) 2965{ 2966 int i, j; 2967 AVProgram *program=NULL; 2968 void *tmp; 2969 2970 if (idx >= ac->nb_streams) { 2971 av_log(ac, AV_LOG_ERROR, "stream index %d is not valid\n", idx); 2972 return; 2973 } 2974 2975 for(i=0; i<ac->nb_programs; i++){ 2976 if(ac->programs[i]->id != progid) 2977 continue; 2978 program = ac->programs[i]; 2979 for(j=0; j<program->nb_stream_indexes; j++) 2980 if(program->stream_index[j] == idx) 2981 return; 2982 2983 tmp = av_realloc(program->stream_index, sizeof(unsigned int)*(program->nb_stream_indexes+1)); 2984 if(!tmp) 2985 return; 2986 program->stream_index = tmp; 2987 program->stream_index[program->nb_stream_indexes++] = idx; 2988 return; 2989 } 2990} 2991 2992static void print_fps(double d, const char *postfix){ 2993 uint64_t v= lrintf(d*100); 2994 if (v% 100 ) av_log(NULL, AV_LOG_INFO, ", %3.2f %s", d, postfix); 2995 else if(v%(100*1000)) av_log(NULL, AV_LOG_INFO, ", %1.0f %s", d, postfix); 2996 else av_log(NULL, AV_LOG_INFO, ", %1.0fk %s", d/1000, postfix); 2997} 2998 2999static void dump_metadata(void *ctx, AVMetadata *m, const char *indent) 3000{ 3001 if(m && !(m->count == 1 && av_metadata_get(m, "language", NULL, 0))){ 3002 AVMetadataTag *tag=NULL; 3003 3004 av_log(ctx, AV_LOG_INFO, "%sMetadata:\n", indent); 3005 while((tag=av_metadata_get(m, "", tag, AV_METADATA_IGNORE_SUFFIX))) { 3006 if(strcmp("language", tag->key)) 3007 av_log(ctx, AV_LOG_INFO, "%s %-16s: %s\n", indent, tag->key, tag->value); 3008 } 3009 } 3010} 3011 3012/* "user interface" functions */ 3013static void dump_stream_format(AVFormatContext *ic, int i, int index, int is_output) 3014{ 3015 char buf[256]; 3016 int flags = (is_output ? ic->oformat->flags : ic->iformat->flags); 3017 AVStream *st = ic->streams[i]; 3018 int g = av_gcd(st->time_base.num, st->time_base.den); 3019 AVMetadataTag *lang = av_metadata_get(st->metadata, "language", NULL, 0); 3020 avcodec_string(buf, sizeof(buf), st->codec, is_output); 3021 av_log(NULL, AV_LOG_INFO, " Stream #%d.%d", index, i); 3022 /* the pid is an important information, so we display it */ 3023 /* XXX: add a generic system */ 3024 if (flags & AVFMT_SHOW_IDS) 3025 av_log(NULL, AV_LOG_INFO, "[0x%x]", st->id); 3026 if (lang) 3027 av_log(NULL, AV_LOG_INFO, "(%s)", lang->value); 3028 av_log(NULL, AV_LOG_DEBUG, ", %d, %d/%d", st->codec_info_nb_frames, st->time_base.num/g, st->time_base.den/g); 3029 av_log(NULL, AV_LOG_INFO, ": %s", buf); 3030 if (st->sample_aspect_ratio.num && // default 3031 av_cmp_q(st->sample_aspect_ratio, st->codec->sample_aspect_ratio)) { 3032 AVRational display_aspect_ratio; 3033 av_reduce(&display_aspect_ratio.num, &display_aspect_ratio.den, 3034 st->codec->width*st->sample_aspect_ratio.num, 3035 st->codec->height*st->sample_aspect_ratio.den, 3036 1024*1024); 3037 av_log(NULL, AV_LOG_INFO, ", PAR %d:%d DAR %d:%d", 3038 st->sample_aspect_ratio.num, st->sample_aspect_ratio.den, 3039 display_aspect_ratio.num, display_aspect_ratio.den); 3040 } 3041 if(st->codec->codec_type == AVMEDIA_TYPE_VIDEO){ 3042 if(st->avg_frame_rate.den && st->avg_frame_rate.num) 3043 print_fps(av_q2d(st->avg_frame_rate), "fps"); 3044 if(st->r_frame_rate.den && st->r_frame_rate.num) 3045 print_fps(av_q2d(st->r_frame_rate), "tbr"); 3046 if(st->time_base.den && st->time_base.num) 3047 print_fps(1/av_q2d(st->time_base), "tbn"); 3048 if(st->codec->time_base.den && st->codec->time_base.num) 3049 print_fps(1/av_q2d(st->codec->time_base), "tbc"); 3050 } 3051 av_log(NULL, AV_LOG_INFO, "\n"); 3052 dump_metadata(NULL, st->metadata, " "); 3053} 3054 3055void dump_format(AVFormatContext *ic, 3056 int index, 3057 const char *url, 3058 int is_output) 3059{ 3060 int i; 3061 uint8_t *printed = av_mallocz(ic->nb_streams); 3062 if (ic->nb_streams && !printed) 3063 return; 3064 3065 av_log(NULL, AV_LOG_INFO, "%s #%d, %s, %s '%s':\n", 3066 is_output ? "Output" : "Input", 3067 index, 3068 is_output ? ic->oformat->name : ic->iformat->name, 3069 is_output ? "to" : "from", url); 3070 dump_metadata(NULL, ic->metadata, " "); 3071 if (!is_output) { 3072 av_log(NULL, AV_LOG_INFO, " Duration: "); 3073 if (ic->duration != AV_NOPTS_VALUE) { 3074 int hours, mins, secs, us; 3075 secs = ic->duration / AV_TIME_BASE; 3076 us = ic->duration % AV_TIME_BASE; 3077 mins = secs / 60; 3078 secs %= 60; 3079 hours = mins / 60; 3080 mins %= 60; 3081 av_log(NULL, AV_LOG_INFO, "%02d:%02d:%02d.%02d", hours, mins, secs, 3082 (100 * us) / AV_TIME_BASE); 3083 } else { 3084 av_log(NULL, AV_LOG_INFO, "N/A"); 3085 } 3086 if (ic->start_time != AV_NOPTS_VALUE) { 3087 int secs, us; 3088 av_log(NULL, AV_LOG_INFO, ", start: "); 3089 secs = ic->start_time / AV_TIME_BASE; 3090 us = ic->start_time % AV_TIME_BASE; 3091 av_log(NULL, AV_LOG_INFO, "%d.%06d", 3092 secs, (int)av_rescale(us, 1000000, AV_TIME_BASE)); 3093 } 3094 av_log(NULL, AV_LOG_INFO, ", bitrate: "); 3095 if (ic->bit_rate) { 3096 av_log(NULL, AV_LOG_INFO,"%d kb/s", ic->bit_rate / 1000); 3097 } else { 3098 av_log(NULL, AV_LOG_INFO, "N/A"); 3099 } 3100 av_log(NULL, AV_LOG_INFO, "\n"); 3101 } 3102 for (i = 0; i < ic->nb_chapters; i++) { 3103 AVChapter *ch = ic->chapters[i]; 3104 av_log(NULL, AV_LOG_INFO, " Chapter #%d.%d: ", index, i); 3105 av_log(NULL, AV_LOG_INFO, "start %f, ", ch->start * av_q2d(ch->time_base)); 3106 av_log(NULL, AV_LOG_INFO, "end %f\n", ch->end * av_q2d(ch->time_base)); 3107 3108 dump_metadata(NULL, ch->metadata, " "); 3109 } 3110 if(ic->nb_programs) { 3111 int j, k, total = 0; 3112 for(j=0; j<ic->nb_programs; j++) { 3113 AVMetadataTag *name = av_metadata_get(ic->programs[j]->metadata, 3114 "name", NULL, 0); 3115 av_log(NULL, AV_LOG_INFO, " Program %d %s\n", ic->programs[j]->id, 3116 name ? name->value : ""); 3117 dump_metadata(NULL, ic->programs[j]->metadata, " "); 3118 for(k=0; k<ic->programs[j]->nb_stream_indexes; k++) { 3119 dump_stream_format(ic, ic->programs[j]->stream_index[k], index, is_output); 3120 printed[ic->programs[j]->stream_index[k]] = 1; 3121 } 3122 total += ic->programs[j]->nb_stream_indexes; 3123 } 3124 if (total < ic->nb_streams) 3125 av_log(NULL, AV_LOG_INFO, " No Program\n"); 3126 } 3127 for(i=0;i<ic->nb_streams;i++) 3128 if (!printed[i]) 3129 dump_stream_format(ic, i, index, is_output); 3130 3131 av_free(printed); 3132} 3133 3134#if LIBAVFORMAT_VERSION_MAJOR < 53 3135int parse_image_size(int *width_ptr, int *height_ptr, const char *str) 3136{ 3137 return av_parse_video_frame_size(width_ptr, height_ptr, str); 3138} 3139 3140int parse_frame_rate(int *frame_rate_num, int *frame_rate_den, const char *arg) 3141{ 3142 AVRational frame_rate; 3143 int ret = av_parse_video_frame_rate(&frame_rate, arg); 3144 *frame_rate_num= frame_rate.num; 3145 *frame_rate_den= frame_rate.den; 3146 return ret; 3147} 3148#endif 3149 3150int64_t av_gettime(void) 3151{ 3152 struct timeval tv; 3153 gettimeofday(&tv,NULL); 3154 return (int64_t)tv.tv_sec * 1000000 + tv.tv_usec; 3155} 3156 3157uint64_t ff_ntp_time(void) 3158{ 3159 return (av_gettime() / 1000) * 1000 + NTP_OFFSET_US; 3160} 3161 3162int64_t parse_date(const char *datestr, int duration) 3163{ 3164 const char *p; 3165 int64_t t; 3166 struct tm dt; 3167 int i; 3168 static const char * const date_fmt[] = { 3169 "%Y-%m-%d", 3170 "%Y%m%d", 3171 }; 3172 static const char * const time_fmt[] = { 3173 "%H:%M:%S", 3174 "%H%M%S", 3175 }; 3176 const char *q; 3177 int is_utc, len; 3178 char lastch; 3179 int negative = 0; 3180 3181#undef time 3182 time_t now = time(0); 3183 3184 len = strlen(datestr); 3185 if (len > 0) 3186 lastch = datestr[len - 1]; 3187 else 3188 lastch = '\0'; 3189 is_utc = (lastch == 'z' || lastch == 'Z'); 3190 3191 memset(&dt, 0, sizeof(dt)); 3192 3193 p = datestr; 3194 q = NULL; 3195 if (!duration) { 3196 if (!strncasecmp(datestr, "now", len)) 3197 return (int64_t) now * 1000000; 3198 3199 /* parse the year-month-day part */ 3200 for (i = 0; i < FF_ARRAY_ELEMS(date_fmt); i++) { 3201 q = small_strptime(p, date_fmt[i], &dt); 3202 if (q) { 3203 break; 3204 } 3205 } 3206 3207 /* if the year-month-day part is missing, then take the 3208 * current year-month-day time */ 3209 if (!q) { 3210 if (is_utc) { 3211 dt = *gmtime(&now); 3212 } else { 3213 dt = *localtime(&now); 3214 } 3215 dt.tm_hour = dt.tm_min = dt.tm_sec = 0; 3216 } else { 3217 p = q; 3218 } 3219 3220 if (*p == 'T' || *p == 't' || *p == ' ') 3221 p++; 3222 3223 /* parse the hour-minute-second part */ 3224 for (i = 0; i < FF_ARRAY_ELEMS(time_fmt); i++) { 3225 q = small_strptime(p, time_fmt[i], &dt); 3226 if (q) { 3227 break; 3228 } 3229 } 3230 } else { 3231 /* parse datestr as a duration */ 3232 if (p[0] == '-') { 3233 negative = 1; 3234 ++p; 3235 } 3236 /* parse datestr as HH:MM:SS */ 3237 q = small_strptime(p, time_fmt[0], &dt); 3238 if (!q) { 3239 /* parse datestr as S+ */ 3240 dt.tm_sec = strtol(p, (char **)&q, 10); 3241 if (q == p) 3242 /* the parsing didn't succeed */ 3243 return INT64_MIN; 3244 dt.tm_min = 0; 3245 dt.tm_hour = 0; 3246 } 3247 } 3248 3249 /* Now we have all the fields that we can get */ 3250 if (!q) { 3251 return INT64_MIN; 3252 } 3253 3254 if (duration) { 3255 t = dt.tm_hour * 3600 + dt.tm_min * 60 + dt.tm_sec; 3256 } else { 3257 dt.tm_isdst = -1; /* unknown */ 3258 if (is_utc) { 3259 t = mktimegm(&dt); 3260 } else { 3261 t = mktime(&dt); 3262 } 3263 } 3264 3265 t *= 1000000; 3266 3267 /* parse the .m... part */ 3268 if (*q == '.') { 3269 int val, n; 3270 q++; 3271 for (val = 0, n = 100000; n >= 1; n /= 10, q++) { 3272 if (!isdigit(*q)) 3273 break; 3274 val += n * (*q - '0'); 3275 } 3276 t += val; 3277 } 3278 return negative ? -t : t; 3279} 3280 3281int find_info_tag(char *arg, int arg_size, const char *tag1, const char *info) 3282{ 3283 const char *p; 3284 char tag[128], *q; 3285 3286 p = info; 3287 if (*p == '?') 3288 p++; 3289 for(;;) { 3290 q = tag; 3291 while (*p != '\0' && *p != '=' && *p != '&') { 3292 if ((q - tag) < sizeof(tag) - 1) 3293 *q++ = *p; 3294 p++; 3295 } 3296 *q = '\0'; 3297 q = arg; 3298 if (*p == '=') { 3299 p++; 3300 while (*p != '&' && *p != '\0') { 3301 if ((q - arg) < arg_size - 1) { 3302 if (*p == '+') 3303 *q++ = ' '; 3304 else 3305 *q++ = *p; 3306 } 3307 p++; 3308 } 3309 *q = '\0'; 3310 } 3311 if (!strcmp(tag, tag1)) 3312 return 1; 3313 if (*p != '&') 3314 break; 3315 p++; 3316 } 3317 return 0; 3318} 3319 3320int av_get_frame_filename(char *buf, int buf_size, 3321 const char *path, int number) 3322{ 3323 const char *p; 3324 char *q, buf1[20], c; 3325 int nd, len, percentd_found; 3326 3327 q = buf; 3328 p = path; 3329 percentd_found = 0; 3330 for(;;) { 3331 c = *p++; 3332 if (c == '\0') 3333 break; 3334 if (c == '%') { 3335 do { 3336 nd = 0; 3337 while (isdigit(*p)) { 3338 nd = nd * 10 + *p++ - '0'; 3339 } 3340 c = *p++; 3341 } while (isdigit(c)); 3342 3343 switch(c) { 3344 case '%': 3345 goto addchar; 3346 case 'd': 3347 if (percentd_found) 3348 goto fail; 3349 percentd_found = 1; 3350 snprintf(buf1, sizeof(buf1), "%0*d", nd, number); 3351 len = strlen(buf1); 3352 if ((q - buf + len) > buf_size - 1) 3353 goto fail; 3354 memcpy(q, buf1, len); 3355 q += len; 3356 break; 3357 default: 3358 goto fail; 3359 } 3360 } else { 3361 addchar: 3362 if ((q - buf) < buf_size - 1) 3363 *q++ = c; 3364 } 3365 } 3366 if (!percentd_found) 3367 goto fail; 3368 *q = '\0'; 3369 return 0; 3370 fail: 3371 *q = '\0'; 3372 return -1; 3373} 3374 3375static void hex_dump_internal(void *avcl, FILE *f, int level, uint8_t *buf, int size) 3376{ 3377 int len, i, j, c; 3378#undef fprintf 3379#define PRINT(...) do { if (!f) av_log(avcl, level, __VA_ARGS__); else fprintf(f, __VA_ARGS__); } while(0) 3380 3381 for(i=0;i<size;i+=16) { 3382 len = size - i; 3383 if (len > 16) 3384 len = 16; 3385 PRINT("%08x ", i); 3386 for(j=0;j<16;j++) { 3387 if (j < len) 3388 PRINT(" %02x", buf[i+j]); 3389 else 3390 PRINT(" "); 3391 } 3392 PRINT(" "); 3393 for(j=0;j<len;j++) { 3394 c = buf[i+j]; 3395 if (c < ' ' || c > '~') 3396 c = '.'; 3397 PRINT("%c", c); 3398 } 3399 PRINT("\n"); 3400 } 3401#undef PRINT 3402} 3403 3404void av_hex_dump(FILE *f, uint8_t *buf, int size) 3405{ 3406 hex_dump_internal(NULL, f, 0, buf, size); 3407} 3408 3409void av_hex_dump_log(void *avcl, int level, uint8_t *buf, int size) 3410{ 3411 hex_dump_internal(avcl, NULL, level, buf, size); 3412} 3413 3414 //FIXME needs to know the time_base 3415static void pkt_dump_internal(void *avcl, FILE *f, int level, AVPacket *pkt, int dump_payload) 3416{ 3417#undef fprintf 3418#define PRINT(...) do { if (!f) av_log(avcl, level, __VA_ARGS__); else fprintf(f, __VA_ARGS__); } while(0) 3419 PRINT("stream #%d:\n", pkt->stream_index); 3420 PRINT(" keyframe=%d\n", ((pkt->flags & AV_PKT_FLAG_KEY) != 0)); 3421 PRINT(" duration=%0.3f\n", (double)pkt->duration / AV_TIME_BASE); 3422 /* DTS is _always_ valid after av_read_frame() */ 3423 PRINT(" dts="); 3424 if (pkt->dts == AV_NOPTS_VALUE) 3425 PRINT("N/A"); 3426 else 3427 PRINT("%0.3f", (double)pkt->dts / AV_TIME_BASE); 3428 /* PTS may not be known if B-frames are present. */ 3429 PRINT(" pts="); 3430 if (pkt->pts == AV_NOPTS_VALUE) 3431 PRINT("N/A"); 3432 else 3433 PRINT("%0.3f", (double)pkt->pts / AV_TIME_BASE); 3434 PRINT("\n"); 3435 PRINT(" size=%d\n", pkt->size); 3436#undef PRINT 3437 if (dump_payload) 3438 av_hex_dump(f, pkt->data, pkt->size); 3439} 3440 3441void av_pkt_dump(FILE *f, AVPacket *pkt, int dump_payload) 3442{ 3443 pkt_dump_internal(NULL, f, 0, pkt, dump_payload); 3444} 3445 3446void av_pkt_dump_log(void *avcl, int level, AVPacket *pkt, int dump_payload) 3447{ 3448 pkt_dump_internal(avcl, NULL, level, pkt, dump_payload); 3449} 3450 3451void ff_url_split(char *proto, int proto_size, 3452 char *authorization, int authorization_size, 3453 char *hostname, int hostname_size, 3454 int *port_ptr, 3455 char *path, int path_size, 3456 const char *url) 3457{ 3458 const char *p, *ls, *at, *col, *brk; 3459 3460 if (port_ptr) *port_ptr = -1; 3461 if (proto_size > 0) proto[0] = 0; 3462 if (authorization_size > 0) authorization[0] = 0; 3463 if (hostname_size > 0) hostname[0] = 0; 3464 if (path_size > 0) path[0] = 0; 3465 3466 /* parse protocol */ 3467 if ((p = strchr(url, ':'))) { 3468 av_strlcpy(proto, url, FFMIN(proto_size, p + 1 - url)); 3469 p++; /* skip ':' */ 3470 if (*p == '/') p++; 3471 if (*p == '/') p++; 3472 } else { 3473 /* no protocol means plain filename */ 3474 av_strlcpy(path, url, path_size); 3475 return; 3476 } 3477 3478 /* separate path from hostname */ 3479 ls = strchr(p, '/'); 3480 if(!ls) 3481 ls = strchr(p, '?'); 3482 if(ls) 3483 av_strlcpy(path, ls, path_size); 3484 else 3485 ls = &p[strlen(p)]; // XXX 3486 3487 /* the rest is hostname, use that to parse auth/port */ 3488 if (ls != p) { 3489 /* authorization (user[:pass]@hostname) */ 3490 if ((at = strchr(p, '@')) && at < ls) { 3491 av_strlcpy(authorization, p, 3492 FFMIN(authorization_size, at + 1 - p)); 3493 p = at + 1; /* skip '@' */ 3494 } 3495 3496 if (*p == '[' && (brk = strchr(p, ']')) && brk < ls) { 3497 /* [host]:port */ 3498 av_strlcpy(hostname, p + 1, 3499 FFMIN(hostname_size, brk - p)); 3500 if (brk[1] == ':' && port_ptr) 3501 *port_ptr = atoi(brk + 2); 3502 } else if ((col = strchr(p, ':')) && col < ls) { 3503 av_strlcpy(hostname, p, 3504 FFMIN(col + 1 - p, hostname_size)); 3505 if (port_ptr) *port_ptr = atoi(col + 1); 3506 } else 3507 av_strlcpy(hostname, p, 3508 FFMIN(ls + 1 - p, hostname_size)); 3509 } 3510} 3511 3512char *ff_data_to_hex(char *buff, const uint8_t *src, int s, int lowercase) 3513{ 3514 int i; 3515 static const char hex_table_uc[16] = { '0', '1', '2', '3', 3516 '4', '5', '6', '7', 3517 '8', '9', 'A', 'B', 3518 'C', 'D', 'E', 'F' }; 3519 static const char hex_table_lc[16] = { '0', '1', '2', '3', 3520 '4', '5', '6', '7', 3521 '8', '9', 'a', 'b', 3522 'c', 'd', 'e', 'f' }; 3523 const char *hex_table = lowercase ? hex_table_lc : hex_table_uc; 3524 3525 for(i = 0; i < s; i++) { 3526 buff[i * 2] = hex_table[src[i] >> 4]; 3527 buff[i * 2 + 1] = hex_table[src[i] & 0xF]; 3528 } 3529 3530 return buff; 3531} 3532 3533void av_set_pts_info(AVStream *s, int pts_wrap_bits, 3534 unsigned int pts_num, unsigned int pts_den) 3535{ 3536 s->pts_wrap_bits = pts_wrap_bits; 3537 3538 if(av_reduce(&s->time_base.num, &s->time_base.den, pts_num, pts_den, INT_MAX)){ 3539 if(s->time_base.num != pts_num) 3540 av_log(NULL, AV_LOG_DEBUG, "st:%d removing common factor %d from timebase\n", s->index, pts_num/s->time_base.num); 3541 }else 3542 av_log(NULL, AV_LOG_WARNING, "st:%d has too large timebase, reducing\n", s->index); 3543 3544 if(!s->time_base.num || !s->time_base.den) 3545 s->time_base.num= s->time_base.den= 0; 3546} 3547 3548int ff_url_join(char *str, int size, const char *proto, 3549 const char *authorization, const char *hostname, 3550 int port, const char *fmt, ...) 3551{ 3552#if CONFIG_NETWORK 3553 struct addrinfo hints, *ai; 3554#endif 3555 3556 str[0] = '\0'; 3557 if (proto) 3558 av_strlcatf(str, size, "%s://", proto); 3559 if (authorization) 3560 av_strlcatf(str, size, "%s@", authorization); 3561#if CONFIG_NETWORK && defined(AF_INET6) 3562 /* Determine if hostname is a numerical IPv6 address, 3563 * properly escape it within [] in that case. */ 3564 memset(&hints, 0, sizeof(hints)); 3565 hints.ai_flags = AI_NUMERICHOST; 3566 if (!getaddrinfo(hostname, NULL, &hints, &ai)) { 3567 if (ai->ai_family == AF_INET6) { 3568 av_strlcat(str, "[", size); 3569 av_strlcat(str, hostname, size); 3570 av_strlcat(str, "]", size); 3571 } else { 3572 av_strlcat(str, hostname, size); 3573 } 3574 freeaddrinfo(ai); 3575 } else 3576#endif 3577 /* Not an IPv6 address, just output the plain string. */ 3578 av_strlcat(str, hostname, size); 3579 3580 if (port >= 0) 3581 av_strlcatf(str, size, ":%d", port); 3582 if (fmt) { 3583 va_list vl; 3584 int len = strlen(str); 3585 3586 va_start(vl, fmt); 3587 vsnprintf(str + len, size > len ? size - len : 0, fmt, vl); 3588 va_end(vl); 3589 } 3590 return strlen(str); 3591} 3592