Statistics
| Branch: | Revision:

ffmpeg / ffmpeg.c @ 890972be

History | View | Annotate | Download (103 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 mb_cmp = FF_CMP_SAD;
115
static int sub_cmp = FF_CMP_SAD;
116
static int cmp = FF_CMP_SAD;
117
static int use_4mv = 0;
118
static int use_obmc = 0;
119
static int use_aic = 0;
120
static int use_aiv = 0;
121
static int use_umv = 0;
122
static int do_deinterlace = 0;
123
static int do_interlace = 0;
124
static int workaround_bugs = FF_BUG_AUTODETECT;
125
static int error_resilience = 2;
126
static int error_concealment = 3;
127
static int dct_algo = 0;
128
static int idct_algo = 0;
129
static int use_part = 0;
130
static int packet_size = 0;
131
static int error_rate = 0;
132
static int strict = 0;
133
static int debug = 0;
134
extern int loop_input; /* currently a hack */
135

    
136
static int gop_size = 12;
137
static int intra_only = 0;
138
static int audio_sample_rate = 44100;
139
static int audio_bit_rate = 64000;
140
static int audio_disable = 0;
141
static int audio_channels = 1;
142
static int audio_codec_id = CODEC_ID_NONE;
143

    
144
static int64_t recording_time = 0;
145
static int64_t start_time = 0;
146
static int file_overwrite = 0;
147
static char *str_title = NULL;
148
static char *str_author = NULL;
149
static char *str_copyright = NULL;
150
static char *str_comment = NULL;
151
static int do_benchmark = 0;
152
static int do_hex_dump = 0;
153
static int do_pkt_dump = 0;
154
static int do_psnr = 0;
155
static int do_vstats = 0;
156
static int do_pass = 0;
157
static int bitexact = 0;
158
static char *pass_logfilename = NULL;
159
static int audio_stream_copy = 0;
160
static int video_stream_copy = 0;
161

    
162
static int rate_emu = 0;
163

    
164
static char *video_grab_format = "video4linux";
165
static char *video_device = NULL;
166
static int  video_channel = 0;
167
static char *video_standard = "ntsc";
168

    
169
static char *audio_grab_format = "audio_device";
170
static char *audio_device = NULL;
171

    
172
static int using_stdin = 0;
173
static int using_vhook = 0;
174
static int verbose = 1;
175

    
176
#define DEFAULT_PASS_LOGFILENAME "ffmpeg2pass"
177

    
178
typedef struct AVOutputStream {
179
    int file_index;          /* file index */
180
    int index;               /* stream index in the output file */
181
    int source_index;        /* AVInputStream index */
182
    AVStream *st;            /* stream in the output file */
183
    int encoding_needed;     /* true if encoding needed for this stream */
184
    int frame_number;
185
    /* input pts and corresponding output pts
186
       for A/V sync */
187
    double sync_ipts;
188
    double sync_ipts_offset;
189
    int64_t sync_opts;
190
    /* video only */
191
    int video_resample;      /* video_resample and video_crop are mutually exclusive */
192
    AVPicture pict_tmp;      /* temporary image for resampling */
193
    ImgReSampleContext *img_resample_ctx; /* for image resampling */
194

    
195
    int video_crop;          /* video_resample and video_crop are mutually exclusive */
196
    int topBand;             /* cropping area sizes */
197
    int leftBand;
198
    
199
    /* audio only */
200
    int audio_resample;
201
    ReSampleContext *resample; /* for audio resampling */
202
    FifoBuffer fifo;     /* for compression: one audio fifo per codec */
203
    FILE *logfile;
204
} AVOutputStream;
205

    
206
typedef struct AVInputStream {
207
    int file_index;
208
    int index;
209
    AVStream *st;
210
    int discard;             /* true if stream data should be discarded */
211
    int decoding_needed;     /* true if the packets must be decoded in 'raw_fifo' */
212
    int64_t sample_index;      /* current sample */
213

    
214
    int64_t       start;     /* time when read started */
215
    unsigned long frame;     /* current frame */
216
    int64_t       next_pts;  /* synthetic pts for cases where pkt.pts
217
                                is not defined */
218
    int64_t       pts;       /* current pts */
219
} AVInputStream;
220

    
221
typedef struct AVInputFile {
222
    int eof_reached;      /* true if eof reached */
223
    int ist_index;        /* index of first stream in ist_table */
224
    int buffer_size;      /* current total buffer size */
225
    int buffer_size_max;  /* buffer size at which we consider we can stop
226
                             buffering */
227
    int nb_streams;       /* nb streams we are aware of */
228
} AVInputFile;
229

    
230
#ifndef CONFIG_WIN32
231

    
232
/* init terminal so that we can grab keys */
233
static struct termios oldtty;
234

    
235
static void term_exit(void)
236
{
237
    tcsetattr (0, TCSANOW, &oldtty);
238
}
239

    
240
static volatile sig_atomic_t received_sigterm = 0;
241

    
242
static void
243
sigterm_handler(int sig)
244
{
245
    received_sigterm = sig;
246
    term_exit();
247
}
248

    
249
static void term_init(void)
250
{
251
    struct termios tty;
252

    
253
    tcgetattr (0, &tty);
254
    oldtty = tty;
255

    
256
    tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
257
                          |INLCR|IGNCR|ICRNL|IXON);
258
    tty.c_oflag |= OPOST;
259
    tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
260
    tty.c_cflag &= ~(CSIZE|PARENB);
261
    tty.c_cflag |= CS8;
262
    tty.c_cc[VMIN] = 1;
263
    tty.c_cc[VTIME] = 0;
264
    
265
    tcsetattr (0, TCSANOW, &tty);
266

    
267
    signal(SIGINT , sigterm_handler); /* Interrupt (ANSI).  */
268
    signal(SIGQUIT, sigterm_handler); /* Quit (POSIX).  */
269
    signal(SIGTERM, sigterm_handler); /* Termination (ANSI).  */
270
    /*
271
    register a function to be called at normal program termination
272
    */
273
    atexit(term_exit);
274
#ifdef CONFIG_BEOS_NETSERVER
275
    fcntl(0, F_SETFL, fcntl(0, F_GETFL) | O_NONBLOCK);
276
#endif
277
}
278

    
279
/* read a key without blocking */
280
static int read_key(void)
281
{
282
    int n = 1;
283
    unsigned char ch;
284
#ifndef CONFIG_BEOS_NETSERVER
285
    struct timeval tv;
286
    fd_set rfds;
287

    
288
    FD_ZERO(&rfds);
289
    FD_SET(0, &rfds);
290
    tv.tv_sec = 0;
291
    tv.tv_usec = 0;
292
    n = select(1, &rfds, NULL, NULL, &tv);
293
#endif
294
    if (n > 0) {
295
        n = read(0, &ch, 1);
296
        if (n == 1)
297
            return ch;
298

    
299
        return n;
300
    }
301
    return -1;
302
}
303

    
304
#else
305

    
306
static volatile int received_sigterm = 0;
307

    
308
/* no interactive support */
309
static void term_exit(void)
310
{
311
}
312

    
313
static void term_init(void)
314
{
315
}
316

    
317
static int read_key(void)
318
{
319
    return 0;
320
}
321

    
322
#endif
323

    
324
static int read_ffserver_streams(AVFormatContext *s, const char *filename)
325
{
326
    int i, err;
327
    AVFormatContext *ic;
328

    
329
    err = av_open_input_file(&ic, filename, NULL, FFM_PACKET_SIZE, NULL);
330
    if (err < 0)
331
        return err;
332
    /* copy stream format */
333
    s->nb_streams = ic->nb_streams;
334
    for(i=0;i<ic->nb_streams;i++) {
335
        AVStream *st;
336

    
337
        st = av_mallocz(sizeof(AVStream));
338
        memcpy(st, ic->streams[i], sizeof(AVStream));
339
        s->streams[i] = st;
340
    }
341

    
342
    av_close_input_file(ic);
343
    return 0;
344
}
345

    
346
#define MAX_AUDIO_PACKET_SIZE (128 * 1024)
347

    
348
static void do_audio_out(AVFormatContext *s, 
349
                         AVOutputStream *ost, 
350
                         AVInputStream *ist,
351
                         unsigned char *buf, int size)
352
{
353
    uint8_t *buftmp;
354
    static uint8_t *audio_buf = NULL;
355
    static uint8_t *audio_out = NULL;
356
    const int audio_out_size= 4*MAX_AUDIO_PACKET_SIZE;
357

    
358
    int size_out, frame_bytes, ret;
359
    AVCodecContext *enc;
360

    
361
    /* SC: dynamic allocation of buffers */
362
    if (!audio_buf)
363
        audio_buf = av_malloc(2*MAX_AUDIO_PACKET_SIZE);
364
    if (!audio_out)
365
        audio_out = av_malloc(audio_out_size);
366
    if (!audio_buf || !audio_out)
367
        return;               /* Should signal an error ! */
368

    
369
    
370
    enc = &ost->st->codec;
371

    
372
    if (ost->audio_resample) {
373
        buftmp = audio_buf;
374
        size_out = audio_resample(ost->resample, 
375
                                  (short *)buftmp, (short *)buf,
376
                                  size / (ist->st->codec.channels * 2));
377
        size_out = size_out * enc->channels * 2;
378
    } else {
379
        buftmp = buf;
380
        size_out = size;
381
    }
382

    
383
    /* now encode as many frames as possible */
384
    if (enc->frame_size > 1) {
385
        /* output resampled raw samples */
386
        fifo_write(&ost->fifo, buftmp, size_out, 
387
                   &ost->fifo.wptr);
388

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

    
416
static void pre_process_video_frame(AVInputStream *ist, AVPicture *picture, void **bufp)
417
{
418
    AVCodecContext *dec;
419
    AVPicture *picture2;
420
    AVPicture picture_tmp;
421
    uint8_t *buf = 0;
422

    
423
    dec = &ist->st->codec;
424

    
425
    /* deinterlace : must be done before any resize */
426
    if (do_deinterlace || using_vhook) {
427
        int size;
428

    
429
        /* create temporary picture */
430
        size = avpicture_get_size(dec->pix_fmt, dec->width, dec->height);
431
        buf = av_malloc(size);
432
        if (!buf)
433
            return;
434
        
435
        picture2 = &picture_tmp;
436
        avpicture_fill(picture2, buf, dec->pix_fmt, dec->width, dec->height);
437

    
438
        if (do_deinterlace){
439
            if(avpicture_deinterlace(picture2, picture, 
440
                                     dec->pix_fmt, dec->width, dec->height) < 0) {
441
                /* if error, do not deinterlace */
442
                av_free(buf);
443
                buf = NULL;
444
                picture2 = picture;
445
            }
446
        } else {
447
            if (img_convert(picture2, dec->pix_fmt, picture, 
448
                            dec->pix_fmt, dec->width, dec->height) < 0) {
449
                /* if error, do not copy */
450
                av_free(buf);
451
                buf = NULL;
452
                picture2 = picture;
453
            }
454
        }
455
    } else {
456
        picture2 = picture;
457
    }
458

    
459
    frame_hook_process(picture2, dec->pix_fmt, dec->width, dec->height);
460

    
461
    if (picture != picture2)
462
        *picture = *picture2;
463
    *bufp = buf;
464
}
465

    
466
/* we begin to correct av delay at this threshold */
467
#define AV_DELAY_MAX 0.100
468

    
469
static void do_video_out(AVFormatContext *s, 
470
                         AVOutputStream *ost, 
471
                         AVInputStream *ist,
472
                         AVFrame *in_picture,
473
                         int *frame_size, AVOutputStream *audio_sync)
474
{
475
    int nb_frames, i, ret;
476
    AVPicture *final_picture, *formatted_picture;
477
    AVPicture picture_format_temp, picture_crop_temp;
478
    static uint8_t *video_buffer;
479
    uint8_t *buf = NULL, *buf1 = NULL;
480
    AVCodecContext *enc, *dec;
481
    enum PixelFormat target_pixfmt;
482

    
483
#define VIDEO_BUFFER_SIZE (1024*1024)
484

    
485
    enc = &ost->st->codec;
486
    dec = &ist->st->codec;
487

    
488
    /* by default, we output a single frame */
489
    nb_frames = 1;
490

    
491
    *frame_size = 0;
492

    
493
    /* NOTE: the A/V sync is always done by considering the audio is
494
       the master clock. It is suffisant for transcoding or playing,
495
       but not for the general case */
496
    if (audio_sync) {
497
        /* compute the A-V delay and duplicate/remove frames if needed */
498
        double adelta, vdelta, av_delay;
499

    
500
        adelta = audio_sync->sync_ipts - ((double)audio_sync->sync_opts * 
501
            s->pts_num / s->pts_den);
502

    
503
        vdelta = ost->sync_ipts - ((double)ost->sync_opts *
504
            s->pts_num / s->pts_den);
505

    
506
        av_delay = adelta - vdelta;
507
        //            printf("delay=%f\n", av_delay);
508
        if (av_delay < -AV_DELAY_MAX)
509
            nb_frames = 2;
510
        else if (av_delay > AV_DELAY_MAX)
511
            nb_frames = 0;
512
    } else {
513
        double vdelta;
514

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

    
542
    if (nb_frames <= 0) 
543
        return;
544

    
545
    if (!video_buffer)
546
        video_buffer = av_malloc(VIDEO_BUFFER_SIZE);
547
    if (!video_buffer)
548
        return;
549

    
550
    /* convert pixel format if needed */
551
    target_pixfmt = ost->video_resample ? PIX_FMT_YUV420P : enc->pix_fmt;
552
    if (dec->pix_fmt != target_pixfmt) {
553
        int size;
554

    
555
        /* create temporary picture */
556
        size = avpicture_get_size(target_pixfmt, dec->width, dec->height);
557
        buf = av_malloc(size);
558
        if (!buf)
559
            return;
560
        formatted_picture = &picture_format_temp;
561
        avpicture_fill(formatted_picture, buf, target_pixfmt, dec->width, dec->height);
562
        
563
        if (img_convert(formatted_picture, target_pixfmt, 
564
                        (AVPicture *)in_picture, dec->pix_fmt, 
565
                        dec->width, dec->height) < 0) {
566
            fprintf(stderr, "pixel format conversion not handled\n");
567
            goto the_end;
568
        }
569
    } else {
570
        formatted_picture = (AVPicture *)in_picture;
571
    }
572

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

    
602
        picture_crop_temp.data[1] = formatted_picture->data[1] +
603
                ((ost->topBand >> 1) * formatted_picture->linesize[1]) +
604
                (ost->leftBand >> 1);
605

    
606
        picture_crop_temp.data[2] = formatted_picture->data[2] +
607
                ((ost->topBand >> 1) * formatted_picture->linesize[2]) +
608
                (ost->leftBand >> 1);
609

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

    
639
            /* handles sameq here. This is not correct because it may
640
               not be a global option */
641
            if (same_quality) {
642
                big_picture.quality = ist->st->quality;
643
            }else
644
                big_picture.quality = ost->st->quality;
645
            
646
            ret = avcodec_encode_video(enc, 
647
                                       video_buffer, VIDEO_BUFFER_SIZE,
648
                                       &big_picture);
649
            //enc->frame_number = enc->real_pict_num;
650
            av_write_frame(s, ost->index, video_buffer, ret);
651
            *frame_size = ret;
652
            //fprintf(stderr,"\nFrame: %3d %3d size: %5d type: %d",
653
            //        enc->frame_number-1, enc->real_pict_num, ret,
654
            //        enc->pict_type);
655
            /* if two pass, output log */
656
            if (ost->logfile && enc->stats_out) {
657
                fprintf(ost->logfile, "%s", enc->stats_out);
658
            }
659
        }
660
        ost->frame_number++;
661
    }
662
 the_end:
663
    av_free(buf);
664
    av_free(buf1);
665
}
666

    
667
static double psnr(double d){
668
    if(d==0) return INFINITY;
669
    return -10.0*log(d)/log(10.0);
670
}
671

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

    
721
static void print_report(AVFormatContext **output_files,
722
                         AVOutputStream **ost_table, int nb_ostreams,
723
                         int is_last_report)
724
{
725
    char buf[1024];
726
    AVOutputStream *ost;
727
    AVFormatContext *oc, *os;
728
    int64_t total_size;
729
    AVCodecContext *enc;
730
    int frame_number, vid, i;
731
    double bitrate, ti1, pts;
732
    static int64_t last_time = -1;
733
    
734
    if (!is_last_report) {
735
        int64_t cur_time;
736
        /* display the report every 0.5 seconds */
737
        cur_time = av_gettime();
738
        if (last_time == -1) {
739
            last_time = cur_time;
740
            return;
741
        } 
742
        if ((cur_time - last_time) < 500000)
743
            return;
744
        last_time = cur_time;
745
    }
746

    
747

    
748
    oc = output_files[0];
749

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

    
815
/* pkt = NULL means EOF (needed to flush decoder buffers) */
816
static int output_packet(AVInputStream *ist, int ist_index,
817
                         AVOutputStream **ost_table, int nb_ostreams,
818
                         AVPacket *pkt)
819
{
820
    AVFormatContext *os;
821
    AVOutputStream *ost;
822
    uint8_t *ptr;
823
    int len, ret, i;
824
    uint8_t *data_buf;
825
    int data_size, got_picture;
826
    AVFrame picture;
827
    short samples[AVCODEC_MAX_AUDIO_FRAME_SIZE / 2];
828
    void *buffer_to_free;
829
        
830
    if (pkt && pkt->pts != AV_NOPTS_VALUE) {
831
        ist->pts = pkt->pts;
832
    } else {
833
        ist->pts = ist->next_pts;
834
    }
835
    
836
    if (pkt == NULL) {
837
        /* EOF handling */
838
        ptr = NULL;
839
        len = 0;
840
        goto handle_eof;
841
    }
842

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

    
901
            buffer_to_free = NULL;
902
            if (ist->st->codec.codec_type == CODEC_TYPE_VIDEO) {
903
                pre_process_video_frame(ist, (AVPicture *)&picture, 
904
                                        &buffer_to_free);
905
            }
906

    
907
            /* frame rate emulation */
908
            if (ist->st->codec.rate_emu) {
909
                int64_t pts = av_rescale((int64_t) ist->frame * ist->st->codec.frame_rate_base, 1000000, ist->st->codec.frame_rate);
910
                int64_t now = av_gettime() - ist->start;
911
                if (pts > now)
912
                    usleep(pts - now);
913

    
914
                ist->frame++;
915
            }
916

    
917
#if 0
918
            /* mpeg PTS deordering : if it is a P or I frame, the PTS
919
               is the one of the next displayed one */
920
            /* XXX: add mpeg4 too ? */
921
            if (ist->st->codec.codec_id == CODEC_ID_MPEG1VIDEO) {
922
                if (ist->st->codec.pict_type != B_TYPE) {
923
                    int64_t tmp;
924
                    tmp = ist->last_ip_pts;
925
                    ist->last_ip_pts  = ist->frac_pts.val;
926
                    ist->frac_pts.val = tmp;
927
                }
928
            }
929
#endif
930
            /* if output time reached then transcode raw format, 
931
               encode packets and output them */
932
            if (start_time == 0 || ist->pts >= start_time)
933
                for(i=0;i<nb_ostreams;i++) {
934
                    int frame_size;
935

    
936
                    ost = ost_table[i];
937
                    if (ost->source_index == ist_index) {
938
                        os = output_files[ost->file_index];
939

    
940
#if 0
941
                        printf("%d: got pts=%0.3f %0.3f\n", i, 
942
                               (double)pkt->pts / AV_TIME_BASE, 
943
                               ((double)ist->pts / AV_TIME_BASE) - 
944
                               ((double)ost->st->pts.val * os->pts_num / os->pts_den));
945
#endif
946
                        /* set the input output pts pairs */
947
                        ost->sync_ipts = (double)ist->pts / AV_TIME_BASE;
948
                        /* XXX: take into account the various fifos,
949
                           in particular for audio */
950
                        ost->sync_opts = ost->st->pts.val;
951
                        //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); 
952

    
953
                        if (ost->encoding_needed) {
954
                            switch(ost->st->codec.codec_type) {
955
                            case CODEC_TYPE_AUDIO:
956
                                do_audio_out(os, ost, ist, data_buf, data_size);
957
                                break;
958
                            case CODEC_TYPE_VIDEO:
959
                                /* find an audio stream for synchro */
960
                                {
961
                                    int i;
962
                                    AVOutputStream *audio_sync, *ost1;
963
                                    audio_sync = NULL;
964
                                    for(i=0;i<nb_ostreams;i++) {
965
                                        ost1 = ost_table[i];
966
                                        if (ost1->file_index == ost->file_index &&
967
                                            ost1->st->codec.codec_type == CODEC_TYPE_AUDIO) {
968
                                            audio_sync = ost1;
969
                                            break;
970
                                        }
971
                                    }
972

    
973
                                    do_video_out(os, ost, ist, &picture, &frame_size, audio_sync);
974
                                    if (do_vstats && frame_size)
975
                                        do_video_stats(os, ost, frame_size);
976
                                }
977
                                break;
978
                            default:
979
                                av_abort();
980
                            }
981
                        } else {
982
                            AVFrame avframe;
983
                                                
984
                            /* no reencoding needed : output the packet directly */
985
                            /* force the input stream PTS */
986
                        
987
                            memset(&avframe, 0, sizeof(AVFrame));
988
                            ost->st->codec.coded_frame= &avframe;
989
                            avframe.key_frame = pkt->flags & PKT_FLAG_KEY; 
990
                        
991
                            av_write_frame(os, ost->index, data_buf, data_size);
992
                            ost->st->codec.frame_number++;
993
                            ost->frame_number++;
994
                        }
995
                    }
996
                }
997
            av_free(buffer_to_free);
998
        }
999
 discard_packet:
1000
    return 0;
1001
 fail_decode:
1002
    return -1;
1003
}
1004

    
1005

    
1006
/*
1007
 * The following code is the main loop of the file converter
1008
 */
1009
static int av_encode(AVFormatContext **output_files,
1010
                     int nb_output_files,
1011
                     AVFormatContext **input_files,
1012
                     int nb_input_files,
1013
                     AVStreamMap *stream_maps, int nb_stream_maps)
1014
{
1015
    int ret, i, j, k, n, nb_istreams = 0, nb_ostreams = 0;
1016
    AVFormatContext *is, *os;
1017
    AVCodecContext *codec, *icodec;
1018
    AVOutputStream *ost, **ost_table = NULL;
1019
    AVInputStream *ist, **ist_table = NULL;
1020
    AVInputFile *file_table;
1021
    AVFormatContext *stream_no_data;
1022
    int key;
1023

    
1024
    file_table= (AVInputFile*) av_mallocz(nb_input_files * sizeof(AVInputFile));
1025
    if (!file_table)
1026
        goto fail;
1027

    
1028
    /* input stream init */
1029
    j = 0;
1030
    for(i=0;i<nb_input_files;i++) {
1031
        is = input_files[i];
1032
        file_table[i].ist_index = j;
1033
        file_table[i].nb_streams = is->nb_streams;
1034
        j += is->nb_streams;
1035
    }
1036
    nb_istreams = j;
1037

    
1038
    ist_table = av_mallocz(nb_istreams * sizeof(AVInputStream *));
1039
    if (!ist_table)
1040
        goto fail;
1041
    
1042
    for(i=0;i<nb_istreams;i++) {
1043
        ist = av_mallocz(sizeof(AVInputStream));
1044
        if (!ist)
1045
            goto fail;
1046
        ist_table[i] = ist;
1047
    }
1048
    j = 0;
1049
    for(i=0;i<nb_input_files;i++) {
1050
        is = input_files[i];
1051
        for(k=0;k<is->nb_streams;k++) {
1052
            ist = ist_table[j++];
1053
            ist->st = is->streams[k];
1054
            ist->file_index = i;
1055
            ist->index = k;
1056
            ist->discard = 1; /* the stream is discarded by default
1057
                                 (changed later) */
1058

    
1059
            if (ist->st->codec.rate_emu) {
1060
                ist->start = av_gettime();
1061
                ist->frame = 0;
1062
            }
1063
        }
1064
    }
1065

    
1066
    /* output stream init */
1067
    nb_ostreams = 0;
1068
    for(i=0;i<nb_output_files;i++) {
1069
        os = output_files[i];
1070
        nb_ostreams += os->nb_streams;
1071
    }
1072
    if (nb_stream_maps > 0 && nb_stream_maps != nb_ostreams) {
1073
        fprintf(stderr, "Number of stream maps must match number of output streams\n");
1074
        exit(1);
1075
    }
1076

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

    
1153
    /* for each output stream, we compute the right encoding parameters */
1154
    for(i=0;i<nb_ostreams;i++) {
1155
        ost = ost_table[i];
1156
        ist = ist_table[ost->source_index];
1157

    
1158
        codec = &ost->st->codec;
1159
        icodec = &ist->st->codec;
1160

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

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

    
1314
    /* dump the file output parameters - cannot be done before in case
1315
       of stream copy */
1316
    for(i=0;i<nb_output_files;i++) {
1317
        dump_format(output_files[i], i, output_files[i]->filename, 1);
1318
    }
1319

    
1320
    /* dump the stream mapping */
1321
    fprintf(stderr, "Stream mapping:\n");
1322
    for(i=0;i<nb_ostreams;i++) {
1323
        ost = ost_table[i];
1324
        fprintf(stderr, "  Stream #%d.%d -> #%d.%d\n",
1325
                ist_table[ost->source_index]->file_index,
1326
                ist_table[ost->source_index]->index,
1327
                ost->file_index, 
1328
                ost->index);
1329
    }
1330

    
1331
    /* open each encoder */
1332
    for(i=0;i<nb_ostreams;i++) {
1333
        ost = ost_table[i];
1334
        if (ost->encoding_needed) {
1335
            AVCodec *codec;
1336
            codec = avcodec_find_encoder(ost->st->codec.codec_id);
1337
            if (!codec) {
1338
                fprintf(stderr, "Unsupported codec for output stream #%d.%d\n", 
1339
                        ost->file_index, ost->index);
1340
                exit(1);
1341
            }
1342
            if (avcodec_open(&ost->st->codec, codec) < 0) {
1343
                fprintf(stderr, "Error while opening codec for stream #%d.%d - maybe incorrect parameters such as bit_rate, rate, width or height\n", 
1344
                        ost->file_index, ost->index);
1345
                exit(1);
1346
            }
1347
        }
1348
    }
1349

    
1350
    /* open each decoder */
1351
    for(i=0;i<nb_istreams;i++) {
1352
        ist = ist_table[i];
1353
        if (ist->decoding_needed) {
1354
            AVCodec *codec;
1355
            codec = avcodec_find_decoder(ist->st->codec.codec_id);
1356
            if (!codec) {
1357
                fprintf(stderr, "Unsupported codec (id=%d) for input stream #%d.%d\n", 
1358
                        ist->st->codec.codec_id, ist->file_index, ist->index);
1359
                exit(1);
1360
            }
1361
            if (avcodec_open(&ist->st->codec, codec) < 0) {
1362
                fprintf(stderr, "Error while opening codec for input stream #%d.%d\n", 
1363
                        ist->file_index, ist->index);
1364
                exit(1);
1365
            }
1366
            //if (ist->st->codec.codec_type == CODEC_TYPE_VIDEO)
1367
            //    ist->st->codec.flags |= CODEC_FLAG_REPEAT_FIELD;
1368
        }
1369
    }
1370

    
1371
    /* init pts */
1372
    for(i=0;i<nb_istreams;i++) {
1373
        ist = ist_table[i];
1374
        is = input_files[ist->file_index];
1375
        ist->pts = 0;
1376
        ist->next_pts = 0;
1377
    }
1378
    
1379
    /* compute buffer size max (should use a complete heuristic) */
1380
    for(i=0;i<nb_input_files;i++) {
1381
        file_table[i].buffer_size_max = 2048;
1382
    }
1383

    
1384
    /* open files and write file headers */
1385
    for(i=0;i<nb_output_files;i++) {
1386
        os = output_files[i];
1387
        if (av_write_header(os) < 0) {
1388
            fprintf(stderr, "Could not write header for output file #%d (incorrect codec paramters ?)\n", i);
1389
            ret = -EINVAL;
1390
            goto fail;
1391
        }
1392
    }
1393

    
1394
#ifndef CONFIG_WIN32
1395
    if ( !using_stdin )
1396
        fprintf(stderr, "Press [q] to stop encoding\n");
1397
#endif
1398
    term_init();
1399

    
1400
    stream_no_data = 0;
1401
    key = -1;
1402

    
1403
    for(; received_sigterm == 0;) {
1404
        int file_index, ist_index;
1405
        AVPacket pkt;
1406
        double pts_min;
1407
        
1408
    redo:
1409
        /* if 'q' pressed, exits */
1410
        if (!using_stdin) {
1411
            /* read_key() returns 0 on EOF */
1412
            key = read_key();
1413
            if (key == 'q')
1414
                break;
1415
        }
1416

    
1417
        /* select the stream that we must read now by looking at the
1418
           smallest output pts */
1419
        file_index = -1;
1420
        pts_min = 1e10;
1421
        for(i=0;i<nb_ostreams;i++) {
1422
            double pts;
1423
            ost = ost_table[i];
1424
            os = output_files[ost->file_index];
1425
            ist = ist_table[ost->source_index];
1426
            pts = (double)ost->st->pts.val * os->pts_num / os->pts_den;
1427
            if (!file_table[ist->file_index].eof_reached && 
1428
                pts < pts_min) {
1429
                pts_min = pts;
1430
                file_index = ist->file_index;
1431
            }
1432
        }
1433
        /* if none, if is finished */
1434
        if (file_index < 0) {
1435
            break;
1436
        }
1437

    
1438
        /* finish if recording time exhausted */
1439
        if (recording_time > 0 && pts_min >= (recording_time / 1000000.0))
1440
            break;
1441

    
1442
        /* read a frame from it and output it in the fifo */
1443
        is = input_files[file_index];
1444
        if (av_read_frame(is, &pkt) < 0) {
1445
            file_table[file_index].eof_reached = 1;
1446
            continue;
1447
        }
1448
        if (!pkt.size) {
1449
            stream_no_data = is;
1450
        } else {
1451
            stream_no_data = 0;
1452
        }
1453
        if (do_pkt_dump) {
1454
            av_pkt_dump(stdout, &pkt, do_hex_dump);
1455
        }
1456
        /* the following test is needed in case new streams appear
1457
           dynamically in stream : we ignore them */
1458
        if (pkt.stream_index >= file_table[file_index].nb_streams)
1459
            goto discard_packet;
1460
        ist_index = file_table[file_index].ist_index + pkt.stream_index;
1461
        ist = ist_table[ist_index];
1462
        if (ist->discard)
1463
            goto discard_packet;
1464

    
1465
        //fprintf(stderr,"read #%d.%d size=%d\n", ist->file_index, ist->index, pkt.size);
1466
        if (output_packet(ist, ist_index, ost_table, nb_ostreams, &pkt) < 0) {
1467
            fprintf(stderr, "Error while decoding stream #%d.%d\n",
1468
                    ist->file_index, ist->index);
1469
            av_free_packet(&pkt);
1470
            goto redo;
1471
        }
1472
        
1473
    discard_packet:
1474
        av_free_packet(&pkt);
1475
        
1476
        /* dump report by using the output first video and audio streams */
1477
        print_report(output_files, ost_table, nb_ostreams, 0);
1478
    }
1479

    
1480
    /* at the end of stream, we must flush the decoder buffers */
1481
    for(i=0;i<nb_istreams;i++) {
1482
        ist = ist_table[i];
1483
        if (ist->decoding_needed) {
1484
            output_packet(ist, i, ost_table, nb_ostreams, NULL);
1485
        }
1486
    }
1487

    
1488
    term_exit();
1489

    
1490
    /* dump report by using the first video and audio streams */
1491
    print_report(output_files, ost_table, nb_ostreams, 1);
1492

    
1493
    /* close each encoder */
1494
    for(i=0;i<nb_ostreams;i++) {
1495
        ost = ost_table[i];
1496
        if (ost->encoding_needed) {
1497
            av_freep(&ost->st->codec.stats_in);
1498
            avcodec_close(&ost->st->codec);
1499
        }
1500
    }
1501
    
1502
    /* close each decoder */
1503
    for(i=0;i<nb_istreams;i++) {
1504
        ist = ist_table[i];
1505
        if (ist->decoding_needed) {
1506
            avcodec_close(&ist->st->codec);
1507
        }
1508
    }
1509
    
1510

    
1511
    /* write the trailer if needed and close file */
1512
    for(i=0;i<nb_output_files;i++) {
1513
        os = output_files[i];
1514
        av_write_trailer(os);
1515
    }
1516
    /* finished ! */
1517
    
1518
    ret = 0;
1519
 fail1:
1520
    av_free(file_table);
1521

    
1522
    if (ist_table) {
1523
        for(i=0;i<nb_istreams;i++) {
1524
            ist = ist_table[i];
1525
            av_free(ist);
1526
        }
1527
        av_free(ist_table);
1528
    }
1529
    if (ost_table) {
1530
        for(i=0;i<nb_ostreams;i++) {
1531
            ost = ost_table[i];
1532
            if (ost) {
1533
                if (ost->logfile) {
1534
                    fclose(ost->logfile);
1535
                    ost->logfile = NULL;
1536
                }
1537
                fifo_free(&ost->fifo); /* works even if fifo is not
1538
                                          initialized but set to zero */
1539
                av_free(ost->pict_tmp.data[0]);
1540
                if (ost->video_resample)
1541
                    img_resample_close(ost->img_resample_ctx);
1542
                if (ost->audio_resample)
1543
                    audio_resample_close(ost->resample);
1544
                av_free(ost);
1545
            }
1546
        }
1547
        av_free(ost_table);
1548
    }
1549
    return ret;
1550
 fail:
1551
    ret = -ENOMEM;
1552
    goto fail1;
1553
}
1554

    
1555
#if 0
1556
int file_read(const char *filename)
1557
{
1558
    URLContext *h;
1559
    unsigned char buffer[1024];
1560
    int len, i;
1561

1562
    if (url_open(&h, filename, O_RDONLY) < 0) {
1563
        printf("could not open '%s'\n", filename);
1564
        return -1;
1565
    }
1566
    for(;;) {
1567
        len = url_read(h, buffer, sizeof(buffer));
1568
        if (len <= 0)
1569
            break;
1570
        for(i=0;i<len;i++) putchar(buffer[i]);
1571
    }
1572
    url_close(h);
1573
    return 0;
1574
}
1575
#endif
1576

    
1577
static void opt_image_format(const char *arg)
1578
{
1579
    AVImageFormat *f;
1580
    
1581
    for(f = first_image_format; f != NULL; f = f->next) {
1582
        if (!strcmp(arg, f->name))
1583
            break;
1584
    }
1585
    if (!f) {
1586
        fprintf(stderr, "Unknown image format: '%s'\n", arg);
1587
        exit(1);
1588
    }
1589
    image_format = f;
1590
}
1591

    
1592
static void opt_format(const char *arg)
1593
{
1594
    /* compatibility stuff for pgmyuv */
1595
    if (!strcmp(arg, "pgmyuv")) {
1596
        opt_image_format(arg);
1597
        arg = "image";
1598
    }
1599

    
1600
    file_iformat = av_find_input_format(arg);
1601
    file_oformat = guess_format(arg, NULL, NULL);
1602
    if (!file_iformat && !file_oformat) {
1603
        fprintf(stderr, "Unknown input or output format: %s\n", arg);
1604
        exit(1);
1605
    }
1606
}
1607

    
1608
static void opt_video_bitrate(const char *arg)
1609
{
1610
    video_bit_rate = atoi(arg) * 1000;
1611
}
1612

    
1613
static void opt_video_bitrate_tolerance(const char *arg)
1614
{
1615
    video_bit_rate_tolerance = atoi(arg) * 1000;
1616
}
1617

    
1618
static void opt_video_bitrate_max(const char *arg)
1619
{
1620
    video_rc_max_rate = atoi(arg) * 1000;
1621
}
1622

    
1623
static void opt_video_bitrate_min(const char *arg)
1624
{
1625
    video_rc_min_rate = atoi(arg) * 1000;
1626
}
1627

    
1628
static void opt_video_buffer_size(const char *arg)
1629
{
1630
    video_rc_buffer_size = atoi(arg) * 1024;
1631
}
1632

    
1633
static void opt_video_rc_eq(char *arg)
1634
{
1635
    video_rc_eq = arg;
1636
}
1637

    
1638
static void opt_video_rc_override_string(char *arg)
1639
{
1640
    video_rc_override_string = arg;
1641
}
1642

    
1643

    
1644
static void opt_workaround_bugs(const char *arg)
1645
{
1646
    workaround_bugs = atoi(arg);
1647
}
1648

    
1649
static void opt_dct_algo(const char *arg)
1650
{
1651
    dct_algo = atoi(arg);
1652
}
1653

    
1654
static void opt_idct_algo(const char *arg)
1655
{
1656
    idct_algo = atoi(arg);
1657
}
1658

    
1659

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

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

    
1670
static void opt_debug(const char *arg)
1671
{
1672
    debug = atoi(arg);
1673
}
1674

    
1675
static void opt_verbose(const char *arg)
1676
{
1677
    verbose = atoi(arg);
1678
}
1679

    
1680
static void opt_frame_rate(const char *arg)
1681
{
1682
    if (parse_frame_rate(&frame_rate, &frame_rate_base, arg) < 0) {
1683
        fprintf(stderr, "Incorrect frame rate\n");
1684
        exit(1);
1685
    }
1686
}
1687

    
1688
static void opt_frame_crop_top(const char *arg)
1689
{
1690
    frame_topBand = atoi(arg); 
1691
    if (frame_topBand < 0) {
1692
        fprintf(stderr, "Incorrect top crop size\n");
1693
        exit(1);
1694
    }
1695
    if ((frame_topBand % 2) != 0) {
1696
        fprintf(stderr, "Top crop size must be a multiple of 2\n");
1697
        exit(1);
1698
    }
1699
    if ((frame_topBand) >= frame_height){
1700
            fprintf(stderr, "Vertical crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
1701
        exit(1);
1702
    }
1703
    frame_height -= frame_topBand;
1704
}
1705

    
1706
static void opt_frame_crop_bottom(const char *arg)
1707
{
1708
    frame_bottomBand = atoi(arg);
1709
    if (frame_bottomBand < 0) {
1710
        fprintf(stderr, "Incorrect bottom crop size\n");
1711
        exit(1);
1712
    }
1713
    if ((frame_bottomBand % 2) != 0) {
1714
        fprintf(stderr, "Bottom crop size must be a multiple of 2\n");
1715
        exit(1);        
1716
    }
1717
    if ((frame_bottomBand) >= 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_bottomBand;
1722
}
1723

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

    
1742
static void opt_frame_crop_right(const char *arg)
1743
{
1744
    frame_rightBand = atoi(arg);
1745
    if (frame_rightBand < 0) {
1746
        fprintf(stderr, "Incorrect right crop size\n");
1747
        exit(1);
1748
    }
1749
    if ((frame_rightBand % 2) != 0) {
1750
        fprintf(stderr, "Right crop size must be a multiple of 2\n");
1751
        exit(1);        
1752
    }
1753
    if ((frame_rightBand) >= 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_rightBand;
1758
}
1759

    
1760
static void opt_frame_size(const char *arg)
1761
{
1762
    if (parse_image_size(&frame_width, &frame_height, arg) < 0) {
1763
        fprintf(stderr, "Incorrect frame size\n");
1764
        exit(1);
1765
    }
1766
    if ((frame_width % 2) != 0 || (frame_height % 2) != 0) {
1767
        fprintf(stderr, "Frame size must be a multiple of 2\n");
1768
        exit(1);
1769
    }
1770
}
1771

    
1772
static void opt_frame_pix_fmt(const char *arg)
1773
{
1774
    frame_pix_fmt = avcodec_get_pix_fmt(arg);
1775
}
1776

    
1777
static void opt_frame_aspect_ratio(const char *arg)
1778
{
1779
    int x = 0, y = 0;
1780
    double ar = 0;
1781
    const char *p;
1782
    
1783
    p = strchr(arg, ':');
1784
    if (p) {
1785
        x = strtol(arg, (char **)&arg, 10);
1786
        if (arg == p)
1787
            y = strtol(arg+1, (char **)&arg, 10);
1788
        if (x > 0 && y > 0)
1789
            ar = (double)x / (double)y;
1790
    } else
1791
        ar = strtod(arg, (char **)&arg);
1792

    
1793
    if (!ar) {
1794
        fprintf(stderr, "Incorrect aspect ratio specification.\n");
1795
        exit(1);
1796
    }
1797
    frame_aspect_ratio = ar;
1798
}
1799

    
1800
static void opt_gop_size(const char *arg)
1801
{
1802
    gop_size = atoi(arg);
1803
}
1804

    
1805
static void opt_b_frames(const char *arg)
1806
{
1807
    b_frames = atoi(arg);
1808
    if (b_frames > FF_MAX_B_FRAMES) {
1809
        fprintf(stderr, "\nCannot have more than %d B frames, increase FF_MAX_B_FRAMES.\n", FF_MAX_B_FRAMES);
1810
        exit(1);
1811
    } else if (b_frames < 1) {
1812
        fprintf(stderr, "\nNumber of B frames must be higher than 0\n");
1813
        exit(1);
1814
    }
1815
}
1816

    
1817
static void opt_mb_decision(const char *arg)
1818
{
1819
    mb_decision = atoi(arg);
1820
}
1821

    
1822
static void opt_mb_cmp(const char *arg)
1823
{
1824
    mb_cmp = atoi(arg);
1825
}
1826

    
1827
static void opt_sub_cmp(const char *arg)
1828
{
1829
    sub_cmp = atoi(arg);
1830
}
1831

    
1832
static void opt_cmp(const char *arg)
1833
{
1834
    cmp = atoi(arg);
1835
}
1836

    
1837
static void opt_qscale(const char *arg)
1838
{
1839
    video_qscale = atof(arg);
1840
    if (video_qscale < 0.01 ||
1841
        video_qscale > 255) {
1842
        fprintf(stderr, "qscale must be >= 0.01 and <= 255\n");
1843
        exit(1);
1844
    }
1845
}
1846

    
1847
static void opt_qmin(const char *arg)
1848
{
1849
    video_qmin = atoi(arg);
1850
    if (video_qmin < 0 ||
1851
        video_qmin > 31) {
1852
        fprintf(stderr, "qmin must be >= 1 and <= 31\n");
1853
        exit(1);
1854
    }
1855
}
1856

    
1857
static void opt_qmax(const char *arg)
1858
{
1859
    video_qmax = atoi(arg);
1860
    if (video_qmax < 0 ||
1861
        video_qmax > 31) {
1862
        fprintf(stderr, "qmax must be >= 1 and <= 31\n");
1863
        exit(1);
1864
    }
1865
}
1866

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

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

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

    
1897
static void opt_qblur(const char *arg)
1898
{
1899
    video_qblur = atof(arg);
1900
}
1901

    
1902
static void opt_qcomp(const char *arg)
1903
{
1904
    video_qcomp = atof(arg);
1905
}
1906

    
1907
static void opt_rc_initial_cplx(const char *arg)
1908
{
1909
    video_rc_initial_cplx = atof(arg);
1910
}
1911
static void opt_b_qfactor(const char *arg)
1912
{
1913
    video_b_qfactor = atof(arg);
1914
}
1915
static void opt_i_qfactor(const char *arg)
1916
{
1917
    video_i_qfactor = atof(arg);
1918
}
1919
static void opt_b_qoffset(const char *arg)
1920
{
1921
    video_b_qoffset = atof(arg);
1922
}
1923
static void opt_i_qoffset(const char *arg)
1924
{
1925
    video_i_qoffset = atof(arg);
1926
}
1927

    
1928
static void opt_packet_size(const char *arg)
1929
{
1930
    packet_size= atoi(arg);
1931
}
1932

    
1933
static void opt_error_rate(const char *arg)
1934
{
1935
    error_rate= atoi(arg);
1936
}
1937

    
1938
static void opt_strict(const char *arg)
1939
{
1940
    strict= atoi(arg);
1941
}
1942

    
1943
static void opt_audio_bitrate(const char *arg)
1944
{
1945
    audio_bit_rate = atoi(arg) * 1000;
1946
}
1947

    
1948
static void opt_audio_rate(const char *arg)
1949
{
1950
    audio_sample_rate = atoi(arg);
1951
}
1952

    
1953
static void opt_audio_channels(const char *arg)
1954
{
1955
    audio_channels = atoi(arg);
1956
}
1957

    
1958
static void opt_video_device(const char *arg)
1959
{
1960
    video_device = av_strdup(arg);
1961
}
1962

    
1963
static void opt_video_channel(const char *arg)
1964
{
1965
    video_channel = strtol(arg, NULL, 0);
1966
}
1967

    
1968
static void opt_video_standard(const char *arg)
1969
{
1970
    video_standard = av_strdup(arg);
1971
}
1972

    
1973
static void opt_audio_device(const char *arg)
1974
{
1975
    audio_device = av_strdup(arg);
1976
}
1977

    
1978
static void opt_dv1394(const char *arg)
1979
{
1980
    video_grab_format = "dv1394";
1981
    audio_grab_format = NULL;
1982
}
1983

    
1984
static void opt_audio_codec(const char *arg)
1985
{
1986
    AVCodec *p;
1987

    
1988
    if (!strcmp(arg, "copy")) {
1989
        audio_stream_copy = 1;
1990
    } else {
1991
        p = first_avcodec;
1992
        while (p) {
1993
            if (!strcmp(p->name, arg) && p->type == CODEC_TYPE_AUDIO)
1994
                break;
1995
            p = p->next;
1996
        }
1997
        if (p == NULL) {
1998
            fprintf(stderr, "Unknown audio codec '%s'\n", arg);
1999
            exit(1);
2000
        } else {
2001
            audio_codec_id = p->id;
2002
        }
2003
    }
2004
}
2005

    
2006
static void add_frame_hooker(const char *arg)
2007
{
2008
    int argc = 0;
2009
    char *argv[64];
2010
    int i;
2011
    char *args = av_strdup(arg);
2012

    
2013
    using_vhook = 1;
2014

    
2015
    argv[0] = strtok(args, " ");
2016
    while (argc < 62 && (argv[++argc] = strtok(NULL, " "))) {
2017
    }
2018

    
2019
    i = frame_hook_add(argc, argv);
2020

    
2021
    if (i != 0) {
2022
        fprintf(stderr, "Failed to add video hook function: %s\n", arg);
2023
        exit(1);
2024
    }
2025
}
2026

    
2027
const char *motion_str[] = {
2028
    "zero",
2029
    "full",
2030
    "log",
2031
    "phods",
2032
    "epzs",
2033
    "x1",
2034
    NULL,
2035
};
2036

    
2037
static void opt_motion_estimation(const char *arg)
2038
{
2039
    const char **p;
2040
    p = motion_str;
2041
    for(;;) {
2042
        if (!*p) {
2043
            fprintf(stderr, "Unknown motion estimation method '%s'\n", arg);
2044
            exit(1);
2045
        }
2046
        if (!strcmp(*p, arg))
2047
            break;
2048
        p++;
2049
    }
2050
    me_method = (p - motion_str) + 1;
2051
}
2052

    
2053
static void opt_video_codec(const char *arg)
2054
{
2055
    AVCodec *p;
2056

    
2057
    if (!strcmp(arg, "copy")) {
2058
        video_stream_copy = 1;
2059
    } else {
2060
        p = first_avcodec;
2061
        while (p) {
2062
            if (!strcmp(p->name, arg) && p->type == CODEC_TYPE_VIDEO)
2063
                break;
2064
            p = p->next;
2065
        }
2066
        if (p == NULL) {
2067
            fprintf(stderr, "Unknown video codec '%s'\n", arg);
2068
            exit(1);
2069
        } else {
2070
            video_codec_id = p->id;
2071
        }
2072
    }
2073
}
2074

    
2075
static void opt_map(const char *arg)
2076
{
2077
    AVStreamMap *m;
2078
    const char *p;
2079

    
2080
    p = arg;
2081
    m = &stream_maps[nb_stream_maps++];
2082

    
2083
    m->file_index = strtol(arg, (char **)&p, 0);
2084
    if (*p)
2085
        p++;
2086

    
2087
    m->stream_index = strtol(p, (char **)&p, 0);
2088
}
2089

    
2090
static void opt_recording_time(const char *arg)
2091
{
2092
    recording_time = parse_date(arg, 1);
2093
}
2094

    
2095
static void opt_start_time(const char *arg)
2096
{
2097
    start_time = parse_date(arg, 1);
2098
}
2099

    
2100
static void opt_input_file(const char *filename)
2101
{
2102
    AVFormatContext *ic;
2103
    AVFormatParameters params, *ap = &params;
2104
    int err, i, ret, rfps, rfps_base;
2105

    
2106
    if (!strcmp(filename, "-"))
2107
        filename = "pipe:";
2108

    
2109
    using_stdin |= !strcmp(filename, "pipe:" ) || 
2110
                   !strcmp( filename, "/dev/stdin" );
2111

    
2112
    /* get default parameters from command line */
2113
    memset(ap, 0, sizeof(*ap));
2114
    ap->sample_rate = audio_sample_rate;
2115
    ap->channels = audio_channels;
2116
    ap->frame_rate = frame_rate;
2117
    ap->frame_rate_base = frame_rate_base;
2118
    ap->width = frame_width;
2119
    ap->height = frame_height;
2120
    ap->image_format = image_format;
2121
    ap->pix_fmt = frame_pix_fmt;
2122

    
2123
    /* open the input file with generic libav function */
2124
    err = av_open_input_file(&ic, filename, file_iformat, 0, ap);
2125
    if (err < 0) {
2126
        print_error(filename, err);
2127
        exit(1);
2128
    }
2129
    
2130
    /* If not enough info to get the stream parameters, we decode the
2131
       first frames to get it. (used in mpeg case for example) */
2132
    ret = av_find_stream_info(ic);
2133
    if (ret < 0) {
2134
        fprintf(stderr, "%s: could not find codec parameters\n", filename);
2135
        exit(1);
2136
    }
2137

    
2138
    /* if seeking requested, we execute it */
2139
    if (start_time != 0) {
2140
        int64_t timestamp;
2141

    
2142
        timestamp = start_time;
2143
        /* add the stream start time */
2144
        if (ic->start_time != AV_NOPTS_VALUE)
2145
            timestamp += ic->start_time;
2146
        ret = av_seek_frame(ic, -1, timestamp);
2147
        if (ret < 0) {
2148
            fprintf(stderr, "%s: could not seek to position %0.3f\n", 
2149
                    filename, (double)timestamp / AV_TIME_BASE);
2150
        }
2151
        /* reset seek info */
2152
        start_time = 0;
2153
    }
2154

    
2155
    /* update the current parameters so that they match the one of the input stream */
2156
    for(i=0;i<ic->nb_streams;i++) {
2157
        AVCodecContext *enc = &ic->streams[i]->codec;
2158
        switch(enc->codec_type) {
2159
        case CODEC_TYPE_AUDIO:
2160
            //fprintf(stderr, "\nInput Audio channels: %d", enc->channels);
2161
            audio_channels = enc->channels;
2162
            audio_sample_rate = enc->sample_rate;
2163
            break;
2164
        case CODEC_TYPE_VIDEO:
2165
            frame_height = enc->height;
2166
            frame_width = enc->width;
2167
            frame_aspect_ratio = av_q2d(enc->sample_aspect_ratio) * enc->width / enc->height;
2168
            frame_pix_fmt = enc->pix_fmt;
2169
            rfps      = ic->streams[i]->r_frame_rate;
2170
            rfps_base = ic->streams[i]->r_frame_rate_base;
2171
            enc->workaround_bugs = workaround_bugs;
2172
            enc->error_resilience = error_resilience; 
2173
            enc->error_concealment = error_concealment; 
2174
            enc->idct_algo= idct_algo;
2175
            enc->debug= debug;
2176
            if(bitexact)
2177
                enc->flags|= CODEC_FLAG_BITEXACT;
2178

    
2179
            assert(enc->frame_rate_base == rfps_base); // should be true for now
2180
            if (enc->frame_rate != rfps) { 
2181
                fprintf(stderr,"\nSeems that stream %d comes from film source: %2.2f->%2.2f\n",
2182
                    i, (float)enc->frame_rate / enc->frame_rate_base,
2183
                    (float)rfps / rfps_base);
2184
            }
2185
            /* update the current frame rate to match the stream frame rate */
2186
            frame_rate      = rfps;
2187
            frame_rate_base = rfps_base;
2188

    
2189
            enc->rate_emu = rate_emu;
2190
            break;
2191
        case CODEC_TYPE_DATA:
2192
            break;
2193
        default:
2194
            av_abort();
2195
        }
2196
    }
2197
    
2198
    input_files[nb_input_files] = ic;
2199
    /* dump the file content */
2200
    dump_format(ic, nb_input_files, filename, 0);
2201
    nb_input_files++;
2202
    file_iformat = NULL;
2203
    file_oformat = NULL;
2204
    image_format = NULL;
2205

    
2206
    rate_emu = 0;
2207
}
2208

    
2209
static void check_audio_video_inputs(int *has_video_ptr, int *has_audio_ptr)
2210
{
2211
    int has_video, has_audio, i, j;
2212
    AVFormatContext *ic;
2213

    
2214
    has_video = 0;
2215
    has_audio = 0;
2216
    for(j=0;j<nb_input_files;j++) {
2217
        ic = input_files[j];
2218
        for(i=0;i<ic->nb_streams;i++) {
2219
            AVCodecContext *enc = &ic->streams[i]->codec;
2220
            switch(enc->codec_type) {
2221
            case CODEC_TYPE_AUDIO:
2222
                has_audio = 1;
2223
                break;
2224
            case CODEC_TYPE_VIDEO:
2225
                has_video = 1;
2226
                break;
2227
            default:
2228
                av_abort();
2229
            }
2230
        }
2231
    }
2232
    *has_video_ptr = has_video;
2233
    *has_audio_ptr = has_audio;
2234
}
2235

    
2236
static void opt_output_file(const char *filename)
2237
{
2238
    AVStream *st;
2239
    AVFormatContext *oc;
2240
    int use_video, use_audio, nb_streams, input_has_video, input_has_audio;
2241
    int codec_id;
2242
    AVFormatParameters params, *ap = &params;
2243

    
2244
    if (!strcmp(filename, "-"))
2245
        filename = "pipe:";
2246

    
2247
    oc = av_mallocz(sizeof(AVFormatContext));
2248

    
2249
    if (!file_oformat) {
2250
        file_oformat = guess_format(NULL, filename, NULL);
2251
        if (!file_oformat) {
2252
            fprintf(stderr, "Unable for find a suitable output format for '%s'\n",
2253
                    filename);
2254
            exit(1);
2255
        }
2256
    }
2257
    
2258
    oc->oformat = file_oformat;
2259

    
2260
    if (!strcmp(file_oformat->name, "ffm") && 
2261
        strstart(filename, "http:", NULL)) {
2262
        /* special case for files sent to ffserver: we get the stream
2263
           parameters from ffserver */
2264
        if (read_ffserver_streams(oc, filename) < 0) {
2265
            fprintf(stderr, "Could not read stream parameters from '%s'\n", filename);
2266
            exit(1);
2267
        }
2268
    } else {
2269
        use_video = file_oformat->video_codec != CODEC_ID_NONE;
2270
        use_audio = file_oformat->audio_codec != CODEC_ID_NONE;
2271

    
2272
        /* disable if no corresponding type found and at least one
2273
           input file */
2274
        if (nb_input_files > 0) {
2275
            check_audio_video_inputs(&input_has_video, &input_has_audio);
2276
            if (!input_has_video)
2277
                use_video = 0;
2278
            if (!input_has_audio)
2279
                use_audio = 0;
2280
        }
2281

    
2282
        /* manual disable */
2283
        if (audio_disable) {
2284
            use_audio = 0;
2285
        }
2286
        if (video_disable) {
2287
            use_video = 0;
2288
        }
2289
        
2290
        nb_streams = 0;
2291
        if (use_video) {
2292
            AVCodecContext *video_enc;
2293
            
2294
            st = av_mallocz(sizeof(AVStream));
2295
            if (!st) {
2296
                fprintf(stderr, "Could not alloc stream\n");
2297
                exit(1);
2298
            }
2299
            avcodec_get_context_defaults(&st->codec);
2300

    
2301
            video_enc = &st->codec;
2302
            
2303
            if(!strcmp(file_oformat->name, "mp4") || !strcmp(file_oformat->name, "mov") || !strcmp(file_oformat->name, "3gp"))
2304
                video_enc->flags |= CODEC_FLAG_GLOBAL_HEADER;
2305
            if (video_stream_copy) {
2306
                st->stream_copy = 1;
2307
                video_enc->codec_type = CODEC_TYPE_VIDEO;
2308
            } else {
2309
                char *p;
2310
                int i;
2311
            
2312
                codec_id = file_oformat->video_codec;
2313
                if (video_codec_id != CODEC_ID_NONE)
2314
                    codec_id = video_codec_id;
2315
                
2316
                video_enc->codec_id = codec_id;
2317
                
2318
                video_enc->bit_rate = video_bit_rate;
2319
                video_enc->bit_rate_tolerance = video_bit_rate_tolerance;
2320
                video_enc->frame_rate = frame_rate; 
2321
                video_enc->frame_rate_base = frame_rate_base; 
2322
                
2323
                video_enc->width = frame_width;
2324
                video_enc->height = frame_height;
2325
                video_enc->sample_aspect_ratio = av_d2q(frame_aspect_ratio*frame_height/frame_width, 255);
2326
                video_enc->pix_fmt = frame_pix_fmt;
2327

    
2328
                if (!intra_only)
2329
                    video_enc->gop_size = gop_size;
2330
                else
2331
                    video_enc->gop_size = 0;
2332
                if (video_qscale || same_quality) {
2333
                    video_enc->flags |= CODEC_FLAG_QSCALE;
2334
                    st->quality = FF_QP2LAMBDA * video_qscale;
2335
                }
2336

    
2337
                if(intra_matrix)
2338
                    video_enc->intra_matrix = intra_matrix;
2339
                if(inter_matrix)
2340
                    video_enc->inter_matrix = inter_matrix;
2341

    
2342
                if(bitexact)
2343
                    video_enc->flags |= CODEC_FLAG_BITEXACT;
2344

    
2345
                video_enc->mb_decision = mb_decision;
2346
                video_enc->mb_cmp = mb_cmp;
2347
                video_enc->me_sub_cmp = sub_cmp;
2348
                video_enc->me_cmp = cmp;
2349
                
2350
                if (use_umv) {
2351
                    video_enc->flags |= CODEC_FLAG_H263P_UMV;
2352
                }
2353
                   if (use_aic) {
2354
                    video_enc->flags |= CODEC_FLAG_H263P_AIC;
2355
                }
2356
                   if (use_aiv) {
2357
                    video_enc->flags |= CODEC_FLAG_H263P_AIV;
2358
                }
2359
                if (use_4mv) {
2360
                    video_enc->flags |= CODEC_FLAG_4MV;
2361
                }
2362
                if (use_obmc) {
2363
                    video_enc->flags |= CODEC_FLAG_OBMC;
2364
                }
2365
            
2366
                if(use_part) {
2367
                    video_enc->flags |= CODEC_FLAG_PART;
2368
                }
2369
                if (b_frames) {
2370
                    video_enc->max_b_frames = b_frames;
2371
                    video_enc->b_frame_strategy = 0;
2372
                    video_enc->b_quant_factor = 2.0;
2373
                }
2374
                if (do_interlace) {
2375
                    video_enc->flags |= CODEC_FLAG_INTERLACED_DCT;
2376
                }
2377
                video_enc->qmin = video_qmin;
2378
                video_enc->qmax = video_qmax;
2379
                video_enc->mb_qmin = video_mb_qmin;
2380
                video_enc->mb_qmax = video_mb_qmax;
2381
                video_enc->max_qdiff = video_qdiff;
2382
                video_enc->qblur = video_qblur;
2383
                video_enc->qcompress = video_qcomp;
2384
                video_enc->rc_eq = video_rc_eq;
2385
                video_enc->debug= debug;
2386
                
2387
                p= video_rc_override_string;
2388
                for(i=0; p; i++){
2389
                    int start, end, q;
2390
                    int e=sscanf(p, "%d,%d,%d", &start, &end, &q);
2391
                    if(e!=3){
2392
                        fprintf(stderr, "error parsing rc_override\n");
2393
                        exit(1);
2394
                    }
2395
                    video_enc->rc_override= 
2396
                        av_realloc(video_enc->rc_override, 
2397
                                   sizeof(RcOverride)*(i+1));
2398
                    video_enc->rc_override[i].start_frame= start;
2399
                    video_enc->rc_override[i].end_frame  = end;
2400
                    if(q>0){
2401
                        video_enc->rc_override[i].qscale= q;
2402
                        video_enc->rc_override[i].quality_factor= 1.0;
2403
                    }
2404
                    else{
2405
                        video_enc->rc_override[i].qscale= 0;
2406
                        video_enc->rc_override[i].quality_factor= -q/100.0;
2407
                    }
2408
                    p= strchr(p, '/');
2409
                    if(p) p++;
2410
                }
2411
                video_enc->rc_override_count=i;
2412

    
2413
                video_enc->rc_max_rate = video_rc_max_rate;
2414
                video_enc->rc_min_rate = video_rc_min_rate;
2415
                video_enc->rc_buffer_size = video_rc_buffer_size;
2416
                video_enc->rc_buffer_aggressivity= video_rc_buffer_aggressivity;
2417
                video_enc->rc_initial_cplx= video_rc_initial_cplx;
2418
                video_enc->i_quant_factor = video_i_qfactor;
2419
                video_enc->b_quant_factor = video_b_qfactor;
2420
                video_enc->i_quant_offset = video_i_qoffset;
2421
                video_enc->b_quant_offset = video_b_qoffset;
2422
                video_enc->dct_algo = dct_algo;
2423
                video_enc->idct_algo = idct_algo;
2424
                video_enc->strict_std_compliance = strict;
2425
                video_enc->error_rate = error_rate;
2426
                if(packet_size){
2427
                    video_enc->rtp_mode= 1;
2428
                    video_enc->rtp_payload_size= packet_size;
2429
                }
2430
            
2431
                if (do_psnr)
2432
                    video_enc->flags|= CODEC_FLAG_PSNR;
2433
            
2434
                video_enc->me_method = me_method;
2435

    
2436
                /* two pass mode */
2437
                if (do_pass) {
2438
                    if (do_pass == 1) {
2439
                        video_enc->flags |= CODEC_FLAG_PASS1;
2440
                    } else {
2441
                        video_enc->flags |= CODEC_FLAG_PASS2;
2442
                    }
2443
                }
2444
            }
2445
            oc->streams[nb_streams] = st;
2446
            nb_streams++;
2447
        }
2448
    
2449
        if (use_audio) {
2450
            AVCodecContext *audio_enc;
2451

    
2452
            st = av_mallocz(sizeof(AVStream));
2453
            if (!st) {
2454
                fprintf(stderr, "Could not alloc stream\n");
2455
                exit(1);
2456
            }
2457
            avcodec_get_context_defaults(&st->codec);
2458

    
2459
            audio_enc = &st->codec;
2460
            audio_enc->codec_type = CODEC_TYPE_AUDIO;
2461

    
2462
            if(!strcmp(file_oformat->name, "mp4") || !strcmp(file_oformat->name, "mov") || !strcmp(file_oformat->name, "3gp"))
2463
                audio_enc->flags |= CODEC_FLAG_GLOBAL_HEADER;
2464
            if (audio_stream_copy) {
2465
                st->stream_copy = 1;
2466
            } else {
2467
                codec_id = file_oformat->audio_codec;
2468
                if (audio_codec_id != CODEC_ID_NONE)
2469
                    codec_id = audio_codec_id;
2470
                audio_enc->codec_id = codec_id;
2471
                
2472
                audio_enc->bit_rate = audio_bit_rate;
2473
                audio_enc->sample_rate = audio_sample_rate;
2474
                /* For audio codecs other than AC3 we limit */
2475
                /* the number of coded channels to stereo   */
2476
                if (audio_channels > 2 && codec_id != CODEC_ID_AC3) {
2477
                    audio_enc->channels = 2;
2478
                } else
2479
                    audio_enc->channels = audio_channels;
2480
            }
2481
            oc->streams[nb_streams] = st;
2482
            nb_streams++;
2483
        }
2484

    
2485
        oc->nb_streams = nb_streams;
2486

    
2487
        if (!nb_streams) {
2488
            fprintf(stderr, "No audio or video streams available\n");
2489
            exit(1);
2490
        }
2491

    
2492
        if (str_title)
2493
            pstrcpy(oc->title, sizeof(oc->title), str_title);
2494
        if (str_author)
2495
            pstrcpy(oc->author, sizeof(oc->author), str_author);
2496
        if (str_copyright)
2497
            pstrcpy(oc->copyright, sizeof(oc->copyright), str_copyright);
2498
        if (str_comment)
2499
            pstrcpy(oc->comment, sizeof(oc->comment), str_comment);
2500
    }
2501

    
2502
    output_files[nb_output_files++] = oc;
2503

    
2504
    strcpy(oc->filename, filename);
2505

    
2506
    /* check filename in case of an image number is expected */
2507
    if (oc->oformat->flags & AVFMT_NEEDNUMBER) {
2508
        if (filename_number_test(oc->filename) < 0) {
2509
            print_error(oc->filename, AVERROR_NUMEXPECTED);
2510
            exit(1);
2511
        }
2512
    }
2513

    
2514
    if (!(oc->oformat->flags & AVFMT_NOFILE)) {
2515
        /* test if it already exists to avoid loosing precious files */
2516
        if (!file_overwrite && 
2517
            (strchr(filename, ':') == NULL ||
2518
             strstart(filename, "file:", NULL))) {
2519
            if (url_exist(filename)) {
2520
                int c;
2521
                
2522
                if ( !using_stdin ) {
2523
                    fprintf(stderr,"File '%s' already exists. Overwrite ? [y/N] ", filename);
2524
                    fflush(stderr);
2525
                    c = getchar();
2526
                    if (toupper(c) != 'Y') {
2527
                        fprintf(stderr, "Not overwriting - exiting\n");
2528
                        exit(1);
2529
                    }
2530
                                }
2531
                                else {
2532
                    fprintf(stderr,"File '%s' already exists. Exiting.\n", filename);
2533
                    exit(1);
2534
                                }
2535
            }
2536
        }
2537
        
2538
        /* open the file */
2539
        if (url_fopen(&oc->pb, filename, URL_WRONLY) < 0) {
2540
            fprintf(stderr, "Could not open '%s'\n", filename);
2541
            exit(1);
2542
        }
2543
    }
2544

    
2545
    memset(ap, 0, sizeof(*ap));
2546
    ap->image_format = image_format;
2547
    if (av_set_parameters(oc, ap) < 0) {
2548
        fprintf(stderr, "%s: Invalid encoding parameters\n",
2549
                oc->filename);
2550
        exit(1);
2551
    }
2552

    
2553
    /* reset some options */
2554
    file_oformat = NULL;
2555
    file_iformat = NULL;
2556
    image_format = NULL;
2557
    audio_disable = 0;
2558
    video_disable = 0;
2559
    audio_codec_id = CODEC_ID_NONE;
2560
    video_codec_id = CODEC_ID_NONE;
2561
    audio_stream_copy = 0;
2562
    video_stream_copy = 0;
2563
}
2564

    
2565
/* prepare dummy protocols for grab */
2566
static void prepare_grab(void)
2567
{
2568
    int has_video, has_audio, i, j;
2569
    AVFormatContext *oc;
2570
    AVFormatContext *ic;
2571
    AVFormatParameters vp1, *vp = &vp1;
2572
    AVFormatParameters ap1, *ap = &ap1;
2573
    
2574
    /* see if audio/video inputs are needed */
2575
    has_video = 0;
2576
    has_audio = 0;
2577
    memset(ap, 0, sizeof(*ap));
2578
    memset(vp, 0, sizeof(*vp));
2579
    for(j=0;j<nb_output_files;j++) {
2580
        oc = output_files[j];
2581
        for(i=0;i<oc->nb_streams;i++) {
2582
            AVCodecContext *enc = &oc->streams[i]->codec;
2583
            switch(enc->codec_type) {
2584
            case CODEC_TYPE_AUDIO:
2585
                if (enc->sample_rate > ap->sample_rate)
2586
                    ap->sample_rate = enc->sample_rate;
2587
                if (enc->channels > ap->channels)
2588
                    ap->channels = enc->channels;
2589
                has_audio = 1;
2590
                break;
2591
            case CODEC_TYPE_VIDEO:
2592
                if (enc->width > vp->width)
2593
                    vp->width = enc->width;
2594
                if (enc->height > vp->height)
2595
                    vp->height = enc->height;
2596
                
2597
                assert(enc->frame_rate_base == DEFAULT_FRAME_RATE_BASE);
2598
                if (enc->frame_rate > vp->frame_rate){
2599
                    vp->frame_rate      = enc->frame_rate;
2600
                    vp->frame_rate_base = enc->frame_rate_base;
2601
                }
2602
                has_video = 1;
2603
                break;
2604
            default:
2605
                av_abort();
2606
            }
2607
        }
2608
    }
2609
    
2610
    if (has_video == 0 && has_audio == 0) {
2611
        fprintf(stderr, "Output file must have at least one audio or video stream\n");
2612
        exit(1);
2613
    }
2614
    
2615
    if (has_video) {
2616
        AVInputFormat *fmt1;
2617
        fmt1 = av_find_input_format(video_grab_format);
2618
        vp->device  = video_device;
2619
        vp->channel = video_channel;
2620
        vp->standard = video_standard;
2621
        if (av_open_input_file(&ic, "", fmt1, 0, vp) < 0) {
2622
            fprintf(stderr, "Could not find video grab device\n");
2623
            exit(1);
2624
        }
2625
        /* If not enough info to get the stream parameters, we decode the
2626
           first frames to get it. */
2627
        if ((ic->ctx_flags & AVFMTCTX_NOHEADER) && av_find_stream_info(ic) < 0) {
2628
            fprintf(stderr, "Could not find video grab parameters\n");
2629
            exit(1);
2630
        }
2631
        /* by now video grab has one stream */
2632
        ic->streams[0]->r_frame_rate      = vp->frame_rate;
2633
        ic->streams[0]->r_frame_rate_base = vp->frame_rate_base;
2634
        input_files[nb_input_files] = ic;
2635
        dump_format(ic, nb_input_files, "", 0);
2636
        nb_input_files++;
2637
    }
2638
    if (has_audio && audio_grab_format) {
2639
        AVInputFormat *fmt1;
2640
        fmt1 = av_find_input_format(audio_grab_format);
2641
        ap->device = audio_device;
2642
        if (av_open_input_file(&ic, "", fmt1, 0, ap) < 0) {
2643
            fprintf(stderr, "Could not find audio grab device\n");
2644
            exit(1);
2645
        }
2646
        input_files[nb_input_files] = ic;
2647
        dump_format(ic, nb_input_files, "", 0);
2648
        nb_input_files++;
2649
    }
2650
}
2651

    
2652
/* same option as mencoder */
2653
static void opt_pass(const char *pass_str)
2654
{
2655
    int pass;
2656
    pass = atoi(pass_str);
2657
    if (pass != 1 && pass != 2) {
2658
        fprintf(stderr, "pass number can be only 1 or 2\n");
2659
        exit(1);
2660
    }
2661
    do_pass = pass;
2662
}
2663

    
2664
#if defined(CONFIG_WIN32) || defined(CONFIG_OS2)
2665
static int64_t getutime(void)
2666
{
2667
  return av_gettime();
2668
}
2669
#else
2670
static int64_t getutime(void)
2671
{
2672
    struct rusage rusage;
2673

    
2674
    getrusage(RUSAGE_SELF, &rusage);
2675
    return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
2676
}
2677
#endif
2678

    
2679
extern int ffm_nopts;
2680

    
2681
static void opt_bitexact(void)
2682
{
2683
    bitexact=1;
2684
    /* disable generate of real time pts in ffm (need to be supressed anyway) */
2685
    ffm_nopts = 1;
2686
}
2687

    
2688
static void show_formats(void)
2689
{
2690
    AVInputFormat *ifmt;
2691
    AVOutputFormat *ofmt;
2692
    AVImageFormat *image_fmt;
2693
    URLProtocol *up;
2694
    AVCodec *p;
2695
    const char **pp;
2696

    
2697
    printf("Output audio/video file formats:");
2698
    for(ofmt = first_oformat; ofmt != NULL; ofmt = ofmt->next) {
2699
        printf(" %s", ofmt->name);
2700
    }
2701
    printf("\n");
2702

    
2703
    printf("Input audio/video file formats:");
2704
    for(ifmt = first_iformat; ifmt != NULL; ifmt = ifmt->next) {
2705
        printf(" %s", ifmt->name);
2706
    }
2707
    printf("\n");
2708

    
2709
    printf("Output image formats:");
2710
    for(image_fmt = first_image_format; image_fmt != NULL; 
2711
        image_fmt = image_fmt->next) {
2712
        if (image_fmt->img_write)
2713
            printf(" %s", image_fmt->name);
2714
    }
2715
    printf("\n");
2716

    
2717
    printf("Input image formats:");
2718
    for(image_fmt = first_image_format; image_fmt != NULL; 
2719
        image_fmt = image_fmt->next) {
2720
        if (image_fmt->img_read)
2721
            printf(" %s", image_fmt->name);
2722
    }
2723
    printf("\n");
2724

    
2725
    printf("Codecs:\n");
2726
    printf("  Encoders:");
2727
    for(p = first_avcodec; p != NULL; p = p->next) {
2728
        if (p->encode)
2729
            printf(" %s", p->name);
2730
    }
2731
    printf("\n");
2732

    
2733
    printf("  Decoders:");
2734
    for(p = first_avcodec; p != NULL; p = p->next) {
2735
        if (p->decode)
2736
            printf(" %s", p->name);
2737
    }
2738
    printf("\n");
2739

    
2740
    printf("Supported file protocols:");
2741
    for(up = first_protocol; up != NULL; up = up->next)
2742
        printf(" %s:", up->name);
2743
    printf("\n");
2744
    
2745
    printf("Frame size, frame rate abbreviations: ntsc pal qntsc qpal sntsc spal film ntsc-film sqcif qcif cif 4cif\n");
2746
    printf("Motion estimation methods:");
2747
    pp = motion_str;
2748
    while (*pp) {
2749
        printf(" %s", *pp);
2750
        if ((pp - motion_str + 1) == ME_ZERO) 
2751
            printf("(fastest)");
2752
        else if ((pp - motion_str + 1) == ME_FULL) 
2753
            printf("(slowest)");
2754
        else if ((pp - motion_str + 1) == ME_EPZS) 
2755
            printf("(default)");
2756
        pp++;
2757
    }
2758
    printf("\n");
2759
    exit(1);
2760
}
2761

    
2762
void parse_matrix_coeffs(uint16_t *dest, const char *str)
2763
{
2764
    int i;
2765
    const char *p = str;
2766
    for(i = 0;; i++) {
2767
        dest[i] = atoi(p);
2768
        if(i == 63)
2769
            break;
2770
        p = strchr(p, ',');
2771
        if(!p) {
2772
            fprintf(stderr, "Syntax error in matrix \"%s\" at coeff %d\n", str, i);
2773
            exit(1);
2774
        }
2775
        p++;
2776
    }
2777
}
2778

    
2779
void opt_inter_matrix(const char *arg)
2780
{
2781
    inter_matrix = av_mallocz(sizeof(uint16_t) * 64);
2782
    parse_matrix_coeffs(inter_matrix, arg);
2783
}
2784

    
2785
void opt_intra_matrix(const char *arg)
2786
{
2787
    intra_matrix = av_mallocz(sizeof(uint16_t) * 64);
2788
    parse_matrix_coeffs(intra_matrix, arg);
2789
}
2790

    
2791
static void opt_target(const char *arg)
2792
{
2793
    int norm = -1;
2794

    
2795
    if(!strncmp(arg, "pal-", 4)) {
2796
        norm = 0;
2797
        arg += 4;
2798
    } else if(!strncmp(arg, "ntsc-", 5)) {
2799
        norm = 1;
2800
        arg += 5;
2801
    } else {
2802
        int fr;
2803
        /* Calculate FR via float to avoid int overflow */
2804
        fr = (int)(frame_rate * 1000.0 / frame_rate_base);
2805
        if(fr == 25000) {
2806
            norm = 0;
2807
        } else if((fr == 29970) || (fr == 23976)) {
2808
            norm = 1;
2809
        } else {
2810
            /* Try to determine PAL/NTSC by peeking in the input files */
2811
            if(nb_input_files) {
2812
                int i, j;
2813
                for(j = 0; j < nb_input_files; j++) {
2814
                    for(i = 0; i < input_files[j]->nb_streams; i++) {
2815
                        AVCodecContext *c = &input_files[j]->streams[i]->codec;
2816
                        if(c->codec_type != CODEC_TYPE_VIDEO)
2817
                            continue;
2818
                        fr = c->frame_rate * 1000 / c->frame_rate_base;
2819
                        if(fr == 25000) {
2820
                            norm = 0;
2821
                            break;
2822
                        } else if((fr == 29970) || (fr == 23976)) {
2823
                            norm = 1;
2824
                            break;
2825
                        }
2826
                    }
2827
                    if(norm >= 0)
2828
                        break;
2829
                }
2830
            }
2831
        }
2832
        if(verbose && norm >= 0)
2833
            printf("Assuming %s for target.\n", norm ? "NTSC" : "PAL");
2834
    }
2835

    
2836
    if(norm < 0) {
2837
        fprintf(stderr, "Could not determine norm (PAL/NTSC) for target.\n");
2838
        fprintf(stderr, "Please prefix target with \"pal-\" or \"ntsc-\",\n");
2839
        fprintf(stderr, "or set a framerate with \"-r xxx\".\n");
2840
        exit(1);
2841
    }
2842

    
2843
    if(!strcmp(arg, "vcd")) {
2844

    
2845
        opt_video_codec("mpeg1video");
2846
        opt_audio_codec("mp2");
2847
        opt_format("vcd");
2848

    
2849
        opt_frame_size(norm ? "352x240" : "352x288");
2850

    
2851
        video_bit_rate = 1150000;
2852
        video_rc_max_rate = 1150000;
2853
        video_rc_min_rate = 1150000;
2854
        video_rc_buffer_size = 40*1024*8;
2855

    
2856
        audio_bit_rate = 224000;
2857
        audio_sample_rate = 44100;
2858

    
2859
    } else if(!strcmp(arg, "svcd")) {
2860

    
2861
        opt_video_codec("mpeg2video");
2862
        opt_audio_codec("mp2");
2863
        opt_format("vcd");
2864

    
2865
        opt_frame_size(norm ? "480x480" : "480x576");
2866
        opt_gop_size(norm ? "18" : "15");
2867

    
2868
        video_bit_rate = 2040000;
2869
        video_rc_max_rate = 2516000;
2870
        video_rc_min_rate = 1145000;
2871
        video_rc_buffer_size = 224*1024*8;
2872

    
2873
        audio_bit_rate = 224000;
2874
        audio_sample_rate = 44100;
2875

    
2876
    } else if(!strcmp(arg, "dvd")) {
2877

    
2878
        opt_video_codec("mpeg2video");
2879
        opt_audio_codec("ac3");
2880
        opt_format("vob");
2881

    
2882
        opt_frame_size(norm ? "720x480" : "720x576");
2883
        opt_gop_size(norm ? "18" : "15");
2884

    
2885
        video_bit_rate = 6000000;
2886
        video_rc_max_rate = 9000000;
2887
        video_rc_min_rate = 1500000;
2888
        video_rc_buffer_size = 224*1024*8;
2889

    
2890
        audio_bit_rate = 448000;
2891
        audio_sample_rate = 48000;
2892

    
2893
    } else {
2894
        fprintf(stderr, "Unknown target: %s\n", arg);
2895
        exit(1);
2896
    }
2897
}
2898

    
2899
const OptionDef options[] = {
2900
    /* main options */
2901
    { "L", 0, {(void*)show_license}, "show license" },
2902
    { "h", 0, {(void*)show_help}, "show help" },
2903
    { "formats", 0, {(void*)show_formats}, "show available formats, codecs, protocols, ..." },
2904
    { "f", HAS_ARG, {(void*)opt_format}, "force format", "fmt" },
2905
    { "img", HAS_ARG, {(void*)opt_image_format}, "force image format", "img_fmt" },
2906
    { "i", HAS_ARG, {(void*)opt_input_file}, "input file name", "filename" },
2907
    { "y", OPT_BOOL, {(void*)&file_overwrite}, "overwrite output files" },
2908
    { "map", HAS_ARG | OPT_EXPERT, {(void*)opt_map}, "set input stream mapping", "file:stream" },
2909
    { "t", HAS_ARG, {(void*)opt_recording_time}, "set the recording time", "duration" },
2910
    { "ss", HAS_ARG, {(void*)opt_start_time}, "set the start time offset", "time_off" },
2911
    { "title", HAS_ARG | OPT_STRING, {(void*)&str_title}, "set the title", "string" },
2912
    { "author", HAS_ARG | OPT_STRING, {(void*)&str_author}, "set the author", "string" },
2913
    { "copyright", HAS_ARG | OPT_STRING, {(void*)&str_copyright}, "set the copyright", "string" },
2914
    { "comment", HAS_ARG | OPT_STRING, {(void*)&str_comment}, "set the comment", "string" },
2915
    { "debug", HAS_ARG | OPT_EXPERT, {(void*)opt_debug}, "print specific debug info", "" },
2916
    { "benchmark", OPT_BOOL | OPT_EXPERT, {(void*)&do_benchmark}, 
2917
      "add timings for benchmarking" },
2918
    { "dump", OPT_BOOL | OPT_EXPERT, {(void*)&do_pkt_dump}, 
2919
      "dump each input packet" },
2920
    { "hex", OPT_BOOL | OPT_EXPERT, {(void*)&do_hex_dump}, 
2921
      "when dumping packets, also dump the payload" },
2922
    { "bitexact", OPT_EXPERT, {(void*)opt_bitexact}, "only use bit exact algorithms (for codec testing)" }, 
2923
    { "re", OPT_BOOL | OPT_EXPERT, {(void*)&rate_emu}, "read input at native frame rate", "" },
2924
    { "loop", OPT_BOOL | OPT_EXPERT, {(void*)&loop_input}, "loop (current only works with images)" },
2925
    { "v", HAS_ARG, {(void*)opt_verbose}, "control amount of logging", "verbose" },
2926
    { "target", HAS_ARG, {(void*)opt_target}, "specify target file type (\"vcd\", \"svcd\" or \"dvd\")", "type" },
2927

    
2928
    /* video options */
2929
    { "b", HAS_ARG | OPT_VIDEO, {(void*)opt_video_bitrate}, "set video bitrate (in kbit/s)", "bitrate" },
2930
    { "r", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_rate}, "set frame rate (Hz value, fraction or abbreviation)", "rate" },
2931
    { "s", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_size}, "set frame size (WxH or abbreviation)", "size" },
2932
    { "aspect", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_aspect_ratio}, "set aspect ratio (4:3, 16:9 or 1.3333, 1.7777)", "aspect" },
2933
    { "pix_fmt", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_frame_pix_fmt}, "set pixel format", "format" },
2934
    { "croptop", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop_top}, "set top crop band size (in pixels)", "size" },
2935
    { "cropbottom", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop_bottom}, "set bottom crop band size (in pixels)", "size" },
2936
    { "cropleft", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop_left}, "set left crop band size (in pixels)", "size" },
2937
    { "cropright", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop_right}, "set right crop band size (in pixels)", "size" },
2938
    { "g", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_gop_size}, "set the group of picture size", "gop_size" },
2939
    { "intra", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&intra_only}, "use only intra frames"},
2940
    { "vn", OPT_BOOL | OPT_VIDEO, {(void*)&video_disable}, "disable video" },
2941
    { "qscale", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qscale}, "use fixed video quantiser scale (VBR)", "q" },
2942
    { "qmin", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qmin}, "min video quantiser scale (VBR)", "q" },
2943
    { "qmax", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qmax}, "max video quantiser scale (VBR)", "q" },
2944
    { "mbqmin", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_mb_qmin}, "min macroblock quantiser scale (VBR)", "q" },
2945
    { "mbqmax", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_mb_qmax}, "max macroblock quantiser scale (VBR)", "q" },
2946
    { "qdiff", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qdiff}, "max difference between the quantiser scale (VBR)", "q" },
2947
    { "qblur", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qblur}, "video quantiser scale blur (VBR)", "blur" },
2948
    { "qcomp", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qcomp}, "video quantiser scale compression (VBR)", "compression" },
2949
    { "rc_init_cplx", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_rc_initial_cplx}, "initial complexity for 1-pass encoding", "complexity" },
2950
    { "b_qfactor", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_b_qfactor}, "qp factor between p and b frames", "factor" },
2951
    { "i_qfactor", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_i_qfactor}, "qp factor between p and i frames", "factor" },
2952
    { "b_qoffset", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_b_qoffset}, "qp offset between p and b frames", "offset" },
2953
    { "i_qoffset", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_i_qoffset}, "qp offset between p and i frames", "offset" },
2954
//    { "b_strategy", HAS_ARG | OPT_EXPERT, {(void*)opt_b_strategy}, "dynamic b frame selection strategy", "strategy" },
2955
    { "rc_eq", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_video_rc_eq}, "set rate control equation", "equation" },
2956
    { "rc_override", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_video_rc_override_string}, "rate control override for specific intervals", "override" },
2957
    { "bt", HAS_ARG | OPT_VIDEO, {(void*)opt_video_bitrate_tolerance}, "set video bitrate tolerance (in kbit/s)", "tolerance" },
2958
    { "maxrate", HAS_ARG | OPT_VIDEO, {(void*)opt_video_bitrate_max}, "set max video bitrate tolerance (in kbit/s)", "bitrate" },
2959
    { "minrate", HAS_ARG | OPT_VIDEO, {(void*)opt_video_bitrate_min}, "set min video bitrate tolerance (in kbit/s)", "bitrate" },
2960
    { "bufsize", HAS_ARG | OPT_VIDEO, {(void*)opt_video_buffer_size}, "set ratecontrol buffere size (in kbit)", "size" },
2961
    { "vcodec", HAS_ARG | OPT_VIDEO, {(void*)opt_video_codec}, "force video codec ('copy' to copy stream)", "codec" },
2962
    { "me", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_motion_estimation}, "set motion estimation method", 
2963
      "method" },
2964
    { "dct_algo", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_dct_algo}, "set dct algo",  "algo" },
2965
    { "idct_algo", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_idct_algo}, "set idct algo",  "algo" },
2966
    { "er", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_error_resilience}, "set error resilience",  "n" },
2967
    { "ec", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_error_concealment}, "set error concealment",  "bit_mask" },
2968
    { "bf", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_b_frames}, "use 'frames' B frames", "frames" },
2969
    { "hq", OPT_BOOL, {(void*)&mb_decision}, "activate high quality settings" },
2970
    { "mbd", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_mb_decision}, "macroblock decision", "mode" },
2971
    { "mbcmp", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_mb_cmp}, "macroblock compare function", "cmp function" },
2972
    { "subcmp", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_sub_cmp}, "subpel compare function", "cmp function" },
2973
    { "cmp", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_cmp}, "fullpel compare function", "cmp function" },
2974
    { "4mv", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_4mv}, "use four motion vector by macroblock (MPEG4)" },
2975
    { "obmc", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_obmc}, "use overlapped block motion compensation (h263+)" },
2976
    { "part", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_part}, "use data partitioning (MPEG4)" },
2977
    { "bug", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_workaround_bugs}, "workaround not auto detected encoder bugs", "param" },
2978
    { "ps", HAS_ARG | OPT_EXPERT, {(void*)opt_packet_size}, "set packet size in bits", "size" },
2979
    { "error", HAS_ARG | OPT_EXPERT, {(void*)opt_error_rate}, "error rate", "rate" },
2980
    { "strict", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_strict}, "how strictly to follow the standarts", "strictness" },
2981
    { "sameq", OPT_BOOL | OPT_VIDEO, {(void*)&same_quality}, 
2982
      "use same video quality as source (implies VBR)" },
2983
    { "pass", HAS_ARG | OPT_VIDEO, {(void*)&opt_pass}, "select the pass number (1 or 2)", "n" },
2984
    { "passlogfile", HAS_ARG | OPT_STRING | OPT_VIDEO, {(void*)&pass_logfilename}, "select two pass log file name", "file" },
2985
    { "deinterlace", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_deinterlace}, 
2986
      "deinterlace pictures" },
2987
    { "interlace", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_interlace}, 
2988
      "force interlacing support in encoder (MPEG2/MPEG4)" },
2989
    { "psnr", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_psnr}, "calculate PSNR of compressed frames" },
2990
    { "vstats", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_vstats}, "dump video coding statistics to file" }, 
2991
    { "vhook", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)add_frame_hooker}, "insert video processing module", "module" },
2992
    { "aic", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_aic}, "enable Advanced intra coding (h263+)" },
2993
    { "aiv", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_aiv}, "enable Alternative inter vlc (h263+)" },
2994
    { "umv", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_umv}, "enable Unlimited Motion Vector (h263+)" },
2995
    { "intra_matrix", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_intra_matrix}, "specify intra matrix coeffs", "matrix" },
2996
    { "inter_matrix", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_inter_matrix}, "specify inter matrix coeffs", "matrix" },
2997

    
2998
    /* audio options */
2999
    { "ab", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_bitrate}, "set audio bitrate (in kbit/s)", "bitrate", },
3000
    { "ar", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_rate}, "set audio sampling rate (in Hz)", "rate" },
3001
    { "ac", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_channels}, "set number of audio channels", "channels" },
3002
    { "an", OPT_BOOL | OPT_AUDIO, {(void*)&audio_disable}, "disable audio" },
3003
    { "acodec", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_codec}, "force audio codec ('copy' to copy stream)", "codec" },
3004

    
3005
    /* grab options */
3006
    { "vd", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_device}, "set video grab device", "device" },
3007
    { "vc", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_channel}, "set video grab channel (DV1394 only)", "channel" },
3008
    { "tvstd", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_standard}, "set television standard (NTSC, PAL (SECAM))", "standard" },
3009
    { "dv1394", OPT_EXPERT | OPT_GRAB, {(void*)opt_dv1394}, "set DV1394 grab", "" },
3010
    { "ad", HAS_ARG | OPT_EXPERT | OPT_AUDIO | OPT_GRAB, {(void*)opt_audio_device}, "set audio device", "device" },
3011
    { NULL, },
3012
};
3013

    
3014
static void show_banner(void)
3015
{
3016
    printf("ffmpeg version " FFMPEG_VERSION ", Copyright (c) 2000-2003 Fabrice Bellard\n");
3017
}
3018

    
3019
static void show_license(void)
3020
{
3021
    show_banner();
3022
    printf(
3023
    "This library is free software; you can redistribute it and/or\n"
3024
    "modify it under the terms of the GNU Lesser General Public\n"
3025
    "License as published by the Free Software Foundation; either\n"
3026
    "version 2 of the License, or (at your option) any later version.\n"
3027
    "\n"
3028
    "This library is distributed in the hope that it will be useful,\n"
3029
    "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
3030
    "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n"
3031
    "Lesser General Public License for more details.\n"
3032
    "\n"
3033
    "You should have received a copy of the GNU Lesser General Public\n"
3034
    "License along with this library; if not, write to the Free Software\n"
3035
    "Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n"
3036
    );
3037
    exit(1);
3038
}
3039

    
3040
static void show_help(void)
3041
{
3042
    show_banner();
3043
    printf("usage: ffmpeg [[options] -i input_file]... {[options] outfile}...\n"
3044
           "Hyper fast Audio and Video encoder\n");
3045
    printf("\n");
3046
    show_help_options(options, "Main options:\n",
3047
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO, 0);
3048
    show_help_options(options, "\nVideo options:\n",
3049
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB, 
3050
                      OPT_VIDEO);
3051
    show_help_options(options, "\nAdvanced Video options:\n",
3052
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB, 
3053
                      OPT_VIDEO | OPT_EXPERT);
3054
    show_help_options(options, "\nAudio options:\n",
3055
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB, 
3056
                      OPT_AUDIO);
3057
    show_help_options(options, "\nAdvanced Audio options:\n",
3058
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB, 
3059
                      OPT_AUDIO | OPT_EXPERT);
3060
    show_help_options(options, "\nAudio/Video grab options:\n",
3061
                      OPT_GRAB, 
3062
                      OPT_GRAB);
3063
    show_help_options(options, "\nAdvanced options:\n",
3064
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB, 
3065
                      OPT_EXPERT);
3066
    exit(1);
3067
}
3068

    
3069
void parse_arg_file(const char *filename)
3070
{
3071
    opt_output_file(filename);
3072
}
3073

    
3074
int main(int argc, char **argv)
3075
{
3076
    int i;
3077
    int64_t ti;
3078

    
3079
    av_register_all();
3080

    
3081
    if (argc <= 1)
3082
        show_help();
3083
    
3084
    /* parse options */
3085
    parse_options(argc, argv, options);
3086

    
3087
    /* file converter / grab */
3088
    if (nb_output_files <= 0) {
3089
        fprintf(stderr, "Must supply at least one output file\n");
3090
        exit(1);
3091
    }
3092
    
3093
    if (nb_input_files == 0) {
3094
        prepare_grab();
3095
    }
3096

    
3097
    ti = getutime();
3098
    av_encode(output_files, nb_output_files, input_files, nb_input_files, 
3099
              stream_maps, nb_stream_maps);
3100
    ti = getutime() - ti;
3101
    if (do_benchmark) {
3102
        printf("bench: utime=%0.3fs\n", ti / 1000000.0);
3103
    }
3104

    
3105
    /* close files */
3106
    for(i=0;i<nb_output_files;i++) {
3107
        /* maybe av_close_output_file ??? */
3108
        AVFormatContext *s = output_files[i];
3109
        int j;
3110
        if (!(s->oformat->flags & AVFMT_NOFILE))
3111
            url_fclose(&s->pb);
3112
        for(j=0;j<s->nb_streams;j++)
3113
            av_free(s->streams[j]);
3114
        av_free(s);
3115
    }
3116
    for(i=0;i<nb_input_files;i++)
3117
        av_close_input_file(input_files[i]);
3118

    
3119
    av_free_static();
3120

    
3121
    if(intra_matrix)
3122
        av_free(intra_matrix);
3123
    if(inter_matrix)
3124
        av_free(inter_matrix);
3125
    
3126
#ifdef POWERPC_PERFORMANCE_REPORT
3127
    extern void powerpc_display_perf_report(void);
3128
    powerpc_display_perf_report();
3129
#endif /* POWERPC_PERFORMANCE_REPORT */
3130

    
3131
#ifndef CONFIG_WIN32
3132
    if (received_sigterm) {
3133
        fprintf(stderr,
3134
            "Received signal %d: terminating.\n",
3135
            (int) received_sigterm);
3136
        exit (255);
3137
    }
3138
#endif
3139
    exit(0); /* not all OS-es handle main() return value */
3140
    return 0;
3141
}