Statistics
| Branch: | Revision:

ffmpeg / ffmpeg.c @ f42eda74

History | View | Annotate | Download (93.7 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 "common.h"
21
#include "avformat.h"
22
#include "framehook.h"
23

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

    
40
#include "cmdutils.h"
41

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

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

    
52
extern const OptionDef options[];
53

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

    
57
#define MAX_FILES 20
58

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

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

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

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

    
128
static int gop_size = 12;
129
static int intra_only = 0;
130
static int audio_sample_rate = 44100;
131
static int audio_bit_rate = 64000;
132
static int audio_disable = 0;
133
static int audio_channels = 1;
134
static int audio_codec_id = CODEC_ID_NONE;
135

    
136
static int64_t recording_time = 0;
137
static int file_overwrite = 0;
138
static char *str_title = NULL;
139
static char *str_author = NULL;
140
static char *str_copyright = NULL;
141
static char *str_comment = NULL;
142
static int do_benchmark = 0;
143
static int do_hex_dump = 0;
144
static int do_psnr = 0;
145
static int do_vstats = 0;
146
static int do_pass = 0;
147
static int bitexact = 0;
148
static char *pass_logfilename = NULL;
149
static int audio_stream_copy = 0;
150
static int video_stream_copy = 0;
151

    
152
static int rate_emu = 0;
153

    
154
static char *video_grab_format = "video4linux";
155
static char *video_device = NULL;
156
static int  video_channel = 0;
157
static char *video_standard = "ntsc";
158

    
159
static char *audio_grab_format = "audio_device";
160
static char *audio_device = NULL;
161

    
162
static int using_stdin = 0;
163
static int using_vhook = 0;
164
static int verbose = 1;
165

    
166
#define DEFAULT_PASS_LOGFILENAME "ffmpeg2pass"
167

    
168
typedef struct AVOutputStream {
169
    int file_index;          /* file index */
170
    int index;               /* stream index in the output file */
171
    int source_index;        /* AVInputStream index */
172
    AVStream *st;            /* stream in the output file */
173
    int encoding_needed;     /* true if encoding needed for this stream */
174
    int frame_number;
175
    /* input pts and corresponding output pts
176
       for A/V sync */
177
    double sync_ipts;
178
    double sync_ipts_offset;
179
    int64_t sync_opts;
180
    /* video only */
181
    int video_resample;      /* video_resample and video_crop are mutually exclusive */
182
    AVPicture pict_tmp;      /* temporary image for resampling */
183
    ImgReSampleContext *img_resample_ctx; /* for image resampling */
184

    
185
    int video_crop;          /* video_resample and video_crop are mutually exclusive */
186
    int topBand;             /* cropping area sizes */
187
    int leftBand;
188
    
189
    /* audio only */
190
    int audio_resample;
191
    ReSampleContext *resample; /* for audio resampling */
192
    FifoBuffer fifo;     /* for compression: one audio fifo per codec */
193
    FILE *logfile;
194
} AVOutputStream;
195

    
196
typedef struct AVInputStream {
197
    int file_index;
198
    int index;
199
    AVStream *st;
200
    int discard;             /* true if stream data should be discarded */
201
    int decoding_needed;     /* true if the packets must be decoded in 'raw_fifo' */
202
    int64_t sample_index;      /* current sample */
203
    int frame_decoded;       /* true if a video or audio frame has been decoded */
204

    
205
    int64_t       start;     /* time when read started */
206
    unsigned long frame;     /* current frame */
207
    AVFrac        next_pts;  /* synthetic pts for cases where pkt.pts == 0 */
208
    int64_t       pts;       /* current pts */
209
} AVInputStream;
210

    
211
typedef struct AVInputFile {
212
    int eof_reached;      /* true if eof reached */
213
    int ist_index;        /* index of first stream in ist_table */
214
    int buffer_size;      /* current total buffer size */
215
    int buffer_size_max;  /* buffer size at which we consider we can stop
216
                             buffering */
217
    int nb_streams;       /* nb streams we are aware of */
218
} AVInputFile;
219

    
220
#ifndef CONFIG_WIN32
221

    
222
/* init terminal so that we can grab keys */
223
static struct termios oldtty;
224

    
225
static void term_exit(void)
226
{
227
    tcsetattr (0, TCSANOW, &oldtty);
228
}
229

    
230
static volatile sig_atomic_t received_sigterm = 0;
231

    
232
static void
233
sigterm_handler(int sig)
234
{
235
    received_sigterm = sig;
236
    term_exit();
237
}
238

    
239
static void term_init(void)
240
{
241
    struct termios tty;
242

    
243
    tcgetattr (0, &tty);
244
    oldtty = tty;
245

    
246
    tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
247
                          |INLCR|IGNCR|ICRNL|IXON);
248
    tty.c_oflag |= OPOST;
249
    tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
250
    tty.c_cflag &= ~(CSIZE|PARENB);
251
    tty.c_cflag |= CS8;
252
    tty.c_cc[VMIN] = 1;
253
    tty.c_cc[VTIME] = 0;
254
    
255
    tcsetattr (0, TCSANOW, &tty);
256

    
257
    signal(SIGINT , sigterm_handler); /* Interrupt (ANSI).  */
258
    signal(SIGQUIT, sigterm_handler); /* Quit (POSIX).  */
259
    signal(SIGTERM, sigterm_handler); /* Termination (ANSI).  */
260
    /*
261
    register a function to be called at normal program termination
262
    */
263
    atexit(term_exit);
264
#ifdef CONFIG_BEOS_NETSERVER
265
    fcntl(0, F_SETFL, fcntl(0, F_GETFL) | O_NONBLOCK);
266
#endif
267
}
268

    
269
/* read a key without blocking */
270
static int read_key(void)
271
{
272
    int n = 1;
273
    unsigned char ch;
274
#ifndef CONFIG_BEOS_NETSERVER
275
    struct timeval tv;
276
    fd_set rfds;
277

    
278
    FD_ZERO(&rfds);
279
    FD_SET(0, &rfds);
280
    tv.tv_sec = 0;
281
    tv.tv_usec = 0;
282
    n = select(1, &rfds, NULL, NULL, &tv);
283
#endif
284
    if (n > 0) {
285
        n = read(0, &ch, 1);
286
        if (n == 1)
287
            return ch;
288

    
289
        return n;
290
    }
291
    return -1;
292
}
293

    
294
#else
295

    
296
static volatile int received_sigterm = 0;
297

    
298
/* no interactive support */
299
static void term_exit(void)
300
{
301
}
302

    
303
static void term_init(void)
304
{
305
}
306

    
307
static int read_key(void)
308
{
309
    return 0;
310
}
311

    
312
#endif
313

    
314
static int read_ffserver_streams(AVFormatContext *s, const char *filename)
315
{
316
    int i, err;
317
    AVFormatContext *ic;
318

    
319
    err = av_open_input_file(&ic, filename, NULL, FFM_PACKET_SIZE, NULL);
320
    if (err < 0)
321
        return err;
322
    /* copy stream format */
323
    s->nb_streams = ic->nb_streams;
324
    for(i=0;i<ic->nb_streams;i++) {
325
        AVStream *st;
326

    
327
        st = av_mallocz(sizeof(AVStream));
328
        memcpy(st, ic->streams[i], sizeof(AVStream));
329
        s->streams[i] = st;
330
    }
331

    
332
    av_close_input_file(ic);
333
    return 0;
334
}
335

    
336
#define MAX_AUDIO_PACKET_SIZE (128 * 1024)
337

    
338
static void do_audio_out(AVFormatContext *s, 
339
                         AVOutputStream *ost, 
340
                         AVInputStream *ist,
341
                         unsigned char *buf, int size)
342
{
343
    uint8_t *buftmp;
344
    static uint8_t *audio_buf = NULL;
345
    static uint8_t *audio_out = NULL;
346
    const int audio_out_size= 4*MAX_AUDIO_PACKET_SIZE;
347

    
348
    int size_out, frame_bytes, ret;
349
    AVCodecContext *enc;
350

    
351
    /* SC: dynamic allocation of buffers */
352
    if (!audio_buf)
353
        audio_buf = av_malloc(2*MAX_AUDIO_PACKET_SIZE);
354
    if (!audio_out)
355
        audio_out = av_malloc(audio_out_size);
356
    if (!audio_buf || !audio_out)
357
        return;               /* Should signal an error ! */
358

    
359
    
360
    enc = &ost->st->codec;
361

    
362
    if (ost->audio_resample) {
363
        buftmp = audio_buf;
364
        size_out = audio_resample(ost->resample, 
365
                                  (short *)buftmp, (short *)buf,
366
                                  size / (ist->st->codec.channels * 2));
367
        size_out = size_out * enc->channels * 2;
368
    } else {
369
        buftmp = buf;
370
        size_out = size;
371
    }
372

    
373
    /* now encode as many frames as possible */
374
    if (enc->frame_size > 1) {
375
        /* output resampled raw samples */
376
        fifo_write(&ost->fifo, buftmp, size_out, 
377
                   &ost->fifo.wptr);
378

    
379
        frame_bytes = enc->frame_size * 2 * enc->channels;
380
        
381
        while (fifo_read(&ost->fifo, audio_buf, frame_bytes, 
382
                     &ost->fifo.rptr) == 0) {
383
            ret = avcodec_encode_audio(enc, audio_out, audio_out_size, 
384
                                       (short *)audio_buf);
385
            av_write_frame(s, ost->index, audio_out, ret);
386
        }
387
    } else {
388
        /* output a pcm frame */
389
        /* XXX: change encoding codec API to avoid this ? */
390
        switch(enc->codec->id) {
391
        case CODEC_ID_PCM_S16LE:
392
        case CODEC_ID_PCM_S16BE:
393
        case CODEC_ID_PCM_U16LE:
394
        case CODEC_ID_PCM_U16BE:
395
            break;
396
        default:
397
            size_out = size_out >> 1;
398
            break;
399
        }
400
        ret = avcodec_encode_audio(enc, audio_out, size_out, 
401
                                   (short *)buftmp);
402
        av_write_frame(s, ost->index, audio_out, ret);
403
    }
404
}
405

    
406
static void pre_process_video_frame(AVInputStream *ist, AVPicture *picture, void **bufp)
407
{
408
    AVCodecContext *dec;
409
    AVPicture *picture2;
410
    AVPicture picture_tmp;
411
    uint8_t *buf = 0;
412

    
413
    dec = &ist->st->codec;
414

    
415
    /* deinterlace : must be done before any resize */
416
    if (do_deinterlace || using_vhook) {
417
        int size;
418

    
419
        /* create temporary picture */
420
        size = avpicture_get_size(dec->pix_fmt, dec->width, dec->height);
421
        buf = av_malloc(size);
422
        if (!buf)
423
            return;
424
        
425
        picture2 = &picture_tmp;
426
        avpicture_fill(picture2, buf, dec->pix_fmt, dec->width, dec->height);
427

    
428
        if (do_deinterlace){
429
            if(avpicture_deinterlace(picture2, picture, 
430
                                     dec->pix_fmt, dec->width, dec->height) < 0) {
431
                /* if error, do not deinterlace */
432
                av_free(buf);
433
                buf = NULL;
434
                picture2 = picture;
435
            }
436
        } else {
437
            if (img_convert(picture2, dec->pix_fmt, picture, 
438
                            dec->pix_fmt, dec->width, dec->height) < 0) {
439
                /* if error, do not copy */
440
                av_free(buf);
441
                buf = NULL;
442
                picture2 = picture;
443
            }
444
        }
445
    } else {
446
        picture2 = picture;
447
    }
448

    
449
    frame_hook_process(picture2, dec->pix_fmt, dec->width, dec->height);
450

    
451
    if (picture != picture2)
452
        *picture = *picture2;
453
    *bufp = buf;
454
}
455

    
456
/* we begin to correct av delay at this threshold */
457
#define AV_DELAY_MAX 0.100
458

    
459
static void do_video_out(AVFormatContext *s, 
460
                         AVOutputStream *ost, 
461
                         AVInputStream *ist,
462
                         AVPicture *in_picture,
463
                         int *frame_size, AVOutputStream *audio_sync)
464
{
465
    int nb_frames, i, ret;
466
    AVPicture *final_picture, *formatted_picture;
467
    AVPicture picture_format_temp, picture_crop_temp;
468
    static uint8_t *video_buffer;
469
    uint8_t *buf = NULL, *buf1 = NULL;
470
    AVCodecContext *enc, *dec;
471

    
472
#define VIDEO_BUFFER_SIZE (1024*1024)
473

    
474
    enc = &ost->st->codec;
475
    dec = &ist->st->codec;
476

    
477
    /* by default, we output a single frame */
478
    nb_frames = 1;
479

    
480
    *frame_size = 0;
481

    
482
    /* NOTE: the A/V sync is always done by considering the audio is
483
       the master clock. It is suffisant for transcoding or playing,
484
       but not for the general case */
485
    if (audio_sync) {
486
        /* compute the A-V delay and duplicate/remove frames if needed */
487
        double adelta, vdelta, av_delay;
488

    
489
        adelta = audio_sync->sync_ipts - ((double)audio_sync->sync_opts * 
490
            s->pts_num / s->pts_den);
491

    
492
        vdelta = ost->sync_ipts - ((double)ost->sync_opts *
493
            s->pts_num / s->pts_den);
494

    
495
        av_delay = adelta - vdelta;
496
        //            printf("delay=%f\n", av_delay);
497
        if (av_delay < -AV_DELAY_MAX)
498
            nb_frames = 2;
499
        else if (av_delay > AV_DELAY_MAX)
500
            nb_frames = 0;
501
    } else {
502
        double vdelta;
503

    
504
        vdelta = (double)(ost->st->pts.val) * s->pts_num / s->pts_den - (ost->sync_ipts - ost->sync_ipts_offset);
505
        if (vdelta < 100 && vdelta > -100 && ost->sync_ipts_offset) {
506
            if (vdelta < -AV_DELAY_MAX)
507
                nb_frames = 2;
508
            else if (vdelta > AV_DELAY_MAX)
509
                nb_frames = 0;
510
        } else {
511
            ost->sync_ipts_offset -= vdelta;
512
            if (!ost->sync_ipts_offset)
513
                ost->sync_ipts_offset = 0.000001; /* one microsecond */
514
        }
515
    }
516
    
517
#if defined(AVSYNC_DEBUG)
518
    static char *action[] = { "drop frame", "copy frame", "dup frame" };
519
    if (audio_sync)
520
        fprintf(stderr, "Input APTS %12.6f, output APTS %12.6f, ",
521
                (double) audio_sync->sync_ipts, 
522
                (double) audio_sync->st->pts.val * s->pts_num / s->pts_den);
523
    fprintf(stderr, "Input VPTS %12.6f, output VPTS %12.6f: %s\n",
524
            (double) ost->sync_ipts, 
525
              (double) ost->st->pts.val * s->pts_num / s->pts_den,
526
            action[nb_frames]);
527
#endif
528

    
529
    if (nb_frames <= 0) 
530
        return;
531

    
532
    if (!video_buffer)
533
        video_buffer = av_malloc(VIDEO_BUFFER_SIZE);
534
    if (!video_buffer)
535
        return;
536

    
537
    /* convert pixel format if needed */
538
    if (enc->pix_fmt != dec->pix_fmt) {
539
        int size;
540

    
541
        /* create temporary picture */
542
        size = avpicture_get_size(enc->pix_fmt, dec->width, dec->height);
543
        buf = av_malloc(size);
544
        if (!buf)
545
            return;
546
        formatted_picture = &picture_format_temp;
547
        avpicture_fill(formatted_picture, buf, enc->pix_fmt, dec->width, dec->height);
548
        
549
        if (img_convert(formatted_picture, enc->pix_fmt, 
550
                        in_picture, dec->pix_fmt, 
551
                        dec->width, dec->height) < 0) {
552
            fprintf(stderr, "pixel format conversion not handled\n");
553
            goto the_end;
554
        }
555
    } else {
556
        formatted_picture = in_picture;
557
    }
558

    
559
    /* XXX: resampling could be done before raw format convertion in
560
       some cases to go faster */
561
    /* XXX: only works for YUV420P */
562
    if (ost->video_resample) {
563
        final_picture = &ost->pict_tmp;
564
        img_resample(ost->img_resample_ctx, final_picture, formatted_picture);
565
    } else if (ost->video_crop) {
566
        picture_crop_temp.data[0] = formatted_picture->data[0] +
567
                (ost->topBand * formatted_picture->linesize[0]) + ost->leftBand;
568

    
569
        picture_crop_temp.data[1] = formatted_picture->data[1] +
570
                ((ost->topBand >> 1) * formatted_picture->linesize[1]) +
571
                (ost->leftBand >> 1);
572

    
573
        picture_crop_temp.data[2] = formatted_picture->data[2] +
574
                ((ost->topBand >> 1) * formatted_picture->linesize[2]) +
575
                (ost->leftBand >> 1);
576

    
577
        picture_crop_temp.linesize[0] = formatted_picture->linesize[0];
578
        picture_crop_temp.linesize[1] = formatted_picture->linesize[1];
579
        picture_crop_temp.linesize[2] = formatted_picture->linesize[2];
580
        final_picture = &picture_crop_temp;
581
    } else {
582
        final_picture = formatted_picture;
583
    }
584
    /* duplicates frame if needed */
585
    /* XXX: pb because no interleaving */
586
    for(i=0;i<nb_frames;i++) {
587
        if (s->oformat->flags & AVFMT_RAWPICTURE) {
588
            /* raw pictures are written as AVPicture structure to
589
               avoid any copies. We support temorarily the older
590
               method. */
591
            av_write_frame(s, ost->index, 
592
                           (uint8_t *)final_picture, sizeof(AVPicture));
593
        } else {
594
            AVFrame big_picture;
595
            
596
            memset(&big_picture, 0, sizeof(AVFrame));
597
            *(AVPicture*)&big_picture= *final_picture;
598
                        
599
            /* handles sameq here. This is not correct because it may
600
               not be a global option */
601
            if (same_quality) {
602
                big_picture.quality = ist->st->quality;
603
            }else
604
                big_picture.quality = ost->st->quality;
605
            
606
            ret = avcodec_encode_video(enc, 
607
                                       video_buffer, VIDEO_BUFFER_SIZE,
608
                                       &big_picture);
609
            //enc->frame_number = enc->real_pict_num;
610
            av_write_frame(s, ost->index, video_buffer, ret);
611
            *frame_size = ret;
612
            //fprintf(stderr,"\nFrame: %3d %3d size: %5d type: %d",
613
            //        enc->frame_number-1, enc->real_pict_num, ret,
614
            //        enc->pict_type);
615
            /* if two pass, output log */
616
            if (ost->logfile && enc->stats_out) {
617
                fprintf(ost->logfile, "%s", enc->stats_out);
618
            }
619
        }
620
        ost->frame_number++;
621
    }
622
 the_end:
623
    av_free(buf);
624
    av_free(buf1);
625
}
626

    
627
static double psnr(double d){
628
    if(d==0) return INFINITY;
629
    return -10.0*log(d)/log(10.0);
630
}
631

    
632
static void do_video_stats(AVFormatContext *os, AVOutputStream *ost, 
633
                           int frame_size)
634
{
635
    static FILE *fvstats=NULL;
636
    static int64_t total_size = 0;
637
    char filename[40];
638
    time_t today2;
639
    struct tm *today;
640
    AVCodecContext *enc;
641
    int frame_number;
642
    int64_t ti;
643
    double ti1, bitrate, avg_bitrate;
644
    
645
    if (!fvstats) {
646
        today2 = time(NULL);
647
        today = localtime(&today2);
648
        sprintf(filename, "vstats_%02d%02d%02d.log", today->tm_hour,
649
                                               today->tm_min,
650
                                               today->tm_sec);
651
        fvstats = fopen(filename,"w");
652
        if (!fvstats) {
653
            perror("fopen");
654
            exit(1);
655
        }
656
    }
657
    
658
    ti = MAXINT64;
659
    enc = &ost->st->codec;
660
    total_size += frame_size;
661
    if (enc->codec_type == CODEC_TYPE_VIDEO) {
662
        frame_number = ost->frame_number;
663
        fprintf(fvstats, "frame= %5d q= %2.1f ", frame_number, enc->coded_frame->quality);
664
        if (enc->flags&CODEC_FLAG_PSNR)
665
            fprintf(fvstats, "PSNR= %6.2f ", psnr(enc->coded_frame->error[0]/(enc->width*enc->height*255.0*255.0)));
666
        
667
        fprintf(fvstats,"f_size= %6d ", frame_size);
668
        /* compute pts value */
669
        ti1 = (double)ost->st->pts.val * os->pts_num / os->pts_den;
670
        if (ti1 < 0.01)
671
            ti1 = 0.01;
672
    
673
        bitrate = (double)(frame_size * 8) * enc->frame_rate / enc->frame_rate_base / 1000.0;
674
        avg_bitrate = (double)(total_size * 8) / ti1 / 1000.0;
675
        fprintf(fvstats, "s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
676
            (double)total_size / 1024, ti1, bitrate, avg_bitrate);
677
        fprintf(fvstats,"type= %c\n", av_get_pict_type_char(enc->coded_frame->pict_type));        
678
    }
679
}
680

    
681
static void print_report(AVFormatContext **output_files,
682
                         AVOutputStream **ost_table, int nb_ostreams,
683
                         int is_last_report)
684
{
685
    char buf[1024];
686
    AVOutputStream *ost;
687
    AVFormatContext *oc, *os;
688
    int64_t total_size;
689
    AVCodecContext *enc;
690
    int frame_number, vid, i;
691
    double bitrate, ti1, pts;
692
    static int64_t last_time = -1;
693
    
694
    if (!is_last_report) {
695
        int64_t cur_time;
696
        /* display the report every 0.5 seconds */
697
        cur_time = av_gettime();
698
        if (last_time == -1) {
699
            last_time = cur_time;
700
            return;
701
        } 
702
        if ((cur_time - last_time) < 500000)
703
            return;
704
        last_time = cur_time;
705
    }
706

    
707

    
708
    oc = output_files[0];
709

    
710
    total_size = url_ftell(&oc->pb);
711
    
712
    buf[0] = '\0';
713
    ti1 = 1e10;
714
    vid = 0;
715
    for(i=0;i<nb_ostreams;i++) {
716
        ost = ost_table[i];
717
        os = output_files[ost->file_index];
718
        enc = &ost->st->codec;
719
        if (vid && enc->codec_type == CODEC_TYPE_VIDEO) {
720
            sprintf(buf + strlen(buf), "q=%2.1f ",
721
                    enc->coded_frame->quality);
722
        }
723
        if (!vid && enc->codec_type == CODEC_TYPE_VIDEO) {
724
            frame_number = ost->frame_number;
725
            sprintf(buf + strlen(buf), "frame=%5d q=%2.1f ",
726
                    frame_number, enc->coded_frame ? enc->coded_frame->quality : 0);
727
            if (enc->flags&CODEC_FLAG_PSNR)
728
                sprintf(buf + strlen(buf), "PSNR= %6.2f ", psnr(enc->coded_frame->error[0]/(enc->width*enc->height*255.0*255.0)));
729
            vid = 1;
730
        }
731
        /* compute min output value */
732
        pts = (double)ost->st->pts.val * os->pts_num / os->pts_den;
733
        if ((pts < ti1) && (pts > 0))
734
            ti1 = pts;
735
    }
736
    if (ti1 < 0.01)
737
        ti1 = 0.01;
738
    
739
    if (verbose || is_last_report) {
740
        bitrate = (double)(total_size * 8) / ti1 / 1000.0;
741
        
742
        sprintf(buf + strlen(buf), 
743
            "size=%8.0fkB time=%0.1f bitrate=%6.1fkbits/s",
744
            (double)total_size / 1024, ti1, bitrate);
745
        
746
        fprintf(stderr, "%s    \r", buf);
747
        fflush(stderr);
748
    }
749
        
750
    if (is_last_report)
751
        fprintf(stderr, "\n");
752
}
753

    
754
/*
755
 * The following code is the main loop of the file converter
756
 */
757
static int av_encode(AVFormatContext **output_files,
758
                     int nb_output_files,
759
                     AVFormatContext **input_files,
760
                     int nb_input_files,
761
                     AVStreamMap *stream_maps, int nb_stream_maps)
762
{
763
    int ret, i, j, k, n, nb_istreams = 0, nb_ostreams = 0;
764
    AVFormatContext *is, *os;
765
    AVCodecContext *codec, *icodec;
766
    AVOutputStream *ost, **ost_table = NULL;
767
    AVInputStream *ist, **ist_table = NULL;
768
    AVInputFile *file_table;
769
    AVFormatContext *stream_no_data;
770
    int key;
771

    
772
    file_table= (AVInputFile*) av_mallocz(nb_input_files * sizeof(AVInputFile));
773
    if (!file_table)
774
        goto fail;
775

    
776
    /* input stream init */
777
    j = 0;
778
    for(i=0;i<nb_input_files;i++) {
779
        is = input_files[i];
780
        file_table[i].ist_index = j;
781
        file_table[i].nb_streams = is->nb_streams;
782
        j += is->nb_streams;
783
    }
784
    nb_istreams = j;
785

    
786
    ist_table = av_mallocz(nb_istreams * sizeof(AVInputStream *));
787
    if (!ist_table)
788
        goto fail;
789
    
790
    for(i=0;i<nb_istreams;i++) {
791
        ist = av_mallocz(sizeof(AVInputStream));
792
        if (!ist)
793
            goto fail;
794
        ist_table[i] = ist;
795
    }
796
    j = 0;
797
    for(i=0;i<nb_input_files;i++) {
798
        is = input_files[i];
799
        for(k=0;k<is->nb_streams;k++) {
800
            ist = ist_table[j++];
801
            ist->st = is->streams[k];
802
            ist->file_index = i;
803
            ist->index = k;
804
            ist->discard = 1; /* the stream is discarded by default
805
                                 (changed later) */
806

    
807
            if (ist->st->codec.rate_emu) {
808
                ist->start = av_gettime();
809
                ist->frame = 0;
810
            }
811
        }
812
    }
813

    
814
    /* output stream init */
815
    nb_ostreams = 0;
816
    for(i=0;i<nb_output_files;i++) {
817
        os = output_files[i];
818
        nb_ostreams += os->nb_streams;
819
    }
820
    if (nb_stream_maps > 0 && nb_stream_maps != nb_ostreams) {
821
        fprintf(stderr, "Number of stream maps must match number of output streams\n");
822
        exit(1);
823
    }
824

    
825
    /* Sanity check the mapping args -- do the input files & streams exist? */
826
    for(i=0;i<nb_stream_maps;i++) {
827
        int fi = stream_maps[i].file_index;
828
        int si = stream_maps[i].stream_index;
829
        
830
        if (fi < 0 || fi > nb_input_files - 1 ||
831
            si < 0 || si > file_table[fi].nb_streams - 1) {
832
            fprintf(stderr,"Could not find input stream #%d.%d\n", fi, si);
833
            exit(1);
834
        }
835
    }
836
    
837
    ost_table = av_mallocz(sizeof(AVOutputStream *) * nb_ostreams);
838
    if (!ost_table)
839
        goto fail;
840
    for(i=0;i<nb_ostreams;i++) {
841
        ost = av_mallocz(sizeof(AVOutputStream));
842
        if (!ost)
843
            goto fail;
844
        ost_table[i] = ost;
845
    }
846
    
847
    n = 0;
848
    for(k=0;k<nb_output_files;k++) {
849
        os = output_files[k];
850
        for(i=0;i<os->nb_streams;i++) {
851
            int found;
852
            ost = ost_table[n++];
853
            ost->file_index = k;
854
            ost->index = i;
855
            ost->st = os->streams[i];
856
            if (nb_stream_maps > 0) {
857
                ost->source_index = file_table[stream_maps[n-1].file_index].ist_index + 
858
                    stream_maps[n-1].stream_index;
859
                    
860
                /* Sanity check that the stream types match */
861
                if (ist_table[ost->source_index]->st->codec.codec_type != ost->st->codec.codec_type) {
862
                    fprintf(stderr, "Codec type mismatch for mapping #%d.%d -> #%d.%d\n",
863
                        stream_maps[n-1].file_index, stream_maps[n-1].stream_index,
864
                        ost->file_index, ost->index);
865
                    exit(1);
866
                }
867
                
868
            } else {
869
                /* get corresponding input stream index : we select the first one with the right type */
870
                found = 0;
871
                for(j=0;j<nb_istreams;j++) {
872
                    ist = ist_table[j];
873
                    if (ist->discard && 
874
                        ist->st->codec.codec_type == ost->st->codec.codec_type) {
875
                        ost->source_index = j;
876
                        found = 1;
877
                    }
878
                }
879
                
880
                if (!found) {
881
                    /* try again and reuse existing stream */
882
                    for(j=0;j<nb_istreams;j++) {
883
                        ist = ist_table[j];
884
                        if (ist->st->codec.codec_type == ost->st->codec.codec_type) {
885
                            ost->source_index = j;
886
                            found = 1;
887
                        }
888
                    }
889
                    if (!found) {
890
                        fprintf(stderr, "Could not find input stream matching output stream #%d.%d\n",
891
                                ost->file_index, ost->index);
892
                        exit(1);
893
                    }
894
                }
895
            }
896
            ist = ist_table[ost->source_index];
897
            ist->discard = 0;
898
        }
899
    }
900

    
901
    /* for each output stream, we compute the right encoding parameters */
902
    for(i=0;i<nb_ostreams;i++) {
903
        ost = ost_table[i];
904
        ist = ist_table[ost->source_index];
905

    
906
        codec = &ost->st->codec;
907
        icodec = &ist->st->codec;
908

    
909
        if (ost->st->stream_copy) {
910
            /* if stream_copy is selected, no need to decode or encode */
911
            codec->codec_id = icodec->codec_id;
912
            codec->codec_type = icodec->codec_type;
913
            codec->codec_tag = icodec->codec_tag;
914
            codec->bit_rate = icodec->bit_rate;
915
            switch(codec->codec_type) {
916
            case CODEC_TYPE_AUDIO:
917
                codec->sample_rate = icodec->sample_rate;
918
                codec->channels = icodec->channels;
919
                break;
920
            case CODEC_TYPE_VIDEO:
921
                codec->frame_rate = icodec->frame_rate;
922
                codec->frame_rate_base = icodec->frame_rate_base;
923
                codec->width = icodec->width;
924
                codec->height = icodec->height;
925
                break;
926
            default:
927
                av_abort();
928
            }
929
        } else {
930
            switch(codec->codec_type) {
931
            case CODEC_TYPE_AUDIO:
932
                if (fifo_init(&ost->fifo, 2 * MAX_AUDIO_PACKET_SIZE))
933
                    goto fail;
934
                
935
                if (codec->channels == icodec->channels &&
936
                    codec->sample_rate == icodec->sample_rate) {
937
                    ost->audio_resample = 0;
938
                } else {
939
                    if (codec->channels != icodec->channels &&
940
                        icodec->codec_id == CODEC_ID_AC3) {
941
                        /* Special case for 5:1 AC3 input */
942
                        /* and mono or stereo output      */
943
                        /* Request specific number of channels */
944
                        icodec->channels = codec->channels;
945
                        if (codec->sample_rate == icodec->sample_rate)
946
                            ost->audio_resample = 0;
947
                        else {
948
                            ost->audio_resample = 1;
949
                            ost->resample = audio_resample_init(codec->channels, icodec->channels,
950
                                                        codec->sample_rate, 
951
                                                        icodec->sample_rate);
952
                            if(!ost->resample)
953
                              {
954
                                printf("Can't resample.  Aborting.\n");
955
                                av_abort();
956
                              }
957
                        }
958
                        /* Request specific number of channels */
959
                        icodec->channels = codec->channels;
960
                    } else {
961
                        ost->audio_resample = 1; 
962
                        ost->resample = audio_resample_init(codec->channels, icodec->channels,
963
                                                        codec->sample_rate, 
964
                                                        icodec->sample_rate);
965
                        if(!ost->resample)
966
                          {
967
                            printf("Can't resample.  Aborting.\n");
968
                            av_abort();
969
                          }
970
                    }
971
                }
972
                ist->decoding_needed = 1;
973
                ost->encoding_needed = 1;
974
                break;
975
            case CODEC_TYPE_VIDEO:
976
                if (codec->width == icodec->width &&
977
                    codec->height == icodec->height &&
978
                    frame_topBand == 0 &&
979
                    frame_bottomBand == 0 &&
980
                    frame_leftBand == 0 &&
981
                    frame_rightBand == 0)
982
                {
983
                    ost->video_resample = 0;
984
                    ost->video_crop = 0;
985
                } else if ((codec->width == icodec->width -
986
                                (frame_leftBand + frame_rightBand)) &&
987
                        (codec->height == icodec->height -
988
                                (frame_topBand  + frame_bottomBand)))
989
                {
990
                    ost->video_resample = 0;
991
                    ost->video_crop = 1;
992
                    ost->topBand = frame_topBand;
993
                    ost->leftBand = frame_leftBand;
994
                } else {
995
                    uint8_t *buf;
996
                    ost->video_resample = 1;
997
                    ost->video_crop = 0; // cropping is handled as part of resample
998
                    buf = av_malloc((codec->width * codec->height * 3) / 2);
999
                    if (!buf)
1000
                        goto fail;
1001
                    ost->pict_tmp.data[0] = buf;
1002
                    ost->pict_tmp.data[1] = ost->pict_tmp.data[0] + (codec->width * codec->height);
1003
                    ost->pict_tmp.data[2] = ost->pict_tmp.data[1] + (codec->width * codec->height) / 4;
1004
                    ost->pict_tmp.linesize[0] = codec->width;
1005
                    ost->pict_tmp.linesize[1] = codec->width / 2;
1006
                    ost->pict_tmp.linesize[2] = codec->width / 2;
1007

    
1008
                    ost->img_resample_ctx = img_resample_full_init( 
1009
                                      ost->st->codec.width, ost->st->codec.height,
1010
                                      ist->st->codec.width, ist->st->codec.height,
1011
                                      frame_topBand, frame_bottomBand,
1012
                                      frame_leftBand, frame_rightBand);
1013
                }
1014
                ost->encoding_needed = 1;
1015
                ist->decoding_needed = 1;
1016
                break;
1017
            default:
1018
                av_abort();
1019
            }
1020
            /* two pass mode */
1021
            if (ost->encoding_needed && 
1022
                (codec->flags & (CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2))) {
1023
                char logfilename[1024];
1024
                FILE *f;
1025
                int size;
1026
                char *logbuffer;
1027
                
1028
                snprintf(logfilename, sizeof(logfilename), "%s-%d.log", 
1029
                         pass_logfilename ? 
1030
                         pass_logfilename : DEFAULT_PASS_LOGFILENAME, i);
1031
                if (codec->flags & CODEC_FLAG_PASS1) {
1032
                    f = fopen(logfilename, "w");
1033
                    if (!f) {
1034
                        perror(logfilename);
1035
                        exit(1);
1036
                    }
1037
                    ost->logfile = f;
1038
                } else {
1039
                    /* read the log file */
1040
                    f = fopen(logfilename, "r");
1041
                    if (!f) {
1042
                        perror(logfilename);
1043
                        exit(1);
1044
                    }
1045
                    fseek(f, 0, SEEK_END);
1046
                    size = ftell(f);
1047
                    fseek(f, 0, SEEK_SET);
1048
                    logbuffer = av_malloc(size + 1);
1049
                    if (!logbuffer) {
1050
                        fprintf(stderr, "Could not allocate log buffer\n");
1051
                        exit(1);
1052
                    }
1053
                    fread(logbuffer, 1, size, f);
1054
                    fclose(f);
1055
                    logbuffer[size] = '\0';
1056
                    codec->stats_in = logbuffer;
1057
                }
1058
            }
1059
        }
1060
    }
1061

    
1062
    /* dump the file output parameters - cannot be done before in case
1063
       of stream copy */
1064
    for(i=0;i<nb_output_files;i++) {
1065
        dump_format(output_files[i], i, output_files[i]->filename, 1);
1066
    }
1067

    
1068
    /* dump the stream mapping */
1069
    fprintf(stderr, "Stream mapping:\n");
1070
    for(i=0;i<nb_ostreams;i++) {
1071
        ost = ost_table[i];
1072
        fprintf(stderr, "  Stream #%d.%d -> #%d.%d\n",
1073
                ist_table[ost->source_index]->file_index,
1074
                ist_table[ost->source_index]->index,
1075
                ost->file_index, 
1076
                ost->index);
1077
    }
1078

    
1079
    /* open each encoder */
1080
    for(i=0;i<nb_ostreams;i++) {
1081
        ost = ost_table[i];
1082
        if (ost->encoding_needed) {
1083
            AVCodec *codec;
1084
            codec = avcodec_find_encoder(ost->st->codec.codec_id);
1085
            if (!codec) {
1086
                fprintf(stderr, "Unsupported codec for output stream #%d.%d\n", 
1087
                        ost->file_index, ost->index);
1088
                exit(1);
1089
            }
1090
            if (avcodec_open(&ost->st->codec, codec) < 0) {
1091
                fprintf(stderr, "Error while opening codec for stream #%d.%d - maybe incorrect parameters such as bit_rate, rate, width or height\n", 
1092
                        ost->file_index, ost->index);
1093
                exit(1);
1094
            }
1095
        }
1096
    }
1097

    
1098
    /* open each decoder */
1099
    for(i=0;i<nb_istreams;i++) {
1100
        ist = ist_table[i];
1101
        if (ist->decoding_needed) {
1102
            AVCodec *codec;
1103
            codec = avcodec_find_decoder(ist->st->codec.codec_id);
1104
            if (!codec) {
1105
                fprintf(stderr, "Unsupported codec (id=%d) for input stream #%d.%d\n", 
1106
                        ist->st->codec.codec_id, ist->file_index, ist->index);
1107
                exit(1);
1108
            }
1109
            if (avcodec_open(&ist->st->codec, codec) < 0) {
1110
                fprintf(stderr, "Error while opening codec for input stream #%d.%d\n", 
1111
                        ist->file_index, ist->index);
1112
                exit(1);
1113
            }
1114
            //if (ist->st->codec.codec_type == CODEC_TYPE_VIDEO)
1115
            //    ist->st->codec.flags |= CODEC_FLAG_REPEAT_FIELD;
1116
            ist->frame_decoded = 1;
1117
        }
1118
    }
1119

    
1120
    /* init pts */
1121
    for(i=0;i<nb_istreams;i++) {
1122
        ist = ist_table[i];
1123
        is = input_files[ist->file_index];
1124
        ist->pts = 0;
1125
        switch (ist->st->codec.codec_type) {
1126
        case CODEC_TYPE_AUDIO:
1127
            av_frac_init(&ist->next_pts, 
1128
                         0, 0, is->pts_num * ist->st->codec.sample_rate);
1129
            break;
1130
        case CODEC_TYPE_VIDEO:
1131
            av_frac_init(&ist->next_pts, 
1132
                         0, 0, is->pts_num * ist->st->codec.frame_rate);
1133
            break;
1134
        default:
1135
            break;
1136
        }
1137
    }
1138
    
1139
    /* compute buffer size max (should use a complete heuristic) */
1140
    for(i=0;i<nb_input_files;i++) {
1141
        file_table[i].buffer_size_max = 2048;
1142
    }
1143

    
1144
    /* open files and write file headers */
1145
    for(i=0;i<nb_output_files;i++) {
1146
        os = output_files[i];
1147
        if (av_write_header(os) < 0) {
1148
            fprintf(stderr, "Could not write header for output file #%d (incorrect codec paramters ?)\n", i);
1149
            ret = -EINVAL;
1150
            goto fail;
1151
        }
1152
    }
1153

    
1154
#ifndef CONFIG_WIN32
1155
    if ( !using_stdin )
1156
        fprintf(stderr, "Press [q] to stop encoding\n");
1157
#endif
1158
    term_init();
1159

    
1160
    stream_no_data = 0;
1161
    key = -1;
1162

    
1163
    for(; received_sigterm == 0;) {
1164
        int file_index, ist_index;
1165
        AVPacket pkt;
1166
        uint8_t *ptr;
1167
        int len;
1168
        uint8_t *data_buf;
1169
        int data_size, got_picture;
1170
        AVPicture picture;
1171
        short samples[AVCODEC_MAX_AUDIO_FRAME_SIZE / 2];
1172
        void *buffer_to_free;
1173
        double pts_min;
1174
        
1175
    redo:
1176
        /* if 'q' pressed, exits */
1177
        if (!using_stdin) {
1178
            /* read_key() returns 0 on EOF */
1179
            key = read_key();
1180
            if (key == 'q')
1181
                break;
1182
        }
1183

    
1184
        /* select the stream that we must read now by looking at the
1185
           smallest output pts */
1186
        file_index = -1;
1187
        pts_min = 1e10;
1188
        for(i=0;i<nb_ostreams;i++) {
1189
            double pts;
1190
            ost = ost_table[i];
1191
            os = output_files[ost->file_index];
1192
            ist = ist_table[ost->source_index];
1193
            pts = (double)ost->st->pts.val * os->pts_num / os->pts_den;
1194
            if (!file_table[ist->file_index].eof_reached && 
1195
                pts < pts_min) {
1196
                pts_min = pts;
1197
                file_index = ist->file_index;
1198
            }
1199
        }
1200
        /* if none, if is finished */
1201
        if (file_index < 0) {
1202
            break;
1203
        }
1204

    
1205
        /* finish if recording time exhausted */
1206
        if (recording_time > 0 && pts_min >= (recording_time / 1000000.0))
1207
            break;
1208

    
1209
        /* read a packet from it and output it in the fifo */
1210
        is = input_files[file_index];
1211
        if (av_read_packet(is, &pkt) < 0) {
1212
            file_table[file_index].eof_reached = 1;
1213
            continue;
1214
        }
1215
        if (!pkt.size) {
1216
            stream_no_data = is;
1217
        } else {
1218
            stream_no_data = 0;
1219
        }
1220
        if (do_hex_dump) {
1221
            printf("stream #%d, size=%d:\n", pkt.stream_index, pkt.size);
1222
            av_hex_dump(pkt.data, pkt.size);
1223
        }
1224
        /* the following test is needed in case new streams appear
1225
           dynamically in stream : we ignore them */
1226
        if (pkt.stream_index >= file_table[file_index].nb_streams)
1227
            goto discard_packet;
1228
        ist_index = file_table[file_index].ist_index + pkt.stream_index;
1229
        ist = ist_table[ist_index];
1230
        if (ist->discard)
1231
            goto discard_packet;
1232

    
1233
        // printf("read #%d.%d size=%d\n", ist->file_index, ist->index, pkt.size);
1234

    
1235
        len = pkt.size;
1236
        ptr = pkt.data;
1237
        while (len > 0) {
1238
            /* decode the packet if needed */
1239
            data_buf = NULL; /* fail safe */
1240
            data_size = 0;
1241
            if (ist->decoding_needed) {
1242
                /* NOTE1: we only take into account the PTS if a new
1243
                   frame has begun (MPEG semantics) */
1244
                /* NOTE2: even if the fraction is not initialized,
1245
                   av_frac_set can be used to set the integer part */
1246
                if (ist->frame_decoded) { 
1247
                    /* If pts is unavailable -- we have to use synthetic one */
1248
                    if( pkt.pts != AV_NOPTS_VALUE )
1249
                    {
1250
                        ist->pts = ist->next_pts.val = pkt.pts;
1251
                    }
1252
                    else
1253
                    {
1254
                        ist->pts = ist->next_pts.val;
1255
                    }
1256
                    ist->frame_decoded = 0;
1257
                }
1258

    
1259
                switch(ist->st->codec.codec_type) {
1260
                case CODEC_TYPE_AUDIO:
1261
                    /* XXX: could avoid copy if PCM 16 bits with same
1262
                       endianness as CPU */
1263
                    ret = avcodec_decode_audio(&ist->st->codec, samples, &data_size,
1264
                                               ptr, len);
1265
                    if (ret < 0)
1266
                        goto fail_decode;
1267
                    /* Some bug in mpeg audio decoder gives */
1268
                    /* data_size < 0, it seems they are overflows */
1269
                    if (data_size <= 0) {
1270
                        /* no audio frame */
1271
                        ptr += ret;
1272
                        len -= ret;
1273
                        continue;
1274
                    }
1275
                    data_buf = (uint8_t *)samples;
1276
                    av_frac_add(&ist->next_pts, 
1277
                                is->pts_den * data_size / (2 * ist->st->codec.channels));
1278
                    break;
1279
                case CODEC_TYPE_VIDEO:
1280
                    {
1281
                        AVFrame big_picture;
1282

    
1283
                        data_size = (ist->st->codec.width * ist->st->codec.height * 3) / 2;
1284
                        ret = avcodec_decode_video(&ist->st->codec, 
1285
                                                   &big_picture, &got_picture, ptr, len);
1286
                        picture= *(AVPicture*)&big_picture;
1287
                        ist->st->quality= big_picture.quality;
1288
                        if (ret < 0) {
1289
                        fail_decode:
1290
                            fprintf(stderr, "Error while decoding stream #%d.%d\n",
1291
                                    ist->file_index, ist->index);
1292
                            av_free_packet(&pkt);
1293
                            goto redo;
1294
                        }
1295
                        if (!got_picture) {
1296
                            /* no picture yet */
1297
                            ptr += ret;
1298
                            len -= ret;
1299
                            continue;
1300
                        }
1301
                        av_frac_add(&ist->next_pts, 
1302
                                    is->pts_den * ist->st->codec.frame_rate_base);          
1303
                    }
1304
                    break;
1305
                default:
1306
                    goto fail_decode;
1307
                }
1308
            } else {
1309
                data_buf = ptr;
1310
                data_size = len;
1311
                ret = len;
1312
            }
1313
            ptr += ret;
1314
            len -= ret;
1315

    
1316
            buffer_to_free = 0;
1317
            if (ist->st->codec.codec_type == CODEC_TYPE_VIDEO) {
1318
                pre_process_video_frame(ist, &picture, &buffer_to_free);
1319
            }
1320

    
1321
            ist->frame_decoded = 1;
1322

    
1323
            /* frame rate emulation */
1324
            if (ist->st->codec.rate_emu) {
1325
                int64_t pts = av_rescale((int64_t) ist->frame * ist->st->codec.frame_rate_base, 1000000, ist->st->codec.frame_rate);
1326
                int64_t now = av_gettime() - ist->start;
1327
                if (pts > now)
1328
                    usleep(pts - now);
1329

    
1330
                ist->frame++;
1331
            }
1332

    
1333
#if 0
1334
            /* mpeg PTS deordering : if it is a P or I frame, the PTS
1335
               is the one of the next displayed one */
1336
            /* XXX: add mpeg4 too ? */
1337
            if (ist->st->codec.codec_id == CODEC_ID_MPEG1VIDEO) {
1338
                if (ist->st->codec.pict_type != B_TYPE) {
1339
                    int64_t tmp;
1340
                    tmp = ist->last_ip_pts;
1341
                    ist->last_ip_pts  = ist->frac_pts.val;
1342
                    ist->frac_pts.val = tmp;
1343
                }
1344
            }
1345
#endif
1346
            /* transcode raw format, encode packets and output them */
1347

    
1348
            for(i=0;i<nb_ostreams;i++) {
1349
                int frame_size;
1350

    
1351
                ost = ost_table[i];
1352
                if (ost->source_index == ist_index) {
1353
                    os = output_files[ost->file_index];
1354

    
1355
#if 0
1356
                    printf("%d: got pts=%f %f\n", i, pkt.pts / 90000.0, 
1357
                           (ist->pts - ost->st->pts.val) / 90000.0);
1358
#endif
1359
                    /* set the input output pts pairs */
1360
                    ost->sync_ipts = (double)ist->pts * is->pts_num / 
1361
                        is->pts_den;
1362
                    /* XXX: take into account the various fifos,
1363
                       in particular for audio */
1364
                    ost->sync_opts = ost->st->pts.val;
1365
                    //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); 
1366

    
1367
                    if (ost->encoding_needed) {
1368
                        switch(ost->st->codec.codec_type) {
1369
                        case CODEC_TYPE_AUDIO:
1370
                            do_audio_out(os, ost, ist, data_buf, data_size);
1371
                            break;
1372
                        case CODEC_TYPE_VIDEO:
1373
                            /* find an audio stream for synchro */
1374
                            {
1375
                                int i;
1376
                                AVOutputStream *audio_sync, *ost1;
1377
                                audio_sync = NULL;
1378
                                for(i=0;i<nb_ostreams;i++) {
1379
                                    ost1 = ost_table[i];
1380
                                    if (ost1->file_index == ost->file_index &&
1381
                                        ost1->st->codec.codec_type == CODEC_TYPE_AUDIO) {
1382
                                        audio_sync = ost1;
1383
                                        break;
1384
                                    }
1385
                                }
1386

    
1387
                                do_video_out(os, ost, ist, &picture, &frame_size, audio_sync);
1388
                                if (do_vstats && frame_size)
1389
                                    do_video_stats(os, ost, frame_size);
1390
                            }
1391
                            break;
1392
                        default:
1393
                            av_abort();
1394
                        }
1395
                    } else {
1396
                        AVFrame avframe;
1397
                                                
1398
                        /* no reencoding needed : output the packet directly */
1399
                        /* force the input stream PTS */
1400
                        
1401
                        memset(&avframe, 0, sizeof(AVFrame));
1402
                        ost->st->codec.coded_frame= &avframe;
1403
                        avframe.key_frame = pkt.flags & PKT_FLAG_KEY; 
1404
                        
1405
                        av_write_frame(os, ost->index, data_buf, data_size);
1406
                        ost->st->codec.frame_number++;
1407
                        ost->frame_number++;
1408
                    }
1409
                }
1410
            }
1411
            av_free(buffer_to_free);
1412
        }
1413
    discard_packet:
1414
        av_free_packet(&pkt);
1415
        
1416
        /* dump report by using the output first video and audio streams */
1417
        print_report(output_files, ost_table, nb_ostreams, 0);
1418
    }
1419
    term_exit();
1420

    
1421
    /* dump report by using the first video and audio streams */
1422
    print_report(output_files, ost_table, nb_ostreams, 1);
1423

    
1424
    /* close each encoder */
1425
    for(i=0;i<nb_ostreams;i++) {
1426
        ost = ost_table[i];
1427
        if (ost->encoding_needed) {
1428
            av_freep(&ost->st->codec.stats_in);
1429
            avcodec_close(&ost->st->codec);
1430
        }
1431
    }
1432
    
1433
    /* close each decoder */
1434
    for(i=0;i<nb_istreams;i++) {
1435
        ist = ist_table[i];
1436
        if (ist->decoding_needed) {
1437
            avcodec_close(&ist->st->codec);
1438
        }
1439
    }
1440
    
1441

    
1442
    /* write the trailer if needed and close file */
1443
    for(i=0;i<nb_output_files;i++) {
1444
        os = output_files[i];
1445
        av_write_trailer(os);
1446
    }
1447
    /* finished ! */
1448
    
1449
    ret = 0;
1450
 fail1:
1451
    av_free(file_table);
1452

    
1453
    if (ist_table) {
1454
        for(i=0;i<nb_istreams;i++) {
1455
            ist = ist_table[i];
1456
            av_free(ist);
1457
        }
1458
        av_free(ist_table);
1459
    }
1460
    if (ost_table) {
1461
        for(i=0;i<nb_ostreams;i++) {
1462
            ost = ost_table[i];
1463
            if (ost) {
1464
                if (ost->logfile) {
1465
                    fclose(ost->logfile);
1466
                    ost->logfile = NULL;
1467
                }
1468
                fifo_free(&ost->fifo); /* works even if fifo is not
1469
                                          initialized but set to zero */
1470
                av_free(ost->pict_tmp.data[0]);
1471
                if (ost->video_resample)
1472
                    img_resample_close(ost->img_resample_ctx);
1473
                if (ost->audio_resample)
1474
                    audio_resample_close(ost->resample);
1475
                av_free(ost);
1476
            }
1477
        }
1478
        av_free(ost_table);
1479
    }
1480
    return ret;
1481
 fail:
1482
    ret = -ENOMEM;
1483
    goto fail1;
1484
}
1485

    
1486
#if 0
1487
int file_read(const char *filename)
1488
{
1489
    URLContext *h;
1490
    unsigned char buffer[1024];
1491
    int len, i;
1492

1493
    if (url_open(&h, filename, O_RDONLY) < 0) {
1494
        printf("could not open '%s'\n", filename);
1495
        return -1;
1496
    }
1497
    for(;;) {
1498
        len = url_read(h, buffer, sizeof(buffer));
1499
        if (len <= 0)
1500
            break;
1501
        for(i=0;i<len;i++) putchar(buffer[i]);
1502
    }
1503
    url_close(h);
1504
    return 0;
1505
}
1506
#endif
1507

    
1508
static void opt_image_format(const char *arg)
1509
{
1510
    AVImageFormat *f;
1511
    
1512
    for(f = first_image_format; f != NULL; f = f->next) {
1513
        if (!strcmp(arg, f->name))
1514
            break;
1515
    }
1516
    if (!f) {
1517
        fprintf(stderr, "Unknown image format: '%s'\n", arg);
1518
        exit(1);
1519
    }
1520
    image_format = f;
1521
}
1522

    
1523
static void opt_format(const char *arg)
1524
{
1525
    /* compatibility stuff for pgmyuv */
1526
    if (!strcmp(arg, "pgmyuv")) {
1527
        opt_image_format(arg);
1528
        arg = "image";
1529
    }
1530

    
1531
    file_iformat = av_find_input_format(arg);
1532
    file_oformat = guess_format(arg, NULL, NULL);
1533
    if (!file_iformat && !file_oformat) {
1534
        fprintf(stderr, "Unknown input or output format: %s\n", arg);
1535
        exit(1);
1536
    }
1537
}
1538

    
1539
static void opt_video_bitrate(const char *arg)
1540
{
1541
    video_bit_rate = atoi(arg) * 1000;
1542
}
1543

    
1544
static void opt_video_bitrate_tolerance(const char *arg)
1545
{
1546
    video_bit_rate_tolerance = atoi(arg) * 1000;
1547
}
1548

    
1549
static void opt_video_bitrate_max(const char *arg)
1550
{
1551
    video_rc_max_rate = atoi(arg) * 1000;
1552
}
1553

    
1554
static void opt_video_bitrate_min(const char *arg)
1555
{
1556
    video_rc_min_rate = atoi(arg) * 1000;
1557
}
1558

    
1559
static void opt_video_buffer_size(const char *arg)
1560
{
1561
    video_rc_buffer_size = atoi(arg) * 1000;
1562
}
1563

    
1564
static void opt_video_rc_eq(char *arg)
1565
{
1566
    video_rc_eq = arg;
1567
}
1568

    
1569
static void opt_video_rc_override_string(char *arg)
1570
{
1571
    video_rc_override_string = arg;
1572
}
1573

    
1574

    
1575
static void opt_workaround_bugs(const char *arg)
1576
{
1577
    workaround_bugs = atoi(arg);
1578
}
1579

    
1580
static void opt_dct_algo(const char *arg)
1581
{
1582
    dct_algo = atoi(arg);
1583
}
1584

    
1585
static void opt_idct_algo(const char *arg)
1586
{
1587
    idct_algo = atoi(arg);
1588
}
1589

    
1590

    
1591
static void opt_error_resilience(const char *arg)
1592
{
1593
    error_resilience = atoi(arg);
1594
}
1595

    
1596
static void opt_error_concealment(const char *arg)
1597
{
1598
    error_concealment = atoi(arg);
1599
}
1600

    
1601
static void opt_debug(const char *arg)
1602
{
1603
    debug = atoi(arg);
1604
}
1605

    
1606
static void opt_verbose(const char *arg)
1607
{
1608
    verbose = atoi(arg);
1609
}
1610

    
1611
static void opt_frame_rate(const char *arg)
1612
{
1613
    if (parse_frame_rate(&frame_rate, &frame_rate_base, arg) < 0) {
1614
        fprintf(stderr, "Incorrect frame rate\n");
1615
        exit(1);
1616
    }
1617
}
1618

    
1619
static void opt_frame_crop_top(const char *arg)
1620
{
1621
    frame_topBand = atoi(arg); 
1622
    if (frame_topBand < 0) {
1623
        fprintf(stderr, "Incorrect top crop size\n");
1624
        exit(1);
1625
    }
1626
    if ((frame_topBand % 2) != 0) {
1627
        fprintf(stderr, "Top crop size must be a multiple of 2\n");
1628
        exit(1);
1629
    }
1630
    if ((frame_topBand) >= frame_height){
1631
            fprintf(stderr, "Vertical crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
1632
        exit(1);
1633
    }
1634
    frame_height -= frame_topBand;
1635
}
1636

    
1637
static void opt_frame_crop_bottom(const char *arg)
1638
{
1639
    frame_bottomBand = atoi(arg);
1640
    if (frame_bottomBand < 0) {
1641
        fprintf(stderr, "Incorrect bottom crop size\n");
1642
        exit(1);
1643
    }
1644
    if ((frame_bottomBand % 2) != 0) {
1645
        fprintf(stderr, "Bottom crop size must be a multiple of 2\n");
1646
        exit(1);        
1647
    }
1648
    if ((frame_bottomBand) >= frame_height){
1649
            fprintf(stderr, "Vertical crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
1650
        exit(1);
1651
    }
1652
    frame_height -= frame_bottomBand;
1653
}
1654

    
1655
static void opt_frame_crop_left(const char *arg)
1656
{
1657
    frame_leftBand = atoi(arg);
1658
    if (frame_leftBand < 0) {
1659
        fprintf(stderr, "Incorrect left crop size\n");
1660
        exit(1);
1661
    }
1662
    if ((frame_leftBand % 2) != 0) {
1663
        fprintf(stderr, "Left crop size must be a multiple of 2\n");
1664
        exit(1);
1665
    }
1666
    if ((frame_leftBand) >= frame_width){
1667
            fprintf(stderr, "Horizontal crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
1668
        exit(1);
1669
    }
1670
    frame_width -= frame_leftBand;
1671
}
1672

    
1673
static void opt_frame_crop_right(const char *arg)
1674
{
1675
    frame_rightBand = atoi(arg);
1676
    if (frame_rightBand < 0) {
1677
        fprintf(stderr, "Incorrect right crop size\n");
1678
        exit(1);
1679
    }
1680
    if ((frame_rightBand % 2) != 0) {
1681
        fprintf(stderr, "Right crop size must be a multiple of 2\n");
1682
        exit(1);        
1683
    }
1684
    if ((frame_rightBand) >= frame_width){
1685
            fprintf(stderr, "Horizontal crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
1686
        exit(1);
1687
    }
1688
    frame_width -= frame_rightBand;
1689
}
1690

    
1691
static void opt_frame_size(const char *arg)
1692
{
1693
    if (parse_image_size(&frame_width, &frame_height, arg) < 0) {
1694
        fprintf(stderr, "Incorrect frame size\n");
1695
        exit(1);
1696
    }
1697
    if ((frame_width % 2) != 0 || (frame_height % 2) != 0) {
1698
        fprintf(stderr, "Frame size must be a multiple of 2\n");
1699
        exit(1);
1700
    }
1701
}
1702

    
1703
static void opt_frame_pix_fmt(const char *arg)
1704
{
1705
    frame_pix_fmt = avcodec_get_pix_fmt(arg);
1706
}
1707

    
1708
static void opt_frame_aspect_ratio(const char *arg)
1709
{
1710
    int x = 0, y = 0;
1711
    double ar = 0;
1712
    const char *p;
1713
    
1714
    p = strchr(arg, ':');
1715
    if (p) {
1716
        x = strtol(arg, (char **)&arg, 10);
1717
        if (arg == p)
1718
            y = strtol(arg+1, (char **)&arg, 10);
1719
        if (x > 0 && y > 0)
1720
            ar = (double)x / (double)y;
1721
    } else
1722
        ar = strtod(arg, (char **)&arg);
1723

    
1724
    if (!ar) {
1725
        fprintf(stderr, "Incorrect aspect ratio specification.\n");
1726
        exit(1);
1727
    }
1728
    frame_aspect_ratio = ar;
1729
}
1730

    
1731
static void opt_gop_size(const char *arg)
1732
{
1733
    gop_size = atoi(arg);
1734
}
1735

    
1736
static void opt_b_frames(const char *arg)
1737
{
1738
    b_frames = atoi(arg);
1739
    if (b_frames > FF_MAX_B_FRAMES) {
1740
        fprintf(stderr, "\nCannot have more than %d B frames, increase FF_MAX_B_FRAMES.\n", FF_MAX_B_FRAMES);
1741
        exit(1);
1742
    } else if (b_frames < 1) {
1743
        fprintf(stderr, "\nNumber of B frames must be higher than 0\n");
1744
        exit(1);
1745
    }
1746
}
1747

    
1748
static void opt_mb_decision(const char *arg)
1749
{
1750
    mb_decision = atoi(arg);
1751
}
1752

    
1753
static void opt_qscale(const char *arg)
1754
{
1755
    video_qscale = atoi(arg);
1756
    if (video_qscale < 0 ||
1757
        video_qscale > 31) {
1758
        fprintf(stderr, "qscale must be >= 1 and <= 31\n");
1759
        exit(1);
1760
    }
1761
}
1762

    
1763
static void opt_qmin(const char *arg)
1764
{
1765
    video_qmin = atoi(arg);
1766
    if (video_qmin < 0 ||
1767
        video_qmin > 31) {
1768
        fprintf(stderr, "qmin must be >= 1 and <= 31\n");
1769
        exit(1);
1770
    }
1771
}
1772

    
1773
static void opt_qmax(const char *arg)
1774
{
1775
    video_qmax = atoi(arg);
1776
    if (video_qmax < 0 ||
1777
        video_qmax > 31) {
1778
        fprintf(stderr, "qmax must be >= 1 and <= 31\n");
1779
        exit(1);
1780
    }
1781
}
1782

    
1783
static void opt_mb_qmin(const char *arg)
1784
{
1785
    video_mb_qmin = atoi(arg);
1786
    if (video_mb_qmin < 0 ||
1787
        video_mb_qmin > 31) {
1788
        fprintf(stderr, "qmin must be >= 1 and <= 31\n");
1789
        exit(1);
1790
    }
1791
}
1792

    
1793
static void opt_mb_qmax(const char *arg)
1794
{
1795
    video_mb_qmax = atoi(arg);
1796
    if (video_mb_qmax < 0 ||
1797
        video_mb_qmax > 31) {
1798
        fprintf(stderr, "qmax must be >= 1 and <= 31\n");
1799
        exit(1);
1800
    }
1801
}
1802

    
1803
static void opt_qdiff(const char *arg)
1804
{
1805
    video_qdiff = atoi(arg);
1806
    if (video_qdiff < 0 ||
1807
        video_qdiff > 31) {
1808
        fprintf(stderr, "qdiff must be >= 1 and <= 31\n");
1809
        exit(1);
1810
    }
1811
}
1812

    
1813
static void opt_qblur(const char *arg)
1814
{
1815
    video_qblur = atof(arg);
1816
}
1817

    
1818
static void opt_qcomp(const char *arg)
1819
{
1820
    video_qcomp = atof(arg);
1821
}
1822

    
1823
static void opt_rc_initial_cplx(const char *arg)
1824
{
1825
    video_rc_initial_cplx = atof(arg);
1826
}
1827
static void opt_b_qfactor(const char *arg)
1828
{
1829
    video_b_qfactor = atof(arg);
1830
}
1831
static void opt_i_qfactor(const char *arg)
1832
{
1833
    video_i_qfactor = atof(arg);
1834
}
1835
static void opt_b_qoffset(const char *arg)
1836
{
1837
    video_b_qoffset = atof(arg);
1838
}
1839
static void opt_i_qoffset(const char *arg)
1840
{
1841
    video_i_qoffset = atof(arg);
1842
}
1843

    
1844
static void opt_packet_size(const char *arg)
1845
{
1846
    packet_size= atoi(arg);
1847
}
1848

    
1849
static void opt_strict(const char *arg)
1850
{
1851
    strict= atoi(arg);
1852
}
1853

    
1854
static void opt_audio_bitrate(const char *arg)
1855
{
1856
    audio_bit_rate = atoi(arg) * 1000;
1857
}
1858

    
1859
static void opt_audio_rate(const char *arg)
1860
{
1861
    audio_sample_rate = atoi(arg);
1862
}
1863

    
1864
static void opt_audio_channels(const char *arg)
1865
{
1866
    audio_channels = atoi(arg);
1867
}
1868

    
1869
static void opt_video_device(const char *arg)
1870
{
1871
    video_device = av_strdup(arg);
1872
}
1873

    
1874
static void opt_video_channel(const char *arg)
1875
{
1876
    video_channel = strtol(arg, NULL, 0);
1877
}
1878

    
1879
static void opt_video_standard(const char *arg)
1880
{
1881
    video_standard = av_strdup(arg);
1882
}
1883

    
1884
static void opt_audio_device(const char *arg)
1885
{
1886
    audio_device = av_strdup(arg);
1887
}
1888

    
1889
static void opt_dv1394(const char *arg)
1890
{
1891
    video_grab_format = "dv1394";
1892
    audio_grab_format = NULL;
1893
}
1894

    
1895
static void opt_audio_codec(const char *arg)
1896
{
1897
    AVCodec *p;
1898

    
1899
    if (!strcmp(arg, "copy")) {
1900
        audio_stream_copy = 1;
1901
    } else {
1902
        p = first_avcodec;
1903
        while (p) {
1904
            if (!strcmp(p->name, arg) && p->type == CODEC_TYPE_AUDIO)
1905
                break;
1906
            p = p->next;
1907
        }
1908
        if (p == NULL) {
1909
            fprintf(stderr, "Unknown audio codec '%s'\n", arg);
1910
            exit(1);
1911
        } else {
1912
            audio_codec_id = p->id;
1913
        }
1914
    }
1915
}
1916

    
1917
static void add_frame_hooker(const char *arg)
1918
{
1919
    int argc = 0;
1920
    char *argv[64];
1921
    int i;
1922
    char *args = av_strdup(arg);
1923

    
1924
    using_vhook = 1;
1925

    
1926
    argv[0] = strtok(args, " ");
1927
    while (argc < 62 && (argv[++argc] = strtok(NULL, " "))) {
1928
    }
1929

    
1930
    i = frame_hook_add(argc, argv);
1931

    
1932
    if (i != 0) {
1933
        fprintf(stderr, "Failed to add video hook function: %s\n", arg);
1934
        exit(1);
1935
    }
1936
}
1937

    
1938
const char *motion_str[] = {
1939
    "zero",
1940
    "full",
1941
    "log",
1942
    "phods",
1943
    "epzs",
1944
    "x1",
1945
    NULL,
1946
};
1947

    
1948
static void opt_motion_estimation(const char *arg)
1949
{
1950
    const char **p;
1951
    p = motion_str;
1952
    for(;;) {
1953
        if (!*p) {
1954
            fprintf(stderr, "Unknown motion estimation method '%s'\n", arg);
1955
            exit(1);
1956
        }
1957
        if (!strcmp(*p, arg))
1958
            break;
1959
        p++;
1960
    }
1961
    me_method = (p - motion_str) + 1;
1962
}
1963

    
1964
static void opt_video_codec(const char *arg)
1965
{
1966
    AVCodec *p;
1967

    
1968
    if (!strcmp(arg, "copy")) {
1969
        video_stream_copy = 1;
1970
    } else {
1971
        p = first_avcodec;
1972
        while (p) {
1973
            if (!strcmp(p->name, arg) && p->type == CODEC_TYPE_VIDEO)
1974
                break;
1975
            p = p->next;
1976
        }
1977
        if (p == NULL) {
1978
            fprintf(stderr, "Unknown video codec '%s'\n", arg);
1979
            exit(1);
1980
        } else {
1981
            video_codec_id = p->id;
1982
        }
1983
    }
1984
}
1985

    
1986
static void opt_map(const char *arg)
1987
{
1988
    AVStreamMap *m;
1989
    const char *p;
1990

    
1991
    p = arg;
1992
    m = &stream_maps[nb_stream_maps++];
1993

    
1994
    m->file_index = strtol(arg, (char **)&p, 0);
1995
    if (*p)
1996
        p++;
1997

    
1998
    m->stream_index = strtol(p, (char **)&p, 0);
1999
}
2000

    
2001
static void opt_recording_time(const char *arg)
2002
{
2003
    recording_time = parse_date(arg, 1);
2004
}
2005

    
2006
static void opt_input_file(const char *filename)
2007
{
2008
    AVFormatContext *ic;
2009
    AVFormatParameters params, *ap = &params;
2010
    int err, i, ret, rfps, rfps_base;
2011

    
2012
    if (!strcmp(filename, "-"))
2013
        filename = "pipe:";
2014

    
2015
    using_stdin |= !strcmp(filename, "pipe:" ) || 
2016
                   !strcmp( filename, "/dev/stdin" );
2017

    
2018
    /* get default parameters from command line */
2019
    memset(ap, 0, sizeof(*ap));
2020
    ap->sample_rate = audio_sample_rate;
2021
    ap->channels = audio_channels;
2022
    ap->frame_rate = frame_rate;
2023
    ap->frame_rate_base = frame_rate_base;
2024
    ap->width = frame_width;
2025
    ap->height = frame_height;
2026
    ap->image_format = image_format;
2027
    ap->pix_fmt = frame_pix_fmt;
2028

    
2029
    /* open the input file with generic libav function */
2030
    err = av_open_input_file(&ic, filename, file_iformat, 0, ap);
2031
    if (err < 0) {
2032
        print_error(filename, err);
2033
        exit(1);
2034
    }
2035
    
2036
    /* If not enough info to get the stream parameters, we decode the
2037
       first frames to get it. (used in mpeg case for example) */
2038
    ret = av_find_stream_info(ic);
2039
    if (ret < 0) {
2040
        fprintf(stderr, "%s: could not find codec parameters\n", filename);
2041
        exit(1);
2042
    }
2043

    
2044
    /* update the current parameters so that they match the one of the input stream */
2045
    for(i=0;i<ic->nb_streams;i++) {
2046
        AVCodecContext *enc = &ic->streams[i]->codec;
2047
        switch(enc->codec_type) {
2048
        case CODEC_TYPE_AUDIO:
2049
            //fprintf(stderr, "\nInput Audio channels: %d", enc->channels);
2050
            audio_channels = enc->channels;
2051
            audio_sample_rate = enc->sample_rate;
2052
            break;
2053
        case CODEC_TYPE_VIDEO:
2054
            frame_height = enc->height;
2055
            frame_width = enc->width;
2056
            frame_aspect_ratio = enc->aspect_ratio;
2057
            frame_pix_fmt = enc->pix_fmt;
2058
            rfps      = ic->streams[i]->r_frame_rate;
2059
            rfps_base = ic->streams[i]->r_frame_rate_base;
2060
            enc->workaround_bugs = workaround_bugs;
2061
            enc->error_resilience = error_resilience; 
2062
            enc->error_concealment = error_concealment; 
2063
            enc->idct_algo= idct_algo;
2064
            enc->debug= debug;
2065
/*            if(enc->codec->capabilities & CODEC_CAP_TRUNCATED)
2066
                enc->flags|= CODEC_FLAG_TRUNCATED; */
2067
            if(/*enc->codec_id==CODEC_ID_MPEG4 || */enc->codec_id==CODEC_ID_MPEG1VIDEO || enc->codec_id==CODEC_ID_H264)
2068
                enc->flags|= CODEC_FLAG_TRUNCATED;
2069
            
2070
            if(bitexact)
2071
                enc->flags|= CODEC_FLAG_BITEXACT;
2072

    
2073
            assert(enc->frame_rate_base == rfps_base); // should be true for now
2074
            if (enc->frame_rate != rfps) { 
2075
                fprintf(stderr,"\nSeems that stream %d comes from film source: %2.2f->%2.2f\n",
2076
                    i, (float)enc->frame_rate / enc->frame_rate_base,
2077
                    (float)rfps / rfps_base);
2078
            }
2079
            /* update the current frame rate to match the stream frame rate */
2080
            frame_rate      = rfps;
2081
            frame_rate_base = rfps_base;
2082

    
2083
            enc->rate_emu = rate_emu;
2084
            break;
2085
        default:
2086
            av_abort();
2087
        }
2088
    }
2089
    
2090
    input_files[nb_input_files] = ic;
2091
    /* dump the file content */
2092
    dump_format(ic, nb_input_files, filename, 0);
2093
    nb_input_files++;
2094
    file_iformat = NULL;
2095
    file_oformat = NULL;
2096
    image_format = NULL;
2097

    
2098
    rate_emu = 0;
2099
}
2100

    
2101
static void check_audio_video_inputs(int *has_video_ptr, int *has_audio_ptr)
2102
{
2103
    int has_video, has_audio, i, j;
2104
    AVFormatContext *ic;
2105

    
2106
    has_video = 0;
2107
    has_audio = 0;
2108
    for(j=0;j<nb_input_files;j++) {
2109
        ic = input_files[j];
2110
        for(i=0;i<ic->nb_streams;i++) {
2111
            AVCodecContext *enc = &ic->streams[i]->codec;
2112
            switch(enc->codec_type) {
2113
            case CODEC_TYPE_AUDIO:
2114
                has_audio = 1;
2115
                break;
2116
            case CODEC_TYPE_VIDEO:
2117
                has_video = 1;
2118
                break;
2119
            default:
2120
                av_abort();
2121
            }
2122
        }
2123
    }
2124
    *has_video_ptr = has_video;
2125
    *has_audio_ptr = has_audio;
2126
}
2127

    
2128
static void opt_output_file(const char *filename)
2129
{
2130
    AVStream *st;
2131
    AVFormatContext *oc;
2132
    int use_video, use_audio, nb_streams, input_has_video, input_has_audio;
2133
    int codec_id;
2134
    AVFormatParameters params, *ap = &params;
2135

    
2136
    if (!strcmp(filename, "-"))
2137
        filename = "pipe:";
2138

    
2139
    oc = av_mallocz(sizeof(AVFormatContext));
2140

    
2141
    if (!file_oformat) {
2142
        file_oformat = guess_format(NULL, filename, NULL);
2143
        if (!file_oformat) {
2144
            fprintf(stderr, "Unable for find a suitable output format for '%s'\n",
2145
                    filename);
2146
            exit(1);
2147
        }
2148
    }
2149
    
2150
    oc->oformat = file_oformat;
2151

    
2152
    if (!strcmp(file_oformat->name, "ffm") && 
2153
        strstart(filename, "http:", NULL)) {
2154
        /* special case for files sent to ffserver: we get the stream
2155
           parameters from ffserver */
2156
        if (read_ffserver_streams(oc, filename) < 0) {
2157
            fprintf(stderr, "Could not read stream parameters from '%s'\n", filename);
2158
            exit(1);
2159
        }
2160
    } else {
2161
        use_video = file_oformat->video_codec != CODEC_ID_NONE;
2162
        use_audio = file_oformat->audio_codec != CODEC_ID_NONE;
2163

    
2164
        /* disable if no corresponding type found and at least one
2165
           input file */
2166
        if (nb_input_files > 0) {
2167
            check_audio_video_inputs(&input_has_video, &input_has_audio);
2168
            if (!input_has_video)
2169
                use_video = 0;
2170
            if (!input_has_audio)
2171
                use_audio = 0;
2172
        }
2173

    
2174
        /* manual disable */
2175
        if (audio_disable) {
2176
            use_audio = 0;
2177
        }
2178
        if (video_disable) {
2179
            use_video = 0;
2180
        }
2181
        
2182
        nb_streams = 0;
2183
        if (use_video) {
2184
            AVCodecContext *video_enc;
2185
            
2186
            st = av_mallocz(sizeof(AVStream));
2187
            if (!st) {
2188
                fprintf(stderr, "Could not alloc stream\n");
2189
                exit(1);
2190
            }
2191
            avcodec_get_context_defaults(&st->codec);
2192

    
2193
            video_enc = &st->codec;
2194
            if (video_stream_copy) {
2195
                st->stream_copy = 1;
2196
                video_enc->codec_type = CODEC_TYPE_VIDEO;
2197
            } else {
2198
                char *p;
2199
                int i;
2200
            
2201
                codec_id = file_oformat->video_codec;
2202
                if (video_codec_id != CODEC_ID_NONE)
2203
                    codec_id = video_codec_id;
2204
                
2205
                video_enc->codec_id = codec_id;
2206
                
2207
                video_enc->bit_rate = video_bit_rate;
2208
                video_enc->bit_rate_tolerance = video_bit_rate_tolerance;
2209
                video_enc->frame_rate = frame_rate; 
2210
                video_enc->frame_rate_base = frame_rate_base; 
2211
                
2212
                video_enc->width = frame_width;
2213
                video_enc->height = frame_height;
2214
                video_enc->aspect_ratio = frame_aspect_ratio;
2215
                video_enc->pix_fmt = frame_pix_fmt;
2216

    
2217
                if (!intra_only)
2218
                    video_enc->gop_size = gop_size;
2219
                else
2220
                    video_enc->gop_size = 0;
2221
                if (video_qscale || same_quality) {
2222
                    video_enc->flags |= CODEC_FLAG_QSCALE;
2223
                    st->quality = video_qscale;
2224
                }
2225
                
2226
                if(bitexact)
2227
                    video_enc->flags |= CODEC_FLAG_BITEXACT;
2228

    
2229
                video_enc->mb_decision = mb_decision;
2230
                
2231
                if (use_umv) {
2232
                    video_enc->flags |= CODEC_FLAG_H263P_UMV;
2233
                }
2234
                   if (use_aic) {
2235
                    video_enc->flags |= CODEC_FLAG_H263P_AIC;
2236
                }
2237
                if (use_4mv) {
2238
                    video_enc->mb_decision = FF_MB_DECISION_BITS; //FIXME remove
2239
                    video_enc->flags |= CODEC_FLAG_4MV;
2240
                }
2241
            
2242
                if(use_part)
2243
                    video_enc->flags |= CODEC_FLAG_PART;
2244
               
2245
            
2246
                if (b_frames) {
2247
                    video_enc->max_b_frames = b_frames;
2248
                    video_enc->b_frame_strategy = 0;
2249
                    video_enc->b_quant_factor = 2.0;
2250
                }
2251
            
2252
                video_enc->qmin = video_qmin;
2253
                video_enc->qmax = video_qmax;
2254
                video_enc->mb_qmin = video_mb_qmin;
2255
                video_enc->mb_qmax = video_mb_qmax;
2256
                video_enc->max_qdiff = video_qdiff;
2257
                video_enc->qblur = video_qblur;
2258
                video_enc->qcompress = video_qcomp;
2259
                video_enc->rc_eq = video_rc_eq;
2260
                video_enc->debug= debug;
2261
                
2262
                p= video_rc_override_string;
2263
                for(i=0; p; i++){
2264
                    int start, end, q;
2265
                    int e=sscanf(p, "%d,%d,%d", &start, &end, &q);
2266
                    if(e!=3){
2267
                        fprintf(stderr, "error parsing rc_override\n");
2268
                        exit(1);
2269
                    }
2270
                    video_enc->rc_override= 
2271
                        av_realloc(video_enc->rc_override, 
2272
                                   sizeof(RcOverride)*(i+1));
2273
                    video_enc->rc_override[i].start_frame= start;
2274
                    video_enc->rc_override[i].end_frame  = end;
2275
                    if(q>0){
2276
                        video_enc->rc_override[i].qscale= q;
2277
                        video_enc->rc_override[i].quality_factor= 1.0;
2278
                    }
2279
                    else{
2280
                        video_enc->rc_override[i].qscale= 0;
2281
                        video_enc->rc_override[i].quality_factor= -q/100.0;
2282
                    }
2283
                    p= strchr(p, '/');
2284
                    if(p) p++;
2285
                }
2286
                video_enc->rc_override_count=i;
2287

    
2288
                video_enc->rc_max_rate = video_rc_max_rate;
2289
                video_enc->rc_min_rate = video_rc_min_rate;
2290
                video_enc->rc_buffer_size = video_rc_buffer_size;
2291
                video_enc->rc_buffer_aggressivity= video_rc_buffer_aggressivity;
2292
                video_enc->rc_initial_cplx= video_rc_initial_cplx;
2293
                video_enc->i_quant_factor = video_i_qfactor;
2294
                video_enc->b_quant_factor = video_b_qfactor;
2295
                video_enc->i_quant_offset = video_i_qoffset;
2296
                video_enc->b_quant_offset = video_b_qoffset;
2297
                video_enc->dct_algo = dct_algo;
2298
                video_enc->idct_algo = idct_algo;
2299
                video_enc->strict_std_compliance = strict;
2300
                if(packet_size){
2301
                    video_enc->rtp_mode= 1;
2302
                    video_enc->rtp_payload_size= packet_size;
2303
                }
2304
            
2305
                if (do_psnr)
2306
                    video_enc->flags|= CODEC_FLAG_PSNR;
2307
            
2308
                video_enc->me_method = me_method;
2309

    
2310
                /* two pass mode */
2311
                if (do_pass) {
2312
                    if (do_pass == 1) {
2313
                        video_enc->flags |= CODEC_FLAG_PASS1;
2314
                    } else {
2315
                        video_enc->flags |= CODEC_FLAG_PASS2;
2316
                    }
2317
                }
2318
            }
2319
            oc->streams[nb_streams] = st;
2320
            nb_streams++;
2321
        }
2322
    
2323
        if (use_audio) {
2324
            AVCodecContext *audio_enc;
2325

    
2326
            st = av_mallocz(sizeof(AVStream));
2327
            if (!st) {
2328
                fprintf(stderr, "Could not alloc stream\n");
2329
                exit(1);
2330
            }
2331
            avcodec_get_context_defaults(&st->codec);
2332

    
2333
            audio_enc = &st->codec;
2334
            audio_enc->codec_type = CODEC_TYPE_AUDIO;
2335
            if (audio_stream_copy) {
2336
                st->stream_copy = 1;
2337
            } else {
2338
                codec_id = file_oformat->audio_codec;
2339
                if (audio_codec_id != CODEC_ID_NONE)
2340
                    codec_id = audio_codec_id;
2341
                audio_enc->codec_id = codec_id;
2342
                
2343
                audio_enc->bit_rate = audio_bit_rate;
2344
                audio_enc->sample_rate = audio_sample_rate;
2345
                /* For audio codecs other than AC3 we limit */
2346
                /* the number of coded channels to stereo   */
2347
                if (audio_channels > 2 && codec_id != CODEC_ID_AC3) {
2348
                    audio_enc->channels = 2;
2349
                } else
2350
                    audio_enc->channels = audio_channels;
2351
            }
2352
            oc->streams[nb_streams] = st;
2353
            nb_streams++;
2354
        }
2355

    
2356
        oc->nb_streams = nb_streams;
2357

    
2358
        if (!nb_streams) {
2359
            fprintf(stderr, "No audio or video streams available\n");
2360
            exit(1);
2361
        }
2362

    
2363
        if (str_title)
2364
            pstrcpy(oc->title, sizeof(oc->title), str_title);
2365
        if (str_author)
2366
            pstrcpy(oc->author, sizeof(oc->author), str_author);
2367
        if (str_copyright)
2368
            pstrcpy(oc->copyright, sizeof(oc->copyright), str_copyright);
2369
        if (str_comment)
2370
            pstrcpy(oc->comment, sizeof(oc->comment), str_comment);
2371
    }
2372

    
2373
    output_files[nb_output_files++] = oc;
2374

    
2375
    strcpy(oc->filename, filename);
2376

    
2377
    /* check filename in case of an image number is expected */
2378
    if (oc->oformat->flags & AVFMT_NEEDNUMBER) {
2379
        if (filename_number_test(oc->filename) < 0) {
2380
            print_error(oc->filename, AVERROR_NUMEXPECTED);
2381
            exit(1);
2382
        }
2383
    }
2384

    
2385
    if (!(oc->oformat->flags & AVFMT_NOFILE)) {
2386
        /* test if it already exists to avoid loosing precious files */
2387
        if (!file_overwrite && 
2388
            (strchr(filename, ':') == NULL ||
2389
             strstart(filename, "file:", NULL))) {
2390
            if (url_exist(filename)) {
2391
                int c;
2392
                
2393
                if ( !using_stdin ) {
2394
                    fprintf(stderr,"File '%s' already exists. Overwrite ? [y/N] ", filename);
2395
                    fflush(stderr);
2396
                    c = getchar();
2397
                    if (toupper(c) != 'Y') {
2398
                        fprintf(stderr, "Not overwriting - exiting\n");
2399
                        exit(1);
2400
                    }
2401
                                }
2402
                                else {
2403
                    fprintf(stderr,"File '%s' already exists. Exiting.\n", filename);
2404
                    exit(1);
2405
                                }
2406
            }
2407
        }
2408
        
2409
        /* open the file */
2410
        if (url_fopen(&oc->pb, filename, URL_WRONLY) < 0) {
2411
            fprintf(stderr, "Could not open '%s'\n", filename);
2412
            exit(1);
2413
        }
2414
    }
2415

    
2416
    memset(ap, 0, sizeof(*ap));
2417
    ap->image_format = image_format;
2418
    if (av_set_parameters(oc, ap) < 0) {
2419
        fprintf(stderr, "%s: Invalid encoding parameters\n",
2420
                oc->filename);
2421
        exit(1);
2422
    }
2423

    
2424
    /* reset some options */
2425
    file_oformat = NULL;
2426
    file_iformat = NULL;
2427
    image_format = NULL;
2428
    audio_disable = 0;
2429
    video_disable = 0;
2430
    audio_codec_id = CODEC_ID_NONE;
2431
    video_codec_id = CODEC_ID_NONE;
2432
    audio_stream_copy = 0;
2433
    video_stream_copy = 0;
2434
}
2435

    
2436
/* prepare dummy protocols for grab */
2437
static void prepare_grab(void)
2438
{
2439
    int has_video, has_audio, i, j;
2440
    AVFormatContext *oc;
2441
    AVFormatContext *ic;
2442
    AVFormatParameters vp1, *vp = &vp1;
2443
    AVFormatParameters ap1, *ap = &ap1;
2444
    
2445
    /* see if audio/video inputs are needed */
2446
    has_video = 0;
2447
    has_audio = 0;
2448
    memset(ap, 0, sizeof(*ap));
2449
    memset(vp, 0, sizeof(*vp));
2450
    for(j=0;j<nb_output_files;j++) {
2451
        oc = output_files[j];
2452
        for(i=0;i<oc->nb_streams;i++) {
2453
            AVCodecContext *enc = &oc->streams[i]->codec;
2454
            switch(enc->codec_type) {
2455
            case CODEC_TYPE_AUDIO:
2456
                if (enc->sample_rate > ap->sample_rate)
2457
                    ap->sample_rate = enc->sample_rate;
2458
                if (enc->channels > ap->channels)
2459
                    ap->channels = enc->channels;
2460
                has_audio = 1;
2461
                break;
2462
            case CODEC_TYPE_VIDEO:
2463
                if (enc->width > vp->width)
2464
                    vp->width = enc->width;
2465
                if (enc->height > vp->height)
2466
                    vp->height = enc->height;
2467
                
2468
                assert(enc->frame_rate_base == DEFAULT_FRAME_RATE_BASE);
2469
                if (enc->frame_rate > vp->frame_rate){
2470
                    vp->frame_rate      = enc->frame_rate;
2471
                    vp->frame_rate_base = enc->frame_rate_base;
2472
                }
2473
                has_video = 1;
2474
                break;
2475
            default:
2476
                av_abort();
2477
            }
2478
        }
2479
    }
2480
    
2481
    if (has_video == 0 && has_audio == 0) {
2482
        fprintf(stderr, "Output file must have at least one audio or video stream\n");
2483
        exit(1);
2484
    }
2485
    
2486
    if (has_video) {
2487
        AVInputFormat *fmt1;
2488
        fmt1 = av_find_input_format(video_grab_format);
2489
        vp->device  = video_device;
2490
        vp->channel = video_channel;
2491
        vp->standard = video_standard;
2492
        if (av_open_input_file(&ic, "", fmt1, 0, vp) < 0) {
2493
            fprintf(stderr, "Could not find video grab device\n");
2494
            exit(1);
2495
        }
2496
        /* by now video grab has one stream */
2497
        ic->streams[0]->r_frame_rate      = vp->frame_rate;
2498
        ic->streams[0]->r_frame_rate_base = vp->frame_rate_base;
2499
        input_files[nb_input_files] = ic;
2500
        dump_format(ic, nb_input_files, "", 0);
2501
        nb_input_files++;
2502
    }
2503
    if (has_audio && audio_grab_format) {
2504
        AVInputFormat *fmt1;
2505
        fmt1 = av_find_input_format(audio_grab_format);
2506
        ap->device = audio_device;
2507
        if (av_open_input_file(&ic, "", fmt1, 0, ap) < 0) {
2508
            fprintf(stderr, "Could not find audio grab device\n");
2509
            exit(1);
2510
        }
2511
        input_files[nb_input_files] = ic;
2512
        dump_format(ic, nb_input_files, "", 0);
2513
        nb_input_files++;
2514
    }
2515
}
2516

    
2517
/* same option as mencoder */
2518
static void opt_pass(const char *pass_str)
2519
{
2520
    int pass;
2521
    pass = atoi(pass_str);
2522
    if (pass != 1 && pass != 2) {
2523
        fprintf(stderr, "pass number can be only 1 or 2\n");
2524
        exit(1);
2525
    }
2526
    do_pass = pass;
2527
}
2528

    
2529
#if defined(CONFIG_WIN32) || defined(CONFIG_OS2)
2530
static int64_t getutime(void)
2531
{
2532
  return av_gettime();
2533
}
2534
#else
2535
static int64_t getutime(void)
2536
{
2537
    struct rusage rusage;
2538

    
2539
    getrusage(RUSAGE_SELF, &rusage);
2540
    return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
2541
}
2542
#endif
2543

    
2544
extern int ffm_nopts;
2545

    
2546
static void opt_bitexact(void)
2547
{
2548
    bitexact=1;
2549
    /* disable generate of real time pts in ffm (need to be supressed anyway) */
2550
    ffm_nopts = 1;
2551
}
2552

    
2553
static void show_formats(void)
2554
{
2555
    AVInputFormat *ifmt;
2556
    AVOutputFormat *ofmt;
2557
    AVImageFormat *image_fmt;
2558
    URLProtocol *up;
2559
    AVCodec *p;
2560
    const char **pp;
2561

    
2562
    printf("Output audio/video file formats:");
2563
    for(ofmt = first_oformat; ofmt != NULL; ofmt = ofmt->next) {
2564
        printf(" %s", ofmt->name);
2565
    }
2566
    printf("\n");
2567

    
2568
    printf("Input audio/video file formats:");
2569
    for(ifmt = first_iformat; ifmt != NULL; ifmt = ifmt->next) {
2570
        printf(" %s", ifmt->name);
2571
    }
2572
    printf("\n");
2573

    
2574
    printf("Output image formats:");
2575
    for(image_fmt = first_image_format; image_fmt != NULL; 
2576
        image_fmt = image_fmt->next) {
2577
        if (image_fmt->img_write)
2578
            printf(" %s", image_fmt->name);
2579
    }
2580
    printf("\n");
2581

    
2582
    printf("Input image formats:");
2583
    for(image_fmt = first_image_format; image_fmt != NULL; 
2584
        image_fmt = image_fmt->next) {
2585
        if (image_fmt->img_read)
2586
            printf(" %s", image_fmt->name);
2587
    }
2588
    printf("\n");
2589

    
2590
    printf("Codecs:\n");
2591
    printf("  Encoders:");
2592
    for(p = first_avcodec; p != NULL; p = p->next) {
2593
        if (p->encode)
2594
            printf(" %s", p->name);
2595
    }
2596
    printf("\n");
2597

    
2598
    printf("  Decoders:");
2599
    for(p = first_avcodec; p != NULL; p = p->next) {
2600
        if (p->decode)
2601
            printf(" %s", p->name);
2602
    }
2603
    printf("\n");
2604

    
2605
    printf("Supported file protocols:");
2606
    for(up = first_protocol; up != NULL; up = up->next)
2607
        printf(" %s:", up->name);
2608
    printf("\n");
2609
    
2610
    printf("Frame size, frame rate abbreviations: ntsc pal qntsc qpal sntsc spal film ntsc-film sqcif qcif cif 4cif\n");
2611
    printf("Motion estimation methods:");
2612
    pp = motion_str;
2613
    while (*pp) {
2614
        printf(" %s", *pp);
2615
        if ((pp - motion_str + 1) == ME_ZERO) 
2616
            printf("(fastest)");
2617
        else if ((pp - motion_str + 1) == ME_FULL) 
2618
            printf("(slowest)");
2619
        else if ((pp - motion_str + 1) == ME_EPZS) 
2620
            printf("(default)");
2621
        pp++;
2622
    }
2623
    printf("\n");
2624
    exit(1);
2625
}
2626

    
2627
const OptionDef options[] = {
2628
    /* main options */
2629
    { "L", 0, {(void*)show_license}, "show license" },
2630
    { "h", 0, {(void*)show_help}, "show help" },
2631
    { "formats", 0, {(void*)show_formats}, "show available formats, codecs, protocols, ..." },
2632
    { "f", HAS_ARG, {(void*)opt_format}, "force format", "fmt" },
2633
    { "img", HAS_ARG, {(void*)opt_image_format}, "force image format", "img_fmt" },
2634
    { "i", HAS_ARG, {(void*)opt_input_file}, "input file name", "filename" },
2635
    { "y", OPT_BOOL, {(void*)&file_overwrite}, "overwrite output files" },
2636
    { "map", HAS_ARG | OPT_EXPERT, {(void*)opt_map}, "set input stream mapping", "file:stream" },
2637
    { "t", HAS_ARG, {(void*)opt_recording_time}, "set the recording time", "duration" },
2638
    { "title", HAS_ARG | OPT_STRING, {(void*)&str_title}, "set the title", "string" },
2639
    { "author", HAS_ARG | OPT_STRING, {(void*)&str_author}, "set the author", "string" },
2640
    { "copyright", HAS_ARG | OPT_STRING, {(void*)&str_copyright}, "set the copyright", "string" },
2641
    { "comment", HAS_ARG | OPT_STRING, {(void*)&str_comment}, "set the comment", "string" },
2642
    { "debug", HAS_ARG | OPT_EXPERT, {(void*)opt_debug}, "print specific debug info", "" },
2643
    { "benchmark", OPT_BOOL | OPT_EXPERT, {(void*)&do_benchmark}, 
2644
      "add timings for benchmarking" },
2645
    { "hex", OPT_BOOL | OPT_EXPERT, {(void*)&do_hex_dump}, 
2646
      "dump each input packet" },
2647
    { "bitexact", OPT_EXPERT, {(void*)opt_bitexact}, "only use bit exact algorithms (for codec testing)" }, 
2648
    { "re", OPT_BOOL | OPT_EXPERT, {(void*)&rate_emu}, "read input at native frame rate", "" },
2649
    { "loop", OPT_BOOL | OPT_EXPERT, {(void*)&loop_input}, "loop (current only works with images)" },
2650
    { "v", HAS_ARG, {(void*)opt_verbose}, "control amount of logging", "verbose" },
2651

    
2652
    /* video options */
2653
    { "b", HAS_ARG | OPT_VIDEO, {(void*)opt_video_bitrate}, "set video bitrate (in kbit/s)", "bitrate" },
2654
    { "r", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_rate}, "set frame rate (Hz value, fraction or abbreviation)", "rate" },
2655
    { "s", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_size}, "set frame size (WxH or abbreviation)", "size" },
2656
    { "aspect", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_aspect_ratio}, "set aspect ratio (4:3, 16:9 or 1.3333, 1.7777)", "aspect" },
2657
    { "pix_fmt", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_frame_pix_fmt}, "set pixel format", "format" },
2658
    { "croptop", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop_top}, "set top crop band size (in pixels)", "size" },
2659
    { "cropbottom", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop_bottom}, "set bottom crop band size (in pixels)", "size" },
2660
    { "cropleft", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop_left}, "set left crop band size (in pixels)", "size" },
2661
    { "cropright", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop_right}, "set right crop band size (in pixels)", "size" },
2662
    { "g", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_gop_size}, "set the group of picture size", "gop_size" },
2663
    { "intra", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&intra_only}, "use only intra frames"},
2664
    { "vn", OPT_BOOL | OPT_VIDEO, {(void*)&video_disable}, "disable video" },
2665
    { "qscale", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qscale}, "use fixed video quantiser scale (VBR)", "q" },
2666
    { "qmin", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qmin}, "min video quantiser scale (VBR)", "q" },
2667
    { "qmax", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qmax}, "max video quantiser scale (VBR)", "q" },
2668
    { "mbqmin", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_mb_qmin}, "min macroblock quantiser scale (VBR)", "q" },
2669
    { "mbqmax", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_mb_qmax}, "max macroblock quantiser scale (VBR)", "q" },
2670
    { "qdiff", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qdiff}, "max difference between the quantiser scale (VBR)", "q" },
2671
    { "qblur", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qblur}, "video quantiser scale blur (VBR)", "blur" },
2672
    { "qcomp", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qcomp}, "video quantiser scale compression (VBR)", "compression" },
2673
    { "rc_init_cplx", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_rc_initial_cplx}, "initial complexity for 1-pass encoding", "complexity" },
2674
    { "b_qfactor", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_b_qfactor}, "qp factor between p and b frames", "factor" },
2675
    { "i_qfactor", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_i_qfactor}, "qp factor between p and i frames", "factor" },
2676
    { "b_qoffset", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_b_qoffset}, "qp offset between p and b frames", "offset" },
2677
    { "i_qoffset", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_i_qoffset}, "qp offset between p and i frames", "offset" },
2678
//    { "b_strategy", HAS_ARG | OPT_EXPERT, {(void*)opt_b_strategy}, "dynamic b frame selection strategy", "strategy" },
2679
    { "rc_eq", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_video_rc_eq}, "set rate control equation", "equation" },
2680
    { "rc_override", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_video_rc_override_string}, "rate control override for specific intervals", "override" },
2681
    { "bt", HAS_ARG | OPT_VIDEO, {(void*)opt_video_bitrate_tolerance}, "set video bitrate tolerance (in kbit/s)", "tolerance" },
2682
    { "maxrate", HAS_ARG | OPT_VIDEO, {(void*)opt_video_bitrate_max}, "set max video bitrate tolerance (in kbit/s)", "bitrate" },
2683
    { "minrate", HAS_ARG | OPT_VIDEO, {(void*)opt_video_bitrate_min}, "set min video bitrate tolerance (in kbit/s)", "bitrate" },
2684
    { "bufsize", HAS_ARG | OPT_VIDEO, {(void*)opt_video_buffer_size}, "set ratecontrol buffere size (in kbit)", "size" },
2685
    { "vcodec", HAS_ARG | OPT_VIDEO, {(void*)opt_video_codec}, "force video codec ('copy' to copy stream)", "codec" },
2686
    { "me", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_motion_estimation}, "set motion estimation method", 
2687
      "method" },
2688
    { "dct_algo", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_dct_algo}, "set dct algo",  "algo" },
2689
    { "idct_algo", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_idct_algo}, "set idct algo",  "algo" },
2690
    { "er", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_error_resilience}, "set error resilience",  "n" },
2691
    { "ec", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_error_concealment}, "set error concealment",  "bit_mask" },
2692
    { "bf", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_b_frames}, "use 'frames' B frames", "frames" },
2693
    { "hq", OPT_BOOL, {(void*)&mb_decision}, "activate high quality settings" },
2694
    { "mbd", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_mb_decision}, "macroblock decision", "mode" },
2695
    { "4mv", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_4mv}, "use four motion vector by macroblock (only MPEG-4)" },
2696
    { "part", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_part}, "use data partitioning (only MPEG-4)" },
2697
    { "bug", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_workaround_bugs}, "workaround not auto detected encoder bugs", "param" },
2698
    { "ps", HAS_ARG | OPT_EXPERT, {(void*)opt_packet_size}, "set packet size in bits", "size" },
2699
    { "strict", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_strict}, "how strictly to follow the standarts", "strictness" },
2700
    { "sameq", OPT_BOOL | OPT_VIDEO, {(void*)&same_quality}, 
2701
      "use same video quality as source (implies VBR)" },
2702
    { "pass", HAS_ARG | OPT_VIDEO, {(void*)&opt_pass}, "select the pass number (1 or 2)", "n" },
2703
    { "passlogfile", HAS_ARG | OPT_STRING | OPT_VIDEO, {(void*)&pass_logfilename}, "select two pass log file name", "file" },
2704
    { "deinterlace", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_deinterlace}, 
2705
      "deinterlace pictures" },
2706
    { "psnr", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_psnr}, "calculate PSNR of compressed frames" },
2707
    { "vstats", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_vstats}, "dump video coding statistics to file" }, 
2708
    { "vhook", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)add_frame_hooker}, "insert video processing module", "module" },
2709
    { "aic", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_aic}, "enable Advanced intra coding (h263+)" },
2710
    { "umv", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_umv}, "enable Unlimited Motion Vector (h263+)" },
2711

    
2712
    /* audio options */
2713
    { "ab", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_bitrate}, "set audio bitrate (in kbit/s)", "bitrate", },
2714
    { "ar", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_rate}, "set audio sampling rate (in Hz)", "rate" },
2715
    { "ac", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_channels}, "set number of audio channels", "channels" },
2716
    { "an", OPT_BOOL | OPT_AUDIO, {(void*)&audio_disable}, "disable audio" },
2717
    { "acodec", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_codec}, "force audio codec ('copy' to copy stream)", "codec" },
2718

    
2719
    /* grab options */
2720
    { "vd", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_device}, "set video grab device", "device" },
2721
    { "vc", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_channel}, "set video grab channel (DV1394 only)", "channel" },
2722
    { "tvstd", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_standard}, "set television standard (NTSC, PAL (SECAM))", "standard" },
2723
    { "dv1394", OPT_EXPERT | OPT_GRAB, {(void*)opt_dv1394}, "set DV1394 grab", "" },
2724
    { "ad", HAS_ARG | OPT_EXPERT | OPT_AUDIO | OPT_GRAB, {(void*)opt_audio_device}, "set audio device", "device" },
2725
    { NULL, },
2726
};
2727

    
2728
static void show_banner(void)
2729
{
2730
    printf("ffmpeg version " FFMPEG_VERSION ", Copyright (c) 2000-2003 Fabrice Bellard\n");
2731
}
2732

    
2733
static void show_license(void)
2734
{
2735
    show_banner();
2736
    printf(
2737
    "This library is free software; you can redistribute it and/or\n"
2738
    "modify it under the terms of the GNU Lesser General Public\n"
2739
    "License as published by the Free Software Foundation; either\n"
2740
    "version 2 of the License, or (at your option) any later version.\n"
2741
    "\n"
2742
    "This library is distributed in the hope that it will be useful,\n"
2743
    "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
2744
    "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n"
2745
    "Lesser General Public License for more details.\n"
2746
    "\n"
2747
    "You should have received a copy of the GNU Lesser General Public\n"
2748
    "License along with this library; if not, write to the Free Software\n"
2749
    "Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n"
2750
    );
2751
    exit(1);
2752
}
2753

    
2754
static void show_help(void)
2755
{
2756
    show_banner();
2757
    printf("usage: ffmpeg [[options] -i input_file]... {[options] outfile}...\n"
2758
           "Hyper fast Audio and Video encoder\n");
2759
    printf("\n");
2760
    show_help_options(options, "Main options:\n",
2761
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO, 0);
2762
    show_help_options(options, "\nVideo options:\n",
2763
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB, 
2764
                      OPT_VIDEO);
2765
    show_help_options(options, "\nAdvanced Video options:\n",
2766
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB, 
2767
                      OPT_VIDEO | OPT_EXPERT);
2768
    show_help_options(options, "\nAudio options:\n",
2769
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB, 
2770
                      OPT_AUDIO);
2771
    show_help_options(options, "\nAdvanced Audio options:\n",
2772
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB, 
2773
                      OPT_AUDIO | OPT_EXPERT);
2774
    show_help_options(options, "\nAudio/Video grab options:\n",
2775
                      OPT_GRAB, 
2776
                      OPT_GRAB);
2777
    show_help_options(options, "\nAdvanced options:\n",
2778
                      OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB, 
2779
                      OPT_EXPERT);
2780
    exit(1);
2781
}
2782

    
2783
void parse_arg_file(const char *filename)
2784
{
2785
    opt_output_file(filename);
2786
}
2787

    
2788
int main(int argc, char **argv)
2789
{
2790
    int i;
2791
    int64_t ti;
2792

    
2793
    av_register_all();
2794

    
2795
    if (argc <= 1)
2796
        show_help();
2797
    
2798
    /* parse options */
2799
    parse_options(argc, argv, options);
2800

    
2801
    /* file converter / grab */
2802
    if (nb_output_files <= 0) {
2803
        fprintf(stderr, "Must supply at least one output file\n");
2804
        exit(1);
2805
    }
2806
    
2807
    if (nb_input_files == 0) {
2808
        prepare_grab();
2809
    }
2810

    
2811
    ti = getutime();
2812
    av_encode(output_files, nb_output_files, input_files, nb_input_files, 
2813
              stream_maps, nb_stream_maps);
2814
    ti = getutime() - ti;
2815
    if (do_benchmark) {
2816
        printf("bench: utime=%0.3fs\n", ti / 1000000.0);
2817
    }
2818

    
2819
    /* close files */
2820
    for(i=0;i<nb_output_files;i++) {
2821
        /* maybe av_close_output_file ??? */
2822
        AVFormatContext *s = output_files[i];
2823
        int j;
2824
        if (!(s->oformat->flags & AVFMT_NOFILE))
2825
            url_fclose(&s->pb);
2826
        for(j=0;j<s->nb_streams;j++)
2827
            av_free(s->streams[j]);
2828
        av_free(s);
2829
    }
2830
    for(i=0;i<nb_input_files;i++)
2831
        av_close_input_file(input_files[i]);
2832

    
2833
    av_free_static();
2834

    
2835
    
2836
#ifdef POWERPC_PERFORMANCE_REPORT
2837
    extern void powerpc_display_perf_report(void);
2838
    powerpc_display_perf_report();
2839
#endif /* POWERPC_PERFORMANCE_REPORT */
2840

    
2841
#ifndef CONFIG_WIN32
2842
    if (received_sigterm) {
2843
        fprintf(stderr,
2844
            "Received signal %d: terminating.\n",
2845
            (int) received_sigterm);
2846
        exit (255);
2847
    }
2848
#endif
2849
    exit(0); /* not all OS-es handle main() return value */
2850
    return 0;
2851
}