Statistics
| Branch: | Revision:

ffmpeg / ffmpeg.c @ ae2e7208

History | View | Annotate | Download (107 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
#include <time.h>
38

    
39
#include "cmdutils.h"
40

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

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

    
51
extern const OptionDef options[];
52

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

    
56
#define MAX_FILES 20
57

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

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

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

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

    
149
static int gop_size = 12;
150
static int intra_only = 0;
151
static int audio_sample_rate = 44100;
152
static int audio_bit_rate = 64000;
153
static int audio_disable = 0;
154
static int audio_channels = 1;
155
static int audio_codec_id = CODEC_ID_NONE;
156

    
157
static int64_t recording_time = 0;
158
static int64_t start_time = 0;
159
static int file_overwrite = 0;
160
static char *str_title = NULL;
161
static char *str_author = NULL;
162
static char *str_copyright = NULL;
163
static char *str_comment = NULL;
164
static int do_benchmark = 0;
165
static int do_hex_dump = 0;
166
static int do_pkt_dump = 0;
167
static int do_psnr = 0;
168
static int do_vstats = 0;
169
static int do_pass = 0;
170
static int bitexact = 0;
171
static char *pass_logfilename = NULL;
172
static int audio_stream_copy = 0;
173
static int video_stream_copy = 0;
174

    
175
static int rate_emu = 0;
176

    
177
static char *video_grab_format = "video4linux";
178
static char *video_device = NULL;
179
static int  video_channel = 0;
180
static char *video_standard = "ntsc";
181

    
182
static char *audio_grab_format = "audio_device";
183
static char *audio_device = NULL;
184

    
185
static int using_stdin = 0;
186
static int using_vhook = 0;
187
static int verbose = 1;
188

    
189
#define DEFAULT_PASS_LOGFILENAME "ffmpeg2pass"
190

    
191
typedef struct AVOutputStream {
192
    int file_index;          /* file index */
193
    int index;               /* stream index in the output file */
194
    int source_index;        /* AVInputStream index */
195
    AVStream *st;            /* stream in the output file */
196
    int encoding_needed;     /* true if encoding needed for this stream */
197
    int frame_number;
198
    /* input pts and corresponding output pts
199
       for A/V sync */
200
    double sync_ipts;
201
    double sync_ipts_offset;
202
    int64_t sync_opts;
203
    /* video only */
204
    int video_resample;      /* video_resample and video_crop are mutually exclusive */
205
    AVPicture pict_tmp;      /* temporary image for resampling */
206
    ImgReSampleContext *img_resample_ctx; /* for image resampling */
207

    
208
    int video_crop;          /* video_resample and video_crop are mutually exclusive */
209
    int topBand;             /* cropping area sizes */
210
    int leftBand;
211
    
212
    /* audio only */
213
    int audio_resample;
214
    ReSampleContext *resample; /* for audio resampling */
215
    FifoBuffer fifo;     /* for compression: one audio fifo per codec */
216
    FILE *logfile;
217
} AVOutputStream;
218

    
219
typedef struct AVInputStream {
220
    int file_index;
221
    int index;
222
    AVStream *st;
223
    int discard;             /* true if stream data should be discarded */
224
    int decoding_needed;     /* true if the packets must be decoded in 'raw_fifo' */
225
    int64_t sample_index;      /* current sample */
226

    
227
    int64_t       start;     /* time when read started */
228
    unsigned long frame;     /* current frame */
229
    int64_t       next_pts;  /* synthetic pts for cases where pkt.pts
230
                                is not defined */
231
    int64_t       pts;       /* current pts */
232
} AVInputStream;
233

    
234
typedef struct AVInputFile {
235
    int eof_reached;      /* true if eof reached */
236
    int ist_index;        /* index of first stream in ist_table */
237
    int buffer_size;      /* current total buffer size */
238
    int buffer_size_max;  /* buffer size at which we consider we can stop
239
                             buffering */
240
    int nb_streams;       /* nb streams we are aware of */
241
} AVInputFile;
242

    
243
#ifndef CONFIG_WIN32
244

    
245
/* init terminal so that we can grab keys */
246
static struct termios oldtty;
247

    
248
static void term_exit(void)
249
{
250
    tcsetattr (0, TCSANOW, &oldtty);
251
}
252

    
253
static volatile sig_atomic_t received_sigterm = 0;
254

    
255
static void
256
sigterm_handler(int sig)
257
{
258
    received_sigterm = sig;
259
    term_exit();
260
}
261

    
262
static void term_init(void)
263
{
264
    struct termios tty;
265

    
266
    tcgetattr (0, &tty);
267
    oldtty = tty;
268

    
269
    tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
270
                          |INLCR|IGNCR|ICRNL|IXON);
271
    tty.c_oflag |= OPOST;
272
    tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
273
    tty.c_cflag &= ~(CSIZE|PARENB);
274
    tty.c_cflag |= CS8;
275
    tty.c_cc[VMIN] = 1;
276
    tty.c_cc[VTIME] = 0;
277
    
278
    tcsetattr (0, TCSANOW, &tty);
279

    
280
    signal(SIGINT , sigterm_handler); /* Interrupt (ANSI).  */
281
    signal(SIGQUIT, sigterm_handler); /* Quit (POSIX).  */
282
    signal(SIGTERM, sigterm_handler); /* Termination (ANSI).  */
283
    /*
284
    register a function to be called at normal program termination
285
    */
286
    atexit(term_exit);
287
#ifdef CONFIG_BEOS_NETSERVER
288
    fcntl(0, F_SETFL, fcntl(0, F_GETFL) | O_NONBLOCK);
289
#endif
290
}
291

    
292
/* read a key without blocking */
293
static int read_key(void)
294
{
295
    int n = 1;
296
    unsigned char ch;
297
#ifndef CONFIG_BEOS_NETSERVER
298
    struct timeval tv;
299
    fd_set rfds;
300

    
301
    FD_ZERO(&rfds);
302
    FD_SET(0, &rfds);
303
    tv.tv_sec = 0;
304
    tv.tv_usec = 0;
305
    n = select(1, &rfds, NULL, NULL, &tv);
306
#endif
307
    if (n > 0) {
308
        n = read(0, &ch, 1);
309
        if (n == 1)
310
            return ch;
311

    
312
        return n;
313
    }
314
    return -1;
315
}
316

    
317
#else
318

    
319
static volatile int received_sigterm = 0;
320

    
321
/* no interactive support */
322
static void term_exit(void)
323
{
324
}
325

    
326
static void term_init(void)
327
{
328
}
329

    
330
static int read_key(void)
331
{
332
    return 0;
333
}
334

    
335
#endif
336

    
337
static int read_ffserver_streams(AVFormatContext *s, const char *filename)
338
{
339
    int i, err;
340
    AVFormatContext *ic;
341

    
342
    err = av_open_input_file(&ic, filename, NULL, FFM_PACKET_SIZE, NULL);
343
    if (err < 0)
344
        return err;
345
    /* copy stream format */
346
    s->nb_streams = ic->nb_streams;
347
    for(i=0;i<ic->nb_streams;i++) {
348
        AVStream *st;
349

    
350
        st = av_mallocz(sizeof(AVStream));
351
        memcpy(st, ic->streams[i], sizeof(AVStream));
352
        s->streams[i] = st;
353
    }
354

    
355
    av_close_input_file(ic);
356
    return 0;
357
}
358

    
359
#define MAX_AUDIO_PACKET_SIZE (128 * 1024)
360

    
361
static void do_audio_out(AVFormatContext *s, 
362
                         AVOutputStream *ost, 
363
                         AVInputStream *ist,
364
                         unsigned char *buf, int size)
365
{
366
    uint8_t *buftmp;
367
    static uint8_t *audio_buf = NULL;
368
    static uint8_t *audio_out = NULL;
369
    const int audio_out_size= 4*MAX_AUDIO_PACKET_SIZE;
370

    
371
    int size_out, frame_bytes, ret;
372
    AVCodecContext *enc;
373

    
374
    /* SC: dynamic allocation of buffers */
375
    if (!audio_buf)
376
        audio_buf = av_malloc(2*MAX_AUDIO_PACKET_SIZE);
377
    if (!audio_out)
378
        audio_out = av_malloc(audio_out_size);
379
    if (!audio_buf || !audio_out)
380
        return;               /* Should signal an error ! */
381

    
382
    
383
    enc = &ost->st->codec;
384

    
385
    if (ost->audio_resample) {
386
        buftmp = audio_buf;
387
        size_out = audio_resample(ost->resample, 
388
                                  (short *)buftmp, (short *)buf,
389
                                  size / (ist->st->codec.channels * 2));
390
        size_out = size_out * enc->channels * 2;
391
    } else {
392
        buftmp = buf;
393
        size_out = size;
394
    }
395

    
396
    /* now encode as many frames as possible */
397
    if (enc->frame_size > 1) {
398
        /* output resampled raw samples */
399
        fifo_write(&ost->fifo, buftmp, size_out, 
400
                   &ost->fifo.wptr);
401

    
402
        frame_bytes = enc->frame_size * 2 * enc->channels;
403
        
404
        while (fifo_read(&ost->fifo, audio_buf, frame_bytes, 
405
                     &ost->fifo.rptr) == 0) {
406
            ret = avcodec_encode_audio(enc, audio_out, audio_out_size, 
407
                                       (short *)audio_buf);
408
            av_write_frame(s, ost->index, audio_out, ret);
409
        }
410
    } else {
411
        /* output a pcm frame */
412
        /* XXX: change encoding codec API to avoid this ? */
413
        switch(enc->codec->id) {
414
        case CODEC_ID_PCM_S16LE:
415
        case CODEC_ID_PCM_S16BE:
416
        case CODEC_ID_PCM_U16LE:
417
        case CODEC_ID_PCM_U16BE:
418
            break;
419
        default:
420
            size_out = size_out >> 1;
421
            break;
422
        }
423
        ret = avcodec_encode_audio(enc, audio_out, size_out, 
424
                                   (short *)buftmp);
425
        av_write_frame(s, ost->index, audio_out, ret);
426
    }
427
}
428

    
429
static void pre_process_video_frame(AVInputStream *ist, AVPicture *picture, void **bufp)
430
{
431
    AVCodecContext *dec;
432
    AVPicture *picture2;
433
    AVPicture picture_tmp;
434
    uint8_t *buf = 0;
435

    
436
    dec = &ist->st->codec;
437

    
438
    /* deinterlace : must be done before any resize */
439
    if (do_deinterlace || using_vhook) {
440
        int size;
441

    
442
        /* create temporary picture */
443
        size = avpicture_get_size(dec->pix_fmt, dec->width, dec->height);
444
        buf = av_malloc(size);
445
        if (!buf)
446
            return;
447
        
448
        picture2 = &picture_tmp;
449
        avpicture_fill(picture2, buf, dec->pix_fmt, dec->width, dec->height);
450

    
451
        if (do_deinterlace){
452
            if(avpicture_deinterlace(picture2, picture, 
453
                                     dec->pix_fmt, dec->width, dec->height) < 0) {
454
                /* if error, do not deinterlace */
455
                av_free(buf);
456
                buf = NULL;
457
                picture2 = picture;
458
            }
459
        } else {
460
            if (img_convert(picture2, dec->pix_fmt, picture, 
461
                            dec->pix_fmt, dec->width, dec->height) < 0) {
462
                /* if error, do not copy */
463
                av_free(buf);
464
                buf = NULL;
465
                picture2 = picture;
466
            }
467
        }
468
    } else {
469
        picture2 = picture;
470
    }
471

    
472
    frame_hook_process(picture2, dec->pix_fmt, dec->width, dec->height);
473

    
474
    if (picture != picture2)
475
        *picture = *picture2;
476
    *bufp = buf;
477
}
478

    
479
/* we begin to correct av delay at this threshold */
480
#define AV_DELAY_MAX 0.100
481

    
482
static void do_video_out(AVFormatContext *s, 
483
                         AVOutputStream *ost, 
484
                         AVInputStream *ist,
485
                         AVFrame *in_picture,
486
                         int *frame_size, AVOutputStream *audio_sync)
487
{
488
    int nb_frames, i, ret;
489
    AVPicture *final_picture, *formatted_picture;
490
    AVPicture picture_format_temp, picture_crop_temp;
491
    static uint8_t *video_buffer= NULL;
492
    uint8_t *buf = NULL, *buf1 = NULL;
493
    AVCodecContext *enc, *dec;
494
    enum PixelFormat target_pixfmt;
495

    
496
#define VIDEO_BUFFER_SIZE (1024*1024)
497

    
498
    enc = &ost->st->codec;
499
    dec = &ist->st->codec;
500

    
501
    /* by default, we output a single frame */
502
    nb_frames = 1;
503

    
504
    *frame_size = 0;
505

    
506
    /* NOTE: the A/V sync is always done by considering the audio is
507
       the master clock. It is suffisant for transcoding or playing,
508
       but not for the general case */
509
    if (audio_sync) {
510
        /* compute the A-V delay and duplicate/remove frames if needed */
511
        double adelta, vdelta, av_delay;
512

    
513
        adelta = audio_sync->sync_ipts - ((double)audio_sync->sync_opts * 
514
            s->pts_num / s->pts_den);
515

    
516
        vdelta = ost->sync_ipts - ((double)ost->sync_opts *
517
            s->pts_num / s->pts_den);
518

    
519
        av_delay = adelta - vdelta;
520
        //            printf("delay=%f\n", av_delay);
521
        if (av_delay < -AV_DELAY_MAX)
522
            nb_frames = 2;
523
        else if (av_delay > AV_DELAY_MAX)
524
            nb_frames = 0;
525
    } else {
526
        double vdelta;
527

    
528
        vdelta = (double)(ost->st->pts.val) * s->pts_num / s->pts_den - (ost->sync_ipts - ost->sync_ipts_offset);
529
        if (vdelta < 100 && vdelta > -100 && ost->sync_ipts_offset) {
530
            if (vdelta < -AV_DELAY_MAX)
531
                nb_frames = 2;
532
            else if (vdelta > AV_DELAY_MAX)
533
                nb_frames = 0;
534
        } else {
535
            ost->sync_ipts_offset -= vdelta;
536
            if (!ost->sync_ipts_offset)
537
                ost->sync_ipts_offset = 0.000001; /* one microsecond */
538
        }
539
    }
540
    
541
#if defined(AVSYNC_DEBUG)
542
    {
543
        static char *action[] = { "drop frame", "copy frame", "dup frame" };
544
        if (audio_sync)
545
            fprintf(stderr, "Input APTS %12.6f, output APTS %12.6f, ",
546
                    (double) audio_sync->sync_ipts, 
547
                    (double) audio_sync->st->pts.val * s->pts_num / s->pts_den);
548
        fprintf(stderr, "Input VPTS %12.6f, output VPTS %12.6f: %s\n",
549
                (double) ost->sync_ipts, 
550
                (double) ost->st->pts.val * s->pts_num / s->pts_den,
551
                action[nb_frames]);
552
    }
553
#endif
554

    
555
    if (nb_frames <= 0) 
556
        return;
557

    
558
    if (!video_buffer)
559
        video_buffer = av_malloc(VIDEO_BUFFER_SIZE);
560
    if (!video_buffer)
561
        return;
562

    
563
    /* convert pixel format if needed */
564
    target_pixfmt = ost->video_resample ? PIX_FMT_YUV420P : enc->pix_fmt;
565
    if (dec->pix_fmt != target_pixfmt) {
566
        int size;
567

    
568
        /* create temporary picture */
569
        size = avpicture_get_size(target_pixfmt, dec->width, dec->height);
570
        buf = av_malloc(size);
571
        if (!buf)
572
            return;
573
        formatted_picture = &picture_format_temp;
574
        avpicture_fill(formatted_picture, buf, target_pixfmt, dec->width, dec->height);
575
        
576
        if (img_convert(formatted_picture, target_pixfmt, 
577
                        (AVPicture *)in_picture, dec->pix_fmt, 
578
                        dec->width, dec->height) < 0) {
579
            fprintf(stderr, "pixel format conversion not handled\n");
580
            goto the_end;
581
        }
582
    } else {
583
        formatted_picture = (AVPicture *)in_picture;
584
    }
585

    
586
    /* XXX: resampling could be done before raw format convertion in
587
       some cases to go faster */
588
    /* XXX: only works for YUV420P */
589
    if (ost->video_resample) {
590
        final_picture = &ost->pict_tmp;
591
        img_resample(ost->img_resample_ctx, final_picture, formatted_picture);
592
        if (enc->pix_fmt != PIX_FMT_YUV420P) {
593
            int size;
594
            
595
            av_free(buf);
596
            /* create temporary picture */
597
            size = avpicture_get_size(enc->pix_fmt, enc->width, enc->height);
598
            buf = av_malloc(size);
599
            if (!buf)
600
                return;
601
            final_picture = &picture_format_temp;
602
            avpicture_fill(final_picture, buf, enc->pix_fmt, enc->width, enc->height);
603
        
604
            if (img_convert(final_picture, enc->pix_fmt, 
605
                            &ost->pict_tmp, PIX_FMT_YUV420P, 
606
                            enc->width, enc->height) < 0) {
607
                fprintf(stderr, "pixel format conversion not handled\n");
608
                goto the_end;
609
            }
610
        }
611
    } else if (ost->video_crop) {
612
        picture_crop_temp.data[0] = formatted_picture->data[0] +
613
                (ost->topBand * formatted_picture->linesize[0]) + ost->leftBand;
614

    
615
        picture_crop_temp.data[1] = formatted_picture->data[1] +
616
                ((ost->topBand >> 1) * formatted_picture->linesize[1]) +
617
                (ost->leftBand >> 1);
618

    
619
        picture_crop_temp.data[2] = formatted_picture->data[2] +
620
                ((ost->topBand >> 1) * formatted_picture->linesize[2]) +
621
                (ost->leftBand >> 1);
622

    
623
        picture_crop_temp.linesize[0] = formatted_picture->linesize[0];
624
        picture_crop_temp.linesize[1] = formatted_picture->linesize[1];
625
        picture_crop_temp.linesize[2] = formatted_picture->linesize[2];
626
        final_picture = &picture_crop_temp;
627
    } else {
628
        final_picture = formatted_picture;
629
    }
630
    /* duplicates frame if needed */
631
    /* XXX: pb because no interleaving */
632
    for(i=0;i<nb_frames;i++) {
633
        if (s->oformat->flags & AVFMT_RAWPICTURE) {
634
            /* raw pictures are written as AVPicture structure to
635
               avoid any copies. We support temorarily the older
636
               method. */
637
            AVFrame* old_frame = enc->coded_frame;
638
            enc->coded_frame = dec->coded_frame;
639
            av_write_frame(s, ost->index, 
640
                           (uint8_t *)final_picture, sizeof(AVPicture));
641
            enc->coded_frame = old_frame;
642
        } else {
643
            AVFrame big_picture;
644
            
645
            memset(&big_picture, 0, sizeof(AVFrame));
646
            *(AVPicture*)&big_picture= *final_picture;
647
            /* better than nothing: use input picture interlaced
648
               settings */
649
            big_picture.interlaced_frame = in_picture->interlaced_frame;
650
            if(do_interlace_me || do_interlace_dct){
651
                if(top_field_first == -1)
652
                    big_picture.top_field_first = in_picture->top_field_first;
653
                else
654
                    big_picture.top_field_first = 1;
655
            }
656

    
657
            /* handles sameq here. This is not correct because it may
658
               not be a global option */
659
            if (same_quality) {
660
                big_picture.quality = ist->st->quality;
661
            }else
662
                big_picture.quality = ost->st->quality;
663
            ret = avcodec_encode_video(enc, 
664
                                       video_buffer, VIDEO_BUFFER_SIZE,
665
                                       &big_picture);
666
            //enc->frame_number = enc->real_pict_num;
667
            av_write_frame(s, ost->index, video_buffer, ret);
668
            *frame_size = ret;
669
            //fprintf(stderr,"\nFrame: %3d %3d size: %5d type: %d",
670
            //        enc->frame_number-1, enc->real_pict_num, ret,
671
            //        enc->pict_type);
672
            /* if two pass, output log */
673
            if (ost->logfile && enc->stats_out) {
674
                fprintf(ost->logfile, "%s", enc->stats_out);
675
            }
676
        }
677
        ost->frame_number++;
678
    }
679
 the_end:
680
    av_free(buf);
681
    av_free(buf1);
682
}
683

    
684
static double psnr(double d){
685
    if(d==0) return INFINITY;
686
    return -10.0*log(d)/log(10.0);
687
}
688

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

    
738
static void print_report(AVFormatContext **output_files,
739
                         AVOutputStream **ost_table, int nb_ostreams,
740
                         int is_last_report)
741
{
742
    char buf[1024];
743
    AVOutputStream *ost;
744
    AVFormatContext *oc, *os;
745
    int64_t total_size;
746
    AVCodecContext *enc;
747
    int frame_number, vid, i;
748
    double bitrate, ti1, pts;
749
    static int64_t last_time = -1;
750
    
751
    if (!is_last_report) {
752
        int64_t cur_time;
753
        /* display the report every 0.5 seconds */
754
        cur_time = av_gettime();
755
        if (last_time == -1) {
756
            last_time = cur_time;
757
            return;
758
        } 
759
        if ((cur_time - last_time) < 500000)
760
            return;
761
        last_time = cur_time;
762
    }
763

    
764

    
765
    oc = output_files[0];
766

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

    
832
/* pkt = NULL means EOF (needed to flush decoder buffers) */
833
static int output_packet(AVInputStream *ist, int ist_index,
834
                         AVOutputStream **ost_table, int nb_ostreams,
835
                         AVPacket *pkt)
836
{
837
    AVFormatContext *os;
838
    AVOutputStream *ost;
839
    uint8_t *ptr;
840
    int len, ret, i;
841
    uint8_t *data_buf;
842
    int data_size, got_picture;
843
    AVFrame picture;
844
    short samples[AVCODEC_MAX_AUDIO_FRAME_SIZE / 2];
845
    void *buffer_to_free;
846
        
847
    if (pkt && pkt->pts != AV_NOPTS_VALUE) {
848
        ist->pts = pkt->pts;
849
    } else {
850
        ist->pts = ist->next_pts;
851
    }
852
    
853
    if (pkt == NULL) {
854
        /* EOF handling */
855
        ptr = NULL;
856
        len = 0;
857
        goto handle_eof;
858
    }
859

    
860
    len = pkt->size;
861
    ptr = pkt->data;
862
    while (len > 0) {
863
    handle_eof:
864
        /* decode the packet if needed */
865
        data_buf = NULL; /* fail safe */
866
        data_size = 0;
867
        if (ist->decoding_needed) {
868
            switch(ist->st->codec.codec_type) {
869
            case CODEC_TYPE_AUDIO:
870
                    /* XXX: could avoid copy if PCM 16 bits with same
871
                       endianness as CPU */
872
                ret = avcodec_decode_audio(&ist->st->codec, samples, &data_size,
873
                                           ptr, len);
874
                if (ret < 0)
875
                    goto fail_decode;
876
                ptr += ret;
877
                len -= ret;
878
                /* Some bug in mpeg audio decoder gives */
879
                /* data_size < 0, it seems they are overflows */
880
                if (data_size <= 0) {
881
                    /* no audio frame */
882
                    continue;
883
                }
884
                data_buf = (uint8_t *)samples;
885
                ist->next_pts += ((int64_t)AV_TIME_BASE * data_size) / 
886
                    (2 * ist->st->codec.channels);
887
                break;
888
            case CODEC_TYPE_VIDEO:
889
                    data_size = (ist->st->codec.width * ist->st->codec.height * 3) / 2;
890
                    /* XXX: allocate picture correctly */
891
                    memset(&picture, 0, sizeof(picture));
892
                    ret = avcodec_decode_video(&ist->st->codec, 
893
                                               &picture, &got_picture, ptr, len);
894
                    ist->st->quality= picture.quality;
895
                    if (ret < 0) 
896
                        goto fail_decode;
897
                    if (!got_picture) {
898
                        /* no picture yet */
899
                        goto discard_packet;
900
                    }
901
                    if (ist->st->codec.frame_rate_base != 0) {
902
                        ist->next_pts += ((int64_t)AV_TIME_BASE * 
903
                                          ist->st->codec.frame_rate_base) /
904
                            ist->st->codec.frame_rate;
905
                    }
906
                    len = 0;
907
                    break;
908
                default:
909
                    goto fail_decode;
910
                }
911
            } else {
912
                data_buf = ptr;
913
                data_size = len;
914
                ret = len;
915
                len = 0;
916
            }
917

    
918
            buffer_to_free = NULL;
919
            if (ist->st->codec.codec_type == CODEC_TYPE_VIDEO) {
920
                pre_process_video_frame(ist, (AVPicture *)&picture, 
921
                                        &buffer_to_free);
922
            }
923

    
924
            /* frame rate emulation */
925
            if (ist->st->codec.rate_emu) {
926
                int64_t pts = av_rescale((int64_t) ist->frame * ist->st->codec.frame_rate_base, 1000000, ist->st->codec.frame_rate);
927
                int64_t now = av_gettime() - ist->start;
928
                if (pts > now)
929
                    usleep(pts - now);
930

    
931
                ist->frame++;
932
            }
933

    
934
#if 0
935
            /* mpeg PTS deordering : if it is a P or I frame, the PTS
936
               is the one of the next displayed one */
937
            /* XXX: add mpeg4 too ? */
938
            if (ist->st->codec.codec_id == CODEC_ID_MPEG1VIDEO) {
939
                if (ist->st->codec.pict_type != B_TYPE) {
940
                    int64_t tmp;
941
                    tmp = ist->last_ip_pts;
942
                    ist->last_ip_pts  = ist->frac_pts.val;
943
                    ist->frac_pts.val = tmp;
944
                }
945
            }
946
#endif
947
            /* if output time reached then transcode raw format, 
948
               encode packets and output them */
949
            if (start_time == 0 || ist->pts >= start_time)
950
                for(i=0;i<nb_ostreams;i++) {
951
                    int frame_size;
952

    
953
                    ost = ost_table[i];
954
                    if (ost->source_index == ist_index) {
955
                        os = output_files[ost->file_index];
956

    
957
#if 0
958
                        printf("%d: got pts=%0.3f %0.3f\n", i, 
959
                               (double)pkt->pts / AV_TIME_BASE, 
960
                               ((double)ist->pts / AV_TIME_BASE) - 
961
                               ((double)ost->st->pts.val * os->pts_num / os->pts_den));
962
#endif
963
                        /* set the input output pts pairs */
964
                        ost->sync_ipts = (double)ist->pts / AV_TIME_BASE;
965
                        /* XXX: take into account the various fifos,
966
                           in particular for audio */
967
                        ost->sync_opts = ost->st->pts.val;
968
                        //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); 
969

    
970
                        if (ost->encoding_needed) {
971
                            switch(ost->st->codec.codec_type) {
972
                            case CODEC_TYPE_AUDIO:
973
                                do_audio_out(os, ost, ist, data_buf, data_size);
974
                                break;
975
                            case CODEC_TYPE_VIDEO:
976
                                /* find an audio stream for synchro */
977
                                {
978
                                    int i;
979
                                    AVOutputStream *audio_sync, *ost1;
980
                                    audio_sync = NULL;
981
                                    for(i=0;i<nb_ostreams;i++) {
982
                                        ost1 = ost_table[i];
983
                                        if (ost1->file_index == ost->file_index &&
984
                                            ost1->st->codec.codec_type == CODEC_TYPE_AUDIO) {
985
                                            audio_sync = ost1;
986
                                            break;
987
                                        }
988
                                    }
989

    
990
                                    do_video_out(os, ost, ist, &picture, &frame_size, audio_sync);
991
                                    if (do_vstats && frame_size)
992
                                        do_video_stats(os, ost, frame_size);
993
                                }
994
                                break;
995
                            default:
996
                                av_abort();
997
                            }
998
                        } else {
999
                            AVFrame avframe;
1000
                                                
1001
                            /* no reencoding needed : output the packet directly */
1002
                            /* force the input stream PTS */
1003
                        
1004
                            memset(&avframe, 0, sizeof(AVFrame));
1005
                            ost->st->codec.coded_frame= &avframe;
1006
                            avframe.key_frame = pkt->flags & PKT_FLAG_KEY; 
1007
                        
1008
                            av_write_frame(os, ost->index, data_buf, data_size);
1009
                            ost->st->codec.frame_number++;
1010
                            ost->frame_number++;
1011
                        }
1012
                    }
1013
                }
1014
            av_free(buffer_to_free);
1015
        }
1016
 discard_packet:
1017
    return 0;
1018
 fail_decode:
1019
    return -1;
1020
}
1021

    
1022

    
1023
/*
1024
 * The following code is the main loop of the file converter
1025
 */
1026
static int av_encode(AVFormatContext **output_files,
1027
                     int nb_output_files,
1028
                     AVFormatContext **input_files,
1029
                     int nb_input_files,
1030
                     AVStreamMap *stream_maps, int nb_stream_maps)
1031
{
1032
    int ret, i, j, k, n, nb_istreams = 0, nb_ostreams = 0;
1033
    AVFormatContext *is, *os;
1034
    AVCodecContext *codec, *icodec;
1035
    AVOutputStream *ost, **ost_table = NULL;
1036
    AVInputStream *ist, **ist_table = NULL;
1037
    AVInputFile *file_table;
1038
    AVFormatContext *stream_no_data;
1039
    int key;
1040

    
1041
    file_table= (AVInputFile*) av_mallocz(nb_input_files * sizeof(AVInputFile));
1042
    if (!file_table)
1043
        goto fail;
1044

    
1045
    /* input stream init */
1046
    j = 0;
1047
    for(i=0;i<nb_input_files;i++) {
1048
        is = input_files[i];
1049
        file_table[i].ist_index = j;
1050
        file_table[i].nb_streams = is->nb_streams;
1051
        j += is->nb_streams;
1052
    }
1053
    nb_istreams = j;
1054

    
1055
    ist_table = av_mallocz(nb_istreams * sizeof(AVInputStream *));
1056
    if (!ist_table)
1057
        goto fail;
1058
    
1059
    for(i=0;i<nb_istreams;i++) {
1060
        ist = av_mallocz(sizeof(AVInputStream));
1061
        if (!ist)
1062
            goto fail;
1063
        ist_table[i] = ist;
1064
    }
1065
    j = 0;
1066
    for(i=0;i<nb_input_files;i++) {
1067
        is = input_files[i];
1068
        for(k=0;k<is->nb_streams;k++) {
1069
            ist = ist_table[j++];
1070
            ist->st = is->streams[k];
1071
            ist->file_index = i;
1072
            ist->index = k;
1073
            ist->discard = 1; /* the stream is discarded by default
1074
                                 (changed later) */
1075

    
1076
            if (ist->st->codec.rate_emu) {
1077
                ist->start = av_gettime();
1078
                ist->frame = 0;
1079
            }
1080
        }
1081
    }
1082

    
1083
    /* output stream init */
1084
    nb_ostreams = 0;
1085
    for(i=0;i<nb_output_files;i++) {
1086
        os = output_files[i];
1087
        nb_ostreams += os->nb_streams;
1088
    }
1089
    if (nb_stream_maps > 0 && nb_stream_maps != nb_ostreams) {
1090
        fprintf(stderr, "Number of stream maps must match number of output streams\n");
1091
        exit(1);
1092
    }
1093

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

    
1170
    /* for each output stream, we compute the right encoding parameters */
1171
    for(i=0;i<nb_ostreams;i++) {
1172
        ost = ost_table[i];
1173
        ist = ist_table[ost->source_index];
1174

    
1175
        codec = &ost->st->codec;
1176
        icodec = &ist->st->codec;
1177

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

    
1270
                    ost->img_resample_ctx = img_resample_full_init( 
1271
                                      ost->st->codec.width, ost->st->codec.height,
1272
                                      ist->st->codec.width, ist->st->codec.height,
1273
                                      frame_topBand, frame_bottomBand,
1274
                                      frame_leftBand, frame_rightBand);
1275
                }
1276
                ost->encoding_needed = 1;
1277
                ist->decoding_needed = 1;
1278
                break;
1279
            default:
1280
                av_abort();
1281
            }
1282
            /* two pass mode */
1283
            if (ost->encoding_needed && 
1284
                (codec->flags & (CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2))) {
1285
                char logfilename[1024];
1286
                FILE *f;
1287
                int size;
1288
                char *logbuffer;
1289
                
1290
                snprintf(logfilename, sizeof(logfilename), "%s-%d.log", 
1291
                         pass_logfilename ? 
1292
                         pass_logfilename : DEFAULT_PASS_LOGFILENAME, i);
1293
                if (codec->flags & CODEC_FLAG_PASS1) {
1294
                    f = fopen(logfilename, "w");
1295
                    if (!f) {
1296
                        perror(logfilename);
1297
                        exit(1);
1298
                    }
1299
                    ost->logfile = f;
1300
                } else {
1301
                    /* read the log file */
1302
                    f = fopen(logfilename, "r");
1303
                    if (!f) {
1304
                        perror(logfilename);
1305
                        exit(1);
1306
                    }
1307
                    fseek(f, 0, SEEK_END);
1308
                    size = ftell(f);
1309
                    fseek(f, 0, SEEK_SET);
1310
                    logbuffer = av_malloc(size + 1);
1311
                    if (!logbuffer) {
1312
                        fprintf(stderr, "Could not allocate log buffer\n");
1313
                        exit(1);
1314
                    }
1315
                    fread(logbuffer, 1, size, f);
1316
                    fclose(f);
1317
                    logbuffer[size] = '\0';
1318
                    codec->stats_in = logbuffer;
1319
                }
1320
            }
1321
        }
1322
    }
1323

    
1324
    /* dump the file output parameters - cannot be done before in case
1325
       of stream copy */
1326
    for(i=0;i<nb_output_files;i++) {
1327
        dump_format(output_files[i], i, output_files[i]->filename, 1);
1328
    }
1329

    
1330
    /* dump the stream mapping */
1331
    fprintf(stderr, "Stream mapping:\n");
1332
    for(i=0;i<nb_ostreams;i++) {
1333
        ost = ost_table[i];
1334
        fprintf(stderr, "  Stream #%d.%d -> #%d.%d\n",
1335
                ist_table[ost->source_index]->file_index,
1336
                ist_table[ost->source_index]->index,
1337
                ost->file_index, 
1338
                ost->index);
1339
    }
1340

    
1341
    /* open each encoder */
1342
    for(i=0;i<nb_ostreams;i++) {
1343
        ost = ost_table[i];
1344
        if (ost->encoding_needed) {
1345
            AVCodec *codec;
1346
            codec = avcodec_find_encoder(ost->st->codec.codec_id);
1347
            if (!codec) {
1348
                fprintf(stderr, "Unsupported codec for output stream #%d.%d\n", 
1349
                        ost->file_index, ost->index);
1350
                exit(1);
1351
            }
1352
            if (avcodec_open(&ost->st->codec, codec) < 0) {
1353
                fprintf(stderr, "Error while opening codec for stream #%d.%d - maybe incorrect parameters such as bit_rate, rate, width or height\n", 
1354
                        ost->file_index, ost->index);
1355
                exit(1);
1356
            }
1357
        }
1358
    }
1359

    
1360
    /* open each decoder */
1361
    for(i=0;i<nb_istreams;i++) {
1362
        ist = ist_table[i];
1363
        if (ist->decoding_needed) {
1364
            AVCodec *codec;
1365
            codec = avcodec_find_decoder(ist->st->codec.codec_id);
1366
            if (!codec) {
1367
                fprintf(stderr, "Unsupported codec (id=%d) for input stream #%d.%d\n", 
1368
                        ist->st->codec.codec_id, ist->file_index, ist->index);
1369
                exit(1);
1370
            }
1371
            if (avcodec_open(&ist->st->codec, codec) < 0) {
1372
                fprintf(stderr, "Error while opening codec for input stream #%d.%d\n", 
1373
                        ist->file_index, ist->index);
1374
                exit(1);
1375
            }
1376
            //if (ist->st->codec.codec_type == CODEC_TYPE_VIDEO)
1377
            //    ist->st->codec.flags |= CODEC_FLAG_REPEAT_FIELD;
1378
        }
1379
    }
1380

    
1381
    /* init pts */
1382
    for(i=0;i<nb_istreams;i++) {
1383
        ist = ist_table[i];
1384
        is = input_files[ist->file_index];
1385
        ist->pts = 0;
1386
        ist->next_pts = 0;
1387
    }
1388
    
1389
    /* compute buffer size max (should use a complete heuristic) */
1390
    for(i=0;i<nb_input_files;i++) {
1391
        file_table[i].buffer_size_max = 2048;
1392
    }
1393

    
1394
    /* open files and write file headers */
1395
    for(i=0;i<nb_output_files;i++) {
1396
        os = output_files[i];
1397
        if (av_write_header(os) < 0) {
1398
            fprintf(stderr, "Could not write header for output file #%d (incorrect codec paramters ?)\n", i);
1399
            ret = -EINVAL;
1400
            goto fail;
1401
        }
1402
    }
1403

    
1404
#ifndef CONFIG_WIN32
1405
    if ( !using_stdin )
1406
        fprintf(stderr, "Press [q] to stop encoding\n");
1407
#endif
1408
    term_init();
1409

    
1410
    stream_no_data = 0;
1411
    key = -1;
1412

    
1413
    for(; received_sigterm == 0;) {
1414
        int file_index, ist_index;
1415
        AVPacket pkt;
1416
        double pts_min;
1417
        
1418
    redo:
1419
        /* if 'q' pressed, exits */
1420
        if (!using_stdin) {
1421
            /* read_key() returns 0 on EOF */
1422
            key = read_key();
1423
            if (key == 'q')
1424
                break;
1425
        }
1426

    
1427
        /* select the stream that we must read now by looking at the
1428
           smallest output pts */
1429
        file_index = -1;
1430
        pts_min = 1e10;
1431
        for(i=0;i<nb_ostreams;i++) {
1432
            double pts;
1433
            ost = ost_table[i];
1434
            os = output_files[ost->file_index];
1435
            ist = ist_table[ost->source_index];
1436
            pts = (double)ost->st->pts.val * os->pts_num / os->pts_den;
1437
            if (!file_table[ist->file_index].eof_reached && 
1438
                pts < pts_min) {
1439
                pts_min = pts;
1440
                file_index = ist->file_index;
1441
            }
1442
        }
1443
        /* if none, if is finished */
1444
        if (file_index < 0) {
1445
            break;
1446
        }
1447

    
1448
        /* finish if recording time exhausted */
1449
        if (recording_time > 0 && pts_min >= (recording_time / 1000000.0))
1450
            break;
1451

    
1452
        /* read a frame from it and output it in the fifo */
1453
        is = input_files[file_index];
1454
        if (av_read_frame(is, &pkt) < 0) {
1455
            file_table[file_index].eof_reached = 1;
1456
            continue;
1457
        }
1458

    
1459
        if (!pkt.size) {
1460
            stream_no_data = is;
1461
        } else {
1462
            stream_no_data = 0;
1463
        }
1464
        if (do_pkt_dump) {
1465
            av_pkt_dump(stdout, &pkt, do_hex_dump);
1466
        }
1467
        /* the following test is needed in case new streams appear
1468
           dynamically in stream : we ignore them */
1469
        if (pkt.stream_index >= file_table[file_index].nb_streams)
1470
            goto discard_packet;
1471
        ist_index = file_table[file_index].ist_index + pkt.stream_index;
1472
        ist = ist_table[ist_index];
1473
        if (ist->discard)
1474
            goto discard_packet;
1475

    
1476
        //fprintf(stderr,"read #%d.%d size=%d\n", ist->file_index, ist->index, pkt.size);
1477
        if (output_packet(ist, ist_index, ost_table, nb_ostreams, &pkt) < 0) {
1478
            fprintf(stderr, "Error while decoding stream #%d.%d\n",
1479
                    ist->file_index, ist->index);
1480
            av_free_packet(&pkt);
1481
            goto redo;
1482
        }
1483
        
1484
    discard_packet:
1485
        av_free_packet(&pkt);
1486
        
1487
        /* dump report by using the output first video and audio streams */
1488
        print_report(output_files, ost_table, nb_ostreams, 0);
1489
    }
1490

    
1491
    /* at the end of stream, we must flush the decoder buffers */
1492
    for(i=0;i<nb_istreams;i++) {
1493
        ist = ist_table[i];
1494
        if (ist->decoding_needed) {
1495
            output_packet(ist, i, ost_table, nb_ostreams, NULL);
1496
        }
1497
    }
1498

    
1499
    term_exit();
1500

    
1501
    /* dump report by using the first video and audio streams */
1502
    print_report(output_files, ost_table, nb_ostreams, 1);
1503

    
1504
    /* close each encoder */
1505
    for(i=0;i<nb_ostreams;i++) {
1506
        ost = ost_table[i];
1507
        if (ost->encoding_needed) {
1508
            av_freep(&ost->st->codec.stats_in);
1509
            avcodec_close(&ost->st->codec);
1510
        }
1511
    }
1512
    
1513
    /* close each decoder */
1514
    for(i=0;i<nb_istreams;i++) {
1515
        ist = ist_table[i];
1516
        if (ist->decoding_needed) {
1517
            avcodec_close(&ist->st->codec);
1518
        }
1519
    }
1520
    
1521

    
1522
    /* write the trailer if needed and close file */
1523
    for(i=0;i<nb_output_files;i++) {
1524
        os = output_files[i];
1525
        av_write_trailer(os);
1526
    }
1527
    /* finished ! */
1528
    
1529
    ret = 0;
1530
 fail1:
1531
    av_free(file_table);
1532

    
1533
    if (ist_table) {
1534
        for(i=0;i<nb_istreams;i++) {
1535
            ist = ist_table[i];
1536
            av_free(ist);
1537
        }
1538
        av_free(ist_table);
1539
    }
1540
    if (ost_table) {
1541
        for(i=0;i<nb_ostreams;i++) {
1542
            ost = ost_table[i];
1543
            if (ost) {
1544
                if (ost->logfile) {
1545
                    fclose(ost->logfile);
1546
                    ost->logfile = NULL;
1547
                }
1548
                fifo_free(&ost->fifo); /* works even if fifo is not
1549
                                          initialized but set to zero */
1550
                av_free(ost->pict_tmp.data[0]);
1551
                if (ost->video_resample)
1552
                    img_resample_close(ost->img_resample_ctx);
1553
                if (ost->audio_resample)
1554
                    audio_resample_close(ost->resample);
1555
                av_free(ost);
1556
            }
1557
        }
1558
        av_free(ost_table);
1559
    }
1560
    return ret;
1561
 fail:
1562
    ret = -ENOMEM;
1563
    goto fail1;
1564
}
1565

    
1566
#if 0
1567
int file_read(const char *filename)
1568
{
1569
    URLContext *h;
1570
    unsigned char buffer[1024];
1571
    int len, i;
1572

1573
    if (url_open(&h, filename, O_RDONLY) < 0) {
1574
        printf("could not open '%s'\n", filename);
1575
        return -1;
1576
    }
1577
    for(;;) {
1578
        len = url_read(h, buffer, sizeof(buffer));
1579
        if (len <= 0)
1580
            break;
1581
        for(i=0;i<len;i++) putchar(buffer[i]);
1582
    }
1583
    url_close(h);
1584
    return 0;
1585
}
1586
#endif
1587

    
1588
static void opt_image_format(const char *arg)
1589
{
1590
    AVImageFormat *f;
1591
    
1592
    for(f = first_image_format; f != NULL; f = f->next) {
1593
        if (!strcmp(arg, f->name))
1594
            break;
1595
    }
1596
    if (!f) {
1597
        fprintf(stderr, "Unknown image format: '%s'\n", arg);
1598
        exit(1);
1599
    }
1600
    image_format = f;
1601
}
1602

    
1603
static void opt_format(const char *arg)
1604
{
1605
    /* compatibility stuff for pgmyuv */
1606
    if (!strcmp(arg, "pgmyuv")) {
1607
        opt_image_format(arg);
1608
        arg = "image";
1609
    }
1610

    
1611
    file_iformat = av_find_input_format(arg);
1612
    file_oformat = guess_format(arg, NULL, NULL);
1613
    if (!file_iformat && !file_oformat) {
1614
        fprintf(stderr, "Unknown input or output format: %s\n", arg);
1615
        exit(1);
1616
    }
1617
}
1618

    
1619
static void opt_video_bitrate(const char *arg)
1620
{
1621
    video_bit_rate = atoi(arg) * 1000;
1622
}
1623

    
1624
static void opt_video_bitrate_tolerance(const char *arg)
1625
{
1626
    video_bit_rate_tolerance = atoi(arg) * 1000;
1627
}
1628

    
1629
static void opt_video_bitrate_max(const char *arg)
1630
{
1631
    video_rc_max_rate = atoi(arg) * 1000;
1632
}
1633

    
1634
static void opt_video_bitrate_min(const char *arg)
1635
{
1636
    video_rc_min_rate = atoi(arg) * 1000;
1637
}
1638

    
1639
static void opt_video_buffer_size(const char *arg)
1640
{
1641
    video_rc_buffer_size = atoi(arg) * 8*1024;
1642
}
1643

    
1644
static void opt_video_rc_eq(char *arg)
1645
{
1646
    video_rc_eq = arg;
1647
}
1648

    
1649
static void opt_video_rc_override_string(char *arg)
1650
{
1651
    video_rc_override_string = arg;
1652
}
1653

    
1654

    
1655
static void opt_workaround_bugs(const char *arg)
1656
{
1657
    workaround_bugs = atoi(arg);
1658
}
1659

    
1660
static void opt_dct_algo(const char *arg)
1661
{
1662
    dct_algo = atoi(arg);
1663
}
1664

    
1665
static void opt_idct_algo(const char *arg)
1666
{
1667
    idct_algo = atoi(arg);
1668
}
1669

    
1670

    
1671
static void opt_error_resilience(const char *arg)
1672
{
1673
    error_resilience = atoi(arg);
1674
}
1675

    
1676
static void opt_error_concealment(const char *arg)
1677
{
1678
    error_concealment = atoi(arg);
1679
}
1680

    
1681
static void opt_debug(const char *arg)
1682
{
1683
    debug = atoi(arg);
1684
}
1685

    
1686
static void opt_vismv(const char *arg)
1687
{
1688
    debug_mv = atoi(arg);
1689
}
1690
    
1691
static void opt_verbose(const char *arg)
1692
{
1693
    verbose = atoi(arg);
1694
}
1695

    
1696
static void opt_frame_rate(const char *arg)
1697
{
1698
    if (parse_frame_rate(&frame_rate, &frame_rate_base, arg) < 0) {
1699
        fprintf(stderr, "Incorrect frame rate\n");
1700
        exit(1);
1701
    }
1702
}
1703

    
1704
static void opt_frame_crop_top(const char *arg)
1705
{
1706
    frame_topBand = atoi(arg); 
1707
    if (frame_topBand < 0) {
1708
        fprintf(stderr, "Incorrect top crop size\n");
1709
        exit(1);
1710
    }
1711
    if ((frame_topBand % 2) != 0) {
1712
        fprintf(stderr, "Top crop size must be a multiple of 2\n");
1713
        exit(1);
1714
    }
1715
    if ((frame_topBand) >= frame_height){
1716
            fprintf(stderr, "Vertical crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
1717
        exit(1);
1718
    }
1719
    frame_height -= frame_topBand;
1720
}
1721

    
1722
static void opt_frame_crop_bottom(const char *arg)
1723
{
1724
    frame_bottomBand = atoi(arg);
1725
    if (frame_bottomBand < 0) {
1726
        fprintf(stderr, "Incorrect bottom crop size\n");
1727
        exit(1);
1728
    }
1729
    if ((frame_bottomBand % 2) != 0) {
1730
        fprintf(stderr, "Bottom crop size must be a multiple of 2\n");
1731
        exit(1);        
1732
    }
1733
    if ((frame_bottomBand) >= frame_height){
1734
            fprintf(stderr, "Vertical crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
1735
        exit(1);
1736
    }
1737
    frame_height -= frame_bottomBand;
1738
}
1739

    
1740
static void opt_frame_crop_left(const char *arg)
1741
{
1742
    frame_leftBand = atoi(arg);
1743
    if (frame_leftBand < 0) {
1744
        fprintf(stderr, "Incorrect left crop size\n");
1745
        exit(1);
1746
    }
1747
    if ((frame_leftBand % 2) != 0) {
1748
        fprintf(stderr, "Left crop size must be a multiple of 2\n");
1749
        exit(1);
1750
    }
1751
    if ((frame_leftBand) >= frame_width){
1752
            fprintf(stderr, "Horizontal crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
1753
        exit(1);
1754
    }
1755
    frame_width -= frame_leftBand;
1756
}
1757

    
1758
static void opt_frame_crop_right(const char *arg)
1759
{
1760
    frame_rightBand = atoi(arg);
1761
    if (frame_rightBand < 0) {
1762
        fprintf(stderr, "Incorrect right crop size\n");
1763
        exit(1);
1764
    }
1765
    if ((frame_rightBand % 2) != 0) {
1766
        fprintf(stderr, "Right crop size must be a multiple of 2\n");
1767
        exit(1);        
1768
    }
1769
    if ((frame_rightBand) >= frame_width){
1770
            fprintf(stderr, "Horizontal crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
1771
        exit(1);
1772
    }
1773
    frame_width -= frame_rightBand;
1774
}
1775

    
1776
static void opt_frame_size(const char *arg)
1777
{
1778
    if (parse_image_size(&frame_width, &frame_height, arg) < 0) {
1779
        fprintf(stderr, "Incorrect frame size\n");
1780
        exit(1);
1781
    }
1782
    if ((frame_width % 2) != 0 || (frame_height % 2) != 0) {
1783
        fprintf(stderr, "Frame size must be a multiple of 2\n");
1784
        exit(1);
1785
    }
1786
}
1787

    
1788
static void opt_frame_pix_fmt(const char *arg)
1789
{
1790
    frame_pix_fmt = avcodec_get_pix_fmt(arg);
1791
}
1792

    
1793
static void opt_frame_aspect_ratio(const char *arg)
1794
{
1795
    int x = 0, y = 0;
1796
    double ar = 0;
1797
    const char *p;
1798
    
1799
    p = strchr(arg, ':');
1800
    if (p) {
1801
        x = strtol(arg, (char **)&arg, 10);
1802
        if (arg == p)
1803
            y = strtol(arg+1, (char **)&arg, 10);
1804
        if (x > 0 && y > 0)
1805
            ar = (double)x / (double)y;
1806
    } else
1807
        ar = strtod(arg, (char **)&arg);
1808

    
1809
    if (!ar) {
1810
        fprintf(stderr, "Incorrect aspect ratio specification.\n");
1811
        exit(1);
1812
    }
1813
    frame_aspect_ratio = ar;
1814
}
1815

    
1816
static void opt_gop_size(const char *arg)
1817
{
1818
    gop_size = atoi(arg);
1819
}
1820

    
1821
static void opt_b_frames(const char *arg)
1822
{
1823
    b_frames = atoi(arg);
1824
    if (b_frames > FF_MAX_B_FRAMES) {
1825
        fprintf(stderr, "\nCannot have more than %d B frames, increase FF_MAX_B_FRAMES.\n", FF_MAX_B_FRAMES);
1826
        exit(1);
1827
    } else if (b_frames < 1) {
1828
        fprintf(stderr, "\nNumber of B frames must be higher than 0\n");
1829
        exit(1);
1830
    }
1831
}
1832

    
1833
static void opt_mb_decision(const char *arg)
1834
{
1835
    mb_decision = atoi(arg);
1836
}
1837

    
1838
static void opt_mb_cmp(const char *arg)
1839
{
1840
    mb_cmp = atoi(arg);
1841
}
1842

    
1843
static void opt_ildct_cmp(const char *arg)
1844
{
1845
    ildct_cmp = atoi(arg);
1846
}
1847

    
1848
static void opt_sub_cmp(const char *arg)
1849
{
1850
    sub_cmp = atoi(arg);
1851
}
1852

    
1853
static void opt_cmp(const char *arg)
1854
{
1855
    cmp = atoi(arg);
1856
}
1857

    
1858
static void opt_qscale(const char *arg)
1859
{
1860
    video_qscale = atof(arg);
1861
    if (video_qscale < 0.01 ||
1862
        video_qscale > 255) {
1863
        fprintf(stderr, "qscale must be >= 0.01 and <= 255\n");
1864
        exit(1);
1865
    }
1866
}
1867

    
1868
static void opt_qmin(const char *arg)
1869
{
1870
    video_qmin = atoi(arg);
1871
    if (video_qmin < 0 ||
1872
        video_qmin > 31) {
1873
        fprintf(stderr, "qmin must be >= 1 and <= 31\n");
1874
        exit(1);
1875
    }
1876
}
1877

    
1878
static void opt_qmax(const char *arg)
1879
{
1880
    video_qmax = atoi(arg);
1881
    if (video_qmax < 0 ||
1882
        video_qmax > 31) {
1883
        fprintf(stderr, "qmax must be >= 1 and <= 31\n");
1884
        exit(1);
1885
    }
1886
}
1887

    
1888
static void opt_mb_qmin(const char *arg)
1889
{
1890
    video_mb_qmin = atoi(arg);
1891
    if (video_mb_qmin < 0 ||
1892
        video_mb_qmin > 31) {
1893
        fprintf(stderr, "qmin must be >= 1 and <= 31\n");
1894
        exit(1);
1895
    }
1896
}
1897

    
1898
static void opt_mb_qmax(const char *arg)
1899
{
1900
    video_mb_qmax = atoi(arg);
1901
    if (video_mb_qmax < 0 ||
1902
        video_mb_qmax > 31) {
1903
        fprintf(stderr, "qmax must be >= 1 and <= 31\n");
1904
        exit(1);
1905
    }
1906
}
1907

    
1908
static void opt_qdiff(const char *arg)
1909
{
1910
    video_qdiff = atoi(arg);
1911
    if (video_qdiff < 0 ||
1912
        video_qdiff > 31) {
1913
        fprintf(stderr, "qdiff must be >= 1 and <= 31\n");
1914
        exit(1);
1915
    }
1916
}
1917

    
1918
static void opt_qblur(const char *arg)
1919
{
1920
    video_qblur = atof(arg);
1921
}
1922

    
1923
static void opt_qcomp(const char *arg)
1924
{
1925
    video_qcomp = atof(arg);
1926
}
1927

    
1928
static void opt_rc_initial_cplx(const char *arg)
1929
{
1930
    video_rc_initial_cplx = atof(arg);
1931
}
1932
static void opt_b_qfactor(const char *arg)
1933
{
1934
    video_b_qfactor = atof(arg);
1935
}
1936
static void opt_i_qfactor(const char *arg)
1937
{
1938
    video_i_qfactor = atof(arg);
1939
}
1940
static void opt_b_qoffset(const char *arg)
1941
{
1942
    video_b_qoffset = atof(arg);
1943
}
1944
static void opt_i_qoffset(const char *arg)
1945
{
1946
    video_i_qoffset = atof(arg);
1947
}
1948

    
1949
static void opt_ibias(const char *arg)
1950
{
1951
    video_intra_quant_bias = atoi(arg);
1952
}
1953
static void opt_pbias(const char *arg)
1954
{
1955
    video_inter_quant_bias = atoi(arg);
1956
}
1957

    
1958
static void opt_packet_size(const char *arg)
1959
{
1960
    packet_size= atoi(arg);
1961
}
1962

    
1963
static void opt_error_rate(const char *arg)
1964
{
1965
    error_rate= atoi(arg);
1966
}
1967

    
1968
static void opt_strict(const char *arg)
1969
{
1970
    strict= atoi(arg);
1971
}
1972

    
1973
static void opt_top_field_first(const char *arg)
1974
{
1975
    top_field_first= atoi(arg);
1976
}
1977

    
1978
static void opt_noise_reduction(const char *arg)
1979
{
1980
    noise_reduction= atoi(arg);
1981
}
1982

    
1983
static void opt_qns(const char *arg)
1984
{
1985
    qns= atoi(arg);
1986
}
1987

    
1988
static void opt_sc_threshold(const char *arg)
1989
{
1990
    sc_threshold= atoi(arg);
1991
}
1992

    
1993
static void opt_audio_bitrate(const char *arg)
1994
{
1995
    audio_bit_rate = atoi(arg) * 1000;
1996
}
1997

    
1998
static void opt_audio_rate(const char *arg)
1999
{
2000
    audio_sample_rate = atoi(arg);
2001
}
2002

    
2003
static void opt_audio_channels(const char *arg)
2004
{
2005
    audio_channels = atoi(arg);
2006
}
2007

    
2008
static void opt_video_device(const char *arg)
2009
{
2010
    video_device = av_strdup(arg);
2011
}
2012

    
2013
static void opt_video_channel(const char *arg)
2014
{
2015
    video_channel = strtol(arg, NULL, 0);
2016
}
2017

    
2018
static void opt_video_standard(const char *arg)
2019
{
2020
    video_standard = av_strdup(arg);
2021
}
2022

    
2023
static void opt_audio_device(const char *arg)
2024
{
2025
    audio_device = av_strdup(arg);
2026
}
2027

    
2028
static void opt_dv1394(const char *arg)
2029
{
2030
    video_grab_format = "dv1394";
2031
    audio_grab_format = NULL;
2032
}
2033

    
2034
static void opt_audio_codec(const char *arg)
2035
{
2036
    AVCodec *p;
2037

    
2038
    if (!strcmp(arg, "copy")) {
2039
        audio_stream_copy = 1;
2040
    } else {
2041
        p = first_avcodec;
2042
        while (p) {
2043
            if (!strcmp(p->name, arg) && p->type == CODEC_TYPE_AUDIO)
2044
                break;
2045
            p = p->next;
2046
        }
2047
        if (p == NULL) {
2048
            fprintf(stderr, "Unknown audio codec '%s'\n", arg);
2049
            exit(1);
2050
        } else {
2051
            audio_codec_id = p->id;
2052
        }
2053
    }
2054
}
2055

    
2056
static void add_frame_hooker(const char *arg)
2057
{
2058
    int argc = 0;
2059
    char *argv[64];
2060
    int i;
2061
    char *args = av_strdup(arg);
2062

    
2063
    using_vhook = 1;
2064

    
2065
    argv[0] = strtok(args, " ");
2066
    while (argc < 62 && (argv[++argc] = strtok(NULL, " "))) {
2067
    }
2068

    
2069
    i = frame_hook_add(argc, argv);
2070

    
2071
    if (i != 0) {
2072
        fprintf(stderr, "Failed to add video hook function: %s\n", arg);
2073
        exit(1);
2074
    }
2075
}
2076

    
2077
const char *motion_str[] = {
2078
    "zero",
2079
    "full",
2080
    "log",
2081
    "phods",
2082
    "epzs",
2083
    "x1",
2084
    NULL,
2085
};
2086

    
2087
static void opt_motion_estimation(const char *arg)
2088
{
2089
    const char **p;
2090
    p = motion_str;
2091
    for(;;) {
2092
        if (!*p) {
2093
            fprintf(stderr, "Unknown motion estimation method '%s'\n", arg);
2094
            exit(1);
2095
        }
2096
        if (!strcmp(*p, arg))
2097
            break;
2098
        p++;
2099
    }
2100
    me_method = (p - motion_str) + 1;
2101
}
2102

    
2103
static void opt_video_codec(const char *arg)
2104
{
2105
    AVCodec *p;
2106

    
2107
    if (!strcmp(arg, "copy")) {
2108
        video_stream_copy = 1;
2109
    } else {
2110
        p = first_avcodec;
2111
        while (p) {
2112
            if (!strcmp(p->name, arg) && p->type == CODEC_TYPE_VIDEO)
2113
                break;
2114
            p = p->next;
2115
        }
2116
        if (p == NULL) {
2117
            fprintf(stderr, "Unknown video codec '%s'\n", arg);
2118
            exit(1);
2119
        } else {
2120
            video_codec_id = p->id;
2121
        }
2122
    }
2123
}
2124

    
2125
static void opt_map(const char *arg)
2126
{
2127
    AVStreamMap *m;
2128
    const char *p;
2129

    
2130
    p = arg;
2131
    m = &stream_maps[nb_stream_maps++];
2132

    
2133
    m->file_index = strtol(arg, (char **)&p, 0);
2134
    if (*p)
2135
        p++;
2136

    
2137
    m->stream_index = strtol(p, (char **)&p, 0);
2138
}
2139

    
2140
static void opt_recording_time(const char *arg)
2141
{
2142
    recording_time = parse_date(arg, 1);
2143
}
2144

    
2145
static void opt_start_time(const char *arg)
2146
{
2147
    start_time = parse_date(arg, 1);
2148
}
2149

    
2150
static void opt_input_file(const char *filename)
2151
{
2152
    AVFormatContext *ic;
2153
    AVFormatParameters params, *ap = &params;
2154
    int err, i, ret, rfps, rfps_base;
2155

    
2156
    if (!strcmp(filename, "-"))
2157
        filename = "pipe:";
2158

    
2159
    using_stdin |= !strcmp(filename, "pipe:" ) || 
2160
                   !strcmp( filename, "/dev/stdin" );
2161

    
2162
    /* get default parameters from command line */
2163
    memset(ap, 0, sizeof(*ap));
2164
    ap->sample_rate = audio_sample_rate;
2165
    ap->channels = audio_channels;
2166
    ap->frame_rate = frame_rate;
2167
    ap->frame_rate_base = frame_rate_base;
2168
    ap->width = frame_width;
2169
    ap->height = frame_height;
2170
    ap->image_format = image_format;
2171
    ap->pix_fmt = frame_pix_fmt;
2172

    
2173
    /* open the input file with generic libav function */
2174
    err = av_open_input_file(&ic, filename, file_iformat, 0, ap);
2175
    if (err < 0) {
2176
        print_error(filename, err);
2177
        exit(1);
2178
    }
2179
    
2180
    /* If not enough info to get the stream parameters, we decode the
2181
       first frames to get it. (used in mpeg case for example) */
2182
    ret = av_find_stream_info(ic);
2183
    if (ret < 0) {
2184
        fprintf(stderr, "%s: could not find codec parameters\n", filename);
2185
        exit(1);
2186
    }
2187

    
2188
    /* if seeking requested, we execute it */
2189
    if (start_time != 0) {
2190
        int64_t timestamp;
2191

    
2192
        timestamp = start_time;
2193
        /* add the stream start time */
2194
        if (ic->start_time != AV_NOPTS_VALUE)
2195
            timestamp += ic->start_time;
2196
        ret = av_seek_frame(ic, -1, timestamp);
2197
        if (ret < 0) {
2198
            fprintf(stderr, "%s: could not seek to position %0.3f\n", 
2199
                    filename, (double)timestamp / AV_TIME_BASE);
2200
        }
2201
        /* reset seek info */
2202
        start_time = 0;
2203
    }
2204

    
2205
    /* update the current parameters so that they match the one of the input stream */
2206
    for(i=0;i<ic->nb_streams;i++) {
2207
        AVCodecContext *enc = &ic->streams[i]->codec;
2208
        switch(enc->codec_type) {
2209
        case CODEC_TYPE_AUDIO:
2210
            //fprintf(stderr, "\nInput Audio channels: %d", enc->channels);
2211
            audio_channels = enc->channels;
2212
            audio_sample_rate = enc->sample_rate;
2213
            break;
2214
        case CODEC_TYPE_VIDEO:
2215
            frame_height = enc->height;
2216
            frame_width = enc->width;
2217
            frame_aspect_ratio = av_q2d(enc->sample_aspect_ratio) * enc->width / enc->height;
2218
            frame_pix_fmt = enc->pix_fmt;
2219
            rfps      = ic->streams[i]->r_frame_rate;
2220
            rfps_base = ic->streams[i]->r_frame_rate_base;
2221
            enc->workaround_bugs = workaround_bugs;
2222
            enc->error_resilience = error_resilience; 
2223
            enc->error_concealment = error_concealment; 
2224
            enc->idct_algo = idct_algo;
2225
            enc->debug = debug;
2226
            enc->debug_mv = debug_mv;            
2227
            if(bitexact)
2228
                enc->flags|= CODEC_FLAG_BITEXACT;
2229

    
2230
            assert(enc->frame_rate_base == rfps_base); // should be true for now
2231
            if (enc->frame_rate != rfps) { 
2232
                fprintf(stderr,"\nSeems that stream %d comes from film source: %2.2f->%2.2f\n",
2233
                    i, (float)enc->frame_rate / enc->frame_rate_base,
2234
                    (float)rfps / rfps_base);
2235
            }
2236
            /* update the current frame rate to match the stream frame rate */
2237
            frame_rate      = rfps;
2238
            frame_rate_base = rfps_base;
2239

    
2240
            enc->rate_emu = rate_emu;
2241
            break;
2242
        case CODEC_TYPE_DATA:
2243
            break;
2244
        default:
2245
            av_abort();
2246
        }
2247
    }
2248
    
2249
    input_files[nb_input_files] = ic;
2250
    /* dump the file content */
2251
    dump_format(ic, nb_input_files, filename, 0);
2252
    nb_input_files++;
2253
    file_iformat = NULL;
2254
    file_oformat = NULL;
2255
    image_format = NULL;
2256

    
2257
    rate_emu = 0;
2258
}
2259

    
2260
static void check_audio_video_inputs(int *has_video_ptr, int *has_audio_ptr)
2261
{
2262
    int has_video, has_audio, i, j;
2263
    AVFormatContext *ic;
2264

    
2265
    has_video = 0;
2266
    has_audio = 0;
2267
    for(j=0;j<nb_input_files;j++) {
2268
        ic = input_files[j];
2269
        for(i=0;i<ic->nb_streams;i++) {
2270
            AVCodecContext *enc = &ic->streams[i]->codec;
2271
            switch(enc->codec_type) {
2272
            case CODEC_TYPE_AUDIO:
2273
                has_audio = 1;
2274
                break;
2275
            case CODEC_TYPE_VIDEO:
2276
                has_video = 1;
2277
                break;
2278
            default:
2279
                av_abort();
2280
            }
2281
        }
2282
    }
2283
    *has_video_ptr = has_video;
2284
    *has_audio_ptr = has_audio;
2285
}
2286

    
2287
static void opt_output_file(const char *filename)
2288
{
2289
    AVStream *st;
2290
    AVFormatContext *oc;
2291
    int use_video, use_audio, nb_streams, input_has_video, input_has_audio;
2292
    int codec_id;
2293
    AVFormatParameters params, *ap = &params;
2294

    
2295
    if (!strcmp(filename, "-"))
2296
        filename = "pipe:";
2297

    
2298
    oc = av_mallocz(sizeof(AVFormatContext));
2299

    
2300
    if (!file_oformat) {
2301
        file_oformat = guess_format(NULL, filename, NULL);
2302
        if (!file_oformat) {
2303
            fprintf(stderr, "Unable for find a suitable output format for '%s'\n",
2304
                    filename);
2305
            exit(1);
2306
        }
2307
    }
2308
    
2309
    oc->oformat = file_oformat;
2310

    
2311
    if (!strcmp(file_oformat->name, "ffm") && 
2312
        strstart(filename, "http:", NULL)) {
2313
        /* special case for files sent to ffserver: we get the stream
2314
           parameters from ffserver */
2315
        if (read_ffserver_streams(oc, filename) < 0) {
2316
            fprintf(stderr, "Could not read stream parameters from '%s'\n", filename);
2317
            exit(1);
2318
        }
2319
    } else {
2320
        use_video = file_oformat->video_codec != CODEC_ID_NONE;
2321
        use_audio = file_oformat->audio_codec != CODEC_ID_NONE;
2322

    
2323
        /* disable if no corresponding type found and at least one
2324
           input file */
2325
        if (nb_input_files > 0) {
2326
            check_audio_video_inputs(&input_has_video, &input_has_audio);
2327
            if (!input_has_video)
2328
                use_video = 0;
2329
            if (!input_has_audio)
2330
                use_audio = 0;
2331
        }
2332

    
2333
        /* manual disable */
2334
        if (audio_disable) {
2335
            use_audio = 0;
2336
        }
2337
        if (video_disable) {
2338
            use_video = 0;
2339
        }
2340
        
2341
        nb_streams = 0;
2342
        if (use_video) {
2343
            AVCodecContext *video_enc;
2344
            
2345
            st = av_mallocz(sizeof(AVStream));
2346
            if (!st) {
2347
                fprintf(stderr, "Could not alloc stream\n");
2348
                exit(1);
2349
            }
2350
            avcodec_get_context_defaults(&st->codec);
2351

    
2352
            video_enc = &st->codec;
2353
            
2354
            if(!strcmp(file_oformat->name, "mp4") || !strcmp(file_oformat->name, "mov") || !strcmp(file_oformat->name, "3gp"))
2355
                video_enc->flags |= CODEC_FLAG_GLOBAL_HEADER;
2356
            if (video_stream_copy) {
2357
                st->stream_copy = 1;
2358
                video_enc->codec_type = CODEC_TYPE_VIDEO;
2359
            } else {
2360
                char *p;
2361
                int i;
2362
            
2363
                codec_id = file_oformat->video_codec;
2364
                if (video_codec_id != CODEC_ID_NONE)
2365
                    codec_id = video_codec_id;
2366
                
2367
                video_enc->codec_id = codec_id;
2368
                
2369
                video_enc->bit_rate = video_bit_rate;
2370
                video_enc->bit_rate_tolerance = video_bit_rate_tolerance;
2371
                video_enc->frame_rate = frame_rate; 
2372
                video_enc->frame_rate_base = frame_rate_base; 
2373
                
2374
                video_enc->width = frame_width;
2375
                video_enc->height = frame_height;
2376
                video_enc->sample_aspect_ratio = av_d2q(frame_aspect_ratio*frame_height/frame_width, 255);
2377
                video_enc->pix_fmt = frame_pix_fmt;
2378

    
2379
                if (!intra_only)
2380
                    video_enc->gop_size = gop_size;
2381
                else
2382
                    video_enc->gop_size = 0;
2383
                if (video_qscale || same_quality) {
2384
                    video_enc->flags |= CODEC_FLAG_QSCALE;
2385
                    st->quality = FF_QP2LAMBDA * video_qscale;
2386
                }
2387

    
2388
                if(intra_matrix)
2389
                    video_enc->intra_matrix = intra_matrix;
2390
                if(inter_matrix)
2391
                    video_enc->inter_matrix = inter_matrix;
2392

    
2393
                if(bitexact)
2394
                    video_enc->flags |= CODEC_FLAG_BITEXACT;
2395

    
2396
                video_enc->mb_decision = mb_decision;
2397
                video_enc->mb_cmp = mb_cmp;
2398
                video_enc->ildct_cmp = ildct_cmp;
2399
                video_enc->me_sub_cmp = sub_cmp;
2400
                video_enc->me_cmp = cmp;
2401
                video_enc->quantizer_noise_shaping= qns;
2402
                
2403
                if (use_umv) {
2404
                    video_enc->flags |= CODEC_FLAG_H263P_UMV;
2405
                }
2406
                   if (use_aic) {
2407
                    video_enc->flags |= CODEC_FLAG_H263P_AIC;
2408
                }
2409
                   if (use_aiv) {
2410
                    video_enc->flags |= CODEC_FLAG_H263P_AIV;
2411
                }
2412
                if (use_4mv) {
2413
                    video_enc->flags |= CODEC_FLAG_4MV;
2414
                }
2415
                if (use_obmc) {
2416
                    video_enc->flags |= CODEC_FLAG_OBMC;
2417
                }
2418
            
2419
                if(use_part) {
2420
                    video_enc->flags |= CODEC_FLAG_PART;
2421
                }
2422
                   if (use_alt_scan) {
2423
                    video_enc->flags |= CODEC_FLAG_ALT_SCAN;
2424
                }
2425
                   if (use_trell) {
2426
                    video_enc->flags |= CODEC_FLAG_TRELLIS_QUANT;
2427
                }
2428
                   if (use_scan_offset) {
2429
                    video_enc->flags |= CODEC_FLAG_SVCD_SCAN_OFFSET;
2430
                }
2431
                   if (closed_gop) {
2432
                    video_enc->flags |= CODEC_FLAG_CLOSED_GOP;
2433
                }
2434
                if (b_frames) {
2435
                    video_enc->max_b_frames = b_frames;
2436
                    video_enc->b_frame_strategy = 0;
2437
                    video_enc->b_quant_factor = 2.0;
2438
                }
2439
                if (do_interlace_dct) {
2440
                    video_enc->flags |= CODEC_FLAG_INTERLACED_DCT;
2441
                }
2442
                if (do_interlace_me) {
2443
                    video_enc->flags |= CODEC_FLAG_INTERLACED_ME;
2444
                }
2445
                video_enc->qmin = video_qmin;
2446
                video_enc->qmax = video_qmax;
2447
                video_enc->mb_qmin = video_mb_qmin;
2448
                video_enc->mb_qmax = video_mb_qmax;
2449
                video_enc->max_qdiff = video_qdiff;
2450
                video_enc->qblur = video_qblur;
2451
                video_enc->qcompress = video_qcomp;
2452
                video_enc->rc_eq = video_rc_eq;
2453
                video_enc->debug = debug;
2454
                video_enc->debug_mv = debug_mv;                
2455
                p= video_rc_override_string;
2456
                for(i=0; p; i++){
2457
                    int start, end, q;
2458
                    int e=sscanf(p, "%d,%d,%d", &start, &end, &q);
2459
                    if(e!=3){
2460
                        fprintf(stderr, "error parsing rc_override\n");
2461
                        exit(1);
2462
                    }
2463
                    video_enc->rc_override= 
2464
                        av_realloc(video_enc->rc_override, 
2465
                                   sizeof(RcOverride)*(i+1));
2466
                    video_enc->rc_override[i].start_frame= start;
2467
                    video_enc->rc_override[i].end_frame  = end;
2468
                    if(q>0){
2469
                        video_enc->rc_override[i].qscale= q;
2470
                        video_enc->rc_override[i].quality_factor= 1.0;
2471
                    }
2472
                    else{
2473
                        video_enc->rc_override[i].qscale= 0;
2474
                        video_enc->rc_override[i].quality_factor= -q/100.0;
2475
                    }
2476
                    p= strchr(p, '/');
2477
                    if(p) p++;
2478
                }
2479
                video_enc->rc_override_count=i;
2480

    
2481
                video_enc->rc_max_rate = video_rc_max_rate;
2482
                video_enc->rc_min_rate = video_rc_min_rate;
2483
                video_enc->rc_buffer_size = video_rc_buffer_size;
2484
                video_enc->rc_buffer_aggressivity= video_rc_buffer_aggressivity;
2485
                video_enc->rc_initial_cplx= video_rc_initial_cplx;
2486
                video_enc->i_quant_factor = video_i_qfactor;
2487
                video_enc->b_quant_factor = video_b_qfactor;
2488
                video_enc->i_quant_offset = video_i_qoffset;
2489
                video_enc->b_quant_offset = video_b_qoffset;
2490
                video_enc->intra_quant_bias = video_intra_quant_bias;
2491
                video_enc->inter_quant_bias = video_inter_quant_bias;
2492
                video_enc->dct_algo = dct_algo;
2493
                video_enc->idct_algo = idct_algo;
2494
                video_enc->strict_std_compliance = strict;
2495
                video_enc->error_rate = error_rate;
2496
                video_enc->noise_reduction= noise_reduction;
2497
                video_enc->scenechange_threshold= sc_threshold;
2498
                if(packet_size){
2499
                    video_enc->rtp_mode= 1;
2500
                    video_enc->rtp_payload_size= packet_size;
2501
                }
2502
            
2503
                if (do_psnr)
2504
                    video_enc->flags|= CODEC_FLAG_PSNR;
2505
            
2506
                video_enc->me_method = me_method;
2507

    
2508
                /* two pass mode */
2509
                if (do_pass) {
2510
                    if (do_pass == 1) {
2511
                        video_enc->flags |= CODEC_FLAG_PASS1;
2512
                    } else {
2513
                        video_enc->flags |= CODEC_FLAG_PASS2;
2514
                    }
2515
                }
2516
            }
2517
            oc->streams[nb_streams] = st;
2518
            nb_streams++;
2519
        }
2520
    
2521
        if (use_audio) {
2522
            AVCodecContext *audio_enc;
2523

    
2524
            st = av_mallocz(sizeof(AVStream));
2525
            if (!st) {
2526
                fprintf(stderr, "Could not alloc stream\n");
2527
                exit(1);
2528
            }
2529
            avcodec_get_context_defaults(&st->codec);
2530

    
2531
            audio_enc = &st->codec;
2532
            audio_enc->codec_type = CODEC_TYPE_AUDIO;
2533

    
2534
            if(!strcmp(file_oformat->name, "mp4") || !strcmp(file_oformat->name, "mov") || !strcmp(file_oformat->name, "3gp"))
2535
                audio_enc->flags |= CODEC_FLAG_GLOBAL_HEADER;
2536
            if (audio_stream_copy) {
2537
                st->stream_copy = 1;
2538
            } else {
2539
                codec_id = file_oformat->audio_codec;
2540
                if (audio_codec_id != CODEC_ID_NONE)
2541
                    codec_id = audio_codec_id;
2542
                audio_enc->codec_id = codec_id;
2543
                
2544
                audio_enc->bit_rate = audio_bit_rate;
2545
                audio_enc->sample_rate = audio_sample_rate;
2546
                audio_enc->strict_std_compliance = strict;
2547
                /* For audio codecs other than AC3 we limit */
2548
                /* the number of coded channels to stereo   */
2549
                if (audio_channels > 2 && codec_id != CODEC_ID_AC3) {
2550
                    audio_enc->channels = 2;
2551
                } else
2552
                    audio_enc->channels = audio_channels;
2553
            }
2554
            oc->streams[nb_streams] = st;
2555
            nb_streams++;
2556
        }
2557

    
2558
        oc->nb_streams = nb_streams;
2559

    
2560
        if (!nb_streams) {
2561
            fprintf(stderr, "No audio or video streams available\n");
2562
            exit(1);
2563
        }
2564

    
2565
        if (str_title)
2566
            pstrcpy(oc->title, sizeof(oc->title), str_title);
2567
        if (str_author)
2568
            pstrcpy(oc->author, sizeof(oc->author), str_author);
2569
        if (str_copyright)
2570
            pstrcpy(oc->copyright, sizeof(oc->copyright), str_copyright);
2571
        if (str_comment)
2572
            pstrcpy(oc->comment, sizeof(oc->comment), str_comment);
2573
    }
2574

    
2575
    output_files[nb_output_files++] = oc;
2576

    
2577
    strcpy(oc->filename, filename);
2578

    
2579
    /* check filename in case of an image number is expected */
2580
    if (oc->oformat->flags & AVFMT_NEEDNUMBER) {
2581
        if (filename_number_test(oc->filename) < 0) {
2582
            print_error(oc->filename, AVERROR_NUMEXPECTED);
2583
            exit(1);
2584
        }
2585
    }
2586

    
2587
    if (!(oc->oformat->flags & AVFMT_NOFILE)) {
2588
        /* test if it already exists to avoid loosing precious files */
2589
        if (!file_overwrite && 
2590
            (strchr(filename, ':') == NULL ||
2591
             strstart(filename, "file:", NULL))) {
2592
            if (url_exist(filename)) {
2593
                int c;
2594
                
2595
                if ( !using_stdin ) {
2596
                    fprintf(stderr,"File '%s' already exists. Overwrite ? [y/N] ", filename);
2597
                    fflush(stderr);
2598
                    c = getchar();
2599
                    if (toupper(c) != 'Y') {
2600
                        fprintf(stderr, "Not overwriting - exiting\n");
2601
                        exit(1);
2602
                    }
2603
                                }
2604
                                else {
2605
                    fprintf(stderr,"File '%s' already exists. Exiting.\n", filename);
2606
                    exit(1);
2607
                                }
2608
            }
2609
        }
2610
        
2611
        /* open the file */
2612
        if (url_fopen(&oc->pb, filename, URL_WRONLY) < 0) {
2613
            fprintf(stderr, "Could not open '%s'\n", filename);
2614
            exit(1);
2615
        }
2616
    }
2617

    
2618
    memset(ap, 0, sizeof(*ap));
2619
    ap->image_format = image_format;
2620
    if (av_set_parameters(oc, ap) < 0) {
2621
        fprintf(stderr, "%s: Invalid encoding parameters\n",
2622
                oc->filename);
2623
        exit(1);
2624
    }
2625

    
2626
    /* reset some options */
2627
    file_oformat = NULL;
2628
    file_iformat = NULL;
2629
    image_format = NULL;
2630
    audio_disable = 0;
2631
    video_disable = 0;
2632
    audio_codec_id = CODEC_ID_NONE;
2633
    video_codec_id = CODEC_ID_NONE;
2634
    audio_stream_copy = 0;
2635
    video_stream_copy = 0;
2636
}
2637

    
2638
/* prepare dummy protocols for grab */
2639
static void prepare_grab(void)
2640
{
2641
    int has_video, has_audio, i, j;
2642
    AVFormatContext *oc;
2643
    AVFormatContext *ic;
2644
    AVFormatParameters vp1, *vp = &vp1;
2645
    AVFormatParameters ap1, *ap = &ap1;
2646
    
2647
    /* see if audio/video inputs are needed */
2648
    has_video = 0;
2649
    has_audio = 0;
2650
    memset(ap, 0, sizeof(*ap));
2651
    memset(vp, 0, sizeof(*vp));
2652
    for(j=0;j<nb_output_files;j++) {
2653
        oc = output_files[j];
2654
        for(i=0;i<oc->nb_streams;i++) {
2655
            AVCodecContext *enc = &oc->streams[i]->codec;
2656
            switch(enc->codec_type) {
2657
            case CODEC_TYPE_AUDIO:
2658
                if (enc->sample_rate > ap->sample_rate)
2659
                    ap->sample_rate = enc->sample_rate;
2660
                if (enc->channels > ap->channels)
2661
                    ap->channels = enc->channels;
2662
                has_audio = 1;
2663
                break;
2664
            case CODEC_TYPE_VIDEO:
2665
                if (enc->width > vp->width)
2666
                    vp->width = enc->width;
2667
                if (enc->height > vp->height)
2668
                    vp->height = enc->height;
2669
                
2670
                assert(enc->frame_rate_base == DEFAULT_FRAME_RATE_BASE);
2671
                if (enc->frame_rate > vp->frame_rate){
2672
                    vp->frame_rate      = enc->frame_rate;
2673
                    vp->frame_rate_base = enc->frame_rate_base;
2674
                }
2675
                has_video = 1;
2676
                break;
2677
            default:
2678
                av_abort();
2679
            }
2680
        }
2681
    }
2682
    
2683
    if (has_video == 0 && has_audio == 0) {
2684
        fprintf(stderr, "Output file must have at least one audio or video stream\n");
2685
        exit(1);
2686
    }
2687
    
2688
    if (has_video) {
2689
        AVInputFormat *fmt1;
2690
        fmt1 = av_find_input_format(video_grab_format);
2691
        vp->device  = video_device;
2692
        vp->channel = video_channel;
2693
        vp->standard = video_standard;
2694
        if (av_open_input_file(&ic, "", fmt1, 0, vp) < 0) {
2695
            fprintf(stderr, "Could not find video grab device\n");
2696
            exit(1);
2697
        }
2698
        /* If not enough info to get the stream parameters, we decode the
2699
           first frames to get it. */
2700
        if ((ic->ctx_flags & AVFMTCTX_NOHEADER) && av_find_stream_info(ic) < 0) {
2701
            fprintf(stderr, "Could not find video grab parameters\n");
2702
            exit(1);
2703
        }
2704
        /* by now video grab has one stream */
2705
        ic->streams[0]->r_frame_rate      = vp->frame_rate;
2706
        ic->streams[0]->r_frame_rate_base = vp->frame_rate_base;
2707
        input_files[nb_input_files] = ic;
2708
        dump_format(ic, nb_input_files, "", 0);
2709
        nb_input_files++;
2710
    }
2711
    if (has_audio && audio_grab_format) {
2712
        AVInputFormat *fmt1;
2713
        fmt1 = av_find_input_format(audio_grab_format);
2714
        ap->device = audio_device;
2715
        if (av_open_input_file(&ic, "", fmt1, 0, ap) < 0) {
2716
            fprintf(stderr, "Could not find audio grab device\n");
2717
            exit(1);
2718
        }
2719
        input_files[nb_input_files] = ic;
2720
        dump_format(ic, nb_input_files, "", 0);
2721
        nb_input_files++;
2722
    }
2723
}
2724

    
2725
/* same option as mencoder */
2726
static void opt_pass(const char *pass_str)
2727
{
2728
    int pass;
2729
    pass = atoi(pass_str);
2730
    if (pass != 1 && pass != 2) {
2731
        fprintf(stderr, "pass number can be only 1 or 2\n");
2732
        exit(1);
2733
    }
2734
    do_pass = pass;
2735
}
2736

    
2737
#if defined(CONFIG_WIN32) || defined(CONFIG_OS2)
2738
static int64_t getutime(void)
2739
{
2740
  return av_gettime();
2741
}
2742
#else
2743
static int64_t getutime(void)
2744
{
2745
    struct rusage rusage;
2746

    
2747
    getrusage(RUSAGE_SELF, &rusage);
2748
    return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
2749
}
2750
#endif
2751

    
2752
extern int ffm_nopts;
2753

    
2754
static void opt_bitexact(void)
2755
{
2756
    bitexact=1;
2757
    /* disable generate of real time pts in ffm (need to be supressed anyway) */
2758
    ffm_nopts = 1;
2759
}
2760

    
2761
static void show_formats(void)
2762
{
2763
    AVInputFormat *ifmt;
2764
    AVOutputFormat *ofmt;
2765
    AVImageFormat *image_fmt;
2766
    URLProtocol *up;
2767
    AVCodec *p;
2768
    const char **pp;
2769

    
2770
    printf("Output audio/video file formats:");
2771
    for(ofmt = first_oformat; ofmt != NULL; ofmt = ofmt->next) {
2772
        printf(" %s", ofmt->name);
2773
    }
2774
    printf("\n");
2775

    
2776
    printf("Input audio/video file formats:");
2777
    for(ifmt = first_iformat; ifmt != NULL; ifmt = ifmt->next) {
2778
        printf(" %s", ifmt->name);
2779
    }
2780
    printf("\n");
2781

    
2782
    printf("Output image formats:");
2783
    for(image_fmt = first_image_format; image_fmt != NULL; 
2784
        image_fmt = image_fmt->next) {
2785
        if (image_fmt->img_write)
2786
            printf(" %s", image_fmt->name);
2787
    }
2788
    printf("\n");
2789

    
2790
    printf("Input image formats:");
2791
    for(image_fmt = first_image_format; image_fmt != NULL; 
2792
        image_fmt = image_fmt->next) {
2793
        if (image_fmt->img_read)
2794
            printf(" %s", image_fmt->name);
2795
    }
2796
    printf("\n");
2797

    
2798
    printf("Codecs:\n");
2799
    printf("  Encoders:");
2800
    for(p = first_avcodec; p != NULL; p = p->next) {
2801
        if (p->encode)
2802
            printf(" %s", p->name);
2803
    }
2804
    printf("\n");
2805

    
2806
    printf("  Decoders:");
2807
    for(p = first_avcodec; p != NULL; p = p->next) {
2808
        if (p->decode)
2809
            printf(" %s", p->name);
2810
    }
2811
    printf("\n");
2812

    
2813
    printf("Supported file protocols:");
2814
    for(up = first_protocol; up != NULL; up = up->next)
2815
        printf(" %s:", up->name);
2816
    printf("\n");
2817
    
2818
    printf("Frame size, frame rate abbreviations: ntsc pal qntsc qpal sntsc spal film ntsc-film sqcif qcif cif 4cif\n");
2819
    printf("Motion estimation methods:");
2820
    pp = motion_str;
2821
    while (*pp) {
2822
        printf(" %s", *pp);
2823
        if ((pp - motion_str + 1) == ME_ZERO) 
2824
            printf("(fastest)");
2825
        else if ((pp - motion_str + 1) == ME_FULL) 
2826
            printf("(slowest)");
2827
        else if ((pp - motion_str + 1) == ME_EPZS) 
2828
            printf("(default)");
2829
        pp++;
2830
    }
2831
    printf("\n");
2832
    exit(1);
2833
}
2834

    
2835
void parse_matrix_coeffs(uint16_t *dest, const char *str)
2836
{
2837
    int i;
2838
    const char *p = str;
2839
    for(i = 0;; i++) {
2840
        dest[i] = atoi(p);
2841
        if(i == 63)
2842
            break;
2843
        p = strchr(p, ',');
2844
        if(!p) {
2845
            fprintf(stderr, "Syntax error in matrix \"%s\" at coeff %d\n", str, i);
2846
            exit(1);
2847
        }
2848
        p++;
2849
    }
2850
}
2851

    
2852
void opt_inter_matrix(const char *arg)
2853
{
2854
    inter_matrix = av_mallocz(sizeof(uint16_t) * 64);
2855
    parse_matrix_coeffs(inter_matrix, arg);
2856
}
2857

    
2858
void opt_intra_matrix(const char *arg)
2859
{
2860
    intra_matrix = av_mallocz(sizeof(uint16_t) * 64);
2861
    parse_matrix_coeffs(intra_matrix, arg);
2862
}
2863

    
2864
static void opt_target(const char *arg)
2865
{
2866
    int norm = -1;
2867

    
2868
    if(!strncmp(arg, "pal-", 4)) {
2869
        norm = 0;
2870
        arg += 4;
2871
    } else if(!strncmp(arg, "ntsc-", 5)) {
2872
        norm = 1;
2873
        arg += 5;
2874
    } else {
2875
        int fr;
2876
        /* Calculate FR via float to avoid int overflow */
2877
        fr = (int)(frame_rate * 1000.0 / frame_rate_base);
2878
        if(fr == 25000) {
2879
            norm = 0;
2880
        } else if((fr == 29970) || (fr == 23976)) {
2881
            norm = 1;
2882
        } else {
2883
            /* Try to determine PAL/NTSC by peeking in the input files */
2884
            if(nb_input_files) {
2885
                int i, j;
2886
                for(j = 0; j < nb_input_files; j++) {
2887
                    for(i = 0; i < input_files[j]->nb_streams; i++) {
2888
                        AVCodecContext *c = &input_files[j]->streams[i]->codec;
2889
                        if(c->codec_type != CODEC_TYPE_VIDEO)
2890
                            continue;
2891
                        fr = c->frame_rate * 1000 / c->frame_rate_base;
2892
                        if(fr == 25000) {
2893
                            norm = 0;
2894
                            break;
2895
                        } else if((fr == 29970) || (fr == 23976)) {
2896
                            norm = 1;
2897
                            break;
2898
                        }
2899
                    }
2900
                    if(norm >= 0)
2901
                        break;
2902
                }
2903
            }
2904
        }
2905
        if(verbose && norm >= 0)
2906
            printf("Assuming %s for target.\n", norm ? "NTSC" : "PAL");
2907
    }
2908

    
2909
    if(norm < 0) {
2910
        fprintf(stderr, "Could not determine norm (PAL/NTSC) for target.\n");
2911
        fprintf(stderr, "Please prefix target with \"pal-\" or \"ntsc-\",\n");
2912
        fprintf(stderr, "or set a framerate with \"-r xxx\".\n");
2913
        exit(1);
2914
    }
2915

    
2916
    if(!strcmp(arg, "vcd")) {
2917

    
2918
        opt_video_codec("mpeg1video");
2919
        opt_audio_codec("mp2");
2920
        opt_format("vcd");
2921

    
2922
        opt_frame_size(norm ? "352x240" : "352x288");
2923

    
2924
        video_bit_rate = 1150000;
2925
        video_rc_max_rate = 1150000;
2926
        video_rc_min_rate = 1150000;
2927
        video_rc_buffer_size = 40*1024*8;
2928

    
2929
        audio_bit_rate = 224000;
2930
        audio_sample_rate = 44100;
2931

    
2932
    } else if(!strcmp(arg, "svcd")) {
2933

    
2934
        opt_video_codec("mpeg2video");
2935
        opt_audio_codec("mp2");
2936
        opt_format("vcd");
2937

    
2938
        opt_frame_size(norm ? "480x480" : "480x576");
2939
        opt_gop_size(norm ? "18" : "15");
2940

    
2941
        video_bit_rate = 2040000;
2942
        video_rc_max_rate = 2516000;
2943
        video_rc_min_rate = 0; //1145000;
2944
        video_rc_buffer_size = 224*1024*8;
2945
        use_scan_offset = 1;
2946

    
2947
        audio_bit_rate = 224000;
2948
        audio_sample_rate = 44100;
2949

    
2950
    } else if(!strcmp(arg, "dvd")) {
2951

    
2952
        opt_video_codec("mpeg2video");
2953
        opt_audio_codec("ac3");
2954
        opt_format("vob");
2955

    
2956
        opt_frame_size(norm ? "720x480" : "720x576");
2957
        opt_gop_size(norm ? "18" : "15");
2958

    
2959
        video_bit_rate = 6000000;
2960
        video_rc_max_rate = 9000000;
2961
        video_rc_min_rate = 0; //1500000;
2962
        video_rc_buffer_size = 224*1024*8;
2963

    
2964
        audio_bit_rate = 448000;
2965
        audio_sample_rate = 48000;
2966

    
2967
    } else {
2968
        fprintf(stderr, "Unknown target: %s\n", arg);
2969
        exit(1);
2970
    }
2971
}
2972

    
2973
const OptionDef options[] = {
2974
    /* main options */
2975
    { "L", 0, {(void*)show_license}, "show license" },
2976
    { "h", 0, {(void*)show_help}, "show help" },
2977
    { "formats", 0, {(void*)show_formats}, "show available formats, codecs, protocols, ..." },
2978
    { "f", HAS_ARG, {(void*)opt_format}, "force format", "fmt" },
2979
    { "img", HAS_ARG, {(void*)opt_image_format}, "force image format", "img_fmt" },
2980
    { "i", HAS_ARG, {(void*)opt_input_file}, "input file name", "filename" },
2981
    { "y", OPT_BOOL, {(void*)&file_overwrite}, "overwrite output files" },
2982
    { "map", HAS_ARG | OPT_EXPERT, {(void*)opt_map}, "set input stream mapping", "file:stream" },
2983
    { "t", HAS_ARG, {(void*)opt_recording_time}, "set the recording time", "duration" },
2984
    { "ss", HAS_ARG, {(void*)opt_start_time}, "set the start time offset", "time_off" },
2985
    { "title", HAS_ARG | OPT_STRING, {(void*)&str_title}, "set the title", "string" },
2986
    { "author", HAS_ARG | OPT_STRING, {(void*)&str_author}, "set the author", "string" },
2987
    { "copyright", HAS_ARG | OPT_STRING, {(void*)&str_copyright}, "set the copyright", "string" },
2988
    { "comment", HAS_ARG | OPT_STRING, {(void*)&str_comment}, "set the comment", "string" },
2989
    { "debug", HAS_ARG | OPT_EXPERT, {(void*)opt_debug}, "print specific debug info", "" },
2990
    { "vismv", HAS_ARG | OPT_EXPERT, {(void*)opt_vismv}, "visualize motion vectors", "" },
2991
    { "benchmark", OPT_BOOL | OPT_EXPERT, {(void*)&do_benchmark}, 
2992
      "add timings for benchmarking" },
2993
    { "dump", OPT_BOOL | OPT_EXPERT, {(void*)&do_pkt_dump}, 
2994
      "dump each input packet" },
2995
    { "hex", OPT_BOOL | OPT_EXPERT, {(void*)&do_hex_dump}, 
2996
      "when dumping packets, also dump the payload" },
2997
    { "bitexact", OPT_EXPERT, {(void*)opt_bitexact}, "only use bit exact algorithms (for codec testing)" }, 
2998
    { "re", OPT_BOOL | OPT_EXPERT, {(void*)&rate_emu}, "read input at native frame rate", "" },
2999
    { "loop", OPT_BOOL | OPT_EXPERT, {(void*)&loop_input}, "loop (current only works with images)" },
3000
    { "v", HAS_ARG, {(void*)opt_verbose}, "control amount of logging", "verbose" },
3001
    { "target", HAS_ARG, {(void*)opt_target}, "specify target file type (\"vcd\", \"svcd\" or \"dvd\")", "type" },
3002

    
3003
    /* video options */
3004
    { "b", HAS_ARG | OPT_VIDEO, {(void*)opt_video_bitrate}, "set video bitrate (in kbit/s)", "bitrate" },
3005
    { "r", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_rate}, "set frame rate (Hz value, fraction or abbreviation)", "rate" },
3006
    { "s", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_size}, "set frame size (WxH or abbreviation)", "size" },
3007
    { "aspect", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_aspect_ratio}, "set aspect ratio (4:3, 16:9 or 1.3333, 1.7777)", "aspect" },
3008
    { "pix_fmt", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_frame_pix_fmt}, "set pixel format", "format" },
3009
    { "croptop", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop_top}, "set top crop band size (in pixels)", "size" },
3010
    { "cropbottom", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop_bottom}, "set bottom crop band size (in pixels)", "size" },
3011
    { "cropleft", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop_left}, "set left crop band size (in pixels)", "size" },
3012
    { "cropright", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop_right}, "set right crop band size (in pixels)", "size" },
3013
    { "g", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_gop_size}, "set the group of picture size", "gop_size" },
3014
    { "intra", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&intra_only}, "use only intra frames"},
3015
    { "vn", OPT_BOOL | OPT_VIDEO, {(void*)&video_disable}, "disable video" },
3016
    { "qscale", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qscale}, "use fixed video quantiser scale (VBR)", "q" },
3017
    { "qmin", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qmin}, "min video quantiser scale (VBR)", "q" },
3018
    { "qmax", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qmax}, "max video quantiser scale (VBR)", "q" },
3019
    { "mbqmin", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_mb_qmin}, "min macroblock quantiser scale (VBR)", "q" },
3020
    { "mbqmax", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_mb_qmax}, "max macroblock quantiser scale (VBR)", "q" },
3021
    { "qdiff", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qdiff}, "max difference between the quantiser scale (VBR)", "q" },
3022
    { "qblur", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qblur}, "video quantiser scale blur (VBR)", "blur" },
3023
    { "qcomp", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qcomp}, "video quantiser scale compression (VBR)", "compression" },
3024
    { "rc_init_cplx", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_rc_initial_cplx}, "initial complexity for 1-pass encoding", "complexity" },
3025
    { "b_qfactor", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_b_qfactor}, "qp factor between p and b frames", "factor" },
3026
    { "i_qfactor", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_i_qfactor}, "qp factor between p and i frames", "factor" },
3027
    { "b_qoffset", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_b_qoffset}, "qp offset between p and b frames", "offset" },
3028
    { "i_qoffset", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_i_qoffset}, "qp offset between p and i frames", "offset" },
3029
    { "ibias", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_ibias}, "intra quant bias", "bias" },
3030
    { "pbias", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_pbias}, "inter quant bias", "bias" },
3031
//    { "b_strategy", HAS_ARG | OPT_EXPERT, {(void*)opt_b_strategy}, "dynamic b frame selection strategy", "strategy" },
3032
    { "rc_eq", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_video_rc_eq}, "set rate control equation", "equation" },
3033
    { "rc_override", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_video_rc_override_string}, "rate control override for specific intervals", "override" },
3034
    { "bt", HAS_ARG | OPT_VIDEO, {(void*)opt_video_bitrate_tolerance}, "set video bitrate tolerance (in kbit/s)", "tolerance" },
3035
    { "maxrate", HAS_ARG | OPT_VIDEO, {(void*)opt_video_bitrate_max}, "set max video bitrate tolerance (in kbit/s)", "bitrate" },
3036
    { "minrate", HAS_ARG | OPT_VIDEO, {(void*)opt_video_bitrate_min}, "set min video bitrate tolerance (in kbit/s)", "bitrate" },
3037
    { "bufsize", HAS_ARG | OPT_VIDEO, {(void*)opt_video_buffer_size}, "set ratecontrol buffere size (in kByte)", "size" },
3038
    { "vcodec", HAS_ARG | OPT_VIDEO, {(void*)opt_video_codec}, "force video codec ('copy' to copy stream)", "codec" },
3039
    { "me", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_motion_estimation}, "set motion estimation method", 
3040
      "method" },
3041
    { "dct_algo", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_dct_algo}, "set dct algo",  "algo" },
3042
    { "idct_algo", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_idct_algo}, "set idct algo",  "algo" },
3043
    { "er", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_error_resilience}, "set error resilience",  "n" },
3044
    { "ec", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_error_concealment}, "set error concealment",  "bit_mask" },
3045
    { "bf", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_b_frames}, "use 'frames' B frames", "frames" },
3046
    { "hq", OPT_BOOL, {(void*)&mb_decision}, "activate high quality settings" },
3047
    { "mbd", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_mb_decision}, "macroblock decision", "mode" },
3048
    { "mbcmp", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_mb_cmp}, "macroblock compare function", "cmp function" },
3049
    { "ildctcmp", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_ildct_cmp}, "ildct compare function", "cmp function" },
3050
    { "subcmp", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_sub_cmp}, "subpel compare function", "cmp function" },
3051
    { "cmp", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_cmp}, "fullpel compare function", "cmp function" },
3052
    { "4mv", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_4mv}, "use four motion vector by macroblock (MPEG4)" },
3053
    { "obmc", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_obmc}, "use overlapped block motion compensation (h263+)" },
3054
    { "part", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_part}, "use data partitioning (MPEG4)" },
3055
    { "bug", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_workaround_bugs}, "workaround not auto detected encoder bugs", "param" },
3056
    { "ps", HAS_ARG | OPT_EXPERT, {(void*)opt_packet_size}, "set packet size in bits", "size" },
3057
    { "error", HAS_ARG | OPT_EXPERT, {(void*)opt_error_rate}, "error rate", "rate" },
3058
    { "strict", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_strict}, "how strictly to follow the standarts", "strictness" },
3059
    { "sameq", OPT_BOOL | OPT_VIDEO, {(void*)&same_quality}, 
3060
      "use same video quality as source (implies VBR)" },
3061
    { "pass", HAS_ARG | OPT_VIDEO, {(void*)&opt_pass}, "select the pass number (1 or 2)", "n" },
3062
    { "passlogfile", HAS_ARG | OPT_STRING | OPT_VIDEO, {(void*)&pass_logfilename}, "select two pass log file name", "file" },
3063
    { "deinterlace", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_deinterlace}, 
3064
      "deinterlace pictures" },
3065
    { "ildct", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_interlace_dct}, 
3066
      "force interlaced dct support in encoder (MPEG2/MPEG4)" },
3067
    { "ilme", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_interlace_me}, 
3068
      "force interlacied me support in encoder MPEG2" },
3069
    { "psnr", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_psnr}, "calculate PSNR of compressed frames" },
3070
    { "vstats", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_vstats}, "dump video coding statistics to file" }, 
3071
    { "vhook", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)add_frame_hooker}, "insert video processing module", "module" },
3072
    { "aic", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_aic}, "enable Advanced intra coding (h263+)" },
3073
    { "aiv", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_aiv}, "enable Alternative inter vlc (h263+)" },
3074
    { "umv", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_umv}, "enable Unlimited Motion Vector (h263+)" },
3075
    { "alt", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_alt_scan}, "enable alternate scantable (mpeg2)" },
3076
    { "trell", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_trell}, "enable trellis quantization" },
3077
    { "cgop", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&closed_gop}, "closed gop" },
3078
    { "scan_offset", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_scan_offset}, "enable SVCD Scan Offset placeholder" },
3079
    { "intra_matrix", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_intra_matrix}, "specify intra matrix coeffs", "matrix" },
3080
    { "inter_matrix", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_inter_matrix}, "specify inter matrix coeffs", "matrix" },
3081
    { "top", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_top_field_first}, "top=1/bottom=0/auto=-1 field first", "" },
3082
    { "nr", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_noise_reduction}, "noise reduction", "" },
3083
    { "qns", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qns}, "quantization noise shaping", "" },
3084
    { "sc_threshold", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_sc_threshold}, "scene change threshold", "threshold" },
3085

    
3086
    /* audio options */
3087
    { "ab", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_bitrate}, "set audio bitrate (in kbit/s)", "bitrate", },
3088
    { "ar", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_rate}, "set audio sampling rate (in Hz)", "rate" },
3089
    { "ac", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_channels}, "set number of audio channels", "channels" },
3090
    { "an", OPT_BOOL | OPT_AUDIO, {(void*)&audio_disable}, "disable audio" },
3091
    { "acodec", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_codec}, "force audio codec ('copy' to copy stream)", "codec" },
3092

    
3093
    /* grab options */
3094
    { "vd", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_device}, "set video grab device", "device" },
3095
    { "vc", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_channel}, "set video grab channel (DV1394 only)", "channel" },
3096
    { "tvstd", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_standard}, "set television standard (NTSC, PAL (SECAM))", "standard" },
3097
    { "dv1394", OPT_EXPERT | OPT_GRAB, {(void*)opt_dv1394}, "set DV1394 grab", "" },
3098
    { "ad", HAS_ARG | OPT_EXPERT | OPT_AUDIO | OPT_GRAB, {(void*)opt_audio_device}, "set audio device", "device" },
3099
    { NULL, },
3100
};
3101

    
3102
static void show_banner(void)
3103
{
3104
    printf("ffmpeg version " FFMPEG_VERSION ", Copyright (c) 2000-2003 Fabrice Bellard\n");
3105
}
3106

    
3107
static void show_license(void)
3108
{
3109
    show_banner();
3110
    printf(
3111
    "This library is free software; you can redistribute it and/or\n"
3112
    "modify it under the terms of the GNU Lesser General Public\n"
3113
    "License as published by the Free Software Foundation; either\n"
3114
    "version 2 of the License, or (at your option) any later version.\n"
3115
    "\n"
3116
    "This library is distributed in the hope that it will be useful,\n"
3117
    "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
3118
    "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n"
3119
    "Lesser General Public License for more details.\n"
3120
    "\n"
3121
    "You should have received a copy of the GNU Lesser General Public\n"
3122
    "License along with this library; if not, write to the Free Software\n"
3123
    "Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n"
3124
    );
3125
    exit(1);
3126
}
3127

    
3128
static void show_help(void)
3129
{
3130
    show_banner();
3131
    printf("usage: ffmpeg [[options] -i input_file]... {[options] outfile}...\n"
3132
           "Hyper fast Audio and Video encoder\n");
3133
    printf("\n");
3134
    show_help_options(options, "Main options:\n",
3135
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO, 0);
3136
    show_help_options(options, "\nVideo options:\n",
3137
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB, 
3138
                      OPT_VIDEO);
3139
    show_help_options(options, "\nAdvanced Video options:\n",
3140
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB, 
3141
                      OPT_VIDEO | OPT_EXPERT);
3142
    show_help_options(options, "\nAudio options:\n",
3143
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB, 
3144
                      OPT_AUDIO);
3145
    show_help_options(options, "\nAdvanced Audio options:\n",
3146
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB, 
3147
                      OPT_AUDIO | OPT_EXPERT);
3148
    show_help_options(options, "\nAudio/Video grab options:\n",
3149
                      OPT_GRAB, 
3150
                      OPT_GRAB);
3151
    show_help_options(options, "\nAdvanced options:\n",
3152
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB, 
3153
                      OPT_EXPERT);
3154
    exit(1);
3155
}
3156

    
3157
void parse_arg_file(const char *filename)
3158
{
3159
    opt_output_file(filename);
3160
}
3161

    
3162
int main(int argc, char **argv)
3163
{
3164
    int i;
3165
    int64_t ti;
3166

    
3167
    av_register_all();
3168

    
3169
    if (argc <= 1)
3170
        show_help();
3171
    
3172
    /* parse options */
3173
    parse_options(argc, argv, options);
3174

    
3175
    /* file converter / grab */
3176
    if (nb_output_files <= 0) {
3177
        fprintf(stderr, "Must supply at least one output file\n");
3178
        exit(1);
3179
    }
3180
    
3181
    if (nb_input_files == 0) {
3182
        prepare_grab();
3183
    }
3184

    
3185
    ti = getutime();
3186
    av_encode(output_files, nb_output_files, input_files, nb_input_files, 
3187
              stream_maps, nb_stream_maps);
3188
    ti = getutime() - ti;
3189
    if (do_benchmark) {
3190
        printf("bench: utime=%0.3fs\n", ti / 1000000.0);
3191
    }
3192

    
3193
    /* close files */
3194
    for(i=0;i<nb_output_files;i++) {
3195
        /* maybe av_close_output_file ??? */
3196
        AVFormatContext *s = output_files[i];
3197
        int j;
3198
        if (!(s->oformat->flags & AVFMT_NOFILE))
3199
            url_fclose(&s->pb);
3200
        for(j=0;j<s->nb_streams;j++)
3201
            av_free(s->streams[j]);
3202
        av_free(s);
3203
    }
3204
    for(i=0;i<nb_input_files;i++)
3205
        av_close_input_file(input_files[i]);
3206

    
3207
    av_free_static();
3208

    
3209
    if(intra_matrix)
3210
        av_free(intra_matrix);
3211
    if(inter_matrix)
3212
        av_free(inter_matrix);
3213
    
3214
#ifdef POWERPC_PERFORMANCE_REPORT
3215
    extern void powerpc_display_perf_report(void);
3216
    powerpc_display_perf_report();
3217
#endif /* POWERPC_PERFORMANCE_REPORT */
3218

    
3219
#ifndef CONFIG_WIN32
3220
    if (received_sigterm) {
3221
        fprintf(stderr,
3222
            "Received signal %d: terminating.\n",
3223
            (int) received_sigterm);
3224
        exit (255);
3225
    }
3226
#endif
3227
    exit(0); /* not all OS-es handle main() return value */
3228
    return 0;
3229
}