Statistics
| Branch: | Revision:

ffmpeg / ffmpeg.c @ 8a6cb114

History | View | Annotate | Download (141 KB)

1 85f07f22 Fabrice Bellard
/*
2
 * FFmpeg main 
3 01310af2 Fabrice Bellard
 * Copyright (c) 2000-2003 Fabrice Bellard
4 85f07f22 Fabrice Bellard
 *
5 bf5af568 Fabrice Bellard
 * This library is free software; you can redistribute it and/or
6
 * modify it under the terms of the GNU Lesser General Public
7
 * License as published by the Free Software Foundation; either
8
 * version 2 of the License, or (at your option) any later version.
9 85f07f22 Fabrice Bellard
 *
10 bf5af568 Fabrice Bellard
 * This library is distributed in the hope that it will be useful,
11 85f07f22 Fabrice Bellard
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 bf5af568 Fabrice Bellard
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13
 * Lesser General Public License for more details.
14 85f07f22 Fabrice Bellard
 *
15 bf5af568 Fabrice Bellard
 * You should have received a copy of the GNU Lesser General Public
16
 * License along with this library; if not, write to the Free Software
17
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18 85f07f22 Fabrice Bellard
 */
19 daf8e955 Fabrice Bellard
#define HAVE_AV_CONFIG_H
20 22f7a060 Michael Niedermayer
#include <limits.h>
21 daf8e955 Fabrice Bellard
#include "avformat.h"
22 10d104e4 Philip Gladstone
#include "framehook.h"
23 1ac31760 Michael Niedermayer
#include "dsputil.h"
24 daf8e955 Fabrice Bellard
25 bdc4796f Fabrice Bellard
#ifndef CONFIG_WIN32
26 85f07f22 Fabrice Bellard
#include <unistd.h>
27
#include <fcntl.h>
28
#include <sys/ioctl.h>
29
#include <sys/time.h>
30
#include <termios.h>
31 5727b222 Fabrice Bellard
#include <sys/resource.h>
32 9680a722 Roumen Petrov
#include <signal.h>
33 bdc4796f Fabrice Bellard
#endif
34 f3ec2d46 Slavik Gnatenko
#ifdef CONFIG_OS2
35
#include <sys/types.h>
36
#include <sys/select.h>
37
#include <stdlib.h>
38
#endif
39 64c020a8 Michael Niedermayer
#undef time //needed because HAVE_AV_CONFIG_H is defined on top
40 bf5af568 Fabrice Bellard
#include <time.h>
41 85f07f22 Fabrice Bellard
42 01310af2 Fabrice Bellard
#include "cmdutils.h"
43
44 2b18dcd0 Michael Niedermayer
#undef NDEBUG
45
#include <assert.h>
46
47 8aa1e3da Michael Niedermayer
#if !defined(INFINITY) && defined(HUGE_VAL)
48
#define INFINITY HUGE_VAL
49
#endif
50 85f07f22 Fabrice Bellard
51
/* select an input stream for an output stream */
52
typedef struct AVStreamMap {
53
    int file_index;
54
    int stream_index;
55
} AVStreamMap;
56
57 0a38bafd Patrice Bensoussan
/** select an input file for an output file */
58
typedef struct AVMetaDataMap {
59
    int out_file;
60
    int in_file;
61
} AVMetaDataMap;
62
63 85f07f22 Fabrice Bellard
extern const OptionDef options[];
64
65 02d504a7 Fabrice Bellard
static void show_help(void);
66
static void show_license(void);
67 85f07f22 Fabrice Bellard
68
#define MAX_FILES 20
69
70
static AVFormatContext *input_files[MAX_FILES];
71 a6a92a9a Wolfram Gloger
static int64_t input_files_ts_offset[MAX_FILES];
72 85f07f22 Fabrice Bellard
static int nb_input_files = 0;
73
74
static AVFormatContext *output_files[MAX_FILES];
75
static int nb_output_files = 0;
76
77
static AVStreamMap stream_maps[MAX_FILES];
78
static int nb_stream_maps;
79
80 0a38bafd Patrice Bensoussan
static AVMetaDataMap meta_data_maps[MAX_FILES];
81
static int nb_meta_data_maps;
82
83 79fdaa4c Fabrice Bellard
static AVInputFormat *file_iformat;
84
static AVOutputFormat *file_oformat;
85 817b23ff Fabrice Bellard
static AVImageFormat *image_format;
86 85f07f22 Fabrice Bellard
static int frame_width  = 160;
87
static int frame_height = 128;
88 880e8ba7 Roman Shaposhnik
static float frame_aspect_ratio = 0;
89 63167088 Roman Shaposhnik
static enum PixelFormat frame_pix_fmt = PIX_FMT_YUV420P;
90 1ff93ffc Todd Kirby
static int frame_padtop  = 0;
91
static int frame_padbottom = 0;
92
static int frame_padleft  = 0;
93
static int frame_padright = 0;
94
static int padcolor[3] = {16,128,128}; /* default to black */
95 ab6d194a Michael Niedermayer
static int frame_topBand  = 0;
96
static int frame_bottomBand = 0;
97
static int frame_leftBand  = 0;
98
static int frame_rightBand = 0;
99 14bea432 Michael Niedermayer
static int frame_rate = 25;
100
static int frame_rate_base = 1;
101 3aa102be Michael Niedermayer
static int video_bit_rate = 200*1000;
102
static int video_bit_rate_tolerance = 4000*1000;
103 158c7f05 Michael Niedermayer
static float video_qscale = 0;
104 3aa102be Michael Niedermayer
static int video_qmin = 2;
105
static int video_qmax = 31;
106 4ea4b274 Michael Niedermayer
static int video_lmin = 2*FF_QP2LAMBDA;
107
static int video_lmax = 31*FF_QP2LAMBDA;
108 17a70fde Michael Niedermayer
static int video_mb_qmin = 2;
109
static int video_mb_qmax = 31;
110 9cdd6a24 Michael Niedermayer
static int video_qdiff = 3;
111
static float video_qblur = 0.5;
112
static float video_qcomp = 0.5;
113 84f608f4 Vidar Madsen
static uint16_t *intra_matrix = NULL;
114
static uint16_t *inter_matrix = NULL;
115 ac2830ec Michael Niedermayer
#if 0 //experimental, (can be removed)
116 3aa102be Michael Niedermayer
static float video_rc_qsquish=1.0;
117
static float video_rc_qmod_amp=0;
118
static int video_rc_qmod_freq=0;
119 ac2830ec Michael Niedermayer
#endif
120 3aa102be Michael Niedermayer
static char *video_rc_override_string=NULL;
121
static char *video_rc_eq="tex^qComp";
122
static int video_rc_buffer_size=0;
123
static float video_rc_buffer_aggressivity=1.0;
124
static int video_rc_max_rate=0;
125
static int video_rc_min_rate=0;
126
static float video_rc_initial_cplx=0;
127
static float video_b_qfactor = 1.25;
128
static float video_b_qoffset = 1.25;
129 b3a391e8 Michael Niedermayer
static float video_i_qfactor = -0.8;
130 3aa102be Michael Niedermayer
static float video_i_qoffset = 0.0;
131 303e50e6 Michael Niedermayer
static int video_intra_quant_bias= FF_DEFAULT_QUANT_BIAS;
132
static int video_inter_quant_bias= FF_DEFAULT_QUANT_BIAS;
133 3bea5386 Michael Niedermayer
static int me_method = ME_EPZS;
134 85f07f22 Fabrice Bellard
static int video_disable = 0;
135
static int video_codec_id = CODEC_ID_NONE;
136 b2a2197e Michael Niedermayer
static int video_codec_tag = 0;
137 85f07f22 Fabrice Bellard
static int same_quality = 0;
138 bc6caae2 Juanjo
static int b_frames = 0;
139 7d1c3fc1 Michael Niedermayer
static int mb_decision = FF_MB_DECISION_SIMPLE;
140 622348f9 Michael Niedermayer
static int ildct_cmp = FF_CMP_VSAD;
141 5d43635e Michael Niedermayer
static int mb_cmp = FF_CMP_SAD;
142
static int sub_cmp = FF_CMP_SAD;
143
static int cmp = FF_CMP_SAD;
144 9c3d33d6 Michael Niedermayer
static int pre_cmp = FF_CMP_SAD;
145
static int pre_me = 0;
146
static float lumi_mask = 0;
147
static float dark_mask = 0;
148
static float scplx_mask = 0;
149
static float tcplx_mask = 0;
150
static float p_mask = 0;
151 29da453b Juanjo
static int use_4mv = 0;
152 8e2162f0 Michael Niedermayer
static int use_obmc = 0;
153 d7646d7d Michael Niedermayer
static int use_loop = 0;
154 21e59552 Michael Niedermayer
static int use_aic = 0;
155 dba019da Michael Niedermayer
static int use_aiv = 0;
156 21e59552 Michael Niedermayer
static int use_umv = 0;
157 458eadda Michael Niedermayer
static int use_ss = 0;
158 bb198e19 Michael Niedermayer
static int use_alt_scan = 0;
159 c0baa56a Michael Niedermayer
static int use_trell = 0;
160 baaf3f46 Michael Niedermayer
static int use_scan_offset = 0;
161 5efe481a Michael Niedermayer
static int use_qpel = 0;
162 f7e1e69e Michael Niedermayer
static int use_qprd = 0;
163 1a11cbcc Michael Niedermayer
static int use_cbprd = 0;
164 77ea0d4b Michael Niedermayer
static int qns = 0;
165 303e50e6 Michael Niedermayer
static int closed_gop = 0;
166 03581772 Michael Niedermayer
static int strict_gop = 0;
167 cfcf0ffd Fabrice Bellard
static int do_deinterlace = 0;
168 bb198e19 Michael Niedermayer
static int do_interlace_dct = 0;
169
static int do_interlace_me = 0;
170 4d2858de Michael Niedermayer
static int workaround_bugs = FF_BUG_AUTODETECT;
171
static int error_resilience = 2;
172
static int error_concealment = 3;
173 463678ac Michael Niedermayer
static int dct_algo = 0;
174 2ad1516a Michael Niedermayer
static int idct_algo = 0;
175 1dbb6d90 Michael Niedermayer
static int use_part = 0;
176
static int packet_size = 0;
177 7ebfc0ea Michael Niedermayer
static int error_rate = 0;
178 f560dd82 Michael Niedermayer
static int strict = 0;
179 bb198e19 Michael Niedermayer
static int top_field_first = -1;
180
static int noise_reduction = 0;
181 303e50e6 Michael Niedermayer
static int sc_threshold = 0;
182 59b571c1 Michael Niedermayer
static int debug = 0;
183 0c9bbaec Wolfgang Hesseler
static int debug_mv = 0;
184 f4f3223f Michael Niedermayer
static int me_threshold = 0;
185 f20f8a8b Michael Niedermayer
static int mb_threshold = 0;
186 1a11cbcc Michael Niedermayer
static int intra_dc_precision = 8;
187 8a0c66a7 Michael Niedermayer
static int coder = 0;
188
static int context = 0;
189
static int predictor = 0;
190 baced9f5 Michael Niedermayer
static int video_profile = FF_PROFILE_UNKNOWN;
191
static int video_level = FF_LEVEL_UNKNOWN;
192 bf0669aa Michael Niedermayer
static int nsse_weight = 8;
193 178fcca8 Michael Niedermayer
static int subpel_quality= 8;
194
static int lowres= 0;
195 b1b77fe9 Fabrice Bellard
extern int loop_input; /* currently a hack */
196 85f07f22 Fabrice Bellard
197
static int gop_size = 12;
198
static int intra_only = 0;
199
static int audio_sample_rate = 44100;
200
static int audio_bit_rate = 64000;
201
static int audio_disable = 0;
202
static int audio_channels = 1;
203
static int audio_codec_id = CODEC_ID_NONE;
204 b2a2197e Michael Niedermayer
static int audio_codec_tag = 0;
205 85f07f22 Fabrice Bellard
206 2db3c638 Michael Niedermayer
static int mux_rate= 0;
207
static int mux_packet_size= 0;
208 17c88cb0 Michael Niedermayer
static float mux_preload= 0.5;
209
static float mux_max_delay= 0.7;
210 2db3c638 Michael Niedermayer
211 0c1a9eda Zdenek Kabelac
static int64_t recording_time = 0;
212 8831db5c Michael Niedermayer
static int64_t start_time = 0;
213 4568325a Roman Shaposhnik
static int64_t rec_timestamp = 0;
214 a6a92a9a Wolfram Gloger
static int64_t input_ts_offset = 0;
215 85f07f22 Fabrice Bellard
static int file_overwrite = 0;
216
static char *str_title = NULL;
217
static char *str_author = NULL;
218
static char *str_copyright = NULL;
219
static char *str_comment = NULL;
220 5727b222 Fabrice Bellard
static int do_benchmark = 0;
221 a0663ba4 Fabrice Bellard
static int do_hex_dump = 0;
222 254abc2e Fabrice Bellard
static int do_pkt_dump = 0;
223 43f1708f Juanjo
static int do_psnr = 0;
224 ce7c56c2 Juanjo
static int do_vstats = 0;
225 5abdb4b1 Fabrice Bellard
static int do_pass = 0;
226 b0368839 Michael Niedermayer
static int bitexact = 0;
227 5abdb4b1 Fabrice Bellard
static char *pass_logfilename = NULL;
228 1629626f Fabrice Bellard
static int audio_stream_copy = 0;
229
static int video_stream_copy = 0;
230 986ebcdb Michael Niedermayer
static int video_sync_method= 1;
231
static int audio_sync_method= 0;
232 72bd8100 Michael Niedermayer
static int copy_ts= 0;
233 5abdb4b1 Fabrice Bellard
234 bdfcbbed Max Krasnyansky
static int rate_emu = 0;
235
236 8aa3ee32 Max Krasnyansky
static char *video_grab_format = "video4linux";
237 79a7c268 Fabrice Bellard
static char *video_device = NULL;
238 2639c651 Roman Shaposhnik
static char *grab_device = NULL;
239 a5df11ab Fabrice Bellard
static int  video_channel = 0;
240 e3ee3283 Alex Beregszaszi
static char *video_standard = "ntsc";
241 79a7c268 Fabrice Bellard
242 8aa3ee32 Max Krasnyansky
static char *audio_grab_format = "audio_device";
243 79a7c268 Fabrice Bellard
static char *audio_device = NULL;
244 8aa3ee32 Max Krasnyansky
245 d9a916e2 Charles Yates
static int using_stdin = 0;
246 bee0d9e5 Charles Yates
static int using_vhook = 0;
247 f068206e Bill Eldridge
static int verbose = 1;
248 9c3d33d6 Michael Niedermayer
static int thread_count= 1;
249 b51469a0 Leon van Stuivenberg
static int q_pressed = 0;
250 2f0472ff Timofei V. Bondarenko
static int me_range = 0;
251 1008ceb3 Michael Niedermayer
static int64_t video_size = 0;
252
static int64_t audio_size = 0;
253
static int64_t extra_size = 0;
254 a6a92a9a Wolfram Gloger
static int nb_frames_dup = 0;
255
static int nb_frames_drop = 0;
256 6e454c38 Luca Abeni
static int input_sync;
257 d9a916e2 Charles Yates
258 5b6d5596 Michael Niedermayer
static int pgmyuv_compatibility_hack=0;
259
260
261 5abdb4b1 Fabrice Bellard
#define DEFAULT_PASS_LOGFILENAME "ffmpeg2pass"
262 85f07f22 Fabrice Bellard
263
typedef struct AVOutputStream {
264
    int file_index;          /* file index */
265
    int index;               /* stream index in the output file */
266
    int source_index;        /* AVInputStream index */
267
    AVStream *st;            /* stream in the output file */
268 ec5517d5 Fabrice Bellard
    int encoding_needed;     /* true if encoding needed for this stream */
269
    int frame_number;
270
    /* input pts and corresponding output pts
271
       for A/V sync */
272 e928649b Michael Niedermayer
    double sync_ipts;        /* dts from the AVPacket of the demuxer in second units */
273
    int64_t sync_opts;       /* output frame counter, could be changed to some true timestamp */ //FIXME look at frame_number
274 85f07f22 Fabrice Bellard
    /* video only */
275 34b10a57 Dieter
    int video_resample;      /* video_resample and video_crop are mutually exclusive */
276 a4d36c11 Michael Niedermayer
    AVFrame pict_tmp;      /* temporary image for resampling */
277 85f07f22 Fabrice Bellard
    ImgReSampleContext *img_resample_ctx; /* for image resampling */
278 34b10a57 Dieter
279
    int video_crop;          /* video_resample and video_crop are mutually exclusive */
280
    int topBand;             /* cropping area sizes */
281
    int leftBand;
282 85f07f22 Fabrice Bellard
    
283 1ff93ffc Todd Kirby
    int video_pad;           /* video_resample and video_pad are mutually exclusive */
284
    int padtop;              /* padding area sizes */
285
    int padbottom;
286
    int padleft;
287
    int padright;
288
    
289 85f07f22 Fabrice Bellard
    /* audio only */
290
    int audio_resample;
291
    ReSampleContext *resample; /* for audio resampling */
292
    FifoBuffer fifo;     /* for compression: one audio fifo per codec */
293 5abdb4b1 Fabrice Bellard
    FILE *logfile;
294 85f07f22 Fabrice Bellard
} AVOutputStream;
295
296
typedef struct AVInputStream {
297
    int file_index;
298
    int index;
299
    AVStream *st;
300
    int discard;             /* true if stream data should be discarded */
301
    int decoding_needed;     /* true if the packets must be decoded in 'raw_fifo' */
302 0c1a9eda Zdenek Kabelac
    int64_t sample_index;      /* current sample */
303 bdfcbbed Max Krasnyansky
304
    int64_t       start;     /* time when read started */
305
    unsigned long frame;     /* current frame */
306 254abc2e Fabrice Bellard
    int64_t       next_pts;  /* synthetic pts for cases where pkt.pts
307
                                is not defined */
308 e7d0374f Roman Shaposhnik
    int64_t       pts;       /* current pts */
309 ff4905a5 Michael Niedermayer
    int is_start;            /* is 1 at the start and after a discontinuity */
310 85f07f22 Fabrice Bellard
} AVInputStream;
311
312
typedef struct AVInputFile {
313
    int eof_reached;      /* true if eof reached */
314
    int ist_index;        /* index of first stream in ist_table */
315
    int buffer_size;      /* current total buffer size */
316
    int buffer_size_max;  /* buffer size at which we consider we can stop
317
                             buffering */
318 79fdaa4c Fabrice Bellard
    int nb_streams;       /* nb streams we are aware of */
319 85f07f22 Fabrice Bellard
} AVInputFile;
320
321 bdc4796f Fabrice Bellard
#ifndef CONFIG_WIN32
322
323 85f07f22 Fabrice Bellard
/* init terminal so that we can grab keys */
324
static struct termios oldtty;
325
326
static void term_exit(void)
327
{
328
    tcsetattr (0, TCSANOW, &oldtty);
329
}
330
331 9680a722 Roumen Petrov
static volatile sig_atomic_t received_sigterm = 0;
332
333
static void
334
sigterm_handler(int sig)
335
{
336
    received_sigterm = sig;
337
    term_exit();
338
}
339
340 85f07f22 Fabrice Bellard
static void term_init(void)
341
{
342
    struct termios tty;
343
344
    tcgetattr (0, &tty);
345
    oldtty = tty;
346
347
    tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
348
                          |INLCR|IGNCR|ICRNL|IXON);
349
    tty.c_oflag |= OPOST;
350
    tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
351
    tty.c_cflag &= ~(CSIZE|PARENB);
352
    tty.c_cflag |= CS8;
353
    tty.c_cc[VMIN] = 1;
354
    tty.c_cc[VTIME] = 0;
355
    
356
    tcsetattr (0, TCSANOW, &tty);
357
358 9680a722 Roumen Petrov
    signal(SIGINT , sigterm_handler); /* Interrupt (ANSI).  */
359
    signal(SIGQUIT, sigterm_handler); /* Quit (POSIX).  */
360
    signal(SIGTERM, sigterm_handler); /* Termination (ANSI).  */
361
    /*
362
    register a function to be called at normal program termination
363
    */
364 85f07f22 Fabrice Bellard
    atexit(term_exit);
365 9ddd71fc François Revol
#ifdef CONFIG_BEOS_NETSERVER
366
    fcntl(0, F_SETFL, fcntl(0, F_GETFL) | O_NONBLOCK);
367
#endif
368 85f07f22 Fabrice Bellard
}
369
370
/* read a key without blocking */
371
static int read_key(void)
372
{
373 9ddd71fc François Revol
    int n = 1;
374 85f07f22 Fabrice Bellard
    unsigned char ch;
375 9ddd71fc François Revol
#ifndef CONFIG_BEOS_NETSERVER
376
    struct timeval tv;
377 85f07f22 Fabrice Bellard
    fd_set rfds;
378
379
    FD_ZERO(&rfds);
380
    FD_SET(0, &rfds);
381
    tv.tv_sec = 0;
382
    tv.tv_usec = 0;
383
    n = select(1, &rfds, NULL, NULL, &tv);
384 9ddd71fc François Revol
#endif
385 85f07f22 Fabrice Bellard
    if (n > 0) {
386 cb09b2ed Philip Gladstone
        n = read(0, &ch, 1);
387
        if (n == 1)
388 85f07f22 Fabrice Bellard
            return ch;
389 cb09b2ed Philip Gladstone
390
        return n;
391 85f07f22 Fabrice Bellard
    }
392
    return -1;
393
}
394
395 b51469a0 Leon van Stuivenberg
static int decode_interrupt_cb(void)
396
{
397
    return q_pressed || (q_pressed = read_key() == 'q');
398
}
399
400 a38469e1 Fabrice Bellard
#else
401 85f07f22 Fabrice Bellard
402 bee0d9e5 Charles Yates
static volatile int received_sigterm = 0;
403
404 a38469e1 Fabrice Bellard
/* no interactive support */
405
static void term_exit(void)
406 85f07f22 Fabrice Bellard
{
407 a38469e1 Fabrice Bellard
}
408 85f07f22 Fabrice Bellard
409 a38469e1 Fabrice Bellard
static void term_init(void)
410
{
411
}
412 85f07f22 Fabrice Bellard
413 a38469e1 Fabrice Bellard
static int read_key(void)
414
{
415 cb09b2ed Philip Gladstone
    return 0;
416 85f07f22 Fabrice Bellard
}
417
418 a38469e1 Fabrice Bellard
#endif
419 bdc4796f Fabrice Bellard
420 b29f97d1 Zdenek Kabelac
static int read_ffserver_streams(AVFormatContext *s, const char *filename)
421 85f07f22 Fabrice Bellard
{
422 79fdaa4c Fabrice Bellard
    int i, err;
423 85f07f22 Fabrice Bellard
    AVFormatContext *ic;
424
425 79fdaa4c Fabrice Bellard
    err = av_open_input_file(&ic, filename, NULL, FFM_PACKET_SIZE, NULL);
426
    if (err < 0)
427
        return err;
428 85f07f22 Fabrice Bellard
    /* copy stream format */
429
    s->nb_streams = ic->nb_streams;
430
    for(i=0;i<ic->nb_streams;i++) {
431
        AVStream *st;
432 1e491e29 Michael Niedermayer
433 e1031171 Alex Beregszaszi
        st = av_mallocz(sizeof(AVStream));
434 85f07f22 Fabrice Bellard
        memcpy(st, ic->streams[i], sizeof(AVStream));
435
        s->streams[i] = st;
436
    }
437
438
    av_close_input_file(ic);
439
    return 0;
440
}
441
442 817b23ff Fabrice Bellard
#define MAX_AUDIO_PACKET_SIZE (128 * 1024)
443 85f07f22 Fabrice Bellard
444
static void do_audio_out(AVFormatContext *s, 
445
                         AVOutputStream *ost, 
446
                         AVInputStream *ist,
447
                         unsigned char *buf, int size)
448
{
449 0c1a9eda Zdenek Kabelac
    uint8_t *buftmp;
450 d66c7abc Sylvain Corré
    static uint8_t *audio_buf = NULL;
451
    static uint8_t *audio_out = NULL;
452 558eae03 Michael Niedermayer
    const int audio_out_size= 4*MAX_AUDIO_PACKET_SIZE;
453 d66c7abc Sylvain Corré
454 85f07f22 Fabrice Bellard
    int size_out, frame_bytes, ret;
455 ff4905a5 Michael Niedermayer
    AVCodecContext *enc= &ost->st->codec;
456 85f07f22 Fabrice Bellard
457 d66c7abc Sylvain Corré
    /* SC: dynamic allocation of buffers */
458
    if (!audio_buf)
459
        audio_buf = av_malloc(2*MAX_AUDIO_PACKET_SIZE);
460
    if (!audio_out)
461 558eae03 Michael Niedermayer
        audio_out = av_malloc(audio_out_size);
462 d66c7abc Sylvain Corré
    if (!audio_buf || !audio_out)
463
        return;               /* Should signal an error ! */
464
465 986ebcdb Michael Niedermayer
    if(audio_sync_method){
466
        double delta = ost->sync_ipts * enc->sample_rate - ost->sync_opts 
467
                - fifo_size(&ost->fifo, ost->fifo.rptr)/(ost->st->codec.channels * 2);
468 ff4905a5 Michael Niedermayer
        double idelta= delta*ist->st->codec.sample_rate / enc->sample_rate;
469
        int byte_delta= ((int)idelta)*2*ist->st->codec.channels;
470
471 986ebcdb Michael Niedermayer
        //FIXME resample delay
472
        if(fabs(delta) > 50){
473 ff4905a5 Michael Niedermayer
            if(ist->is_start){
474
                if(byte_delta < 0){
475 f41dd5aa Michael Niedermayer
                    byte_delta= FFMAX(byte_delta, -size);
476 ff4905a5 Michael Niedermayer
                    size += byte_delta;
477
                    buf  -= byte_delta;
478
                    if(verbose > 2)
479
                        fprintf(stderr, "discarding %d audio samples\n", (int)-delta);
480
                    if(!size)
481
                        return;
482
                    ist->is_start=0;
483
                }else{
484
                    static uint8_t *input_tmp= NULL;
485
                    input_tmp= av_realloc(input_tmp, byte_delta + size);
486
487
                    if(byte_delta + size <= MAX_AUDIO_PACKET_SIZE)
488
                        ist->is_start=0;
489
                    else
490
                        byte_delta= MAX_AUDIO_PACKET_SIZE - size;
491
492
                    memset(input_tmp, 0, byte_delta);
493
                    memcpy(input_tmp + byte_delta, buf, size);
494
                    buf= input_tmp;
495
                    size += byte_delta;
496
                    if(verbose > 2)
497
                        fprintf(stderr, "adding %d audio samples of silence\n", (int)delta);
498
                }
499
            }else if(audio_sync_method>1){
500
                int comp= clip(delta, -audio_sync_method, audio_sync_method);
501
                assert(ost->audio_resample);
502
                if(verbose > 2)
503
                    fprintf(stderr, "compensating audio timestamp drift:%f compensation:%d in:%d\n", delta, comp, enc->sample_rate);
504 58978c07 Michael Niedermayer
//                fprintf(stderr, "drift:%f len:%d opts:%lld ipts:%lld fifo:%d\n", delta, -1, ost->sync_opts, (int64_t)(ost->sync_ipts * enc->sample_rate), fifo_size(&ost->fifo, ost->fifo.rptr)/(ost->st->codec.channels * 2));
505 ff4905a5 Michael Niedermayer
                av_resample_compensate(*(struct AVResampleContext**)ost->resample, comp, enc->sample_rate);
506
            }
507
        } 
508 986ebcdb Michael Niedermayer
    }else
509
        ost->sync_opts= lrintf(ost->sync_ipts * enc->sample_rate)
510
                        - fifo_size(&ost->fifo, ost->fifo.rptr)/(ost->st->codec.channels * 2); //FIXME wrong
511 85f07f22 Fabrice Bellard
512
    if (ost->audio_resample) {
513
        buftmp = audio_buf;
514
        size_out = audio_resample(ost->resample, 
515
                                  (short *)buftmp, (short *)buf,
516
                                  size / (ist->st->codec.channels * 2));
517
        size_out = size_out * enc->channels * 2;
518
    } else {
519
        buftmp = buf;
520
        size_out = size;
521
    }
522
523
    /* now encode as many frames as possible */
524 a0663ba4 Fabrice Bellard
    if (enc->frame_size > 1) {
525 85f07f22 Fabrice Bellard
        /* output resampled raw samples */
526
        fifo_write(&ost->fifo, buftmp, size_out, 
527
                   &ost->fifo.wptr);
528
529
        frame_bytes = enc->frame_size * 2 * enc->channels;
530
        
531
        while (fifo_read(&ost->fifo, audio_buf, frame_bytes, 
532
                     &ost->fifo.rptr) == 0) {
533 e928649b Michael Niedermayer
            AVPacket pkt;
534
            av_init_packet(&pkt);
535
536 558eae03 Michael Niedermayer
            ret = avcodec_encode_audio(enc, audio_out, audio_out_size, 
537 a0663ba4 Fabrice Bellard
                                       (short *)audio_buf);
538 1008ceb3 Michael Niedermayer
            audio_size += ret;
539 e928649b Michael Niedermayer
            pkt.stream_index= ost->index;
540
            pkt.data= audio_out;
541
            pkt.size= ret;
542
            if(enc->coded_frame)
543
                pkt.pts= enc->coded_frame->pts;
544
            pkt.flags |= PKT_FLAG_KEY;
545 3c895fc0 Michael Niedermayer
            av_interleaved_write_frame(s, &pkt);
546 986ebcdb Michael Niedermayer
            
547
            ost->sync_opts += enc->frame_size;
548 85f07f22 Fabrice Bellard
        }
549
    } else {
550 e928649b Michael Niedermayer
        AVPacket pkt;
551
        av_init_packet(&pkt);
552 986ebcdb Michael Niedermayer
553 c43042a7 Michael Niedermayer
        ost->sync_opts += size_out / (2 * enc->channels);
554 986ebcdb Michael Niedermayer
555 a0663ba4 Fabrice Bellard
        /* output a pcm frame */
556
        /* XXX: change encoding codec API to avoid this ? */
557
        switch(enc->codec->id) {
558
        case CODEC_ID_PCM_S16LE:
559
        case CODEC_ID_PCM_S16BE:
560
        case CODEC_ID_PCM_U16LE:
561
        case CODEC_ID_PCM_U16BE:
562
            break;
563
        default:
564
            size_out = size_out >> 1;
565
            break;
566
        }
567
        ret = avcodec_encode_audio(enc, audio_out, size_out, 
568 ff29712a Zdenek Kabelac
                                   (short *)buftmp);
569 1008ceb3 Michael Niedermayer
        audio_size += ret;
570 e928649b Michael Niedermayer
        pkt.stream_index= ost->index;
571
        pkt.data= audio_out;
572
        pkt.size= ret;
573
        if(enc->coded_frame)
574
            pkt.pts= enc->coded_frame->pts;
575
        pkt.flags |= PKT_FLAG_KEY;
576 3c895fc0 Michael Niedermayer
        av_interleaved_write_frame(s, &pkt);
577 85f07f22 Fabrice Bellard
    }
578
}
579
580 10d104e4 Philip Gladstone
static void pre_process_video_frame(AVInputStream *ist, AVPicture *picture, void **bufp)
581
{
582
    AVCodecContext *dec;
583
    AVPicture *picture2;
584
    AVPicture picture_tmp;
585 0c1a9eda Zdenek Kabelac
    uint8_t *buf = 0;
586 10d104e4 Philip Gladstone
587
    dec = &ist->st->codec;
588
589
    /* deinterlace : must be done before any resize */
590 bee0d9e5 Charles Yates
    if (do_deinterlace || using_vhook) {
591 10d104e4 Philip Gladstone
        int size;
592
593
        /* create temporary picture */
594
        size = avpicture_get_size(dec->pix_fmt, dec->width, dec->height);
595
        buf = av_malloc(size);
596
        if (!buf)
597
            return;
598
        
599
        picture2 = &picture_tmp;
600
        avpicture_fill(picture2, buf, dec->pix_fmt, dec->width, dec->height);
601
602 dafc3856 Michael Niedermayer
        if (do_deinterlace){
603
            if(avpicture_deinterlace(picture2, picture, 
604
                                     dec->pix_fmt, dec->width, dec->height) < 0) {
605
                /* if error, do not deinterlace */
606
                av_free(buf);
607
                buf = NULL;
608
                picture2 = picture;
609
            }
610
        } else {
611 bee0d9e5 Charles Yates
            if (img_convert(picture2, dec->pix_fmt, picture, 
612
                            dec->pix_fmt, dec->width, dec->height) < 0) {
613
                /* if error, do not copy */
614
                av_free(buf);
615
                buf = NULL;
616
                picture2 = picture;
617
            }
618
        }
619 10d104e4 Philip Gladstone
    } else {
620
        picture2 = picture;
621
    }
622
623
    frame_hook_process(picture2, dec->pix_fmt, dec->width, dec->height);
624
625
    if (picture != picture2)
626
        *picture = *picture2;
627
    *bufp = buf;
628
}
629
630 ec5517d5 Fabrice Bellard
/* we begin to correct av delay at this threshold */
631
#define AV_DELAY_MAX 0.100
632 85f07f22 Fabrice Bellard
633 1ff93ffc Todd Kirby
634
/* Expects img to be yuv420 */
635
static void fill_pad_region(AVPicture* img, int height, int width,
636
        int padtop, int padbottom, int padleft, int padright, int *color) {
637
  
638
    int i, y, shift;
639
    uint8_t *optr;
640
    
641
    for (i = 0; i < 3; i++) {
642
        shift = (i == 0) ? 0 : 1;
643
        
644
        if (padtop || padleft) {
645
            memset(img->data[i], color[i], (((img->linesize[i] * padtop) + 
646
                            padleft) >> shift));
647
        }
648
649
        if (padleft || padright) {
650
            optr = img->data[i] + (img->linesize[i] * (padtop >> shift)) +
651
                (img->linesize[i] - (padright >> shift));
652
653
            for (y = 0; y < ((height - (padtop + padbottom)) >> shift); y++) {
654
                memset(optr, color[i], (padleft + padright) >> shift);
655
                optr += img->linesize[i];
656
            }
657
        }
658
      
659
        if (padbottom) {
660
            optr = img->data[i] + (img->linesize[i] * ((height - padbottom) >> shift));
661
            memset(optr, color[i], ((img->linesize[i] * padbottom) >> shift));
662
        }
663
    }
664
}
665
666 8a6cb114 Michael Niedermayer
static int bit_buffer_size= 1024*256;
667 27537106 Michael Niedermayer
static uint8_t *bit_buffer= NULL;
668 1ff93ffc Todd Kirby
669 85f07f22 Fabrice Bellard
static void do_video_out(AVFormatContext *s, 
670
                         AVOutputStream *ost, 
671
                         AVInputStream *ist,
672 7a0f9d7e Fabrice Bellard
                         AVFrame *in_picture,
673 986ebcdb Michael Niedermayer
                         int *frame_size)
674 85f07f22 Fabrice Bellard
{
675 ec5517d5 Fabrice Bellard
    int nb_frames, i, ret;
676 a4d36c11 Michael Niedermayer
    AVFrame *final_picture, *formatted_picture;
677
    AVFrame picture_format_temp, picture_crop_temp;
678 0c1a9eda Zdenek Kabelac
    uint8_t *buf = NULL, *buf1 = NULL;
679 cfcf0ffd Fabrice Bellard
    AVCodecContext *enc, *dec;
680 a686caf0 Roman Shaposhnik
    enum PixelFormat target_pixfmt;
681 a4d36c11 Michael Niedermayer
    
682
    avcodec_get_frame_defaults(&picture_format_temp);
683
    avcodec_get_frame_defaults(&picture_crop_temp);
684
685 85f07f22 Fabrice Bellard
    enc = &ost->st->codec;
686 cfcf0ffd Fabrice Bellard
    dec = &ist->st->codec;
687 85f07f22 Fabrice Bellard
688 ec5517d5 Fabrice Bellard
    /* by default, we output a single frame */
689
    nb_frames = 1;
690
691 204c0f48 Philip Gladstone
    *frame_size = 0;
692
693 986ebcdb Michael Niedermayer
    if(video_sync_method){
694 10d104e4 Philip Gladstone
        double vdelta;
695 e928649b Michael Niedermayer
        vdelta = ost->sync_ipts * enc->frame_rate / enc->frame_rate_base - ost->sync_opts;
696
        //FIXME set to 0.5 after we fix some dts/pts bugs like in avidec.c
697
        if (vdelta < -1.1)
698
            nb_frames = 0;
699
        else if (vdelta > 1.1)
700 70122f29 Michael Niedermayer
            nb_frames = lrintf(vdelta);
701 72bd8100 Michael Niedermayer
//fprintf(stderr, "vdelta:%f, ost->sync_opts:%lld, ost->sync_ipts:%f nb_frames:%d\n", vdelta, ost->sync_opts, ost->sync_ipts, nb_frames);
702 50c3dd32 Michael Niedermayer
        if (nb_frames == 0){
703
            ++nb_frames_drop;
704
            if (verbose>2)
705
                fprintf(stderr, "*** drop!\n");
706 8300609b Michael Niedermayer
        }else if (nb_frames > 1) {
707
            nb_frames_dup += nb_frames;
708 50c3dd32 Michael Niedermayer
            if (verbose>2)
709 8300609b Michael Niedermayer
                fprintf(stderr, "*** %d dup!\n", nb_frames-1);
710 50c3dd32 Michael Niedermayer
        }
711
    }else
712
        ost->sync_opts= lrintf(ost->sync_ipts * enc->frame_rate / enc->frame_rate_base);
713 445f1b83 Roman Shaposhnik
714 ec5517d5 Fabrice Bellard
    if (nb_frames <= 0) 
715 85f07f22 Fabrice Bellard
        return;
716 ce7c56c2 Juanjo
717 cfcf0ffd Fabrice Bellard
    /* convert pixel format if needed */
718 1ff93ffc Todd Kirby
    target_pixfmt = ost->video_resample || ost->video_pad
719
        ? PIX_FMT_YUV420P : enc->pix_fmt;
720 a686caf0 Roman Shaposhnik
    if (dec->pix_fmt != target_pixfmt) {
721 cfcf0ffd Fabrice Bellard
        int size;
722
723
        /* create temporary picture */
724 39518b49 Roman Shaposhnik
        size = avpicture_get_size(target_pixfmt, dec->width, dec->height);
725 0f1578af Fabrice Bellard
        buf = av_malloc(size);
726 cfcf0ffd Fabrice Bellard
        if (!buf)
727
            return;
728 34b10a57 Dieter
        formatted_picture = &picture_format_temp;
729 a4d36c11 Michael Niedermayer
        avpicture_fill((AVPicture*)formatted_picture, buf, target_pixfmt, dec->width, dec->height);
730 cfcf0ffd Fabrice Bellard
        
731 a4d36c11 Michael Niedermayer
        if (img_convert((AVPicture*)formatted_picture, target_pixfmt, 
732 7a0f9d7e Fabrice Bellard
                        (AVPicture *)in_picture, dec->pix_fmt, 
733 cfcf0ffd Fabrice Bellard
                        dec->width, dec->height) < 0) {
734 d8019eb5 Allen Day
735
            if (verbose >= 0)
736
                fprintf(stderr, "pixel format conversion not handled\n");
737
738 cfcf0ffd Fabrice Bellard
            goto the_end;
739
        }
740
    } else {
741 a4d36c11 Michael Niedermayer
        formatted_picture = in_picture;
742 cfcf0ffd Fabrice Bellard
    }
743
744 1ff93ffc Todd Kirby
    /* XXX: resampling could be done before raw format conversion in
745 cfcf0ffd Fabrice Bellard
       some cases to go faster */
746
    /* XXX: only works for YUV420P */
747 85f07f22 Fabrice Bellard
    if (ost->video_resample) {
748 34b10a57 Dieter
        final_picture = &ost->pict_tmp;
749 a4d36c11 Michael Niedermayer
        img_resample(ost->img_resample_ctx, (AVPicture*)final_picture, (AVPicture*)formatted_picture);
750 1ff93ffc Todd Kirby
       
751
        if (ost->padtop || ost->padbottom || ost->padleft || ost->padright) {
752 a4d36c11 Michael Niedermayer
            fill_pad_region((AVPicture*)final_picture, enc->height, enc->width,
753 1ff93ffc Todd Kirby
                    ost->padtop, ost->padbottom, ost->padleft, ost->padright,
754
                    padcolor);
755
        }
756
        
757 a686caf0 Roman Shaposhnik
        if (enc->pix_fmt != PIX_FMT_YUV420P) {
758
            int size;
759
            
760
            av_free(buf);
761
            /* create temporary picture */
762
            size = avpicture_get_size(enc->pix_fmt, enc->width, enc->height);
763
            buf = av_malloc(size);
764
            if (!buf)
765
                return;
766
            final_picture = &picture_format_temp;
767 a4d36c11 Michael Niedermayer
            avpicture_fill((AVPicture*)final_picture, buf, enc->pix_fmt, enc->width, enc->height);
768 a686caf0 Roman Shaposhnik
        
769 a4d36c11 Michael Niedermayer
            if (img_convert((AVPicture*)final_picture, enc->pix_fmt, 
770
                            (AVPicture*)&ost->pict_tmp, PIX_FMT_YUV420P, 
771 a686caf0 Roman Shaposhnik
                            enc->width, enc->height) < 0) {
772 d8019eb5 Allen Day
773
                if (verbose >= 0)
774
                    fprintf(stderr, "pixel format conversion not handled\n");
775
776 a686caf0 Roman Shaposhnik
                goto the_end;
777
            }
778
        }
779 34b10a57 Dieter
    } else if (ost->video_crop) {
780
        picture_crop_temp.data[0] = formatted_picture->data[0] +
781
                (ost->topBand * formatted_picture->linesize[0]) + ost->leftBand;
782
783
        picture_crop_temp.data[1] = formatted_picture->data[1] +
784
                ((ost->topBand >> 1) * formatted_picture->linesize[1]) +
785
                (ost->leftBand >> 1);
786
787
        picture_crop_temp.data[2] = formatted_picture->data[2] +
788
                ((ost->topBand >> 1) * formatted_picture->linesize[2]) +
789
                (ost->leftBand >> 1);
790
791
        picture_crop_temp.linesize[0] = formatted_picture->linesize[0];
792
        picture_crop_temp.linesize[1] = formatted_picture->linesize[1];
793
        picture_crop_temp.linesize[2] = formatted_picture->linesize[2];
794
        final_picture = &picture_crop_temp;
795 1ff93ffc Todd Kirby
    } else if (ost->video_pad) {
796
        final_picture = &ost->pict_tmp;
797
798
        for (i = 0; i < 3; i++) {
799
            uint8_t *optr, *iptr;
800
            int shift = (i == 0) ? 0 : 1;
801
            int y, yheight;
802
            
803
            /* set offset to start writing image into */
804
            optr = final_picture->data[i] + (((final_picture->linesize[i] * 
805
                            ost->padtop) + ost->padleft) >> shift);
806
            iptr = formatted_picture->data[i];
807
808
            yheight = (enc->height - ost->padtop - ost->padbottom) >> shift;
809
            for (y = 0; y < yheight; y++) {
810
                /* copy unpadded image row into padded image row */
811
                memcpy(optr, iptr, formatted_picture->linesize[i]);
812
                optr += final_picture->linesize[i];
813
                iptr += formatted_picture->linesize[i];
814
            }
815
        }
816
817 a4d36c11 Michael Niedermayer
        fill_pad_region((AVPicture*)final_picture, enc->height, enc->width,
818 1ff93ffc Todd Kirby
                ost->padtop, ost->padbottom, ost->padleft, ost->padright,
819
                padcolor);
820
        
821
        if (enc->pix_fmt != PIX_FMT_YUV420P) {
822
            int size;
823
824
            av_free(buf);
825
            /* create temporary picture */
826
            size = avpicture_get_size(enc->pix_fmt, enc->width, enc->height);
827
            buf = av_malloc(size);
828
            if (!buf)
829
                return;
830
            final_picture = &picture_format_temp;
831 a4d36c11 Michael Niedermayer
            avpicture_fill((AVPicture*)final_picture, buf, enc->pix_fmt, enc->width, enc->height);
832 1ff93ffc Todd Kirby
833 a4d36c11 Michael Niedermayer
            if (img_convert((AVPicture*)final_picture, enc->pix_fmt, 
834
                        (AVPicture*)&ost->pict_tmp, PIX_FMT_YUV420P, 
835 1ff93ffc Todd Kirby
                        enc->width, enc->height) < 0) {
836 d8019eb5 Allen Day
837
                if (verbose >= 0)
838
                    fprintf(stderr, "pixel format conversion not handled\n");
839
840 1ff93ffc Todd Kirby
                goto the_end;
841
            }
842
        }
843 85f07f22 Fabrice Bellard
    } else {
844 34b10a57 Dieter
        final_picture = formatted_picture;
845 85f07f22 Fabrice Bellard
    }
846
    /* duplicates frame if needed */
847 ec5517d5 Fabrice Bellard
    for(i=0;i<nb_frames;i++) {
848 e928649b Michael Niedermayer
        AVPacket pkt;
849
        av_init_packet(&pkt);
850
        pkt.stream_index= ost->index;
851
852 e8750b00 Fred Rothganger
        if (s->oformat->flags & AVFMT_RAWPICTURE) {
853
            /* raw pictures are written as AVPicture structure to
854
               avoid any copies. We support temorarily the older
855
               method. */
856 2744ca9a Roman Shaposhnik
            AVFrame* old_frame = enc->coded_frame;
857 e928649b Michael Niedermayer
            enc->coded_frame = dec->coded_frame; //FIXME/XXX remove this hack
858
            pkt.data= (uint8_t *)final_picture;
859
            pkt.size=  sizeof(AVPicture);
860
            if(dec->coded_frame)
861
                pkt.pts= dec->coded_frame->pts;
862
            if(dec->coded_frame && dec->coded_frame->key_frame)
863
                pkt.flags |= PKT_FLAG_KEY;
864
865 3c895fc0 Michael Niedermayer
            av_interleaved_write_frame(s, &pkt);
866 2744ca9a Roman Shaposhnik
            enc->coded_frame = old_frame;
867 e8750b00 Fred Rothganger
        } else {
868 492cd3a9 Michael Niedermayer
            AVFrame big_picture;
869 a4d36c11 Michael Niedermayer
870
            big_picture= *final_picture;
871 7a0f9d7e Fabrice Bellard
            /* better than nothing: use input picture interlaced
872
               settings */
873
            big_picture.interlaced_frame = in_picture->interlaced_frame;
874 bb198e19 Michael Niedermayer
            if(do_interlace_me || do_interlace_dct){
875
                if(top_field_first == -1)
876
                    big_picture.top_field_first = in_picture->top_field_first;
877
                else
878 2a8edc5d Michael Niedermayer
                    big_picture.top_field_first = top_field_first;
879 bb198e19 Michael Niedermayer
            }
880 7a0f9d7e Fabrice Bellard
881 85f07f22 Fabrice Bellard
            /* handles sameq here. This is not correct because it may
882
               not be a global option */
883
            if (same_quality) {
884 1e491e29 Michael Niedermayer
                big_picture.quality = ist->st->quality;
885
            }else
886
                big_picture.quality = ost->st->quality;
887 f4f3223f Michael Niedermayer
            if(!me_threshold)
888
                big_picture.pict_type = 0;
889 50c3dd32 Michael Niedermayer
//            big_picture.pts = AV_NOPTS_VALUE;
890
            big_picture.pts= av_rescale(ost->sync_opts, AV_TIME_BASE*(int64_t)enc->frame_rate_base, enc->frame_rate);
891
//av_log(NULL, AV_LOG_DEBUG, "%lld -> encoder\n", ost->sync_opts);
892 cfcf0ffd Fabrice Bellard
            ret = avcodec_encode_video(enc, 
893 8a6cb114 Michael Niedermayer
                                       bit_buffer, bit_buffer_size,
894 1e491e29 Michael Niedermayer
                                       &big_picture);
895 44429457 Juanjo
            //enc->frame_number = enc->real_pict_num;
896 e928649b Michael Niedermayer
            if(ret){
897 27537106 Michael Niedermayer
                pkt.data= bit_buffer;
898 e928649b Michael Niedermayer
                pkt.size= ret;
899
                if(enc->coded_frame)
900
                    pkt.pts= enc->coded_frame->pts;
901 50c3dd32 Michael Niedermayer
/*av_log(NULL, AV_LOG_DEBUG, "encoder -> %lld/%lld\n", 
902
   pkt.pts != AV_NOPTS_VALUE ? av_rescale(pkt.pts, enc->frame_rate, AV_TIME_BASE*(int64_t)enc->frame_rate_base) : -1,
903
   pkt.dts != AV_NOPTS_VALUE ? av_rescale(pkt.dts, enc->frame_rate, AV_TIME_BASE*(int64_t)enc->frame_rate_base) : -1);*/
904
905 e928649b Michael Niedermayer
                if(enc->coded_frame && enc->coded_frame->key_frame)
906
                    pkt.flags |= PKT_FLAG_KEY;
907 3c895fc0 Michael Niedermayer
                av_interleaved_write_frame(s, &pkt);
908 e928649b Michael Niedermayer
                *frame_size = ret;
909
                //fprintf(stderr,"\nFrame: %3d %3d size: %5d type: %d",
910
                //        enc->frame_number-1, enc->real_pict_num, ret,
911
                //        enc->pict_type);
912
                /* if two pass, output log */
913
                if (ost->logfile && enc->stats_out) {
914
                    fprintf(ost->logfile, "%s", enc->stats_out);
915
                }
916 5abdb4b1 Fabrice Bellard
            }
917 85f07f22 Fabrice Bellard
        }
918 50c3dd32 Michael Niedermayer
        ost->sync_opts++;
919 ec5517d5 Fabrice Bellard
        ost->frame_number++;
920 85f07f22 Fabrice Bellard
    }
921 ec5517d5 Fabrice Bellard
 the_end:
922 0f1578af Fabrice Bellard
    av_free(buf);
923
    av_free(buf1);
924 85f07f22 Fabrice Bellard
}
925
926 140cb663 Michael Niedermayer
static double psnr(double d){
927
    if(d==0) return INFINITY;
928 b29f97d1 Zdenek Kabelac
    return -10.0*log(d)/log(10.0);
929 140cb663 Michael Niedermayer
}
930
931 ec5517d5 Fabrice Bellard
static void do_video_stats(AVFormatContext *os, AVOutputStream *ost, 
932
                           int frame_size)
933 ce7c56c2 Juanjo
{
934
    static FILE *fvstats=NULL;
935
    char filename[40];
936 bf5af568 Fabrice Bellard
    time_t today2;
937
    struct tm *today;
938 ce7c56c2 Juanjo
    AVCodecContext *enc;
939
    int frame_number;
940 0c1a9eda Zdenek Kabelac
    int64_t ti;
941 ce7c56c2 Juanjo
    double ti1, bitrate, avg_bitrate;
942
    
943
    if (!fvstats) {
944
        today2 = time(NULL);
945
        today = localtime(&today2);
946
        sprintf(filename, "vstats_%02d%02d%02d.log", today->tm_hour,
947
                                               today->tm_min,
948
                                               today->tm_sec);
949
        fvstats = fopen(filename,"w");
950
        if (!fvstats) {
951
            perror("fopen");
952
            exit(1);
953
        }
954
    }
955
    
956
    ti = MAXINT64;
957
    enc = &ost->st->codec;
958
    if (enc->codec_type == CODEC_TYPE_VIDEO) {
959 ec5517d5 Fabrice Bellard
        frame_number = ost->frame_number;
960 158c7f05 Michael Niedermayer
        fprintf(fvstats, "frame= %5d q= %2.1f ", frame_number, enc->coded_frame->quality/(float)FF_QP2LAMBDA);
961 140cb663 Michael Niedermayer
        if (enc->flags&CODEC_FLAG_PSNR)
962 492cd3a9 Michael Niedermayer
            fprintf(fvstats, "PSNR= %6.2f ", psnr(enc->coded_frame->error[0]/(enc->width*enc->height*255.0*255.0)));
963 ce7c56c2 Juanjo
        
964
        fprintf(fvstats,"f_size= %6d ", frame_size);
965 ec5517d5 Fabrice Bellard
        /* compute pts value */
966 e928649b Michael Niedermayer
        ti1 = (double)ost->sync_opts *enc->frame_rate_base / enc->frame_rate;
967 ce7c56c2 Juanjo
        if (ti1 < 0.01)
968
            ti1 = 0.01;
969
    
970 14bea432 Michael Niedermayer
        bitrate = (double)(frame_size * 8) * enc->frame_rate / enc->frame_rate_base / 1000.0;
971 1008ceb3 Michael Niedermayer
        avg_bitrate = (double)(video_size * 8) / ti1 / 1000.0;
972 ce7c56c2 Juanjo
        fprintf(fvstats, "s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
973 1008ceb3 Michael Niedermayer
            (double)video_size / 1024, ti1, bitrate, avg_bitrate);
974 3db320ea Falk Hüffner
        fprintf(fvstats,"type= %c\n", av_get_pict_type_char(enc->coded_frame->pict_type));        
975 ce7c56c2 Juanjo
    }
976 ec5517d5 Fabrice Bellard
}
977
978 b29f97d1 Zdenek Kabelac
static void print_report(AVFormatContext **output_files,
979
                         AVOutputStream **ost_table, int nb_ostreams,
980
                         int is_last_report)
981 ec5517d5 Fabrice Bellard
{
982
    char buf[1024];
983
    AVOutputStream *ost;
984
    AVFormatContext *oc, *os;
985 0c1a9eda Zdenek Kabelac
    int64_t total_size;
986 ec5517d5 Fabrice Bellard
    AVCodecContext *enc;
987
    int frame_number, vid, i;
988
    double bitrate, ti1, pts;
989 0c1a9eda Zdenek Kabelac
    static int64_t last_time = -1;
990 ec5517d5 Fabrice Bellard
    
991
    if (!is_last_report) {
992 0c1a9eda Zdenek Kabelac
        int64_t cur_time;
993 ec5517d5 Fabrice Bellard
        /* display the report every 0.5 seconds */
994
        cur_time = av_gettime();
995
        if (last_time == -1) {
996
            last_time = cur_time;
997
            return;
998
        } 
999
        if ((cur_time - last_time) < 500000)
1000
            return;
1001
        last_time = cur_time;
1002
    }
1003
1004 ce7c56c2 Juanjo
1005 ec5517d5 Fabrice Bellard
    oc = output_files[0];
1006
1007
    total_size = url_ftell(&oc->pb);
1008
    
1009
    buf[0] = '\0';
1010
    ti1 = 1e10;
1011
    vid = 0;
1012
    for(i=0;i<nb_ostreams;i++) {
1013
        ost = ost_table[i];
1014
        os = output_files[ost->file_index];
1015
        enc = &ost->st->codec;
1016 10d104e4 Philip Gladstone
        if (vid && enc->codec_type == CODEC_TYPE_VIDEO) {
1017 1e491e29 Michael Niedermayer
            sprintf(buf + strlen(buf), "q=%2.1f ",
1018 158c7f05 Michael Niedermayer
                    enc->coded_frame->quality/(float)FF_QP2LAMBDA);
1019 10d104e4 Philip Gladstone
        }
1020 ec5517d5 Fabrice Bellard
        if (!vid && enc->codec_type == CODEC_TYPE_VIDEO) {
1021
            frame_number = ost->frame_number;
1022 1e491e29 Michael Niedermayer
            sprintf(buf + strlen(buf), "frame=%5d q=%2.1f ",
1023 158c7f05 Michael Niedermayer
                    frame_number, enc->coded_frame ? enc->coded_frame->quality/(float)FF_QP2LAMBDA : 0);
1024 890972be Michael Niedermayer
            if(is_last_report)
1025
                sprintf(buf + strlen(buf), "L");
1026
            if (enc->flags&CODEC_FLAG_PSNR){
1027
                int j;
1028
                double error, error_sum=0;
1029
                double scale, scale_sum=0;
1030
                char type[3]= {'Y','U','V'};
1031
                sprintf(buf + strlen(buf), "PSNR=");
1032
                for(j=0; j<3; j++){
1033
                    if(is_last_report){
1034
                        error= enc->error[j];
1035
                        scale= enc->width*enc->height*255.0*255.0*frame_number;
1036
                    }else{
1037
                        error= enc->coded_frame->error[j];
1038
                        scale= enc->width*enc->height*255.0*255.0;
1039
                    }
1040
                    if(j) scale/=4;
1041
                    error_sum += error;
1042
                    scale_sum += scale;
1043
                    sprintf(buf + strlen(buf), "%c:%2.2f ", type[j], psnr(error/scale));
1044
                }
1045
                sprintf(buf + strlen(buf), "*:%2.2f ", psnr(error_sum/scale_sum));
1046
            }
1047 ec5517d5 Fabrice Bellard
            vid = 1;
1048
        }
1049
        /* compute min output value */
1050 9ee91c2f Michael Niedermayer
        pts = (double)ost->st->pts.val * ost->st->time_base.num / ost->st->time_base.den;
1051 5d9827bc Kareila
        if ((pts < ti1) && (pts > 0))
1052 ec5517d5 Fabrice Bellard
            ti1 = pts;
1053
    }
1054
    if (ti1 < 0.01)
1055
        ti1 = 0.01;
1056
    
1057 f068206e Bill Eldridge
    if (verbose || is_last_report) {
1058
        bitrate = (double)(total_size * 8) / ti1 / 1000.0;
1059
        
1060
        sprintf(buf + strlen(buf), 
1061 ec5517d5 Fabrice Bellard
            "size=%8.0fkB time=%0.1f bitrate=%6.1fkbits/s",
1062
            (double)total_size / 1024, ti1, bitrate);
1063 a6a92a9a Wolfram Gloger
1064
        if (verbose > 1)
1065
          sprintf(buf + strlen(buf), " dup=%d drop=%d",
1066
                  nb_frames_dup, nb_frames_drop);
1067 f068206e Bill Eldridge
        
1068 d8019eb5 Allen Day
        if (verbose >= 0)
1069
            fprintf(stderr, "%s    \r", buf);
1070
1071 ec5517d5 Fabrice Bellard
        fflush(stderr);
1072
    }
1073 f068206e Bill Eldridge
        
1074 1008ceb3 Michael Niedermayer
    if (is_last_report && verbose >= 0){
1075
        int64_t raw= audio_size + video_size + extra_size;
1076 f068206e Bill Eldridge
        fprintf(stderr, "\n");
1077 1008ceb3 Michael Niedermayer
        fprintf(stderr, "video:%1.0fkB audio:%1.0fkB global headers:%1.0fkB muxing overhead %f%%\n",
1078
                video_size/1024.0,
1079
                audio_size/1024.0,
1080
                extra_size/1024.0,
1081
                100.0*(total_size - raw)/raw
1082
        );
1083
    }
1084 ce7c56c2 Juanjo
}
1085
1086 a700a6ae Fabrice Bellard
/* pkt = NULL means EOF (needed to flush decoder buffers) */
1087
static int output_packet(AVInputStream *ist, int ist_index,
1088
                         AVOutputStream **ost_table, int nb_ostreams,
1089 4b85a28f Wolfram Gloger
                         const AVPacket *pkt)
1090 a700a6ae Fabrice Bellard
{
1091
    AVFormatContext *os;
1092
    AVOutputStream *ost;
1093
    uint8_t *ptr;
1094
    int len, ret, i;
1095
    uint8_t *data_buf;
1096
    int data_size, got_picture;
1097
    AVFrame picture;
1098
    void *buffer_to_free;
1099 78953e62 Michael Niedermayer
    static int samples_size= 0;
1100
    static short *samples= NULL;
1101
    
1102 2b18dcd0 Michael Niedermayer
    if(!pkt){
1103
        ist->pts= ist->next_pts; // needed for last packet if vsync=0
1104
    } else if (pkt->dts != AV_NOPTS_VALUE) { //FIXME seems redundant, as libavformat does this too
1105 e928649b Michael Niedermayer
        ist->next_pts = ist->pts = pkt->dts;
1106 a700a6ae Fabrice Bellard
    } else {
1107 986ebcdb Michael Niedermayer
        assert(ist->pts == ist->next_pts);
1108 a700a6ae Fabrice Bellard
    }
1109 eb5ec8fe Michael Niedermayer
    
1110 a700a6ae Fabrice Bellard
    if (pkt == NULL) {
1111
        /* EOF handling */
1112
        ptr = NULL;
1113
        len = 0;
1114
        goto handle_eof;
1115
    }
1116
1117
    len = pkt->size;
1118
    ptr = pkt->data;
1119
    while (len > 0) {
1120
    handle_eof:
1121
        /* decode the packet if needed */
1122
        data_buf = NULL; /* fail safe */
1123
        data_size = 0;
1124
        if (ist->decoding_needed) {
1125
            switch(ist->st->codec.codec_type) {
1126 df84ac2e Michael Niedermayer
            case CODEC_TYPE_AUDIO:{
1127 78953e62 Michael Niedermayer
                if(pkt) 
1128
                    samples= av_fast_realloc(samples, &samples_size, FFMAX(pkt->size, AVCODEC_MAX_AUDIO_FRAME_SIZE));
1129 a700a6ae Fabrice Bellard
                    /* XXX: could avoid copy if PCM 16 bits with same
1130
                       endianness as CPU */
1131
                ret = avcodec_decode_audio(&ist->st->codec, samples, &data_size,
1132
                                           ptr, len);
1133
                if (ret < 0)
1134
                    goto fail_decode;
1135
                ptr += ret;
1136
                len -= ret;
1137
                /* Some bug in mpeg audio decoder gives */
1138
                /* data_size < 0, it seems they are overflows */
1139
                if (data_size <= 0) {
1140
                    /* no audio frame */
1141
                    continue;
1142
                }
1143
                data_buf = (uint8_t *)samples;
1144 4b85a28f Wolfram Gloger
                ist->next_pts += ((int64_t)AV_TIME_BASE/2 * data_size) / 
1145
                    (ist->st->codec.sample_rate * ist->st->codec.channels);
1146 df84ac2e Michael Niedermayer
                break;}
1147 a700a6ae Fabrice Bellard
            case CODEC_TYPE_VIDEO:
1148
                    data_size = (ist->st->codec.width * ist->st->codec.height * 3) / 2;
1149
                    /* XXX: allocate picture correctly */
1150 9740beff Michael Niedermayer
                    avcodec_get_frame_defaults(&picture);
1151
1152 a700a6ae Fabrice Bellard
                    ret = avcodec_decode_video(&ist->st->codec, 
1153
                                               &picture, &got_picture, ptr, len);
1154
                    ist->st->quality= picture.quality;
1155
                    if (ret < 0) 
1156
                        goto fail_decode;
1157
                    if (!got_picture) {
1158
                        /* no picture yet */
1159
                        goto discard_packet;
1160
                    }
1161
                    if (ist->st->codec.frame_rate_base != 0) {
1162
                        ist->next_pts += ((int64_t)AV_TIME_BASE * 
1163
                                          ist->st->codec.frame_rate_base) /
1164
                            ist->st->codec.frame_rate;
1165
                    }
1166
                    len = 0;
1167
                    break;
1168
                default:
1169
                    goto fail_decode;
1170
                }
1171
            } else {
1172
                data_buf = ptr;
1173
                data_size = len;
1174
                ret = len;
1175
                len = 0;
1176
            }
1177
1178
            buffer_to_free = NULL;
1179
            if (ist->st->codec.codec_type == CODEC_TYPE_VIDEO) {
1180
                pre_process_video_frame(ist, (AVPicture *)&picture, 
1181
                                        &buffer_to_free);
1182
            }
1183
1184
            /* frame rate emulation */
1185
            if (ist->st->codec.rate_emu) {
1186
                int64_t pts = av_rescale((int64_t) ist->frame * ist->st->codec.frame_rate_base, 1000000, ist->st->codec.frame_rate);
1187
                int64_t now = av_gettime() - ist->start;
1188
                if (pts > now)
1189
                    usleep(pts - now);
1190
1191
                ist->frame++;
1192
            }
1193
1194
#if 0
1195
            /* mpeg PTS deordering : if it is a P or I frame, the PTS
1196
               is the one of the next displayed one */
1197
            /* XXX: add mpeg4 too ? */
1198
            if (ist->st->codec.codec_id == CODEC_ID_MPEG1VIDEO) {
1199
                if (ist->st->codec.pict_type != B_TYPE) {
1200
                    int64_t tmp;
1201
                    tmp = ist->last_ip_pts;
1202
                    ist->last_ip_pts  = ist->frac_pts.val;
1203
                    ist->frac_pts.val = tmp;
1204
                }
1205
            }
1206
#endif
1207
            /* if output time reached then transcode raw format, 
1208
               encode packets and output them */
1209
            if (start_time == 0 || ist->pts >= start_time)
1210
                for(i=0;i<nb_ostreams;i++) {
1211
                    int frame_size;
1212
1213
                    ost = ost_table[i];
1214
                    if (ost->source_index == ist_index) {
1215
                        os = output_files[ost->file_index];
1216
1217
#if 0
1218
                        printf("%d: got pts=%0.3f %0.3f\n", i, 
1219
                               (double)pkt->pts / AV_TIME_BASE, 
1220
                               ((double)ist->pts / AV_TIME_BASE) - 
1221 986ebcdb Michael Niedermayer
                               ((double)ost->st->pts.val * ost->st->time_base.num / ost->st->time_base.den));
1222 a700a6ae Fabrice Bellard
#endif
1223
                        /* set the input output pts pairs */
1224 a6a92a9a Wolfram Gloger
                        ost->sync_ipts = (double)(ist->pts + input_files_ts_offset[ist->file_index])/ AV_TIME_BASE;
1225 a700a6ae Fabrice Bellard
1226
                        if (ost->encoding_needed) {
1227
                            switch(ost->st->codec.codec_type) {
1228
                            case CODEC_TYPE_AUDIO:
1229
                                do_audio_out(os, ost, ist, data_buf, data_size);
1230
                                break;
1231
                            case CODEC_TYPE_VIDEO:
1232 986ebcdb Michael Niedermayer
                                    do_video_out(os, ost, ist, &picture, &frame_size);
1233 1008ceb3 Michael Niedermayer
                                    video_size += frame_size;
1234 a700a6ae Fabrice Bellard
                                    if (do_vstats && frame_size)
1235
                                        do_video_stats(os, ost, frame_size);
1236
                                break;
1237
                            default:
1238
                                av_abort();
1239
                            }
1240
                        } else {
1241 e928649b Michael Niedermayer
                            AVFrame avframe; //FIXME/XXX remove this
1242
                            AVPacket opkt;
1243
                            av_init_packet(&opkt);
1244
1245 a700a6ae Fabrice Bellard
                            /* no reencoding needed : output the packet directly */
1246
                            /* force the input stream PTS */
1247
                        
1248 9740beff Michael Niedermayer
                            avcodec_get_frame_defaults(&avframe);
1249 a700a6ae Fabrice Bellard
                            ost->st->codec.coded_frame= &avframe;
1250
                            avframe.key_frame = pkt->flags & PKT_FLAG_KEY; 
1251 bf17ff61 Michael Niedermayer
1252 c7baf14b Michael Niedermayer
                            if(ost->st->codec.codec_type == CODEC_TYPE_AUDIO)
1253
                                audio_size += data_size;
1254 daed32f7 Wolfram Gloger
                            else if (ost->st->codec.codec_type == CODEC_TYPE_VIDEO) {
1255 c7baf14b Michael Niedermayer
                                video_size += data_size;
1256 daed32f7 Wolfram Gloger
                                ost->sync_opts++;
1257
                            }
1258 c7baf14b Michael Niedermayer
1259 e928649b Michael Niedermayer
                            opkt.stream_index= ost->index;
1260
                            opkt.data= data_buf;
1261
                            opkt.size= data_size;
1262 6c55b27f Michael Niedermayer
                            if(pkt->pts != AV_NOPTS_VALUE)
1263
                                opkt.pts= pkt->pts + input_files_ts_offset[ist->file_index];
1264
                            else
1265
                                opkt.pts= AV_NOPTS_VALUE;
1266 a6a92a9a Wolfram Gloger
                            opkt.dts= pkt->dts + input_files_ts_offset[ist->file_index];
1267 e928649b Michael Niedermayer
                            opkt.flags= pkt->flags;
1268
                            
1269 3c895fc0 Michael Niedermayer
                            av_interleaved_write_frame(os, &opkt);
1270 a700a6ae Fabrice Bellard
                            ost->st->codec.frame_number++;
1271
                            ost->frame_number++;
1272
                        }
1273
                    }
1274
                }
1275
            av_free(buffer_to_free);
1276
        }
1277
 discard_packet:
1278 6f824977 Michael Niedermayer
    if (pkt == NULL) {
1279
        /* EOF handling */
1280
  
1281
        for(i=0;i<nb_ostreams;i++) {
1282
            ost = ost_table[i];
1283
            if (ost->source_index == ist_index) {
1284
                AVCodecContext *enc= &ost->st->codec;
1285
                os = output_files[ost->file_index];
1286
                
1287
                if(ost->st->codec.codec_type == CODEC_TYPE_AUDIO && enc->frame_size <=1)
1288
                    continue;
1289
                if(ost->st->codec.codec_type == CODEC_TYPE_VIDEO && (os->oformat->flags & AVFMT_RAWPICTURE))
1290
                    continue;
1291
1292
                if (ost->encoding_needed) {
1293
                    for(;;) {
1294
                        AVPacket pkt;
1295
                        av_init_packet(&pkt);
1296
                        pkt.stream_index= ost->index;
1297
 
1298
                        switch(ost->st->codec.codec_type) {
1299
                        case CODEC_TYPE_AUDIO:        
1300 8a6cb114 Michael Niedermayer
                            ret = avcodec_encode_audio(enc, bit_buffer, bit_buffer_size, NULL);
1301 6f824977 Michael Niedermayer
                            audio_size += ret;
1302
                            pkt.flags |= PKT_FLAG_KEY;
1303
                            break;
1304
                        case CODEC_TYPE_VIDEO:
1305 8a6cb114 Michael Niedermayer
                            ret = avcodec_encode_video(enc, bit_buffer, bit_buffer_size, NULL);
1306 6f824977 Michael Niedermayer
                            video_size += ret;
1307
                            if(enc->coded_frame && enc->coded_frame->key_frame)
1308
                                pkt.flags |= PKT_FLAG_KEY;
1309
                            if (ost->logfile && enc->stats_out) {
1310
                                fprintf(ost->logfile, "%s", enc->stats_out);
1311
                            }
1312
                            break;
1313
                        default:
1314
                            ret=-1;
1315
                        }
1316
                            
1317
                        if(ret<=0)
1318
                            break;
1319 27537106 Michael Niedermayer
                        pkt.data= bit_buffer;
1320 6f824977 Michael Niedermayer
                        pkt.size= ret;
1321
                        if(enc->coded_frame)
1322
                            pkt.pts= enc->coded_frame->pts;
1323
                        av_interleaved_write_frame(os, &pkt);
1324
                    }
1325
                }
1326
            }
1327
        }
1328
    }
1329
 
1330 a700a6ae Fabrice Bellard
    return 0;
1331
 fail_decode:
1332
    return -1;
1333
}
1334
1335
1336 85f07f22 Fabrice Bellard
/*
1337
 * The following code is the main loop of the file converter
1338
 */
1339
static int av_encode(AVFormatContext **output_files,
1340
                     int nb_output_files,
1341
                     AVFormatContext **input_files,
1342
                     int nb_input_files,
1343
                     AVStreamMap *stream_maps, int nb_stream_maps)
1344
{
1345 445f1b83 Roman Shaposhnik
    int ret, i, j, k, n, nb_istreams = 0, nb_ostreams = 0;
1346 85f07f22 Fabrice Bellard
    AVFormatContext *is, *os;
1347
    AVCodecContext *codec, *icodec;
1348
    AVOutputStream *ost, **ost_table = NULL;
1349
    AVInputStream *ist, **ist_table = NULL;
1350 bdc4796f Fabrice Bellard
    AVInputFile *file_table;
1351 51bd4565 Philip Gladstone
    AVFormatContext *stream_no_data;
1352 cb09b2ed Philip Gladstone
    int key;
1353 bdc4796f Fabrice Bellard
1354 51bd4565 Philip Gladstone
    file_table= (AVInputFile*) av_mallocz(nb_input_files * sizeof(AVInputFile));
1355 bdc4796f Fabrice Bellard
    if (!file_table)
1356
        goto fail;
1357 27537106 Michael Niedermayer
        
1358 85f07f22 Fabrice Bellard
    /* input stream init */
1359
    j = 0;
1360
    for(i=0;i<nb_input_files;i++) {
1361
        is = input_files[i];
1362
        file_table[i].ist_index = j;
1363 79fdaa4c Fabrice Bellard
        file_table[i].nb_streams = is->nb_streams;
1364 85f07f22 Fabrice Bellard
        j += is->nb_streams;
1365
    }
1366
    nb_istreams = j;
1367
1368
    ist_table = av_mallocz(nb_istreams * sizeof(AVInputStream *));
1369
    if (!ist_table)
1370 bdc4796f Fabrice Bellard
        goto fail;
1371 85f07f22 Fabrice Bellard
    
1372
    for(i=0;i<nb_istreams;i++) {
1373
        ist = av_mallocz(sizeof(AVInputStream));
1374
        if (!ist)
1375
            goto fail;
1376
        ist_table[i] = ist;
1377
    }
1378
    j = 0;
1379
    for(i=0;i<nb_input_files;i++) {
1380
        is = input_files[i];
1381
        for(k=0;k<is->nb_streams;k++) {
1382
            ist = ist_table[j++];
1383
            ist->st = is->streams[k];
1384
            ist->file_index = i;
1385
            ist->index = k;
1386
            ist->discard = 1; /* the stream is discarded by default
1387
                                 (changed later) */
1388 bdfcbbed Max Krasnyansky
1389
            if (ist->st->codec.rate_emu) {
1390
                ist->start = av_gettime();
1391
                ist->frame = 0;
1392
            }
1393 85f07f22 Fabrice Bellard
        }
1394
    }
1395
1396
    /* output stream init */
1397
    nb_ostreams = 0;
1398
    for(i=0;i<nb_output_files;i++) {
1399
        os = output_files[i];
1400
        nb_ostreams += os->nb_streams;
1401
    }
1402
    if (nb_stream_maps > 0 && nb_stream_maps != nb_ostreams) {
1403
        fprintf(stderr, "Number of stream maps must match number of output streams\n");
1404
        exit(1);
1405
    }
1406
1407 bd073980 Brian Foley
    /* Sanity check the mapping args -- do the input files & streams exist? */
1408
    for(i=0;i<nb_stream_maps;i++) {
1409
        int fi = stream_maps[i].file_index;
1410
        int si = stream_maps[i].stream_index;
1411
        
1412
        if (fi < 0 || fi > nb_input_files - 1 ||
1413
            si < 0 || si > file_table[fi].nb_streams - 1) {
1414
            fprintf(stderr,"Could not find input stream #%d.%d\n", fi, si);
1415
            exit(1);
1416
        }
1417
    }
1418
    
1419 85f07f22 Fabrice Bellard
    ost_table = av_mallocz(sizeof(AVOutputStream *) * nb_ostreams);
1420
    if (!ost_table)
1421
        goto fail;
1422
    for(i=0;i<nb_ostreams;i++) {
1423
        ost = av_mallocz(sizeof(AVOutputStream));
1424
        if (!ost)
1425
            goto fail;
1426
        ost_table[i] = ost;
1427
    }
1428
    
1429
    n = 0;
1430
    for(k=0;k<nb_output_files;k++) {
1431
        os = output_files[k];
1432
        for(i=0;i<os->nb_streams;i++) {
1433
            int found;
1434
            ost = ost_table[n++];
1435
            ost->file_index = k;
1436
            ost->index = i;
1437
            ost->st = os->streams[i];
1438
            if (nb_stream_maps > 0) {
1439
                ost->source_index = file_table[stream_maps[n-1].file_index].ist_index + 
1440
                    stream_maps[n-1].stream_index;
1441 bd073980 Brian Foley
                    
1442
                /* Sanity check that the stream types match */
1443
                if (ist_table[ost->source_index]->st->codec.codec_type != ost->st->codec.codec_type) {
1444
                    fprintf(stderr, "Codec type mismatch for mapping #%d.%d -> #%d.%d\n",
1445
                        stream_maps[n-1].file_index, stream_maps[n-1].stream_index,
1446
                        ost->file_index, ost->index);
1447
                    exit(1);
1448
                }
1449
                
1450 85f07f22 Fabrice Bellard
            } else {
1451
                /* get corresponding input stream index : we select the first one with the right type */
1452
                found = 0;
1453
                for(j=0;j<nb_istreams;j++) {
1454
                    ist = ist_table[j];
1455
                    if (ist->discard && 
1456
                        ist->st->codec.codec_type == ost->st->codec.codec_type) {
1457
                        ost->source_index = j;
1458
                        found = 1;
1459 c19e76ce Nathan Kurz
                        break;
1460 85f07f22 Fabrice Bellard
                    }
1461
                }
1462
                
1463
                if (!found) {
1464
                    /* try again and reuse existing stream */
1465
                    for(j=0;j<nb_istreams;j++) {
1466
                        ist = ist_table[j];
1467
                        if (ist->st->codec.codec_type == ost->st->codec.codec_type) {
1468
                            ost->source_index = j;
1469
                            found = 1;
1470
                        }
1471
                    }
1472
                    if (!found) {
1473
                        fprintf(stderr, "Could not find input stream matching output stream #%d.%d\n",
1474
                                ost->file_index, ost->index);
1475
                        exit(1);
1476
                    }
1477
                }
1478
            }
1479
            ist = ist_table[ost->source_index];
1480
            ist->discard = 0;
1481
        }
1482
    }
1483
1484
    /* for each output stream, we compute the right encoding parameters */
1485
    for(i=0;i<nb_ostreams;i++) {
1486
        ost = ost_table[i];
1487
        ist = ist_table[ost->source_index];
1488
1489
        codec = &ost->st->codec;
1490
        icodec = &ist->st->codec;
1491
1492 1629626f Fabrice Bellard
        if (ost->st->stream_copy) {
1493
            /* if stream_copy is selected, no need to decode or encode */
1494
            codec->codec_id = icodec->codec_id;
1495
            codec->codec_type = icodec->codec_type;
1496 b2a2197e Michael Niedermayer
            if(!codec->codec_tag) codec->codec_tag = icodec->codec_tag;
1497 1629626f Fabrice Bellard
            codec->bit_rate = icodec->bit_rate;
1498
            switch(codec->codec_type) {
1499
            case CODEC_TYPE_AUDIO:
1500
                codec->sample_rate = icodec->sample_rate;
1501
                codec->channels = icodec->channels;
1502 0a3b0447 Michael Niedermayer
                codec->frame_size = icodec->frame_size;
1503 1629626f Fabrice Bellard
                break;
1504
            case CODEC_TYPE_VIDEO:
1505
                codec->frame_rate = icodec->frame_rate;
1506 14bea432 Michael Niedermayer
                codec->frame_rate_base = icodec->frame_rate_base;
1507 1629626f Fabrice Bellard
                codec->width = icodec->width;
1508
                codec->height = icodec->height;
1509
                break;
1510
            default:
1511
                av_abort();
1512
            }
1513
        } else {
1514
            switch(codec->codec_type) {
1515
            case CODEC_TYPE_AUDIO:
1516 85f07f22 Fabrice Bellard
                if (fifo_init(&ost->fifo, 2 * MAX_AUDIO_PACKET_SIZE))
1517
                    goto fail;
1518 1629626f Fabrice Bellard
                
1519 85f07f22 Fabrice Bellard
                if (codec->channels == icodec->channels &&
1520
                    codec->sample_rate == icodec->sample_rate) {
1521
                    ost->audio_resample = 0;
1522
                } else {
1523 e0d2714a Juanjo
                    if (codec->channels != icodec->channels &&
1524 23c99253 Michael Niedermayer
                        (icodec->codec_id == CODEC_ID_AC3 ||
1525
                         icodec->codec_id == CODEC_ID_DTS)) {
1526
                        /* Special case for 5:1 AC3 and DTS input */
1527 e0d2714a Juanjo
                        /* and mono or stereo output      */
1528 6dc96cb0 Juanjo
                        /* Request specific number of channels */
1529
                        icodec->channels = codec->channels;
1530
                        if (codec->sample_rate == icodec->sample_rate)
1531
                            ost->audio_resample = 0;
1532
                        else {
1533
                            ost->audio_resample = 1;
1534
                        }
1535 e0d2714a Juanjo
                    } else {
1536
                        ost->audio_resample = 1; 
1537 986ebcdb Michael Niedermayer
                    }
1538
                }
1539 ff4905a5 Michael Niedermayer
                if(audio_sync_method>1)
1540 986ebcdb Michael Niedermayer
                    ost->audio_resample = 1;
1541
1542
                if(ost->audio_resample){
1543
                    ost->resample = audio_resample_init(codec->channels, icodec->channels,
1544
                                                    codec->sample_rate, icodec->sample_rate);
1545
                    if(!ost->resample){
1546
                        printf("Can't resample.  Aborting.\n");
1547
                        av_abort();
1548 e0d2714a Juanjo
                    }
1549 85f07f22 Fabrice Bellard
                }
1550
                ist->decoding_needed = 1;
1551
                ost->encoding_needed = 1;
1552 1629626f Fabrice Bellard
                break;
1553
            case CODEC_TYPE_VIDEO:
1554 85f07f22 Fabrice Bellard
                if (codec->width == icodec->width &&
1555 34b10a57 Dieter
                    codec->height == icodec->height &&
1556
                    frame_topBand == 0 &&
1557
                    frame_bottomBand == 0 &&
1558
                    frame_leftBand == 0 &&
1559 1ff93ffc Todd Kirby
                    frame_rightBand == 0 && 
1560
                    frame_padtop == 0 &&
1561
                    frame_padbottom == 0 &&
1562
                    frame_padleft == 0 &&
1563
                    frame_padright == 0)
1564 34b10a57 Dieter
                {
1565
                    ost->video_resample = 0;
1566
                    ost->video_crop = 0;
1567 1ff93ffc Todd Kirby
                    ost->video_pad = 0;
1568 34b10a57 Dieter
                } else if ((codec->width == icodec->width -
1569
                                (frame_leftBand + frame_rightBand)) &&
1570
                        (codec->height == icodec->height -
1571
                                (frame_topBand  + frame_bottomBand)))
1572
                {
1573 85f07f22 Fabrice Bellard
                    ost->video_resample = 0;
1574 34b10a57 Dieter
                    ost->video_crop = 1;
1575
                    ost->topBand = frame_topBand;
1576
                    ost->leftBand = frame_leftBand;
1577 1ff93ffc Todd Kirby
                } else if ((codec->width == icodec->width + 
1578
                                (frame_padleft + frame_padright)) &&
1579
                        (codec->height == icodec->height +
1580
                                (frame_padtop + frame_padbottom))) {
1581
                    ost->video_resample = 0;
1582
                    ost->video_crop = 0;
1583
                    ost->video_pad = 1;
1584
                    ost->padtop = frame_padtop;
1585
                    ost->padleft = frame_padleft;
1586
                    ost->padbottom = frame_padbottom;
1587
                    ost->padright = frame_padright;
1588 2de28abb Michael Niedermayer
                    avcodec_get_frame_defaults(&ost->pict_tmp);
1589 a4d36c11 Michael Niedermayer
                    if( avpicture_alloc( (AVPicture*)&ost->pict_tmp, PIX_FMT_YUV420P,
1590 1ff93ffc Todd Kirby
                                codec->width, codec->height ) )
1591
                        goto fail;
1592 85f07f22 Fabrice Bellard
                } else {
1593
                    ost->video_resample = 1;
1594 34b10a57 Dieter
                    ost->video_crop = 0; // cropping is handled as part of resample
1595 2de28abb Michael Niedermayer
                    avcodec_get_frame_defaults(&ost->pict_tmp);
1596 a4d36c11 Michael Niedermayer
                    if( avpicture_alloc( (AVPicture*)&ost->pict_tmp, PIX_FMT_YUV420P,
1597 2caa92d9 Michael Niedermayer
                                         codec->width, codec->height ) )
1598 85f07f22 Fabrice Bellard
                        goto fail;
1599
1600 ab6d194a Michael Niedermayer
                    ost->img_resample_ctx = img_resample_full_init( 
1601 85f07f22 Fabrice Bellard
                                      ost->st->codec.width, ost->st->codec.height,
1602 ab6d194a Michael Niedermayer
                                      ist->st->codec.width, ist->st->codec.height,
1603
                                      frame_topBand, frame_bottomBand,
1604 1ff93ffc Todd Kirby
                            frame_leftBand, frame_rightBand, 
1605
                            frame_padtop, frame_padbottom, 
1606
                            frame_padleft, frame_padright);
1607
                    
1608
                    ost->padtop = frame_padtop;
1609
                    ost->padleft = frame_padleft;
1610
                    ost->padbottom = frame_padbottom;
1611
                    ost->padright = frame_padright;
1612
                   
1613 85f07f22 Fabrice Bellard
                }
1614
                ost->encoding_needed = 1;
1615
                ist->decoding_needed = 1;
1616 1629626f Fabrice Bellard
                break;
1617
            default:
1618
                av_abort();
1619 85f07f22 Fabrice Bellard
            }
1620 1629626f Fabrice Bellard
            /* two pass mode */
1621
            if (ost->encoding_needed && 
1622
                (codec->flags & (CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2))) {
1623
                char logfilename[1024];
1624
                FILE *f;
1625
                int size;
1626
                char *logbuffer;
1627
                
1628
                snprintf(logfilename, sizeof(logfilename), "%s-%d.log", 
1629
                         pass_logfilename ? 
1630
                         pass_logfilename : DEFAULT_PASS_LOGFILENAME, i);
1631
                if (codec->flags & CODEC_FLAG_PASS1) {
1632
                    f = fopen(logfilename, "w");
1633
                    if (!f) {
1634
                        perror(logfilename);
1635
                        exit(1);
1636
                    }
1637
                    ost->logfile = f;
1638
                } else {
1639
                    /* read the log file */
1640
                    f = fopen(logfilename, "r");
1641
                    if (!f) {
1642
                        perror(logfilename);
1643
                        exit(1);
1644
                    }
1645
                    fseek(f, 0, SEEK_END);
1646
                    size = ftell(f);
1647
                    fseek(f, 0, SEEK_SET);
1648
                    logbuffer = av_malloc(size + 1);
1649
                    if (!logbuffer) {
1650
                        fprintf(stderr, "Could not allocate log buffer\n");
1651
                        exit(1);
1652
                    }
1653 4776fa92 Gael Chardon
                    size = fread(logbuffer, 1, size, f);
1654 1629626f Fabrice Bellard
                    fclose(f);
1655
                    logbuffer[size] = '\0';
1656
                    codec->stats_in = logbuffer;
1657 5abdb4b1 Fabrice Bellard
                }
1658
            }
1659
        }
1660 8a6cb114 Michael Niedermayer
        if(codec->codec_type == CODEC_TYPE_VIDEO){
1661
            int size= codec->width * codec->height;
1662
            bit_buffer_size= FFMAX(bit_buffer_size, 4*size);
1663
        }
1664 85f07f22 Fabrice Bellard
    }
1665
1666 8a6cb114 Michael Niedermayer
    if (!bit_buffer)
1667
        bit_buffer = av_malloc(bit_buffer_size);
1668
    if (!bit_buffer)
1669
        goto fail;
1670
1671 1629626f Fabrice Bellard
    /* dump the file output parameters - cannot be done before in case
1672
       of stream copy */
1673
    for(i=0;i<nb_output_files;i++) {
1674
        dump_format(output_files[i], i, output_files[i]->filename, 1);
1675
    }
1676
1677
    /* dump the stream mapping */
1678 d8019eb5 Allen Day
    if (verbose >= 0) {
1679
        fprintf(stderr, "Stream mapping:\n");
1680
        for(i=0;i<nb_ostreams;i++) {
1681
            ost = ost_table[i];
1682
            fprintf(stderr, "  Stream #%d.%d -> #%d.%d\n",
1683
                    ist_table[ost->source_index]->file_index,
1684
                    ist_table[ost->source_index]->index,
1685
                    ost->file_index, 
1686
                    ost->index);
1687
        }
1688 1629626f Fabrice Bellard
    }
1689
1690 85f07f22 Fabrice Bellard
    /* open each encoder */
1691
    for(i=0;i<nb_ostreams;i++) {
1692
        ost = ost_table[i];
1693
        if (ost->encoding_needed) {
1694
            AVCodec *codec;
1695
            codec = avcodec_find_encoder(ost->st->codec.codec_id);
1696
            if (!codec) {
1697
                fprintf(stderr, "Unsupported codec for output stream #%d.%d\n", 
1698
                        ost->file_index, ost->index);
1699
                exit(1);
1700
            }
1701
            if (avcodec_open(&ost->st->codec, codec) < 0) {
1702
                fprintf(stderr, "Error while opening codec for stream #%d.%d - maybe incorrect parameters such as bit_rate, rate, width or height\n", 
1703
                        ost->file_index, ost->index);
1704
                exit(1);
1705
            }
1706 1008ceb3 Michael Niedermayer
            extra_size += ost->st->codec.extradata_size;
1707 85f07f22 Fabrice Bellard
        }
1708
    }
1709
1710
    /* open each decoder */
1711
    for(i=0;i<nb_istreams;i++) {
1712
        ist = ist_table[i];
1713
        if (ist->decoding_needed) {
1714
            AVCodec *codec;
1715
            codec = avcodec_find_decoder(ist->st->codec.codec_id);
1716
            if (!codec) {
1717 10d104e4 Philip Gladstone
                fprintf(stderr, "Unsupported codec (id=%d) for input stream #%d.%d\n", 
1718
                        ist->st->codec.codec_id, ist->file_index, ist->index);
1719 85f07f22 Fabrice Bellard
                exit(1);
1720
            }
1721
            if (avcodec_open(&ist->st->codec, codec) < 0) {
1722
                fprintf(stderr, "Error while opening codec for input stream #%d.%d\n", 
1723
                        ist->file_index, ist->index);
1724
                exit(1);
1725
            }
1726 6dc96cb0 Juanjo
            //if (ist->st->codec.codec_type == CODEC_TYPE_VIDEO)
1727
            //    ist->st->codec.flags |= CODEC_FLAG_REPEAT_FIELD;
1728 85f07f22 Fabrice Bellard
        }
1729
    }
1730
1731
    /* init pts */
1732
    for(i=0;i<nb_istreams;i++) {
1733
        ist = ist_table[i];
1734 445f1b83 Roman Shaposhnik
        is = input_files[ist->file_index];
1735 e7d0374f Roman Shaposhnik
        ist->pts = 0;
1736 bd1b79a1 Michael Niedermayer
        ist->next_pts = ist->st->start_time;
1737
        if(ist->next_pts == AV_NOPTS_VALUE) 
1738
            ist->next_pts=0;
1739 ff4905a5 Michael Niedermayer
        ist->is_start = 1;
1740 85f07f22 Fabrice Bellard
    }
1741 bd1b79a1 Michael Niedermayer
1742 85f07f22 Fabrice Bellard
    /* compute buffer size max (should use a complete heuristic) */
1743
    for(i=0;i<nb_input_files;i++) {
1744
        file_table[i].buffer_size_max = 2048;
1745
    }
1746
1747 0a38bafd Patrice Bensoussan
    /* set meta data information from input file if required */
1748
    for (i=0;i<nb_meta_data_maps;i++) {
1749
        AVFormatContext *out_file;
1750
        AVFormatContext *in_file;
1751
1752
        int out_file_index = meta_data_maps[i].out_file;
1753
        int in_file_index = meta_data_maps[i].in_file;
1754
        if ( out_file_index < 0 || out_file_index >= nb_output_files ) {
1755
            fprintf(stderr, "Invalid output file index %d map_meta_data(%d,%d)\n", out_file_index, out_file_index, in_file_index);
1756
            ret = -EINVAL;
1757
            goto fail;
1758
        }
1759
        if ( in_file_index < 0 || in_file_index >= nb_input_files ) {
1760
            fprintf(stderr, "Invalid input file index %d map_meta_data(%d,%d)\n", in_file_index, out_file_index, in_file_index);
1761
            ret = -EINVAL;
1762
            goto fail;
1763
        }                
1764
                 
1765
        out_file = output_files[out_file_index];
1766
        in_file = input_files[in_file_index];
1767
1768
        strcpy(out_file->title, in_file->title);
1769
        strcpy(out_file->author, in_file->author);
1770
        strcpy(out_file->copyright, in_file->copyright);
1771
        strcpy(out_file->comment, in_file->comment);
1772
        strcpy(out_file->album, in_file->album);
1773
        out_file->year = in_file->year;
1774
        out_file->track = in_file->track;
1775
        strcpy(out_file->genre, in_file->genre);
1776
    }
1777
        
1778 85f07f22 Fabrice Bellard
    /* open files and write file headers */
1779
    for(i=0;i<nb_output_files;i++) {
1780
        os = output_files[i];
1781 79fdaa4c Fabrice Bellard
        if (av_write_header(os) < 0) {
1782 65bf3c53 Michael Niedermayer
            fprintf(stderr, "Could not write header for output file #%d (incorrect codec parameters ?)\n", i);
1783 a38469e1 Fabrice Bellard
            ret = -EINVAL;
1784
            goto fail;
1785
        }
1786 85f07f22 Fabrice Bellard
    }
1787
1788 a38469e1 Fabrice Bellard
#ifndef CONFIG_WIN32
1789 d8019eb5 Allen Day
    if ( !using_stdin && verbose >= 0) {
1790 d9a916e2 Charles Yates
        fprintf(stderr, "Press [q] to stop encoding\n");
1791 b51469a0 Leon van Stuivenberg
        url_set_interrupt_cb(decode_interrupt_cb);
1792
    }
1793 a38469e1 Fabrice Bellard
#endif
1794
    term_init();
1795
1796 51bd4565 Philip Gladstone
    stream_no_data = 0;
1797 cb09b2ed Philip Gladstone
    key = -1;
1798 51bd4565 Philip Gladstone
1799 d9a916e2 Charles Yates
    for(; received_sigterm == 0;) {
1800 85f07f22 Fabrice Bellard
        int file_index, ist_index;
1801
        AVPacket pkt;
1802 a9aeda81 Patrice Bensoussan
        double ipts_min;
1803
        double opts_min;
1804 23ffe323 Michael Niedermayer
1805 85f07f22 Fabrice Bellard
    redo:
1806 a9aeda81 Patrice Bensoussan
        ipts_min= 1e100;
1807
        opts_min= 1e100;
1808 a38469e1 Fabrice Bellard
        /* if 'q' pressed, exits */
1809 d9a916e2 Charles Yates
        if (!using_stdin) {
1810 b51469a0 Leon van Stuivenberg
            if (q_pressed)
1811
                break;
1812 cb09b2ed Philip Gladstone
            /* read_key() returns 0 on EOF */
1813
            key = read_key();
1814
            if (key == 'q')
1815
                break;
1816
        }
1817 a38469e1 Fabrice Bellard
1818 ec5517d5 Fabrice Bellard
        /* select the stream that we must read now by looking at the
1819
           smallest output pts */
1820 85f07f22 Fabrice Bellard
        file_index = -1;
1821 ec5517d5 Fabrice Bellard
        for(i=0;i<nb_ostreams;i++) {
1822 23ffe323 Michael Niedermayer
            double ipts, opts;
1823 ec5517d5 Fabrice Bellard
            ost = ost_table[i];
1824
            os = output_files[ost->file_index];
1825
            ist = ist_table[ost->source_index];
1826 23ffe323 Michael Niedermayer
            if(ost->st->codec.codec_type == CODEC_TYPE_VIDEO)
1827
                opts = (double)ost->sync_opts * ost->st->codec.frame_rate_base / ost->st->codec.frame_rate;
1828
            else
1829
                opts = (double)ost->st->pts.val * ost->st->time_base.num / ost->st->time_base.den;
1830
            ipts = (double)ist->pts;
1831
            if (!file_table[ist->file_index].eof_reached){
1832
                if(ipts < ipts_min) {
1833
                    ipts_min = ipts;
1834
                    if(input_sync ) file_index = ist->file_index;
1835
                }
1836
                if(opts < opts_min) {
1837
                    opts_min = opts;
1838
                    if(!input_sync) file_index = ist->file_index;
1839
                }
1840 85f07f22 Fabrice Bellard
            }
1841
        }
1842
        /* if none, if is finished */
1843 51bd4565 Philip Gladstone
        if (file_index < 0) {
1844 85f07f22 Fabrice Bellard
            break;
1845 ec5517d5 Fabrice Bellard
        }
1846
1847 85f07f22 Fabrice Bellard
        /* finish if recording time exhausted */
1848 23ffe323 Michael Niedermayer
        if (recording_time > 0 && opts_min >= (recording_time / 1000000.0))
1849 85f07f22 Fabrice Bellard
            break;
1850 ec5517d5 Fabrice Bellard
1851 254abc2e Fabrice Bellard
        /* read a frame from it and output it in the fifo */
1852 85f07f22 Fabrice Bellard
        is = input_files[file_index];
1853 254abc2e Fabrice Bellard
        if (av_read_frame(is, &pkt) < 0) {
1854 85f07f22 Fabrice Bellard
            file_table[file_index].eof_reached = 1;
1855
            continue;
1856
        }
1857 303e50e6 Michael Niedermayer
1858 51bd4565 Philip Gladstone
        if (!pkt.size) {
1859
            stream_no_data = is;
1860
        } else {
1861
            stream_no_data = 0;
1862
        }
1863 254abc2e Fabrice Bellard
        if (do_pkt_dump) {
1864
            av_pkt_dump(stdout, &pkt, do_hex_dump);
1865 817b23ff Fabrice Bellard
        }
1866 79fdaa4c Fabrice Bellard
        /* the following test is needed in case new streams appear
1867
           dynamically in stream : we ignore them */
1868
        if (pkt.stream_index >= file_table[file_index].nb_streams)
1869 bf5af568 Fabrice Bellard
            goto discard_packet;
1870 85f07f22 Fabrice Bellard
        ist_index = file_table[file_index].ist_index + pkt.stream_index;
1871
        ist = ist_table[ist_index];
1872 bf5af568 Fabrice Bellard
        if (ist->discard)
1873
            goto discard_packet;
1874 85f07f22 Fabrice Bellard
1875 72bd8100 Michael Niedermayer
//        fprintf(stderr, "next:%lld dts:%lld off:%lld %d\n", ist->next_pts, pkt.dts, input_files_ts_offset[ist->file_index], ist->st->codec.codec_type);
1876
        if (pkt.dts != AV_NOPTS_VALUE) {
1877
            int64_t delta= pkt.dts - ist->next_pts;
1878
            if(ABS(delta) > 10LL*AV_TIME_BASE && !copy_ts){
1879
                input_files_ts_offset[ist->file_index]-= delta;
1880
                if (verbose > 2)
1881
                    fprintf(stderr, "timestamp discontinuity %lld, new offset= %lld\n", delta, input_files_ts_offset[ist->file_index]);
1882
                for(i=0; i<file_table[file_index].nb_streams; i++){
1883
                    int index= file_table[file_index].ist_index + i;
1884
                    ist_table[index]->next_pts += delta;
1885 ff4905a5 Michael Niedermayer
                    ist_table[index]->is_start=1;
1886 72bd8100 Michael Niedermayer
                }
1887
            }
1888
        }
1889
1890 8831db5c Michael Niedermayer
        //fprintf(stderr,"read #%d.%d size=%d\n", ist->file_index, ist->index, pkt.size);
1891 a700a6ae Fabrice Bellard
        if (output_packet(ist, ist_index, ost_table, nb_ostreams, &pkt) < 0) {
1892 d8019eb5 Allen Day
1893
            if (verbose >= 0)
1894
                fprintf(stderr, "Error while decoding stream #%d.%d\n",
1895
                        ist->file_index, ist->index);
1896
1897 a700a6ae Fabrice Bellard
            av_free_packet(&pkt);
1898
            goto redo;
1899 fe08925f Michael Niedermayer
        }
1900 a700a6ae Fabrice Bellard
        
1901 bf5af568 Fabrice Bellard
    discard_packet:
1902 85f07f22 Fabrice Bellard
        av_free_packet(&pkt);
1903
        
1904 ec5517d5 Fabrice Bellard
        /* dump report by using the output first video and audio streams */
1905
        print_report(output_files, ost_table, nb_ostreams, 0);
1906 85f07f22 Fabrice Bellard
    }
1907 a700a6ae Fabrice Bellard
1908
    /* at the end of stream, we must flush the decoder buffers */
1909
    for(i=0;i<nb_istreams;i++) {
1910
        ist = ist_table[i];
1911
        if (ist->decoding_needed) {
1912
            output_packet(ist, i, ost_table, nb_ostreams, NULL);
1913
        }
1914
    }
1915
1916 a38469e1 Fabrice Bellard
    term_exit();
1917 85f07f22 Fabrice Bellard
1918 c4e37247 Michael Niedermayer
    /* write the trailer if needed and close file */
1919
    for(i=0;i<nb_output_files;i++) {
1920
        os = output_files[i];
1921
        av_write_trailer(os);
1922
    }
1923
1924 37f5cd5a Michael Niedermayer
    /* dump report by using the first video and audio streams */
1925
    print_report(output_files, ost_table, nb_ostreams, 1);
1926
1927 85f07f22 Fabrice Bellard
    /* close each encoder */
1928
    for(i=0;i<nb_ostreams;i++) {
1929
        ost = ost_table[i];
1930
        if (ost->encoding_needed) {
1931 5abdb4b1 Fabrice Bellard
            av_freep(&ost->st->codec.stats_in);
1932 85f07f22 Fabrice Bellard
            avcodec_close(&ost->st->codec);
1933
        }
1934
    }
1935
    
1936
    /* close each decoder */
1937
    for(i=0;i<nb_istreams;i++) {
1938
        ist = ist_table[i];
1939
        if (ist->decoding_needed) {
1940
            avcodec_close(&ist->st->codec);
1941
        }
1942
    }
1943
1944
    /* finished ! */
1945
    
1946
    ret = 0;
1947
 fail1:
1948 0f1578af Fabrice Bellard
    av_free(file_table);
1949 bdc4796f Fabrice Bellard
1950 85f07f22 Fabrice Bellard
    if (ist_table) {
1951
        for(i=0;i<nb_istreams;i++) {
1952
            ist = ist_table[i];
1953 0f1578af Fabrice Bellard
            av_free(ist);
1954 85f07f22 Fabrice Bellard
        }
1955 0f1578af Fabrice Bellard
        av_free(ist_table);
1956 85f07f22 Fabrice Bellard
    }
1957
    if (ost_table) {
1958
        for(i=0;i<nb_ostreams;i++) {
1959
            ost = ost_table[i];
1960
            if (ost) {
1961 5abdb4b1 Fabrice Bellard
                if (ost->logfile) {
1962
                    fclose(ost->logfile);
1963
                    ost->logfile = NULL;
1964
                }
1965 bf5af568 Fabrice Bellard
                fifo_free(&ost->fifo); /* works even if fifo is not
1966
                                          initialized but set to zero */
1967 0f1578af Fabrice Bellard
                av_free(ost->pict_tmp.data[0]);
1968 85f07f22 Fabrice Bellard
                if (ost->video_resample)
1969
                    img_resample_close(ost->img_resample_ctx);
1970
                if (ost->audio_resample)
1971
                    audio_resample_close(ost->resample);
1972 0f1578af Fabrice Bellard
                av_free(ost);
1973 85f07f22 Fabrice Bellard
            }
1974
        }
1975 0f1578af Fabrice Bellard
        av_free(ost_table);
1976 85f07f22 Fabrice Bellard
    }
1977
    return ret;
1978
 fail:
1979
    ret = -ENOMEM;
1980
    goto fail1;
1981
}
1982
1983
#if 0
1984
int file_read(const char *filename)
1985
{
1986
    URLContext *h;
1987
    unsigned char buffer[1024];
1988
    int len, i;
1989

1990
    if (url_open(&h, filename, O_RDONLY) < 0) {
1991
        printf("could not open '%s'\n", filename);
1992
        return -1;
1993
    }
1994
    for(;;) {
1995
        len = url_read(h, buffer, sizeof(buffer));
1996
        if (len <= 0)
1997
            break;
1998
        for(i=0;i<len;i++) putchar(buffer[i]);
1999
    }
2000
    url_close(h);
2001
    return 0;
2002
}
2003
#endif
2004
2005 b29f97d1 Zdenek Kabelac
static void opt_image_format(const char *arg)
2006 817b23ff Fabrice Bellard
{
2007
    AVImageFormat *f;
2008
    
2009
    for(f = first_image_format; f != NULL; f = f->next) {
2010
        if (!strcmp(arg, f->name))
2011
            break;
2012
    }
2013
    if (!f) {
2014
        fprintf(stderr, "Unknown image format: '%s'\n", arg);
2015
        exit(1);
2016
    }
2017
    image_format = f;
2018
}
2019
2020 b29f97d1 Zdenek Kabelac
static void opt_format(const char *arg)
2021 85f07f22 Fabrice Bellard
{
2022 817b23ff Fabrice Bellard
    /* compatibility stuff for pgmyuv */
2023
    if (!strcmp(arg, "pgmyuv")) {
2024 5b6d5596 Michael Niedermayer
        pgmyuv_compatibility_hack=1;
2025 9286699a Michael Niedermayer
//        opt_image_format(arg);
2026 5b6d5596 Michael Niedermayer
        arg = "image2";
2027 817b23ff Fabrice Bellard
    }
2028
2029 79fdaa4c Fabrice Bellard
    file_iformat = av_find_input_format(arg);
2030
    file_oformat = guess_format(arg, NULL, NULL);
2031
    if (!file_iformat && !file_oformat) {
2032
        fprintf(stderr, "Unknown input or output format: %s\n", arg);
2033 85f07f22 Fabrice Bellard
        exit(1);
2034
    }
2035
}
2036
2037 b29f97d1 Zdenek Kabelac
static void opt_video_bitrate(const char *arg)
2038 85f07f22 Fabrice Bellard
{
2039
    video_bit_rate = atoi(arg) * 1000;
2040
}
2041
2042 b29f97d1 Zdenek Kabelac
static void opt_video_bitrate_tolerance(const char *arg)
2043 9cdd6a24 Michael Niedermayer
{
2044
    video_bit_rate_tolerance = atoi(arg) * 1000;
2045
}
2046
2047 b29f97d1 Zdenek Kabelac
static void opt_video_bitrate_max(const char *arg)
2048 3aa102be Michael Niedermayer
{
2049
    video_rc_max_rate = atoi(arg) * 1000;
2050
}
2051
2052 b29f97d1 Zdenek Kabelac
static void opt_video_bitrate_min(const char *arg)
2053 3aa102be Michael Niedermayer
{
2054
    video_rc_min_rate = atoi(arg) * 1000;
2055
}
2056
2057 b29f97d1 Zdenek Kabelac
static void opt_video_buffer_size(const char *arg)
2058 946c8a12 Michael Niedermayer
{
2059 622348f9 Michael Niedermayer
    video_rc_buffer_size = atoi(arg) * 8*1024;
2060 946c8a12 Michael Niedermayer
}
2061
2062 b29f97d1 Zdenek Kabelac
static void opt_video_rc_eq(char *arg)
2063 3aa102be Michael Niedermayer
{
2064
    video_rc_eq = arg;
2065
}
2066
2067 b29f97d1 Zdenek Kabelac
static void opt_video_rc_override_string(char *arg)
2068 ac2830ec Michael Niedermayer
{
2069
    video_rc_override_string = arg;
2070
}
2071
2072 3aa102be Michael Niedermayer
2073 b29f97d1 Zdenek Kabelac
static void opt_workaround_bugs(const char *arg)
2074 fe670d09 Michael Niedermayer
{
2075
    workaround_bugs = atoi(arg);
2076
}
2077
2078 b29f97d1 Zdenek Kabelac
static void opt_dct_algo(const char *arg)
2079 463678ac Michael Niedermayer
{
2080
    dct_algo = atoi(arg);
2081
}
2082
2083 b29f97d1 Zdenek Kabelac
static void opt_idct_algo(const char *arg)
2084 2ad1516a Michael Niedermayer
{
2085
    idct_algo = atoi(arg);
2086
}
2087
2088 f4f3223f Michael Niedermayer
static void opt_me_threshold(const char *arg)
2089
{
2090
    me_threshold = atoi(arg);
2091
}
2092
2093 f20f8a8b Michael Niedermayer
static void opt_mb_threshold(const char *arg)
2094
{
2095
    mb_threshold = atoi(arg);
2096
}
2097 2ad1516a Michael Niedermayer
2098 b29f97d1 Zdenek Kabelac
static void opt_error_resilience(const char *arg)
2099 8409b8fe Michael Niedermayer
{
2100
    error_resilience = atoi(arg);
2101
}
2102
2103 b29f97d1 Zdenek Kabelac
static void opt_error_concealment(const char *arg)
2104 4d2858de Michael Niedermayer
{
2105
    error_concealment = atoi(arg);
2106
}
2107
2108 b29f97d1 Zdenek Kabelac
static void opt_debug(const char *arg)
2109 59b571c1 Michael Niedermayer
{
2110
    debug = atoi(arg);
2111
}
2112 4d2858de Michael Niedermayer
2113 0c9bbaec Wolfgang Hesseler
static void opt_vismv(const char *arg)
2114
{
2115
    debug_mv = atoi(arg);
2116
}
2117
    
2118 f068206e Bill Eldridge
static void opt_verbose(const char *arg)
2119
{
2120
    verbose = atoi(arg);
2121 d8019eb5 Allen Day
    av_log_set_level(atoi(arg));
2122 f068206e Bill Eldridge
}
2123
2124 b29f97d1 Zdenek Kabelac
static void opt_frame_rate(const char *arg)
2125 85f07f22 Fabrice Bellard
{
2126 445f1b83 Roman Shaposhnik
    if (parse_frame_rate(&frame_rate, &frame_rate_base, arg) < 0) {
2127
        fprintf(stderr, "Incorrect frame rate\n");
2128
        exit(1);
2129
    }
2130 85f07f22 Fabrice Bellard
}
2131
2132 b29f97d1 Zdenek Kabelac
static void opt_frame_crop_top(const char *arg)
2133 ab6d194a Michael Niedermayer
{
2134
    frame_topBand = atoi(arg); 
2135
    if (frame_topBand < 0) {
2136
        fprintf(stderr, "Incorrect top crop size\n");
2137
        exit(1);
2138
    }
2139
    if ((frame_topBand % 2) != 0) {
2140
        fprintf(stderr, "Top crop size must be a multiple of 2\n");
2141
        exit(1);
2142
    }
2143
    if ((frame_topBand) >= frame_height){
2144
            fprintf(stderr, "Vertical crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
2145
        exit(1);
2146
    }
2147
    frame_height -= frame_topBand;
2148
}
2149
2150 b29f97d1 Zdenek Kabelac
static void opt_frame_crop_bottom(const char *arg)
2151 ab6d194a Michael Niedermayer
{
2152
    frame_bottomBand = atoi(arg);
2153
    if (frame_bottomBand < 0) {
2154
        fprintf(stderr, "Incorrect bottom crop size\n");
2155
        exit(1);
2156
    }
2157
    if ((frame_bottomBand % 2) != 0) {
2158
        fprintf(stderr, "Bottom crop size must be a multiple of 2\n");
2159
        exit(1);        
2160
    }
2161
    if ((frame_bottomBand) >= frame_height){
2162
            fprintf(stderr, "Vertical crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
2163
        exit(1);
2164
    }
2165
    frame_height -= frame_bottomBand;
2166
}
2167
2168 b29f97d1 Zdenek Kabelac
static void opt_frame_crop_left(const char *arg)
2169 ab6d194a Michael Niedermayer
{
2170
    frame_leftBand = atoi(arg);
2171
    if (frame_leftBand < 0) {
2172
        fprintf(stderr, "Incorrect left crop size\n");
2173
        exit(1);
2174
    }
2175
    if ((frame_leftBand % 2) != 0) {
2176
        fprintf(stderr, "Left crop size must be a multiple of 2\n");
2177
        exit(1);
2178
    }
2179
    if ((frame_leftBand) >= frame_width){
2180
            fprintf(stderr, "Horizontal crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
2181
        exit(1);
2182
    }
2183
    frame_width -= frame_leftBand;
2184
}
2185
2186 b29f97d1 Zdenek Kabelac
static void opt_frame_crop_right(const char *arg)
2187 ab6d194a Michael Niedermayer
{
2188
    frame_rightBand = atoi(arg);
2189
    if (frame_rightBand < 0) {
2190
        fprintf(stderr, "Incorrect right crop size\n");
2191
        exit(1);
2192
    }
2193
    if ((frame_rightBand % 2) != 0) {
2194
        fprintf(stderr, "Right crop size must be a multiple of 2\n");
2195
        exit(1);        
2196
    }
2197
    if ((frame_rightBand) >= frame_width){
2198
            fprintf(stderr, "Horizontal crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
2199
        exit(1);
2200
    }
2201
    frame_width -= frame_rightBand;
2202
}
2203
2204 b29f97d1 Zdenek Kabelac
static void opt_frame_size(const char *arg)
2205 85f07f22 Fabrice Bellard
{
2206 445f1b83 Roman Shaposhnik
    if (parse_image_size(&frame_width, &frame_height, arg) < 0) {
2207 85f07f22 Fabrice Bellard
        fprintf(stderr, "Incorrect frame size\n");
2208
        exit(1);
2209
    }
2210
    if ((frame_width % 2) != 0 || (frame_height % 2) != 0) {
2211
        fprintf(stderr, "Frame size must be a multiple of 2\n");
2212
        exit(1);
2213
    }
2214
}
2215
2216 1ff93ffc Todd Kirby
2217
#define SCALEBITS 10
2218
#define ONE_HALF  (1 << (SCALEBITS - 1))
2219
#define FIX(x)          ((int) ((x) * (1<<SCALEBITS) + 0.5))
2220
2221
#define RGB_TO_Y(r, g, b) \
2222
((FIX(0.29900) * (r) + FIX(0.58700) * (g) + \
2223
  FIX(0.11400) * (b) + ONE_HALF) >> SCALEBITS)
2224
2225
#define RGB_TO_U(r1, g1, b1, shift)\
2226
(((- FIX(0.16874) * r1 - FIX(0.33126) * g1 +         \
2227
     FIX(0.50000) * b1 + (ONE_HALF << shift) - 1) >> (SCALEBITS + shift)) + 128)
2228
2229
#define RGB_TO_V(r1, g1, b1, shift)\
2230
(((FIX(0.50000) * r1 - FIX(0.41869) * g1 -           \
2231
   FIX(0.08131) * b1 + (ONE_HALF << shift) - 1) >> (SCALEBITS + shift)) + 128)
2232
2233
static void opt_pad_color(const char *arg) {
2234
    /* Input is expected to be six hex digits similar to
2235
       how colors are expressed in html tags (but without the #) */
2236
    int rgb = strtol(arg, NULL, 16);
2237
    int r,g,b;
2238
    
2239
    r = (rgb >> 16); 
2240
    g = ((rgb >> 8) & 255);
2241
    b = (rgb & 255);
2242
2243
    padcolor[0] = RGB_TO_Y(r,g,b);
2244
    padcolor[1] = RGB_TO_U(r,g,b,0);
2245
    padcolor[2] = RGB_TO_V(r,g,b,0);
2246
}
2247
2248
static void opt_frame_pad_top(const char *arg)
2249
{
2250
    frame_padtop = atoi(arg); 
2251
    if (frame_padtop < 0) {
2252
        fprintf(stderr, "Incorrect top pad size\n");
2253
        exit(1);
2254
    }
2255
    if ((frame_padtop % 2) != 0) {
2256
        fprintf(stderr, "Top pad size must be a multiple of 2\n");
2257
        exit(1);
2258
    }
2259
}
2260
2261
static void opt_frame_pad_bottom(const char *arg)
2262
{
2263
    frame_padbottom = atoi(arg); 
2264
    if (frame_padbottom < 0) {
2265
        fprintf(stderr, "Incorrect bottom pad size\n");
2266
        exit(1);
2267
    }
2268
    if ((frame_padbottom % 2) != 0) {
2269
        fprintf(stderr, "Bottom pad size must be a multiple of 2\n");
2270
        exit(1);
2271
    }
2272
}
2273
2274
2275
static void opt_frame_pad_left(const char *arg)
2276
{
2277
    frame_padleft = atoi(arg); 
2278
    if (frame_padleft < 0) {
2279
        fprintf(stderr, "Incorrect left pad size\n");
2280
        exit(1);
2281
    }
2282
    if ((frame_padleft % 2) != 0) {
2283
        fprintf(stderr, "Left pad size must be a multiple of 2\n");
2284
        exit(1);
2285
    }
2286
}
2287
2288
2289
static void opt_frame_pad_right(const char *arg)
2290
{
2291
    frame_padright = atoi(arg); 
2292
    if (frame_padright < 0) {
2293
        fprintf(stderr, "Incorrect right pad size\n");
2294
        exit(1);
2295
    }
2296
    if ((frame_padright % 2) != 0) {
2297
        fprintf(stderr, "Right pad size must be a multiple of 2\n");
2298
        exit(1);
2299
    }
2300
}
2301
2302
2303 63167088 Roman Shaposhnik
static void opt_frame_pix_fmt(const char *arg)
2304
{
2305
    frame_pix_fmt = avcodec_get_pix_fmt(arg);
2306
}
2307
2308 5fe03e38 Roman Shaposhnik
static void opt_frame_aspect_ratio(const char *arg)
2309
{
2310
    int x = 0, y = 0;
2311
    double ar = 0;
2312
    const char *p;
2313
    
2314
    p = strchr(arg, ':');
2315
    if (p) {
2316
        x = strtol(arg, (char **)&arg, 10);
2317
        if (arg == p)
2318
            y = strtol(arg+1, (char **)&arg, 10);
2319
        if (x > 0 && y > 0)
2320
            ar = (double)x / (double)y;
2321
    } else
2322
        ar = strtod(arg, (char **)&arg);
2323
2324
    if (!ar) {
2325
        fprintf(stderr, "Incorrect aspect ratio specification.\n");
2326
        exit(1);
2327
    }
2328
    frame_aspect_ratio = ar;
2329
}
2330
2331 b29f97d1 Zdenek Kabelac
static void opt_gop_size(const char *arg)
2332 85f07f22 Fabrice Bellard
{
2333
    gop_size = atoi(arg);
2334
}
2335
2336 b29f97d1 Zdenek Kabelac
static void opt_b_frames(const char *arg)
2337 bc6caae2 Juanjo
{
2338
    b_frames = atoi(arg);
2339
    if (b_frames > FF_MAX_B_FRAMES) {
2340
        fprintf(stderr, "\nCannot have more than %d B frames, increase FF_MAX_B_FRAMES.\n", FF_MAX_B_FRAMES);
2341
        exit(1);
2342
    } else if (b_frames < 1) {
2343
        fprintf(stderr, "\nNumber of B frames must be higher than 0\n");
2344
        exit(1);
2345
    }
2346
}
2347
2348 7d1c3fc1 Michael Niedermayer
static void opt_mb_decision(const char *arg)
2349
{
2350
    mb_decision = atoi(arg);
2351
}
2352
2353 5d43635e Michael Niedermayer
static void opt_mb_cmp(const char *arg)
2354
{
2355
    mb_cmp = atoi(arg);
2356
}
2357
2358 622348f9 Michael Niedermayer
static void opt_ildct_cmp(const char *arg)
2359
{
2360
    ildct_cmp = atoi(arg);
2361
}
2362
2363 5d43635e Michael Niedermayer
static void opt_sub_cmp(const char *arg)
2364
{
2365
    sub_cmp = atoi(arg);
2366
}
2367
2368
static void opt_cmp(const char *arg)
2369
{
2370
    cmp = atoi(arg);
2371
}
2372
2373 9c3d33d6 Michael Niedermayer
static void opt_pre_cmp(const char *arg)
2374
{
2375
    pre_cmp = atoi(arg);
2376
}
2377
2378
static void opt_pre_me(const char *arg)
2379
{
2380
    pre_me = atoi(arg);
2381
}
2382
2383
static void opt_lumi_mask(const char *arg)
2384
{
2385
    lumi_mask = atof(arg);
2386
}
2387
2388
static void opt_dark_mask(const char *arg)
2389
{
2390
    dark_mask = atof(arg);
2391
}
2392
2393
static void opt_scplx_mask(const char *arg)
2394
{
2395
    scplx_mask = atof(arg);
2396
}
2397
2398
static void opt_tcplx_mask(const char *arg)
2399
{
2400
    tcplx_mask = atof(arg);
2401
}
2402
2403
static void opt_p_mask(const char *arg)
2404
{
2405
    p_mask = atof(arg);
2406
}
2407
2408 b29f97d1 Zdenek Kabelac
static void opt_qscale(const char *arg)
2409 85f07f22 Fabrice Bellard
{
2410 158c7f05 Michael Niedermayer
    video_qscale = atof(arg);
2411
    if (video_qscale < 0.01 ||
2412
        video_qscale > 255) {
2413
        fprintf(stderr, "qscale must be >= 0.01 and <= 255\n");
2414 85f07f22 Fabrice Bellard
        exit(1);
2415
    }
2416
}
2417
2418 4ea4b274 Michael Niedermayer
static void opt_lmax(const char *arg)
2419
{
2420
    video_lmax = atof(arg)*FF_QP2LAMBDA;
2421
}
2422
2423
static void opt_lmin(const char *arg)
2424
{
2425
    video_lmin = atof(arg)*FF_QP2LAMBDA;
2426
}
2427
2428 b29f97d1 Zdenek Kabelac
static void opt_qmin(const char *arg)
2429 9cdd6a24 Michael Niedermayer
{
2430
    video_qmin = atoi(arg);
2431
    if (video_qmin < 0 ||
2432
        video_qmin > 31) {
2433
        fprintf(stderr, "qmin must be >= 1 and <= 31\n");
2434
        exit(1);
2435
    }
2436
}
2437
2438 b29f97d1 Zdenek Kabelac
static void opt_qmax(const char *arg)
2439 9cdd6a24 Michael Niedermayer
{
2440
    video_qmax = atoi(arg);
2441
    if (video_qmax < 0 ||
2442
        video_qmax > 31) {
2443
        fprintf(stderr, "qmax must be >= 1 and <= 31\n");
2444
        exit(1);
2445
    }
2446
}
2447
2448 b29f97d1 Zdenek Kabelac
static void opt_mb_qmin(const char *arg)
2449 17a70fde Michael Niedermayer
{
2450
    video_mb_qmin = atoi(arg);
2451
    if (video_mb_qmin < 0 ||
2452
        video_mb_qmin > 31) {
2453
        fprintf(stderr, "qmin must be >= 1 and <= 31\n");
2454
        exit(1);
2455
    }
2456
}
2457
2458 b29f97d1 Zdenek Kabelac
static void opt_mb_qmax(const char *arg)
2459 17a70fde Michael Niedermayer
{
2460
    video_mb_qmax = atoi(arg);
2461
    if (video_mb_qmax < 0 ||
2462
        video_mb_qmax > 31) {
2463
        fprintf(stderr, "qmax must be >= 1 and <= 31\n");
2464
        exit(1);
2465
    }
2466
}
2467
2468 b29f97d1 Zdenek Kabelac
static void opt_qdiff(const char *arg)
2469 9cdd6a24 Michael Niedermayer
{
2470
    video_qdiff = atoi(arg);
2471
    if (video_qdiff < 0 ||
2472
        video_qdiff > 31) {
2473
        fprintf(stderr, "qdiff must be >= 1 and <= 31\n");
2474
        exit(1);
2475
    }
2476
}
2477
2478 b29f97d1 Zdenek Kabelac
static void opt_qblur(const char *arg)
2479 9cdd6a24 Michael Niedermayer
{
2480
    video_qblur = atof(arg);
2481
}
2482
2483 b29f97d1 Zdenek Kabelac
static void opt_qcomp(const char *arg)
2484 9cdd6a24 Michael Niedermayer
{
2485
    video_qcomp = atof(arg);
2486
}
2487 85f07f22 Fabrice Bellard
2488 b29f97d1 Zdenek Kabelac
static void opt_rc_initial_cplx(const char *arg)
2489 ac2830ec Michael Niedermayer
{
2490
    video_rc_initial_cplx = atof(arg);
2491
}
2492 b29f97d1 Zdenek Kabelac
static void opt_b_qfactor(const char *arg)
2493 29700fa6 Michael Niedermayer
{
2494
    video_b_qfactor = atof(arg);
2495
}
2496 b29f97d1 Zdenek Kabelac
static void opt_i_qfactor(const char *arg)
2497 29700fa6 Michael Niedermayer
{
2498
    video_i_qfactor = atof(arg);
2499
}
2500 b29f97d1 Zdenek Kabelac
static void opt_b_qoffset(const char *arg)
2501 29700fa6 Michael Niedermayer
{
2502
    video_b_qoffset = atof(arg);
2503
}
2504 b29f97d1 Zdenek Kabelac
static void opt_i_qoffset(const char *arg)
2505 29700fa6 Michael Niedermayer
{
2506
    video_i_qoffset = atof(arg);
2507
}
2508
2509 303e50e6 Michael Niedermayer
static void opt_ibias(const char *arg)
2510
{
2511
    video_intra_quant_bias = atoi(arg);
2512
}
2513
static void opt_pbias(const char *arg)
2514
{
2515
    video_inter_quant_bias = atoi(arg);
2516
}
2517
2518 b29f97d1 Zdenek Kabelac
static void opt_packet_size(const char *arg)
2519 1dbb6d90 Michael Niedermayer
{
2520
    packet_size= atoi(arg);
2521
}
2522
2523 7ebfc0ea Michael Niedermayer
static void opt_error_rate(const char *arg)
2524
{
2525
    error_rate= atoi(arg);
2526
}
2527
2528 b29f97d1 Zdenek Kabelac
static void opt_strict(const char *arg)
2529 f560dd82 Michael Niedermayer
{
2530
    strict= atoi(arg);
2531
}
2532
2533 bb198e19 Michael Niedermayer
static void opt_top_field_first(const char *arg)
2534
{
2535
    top_field_first= atoi(arg);
2536
}
2537
2538
static void opt_noise_reduction(const char *arg)
2539
{
2540
    noise_reduction= atoi(arg);
2541
}
2542
2543 77ea0d4b Michael Niedermayer
static void opt_qns(const char *arg)
2544
{
2545
    qns= atoi(arg);
2546
}
2547
2548 303e50e6 Michael Niedermayer
static void opt_sc_threshold(const char *arg)
2549
{
2550
    sc_threshold= atoi(arg);
2551
}
2552
2553 2f0472ff Timofei V. Bondarenko
static void opt_me_range(const char *arg)
2554
{
2555
    me_range = atoi(arg);
2556
}
2557
2558 9c3d33d6 Michael Niedermayer
static void opt_thread_count(const char *arg)
2559
{
2560
    thread_count= atoi(arg);
2561 2450cff2 François Revol
#if !defined(HAVE_THREADS)
2562 d8019eb5 Allen Day
    if (verbose >= 0)
2563
        fprintf(stderr, "Warning: not compiled with thread support, using thread emulation\n");
2564 842b556a Michael Niedermayer
#endif
2565 9c3d33d6 Michael Niedermayer
}
2566
2567 b29f97d1 Zdenek Kabelac
static void opt_audio_bitrate(const char *arg)
2568 85f07f22 Fabrice Bellard
{
2569
    audio_bit_rate = atoi(arg) * 1000;
2570
}
2571
2572 b29f97d1 Zdenek Kabelac
static void opt_audio_rate(const char *arg)
2573 85f07f22 Fabrice Bellard
{
2574
    audio_sample_rate = atoi(arg);
2575
}
2576
2577 b29f97d1 Zdenek Kabelac
static void opt_audio_channels(const char *arg)
2578 85f07f22 Fabrice Bellard
{
2579
    audio_channels = atoi(arg);
2580
}
2581
2582 b29f97d1 Zdenek Kabelac
static void opt_video_device(const char *arg)
2583 85f07f22 Fabrice Bellard
{
2584 e9a9e0c2 Fabrice Bellard
    video_device = av_strdup(arg);
2585 85f07f22 Fabrice Bellard
}
2586
2587 2639c651 Roman Shaposhnik
static void opt_grab_device(const char *arg)
2588
{
2589
    grab_device = av_strdup(arg);
2590
}
2591
2592 b29f97d1 Zdenek Kabelac
static void opt_video_channel(const char *arg)
2593 a5df11ab Fabrice Bellard
{
2594
    video_channel = strtol(arg, NULL, 0);
2595
}
2596
2597 e3ee3283 Alex Beregszaszi
static void opt_video_standard(const char *arg)
2598
{
2599
    video_standard = av_strdup(arg);
2600
}
2601
2602 b29f97d1 Zdenek Kabelac
static void opt_audio_device(const char *arg)
2603 85f07f22 Fabrice Bellard
{
2604 e9a9e0c2 Fabrice Bellard
    audio_device = av_strdup(arg);
2605 85f07f22 Fabrice Bellard
}
2606
2607 b29f97d1 Zdenek Kabelac
static void opt_audio_codec(const char *arg)
2608 85f07f22 Fabrice Bellard
{
2609
    AVCodec *p;
2610
2611 1629626f Fabrice Bellard
    if (!strcmp(arg, "copy")) {
2612
        audio_stream_copy = 1;
2613 85f07f22 Fabrice Bellard
    } else {
2614 1629626f Fabrice Bellard
        p = first_avcodec;
2615
        while (p) {
2616
            if (!strcmp(p->name, arg) && p->type == CODEC_TYPE_AUDIO)
2617
                break;
2618
            p = p->next;
2619
        }
2620
        if (p == NULL) {
2621
            fprintf(stderr, "Unknown audio codec '%s'\n", arg);
2622
            exit(1);
2623
        } else {
2624
            audio_codec_id = p->id;
2625
        }
2626 85f07f22 Fabrice Bellard
    }
2627
}
2628
2629 b2a2197e Michael Niedermayer
static void opt_audio_tag(const char *arg)
2630
{
2631
    char *tail;
2632
    audio_codec_tag= strtol(arg, &tail, 0);
2633
2634
    if(!tail || *tail)
2635
        audio_codec_tag= arg[0] + (arg[1]<<8) + (arg[2]<<16) + (arg[3]<<24);
2636
}
2637
2638
static void opt_video_tag(const char *arg)
2639
{
2640
    char *tail;
2641
    video_codec_tag= strtol(arg, &tail, 0);
2642
2643
    if(!tail || *tail)
2644
        video_codec_tag= arg[0] + (arg[1]<<8) + (arg[2]<<16) + (arg[3]<<24);
2645
}
2646
2647 b29f97d1 Zdenek Kabelac
static void add_frame_hooker(const char *arg)
2648 10d104e4 Philip Gladstone
{
2649
    int argc = 0;
2650
    char *argv[64];
2651
    int i;
2652 e9a9e0c2 Fabrice Bellard
    char *args = av_strdup(arg);
2653 10d104e4 Philip Gladstone
2654 bee0d9e5 Charles Yates
    using_vhook = 1;
2655
2656 10d104e4 Philip Gladstone
    argv[0] = strtok(args, " ");
2657
    while (argc < 62 && (argv[++argc] = strtok(NULL, " "))) {
2658
    }
2659
2660
    i = frame_hook_add(argc, argv);
2661
2662
    if (i != 0) {
2663
        fprintf(stderr, "Failed to add video hook function: %s\n", arg);
2664
        exit(1);
2665
    }
2666
}
2667
2668 85f07f22 Fabrice Bellard
const char *motion_str[] = {
2669
    "zero",
2670
    "full",
2671
    "log",
2672
    "phods",
2673 7084c149 Michael Niedermayer
    "epzs",
2674
    "x1",
2675 85f07f22 Fabrice Bellard
    NULL,
2676
};
2677
2678 b29f97d1 Zdenek Kabelac
static void opt_motion_estimation(const char *arg)
2679 85f07f22 Fabrice Bellard
{
2680
    const char **p;
2681
    p = motion_str;
2682
    for(;;) {
2683
        if (!*p) {
2684
            fprintf(stderr, "Unknown motion estimation method '%s'\n", arg);
2685
            exit(1);
2686
        }
2687
        if (!strcmp(*p, arg))
2688
            break;
2689
        p++;
2690
    }
2691 101bea5f Juanjo
    me_method = (p - motion_str) + 1;
2692 85f07f22 Fabrice Bellard
}
2693
2694 b29f97d1 Zdenek Kabelac
static void opt_video_codec(const char *arg)
2695 85f07f22 Fabrice Bellard
{
2696
    AVCodec *p;
2697
2698 1629626f Fabrice Bellard
    if (!strcmp(arg, "copy")) {
2699
        video_stream_copy = 1;
2700 85f07f22 Fabrice Bellard
    } else {
2701 1629626f Fabrice Bellard
        p = first_avcodec;
2702
        while (p) {
2703
            if (!strcmp(p->name, arg) && p->type == CODEC_TYPE_VIDEO)
2704
                break;
2705
            p = p->next;
2706
        }
2707
        if (p == NULL) {
2708
            fprintf(stderr, "Unknown video codec '%s'\n", arg);
2709
            exit(1);
2710
        } else {
2711
            video_codec_id = p->id;
2712
        }
2713 85f07f22 Fabrice Bellard
    }
2714
}
2715
2716 b29f97d1 Zdenek Kabelac
static void opt_map(const char *arg)
2717 85f07f22 Fabrice Bellard
{
2718
    AVStreamMap *m;
2719
    const char *p;
2720
2721
    p = arg;
2722
    m = &stream_maps[nb_stream_maps++];
2723
2724
    m->file_index = strtol(arg, (char **)&p, 0);
2725
    if (*p)
2726
        p++;
2727 a5dc85ef Juanjo
2728
    m->stream_index = strtol(p, (char **)&p, 0);
2729 85f07f22 Fabrice Bellard
}
2730
2731 0a38bafd Patrice Bensoussan
static void opt_map_meta_data(const char *arg)
2732
{
2733
    AVMetaDataMap *m;
2734
    const char *p;
2735
        
2736
    p = arg;
2737
    m = &meta_data_maps[nb_meta_data_maps++];
2738
2739
    m->out_file = strtol(arg, (char **)&p, 0);
2740
    if (*p)
2741
        p++;
2742
2743
    m->in_file = strtol(p, (char **)&p, 0);
2744
}
2745
2746 b29f97d1 Zdenek Kabelac
static void opt_recording_time(const char *arg)
2747 85f07f22 Fabrice Bellard
{
2748
    recording_time = parse_date(arg, 1);
2749
}
2750
2751 8831db5c Michael Niedermayer
static void opt_start_time(const char *arg)
2752
{
2753
    start_time = parse_date(arg, 1);
2754
}
2755
2756 4568325a Roman Shaposhnik
static void opt_rec_timestamp(const char *arg)
2757
{
2758
    rec_timestamp = parse_date(arg, 0) / 1000000;
2759
}
2760
2761 a6a92a9a Wolfram Gloger
static void opt_input_ts_offset(const char *arg)
2762
{
2763
    input_ts_offset = parse_date(arg, 1);
2764
}
2765
2766 b29f97d1 Zdenek Kabelac
static void opt_input_file(const char *filename)
2767 85f07f22 Fabrice Bellard
{
2768
    AVFormatContext *ic;
2769
    AVFormatParameters params, *ap = &params;
2770 14bea432 Michael Niedermayer
    int err, i, ret, rfps, rfps_base;
2771 bd1b79a1 Michael Niedermayer
    int64_t timestamp;
2772 85f07f22 Fabrice Bellard
2773 b242baa4 Fabrice Bellard
    if (!strcmp(filename, "-"))
2774
        filename = "pipe:";
2775
2776 b551204a Michael Niedermayer
    using_stdin |= !strncmp(filename, "pipe:", 5) || 
2777 d9a916e2 Charles Yates
                   !strcmp( filename, "/dev/stdin" );
2778
2779 85f07f22 Fabrice Bellard
    /* get default parameters from command line */
2780 79fdaa4c Fabrice Bellard
    memset(ap, 0, sizeof(*ap));
2781
    ap->sample_rate = audio_sample_rate;
2782
    ap->channels = audio_channels;
2783
    ap->frame_rate = frame_rate;
2784 14bea432 Michael Niedermayer
    ap->frame_rate_base = frame_rate_base;
2785 1ff93ffc Todd Kirby
    ap->width = frame_width + frame_padleft + frame_padright;
2786
    ap->height = frame_height + frame_padtop + frame_padbottom;
2787 817b23ff Fabrice Bellard
    ap->image_format = image_format;
2788 63167088 Roman Shaposhnik
    ap->pix_fmt = frame_pix_fmt;
2789 2639c651 Roman Shaposhnik
    ap->device  = grab_device;
2790
    ap->channel = video_channel;
2791
    ap->standard = video_standard;
2792 5b6d5596 Michael Niedermayer
    ap->video_codec_id = video_codec_id;
2793
    ap->audio_codec_id = audio_codec_id;
2794
    if(pgmyuv_compatibility_hack)
2795
        ap->video_codec_id= CODEC_ID_PGMYUV;
2796 79fdaa4c Fabrice Bellard
2797
    /* open the input file with generic libav function */
2798
    err = av_open_input_file(&ic, filename, file_iformat, 0, ap);
2799 85f07f22 Fabrice Bellard
    if (err < 0) {
2800 79fdaa4c Fabrice Bellard
        print_error(filename, err);
2801 85f07f22 Fabrice Bellard
        exit(1);
2802
    }
2803
    
2804 79fdaa4c Fabrice Bellard
    /* If not enough info to get the stream parameters, we decode the
2805
       first frames to get it. (used in mpeg case for example) */
2806
    ret = av_find_stream_info(ic);
2807 d8019eb5 Allen Day
    if (ret < 0 && verbose >= 0) {
2808 85f07f22 Fabrice Bellard
        fprintf(stderr, "%s: could not find codec parameters\n", filename);
2809
        exit(1);
2810
    }
2811
2812 bd1b79a1 Michael Niedermayer
    timestamp = start_time;
2813
    /* add the stream start time */
2814
    if (ic->start_time != AV_NOPTS_VALUE)
2815
        timestamp += ic->start_time;
2816
2817 254abc2e Fabrice Bellard
    /* if seeking requested, we execute it */
2818
    if (start_time != 0) {
2819 3ba1438d Michael Niedermayer
        ret = av_seek_frame(ic, -1, timestamp, AVSEEK_FLAG_BACKWARD);
2820 254abc2e Fabrice Bellard
        if (ret < 0) {
2821
            fprintf(stderr, "%s: could not seek to position %0.3f\n", 
2822
                    filename, (double)timestamp / AV_TIME_BASE);
2823
        }
2824
        /* reset seek info */
2825
        start_time = 0;
2826
    }
2827
2828 85f07f22 Fabrice Bellard
    /* update the current parameters so that they match the one of the input stream */
2829
    for(i=0;i<ic->nb_streams;i++) {
2830
        AVCodecContext *enc = &ic->streams[i]->codec;
2831 2450cff2 François Revol
#if defined(HAVE_THREADS)
2832 c62c07d3 Michael Niedermayer
        if(thread_count>1)
2833
            avcodec_thread_init(enc, thread_count);
2834
#endif
2835
        enc->thread_count= thread_count;
2836 85f07f22 Fabrice Bellard
        switch(enc->codec_type) {
2837
        case CODEC_TYPE_AUDIO:
2838 e0d2714a Juanjo
            //fprintf(stderr, "\nInput Audio channels: %d", enc->channels);
2839 85f07f22 Fabrice Bellard
            audio_channels = enc->channels;
2840
            audio_sample_rate = enc->sample_rate;
2841
            break;
2842
        case CODEC_TYPE_VIDEO:
2843
            frame_height = enc->height;
2844
            frame_width = enc->width;
2845 5ff85f1d Michael Niedermayer
            frame_aspect_ratio = av_q2d(enc->sample_aspect_ratio) * enc->width / enc->height;
2846 63167088 Roman Shaposhnik
            frame_pix_fmt = enc->pix_fmt;
2847 14bea432 Michael Niedermayer
            rfps      = ic->streams[i]->r_frame_rate;
2848
            rfps_base = ic->streams[i]->r_frame_rate_base;
2849 fe670d09 Michael Niedermayer
            enc->workaround_bugs = workaround_bugs;
2850 8409b8fe Michael Niedermayer
            enc->error_resilience = error_resilience; 
2851 4d2858de Michael Niedermayer
            enc->error_concealment = error_concealment; 
2852 0c9bbaec Wolfgang Hesseler
            enc->idct_algo = idct_algo;
2853
            enc->debug = debug;
2854
            enc->debug_mv = debug_mv;            
2855 8cbd529f Michael Niedermayer
            enc->lowres= lowres;
2856 b0368839 Michael Niedermayer