Statistics
| Branch: | Revision:

ffmpeg / ffmpeg.c @ 622348f9

History | View | Annotate | Download (106 KB)

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

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

    
39
#include "cmdutils.h"
40

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

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

    
51
extern const OptionDef options[];
52

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

    
56
#define MAX_FILES 20
57

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

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

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

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

    
144
static int gop_size = 12;
145
static int intra_only = 0;
146
static int audio_sample_rate = 44100;
147
static int audio_bit_rate = 64000;
148
static int audio_disable = 0;
149
static int audio_channels = 1;
150
static int audio_codec_id = CODEC_ID_NONE;
151

    
152
static int64_t recording_time = 0;
153
static int64_t start_time = 0;
154
static int file_overwrite = 0;
155
static char *str_title = NULL;
156
static char *str_author = NULL;
157
static char *str_copyright = NULL;
158
static char *str_comment = NULL;
159
static int do_benchmark = 0;
160
static int do_hex_dump = 0;
161
static int do_pkt_dump = 0;
162
static int do_psnr = 0;
163
static int do_vstats = 0;
164
static int do_pass = 0;
165
static int bitexact = 0;
166
static char *pass_logfilename = NULL;
167
static int audio_stream_copy = 0;
168
static int video_stream_copy = 0;
169

    
170
static int rate_emu = 0;
171

    
172
static char *video_grab_format = "video4linux";
173
static char *video_device = NULL;
174
static int  video_channel = 0;
175
static char *video_standard = "ntsc";
176

    
177
static char *audio_grab_format = "audio_device";
178
static char *audio_device = NULL;
179

    
180
static int using_stdin = 0;
181
static int using_vhook = 0;
182
static int verbose = 1;
183

    
184
#define DEFAULT_PASS_LOGFILENAME "ffmpeg2pass"
185

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

    
203
    int video_crop;          /* video_resample and video_crop are mutually exclusive */
204
    int topBand;             /* cropping area sizes */
205
    int leftBand;
206
    
207
    /* audio only */
208
    int audio_resample;
209
    ReSampleContext *resample; /* for audio resampling */
210
    FifoBuffer fifo;     /* for compression: one audio fifo per codec */
211
    FILE *logfile;
212
} AVOutputStream;
213

    
214
typedef struct AVInputStream {
215
    int file_index;
216
    int index;
217
    AVStream *st;
218
    int discard;             /* true if stream data should be discarded */
219
    int decoding_needed;     /* true if the packets must be decoded in 'raw_fifo' */
220
    int64_t sample_index;      /* current sample */
221

    
222
    int64_t       start;     /* time when read started */
223
    unsigned long frame;     /* current frame */
224
    int64_t       next_pts;  /* synthetic pts for cases where pkt.pts
225
                                is not defined */
226
    int64_t       pts;       /* current pts */
227
} AVInputStream;
228

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

    
238
#ifndef CONFIG_WIN32
239

    
240
/* init terminal so that we can grab keys */
241
static struct termios oldtty;
242

    
243
static void term_exit(void)
244
{
245
    tcsetattr (0, TCSANOW, &oldtty);
246
}
247

    
248
static volatile sig_atomic_t received_sigterm = 0;
249

    
250
static void
251
sigterm_handler(int sig)
252
{
253
    received_sigterm = sig;
254
    term_exit();
255
}
256

    
257
static void term_init(void)
258
{
259
    struct termios tty;
260

    
261
    tcgetattr (0, &tty);
262
    oldtty = tty;
263

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

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

    
287
/* read a key without blocking */
288
static int read_key(void)
289
{
290
    int n = 1;
291
    unsigned char ch;
292
#ifndef CONFIG_BEOS_NETSERVER
293
    struct timeval tv;
294
    fd_set rfds;
295

    
296
    FD_ZERO(&rfds);
297
    FD_SET(0, &rfds);
298
    tv.tv_sec = 0;
299
    tv.tv_usec = 0;
300
    n = select(1, &rfds, NULL, NULL, &tv);
301
#endif
302
    if (n > 0) {
303
        n = read(0, &ch, 1);
304
        if (n == 1)
305
            return ch;
306

    
307
        return n;
308
    }
309
    return -1;
310
}
311

    
312
#else
313

    
314
static volatile int received_sigterm = 0;
315

    
316
/* no interactive support */
317
static void term_exit(void)
318
{
319
}
320

    
321
static void term_init(void)
322
{
323
}
324

    
325
static int read_key(void)
326
{
327
    return 0;
328
}
329

    
330
#endif
331

    
332
static int read_ffserver_streams(AVFormatContext *s, const char *filename)
333
{
334
    int i, err;
335
    AVFormatContext *ic;
336

    
337
    err = av_open_input_file(&ic, filename, NULL, FFM_PACKET_SIZE, NULL);
338
    if (err < 0)
339
        return err;
340
    /* copy stream format */
341
    s->nb_streams = ic->nb_streams;
342
    for(i=0;i<ic->nb_streams;i++) {
343
        AVStream *st;
344

    
345
        st = av_mallocz(sizeof(AVStream));
346
        memcpy(st, ic->streams[i], sizeof(AVStream));
347
        s->streams[i] = st;
348
    }
349

    
350
    av_close_input_file(ic);
351
    return 0;
352
}
353

    
354
#define MAX_AUDIO_PACKET_SIZE (128 * 1024)
355

    
356
static void do_audio_out(AVFormatContext *s, 
357
                         AVOutputStream *ost, 
358
                         AVInputStream *ist,
359
                         unsigned char *buf, int size)
360
{
361
    uint8_t *buftmp;
362
    static uint8_t *audio_buf = NULL;
363
    static uint8_t *audio_out = NULL;
364
    const int audio_out_size= 4*MAX_AUDIO_PACKET_SIZE;
365

    
366
    int size_out, frame_bytes, ret;
367
    AVCodecContext *enc;
368

    
369
    /* SC: dynamic allocation of buffers */
370
    if (!audio_buf)
371
        audio_buf = av_malloc(2*MAX_AUDIO_PACKET_SIZE);
372
    if (!audio_out)
373
        audio_out = av_malloc(audio_out_size);
374
    if (!audio_buf || !audio_out)
375
        return;               /* Should signal an error ! */
376

    
377
    
378
    enc = &ost->st->codec;
379

    
380
    if (ost->audio_resample) {
381
        buftmp = audio_buf;
382
        size_out = audio_resample(ost->resample, 
383
                                  (short *)buftmp, (short *)buf,
384
                                  size / (ist->st->codec.channels * 2));
385
        size_out = size_out * enc->channels * 2;
386
    } else {
387
        buftmp = buf;
388
        size_out = size;
389
    }
390

    
391
    /* now encode as many frames as possible */
392
    if (enc->frame_size > 1) {
393
        /* output resampled raw samples */
394
        fifo_write(&ost->fifo, buftmp, size_out, 
395
                   &ost->fifo.wptr);
396

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

    
424
static void pre_process_video_frame(AVInputStream *ist, AVPicture *picture, void **bufp)
425
{
426
    AVCodecContext *dec;
427
    AVPicture *picture2;
428
    AVPicture picture_tmp;
429
    uint8_t *buf = 0;
430

    
431
    dec = &ist->st->codec;
432

    
433
    /* deinterlace : must be done before any resize */
434
    if (do_deinterlace || using_vhook) {
435
        int size;
436

    
437
        /* create temporary picture */
438
        size = avpicture_get_size(dec->pix_fmt, dec->width, dec->height);
439
        buf = av_malloc(size);
440
        if (!buf)
441
            return;
442
        
443
        picture2 = &picture_tmp;
444
        avpicture_fill(picture2, buf, dec->pix_fmt, dec->width, dec->height);
445

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

    
467
    frame_hook_process(picture2, dec->pix_fmt, dec->width, dec->height);
468

    
469
    if (picture != picture2)
470
        *picture = *picture2;
471
    *bufp = buf;
472
}
473

    
474
/* we begin to correct av delay at this threshold */
475
#define AV_DELAY_MAX 0.100
476

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

    
491
#define VIDEO_BUFFER_SIZE (1024*1024)
492

    
493
    enc = &ost->st->codec;
494
    dec = &ist->st->codec;
495

    
496
    /* by default, we output a single frame */
497
    nb_frames = 1;
498

    
499
    *frame_size = 0;
500

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

    
508
        adelta = audio_sync->sync_ipts - ((double)audio_sync->sync_opts * 
509
            s->pts_num / s->pts_den);
510

    
511
        vdelta = ost->sync_ipts - ((double)ost->sync_opts *
512
            s->pts_num / s->pts_den);
513

    
514
        av_delay = adelta - vdelta;
515
        //            printf("delay=%f\n", av_delay);
516
        if (av_delay < -AV_DELAY_MAX)
517
            nb_frames = 2;
518
        else if (av_delay > AV_DELAY_MAX)
519
            nb_frames = 0;
520
    } else {
521
        double vdelta;
522

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

    
550
    if (nb_frames <= 0) 
551
        return;
552

    
553
    if (!video_buffer)
554
        video_buffer = av_malloc(VIDEO_BUFFER_SIZE);
555
    if (!video_buffer)
556
        return;
557

    
558
    /* convert pixel format if needed */
559
    target_pixfmt = ost->video_resample ? PIX_FMT_YUV420P : enc->pix_fmt;
560
    if (dec->pix_fmt != target_pixfmt) {
561
        int size;
562

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

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

    
610
        picture_crop_temp.data[1] = formatted_picture->data[1] +
611
                ((ost->topBand >> 1) * formatted_picture->linesize[1]) +
612
                (ost->leftBand >> 1);
613

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

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

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

    
680
static double psnr(double d){
681
    if(d==0) return INFINITY;
682
    return -10.0*log(d)/log(10.0);
683
}
684

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

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

    
760

    
761
    oc = output_files[0];
762

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

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

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

    
914
            buffer_to_free = NULL;
915
            if (ist->st->codec.codec_type == CODEC_TYPE_VIDEO) {
916
                pre_process_video_frame(ist, (AVPicture *)&picture, 
917
                                        &buffer_to_free);
918
            }
919

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

    
927
                ist->frame++;
928
            }
929

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

    
949
                    ost = ost_table[i];
950
                    if (ost->source_index == ist_index) {
951
                        os = output_files[ost->file_index];
952

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

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

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

    
1018

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

    
1037
    file_table= (AVInputFile*) av_mallocz(nb_input_files * sizeof(AVInputFile));
1038
    if (!file_table)
1039
        goto fail;
1040

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

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

    
1072
            if (ist->st->codec.rate_emu) {
1073
                ist->start = av_gettime();
1074
                ist->frame = 0;
1075
            }
1076
        }
1077
    }
1078

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

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

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

    
1171
        codec = &ost->st->codec;
1172
        icodec = &ist->st->codec;
1173

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

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

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

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

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

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

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

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

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

    
1413
    stream_no_data = 0;
1414
    key = -1;
1415

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

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

    
1451
        /* finish if recording time exhausted */
1452
        if (recording_time > 0 && pts_min >= (recording_time / 1000000.0))
1453
            break;
1454

    
1455
        /* read a frame from it and output it in the fifo */
1456
        is = input_files[file_index];
1457
        if (av_read_frame(is, &pkt) < 0) {
1458
            file_table[file_index].eof_reached = 1;
1459
            continue;
1460
        }
1461
        if (!pkt.size) {
1462
            stream_no_data = is;
1463
        } else {
1464
            stream_no_data = 0;
1465
        }
1466
        if (do_pkt_dump) {
1467
            av_pkt_dump(stdout, &pkt, do_hex_dump);
1468
        }
1469
        /* the following test is needed in case new streams appear
1470
           dynamically in stream : we ignore them */
1471
        if (pkt.stream_index >= file_table[file_index].nb_streams)
1472
            goto discard_packet;
1473
        ist_index = file_table[file_index].ist_index + pkt.stream_index;
1474
        ist = ist_table[ist_index];
1475
        if (ist->discard)
1476
            goto discard_packet;
1477

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

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

    
1501
    term_exit();
1502

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1656

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

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

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

    
1672

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1951
static void opt_packet_size(const char *arg)
1952
{
1953
    packet_size= atoi(arg);
1954
}
1955

    
1956
static void opt_error_rate(const char *arg)
1957
{
1958
    error_rate= atoi(arg);
1959
}
1960

    
1961
static void opt_strict(const char *arg)
1962
{
1963
    strict= atoi(arg);
1964
}
1965

    
1966
static void opt_top_field_first(const char *arg)
1967
{
1968
    top_field_first= atoi(arg);
1969
}
1970

    
1971
static void opt_noise_reduction(const char *arg)
1972
{
1973
    noise_reduction= atoi(arg);
1974
}
1975

    
1976
static void opt_audio_bitrate(const char *arg)
1977
{
1978
    audio_bit_rate = atoi(arg) * 1000;
1979
}
1980

    
1981
static void opt_audio_rate(const char *arg)
1982
{
1983
    audio_sample_rate = atoi(arg);
1984
}
1985

    
1986
static void opt_audio_channels(const char *arg)
1987
{
1988
    audio_channels = atoi(arg);
1989
}
1990

    
1991
static void opt_video_device(const char *arg)
1992
{
1993
    video_device = av_strdup(arg);
1994
}
1995

    
1996
static void opt_video_channel(const char *arg)
1997
{
1998
    video_channel = strtol(arg, NULL, 0);
1999
}
2000

    
2001
static void opt_video_standard(const char *arg)
2002
{
2003
    video_standard = av_strdup(arg);
2004
}
2005

    
2006
static void opt_audio_device(const char *arg)
2007
{
2008
    audio_device = av_strdup(arg);
2009
}
2010

    
2011
static void opt_dv1394(const char *arg)
2012
{
2013
    video_grab_format = "dv1394";
2014
    audio_grab_format = NULL;
2015
}
2016

    
2017
static void opt_audio_codec(const char *arg)
2018
{
2019
    AVCodec *p;
2020

    
2021
    if (!strcmp(arg, "copy")) {
2022
        audio_stream_copy = 1;
2023
    } else {
2024
        p = first_avcodec;
2025
        while (p) {
2026
            if (!strcmp(p->name, arg) && p->type == CODEC_TYPE_AUDIO)
2027
                break;
2028
            p = p->next;
2029
        }
2030
        if (p == NULL) {
2031
            fprintf(stderr, "Unknown audio codec '%s'\n", arg);
2032
            exit(1);
2033
        } else {
2034
            audio_codec_id = p->id;
2035
        }
2036
    }
2037
}
2038

    
2039
static void add_frame_hooker(const char *arg)
2040
{
2041
    int argc = 0;
2042
    char *argv[64];
2043
    int i;
2044
    char *args = av_strdup(arg);
2045

    
2046
    using_vhook = 1;
2047

    
2048
    argv[0] = strtok(args, " ");
2049
    while (argc < 62 && (argv[++argc] = strtok(NULL, " "))) {
2050
    }
2051

    
2052
    i = frame_hook_add(argc, argv);
2053

    
2054
    if (i != 0) {
2055
        fprintf(stderr, "Failed to add video hook function: %s\n", arg);
2056
        exit(1);
2057
    }
2058
}
2059

    
2060
const char *motion_str[] = {
2061
    "zero",
2062
    "full",
2063
    "log",
2064
    "phods",
2065
    "epzs",
2066
    "x1",
2067
    NULL,
2068
};
2069

    
2070
static void opt_motion_estimation(const char *arg)
2071
{
2072
    const char **p;
2073
    p = motion_str;
2074
    for(;;) {
2075
        if (!*p) {
2076
            fprintf(stderr, "Unknown motion estimation method '%s'\n", arg);
2077
            exit(1);
2078
        }
2079
        if (!strcmp(*p, arg))
2080
            break;
2081
        p++;
2082
    }
2083
    me_method = (p - motion_str) + 1;
2084
}
2085

    
2086
static void opt_video_codec(const char *arg)
2087
{
2088
    AVCodec *p;
2089

    
2090
    if (!strcmp(arg, "copy")) {
2091
        video_stream_copy = 1;
2092
    } else {
2093
        p = first_avcodec;
2094
        while (p) {
2095
            if (!strcmp(p->name, arg) && p->type == CODEC_TYPE_VIDEO)
2096
                break;
2097
            p = p->next;
2098
        }
2099
        if (p == NULL) {
2100
            fprintf(stderr, "Unknown video codec '%s'\n", arg);
2101
            exit(1);
2102
        } else {
2103
            video_codec_id = p->id;
2104
        }
2105
    }
2106
}
2107

    
2108
static void opt_map(const char *arg)
2109
{
2110
    AVStreamMap *m;
2111
    const char *p;
2112

    
2113
    p = arg;
2114
    m = &stream_maps[nb_stream_maps++];
2115

    
2116
    m->file_index = strtol(arg, (char **)&p, 0);
2117
    if (*p)
2118
        p++;
2119

    
2120
    m->stream_index = strtol(p, (char **)&p, 0);
2121
}
2122

    
2123
static void opt_recording_time(const char *arg)
2124
{
2125
    recording_time = parse_date(arg, 1);
2126
}
2127

    
2128
static void opt_start_time(const char *arg)
2129
{
2130
    start_time = parse_date(arg, 1);
2131
}
2132

    
2133
static void opt_input_file(const char *filename)
2134
{
2135
    AVFormatContext *ic;
2136
    AVFormatParameters params, *ap = &params;
2137
    int err, i, ret, rfps, rfps_base;
2138

    
2139
    if (!strcmp(filename, "-"))
2140
        filename = "pipe:";
2141

    
2142
    using_stdin |= !strcmp(filename, "pipe:" ) || 
2143
                   !strcmp( filename, "/dev/stdin" );
2144

    
2145
    /* get default parameters from command line */
2146
    memset(ap, 0, sizeof(*ap));
2147
    ap->sample_rate = audio_sample_rate;
2148
    ap->channels = audio_channels;
2149
    ap->frame_rate = frame_rate;
2150
    ap->frame_rate_base = frame_rate_base;
2151
    ap->width = frame_width;
2152
    ap->height = frame_height;
2153
    ap->image_format = image_format;
2154
    ap->pix_fmt = frame_pix_fmt;
2155

    
2156
    /* open the input file with generic libav function */
2157
    err = av_open_input_file(&ic, filename, file_iformat, 0, ap);
2158
    if (err < 0) {
2159
        print_error(filename, err);
2160
        exit(1);
2161
    }
2162
    
2163
    /* If not enough info to get the stream parameters, we decode the
2164
       first frames to get it. (used in mpeg case for example) */
2165
    ret = av_find_stream_info(ic);
2166
    if (ret < 0) {
2167
        fprintf(stderr, "%s: could not find codec parameters\n", filename);
2168
        exit(1);
2169
    }
2170

    
2171
    /* if seeking requested, we execute it */
2172
    if (start_time != 0) {
2173
        int64_t timestamp;
2174

    
2175
        timestamp = start_time;
2176
        /* add the stream start time */
2177
        if (ic->start_time != AV_NOPTS_VALUE)
2178
            timestamp += ic->start_time;
2179
        ret = av_seek_frame(ic, -1, timestamp);
2180
        if (ret < 0) {
2181
            fprintf(stderr, "%s: could not seek to position %0.3f\n", 
2182
                    filename, (double)timestamp / AV_TIME_BASE);
2183
        }
2184
        /* reset seek info */
2185
        start_time = 0;
2186
    }
2187

    
2188
    /* update the current parameters so that they match the one of the input stream */
2189
    for(i=0;i<ic->nb_streams;i++) {
2190
        AVCodecContext *enc = &ic->streams[i]->codec;
2191
        switch(enc->codec_type) {
2192
        case CODEC_TYPE_AUDIO:
2193
            //fprintf(stderr, "\nInput Audio channels: %d", enc->channels);
2194
            audio_channels = enc->channels;
2195
            audio_sample_rate = enc->sample_rate;
2196
            break;
2197
        case CODEC_TYPE_VIDEO:
2198
            frame_height = enc->height;
2199
            frame_width = enc->width;
2200
            frame_aspect_ratio = av_q2d(enc->sample_aspect_ratio) * enc->width / enc->height;
2201
            frame_pix_fmt = enc->pix_fmt;
2202
            rfps      = ic->streams[i]->r_frame_rate;
2203
            rfps_base = ic->streams[i]->r_frame_rate_base;
2204
            enc->workaround_bugs = workaround_bugs;
2205
            enc->error_resilience = error_resilience; 
2206
            enc->error_concealment = error_concealment; 
2207
            enc->idct_algo = idct_algo;
2208
            enc->debug = debug;
2209
            enc->debug_mv = debug_mv;            
2210
            if(bitexact)
2211
                enc->flags|= CODEC_FLAG_BITEXACT;
2212

    
2213
            assert(enc->frame_rate_base == rfps_base); // should be true for now
2214
            if (enc->frame_rate != rfps) { 
2215
                fprintf(stderr,"\nSeems that stream %d comes from film source: %2.2f->%2.2f\n",
2216
                    i, (float)enc->frame_rate / enc->frame_rate_base,
2217
                    (float)rfps / rfps_base);
2218
            }
2219
            /* update the current frame rate to match the stream frame rate */
2220
            frame_rate      = rfps;
2221
            frame_rate_base = rfps_base;
2222

    
2223
            enc->rate_emu = rate_emu;
2224
            break;
2225
        case CODEC_TYPE_DATA:
2226
            break;
2227
        default:
2228
            av_abort();
2229
        }
2230
    }
2231
    
2232
    input_files[nb_input_files] = ic;
2233
    /* dump the file content */
2234
    dump_format(ic, nb_input_files, filename, 0);
2235
    nb_input_files++;
2236
    file_iformat = NULL;
2237
    file_oformat = NULL;
2238
    image_format = NULL;
2239

    
2240
    rate_emu = 0;
2241
}
2242

    
2243
static void check_audio_video_inputs(int *has_video_ptr, int *has_audio_ptr)
2244
{
2245
    int has_video, has_audio, i, j;
2246
    AVFormatContext *ic;
2247

    
2248
    has_video = 0;
2249
    has_audio = 0;
2250
    for(j=0;j<nb_input_files;j++) {
2251
        ic = input_files[j];
2252
        for(i=0;i<ic->nb_streams;i++) {
2253
            AVCodecContext *enc = &ic->streams[i]->codec;
2254
            switch(enc->codec_type) {
2255
            case CODEC_TYPE_AUDIO:
2256
                has_audio = 1;
2257
                break;
2258
            case CODEC_TYPE_VIDEO:
2259
                has_video = 1;
2260
                break;
2261
            default:
2262
                av_abort();
2263
            }
2264
        }
2265
    }
2266
    *has_video_ptr = has_video;
2267
    *has_audio_ptr = has_audio;
2268
}
2269

    
2270
static void opt_output_file(const char *filename)
2271
{
2272
    AVStream *st;
2273
    AVFormatContext *oc;
2274
    int use_video, use_audio, nb_streams, input_has_video, input_has_audio;
2275
    int codec_id;
2276
    AVFormatParameters params, *ap = &params;
2277

    
2278
    if (!strcmp(filename, "-"))
2279
        filename = "pipe:";
2280

    
2281
    oc = av_mallocz(sizeof(AVFormatContext));
2282

    
2283
    if (!file_oformat) {
2284
        file_oformat = guess_format(NULL, filename, NULL);
2285
        if (!file_oformat) {
2286
            fprintf(stderr, "Unable for find a suitable output format for '%s'\n",
2287
                    filename);
2288
            exit(1);
2289
        }
2290
    }
2291
    
2292
    oc->oformat = file_oformat;
2293

    
2294
    if (!strcmp(file_oformat->name, "ffm") && 
2295
        strstart(filename, "http:", NULL)) {
2296
        /* special case for files sent to ffserver: we get the stream
2297
           parameters from ffserver */
2298
        if (read_ffserver_streams(oc, filename) < 0) {
2299
            fprintf(stderr, "Could not read stream parameters from '%s'\n", filename);
2300
            exit(1);
2301
        }
2302
    } else {
2303
        use_video = file_oformat->video_codec != CODEC_ID_NONE;
2304
        use_audio = file_oformat->audio_codec != CODEC_ID_NONE;
2305

    
2306
        /* disable if no corresponding type found and at least one
2307
           input file */
2308
        if (nb_input_files > 0) {
2309
            check_audio_video_inputs(&input_has_video, &input_has_audio);
2310
            if (!input_has_video)
2311
                use_video = 0;
2312
            if (!input_has_audio)
2313
                use_audio = 0;
2314
        }
2315

    
2316
        /* manual disable */
2317
        if (audio_disable) {
2318
            use_audio = 0;
2319
        }
2320
        if (video_disable) {
2321
            use_video = 0;
2322
        }
2323
        
2324
        nb_streams = 0;
2325
        if (use_video) {
2326
            AVCodecContext *video_enc;
2327
            
2328
            st = av_mallocz(sizeof(AVStream));
2329
            if (!st) {
2330
                fprintf(stderr, "Could not alloc stream\n");
2331
                exit(1);
2332
            }
2333
            avcodec_get_context_defaults(&st->codec);
2334

    
2335
            video_enc = &st->codec;
2336
            
2337
            if(!strcmp(file_oformat->name, "mp4") || !strcmp(file_oformat->name, "mov") || !strcmp(file_oformat->name, "3gp"))
2338
                video_enc->flags |= CODEC_FLAG_GLOBAL_HEADER;
2339
            if (video_stream_copy) {
2340
                st->stream_copy = 1;
2341
                video_enc->codec_type = CODEC_TYPE_VIDEO;
2342
            } else {
2343
                char *p;
2344
                int i;
2345
            
2346
                codec_id = file_oformat->video_codec;
2347
                if (video_codec_id != CODEC_ID_NONE)
2348
                    codec_id = video_codec_id;
2349
                
2350
                video_enc->codec_id = codec_id;
2351
                
2352
                video_enc->bit_rate = video_bit_rate;
2353
                video_enc->bit_rate_tolerance = video_bit_rate_tolerance;
2354
                video_enc->frame_rate = frame_rate; 
2355
                video_enc->frame_rate_base = frame_rate_base; 
2356
                
2357
                video_enc->width = frame_width;
2358
                video_enc->height = frame_height;
2359
                video_enc->sample_aspect_ratio = av_d2q(frame_aspect_ratio*frame_height/frame_width, 255);
2360
                video_enc->pix_fmt = frame_pix_fmt;
2361

    
2362
                if (!intra_only)
2363
                    video_enc->gop_size = gop_size;
2364
                else
2365
                    video_enc->gop_size = 0;
2366
                if (video_qscale || same_quality) {
2367
                    video_enc->flags |= CODEC_FLAG_QSCALE;
2368
                    st->quality = FF_QP2LAMBDA * video_qscale;
2369
                }
2370

    
2371
                if(intra_matrix)
2372
                    video_enc->intra_matrix = intra_matrix;
2373
                if(inter_matrix)
2374
                    video_enc->inter_matrix = inter_matrix;
2375

    
2376
                if(bitexact)
2377
                    video_enc->flags |= CODEC_FLAG_BITEXACT;
2378

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

    
2460
                video_enc->rc_max_rate = video_rc_max_rate;
2461
                video_enc->rc_min_rate = video_rc_min_rate;
2462
                video_enc->rc_buffer_size = video_rc_buffer_size;
2463
                video_enc->rc_buffer_aggressivity= video_rc_buffer_aggressivity;
2464
                video_enc->rc_initial_cplx= video_rc_initial_cplx;
2465
                video_enc->i_quant_factor = video_i_qfactor;
2466
                video_enc->b_quant_factor = video_b_qfactor;
2467
                video_enc->i_quant_offset = video_i_qoffset;
2468
                video_enc->b_quant_offset = video_b_qoffset;
2469
                video_enc->dct_algo = dct_algo;
2470
                video_enc->idct_algo = idct_algo;
2471
                video_enc->strict_std_compliance = strict;
2472
                video_enc->error_rate = error_rate;
2473
                video_enc->noise_reduction= noise_reduction;
2474
                if(packet_size){
2475
                    video_enc->rtp_mode= 1;
2476
                    video_enc->rtp_payload_size= packet_size;
2477
                }
2478
            
2479
                if (do_psnr)
2480
                    video_enc->flags|= CODEC_FLAG_PSNR;
2481
            
2482
                video_enc->me_method = me_method;
2483

    
2484
                /* two pass mode */
2485
                if (do_pass) {
2486
                    if (do_pass == 1) {
2487
                        video_enc->flags |= CODEC_FLAG_PASS1;
2488
                    } else {
2489
                        video_enc->flags |= CODEC_FLAG_PASS2;
2490
                    }
2491
                }
2492
            }
2493
            oc->streams[nb_streams] = st;
2494
            nb_streams++;
2495
        }
2496
    
2497
        if (use_audio) {
2498
            AVCodecContext *audio_enc;
2499

    
2500
            st = av_mallocz(sizeof(AVStream));
2501
            if (!st) {
2502
                fprintf(stderr, "Could not alloc stream\n");
2503
                exit(1);
2504
            }
2505
            avcodec_get_context_defaults(&st->codec);
2506

    
2507
            audio_enc = &st->codec;
2508
            audio_enc->codec_type = CODEC_TYPE_AUDIO;
2509

    
2510
            if(!strcmp(file_oformat->name, "mp4") || !strcmp(file_oformat->name, "mov") || !strcmp(file_oformat->name, "3gp"))
2511
                audio_enc->flags |= CODEC_FLAG_GLOBAL_HEADER;
2512
            if (audio_stream_copy) {
2513
                st->stream_copy = 1;
2514
            } else {
2515
                codec_id = file_oformat->audio_codec;
2516
                if (audio_codec_id != CODEC_ID_NONE)
2517
                    codec_id = audio_codec_id;
2518
                audio_enc->codec_id = codec_id;
2519
                
2520
                audio_enc->bit_rate = audio_bit_rate;
2521
                audio_enc->sample_rate = audio_sample_rate;
2522
                /* For audio codecs other than AC3 we limit */
2523
                /* the number of coded channels to stereo   */
2524
                if (audio_channels > 2 && codec_id != CODEC_ID_AC3) {
2525
                    audio_enc->channels = 2;
2526
                } else
2527
                    audio_enc->channels = audio_channels;
2528
            }
2529
            oc->streams[nb_streams] = st;
2530
            nb_streams++;
2531
        }
2532

    
2533
        oc->nb_streams = nb_streams;
2534

    
2535
        if (!nb_streams) {
2536
            fprintf(stderr, "No audio or video streams available\n");
2537
            exit(1);
2538
        }
2539

    
2540
        if (str_title)
2541
            pstrcpy(oc->title, sizeof(oc->title), str_title);
2542
        if (str_author)
2543
            pstrcpy(oc->author, sizeof(oc->author), str_author);
2544
        if (str_copyright)
2545
            pstrcpy(oc->copyright, sizeof(oc->copyright), str_copyright);
2546
        if (str_comment)
2547
            pstrcpy(oc->comment, sizeof(oc->comment), str_comment);
2548
    }
2549

    
2550
    output_files[nb_output_files++] = oc;
2551

    
2552
    strcpy(oc->filename, filename);
2553

    
2554
    /* check filename in case of an image number is expected */
2555
    if (oc->oformat->flags & AVFMT_NEEDNUMBER) {
2556
        if (filename_number_test(oc->filename) < 0) {
2557
            print_error(oc->filename, AVERROR_NUMEXPECTED);
2558
            exit(1);
2559
        }
2560
    }
2561

    
2562
    if (!(oc->oformat->flags & AVFMT_NOFILE)) {
2563
        /* test if it already exists to avoid loosing precious files */
2564
        if (!file_overwrite && 
2565
            (strchr(filename, ':') == NULL ||
2566
             strstart(filename, "file:", NULL))) {
2567
            if (url_exist(filename)) {
2568
                int c;
2569
                
2570
                if ( !using_stdin ) {
2571
                    fprintf(stderr,"File '%s' already exists. Overwrite ? [y/N] ", filename);
2572
                    fflush(stderr);
2573
                    c = getchar();
2574
                    if (toupper(c) != 'Y') {
2575
                        fprintf(stderr, "Not overwriting - exiting\n");
2576
                        exit(1);
2577
                    }
2578
                                }
2579
                                else {
2580
                    fprintf(stderr,"File '%s' already exists. Exiting.\n", filename);
2581
                    exit(1);
2582
                                }
2583
            }
2584
        }
2585
        
2586
        /* open the file */
2587
        if (url_fopen(&oc->pb, filename, URL_WRONLY) < 0) {
2588
            fprintf(stderr, "Could not open '%s'\n", filename);
2589
            exit(1);
2590
        }
2591
    }
2592

    
2593
    memset(ap, 0, sizeof(*ap));
2594
    ap->image_format = image_format;
2595
    if (av_set_parameters(oc, ap) < 0) {
2596
        fprintf(stderr, "%s: Invalid encoding parameters\n",
2597
                oc->filename);
2598
        exit(1);
2599
    }
2600

    
2601
    /* reset some options */
2602
    file_oformat = NULL;
2603
    file_iformat = NULL;
2604
    image_format = NULL;
2605
    audio_disable = 0;
2606
    video_disable = 0;
2607
    audio_codec_id = CODEC_ID_NONE;
2608
    video_codec_id = CODEC_ID_NONE;
2609
    audio_stream_copy = 0;
2610
    video_stream_copy = 0;
2611
}
2612

    
2613
/* prepare dummy protocols for grab */
2614
static void prepare_grab(void)
2615
{
2616
    int has_video, has_audio, i, j;
2617
    AVFormatContext *oc;
2618
    AVFormatContext *ic;
2619
    AVFormatParameters vp1, *vp = &vp1;
2620
    AVFormatParameters ap1, *ap = &ap1;
2621
    
2622
    /* see if audio/video inputs are needed */
2623
    has_video = 0;
2624
    has_audio = 0;
2625
    memset(ap, 0, sizeof(*ap));
2626
    memset(vp, 0, sizeof(*vp));
2627
    for(j=0;j<nb_output_files;j++) {
2628
        oc = output_files[j];
2629
        for(i=0;i<oc->nb_streams;i++) {
2630
            AVCodecContext *enc = &oc->streams[i]->codec;
2631
            switch(enc->codec_type) {
2632
            case CODEC_TYPE_AUDIO:
2633
                if (enc->sample_rate > ap->sample_rate)
2634
                    ap->sample_rate = enc->sample_rate;
2635
                if (enc->channels > ap->channels)
2636
                    ap->channels = enc->channels;
2637
                has_audio = 1;
2638
                break;
2639
            case CODEC_TYPE_VIDEO:
2640
                if (enc->width > vp->width)
2641
                    vp->width = enc->width;
2642
                if (enc->height > vp->height)
2643
                    vp->height = enc->height;
2644
                
2645
                assert(enc->frame_rate_base == DEFAULT_FRAME_RATE_BASE);
2646
                if (enc->frame_rate > vp->frame_rate){
2647
                    vp->frame_rate      = enc->frame_rate;
2648
                    vp->frame_rate_base = enc->frame_rate_base;
2649
                }
2650
                has_video = 1;
2651
                break;
2652
            default:
2653
                av_abort();
2654
            }
2655
        }
2656
    }
2657
    
2658
    if (has_video == 0 && has_audio == 0) {
2659
        fprintf(stderr, "Output file must have at least one audio or video stream\n");
2660
        exit(1);
2661
    }
2662
    
2663
    if (has_video) {
2664
        AVInputFormat *fmt1;
2665
        fmt1 = av_find_input_format(video_grab_format);
2666
        vp->device  = video_device;
2667
        vp->channel = video_channel;
2668
        vp->standard = video_standard;
2669
        if (av_open_input_file(&ic, "", fmt1, 0, vp) < 0) {
2670
            fprintf(stderr, "Could not find video grab device\n");
2671
            exit(1);
2672
        }
2673
        /* If not enough info to get the stream parameters, we decode the
2674
           first frames to get it. */
2675
        if ((ic->ctx_flags & AVFMTCTX_NOHEADER) && av_find_stream_info(ic) < 0) {
2676
            fprintf(stderr, "Could not find video grab parameters\n");
2677
            exit(1);
2678
        }
2679
        /* by now video grab has one stream */
2680
        ic->streams[0]->r_frame_rate      = vp->frame_rate;
2681
        ic->streams[0]->r_frame_rate_base = vp->frame_rate_base;
2682
        input_files[nb_input_files] = ic;
2683
        dump_format(ic, nb_input_files, "", 0);
2684
        nb_input_files++;
2685
    }
2686
    if (has_audio && audio_grab_format) {
2687
        AVInputFormat *fmt1;
2688
        fmt1 = av_find_input_format(audio_grab_format);
2689
        ap->device = audio_device;
2690
        if (av_open_input_file(&ic, "", fmt1, 0, ap) < 0) {
2691
            fprintf(stderr, "Could not find audio grab device\n");
2692
            exit(1);
2693
        }
2694
        input_files[nb_input_files] = ic;
2695
        dump_format(ic, nb_input_files, "", 0);
2696
        nb_input_files++;
2697
    }
2698
}
2699

    
2700
/* same option as mencoder */
2701
static void opt_pass(const char *pass_str)
2702
{
2703
    int pass;
2704
    pass = atoi(pass_str);
2705
    if (pass != 1 && pass != 2) {
2706
        fprintf(stderr, "pass number can be only 1 or 2\n");
2707
        exit(1);
2708
    }
2709
    do_pass = pass;
2710
}
2711

    
2712
#if defined(CONFIG_WIN32) || defined(CONFIG_OS2)
2713
static int64_t getutime(void)
2714
{
2715
  return av_gettime();
2716
}
2717
#else
2718
static int64_t getutime(void)
2719
{
2720
    struct rusage rusage;
2721

    
2722
    getrusage(RUSAGE_SELF, &rusage);
2723
    return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
2724
}
2725
#endif
2726

    
2727
extern int ffm_nopts;
2728

    
2729
static void opt_bitexact(void)
2730
{
2731
    bitexact=1;
2732
    /* disable generate of real time pts in ffm (need to be supressed anyway) */
2733
    ffm_nopts = 1;
2734
}
2735

    
2736
static void show_formats(void)
2737
{
2738
    AVInputFormat *ifmt;
2739
    AVOutputFormat *ofmt;
2740
    AVImageFormat *image_fmt;
2741
    URLProtocol *up;
2742
    AVCodec *p;
2743
    const char **pp;
2744

    
2745
    printf("Output audio/video file formats:");
2746
    for(ofmt = first_oformat; ofmt != NULL; ofmt = ofmt->next) {
2747
        printf(" %s", ofmt->name);
2748
    }
2749
    printf("\n");
2750

    
2751
    printf("Input audio/video file formats:");
2752
    for(ifmt = first_iformat; ifmt != NULL; ifmt = ifmt->next) {
2753
        printf(" %s", ifmt->name);
2754
    }
2755
    printf("\n");
2756

    
2757
    printf("Output image formats:");
2758
    for(image_fmt = first_image_format; image_fmt != NULL; 
2759
        image_fmt = image_fmt->next) {
2760
        if (image_fmt->img_write)
2761
            printf(" %s", image_fmt->name);
2762
    }
2763
    printf("\n");
2764

    
2765
    printf("Input image formats:");
2766
    for(image_fmt = first_image_format; image_fmt != NULL; 
2767
        image_fmt = image_fmt->next) {
2768
        if (image_fmt->img_read)
2769
            printf(" %s", image_fmt->name);
2770
    }
2771
    printf("\n");
2772

    
2773
    printf("Codecs:\n");
2774
    printf("  Encoders:");
2775
    for(p = first_avcodec; p != NULL; p = p->next) {
2776
        if (p->encode)
2777
            printf(" %s", p->name);
2778
    }
2779
    printf("\n");
2780

    
2781
    printf("  Decoders:");
2782
    for(p = first_avcodec; p != NULL; p = p->next) {
2783
        if (p->decode)
2784
            printf(" %s", p->name);
2785
    }
2786
    printf("\n");
2787

    
2788
    printf("Supported file protocols:");
2789
    for(up = first_protocol; up != NULL; up = up->next)
2790
        printf(" %s:", up->name);
2791
    printf("\n");
2792
    
2793
    printf("Frame size, frame rate abbreviations: ntsc pal qntsc qpal sntsc spal film ntsc-film sqcif qcif cif 4cif\n");
2794
    printf("Motion estimation methods:");
2795
    pp = motion_str;
2796
    while (*pp) {
2797
        printf(" %s", *pp);
2798
        if ((pp - motion_str + 1) == ME_ZERO) 
2799
            printf("(fastest)");
2800
        else if ((pp - motion_str + 1) == ME_FULL) 
2801
            printf("(slowest)");
2802
        else if ((pp - motion_str + 1) == ME_EPZS) 
2803
            printf("(default)");
2804
        pp++;
2805
    }
2806
    printf("\n");
2807
    exit(1);
2808
}
2809

    
2810
void parse_matrix_coeffs(uint16_t *dest, const char *str)
2811
{
2812
    int i;
2813
    const char *p = str;
2814
    for(i = 0;; i++) {
2815
        dest[i] = atoi(p);
2816
        if(i == 63)
2817
            break;
2818
        p = strchr(p, ',');
2819
        if(!p) {
2820
            fprintf(stderr, "Syntax error in matrix \"%s\" at coeff %d\n", str, i);
2821
            exit(1);
2822
        }
2823
        p++;
2824
    }
2825
}
2826

    
2827
void opt_inter_matrix(const char *arg)
2828
{
2829
    inter_matrix = av_mallocz(sizeof(uint16_t) * 64);
2830
    parse_matrix_coeffs(inter_matrix, arg);
2831
}
2832

    
2833
void opt_intra_matrix(const char *arg)
2834
{
2835
    intra_matrix = av_mallocz(sizeof(uint16_t) * 64);
2836
    parse_matrix_coeffs(intra_matrix, arg);
2837
}
2838

    
2839
static void opt_target(const char *arg)
2840
{
2841
    int norm = -1;
2842

    
2843
    if(!strncmp(arg, "pal-", 4)) {
2844
        norm = 0;
2845
        arg += 4;
2846
    } else if(!strncmp(arg, "ntsc-", 5)) {
2847
        norm = 1;
2848
        arg += 5;
2849
    } else {
2850
        int fr;
2851
        /* Calculate FR via float to avoid int overflow */
2852
        fr = (int)(frame_rate * 1000.0 / frame_rate_base);
2853
        if(fr == 25000) {
2854
            norm = 0;
2855
        } else if((fr == 29970) || (fr == 23976)) {
2856
            norm = 1;
2857
        } else {
2858
            /* Try to determine PAL/NTSC by peeking in the input files */
2859
            if(nb_input_files) {
2860
                int i, j;
2861
                for(j = 0; j < nb_input_files; j++) {
2862
                    for(i = 0; i < input_files[j]->nb_streams; i++) {
2863
                        AVCodecContext *c = &input_files[j]->streams[i]->codec;
2864
                        if(c->codec_type != CODEC_TYPE_VIDEO)
2865
                            continue;
2866
                        fr = c->frame_rate * 1000 / c->frame_rate_base;
2867
                        if(fr == 25000) {
2868
                            norm = 0;
2869
                            break;
2870
                        } else if((fr == 29970) || (fr == 23976)) {
2871
                            norm = 1;
2872
                            break;
2873
                        }
2874
                    }
2875
                    if(norm >= 0)
2876
                        break;
2877
                }
2878
            }
2879
        }
2880
        if(verbose && norm >= 0)
2881
            printf("Assuming %s for target.\n", norm ? "NTSC" : "PAL");
2882
    }
2883

    
2884
    if(norm < 0) {
2885
        fprintf(stderr, "Could not determine norm (PAL/NTSC) for target.\n");
2886
        fprintf(stderr, "Please prefix target with \"pal-\" or \"ntsc-\",\n");
2887
        fprintf(stderr, "or set a framerate with \"-r xxx\".\n");
2888
        exit(1);
2889
    }
2890

    
2891
    if(!strcmp(arg, "vcd")) {
2892

    
2893
        opt_video_codec("mpeg1video");
2894
        opt_audio_codec("mp2");
2895
        opt_format("vcd");
2896

    
2897
        opt_frame_size(norm ? "352x240" : "352x288");
2898

    
2899
        video_bit_rate = 1150000;
2900
        video_rc_max_rate = 1150000;
2901
        video_rc_min_rate = 1150000;
2902
        video_rc_buffer_size = 40*1024*8;
2903

    
2904
        audio_bit_rate = 224000;
2905
        audio_sample_rate = 44100;
2906

    
2907
    } else if(!strcmp(arg, "svcd")) {
2908

    
2909
        opt_video_codec("mpeg2video");
2910
        opt_audio_codec("mp2");
2911
        opt_format("vcd");
2912

    
2913
        opt_frame_size(norm ? "480x480" : "480x576");
2914
        opt_gop_size(norm ? "18" : "15");
2915

    
2916
        video_bit_rate = 2040000;
2917
        video_rc_max_rate = 2516000;
2918
        video_rc_min_rate = 0; //1145000;
2919
        video_rc_buffer_size = 224*1024*8;
2920
        use_scan_offset = 1;
2921

    
2922
        audio_bit_rate = 224000;
2923
        audio_sample_rate = 44100;
2924

    
2925
    } else if(!strcmp(arg, "dvd")) {
2926

    
2927
        opt_video_codec("mpeg2video");
2928
        opt_audio_codec("ac3");
2929
        opt_format("vob");
2930

    
2931
        opt_frame_size(norm ? "720x480" : "720x576");
2932
        opt_gop_size(norm ? "18" : "15");
2933

    
2934
        video_bit_rate = 6000000;
2935
        video_rc_max_rate = 9000000;
2936
        video_rc_min_rate = 0; //1500000;
2937
        video_rc_buffer_size = 224*1024*8;
2938

    
2939
        audio_bit_rate = 448000;
2940
        audio_sample_rate = 48000;
2941

    
2942
    } else {
2943
        fprintf(stderr, "Unknown target: %s\n", arg);
2944
        exit(1);
2945
    }
2946
}
2947

    
2948
const OptionDef options[] = {
2949
    /* main options */
2950
    { "L", 0, {(void*)show_license}, "show license" },
2951
    { "h", 0, {(void*)show_help}, "show help" },
2952
    { "formats", 0, {(void*)show_formats}, "show available formats, codecs, protocols, ..." },
2953
    { "f", HAS_ARG, {(void*)opt_format}, "force format", "fmt" },
2954
    { "img", HAS_ARG, {(void*)opt_image_format}, "force image format", "img_fmt" },
2955
    { "i", HAS_ARG, {(void*)opt_input_file}, "input file name", "filename" },
2956
    { "y", OPT_BOOL, {(void*)&file_overwrite}, "overwrite output files" },
2957
    { "map", HAS_ARG | OPT_EXPERT, {(void*)opt_map}, "set input stream mapping", "file:stream" },
2958
    { "t", HAS_ARG, {(void*)opt_recording_time}, "set the recording time", "duration" },
2959
    { "ss", HAS_ARG, {(void*)opt_start_time}, "set the start time offset", "time_off" },
2960
    { "title", HAS_ARG | OPT_STRING, {(void*)&str_title}, "set the title", "string" },
2961
    { "author", HAS_ARG | OPT_STRING, {(void*)&str_author}, "set the author", "string" },
2962
    { "copyright", HAS_ARG | OPT_STRING, {(void*)&str_copyright}, "set the copyright", "string" },
2963
    { "comment", HAS_ARG | OPT_STRING, {(void*)&str_comment}, "set the comment", "string" },
2964
    { "debug", HAS_ARG | OPT_EXPERT, {(void*)opt_debug}, "print specific debug info", "" },
2965
    { "vismv", HAS_ARG | OPT_EXPERT, {(void*)opt_vismv}, "visualize motion vectors", "" },
2966
    { "benchmark", OPT_BOOL | OPT_EXPERT, {(void*)&do_benchmark}, 
2967
      "add timings for benchmarking" },
2968
    { "dump", OPT_BOOL | OPT_EXPERT, {(void*)&do_pkt_dump}, 
2969
      "dump each input packet" },
2970
    { "hex", OPT_BOOL | OPT_EXPERT, {(void*)&do_hex_dump}, 
2971
      "when dumping packets, also dump the payload" },
2972
    { "bitexact", OPT_EXPERT, {(void*)opt_bitexact}, "only use bit exact algorithms (for codec testing)" }, 
2973
    { "re", OPT_BOOL | OPT_EXPERT, {(void*)&rate_emu}, "read input at native frame rate", "" },
2974
    { "loop", OPT_BOOL | OPT_EXPERT, {(void*)&loop_input}, "loop (current only works with images)" },
2975
    { "v", HAS_ARG, {(void*)opt_verbose}, "control amount of logging", "verbose" },
2976
    { "target", HAS_ARG, {(void*)opt_target}, "specify target file type (\"vcd\", \"svcd\" or \"dvd\")", "type" },
2977

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

    
3056
    /* audio options */
3057
    { "ab", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_bitrate}, "set audio bitrate (in kbit/s)", "bitrate", },
3058
    { "ar", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_rate}, "set audio sampling rate (in Hz)", "rate" },
3059
    { "ac", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_channels}, "set number of audio channels", "channels" },
3060
    { "an", OPT_BOOL | OPT_AUDIO, {(void*)&audio_disable}, "disable audio" },
3061
    { "acodec", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_codec}, "force audio codec ('copy' to copy stream)", "codec" },
3062

    
3063
    /* grab options */
3064
    { "vd", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_device}, "set video grab device", "device" },
3065
    { "vc", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_channel}, "set video grab channel (DV1394 only)", "channel" },
3066
    { "tvstd", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_standard}, "set television standard (NTSC, PAL (SECAM))", "standard" },
3067
    { "dv1394", OPT_EXPERT | OPT_GRAB, {(void*)opt_dv1394}, "set DV1394 grab", "" },
3068
    { "ad", HAS_ARG | OPT_EXPERT | OPT_AUDIO | OPT_GRAB, {(void*)opt_audio_device}, "set audio device", "device" },
3069
    { NULL, },
3070
};
3071

    
3072
static void show_banner(void)
3073
{
3074
    printf("ffmpeg version " FFMPEG_VERSION ", Copyright (c) 2000-2003 Fabrice Bellard\n");
3075
}
3076

    
3077
static void show_license(void)
3078
{
3079
    show_banner();
3080
    printf(
3081
    "This library is free software; you can redistribute it and/or\n"
3082
    "modify it under the terms of the GNU Lesser General Public\n"
3083
    "License as published by the Free Software Foundation; either\n"
3084
    "version 2 of the License, or (at your option) any later version.\n"
3085
    "\n"
3086
    "This library is distributed in the hope that it will be useful,\n"
3087
    "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
3088
    "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n"
3089
    "Lesser General Public License for more details.\n"
3090
    "\n"
3091
    "You should have received a copy of the GNU Lesser General Public\n"
3092
    "License along with this library; if not, write to the Free Software\n"
3093
    "Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n"
3094
    );
3095
    exit(1);
3096
}
3097

    
3098
static void show_help(void)
3099
{
3100
    show_banner();
3101
    printf("usage: ffmpeg [[options] -i input_file]... {[options] outfile}...\n"
3102
           "Hyper fast Audio and Video encoder\n");
3103
    printf("\n");
3104
    show_help_options(options, "Main options:\n",
3105
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO, 0);
3106
    show_help_options(options, "\nVideo options:\n",
3107
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB, 
3108
                      OPT_VIDEO);
3109
    show_help_options(options, "\nAdvanced Video options:\n",
3110
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB, 
3111
                      OPT_VIDEO | OPT_EXPERT);
3112
    show_help_options(options, "\nAudio options:\n",
3113
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB, 
3114
                      OPT_AUDIO);
3115
    show_help_options(options, "\nAdvanced Audio options:\n",
3116
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB, 
3117
                      OPT_AUDIO | OPT_EXPERT);
3118
    show_help_options(options, "\nAudio/Video grab options:\n",
3119
                      OPT_GRAB, 
3120
                      OPT_GRAB);
3121
    show_help_options(options, "\nAdvanced options:\n",
3122
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB, 
3123
                      OPT_EXPERT);
3124
    exit(1);
3125
}
3126

    
3127
void parse_arg_file(const char *filename)
3128
{
3129
    opt_output_file(filename);
3130
}
3131

    
3132
int main(int argc, char **argv)
3133
{
3134
    int i;
3135
    int64_t ti;
3136

    
3137
    av_register_all();
3138

    
3139
    if (argc <= 1)
3140
        show_help();
3141
    
3142
    /* parse options */
3143
    parse_options(argc, argv, options);
3144

    
3145
    /* file converter / grab */
3146
    if (nb_output_files <= 0) {
3147
        fprintf(stderr, "Must supply at least one output file\n");
3148
        exit(1);
3149
    }
3150
    
3151
    if (nb_input_files == 0) {
3152
        prepare_grab();
3153
    }
3154

    
3155
    ti = getutime();
3156
    av_encode(output_files, nb_output_files, input_files, nb_input_files, 
3157
              stream_maps, nb_stream_maps);
3158
    ti = getutime() - ti;
3159
    if (do_benchmark) {
3160
        printf("bench: utime=%0.3fs\n", ti / 1000000.0);
3161
    }
3162

    
3163
    /* close files */
3164
    for(i=0;i<nb_output_files;i++) {
3165
        /* maybe av_close_output_file ??? */
3166
        AVFormatContext *s = output_files[i];
3167
        int j;
3168
        if (!(s->oformat->flags & AVFMT_NOFILE))
3169
            url_fclose(&s->pb);
3170
        for(j=0;j<s->nb_streams;j++)
3171
            av_free(s->streams[j]);
3172
        av_free(s);
3173
    }
3174
    for(i=0;i<nb_input_files;i++)
3175
        av_close_input_file(input_files[i]);
3176

    
3177
    av_free_static();
3178

    
3179
    if(intra_matrix)
3180
        av_free(intra_matrix);
3181
    if(inter_matrix)
3182
        av_free(inter_matrix);
3183
    
3184
#ifdef POWERPC_PERFORMANCE_REPORT
3185
    extern void powerpc_display_perf_report(void);
3186
    powerpc_display_perf_report();
3187
#endif /* POWERPC_PERFORMANCE_REPORT */
3188

    
3189
#ifndef CONFIG_WIN32
3190
    if (received_sigterm) {
3191
        fprintf(stderr,
3192
            "Received signal %d: terminating.\n",
3193
            (int) received_sigterm);
3194
        exit (255);
3195
    }
3196
#endif
3197
    exit(0); /* not all OS-es handle main() return value */
3198
    return 0;
3199
}