Statistics
| Branch: | Revision:

ffmpeg / ffmpeg.c @ 64c020a8

History | View | Annotate | Download (112 KB)

1
/*
2
 * FFmpeg main 
3
 * Copyright (c) 2000-2003 Fabrice Bellard
4
 *
5
 * 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
 *
10
 * This library is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13
 * Lesser General Public License for more details.
14
 *
15
 * 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
 */
19
#define HAVE_AV_CONFIG_H
20
#include "avformat.h"
21
#include "framehook.h"
22

    
23
#ifndef CONFIG_WIN32
24
#include <unistd.h>
25
#include <fcntl.h>
26
#include <sys/ioctl.h>
27
#include <sys/time.h>
28
#include <termios.h>
29
#include <sys/resource.h>
30
#include <signal.h>
31
#endif
32
#ifdef CONFIG_OS2
33
#include <sys/types.h>
34
#include <sys/select.h>
35
#include <stdlib.h>
36
#endif
37
#undef time //needed because HAVE_AV_CONFIG_H is defined on top
38
#include <time.h>
39

    
40
#include "cmdutils.h"
41

    
42
#if !defined(INFINITY) && defined(HUGE_VAL)
43
#define INFINITY HUGE_VAL
44
#endif
45

    
46
/* select an input stream for an output stream */
47
typedef struct AVStreamMap {
48
    int file_index;
49
    int stream_index;
50
} AVStreamMap;
51

    
52
extern const OptionDef options[];
53

    
54
static void show_help(void);
55
static void show_license(void);
56

    
57
#define MAX_FILES 20
58

    
59
static AVFormatContext *input_files[MAX_FILES];
60
static int nb_input_files = 0;
61

    
62
static AVFormatContext *output_files[MAX_FILES];
63
static int nb_output_files = 0;
64

    
65
static AVStreamMap stream_maps[MAX_FILES];
66
static int nb_stream_maps;
67

    
68
static AVInputFormat *file_iformat;
69
static AVOutputFormat *file_oformat;
70
static AVImageFormat *image_format;
71
static int frame_width  = 160;
72
static int frame_height = 128;
73
static float frame_aspect_ratio = 0;
74
static enum PixelFormat frame_pix_fmt = PIX_FMT_YUV420P;
75
static int frame_topBand  = 0;
76
static int frame_bottomBand = 0;
77
static int frame_leftBand  = 0;
78
static int frame_rightBand = 0;
79
static int frame_rate = 25;
80
static int frame_rate_base = 1;
81
static int video_bit_rate = 200*1000;
82
static int video_bit_rate_tolerance = 4000*1000;
83
static float video_qscale = 0;
84
static int video_qmin = 2;
85
static int video_qmax = 31;
86
static int video_mb_qmin = 2;
87
static int video_mb_qmax = 31;
88
static int video_qdiff = 3;
89
static float video_qblur = 0.5;
90
static float video_qcomp = 0.5;
91
static uint16_t *intra_matrix = NULL;
92
static uint16_t *inter_matrix = NULL;
93
#if 0 //experimental, (can be removed)
94
static float video_rc_qsquish=1.0;
95
static float video_rc_qmod_amp=0;
96
static int video_rc_qmod_freq=0;
97
#endif
98
static char *video_rc_override_string=NULL;
99
static char *video_rc_eq="tex^qComp";
100
static int video_rc_buffer_size=0;
101
static float video_rc_buffer_aggressivity=1.0;
102
static int video_rc_max_rate=0;
103
static int video_rc_min_rate=0;
104
static float video_rc_initial_cplx=0;
105
static float video_b_qfactor = 1.25;
106
static float video_b_qoffset = 1.25;
107
static float video_i_qfactor = -0.8;
108
static float video_i_qoffset = 0.0;
109
static int video_intra_quant_bias= FF_DEFAULT_QUANT_BIAS;
110
static int video_inter_quant_bias= FF_DEFAULT_QUANT_BIAS;
111
static int me_method = ME_EPZS;
112
static int video_disable = 0;
113
static int video_codec_id = CODEC_ID_NONE;
114
static int same_quality = 0;
115
static int b_frames = 0;
116
static int mb_decision = FF_MB_DECISION_SIMPLE;
117
static int ildct_cmp = FF_CMP_VSAD;
118
static int mb_cmp = FF_CMP_SAD;
119
static int sub_cmp = FF_CMP_SAD;
120
static int cmp = FF_CMP_SAD;
121
static int pre_cmp = FF_CMP_SAD;
122
static int pre_me = 0;
123
static float lumi_mask = 0;
124
static float dark_mask = 0;
125
static float scplx_mask = 0;
126
static float tcplx_mask = 0;
127
static float p_mask = 0;
128
static int use_4mv = 0;
129
static int use_obmc = 0;
130
static int use_loop = 0;
131
static int use_aic = 0;
132
static int use_aiv = 0;
133
static int use_umv = 0;
134
static int use_ss = 0;
135
static int use_alt_scan = 0;
136
static int use_trell = 0;
137
static int use_scan_offset = 0;
138
static int qns = 0;
139
static int closed_gop = 0;
140
static int do_deinterlace = 0;
141
static int do_interlace_dct = 0;
142
static int do_interlace_me = 0;
143
static int workaround_bugs = FF_BUG_AUTODETECT;
144
static int error_resilience = 2;
145
static int error_concealment = 3;
146
static int dct_algo = 0;
147
static int idct_algo = 0;
148
static int use_part = 0;
149
static int packet_size = 0;
150
static int error_rate = 0;
151
static int strict = 0;
152
static int top_field_first = -1;
153
static int noise_reduction = 0;
154
static int sc_threshold = 0;
155
static int debug = 0;
156
static int debug_mv = 0;
157
extern int loop_input; /* currently a hack */
158

    
159
static int gop_size = 12;
160
static int intra_only = 0;
161
static int audio_sample_rate = 44100;
162
static int audio_bit_rate = 64000;
163
static int audio_disable = 0;
164
static int audio_channels = 1;
165
static int audio_codec_id = CODEC_ID_NONE;
166

    
167
static int64_t recording_time = 0;
168
static int64_t start_time = 0;
169
static int file_overwrite = 0;
170
static char *str_title = NULL;
171
static char *str_author = NULL;
172
static char *str_copyright = NULL;
173
static char *str_comment = NULL;
174
static int do_benchmark = 0;
175
static int do_hex_dump = 0;
176
static int do_pkt_dump = 0;
177
static int do_psnr = 0;
178
static int do_vstats = 0;
179
static int do_pass = 0;
180
static int bitexact = 0;
181
static char *pass_logfilename = NULL;
182
static int audio_stream_copy = 0;
183
static int video_stream_copy = 0;
184

    
185
static int rate_emu = 0;
186

    
187
static char *video_grab_format = "video4linux";
188
static char *video_device = NULL;
189
static int  video_channel = 0;
190
static char *video_standard = "ntsc";
191

    
192
static char *audio_grab_format = "audio_device";
193
static char *audio_device = NULL;
194

    
195
static int using_stdin = 0;
196
static int using_vhook = 0;
197
static int verbose = 1;
198
static int thread_count= 1;
199
static int q_pressed = 0;
200

    
201
#define DEFAULT_PASS_LOGFILENAME "ffmpeg2pass"
202

    
203
typedef struct AVOutputStream {
204
    int file_index;          /* file index */
205
    int index;               /* stream index in the output file */
206
    int source_index;        /* AVInputStream index */
207
    AVStream *st;            /* stream in the output file */
208
    int encoding_needed;     /* true if encoding needed for this stream */
209
    int frame_number;
210
    /* input pts and corresponding output pts
211
       for A/V sync */
212
    double sync_ipts;
213
    double sync_ipts_offset;
214
    int64_t sync_opts;
215
    /* video only */
216
    int video_resample;      /* video_resample and video_crop are mutually exclusive */
217
    AVPicture pict_tmp;      /* temporary image for resampling */
218
    ImgReSampleContext *img_resample_ctx; /* for image resampling */
219

    
220
    int video_crop;          /* video_resample and video_crop are mutually exclusive */
221
    int topBand;             /* cropping area sizes */
222
    int leftBand;
223
    
224
    /* audio only */
225
    int audio_resample;
226
    ReSampleContext *resample; /* for audio resampling */
227
    FifoBuffer fifo;     /* for compression: one audio fifo per codec */
228
    FILE *logfile;
229
} AVOutputStream;
230

    
231
typedef struct AVInputStream {
232
    int file_index;
233
    int index;
234
    AVStream *st;
235
    int discard;             /* true if stream data should be discarded */
236
    int decoding_needed;     /* true if the packets must be decoded in 'raw_fifo' */
237
    int64_t sample_index;      /* current sample */
238

    
239
    int64_t       start;     /* time when read started */
240
    unsigned long frame;     /* current frame */
241
    int64_t       next_pts;  /* synthetic pts for cases where pkt.pts
242
                                is not defined */
243
    int64_t       pts;       /* current pts */
244
} AVInputStream;
245

    
246
typedef struct AVInputFile {
247
    int eof_reached;      /* true if eof reached */
248
    int ist_index;        /* index of first stream in ist_table */
249
    int buffer_size;      /* current total buffer size */
250
    int buffer_size_max;  /* buffer size at which we consider we can stop
251
                             buffering */
252
    int nb_streams;       /* nb streams we are aware of */
253
} AVInputFile;
254

    
255
#ifndef CONFIG_WIN32
256

    
257
/* init terminal so that we can grab keys */
258
static struct termios oldtty;
259

    
260
static void term_exit(void)
261
{
262
    tcsetattr (0, TCSANOW, &oldtty);
263
}
264

    
265
static volatile sig_atomic_t received_sigterm = 0;
266

    
267
static void
268
sigterm_handler(int sig)
269
{
270
    received_sigterm = sig;
271
    term_exit();
272
}
273

    
274
static void term_init(void)
275
{
276
    struct termios tty;
277

    
278
    tcgetattr (0, &tty);
279
    oldtty = tty;
280

    
281
    tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
282
                          |INLCR|IGNCR|ICRNL|IXON);
283
    tty.c_oflag |= OPOST;
284
    tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
285
    tty.c_cflag &= ~(CSIZE|PARENB);
286
    tty.c_cflag |= CS8;
287
    tty.c_cc[VMIN] = 1;
288
    tty.c_cc[VTIME] = 0;
289
    
290
    tcsetattr (0, TCSANOW, &tty);
291

    
292
    signal(SIGINT , sigterm_handler); /* Interrupt (ANSI).  */
293
    signal(SIGQUIT, sigterm_handler); /* Quit (POSIX).  */
294
    signal(SIGTERM, sigterm_handler); /* Termination (ANSI).  */
295
    /*
296
    register a function to be called at normal program termination
297
    */
298
    atexit(term_exit);
299
#ifdef CONFIG_BEOS_NETSERVER
300
    fcntl(0, F_SETFL, fcntl(0, F_GETFL) | O_NONBLOCK);
301
#endif
302
}
303

    
304
/* read a key without blocking */
305
static int read_key(void)
306
{
307
    int n = 1;
308
    unsigned char ch;
309
#ifndef CONFIG_BEOS_NETSERVER
310
    struct timeval tv;
311
    fd_set rfds;
312

    
313
    FD_ZERO(&rfds);
314
    FD_SET(0, &rfds);
315
    tv.tv_sec = 0;
316
    tv.tv_usec = 0;
317
    n = select(1, &rfds, NULL, NULL, &tv);
318
#endif
319
    if (n > 0) {
320
        n = read(0, &ch, 1);
321
        if (n == 1)
322
            return ch;
323

    
324
        return n;
325
    }
326
    return -1;
327
}
328

    
329
static int decode_interrupt_cb(void)
330
{
331
    return q_pressed || (q_pressed = read_key() == 'q');
332
}
333

    
334
#else
335

    
336
static volatile int received_sigterm = 0;
337

    
338
/* no interactive support */
339
static void term_exit(void)
340
{
341
}
342

    
343
static void term_init(void)
344
{
345
}
346

    
347
static int read_key(void)
348
{
349
    return 0;
350
}
351

    
352
#endif
353

    
354
static int read_ffserver_streams(AVFormatContext *s, const char *filename)
355
{
356
    int i, err;
357
    AVFormatContext *ic;
358

    
359
    err = av_open_input_file(&ic, filename, NULL, FFM_PACKET_SIZE, NULL);
360
    if (err < 0)
361
        return err;
362
    /* copy stream format */
363
    s->nb_streams = ic->nb_streams;
364
    for(i=0;i<ic->nb_streams;i++) {
365
        AVStream *st;
366

    
367
        st = av_mallocz(sizeof(AVStream));
368
        memcpy(st, ic->streams[i], sizeof(AVStream));
369
        s->streams[i] = st;
370
    }
371

    
372
    av_close_input_file(ic);
373
    return 0;
374
}
375

    
376
#define MAX_AUDIO_PACKET_SIZE (128 * 1024)
377

    
378
static void do_audio_out(AVFormatContext *s, 
379
                         AVOutputStream *ost, 
380
                         AVInputStream *ist,
381
                         unsigned char *buf, int size)
382
{
383
    uint8_t *buftmp;
384
    static uint8_t *audio_buf = NULL;
385
    static uint8_t *audio_out = NULL;
386
    const int audio_out_size= 4*MAX_AUDIO_PACKET_SIZE;
387

    
388
    int size_out, frame_bytes, ret;
389
    AVCodecContext *enc;
390

    
391
    /* SC: dynamic allocation of buffers */
392
    if (!audio_buf)
393
        audio_buf = av_malloc(2*MAX_AUDIO_PACKET_SIZE);
394
    if (!audio_out)
395
        audio_out = av_malloc(audio_out_size);
396
    if (!audio_buf || !audio_out)
397
        return;               /* Should signal an error ! */
398

    
399
    
400
    enc = &ost->st->codec;
401

    
402
    if (ost->audio_resample) {
403
        buftmp = audio_buf;
404
        size_out = audio_resample(ost->resample, 
405
                                  (short *)buftmp, (short *)buf,
406
                                  size / (ist->st->codec.channels * 2));
407
        size_out = size_out * enc->channels * 2;
408
    } else {
409
        buftmp = buf;
410
        size_out = size;
411
    }
412

    
413
    /* now encode as many frames as possible */
414
    if (enc->frame_size > 1) {
415
        /* output resampled raw samples */
416
        fifo_write(&ost->fifo, buftmp, size_out, 
417
                   &ost->fifo.wptr);
418

    
419
        frame_bytes = enc->frame_size * 2 * enc->channels;
420
        
421
        while (fifo_read(&ost->fifo, audio_buf, frame_bytes, 
422
                     &ost->fifo.rptr) == 0) {
423
            ret = avcodec_encode_audio(enc, audio_out, audio_out_size, 
424
                                       (short *)audio_buf);
425
            av_write_frame(s, ost->index, audio_out, ret);
426
        }
427
    } else {
428
        /* output a pcm frame */
429
        /* XXX: change encoding codec API to avoid this ? */
430
        switch(enc->codec->id) {
431
        case CODEC_ID_PCM_S16LE:
432
        case CODEC_ID_PCM_S16BE:
433
        case CODEC_ID_PCM_U16LE:
434
        case CODEC_ID_PCM_U16BE:
435
            break;
436
        default:
437
            size_out = size_out >> 1;
438
            break;
439
        }
440
        ret = avcodec_encode_audio(enc, audio_out, size_out, 
441
                                   (short *)buftmp);
442
        av_write_frame(s, ost->index, audio_out, ret);
443
    }
444
}
445

    
446
static void pre_process_video_frame(AVInputStream *ist, AVPicture *picture, void **bufp)
447
{
448
    AVCodecContext *dec;
449
    AVPicture *picture2;
450
    AVPicture picture_tmp;
451
    uint8_t *buf = 0;
452

    
453
    dec = &ist->st->codec;
454

    
455
    /* deinterlace : must be done before any resize */
456
    if (do_deinterlace || using_vhook) {
457
        int size;
458

    
459
        /* create temporary picture */
460
        size = avpicture_get_size(dec->pix_fmt, dec->width, dec->height);
461
        buf = av_malloc(size);
462
        if (!buf)
463
            return;
464
        
465
        picture2 = &picture_tmp;
466
        avpicture_fill(picture2, buf, dec->pix_fmt, dec->width, dec->height);
467

    
468
        if (do_deinterlace){
469
            if(avpicture_deinterlace(picture2, picture, 
470
                                     dec->pix_fmt, dec->width, dec->height) < 0) {
471
                /* if error, do not deinterlace */
472
                av_free(buf);
473
                buf = NULL;
474
                picture2 = picture;
475
            }
476
        } else {
477
            if (img_convert(picture2, dec->pix_fmt, picture, 
478
                            dec->pix_fmt, dec->width, dec->height) < 0) {
479
                /* if error, do not copy */
480
                av_free(buf);
481
                buf = NULL;
482
                picture2 = picture;
483
            }
484
        }
485
    } else {
486
        picture2 = picture;
487
    }
488

    
489
    frame_hook_process(picture2, dec->pix_fmt, dec->width, dec->height);
490

    
491
    if (picture != picture2)
492
        *picture = *picture2;
493
    *bufp = buf;
494
}
495

    
496
/* we begin to correct av delay at this threshold */
497
#define AV_DELAY_MAX 0.100
498

    
499
static void do_video_out(AVFormatContext *s, 
500
                         AVOutputStream *ost, 
501
                         AVInputStream *ist,
502
                         AVFrame *in_picture,
503
                         int *frame_size, AVOutputStream *audio_sync)
504
{
505
    int nb_frames, i, ret;
506
    AVPicture *final_picture, *formatted_picture;
507
    AVPicture picture_format_temp, picture_crop_temp;
508
    static uint8_t *video_buffer= NULL;
509
    uint8_t *buf = NULL, *buf1 = NULL;
510
    AVCodecContext *enc, *dec;
511
    enum PixelFormat target_pixfmt;
512

    
513
#define VIDEO_BUFFER_SIZE (1024*1024)
514

    
515
    enc = &ost->st->codec;
516
    dec = &ist->st->codec;
517

    
518
    /* by default, we output a single frame */
519
    nb_frames = 1;
520

    
521
    *frame_size = 0;
522

    
523
    /* NOTE: the A/V sync is always done by considering the audio is
524
       the master clock. It is suffisant for transcoding or playing,
525
       but not for the general case */
526
    if (audio_sync) {
527
        /* compute the A-V delay and duplicate/remove frames if needed */
528
        double adelta, vdelta, av_delay;
529

    
530
        adelta = audio_sync->sync_ipts - ((double)audio_sync->sync_opts * 
531
            s->pts_num / s->pts_den);
532

    
533
        vdelta = ost->sync_ipts - ((double)ost->sync_opts *
534
            s->pts_num / s->pts_den);
535

    
536
        av_delay = adelta - vdelta;
537
        //            printf("delay=%f\n", av_delay);
538
        if (av_delay < -AV_DELAY_MAX)
539
            nb_frames = 2;
540
        else if (av_delay > AV_DELAY_MAX)
541
            nb_frames = 0;
542
    } else {
543
        double vdelta;
544

    
545
        vdelta = (double)(ost->st->pts.val) * s->pts_num / s->pts_den - (ost->sync_ipts - ost->sync_ipts_offset);
546
        if (vdelta < 100 && vdelta > -100 && ost->sync_ipts_offset) {
547
            if (vdelta < -AV_DELAY_MAX)
548
                nb_frames = 2;
549
            else if (vdelta > AV_DELAY_MAX)
550
                nb_frames = 0;
551
        } else {
552
            ost->sync_ipts_offset -= vdelta;
553
            if (!ost->sync_ipts_offset)
554
                ost->sync_ipts_offset = 0.000001; /* one microsecond */
555
        }
556
    }
557
    
558
#if defined(AVSYNC_DEBUG)
559
    {
560
        static char *action[] = { "drop frame", "copy frame", "dup frame" };
561
        if (audio_sync)
562
            fprintf(stderr, "Input APTS %12.6f, output APTS %12.6f, ",
563
                    (double) audio_sync->sync_ipts, 
564
                    (double) audio_sync->st->pts.val * s->pts_num / s->pts_den);
565
        fprintf(stderr, "Input VPTS %12.6f, output VPTS %12.6f: %s\n",
566
                (double) ost->sync_ipts, 
567
                (double) ost->st->pts.val * s->pts_num / s->pts_den,
568
                action[nb_frames]);
569
    }
570
#endif
571

    
572
    if (nb_frames <= 0) 
573
        return;
574

    
575
    if (!video_buffer)
576
        video_buffer = av_malloc(VIDEO_BUFFER_SIZE);
577
    if (!video_buffer)
578
        return;
579

    
580
    /* convert pixel format if needed */
581
    target_pixfmt = ost->video_resample ? PIX_FMT_YUV420P : enc->pix_fmt;
582
    if (dec->pix_fmt != target_pixfmt) {
583
        int size;
584

    
585
        /* create temporary picture */
586
        size = avpicture_get_size(target_pixfmt, dec->width, dec->height);
587
        buf = av_malloc(size);
588
        if (!buf)
589
            return;
590
        formatted_picture = &picture_format_temp;
591
        avpicture_fill(formatted_picture, buf, target_pixfmt, dec->width, dec->height);
592
        
593
        if (img_convert(formatted_picture, target_pixfmt, 
594
                        (AVPicture *)in_picture, dec->pix_fmt, 
595
                        dec->width, dec->height) < 0) {
596
            fprintf(stderr, "pixel format conversion not handled\n");
597
            goto the_end;
598
        }
599
    } else {
600
        formatted_picture = (AVPicture *)in_picture;
601
    }
602

    
603
    /* XXX: resampling could be done before raw format convertion in
604
       some cases to go faster */
605
    /* XXX: only works for YUV420P */
606
    if (ost->video_resample) {
607
        final_picture = &ost->pict_tmp;
608
        img_resample(ost->img_resample_ctx, final_picture, formatted_picture);
609
        if (enc->pix_fmt != PIX_FMT_YUV420P) {
610
            int size;
611
            
612
            av_free(buf);
613
            /* create temporary picture */
614
            size = avpicture_get_size(enc->pix_fmt, enc->width, enc->height);
615
            buf = av_malloc(size);
616
            if (!buf)
617
                return;
618
            final_picture = &picture_format_temp;
619
            avpicture_fill(final_picture, buf, enc->pix_fmt, enc->width, enc->height);
620
        
621
            if (img_convert(final_picture, enc->pix_fmt, 
622
                            &ost->pict_tmp, PIX_FMT_YUV420P, 
623
                            enc->width, enc->height) < 0) {
624
                fprintf(stderr, "pixel format conversion not handled\n");
625
                goto the_end;
626
            }
627
        }
628
    } else if (ost->video_crop) {
629
        picture_crop_temp.data[0] = formatted_picture->data[0] +
630
                (ost->topBand * formatted_picture->linesize[0]) + ost->leftBand;
631

    
632
        picture_crop_temp.data[1] = formatted_picture->data[1] +
633
                ((ost->topBand >> 1) * formatted_picture->linesize[1]) +
634
                (ost->leftBand >> 1);
635

    
636
        picture_crop_temp.data[2] = formatted_picture->data[2] +
637
                ((ost->topBand >> 1) * formatted_picture->linesize[2]) +
638
                (ost->leftBand >> 1);
639

    
640
        picture_crop_temp.linesize[0] = formatted_picture->linesize[0];
641
        picture_crop_temp.linesize[1] = formatted_picture->linesize[1];
642
        picture_crop_temp.linesize[2] = formatted_picture->linesize[2];
643
        final_picture = &picture_crop_temp;
644
    } else {
645
        final_picture = formatted_picture;
646
    }
647
    /* duplicates frame if needed */
648
    /* XXX: pb because no interleaving */
649
    for(i=0;i<nb_frames;i++) {
650
        if (s->oformat->flags & AVFMT_RAWPICTURE) {
651
            /* raw pictures are written as AVPicture structure to
652
               avoid any copies. We support temorarily the older
653
               method. */
654
            AVFrame* old_frame = enc->coded_frame;
655
            enc->coded_frame = dec->coded_frame;
656
            av_write_frame(s, ost->index, 
657
                           (uint8_t *)final_picture, sizeof(AVPicture));
658
            enc->coded_frame = old_frame;
659
        } else {
660
            AVFrame big_picture;
661
            
662
            avcodec_get_frame_defaults(&big_picture);
663
            *(AVPicture*)&big_picture= *final_picture;
664
            /* better than nothing: use input picture interlaced
665
               settings */
666
            big_picture.interlaced_frame = in_picture->interlaced_frame;
667
            if(do_interlace_me || do_interlace_dct){
668
                if(top_field_first == -1)
669
                    big_picture.top_field_first = in_picture->top_field_first;
670
                else
671
                    big_picture.top_field_first = 1;
672
            }
673

    
674
            /* handles sameq here. This is not correct because it may
675
               not be a global option */
676
            if (same_quality) {
677
                big_picture.quality = ist->st->quality;
678
            }else
679
                big_picture.quality = ost->st->quality;
680
            ret = avcodec_encode_video(enc, 
681
                                       video_buffer, VIDEO_BUFFER_SIZE,
682
                                       &big_picture);
683
            //enc->frame_number = enc->real_pict_num;
684
            av_write_frame(s, ost->index, video_buffer, ret);
685
            *frame_size = ret;
686
            //fprintf(stderr,"\nFrame: %3d %3d size: %5d type: %d",
687
            //        enc->frame_number-1, enc->real_pict_num, ret,
688
            //        enc->pict_type);
689
            /* if two pass, output log */
690
            if (ost->logfile && enc->stats_out) {
691
                fprintf(ost->logfile, "%s", enc->stats_out);
692
            }
693
        }
694
        ost->frame_number++;
695
    }
696
 the_end:
697
    av_free(buf);
698
    av_free(buf1);
699
}
700

    
701
static double psnr(double d){
702
    if(d==0) return INFINITY;
703
    return -10.0*log(d)/log(10.0);
704
}
705

    
706
static void do_video_stats(AVFormatContext *os, AVOutputStream *ost, 
707
                           int frame_size)
708
{
709
    static FILE *fvstats=NULL;
710
    static int64_t total_size = 0;
711
    char filename[40];
712
    time_t today2;
713
    struct tm *today;
714
    AVCodecContext *enc;
715
    int frame_number;
716
    int64_t ti;
717
    double ti1, bitrate, avg_bitrate;
718
    
719
    if (!fvstats) {
720
        today2 = time(NULL);
721
        today = localtime(&today2);
722
        sprintf(filename, "vstats_%02d%02d%02d.log", today->tm_hour,
723
                                               today->tm_min,
724
                                               today->tm_sec);
725
        fvstats = fopen(filename,"w");
726
        if (!fvstats) {
727
            perror("fopen");
728
            exit(1);
729
        }
730
    }
731
    
732
    ti = MAXINT64;
733
    enc = &ost->st->codec;
734
    total_size += frame_size;
735
    if (enc->codec_type == CODEC_TYPE_VIDEO) {
736
        frame_number = ost->frame_number;
737
        fprintf(fvstats, "frame= %5d q= %2.1f ", frame_number, enc->coded_frame->quality/(float)FF_QP2LAMBDA);
738
        if (enc->flags&CODEC_FLAG_PSNR)
739
            fprintf(fvstats, "PSNR= %6.2f ", psnr(enc->coded_frame->error[0]/(enc->width*enc->height*255.0*255.0)));
740
        
741
        fprintf(fvstats,"f_size= %6d ", frame_size);
742
        /* compute pts value */
743
        ti1 = (double)ost->st->pts.val * os->pts_num / os->pts_den;
744
        if (ti1 < 0.01)
745
            ti1 = 0.01;
746
    
747
        bitrate = (double)(frame_size * 8) * enc->frame_rate / enc->frame_rate_base / 1000.0;
748
        avg_bitrate = (double)(total_size * 8) / ti1 / 1000.0;
749
        fprintf(fvstats, "s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
750
            (double)total_size / 1024, ti1, bitrate, avg_bitrate);
751
        fprintf(fvstats,"type= %c\n", av_get_pict_type_char(enc->coded_frame->pict_type));        
752
    }
753
}
754

    
755
static void print_report(AVFormatContext **output_files,
756
                         AVOutputStream **ost_table, int nb_ostreams,
757
                         int is_last_report)
758
{
759
    char buf[1024];
760
    AVOutputStream *ost;
761
    AVFormatContext *oc, *os;
762
    int64_t total_size;
763
    AVCodecContext *enc;
764
    int frame_number, vid, i;
765
    double bitrate, ti1, pts;
766
    static int64_t last_time = -1;
767
    
768
    if (!is_last_report) {
769
        int64_t cur_time;
770
        /* display the report every 0.5 seconds */
771
        cur_time = av_gettime();
772
        if (last_time == -1) {
773
            last_time = cur_time;
774
            return;
775
        } 
776
        if ((cur_time - last_time) < 500000)
777
            return;
778
        last_time = cur_time;
779
    }
780

    
781

    
782
    oc = output_files[0];
783

    
784
    total_size = url_ftell(&oc->pb);
785
    
786
    buf[0] = '\0';
787
    ti1 = 1e10;
788
    vid = 0;
789
    for(i=0;i<nb_ostreams;i++) {
790
        ost = ost_table[i];
791
        os = output_files[ost->file_index];
792
        enc = &ost->st->codec;
793
        if (vid && enc->codec_type == CODEC_TYPE_VIDEO) {
794
            sprintf(buf + strlen(buf), "q=%2.1f ",
795
                    enc->coded_frame->quality/(float)FF_QP2LAMBDA);
796
        }
797
        if (!vid && enc->codec_type == CODEC_TYPE_VIDEO) {
798
            frame_number = ost->frame_number;
799
            sprintf(buf + strlen(buf), "frame=%5d q=%2.1f ",
800
                    frame_number, enc->coded_frame ? enc->coded_frame->quality/(float)FF_QP2LAMBDA : 0);
801
            if(is_last_report)
802
                sprintf(buf + strlen(buf), "L");
803
            if (enc->flags&CODEC_FLAG_PSNR){
804
                int j;
805
                double error, error_sum=0;
806
                double scale, scale_sum=0;
807
                char type[3]= {'Y','U','V'};
808
                sprintf(buf + strlen(buf), "PSNR=");
809
                for(j=0; j<3; j++){
810
                    if(is_last_report){
811
                        error= enc->error[j];
812
                        scale= enc->width*enc->height*255.0*255.0*frame_number;
813
                    }else{
814
                        error= enc->coded_frame->error[j];
815
                        scale= enc->width*enc->height*255.0*255.0;
816
                    }
817
                    if(j) scale/=4;
818
                    error_sum += error;
819
                    scale_sum += scale;
820
                    sprintf(buf + strlen(buf), "%c:%2.2f ", type[j], psnr(error/scale));
821
                }
822
                sprintf(buf + strlen(buf), "*:%2.2f ", psnr(error_sum/scale_sum));
823
            }
824
            vid = 1;
825
        }
826
        /* compute min output value */
827
        pts = (double)ost->st->pts.val * os->pts_num / os->pts_den;
828
        if ((pts < ti1) && (pts > 0))
829
            ti1 = pts;
830
    }
831
    if (ti1 < 0.01)
832
        ti1 = 0.01;
833
    
834
    if (verbose || is_last_report) {
835
        bitrate = (double)(total_size * 8) / ti1 / 1000.0;
836
        
837
        sprintf(buf + strlen(buf), 
838
            "size=%8.0fkB time=%0.1f bitrate=%6.1fkbits/s",
839
            (double)total_size / 1024, ti1, bitrate);
840
        
841
        fprintf(stderr, "%s    \r", buf);
842
        fflush(stderr);
843
    }
844
        
845
    if (is_last_report)
846
        fprintf(stderr, "\n");
847
}
848

    
849
/* pkt = NULL means EOF (needed to flush decoder buffers) */
850
static int output_packet(AVInputStream *ist, int ist_index,
851
                         AVOutputStream **ost_table, int nb_ostreams,
852
                         AVPacket *pkt)
853
{
854
    AVFormatContext *os;
855
    AVOutputStream *ost;
856
    uint8_t *ptr;
857
    int len, ret, i;
858
    uint8_t *data_buf;
859
    int data_size, got_picture;
860
    AVFrame picture;
861
    short samples[AVCODEC_MAX_AUDIO_FRAME_SIZE / 2];
862
    void *buffer_to_free;
863
    
864
    if (pkt && pkt->pts != AV_NOPTS_VALUE) {
865
        ist->pts = pkt->pts;
866
    } else {
867
        ist->pts = ist->next_pts;
868
    }
869
    
870
    if (pkt == NULL) {
871
        /* EOF handling */
872
        ptr = NULL;
873
        len = 0;
874
        goto handle_eof;
875
    }
876

    
877
    len = pkt->size;
878
    ptr = pkt->data;
879
    while (len > 0) {
880
    handle_eof:
881
        /* decode the packet if needed */
882
        data_buf = NULL; /* fail safe */
883
        data_size = 0;
884
        if (ist->decoding_needed) {
885
            switch(ist->st->codec.codec_type) {
886
            case CODEC_TYPE_AUDIO:
887
                    /* XXX: could avoid copy if PCM 16 bits with same
888
                       endianness as CPU */
889
                ret = avcodec_decode_audio(&ist->st->codec, samples, &data_size,
890
                                           ptr, len);
891
                if (ret < 0)
892
                    goto fail_decode;
893
                ptr += ret;
894
                len -= ret;
895
                /* Some bug in mpeg audio decoder gives */
896
                /* data_size < 0, it seems they are overflows */
897
                if (data_size <= 0) {
898
                    /* no audio frame */
899
                    continue;
900
                }
901
                data_buf = (uint8_t *)samples;
902
                ist->next_pts += ((int64_t)AV_TIME_BASE * data_size) / 
903
                    (2 * ist->st->codec.channels);
904
                break;
905
            case CODEC_TYPE_VIDEO:
906
                    data_size = (ist->st->codec.width * ist->st->codec.height * 3) / 2;
907
                    /* XXX: allocate picture correctly */
908
                    avcodec_get_frame_defaults(&picture);
909

    
910
                    ret = avcodec_decode_video(&ist->st->codec, 
911
                                               &picture, &got_picture, ptr, len);
912
                    ist->st->quality= picture.quality;
913
                    if (ret < 0) 
914
                        goto fail_decode;
915
                    if (!got_picture) {
916
                        /* no picture yet */
917
                        goto discard_packet;
918
                    }
919
                    if (ist->st->codec.frame_rate_base != 0) {
920
                        ist->next_pts += ((int64_t)AV_TIME_BASE * 
921
                                          ist->st->codec.frame_rate_base) /
922
                            ist->st->codec.frame_rate;
923
                    }
924
                    len = 0;
925
                    break;
926
                default:
927
                    goto fail_decode;
928
                }
929
            } else {
930
                data_buf = ptr;
931
                data_size = len;
932
                ret = len;
933
                len = 0;
934
            }
935

    
936
            buffer_to_free = NULL;
937
            if (ist->st->codec.codec_type == CODEC_TYPE_VIDEO) {
938
                pre_process_video_frame(ist, (AVPicture *)&picture, 
939
                                        &buffer_to_free);
940
            }
941

    
942
            /* frame rate emulation */
943
            if (ist->st->codec.rate_emu) {
944
                int64_t pts = av_rescale((int64_t) ist->frame * ist->st->codec.frame_rate_base, 1000000, ist->st->codec.frame_rate);
945
                int64_t now = av_gettime() - ist->start;
946
                if (pts > now)
947
                    usleep(pts - now);
948

    
949
                ist->frame++;
950
            }
951

    
952
#if 0
953
            /* mpeg PTS deordering : if it is a P or I frame, the PTS
954
               is the one of the next displayed one */
955
            /* XXX: add mpeg4 too ? */
956
            if (ist->st->codec.codec_id == CODEC_ID_MPEG1VIDEO) {
957
                if (ist->st->codec.pict_type != B_TYPE) {
958
                    int64_t tmp;
959
                    tmp = ist->last_ip_pts;
960
                    ist->last_ip_pts  = ist->frac_pts.val;
961
                    ist->frac_pts.val = tmp;
962
                }
963
            }
964
#endif
965
            /* if output time reached then transcode raw format, 
966
               encode packets and output them */
967
            if (start_time == 0 || ist->pts >= start_time)
968
                for(i=0;i<nb_ostreams;i++) {
969
                    int frame_size;
970

    
971
                    ost = ost_table[i];
972
                    if (ost->source_index == ist_index) {
973
                        os = output_files[ost->file_index];
974

    
975
#if 0
976
                        printf("%d: got pts=%0.3f %0.3f\n", i, 
977
                               (double)pkt->pts / AV_TIME_BASE, 
978
                               ((double)ist->pts / AV_TIME_BASE) - 
979
                               ((double)ost->st->pts.val * os->pts_num / os->pts_den));
980
#endif
981
                        /* set the input output pts pairs */
982
                        ost->sync_ipts = (double)ist->pts / AV_TIME_BASE;
983
                        /* XXX: take into account the various fifos,
984
                           in particular for audio */
985
                        ost->sync_opts = ost->st->pts.val;
986
                        //printf("ipts=%lld sync_ipts=%f sync_opts=%lld pts.val=%lld pkt->pts=%lld\n", ist->pts, ost->sync_ipts, ost->sync_opts, ost->st->pts.val, pkt->pts); 
987

    
988
                        if (ost->encoding_needed) {
989
                            switch(ost->st->codec.codec_type) {
990
                            case CODEC_TYPE_AUDIO:
991
                                do_audio_out(os, ost, ist, data_buf, data_size);
992
                                break;
993
                            case CODEC_TYPE_VIDEO:
994
                                /* find an audio stream for synchro */
995
                                {
996
                                    int i;
997
                                    AVOutputStream *audio_sync, *ost1;
998
                                    audio_sync = NULL;
999
                                    for(i=0;i<nb_ostreams;i++) {
1000
                                        ost1 = ost_table[i];
1001
                                        if (ost1->file_index == ost->file_index &&
1002
                                            ost1->st->codec.codec_type == CODEC_TYPE_AUDIO) {
1003
                                            audio_sync = ost1;
1004
                                            break;
1005
                                        }
1006
                                    }
1007

    
1008
                                    do_video_out(os, ost, ist, &picture, &frame_size, audio_sync);
1009
                                    if (do_vstats && frame_size)
1010
                                        do_video_stats(os, ost, frame_size);
1011
                                }
1012
                                break;
1013
                            default:
1014
                                av_abort();
1015
                            }
1016
                        } else {
1017
                            AVFrame avframe;
1018
                                                
1019
                            /* no reencoding needed : output the packet directly */
1020
                            /* force the input stream PTS */
1021
                        
1022
                            avcodec_get_frame_defaults(&avframe);
1023
                            ost->st->codec.coded_frame= &avframe;
1024
                            avframe.key_frame = pkt->flags & PKT_FLAG_KEY; 
1025
                        
1026
                            av_write_frame(os, ost->index, data_buf, data_size);
1027
                            ost->st->codec.frame_number++;
1028
                            ost->frame_number++;
1029
                        }
1030
                    }
1031
                }
1032
            av_free(buffer_to_free);
1033
        }
1034
 discard_packet:
1035
    return 0;
1036
 fail_decode:
1037
    return -1;
1038
}
1039

    
1040

    
1041
/*
1042
 * The following code is the main loop of the file converter
1043
 */
1044
static int av_encode(AVFormatContext **output_files,
1045
                     int nb_output_files,
1046
                     AVFormatContext **input_files,
1047
                     int nb_input_files,
1048
                     AVStreamMap *stream_maps, int nb_stream_maps)
1049
{
1050
    int ret, i, j, k, n, nb_istreams = 0, nb_ostreams = 0;
1051
    AVFormatContext *is, *os;
1052
    AVCodecContext *codec, *icodec;
1053
    AVOutputStream *ost, **ost_table = NULL;
1054
    AVInputStream *ist, **ist_table = NULL;
1055
    AVInputFile *file_table;
1056
    AVFormatContext *stream_no_data;
1057
    int key;
1058

    
1059
    file_table= (AVInputFile*) av_mallocz(nb_input_files * sizeof(AVInputFile));
1060
    if (!file_table)
1061
        goto fail;
1062

    
1063
    /* input stream init */
1064
    j = 0;
1065
    for(i=0;i<nb_input_files;i++) {
1066
        is = input_files[i];
1067
        file_table[i].ist_index = j;
1068
        file_table[i].nb_streams = is->nb_streams;
1069
        j += is->nb_streams;
1070
    }
1071
    nb_istreams = j;
1072

    
1073
    ist_table = av_mallocz(nb_istreams * sizeof(AVInputStream *));
1074
    if (!ist_table)
1075
        goto fail;
1076
    
1077
    for(i=0;i<nb_istreams;i++) {
1078
        ist = av_mallocz(sizeof(AVInputStream));
1079
        if (!ist)
1080
            goto fail;
1081
        ist_table[i] = ist;
1082
    }
1083
    j = 0;
1084
    for(i=0;i<nb_input_files;i++) {
1085
        is = input_files[i];
1086
        for(k=0;k<is->nb_streams;k++) {
1087
            ist = ist_table[j++];
1088
            ist->st = is->streams[k];
1089
            ist->file_index = i;
1090
            ist->index = k;
1091
            ist->discard = 1; /* the stream is discarded by default
1092
                                 (changed later) */
1093

    
1094
            if (ist->st->codec.rate_emu) {
1095
                ist->start = av_gettime();
1096
                ist->frame = 0;
1097
            }
1098
        }
1099
    }
1100

    
1101
    /* output stream init */
1102
    nb_ostreams = 0;
1103
    for(i=0;i<nb_output_files;i++) {
1104
        os = output_files[i];
1105
        nb_ostreams += os->nb_streams;
1106
    }
1107
    if (nb_stream_maps > 0 && nb_stream_maps != nb_ostreams) {
1108
        fprintf(stderr, "Number of stream maps must match number of output streams\n");
1109
        exit(1);
1110
    }
1111

    
1112
    /* Sanity check the mapping args -- do the input files & streams exist? */
1113
    for(i=0;i<nb_stream_maps;i++) {
1114
        int fi = stream_maps[i].file_index;
1115
        int si = stream_maps[i].stream_index;
1116
        
1117
        if (fi < 0 || fi > nb_input_files - 1 ||
1118
            si < 0 || si > file_table[fi].nb_streams - 1) {
1119
            fprintf(stderr,"Could not find input stream #%d.%d\n", fi, si);
1120
            exit(1);
1121
        }
1122
    }
1123
    
1124
    ost_table = av_mallocz(sizeof(AVOutputStream *) * nb_ostreams);
1125
    if (!ost_table)
1126
        goto fail;
1127
    for(i=0;i<nb_ostreams;i++) {
1128
        ost = av_mallocz(sizeof(AVOutputStream));
1129
        if (!ost)
1130
            goto fail;
1131
        ost_table[i] = ost;
1132
    }
1133
    
1134
    n = 0;
1135
    for(k=0;k<nb_output_files;k++) {
1136
        os = output_files[k];
1137
        for(i=0;i<os->nb_streams;i++) {
1138
            int found;
1139
            ost = ost_table[n++];
1140
            ost->file_index = k;
1141
            ost->index = i;
1142
            ost->st = os->streams[i];
1143
            if (nb_stream_maps > 0) {
1144
                ost->source_index = file_table[stream_maps[n-1].file_index].ist_index + 
1145
                    stream_maps[n-1].stream_index;
1146
                    
1147
                /* Sanity check that the stream types match */
1148
                if (ist_table[ost->source_index]->st->codec.codec_type != ost->st->codec.codec_type) {
1149
                    fprintf(stderr, "Codec type mismatch for mapping #%d.%d -> #%d.%d\n",
1150
                        stream_maps[n-1].file_index, stream_maps[n-1].stream_index,
1151
                        ost->file_index, ost->index);
1152
                    exit(1);
1153
                }
1154
                
1155
            } else {
1156
                /* get corresponding input stream index : we select the first one with the right type */
1157
                found = 0;
1158
                for(j=0;j<nb_istreams;j++) {
1159
                    ist = ist_table[j];
1160
                    if (ist->discard && 
1161
                        ist->st->codec.codec_type == ost->st->codec.codec_type) {
1162
                        ost->source_index = j;
1163
                        found = 1;
1164
                    }
1165
                }
1166
                
1167
                if (!found) {
1168
                    /* try again and reuse existing stream */
1169
                    for(j=0;j<nb_istreams;j++) {
1170
                        ist = ist_table[j];
1171
                        if (ist->st->codec.codec_type == ost->st->codec.codec_type) {
1172
                            ost->source_index = j;
1173
                            found = 1;
1174
                        }
1175
                    }
1176
                    if (!found) {
1177
                        fprintf(stderr, "Could not find input stream matching output stream #%d.%d\n",
1178
                                ost->file_index, ost->index);
1179
                        exit(1);
1180
                    }
1181
                }
1182
            }
1183
            ist = ist_table[ost->source_index];
1184
            ist->discard = 0;
1185
        }
1186
    }
1187

    
1188
    /* for each output stream, we compute the right encoding parameters */
1189
    for(i=0;i<nb_ostreams;i++) {
1190
        ost = ost_table[i];
1191
        ist = ist_table[ost->source_index];
1192

    
1193
        codec = &ost->st->codec;
1194
        icodec = &ist->st->codec;
1195

    
1196
        if (ost->st->stream_copy) {
1197
            /* if stream_copy is selected, no need to decode or encode */
1198
            codec->codec_id = icodec->codec_id;
1199
            codec->codec_type = icodec->codec_type;
1200
            codec->codec_tag = icodec->codec_tag;
1201
            codec->bit_rate = icodec->bit_rate;
1202
            switch(codec->codec_type) {
1203
            case CODEC_TYPE_AUDIO:
1204
                codec->sample_rate = icodec->sample_rate;
1205
                codec->channels = icodec->channels;
1206
                codec->frame_size = icodec->frame_size;
1207
                break;
1208
            case CODEC_TYPE_VIDEO:
1209
                codec->frame_rate = icodec->frame_rate;
1210
                codec->frame_rate_base = icodec->frame_rate_base;
1211
                codec->width = icodec->width;
1212
                codec->height = icodec->height;
1213
                break;
1214
            default:
1215
                av_abort();
1216
            }
1217
        } else {
1218
            switch(codec->codec_type) {
1219
            case CODEC_TYPE_AUDIO:
1220
                if (fifo_init(&ost->fifo, 2 * MAX_AUDIO_PACKET_SIZE))
1221
                    goto fail;
1222
                
1223
                if (codec->channels == icodec->channels &&
1224
                    codec->sample_rate == icodec->sample_rate) {
1225
                    ost->audio_resample = 0;
1226
                } else {
1227
                    if (codec->channels != icodec->channels &&
1228
                        icodec->codec_id == CODEC_ID_AC3) {
1229
                        /* Special case for 5:1 AC3 input */
1230
                        /* and mono or stereo output      */
1231
                        /* Request specific number of channels */
1232
                        icodec->channels = codec->channels;
1233
                        if (codec->sample_rate == icodec->sample_rate)
1234
                            ost->audio_resample = 0;
1235
                        else {
1236
                            ost->audio_resample = 1;
1237
                            ost->resample = audio_resample_init(codec->channels, icodec->channels,
1238
                                                        codec->sample_rate, 
1239
                                                        icodec->sample_rate);
1240
                            if(!ost->resample)
1241
                              {
1242
                                printf("Can't resample.  Aborting.\n");
1243
                                av_abort();
1244
                              }
1245
                        }
1246
                        /* Request specific number of channels */
1247
                        icodec->channels = codec->channels;
1248
                    } else {
1249
                        ost->audio_resample = 1; 
1250
                        ost->resample = audio_resample_init(codec->channels, icodec->channels,
1251
                                                        codec->sample_rate, 
1252
                                                        icodec->sample_rate);
1253
                        if(!ost->resample)
1254
                          {
1255
                            printf("Can't resample.  Aborting.\n");
1256
                            av_abort();
1257
                          }
1258
                    }
1259
                }
1260
                ist->decoding_needed = 1;
1261
                ost->encoding_needed = 1;
1262
                break;
1263
            case CODEC_TYPE_VIDEO:
1264
                if (codec->width == icodec->width &&
1265
                    codec->height == icodec->height &&
1266
                    frame_topBand == 0 &&
1267
                    frame_bottomBand == 0 &&
1268
                    frame_leftBand == 0 &&
1269
                    frame_rightBand == 0)
1270
                {
1271
                    ost->video_resample = 0;
1272
                    ost->video_crop = 0;
1273
                } else if ((codec->width == icodec->width -
1274
                                (frame_leftBand + frame_rightBand)) &&
1275
                        (codec->height == icodec->height -
1276
                                (frame_topBand  + frame_bottomBand)))
1277
                {
1278
                    ost->video_resample = 0;
1279
                    ost->video_crop = 1;
1280
                    ost->topBand = frame_topBand;
1281
                    ost->leftBand = frame_leftBand;
1282
                } else {
1283
                    ost->video_resample = 1;
1284
                    ost->video_crop = 0; // cropping is handled as part of resample
1285
                    if( avpicture_alloc( &ost->pict_tmp, PIX_FMT_YUV420P,
1286
                                         codec->width, codec->height ) )
1287
                        goto fail;
1288

    
1289
                    ost->img_resample_ctx = img_resample_full_init( 
1290
                                      ost->st->codec.width, ost->st->codec.height,
1291
                                      ist->st->codec.width, ist->st->codec.height,
1292
                                      frame_topBand, frame_bottomBand,
1293
                                      frame_leftBand, frame_rightBand);
1294
                }
1295
                ost->encoding_needed = 1;
1296
                ist->decoding_needed = 1;
1297
                break;
1298
            default:
1299
                av_abort();
1300
            }
1301
            /* two pass mode */
1302
            if (ost->encoding_needed && 
1303
                (codec->flags & (CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2))) {
1304
                char logfilename[1024];
1305
                FILE *f;
1306
                int size;
1307
                char *logbuffer;
1308
                
1309
                snprintf(logfilename, sizeof(logfilename), "%s-%d.log", 
1310
                         pass_logfilename ? 
1311
                         pass_logfilename : DEFAULT_PASS_LOGFILENAME, i);
1312
                if (codec->flags & CODEC_FLAG_PASS1) {
1313
                    f = fopen(logfilename, "w");
1314
                    if (!f) {
1315
                        perror(logfilename);
1316
                        exit(1);
1317
                    }
1318
                    ost->logfile = f;
1319
                } else {
1320
                    /* read the log file */
1321
                    f = fopen(logfilename, "r");
1322
                    if (!f) {
1323
                        perror(logfilename);
1324
                        exit(1);
1325
                    }
1326
                    fseek(f, 0, SEEK_END);
1327
                    size = ftell(f);
1328
                    fseek(f, 0, SEEK_SET);
1329
                    logbuffer = av_malloc(size + 1);
1330
                    if (!logbuffer) {
1331
                        fprintf(stderr, "Could not allocate log buffer\n");
1332
                        exit(1);
1333
                    }
1334
                    size = fread(logbuffer, 1, size, f);
1335
                    fclose(f);
1336
                    logbuffer[size] = '\0';
1337
                    codec->stats_in = logbuffer;
1338
                }
1339
            }
1340
        }
1341
    }
1342

    
1343
    /* dump the file output parameters - cannot be done before in case
1344
       of stream copy */
1345
    for(i=0;i<nb_output_files;i++) {
1346
        dump_format(output_files[i], i, output_files[i]->filename, 1);
1347
    }
1348

    
1349
    /* dump the stream mapping */
1350
    fprintf(stderr, "Stream mapping:\n");
1351
    for(i=0;i<nb_ostreams;i++) {
1352
        ost = ost_table[i];
1353
        fprintf(stderr, "  Stream #%d.%d -> #%d.%d\n",
1354
                ist_table[ost->source_index]->file_index,
1355
                ist_table[ost->source_index]->index,
1356
                ost->file_index, 
1357
                ost->index);
1358
    }
1359

    
1360
    /* open each encoder */
1361
    for(i=0;i<nb_ostreams;i++) {
1362
        ost = ost_table[i];
1363
        if (ost->encoding_needed) {
1364
            AVCodec *codec;
1365
            codec = avcodec_find_encoder(ost->st->codec.codec_id);
1366
            if (!codec) {
1367
                fprintf(stderr, "Unsupported codec for output stream #%d.%d\n", 
1368
                        ost->file_index, ost->index);
1369
                exit(1);
1370
            }
1371
            if (avcodec_open(&ost->st->codec, codec) < 0) {
1372
                fprintf(stderr, "Error while opening codec for stream #%d.%d - maybe incorrect parameters such as bit_rate, rate, width or height\n", 
1373
                        ost->file_index, ost->index);
1374
                exit(1);
1375
            }
1376
        }
1377
    }
1378

    
1379
    /* open each decoder */
1380
    for(i=0;i<nb_istreams;i++) {
1381
        ist = ist_table[i];
1382
        if (ist->decoding_needed) {
1383
            AVCodec *codec;
1384
            codec = avcodec_find_decoder(ist->st->codec.codec_id);
1385
            if (!codec) {
1386
                fprintf(stderr, "Unsupported codec (id=%d) for input stream #%d.%d\n", 
1387
                        ist->st->codec.codec_id, ist->file_index, ist->index);
1388
                exit(1);
1389
            }
1390
            if (avcodec_open(&ist->st->codec, codec) < 0) {
1391
                fprintf(stderr, "Error while opening codec for input stream #%d.%d\n", 
1392
                        ist->file_index, ist->index);
1393
                exit(1);
1394
            }
1395
            //if (ist->st->codec.codec_type == CODEC_TYPE_VIDEO)
1396
            //    ist->st->codec.flags |= CODEC_FLAG_REPEAT_FIELD;
1397
        }
1398
    }
1399

    
1400
    /* init pts */
1401
    for(i=0;i<nb_istreams;i++) {
1402
        ist = ist_table[i];
1403
        is = input_files[ist->file_index];
1404
        ist->pts = 0;
1405
        ist->next_pts = 0;
1406
    }
1407
    
1408
    /* compute buffer size max (should use a complete heuristic) */
1409
    for(i=0;i<nb_input_files;i++) {
1410
        file_table[i].buffer_size_max = 2048;
1411
    }
1412

    
1413
    /* open files and write file headers */
1414
    for(i=0;i<nb_output_files;i++) {
1415
        os = output_files[i];
1416
        if (av_write_header(os) < 0) {
1417
            fprintf(stderr, "Could not write header for output file #%d (incorrect codec paramters ?)\n", i);
1418
            ret = -EINVAL;
1419
            goto fail;
1420
        }
1421
    }
1422

    
1423
#ifndef CONFIG_WIN32
1424
    if ( !using_stdin ) {
1425
        fprintf(stderr, "Press [q] to stop encoding\n");
1426
        url_set_interrupt_cb(decode_interrupt_cb);
1427
    }
1428
#endif
1429
    term_init();
1430

    
1431
    stream_no_data = 0;
1432
    key = -1;
1433

    
1434
    for(; received_sigterm == 0;) {
1435
        int file_index, ist_index;
1436
        AVPacket pkt;
1437
        double pts_min;
1438
        
1439
    redo:
1440
        /* if 'q' pressed, exits */
1441
        if (!using_stdin) {
1442
            if (q_pressed)
1443
                break;
1444
            /* read_key() returns 0 on EOF */
1445
            key = read_key();
1446
            if (key == 'q')
1447
                break;
1448
        }
1449

    
1450
        /* select the stream that we must read now by looking at the
1451
           smallest output pts */
1452
        file_index = -1;
1453
        pts_min = 1e10;
1454
        for(i=0;i<nb_ostreams;i++) {
1455
            double pts;
1456
            ost = ost_table[i];
1457
            os = output_files[ost->file_index];
1458
            ist = ist_table[ost->source_index];
1459
            pts = (double)ost->st->pts.val * os->pts_num / os->pts_den;
1460
            if (!file_table[ist->file_index].eof_reached && 
1461
                pts < pts_min) {
1462
                pts_min = pts;
1463
                file_index = ist->file_index;
1464
            }
1465
        }
1466
        /* if none, if is finished */
1467
        if (file_index < 0) {
1468
            break;
1469
        }
1470

    
1471
        /* finish if recording time exhausted */
1472
        if (recording_time > 0 && pts_min >= (recording_time / 1000000.0))
1473
            break;
1474

    
1475
        /* read a frame from it and output it in the fifo */
1476
        is = input_files[file_index];
1477
        if (av_read_frame(is, &pkt) < 0) {
1478
            file_table[file_index].eof_reached = 1;
1479
            continue;
1480
        }
1481

    
1482
        if (!pkt.size) {
1483
            stream_no_data = is;
1484
        } else {
1485
            stream_no_data = 0;
1486
        }
1487
        if (do_pkt_dump) {
1488
            av_pkt_dump(stdout, &pkt, do_hex_dump);
1489
        }
1490
        /* the following test is needed in case new streams appear
1491
           dynamically in stream : we ignore them */
1492
        if (pkt.stream_index >= file_table[file_index].nb_streams)
1493
            goto discard_packet;
1494
        ist_index = file_table[file_index].ist_index + pkt.stream_index;
1495
        ist = ist_table[ist_index];
1496
        if (ist->discard)
1497
            goto discard_packet;
1498

    
1499
        //fprintf(stderr,"read #%d.%d size=%d\n", ist->file_index, ist->index, pkt.size);
1500
        if (output_packet(ist, ist_index, ost_table, nb_ostreams, &pkt) < 0) {
1501
            fprintf(stderr, "Error while decoding stream #%d.%d\n",
1502
                    ist->file_index, ist->index);
1503
            av_free_packet(&pkt);
1504
            goto redo;
1505
        }
1506
        
1507
    discard_packet:
1508
        av_free_packet(&pkt);
1509
        
1510
        /* dump report by using the output first video and audio streams */
1511
        print_report(output_files, ost_table, nb_ostreams, 0);
1512
    }
1513

    
1514
    /* at the end of stream, we must flush the decoder buffers */
1515
    for(i=0;i<nb_istreams;i++) {
1516
        ist = ist_table[i];
1517
        if (ist->decoding_needed) {
1518
            output_packet(ist, i, ost_table, nb_ostreams, NULL);
1519
        }
1520
    }
1521

    
1522
    term_exit();
1523

    
1524
    /* dump report by using the first video and audio streams */
1525
    print_report(output_files, ost_table, nb_ostreams, 1);
1526

    
1527
    /* write the trailer if needed and close file */
1528
    for(i=0;i<nb_output_files;i++) {
1529
        os = output_files[i];
1530
        av_write_trailer(os);
1531
    }
1532

    
1533
    /* close each encoder */
1534
    for(i=0;i<nb_ostreams;i++) {
1535
        ost = ost_table[i];
1536
        if (ost->encoding_needed) {
1537
            av_freep(&ost->st->codec.stats_in);
1538
            avcodec_close(&ost->st->codec);
1539
        }
1540
    }
1541
    
1542
    /* close each decoder */
1543
    for(i=0;i<nb_istreams;i++) {
1544
        ist = ist_table[i];
1545
        if (ist->decoding_needed) {
1546
            avcodec_close(&ist->st->codec);
1547
        }
1548
    }
1549

    
1550
    /* finished ! */
1551
    
1552
    ret = 0;
1553
 fail1:
1554
    av_free(file_table);
1555

    
1556
    if (ist_table) {
1557
        for(i=0;i<nb_istreams;i++) {
1558
            ist = ist_table[i];
1559
            av_free(ist);
1560
        }
1561
        av_free(ist_table);
1562
    }
1563
    if (ost_table) {
1564
        for(i=0;i<nb_ostreams;i++) {
1565
            ost = ost_table[i];
1566
            if (ost) {
1567
                if (ost->logfile) {
1568
                    fclose(ost->logfile);
1569
                    ost->logfile = NULL;
1570
                }
1571
                fifo_free(&ost->fifo); /* works even if fifo is not
1572
                                          initialized but set to zero */
1573
                av_free(ost->pict_tmp.data[0]);
1574
                if (ost->video_resample)
1575
                    img_resample_close(ost->img_resample_ctx);
1576
                if (ost->audio_resample)
1577
                    audio_resample_close(ost->resample);
1578
                av_free(ost);
1579
            }
1580
        }
1581
        av_free(ost_table);
1582
    }
1583
    return ret;
1584
 fail:
1585
    ret = -ENOMEM;
1586
    goto fail1;
1587
}
1588

    
1589
#if 0
1590
int file_read(const char *filename)
1591
{
1592
    URLContext *h;
1593
    unsigned char buffer[1024];
1594
    int len, i;
1595

1596
    if (url_open(&h, filename, O_RDONLY) < 0) {
1597
        printf("could not open '%s'\n", filename);
1598
        return -1;
1599
    }
1600
    for(;;) {
1601
        len = url_read(h, buffer, sizeof(buffer));
1602
        if (len <= 0)
1603
            break;
1604
        for(i=0;i<len;i++) putchar(buffer[i]);
1605
    }
1606
    url_close(h);
1607
    return 0;
1608
}
1609
#endif
1610

    
1611
static void opt_image_format(const char *arg)
1612
{
1613
    AVImageFormat *f;
1614
    
1615
    for(f = first_image_format; f != NULL; f = f->next) {
1616
        if (!strcmp(arg, f->name))
1617
            break;
1618
    }
1619
    if (!f) {
1620
        fprintf(stderr, "Unknown image format: '%s'\n", arg);
1621
        exit(1);
1622
    }
1623
    image_format = f;
1624
}
1625

    
1626
static void opt_format(const char *arg)
1627
{
1628
    /* compatibility stuff for pgmyuv */
1629
    if (!strcmp(arg, "pgmyuv")) {
1630
        opt_image_format(arg);
1631
        arg = "image";
1632
    }
1633

    
1634
    file_iformat = av_find_input_format(arg);
1635
    file_oformat = guess_format(arg, NULL, NULL);
1636
    if (!file_iformat && !file_oformat) {
1637
        fprintf(stderr, "Unknown input or output format: %s\n", arg);
1638
        exit(1);
1639
    }
1640
}
1641

    
1642
static void opt_video_bitrate(const char *arg)
1643
{
1644
    video_bit_rate = atoi(arg) * 1000;
1645
}
1646

    
1647
static void opt_video_bitrate_tolerance(const char *arg)
1648
{
1649
    video_bit_rate_tolerance = atoi(arg) * 1000;
1650
}
1651

    
1652
static void opt_video_bitrate_max(const char *arg)
1653
{
1654
    video_rc_max_rate = atoi(arg) * 1000;
1655
}
1656

    
1657
static void opt_video_bitrate_min(const char *arg)
1658
{
1659
    video_rc_min_rate = atoi(arg) * 1000;
1660
}
1661

    
1662
static void opt_video_buffer_size(const char *arg)
1663
{
1664
    video_rc_buffer_size = atoi(arg) * 8*1024;
1665
}
1666

    
1667
static void opt_video_rc_eq(char *arg)
1668
{
1669
    video_rc_eq = arg;
1670
}
1671

    
1672
static void opt_video_rc_override_string(char *arg)
1673
{
1674
    video_rc_override_string = arg;
1675
}
1676

    
1677

    
1678
static void opt_workaround_bugs(const char *arg)
1679
{
1680
    workaround_bugs = atoi(arg);
1681
}
1682

    
1683
static void opt_dct_algo(const char *arg)
1684
{
1685
    dct_algo = atoi(arg);
1686
}
1687

    
1688
static void opt_idct_algo(const char *arg)
1689
{
1690
    idct_algo = atoi(arg);
1691
}
1692

    
1693

    
1694
static void opt_error_resilience(const char *arg)
1695
{
1696
    error_resilience = atoi(arg);
1697
}
1698

    
1699
static void opt_error_concealment(const char *arg)
1700
{
1701
    error_concealment = atoi(arg);
1702
}
1703

    
1704
static void opt_debug(const char *arg)
1705
{
1706
    debug = atoi(arg);
1707
}
1708

    
1709
static void opt_vismv(const char *arg)
1710
{
1711
    debug_mv = atoi(arg);
1712
}
1713
    
1714
static void opt_verbose(const char *arg)
1715
{
1716
    verbose = atoi(arg);
1717
}
1718

    
1719
static void opt_frame_rate(const char *arg)
1720
{
1721
    if (parse_frame_rate(&frame_rate, &frame_rate_base, arg) < 0) {
1722
        fprintf(stderr, "Incorrect frame rate\n");
1723
        exit(1);
1724
    }
1725
}
1726

    
1727
static void opt_frame_crop_top(const char *arg)
1728
{
1729
    frame_topBand = atoi(arg); 
1730
    if (frame_topBand < 0) {
1731
        fprintf(stderr, "Incorrect top crop size\n");
1732
        exit(1);
1733
    }
1734
    if ((frame_topBand % 2) != 0) {
1735
        fprintf(stderr, "Top crop size must be a multiple of 2\n");
1736
        exit(1);
1737
    }
1738
    if ((frame_topBand) >= frame_height){
1739
            fprintf(stderr, "Vertical crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
1740
        exit(1);
1741
    }
1742
    frame_height -= frame_topBand;
1743
}
1744

    
1745
static void opt_frame_crop_bottom(const char *arg)
1746
{
1747
    frame_bottomBand = atoi(arg);
1748
    if (frame_bottomBand < 0) {
1749
        fprintf(stderr, "Incorrect bottom crop size\n");
1750
        exit(1);
1751
    }
1752
    if ((frame_bottomBand % 2) != 0) {
1753
        fprintf(stderr, "Bottom crop size must be a multiple of 2\n");
1754
        exit(1);        
1755
    }
1756
    if ((frame_bottomBand) >= frame_height){
1757
            fprintf(stderr, "Vertical crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
1758
        exit(1);
1759
    }
1760
    frame_height -= frame_bottomBand;
1761
}
1762

    
1763
static void opt_frame_crop_left(const char *arg)
1764
{
1765
    frame_leftBand = atoi(arg);
1766
    if (frame_leftBand < 0) {
1767
        fprintf(stderr, "Incorrect left crop size\n");
1768
        exit(1);
1769
    }
1770
    if ((frame_leftBand % 2) != 0) {
1771
        fprintf(stderr, "Left crop size must be a multiple of 2\n");
1772
        exit(1);
1773
    }
1774
    if ((frame_leftBand) >= frame_width){
1775
            fprintf(stderr, "Horizontal crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
1776
        exit(1);
1777
    }
1778
    frame_width -= frame_leftBand;
1779
}
1780

    
1781
static void opt_frame_crop_right(const char *arg)
1782
{
1783
    frame_rightBand = atoi(arg);
1784
    if (frame_rightBand < 0) {
1785
        fprintf(stderr, "Incorrect right crop size\n");
1786
        exit(1);
1787
    }
1788
    if ((frame_rightBand % 2) != 0) {
1789
        fprintf(stderr, "Right crop size must be a multiple of 2\n");
1790
        exit(1);        
1791
    }
1792
    if ((frame_rightBand) >= frame_width){
1793
            fprintf(stderr, "Horizontal crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
1794
        exit(1);
1795
    }
1796
    frame_width -= frame_rightBand;
1797
}
1798

    
1799
static void opt_frame_size(const char *arg)
1800
{
1801
    if (parse_image_size(&frame_width, &frame_height, arg) < 0) {
1802
        fprintf(stderr, "Incorrect frame size\n");
1803
        exit(1);
1804
    }
1805
    if ((frame_width % 2) != 0 || (frame_height % 2) != 0) {
1806
        fprintf(stderr, "Frame size must be a multiple of 2\n");
1807
        exit(1);
1808
    }
1809
}
1810

    
1811
static void opt_frame_pix_fmt(const char *arg)
1812
{
1813
    frame_pix_fmt = avcodec_get_pix_fmt(arg);
1814
}
1815

    
1816
static void opt_frame_aspect_ratio(const char *arg)
1817
{
1818
    int x = 0, y = 0;
1819
    double ar = 0;
1820
    const char *p;
1821
    
1822
    p = strchr(arg, ':');
1823
    if (p) {
1824
        x = strtol(arg, (char **)&arg, 10);
1825
        if (arg == p)
1826
            y = strtol(arg+1, (char **)&arg, 10);
1827
        if (x > 0 && y > 0)
1828
            ar = (double)x / (double)y;
1829
    } else
1830
        ar = strtod(arg, (char **)&arg);
1831

    
1832
    if (!ar) {
1833
        fprintf(stderr, "Incorrect aspect ratio specification.\n");
1834
        exit(1);
1835
    }
1836
    frame_aspect_ratio = ar;
1837
}
1838

    
1839
static void opt_gop_size(const char *arg)
1840
{
1841
    gop_size = atoi(arg);
1842
}
1843

    
1844
static void opt_b_frames(const char *arg)
1845
{
1846
    b_frames = atoi(arg);
1847
    if (b_frames > FF_MAX_B_FRAMES) {
1848
        fprintf(stderr, "\nCannot have more than %d B frames, increase FF_MAX_B_FRAMES.\n", FF_MAX_B_FRAMES);
1849
        exit(1);
1850
    } else if (b_frames < 1) {
1851
        fprintf(stderr, "\nNumber of B frames must be higher than 0\n");
1852
        exit(1);
1853
    }
1854
}
1855

    
1856
static void opt_mb_decision(const char *arg)
1857
{
1858
    mb_decision = atoi(arg);
1859
}
1860

    
1861
static void opt_mb_cmp(const char *arg)
1862
{
1863
    mb_cmp = atoi(arg);
1864
}
1865

    
1866
static void opt_ildct_cmp(const char *arg)
1867
{
1868
    ildct_cmp = atoi(arg);
1869
}
1870

    
1871
static void opt_sub_cmp(const char *arg)
1872
{
1873
    sub_cmp = atoi(arg);
1874
}
1875

    
1876
static void opt_cmp(const char *arg)
1877
{
1878
    cmp = atoi(arg);
1879
}
1880

    
1881
static void opt_pre_cmp(const char *arg)
1882
{
1883
    pre_cmp = atoi(arg);
1884
}
1885

    
1886
static void opt_pre_me(const char *arg)
1887
{
1888
    pre_me = atoi(arg);
1889
}
1890

    
1891
static void opt_lumi_mask(const char *arg)
1892
{
1893
    lumi_mask = atof(arg);
1894
}
1895

    
1896
static void opt_dark_mask(const char *arg)
1897
{
1898
    dark_mask = atof(arg);
1899
}
1900

    
1901
static void opt_scplx_mask(const char *arg)
1902
{
1903
    scplx_mask = atof(arg);
1904
}
1905

    
1906
static void opt_tcplx_mask(const char *arg)
1907
{
1908
    tcplx_mask = atof(arg);
1909
}
1910

    
1911
static void opt_p_mask(const char *arg)
1912
{
1913
    p_mask = atof(arg);
1914
}
1915

    
1916
static void opt_qscale(const char *arg)
1917
{
1918
    video_qscale = atof(arg);
1919
    if (video_qscale < 0.01 ||
1920
        video_qscale > 255) {
1921
        fprintf(stderr, "qscale must be >= 0.01 and <= 255\n");
1922
        exit(1);
1923
    }
1924
}
1925

    
1926
static void opt_qmin(const char *arg)
1927
{
1928
    video_qmin = atoi(arg);
1929
    if (video_qmin < 0 ||
1930
        video_qmin > 31) {
1931
        fprintf(stderr, "qmin must be >= 1 and <= 31\n");
1932
        exit(1);
1933
    }
1934
}
1935

    
1936
static void opt_qmax(const char *arg)
1937
{
1938
    video_qmax = atoi(arg);
1939
    if (video_qmax < 0 ||
1940
        video_qmax > 31) {
1941
        fprintf(stderr, "qmax must be >= 1 and <= 31\n");
1942
        exit(1);
1943
    }
1944
}
1945

    
1946
static void opt_mb_qmin(const char *arg)
1947
{
1948
    video_mb_qmin = atoi(arg);
1949
    if (video_mb_qmin < 0 ||
1950
        video_mb_qmin > 31) {
1951
        fprintf(stderr, "qmin must be >= 1 and <= 31\n");
1952
        exit(1);
1953
    }
1954
}
1955

    
1956
static void opt_mb_qmax(const char *arg)
1957
{
1958
    video_mb_qmax = atoi(arg);
1959
    if (video_mb_qmax < 0 ||
1960
        video_mb_qmax > 31) {
1961
        fprintf(stderr, "qmax must be >= 1 and <= 31\n");
1962
        exit(1);
1963
    }
1964
}
1965

    
1966
static void opt_qdiff(const char *arg)
1967
{
1968
    video_qdiff = atoi(arg);
1969
    if (video_qdiff < 0 ||
1970
        video_qdiff > 31) {
1971
        fprintf(stderr, "qdiff must be >= 1 and <= 31\n");
1972
        exit(1);
1973
    }
1974
}
1975

    
1976
static void opt_qblur(const char *arg)
1977
{
1978
    video_qblur = atof(arg);
1979
}
1980

    
1981
static void opt_qcomp(const char *arg)
1982
{
1983
    video_qcomp = atof(arg);
1984
}
1985

    
1986
static void opt_rc_initial_cplx(const char *arg)
1987
{
1988
    video_rc_initial_cplx = atof(arg);
1989
}
1990
static void opt_b_qfactor(const char *arg)
1991
{
1992
    video_b_qfactor = atof(arg);
1993
}
1994
static void opt_i_qfactor(const char *arg)
1995
{
1996
    video_i_qfactor = atof(arg);
1997
}
1998
static void opt_b_qoffset(const char *arg)
1999
{
2000
    video_b_qoffset = atof(arg);
2001
}
2002
static void opt_i_qoffset(const char *arg)
2003
{
2004
    video_i_qoffset = atof(arg);
2005
}
2006

    
2007
static void opt_ibias(const char *arg)
2008
{
2009
    video_intra_quant_bias = atoi(arg);
2010
}
2011
static void opt_pbias(const char *arg)
2012
{
2013
    video_inter_quant_bias = atoi(arg);
2014
}
2015

    
2016
static void opt_packet_size(const char *arg)
2017
{
2018
    packet_size= atoi(arg);
2019
}
2020

    
2021
static void opt_error_rate(const char *arg)
2022
{
2023
    error_rate= atoi(arg);
2024
}
2025

    
2026
static void opt_strict(const char *arg)
2027
{
2028
    strict= atoi(arg);
2029
}
2030

    
2031
static void opt_top_field_first(const char *arg)
2032
{
2033
    top_field_first= atoi(arg);
2034
}
2035

    
2036
static void opt_noise_reduction(const char *arg)
2037
{
2038
    noise_reduction= atoi(arg);
2039
}
2040

    
2041
static void opt_qns(const char *arg)
2042
{
2043
    qns= atoi(arg);
2044
}
2045

    
2046
static void opt_sc_threshold(const char *arg)
2047
{
2048
    sc_threshold= atoi(arg);
2049
}
2050

    
2051
static void opt_thread_count(const char *arg)
2052
{
2053
    thread_count= atoi(arg);
2054
#if !defined(HAVE_PTHREADS) && !defined(HAVE_W32THREADS)
2055
    fprintf(stderr, "Warning: not compiled with thread support, using thread emulation\n");
2056
#endif
2057
}
2058

    
2059
static void opt_audio_bitrate(const char *arg)
2060
{
2061
    audio_bit_rate = atoi(arg) * 1000;
2062
}
2063

    
2064
static void opt_audio_rate(const char *arg)
2065
{
2066
    audio_sample_rate = atoi(arg);
2067
}
2068

    
2069
static void opt_audio_channels(const char *arg)
2070
{
2071
    audio_channels = atoi(arg);
2072
}
2073

    
2074
static void opt_video_device(const char *arg)
2075
{
2076
    video_device = av_strdup(arg);
2077
}
2078

    
2079
static void opt_video_channel(const char *arg)
2080
{
2081
    video_channel = strtol(arg, NULL, 0);
2082
}
2083

    
2084
static void opt_video_standard(const char *arg)
2085
{
2086
    video_standard = av_strdup(arg);
2087
}
2088

    
2089
static void opt_audio_device(const char *arg)
2090
{
2091
    audio_device = av_strdup(arg);
2092
}
2093

    
2094
static void opt_dv1394(const char *arg)
2095
{
2096
    video_grab_format = "dv1394";
2097
    audio_grab_format = NULL;
2098
}
2099

    
2100
static void opt_audio_codec(const char *arg)
2101
{
2102
    AVCodec *p;
2103

    
2104
    if (!strcmp(arg, "copy")) {
2105
        audio_stream_copy = 1;
2106
    } else {
2107
        p = first_avcodec;
2108
        while (p) {
2109
            if (!strcmp(p->name, arg) && p->type == CODEC_TYPE_AUDIO)
2110
                break;
2111
            p = p->next;
2112
        }
2113
        if (p == NULL) {
2114
            fprintf(stderr, "Unknown audio codec '%s'\n", arg);
2115
            exit(1);
2116
        } else {
2117
            audio_codec_id = p->id;
2118
        }
2119
    }
2120
}
2121

    
2122
static void add_frame_hooker(const char *arg)
2123
{
2124
    int argc = 0;
2125
    char *argv[64];
2126
    int i;
2127
    char *args = av_strdup(arg);
2128

    
2129
    using_vhook = 1;
2130

    
2131
    argv[0] = strtok(args, " ");
2132
    while (argc < 62 && (argv[++argc] = strtok(NULL, " "))) {
2133
    }
2134

    
2135
    i = frame_hook_add(argc, argv);
2136

    
2137
    if (i != 0) {
2138
        fprintf(stderr, "Failed to add video hook function: %s\n", arg);
2139
        exit(1);
2140
    }
2141
}
2142

    
2143
const char *motion_str[] = {
2144
    "zero",
2145
    "full",
2146
    "log",
2147
    "phods",
2148
    "epzs",
2149
    "x1",
2150
    NULL,
2151
};
2152

    
2153
static void opt_motion_estimation(const char *arg)
2154
{
2155
    const char **p;
2156
    p = motion_str;
2157
    for(;;) {
2158
        if (!*p) {
2159
            fprintf(stderr, "Unknown motion estimation method '%s'\n", arg);
2160
            exit(1);
2161
        }
2162
        if (!strcmp(*p, arg))
2163
            break;
2164
        p++;
2165
    }
2166
    me_method = (p - motion_str) + 1;
2167
}
2168

    
2169
static void opt_video_codec(const char *arg)
2170
{
2171
    AVCodec *p;
2172

    
2173
    if (!strcmp(arg, "copy")) {
2174
        video_stream_copy = 1;
2175
    } else {
2176
        p = first_avcodec;
2177
        while (p) {
2178
            if (!strcmp(p->name, arg) && p->type == CODEC_TYPE_VIDEO)
2179
                break;
2180
            p = p->next;
2181
        }
2182
        if (p == NULL) {
2183
            fprintf(stderr, "Unknown video codec '%s'\n", arg);
2184
            exit(1);
2185
        } else {
2186
            video_codec_id = p->id;
2187
        }
2188
    }
2189
}
2190

    
2191
static void opt_map(const char *arg)
2192
{
2193
    AVStreamMap *m;
2194
    const char *p;
2195

    
2196
    p = arg;
2197
    m = &stream_maps[nb_stream_maps++];
2198

    
2199
    m->file_index = strtol(arg, (char **)&p, 0);
2200
    if (*p)
2201
        p++;
2202

    
2203
    m->stream_index = strtol(p, (char **)&p, 0);
2204
}
2205

    
2206
static void opt_recording_time(const char *arg)
2207
{
2208
    recording_time = parse_date(arg, 1);
2209
}
2210

    
2211
static void opt_start_time(const char *arg)
2212
{
2213
    start_time = parse_date(arg, 1);
2214
}
2215

    
2216
static void opt_input_file(const char *filename)
2217
{
2218
    AVFormatContext *ic;
2219
    AVFormatParameters params, *ap = &params;
2220
    int err, i, ret, rfps, rfps_base;
2221

    
2222
    if (!strcmp(filename, "-"))
2223
        filename = "pipe:";
2224

    
2225
    using_stdin |= !strcmp(filename, "pipe:" ) || 
2226
                   !strcmp( filename, "/dev/stdin" );
2227

    
2228
    /* get default parameters from command line */
2229
    memset(ap, 0, sizeof(*ap));
2230
    ap->sample_rate = audio_sample_rate;
2231
    ap->channels = audio_channels;
2232
    ap->frame_rate = frame_rate;
2233
    ap->frame_rate_base = frame_rate_base;
2234
    ap->width = frame_width;
2235
    ap->height = frame_height;
2236
    ap->image_format = image_format;
2237
    ap->pix_fmt = frame_pix_fmt;
2238

    
2239
    /* open the input file with generic libav function */
2240
    err = av_open_input_file(&ic, filename, file_iformat, 0, ap);
2241
    if (err < 0) {
2242
        print_error(filename, err);
2243
        exit(1);
2244
    }
2245
    
2246
    /* If not enough info to get the stream parameters, we decode the
2247
       first frames to get it. (used in mpeg case for example) */
2248
    ret = av_find_stream_info(ic);
2249
    if (ret < 0) {
2250
        fprintf(stderr, "%s: could not find codec parameters\n", filename);
2251
        exit(1);
2252
    }
2253

    
2254
    /* if seeking requested, we execute it */
2255
    if (start_time != 0) {
2256
        int64_t timestamp;
2257

    
2258
        timestamp = start_time;
2259
        /* add the stream start time */
2260
        if (ic->start_time != AV_NOPTS_VALUE)
2261
            timestamp += ic->start_time;
2262
        ret = av_seek_frame(ic, -1, timestamp);
2263
        if (ret < 0) {
2264
            fprintf(stderr, "%s: could not seek to position %0.3f\n", 
2265
                    filename, (double)timestamp / AV_TIME_BASE);
2266
        }
2267
        /* reset seek info */
2268
        start_time = 0;
2269
    }
2270

    
2271
    /* update the current parameters so that they match the one of the input stream */
2272
    for(i=0;i<ic->nb_streams;i++) {
2273
        AVCodecContext *enc = &ic->streams[i]->codec;
2274
#if defined(HAVE_PTHREADS) || defined(HAVE_W32THREADS)
2275
        if(thread_count>1)
2276
            avcodec_thread_init(enc, thread_count);
2277
#endif
2278
        enc->thread_count= thread_count;
2279
        switch(enc->codec_type) {
2280
        case CODEC_TYPE_AUDIO:
2281
            //fprintf(stderr, "\nInput Audio channels: %d", enc->channels);
2282
            audio_channels = enc->channels;
2283
            audio_sample_rate = enc->sample_rate;
2284
            break;
2285
        case CODEC_TYPE_VIDEO:
2286
            frame_height = enc->height;
2287
            frame_width = enc->width;
2288
            frame_aspect_ratio = av_q2d(enc->sample_aspect_ratio) * enc->width / enc->height;
2289
            frame_pix_fmt = enc->pix_fmt;
2290
            rfps      = ic->streams[i]->r_frame_rate;
2291
            rfps_base = ic->streams[i]->r_frame_rate_base;
2292
            enc->workaround_bugs = workaround_bugs;
2293
            enc->error_resilience = error_resilience; 
2294
            enc->error_concealment = error_concealment; 
2295
            enc->idct_algo = idct_algo;
2296
            enc->debug = debug;
2297
            enc->debug_mv = debug_mv;            
2298
            if(bitexact)
2299
                enc->flags|= CODEC_FLAG_BITEXACT;
2300

    
2301
            assert(enc->frame_rate_base == rfps_base); // should be true for now
2302
            if (enc->frame_rate != rfps) { 
2303
                fprintf(stderr,"\nSeems that stream %d comes from film source: %2.2f->%2.2f\n",
2304
                    i, (float)enc->frame_rate / enc->frame_rate_base,
2305
                    (float)rfps / rfps_base);
2306
            }
2307
            /* update the current frame rate to match the stream frame rate */
2308
            frame_rate      = rfps;
2309
            frame_rate_base = rfps_base;
2310

    
2311
            enc->rate_emu = rate_emu;
2312
            break;
2313
        case CODEC_TYPE_DATA:
2314
            break;
2315
        default:
2316
            av_abort();
2317
        }
2318
    }
2319
    
2320
    input_files[nb_input_files] = ic;
2321
    /* dump the file content */
2322
    dump_format(ic, nb_input_files, filename, 0);
2323
    nb_input_files++;
2324
    file_iformat = NULL;
2325
    file_oformat = NULL;
2326
    image_format = NULL;
2327

    
2328
    rate_emu = 0;
2329
}
2330

    
2331
static void check_audio_video_inputs(int *has_video_ptr, int *has_audio_ptr)
2332
{
2333
    int has_video, has_audio, i, j;
2334
    AVFormatContext *ic;
2335

    
2336
    has_video = 0;
2337
    has_audio = 0;
2338
    for(j=0;j<nb_input_files;j++) {
2339
        ic = input_files[j];
2340
        for(i=0;i<ic->nb_streams;i++) {
2341
            AVCodecContext *enc = &ic->streams[i]->codec;
2342
            switch(enc->codec_type) {
2343
            case CODEC_TYPE_AUDIO:
2344
                has_audio = 1;
2345
                break;
2346
            case CODEC_TYPE_VIDEO:
2347
                has_video = 1;
2348
                break;
2349
            case CODEC_TYPE_DATA:
2350
                break;
2351
            default:
2352
                av_abort();
2353
            }
2354
        }
2355
    }
2356
    *has_video_ptr = has_video;
2357
    *has_audio_ptr = has_audio;
2358
}
2359

    
2360
static void opt_output_file(const char *filename)
2361
{
2362
    AVStream *st;
2363
    AVFormatContext *oc;
2364
    int use_video, use_audio, nb_streams, input_has_video, input_has_audio;
2365
    int codec_id;
2366
    AVFormatParameters params, *ap = &params;
2367

    
2368
    if (!strcmp(filename, "-"))
2369
        filename = "pipe:";
2370

    
2371
    oc = av_alloc_format_context();
2372

    
2373
    if (!file_oformat) {
2374
        file_oformat = guess_format(NULL, filename, NULL);
2375
        if (!file_oformat) {
2376
            fprintf(stderr, "Unable for find a suitable output format for '%s'\n",
2377
                    filename);
2378
            exit(1);
2379
        }
2380
    }
2381
    
2382
    oc->oformat = file_oformat;
2383

    
2384
    if (!strcmp(file_oformat->name, "ffm") && 
2385
        strstart(filename, "http:", NULL)) {
2386
        /* special case for files sent to ffserver: we get the stream
2387
           parameters from ffserver */
2388
        if (read_ffserver_streams(oc, filename) < 0) {
2389
            fprintf(stderr, "Could not read stream parameters from '%s'\n", filename);
2390
            exit(1);
2391
        }
2392
    } else {
2393
        use_video = file_oformat->video_codec != CODEC_ID_NONE;
2394
        use_audio = file_oformat->audio_codec != CODEC_ID_NONE;
2395

    
2396
        /* disable if no corresponding type found and at least one
2397
           input file */
2398
        if (nb_input_files > 0) {
2399
            check_audio_video_inputs(&input_has_video, &input_has_audio);
2400
            if (!input_has_video)
2401
                use_video = 0;
2402
            if (!input_has_audio)
2403
                use_audio = 0;
2404
        }
2405

    
2406
        /* manual disable */
2407
        if (audio_disable) {
2408
            use_audio = 0;
2409
        }
2410
        if (video_disable) {
2411
            use_video = 0;
2412
        }
2413
        
2414
        nb_streams = 0;
2415
        if (use_video) {
2416
            AVCodecContext *video_enc;
2417
            
2418
            st = av_mallocz(sizeof(AVStream));
2419
            if (!st) {
2420
                fprintf(stderr, "Could not alloc stream\n");
2421
                exit(1);
2422
            }
2423
            avcodec_get_context_defaults(&st->codec);
2424
#if defined(HAVE_PTHREADS) || defined(HAVE_W32THREADS)
2425
            if(thread_count>1)
2426
                avcodec_thread_init(&st->codec, thread_count);
2427
#endif
2428

    
2429
            video_enc = &st->codec;
2430
            
2431
            if(!strcmp(file_oformat->name, "mp4") || !strcmp(file_oformat->name, "mov") || !strcmp(file_oformat->name, "3gp"))
2432
                video_enc->flags |= CODEC_FLAG_GLOBAL_HEADER;
2433
            if (video_stream_copy) {
2434
                st->stream_copy = 1;
2435
                video_enc->codec_type = CODEC_TYPE_VIDEO;
2436
            } else {
2437
                char *p;
2438
                int i;
2439
            
2440
                codec_id = file_oformat->video_codec;
2441
                if (video_codec_id != CODEC_ID_NONE)
2442
                    codec_id = video_codec_id;
2443
                
2444
                video_enc->codec_id = codec_id;
2445
                
2446
                video_enc->bit_rate = video_bit_rate;
2447
                video_enc->bit_rate_tolerance = video_bit_rate_tolerance;
2448
                video_enc->frame_rate = frame_rate; 
2449
                video_enc->frame_rate_base = frame_rate_base; 
2450
                
2451
                video_enc->width = frame_width;
2452
                video_enc->height = frame_height;
2453
                video_enc->sample_aspect_ratio = av_d2q(frame_aspect_ratio*frame_height/frame_width, 255);
2454
                video_enc->pix_fmt = frame_pix_fmt;
2455

    
2456
                if (!intra_only)
2457
                    video_enc->gop_size = gop_size;
2458
                else
2459
                    video_enc->gop_size = 0;
2460
                if (video_qscale || same_quality) {
2461
                    video_enc->flags |= CODEC_FLAG_QSCALE;
2462
                    st->quality = FF_QP2LAMBDA * video_qscale;
2463
                }
2464

    
2465
                if(intra_matrix)
2466
                    video_enc->intra_matrix = intra_matrix;
2467
                if(inter_matrix)
2468
                    video_enc->inter_matrix = inter_matrix;
2469

    
2470
                if(bitexact)
2471
                    video_enc->flags |= CODEC_FLAG_BITEXACT;
2472

    
2473
                video_enc->mb_decision = mb_decision;
2474
                video_enc->mb_cmp = mb_cmp;
2475
                video_enc->ildct_cmp = ildct_cmp;
2476
                video_enc->me_sub_cmp = sub_cmp;
2477
                video_enc->me_cmp = cmp;
2478
                video_enc->me_pre_cmp = pre_cmp;
2479
                video_enc->pre_me = pre_me;
2480
                video_enc->lumi_masking = lumi_mask;
2481
                video_enc->dark_masking = dark_mask;
2482
                video_enc->spatial_cplx_masking = scplx_mask;
2483
                video_enc->temporal_cplx_masking = tcplx_mask;
2484
                video_enc->p_masking = p_mask;
2485
                video_enc->quantizer_noise_shaping= qns;
2486
                
2487
                if (use_umv) {
2488
                    video_enc->flags |= CODEC_FLAG_H263P_UMV;
2489
                }
2490
                if (use_ss) {
2491
                    video_enc->flags |= CODEC_FLAG_H263P_SLICE_STRUCT;
2492
                }
2493
                   if (use_aic) {
2494
                    video_enc->flags |= CODEC_FLAG_H263P_AIC;
2495
                }
2496
                   if (use_aiv) {
2497
                    video_enc->flags |= CODEC_FLAG_H263P_AIV;
2498
                }
2499
                if (use_4mv) {
2500
                    video_enc->flags |= CODEC_FLAG_4MV;
2501
                }
2502
                if (use_obmc) {
2503
                    video_enc->flags |= CODEC_FLAG_OBMC;
2504
                }
2505
                if (use_loop) {
2506
                    video_enc->flags |= CODEC_FLAG_LOOP_FILTER;
2507
                }
2508
            
2509
                if(use_part) {
2510
                    video_enc->flags |= CODEC_FLAG_PART;
2511
                }
2512
                   if (use_alt_scan) {
2513
                    video_enc->flags |= CODEC_FLAG_ALT_SCAN;
2514
                }
2515
                   if (use_trell) {
2516
                    video_enc->flags |= CODEC_FLAG_TRELLIS_QUANT;
2517
                }
2518
                   if (use_scan_offset) {
2519
                    video_enc->flags |= CODEC_FLAG_SVCD_SCAN_OFFSET;
2520
                }
2521
                   if (closed_gop) {
2522
                    video_enc->flags |= CODEC_FLAG_CLOSED_GOP;
2523
                }
2524
                if (b_frames) {
2525
                    video_enc->max_b_frames = b_frames;
2526
                    video_enc->b_frame_strategy = 0;
2527
                    video_enc->b_quant_factor = 2.0;
2528
                }
2529
                if (do_interlace_dct) {
2530
                    video_enc->flags |= CODEC_FLAG_INTERLACED_DCT;
2531
                }
2532
                if (do_interlace_me) {
2533
                    video_enc->flags |= CODEC_FLAG_INTERLACED_ME;
2534
                }
2535
                video_enc->qmin = video_qmin;
2536
                video_enc->qmax = video_qmax;
2537
                video_enc->mb_qmin = video_mb_qmin;
2538
                video_enc->mb_qmax = video_mb_qmax;
2539
                video_enc->max_qdiff = video_qdiff;
2540
                video_enc->qblur = video_qblur;
2541
                video_enc->qcompress = video_qcomp;
2542
                video_enc->rc_eq = video_rc_eq;
2543
                video_enc->debug = debug;
2544
                video_enc->debug_mv = debug_mv;
2545
                video_enc->thread_count = thread_count;
2546
                p= video_rc_override_string;
2547
                for(i=0; p; i++){
2548
                    int start, end, q;
2549
                    int e=sscanf(p, "%d,%d,%d", &start, &end, &q);
2550
                    if(e!=3){
2551
                        fprintf(stderr, "error parsing rc_override\n");
2552
                        exit(1);
2553
                    }
2554
                    video_enc->rc_override= 
2555
                        av_realloc(video_enc->rc_override, 
2556
                                   sizeof(RcOverride)*(i+1));
2557
                    video_enc->rc_override[i].start_frame= start;
2558
                    video_enc->rc_override[i].end_frame  = end;
2559
                    if(q>0){
2560
                        video_enc->rc_override[i].qscale= q;
2561
                        video_enc->rc_override[i].quality_factor= 1.0;
2562
                    }
2563
                    else{
2564
                        video_enc->rc_override[i].qscale= 0;
2565
                        video_enc->rc_override[i].quality_factor= -q/100.0;
2566
                    }
2567
                    p= strchr(p, '/');
2568
                    if(p) p++;
2569
                }
2570
                video_enc->rc_override_count=i;
2571

    
2572
                video_enc->rc_max_rate = video_rc_max_rate;
2573
                video_enc->rc_min_rate = video_rc_min_rate;
2574
                video_enc->rc_buffer_size = video_rc_buffer_size;
2575
                video_enc->rc_buffer_aggressivity= video_rc_buffer_aggressivity;
2576
                video_enc->rc_initial_cplx= video_rc_initial_cplx;
2577
                video_enc->i_quant_factor = video_i_qfactor;
2578
                video_enc->b_quant_factor = video_b_qfactor;
2579
                video_enc->i_quant_offset = video_i_qoffset;
2580
                video_enc->b_quant_offset = video_b_qoffset;
2581
                video_enc->intra_quant_bias = video_intra_quant_bias;
2582
                video_enc->inter_quant_bias = video_inter_quant_bias;
2583
                video_enc->dct_algo = dct_algo;
2584
                video_enc->idct_algo = idct_algo;
2585
                video_enc->strict_std_compliance = strict;
2586
                video_enc->error_rate = error_rate;
2587
                video_enc->noise_reduction= noise_reduction;
2588
                video_enc->scenechange_threshold= sc_threshold;
2589
                if(packet_size){
2590
                    video_enc->rtp_mode= 1;
2591
                    video_enc->rtp_payload_size= packet_size;
2592
                }
2593
            
2594
                if (do_psnr)
2595
                    video_enc->flags|= CODEC_FLAG_PSNR;
2596
            
2597
                video_enc->me_method = me_method;
2598

    
2599
                /* two pass mode */
2600
                if (do_pass) {
2601
                    if (do_pass == 1) {
2602
                        video_enc->flags |= CODEC_FLAG_PASS1;
2603
                    } else {
2604
                        video_enc->flags |= CODEC_FLAG_PASS2;
2605
                    }
2606
                }
2607
            }
2608
            oc->streams[nb_streams] = st;
2609
            nb_streams++;
2610
        }
2611
    
2612
        if (use_audio) {
2613
            AVCodecContext *audio_enc;
2614

    
2615
            st = av_mallocz(sizeof(AVStream));
2616
            if (!st) {
2617
                fprintf(stderr, "Could not alloc stream\n");
2618
                exit(1);
2619
            }
2620
            avcodec_get_context_defaults(&st->codec);
2621
#if defined(HAVE_PTHREADS) || defined(HAVE_W32THREADS)
2622
            if(thread_count>1)
2623
                avcodec_thread_init(&st->codec, thread_count);
2624
#endif
2625

    
2626
            audio_enc = &st->codec;
2627
            audio_enc->codec_type = CODEC_TYPE_AUDIO;
2628

    
2629
            if(!strcmp(file_oformat->name, "mp4") || !strcmp(file_oformat->name, "mov") || !strcmp(file_oformat->name, "3gp"))
2630
                audio_enc->flags |= CODEC_FLAG_GLOBAL_HEADER;
2631
            if (audio_stream_copy) {
2632
                st->stream_copy = 1;
2633
            } else {
2634
                codec_id = file_oformat->audio_codec;
2635
                if (audio_codec_id != CODEC_ID_NONE)
2636
                    codec_id = audio_codec_id;
2637
                audio_enc->codec_id = codec_id;
2638
                
2639
                audio_enc->bit_rate = audio_bit_rate;
2640
                audio_enc->sample_rate = audio_sample_rate;
2641
                audio_enc->strict_std_compliance = strict;
2642
                audio_enc->thread_count = thread_count;
2643
                /* For audio codecs other than AC3 we limit */
2644
                /* the number of coded channels to stereo   */
2645
                if (audio_channels > 2 && codec_id != CODEC_ID_AC3) {
2646
                    audio_enc->channels = 2;
2647
                } else
2648
                    audio_enc->channels = audio_channels;
2649
            }
2650
            oc->streams[nb_streams] = st;
2651
            nb_streams++;
2652
        }
2653

    
2654
        oc->nb_streams = nb_streams;
2655

    
2656
        if (!nb_streams) {
2657
            fprintf(stderr, "No audio or video streams available\n");
2658
            exit(1);
2659
        }
2660

    
2661
        if (str_title)
2662
            pstrcpy(oc->title, sizeof(oc->title), str_title);
2663
        if (str_author)
2664
            pstrcpy(oc->author, sizeof(oc->author), str_author);
2665
        if (str_copyright)
2666
            pstrcpy(oc->copyright, sizeof(oc->copyright), str_copyright);
2667
        if (str_comment)
2668
            pstrcpy(oc->comment, sizeof(oc->comment), str_comment);
2669
    }
2670

    
2671
    output_files[nb_output_files++] = oc;
2672

    
2673
    strcpy(oc->filename, filename);
2674

    
2675
    /* check filename in case of an image number is expected */
2676
    if (oc->oformat->flags & AVFMT_NEEDNUMBER) {
2677
        if (filename_number_test(oc->filename) < 0) {
2678
            print_error(oc->filename, AVERROR_NUMEXPECTED);
2679
            exit(1);
2680
        }
2681
    }
2682

    
2683
    if (!(oc->oformat->flags & AVFMT_NOFILE)) {
2684
        /* test if it already exists to avoid loosing precious files */
2685
        if (!file_overwrite && 
2686
            (strchr(filename, ':') == NULL ||
2687
             strstart(filename, "file:", NULL))) {
2688
            if (url_exist(filename)) {
2689
                int c;
2690
                
2691
                if ( !using_stdin ) {
2692
                    fprintf(stderr,"File '%s' already exists. Overwrite ? [y/N] ", filename);
2693
                    fflush(stderr);
2694
                    c = getchar();
2695
                    if (toupper(c) != 'Y') {
2696
                        fprintf(stderr, "Not overwriting - exiting\n");
2697
                        exit(1);
2698
                    }
2699
                                }
2700
                                else {
2701
                    fprintf(stderr,"File '%s' already exists. Exiting.\n", filename);
2702
                    exit(1);
2703
                                }
2704
            }
2705
        }
2706
        
2707
        /* open the file */
2708
        if (url_fopen(&oc->pb, filename, URL_WRONLY) < 0) {
2709
            fprintf(stderr, "Could not open '%s'\n", filename);
2710
            exit(1);
2711
        }
2712
    }
2713

    
2714
    memset(ap, 0, sizeof(*ap));
2715
    ap->image_format = image_format;
2716
    if (av_set_parameters(oc, ap) < 0) {
2717
        fprintf(stderr, "%s: Invalid encoding parameters\n",
2718
                oc->filename);
2719
        exit(1);
2720
    }
2721

    
2722
    /* reset some options */
2723
    file_oformat = NULL;
2724
    file_iformat = NULL;
2725
    image_format = NULL;
2726
    audio_disable = 0;
2727
    video_disable = 0;
2728
    audio_codec_id = CODEC_ID_NONE;
2729
    video_codec_id = CODEC_ID_NONE;
2730
    audio_stream_copy = 0;
2731
    video_stream_copy = 0;
2732
}
2733

    
2734
/* prepare dummy protocols for grab */
2735
static void prepare_grab(void)
2736
{
2737
    int has_video, has_audio, i, j;
2738
    AVFormatContext *oc;
2739
    AVFormatContext *ic;
2740
    AVFormatParameters vp1, *vp = &vp1;
2741
    AVFormatParameters ap1, *ap = &ap1;
2742
    
2743
    /* see if audio/video inputs are needed */
2744
    has_video = 0;
2745
    has_audio = 0;
2746
    memset(ap, 0, sizeof(*ap));
2747
    memset(vp, 0, sizeof(*vp));
2748
    for(j=0;j<nb_output_files;j++) {
2749
        oc = output_files[j];
2750
        for(i=0;i<oc->nb_streams;i++) {
2751
            AVCodecContext *enc = &oc->streams[i]->codec;
2752
            switch(enc->codec_type) {
2753
            case CODEC_TYPE_AUDIO:
2754
                if (enc->sample_rate > ap->sample_rate)
2755
                    ap->sample_rate = enc->sample_rate;
2756
                if (enc->channels > ap->channels)
2757
                    ap->channels = enc->channels;
2758
                has_audio = 1;
2759
                break;
2760
            case CODEC_TYPE_VIDEO:
2761
                if (enc->width > vp->width)
2762
                    vp->width = enc->width;
2763
                if (enc->height > vp->height)
2764
                    vp->height = enc->height;
2765
                
2766
                assert(enc->frame_rate_base == DEFAULT_FRAME_RATE_BASE);
2767
                if (enc->frame_rate > vp->frame_rate){
2768
                    vp->frame_rate      = enc->frame_rate;
2769
                    vp->frame_rate_base = enc->frame_rate_base;
2770
                }
2771
                has_video = 1;
2772
                break;
2773
            default:
2774
                av_abort();
2775
            }
2776
        }
2777
    }
2778
    
2779
    if (has_video == 0 && has_audio == 0) {
2780
        fprintf(stderr, "Output file must have at least one audio or video stream\n");
2781
        exit(1);
2782
    }
2783
    
2784
    if (has_video) {
2785
        AVInputFormat *fmt1;
2786
        fmt1 = av_find_input_format(video_grab_format);
2787
        vp->device  = video_device;
2788
        vp->channel = video_channel;
2789
        vp->standard = video_standard;
2790
        if (av_open_input_file(&ic, "", fmt1, 0, vp) < 0) {
2791
            fprintf(stderr, "Could not find video grab device\n");
2792
            exit(1);
2793
        }
2794
        /* If not enough info to get the stream parameters, we decode the
2795
           first frames to get it. */
2796
        if ((ic->ctx_flags & AVFMTCTX_NOHEADER) && av_find_stream_info(ic) < 0) {
2797
            fprintf(stderr, "Could not find video grab parameters\n");
2798
            exit(1);
2799
        }
2800
        /* by now video grab has one stream */
2801
        ic->streams[0]->r_frame_rate      = vp->frame_rate;
2802
        ic->streams[0]->r_frame_rate_base = vp->frame_rate_base;
2803
        input_files[nb_input_files] = ic;
2804
        dump_format(ic, nb_input_files, "", 0);
2805
        nb_input_files++;
2806
    }
2807
    if (has_audio && audio_grab_format) {
2808
        AVInputFormat *fmt1;
2809
        fmt1 = av_find_input_format(audio_grab_format);
2810
        ap->device = audio_device;
2811
        if (av_open_input_file(&ic, "", fmt1, 0, ap) < 0) {
2812
            fprintf(stderr, "Could not find audio grab device\n");
2813
            exit(1);
2814
        }
2815
        input_files[nb_input_files] = ic;
2816
        dump_format(ic, nb_input_files, "", 0);
2817
        nb_input_files++;
2818
    }
2819
}
2820

    
2821
/* same option as mencoder */
2822
static void opt_pass(const char *pass_str)
2823
{
2824
    int pass;
2825
    pass = atoi(pass_str);
2826
    if (pass != 1 && pass != 2) {
2827
        fprintf(stderr, "pass number can be only 1 or 2\n");
2828
        exit(1);
2829
    }
2830
    do_pass = pass;
2831
}
2832

    
2833
#if defined(CONFIG_WIN32) || defined(CONFIG_OS2)
2834
static int64_t getutime(void)
2835
{
2836
  return av_gettime();
2837
}
2838
#else
2839
static int64_t getutime(void)
2840
{
2841
    struct rusage rusage;
2842

    
2843
    getrusage(RUSAGE_SELF, &rusage);
2844
    return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
2845
}
2846
#endif
2847

    
2848
extern int ffm_nopts;
2849

    
2850
static void opt_bitexact(void)
2851
{
2852
    bitexact=1;
2853
    /* disable generate of real time pts in ffm (need to be supressed anyway) */
2854
    ffm_nopts = 1;
2855
}
2856

    
2857
static void show_formats(void)
2858
{
2859
    AVInputFormat *ifmt;
2860
    AVOutputFormat *ofmt;
2861
    AVImageFormat *image_fmt;
2862
    URLProtocol *up;
2863
    AVCodec *p, *p2;
2864
    const char **pp, *last_name;
2865

    
2866
    printf("File formats:\n");
2867
    last_name= "000";
2868
    for(;;){
2869
        int decode=0;
2870
        int encode=0;
2871
        const char *name=NULL;
2872

    
2873
        for(ofmt = first_oformat; ofmt != NULL; ofmt = ofmt->next) {
2874
            if((name == NULL || strcmp(ofmt->name, name)<0) &&
2875
                strcmp(ofmt->name, last_name)>0){
2876
                name= ofmt->name;
2877
                encode=1;
2878
            }
2879
        }
2880
        for(ifmt = first_iformat; ifmt != NULL; ifmt = ifmt->next) {
2881
            if((name == NULL || strcmp(ifmt->name, name)<0) &&
2882
                strcmp(ifmt->name, last_name)>0){
2883
                name= ifmt->name;
2884
                encode=0;
2885
            }
2886
            if(name && strcmp(ifmt->name, name)==0)
2887
                decode=1;
2888
        }
2889
        if(name==NULL)
2890
            break;
2891
        last_name= name;
2892
        
2893
        printf(
2894
            " %s%s %s\n", 
2895
            decode ? "D":" ", 
2896
            encode ? "E":" ", 
2897
            name);
2898
    }
2899
    printf("\n");
2900

    
2901
    printf("Image formats:\n");
2902
    for(image_fmt = first_image_format; image_fmt != NULL; 
2903
        image_fmt = image_fmt->next) {
2904
        printf(
2905
            " %s%s %s\n",
2906
            image_fmt->img_read  ? "D":" ",
2907
            image_fmt->img_write ? "E":" ",
2908
            image_fmt->name);
2909
    }
2910
    printf("\n");
2911

    
2912
    printf("Codecs:\n");
2913
    last_name= "000";
2914
    for(;;){
2915
        int decode=0;
2916
        int encode=0;
2917
        int cap=0;
2918

    
2919
        p2=NULL;
2920
        for(p = first_avcodec; p != NULL; p = p->next) {
2921
            if((p2==NULL || strcmp(p->name, p2->name)<0) &&
2922
                strcmp(p->name, last_name)>0){
2923
                p2= p;
2924
                decode= encode= cap=0;
2925
            }
2926
            if(p2 && strcmp(p->name, p2->name)==0){
2927
                if(p->decode) decode=1;
2928
                if(p->encode) encode=1;
2929
                cap |= p->capabilities;
2930
            }
2931
        }
2932
        if(p2==NULL)
2933
            break;
2934
        last_name= p2->name;
2935
        
2936
        printf(
2937
            " %s%s%s%s%s%s %s", 
2938
            decode ? "D": (/*p2->decoder ? "d":*/" "), 
2939
            encode ? "E":" ", 
2940
            p2->type == CODEC_TYPE_AUDIO ? "A":"V",
2941
            cap & CODEC_CAP_DRAW_HORIZ_BAND ? "S":" ",
2942
            cap & CODEC_CAP_DR1 ? "D":" ",
2943
            cap & CODEC_CAP_TRUNCATED ? "T":" ",
2944
            p2->name);
2945
       /* if(p2->decoder && decode==0)
2946
            printf(" use %s for decoding", p2->decoder->name);*/
2947
        printf("\n");
2948
    }
2949
    printf("\n");
2950

    
2951
    printf("Supported file protocols:\n");
2952
    for(up = first_protocol; up != NULL; up = up->next)
2953
        printf(" %s:", up->name);
2954
    printf("\n");
2955
    
2956
    printf("Frame size, frame rate abbreviations:\n ntsc pal qntsc qpal sntsc spal film ntsc-film sqcif qcif cif 4cif\n");
2957
    printf("Motion estimation methods:\n");
2958
    pp = motion_str;
2959
    while (*pp) {
2960
        printf(" %s", *pp);
2961
        if ((pp - motion_str + 1) == ME_ZERO) 
2962
            printf("(fastest)");
2963
        else if ((pp - motion_str + 1) == ME_FULL) 
2964
            printf("(slowest)");
2965
        else if ((pp - motion_str + 1) == ME_EPZS) 
2966
            printf("(default)");
2967
        pp++;
2968
    }
2969
    printf("\n\n");
2970
    printf(
2971
"Note, the names of encoders and decoders dont always match, so there are\n"
2972
"several cases where the above table shows encoder only or decoder only entries\n"
2973
"even though both encoding and decoding are supported for example, the h263\n"
2974
"decoder corresponds to the h263 and h263p encoders, for file formats its even\n"
2975
"worse\n");
2976
    exit(1);
2977
}
2978

    
2979
void parse_matrix_coeffs(uint16_t *dest, const char *str)
2980
{
2981
    int i;
2982
    const char *p = str;
2983
    for(i = 0;; i++) {
2984
        dest[i] = atoi(p);
2985
        if(i == 63)
2986
            break;
2987
        p = strchr(p, ',');
2988
        if(!p) {
2989
            fprintf(stderr, "Syntax error in matrix \"%s\" at coeff %d\n", str, i);
2990
            exit(1);
2991
        }
2992
        p++;
2993
    }
2994
}
2995

    
2996
void opt_inter_matrix(const char *arg)
2997
{
2998
    inter_matrix = av_mallocz(sizeof(uint16_t) * 64);
2999
    parse_matrix_coeffs(inter_matrix, arg);
3000
}
3001

    
3002
void opt_intra_matrix(const char *arg)
3003
{
3004
    intra_matrix = av_mallocz(sizeof(uint16_t) * 64);
3005
    parse_matrix_coeffs(intra_matrix, arg);
3006
}
3007

    
3008
static void opt_target(const char *arg)
3009
{
3010
    int norm = -1;
3011

    
3012
    if(!strncmp(arg, "pal-", 4)) {
3013
        norm = 0;
3014
        arg += 4;
3015
    } else if(!strncmp(arg, "ntsc-", 5)) {
3016
        norm = 1;
3017
        arg += 5;
3018
    } else {
3019
        int fr;
3020
        /* Calculate FR via float to avoid int overflow */
3021
        fr = (int)(frame_rate * 1000.0 / frame_rate_base);
3022
        if(fr == 25000) {
3023
            norm = 0;
3024
        } else if((fr == 29970) || (fr == 23976)) {
3025
            norm = 1;
3026
        } else {
3027
            /* Try to determine PAL/NTSC by peeking in the input files */
3028
            if(nb_input_files) {
3029
                int i, j;
3030
                for(j = 0; j < nb_input_files; j++) {
3031
                    for(i = 0; i < input_files[j]->nb_streams; i++) {
3032
                        AVCodecContext *c = &input_files[j]->streams[i]->codec;
3033
                        if(c->codec_type != CODEC_TYPE_VIDEO)
3034
                            continue;
3035
                        fr = c->frame_rate * 1000 / c->frame_rate_base;
3036
                        if(fr == 25000) {
3037
                            norm = 0;
3038
                            break;
3039
                        } else if((fr == 29970) || (fr == 23976)) {
3040
                            norm = 1;
3041
                            break;
3042
                        }
3043
                    }
3044
                    if(norm >= 0)
3045
                        break;
3046
                }
3047
            }
3048
        }
3049
        if(verbose && norm >= 0)
3050
            printf("Assuming %s for target.\n", norm ? "NTSC" : "PAL");
3051
    }
3052

    
3053
    if(norm < 0) {
3054
        fprintf(stderr, "Could not determine norm (PAL/NTSC) for target.\n");
3055
        fprintf(stderr, "Please prefix target with \"pal-\" or \"ntsc-\",\n");
3056
        fprintf(stderr, "or set a framerate with \"-r xxx\".\n");
3057
        exit(1);
3058
    }
3059

    
3060
    if(!strcmp(arg, "vcd")) {
3061

    
3062
        opt_video_codec("mpeg1video");
3063
        opt_audio_codec("mp2");
3064
        opt_format("vcd");
3065

    
3066
        opt_frame_size(norm ? "352x240" : "352x288");
3067

    
3068
        video_bit_rate = 1150000;
3069
        video_rc_max_rate = 1150000;
3070
        video_rc_min_rate = 1150000;
3071
        video_rc_buffer_size = 40*1024*8;
3072

    
3073
        audio_bit_rate = 224000;
3074
        audio_sample_rate = 44100;
3075

    
3076
    } else if(!strcmp(arg, "svcd")) {
3077

    
3078
        opt_video_codec("mpeg2video");
3079
        opt_audio_codec("mp2");
3080
        opt_format("svcd");
3081

    
3082
        opt_frame_size(norm ? "480x480" : "480x576");
3083
        opt_gop_size(norm ? "18" : "15");
3084

    
3085
        video_bit_rate = 2040000;
3086
        video_rc_max_rate = 2516000;
3087
        video_rc_min_rate = 0; //1145000;
3088
        video_rc_buffer_size = 224*1024*8;
3089
        use_scan_offset = 1;
3090

    
3091
        audio_bit_rate = 224000;
3092
        audio_sample_rate = 44100;
3093

    
3094
    } else if(!strcmp(arg, "dvd")) {
3095

    
3096
        opt_video_codec("mpeg2video");
3097
        opt_audio_codec("ac3");
3098
        opt_format("vob");
3099

    
3100
        opt_frame_size(norm ? "720x480" : "720x576");
3101
        opt_gop_size(norm ? "18" : "15");
3102

    
3103
        video_bit_rate = 6000000;
3104
        video_rc_max_rate = 9000000;
3105
        video_rc_min_rate = 0; //1500000;
3106
        video_rc_buffer_size = 224*1024*8;
3107

    
3108
        audio_bit_rate = 448000;
3109
        audio_sample_rate = 48000;
3110

    
3111
    } else {
3112
        fprintf(stderr, "Unknown target: %s\n", arg);
3113
        exit(1);
3114
    }
3115
}
3116

    
3117
const OptionDef options[] = {
3118
    /* main options */
3119
    { "L", 0, {(void*)show_license}, "show license" },
3120
    { "h", 0, {(void*)show_help}, "show help" },
3121
    { "formats", 0, {(void*)show_formats}, "show available formats, codecs, protocols, ..." },
3122
    { "f", HAS_ARG, {(void*)opt_format}, "force format", "fmt" },
3123
    { "img", HAS_ARG, {(void*)opt_image_format}, "force image format", "img_fmt" },
3124
    { "i", HAS_ARG, {(void*)opt_input_file}, "input file name", "filename" },
3125
    { "y", OPT_BOOL, {(void*)&file_overwrite}, "overwrite output files" },
3126
    { "map", HAS_ARG | OPT_EXPERT, {(void*)opt_map}, "set input stream mapping", "file:stream" },
3127
    { "t", HAS_ARG, {(void*)opt_recording_time}, "set the recording time", "duration" },
3128
    { "ss", HAS_ARG, {(void*)opt_start_time}, "set the start time offset", "time_off" },
3129
    { "title", HAS_ARG | OPT_STRING, {(void*)&str_title}, "set the title", "string" },
3130
    { "author", HAS_ARG | OPT_STRING, {(void*)&str_author}, "set the author", "string" },
3131
    { "copyright", HAS_ARG | OPT_STRING, {(void*)&str_copyright}, "set the copyright", "string" },
3132
    { "comment", HAS_ARG | OPT_STRING, {(void*)&str_comment}, "set the comment", "string" },
3133
    { "debug", HAS_ARG | OPT_EXPERT, {(void*)opt_debug}, "print specific debug info", "" },
3134
    { "vismv", HAS_ARG | OPT_EXPERT, {(void*)opt_vismv}, "visualize motion vectors", "" },
3135
    { "benchmark", OPT_BOOL | OPT_EXPERT, {(void*)&do_benchmark}, 
3136
      "add timings for benchmarking" },
3137
    { "dump", OPT_BOOL | OPT_EXPERT, {(void*)&do_pkt_dump}, 
3138
      "dump each input packet" },
3139
    { "hex", OPT_BOOL | OPT_EXPERT, {(void*)&do_hex_dump}, 
3140
      "when dumping packets, also dump the payload" },
3141
    { "bitexact", OPT_EXPERT, {(void*)opt_bitexact}, "only use bit exact algorithms (for codec testing)" }, 
3142
    { "re", OPT_BOOL | OPT_EXPERT, {(void*)&rate_emu}, "read input at native frame rate", "" },
3143
    { "loop", OPT_BOOL | OPT_EXPERT, {(void*)&loop_input}, "loop (current only works with images)" },
3144
    { "v", HAS_ARG, {(void*)opt_verbose}, "control amount of logging", "verbose" },
3145
    { "target", HAS_ARG, {(void*)opt_target}, "specify target file type (\"vcd\", \"svcd\" or \"dvd\")", "type" },
3146
    { "threads", HAS_ARG | OPT_EXPERT, {(void*)opt_thread_count}, "thread count", "count" },
3147

    
3148
    /* video options */
3149
    { "b", HAS_ARG | OPT_VIDEO, {(void*)opt_video_bitrate}, "set video bitrate (in kbit/s)", "bitrate" },
3150
    { "r", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_rate}, "set frame rate (Hz value, fraction or abbreviation)", "rate" },
3151
    { "s", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_size}, "set frame size (WxH or abbreviation)", "size" },
3152
    { "aspect", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_aspect_ratio}, "set aspect ratio (4:3, 16:9 or 1.3333, 1.7777)", "aspect" },
3153
    { "pix_fmt", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_frame_pix_fmt}, "set pixel format", "format" },
3154
    { "croptop", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop_top}, "set top crop band size (in pixels)", "size" },
3155
    { "cropbottom", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop_bottom}, "set bottom crop band size (in pixels)", "size" },
3156
    { "cropleft", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop_left}, "set left crop band size (in pixels)", "size" },
3157
    { "cropright", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop_right}, "set right crop band size (in pixels)", "size" },
3158
    { "g", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_gop_size}, "set the group of picture size", "gop_size" },
3159
    { "intra", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&intra_only}, "use only intra frames"},
3160
    { "vn", OPT_BOOL | OPT_VIDEO, {(void*)&video_disable}, "disable video" },
3161
    { "qscale", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qscale}, "use fixed video quantiser scale (VBR)", "q" },
3162
    { "qmin", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qmin}, "min video quantiser scale (VBR)", "q" },
3163
    { "qmax", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qmax}, "max video quantiser scale (VBR)", "q" },
3164
    { "mbqmin", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_mb_qmin}, "min macroblock quantiser scale (VBR)", "q" },
3165
    { "mbqmax", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_mb_qmax}, "max macroblock quantiser scale (VBR)", "q" },
3166
    { "qdiff", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qdiff}, "max difference between the quantiser scale (VBR)", "q" },
3167
    { "qblur", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qblur}, "video quantiser scale blur (VBR)", "blur" },
3168
    { "qcomp", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qcomp}, "video quantiser scale compression (VBR)", "compression" },
3169
    { "rc_init_cplx", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_rc_initial_cplx}, "initial complexity for 1-pass encoding", "complexity" },
3170
    { "b_qfactor", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_b_qfactor}, "qp factor between p and b frames", "factor" },
3171
    { "i_qfactor", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_i_qfactor}, "qp factor between p and i frames", "factor" },
3172
    { "b_qoffset", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_b_qoffset}, "qp offset between p and b frames", "offset" },
3173
    { "i_qoffset", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_i_qoffset}, "qp offset between p and i frames", "offset" },
3174
    { "ibias", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_ibias}, "intra quant bias", "bias" },
3175
    { "pbias", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_pbias}, "inter quant bias", "bias" },
3176
//    { "b_strategy", HAS_ARG | OPT_EXPERT, {(void*)opt_b_strategy}, "dynamic b frame selection strategy", "strategy" },
3177
    { "rc_eq", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_video_rc_eq}, "set rate control equation", "equation" },
3178
    { "rc_override", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_video_rc_override_string}, "rate control override for specific intervals", "override" },
3179
    { "bt", HAS_ARG | OPT_VIDEO, {(void*)opt_video_bitrate_tolerance}, "set video bitrate tolerance (in kbit/s)", "tolerance" },
3180
    { "maxrate", HAS_ARG | OPT_VIDEO, {(void*)opt_video_bitrate_max}, "set max video bitrate tolerance (in kbit/s)", "bitrate" },
3181
    { "minrate", HAS_ARG | OPT_VIDEO, {(void*)opt_video_bitrate_min}, "set min video bitrate tolerance (in kbit/s)", "bitrate" },
3182
    { "bufsize", HAS_ARG | OPT_VIDEO, {(void*)opt_video_buffer_size}, "set ratecontrol buffere size (in kByte)", "size" },
3183
    { "vcodec", HAS_ARG | OPT_VIDEO, {(void*)opt_video_codec}, "force video codec ('copy' to copy stream)", "codec" },
3184
    { "me", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_motion_estimation}, "set motion estimation method", 
3185
      "method" },
3186
    { "dct_algo", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_dct_algo}, "set dct algo",  "algo" },
3187
    { "idct_algo", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_idct_algo}, "set idct algo",  "algo" },
3188
    { "er", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_error_resilience}, "set error resilience",  "n" },
3189
    { "ec", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_error_concealment}, "set error concealment",  "bit_mask" },
3190
    { "bf", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_b_frames}, "use 'frames' B frames", "frames" },
3191
    { "hq", OPT_BOOL, {(void*)&mb_decision}, "activate high quality settings" },
3192
    { "mbd", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_mb_decision}, "macroblock decision", "mode" },
3193
    { "mbcmp", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_mb_cmp}, "macroblock compare function", "cmp function" },
3194
    { "ildctcmp", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_ildct_cmp}, "ildct compare function", "cmp function" },
3195
    { "subcmp", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_sub_cmp}, "subpel compare function", "cmp function" },
3196
    { "cmp", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_cmp}, "fullpel compare function", "cmp function" },
3197
    { "precmp", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_pre_cmp}, "pre motion estimation compare function", "cmp function" },
3198
    { "preme", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_pre_me}, "pre motion estimation", "" },
3199
    { "lumi_mask", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_lumi_mask}, "luminance masking", "" },
3200
    { "dark_mask", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_dark_mask}, "darkness masking", "" },
3201
    { "scplx_mask", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_scplx_mask}, "spatial complexity masking", "" },
3202
    { "tcplx_mask", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_tcplx_mask}, "teporal complexity masking", "" },
3203
    { "p_mask", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_p_mask}, "inter masking", "" },
3204
    { "4mv", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_4mv}, "use four motion vector by macroblock (MPEG4)" },
3205
    { "obmc", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_obmc}, "use overlapped block motion compensation (h263+)" },
3206
    { "lf", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_loop}, "use loop filter (h263+)" },
3207
    { "part", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_part}, "use data partitioning (MPEG4)" },
3208
    { "bug", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_workaround_bugs}, "workaround not auto detected encoder bugs", "param" },
3209
    { "ps", HAS_ARG | OPT_EXPERT, {(void*)opt_packet_size}, "set packet size in bits", "size" },
3210
    { "error", HAS_ARG | OPT_EXPERT, {(void*)opt_error_rate}, "error rate", "rate" },
3211
    { "strict", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_strict}, "how strictly to follow the standarts", "strictness" },
3212
    { "sameq", OPT_BOOL | OPT_VIDEO, {(void*)&same_quality}, 
3213
      "use same video quality as source (implies VBR)" },
3214
    { "pass", HAS_ARG | OPT_VIDEO, {(void*)&opt_pass}, "select the pass number (1 or 2)", "n" },
3215
    { "passlogfile", HAS_ARG | OPT_STRING | OPT_VIDEO, {(void*)&pass_logfilename}, "select two pass log file name", "file" },
3216
    { "deinterlace", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_deinterlace}, 
3217
      "deinterlace pictures" },
3218
    { "ildct", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_interlace_dct}, 
3219
      "force interlaced dct support in encoder (MPEG2/MPEG4)" },
3220
    { "ilme", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_interlace_me}, 
3221
      "force interlaced me support in encoder (MPEG2/MPEG4)" },
3222
    { "psnr", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_psnr}, "calculate PSNR of compressed frames" },
3223
    { "vstats", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_vstats}, "dump video coding statistics to file" }, 
3224
    { "vhook", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)add_frame_hooker}, "insert video processing module", "module" },
3225
    { "aic", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_aic}, "enable Advanced intra coding (h263+)" },
3226
    { "aiv", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_aiv}, "enable Alternative inter vlc (h263+)" },
3227
    { "umv", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_umv}, "enable Unlimited Motion Vector (h263+)" },
3228
    { "ssm", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_ss}, "enable Slice Structured mode (h263+)" },
3229
    { "alt", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_alt_scan}, "enable alternate scantable (MPEG2/MPEG4)" },
3230
    { "trell", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_trell}, "enable trellis quantization" },
3231
    { "cgop", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&closed_gop}, "closed gop" },
3232
    { "scan_offset", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_scan_offset}, "enable SVCD Scan Offset placeholder" },
3233
    { "intra_matrix", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_intra_matrix}, "specify intra matrix coeffs", "matrix" },
3234
    { "inter_matrix", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_inter_matrix}, "specify inter matrix coeffs", "matrix" },
3235
    { "top", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_top_field_first}, "top=1/bottom=0/auto=-1 field first", "" },
3236
    { "nr", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_noise_reduction}, "noise reduction", "" },
3237
    { "qns", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qns}, "quantization noise shaping", "" },
3238
    { "sc_threshold", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_sc_threshold}, "scene change threshold", "threshold" },
3239

    
3240
    /* audio options */
3241
    { "ab", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_bitrate}, "set audio bitrate (in kbit/s)", "bitrate", },
3242
    { "ar", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_rate}, "set audio sampling rate (in Hz)", "rate" },
3243
    { "ac", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_channels}, "set number of audio channels", "channels" },
3244
    { "an", OPT_BOOL | OPT_AUDIO, {(void*)&audio_disable}, "disable audio" },
3245
    { "acodec", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_codec}, "force audio codec ('copy' to copy stream)", "codec" },
3246

    
3247
    /* grab options */
3248
    { "vd", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_device}, "set video grab device", "device" },
3249
    { "vc", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_channel}, "set video grab channel (DV1394 only)", "channel" },
3250
    { "tvstd", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_standard}, "set television standard (NTSC, PAL (SECAM))", "standard" },
3251
    { "dv1394", OPT_EXPERT | OPT_GRAB, {(void*)opt_dv1394}, "set DV1394 grab", "" },
3252
    { "ad", HAS_ARG | OPT_EXPERT | OPT_AUDIO | OPT_GRAB, {(void*)opt_audio_device}, "set audio device", "device" },
3253
    { NULL, },
3254
};
3255

    
3256
static void show_banner(void)
3257
{
3258
    printf("ffmpeg version " FFMPEG_VERSION ", Copyright (c) 2000-2003 Fabrice Bellard\n");
3259
}
3260

    
3261
static void show_license(void)
3262
{
3263
    show_banner();
3264
    printf(
3265
    "This library is free software; you can redistribute it and/or\n"
3266
    "modify it under the terms of the GNU Lesser General Public\n"
3267
    "License as published by the Free Software Foundation; either\n"
3268
    "version 2 of the License, or (at your option) any later version.\n"
3269
    "\n"
3270
    "This library is distributed in the hope that it will be useful,\n"
3271
    "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
3272
    "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n"
3273
    "Lesser General Public License for more details.\n"
3274
    "\n"
3275
    "You should have received a copy of the GNU Lesser General Public\n"
3276
    "License along with this library; if not, write to the Free Software\n"
3277
    "Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n"
3278
    );
3279
    exit(1);
3280
}
3281

    
3282
static void show_help(void)
3283
{
3284
    show_banner();
3285
    printf("usage: ffmpeg [[options] -i input_file]... {[options] outfile}...\n"
3286
           "Hyper fast Audio and Video encoder\n");
3287
    printf("\n");
3288
    show_help_options(options, "Main options:\n",
3289
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO, 0);
3290
    show_help_options(options, "\nVideo options:\n",
3291
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB, 
3292
                      OPT_VIDEO);
3293
    show_help_options(options, "\nAdvanced Video options:\n",
3294
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB, 
3295
                      OPT_VIDEO | OPT_EXPERT);
3296
    show_help_options(options, "\nAudio options:\n",
3297
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB, 
3298
                      OPT_AUDIO);
3299
    show_help_options(options, "\nAdvanced Audio options:\n",
3300
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB, 
3301
                      OPT_AUDIO | OPT_EXPERT);
3302
    show_help_options(options, "\nAudio/Video grab options:\n",
3303
                      OPT_GRAB, 
3304
                      OPT_GRAB);
3305
    show_help_options(options, "\nAdvanced options:\n",
3306
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB, 
3307
                      OPT_EXPERT);
3308
    exit(1);
3309
}
3310

    
3311
void parse_arg_file(const char *filename)
3312
{
3313
    opt_output_file(filename);
3314
}
3315

    
3316
int main(int argc, char **argv)
3317
{
3318
    int i;
3319
    int64_t ti;
3320

    
3321
    av_register_all();
3322

    
3323
    if (argc <= 1)
3324
        show_help();
3325
    
3326
    /* parse options */
3327
    parse_options(argc, argv, options);
3328

    
3329
    /* file converter / grab */
3330
    if (nb_output_files <= 0) {
3331
        fprintf(stderr, "Must supply at least one output file\n");
3332
        exit(1);
3333
    }
3334
    
3335
    if (nb_input_files == 0) {
3336
        prepare_grab();
3337
    }
3338

    
3339
    ti = getutime();
3340
    av_encode(output_files, nb_output_files, input_files, nb_input_files, 
3341
              stream_maps, nb_stream_maps);
3342
    ti = getutime() - ti;
3343
    if (do_benchmark) {
3344
        printf("bench: utime=%0.3fs\n", ti / 1000000.0);
3345
    }
3346

    
3347
    /* close files */
3348
    for(i=0;i<nb_output_files;i++) {
3349
        /* maybe av_close_output_file ??? */
3350
        AVFormatContext *s = output_files[i];
3351
        int j;
3352
        if (!(s->oformat->flags & AVFMT_NOFILE))
3353
            url_fclose(&s->pb);
3354
        for(j=0;j<s->nb_streams;j++)
3355
            av_free(s->streams[j]);
3356
        av_free(s);
3357
    }
3358
    for(i=0;i<nb_input_files;i++)
3359
        av_close_input_file(input_files[i]);
3360

    
3361
    av_free_static();
3362

    
3363
    if(intra_matrix)
3364
        av_free(intra_matrix);
3365
    if(inter_matrix)
3366
        av_free(inter_matrix);
3367
    
3368
#ifdef POWERPC_PERFORMANCE_REPORT
3369
    extern void powerpc_display_perf_report(void);
3370
    powerpc_display_perf_report();
3371
#endif /* POWERPC_PERFORMANCE_REPORT */
3372

    
3373
#ifndef CONFIG_WIN32
3374
    if (received_sigterm) {
3375
        fprintf(stderr,
3376
            "Received signal %d: terminating.\n",
3377
            (int) received_sigterm);
3378
        exit (255);
3379
    }
3380
#endif
3381
    exit(0); /* not all OS-es handle main() return value */
3382
    return 0;
3383
}