Statistics
| Branch: | Revision:

ffmpeg / ffmpeg.c @ 2de28abb

History | View | Annotate | Download (122 KB)

1
/*
2
 * FFmpeg main 
3
 * Copyright (c) 2000-2003 Fabrice Bellard
4
 *
5
 * This library is free software; you can redistribute it and/or
6
 * modify it under the terms of the GNU Lesser General Public
7
 * License as published by the Free Software Foundation; either
8
 * version 2 of the License, or (at your option) any later version.
9
 *
10
 * This library is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13
 * Lesser General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU Lesser General Public
16
 * License along with this library; if not, write to the Free Software
17
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18
 */
19
#define HAVE_AV_CONFIG_H
20
#include "avformat.h"
21
#include "framehook.h"
22

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

    
40
#include "cmdutils.h"
41

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

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

    
52
extern const OptionDef options[];
53

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

    
57
#define MAX_FILES 20
58

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

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

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

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

    
164
static int gop_size = 12;
165
static int intra_only = 0;
166
static int audio_sample_rate = 44100;
167
static int audio_bit_rate = 64000;
168
static int audio_disable = 0;
169
static int audio_channels = 1;
170
static int audio_codec_id = CODEC_ID_NONE;
171

    
172
static int64_t recording_time = 0;
173
static int64_t start_time = 0;
174
static int64_t rec_timestamp = 0;
175
static int file_overwrite = 0;
176
static char *str_title = NULL;
177
static char *str_author = NULL;
178
static char *str_copyright = NULL;
179
static char *str_comment = NULL;
180
static int do_benchmark = 0;
181
static int do_hex_dump = 0;
182
static int do_pkt_dump = 0;
183
static int do_psnr = 0;
184
static int do_vstats = 0;
185
static int do_pass = 0;
186
static int bitexact = 0;
187
static char *pass_logfilename = NULL;
188
static int audio_stream_copy = 0;
189
static int video_stream_copy = 0;
190

    
191
static int rate_emu = 0;
192

    
193
static char *video_grab_format = "video4linux";
194
static char *video_device = NULL;
195
static int  video_channel = 0;
196
static char *video_standard = "ntsc";
197

    
198
static char *audio_grab_format = "audio_device";
199
static char *audio_device = NULL;
200

    
201
static int using_stdin = 0;
202
static int using_vhook = 0;
203
static int verbose = 1;
204
static int thread_count= 1;
205
static int q_pressed = 0;
206
static int64_t video_size = 0;
207
static int64_t audio_size = 0;
208
static int64_t extra_size = 0;
209

    
210
#define DEFAULT_PASS_LOGFILENAME "ffmpeg2pass"
211

    
212
typedef struct AVOutputStream {
213
    int file_index;          /* file index */
214
    int index;               /* stream index in the output file */
215
    int source_index;        /* AVInputStream index */
216
    AVStream *st;            /* stream in the output file */
217
    int encoding_needed;     /* true if encoding needed for this stream */
218
    int frame_number;
219
    /* input pts and corresponding output pts
220
       for A/V sync */
221
    double sync_ipts;
222
    double sync_ipts_offset;
223
    int64_t sync_opts;
224
    /* video only */
225
    int video_resample;      /* video_resample and video_crop are mutually exclusive */
226
    AVFrame pict_tmp;      /* temporary image for resampling */
227
    ImgReSampleContext *img_resample_ctx; /* for image resampling */
228

    
229
    int video_crop;          /* video_resample and video_crop are mutually exclusive */
230
    int topBand;             /* cropping area sizes */
231
    int leftBand;
232
    
233
    int video_pad;           /* video_resample and video_pad are mutually exclusive */
234
    int padtop;              /* padding area sizes */
235
    int padbottom;
236
    int padleft;
237
    int padright;
238
    
239
    /* audio only */
240
    int audio_resample;
241
    ReSampleContext *resample; /* for audio resampling */
242
    FifoBuffer fifo;     /* for compression: one audio fifo per codec */
243
    FILE *logfile;
244
} AVOutputStream;
245

    
246
typedef struct AVInputStream {
247
    int file_index;
248
    int index;
249
    AVStream *st;
250
    int discard;             /* true if stream data should be discarded */
251
    int decoding_needed;     /* true if the packets must be decoded in 'raw_fifo' */
252
    int64_t sample_index;      /* current sample */
253

    
254
    int64_t       start;     /* time when read started */
255
    unsigned long frame;     /* current frame */
256
    int64_t       next_pts;  /* synthetic pts for cases where pkt.pts
257
                                is not defined */
258
    int64_t       pts;       /* current pts */
259
} AVInputStream;
260

    
261
typedef struct AVInputFile {
262
    int eof_reached;      /* true if eof reached */
263
    int ist_index;        /* index of first stream in ist_table */
264
    int buffer_size;      /* current total buffer size */
265
    int buffer_size_max;  /* buffer size at which we consider we can stop
266
                             buffering */
267
    int nb_streams;       /* nb streams we are aware of */
268
} AVInputFile;
269

    
270
#ifndef CONFIG_WIN32
271

    
272
/* init terminal so that we can grab keys */
273
static struct termios oldtty;
274

    
275
static void term_exit(void)
276
{
277
    tcsetattr (0, TCSANOW, &oldtty);
278
}
279

    
280
static volatile sig_atomic_t received_sigterm = 0;
281

    
282
static void
283
sigterm_handler(int sig)
284
{
285
    received_sigterm = sig;
286
    term_exit();
287
}
288

    
289
static void term_init(void)
290
{
291
    struct termios tty;
292

    
293
    tcgetattr (0, &tty);
294
    oldtty = tty;
295

    
296
    tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
297
                          |INLCR|IGNCR|ICRNL|IXON);
298
    tty.c_oflag |= OPOST;
299
    tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
300
    tty.c_cflag &= ~(CSIZE|PARENB);
301
    tty.c_cflag |= CS8;
302
    tty.c_cc[VMIN] = 1;
303
    tty.c_cc[VTIME] = 0;
304
    
305
    tcsetattr (0, TCSANOW, &tty);
306

    
307
    signal(SIGINT , sigterm_handler); /* Interrupt (ANSI).  */
308
    signal(SIGQUIT, sigterm_handler); /* Quit (POSIX).  */
309
    signal(SIGTERM, sigterm_handler); /* Termination (ANSI).  */
310
    /*
311
    register a function to be called at normal program termination
312
    */
313
    atexit(term_exit);
314
#ifdef CONFIG_BEOS_NETSERVER
315
    fcntl(0, F_SETFL, fcntl(0, F_GETFL) | O_NONBLOCK);
316
#endif
317
}
318

    
319
/* read a key without blocking */
320
static int read_key(void)
321
{
322
    int n = 1;
323
    unsigned char ch;
324
#ifndef CONFIG_BEOS_NETSERVER
325
    struct timeval tv;
326
    fd_set rfds;
327

    
328
    FD_ZERO(&rfds);
329
    FD_SET(0, &rfds);
330
    tv.tv_sec = 0;
331
    tv.tv_usec = 0;
332
    n = select(1, &rfds, NULL, NULL, &tv);
333
#endif
334
    if (n > 0) {
335
        n = read(0, &ch, 1);
336
        if (n == 1)
337
            return ch;
338

    
339
        return n;
340
    }
341
    return -1;
342
}
343

    
344
static int decode_interrupt_cb(void)
345
{
346
    return q_pressed || (q_pressed = read_key() == 'q');
347
}
348

    
349
#else
350

    
351
static volatile int received_sigterm = 0;
352

    
353
/* no interactive support */
354
static void term_exit(void)
355
{
356
}
357

    
358
static void term_init(void)
359
{
360
}
361

    
362
static int read_key(void)
363
{
364
    return 0;
365
}
366

    
367
#endif
368

    
369
static int read_ffserver_streams(AVFormatContext *s, const char *filename)
370
{
371
    int i, err;
372
    AVFormatContext *ic;
373

    
374
    err = av_open_input_file(&ic, filename, NULL, FFM_PACKET_SIZE, NULL);
375
    if (err < 0)
376
        return err;
377
    /* copy stream format */
378
    s->nb_streams = ic->nb_streams;
379
    for(i=0;i<ic->nb_streams;i++) {
380
        AVStream *st;
381

    
382
        st = av_mallocz(sizeof(AVStream));
383
        memcpy(st, ic->streams[i], sizeof(AVStream));
384
        s->streams[i] = st;
385
    }
386

    
387
    av_close_input_file(ic);
388
    return 0;
389
}
390

    
391
#define MAX_AUDIO_PACKET_SIZE (128 * 1024)
392

    
393
static void do_audio_out(AVFormatContext *s, 
394
                         AVOutputStream *ost, 
395
                         AVInputStream *ist,
396
                         unsigned char *buf, int size)
397
{
398
    uint8_t *buftmp;
399
    static uint8_t *audio_buf = NULL;
400
    static uint8_t *audio_out = NULL;
401
    const int audio_out_size= 4*MAX_AUDIO_PACKET_SIZE;
402

    
403
    int size_out, frame_bytes, ret;
404
    AVCodecContext *enc;
405

    
406
    /* SC: dynamic allocation of buffers */
407
    if (!audio_buf)
408
        audio_buf = av_malloc(2*MAX_AUDIO_PACKET_SIZE);
409
    if (!audio_out)
410
        audio_out = av_malloc(audio_out_size);
411
    if (!audio_buf || !audio_out)
412
        return;               /* Should signal an error ! */
413

    
414
    
415
    enc = &ost->st->codec;
416

    
417
    if (ost->audio_resample) {
418
        buftmp = audio_buf;
419
        size_out = audio_resample(ost->resample, 
420
                                  (short *)buftmp, (short *)buf,
421
                                  size / (ist->st->codec.channels * 2));
422
        size_out = size_out * enc->channels * 2;
423
    } else {
424
        buftmp = buf;
425
        size_out = size;
426
    }
427

    
428
    /* now encode as many frames as possible */
429
    if (enc->frame_size > 1) {
430
        /* output resampled raw samples */
431
        fifo_write(&ost->fifo, buftmp, size_out, 
432
                   &ost->fifo.wptr);
433

    
434
        frame_bytes = enc->frame_size * 2 * enc->channels;
435
        
436
        while (fifo_read(&ost->fifo, audio_buf, frame_bytes, 
437
                     &ost->fifo.rptr) == 0) {
438
            ret = avcodec_encode_audio(enc, audio_out, audio_out_size, 
439
                                       (short *)audio_buf);
440
            audio_size += ret;
441
            av_write_frame(s, ost->index, audio_out, ret);
442
        }
443
    } else {
444
        /* output a pcm frame */
445
        /* XXX: change encoding codec API to avoid this ? */
446
        switch(enc->codec->id) {
447
        case CODEC_ID_PCM_S16LE:
448
        case CODEC_ID_PCM_S16BE:
449
        case CODEC_ID_PCM_U16LE:
450
        case CODEC_ID_PCM_U16BE:
451
            break;
452
        default:
453
            size_out = size_out >> 1;
454
            break;
455
        }
456
        ret = avcodec_encode_audio(enc, audio_out, size_out, 
457
                                   (short *)buftmp);
458
        audio_size += ret;
459
        av_write_frame(s, ost->index, audio_out, ret);
460
    }
461
}
462

    
463
static void pre_process_video_frame(AVInputStream *ist, AVPicture *picture, void **bufp)
464
{
465
    AVCodecContext *dec;
466
    AVPicture *picture2;
467
    AVPicture picture_tmp;
468
    uint8_t *buf = 0;
469

    
470
    dec = &ist->st->codec;
471

    
472
    /* deinterlace : must be done before any resize */
473
    if (do_deinterlace || using_vhook) {
474
        int size;
475

    
476
        /* create temporary picture */
477
        size = avpicture_get_size(dec->pix_fmt, dec->width, dec->height);
478
        buf = av_malloc(size);
479
        if (!buf)
480
            return;
481
        
482
        picture2 = &picture_tmp;
483
        avpicture_fill(picture2, buf, dec->pix_fmt, dec->width, dec->height);
484

    
485
        if (do_deinterlace){
486
            if(avpicture_deinterlace(picture2, picture, 
487
                                     dec->pix_fmt, dec->width, dec->height) < 0) {
488
                /* if error, do not deinterlace */
489
                av_free(buf);
490
                buf = NULL;
491
                picture2 = picture;
492
            }
493
        } else {
494
            if (img_convert(picture2, dec->pix_fmt, picture, 
495
                            dec->pix_fmt, dec->width, dec->height) < 0) {
496
                /* if error, do not copy */
497
                av_free(buf);
498
                buf = NULL;
499
                picture2 = picture;
500
            }
501
        }
502
    } else {
503
        picture2 = picture;
504
    }
505

    
506
    frame_hook_process(picture2, dec->pix_fmt, dec->width, dec->height);
507

    
508
    if (picture != picture2)
509
        *picture = *picture2;
510
    *bufp = buf;
511
}
512

    
513
/* we begin to correct av delay at this threshold */
514
#define AV_DELAY_MAX 0.100
515

    
516

    
517
/* Expects img to be yuv420 */
518
static void fill_pad_region(AVPicture* img, int height, int width,
519
        int padtop, int padbottom, int padleft, int padright, int *color) {
520
  
521
    int i, y, shift;
522
    uint8_t *optr;
523
    
524
    for (i = 0; i < 3; i++) {
525
        shift = (i == 0) ? 0 : 1;
526
        
527
        if (padtop || padleft) {
528
            memset(img->data[i], color[i], (((img->linesize[i] * padtop) + 
529
                            padleft) >> shift));
530
        }
531

    
532
        if (padleft || padright) {
533
            optr = img->data[i] + (img->linesize[i] * (padtop >> shift)) +
534
                (img->linesize[i] - (padright >> shift));
535

    
536
            for (y = 0; y < ((height - (padtop + padbottom)) >> shift); y++) {
537
                memset(optr, color[i], (padleft + padright) >> shift);
538
                optr += img->linesize[i];
539
            }
540
        }
541
      
542
        if (padbottom) {
543
            optr = img->data[i] + (img->linesize[i] * ((height - padbottom) >> shift));
544
            memset(optr, color[i], ((img->linesize[i] * padbottom) >> shift));
545
        }
546
    }
547
}
548

    
549

    
550
static void do_video_out(AVFormatContext *s, 
551
                         AVOutputStream *ost, 
552
                         AVInputStream *ist,
553
                         AVFrame *in_picture,
554
                         int *frame_size, AVOutputStream *audio_sync)
555
{
556
    int nb_frames, i, ret;
557
    AVFrame *final_picture, *formatted_picture;
558
    AVFrame picture_format_temp, picture_crop_temp;
559
    static uint8_t *video_buffer= NULL;
560
    uint8_t *buf = NULL, *buf1 = NULL;
561
    AVCodecContext *enc, *dec;
562
    enum PixelFormat target_pixfmt;
563
    
564
#define VIDEO_BUFFER_SIZE (1024*1024)
565

    
566
    avcodec_get_frame_defaults(&picture_format_temp);
567
    avcodec_get_frame_defaults(&picture_crop_temp);
568

    
569
    enc = &ost->st->codec;
570
    dec = &ist->st->codec;
571

    
572
    /* by default, we output a single frame */
573
    nb_frames = 1;
574

    
575
    *frame_size = 0;
576

    
577
    /* NOTE: the A/V sync is always done by considering the audio is
578
       the master clock. It is suffisant for transcoding or playing,
579
       but not for the general case */
580
    if (audio_sync) {
581
        /* compute the A-V delay and duplicate/remove frames if needed */
582
        double adelta, vdelta, av_delay;
583

    
584
        adelta = audio_sync->sync_ipts - ((double)audio_sync->sync_opts * 
585
            s->pts_num / s->pts_den);
586

    
587
        vdelta = ost->sync_ipts - ((double)ost->sync_opts *
588
            s->pts_num / s->pts_den);
589

    
590
        av_delay = adelta - vdelta;
591
        //            printf("delay=%f\n", av_delay);
592
        if (av_delay < -AV_DELAY_MAX)
593
            nb_frames = 2;
594
        else if (av_delay > AV_DELAY_MAX)
595
            nb_frames = 0;
596
    } else {
597
        double vdelta;
598

    
599
        vdelta = (double)(ost->st->pts.val) * s->pts_num / s->pts_den - (ost->sync_ipts - ost->sync_ipts_offset);
600
        if (vdelta < 100 && vdelta > -100 && ost->sync_ipts_offset) {
601
            if (vdelta < -AV_DELAY_MAX)
602
                nb_frames = 2;
603
            else if (vdelta > AV_DELAY_MAX)
604
                nb_frames = 0;
605
        } else {
606
            ost->sync_ipts_offset -= vdelta;
607
            if (!ost->sync_ipts_offset)
608
                ost->sync_ipts_offset = 0.000001; /* one microsecond */
609
        }
610
    }
611
    
612
#if defined(AVSYNC_DEBUG)
613
    {
614
        static char *action[] = { "drop frame", "copy frame", "dup frame" };
615
        if (audio_sync && verbose >=0) {
616
            fprintf(stderr, "Input APTS %12.6f, output APTS %12.6f, ",
617
                    (double) audio_sync->sync_ipts, 
618
                    (double) audio_sync->st->pts.val * s->pts_num / s->pts_den);
619
            fprintf(stderr, "Input VPTS %12.6f, output VPTS %12.6f: %s\n",
620
                    (double) ost->sync_ipts, 
621
                    (double) ost->st->pts.val * s->pts_num / s->pts_den,
622
                    action[nb_frames]);
623
        }
624
    }
625
#endif
626

    
627
    if (nb_frames <= 0) 
628
        return;
629

    
630
    if (!video_buffer)
631
        video_buffer = av_malloc(VIDEO_BUFFER_SIZE);
632
    if (!video_buffer)
633
        return;
634

    
635
    /* convert pixel format if needed */
636
    target_pixfmt = ost->video_resample || ost->video_pad
637
        ? PIX_FMT_YUV420P : enc->pix_fmt;
638
    if (dec->pix_fmt != target_pixfmt) {
639
        int size;
640

    
641
        /* create temporary picture */
642
        size = avpicture_get_size(target_pixfmt, dec->width, dec->height);
643
        buf = av_malloc(size);
644
        if (!buf)
645
            return;
646
        formatted_picture = &picture_format_temp;
647
        avpicture_fill((AVPicture*)formatted_picture, buf, target_pixfmt, dec->width, dec->height);
648
        
649
        if (img_convert((AVPicture*)formatted_picture, target_pixfmt, 
650
                        (AVPicture *)in_picture, dec->pix_fmt, 
651
                        dec->width, dec->height) < 0) {
652

    
653
            if (verbose >= 0)
654
                fprintf(stderr, "pixel format conversion not handled\n");
655

    
656
            goto the_end;
657
        }
658
    } else {
659
        formatted_picture = in_picture;
660
    }
661

    
662
    /* XXX: resampling could be done before raw format conversion in
663
       some cases to go faster */
664
    /* XXX: only works for YUV420P */
665
    if (ost->video_resample) {
666
        final_picture = &ost->pict_tmp;
667
        img_resample(ost->img_resample_ctx, (AVPicture*)final_picture, (AVPicture*)formatted_picture);
668
       
669
        if (ost->padtop || ost->padbottom || ost->padleft || ost->padright) {
670
            fill_pad_region((AVPicture*)final_picture, enc->height, enc->width,
671
                    ost->padtop, ost->padbottom, ost->padleft, ost->padright,
672
                    padcolor);
673
        }
674
        
675
        if (enc->pix_fmt != PIX_FMT_YUV420P) {
676
            int size;
677
            
678
            av_free(buf);
679
            /* create temporary picture */
680
            size = avpicture_get_size(enc->pix_fmt, enc->width, enc->height);
681
            buf = av_malloc(size);
682
            if (!buf)
683
                return;
684
            final_picture = &picture_format_temp;
685
            avpicture_fill((AVPicture*)final_picture, buf, enc->pix_fmt, enc->width, enc->height);
686
        
687
            if (img_convert((AVPicture*)final_picture, enc->pix_fmt, 
688
                            (AVPicture*)&ost->pict_tmp, PIX_FMT_YUV420P, 
689
                            enc->width, enc->height) < 0) {
690

    
691
                if (verbose >= 0)
692
                    fprintf(stderr, "pixel format conversion not handled\n");
693

    
694
                goto the_end;
695
            }
696
        }
697
    } else if (ost->video_crop) {
698
        picture_crop_temp.data[0] = formatted_picture->data[0] +
699
                (ost->topBand * formatted_picture->linesize[0]) + ost->leftBand;
700

    
701
        picture_crop_temp.data[1] = formatted_picture->data[1] +
702
                ((ost->topBand >> 1) * formatted_picture->linesize[1]) +
703
                (ost->leftBand >> 1);
704

    
705
        picture_crop_temp.data[2] = formatted_picture->data[2] +
706
                ((ost->topBand >> 1) * formatted_picture->linesize[2]) +
707
                (ost->leftBand >> 1);
708

    
709
        picture_crop_temp.linesize[0] = formatted_picture->linesize[0];
710
        picture_crop_temp.linesize[1] = formatted_picture->linesize[1];
711
        picture_crop_temp.linesize[2] = formatted_picture->linesize[2];
712
        final_picture = &picture_crop_temp;
713
    } else if (ost->video_pad) {
714
        final_picture = &ost->pict_tmp;
715

    
716
        for (i = 0; i < 3; i++) {
717
            uint8_t *optr, *iptr;
718
            int shift = (i == 0) ? 0 : 1;
719
            int y, yheight;
720
            
721
            /* set offset to start writing image into */
722
            optr = final_picture->data[i] + (((final_picture->linesize[i] * 
723
                            ost->padtop) + ost->padleft) >> shift);
724
            iptr = formatted_picture->data[i];
725

    
726
            yheight = (enc->height - ost->padtop - ost->padbottom) >> shift;
727
            for (y = 0; y < yheight; y++) {
728
                /* copy unpadded image row into padded image row */
729
                memcpy(optr, iptr, formatted_picture->linesize[i]);
730
                optr += final_picture->linesize[i];
731
                iptr += formatted_picture->linesize[i];
732
            }
733
        }
734

    
735
        fill_pad_region((AVPicture*)final_picture, enc->height, enc->width,
736
                ost->padtop, ost->padbottom, ost->padleft, ost->padright,
737
                padcolor);
738
        
739
        if (enc->pix_fmt != PIX_FMT_YUV420P) {
740
            int size;
741

    
742
            av_free(buf);
743
            /* create temporary picture */
744
            size = avpicture_get_size(enc->pix_fmt, enc->width, enc->height);
745
            buf = av_malloc(size);
746
            if (!buf)
747
                return;
748
            final_picture = &picture_format_temp;
749
            avpicture_fill((AVPicture*)final_picture, buf, enc->pix_fmt, enc->width, enc->height);
750

    
751
            if (img_convert((AVPicture*)final_picture, enc->pix_fmt, 
752
                        (AVPicture*)&ost->pict_tmp, PIX_FMT_YUV420P, 
753
                        enc->width, enc->height) < 0) {
754

    
755
                if (verbose >= 0)
756
                    fprintf(stderr, "pixel format conversion not handled\n");
757

    
758
                goto the_end;
759
            }
760
        }
761
    } else {
762
        final_picture = formatted_picture;
763
    }
764
    /* duplicates frame if needed */
765
    /* XXX: pb because no interleaving */
766
    for(i=0;i<nb_frames;i++) {
767
        if (s->oformat->flags & AVFMT_RAWPICTURE) {
768
            /* raw pictures are written as AVPicture structure to
769
               avoid any copies. We support temorarily the older
770
               method. */
771
            AVFrame* old_frame = enc->coded_frame;
772
            enc->coded_frame = dec->coded_frame;
773
            av_write_frame(s, ost->index, 
774
                           (uint8_t *)final_picture, sizeof(AVPicture));
775
            enc->coded_frame = old_frame;
776
        } else {
777
            AVFrame big_picture;
778

    
779
            big_picture= *final_picture;
780
            /* better than nothing: use input picture interlaced
781
               settings */
782
            big_picture.interlaced_frame = in_picture->interlaced_frame;
783
            if(do_interlace_me || do_interlace_dct){
784
                if(top_field_first == -1)
785
                    big_picture.top_field_first = in_picture->top_field_first;
786
                else
787
                    big_picture.top_field_first = 1;
788
            }
789

    
790
            /* handles sameq here. This is not correct because it may
791
               not be a global option */
792
            if (same_quality) {
793
                big_picture.quality = ist->st->quality;
794
            }else
795
                big_picture.quality = ost->st->quality;
796
            big_picture.pict_type = 0;
797
            ret = avcodec_encode_video(enc, 
798
                                       video_buffer, VIDEO_BUFFER_SIZE,
799
                                       &big_picture);
800
            //enc->frame_number = enc->real_pict_num;
801
            av_write_frame(s, ost->index, video_buffer, ret);
802
            *frame_size = ret;
803
            //fprintf(stderr,"\nFrame: %3d %3d size: %5d type: %d",
804
            //        enc->frame_number-1, enc->real_pict_num, ret,
805
            //        enc->pict_type);
806
            /* if two pass, output log */
807
            if (ost->logfile && enc->stats_out) {
808
                fprintf(ost->logfile, "%s", enc->stats_out);
809
            }
810
        }
811
        ost->frame_number++;
812
    }
813
 the_end:
814
    av_free(buf);
815
    av_free(buf1);
816
}
817

    
818
static double psnr(double d){
819
    if(d==0) return INFINITY;
820
    return -10.0*log(d)/log(10.0);
821
}
822

    
823
static void do_video_stats(AVFormatContext *os, AVOutputStream *ost, 
824
                           int frame_size)
825
{
826
    static FILE *fvstats=NULL;
827
    char filename[40];
828
    time_t today2;
829
    struct tm *today;
830
    AVCodecContext *enc;
831
    int frame_number;
832
    int64_t ti;
833
    double ti1, bitrate, avg_bitrate;
834
    
835
    if (!fvstats) {
836
        today2 = time(NULL);
837
        today = localtime(&today2);
838
        sprintf(filename, "vstats_%02d%02d%02d.log", today->tm_hour,
839
                                               today->tm_min,
840
                                               today->tm_sec);
841
        fvstats = fopen(filename,"w");
842
        if (!fvstats) {
843
            perror("fopen");
844
            exit(1);
845
        }
846
    }
847
    
848
    ti = MAXINT64;
849
    enc = &ost->st->codec;
850
    if (enc->codec_type == CODEC_TYPE_VIDEO) {
851
        frame_number = ost->frame_number;
852
        fprintf(fvstats, "frame= %5d q= %2.1f ", frame_number, enc->coded_frame->quality/(float)FF_QP2LAMBDA);
853
        if (enc->flags&CODEC_FLAG_PSNR)
854
            fprintf(fvstats, "PSNR= %6.2f ", psnr(enc->coded_frame->error[0]/(enc->width*enc->height*255.0*255.0)));
855
        
856
        fprintf(fvstats,"f_size= %6d ", frame_size);
857
        /* compute pts value */
858
        ti1 = (double)ost->st->pts.val * os->pts_num / os->pts_den;
859
        if (ti1 < 0.01)
860
            ti1 = 0.01;
861
    
862
        bitrate = (double)(frame_size * 8) * enc->frame_rate / enc->frame_rate_base / 1000.0;
863
        avg_bitrate = (double)(video_size * 8) / ti1 / 1000.0;
864
        fprintf(fvstats, "s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
865
            (double)video_size / 1024, ti1, bitrate, avg_bitrate);
866
        fprintf(fvstats,"type= %c\n", av_get_pict_type_char(enc->coded_frame->pict_type));        
867
    }
868
}
869

    
870
static void print_report(AVFormatContext **output_files,
871
                         AVOutputStream **ost_table, int nb_ostreams,
872
                         int is_last_report)
873
{
874
    char buf[1024];
875
    AVOutputStream *ost;
876
    AVFormatContext *oc, *os;
877
    int64_t total_size;
878
    AVCodecContext *enc;
879
    int frame_number, vid, i;
880
    double bitrate, ti1, pts;
881
    static int64_t last_time = -1;
882
    
883
    if (!is_last_report) {
884
        int64_t cur_time;
885
        /* display the report every 0.5 seconds */
886
        cur_time = av_gettime();
887
        if (last_time == -1) {
888
            last_time = cur_time;
889
            return;
890
        } 
891
        if ((cur_time - last_time) < 500000)
892
            return;
893
        last_time = cur_time;
894
    }
895

    
896

    
897
    oc = output_files[0];
898

    
899
    total_size = url_ftell(&oc->pb);
900
    
901
    buf[0] = '\0';
902
    ti1 = 1e10;
903
    vid = 0;
904
    for(i=0;i<nb_ostreams;i++) {
905
        ost = ost_table[i];
906
        os = output_files[ost->file_index];
907
        enc = &ost->st->codec;
908
        if (vid && enc->codec_type == CODEC_TYPE_VIDEO) {
909
            sprintf(buf + strlen(buf), "q=%2.1f ",
910
                    enc->coded_frame->quality/(float)FF_QP2LAMBDA);
911
        }
912
        if (!vid && enc->codec_type == CODEC_TYPE_VIDEO) {
913
            frame_number = ost->frame_number;
914
            sprintf(buf + strlen(buf), "frame=%5d q=%2.1f ",
915
                    frame_number, enc->coded_frame ? enc->coded_frame->quality/(float)FF_QP2LAMBDA : 0);
916
            if(is_last_report)
917
                sprintf(buf + strlen(buf), "L");
918
            if (enc->flags&CODEC_FLAG_PSNR){
919
                int j;
920
                double error, error_sum=0;
921
                double scale, scale_sum=0;
922
                char type[3]= {'Y','U','V'};
923
                sprintf(buf + strlen(buf), "PSNR=");
924
                for(j=0; j<3; j++){
925
                    if(is_last_report){
926
                        error= enc->error[j];
927
                        scale= enc->width*enc->height*255.0*255.0*frame_number;
928
                    }else{
929
                        error= enc->coded_frame->error[j];
930
                        scale= enc->width*enc->height*255.0*255.0;
931
                    }
932
                    if(j) scale/=4;
933
                    error_sum += error;
934
                    scale_sum += scale;
935
                    sprintf(buf + strlen(buf), "%c:%2.2f ", type[j], psnr(error/scale));
936
                }
937
                sprintf(buf + strlen(buf), "*:%2.2f ", psnr(error_sum/scale_sum));
938
            }
939
            vid = 1;
940
        }
941
        /* compute min output value */
942
        pts = (double)ost->st->pts.val * os->pts_num / os->pts_den;
943
        if ((pts < ti1) && (pts > 0))
944
            ti1 = pts;
945
    }
946
    if (ti1 < 0.01)
947
        ti1 = 0.01;
948
    
949
    if (verbose || is_last_report) {
950
        bitrate = (double)(total_size * 8) / ti1 / 1000.0;
951
        
952
        sprintf(buf + strlen(buf), 
953
            "size=%8.0fkB time=%0.1f bitrate=%6.1fkbits/s",
954
            (double)total_size / 1024, ti1, bitrate);
955
        
956
        if (verbose >= 0)
957
            fprintf(stderr, "%s    \r", buf);
958

    
959
        fflush(stderr);
960
    }
961
        
962
    if (is_last_report && verbose >= 0){
963
        int64_t raw= audio_size + video_size + extra_size;
964
        fprintf(stderr, "\n");
965
        fprintf(stderr, "video:%1.0fkB audio:%1.0fkB global headers:%1.0fkB muxing overhead %f%%\n",
966
                video_size/1024.0,
967
                audio_size/1024.0,
968
                extra_size/1024.0,
969
                100.0*(total_size - raw)/raw
970
        );
971
    }
972
}
973

    
974
/* pkt = NULL means EOF (needed to flush decoder buffers) */
975
static int output_packet(AVInputStream *ist, int ist_index,
976
                         AVOutputStream **ost_table, int nb_ostreams,
977
                         AVPacket *pkt)
978
{
979
    AVFormatContext *os;
980
    AVOutputStream *ost;
981
    uint8_t *ptr;
982
    int len, ret, i;
983
    uint8_t *data_buf;
984
    int data_size, got_picture;
985
    AVFrame picture;
986
    short samples[AVCODEC_MAX_AUDIO_FRAME_SIZE / 2];
987
    void *buffer_to_free;
988
    
989
    if (pkt && pkt->pts != AV_NOPTS_VALUE) {
990
        ist->pts = pkt->pts;
991
    } else {
992
        ist->pts = ist->next_pts;
993
    }
994
    
995
    if (pkt == NULL) {
996
        /* EOF handling */
997
        ptr = NULL;
998
        len = 0;
999
        goto handle_eof;
1000
    }
1001

    
1002
    len = pkt->size;
1003
    ptr = pkt->data;
1004
    while (len > 0) {
1005
    handle_eof:
1006
        /* decode the packet if needed */
1007
        data_buf = NULL; /* fail safe */
1008
        data_size = 0;
1009
        if (ist->decoding_needed) {
1010
            switch(ist->st->codec.codec_type) {
1011
            case CODEC_TYPE_AUDIO:
1012
                    /* XXX: could avoid copy if PCM 16 bits with same
1013
                       endianness as CPU */
1014
                ret = avcodec_decode_audio(&ist->st->codec, samples, &data_size,
1015
                                           ptr, len);
1016
                if (ret < 0)
1017
                    goto fail_decode;
1018
                ptr += ret;
1019
                len -= ret;
1020
                /* Some bug in mpeg audio decoder gives */
1021
                /* data_size < 0, it seems they are overflows */
1022
                if (data_size <= 0) {
1023
                    /* no audio frame */
1024
                    continue;
1025
                }
1026
                data_buf = (uint8_t *)samples;
1027
                ist->next_pts += ((int64_t)AV_TIME_BASE * data_size) / 
1028
                    (2 * ist->st->codec.channels);
1029
                break;
1030
            case CODEC_TYPE_VIDEO:
1031
                    data_size = (ist->st->codec.width * ist->st->codec.height * 3) / 2;
1032
                    /* XXX: allocate picture correctly */
1033
                    avcodec_get_frame_defaults(&picture);
1034

    
1035
                    ret = avcodec_decode_video(&ist->st->codec, 
1036
                                               &picture, &got_picture, ptr, len);
1037
                    ist->st->quality= picture.quality;
1038
                    if (ret < 0) 
1039
                        goto fail_decode;
1040
                    if (!got_picture) {
1041
                        /* no picture yet */
1042
                        goto discard_packet;
1043
                    }
1044
                    if (ist->st->codec.frame_rate_base != 0) {
1045
                        ist->next_pts += ((int64_t)AV_TIME_BASE * 
1046
                                          ist->st->codec.frame_rate_base) /
1047
                            ist->st->codec.frame_rate;
1048
                    }
1049
                    len = 0;
1050
                    break;
1051
                default:
1052
                    goto fail_decode;
1053
                }
1054
            } else {
1055
                data_buf = ptr;
1056
                data_size = len;
1057
                ret = len;
1058
                len = 0;
1059
            }
1060

    
1061
            buffer_to_free = NULL;
1062
            if (ist->st->codec.codec_type == CODEC_TYPE_VIDEO) {
1063
                pre_process_video_frame(ist, (AVPicture *)&picture, 
1064
                                        &buffer_to_free);
1065
            }
1066

    
1067
            /* frame rate emulation */
1068
            if (ist->st->codec.rate_emu) {
1069
                int64_t pts = av_rescale((int64_t) ist->frame * ist->st->codec.frame_rate_base, 1000000, ist->st->codec.frame_rate);
1070
                int64_t now = av_gettime() - ist->start;
1071
                if (pts > now)
1072
                    usleep(pts - now);
1073

    
1074
                ist->frame++;
1075
            }
1076

    
1077
#if 0
1078
            /* mpeg PTS deordering : if it is a P or I frame, the PTS
1079
               is the one of the next displayed one */
1080
            /* XXX: add mpeg4 too ? */
1081
            if (ist->st->codec.codec_id == CODEC_ID_MPEG1VIDEO) {
1082
                if (ist->st->codec.pict_type != B_TYPE) {
1083
                    int64_t tmp;
1084
                    tmp = ist->last_ip_pts;
1085
                    ist->last_ip_pts  = ist->frac_pts.val;
1086
                    ist->frac_pts.val = tmp;
1087
                }
1088
            }
1089
#endif
1090
            /* if output time reached then transcode raw format, 
1091
               encode packets and output them */
1092
            if (start_time == 0 || ist->pts >= start_time)
1093
                for(i=0;i<nb_ostreams;i++) {
1094
                    int frame_size;
1095

    
1096
                    ost = ost_table[i];
1097
                    if (ost->source_index == ist_index) {
1098
                        os = output_files[ost->file_index];
1099

    
1100
#if 0
1101
                        printf("%d: got pts=%0.3f %0.3f\n", i, 
1102
                               (double)pkt->pts / AV_TIME_BASE, 
1103
                               ((double)ist->pts / AV_TIME_BASE) - 
1104
                               ((double)ost->st->pts.val * os->pts_num / os->pts_den));
1105
#endif
1106
                        /* set the input output pts pairs */
1107
                        ost->sync_ipts = (double)ist->pts / AV_TIME_BASE;
1108
                        /* XXX: take into account the various fifos,
1109
                           in particular for audio */
1110
                        ost->sync_opts = ost->st->pts.val;
1111
                        //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); 
1112

    
1113
                        if (ost->encoding_needed) {
1114
                            switch(ost->st->codec.codec_type) {
1115
                            case CODEC_TYPE_AUDIO:
1116
                                do_audio_out(os, ost, ist, data_buf, data_size);
1117
                                break;
1118
                            case CODEC_TYPE_VIDEO:
1119
                                /* find an audio stream for synchro */
1120
                                {
1121
                                    int i;
1122
                                    AVOutputStream *audio_sync, *ost1;
1123
                                    audio_sync = NULL;
1124
                                    for(i=0;i<nb_ostreams;i++) {
1125
                                        ost1 = ost_table[i];
1126
                                        if (ost1->file_index == ost->file_index &&
1127
                                            ost1->st->codec.codec_type == CODEC_TYPE_AUDIO) {
1128
                                            audio_sync = ost1;
1129
                                            break;
1130
                                        }
1131
                                    }
1132

    
1133
                                    do_video_out(os, ost, ist, &picture, &frame_size, audio_sync);
1134
                                    video_size += frame_size;
1135
                                    if (do_vstats && frame_size)
1136
                                        do_video_stats(os, ost, frame_size);
1137
                                }
1138
                                break;
1139
                            default:
1140
                                av_abort();
1141
                            }
1142
                        } else {
1143
                            AVFrame avframe;
1144
                                                
1145
                            /* no reencoding needed : output the packet directly */
1146
                            /* force the input stream PTS */
1147
                        
1148
                            avcodec_get_frame_defaults(&avframe);
1149
                            ost->st->codec.coded_frame= &avframe;
1150
                            avframe.key_frame = pkt->flags & PKT_FLAG_KEY; 
1151
                            ost->st->pts.val= av_rescale(ist->pts, os->pts_den, os->pts_num*AV_TIME_BASE);
1152

    
1153
                            av_write_frame(os, ost->index, data_buf, data_size);
1154
                            ost->st->codec.frame_number++;
1155
                            ost->frame_number++;
1156
                        }
1157
                    }
1158
                }
1159
            av_free(buffer_to_free);
1160
        }
1161
 discard_packet:
1162
    return 0;
1163
 fail_decode:
1164
    return -1;
1165
}
1166

    
1167

    
1168
/*
1169
 * The following code is the main loop of the file converter
1170
 */
1171
static int av_encode(AVFormatContext **output_files,
1172
                     int nb_output_files,
1173
                     AVFormatContext **input_files,
1174
                     int nb_input_files,
1175
                     AVStreamMap *stream_maps, int nb_stream_maps)
1176
{
1177
    int ret, i, j, k, n, nb_istreams = 0, nb_ostreams = 0;
1178
    AVFormatContext *is, *os;
1179
    AVCodecContext *codec, *icodec;
1180
    AVOutputStream *ost, **ost_table = NULL;
1181
    AVInputStream *ist, **ist_table = NULL;
1182
    AVInputFile *file_table;
1183
    AVFormatContext *stream_no_data;
1184
    int key;
1185

    
1186
    file_table= (AVInputFile*) av_mallocz(nb_input_files * sizeof(AVInputFile));
1187
    if (!file_table)
1188
        goto fail;
1189

    
1190
    /* input stream init */
1191
    j = 0;
1192
    for(i=0;i<nb_input_files;i++) {
1193
        is = input_files[i];
1194
        file_table[i].ist_index = j;
1195
        file_table[i].nb_streams = is->nb_streams;
1196
        j += is->nb_streams;
1197
    }
1198
    nb_istreams = j;
1199

    
1200
    ist_table = av_mallocz(nb_istreams * sizeof(AVInputStream *));
1201
    if (!ist_table)
1202
        goto fail;
1203
    
1204
    for(i=0;i<nb_istreams;i++) {
1205
        ist = av_mallocz(sizeof(AVInputStream));
1206
        if (!ist)
1207
            goto fail;
1208
        ist_table[i] = ist;
1209
    }
1210
    j = 0;
1211
    for(i=0;i<nb_input_files;i++) {
1212
        is = input_files[i];
1213
        for(k=0;k<is->nb_streams;k++) {
1214
            ist = ist_table[j++];
1215
            ist->st = is->streams[k];
1216
            ist->file_index = i;
1217
            ist->index = k;
1218
            ist->discard = 1; /* the stream is discarded by default
1219
                                 (changed later) */
1220

    
1221
            if (ist->st->codec.rate_emu) {
1222
                ist->start = av_gettime();
1223
                ist->frame = 0;
1224
            }
1225
        }
1226
    }
1227

    
1228
    /* output stream init */
1229
    nb_ostreams = 0;
1230
    for(i=0;i<nb_output_files;i++) {
1231
        os = output_files[i];
1232
        nb_ostreams += os->nb_streams;
1233
    }
1234
    if (nb_stream_maps > 0 && nb_stream_maps != nb_ostreams) {
1235
        fprintf(stderr, "Number of stream maps must match number of output streams\n");
1236
        exit(1);
1237
    }
1238

    
1239
    /* Sanity check the mapping args -- do the input files & streams exist? */
1240
    for(i=0;i<nb_stream_maps;i++) {
1241
        int fi = stream_maps[i].file_index;
1242
        int si = stream_maps[i].stream_index;
1243
        
1244
        if (fi < 0 || fi > nb_input_files - 1 ||
1245
            si < 0 || si > file_table[fi].nb_streams - 1) {
1246
            fprintf(stderr,"Could not find input stream #%d.%d\n", fi, si);
1247
            exit(1);
1248
        }
1249
    }
1250
    
1251
    ost_table = av_mallocz(sizeof(AVOutputStream *) * nb_ostreams);
1252
    if (!ost_table)
1253
        goto fail;
1254
    for(i=0;i<nb_ostreams;i++) {
1255
        ost = av_mallocz(sizeof(AVOutputStream));
1256
        if (!ost)
1257
            goto fail;
1258
        ost_table[i] = ost;
1259
    }
1260
    
1261
    n = 0;
1262
    for(k=0;k<nb_output_files;k++) {
1263
        os = output_files[k];
1264
        for(i=0;i<os->nb_streams;i++) {
1265
            int found;
1266
            ost = ost_table[n++];
1267
            ost->file_index = k;
1268
            ost->index = i;
1269
            ost->st = os->streams[i];
1270
            if (nb_stream_maps > 0) {
1271
                ost->source_index = file_table[stream_maps[n-1].file_index].ist_index + 
1272
                    stream_maps[n-1].stream_index;
1273
                    
1274
                /* Sanity check that the stream types match */
1275
                if (ist_table[ost->source_index]->st->codec.codec_type != ost->st->codec.codec_type) {
1276
                    fprintf(stderr, "Codec type mismatch for mapping #%d.%d -> #%d.%d\n",
1277
                        stream_maps[n-1].file_index, stream_maps[n-1].stream_index,
1278
                        ost->file_index, ost->index);
1279
                    exit(1);
1280
                }
1281
                
1282
            } else {
1283
                /* get corresponding input stream index : we select the first one with the right type */
1284
                found = 0;
1285
                for(j=0;j<nb_istreams;j++) {
1286
                    ist = ist_table[j];
1287
                    if (ist->discard && 
1288
                        ist->st->codec.codec_type == ost->st->codec.codec_type) {
1289
                        ost->source_index = j;
1290
                        found = 1;
1291
                    }
1292
                }
1293
                
1294
                if (!found) {
1295
                    /* try again and reuse existing stream */
1296
                    for(j=0;j<nb_istreams;j++) {
1297
                        ist = ist_table[j];
1298
                        if (ist->st->codec.codec_type == ost->st->codec.codec_type) {
1299
                            ost->source_index = j;
1300
                            found = 1;
1301
                        }
1302
                    }
1303
                    if (!found) {
1304
                        fprintf(stderr, "Could not find input stream matching output stream #%d.%d\n",
1305
                                ost->file_index, ost->index);
1306
                        exit(1);
1307
                    }
1308
                }
1309
            }
1310
            ist = ist_table[ost->source_index];
1311
            ist->discard = 0;
1312
        }
1313
    }
1314

    
1315
    /* for each output stream, we compute the right encoding parameters */
1316
    for(i=0;i<nb_ostreams;i++) {
1317
        ost = ost_table[i];
1318
        ist = ist_table[ost->source_index];
1319

    
1320
        codec = &ost->st->codec;
1321
        icodec = &ist->st->codec;
1322

    
1323
        if (ost->st->stream_copy) {
1324
            /* if stream_copy is selected, no need to decode or encode */
1325
            codec->codec_id = icodec->codec_id;
1326
            codec->codec_type = icodec->codec_type;
1327
            codec->codec_tag = icodec->codec_tag;
1328
            codec->bit_rate = icodec->bit_rate;
1329
            switch(codec->codec_type) {
1330
            case CODEC_TYPE_AUDIO:
1331
                codec->sample_rate = icodec->sample_rate;
1332
                codec->channels = icodec->channels;
1333
                codec->frame_size = icodec->frame_size;
1334
                break;
1335
            case CODEC_TYPE_VIDEO:
1336
                codec->frame_rate = icodec->frame_rate;
1337
                codec->frame_rate_base = icodec->frame_rate_base;
1338
                codec->width = icodec->width;
1339
                codec->height = icodec->height;
1340
                break;
1341
            default:
1342
                av_abort();
1343
            }
1344
        } else {
1345
            switch(codec->codec_type) {
1346
            case CODEC_TYPE_AUDIO:
1347
                if (fifo_init(&ost->fifo, 2 * MAX_AUDIO_PACKET_SIZE))
1348
                    goto fail;
1349
                
1350
                if (codec->channels == icodec->channels &&
1351
                    codec->sample_rate == icodec->sample_rate) {
1352
                    ost->audio_resample = 0;
1353
                } else {
1354
                    if (codec->channels != icodec->channels &&
1355
                        icodec->codec_id == CODEC_ID_AC3) {
1356
                        /* Special case for 5:1 AC3 input */
1357
                        /* and mono or stereo output      */
1358
                        /* Request specific number of channels */
1359
                        icodec->channels = codec->channels;
1360
                        if (codec->sample_rate == icodec->sample_rate)
1361
                            ost->audio_resample = 0;
1362
                        else {
1363
                            ost->audio_resample = 1;
1364
                            ost->resample = audio_resample_init(codec->channels, icodec->channels,
1365
                                                        codec->sample_rate, 
1366
                                                        icodec->sample_rate);
1367
                            if(!ost->resample)
1368
                              {
1369
                                printf("Can't resample.  Aborting.\n");
1370
                                av_abort();
1371
                              }
1372
                        }
1373
                        /* Request specific number of channels */
1374
                        icodec->channels = codec->channels;
1375
                    } else {
1376
                        ost->audio_resample = 1; 
1377
                        ost->resample = audio_resample_init(codec->channels, icodec->channels,
1378
                                                        codec->sample_rate, 
1379
                                                        icodec->sample_rate);
1380
                        if(!ost->resample)
1381
                          {
1382
                            printf("Can't resample.  Aborting.\n");
1383
                            av_abort();
1384
                          }
1385
                    }
1386
                }
1387
                ist->decoding_needed = 1;
1388
                ost->encoding_needed = 1;
1389
                break;
1390
            case CODEC_TYPE_VIDEO:
1391
                if (codec->width == icodec->width &&
1392
                    codec->height == icodec->height &&
1393
                    frame_topBand == 0 &&
1394
                    frame_bottomBand == 0 &&
1395
                    frame_leftBand == 0 &&
1396
                    frame_rightBand == 0 && 
1397
                    frame_padtop == 0 &&
1398
                    frame_padbottom == 0 &&
1399
                    frame_padleft == 0 &&
1400
                    frame_padright == 0)
1401
                {
1402
                    ost->video_resample = 0;
1403
                    ost->video_crop = 0;
1404
                    ost->video_pad = 0;
1405
                } else if ((codec->width == icodec->width -
1406
                                (frame_leftBand + frame_rightBand)) &&
1407
                        (codec->height == icodec->height -
1408
                                (frame_topBand  + frame_bottomBand)))
1409
                {
1410
                    ost->video_resample = 0;
1411
                    ost->video_crop = 1;
1412
                    ost->topBand = frame_topBand;
1413
                    ost->leftBand = frame_leftBand;
1414
                } else if ((codec->width == icodec->width + 
1415
                                (frame_padleft + frame_padright)) &&
1416
                        (codec->height == icodec->height +
1417
                                (frame_padtop + frame_padbottom))) {
1418
                    ost->video_resample = 0;
1419
                    ost->video_crop = 0;
1420
                    ost->video_pad = 1;
1421
                    ost->padtop = frame_padtop;
1422
                    ost->padleft = frame_padleft;
1423
                    ost->padbottom = frame_padbottom;
1424
                    ost->padright = frame_padright;
1425
                    avcodec_get_frame_defaults(&ost->pict_tmp);
1426
                    if( avpicture_alloc( (AVPicture*)&ost->pict_tmp, PIX_FMT_YUV420P,
1427
                                codec->width, codec->height ) )
1428
                        goto fail;
1429
                } else {
1430
                    ost->video_resample = 1;
1431
                    ost->video_crop = 0; // cropping is handled as part of resample
1432
                    avcodec_get_frame_defaults(&ost->pict_tmp);
1433
                    if( avpicture_alloc( (AVPicture*)&ost->pict_tmp, PIX_FMT_YUV420P,
1434
                                         codec->width, codec->height ) )
1435
                        goto fail;
1436

    
1437
                    ost->img_resample_ctx = img_resample_full_init( 
1438
                                      ost->st->codec.width, ost->st->codec.height,
1439
                                      ist->st->codec.width, ist->st->codec.height,
1440
                                      frame_topBand, frame_bottomBand,
1441
                            frame_leftBand, frame_rightBand, 
1442
                            frame_padtop, frame_padbottom, 
1443
                            frame_padleft, frame_padright);
1444
                    
1445
                    ost->padtop = frame_padtop;
1446
                    ost->padleft = frame_padleft;
1447
                    ost->padbottom = frame_padbottom;
1448
                    ost->padright = frame_padright;
1449
                   
1450
                }
1451
                ost->encoding_needed = 1;
1452
                ist->decoding_needed = 1;
1453
                break;
1454
            default:
1455
                av_abort();
1456
            }
1457
            /* two pass mode */
1458
            if (ost->encoding_needed && 
1459
                (codec->flags & (CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2))) {
1460
                char logfilename[1024];
1461
                FILE *f;
1462
                int size;
1463
                char *logbuffer;
1464
                
1465
                snprintf(logfilename, sizeof(logfilename), "%s-%d.log", 
1466
                         pass_logfilename ? 
1467
                         pass_logfilename : DEFAULT_PASS_LOGFILENAME, i);
1468
                if (codec->flags & CODEC_FLAG_PASS1) {
1469
                    f = fopen(logfilename, "w");
1470
                    if (!f) {
1471
                        perror(logfilename);
1472
                        exit(1);
1473
                    }
1474
                    ost->logfile = f;
1475
                } else {
1476
                    /* read the log file */
1477
                    f = fopen(logfilename, "r");
1478
                    if (!f) {
1479
                        perror(logfilename);
1480
                        exit(1);
1481
                    }
1482
                    fseek(f, 0, SEEK_END);
1483
                    size = ftell(f);
1484
                    fseek(f, 0, SEEK_SET);
1485
                    logbuffer = av_malloc(size + 1);
1486
                    if (!logbuffer) {
1487
                        fprintf(stderr, "Could not allocate log buffer\n");
1488
                        exit(1);
1489
                    }
1490
                    size = fread(logbuffer, 1, size, f);
1491
                    fclose(f);
1492
                    logbuffer[size] = '\0';
1493
                    codec->stats_in = logbuffer;
1494
                }
1495
            }
1496
        }
1497
    }
1498

    
1499
    /* dump the file output parameters - cannot be done before in case
1500
       of stream copy */
1501
    for(i=0;i<nb_output_files;i++) {
1502
        dump_format(output_files[i], i, output_files[i]->filename, 1);
1503
    }
1504

    
1505
    /* dump the stream mapping */
1506
    if (verbose >= 0) {
1507
        fprintf(stderr, "Stream mapping:\n");
1508
        for(i=0;i<nb_ostreams;i++) {
1509
            ost = ost_table[i];
1510
            fprintf(stderr, "  Stream #%d.%d -> #%d.%d\n",
1511
                    ist_table[ost->source_index]->file_index,
1512
                    ist_table[ost->source_index]->index,
1513
                    ost->file_index, 
1514
                    ost->index);
1515
        }
1516
    }
1517

    
1518
    /* open each encoder */
1519
    for(i=0;i<nb_ostreams;i++) {
1520
        ost = ost_table[i];
1521
        if (ost->encoding_needed) {
1522
            AVCodec *codec;
1523
            codec = avcodec_find_encoder(ost->st->codec.codec_id);
1524
            if (!codec) {
1525
                fprintf(stderr, "Unsupported codec for output stream #%d.%d\n", 
1526
                        ost->file_index, ost->index);
1527
                exit(1);
1528
            }
1529
            if (avcodec_open(&ost->st->codec, codec) < 0) {
1530
                fprintf(stderr, "Error while opening codec for stream #%d.%d - maybe incorrect parameters such as bit_rate, rate, width or height\n", 
1531
                        ost->file_index, ost->index);
1532
                exit(1);
1533
            }
1534
            extra_size += ost->st->codec.extradata_size;
1535
        }
1536
    }
1537

    
1538
    /* open each decoder */
1539
    for(i=0;i<nb_istreams;i++) {
1540
        ist = ist_table[i];
1541
        if (ist->decoding_needed) {
1542
            AVCodec *codec;
1543
            codec = avcodec_find_decoder(ist->st->codec.codec_id);
1544
            if (!codec) {
1545
                fprintf(stderr, "Unsupported codec (id=%d) for input stream #%d.%d\n", 
1546
                        ist->st->codec.codec_id, ist->file_index, ist->index);
1547
                exit(1);
1548
            }
1549
            if (avcodec_open(&ist->st->codec, codec) < 0) {
1550
                fprintf(stderr, "Error while opening codec for input stream #%d.%d\n", 
1551
                        ist->file_index, ist->index);
1552
                exit(1);
1553
            }
1554
            //if (ist->st->codec.codec_type == CODEC_TYPE_VIDEO)
1555
            //    ist->st->codec.flags |= CODEC_FLAG_REPEAT_FIELD;
1556
        }
1557
    }
1558

    
1559
    /* init pts */
1560
    for(i=0;i<nb_istreams;i++) {
1561
        ist = ist_table[i];
1562
        is = input_files[ist->file_index];
1563
        ist->pts = 0;
1564
        ist->next_pts = 0;
1565
    }
1566
    
1567
    /* compute buffer size max (should use a complete heuristic) */
1568
    for(i=0;i<nb_input_files;i++) {
1569
        file_table[i].buffer_size_max = 2048;
1570
    }
1571

    
1572
    /* open files and write file headers */
1573
    for(i=0;i<nb_output_files;i++) {
1574
        os = output_files[i];
1575
        if (av_write_header(os) < 0) {
1576
            fprintf(stderr, "Could not write header for output file #%d (incorrect codec paramters ?)\n", i);
1577
            ret = -EINVAL;
1578
            goto fail;
1579
        }
1580
    }
1581

    
1582
#ifndef CONFIG_WIN32
1583
    if ( !using_stdin && verbose >= 0) {
1584
        fprintf(stderr, "Press [q] to stop encoding\n");
1585
        url_set_interrupt_cb(decode_interrupt_cb);
1586
    }
1587
#endif
1588
    term_init();
1589

    
1590
    stream_no_data = 0;
1591
    key = -1;
1592

    
1593
    for(; received_sigterm == 0;) {
1594
        int file_index, ist_index;
1595
        AVPacket pkt;
1596
        double pts_min;
1597
        
1598
    redo:
1599
        /* if 'q' pressed, exits */
1600
        if (!using_stdin) {
1601
            if (q_pressed)
1602
                break;
1603
            /* read_key() returns 0 on EOF */
1604
            key = read_key();
1605
            if (key == 'q')
1606
                break;
1607
        }
1608

    
1609
        /* select the stream that we must read now by looking at the
1610
           smallest output pts */
1611
        file_index = -1;
1612
        pts_min = 1e10;
1613
        for(i=0;i<nb_ostreams;i++) {
1614
            double pts;
1615
            ost = ost_table[i];
1616
            os = output_files[ost->file_index];
1617
            ist = ist_table[ost->source_index];
1618
            pts = (double)ost->st->pts.val * os->pts_num / os->pts_den;
1619
            if (!file_table[ist->file_index].eof_reached && 
1620
                pts < pts_min) {
1621
                pts_min = pts;
1622
                file_index = ist->file_index;
1623
            }
1624
        }
1625
        /* if none, if is finished */
1626
        if (file_index < 0) {
1627
            break;
1628
        }
1629

    
1630
        /* finish if recording time exhausted */
1631
        if (recording_time > 0 && pts_min >= (recording_time / 1000000.0))
1632
            break;
1633

    
1634
        /* read a frame from it and output it in the fifo */
1635
        is = input_files[file_index];
1636
        if (av_read_frame(is, &pkt) < 0) {
1637
            file_table[file_index].eof_reached = 1;
1638
            continue;
1639
        }
1640

    
1641
        if (!pkt.size) {
1642
            stream_no_data = is;
1643
        } else {
1644
            stream_no_data = 0;
1645
        }
1646
        if (do_pkt_dump) {
1647
            av_pkt_dump(stdout, &pkt, do_hex_dump);
1648
        }
1649
        /* the following test is needed in case new streams appear
1650
           dynamically in stream : we ignore them */
1651
        if (pkt.stream_index >= file_table[file_index].nb_streams)
1652
            goto discard_packet;
1653
        ist_index = file_table[file_index].ist_index + pkt.stream_index;
1654
        ist = ist_table[ist_index];
1655
        if (ist->discard)
1656
            goto discard_packet;
1657

    
1658
        //fprintf(stderr,"read #%d.%d size=%d\n", ist->file_index, ist->index, pkt.size);
1659
        if (output_packet(ist, ist_index, ost_table, nb_ostreams, &pkt) < 0) {
1660

    
1661
            if (verbose >= 0)
1662
                fprintf(stderr, "Error while decoding stream #%d.%d\n",
1663
                        ist->file_index, ist->index);
1664

    
1665
            av_free_packet(&pkt);
1666
            goto redo;
1667
        }
1668
        
1669
    discard_packet:
1670
        av_free_packet(&pkt);
1671
        
1672
        /* dump report by using the output first video and audio streams */
1673
        print_report(output_files, ost_table, nb_ostreams, 0);
1674
    }
1675

    
1676
    /* at the end of stream, we must flush the decoder buffers */
1677
    for(i=0;i<nb_istreams;i++) {
1678
        ist = ist_table[i];
1679
        if (ist->decoding_needed) {
1680
            output_packet(ist, i, ost_table, nb_ostreams, NULL);
1681
        }
1682
    }
1683

    
1684
    term_exit();
1685

    
1686
    /* write the trailer if needed and close file */
1687
    for(i=0;i<nb_output_files;i++) {
1688
        os = output_files[i];
1689
        av_write_trailer(os);
1690
    }
1691

    
1692
    /* dump report by using the first video and audio streams */
1693
    print_report(output_files, ost_table, nb_ostreams, 1);
1694

    
1695
    /* close each encoder */
1696
    for(i=0;i<nb_ostreams;i++) {
1697
        ost = ost_table[i];
1698
        if (ost->encoding_needed) {
1699
            av_freep(&ost->st->codec.stats_in);
1700
            avcodec_close(&ost->st->codec);
1701
        }
1702
    }
1703
    
1704
    /* close each decoder */
1705
    for(i=0;i<nb_istreams;i++) {
1706
        ist = ist_table[i];
1707
        if (ist->decoding_needed) {
1708
            avcodec_close(&ist->st->codec);
1709
        }
1710
    }
1711

    
1712
    /* finished ! */
1713
    
1714
    ret = 0;
1715
 fail1:
1716
    av_free(file_table);
1717

    
1718
    if (ist_table) {
1719
        for(i=0;i<nb_istreams;i++) {
1720
            ist = ist_table[i];
1721
            av_free(ist);
1722
        }
1723
        av_free(ist_table);
1724
    }
1725
    if (ost_table) {
1726
        for(i=0;i<nb_ostreams;i++) {
1727
            ost = ost_table[i];
1728
            if (ost) {
1729
                if (ost->logfile) {
1730
                    fclose(ost->logfile);
1731
                    ost->logfile = NULL;
1732
                }
1733
                fifo_free(&ost->fifo); /* works even if fifo is not
1734
                                          initialized but set to zero */
1735
                av_free(ost->pict_tmp.data[0]);
1736
                if (ost->video_resample)
1737
                    img_resample_close(ost->img_resample_ctx);
1738
                if (ost->audio_resample)
1739
                    audio_resample_close(ost->resample);
1740
                av_free(ost);
1741
            }
1742
        }
1743
        av_free(ost_table);
1744
    }
1745
    return ret;
1746
 fail:
1747
    ret = -ENOMEM;
1748
    goto fail1;
1749
}
1750

    
1751
#if 0
1752
int file_read(const char *filename)
1753
{
1754
    URLContext *h;
1755
    unsigned char buffer[1024];
1756
    int len, i;
1757

1758
    if (url_open(&h, filename, O_RDONLY) < 0) {
1759
        printf("could not open '%s'\n", filename);
1760
        return -1;
1761
    }
1762
    for(;;) {
1763
        len = url_read(h, buffer, sizeof(buffer));
1764
        if (len <= 0)
1765
            break;
1766
        for(i=0;i<len;i++) putchar(buffer[i]);
1767
    }
1768
    url_close(h);
1769
    return 0;
1770
}
1771
#endif
1772

    
1773
static void opt_image_format(const char *arg)
1774
{
1775
    AVImageFormat *f;
1776
    
1777
    for(f = first_image_format; f != NULL; f = f->next) {
1778
        if (!strcmp(arg, f->name))
1779
            break;
1780
    }
1781
    if (!f) {
1782
        fprintf(stderr, "Unknown image format: '%s'\n", arg);
1783
        exit(1);
1784
    }
1785
    image_format = f;
1786
}
1787

    
1788
static void opt_format(const char *arg)
1789
{
1790
    /* compatibility stuff for pgmyuv */
1791
    if (!strcmp(arg, "pgmyuv")) {
1792
        opt_image_format(arg);
1793
        arg = "image";
1794
    }
1795

    
1796
    file_iformat = av_find_input_format(arg);
1797
    file_oformat = guess_format(arg, NULL, NULL);
1798
    if (!file_iformat && !file_oformat) {
1799
        fprintf(stderr, "Unknown input or output format: %s\n", arg);
1800
        exit(1);
1801
    }
1802
}
1803

    
1804
static void opt_video_bitrate(const char *arg)
1805
{
1806
    video_bit_rate = atoi(arg) * 1000;
1807
}
1808

    
1809
static void opt_video_bitrate_tolerance(const char *arg)
1810
{
1811
    video_bit_rate_tolerance = atoi(arg) * 1000;
1812
}
1813

    
1814
static void opt_video_bitrate_max(const char *arg)
1815
{
1816
    video_rc_max_rate = atoi(arg) * 1000;
1817
}
1818

    
1819
static void opt_video_bitrate_min(const char *arg)
1820
{
1821
    video_rc_min_rate = atoi(arg) * 1000;
1822
}
1823

    
1824
static void opt_video_buffer_size(const char *arg)
1825
{
1826
    video_rc_buffer_size = atoi(arg) * 8*1024;
1827
}
1828

    
1829
static void opt_video_rc_eq(char *arg)
1830
{
1831
    video_rc_eq = arg;
1832
}
1833

    
1834
static void opt_video_rc_override_string(char *arg)
1835
{
1836
    video_rc_override_string = arg;
1837
}
1838

    
1839

    
1840
static void opt_workaround_bugs(const char *arg)
1841
{
1842
    workaround_bugs = atoi(arg);
1843
}
1844

    
1845
static void opt_dct_algo(const char *arg)
1846
{
1847
    dct_algo = atoi(arg);
1848
}
1849

    
1850
static void opt_idct_algo(const char *arg)
1851
{
1852
    idct_algo = atoi(arg);
1853
}
1854

    
1855

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

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

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

    
1871
static void opt_vismv(const char *arg)
1872
{
1873
    debug_mv = atoi(arg);
1874
}
1875
    
1876
static void opt_verbose(const char *arg)
1877
{
1878
    verbose = atoi(arg);
1879
    av_log_set_level(atoi(arg));
1880
}
1881

    
1882
static void opt_frame_rate(const char *arg)
1883
{
1884
    if (parse_frame_rate(&frame_rate, &frame_rate_base, arg) < 0) {
1885
        fprintf(stderr, "Incorrect frame rate\n");
1886
        exit(1);
1887
    }
1888
}
1889

    
1890
static void opt_frame_crop_top(const char *arg)
1891
{
1892
    frame_topBand = atoi(arg); 
1893
    if (frame_topBand < 0) {
1894
        fprintf(stderr, "Incorrect top crop size\n");
1895
        exit(1);
1896
    }
1897
    if ((frame_topBand % 2) != 0) {
1898
        fprintf(stderr, "Top crop size must be a multiple of 2\n");
1899
        exit(1);
1900
    }
1901
    if ((frame_topBand) >= frame_height){
1902
            fprintf(stderr, "Vertical crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
1903
        exit(1);
1904
    }
1905
    frame_height -= frame_topBand;
1906
}
1907

    
1908
static void opt_frame_crop_bottom(const char *arg)
1909
{
1910
    frame_bottomBand = atoi(arg);
1911
    if (frame_bottomBand < 0) {
1912
        fprintf(stderr, "Incorrect bottom crop size\n");
1913
        exit(1);
1914
    }
1915
    if ((frame_bottomBand % 2) != 0) {
1916
        fprintf(stderr, "Bottom crop size must be a multiple of 2\n");
1917
        exit(1);        
1918
    }
1919
    if ((frame_bottomBand) >= frame_height){
1920
            fprintf(stderr, "Vertical crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
1921
        exit(1);
1922
    }
1923
    frame_height -= frame_bottomBand;
1924
}
1925

    
1926
static void opt_frame_crop_left(const char *arg)
1927
{
1928
    frame_leftBand = atoi(arg);
1929
    if (frame_leftBand < 0) {
1930
        fprintf(stderr, "Incorrect left crop size\n");
1931
        exit(1);
1932
    }
1933
    if ((frame_leftBand % 2) != 0) {
1934
        fprintf(stderr, "Left crop size must be a multiple of 2\n");
1935
        exit(1);
1936
    }
1937
    if ((frame_leftBand) >= frame_width){
1938
            fprintf(stderr, "Horizontal crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
1939
        exit(1);
1940
    }
1941
    frame_width -= frame_leftBand;
1942
}
1943

    
1944
static void opt_frame_crop_right(const char *arg)
1945
{
1946
    frame_rightBand = atoi(arg);
1947
    if (frame_rightBand < 0) {
1948
        fprintf(stderr, "Incorrect right crop size\n");
1949
        exit(1);
1950
    }
1951
    if ((frame_rightBand % 2) != 0) {
1952
        fprintf(stderr, "Right crop size must be a multiple of 2\n");
1953
        exit(1);        
1954
    }
1955
    if ((frame_rightBand) >= frame_width){
1956
            fprintf(stderr, "Horizontal crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
1957
        exit(1);
1958
    }
1959
    frame_width -= frame_rightBand;
1960
}
1961

    
1962
static void opt_frame_size(const char *arg)
1963
{
1964
    if (parse_image_size(&frame_width, &frame_height, arg) < 0) {
1965
        fprintf(stderr, "Incorrect frame size\n");
1966
        exit(1);
1967
    }
1968
    if ((frame_width % 2) != 0 || (frame_height % 2) != 0) {
1969
        fprintf(stderr, "Frame size must be a multiple of 2\n");
1970
        exit(1);
1971
    }
1972
}
1973

    
1974

    
1975
#define SCALEBITS 10
1976
#define ONE_HALF  (1 << (SCALEBITS - 1))
1977
#define FIX(x)          ((int) ((x) * (1<<SCALEBITS) + 0.5))
1978

    
1979
#define RGB_TO_Y(r, g, b) \
1980
((FIX(0.29900) * (r) + FIX(0.58700) * (g) + \
1981
  FIX(0.11400) * (b) + ONE_HALF) >> SCALEBITS)
1982

    
1983
#define RGB_TO_U(r1, g1, b1, shift)\
1984
(((- FIX(0.16874) * r1 - FIX(0.33126) * g1 +         \
1985
     FIX(0.50000) * b1 + (ONE_HALF << shift) - 1) >> (SCALEBITS + shift)) + 128)
1986

    
1987
#define RGB_TO_V(r1, g1, b1, shift)\
1988
(((FIX(0.50000) * r1 - FIX(0.41869) * g1 -           \
1989
   FIX(0.08131) * b1 + (ONE_HALF << shift) - 1) >> (SCALEBITS + shift)) + 128)
1990

    
1991
static void opt_pad_color(const char *arg) {
1992
    /* Input is expected to be six hex digits similar to
1993
       how colors are expressed in html tags (but without the #) */
1994
    int rgb = strtol(arg, NULL, 16);
1995
    int r,g,b;
1996
    
1997
    r = (rgb >> 16); 
1998
    g = ((rgb >> 8) & 255);
1999
    b = (rgb & 255);
2000

    
2001
    padcolor[0] = RGB_TO_Y(r,g,b);
2002
    padcolor[1] = RGB_TO_U(r,g,b,0);
2003
    padcolor[2] = RGB_TO_V(r,g,b,0);
2004
}
2005

    
2006
static void opt_frame_pad_top(const char *arg)
2007
{
2008
    frame_padtop = atoi(arg); 
2009
    if (frame_padtop < 0) {
2010
        fprintf(stderr, "Incorrect top pad size\n");
2011
        exit(1);
2012
    }
2013
    if ((frame_padtop % 2) != 0) {
2014
        fprintf(stderr, "Top pad size must be a multiple of 2\n");
2015
        exit(1);
2016
    }
2017
}
2018

    
2019
static void opt_frame_pad_bottom(const char *arg)
2020
{
2021
    frame_padbottom = atoi(arg); 
2022
    if (frame_padbottom < 0) {
2023
        fprintf(stderr, "Incorrect bottom pad size\n");
2024
        exit(1);
2025
    }
2026
    if ((frame_padbottom % 2) != 0) {
2027
        fprintf(stderr, "Bottom pad size must be a multiple of 2\n");
2028
        exit(1);
2029
    }
2030
}
2031

    
2032

    
2033
static void opt_frame_pad_left(const char *arg)
2034
{
2035
    frame_padleft = atoi(arg); 
2036
    if (frame_padleft < 0) {
2037
        fprintf(stderr, "Incorrect left pad size\n");
2038
        exit(1);
2039
    }
2040
    if ((frame_padleft % 2) != 0) {
2041
        fprintf(stderr, "Left pad size must be a multiple of 2\n");
2042
        exit(1);
2043
    }
2044
}
2045

    
2046

    
2047
static void opt_frame_pad_right(const char *arg)
2048
{
2049
    frame_padright = atoi(arg); 
2050
    if (frame_padright < 0) {
2051
        fprintf(stderr, "Incorrect right pad size\n");
2052
        exit(1);
2053
    }
2054
    if ((frame_padright % 2) != 0) {
2055
        fprintf(stderr, "Right pad size must be a multiple of 2\n");
2056
        exit(1);
2057
    }
2058
}
2059

    
2060

    
2061
static void opt_frame_pix_fmt(const char *arg)
2062
{
2063
    frame_pix_fmt = avcodec_get_pix_fmt(arg);
2064
}
2065

    
2066
static void opt_frame_aspect_ratio(const char *arg)
2067
{
2068
    int x = 0, y = 0;
2069
    double ar = 0;
2070
    const char *p;
2071
    
2072
    p = strchr(arg, ':');
2073
    if (p) {
2074
        x = strtol(arg, (char **)&arg, 10);
2075
        if (arg == p)
2076
            y = strtol(arg+1, (char **)&arg, 10);
2077
        if (x > 0 && y > 0)
2078
            ar = (double)x / (double)y;
2079
    } else
2080
        ar = strtod(arg, (char **)&arg);
2081

    
2082
    if (!ar) {
2083
        fprintf(stderr, "Incorrect aspect ratio specification.\n");
2084
        exit(1);
2085
    }
2086
    frame_aspect_ratio = ar;
2087
}
2088

    
2089
static void opt_gop_size(const char *arg)
2090
{
2091
    gop_size = atoi(arg);
2092
}
2093

    
2094
static void opt_b_frames(const char *arg)
2095
{
2096
    b_frames = atoi(arg);
2097
    if (b_frames > FF_MAX_B_FRAMES) {
2098
        fprintf(stderr, "\nCannot have more than %d B frames, increase FF_MAX_B_FRAMES.\n", FF_MAX_B_FRAMES);
2099
        exit(1);
2100
    } else if (b_frames < 1) {
2101
        fprintf(stderr, "\nNumber of B frames must be higher than 0\n");
2102
        exit(1);
2103
    }
2104
}
2105

    
2106
static void opt_mb_decision(const char *arg)
2107
{
2108
    mb_decision = atoi(arg);
2109
}
2110

    
2111
static void opt_mb_cmp(const char *arg)
2112
{
2113
    mb_cmp = atoi(arg);
2114
}
2115

    
2116
static void opt_ildct_cmp(const char *arg)
2117
{
2118
    ildct_cmp = atoi(arg);
2119
}
2120

    
2121
static void opt_sub_cmp(const char *arg)
2122
{
2123
    sub_cmp = atoi(arg);
2124
}
2125

    
2126
static void opt_cmp(const char *arg)
2127
{
2128
    cmp = atoi(arg);
2129
}
2130

    
2131
static void opt_pre_cmp(const char *arg)
2132
{
2133
    pre_cmp = atoi(arg);
2134
}
2135

    
2136
static void opt_pre_me(const char *arg)
2137
{
2138
    pre_me = atoi(arg);
2139
}
2140

    
2141
static void opt_lumi_mask(const char *arg)
2142
{
2143
    lumi_mask = atof(arg);
2144
}
2145

    
2146
static void opt_dark_mask(const char *arg)
2147
{
2148
    dark_mask = atof(arg);
2149
}
2150

    
2151
static void opt_scplx_mask(const char *arg)
2152
{
2153
    scplx_mask = atof(arg);
2154
}
2155

    
2156
static void opt_tcplx_mask(const char *arg)
2157
{
2158
    tcplx_mask = atof(arg);
2159
}
2160

    
2161
static void opt_p_mask(const char *arg)
2162
{
2163
    p_mask = atof(arg);
2164
}
2165

    
2166
static void opt_qscale(const char *arg)
2167
{
2168
    video_qscale = atof(arg);
2169
    if (video_qscale < 0.01 ||
2170
        video_qscale > 255) {
2171
        fprintf(stderr, "qscale must be >= 0.01 and <= 255\n");
2172
        exit(1);
2173
    }
2174
}
2175

    
2176
static void opt_qmin(const char *arg)
2177
{
2178
    video_qmin = atoi(arg);
2179
    if (video_qmin < 0 ||
2180
        video_qmin > 31) {
2181
        fprintf(stderr, "qmin must be >= 1 and <= 31\n");
2182
        exit(1);
2183
    }
2184
}
2185

    
2186
static void opt_qmax(const char *arg)
2187
{
2188
    video_qmax = atoi(arg);
2189
    if (video_qmax < 0 ||
2190
        video_qmax > 31) {
2191
        fprintf(stderr, "qmax must be >= 1 and <= 31\n");
2192
        exit(1);
2193
    }
2194
}
2195

    
2196
static void opt_mb_qmin(const char *arg)
2197
{
2198
    video_mb_qmin = atoi(arg);
2199
    if (video_mb_qmin < 0 ||
2200
        video_mb_qmin > 31) {
2201
        fprintf(stderr, "qmin must be >= 1 and <= 31\n");
2202
        exit(1);
2203
    }
2204
}
2205

    
2206
static void opt_mb_qmax(const char *arg)
2207
{
2208
    video_mb_qmax = atoi(arg);
2209
    if (video_mb_qmax < 0 ||
2210
        video_mb_qmax > 31) {
2211
        fprintf(stderr, "qmax must be >= 1 and <= 31\n");
2212
        exit(1);
2213
    }
2214
}
2215

    
2216
static void opt_qdiff(const char *arg)
2217
{
2218
    video_qdiff = atoi(arg);
2219
    if (video_qdiff < 0 ||
2220
        video_qdiff > 31) {
2221
        fprintf(stderr, "qdiff must be >= 1 and <= 31\n");
2222
        exit(1);
2223
    }
2224
}
2225

    
2226
static void opt_qblur(const char *arg)
2227
{
2228
    video_qblur = atof(arg);
2229
}
2230

    
2231
static void opt_qcomp(const char *arg)
2232
{
2233
    video_qcomp = atof(arg);
2234
}
2235

    
2236
static void opt_rc_initial_cplx(const char *arg)
2237
{
2238
    video_rc_initial_cplx = atof(arg);
2239
}
2240
static void opt_b_qfactor(const char *arg)
2241
{
2242
    video_b_qfactor = atof(arg);
2243
}
2244
static void opt_i_qfactor(const char *arg)
2245
{
2246
    video_i_qfactor = atof(arg);
2247
}
2248
static void opt_b_qoffset(const char *arg)
2249
{
2250
    video_b_qoffset = atof(arg);
2251
}
2252
static void opt_i_qoffset(const char *arg)
2253
{
2254
    video_i_qoffset = atof(arg);
2255
}
2256

    
2257
static void opt_ibias(const char *arg)
2258
{
2259
    video_intra_quant_bias = atoi(arg);
2260
}
2261
static void opt_pbias(const char *arg)
2262
{
2263
    video_inter_quant_bias = atoi(arg);
2264
}
2265

    
2266
static void opt_packet_size(const char *arg)
2267
{
2268
    packet_size= atoi(arg);
2269
}
2270

    
2271
static void opt_error_rate(const char *arg)
2272
{
2273
    error_rate= atoi(arg);
2274
}
2275

    
2276
static void opt_strict(const char *arg)
2277
{
2278
    strict= atoi(arg);
2279
}
2280

    
2281
static void opt_top_field_first(const char *arg)
2282
{
2283
    top_field_first= atoi(arg);
2284
}
2285

    
2286
static void opt_noise_reduction(const char *arg)
2287
{
2288
    noise_reduction= atoi(arg);
2289
}
2290

    
2291
static void opt_qns(const char *arg)
2292
{
2293
    qns= atoi(arg);
2294
}
2295

    
2296
static void opt_sc_threshold(const char *arg)
2297
{
2298
    sc_threshold= atoi(arg);
2299
}
2300

    
2301
static void opt_thread_count(const char *arg)
2302
{
2303
    thread_count= atoi(arg);
2304
#if !defined(HAVE_PTHREADS) && !defined(HAVE_W32THREADS)
2305
    if (verbose >= 0)
2306
        fprintf(stderr, "Warning: not compiled with thread support, using thread emulation\n");
2307
#endif
2308
}
2309

    
2310
static void opt_audio_bitrate(const char *arg)
2311
{
2312
    audio_bit_rate = atoi(arg) * 1000;
2313
}
2314

    
2315
static void opt_audio_rate(const char *arg)
2316
{
2317
    audio_sample_rate = atoi(arg);
2318
}
2319

    
2320
static void opt_audio_channels(const char *arg)
2321
{
2322
    audio_channels = atoi(arg);
2323
}
2324

    
2325
static void opt_video_device(const char *arg)
2326
{
2327
    video_device = av_strdup(arg);
2328
}
2329

    
2330
static void opt_video_channel(const char *arg)
2331
{
2332
    video_channel = strtol(arg, NULL, 0);
2333
}
2334

    
2335
static void opt_video_standard(const char *arg)
2336
{
2337
    video_standard = av_strdup(arg);
2338
}
2339

    
2340
static void opt_audio_device(const char *arg)
2341
{
2342
    audio_device = av_strdup(arg);
2343
}
2344

    
2345
static void opt_dv1394(const char *arg)
2346
{
2347
    video_grab_format = "dv1394";
2348
    audio_grab_format = NULL;
2349
}
2350

    
2351
static void opt_audio_codec(const char *arg)
2352
{
2353
    AVCodec *p;
2354

    
2355
    if (!strcmp(arg, "copy")) {
2356
        audio_stream_copy = 1;
2357
    } else {
2358
        p = first_avcodec;
2359
        while (p) {
2360
            if (!strcmp(p->name, arg) && p->type == CODEC_TYPE_AUDIO)
2361
                break;
2362
            p = p->next;
2363
        }
2364
        if (p == NULL) {
2365
            fprintf(stderr, "Unknown audio codec '%s'\n", arg);
2366
            exit(1);
2367
        } else {
2368
            audio_codec_id = p->id;
2369
        }
2370
    }
2371
}
2372

    
2373
static void add_frame_hooker(const char *arg)
2374
{
2375
    int argc = 0;
2376
    char *argv[64];
2377
    int i;
2378
    char *args = av_strdup(arg);
2379

    
2380
    using_vhook = 1;
2381

    
2382
    argv[0] = strtok(args, " ");
2383
    while (argc < 62 && (argv[++argc] = strtok(NULL, " "))) {
2384
    }
2385

    
2386
    i = frame_hook_add(argc, argv);
2387

    
2388
    if (i != 0) {
2389
        fprintf(stderr, "Failed to add video hook function: %s\n", arg);
2390
        exit(1);
2391
    }
2392
}
2393

    
2394
const char *motion_str[] = {
2395
    "zero",
2396
    "full",
2397
    "log",
2398
    "phods",
2399
    "epzs",
2400
    "x1",
2401
    NULL,
2402
};
2403

    
2404
static void opt_motion_estimation(const char *arg)
2405
{
2406
    const char **p;
2407
    p = motion_str;
2408
    for(;;) {
2409
        if (!*p) {
2410
            fprintf(stderr, "Unknown motion estimation method '%s'\n", arg);
2411
            exit(1);
2412
        }
2413
        if (!strcmp(*p, arg))
2414
            break;
2415
        p++;
2416
    }
2417
    me_method = (p - motion_str) + 1;
2418
}
2419

    
2420
static void opt_video_codec(const char *arg)
2421
{
2422
    AVCodec *p;
2423

    
2424
    if (!strcmp(arg, "copy")) {
2425
        video_stream_copy = 1;
2426
    } else {
2427
        p = first_avcodec;
2428
        while (p) {
2429
            if (!strcmp(p->name, arg) && p->type == CODEC_TYPE_VIDEO)
2430
                break;
2431
            p = p->next;
2432
        }
2433
        if (p == NULL) {
2434
            fprintf(stderr, "Unknown video codec '%s'\n", arg);
2435
            exit(1);
2436
        } else {
2437
            video_codec_id = p->id;
2438
        }
2439
    }
2440
}
2441

    
2442
static void opt_map(const char *arg)
2443
{
2444
    AVStreamMap *m;
2445
    const char *p;
2446

    
2447
    p = arg;
2448
    m = &stream_maps[nb_stream_maps++];
2449

    
2450
    m->file_index = strtol(arg, (char **)&p, 0);
2451
    if (*p)
2452
        p++;
2453

    
2454
    m->stream_index = strtol(p, (char **)&p, 0);
2455
}
2456

    
2457
static void opt_recording_time(const char *arg)
2458
{
2459
    recording_time = parse_date(arg, 1);
2460
}
2461

    
2462
static void opt_start_time(const char *arg)
2463
{
2464
    start_time = parse_date(arg, 1);
2465
}
2466

    
2467
static void opt_rec_timestamp(const char *arg)
2468
{
2469
    rec_timestamp = parse_date(arg, 0) / 1000000;
2470
}
2471

    
2472
static void opt_input_file(const char *filename)
2473
{
2474
    AVFormatContext *ic;
2475
    AVFormatParameters params, *ap = &params;
2476
    int err, i, ret, rfps, rfps_base;
2477

    
2478
    if (!strcmp(filename, "-"))
2479
        filename = "pipe:";
2480

    
2481
    using_stdin |= !strcmp(filename, "pipe:" ) || 
2482
                   !strcmp( filename, "/dev/stdin" );
2483

    
2484
    /* get default parameters from command line */
2485
    memset(ap, 0, sizeof(*ap));
2486
    ap->sample_rate = audio_sample_rate;
2487
    ap->channels = audio_channels;
2488
    ap->frame_rate = frame_rate;
2489
    ap->frame_rate_base = frame_rate_base;
2490
    ap->width = frame_width + frame_padleft + frame_padright;
2491
    ap->height = frame_height + frame_padtop + frame_padbottom;
2492
    ap->image_format = image_format;
2493
    ap->pix_fmt = frame_pix_fmt;
2494

    
2495
    /* open the input file with generic libav function */
2496
    err = av_open_input_file(&ic, filename, file_iformat, 0, ap);
2497
    if (err < 0) {
2498
        print_error(filename, err);
2499
        exit(1);
2500
    }
2501
    
2502
    /* If not enough info to get the stream parameters, we decode the
2503
       first frames to get it. (used in mpeg case for example) */
2504
    ret = av_find_stream_info(ic);
2505
    if (ret < 0 && verbose >= 0) {
2506
        fprintf(stderr, "%s: could not find codec parameters\n", filename);
2507
        exit(1);
2508
    }
2509

    
2510
    /* if seeking requested, we execute it */
2511
    if (start_time != 0) {
2512
        int64_t timestamp;
2513

    
2514
        timestamp = start_time;
2515
        /* add the stream start time */
2516
        if (ic->start_time != AV_NOPTS_VALUE)
2517
            timestamp += ic->start_time;
2518
        ret = av_seek_frame(ic, -1, timestamp);
2519
        if (ret < 0) {
2520
            fprintf(stderr, "%s: could not seek to position %0.3f\n", 
2521
                    filename, (double)timestamp / AV_TIME_BASE);
2522
        }
2523
        /* reset seek info */
2524
        start_time = 0;
2525
    }
2526

    
2527
    /* update the current parameters so that they match the one of the input stream */
2528
    for(i=0;i<ic->nb_streams;i++) {
2529
        AVCodecContext *enc = &ic->streams[i]->codec;
2530
#if defined(HAVE_PTHREADS) || defined(HAVE_W32THREADS)
2531
        if(thread_count>1)
2532
            avcodec_thread_init(enc, thread_count);
2533
#endif
2534
        enc->thread_count= thread_count;
2535
        switch(enc->codec_type) {
2536
        case CODEC_TYPE_AUDIO:
2537
            //fprintf(stderr, "\nInput Audio channels: %d", enc->channels);
2538
            audio_channels = enc->channels;
2539
            audio_sample_rate = enc->sample_rate;
2540
            break;
2541
        case CODEC_TYPE_VIDEO:
2542
            frame_height = enc->height;
2543
            frame_width = enc->width;
2544
            frame_aspect_ratio = av_q2d(enc->sample_aspect_ratio) * enc->width / enc->height;
2545
            frame_pix_fmt = enc->pix_fmt;
2546
            rfps      = ic->streams[i]->r_frame_rate;
2547
            rfps_base = ic->streams[i]->r_frame_rate_base;
2548
            enc->workaround_bugs = workaround_bugs;
2549
            enc->error_resilience = error_resilience; 
2550
            enc->error_concealment = error_concealment; 
2551
            enc->idct_algo = idct_algo;
2552
            enc->debug = debug;
2553
            enc->debug_mv = debug_mv;            
2554
            if(bitexact)
2555
                enc->flags|= CODEC_FLAG_BITEXACT;
2556

    
2557
            assert(enc->frame_rate_base == rfps_base); // should be true for now
2558
            if (enc->frame_rate != rfps) { 
2559

    
2560
                if (verbose >= 0)
2561
                    fprintf(stderr,"\nSeems that stream %d comes from film source: %2.2f->%2.2f\n",
2562
                            i, (float)enc->frame_rate / enc->frame_rate_base,
2563

    
2564
                    (float)rfps / rfps_base);
2565
            }
2566
            /* update the current frame rate to match the stream frame rate */
2567
            frame_rate      = rfps;
2568
            frame_rate_base = rfps_base;
2569

    
2570
            enc->rate_emu = rate_emu;
2571
            break;
2572
        case CODEC_TYPE_DATA:
2573
            break;
2574
        default:
2575
            av_abort();
2576
        }
2577
    }
2578
    
2579
    input_files[nb_input_files] = ic;
2580
    /* dump the file content */
2581
    if (verbose >= 0)
2582
        dump_format(ic, nb_input_files, filename, 0);
2583

    
2584
    nb_input_files++;
2585
    file_iformat = NULL;
2586
    file_oformat = NULL;
2587
    image_format = NULL;
2588

    
2589
    rate_emu = 0;
2590
}
2591

    
2592
static void check_audio_video_inputs(int *has_video_ptr, int *has_audio_ptr)
2593
{
2594
    int has_video, has_audio, i, j;
2595
    AVFormatContext *ic;
2596

    
2597
    has_video = 0;
2598
    has_audio = 0;
2599
    for(j=0;j<nb_input_files;j++) {
2600
        ic = input_files[j];
2601
        for(i=0;i<ic->nb_streams;i++) {
2602
            AVCodecContext *enc = &ic->streams[i]->codec;
2603
            switch(enc->codec_type) {
2604
            case CODEC_TYPE_AUDIO:
2605
                has_audio = 1;
2606
                break;
2607
            case CODEC_TYPE_VIDEO:
2608
                has_video = 1;
2609
                break;
2610
            case CODEC_TYPE_DATA:
2611
                break;
2612
            default:
2613
                av_abort();
2614
            }
2615
        }
2616
    }
2617
    *has_video_ptr = has_video;
2618
    *has_audio_ptr = has_audio;
2619
}
2620

    
2621
static void opt_output_file(const char *filename)
2622
{
2623
    AVStream *st;
2624
    AVFormatContext *oc;
2625
    int use_video, use_audio, nb_streams, input_has_video, input_has_audio;
2626
    int codec_id;
2627
    AVFormatParameters params, *ap = &params;
2628

    
2629
    if (!strcmp(filename, "-"))
2630
        filename = "pipe:";
2631

    
2632
    oc = av_alloc_format_context();
2633

    
2634
    if (!file_oformat) {
2635
        file_oformat = guess_format(NULL, filename, NULL);
2636
        if (!file_oformat) {
2637
            fprintf(stderr, "Unable for find a suitable output format for '%s'\n",
2638
                    filename);
2639
            exit(1);
2640
        }
2641
    }
2642
    
2643
    oc->oformat = file_oformat;
2644

    
2645
    if (!strcmp(file_oformat->name, "ffm") && 
2646
        strstart(filename, "http:", NULL)) {
2647
        /* special case for files sent to ffserver: we get the stream
2648
           parameters from ffserver */
2649
        if (read_ffserver_streams(oc, filename) < 0) {
2650
            fprintf(stderr, "Could not read stream parameters from '%s'\n", filename);
2651
            exit(1);
2652
        }
2653
    } else {
2654
        use_video = file_oformat->video_codec != CODEC_ID_NONE;
2655
        use_audio = file_oformat->audio_codec != CODEC_ID_NONE;
2656

    
2657
        /* disable if no corresponding type found and at least one
2658
           input file */
2659
        if (nb_input_files > 0) {
2660
            check_audio_video_inputs(&input_has_video, &input_has_audio);
2661
            if (!input_has_video)
2662
                use_video = 0;
2663
            if (!input_has_audio)
2664
                use_audio = 0;
2665
        }
2666

    
2667
        /* manual disable */
2668
        if (audio_disable) {
2669
            use_audio = 0;
2670
        }
2671
        if (video_disable) {
2672
            use_video = 0;
2673
        }
2674
        
2675
        nb_streams = 0;
2676
        if (use_video) {
2677
            AVCodecContext *video_enc;
2678
            
2679
            st = av_mallocz(sizeof(AVStream));
2680
            if (!st) {
2681
                fprintf(stderr, "Could not alloc stream\n");
2682
                exit(1);
2683
            }
2684
            avcodec_get_context_defaults(&st->codec);
2685
#if defined(HAVE_PTHREADS) || defined(HAVE_W32THREADS)
2686
            if(thread_count>1)
2687
                avcodec_thread_init(&st->codec, thread_count);
2688
#endif
2689

    
2690
            video_enc = &st->codec;
2691
            
2692
            if(!strcmp(file_oformat->name, "mp4") || !strcmp(file_oformat->name, "mov") || !strcmp(file_oformat->name, "3gp"))
2693
                video_enc->flags |= CODEC_FLAG_GLOBAL_HEADER;
2694
            if (video_stream_copy) {
2695
                st->stream_copy = 1;
2696
                video_enc->codec_type = CODEC_TYPE_VIDEO;
2697
            } else {
2698
                char *p;
2699
                int i;
2700
            
2701
                codec_id = file_oformat->video_codec;
2702
                if (video_codec_id != CODEC_ID_NONE)
2703
                    codec_id = video_codec_id;
2704
                
2705
                video_enc->codec_id = codec_id;
2706
                
2707
                video_enc->bit_rate = video_bit_rate;
2708
                video_enc->bit_rate_tolerance = video_bit_rate_tolerance;
2709
                video_enc->frame_rate = frame_rate; 
2710
                video_enc->frame_rate_base = frame_rate_base; 
2711
                
2712
                video_enc->width = frame_width + frame_padright + frame_padleft;
2713
                video_enc->height = frame_height + frame_padtop + frame_padbottom;
2714
                video_enc->sample_aspect_ratio = av_d2q(frame_aspect_ratio*frame_height/frame_width, 255);
2715
                video_enc->pix_fmt = frame_pix_fmt;
2716

    
2717
                if (!intra_only)
2718
                    video_enc->gop_size = gop_size;
2719
                else
2720
                    video_enc->gop_size = 0;
2721
                if (video_qscale || same_quality) {
2722
                    video_enc->flags |= CODEC_FLAG_QSCALE;
2723
                    st->quality = FF_QP2LAMBDA * video_qscale;
2724
                }
2725

    
2726
                if(intra_matrix)
2727
                    video_enc->intra_matrix = intra_matrix;
2728
                if(inter_matrix)
2729
                    video_enc->inter_matrix = inter_matrix;
2730

    
2731
                if(bitexact)
2732
                    video_enc->flags |= CODEC_FLAG_BITEXACT;
2733

    
2734
                video_enc->mb_decision = mb_decision;
2735
                video_enc->mb_cmp = mb_cmp;
2736
                video_enc->ildct_cmp = ildct_cmp;
2737
                video_enc->me_sub_cmp = sub_cmp;
2738
                video_enc->me_cmp = cmp;
2739
                video_enc->me_pre_cmp = pre_cmp;
2740
                video_enc->pre_me = pre_me;
2741
                video_enc->lumi_masking = lumi_mask;
2742
                video_enc->dark_masking = dark_mask;
2743
                video_enc->spatial_cplx_masking = scplx_mask;
2744
                video_enc->temporal_cplx_masking = tcplx_mask;
2745
                video_enc->p_masking = p_mask;
2746
                video_enc->quantizer_noise_shaping= qns;
2747
                
2748
                if (use_umv) {
2749
                    video_enc->flags |= CODEC_FLAG_H263P_UMV;
2750
                }
2751
                if (use_ss) {
2752
                    video_enc->flags |= CODEC_FLAG_H263P_SLICE_STRUCT;
2753
                }
2754
                   if (use_aic) {
2755
                    video_enc->flags |= CODEC_FLAG_H263P_AIC;
2756
                }
2757
                   if (use_aiv) {
2758
                    video_enc->flags |= CODEC_FLAG_H263P_AIV;
2759
                }
2760
                if (use_4mv) {
2761
                    video_enc->flags |= CODEC_FLAG_4MV;
2762
                }
2763
                if (use_obmc) {
2764
                    video_enc->flags |= CODEC_FLAG_OBMC;
2765
                }
2766
                if (use_loop) {
2767
                    video_enc->flags |= CODEC_FLAG_LOOP_FILTER;
2768
                }
2769
            
2770
                if(use_part) {
2771
                    video_enc->flags |= CODEC_FLAG_PART;
2772
                }
2773
                   if (use_alt_scan) {
2774
                    video_enc->flags |= CODEC_FLAG_ALT_SCAN;
2775
                }
2776
                   if (use_trell) {
2777
                    video_enc->flags |= CODEC_FLAG_TRELLIS_QUANT;
2778
                }
2779
                   if (use_scan_offset) {
2780
                    video_enc->flags |= CODEC_FLAG_SVCD_SCAN_OFFSET;
2781
                }
2782
                   if (closed_gop) {
2783
                    video_enc->flags |= CODEC_FLAG_CLOSED_GOP;
2784
                }
2785
                if (b_frames) {
2786
                    video_enc->max_b_frames = b_frames;
2787
                    video_enc->b_frame_strategy = 0;
2788
                    video_enc->b_quant_factor = 2.0;
2789
                }
2790
                if (do_interlace_dct) {
2791
                    video_enc->flags |= CODEC_FLAG_INTERLACED_DCT;
2792
                }
2793
                if (do_interlace_me) {
2794
                    video_enc->flags |= CODEC_FLAG_INTERLACED_ME;
2795
                }
2796
                video_enc->qmin = video_qmin;
2797
                video_enc->qmax = video_qmax;
2798
                video_enc->mb_qmin = video_mb_qmin;
2799
                video_enc->mb_qmax = video_mb_qmax;
2800
                video_enc->max_qdiff = video_qdiff;
2801
                video_enc->qblur = video_qblur;
2802
                video_enc->qcompress = video_qcomp;
2803
                video_enc->rc_eq = video_rc_eq;
2804
                video_enc->debug = debug;
2805
                video_enc->debug_mv = debug_mv;
2806
                video_enc->thread_count = thread_count;
2807
                p= video_rc_override_string;
2808
                for(i=0; p; i++){
2809
                    int start, end, q;
2810
                    int e=sscanf(p, "%d,%d,%d", &start, &end, &q);
2811
                    if(e!=3){
2812
                        fprintf(stderr, "error parsing rc_override\n");
2813
                        exit(1);
2814
                    }
2815
                    video_enc->rc_override= 
2816
                        av_realloc(video_enc->rc_override, 
2817
                                   sizeof(RcOverride)*(i+1));
2818
                    video_enc->rc_override[i].start_frame= start;
2819
                    video_enc->rc_override[i].end_frame  = end;
2820
                    if(q>0){
2821
                        video_enc->rc_override[i].qscale= q;
2822
                        video_enc->rc_override[i].quality_factor= 1.0;
2823
                    }
2824
                    else{
2825
                        video_enc->rc_override[i].qscale= 0;
2826
                        video_enc->rc_override[i].quality_factor= -q/100.0;
2827
                    }
2828
                    p= strchr(p, '/');
2829
                    if(p) p++;
2830
                }
2831
                video_enc->rc_override_count=i;
2832

    
2833
                video_enc->rc_max_rate = video_rc_max_rate;
2834
                video_enc->rc_min_rate = video_rc_min_rate;
2835
                video_enc->rc_buffer_size = video_rc_buffer_size;
2836
                video_enc->rc_buffer_aggressivity= video_rc_buffer_aggressivity;
2837
                video_enc->rc_initial_cplx= video_rc_initial_cplx;
2838
                video_enc->i_quant_factor = video_i_qfactor;
2839
                video_enc->b_quant_factor = video_b_qfactor;
2840
                video_enc->i_quant_offset = video_i_qoffset;
2841
                video_enc->b_quant_offset = video_b_qoffset;
2842
                video_enc->intra_quant_bias = video_intra_quant_bias;
2843
                video_enc->inter_quant_bias = video_inter_quant_bias;
2844
                video_enc->dct_algo = dct_algo;
2845
                video_enc->idct_algo = idct_algo;
2846
                video_enc->strict_std_compliance = strict;
2847
                video_enc->error_rate = error_rate;
2848
                video_enc->noise_reduction= noise_reduction;
2849
                video_enc->scenechange_threshold= sc_threshold;
2850
                if(packet_size){
2851
                    video_enc->rtp_mode= 1;
2852
                    video_enc->rtp_payload_size= packet_size;
2853
                }
2854
            
2855
                if (do_psnr)
2856
                    video_enc->flags|= CODEC_FLAG_PSNR;
2857
            
2858
                video_enc->me_method = me_method;
2859

    
2860
                /* two pass mode */
2861
                if (do_pass) {
2862
                    if (do_pass == 1) {
2863
                        video_enc->flags |= CODEC_FLAG_PASS1;
2864
                    } else {
2865
                        video_enc->flags |= CODEC_FLAG_PASS2;
2866
                    }
2867
                }
2868
            }
2869
            oc->streams[nb_streams] = st;
2870
            nb_streams++;
2871
        }
2872
    
2873
        if (use_audio) {
2874
            AVCodecContext *audio_enc;
2875

    
2876
            st = av_mallocz(sizeof(AVStream));
2877
            if (!st) {
2878
                fprintf(stderr, "Could not alloc stream\n");
2879
                exit(1);
2880
            }
2881
            avcodec_get_context_defaults(&st->codec);
2882
#if defined(HAVE_PTHREADS) || defined(HAVE_W32THREADS)
2883
            if(thread_count>1)
2884
                avcodec_thread_init(&st->codec, thread_count);
2885
#endif
2886

    
2887
            audio_enc = &st->codec;
2888
            audio_enc->codec_type = CODEC_TYPE_AUDIO;
2889

    
2890
            if(!strcmp(file_oformat->name, "mp4") || !strcmp(file_oformat->name, "mov") || !strcmp(file_oformat->name, "3gp"))
2891
                audio_enc->flags |= CODEC_FLAG_GLOBAL_HEADER;
2892
            if (audio_stream_copy) {
2893
                st->stream_copy = 1;
2894
            } else {
2895
                codec_id = file_oformat->audio_codec;
2896
                if (audio_codec_id != CODEC_ID_NONE)
2897
                    codec_id = audio_codec_id;
2898
                audio_enc->codec_id = codec_id;
2899
                
2900
                audio_enc->bit_rate = audio_bit_rate;
2901
                audio_enc->sample_rate = audio_sample_rate;
2902
                audio_enc->strict_std_compliance = strict;
2903
                audio_enc->thread_count = thread_count;
2904
                /* For audio codecs other than AC3 we limit */
2905
                /* the number of coded channels to stereo   */
2906
                if (audio_channels > 2 && codec_id != CODEC_ID_AC3) {
2907
                    audio_enc->channels = 2;
2908
                } else
2909
                    audio_enc->channels = audio_channels;
2910
            }
2911
            oc->streams[nb_streams] = st;
2912
            nb_streams++;
2913
        }
2914

    
2915
        oc->nb_streams = nb_streams;
2916

    
2917
        if (!nb_streams) {
2918
            fprintf(stderr, "No audio or video streams available\n");
2919
            exit(1);
2920
        }
2921

    
2922
        oc->timestamp = rec_timestamp;
2923
            
2924
        if (str_title)
2925
            pstrcpy(oc->title, sizeof(oc->title), str_title);
2926
        if (str_author)
2927
            pstrcpy(oc->author, sizeof(oc->author), str_author);
2928
        if (str_copyright)
2929
            pstrcpy(oc->copyright, sizeof(oc->copyright), str_copyright);
2930
        if (str_comment)
2931
            pstrcpy(oc->comment, sizeof(oc->comment), str_comment);
2932
    }
2933

    
2934
    output_files[nb_output_files++] = oc;
2935

    
2936
    strcpy(oc->filename, filename);
2937

    
2938
    /* check filename in case of an image number is expected */
2939
    if (oc->oformat->flags & AVFMT_NEEDNUMBER) {
2940
        if (filename_number_test(oc->filename) < 0) {
2941
            print_error(oc->filename, AVERROR_NUMEXPECTED);
2942
            exit(1);
2943
        }
2944
    }
2945

    
2946
    if (!(oc->oformat->flags & AVFMT_NOFILE)) {
2947
        /* test if it already exists to avoid loosing precious files */
2948
        if (!file_overwrite && 
2949
            (strchr(filename, ':') == NULL ||
2950
             strstart(filename, "file:", NULL))) {
2951
            if (url_exist(filename)) {
2952
                int c;
2953
                
2954
                if ( !using_stdin ) {
2955
                    fprintf(stderr,"File '%s' already exists. Overwrite ? [y/N] ", filename);
2956
                    fflush(stderr);
2957
                    c = getchar();
2958
                    if (toupper(c) != 'Y') {
2959
                        fprintf(stderr, "Not overwriting - exiting\n");
2960
                        exit(1);
2961
                    }
2962
                                }
2963
                                else {
2964
                    fprintf(stderr,"File '%s' already exists. Exiting.\n", filename);
2965
                    exit(1);
2966
                                }
2967
            }
2968
        }
2969
        
2970
        /* open the file */
2971
        if (url_fopen(&oc->pb, filename, URL_WRONLY) < 0) {
2972
            fprintf(stderr, "Could not open '%s'\n", filename);
2973
            exit(1);
2974
        }
2975
    }
2976

    
2977
    memset(ap, 0, sizeof(*ap));
2978
    ap->image_format = image_format;
2979
    if (av_set_parameters(oc, ap) < 0) {
2980
        fprintf(stderr, "%s: Invalid encoding parameters\n",
2981
                oc->filename);
2982
        exit(1);
2983
    }
2984

    
2985
    /* reset some options */
2986
    file_oformat = NULL;
2987
    file_iformat = NULL;
2988
    image_format = NULL;
2989
    audio_disable = 0;
2990
    video_disable = 0;
2991
    audio_codec_id = CODEC_ID_NONE;
2992
    video_codec_id = CODEC_ID_NONE;
2993
    audio_stream_copy = 0;
2994
    video_stream_copy = 0;
2995
}
2996

    
2997
/* prepare dummy protocols for grab */
2998
static void prepare_grab(void)
2999
{
3000
    int has_video, has_audio, i, j;
3001
    AVFormatContext *oc;
3002
    AVFormatContext *ic;
3003
    AVFormatParameters vp1, *vp = &vp1;
3004
    AVFormatParameters ap1, *ap = &ap1;
3005
    
3006
    /* see if audio/video inputs are needed */
3007
    has_video = 0;
3008
    has_audio = 0;
3009
    memset(ap, 0, sizeof(*ap));
3010
    memset(vp, 0, sizeof(*vp));
3011
    for(j=0;j<nb_output_files;j++) {
3012
        oc = output_files[j];
3013
        for(i=0;i<oc->nb_streams;i++) {
3014
            AVCodecContext *enc = &oc->streams[i]->codec;
3015
            switch(enc->codec_type) {
3016
            case CODEC_TYPE_AUDIO:
3017
                if (enc->sample_rate > ap->sample_rate)
3018
                    ap->sample_rate = enc->sample_rate;
3019
                if (enc->channels > ap->channels)
3020
                    ap->channels = enc->channels;
3021
                has_audio = 1;
3022
                break;
3023
            case CODEC_TYPE_VIDEO:
3024
                if (enc->width > vp->width)
3025
                    vp->width = enc->width;
3026
                if (enc->height > vp->height)
3027
                    vp->height = enc->height;
3028
                
3029
                assert(enc->frame_rate_base == DEFAULT_FRAME_RATE_BASE);
3030
                if (enc->frame_rate > vp->frame_rate){
3031
                    vp->frame_rate      = enc->frame_rate;
3032
                    vp->frame_rate_base = enc->frame_rate_base;
3033
                }
3034
                has_video = 1;
3035
                break;
3036
            default:
3037
                av_abort();
3038
            }
3039
        }
3040
    }
3041
    
3042
    if (has_video == 0 && has_audio == 0) {
3043
        fprintf(stderr, "Output file must have at least one audio or video stream\n");
3044
        exit(1);
3045
    }
3046
    
3047
    if (has_video) {
3048
        AVInputFormat *fmt1;
3049
        fmt1 = av_find_input_format(video_grab_format);
3050
        vp->device  = video_device;
3051
        vp->channel = video_channel;
3052
        vp->standard = video_standard;
3053
        if (av_open_input_file(&ic, "", fmt1, 0, vp) < 0) {
3054
            fprintf(stderr, "Could not find video grab device\n");
3055
            exit(1);
3056
        }
3057
        /* If not enough info to get the stream parameters, we decode the
3058
           first frames to get it. */
3059
        if ((ic->ctx_flags & AVFMTCTX_NOHEADER) && av_find_stream_info(ic) < 0) {
3060
            fprintf(stderr, "Could not find video grab parameters\n");
3061
            exit(1);
3062
        }
3063
        /* by now video grab has one stream */
3064
        ic->streams[0]->r_frame_rate      = vp->frame_rate;
3065
        ic->streams[0]->r_frame_rate_base = vp->frame_rate_base;
3066
        input_files[nb_input_files] = ic;
3067

    
3068
        if (verbose >= 0)
3069
            dump_format(ic, nb_input_files, "", 0);
3070

    
3071
        nb_input_files++;
3072
    }
3073
    if (has_audio && audio_grab_format) {
3074
        AVInputFormat *fmt1;
3075
        fmt1 = av_find_input_format(audio_grab_format);
3076
        ap->device = audio_device;
3077
        if (av_open_input_file(&ic, "", fmt1, 0, ap) < 0) {
3078
            fprintf(stderr, "Could not find audio grab device\n");
3079
            exit(1);
3080
        }
3081
        input_files[nb_input_files] = ic;
3082

    
3083
        if (verbose >= 0)
3084
            dump_format(ic, nb_input_files, "", 0);
3085

    
3086
        nb_input_files++;
3087
    }
3088
}
3089

    
3090
/* same option as mencoder */
3091
static void opt_pass(const char *pass_str)
3092
{
3093
    int pass;
3094
    pass = atoi(pass_str);
3095
    if (pass != 1 && pass != 2) {
3096
        fprintf(stderr, "pass number can be only 1 or 2\n");
3097
        exit(1);
3098
    }
3099
    do_pass = pass;
3100
}
3101

    
3102
#if defined(CONFIG_WIN32) || defined(CONFIG_OS2)
3103
static int64_t getutime(void)
3104
{
3105
  return av_gettime();
3106
}
3107
#else
3108
static int64_t getutime(void)
3109
{
3110
    struct rusage rusage;
3111

    
3112
    getrusage(RUSAGE_SELF, &rusage);
3113
    return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
3114
}
3115
#endif
3116

    
3117
extern int ffm_nopts;
3118

    
3119
static void opt_bitexact(void)
3120
{
3121
    bitexact=1;
3122
    /* disable generate of real time pts in ffm (need to be supressed anyway) */
3123
    ffm_nopts = 1;
3124
}
3125

    
3126
static void show_formats(void)
3127
{
3128
    AVInputFormat *ifmt;
3129
    AVOutputFormat *ofmt;
3130
    AVImageFormat *image_fmt;
3131
    URLProtocol *up;
3132
    AVCodec *p, *p2;
3133
    const char **pp, *last_name;
3134

    
3135
    printf("File formats:\n");
3136
    last_name= "000";
3137
    for(;;){
3138
        int decode=0;
3139
        int encode=0;
3140
        const char *name=NULL;
3141

    
3142
        for(ofmt = first_oformat; ofmt != NULL; ofmt = ofmt->next) {
3143
            if((name == NULL || strcmp(ofmt->name, name)<0) &&
3144
                strcmp(ofmt->name, last_name)>0){
3145
                name= ofmt->name;
3146
                encode=1;
3147
            }
3148
        }
3149
        for(ifmt = first_iformat; ifmt != NULL; ifmt = ifmt->next) {
3150
            if((name == NULL || strcmp(ifmt->name, name)<0) &&
3151
                strcmp(ifmt->name, last_name)>0){
3152
                name= ifmt->name;
3153
                encode=0;
3154
            }
3155
            if(name && strcmp(ifmt->name, name)==0)
3156
                decode=1;
3157
        }
3158
        if(name==NULL)
3159
            break;
3160
        last_name= name;
3161
        
3162
        printf(
3163
            " %s%s %s\n", 
3164
            decode ? "D":" ", 
3165
            encode ? "E":" ", 
3166
            name);
3167
    }
3168
    printf("\n");
3169

    
3170
    printf("Image formats:\n");
3171
    for(image_fmt = first_image_format; image_fmt != NULL; 
3172
        image_fmt = image_fmt->next) {
3173
        printf(
3174
            " %s%s %s\n",
3175
            image_fmt->img_read  ? "D":" ",
3176
            image_fmt->img_write ? "E":" ",
3177
            image_fmt->name);
3178
    }
3179
    printf("\n");
3180

    
3181
    printf("Codecs:\n");
3182
    last_name= "000";
3183
    for(;;){
3184
        int decode=0;
3185
        int encode=0;
3186
        int cap=0;
3187

    
3188
        p2=NULL;
3189
        for(p = first_avcodec; p != NULL; p = p->next) {
3190
            if((p2==NULL || strcmp(p->name, p2->name)<0) &&
3191
                strcmp(p->name, last_name)>0){
3192
                p2= p;
3193
                decode= encode= cap=0;
3194
            }
3195
            if(p2 && strcmp(p->name, p2->name)==0){
3196
                if(p->decode) decode=1;
3197
                if(p->encode) encode=1;
3198
                cap |= p->capabilities;
3199
            }
3200
        }
3201
        if(p2==NULL)
3202
            break;
3203
        last_name= p2->name;
3204
        
3205
        printf(
3206
            " %s%s%s%s%s%s %s", 
3207
            decode ? "D": (/*p2->decoder ? "d":*/" "), 
3208
            encode ? "E":" ", 
3209
            p2->type == CODEC_TYPE_AUDIO ? "A":"V",
3210
            cap & CODEC_CAP_DRAW_HORIZ_BAND ? "S":" ",
3211
            cap & CODEC_CAP_DR1 ? "D":" ",
3212
            cap & CODEC_CAP_TRUNCATED ? "T":" ",
3213
            p2->name);
3214
       /* if(p2->decoder && decode==0)
3215
            printf(" use %s for decoding", p2->decoder->name);*/
3216
        printf("\n");
3217
    }
3218
    printf("\n");
3219

    
3220
    printf("Supported file protocols:\n");
3221
    for(up = first_protocol; up != NULL; up = up->next)
3222
        printf(" %s:", up->name);
3223
    printf("\n");
3224
    
3225
    printf("Frame size, frame rate abbreviations:\n ntsc pal qntsc qpal sntsc spal film ntsc-film sqcif qcif cif 4cif\n");
3226
    printf("Motion estimation methods:\n");
3227
    pp = motion_str;
3228
    while (*pp) {
3229
        printf(" %s", *pp);
3230
        if ((pp - motion_str + 1) == ME_ZERO) 
3231
            printf("(fastest)");
3232
        else if ((pp - motion_str + 1) == ME_FULL) 
3233
            printf("(slowest)");
3234
        else if ((pp - motion_str + 1) == ME_EPZS) 
3235
            printf("(default)");
3236
        pp++;
3237
    }
3238
    printf("\n\n");
3239
    printf(
3240
"Note, the names of encoders and decoders dont always match, so there are\n"
3241
"several cases where the above table shows encoder only or decoder only entries\n"
3242
"even though both encoding and decoding are supported for example, the h263\n"
3243
"decoder corresponds to the h263 and h263p encoders, for file formats its even\n"
3244
"worse\n");
3245
    exit(1);
3246
}
3247

    
3248
void parse_matrix_coeffs(uint16_t *dest, const char *str)
3249
{
3250
    int i;
3251
    const char *p = str;
3252
    for(i = 0;; i++) {
3253
        dest[i] = atoi(p);
3254
        if(i == 63)
3255
            break;
3256
        p = strchr(p, ',');
3257
        if(!p) {
3258
            fprintf(stderr, "Syntax error in matrix \"%s\" at coeff %d\n", str, i);
3259
            exit(1);
3260
        }
3261
        p++;
3262
    }
3263
}
3264

    
3265
void opt_inter_matrix(const char *arg)
3266
{
3267
    inter_matrix = av_mallocz(sizeof(uint16_t) * 64);
3268
    parse_matrix_coeffs(inter_matrix, arg);
3269
}
3270

    
3271
void opt_intra_matrix(const char *arg)
3272
{
3273
    intra_matrix = av_mallocz(sizeof(uint16_t) * 64);
3274
    parse_matrix_coeffs(intra_matrix, arg);
3275
}
3276

    
3277
static void opt_target(const char *arg)
3278
{
3279
    int norm = -1;
3280

    
3281
    if(!strncmp(arg, "pal-", 4)) {
3282
        norm = 0;
3283
        arg += 4;
3284
    } else if(!strncmp(arg, "ntsc-", 5)) {
3285
        norm = 1;
3286
        arg += 5;
3287
    } else {
3288
        int fr;
3289
        /* Calculate FR via float to avoid int overflow */
3290
        fr = (int)(frame_rate * 1000.0 / frame_rate_base);
3291
        if(fr == 25000) {
3292
            norm = 0;
3293
        } else if((fr == 29970) || (fr == 23976)) {
3294
            norm = 1;
3295
        } else {
3296
            /* Try to determine PAL/NTSC by peeking in the input files */
3297
            if(nb_input_files) {
3298
                int i, j;
3299
                for(j = 0; j < nb_input_files; j++) {
3300
                    for(i = 0; i < input_files[j]->nb_streams; i++) {
3301
                        AVCodecContext *c = &input_files[j]->streams[i]->codec;
3302
                        if(c->codec_type != CODEC_TYPE_VIDEO)
3303
                            continue;
3304
                        fr = c->frame_rate * 1000 / c->frame_rate_base;
3305
                        if(fr == 25000) {
3306
                            norm = 0;
3307
                            break;
3308
                        } else if((fr == 29970) || (fr == 23976)) {
3309
                            norm = 1;
3310
                            break;
3311
                        }
3312
                    }
3313
                    if(norm >= 0)
3314
                        break;
3315
                }
3316
            }
3317
        }
3318
        if(verbose && norm >= 0)
3319
            printf("Assuming %s for target.\n", norm ? "NTSC" : "PAL");
3320
    }
3321

    
3322
    if(norm < 0) {
3323
        fprintf(stderr, "Could not determine norm (PAL/NTSC) for target.\n");
3324
        fprintf(stderr, "Please prefix target with \"pal-\" or \"ntsc-\",\n");
3325
        fprintf(stderr, "or set a framerate with \"-r xxx\".\n");
3326
        exit(1);
3327
    }
3328

    
3329
    if(!strcmp(arg, "vcd")) {
3330

    
3331
        opt_video_codec("mpeg1video");
3332
        opt_audio_codec("mp2");
3333
        opt_format("vcd");
3334

    
3335
        opt_frame_size(norm ? "352x240" : "352x288");
3336

    
3337
        video_bit_rate = 1150000;
3338
        video_rc_max_rate = 1150000;
3339
        video_rc_min_rate = 1150000;
3340
        video_rc_buffer_size = 40*1024*8;
3341

    
3342
        audio_bit_rate = 224000;
3343
        audio_sample_rate = 44100;
3344

    
3345
    } else if(!strcmp(arg, "svcd")) {
3346

    
3347
        opt_video_codec("mpeg2video");
3348
        opt_audio_codec("mp2");
3349
        opt_format("svcd");
3350

    
3351
        opt_frame_size(norm ? "480x480" : "480x576");
3352
        opt_gop_size(norm ? "18" : "15");
3353

    
3354
        video_bit_rate = 2040000;
3355
        video_rc_max_rate = 2516000;
3356
        video_rc_min_rate = 0; //1145000;
3357
        video_rc_buffer_size = 224*1024*8;
3358
        use_scan_offset = 1;
3359

    
3360
        audio_bit_rate = 224000;
3361
        audio_sample_rate = 44100;
3362

    
3363
    } else if(!strcmp(arg, "dvd")) {
3364

    
3365
        opt_video_codec("mpeg2video");
3366
        opt_audio_codec("ac3");
3367
        opt_format("vob");
3368

    
3369
        opt_frame_size(norm ? "720x480" : "720x576");
3370
        opt_gop_size(norm ? "18" : "15");
3371

    
3372
        video_bit_rate = 6000000;
3373
        video_rc_max_rate = 9000000;
3374
        video_rc_min_rate = 0; //1500000;
3375
        video_rc_buffer_size = 224*1024*8;
3376

    
3377
        audio_bit_rate = 448000;
3378
        audio_sample_rate = 48000;
3379

    
3380
    } else {
3381
        fprintf(stderr, "Unknown target: %s\n", arg);
3382
        exit(1);
3383
    }
3384
}
3385

    
3386
const OptionDef options[] = {
3387
    /* main options */
3388
    { "L", 0, {(void*)show_license}, "show license" },
3389
    { "h", 0, {(void*)show_help}, "show help" },
3390
    { "formats", 0, {(void*)show_formats}, "show available formats, codecs, protocols, ..." },
3391
    { "f", HAS_ARG, {(void*)opt_format}, "force format", "fmt" },
3392
    { "img", HAS_ARG, {(void*)opt_image_format}, "force image format", "img_fmt" },
3393
    { "i", HAS_ARG, {(void*)opt_input_file}, "input file name", "filename" },
3394
    { "y", OPT_BOOL, {(void*)&file_overwrite}, "overwrite output files" },
3395
    { "map", HAS_ARG | OPT_EXPERT, {(void*)opt_map}, "set input stream mapping", "file:stream" },
3396
    { "t", HAS_ARG, {(void*)opt_recording_time}, "set the recording time", "duration" },
3397
    { "ss", HAS_ARG, {(void*)opt_start_time}, "set the start time offset", "time_off" },
3398
    { "title", HAS_ARG | OPT_STRING, {(void*)&str_title}, "set the title", "string" },
3399
    { "timestamp", HAS_ARG, {(void*)&opt_rec_timestamp}, "set the timestamp", "time" },
3400
    { "author", HAS_ARG | OPT_STRING, {(void*)&str_author}, "set the author", "string" },
3401
    { "copyright", HAS_ARG | OPT_STRING, {(void*)&str_copyright}, "set the copyright", "string" },
3402
    { "comment", HAS_ARG | OPT_STRING, {(void*)&str_comment}, "set the comment", "string" },
3403
    { "debug", HAS_ARG | OPT_EXPERT, {(void*)opt_debug}, "print specific debug info", "" },
3404
    { "vismv", HAS_ARG | OPT_EXPERT, {(void*)opt_vismv}, "visualize motion vectors", "" },
3405
    { "benchmark", OPT_BOOL | OPT_EXPERT, {(void*)&do_benchmark}, 
3406
      "add timings for benchmarking" },
3407
    { "dump", OPT_BOOL | OPT_EXPERT, {(void*)&do_pkt_dump}, 
3408
      "dump each input packet" },
3409
    { "hex", OPT_BOOL | OPT_EXPERT, {(void*)&do_hex_dump}, 
3410
      "when dumping packets, also dump the payload" },
3411
    { "bitexact", OPT_EXPERT, {(void*)opt_bitexact}, "only use bit exact algorithms (for codec testing)" }, 
3412
    { "re", OPT_BOOL | OPT_EXPERT, {(void*)&rate_emu}, "read input at native frame rate", "" },
3413
    { "loop", OPT_BOOL | OPT_EXPERT, {(void*)&loop_input}, "loop (current only works with images)" },
3414
    { "v", HAS_ARG, {(void*)opt_verbose}, "control amount of logging", "verbose" },
3415
    { "target", HAS_ARG, {(void*)opt_target}, "specify target file type (\"vcd\", \"svcd\" or \"dvd\")", "type" },
3416
    { "threads", HAS_ARG | OPT_EXPERT, {(void*)opt_thread_count}, "thread count", "count" },
3417

    
3418
    /* video options */
3419
    { "b", HAS_ARG | OPT_VIDEO, {(void*)opt_video_bitrate}, "set video bitrate (in kbit/s)", "bitrate" },
3420
    { "r", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_rate}, "set frame rate (Hz value, fraction or abbreviation)", "rate" },
3421
    { "s", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_size}, "set frame size (WxH or abbreviation)", "size" },
3422
    { "aspect", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_aspect_ratio}, "set aspect ratio (4:3, 16:9 or 1.3333, 1.7777)", "aspect" },
3423
    { "pix_fmt", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_frame_pix_fmt}, "set pixel format", "format" },
3424
    { "croptop", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop_top}, "set top crop band size (in pixels)", "size" },
3425
    { "cropbottom", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop_bottom}, "set bottom crop band size (in pixels)", "size" },
3426
    { "cropleft", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop_left}, "set left crop band size (in pixels)", "size" },
3427
    { "cropright", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop_right}, "set right crop band size (in pixels)", "size" },
3428
    { "padtop", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_pad_top}, "set top pad band size (in pixels)", "size" },
3429
    { "padbottom", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_pad_bottom}, "set bottom pad band size (in pixels)", "size" },
3430
    { "padleft", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_pad_left}, "set left pad band size (in pixels)", "size" },
3431
    { "padright", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_pad_right}, "set right pad band size (in pixels)", "size" },
3432
    { "padcolor", HAS_ARG | OPT_VIDEO, {(void*)opt_pad_color}, "set color of pad bands (Hex 000000 thru FFFFFF)", "color" },
3433
    { "g", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_gop_size}, "set the group of picture size", "gop_size" },
3434
    { "intra", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&intra_only}, "use only intra frames"},
3435
    { "vn", OPT_BOOL | OPT_VIDEO, {(void*)&video_disable}, "disable video" },
3436
    { "qscale", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qscale}, "use fixed video quantiser scale (VBR)", "q" },
3437
    { "qmin", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qmin}, "min video quantiser scale (VBR)", "q" },
3438
    { "qmax", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qmax}, "max video quantiser scale (VBR)", "q" },
3439
    { "mbqmin", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_mb_qmin}, "min macroblock quantiser scale (VBR)", "q" },
3440
    { "mbqmax", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_mb_qmax}, "max macroblock quantiser scale (VBR)", "q" },
3441
    { "qdiff", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qdiff}, "max difference between the quantiser scale (VBR)", "q" },
3442
    { "qblur", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qblur}, "video quantiser scale blur (VBR)", "blur" },
3443
    { "qcomp", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qcomp}, "video quantiser scale compression (VBR)", "compression" },
3444
    { "rc_init_cplx", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_rc_initial_cplx}, "initial complexity for 1-pass encoding", "complexity" },
3445
    { "b_qfactor", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_b_qfactor}, "qp factor between p and b frames", "factor" },
3446
    { "i_qfactor", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_i_qfactor}, "qp factor between p and i frames", "factor" },
3447
    { "b_qoffset", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_b_qoffset}, "qp offset between p and b frames", "offset" },
3448
    { "i_qoffset", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_i_qoffset}, "qp offset between p and i frames", "offset" },
3449
    { "ibias", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_ibias}, "intra quant bias", "bias" },
3450
    { "pbias", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_pbias}, "inter quant bias", "bias" },
3451
//    { "b_strategy", HAS_ARG | OPT_EXPERT, {(void*)opt_b_strategy}, "dynamic b frame selection strategy", "strategy" },
3452
    { "rc_eq", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_video_rc_eq}, "set rate control equation", "equation" },
3453
    { "rc_override", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_video_rc_override_string}, "rate control override for specific intervals", "override" },
3454
    { "bt", HAS_ARG | OPT_VIDEO, {(void*)opt_video_bitrate_tolerance}, "set video bitrate tolerance (in kbit/s)", "tolerance" },
3455
    { "maxrate", HAS_ARG | OPT_VIDEO, {(void*)opt_video_bitrate_max}, "set max video bitrate tolerance (in kbit/s)", "bitrate" },
3456
    { "minrate", HAS_ARG | OPT_VIDEO, {(void*)opt_video_bitrate_min}, "set min video bitrate tolerance (in kbit/s)", "bitrate" },
3457
    { "bufsize", HAS_ARG | OPT_VIDEO, {(void*)opt_video_buffer_size}, "set ratecontrol buffere size (in kByte)", "size" },
3458
    { "vcodec", HAS_ARG | OPT_VIDEO, {(void*)opt_video_codec}, "force video codec ('copy' to copy stream)", "codec" },
3459
    { "me", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_motion_estimation}, "set motion estimation method", 
3460
      "method" },
3461
    { "dct_algo", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_dct_algo}, "set dct algo",  "algo" },
3462
    { "idct_algo", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_idct_algo}, "set idct algo",  "algo" },
3463
    { "er", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_error_resilience}, "set error resilience",  "n" },
3464
    { "ec", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_error_concealment}, "set error concealment",  "bit_mask" },
3465
    { "bf", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_b_frames}, "use 'frames' B frames", "frames" },
3466
    { "hq", OPT_BOOL, {(void*)&mb_decision}, "activate high quality settings" },
3467
    { "mbd", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_mb_decision}, "macroblock decision", "mode" },
3468
    { "mbcmp", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_mb_cmp}, "macroblock compare function", "cmp function" },
3469
    { "ildctcmp", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_ildct_cmp}, "ildct compare function", "cmp function" },
3470
    { "subcmp", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_sub_cmp}, "subpel compare function", "cmp function" },
3471
    { "cmp", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_cmp}, "fullpel compare function", "cmp function" },
3472
    { "precmp", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_pre_cmp}, "pre motion estimation compare function", "cmp function" },
3473
    { "preme", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_pre_me}, "pre motion estimation", "" },
3474
    { "lumi_mask", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_lumi_mask}, "luminance masking", "" },
3475
    { "dark_mask", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_dark_mask}, "darkness masking", "" },
3476
    { "scplx_mask", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_scplx_mask}, "spatial complexity masking", "" },
3477
    { "tcplx_mask", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_tcplx_mask}, "teporal complexity masking", "" },
3478
    { "p_mask", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_p_mask}, "inter masking", "" },
3479
    { "4mv", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_4mv}, "use four motion vector by macroblock (MPEG4)" },
3480
    { "obmc", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_obmc}, "use overlapped block motion compensation (h263+)" },
3481
    { "lf", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_loop}, "use loop filter (h263+)" },
3482
    { "part", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_part}, "use data partitioning (MPEG4)" },
3483
    { "bug", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_workaround_bugs}, "workaround not auto detected encoder bugs", "param" },
3484
    { "ps", HAS_ARG | OPT_EXPERT, {(void*)opt_packet_size}, "set packet size in bits", "size" },
3485
    { "error", HAS_ARG | OPT_EXPERT, {(void*)opt_error_rate}, "error rate", "rate" },
3486
    { "strict", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_strict}, "how strictly to follow the standards", "strictness" },
3487
    { "sameq", OPT_BOOL | OPT_VIDEO, {(void*)&same_quality}, 
3488
      "use same video quality as source (implies VBR)" },
3489
    { "pass", HAS_ARG | OPT_VIDEO, {(void*)&opt_pass}, "select the pass number (1 or 2)", "n" },
3490
    { "passlogfile", HAS_ARG | OPT_STRING | OPT_VIDEO, {(void*)&pass_logfilename}, "select two pass log file name", "file" },
3491
    { "deinterlace", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_deinterlace}, 
3492
      "deinterlace pictures" },
3493
    { "ildct", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_interlace_dct}, 
3494
      "force interlaced dct support in encoder (MPEG2/MPEG4)" },
3495
    { "ilme", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_interlace_me}, 
3496
      "force interlaced me support in encoder (MPEG2/MPEG4)" },
3497
    { "psnr", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_psnr}, "calculate PSNR of compressed frames" },
3498
    { "vstats", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_vstats}, "dump video coding statistics to file" }, 
3499
    { "vhook", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)add_frame_hooker}, "insert video processing module", "module" },
3500
    { "aic", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_aic}, "enable Advanced intra coding (h263+)" },
3501
    { "aiv", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_aiv}, "enable Alternative inter vlc (h263+)" },
3502
    { "umv", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_umv}, "enable Unlimited Motion Vector (h263+)" },
3503
    { "ssm", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_ss}, "enable Slice Structured mode (h263+)" },
3504
    { "alt", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_alt_scan}, "enable alternate scantable (MPEG2/MPEG4)" },
3505
    { "trell", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_trell}, "enable trellis quantization" },
3506
    { "cgop", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&closed_gop}, "closed gop" },
3507
    { "scan_offset", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_scan_offset}, "enable SVCD Scan Offset placeholder" },
3508
    { "intra_matrix", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_intra_matrix}, "specify intra matrix coeffs", "matrix" },
3509
    { "inter_matrix", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_inter_matrix}, "specify inter matrix coeffs", "matrix" },
3510
    { "top", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_top_field_first}, "top=1/bottom=0/auto=-1 field first", "" },
3511
    { "nr", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_noise_reduction}, "noise reduction", "" },
3512
    { "qns", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qns}, "quantization noise shaping", "" },
3513
    { "sc_threshold", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_sc_threshold}, "scene change threshold", "threshold" },
3514

    
3515
    /* audio options */
3516
    { "ab", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_bitrate}, "set audio bitrate (in kbit/s)", "bitrate", },
3517
    { "ar", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_rate}, "set audio sampling rate (in Hz)", "rate" },
3518
    { "ac", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_channels}, "set number of audio channels", "channels" },
3519
    { "an", OPT_BOOL | OPT_AUDIO, {(void*)&audio_disable}, "disable audio" },
3520
    { "acodec", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_codec}, "force audio codec ('copy' to copy stream)", "codec" },
3521

    
3522
    /* grab options */
3523
    { "vd", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_device}, "set video grab device", "device" },
3524
    { "vc", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_channel}, "set video grab channel (DV1394 only)", "channel" },
3525
    { "tvstd", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_standard}, "set television standard (NTSC, PAL (SECAM))", "standard" },
3526
    { "dv1394", OPT_EXPERT | OPT_GRAB, {(void*)opt_dv1394}, "set DV1394 grab", "" },
3527
    { "ad", HAS_ARG | OPT_EXPERT | OPT_AUDIO | OPT_GRAB, {(void*)opt_audio_device}, "set audio device", "device" },
3528
    { NULL, },
3529
};
3530

    
3531
static void show_banner(void)
3532
{
3533
    printf("ffmpeg version " FFMPEG_VERSION ", Copyright (c) 2000-2003 Fabrice Bellard\n");
3534
}
3535

    
3536
static void show_license(void)
3537
{
3538
    show_banner();
3539
#ifdef CONFIG_GPL
3540
    printf(
3541
    "This program is free software; you can redistribute it and/or modify\n"   
3542
    "it under the terms of the GNU General Public License as published by\n"
3543
    "the Free Software Foundation; either version 2 of the License, or\n"
3544
    "(at your option) any later version.\n"
3545
    "\n"
3546
    "This program is distributed in the hope that it will be useful,\n"
3547
    "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
3548
    "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n"
3549
    "GNU General Public License for more details.\n"
3550
    "\n"
3551
    "You should have received a copy of the GNU General Public License\n"
3552
    "along with this program; if not, write to the Free Software\n"
3553
    "Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n"
3554
    );
3555
#else
3556
    printf(
3557
    "This library is free software; you can redistribute it and/or\n"
3558
    "modify it under the terms of the GNU Lesser General Public\n"
3559
    "License as published by the Free Software Foundation; either\n"
3560
    "version 2 of the License, or (at your option) any later version.\n"
3561
    "\n"
3562
    "This library is distributed in the hope that it will be useful,\n"
3563
    "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
3564
    "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n"
3565
    "Lesser General Public License for more details.\n"
3566
    "\n"
3567
    "You should have received a copy of the GNU Lesser General Public\n"
3568
    "License along with this library; if not, write to the Free Software\n"
3569
    "Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n"
3570
    );
3571
#endif
3572
    exit(1);
3573
}
3574

    
3575
static void show_help(void)
3576
{
3577
    show_banner();
3578
    printf("usage: ffmpeg [[options] -i input_file]... {[options] outfile}...\n"
3579
           "Hyper fast Audio and Video encoder\n");
3580
    printf("\n");
3581
    show_help_options(options, "Main options:\n",
3582
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO, 0);
3583
    show_help_options(options, "\nVideo options:\n",
3584
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB, 
3585
                      OPT_VIDEO);
3586
    show_help_options(options, "\nAdvanced Video options:\n",
3587
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB, 
3588
                      OPT_VIDEO | OPT_EXPERT);
3589
    show_help_options(options, "\nAudio options:\n",
3590
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB, 
3591
                      OPT_AUDIO);
3592
    show_help_options(options, "\nAdvanced Audio options:\n",
3593
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB, 
3594
                      OPT_AUDIO | OPT_EXPERT);
3595
    show_help_options(options, "\nAudio/Video grab options:\n",
3596
                      OPT_GRAB, 
3597
                      OPT_GRAB);
3598
    show_help_options(options, "\nAdvanced options:\n",
3599
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB, 
3600
                      OPT_EXPERT);
3601
    exit(1);
3602
}
3603

    
3604
void parse_arg_file(const char *filename)
3605
{
3606
    opt_output_file(filename);
3607
}
3608

    
3609
int main(int argc, char **argv)
3610
{
3611
    int i;
3612
    int64_t ti;
3613

    
3614
    av_register_all();
3615

    
3616
    if (argc <= 1)
3617
        show_help();
3618
    
3619
    /* parse options */
3620
    parse_options(argc, argv, options);
3621

    
3622
    /* file converter / grab */
3623
    if (nb_output_files <= 0) {
3624
        fprintf(stderr, "Must supply at least one output file\n");
3625
        exit(1);
3626
    }
3627
    
3628
    if (nb_input_files == 0) {
3629
        prepare_grab();
3630
    }
3631

    
3632
    ti = getutime();
3633
    av_encode(output_files, nb_output_files, input_files, nb_input_files, 
3634
              stream_maps, nb_stream_maps);
3635
    ti = getutime() - ti;
3636
    if (do_benchmark) {
3637
        printf("bench: utime=%0.3fs\n", ti / 1000000.0);
3638
    }
3639

    
3640
    /* close files */
3641
    for(i=0;i<nb_output_files;i++) {
3642
        /* maybe av_close_output_file ??? */
3643
        AVFormatContext *s = output_files[i];
3644
        int j;
3645
        if (!(s->oformat->flags & AVFMT_NOFILE))
3646
            url_fclose(&s->pb);
3647
        for(j=0;j<s->nb_streams;j++)
3648
            av_free(s->streams[j]);
3649
        av_free(s);
3650
    }
3651
    for(i=0;i<nb_input_files;i++)
3652
        av_close_input_file(input_files[i]);
3653

    
3654
    av_free_static();
3655

    
3656
    if(intra_matrix)
3657
        av_free(intra_matrix);
3658
    if(inter_matrix)
3659
        av_free(inter_matrix);
3660
    
3661
#ifdef POWERPC_PERFORMANCE_REPORT
3662
    extern void powerpc_display_perf_report(void);
3663
    powerpc_display_perf_report();
3664
#endif /* POWERPC_PERFORMANCE_REPORT */
3665

    
3666
#ifndef CONFIG_WIN32
3667
    if (received_sigterm) {
3668
        fprintf(stderr,
3669
            "Received signal %d: terminating.\n",
3670
            (int) received_sigterm);
3671
        exit (255);
3672
    }
3673
#endif
3674
    exit(0); /* not all OS-es handle main() return value */
3675
    return 0;
3676
}