00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023 #define _XOPEN_SOURCE 600
00024
00025 #include "config.h"
00026 #include <ctype.h>
00027 #include <string.h>
00028 #include <math.h>
00029 #include <stdlib.h>
00030 #include <errno.h>
00031 #include <signal.h>
00032 #include <limits.h>
00033 #include <unistd.h>
00034 #include "libavformat/avformat.h"
00035 #include "libavdevice/avdevice.h"
00036 #include "libswscale/swscale.h"
00037 #include "libavcodec/opt.h"
00038 #include "libavcodec/audioconvert.h"
00039 #include "libavutil/audioconvert.h"
00040 #include "libavutil/parseutils.h"
00041 #include "libavutil/samplefmt.h"
00042 #include "libavutil/colorspace.h"
00043 #include "libavutil/fifo.h"
00044 #include "libavutil/intreadwrite.h"
00045 #include "libavutil/pixdesc.h"
00046 #include "libavutil/avstring.h"
00047 #include "libavutil/libm.h"
00048 #include "libavformat/os_support.h"
00049
00050 #if CONFIG_AVFILTER
00051 # include "libavfilter/avfilter.h"
00052 # include "libavfilter/avfiltergraph.h"
00053 # include "libavfilter/vsrc_buffer.h"
00054 #endif
00055
00056 #if HAVE_SYS_RESOURCE_H
00057 #include <sys/types.h>
00058 #include <sys/time.h>
00059 #include <sys/resource.h>
00060 #elif HAVE_GETPROCESSTIMES
00061 #include <windows.h>
00062 #endif
00063 #if HAVE_GETPROCESSMEMORYINFO
00064 #include <windows.h>
00065 #include <psapi.h>
00066 #endif
00067
00068 #if HAVE_SYS_SELECT_H
00069 #include <sys/select.h>
00070 #endif
00071
00072 #if HAVE_TERMIOS_H
00073 #include <fcntl.h>
00074 #include <sys/ioctl.h>
00075 #include <sys/time.h>
00076 #include <termios.h>
00077 #elif HAVE_CONIO_H
00078 #include <conio.h>
00079 #endif
00080 #include <time.h>
00081
00082 #include "cmdutils.h"
00083
00084 #include "libavutil/avassert.h"
00085
00086 const char program_name[] = "FFmpeg";
00087 const int program_birth_year = 2000;
00088
00089
00090 typedef struct AVStreamMap {
00091 int file_index;
00092 int stream_index;
00093 int sync_file_index;
00094 int sync_stream_index;
00095 } AVStreamMap;
00096
00100 typedef struct AVMetaDataMap {
00101 int file;
00102 char type;
00103 int index;
00104 } AVMetaDataMap;
00105
00106 typedef struct AVChapterMap {
00107 int in_file;
00108 int out_file;
00109 } AVChapterMap;
00110
00111 static const OptionDef options[];
00112
00113 #define MAX_FILES 100
00114 #if !FF_API_MAX_STREAMS
00115 #define MAX_STREAMS 1024
00116 #endif
00117
00118 static const char *last_asked_format = NULL;
00119 static AVFormatContext *input_files[MAX_FILES];
00120 static int64_t input_files_ts_offset[MAX_FILES];
00121 static double *input_files_ts_scale[MAX_FILES] = {NULL};
00122 static AVCodec **input_codecs = NULL;
00123 static int nb_input_files = 0;
00124 static int nb_input_codecs = 0;
00125 static int nb_input_files_ts_scale[MAX_FILES] = {0};
00126
00127 static AVFormatContext *output_files[MAX_FILES];
00128 static AVCodec **output_codecs = NULL;
00129 static int nb_output_files = 0;
00130 static int nb_output_codecs = 0;
00131
00132 static AVStreamMap *stream_maps = NULL;
00133 static int nb_stream_maps;
00134
00135
00136 static AVMetaDataMap (*meta_data_maps)[2] = NULL;
00137 static int nb_meta_data_maps;
00138 static int metadata_global_autocopy = 1;
00139 static int metadata_streams_autocopy = 1;
00140 static int metadata_chapters_autocopy = 1;
00141
00142 static AVChapterMap *chapter_maps = NULL;
00143 static int nb_chapter_maps;
00144
00145
00146 static int *streamid_map = NULL;
00147 static int nb_streamid_map = 0;
00148
00149 static int frame_width = 0;
00150 static int frame_height = 0;
00151 static float frame_aspect_ratio = 0;
00152 static enum PixelFormat frame_pix_fmt = PIX_FMT_NONE;
00153 static enum AVSampleFormat audio_sample_fmt = AV_SAMPLE_FMT_NONE;
00154 static int max_frames[4] = {INT_MAX, INT_MAX, INT_MAX, INT_MAX};
00155 static AVRational frame_rate;
00156 static float video_qscale = 0;
00157 static uint16_t *intra_matrix = NULL;
00158 static uint16_t *inter_matrix = NULL;
00159 static const char *video_rc_override_string=NULL;
00160 static int video_disable = 0;
00161 static int video_discard = 0;
00162 static char *video_codec_name = NULL;
00163 static unsigned int video_codec_tag = 0;
00164 static char *video_language = NULL;
00165 static int same_quality = 0;
00166 static int do_deinterlace = 0;
00167 static int top_field_first = -1;
00168 static int me_threshold = 0;
00169 static int intra_dc_precision = 8;
00170 static int loop_input = 0;
00171 static int loop_output = AVFMT_NOOUTPUTLOOP;
00172 static int qp_hist = 0;
00173 #if CONFIG_AVFILTER
00174 static char *vfilters = NULL;
00175 #endif
00176
00177 static int intra_only = 0;
00178 static int audio_sample_rate = 44100;
00179 static int64_t channel_layout = 0;
00180 #define QSCALE_NONE -99999
00181 static float audio_qscale = QSCALE_NONE;
00182 static int audio_disable = 0;
00183 static int audio_channels = 1;
00184 static char *audio_codec_name = NULL;
00185 static unsigned int audio_codec_tag = 0;
00186 static char *audio_language = NULL;
00187
00188 static int subtitle_disable = 0;
00189 static char *subtitle_codec_name = NULL;
00190 static char *subtitle_language = NULL;
00191 static unsigned int subtitle_codec_tag = 0;
00192
00193 static float mux_preload= 0.5;
00194 static float mux_max_delay= 0.7;
00195
00196 static int64_t recording_time = INT64_MAX;
00197 static int64_t start_time = 0;
00198 static int64_t recording_timestamp = 0;
00199 static int64_t input_ts_offset = 0;
00200 static int file_overwrite = 0;
00201 static AVMetadata *metadata;
00202 static int do_benchmark = 0;
00203 static int do_hex_dump = 0;
00204 static int do_pkt_dump = 0;
00205 static int do_psnr = 0;
00206 static int do_pass = 0;
00207 static char *pass_logfilename_prefix = NULL;
00208 static int audio_stream_copy = 0;
00209 static int video_stream_copy = 0;
00210 static int subtitle_stream_copy = 0;
00211 static int video_sync_method= -1;
00212 static int audio_sync_method= 0;
00213 static float audio_drift_threshold= 0.1;
00214 static int copy_ts= 0;
00215 static int copy_tb;
00216 static int opt_shortest = 0;
00217 static int video_global_header = 0;
00218 static char *vstats_filename;
00219 static FILE *vstats_file;
00220 static int opt_programid = 0;
00221 static int copy_initial_nonkeyframes = 0;
00222
00223 static int rate_emu = 0;
00224
00225 static int video_channel = 0;
00226 static char *video_standard;
00227
00228 static int audio_volume = 256;
00229
00230 static int exit_on_error = 0;
00231 static int using_stdin = 0;
00232 static int verbose = 1;
00233 static int thread_count= 1;
00234 static int q_pressed = 0;
00235 static int64_t video_size = 0;
00236 static int64_t audio_size = 0;
00237 static int64_t extra_size = 0;
00238 static int nb_frames_dup = 0;
00239 static int nb_frames_drop = 0;
00240 static int input_sync;
00241 static uint64_t limit_filesize = 0;
00242 static int force_fps = 0;
00243 static char *forced_key_frames = NULL;
00244
00245 static float dts_delta_threshold = 10;
00246
00247 static unsigned int sws_flags = SWS_BICUBIC;
00248
00249 static int64_t timer_start;
00250
00251 static uint8_t *audio_buf;
00252 static uint8_t *audio_out;
00253 static unsigned int allocated_audio_out_size, allocated_audio_buf_size;
00254
00255 static short *samples;
00256
00257 static AVBitStreamFilterContext *video_bitstream_filters=NULL;
00258 static AVBitStreamFilterContext *audio_bitstream_filters=NULL;
00259 static AVBitStreamFilterContext *subtitle_bitstream_filters=NULL;
00260
00261 #define DEFAULT_PASS_LOGFILENAME_PREFIX "ffmpeg2pass"
00262
00263 struct AVInputStream;
00264
00265 typedef struct AVOutputStream {
00266 int file_index;
00267 int index;
00268 int source_index;
00269 AVStream *st;
00270 int encoding_needed;
00271 int frame_number;
00272
00273
00274
00275 struct AVInputStream *sync_ist;
00276 int64_t sync_opts;
00277 AVBitStreamFilterContext *bitstream_filters;
00278
00279 int video_resample;
00280 AVFrame pict_tmp;
00281 struct SwsContext *img_resample_ctx;
00282 int resample_height;
00283 int resample_width;
00284 int resample_pix_fmt;
00285
00286
00287 int original_height;
00288 int original_width;
00289
00290
00291 int64_t *forced_kf_pts;
00292 int forced_kf_count;
00293 int forced_kf_index;
00294
00295
00296 int audio_resample;
00297 ReSampleContext *resample;
00298 int resample_sample_fmt;
00299 int resample_channels;
00300 int resample_sample_rate;
00301 int reformat_pair;
00302 AVAudioConvert *reformat_ctx;
00303 AVFifoBuffer *fifo;
00304 FILE *logfile;
00305
00306 #if CONFIG_AVFILTER
00307 AVFilterContext *output_video_filter;
00308 AVFilterContext *input_video_filter;
00309 AVFilterBufferRef *picref;
00310 char *avfilter;
00311 AVFilterGraph *graph;
00312 #endif
00313 } AVOutputStream;
00314
00315 static AVOutputStream **output_streams_for_file[MAX_FILES] = { NULL };
00316 static int nb_output_streams_for_file[MAX_FILES] = { 0 };
00317
00318 typedef struct AVInputStream {
00319 int file_index;
00320 int index;
00321 AVStream *st;
00322 int discard;
00323 int decoding_needed;
00324 int64_t sample_index;
00325
00326 int64_t start;
00327 int64_t next_pts;
00328
00329 int64_t pts;
00330 int is_start;
00331 int showed_multi_packet_warning;
00332 int is_past_recording_time;
00333 #if CONFIG_AVFILTER
00334 AVFrame *filter_frame;
00335 int has_filter_frame;
00336 #endif
00337 } AVInputStream;
00338
00339 typedef struct AVInputFile {
00340 int eof_reached;
00341 int ist_index;
00342 int buffer_size;
00343 int nb_streams;
00344 } AVInputFile;
00345
00346 #if HAVE_TERMIOS_H
00347
00348
00349 static struct termios oldtty;
00350 #endif
00351
00352 #if CONFIG_AVFILTER
00353
00354 static int configure_filters(AVInputStream *ist, AVOutputStream *ost)
00355 {
00356 AVFilterContext *last_filter, *filter;
00358 AVCodecContext *codec = ost->st->codec;
00359 AVCodecContext *icodec = ist->st->codec;
00360 FFSinkContext ffsink_ctx = { .pix_fmt = codec->pix_fmt };
00361 AVRational sample_aspect_ratio;
00362 char args[255];
00363 int ret;
00364
00365 ost->graph = avfilter_graph_alloc();
00366
00367 if (ist->st->sample_aspect_ratio.num){
00368 sample_aspect_ratio = ist->st->sample_aspect_ratio;
00369 }else
00370 sample_aspect_ratio = ist->st->codec->sample_aspect_ratio;
00371
00372 snprintf(args, 255, "%d:%d:%d:%d:%d:%d:%d", ist->st->codec->width,
00373 ist->st->codec->height, ist->st->codec->pix_fmt, 1, AV_TIME_BASE,
00374 sample_aspect_ratio.num, sample_aspect_ratio.den);
00375
00376 ret = avfilter_graph_create_filter(&ost->input_video_filter, avfilter_get_by_name("buffer"),
00377 "src", args, NULL, ost->graph);
00378 if (ret < 0)
00379 return ret;
00380 ret = avfilter_graph_create_filter(&ost->output_video_filter, &ffsink,
00381 "out", NULL, &ffsink_ctx, ost->graph);
00382 if (ret < 0)
00383 return ret;
00384 last_filter = ost->input_video_filter;
00385
00386 if (codec->width != icodec->width || codec->height != icodec->height) {
00387 snprintf(args, 255, "%d:%d:flags=0x%X",
00388 codec->width,
00389 codec->height,
00390 (int)av_get_int(sws_opts, "sws_flags", NULL));
00391 if ((ret = avfilter_graph_create_filter(&filter, avfilter_get_by_name("scale"),
00392 NULL, args, NULL, ost->graph)) < 0)
00393 return ret;
00394 if ((ret = avfilter_link(last_filter, 0, filter, 0)) < 0)
00395 return ret;
00396 last_filter = filter;
00397 }
00398
00399 snprintf(args, sizeof(args), "flags=0x%X", (int)av_get_int(sws_opts, "sws_flags", NULL));
00400 ost->graph->scale_sws_opts = av_strdup(args);
00401
00402 if (ost->avfilter) {
00403 AVFilterInOut *outputs = av_malloc(sizeof(AVFilterInOut));
00404 AVFilterInOut *inputs = av_malloc(sizeof(AVFilterInOut));
00405
00406 outputs->name = av_strdup("in");
00407 outputs->filter_ctx = last_filter;
00408 outputs->pad_idx = 0;
00409 outputs->next = NULL;
00410
00411 inputs->name = av_strdup("out");
00412 inputs->filter_ctx = ost->output_video_filter;
00413 inputs->pad_idx = 0;
00414 inputs->next = NULL;
00415
00416 if ((ret = avfilter_graph_parse(ost->graph, ost->avfilter, inputs, outputs, NULL)) < 0)
00417 return ret;
00418 av_freep(&ost->avfilter);
00419 } else {
00420 if ((ret = avfilter_link(last_filter, 0, ost->output_video_filter, 0)) < 0)
00421 return ret;
00422 }
00423
00424 if ((ret = avfilter_graph_config(ost->graph, NULL)) < 0)
00425 return ret;
00426
00427 codec->width = ost->output_video_filter->inputs[0]->w;
00428 codec->height = ost->output_video_filter->inputs[0]->h;
00429 codec->sample_aspect_ratio = ost->st->sample_aspect_ratio =
00430 ost->output_video_filter->inputs[0]->sample_aspect_ratio;
00431
00432 return 0;
00433 }
00434 #endif
00435
00436 static void term_exit(void)
00437 {
00438 av_log(NULL, AV_LOG_QUIET, "");
00439 #if HAVE_TERMIOS_H
00440 tcsetattr (0, TCSANOW, &oldtty);
00441 #endif
00442 }
00443
00444 static volatile int received_sigterm = 0;
00445
00446 static void
00447 sigterm_handler(int sig)
00448 {
00449 received_sigterm = sig;
00450 term_exit();
00451 }
00452
00453 static void term_init(void)
00454 {
00455 #if HAVE_TERMIOS_H
00456 struct termios tty;
00457
00458 tcgetattr (0, &tty);
00459 oldtty = tty;
00460 atexit(term_exit);
00461
00462 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
00463 |INLCR|IGNCR|ICRNL|IXON);
00464 tty.c_oflag |= OPOST;
00465 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
00466 tty.c_cflag &= ~(CSIZE|PARENB);
00467 tty.c_cflag |= CS8;
00468 tty.c_cc[VMIN] = 1;
00469 tty.c_cc[VTIME] = 0;
00470
00471 tcsetattr (0, TCSANOW, &tty);
00472 signal(SIGQUIT, sigterm_handler);
00473 #endif
00474
00475 signal(SIGINT , sigterm_handler);
00476 signal(SIGTERM, sigterm_handler);
00477 #ifdef SIGXCPU
00478 signal(SIGXCPU, sigterm_handler);
00479 #endif
00480 }
00481
00482
00483 static int read_key(void)
00484 {
00485 #if HAVE_TERMIOS_H
00486 int n = 1;
00487 unsigned char ch;
00488 struct timeval tv;
00489 fd_set rfds;
00490
00491 FD_ZERO(&rfds);
00492 FD_SET(0, &rfds);
00493 tv.tv_sec = 0;
00494 tv.tv_usec = 0;
00495 n = select(1, &rfds, NULL, NULL, &tv);
00496 if (n > 0) {
00497 n = read(0, &ch, 1);
00498 if (n == 1)
00499 return ch;
00500
00501 return n;
00502 }
00503 #elif HAVE_CONIO_H
00504 if(kbhit())
00505 return(getch());
00506 #endif
00507 return -1;
00508 }
00509
00510 static int decode_interrupt_cb(void)
00511 {
00512 q_pressed += read_key() == 'q';
00513 return q_pressed > 1;
00514 }
00515
00516 static int ffmpeg_exit(int ret)
00517 {
00518 int i;
00519
00520
00521 for(i=0;i<nb_output_files;i++) {
00522 AVFormatContext *s = output_files[i];
00523 if (!(s->oformat->flags & AVFMT_NOFILE) && s->pb)
00524 avio_close(s->pb);
00525 avformat_free_context(s);
00526 av_free(output_streams_for_file[i]);
00527 }
00528 for(i=0;i<nb_input_files;i++) {
00529 av_close_input_file(input_files[i]);
00530 av_free(input_files_ts_scale[i]);
00531 }
00532
00533 av_free(intra_matrix);
00534 av_free(inter_matrix);
00535
00536 if (vstats_file)
00537 fclose(vstats_file);
00538 av_free(vstats_filename);
00539
00540 av_free(streamid_map);
00541 av_free(input_codecs);
00542 av_free(output_codecs);
00543 av_free(stream_maps);
00544 av_free(meta_data_maps);
00545
00546 av_free(video_codec_name);
00547 av_free(audio_codec_name);
00548 av_free(subtitle_codec_name);
00549
00550 av_free(video_standard);
00551
00552 uninit_opts();
00553 av_free(audio_buf);
00554 av_free(audio_out);
00555 allocated_audio_buf_size= allocated_audio_out_size= 0;
00556 av_free(samples);
00557
00558 #if CONFIG_AVFILTER
00559 avfilter_uninit();
00560 #endif
00561
00562 if (received_sigterm) {
00563 fprintf(stderr,
00564 "Received signal %d: terminating.\n",
00565 (int) received_sigterm);
00566 exit (255);
00567 }
00568
00569 exit(ret);
00570 return ret;
00571 }
00572
00573
00574 static void *grow_array(void *array, int elem_size, int *size, int new_size)
00575 {
00576 if (new_size >= INT_MAX / elem_size) {
00577 fprintf(stderr, "Array too big.\n");
00578 ffmpeg_exit(1);
00579 }
00580 if (*size < new_size) {
00581 uint8_t *tmp = av_realloc(array, new_size*elem_size);
00582 if (!tmp) {
00583 fprintf(stderr, "Could not alloc buffer.\n");
00584 ffmpeg_exit(1);
00585 }
00586 memset(tmp + *size*elem_size, 0, (new_size-*size) * elem_size);
00587 *size = new_size;
00588 return tmp;
00589 }
00590 return array;
00591 }
00592
00593 static void choose_sample_fmt(AVStream *st, AVCodec *codec)
00594 {
00595 if(codec && codec->sample_fmts){
00596 const enum AVSampleFormat *p= codec->sample_fmts;
00597 for(; *p!=-1; p++){
00598 if(*p == st->codec->sample_fmt)
00599 break;
00600 }
00601 if (*p == -1) {
00602 av_log(NULL, AV_LOG_WARNING,
00603 "Incompatible sample format '%s' for codec '%s', auto-selecting format '%s'\n",
00604 av_get_sample_fmt_name(st->codec->sample_fmt),
00605 codec->name,
00606 av_get_sample_fmt_name(codec->sample_fmts[0]));
00607 st->codec->sample_fmt = codec->sample_fmts[0];
00608 }
00609 }
00610 }
00611
00612 static void choose_sample_rate(AVStream *st, AVCodec *codec)
00613 {
00614 if(codec && codec->supported_samplerates){
00615 const int *p= codec->supported_samplerates;
00616 int best=0;
00617 int best_dist=INT_MAX;
00618 for(; *p; p++){
00619 int dist= abs(st->codec->sample_rate - *p);
00620 if(dist < best_dist){
00621 best_dist= dist;
00622 best= *p;
00623 }
00624 }
00625 if(best_dist){
00626 av_log(st->codec, AV_LOG_WARNING, "Requested sampling rate unsupported using closest supported (%d)\n", best);
00627 }
00628 st->codec->sample_rate= best;
00629 }
00630 }
00631
00632 static void choose_pixel_fmt(AVStream *st, AVCodec *codec)
00633 {
00634 if(codec && codec->pix_fmts){
00635 const enum PixelFormat *p= codec->pix_fmts;
00636 if(st->codec->strict_std_compliance <= FF_COMPLIANCE_UNOFFICIAL){
00637 if(st->codec->codec_id==CODEC_ID_MJPEG){
00638 p= (const enum PixelFormat[]){PIX_FMT_YUVJ420P, PIX_FMT_YUVJ422P, PIX_FMT_YUV420P, PIX_FMT_YUV422P, PIX_FMT_NONE};
00639 }else if(st->codec->codec_id==CODEC_ID_LJPEG){
00640 p= (const enum PixelFormat[]){PIX_FMT_YUVJ420P, PIX_FMT_YUVJ422P, PIX_FMT_YUVJ444P, PIX_FMT_YUV420P, PIX_FMT_YUV422P, PIX_FMT_YUV444P, PIX_FMT_BGRA, PIX_FMT_NONE};
00641 }
00642 }
00643 for(; *p!=-1; p++){
00644 if(*p == st->codec->pix_fmt)
00645 break;
00646 }
00647 if(*p == -1)
00648 st->codec->pix_fmt = codec->pix_fmts[0];
00649 }
00650 }
00651
00652 static AVOutputStream *new_output_stream(AVFormatContext *oc, int file_idx)
00653 {
00654 int idx = oc->nb_streams - 1;
00655 AVOutputStream *ost;
00656
00657 output_streams_for_file[file_idx] =
00658 grow_array(output_streams_for_file[file_idx],
00659 sizeof(*output_streams_for_file[file_idx]),
00660 &nb_output_streams_for_file[file_idx],
00661 oc->nb_streams);
00662 ost = output_streams_for_file[file_idx][idx] =
00663 av_mallocz(sizeof(AVOutputStream));
00664 if (!ost) {
00665 fprintf(stderr, "Could not alloc output stream\n");
00666 ffmpeg_exit(1);
00667 }
00668 ost->file_index = file_idx;
00669 ost->index = idx;
00670 return ost;
00671 }
00672
00673 static int read_ffserver_streams(AVFormatContext *s, const char *filename)
00674 {
00675 int i, err;
00676 AVFormatContext *ic;
00677 int nopts = 0;
00678
00679 err = av_open_input_file(&ic, filename, NULL, FFM_PACKET_SIZE, NULL);
00680 if (err < 0)
00681 return err;
00682
00683 s->nb_streams = 0;
00684 for(i=0;i<ic->nb_streams;i++) {
00685 AVStream *st;
00686 AVCodec *codec;
00687
00688 s->nb_streams++;
00689
00690
00691 st = av_mallocz(sizeof(AVStream));
00692 memcpy(st, ic->streams[i], sizeof(AVStream));
00693 st->codec = avcodec_alloc_context();
00694 if (!st->codec) {
00695 print_error(filename, AVERROR(ENOMEM));
00696 ffmpeg_exit(1);
00697 }
00698 avcodec_copy_context(st->codec, ic->streams[i]->codec);
00699 s->streams[i] = st;
00700
00701 codec = avcodec_find_encoder(st->codec->codec_id);
00702 if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
00703 if (audio_stream_copy) {
00704 st->stream_copy = 1;
00705 } else
00706 choose_sample_fmt(st, codec);
00707 } else if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
00708 if (video_stream_copy) {
00709 st->stream_copy = 1;
00710 } else
00711 choose_pixel_fmt(st, codec);
00712 }
00713
00714 if(st->codec->flags & CODEC_FLAG_BITEXACT)
00715 nopts = 1;
00716
00717 new_output_stream(s, nb_output_files);
00718 }
00719
00720 if (!nopts)
00721 s->timestamp = av_gettime();
00722
00723 av_close_input_file(ic);
00724 return 0;
00725 }
00726
00727 static double
00728 get_sync_ipts(const AVOutputStream *ost)
00729 {
00730 const AVInputStream *ist = ost->sync_ist;
00731 return (double)(ist->pts - start_time)/AV_TIME_BASE;
00732 }
00733
00734 static void write_frame(AVFormatContext *s, AVPacket *pkt, AVCodecContext *avctx, AVBitStreamFilterContext *bsfc){
00735 int ret;
00736
00737 while(bsfc){
00738 AVPacket new_pkt= *pkt;
00739 int a= av_bitstream_filter_filter(bsfc, avctx, NULL,
00740 &new_pkt.data, &new_pkt.size,
00741 pkt->data, pkt->size,
00742 pkt->flags & AV_PKT_FLAG_KEY);
00743 if(a>0){
00744 av_free_packet(pkt);
00745 new_pkt.destruct= av_destruct_packet;
00746 } else if(a<0){
00747 fprintf(stderr, "%s failed for stream %d, codec %s",
00748 bsfc->filter->name, pkt->stream_index,
00749 avctx->codec ? avctx->codec->name : "copy");
00750 print_error("", a);
00751 if (exit_on_error)
00752 ffmpeg_exit(1);
00753 }
00754 *pkt= new_pkt;
00755
00756 bsfc= bsfc->next;
00757 }
00758
00759 ret= av_interleaved_write_frame(s, pkt);
00760 if(ret < 0){
00761 print_error("av_interleaved_write_frame()", ret);
00762 ffmpeg_exit(1);
00763 }
00764 }
00765
00766 #define MAX_AUDIO_PACKET_SIZE (128 * 1024)
00767
00768 static void do_audio_out(AVFormatContext *s,
00769 AVOutputStream *ost,
00770 AVInputStream *ist,
00771 unsigned char *buf, int size)
00772 {
00773 uint8_t *buftmp;
00774 int64_t audio_out_size, audio_buf_size;
00775 int64_t allocated_for_size= size;
00776
00777 int size_out, frame_bytes, ret, resample_changed;
00778 AVCodecContext *enc= ost->st->codec;
00779 AVCodecContext *dec= ist->st->codec;
00780 int osize= av_get_bits_per_sample_fmt(enc->sample_fmt)/8;
00781 int isize= av_get_bits_per_sample_fmt(dec->sample_fmt)/8;
00782 const int coded_bps = av_get_bits_per_sample(enc->codec->id);
00783
00784 need_realloc:
00785 audio_buf_size= (allocated_for_size + isize*dec->channels - 1) / (isize*dec->channels);
00786 audio_buf_size= (audio_buf_size*enc->sample_rate + dec->sample_rate) / dec->sample_rate;
00787 audio_buf_size= audio_buf_size*2 + 10000;
00788 audio_buf_size= FFMAX(audio_buf_size, enc->frame_size);
00789 audio_buf_size*= osize*enc->channels;
00790
00791 audio_out_size= FFMAX(audio_buf_size, enc->frame_size * osize * enc->channels);
00792 if(coded_bps > 8*osize)
00793 audio_out_size= audio_out_size * coded_bps / (8*osize);
00794 audio_out_size += FF_MIN_BUFFER_SIZE;
00795
00796 if(audio_out_size > INT_MAX || audio_buf_size > INT_MAX){
00797 fprintf(stderr, "Buffer sizes too large\n");
00798 ffmpeg_exit(1);
00799 }
00800
00801 av_fast_malloc(&audio_buf, &allocated_audio_buf_size, audio_buf_size);
00802 av_fast_malloc(&audio_out, &allocated_audio_out_size, audio_out_size);
00803 if (!audio_buf || !audio_out){
00804 fprintf(stderr, "Out of memory in do_audio_out\n");
00805 ffmpeg_exit(1);
00806 }
00807
00808 if (enc->channels != dec->channels)
00809 ost->audio_resample = 1;
00810
00811 resample_changed = ost->resample_sample_fmt != dec->sample_fmt ||
00812 ost->resample_channels != dec->channels ||
00813 ost->resample_sample_rate != dec->sample_rate;
00814
00815 if ((ost->audio_resample && !ost->resample) || resample_changed) {
00816 if (resample_changed) {
00817 av_log(NULL, AV_LOG_INFO, "Input stream #%d.%d frame changed from rate:%d fmt:%s ch:%d to rate:%d fmt:%s ch:%d\n",
00818 ist->file_index, ist->index,
00819 ost->resample_sample_rate, av_get_sample_fmt_name(ost->resample_sample_fmt), ost->resample_channels,
00820 dec->sample_rate, av_get_sample_fmt_name(dec->sample_fmt), dec->channels);
00821 ost->resample_sample_fmt = dec->sample_fmt;
00822 ost->resample_channels = dec->channels;
00823 ost->resample_sample_rate = dec->sample_rate;
00824 if (ost->resample)
00825 audio_resample_close(ost->resample);
00826 }
00827
00828 if (audio_sync_method <= 1 &&
00829 ost->resample_sample_fmt == enc->sample_fmt &&
00830 ost->resample_channels == enc->channels &&
00831 ost->resample_sample_rate == enc->sample_rate) {
00832 ost->resample = NULL;
00833 ost->audio_resample = 0;
00834 } else {
00835 if (dec->sample_fmt != AV_SAMPLE_FMT_S16)
00836 fprintf(stderr, "Warning, using s16 intermediate sample format for resampling\n");
00837 ost->resample = av_audio_resample_init(enc->channels, dec->channels,
00838 enc->sample_rate, dec->sample_rate,
00839 enc->sample_fmt, dec->sample_fmt,
00840 16, 10, 0, 0.8);
00841 if (!ost->resample) {
00842 fprintf(stderr, "Can not resample %d channels @ %d Hz to %d channels @ %d Hz\n",
00843 dec->channels, dec->sample_rate,
00844 enc->channels, enc->sample_rate);
00845 ffmpeg_exit(1);
00846 }
00847 }
00848 }
00849
00850 #define MAKE_SFMT_PAIR(a,b) ((a)+AV_SAMPLE_FMT_NB*(b))
00851 if (!ost->audio_resample && dec->sample_fmt!=enc->sample_fmt &&
00852 MAKE_SFMT_PAIR(enc->sample_fmt,dec->sample_fmt)!=ost->reformat_pair) {
00853 if (ost->reformat_ctx)
00854 av_audio_convert_free(ost->reformat_ctx);
00855 ost->reformat_ctx = av_audio_convert_alloc(enc->sample_fmt, 1,
00856 dec->sample_fmt, 1, NULL, 0);
00857 if (!ost->reformat_ctx) {
00858 fprintf(stderr, "Cannot convert %s sample format to %s sample format\n",
00859 av_get_sample_fmt_name(dec->sample_fmt),
00860 av_get_sample_fmt_name(enc->sample_fmt));
00861 ffmpeg_exit(1);
00862 }
00863 ost->reformat_pair=MAKE_SFMT_PAIR(enc->sample_fmt,dec->sample_fmt);
00864 }
00865
00866 if(audio_sync_method){
00867 double delta = get_sync_ipts(ost) * enc->sample_rate - ost->sync_opts
00868 - av_fifo_size(ost->fifo)/(enc->channels * 2);
00869 double idelta= delta*dec->sample_rate / enc->sample_rate;
00870 int byte_delta= ((int)idelta)*2*dec->channels;
00871
00872
00873 if(fabs(delta) > 50){
00874 if(ist->is_start || fabs(delta) > audio_drift_threshold*enc->sample_rate){
00875 if(byte_delta < 0){
00876 byte_delta= FFMAX(byte_delta, -size);
00877 size += byte_delta;
00878 buf -= byte_delta;
00879 if(verbose > 2)
00880 fprintf(stderr, "discarding %d audio samples\n", (int)-delta);
00881 if(!size)
00882 return;
00883 ist->is_start=0;
00884 }else{
00885 static uint8_t *input_tmp= NULL;
00886 input_tmp= av_realloc(input_tmp, byte_delta + size);
00887
00888 if(byte_delta > allocated_for_size - size){
00889 allocated_for_size= byte_delta + (int64_t)size;
00890 goto need_realloc;
00891 }
00892 ist->is_start=0;
00893
00894 memset(input_tmp, 0, byte_delta);
00895 memcpy(input_tmp + byte_delta, buf, size);
00896 buf= input_tmp;
00897 size += byte_delta;
00898 if(verbose > 2)
00899 fprintf(stderr, "adding %d audio samples of silence\n", (int)delta);
00900 }
00901 }else if(audio_sync_method>1){
00902 int comp= av_clip(delta, -audio_sync_method, audio_sync_method);
00903 av_assert0(ost->audio_resample);
00904 if(verbose > 2)
00905 fprintf(stderr, "compensating audio timestamp drift:%f compensation:%d in:%d\n", delta, comp, enc->sample_rate);
00906
00907 av_resample_compensate(*(struct AVResampleContext**)ost->resample, comp, enc->sample_rate);
00908 }
00909 }
00910 }else
00911 ost->sync_opts= lrintf(get_sync_ipts(ost) * enc->sample_rate)
00912 - av_fifo_size(ost->fifo)/(enc->channels * 2);
00913
00914 if (ost->audio_resample) {
00915 buftmp = audio_buf;
00916 size_out = audio_resample(ost->resample,
00917 (short *)buftmp, (short *)buf,
00918 size / (dec->channels * isize));
00919 size_out = size_out * enc->channels * osize;
00920 } else {
00921 buftmp = buf;
00922 size_out = size;
00923 }
00924
00925 if (!ost->audio_resample && dec->sample_fmt!=enc->sample_fmt) {
00926 const void *ibuf[6]= {buftmp};
00927 void *obuf[6]= {audio_buf};
00928 int istride[6]= {isize};
00929 int ostride[6]= {osize};
00930 int len= size_out/istride[0];
00931 if (av_audio_convert(ost->reformat_ctx, obuf, ostride, ibuf, istride, len)<0) {
00932 printf("av_audio_convert() failed\n");
00933 if (exit_on_error)
00934 ffmpeg_exit(1);
00935 return;
00936 }
00937 buftmp = audio_buf;
00938 size_out = len*osize;
00939 }
00940
00941
00942 if (enc->frame_size > 1) {
00943
00944 if (av_fifo_realloc2(ost->fifo, av_fifo_size(ost->fifo) + size_out) < 0) {
00945 fprintf(stderr, "av_fifo_realloc2() failed\n");
00946 ffmpeg_exit(1);
00947 }
00948 av_fifo_generic_write(ost->fifo, buftmp, size_out, NULL);
00949
00950 frame_bytes = enc->frame_size * osize * enc->channels;
00951
00952 while (av_fifo_size(ost->fifo) >= frame_bytes) {
00953 AVPacket pkt;
00954 av_init_packet(&pkt);
00955
00956 av_fifo_generic_read(ost->fifo, audio_buf, frame_bytes, NULL);
00957
00958
00959
00960 ret = avcodec_encode_audio(enc, audio_out, audio_out_size,
00961 (short *)audio_buf);
00962 if (ret < 0) {
00963 fprintf(stderr, "Audio encoding failed\n");
00964 ffmpeg_exit(1);
00965 }
00966 audio_size += ret;
00967 pkt.stream_index= ost->index;
00968 pkt.data= audio_out;
00969 pkt.size= ret;
00970 if(enc->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)
00971 pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
00972 pkt.flags |= AV_PKT_FLAG_KEY;
00973 write_frame(s, &pkt, enc, ost->bitstream_filters);
00974
00975 ost->sync_opts += enc->frame_size;
00976 }
00977 } else {
00978 AVPacket pkt;
00979 av_init_packet(&pkt);
00980
00981 ost->sync_opts += size_out / (osize * enc->channels);
00982
00983
00984
00985 size_out /= osize;
00986 if (coded_bps)
00987 size_out = size_out*coded_bps/8;
00988
00989 if(size_out > audio_out_size){
00990 fprintf(stderr, "Internal error, buffer size too small\n");
00991 ffmpeg_exit(1);
00992 }
00993
00994
00995 ret = avcodec_encode_audio(enc, audio_out, size_out,
00996 (short *)buftmp);
00997 if (ret < 0) {
00998 fprintf(stderr, "Audio encoding failed\n");
00999 ffmpeg_exit(1);
01000 }
01001 audio_size += ret;
01002 pkt.stream_index= ost->index;
01003 pkt.data= audio_out;
01004 pkt.size= ret;
01005 if(enc->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)
01006 pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
01007 pkt.flags |= AV_PKT_FLAG_KEY;
01008 write_frame(s, &pkt, enc, ost->bitstream_filters);
01009 }
01010 }
01011
01012 static void pre_process_video_frame(AVInputStream *ist, AVPicture *picture, void **bufp)
01013 {
01014 AVCodecContext *dec;
01015 AVPicture *picture2;
01016 AVPicture picture_tmp;
01017 uint8_t *buf = 0;
01018
01019 dec = ist->st->codec;
01020
01021
01022 if (do_deinterlace) {
01023 int size;
01024
01025
01026 size = avpicture_get_size(dec->pix_fmt, dec->width, dec->height);
01027 buf = av_malloc(size);
01028 if (!buf)
01029 return;
01030
01031 picture2 = &picture_tmp;
01032 avpicture_fill(picture2, buf, dec->pix_fmt, dec->width, dec->height);
01033
01034 if(avpicture_deinterlace(picture2, picture,
01035 dec->pix_fmt, dec->width, dec->height) < 0) {
01036
01037 fprintf(stderr, "Deinterlacing failed\n");
01038 av_free(buf);
01039 buf = NULL;
01040 picture2 = picture;
01041 }
01042 } else {
01043 picture2 = picture;
01044 }
01045
01046 if (picture != picture2)
01047 *picture = *picture2;
01048 *bufp = buf;
01049 }
01050
01051
01052 #define AV_DELAY_MAX 0.100
01053
01054 static void do_subtitle_out(AVFormatContext *s,
01055 AVOutputStream *ost,
01056 AVInputStream *ist,
01057 AVSubtitle *sub,
01058 int64_t pts)
01059 {
01060 static uint8_t *subtitle_out = NULL;
01061 int subtitle_out_max_size = 1024 * 1024;
01062 int subtitle_out_size, nb, i;
01063 AVCodecContext *enc;
01064 AVPacket pkt;
01065
01066 if (pts == AV_NOPTS_VALUE) {
01067 fprintf(stderr, "Subtitle packets must have a pts\n");
01068 if (exit_on_error)
01069 ffmpeg_exit(1);
01070 return;
01071 }
01072
01073 enc = ost->st->codec;
01074
01075 if (!subtitle_out) {
01076 subtitle_out = av_malloc(subtitle_out_max_size);
01077 }
01078
01079
01080
01081
01082 if (enc->codec_id == CODEC_ID_DVB_SUBTITLE)
01083 nb = 2;
01084 else
01085 nb = 1;
01086
01087 for(i = 0; i < nb; i++) {
01088 sub->pts = av_rescale_q(pts, ist->st->time_base, AV_TIME_BASE_Q);
01089
01090 sub->pts += av_rescale_q(sub->start_display_time, (AVRational){1, 1000}, AV_TIME_BASE_Q);
01091 sub->end_display_time -= sub->start_display_time;
01092 sub->start_display_time = 0;
01093 subtitle_out_size = avcodec_encode_subtitle(enc, subtitle_out,
01094 subtitle_out_max_size, sub);
01095 if (subtitle_out_size < 0) {
01096 fprintf(stderr, "Subtitle encoding failed\n");
01097 ffmpeg_exit(1);
01098 }
01099
01100 av_init_packet(&pkt);
01101 pkt.stream_index = ost->index;
01102 pkt.data = subtitle_out;
01103 pkt.size = subtitle_out_size;
01104 pkt.pts = av_rescale_q(sub->pts, AV_TIME_BASE_Q, ost->st->time_base);
01105 if (enc->codec_id == CODEC_ID_DVB_SUBTITLE) {
01106
01107
01108 if (i == 0)
01109 pkt.pts += 90 * sub->start_display_time;
01110 else
01111 pkt.pts += 90 * sub->end_display_time;
01112 }
01113 write_frame(s, &pkt, ost->st->codec, ost->bitstream_filters);
01114 }
01115 }
01116
01117 static int bit_buffer_size= 1024*256;
01118 static uint8_t *bit_buffer= NULL;
01119
01120 static void do_video_out(AVFormatContext *s,
01121 AVOutputStream *ost,
01122 AVInputStream *ist,
01123 AVFrame *in_picture,
01124 int *frame_size)
01125 {
01126 int nb_frames, i, ret;
01127 AVFrame *final_picture, *formatted_picture, *resampling_dst, *padding_src;
01128 AVCodecContext *enc, *dec;
01129 double sync_ipts;
01130
01131 enc = ost->st->codec;
01132 dec = ist->st->codec;
01133
01134 sync_ipts = get_sync_ipts(ost) / av_q2d(enc->time_base);
01135
01136
01137 nb_frames = 1;
01138
01139 *frame_size = 0;
01140
01141 if(video_sync_method){
01142 double vdelta = sync_ipts - ost->sync_opts;
01143
01144 if (vdelta < -1.1)
01145 nb_frames = 0;
01146 else if (video_sync_method == 2 || (video_sync_method<0 && (s->oformat->flags & AVFMT_VARIABLE_FPS))){
01147 if(vdelta<=-0.6){
01148 nb_frames=0;
01149 }else if(vdelta>0.6)
01150 ost->sync_opts= lrintf(sync_ipts);
01151 }else if (vdelta > 1.1)
01152 nb_frames = lrintf(vdelta);
01153
01154 if (nb_frames == 0){
01155 ++nb_frames_drop;
01156 if (verbose>2)
01157 fprintf(stderr, "*** drop!\n");
01158 }else if (nb_frames > 1) {
01159 nb_frames_dup += nb_frames - 1;
01160 if (verbose>2)
01161 fprintf(stderr, "*** %d dup!\n", nb_frames-1);
01162 }
01163 }else
01164 ost->sync_opts= lrintf(sync_ipts);
01165
01166 nb_frames= FFMIN(nb_frames, max_frames[AVMEDIA_TYPE_VIDEO] - ost->frame_number);
01167 if (nb_frames <= 0)
01168 return;
01169
01170 formatted_picture = in_picture;
01171 final_picture = formatted_picture;
01172 padding_src = formatted_picture;
01173 resampling_dst = &ost->pict_tmp;
01174
01175 if ( ost->resample_height != ist->st->codec->height
01176 || ost->resample_width != ist->st->codec->width
01177 || (ost->resample_pix_fmt!= ist->st->codec->pix_fmt) ) {
01178
01179 fprintf(stderr,"Input Stream #%d.%d frame size changed to %dx%d, %s\n", ist->file_index, ist->index, ist->st->codec->width, ist->st->codec->height,avcodec_get_pix_fmt_name(ist->st->codec->pix_fmt));
01180 if(!ost->video_resample)
01181 ffmpeg_exit(1);
01182 }
01183
01184 #if !CONFIG_AVFILTER
01185 if (ost->video_resample) {
01186 padding_src = NULL;
01187 final_picture = &ost->pict_tmp;
01188 if( ost->resample_height != ist->st->codec->height
01189 || ost->resample_width != ist->st->codec->width
01190 || (ost->resample_pix_fmt!= ist->st->codec->pix_fmt) ) {
01191
01192
01193 sws_freeContext(ost->img_resample_ctx);
01194 sws_flags = av_get_int(sws_opts, "sws_flags", NULL);
01195 ost->img_resample_ctx = sws_getContext(
01196 ist->st->codec->width,
01197 ist->st->codec->height,
01198 ist->st->codec->pix_fmt,
01199 ost->st->codec->width,
01200 ost->st->codec->height,
01201 ost->st->codec->pix_fmt,
01202 sws_flags, NULL, NULL, NULL);
01203 if (ost->img_resample_ctx == NULL) {
01204 fprintf(stderr, "Cannot get resampling context\n");
01205 ffmpeg_exit(1);
01206 }
01207 }
01208 sws_scale(ost->img_resample_ctx, formatted_picture->data, formatted_picture->linesize,
01209 0, ost->resample_height, resampling_dst->data, resampling_dst->linesize);
01210 }
01211 #endif
01212
01213
01214 for(i=0;i<nb_frames;i++) {
01215 AVPacket pkt;
01216 av_init_packet(&pkt);
01217 pkt.stream_index= ost->index;
01218
01219 if (s->oformat->flags & AVFMT_RAWPICTURE) {
01220
01221
01222
01223 AVFrame* old_frame = enc->coded_frame;
01224 enc->coded_frame = dec->coded_frame;
01225 pkt.data= (uint8_t *)final_picture;
01226 pkt.size= sizeof(AVPicture);
01227 pkt.pts= av_rescale_q(ost->sync_opts, enc->time_base, ost->st->time_base);
01228 pkt.flags |= AV_PKT_FLAG_KEY;
01229
01230 write_frame(s, &pkt, ost->st->codec, ost->bitstream_filters);
01231 enc->coded_frame = old_frame;
01232 } else {
01233 AVFrame big_picture;
01234
01235 big_picture= *final_picture;
01236
01237
01238 big_picture.interlaced_frame = in_picture->interlaced_frame;
01239 if(avcodec_opts[AVMEDIA_TYPE_VIDEO]->flags & (CODEC_FLAG_INTERLACED_DCT|CODEC_FLAG_INTERLACED_ME)){
01240 if(top_field_first == -1)
01241 big_picture.top_field_first = in_picture->top_field_first;
01242 else
01243 big_picture.top_field_first = top_field_first;
01244 }
01245
01246
01247
01248 big_picture.quality = same_quality ? ist->st->quality : ost->st->quality;
01249 if(!me_threshold)
01250 big_picture.pict_type = 0;
01251
01252 big_picture.pts= ost->sync_opts;
01253
01254
01255 if (ost->forced_kf_index < ost->forced_kf_count &&
01256 big_picture.pts >= ost->forced_kf_pts[ost->forced_kf_index]) {
01257 big_picture.pict_type = FF_I_TYPE;
01258 ost->forced_kf_index++;
01259 }
01260 ret = avcodec_encode_video(enc,
01261 bit_buffer, bit_buffer_size,
01262 &big_picture);
01263 if (ret < 0) {
01264 fprintf(stderr, "Video encoding failed\n");
01265 ffmpeg_exit(1);
01266 }
01267
01268 if(ret>0){
01269 pkt.data= bit_buffer;
01270 pkt.size= ret;
01271 if(enc->coded_frame->pts != AV_NOPTS_VALUE)
01272 pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
01273
01274
01275
01276
01277 if(enc->coded_frame->key_frame)
01278 pkt.flags |= AV_PKT_FLAG_KEY;
01279 write_frame(s, &pkt, ost->st->codec, ost->bitstream_filters);
01280 *frame_size = ret;
01281 video_size += ret;
01282
01283
01284
01285 if (ost->logfile && enc->stats_out) {
01286 fprintf(ost->logfile, "%s", enc->stats_out);
01287 }
01288 }
01289 }
01290 ost->sync_opts++;
01291 ost->frame_number++;
01292 }
01293 }
01294
01295 static double psnr(double d){
01296 return -10.0*log(d)/log(10.0);
01297 }
01298
01299 static void do_video_stats(AVFormatContext *os, AVOutputStream *ost,
01300 int frame_size)
01301 {
01302 AVCodecContext *enc;
01303 int frame_number;
01304 double ti1, bitrate, avg_bitrate;
01305
01306
01307 if (!vstats_file) {
01308 vstats_file = fopen(vstats_filename, "w");
01309 if (!vstats_file) {
01310 perror("fopen");
01311 ffmpeg_exit(1);
01312 }
01313 }
01314
01315 enc = ost->st->codec;
01316 if (enc->codec_type == AVMEDIA_TYPE_VIDEO) {
01317 frame_number = ost->frame_number;
01318 fprintf(vstats_file, "frame= %5d q= %2.1f ", frame_number, enc->coded_frame->quality/(float)FF_QP2LAMBDA);
01319 if (enc->flags&CODEC_FLAG_PSNR)
01320 fprintf(vstats_file, "PSNR= %6.2f ", psnr(enc->coded_frame->error[0]/(enc->width*enc->height*255.0*255.0)));
01321
01322 fprintf(vstats_file,"f_size= %6d ", frame_size);
01323
01324 ti1 = ost->sync_opts * av_q2d(enc->time_base);
01325 if (ti1 < 0.01)
01326 ti1 = 0.01;
01327
01328 bitrate = (frame_size * 8) / av_q2d(enc->time_base) / 1000.0;
01329 avg_bitrate = (double)(video_size * 8) / ti1 / 1000.0;
01330 fprintf(vstats_file, "s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
01331 (double)video_size / 1024, ti1, bitrate, avg_bitrate);
01332 fprintf(vstats_file,"type= %c\n", av_get_pict_type_char(enc->coded_frame->pict_type));
01333 }
01334 }
01335
01336 static void print_report(AVFormatContext **output_files,
01337 AVOutputStream **ost_table, int nb_ostreams,
01338 int is_last_report)
01339 {
01340 char buf[1024];
01341 AVOutputStream *ost;
01342 AVFormatContext *oc;
01343 int64_t total_size;
01344 AVCodecContext *enc;
01345 int frame_number, vid, i;
01346 double bitrate, ti1, pts;
01347 static int64_t last_time = -1;
01348 static int qp_histogram[52];
01349
01350 if (!is_last_report) {
01351 int64_t cur_time;
01352
01353 cur_time = av_gettime();
01354 if (last_time == -1) {
01355 last_time = cur_time;
01356 return;
01357 }
01358 if ((cur_time - last_time) < 500000)
01359 return;
01360 last_time = cur_time;
01361 }
01362
01363
01364 oc = output_files[0];
01365
01366 total_size = avio_size(oc->pb);
01367 if(total_size<0)
01368 total_size= avio_tell(oc->pb);
01369
01370 buf[0] = '\0';
01371 ti1 = 1e10;
01372 vid = 0;
01373 for(i=0;i<nb_ostreams;i++) {
01374 ost = ost_table[i];
01375 enc = ost->st->codec;
01376 if (vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
01377 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "q=%2.1f ",
01378 !ost->st->stream_copy ?
01379 enc->coded_frame->quality/(float)FF_QP2LAMBDA : -1);
01380 }
01381 if (!vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
01382 float t = (av_gettime()-timer_start) / 1000000.0;
01383
01384 frame_number = ost->frame_number;
01385 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "frame=%5d fps=%3d q=%3.1f ",
01386 frame_number, (t>1)?(int)(frame_number/t+0.5) : 0,
01387 !ost->st->stream_copy ?
01388 enc->coded_frame->quality/(float)FF_QP2LAMBDA : -1);
01389 if(is_last_report)
01390 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "L");
01391 if(qp_hist){
01392 int j;
01393 int qp= lrintf(enc->coded_frame->quality/(float)FF_QP2LAMBDA);
01394 if(qp>=0 && qp<FF_ARRAY_ELEMS(qp_histogram))
01395 qp_histogram[qp]++;
01396 for(j=0; j<32; j++)
01397 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%X", (int)lrintf(log(qp_histogram[j]+1)/log(2)));
01398 }
01399 if (enc->flags&CODEC_FLAG_PSNR){
01400 int j;
01401 double error, error_sum=0;
01402 double scale, scale_sum=0;
01403 char type[3]= {'Y','U','V'};
01404 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "PSNR=");
01405 for(j=0; j<3; j++){
01406 if(is_last_report){
01407 error= enc->error[j];
01408 scale= enc->width*enc->height*255.0*255.0*frame_number;
01409 }else{
01410 error= enc->coded_frame->error[j];
01411 scale= enc->width*enc->height*255.0*255.0;
01412 }
01413 if(j) scale/=4;
01414 error_sum += error;
01415 scale_sum += scale;
01416 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%c:%2.2f ", type[j], psnr(error/scale));
01417 }
01418 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "*:%2.2f ", psnr(error_sum/scale_sum));
01419 }
01420 vid = 1;
01421 }
01422
01423 pts = (double)ost->st->pts.val * av_q2d(ost->st->time_base);
01424 if ((pts < ti1) && (pts > 0))
01425 ti1 = pts;
01426 }
01427 if (ti1 < 0.01)
01428 ti1 = 0.01;
01429
01430 if (verbose || is_last_report) {
01431 bitrate = (double)(total_size * 8) / ti1 / 1000.0;
01432
01433 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
01434 "size=%8.0fkB time=%0.2f bitrate=%6.1fkbits/s",
01435 (double)total_size / 1024, ti1, bitrate);
01436
01437 if (nb_frames_dup || nb_frames_drop)
01438 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), " dup=%d drop=%d",
01439 nb_frames_dup, nb_frames_drop);
01440
01441 if (verbose >= 0)
01442 fprintf(stderr, "%s \r", buf);
01443
01444 fflush(stderr);
01445 }
01446
01447 if (is_last_report && verbose >= 0){
01448 int64_t raw= audio_size + video_size + extra_size;
01449 fprintf(stderr, "\n");
01450 fprintf(stderr, "video:%1.0fkB audio:%1.0fkB global headers:%1.0fkB muxing overhead %f%%\n",
01451 video_size/1024.0,
01452 audio_size/1024.0,
01453 extra_size/1024.0,
01454 100.0*(total_size - raw)/raw
01455 );
01456 }
01457 }
01458
01459
01460 static int output_packet(AVInputStream *ist, int ist_index,
01461 AVOutputStream **ost_table, int nb_ostreams,
01462 const AVPacket *pkt)
01463 {
01464 AVFormatContext *os;
01465 AVOutputStream *ost;
01466 int ret, i;
01467 int got_picture;
01468 AVFrame picture;
01469 void *buffer_to_free;
01470 static unsigned int samples_size= 0;
01471 AVSubtitle subtitle, *subtitle_to_free;
01472 int64_t pkt_pts = AV_NOPTS_VALUE;
01473 #if CONFIG_AVFILTER
01474 int frame_available;
01475 #endif
01476
01477 AVPacket avpkt;
01478 int bps = av_get_bits_per_sample_fmt(ist->st->codec->sample_fmt)>>3;
01479
01480 if(ist->next_pts == AV_NOPTS_VALUE)
01481 ist->next_pts= ist->pts;
01482
01483 if (pkt == NULL) {
01484
01485 av_init_packet(&avpkt);
01486 avpkt.data = NULL;
01487 avpkt.size = 0;
01488 goto handle_eof;
01489 } else {
01490 avpkt = *pkt;
01491 }
01492
01493 if(pkt->dts != AV_NOPTS_VALUE)
01494 ist->next_pts = ist->pts = av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);
01495 if(pkt->pts != AV_NOPTS_VALUE)
01496 pkt_pts = av_rescale_q(pkt->pts, ist->st->time_base, AV_TIME_BASE_Q);
01497
01498
01499 while (avpkt.size > 0 || (!pkt && ist->next_pts != ist->pts)) {
01500 uint8_t *data_buf, *decoded_data_buf;
01501 int data_size, decoded_data_size;
01502 handle_eof:
01503 ist->pts= ist->next_pts;
01504
01505 if(avpkt.size && avpkt.size != pkt->size &&
01506 ((!ist->showed_multi_packet_warning && verbose>0) || verbose>1)){
01507 fprintf(stderr, "Multiple frames in a packet from stream %d\n", pkt->stream_index);
01508 ist->showed_multi_packet_warning=1;
01509 }
01510
01511
01512 decoded_data_buf = NULL;
01513 decoded_data_size= 0;
01514 data_buf = avpkt.data;
01515 data_size = avpkt.size;
01516 subtitle_to_free = NULL;
01517 if (ist->decoding_needed) {
01518 switch(ist->st->codec->codec_type) {
01519 case AVMEDIA_TYPE_AUDIO:{
01520 if(pkt && samples_size < FFMAX(pkt->size*sizeof(*samples), AVCODEC_MAX_AUDIO_FRAME_SIZE)) {
01521 samples_size = FFMAX(pkt->size*sizeof(*samples), AVCODEC_MAX_AUDIO_FRAME_SIZE);
01522 av_free(samples);
01523 samples= av_malloc(samples_size);
01524 }
01525 decoded_data_size= samples_size;
01526
01527
01528 ret = avcodec_decode_audio3(ist->st->codec, samples, &decoded_data_size,
01529 &avpkt);
01530 if (ret < 0)
01531 goto fail_decode;
01532 avpkt.data += ret;
01533 avpkt.size -= ret;
01534 data_size = ret;
01535
01536
01537 if (decoded_data_size <= 0) {
01538
01539 continue;
01540 }
01541 decoded_data_buf = (uint8_t *)samples;
01542 ist->next_pts += ((int64_t)AV_TIME_BASE/bps * decoded_data_size) /
01543 (ist->st->codec->sample_rate * ist->st->codec->channels);
01544 break;}
01545 case AVMEDIA_TYPE_VIDEO:
01546 decoded_data_size = (ist->st->codec->width * ist->st->codec->height * 3) / 2;
01547
01548 avcodec_get_frame_defaults(&picture);
01549 avpkt.pts = pkt_pts;
01550 avpkt.dts = ist->pts;
01551 pkt_pts = AV_NOPTS_VALUE;
01552
01553 ret = avcodec_decode_video2(ist->st->codec,
01554 &picture, &got_picture, &avpkt);
01555 ist->st->quality= picture.quality;
01556 if (ret < 0)
01557 goto fail_decode;
01558 if (!got_picture) {
01559
01560 goto discard_packet;
01561 }
01562 ist->next_pts = ist->pts = picture.best_effort_timestamp;
01563 if (ist->st->codec->time_base.num != 0) {
01564 int ticks= ist->st->parser ? ist->st->parser->repeat_pict+1 : ist->st->codec->ticks_per_frame;
01565 ist->next_pts += ((int64_t)AV_TIME_BASE *
01566 ist->st->codec->time_base.num * ticks) /
01567 ist->st->codec->time_base.den;
01568 }
01569 avpkt.size = 0;
01570 break;
01571 case AVMEDIA_TYPE_SUBTITLE:
01572 ret = avcodec_decode_subtitle2(ist->st->codec,
01573 &subtitle, &got_picture, &avpkt);
01574 if (ret < 0)
01575 goto fail_decode;
01576 if (!got_picture) {
01577 goto discard_packet;
01578 }
01579 subtitle_to_free = &subtitle;
01580 avpkt.size = 0;
01581 break;
01582 default:
01583 goto fail_decode;
01584 }
01585 } else {
01586 switch(ist->st->codec->codec_type) {
01587 case AVMEDIA_TYPE_AUDIO:
01588 ist->next_pts += ((int64_t)AV_TIME_BASE * ist->st->codec->frame_size) /
01589 ist->st->codec->sample_rate;
01590 break;
01591 case AVMEDIA_TYPE_VIDEO:
01592 if (ist->st->codec->time_base.num != 0) {
01593 int ticks= ist->st->parser ? ist->st->parser->repeat_pict+1 : ist->st->codec->ticks_per_frame;
01594 ist->next_pts += ((int64_t)AV_TIME_BASE *
01595 ist->st->codec->time_base.num * ticks) /
01596 ist->st->codec->time_base.den;
01597 }
01598 break;
01599 }
01600 ret = avpkt.size;
01601 avpkt.size = 0;
01602 }
01603
01604 buffer_to_free = NULL;
01605 if (ist->st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
01606 pre_process_video_frame(ist, (AVPicture *)&picture,
01607 &buffer_to_free);
01608 }
01609
01610 #if CONFIG_AVFILTER
01611 if(ist->st->codec->codec_type == AVMEDIA_TYPE_VIDEO){
01612 for(i=0;i<nb_ostreams;i++) {
01613 ost = ost_table[i];
01614 if (ost->input_video_filter && ost->source_index == ist_index) {
01615 AVRational sar;
01616 if (ist->st->sample_aspect_ratio.num) sar = ist->st->sample_aspect_ratio;
01617 else sar = ist->st->codec->sample_aspect_ratio;
01618
01619 av_vsrc_buffer_add_frame(ost->input_video_filter, &picture,
01620 ist->pts,
01621 sar);
01622 }
01623 }
01624 }
01625 #endif
01626
01627
01628 if (ist->st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
01629 if (audio_volume != 256) {
01630 short *volp;
01631 volp = samples;
01632 for(i=0;i<(decoded_data_size / sizeof(short));i++) {
01633 int v = ((*volp) * audio_volume + 128) >> 8;
01634 if (v < -32768) v = -32768;
01635 if (v > 32767) v = 32767;
01636 *volp++ = v;
01637 }
01638 }
01639 }
01640
01641
01642 if (rate_emu) {
01643 int64_t pts = av_rescale(ist->pts, 1000000, AV_TIME_BASE);
01644 int64_t now = av_gettime() - ist->start;
01645 if (pts > now)
01646 usleep(pts - now);
01647 }
01648
01649
01650 if (start_time == 0 || ist->pts >= start_time)
01651 for(i=0;i<nb_ostreams;i++) {
01652 int frame_size;
01653
01654 ost = ost_table[i];
01655 if (ost->source_index == ist_index) {
01656 #if CONFIG_AVFILTER
01657 frame_available = ist->st->codec->codec_type != AVMEDIA_TYPE_VIDEO ||
01658 !ost->output_video_filter || avfilter_poll_frame(ost->output_video_filter->inputs[0]);
01659 while (frame_available) {
01660 AVRational ist_pts_tb;
01661 if (ist->st->codec->codec_type == AVMEDIA_TYPE_VIDEO && ost->output_video_filter)
01662 get_filtered_video_frame(ost->output_video_filter, &picture, &ost->picref, &ist_pts_tb);
01663 if (ost->picref)
01664 ist->pts = av_rescale_q(ost->picref->pts, ist_pts_tb, AV_TIME_BASE_Q);
01665 #endif
01666 os = output_files[ost->file_index];
01667
01668
01669
01670
01671 if (ost->encoding_needed) {
01672 av_assert0(ist->decoding_needed);
01673 switch(ost->st->codec->codec_type) {
01674 case AVMEDIA_TYPE_AUDIO:
01675 do_audio_out(os, ost, ist, decoded_data_buf, decoded_data_size);
01676 break;
01677 case AVMEDIA_TYPE_VIDEO:
01678 #if CONFIG_AVFILTER
01679 if (ost->picref->video)
01680 ost->st->codec->sample_aspect_ratio = ost->picref->video->pixel_aspect;
01681 #endif
01682 do_video_out(os, ost, ist, &picture, &frame_size);
01683 if (vstats_filename && frame_size)
01684 do_video_stats(os, ost, frame_size);
01685 break;
01686 case AVMEDIA_TYPE_SUBTITLE:
01687 do_subtitle_out(os, ost, ist, &subtitle,
01688 pkt->pts);
01689 break;
01690 default:
01691 abort();
01692 }
01693 } else {
01694 AVFrame avframe;
01695 AVPacket opkt;
01696 int64_t ost_tb_start_time= av_rescale_q(start_time, AV_TIME_BASE_Q, ost->st->time_base);
01697
01698 av_init_packet(&opkt);
01699
01700 if ((!ost->frame_number && !(pkt->flags & AV_PKT_FLAG_KEY)) && !copy_initial_nonkeyframes)
01701 #if !CONFIG_AVFILTER
01702 continue;
01703 #else
01704 goto cont;
01705 #endif
01706
01707
01708
01709
01710 avcodec_get_frame_defaults(&avframe);
01711 ost->st->codec->coded_frame= &avframe;
01712 avframe.key_frame = pkt->flags & AV_PKT_FLAG_KEY;
01713
01714 if(ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
01715 audio_size += data_size;
01716 else if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
01717 video_size += data_size;
01718 ost->sync_opts++;
01719 }
01720
01721 opkt.stream_index= ost->index;
01722 if(pkt->pts != AV_NOPTS_VALUE)
01723 opkt.pts= av_rescale_q(pkt->pts, ist->st->time_base, ost->st->time_base) - ost_tb_start_time;
01724 else
01725 opkt.pts= AV_NOPTS_VALUE;
01726
01727 if (pkt->dts == AV_NOPTS_VALUE)
01728 opkt.dts = av_rescale_q(ist->pts, AV_TIME_BASE_Q, ost->st->time_base);
01729 else
01730 opkt.dts = av_rescale_q(pkt->dts, ist->st->time_base, ost->st->time_base);
01731 opkt.dts -= ost_tb_start_time;
01732
01733 opkt.duration = av_rescale_q(pkt->duration, ist->st->time_base, ost->st->time_base);
01734 opkt.flags= pkt->flags;
01735
01736
01737 if( ost->st->codec->codec_id != CODEC_ID_H264
01738 && ost->st->codec->codec_id != CODEC_ID_MPEG1VIDEO
01739 && ost->st->codec->codec_id != CODEC_ID_MPEG2VIDEO
01740 ) {
01741 if(av_parser_change(ist->st->parser, ost->st->codec, &opkt.data, &opkt.size, data_buf, data_size, pkt->flags & AV_PKT_FLAG_KEY))
01742 opkt.destruct= av_destruct_packet;
01743 } else {
01744 opkt.data = data_buf;
01745 opkt.size = data_size;
01746 }
01747
01748 write_frame(os, &opkt, ost->st->codec, ost->bitstream_filters);
01749 ost->st->codec->frame_number++;
01750 ost->frame_number++;
01751 av_free_packet(&opkt);
01752 }
01753 #if CONFIG_AVFILTER
01754 cont:
01755 frame_available = (ist->st->codec->codec_type == AVMEDIA_TYPE_VIDEO) &&
01756 ost->output_video_filter && avfilter_poll_frame(ost->output_video_filter->inputs[0]);
01757 if(ost->picref)
01758 avfilter_unref_buffer(ost->picref);
01759 }
01760 #endif
01761 }
01762 }
01763
01764 av_free(buffer_to_free);
01765
01766 if (subtitle_to_free) {
01767 avsubtitle_free(subtitle_to_free);
01768 subtitle_to_free = NULL;
01769 }
01770 }
01771 discard_packet:
01772 if (pkt == NULL) {
01773
01774
01775 for(i=0;i<nb_ostreams;i++) {
01776 ost = ost_table[i];
01777 if (ost->source_index == ist_index) {
01778 AVCodecContext *enc= ost->st->codec;
01779 os = output_files[ost->file_index];
01780
01781 if(ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO && enc->frame_size <=1)
01782 continue;
01783 if(ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO && (os->oformat->flags & AVFMT_RAWPICTURE))
01784 continue;
01785
01786 if (ost->encoding_needed) {
01787 for(;;) {
01788 AVPacket pkt;
01789 int fifo_bytes;
01790 av_init_packet(&pkt);
01791 pkt.stream_index= ost->index;
01792
01793 switch(ost->st->codec->codec_type) {
01794 case AVMEDIA_TYPE_AUDIO:
01795 fifo_bytes = av_fifo_size(ost->fifo);
01796 ret = 0;
01797
01798 if (fifo_bytes > 0) {
01799 int osize = av_get_bits_per_sample_fmt(enc->sample_fmt) >> 3;
01800 int fs_tmp = enc->frame_size;
01801
01802 av_fifo_generic_read(ost->fifo, audio_buf, fifo_bytes, NULL);
01803 if (enc->codec->capabilities & CODEC_CAP_SMALL_LAST_FRAME) {
01804 enc->frame_size = fifo_bytes / (osize * enc->channels);
01805 } else {
01806 int frame_bytes = enc->frame_size*osize*enc->channels;
01807 if (allocated_audio_buf_size < frame_bytes)
01808 ffmpeg_exit(1);
01809 memset(audio_buf+fifo_bytes, 0, frame_bytes - fifo_bytes);
01810 }
01811
01812 ret = avcodec_encode_audio(enc, bit_buffer, bit_buffer_size, (short *)audio_buf);
01813 pkt.duration = av_rescale((int64_t)enc->frame_size*ost->st->time_base.den,
01814 ost->st->time_base.num, enc->sample_rate);
01815 enc->frame_size = fs_tmp;
01816 }
01817 if(ret <= 0) {
01818 ret = avcodec_encode_audio(enc, bit_buffer, bit_buffer_size, NULL);
01819 }
01820 if (ret < 0) {
01821 fprintf(stderr, "Audio encoding failed\n");
01822 ffmpeg_exit(1);
01823 }
01824 audio_size += ret;
01825 pkt.flags |= AV_PKT_FLAG_KEY;
01826 break;
01827 case AVMEDIA_TYPE_VIDEO:
01828 ret = avcodec_encode_video(enc, bit_buffer, bit_buffer_size, NULL);
01829 if (ret < 0) {
01830 fprintf(stderr, "Video encoding failed\n");
01831 ffmpeg_exit(1);
01832 }
01833 video_size += ret;
01834 if(enc->coded_frame && enc->coded_frame->key_frame)
01835 pkt.flags |= AV_PKT_FLAG_KEY;
01836 if (ost->logfile && enc->stats_out) {
01837 fprintf(ost->logfile, "%s", enc->stats_out);
01838 }
01839 break;
01840 default:
01841 ret=-1;
01842 }
01843
01844 if(ret<=0)
01845 break;
01846 pkt.data= bit_buffer;
01847 pkt.size= ret;
01848 if(enc->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)
01849 pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
01850 write_frame(os, &pkt, ost->st->codec, ost->bitstream_filters);
01851 }
01852 }
01853 }
01854 }
01855 }
01856
01857 return 0;
01858 fail_decode:
01859 return -1;
01860 }
01861
01862 static void print_sdp(AVFormatContext **avc, int n)
01863 {
01864 char sdp[2048];
01865
01866 avf_sdp_create(avc, n, sdp, sizeof(sdp));
01867 printf("SDP:\n%s\n", sdp);
01868 fflush(stdout);
01869 }
01870
01871 static int copy_chapters(int infile, int outfile)
01872 {
01873 AVFormatContext *is = input_files[infile];
01874 AVFormatContext *os = output_files[outfile];
01875 int i;
01876
01877 for (i = 0; i < is->nb_chapters; i++) {
01878 AVChapter *in_ch = is->chapters[i], *out_ch;
01879 int64_t ts_off = av_rescale_q(start_time - input_files_ts_offset[infile],
01880 AV_TIME_BASE_Q, in_ch->time_base);
01881 int64_t rt = (recording_time == INT64_MAX) ? INT64_MAX :
01882 av_rescale_q(recording_time, AV_TIME_BASE_Q, in_ch->time_base);
01883
01884
01885 if (in_ch->end < ts_off)
01886 continue;
01887 if (rt != INT64_MAX && in_ch->start > rt + ts_off)
01888 break;
01889
01890 out_ch = av_mallocz(sizeof(AVChapter));
01891 if (!out_ch)
01892 return AVERROR(ENOMEM);
01893
01894 out_ch->id = in_ch->id;
01895 out_ch->time_base = in_ch->time_base;
01896 out_ch->start = FFMAX(0, in_ch->start - ts_off);
01897 out_ch->end = FFMIN(rt, in_ch->end - ts_off);
01898
01899 if (metadata_chapters_autocopy)
01900 av_metadata_copy(&out_ch->metadata, in_ch->metadata, 0);
01901
01902 os->nb_chapters++;
01903 os->chapters = av_realloc(os->chapters, sizeof(AVChapter)*os->nb_chapters);
01904 if (!os->chapters)
01905 return AVERROR(ENOMEM);
01906 os->chapters[os->nb_chapters - 1] = out_ch;
01907 }
01908 return 0;
01909 }
01910
01911 static void parse_forced_key_frames(char *kf, AVOutputStream *ost,
01912 AVCodecContext *avctx)
01913 {
01914 char *p;
01915 int n = 1, i;
01916 int64_t t;
01917
01918 for (p = kf; *p; p++)
01919 if (*p == ',')
01920 n++;
01921 ost->forced_kf_count = n;
01922 ost->forced_kf_pts = av_malloc(sizeof(*ost->forced_kf_pts) * n);
01923 if (!ost->forced_kf_pts) {
01924 av_log(NULL, AV_LOG_FATAL, "Could not allocate forced key frames array.\n");
01925 ffmpeg_exit(1);
01926 }
01927 for (i = 0; i < n; i++) {
01928 p = i ? strchr(p, ',') + 1 : kf;
01929 t = parse_time_or_die("force_key_frames", p, 1);
01930 ost->forced_kf_pts[i] = av_rescale_q(t, AV_TIME_BASE_Q, avctx->time_base);
01931 }
01932 }
01933
01934
01935
01936
01937 static int transcode(AVFormatContext **output_files,
01938 int nb_output_files,
01939 AVFormatContext **input_files,
01940 int nb_input_files,
01941 AVStreamMap *stream_maps, int nb_stream_maps)
01942 {
01943 int ret = 0, i, j, k, n, nb_istreams = 0, nb_ostreams = 0;
01944 AVFormatContext *is, *os;
01945 AVCodecContext *codec, *icodec;
01946 AVOutputStream *ost, **ost_table = NULL;
01947 AVInputStream *ist, **ist_table = NULL;
01948 AVInputFile *file_table;
01949 char error[1024];
01950 int key;
01951 int want_sdp = 1;
01952 uint8_t no_packet[MAX_FILES]={0};
01953 int no_packet_count=0;
01954
01955 file_table= av_mallocz(nb_input_files * sizeof(AVInputFile));
01956 if (!file_table)
01957 goto fail;
01958
01959
01960 j = 0;
01961 for(i=0;i<nb_input_files;i++) {
01962 is = input_files[i];
01963 file_table[i].ist_index = j;
01964 file_table[i].nb_streams = is->nb_streams;
01965 j += is->nb_streams;
01966 }
01967 nb_istreams = j;
01968
01969 ist_table = av_mallocz(nb_istreams * sizeof(AVInputStream *));
01970 if (!ist_table)
01971 goto fail;
01972
01973 for(i=0;i<nb_istreams;i++) {
01974 ist = av_mallocz(sizeof(AVInputStream));
01975 if (!ist)
01976 goto fail;
01977 ist_table[i] = ist;
01978 }
01979 j = 0;
01980 for(i=0;i<nb_input_files;i++) {
01981 is = input_files[i];
01982 for(k=0;k<is->nb_streams;k++) {
01983 ist = ist_table[j++];
01984 ist->st = is->streams[k];
01985 ist->file_index = i;
01986 ist->index = k;
01987 ist->discard = 1;
01988
01989
01990 if (rate_emu) {
01991 ist->start = av_gettime();
01992 }
01993 }
01994 }
01995
01996
01997 nb_ostreams = 0;
01998 for(i=0;i<nb_output_files;i++) {
01999 os = output_files[i];
02000 if (!os->nb_streams && !(os->oformat->flags & AVFMT_NOSTREAMS)) {
02001 av_dump_format(output_files[i], i, output_files[i]->filename, 1);
02002 fprintf(stderr, "Output file #%d does not contain any stream\n", i);
02003 ret = AVERROR(EINVAL);
02004 goto fail;
02005 }
02006 nb_ostreams += os->nb_streams;
02007 }
02008 if (nb_stream_maps > 0 && nb_stream_maps != nb_ostreams) {
02009 fprintf(stderr, "Number of stream maps must match number of output streams\n");
02010 ret = AVERROR(EINVAL);
02011 goto fail;
02012 }
02013
02014
02015 for(i=0;i<nb_stream_maps;i++) {
02016 int fi = stream_maps[i].file_index;
02017 int si = stream_maps[i].stream_index;
02018
02019 if (fi < 0 || fi > nb_input_files - 1 ||
02020 si < 0 || si > file_table[fi].nb_streams - 1) {
02021 fprintf(stderr,"Could not find input stream #%d.%d\n", fi, si);
02022 ret = AVERROR(EINVAL);
02023 goto fail;
02024 }
02025 fi = stream_maps[i].sync_file_index;
02026 si = stream_maps[i].sync_stream_index;
02027 if (fi < 0 || fi > nb_input_files - 1 ||
02028 si < 0 || si > file_table[fi].nb_streams - 1) {
02029 fprintf(stderr,"Could not find sync stream #%d.%d\n", fi, si);
02030 ret = AVERROR(EINVAL);
02031 goto fail;
02032 }
02033 }
02034
02035 ost_table = av_mallocz(sizeof(AVOutputStream *) * nb_ostreams);
02036 if (!ost_table)
02037 goto fail;
02038 n = 0;
02039 for(k=0;k<nb_output_files;k++) {
02040 os = output_files[k];
02041 for(i=0;i<os->nb_streams;i++,n++) {
02042 int found;
02043 ost = ost_table[n] = output_streams_for_file[k][i];
02044 ost->st = os->streams[i];
02045 if (nb_stream_maps > 0) {
02046 ost->source_index = file_table[stream_maps[n].file_index].ist_index +
02047 stream_maps[n].stream_index;
02048
02049
02050 if (ist_table[ost->source_index]->st->codec->codec_type != ost->st->codec->codec_type) {
02051 int i= ost->file_index;
02052 av_dump_format(output_files[i], i, output_files[i]->filename, 1);
02053 fprintf(stderr, "Codec type mismatch for mapping #%d.%d -> #%d.%d\n",
02054 stream_maps[n].file_index, stream_maps[n].stream_index,
02055 ost->file_index, ost->index);
02056 ffmpeg_exit(1);
02057 }
02058
02059 } else {
02060 int best_nb_frames=-1;
02061
02062 found = 0;
02063 for(j=0;j<nb_istreams;j++) {
02064 int skip=0;
02065 ist = ist_table[j];
02066 if(opt_programid){
02067 int pi,si;
02068 AVFormatContext *f= input_files[ ist->file_index ];
02069 skip=1;
02070 for(pi=0; pi<f->nb_programs; pi++){
02071 AVProgram *p= f->programs[pi];
02072 if(p->id == opt_programid)
02073 for(si=0; si<p->nb_stream_indexes; si++){
02074 if(f->streams[ p->stream_index[si] ] == ist->st)
02075 skip=0;
02076 }
02077 }
02078 }
02079 if (ist->discard && ist->st->discard != AVDISCARD_ALL && !skip &&
02080 ist->st->codec->codec_type == ost->st->codec->codec_type) {
02081 if(best_nb_frames < ist->st->codec_info_nb_frames){
02082 best_nb_frames= ist->st->codec_info_nb_frames;
02083 ost->source_index = j;
02084 found = 1;
02085 }
02086 }
02087 }
02088
02089 if (!found) {
02090 if(! opt_programid) {
02091
02092 for(j=0;j<nb_istreams;j++) {
02093 ist = ist_table[j];
02094 if ( ist->st->codec->codec_type == ost->st->codec->codec_type
02095 && ist->st->discard != AVDISCARD_ALL) {
02096 ost->source_index = j;
02097 found = 1;
02098 }
02099 }
02100 }
02101 if (!found) {
02102 int i= ost->file_index;
02103 av_dump_format(output_files[i], i, output_files[i]->filename, 1);
02104 fprintf(stderr, "Could not find input stream matching output stream #%d.%d\n",
02105 ost->file_index, ost->index);
02106 ffmpeg_exit(1);
02107 }
02108 }
02109 }
02110 ist = ist_table[ost->source_index];
02111 ist->discard = 0;
02112 ost->sync_ist = (nb_stream_maps > 0) ?
02113 ist_table[file_table[stream_maps[n].sync_file_index].ist_index +
02114 stream_maps[n].sync_stream_index] : ist;
02115 }
02116 }
02117
02118
02119 for(i=0;i<nb_ostreams;i++) {
02120 ost = ost_table[i];
02121 os = output_files[ost->file_index];
02122 ist = ist_table[ost->source_index];
02123
02124 codec = ost->st->codec;
02125 icodec = ist->st->codec;
02126
02127 if (metadata_streams_autocopy)
02128 av_metadata_copy(&ost->st->metadata, ist->st->metadata,
02129 AV_METADATA_DONT_OVERWRITE);
02130
02131 ost->st->disposition = ist->st->disposition;
02132 codec->bits_per_raw_sample= icodec->bits_per_raw_sample;
02133 codec->chroma_sample_location = icodec->chroma_sample_location;
02134
02135 if (ost->st->stream_copy) {
02136 uint64_t extra_size = (uint64_t)icodec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE;
02137
02138 if (extra_size > INT_MAX)
02139 goto fail;
02140
02141
02142 codec->codec_id = icodec->codec_id;
02143 codec->codec_type = icodec->codec_type;
02144
02145 if(!codec->codec_tag){
02146 if( !os->oformat->codec_tag
02147 || av_codec_get_id (os->oformat->codec_tag, icodec->codec_tag) == codec->codec_id
02148 || av_codec_get_tag(os->oformat->codec_tag, icodec->codec_id) <= 0)
02149 codec->codec_tag = icodec->codec_tag;
02150 }
02151
02152 codec->bit_rate = icodec->bit_rate;
02153 codec->rc_max_rate = icodec->rc_max_rate;
02154 codec->rc_buffer_size = icodec->rc_buffer_size;
02155 codec->extradata= av_mallocz(extra_size);
02156 if (!codec->extradata)
02157 goto fail;
02158 memcpy(codec->extradata, icodec->extradata, icodec->extradata_size);
02159 codec->extradata_size= icodec->extradata_size;
02160 if(!copy_tb && av_q2d(icodec->time_base)*icodec->ticks_per_frame > av_q2d(ist->st->time_base) && av_q2d(ist->st->time_base) < 1.0/500){
02161 codec->time_base = icodec->time_base;
02162 codec->time_base.num *= icodec->ticks_per_frame;
02163 av_reduce(&codec->time_base.num, &codec->time_base.den,
02164 codec->time_base.num, codec->time_base.den, INT_MAX);
02165 }else
02166 codec->time_base = ist->st->time_base;
02167 switch(codec->codec_type) {
02168 case AVMEDIA_TYPE_AUDIO:
02169 if(audio_volume != 256) {
02170 fprintf(stderr,"-acodec copy and -vol are incompatible (frames are not decoded)\n");
02171 ffmpeg_exit(1);
02172 }
02173 codec->channel_layout = icodec->channel_layout;
02174 codec->sample_rate = icodec->sample_rate;
02175 codec->channels = icodec->channels;
02176 codec->frame_size = icodec->frame_size;
02177 codec->block_align= icodec->block_align;
02178 if(codec->block_align == 1 && codec->codec_id == CODEC_ID_MP3)
02179 codec->block_align= 0;
02180 if(codec->codec_id == CODEC_ID_AC3)
02181 codec->block_align= 0;
02182 break;
02183 case AVMEDIA_TYPE_VIDEO:
02184 codec->pix_fmt = icodec->pix_fmt;
02185 codec->width = icodec->width;
02186 codec->height = icodec->height;
02187 codec->has_b_frames = icodec->has_b_frames;
02188 break;
02189 case AVMEDIA_TYPE_SUBTITLE:
02190 codec->width = icodec->width;
02191 codec->height = icodec->height;
02192 break;
02193 default:
02194 abort();
02195 }
02196 } else {
02197 switch(codec->codec_type) {
02198 case AVMEDIA_TYPE_AUDIO:
02199 ost->fifo= av_fifo_alloc(1024);
02200 if(!ost->fifo)
02201 goto fail;
02202 ost->reformat_pair = MAKE_SFMT_PAIR(AV_SAMPLE_FMT_NONE,AV_SAMPLE_FMT_NONE);
02203 ost->audio_resample = codec->sample_rate != icodec->sample_rate || audio_sync_method > 1;
02204 icodec->request_channels = codec->channels;
02205 ist->decoding_needed = 1;
02206 ost->encoding_needed = 1;
02207 ost->resample_sample_fmt = icodec->sample_fmt;
02208 ost->resample_sample_rate = icodec->sample_rate;
02209 ost->resample_channels = icodec->channels;
02210 break;
02211 case AVMEDIA_TYPE_VIDEO:
02212 if (ost->st->codec->pix_fmt == PIX_FMT_NONE) {
02213 fprintf(stderr, "Video pixel format is unknown, stream cannot be encoded\n");
02214 ffmpeg_exit(1);
02215 }
02216 ost->video_resample = (codec->width != icodec->width ||
02217 codec->height != icodec->height ||
02218 (codec->pix_fmt != icodec->pix_fmt));
02219 if (ost->video_resample) {
02220 #if !CONFIG_AVFILTER
02221 avcodec_get_frame_defaults(&ost->pict_tmp);
02222 if(avpicture_alloc((AVPicture*)&ost->pict_tmp, codec->pix_fmt,
02223 codec->width, codec->height)) {
02224 fprintf(stderr, "Cannot allocate temp picture, check pix fmt\n");
02225 ffmpeg_exit(1);
02226 }
02227 sws_flags = av_get_int(sws_opts, "sws_flags", NULL);
02228 ost->img_resample_ctx = sws_getContext(
02229 icodec->width,
02230 icodec->height,
02231 icodec->pix_fmt,
02232 codec->width,
02233 codec->height,
02234 codec->pix_fmt,
02235 sws_flags, NULL, NULL, NULL);
02236 if (ost->img_resample_ctx == NULL) {
02237 fprintf(stderr, "Cannot get resampling context\n");
02238 ffmpeg_exit(1);
02239 }
02240
02241 ost->original_height = icodec->height;
02242 ost->original_width = icodec->width;
02243 #endif
02244 codec->bits_per_raw_sample= 0;
02245 }
02246 ost->resample_height = icodec->height;
02247 ost->resample_width = icodec->width;
02248 ost->resample_pix_fmt= icodec->pix_fmt;
02249 ost->encoding_needed = 1;
02250 ist->decoding_needed = 1;
02251
02252 #if CONFIG_AVFILTER
02253 if (configure_filters(ist, ost)) {
02254 fprintf(stderr, "Error opening filters!\n");
02255 exit(1);
02256 }
02257 #endif
02258 break;
02259 case AVMEDIA_TYPE_SUBTITLE:
02260 ost->encoding_needed = 1;
02261 ist->decoding_needed = 1;
02262 break;
02263 default:
02264 abort();
02265 break;
02266 }
02267
02268 if (ost->encoding_needed &&
02269 (codec->flags & (CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2))) {
02270 char logfilename[1024];
02271 FILE *f;
02272
02273 snprintf(logfilename, sizeof(logfilename), "%s-%d.log",
02274 pass_logfilename_prefix ? pass_logfilename_prefix : DEFAULT_PASS_LOGFILENAME_PREFIX,
02275 i);
02276 if (codec->flags & CODEC_FLAG_PASS1) {
02277 f = fopen(logfilename, "wb");
02278 if (!f) {
02279 fprintf(stderr, "Cannot write log file '%s' for pass-1 encoding: %s\n", logfilename, strerror(errno));
02280 ffmpeg_exit(1);
02281 }
02282 ost->logfile = f;
02283 } else {
02284 char *logbuffer;
02285 size_t logbuffer_size;
02286 if (read_file(logfilename, &logbuffer, &logbuffer_size) < 0) {
02287 fprintf(stderr, "Error reading log file '%s' for pass-2 encoding\n", logfilename);
02288 ffmpeg_exit(1);
02289 }
02290 codec->stats_in = logbuffer;
02291 }
02292 }
02293 }
02294 if(codec->codec_type == AVMEDIA_TYPE_VIDEO){
02295 int size= codec->width * codec->height;
02296 bit_buffer_size= FFMAX(bit_buffer_size, 6*size + 200);
02297 }
02298 }
02299
02300 if (!bit_buffer)
02301 bit_buffer = av_malloc(bit_buffer_size);
02302 if (!bit_buffer) {
02303 fprintf(stderr, "Cannot allocate %d bytes output buffer\n",
02304 bit_buffer_size);
02305 ret = AVERROR(ENOMEM);
02306 goto fail;
02307 }
02308
02309
02310 for(i=0;i<nb_ostreams;i++) {
02311 ost = ost_table[i];
02312 if (ost->encoding_needed) {
02313 AVCodec *codec = i < nb_output_codecs ? output_codecs[i] : NULL;
02314 AVCodecContext *dec = ist_table[ost->source_index]->st->codec;
02315 if (!codec)
02316 codec = avcodec_find_encoder(ost->st->codec->codec_id);
02317 if (!codec) {
02318 snprintf(error, sizeof(error), "Encoder (codec id %d) not found for output stream #%d.%d",
02319 ost->st->codec->codec_id, ost->file_index, ost->index);
02320 ret = AVERROR(EINVAL);
02321 goto dump_format;
02322 }
02323 if (dec->subtitle_header) {
02324 ost->st->codec->subtitle_header = av_malloc(dec->subtitle_header_size);
02325 if (!ost->st->codec->subtitle_header) {
02326 ret = AVERROR(ENOMEM);
02327 goto dump_format;
02328 }
02329 memcpy(ost->st->codec->subtitle_header, dec->subtitle_header, dec->subtitle_header_size);
02330 ost->st->codec->subtitle_header_size = dec->subtitle_header_size;
02331 }
02332 if (avcodec_open(ost->st->codec, codec) < 0) {
02333 snprintf(error, sizeof(error), "Error while opening encoder for output stream #%d.%d - maybe incorrect parameters such as bit_rate, rate, width or height",
02334 ost->file_index, ost->index);
02335 ret = AVERROR(EINVAL);
02336 goto dump_format;
02337 }
02338 extra_size += ost->st->codec->extradata_size;
02339 }
02340 }
02341
02342
02343 for(i=0;i<nb_istreams;i++) {
02344 ist = ist_table[i];
02345 if (ist->decoding_needed) {
02346 AVCodec *codec = i < nb_input_codecs ? input_codecs[i] : NULL;
02347 if (!codec)
02348 codec = avcodec_find_decoder(ist->st->codec->codec_id);
02349 if (!codec) {
02350 snprintf(error, sizeof(error), "Decoder (codec id %d) not found for input stream #%d.%d",
02351 ist->st->codec->codec_id, ist->file_index, ist->index);
02352 ret = AVERROR(EINVAL);
02353 goto dump_format;
02354 }
02355 if (avcodec_open(ist->st->codec, codec) < 0) {
02356 snprintf(error, sizeof(error), "Error while opening decoder for input stream #%d.%d",
02357 ist->file_index, ist->index);
02358 ret = AVERROR(EINVAL);
02359 goto dump_format;
02360 }
02361
02362
02363 }
02364 }
02365
02366
02367 for(i=0;i<nb_istreams;i++) {
02368 AVStream *st;
02369 ist = ist_table[i];
02370 st= ist->st;
02371 ist->pts = st->avg_frame_rate.num ? - st->codec->has_b_frames*AV_TIME_BASE / av_q2d(st->avg_frame_rate) : 0;
02372 ist->next_pts = AV_NOPTS_VALUE;
02373 ist->is_start = 1;
02374 }
02375
02376
02377 for (i=0;i<nb_meta_data_maps;i++) {
02378 AVFormatContext *files[2];
02379 AVMetadata **meta[2];
02380 int j;
02381
02382 #define METADATA_CHECK_INDEX(index, nb_elems, desc)\
02383 if ((index) < 0 || (index) >= (nb_elems)) {\
02384 snprintf(error, sizeof(error), "Invalid %s index %d while processing metadata maps\n",\
02385 (desc), (index));\
02386 ret = AVERROR(EINVAL);\
02387 goto dump_format;\
02388 }
02389
02390 int out_file_index = meta_data_maps[i][0].file;
02391 int in_file_index = meta_data_maps[i][1].file;
02392 if (in_file_index < 0 || out_file_index < 0)
02393 continue;
02394 METADATA_CHECK_INDEX(out_file_index, nb_output_files, "output file")
02395 METADATA_CHECK_INDEX(in_file_index, nb_input_files, "input file")
02396
02397 files[0] = output_files[out_file_index];
02398 files[1] = input_files[in_file_index];
02399
02400 for (j = 0; j < 2; j++) {
02401 AVMetaDataMap *map = &meta_data_maps[i][j];
02402
02403 switch (map->type) {
02404 case 'g':
02405 meta[j] = &files[j]->metadata;
02406 break;
02407 case 's':
02408 METADATA_CHECK_INDEX(map->index, files[j]->nb_streams, "stream")
02409 meta[j] = &files[j]->streams[map->index]->metadata;
02410 break;
02411 case 'c':
02412 METADATA_CHECK_INDEX(map->index, files[j]->nb_chapters, "chapter")
02413 meta[j] = &files[j]->chapters[map->index]->metadata;
02414 break;
02415 case 'p':
02416 METADATA_CHECK_INDEX(map->index, files[j]->nb_programs, "program")
02417 meta[j] = &files[j]->programs[map->index]->metadata;
02418 break;
02419 }
02420 }
02421
02422 av_metadata_copy(meta[0], *meta[1], AV_METADATA_DONT_OVERWRITE);
02423 }
02424
02425
02426 if (metadata_global_autocopy) {
02427
02428 for (i = 0; i < nb_output_files; i++)
02429 av_metadata_copy(&output_files[i]->metadata, input_files[0]->metadata,
02430 AV_METADATA_DONT_OVERWRITE);
02431 }
02432
02433
02434 for (i = 0; i < nb_chapter_maps; i++) {
02435 int infile = chapter_maps[i].in_file;
02436 int outfile = chapter_maps[i].out_file;
02437
02438 if (infile < 0 || outfile < 0)
02439 continue;
02440 if (infile >= nb_input_files) {
02441 snprintf(error, sizeof(error), "Invalid input file index %d in chapter mapping.\n", infile);
02442 ret = AVERROR(EINVAL);
02443 goto dump_format;
02444 }
02445 if (outfile >= nb_output_files) {
02446 snprintf(error, sizeof(error), "Invalid output file index %d in chapter mapping.\n",outfile);
02447 ret = AVERROR(EINVAL);
02448 goto dump_format;
02449 }
02450 copy_chapters(infile, outfile);
02451 }
02452
02453
02454 if (!nb_chapter_maps)
02455 for (i = 0; i < nb_input_files; i++) {
02456 if (!input_files[i]->nb_chapters)
02457 continue;
02458
02459 for (j = 0; j < nb_output_files; j++)
02460 if ((ret = copy_chapters(i, j)) < 0)
02461 goto dump_format;
02462 break;
02463 }
02464
02465
02466 for(i=0;i<nb_output_files;i++) {
02467 os = output_files[i];
02468 if (av_write_header(os) < 0) {
02469 snprintf(error, sizeof(error), "Could not write header for output file #%d (incorrect codec parameters ?)", i);
02470 ret = AVERROR(EINVAL);
02471 goto dump_format;
02472 }
02473 if (strcmp(output_files[i]->oformat->name, "rtp")) {
02474 want_sdp = 0;
02475 }
02476 }
02477
02478 dump_format:
02479
02480
02481 for(i=0;i<nb_output_files;i++) {
02482 av_dump_format(output_files[i], i, output_files[i]->filename, 1);
02483 }
02484
02485
02486 if (verbose >= 0) {
02487 fprintf(stderr, "Stream mapping:\n");
02488 for(i=0;i<nb_ostreams;i++) {
02489 ost = ost_table[i];
02490 fprintf(stderr, " Stream #%d.%d -> #%d.%d",
02491 ist_table[ost->source_index]->file_index,
02492 ist_table[ost->source_index]->index,
02493 ost->file_index,
02494 ost->index);
02495 if (ost->sync_ist != ist_table[ost->source_index])
02496 fprintf(stderr, " [sync #%d.%d]",
02497 ost->sync_ist->file_index,
02498 ost->sync_ist->index);
02499 fprintf(stderr, "\n");
02500 }
02501 }
02502
02503 if (ret) {
02504 fprintf(stderr, "%s\n", error);
02505 goto fail;
02506 }
02507
02508 if (want_sdp) {
02509 print_sdp(output_files, nb_output_files);
02510 }
02511
02512 if (!using_stdin) {
02513 if(verbose >= 0)
02514 fprintf(stderr, "Press [q] to stop encoding\n");
02515 url_set_interrupt_cb(decode_interrupt_cb);
02516 }
02517 term_init();
02518
02519 timer_start = av_gettime();
02520
02521 for(; received_sigterm == 0;) {
02522 int file_index, ist_index;
02523 AVPacket pkt;
02524 double ipts_min;
02525 double opts_min;
02526
02527 redo:
02528 ipts_min= 1e100;
02529 opts_min= 1e100;
02530
02531 if (!using_stdin) {
02532 if (q_pressed)
02533 break;
02534
02535 key = read_key();
02536 if (key == 'q')
02537 break;
02538 }
02539
02540
02541
02542 file_index = -1;
02543 for(i=0;i<nb_ostreams;i++) {
02544 double ipts, opts;
02545 ost = ost_table[i];
02546 os = output_files[ost->file_index];
02547 ist = ist_table[ost->source_index];
02548 if(ist->is_past_recording_time || no_packet[ist->file_index])
02549 continue;
02550 opts = ost->st->pts.val * av_q2d(ost->st->time_base);
02551 ipts = (double)ist->pts;
02552 if (!file_table[ist->file_index].eof_reached){
02553 if(ipts < ipts_min) {
02554 ipts_min = ipts;
02555 if(input_sync ) file_index = ist->file_index;
02556 }
02557 if(opts < opts_min) {
02558 opts_min = opts;
02559 if(!input_sync) file_index = ist->file_index;
02560 }
02561 }
02562 if(ost->frame_number >= max_frames[ost->st->codec->codec_type]){
02563 file_index= -1;
02564 break;
02565 }
02566 }
02567
02568 if (file_index < 0) {
02569 if(no_packet_count){
02570 no_packet_count=0;
02571 memset(no_packet, 0, sizeof(no_packet));
02572 usleep(10000);
02573 continue;
02574 }
02575 break;
02576 }
02577
02578
02579 if (limit_filesize != 0 && limit_filesize <= avio_tell(output_files[0]->pb))
02580 break;
02581
02582
02583 is = input_files[file_index];
02584 ret= av_read_frame(is, &pkt);
02585 if(ret == AVERROR(EAGAIN)){
02586 no_packet[file_index]=1;
02587 no_packet_count++;
02588 continue;
02589 }
02590 if (ret < 0) {
02591 file_table[file_index].eof_reached = 1;
02592 if (opt_shortest)
02593 break;
02594 else
02595 continue;
02596 }
02597
02598 no_packet_count=0;
02599 memset(no_packet, 0, sizeof(no_packet));
02600
02601 if (do_pkt_dump) {
02602 av_pkt_dump_log2(NULL, AV_LOG_DEBUG, &pkt, do_hex_dump,
02603 is->streams[pkt.stream_index]);
02604 }
02605
02606
02607 if (pkt.stream_index >= file_table[file_index].nb_streams)
02608 goto discard_packet;
02609 ist_index = file_table[file_index].ist_index + pkt.stream_index;
02610 ist = ist_table[ist_index];
02611 if (ist->discard)
02612 goto discard_packet;
02613
02614 if (pkt.dts != AV_NOPTS_VALUE)
02615 pkt.dts += av_rescale_q(input_files_ts_offset[ist->file_index], AV_TIME_BASE_Q, ist->st->time_base);
02616 if (pkt.pts != AV_NOPTS_VALUE)
02617 pkt.pts += av_rescale_q(input_files_ts_offset[ist->file_index], AV_TIME_BASE_Q, ist->st->time_base);
02618
02619 if (pkt.stream_index < nb_input_files_ts_scale[file_index]
02620 && input_files_ts_scale[file_index][pkt.stream_index]){
02621 if(pkt.pts != AV_NOPTS_VALUE)
02622 pkt.pts *= input_files_ts_scale[file_index][pkt.stream_index];
02623 if(pkt.dts != AV_NOPTS_VALUE)
02624 pkt.dts *= input_files_ts_scale[file_index][pkt.stream_index];
02625 }
02626
02627
02628 if (pkt.dts != AV_NOPTS_VALUE && ist->next_pts != AV_NOPTS_VALUE
02629 && (is->iformat->flags & AVFMT_TS_DISCONT)) {
02630 int64_t pkt_dts= av_rescale_q(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q);
02631 int64_t delta= pkt_dts - ist->next_pts;
02632 if((FFABS(delta) > 1LL*dts_delta_threshold*AV_TIME_BASE || pkt_dts+1<ist->pts)&& !copy_ts){
02633 input_files_ts_offset[ist->file_index]-= delta;
02634 if (verbose > 2)
02635 fprintf(stderr, "timestamp discontinuity %"PRId64", new offset= %"PRId64"\n", delta, input_files_ts_offset[ist->file_index]);
02636 pkt.dts-= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
02637 if(pkt.pts != AV_NOPTS_VALUE)
02638 pkt.pts-= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
02639 }
02640 }
02641
02642
02643 if (recording_time != INT64_MAX &&
02644 av_compare_ts(pkt.pts, ist->st->time_base, recording_time + start_time, (AVRational){1, 1000000}) >= 0) {
02645 ist->is_past_recording_time = 1;
02646 goto discard_packet;
02647 }
02648
02649
02650 if (output_packet(ist, ist_index, ost_table, nb_ostreams, &pkt) < 0) {
02651
02652 if (verbose >= 0)
02653 fprintf(stderr, "Error while decoding stream #%d.%d\n",
02654 ist->file_index, ist->index);
02655 if (exit_on_error)
02656 ffmpeg_exit(1);
02657 av_free_packet(&pkt);
02658 goto redo;
02659 }
02660
02661 discard_packet:
02662 av_free_packet(&pkt);
02663
02664
02665 print_report(output_files, ost_table, nb_ostreams, 0);
02666 }
02667
02668
02669 for(i=0;i<nb_istreams;i++) {
02670 ist = ist_table[i];
02671 if (ist->decoding_needed) {
02672 output_packet(ist, i, ost_table, nb_ostreams, NULL);
02673 }
02674 }
02675
02676 term_exit();
02677
02678
02679 for(i=0;i<nb_output_files;i++) {
02680 os = output_files[i];
02681 av_write_trailer(os);
02682 }
02683
02684
02685 print_report(output_files, ost_table, nb_ostreams, 1);
02686
02687
02688 for(i=0;i<nb_ostreams;i++) {
02689 ost = ost_table[i];
02690 if (ost->encoding_needed) {
02691 av_freep(&ost->st->codec->stats_in);
02692 avcodec_close(ost->st->codec);
02693 }
02694 #if CONFIG_AVFILTER
02695 avfilter_graph_free(&ost->graph);
02696 #endif
02697 }
02698
02699
02700 for(i=0;i<nb_istreams;i++) {
02701 ist = ist_table[i];
02702 if (ist->decoding_needed) {
02703 avcodec_close(ist->st->codec);
02704 }
02705 }
02706
02707
02708 ret = 0;
02709
02710 fail:
02711 av_freep(&bit_buffer);
02712 av_free(file_table);
02713
02714 if (ist_table) {
02715 for(i=0;i<nb_istreams;i++) {
02716 ist = ist_table[i];
02717 av_free(ist);
02718 }
02719 av_free(ist_table);
02720 }
02721 if (ost_table) {
02722 for(i=0;i<nb_ostreams;i++) {
02723 ost = ost_table[i];
02724 if (ost) {
02725 if (ost->st->stream_copy)
02726 av_freep(&ost->st->codec->extradata);
02727 if (ost->logfile) {
02728 fclose(ost->logfile);
02729 ost->logfile = NULL;
02730 }
02731 av_fifo_free(ost->fifo);
02732
02733 av_freep(&ost->st->codec->subtitle_header);
02734 av_free(ost->pict_tmp.data[0]);
02735 av_free(ost->forced_kf_pts);
02736 if (ost->video_resample)
02737 sws_freeContext(ost->img_resample_ctx);
02738 if (ost->resample)
02739 audio_resample_close(ost->resample);
02740 if (ost->reformat_ctx)
02741 av_audio_convert_free(ost->reformat_ctx);
02742 av_free(ost);
02743 }
02744 }
02745 av_free(ost_table);
02746 }
02747 return ret;
02748 }
02749
02750 static void opt_format(const char *arg)
02751 {
02752 last_asked_format = arg;
02753 }
02754
02755 static void opt_video_rc_override_string(const char *arg)
02756 {
02757 video_rc_override_string = arg;
02758 }
02759
02760 static int opt_me_threshold(const char *opt, const char *arg)
02761 {
02762 me_threshold = parse_number_or_die(opt, arg, OPT_INT64, INT_MIN, INT_MAX);
02763 return 0;
02764 }
02765
02766 static int opt_verbose(const char *opt, const char *arg)
02767 {
02768 verbose = parse_number_or_die(opt, arg, OPT_INT64, -10, 10);
02769 return 0;
02770 }
02771
02772 static int opt_frame_rate(const char *opt, const char *arg)
02773 {
02774 if (av_parse_video_rate(&frame_rate, arg) < 0) {
02775 fprintf(stderr, "Incorrect value for %s: %s\n", opt, arg);
02776 ffmpeg_exit(1);
02777 }
02778 return 0;
02779 }
02780
02781 static int opt_bitrate(const char *opt, const char *arg)
02782 {
02783 int codec_type = opt[0]=='a' ? AVMEDIA_TYPE_AUDIO : AVMEDIA_TYPE_VIDEO;
02784
02785 opt_default(opt, arg);
02786
02787 if (av_get_int(avcodec_opts[codec_type], "b", NULL) < 1000)
02788 fprintf(stderr, "WARNING: The bitrate parameter is set too low. It takes bits/s as argument, not kbits/s\n");
02789
02790 return 0;
02791 }
02792
02793 static int opt_frame_crop(const char *opt, const char *arg)
02794 {
02795 fprintf(stderr, "Option '%s' has been removed, use the crop filter instead\n", opt);
02796 return AVERROR(EINVAL);
02797 }
02798
02799 static void opt_frame_size(const char *arg)
02800 {
02801 if (av_parse_video_size(&frame_width, &frame_height, arg) < 0) {
02802 fprintf(stderr, "Incorrect frame size\n");
02803 ffmpeg_exit(1);
02804 }
02805 }
02806
02807 static int opt_pad(const char *opt, const char *arg) {
02808 fprintf(stderr, "Option '%s' has been removed, use the pad filter instead\n", opt);
02809 return -1;
02810 }
02811
02812 static void opt_frame_pix_fmt(const char *arg)
02813 {
02814 if (strcmp(arg, "list")) {
02815 frame_pix_fmt = av_get_pix_fmt(arg);
02816 if (frame_pix_fmt == PIX_FMT_NONE) {
02817 fprintf(stderr, "Unknown pixel format requested: %s\n", arg);
02818 ffmpeg_exit(1);
02819 }
02820 } else {
02821 show_pix_fmts();
02822 ffmpeg_exit(0);
02823 }
02824 }
02825
02826 static void opt_frame_aspect_ratio(const char *arg)
02827 {
02828 int x = 0, y = 0;
02829 double ar = 0;
02830 const char *p;
02831 char *end;
02832
02833 p = strchr(arg, ':');
02834 if (p) {
02835 x = strtol(arg, &end, 10);
02836 if (end == p)
02837 y = strtol(end+1, &end, 10);
02838 if (x > 0 && y > 0)
02839 ar = (double)x / (double)y;
02840 } else
02841 ar = strtod(arg, NULL);
02842
02843 if (!ar) {
02844 fprintf(stderr, "Incorrect aspect ratio specification.\n");
02845 ffmpeg_exit(1);
02846 }
02847 frame_aspect_ratio = ar;
02848 }
02849
02850 static int opt_metadata(const char *opt, const char *arg)
02851 {
02852 char *mid= strchr(arg, '=');
02853
02854 if(!mid){
02855 fprintf(stderr, "Missing =\n");
02856 ffmpeg_exit(1);
02857 }
02858 *mid++= 0;
02859
02860 av_metadata_set2(&metadata, arg, mid, 0);
02861
02862 return 0;
02863 }
02864
02865 static void opt_qscale(const char *arg)
02866 {
02867 video_qscale = atof(arg);
02868 if (video_qscale <= 0 ||
02869 video_qscale > 255) {
02870 fprintf(stderr, "qscale must be > 0.0 and <= 255\n");
02871 ffmpeg_exit(1);
02872 }
02873 }
02874
02875 static void opt_top_field_first(const char *arg)
02876 {
02877 top_field_first= atoi(arg);
02878 }
02879
02880 static int opt_thread_count(const char *opt, const char *arg)
02881 {
02882 thread_count= parse_number_or_die(opt, arg, OPT_INT64, 0, INT_MAX);
02883 #if !HAVE_THREADS
02884 if (verbose >= 0)
02885 fprintf(stderr, "Warning: not compiled with thread support, using thread emulation\n");
02886 #endif
02887 return 0;
02888 }
02889
02890 static void opt_audio_sample_fmt(const char *arg)
02891 {
02892 if (strcmp(arg, "list")) {
02893 audio_sample_fmt = av_get_sample_fmt(arg);
02894 if (audio_sample_fmt == AV_SAMPLE_FMT_NONE) {
02895 av_log(NULL, AV_LOG_ERROR, "Invalid sample format '%s'\n", arg);
02896 ffmpeg_exit(1);
02897 }
02898 } else {
02899 list_fmts(av_get_sample_fmt_string, AV_SAMPLE_FMT_NB);
02900 ffmpeg_exit(0);
02901 }
02902 }
02903
02904 static int opt_audio_rate(const char *opt, const char *arg)
02905 {
02906 audio_sample_rate = parse_number_or_die(opt, arg, OPT_INT64, 0, INT_MAX);
02907 return 0;
02908 }
02909
02910 static int opt_audio_channels(const char *opt, const char *arg)
02911 {
02912 audio_channels = parse_number_or_die(opt, arg, OPT_INT64, 0, INT_MAX);
02913 return 0;
02914 }
02915
02916 static void opt_video_channel(const char *arg)
02917 {
02918 video_channel = strtol(arg, NULL, 0);
02919 }
02920
02921 static void opt_video_standard(const char *arg)
02922 {
02923 video_standard = av_strdup(arg);
02924 }
02925
02926 static void opt_codec(int *pstream_copy, char **pcodec_name,
02927 int codec_type, const char *arg)
02928 {
02929 av_freep(pcodec_name);
02930 if (!strcmp(arg, "copy")) {
02931 *pstream_copy = 1;
02932 } else {
02933 *pcodec_name = av_strdup(arg);
02934 }
02935 }
02936
02937 static void opt_audio_codec(const char *arg)
02938 {
02939 opt_codec(&audio_stream_copy, &audio_codec_name, AVMEDIA_TYPE_AUDIO, arg);
02940 }
02941
02942 static void opt_video_codec(const char *arg)
02943 {
02944 opt_codec(&video_stream_copy, &video_codec_name, AVMEDIA_TYPE_VIDEO, arg);
02945 }
02946
02947 static void opt_subtitle_codec(const char *arg)
02948 {
02949 opt_codec(&subtitle_stream_copy, &subtitle_codec_name, AVMEDIA_TYPE_SUBTITLE, arg);
02950 }
02951
02952 static int opt_codec_tag(const char *opt, const char *arg)
02953 {
02954 char *tail;
02955 uint32_t *codec_tag;
02956
02957 codec_tag = !strcmp(opt, "atag") ? &audio_codec_tag :
02958 !