Statistics
| Branch: | Revision:

ffmpeg / ffmpeg.c @ d4ad24c1

History | View | Annotate | Download (94.4 KB)

1
/*
2
 * FFmpeg main 
3
 * Copyright (c) 2000, 2001, 2002 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
/* usleep() */
24
#include "os_support.h"
25

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

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

    
46
#define MAXINT64 int64_t_C(0x7fffffffffffffff)
47

    
48
typedef struct {
49
    const char *name;
50
    int flags;
51
#define HAS_ARG    0x0001
52
#define OPT_BOOL   0x0002
53
#define OPT_EXPERT 0x0004
54
#define OPT_STRING 0x0008
55
    union {
56
        void (*func_arg)(const char *);
57
        int *int_arg;
58
        char **str_arg;
59
    } u;
60
    const char *help;
61
    const char *argname;
62
} OptionDef;
63

    
64
/* select an input stream for an output stream */
65
typedef struct AVStreamMap {
66
    int file_index;
67
    int stream_index;
68
} AVStreamMap;
69

    
70
extern const OptionDef options[];
71

    
72
void show_help(void);
73

    
74
#define MAX_FILES 20
75

    
76
static AVFormatContext *input_files[MAX_FILES];
77
static int nb_input_files = 0;
78

    
79
static AVFormatContext *output_files[MAX_FILES];
80
static int nb_output_files = 0;
81

    
82
static AVStreamMap stream_maps[MAX_FILES];
83
static int nb_stream_maps;
84

    
85
static AVInputFormat *file_iformat;
86
static AVOutputFormat *file_oformat;
87
static AVImageFormat *image_format;
88
static int frame_width  = 160;
89
static int frame_height = 128;
90
static int frame_topBand  = 0;
91
static int frame_bottomBand = 0;
92
static int frame_leftBand  = 0;
93
static int frame_rightBand = 0;
94
static int frame_rate = 25;
95
static int frame_rate_base = 1;
96
static int video_bit_rate = 200*1000;
97
static int video_bit_rate_tolerance = 4000*1000;
98
static int video_qscale = 0;
99
static int video_qmin = 2;
100
static int video_qmax = 31;
101
static int video_mb_qmin = 2;
102
static int video_mb_qmax = 31;
103
static int video_qdiff = 3;
104
static float video_qblur = 0.5;
105
static float video_qcomp = 0.5;
106
#if 0 //experimental, (can be removed)
107
static float video_rc_qsquish=1.0;
108
static float video_rc_qmod_amp=0;
109
static int video_rc_qmod_freq=0;
110
#endif
111
static char *video_rc_override_string=NULL;
112
static char *video_rc_eq="tex^qComp";
113
static int video_rc_buffer_size=0;
114
static float video_rc_buffer_aggressivity=1.0;
115
static int video_rc_max_rate=0;
116
static int video_rc_min_rate=0;
117
static float video_rc_initial_cplx=0;
118
static float video_b_qfactor = 1.25;
119
static float video_b_qoffset = 1.25;
120
static float video_i_qfactor = -0.8;
121
static float video_i_qoffset = 0.0;
122
static int me_method = ME_EPZS;
123
static int video_disable = 0;
124
static int video_codec_id = CODEC_ID_NONE;
125
static int same_quality = 0;
126
static int b_frames = 0;
127
static int use_hq = 0;
128
static int use_4mv = 0;
129
/* Fx */
130
static int use_aic = 0;
131
static int use_umv = 0;
132
/* /Fx */
133
static int use_h263p_extra = 0;
134
static int do_deinterlace = 0;
135
static int workaround_bugs = FF_BUG_AUTODETECT;
136
static int error_resilience = 2;
137
static int error_concealment = 3;
138
static int dct_algo = 0;
139
static int idct_algo = 0;
140
static int use_part = 0;
141
static int packet_size = 0;
142
static int strict = 0;
143
static int debug = 0;
144

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

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

    
170
static int rate_emu = 0;
171

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

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

    
179
#define DEFAULT_PASS_LOGFILENAME "ffmpeg2pass"
180

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

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

    
209
typedef struct AVInputStream {
210
    int file_index;
211
    int index;
212
    AVStream *st;
213
    int discard;             /* true if stream data should be discarded */
214
    int decoding_needed;     /* true if the packets must be decoded in 'raw_fifo' */
215
    int64_t sample_index;      /* current sample */
216
    int frame_decoded;       /* true if a video or audio frame has been decoded */
217

    
218
    int64_t       start;     /* time when read started */
219
    unsigned long frame;     /* current frame */
220
} AVInputStream;
221

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

    
231
#ifndef CONFIG_WIN32
232

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

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

    
241
static void term_init(void)
242
{
243
    struct termios tty;
244

    
245
    tcgetattr (0, &tty);
246
    oldtty = tty;
247

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

    
259
    atexit(term_exit);
260
#ifdef CONFIG_BEOS_NETSERVER
261
    fcntl(0, F_SETFL, fcntl(0, F_GETFL) | O_NONBLOCK);
262
#endif
263
}
264

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

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

    
285
        return n;
286
    }
287
    return -1;
288
}
289

    
290
#else
291

    
292
/* no interactive support */
293
static void term_exit(void)
294
{
295
}
296

    
297
static void term_init(void)
298
{
299
}
300

    
301
static int read_key(void)
302
{
303
    return 0;
304
}
305

    
306
#endif
307

    
308
static int read_ffserver_streams(AVFormatContext *s, const char *filename)
309
{
310
    int i, err;
311
    AVFormatContext *ic;
312

    
313
    err = av_open_input_file(&ic, filename, NULL, FFM_PACKET_SIZE, NULL);
314
    if (err < 0)
315
        return err;
316
    /* copy stream format */
317
    s->nb_streams = ic->nb_streams;
318
    for(i=0;i<ic->nb_streams;i++) {
319
        AVStream *st;
320

    
321
        st = av_mallocz(sizeof(AVFormatContext));
322
        memcpy(st, ic->streams[i], sizeof(AVStream));
323
        s->streams[i] = st;
324
    }
325

    
326
    av_close_input_file(ic);
327
    return 0;
328
}
329

    
330
#define MAX_AUDIO_PACKET_SIZE (128 * 1024)
331

    
332
static void do_audio_out(AVFormatContext *s, 
333
                         AVOutputStream *ost, 
334
                         AVInputStream *ist,
335
                         unsigned char *buf, int size)
336
{
337
    uint8_t *buftmp;
338
    uint8_t audio_buf[2*MAX_AUDIO_PACKET_SIZE]; /* XXX: allocate it */
339
    uint8_t audio_out[4*MAX_AUDIO_PACKET_SIZE]; /* XXX: allocate it - yep really WMA */
340
    int size_out, frame_bytes, ret;
341
    AVCodecContext *enc;
342

    
343
    enc = &ost->st->codec;
344

    
345
    if (ost->audio_resample) {
346
        buftmp = audio_buf;
347
        size_out = audio_resample(ost->resample, 
348
                                  (short *)buftmp, (short *)buf,
349
                                  size / (ist->st->codec.channels * 2));
350
        size_out = size_out * enc->channels * 2;
351
    } else {
352
        buftmp = buf;
353
        size_out = size;
354
    }
355

    
356
    /* now encode as many frames as possible */
357
    if (enc->frame_size > 1) {
358
        /* output resampled raw samples */
359
        fifo_write(&ost->fifo, buftmp, size_out, 
360
                   &ost->fifo.wptr);
361

    
362
        frame_bytes = enc->frame_size * 2 * enc->channels;
363
        
364
        while (fifo_read(&ost->fifo, audio_buf, frame_bytes, 
365
                     &ost->fifo.rptr) == 0) {
366
            ret = avcodec_encode_audio(enc, audio_out, sizeof(audio_out), 
367
                                       (short *)audio_buf);
368
            av_write_frame(s, ost->index, audio_out, ret);
369
        }
370
    } else {
371
        /* output a pcm frame */
372
        /* XXX: change encoding codec API to avoid this ? */
373
        switch(enc->codec->id) {
374
        case CODEC_ID_PCM_S16LE:
375
        case CODEC_ID_PCM_S16BE:
376
        case CODEC_ID_PCM_U16LE:
377
        case CODEC_ID_PCM_U16BE:
378
            break;
379
        default:
380
            size_out = size_out >> 1;
381
            break;
382
        }
383
        ret = avcodec_encode_audio(enc, audio_out, size_out, 
384
                                   (short *)buftmp);
385
        av_write_frame(s, ost->index, audio_out, ret);
386
    }
387
}
388

    
389
/* write a picture to a raw mux */
390
static void write_picture(AVFormatContext *s, int index, AVPicture *picture, 
391
                          int pix_fmt, int w, int h)
392
{
393
    uint8_t *buf, *src, *dest;
394
    int size, j, i;
395

    
396
    /* XXX: not efficient, should add test if we can take
397
       directly the AVPicture */
398
    switch(pix_fmt) {
399
    case PIX_FMT_YUV420P:
400
        size = avpicture_get_size(pix_fmt, w, h);
401
        buf = av_malloc(size);
402
        if (!buf)
403
            return;
404
        dest = buf;
405
        for(i=0;i<3;i++) {
406
            if (i == 1) {
407
                w >>= 1;
408
                h >>= 1;
409
            }
410
            src = picture->data[i];
411
            for(j=0;j<h;j++) {
412
                memcpy(dest, src, w);
413
                dest += w;
414
                src += picture->linesize[i];
415
            }
416
        }
417
        break;
418
    case PIX_FMT_YUV422P:
419
        size = (w * h) * 2; 
420
        buf = av_malloc(size);
421
        if (!buf)
422
            return;
423
        dest = buf;
424
        for(i=0;i<3;i++) {
425
            if (i == 1) {
426
                w >>= 1;
427
            }
428
            src = picture->data[i];
429
            for(j=0;j<h;j++) {
430
                memcpy(dest, src, w);
431
                dest += w;
432
                src += picture->linesize[i];
433
            }
434
        }
435
        break;
436
    case PIX_FMT_YUV444P:
437
        size = (w * h) * 3; 
438
        buf = av_malloc(size);
439
        if (!buf)
440
            return;
441
        dest = buf;
442
        for(i=0;i<3;i++) {
443
            src = picture->data[i];
444
            for(j=0;j<h;j++) {
445
                memcpy(dest, src, w);
446
                dest += w;
447
                src += picture->linesize[i];
448
            }
449
        }
450
        break;
451
    case PIX_FMT_YUV422:
452
        size = (w * h) * 2; 
453
        buf = av_malloc(size);
454
        if (!buf)
455
            return;
456
        dest = buf;
457
        src = picture->data[0];
458
        for(j=0;j<h;j++) {
459
            memcpy(dest, src, w * 2);
460
            dest += w * 2;
461
            src += picture->linesize[0];
462
        }
463
        break;
464
    case PIX_FMT_RGB24:
465
    case PIX_FMT_BGR24:
466
        size = (w * h) * 3; 
467
        buf = av_malloc(size);
468
        if (!buf)
469
            return;
470
        dest = buf;
471
        src = picture->data[0];
472
        for(j=0;j<h;j++) {
473
            memcpy(dest, src, w * 3);
474
            dest += w * 3;
475
            src += picture->linesize[0];
476
        }
477
        break;
478
    default:
479
        return;
480
    }
481
    av_write_frame(s, index, buf, size);
482
    av_free(buf);
483
}
484

    
485
static void pre_process_video_frame(AVInputStream *ist, AVPicture *picture, void **bufp)
486
{
487
    AVCodecContext *dec;
488
    AVPicture *picture2;
489
    AVPicture picture_tmp;
490
    uint8_t *buf = 0;
491

    
492
    dec = &ist->st->codec;
493

    
494
    /* deinterlace : must be done before any resize */
495
    if (do_deinterlace) {
496
        int size;
497

    
498
        /* create temporary picture */
499
        size = avpicture_get_size(dec->pix_fmt, dec->width, dec->height);
500
        buf = av_malloc(size);
501
        if (!buf)
502
            return;
503
        
504
        picture2 = &picture_tmp;
505
        avpicture_fill(picture2, buf, dec->pix_fmt, dec->width, dec->height);
506

    
507
        if (avpicture_deinterlace(picture2, picture, 
508
                                  dec->pix_fmt, dec->width, dec->height) < 0) {
509
            /* if error, do not deinterlace */
510
            av_free(buf);
511
            buf = NULL;
512
            picture2 = picture;
513
        }
514
    } else {
515
        picture2 = picture;
516
    }
517

    
518
    frame_hook_process(picture2, dec->pix_fmt, dec->width, dec->height);
519

    
520
    if (picture != picture2)
521
        *picture = *picture2;
522
    *bufp = buf;
523
}
524

    
525
/* we begin to correct av delay at this threshold */
526
#define AV_DELAY_MAX 0.100
527

    
528
static void do_video_out(AVFormatContext *s, 
529
                         AVOutputStream *ost, 
530
                         AVInputStream *ist,
531
                         AVPicture *in_picture,
532
                         int *frame_size, AVOutputStream *audio_sync)
533
{
534
    int nb_frames, i, ret;
535
    AVPicture *final_picture, *formatted_picture;
536
    AVPicture picture_format_temp, picture_crop_temp;
537
    static uint8_t *video_buffer;
538
    uint8_t *buf = NULL, *buf1 = NULL;
539
    AVCodecContext *enc, *dec;
540

    
541
#define VIDEO_BUFFER_SIZE (1024*1024)
542

    
543
    enc = &ost->st->codec;
544
    dec = &ist->st->codec;
545

    
546
    /* by default, we output a single frame */
547
    nb_frames = 1;
548

    
549
    *frame_size = 0;
550

    
551
    /* NOTE: the A/V sync is always done by considering the audio is
552
       the master clock. It is suffisant for transcoding or playing,
553
       but not for the general case */
554
    if (audio_sync) {
555
        /* compute the A-V delay and duplicate/remove frames if needed */
556
        double adelta, vdelta, apts, vpts, av_delay;
557
        
558
        if (audio_sync->sync_ipts != AV_NOPTS_VALUE &&
559
            ost->sync_ipts != AV_NOPTS_VALUE) {
560
            
561
            adelta = (double)(ost->st->pts.val - audio_sync->sync_opts) * 
562
                s->pts_num / s->pts_den;
563
            apts = audio_sync->sync_ipts + adelta; 
564
            
565
            vdelta = (double)(ost->st->pts.val - ost->sync_opts) *
566
                s->pts_num / s->pts_den;
567
            vpts = ost->sync_ipts + vdelta;
568
            
569
            av_delay = apts - vpts;
570
            //            printf("delay=%f\n", av_delay);
571
            if (av_delay < -AV_DELAY_MAX)
572
                nb_frames = 2;
573
            else if (av_delay > AV_DELAY_MAX)
574
                nb_frames = 0;
575
        }
576
    } else {
577
        double vdelta;
578

    
579
        if (ost->sync_ipts != AV_NOPTS_VALUE) {
580
            vdelta = (double)(ost->st->pts.val) * s->pts_num / s->pts_den - (ost->sync_ipts - ost->sync_ipts_offset);
581
            if (vdelta < 100 && vdelta > -100 && ost->sync_ipts_offset) {
582
                if (vdelta < -AV_DELAY_MAX)
583
                    nb_frames = 2;
584
                else if (vdelta > AV_DELAY_MAX)
585
                    nb_frames = 0;
586
            } else {
587
                ost->sync_ipts_offset -= vdelta;
588
                if (!ost->sync_ipts_offset)
589
                    ost->sync_ipts_offset = 0.000001; /* one microsecond */
590
            }
591

    
592
#if defined(PJSG)
593
            {
594
                static char *action[] = { "drop frame", "copy frame", "dup frame" };
595
                printf("Input PTS %12.6f, output PTS %12.6f: %s\n",
596
                    (double) ost->sync_ipts, (double) ost->st->pts.val * s->pts_num / s->pts_den,
597
                    action[nb_frames]);
598
            }
599
#endif
600
        }
601
    }
602
    if (nb_frames <= 0) 
603
        return;
604

    
605
    if (!video_buffer)
606
        video_buffer = av_malloc(VIDEO_BUFFER_SIZE);
607
    if (!video_buffer)
608
        return;
609

    
610
    /* convert pixel format if needed */
611
    if (enc->pix_fmt != dec->pix_fmt) {
612
        int size;
613

    
614
        /* create temporary picture */
615
        size = avpicture_get_size(enc->pix_fmt, dec->width, dec->height);
616
        buf = av_malloc(size);
617
        if (!buf)
618
            return;
619
        formatted_picture = &picture_format_temp;
620
        avpicture_fill(formatted_picture, buf, enc->pix_fmt, dec->width, dec->height);
621
        
622
        if (img_convert(formatted_picture, enc->pix_fmt, 
623
                        in_picture, dec->pix_fmt, 
624
                        dec->width, dec->height) < 0) {
625
            fprintf(stderr, "pixel format conversion not handled\n");
626
            goto the_end;
627
        }
628
    } else {
629
        formatted_picture = in_picture;
630
    }
631

    
632
    /* XXX: resampling could be done before raw format convertion in
633
       some cases to go faster */
634
    /* XXX: only works for YUV420P */
635
    if (ost->video_resample) {
636
        final_picture = &ost->pict_tmp;
637
        img_resample(ost->img_resample_ctx, final_picture, formatted_picture);
638
    } else if (ost->video_crop) {
639
        picture_crop_temp.data[0] = formatted_picture->data[0] +
640
                (ost->topBand * formatted_picture->linesize[0]) + ost->leftBand;
641

    
642
        picture_crop_temp.data[1] = formatted_picture->data[1] +
643
                ((ost->topBand >> 1) * formatted_picture->linesize[1]) +
644
                (ost->leftBand >> 1);
645

    
646
        picture_crop_temp.data[2] = formatted_picture->data[2] +
647
                ((ost->topBand >> 1) * formatted_picture->linesize[2]) +
648
                (ost->leftBand >> 1);
649

    
650
        picture_crop_temp.linesize[0] = formatted_picture->linesize[0];
651
        picture_crop_temp.linesize[1] = formatted_picture->linesize[1];
652
        picture_crop_temp.linesize[2] = formatted_picture->linesize[2];
653
        final_picture = &picture_crop_temp;
654
    } else {
655
        final_picture = formatted_picture;
656
    }
657
    /* duplicates frame if needed */
658
    /* XXX: pb because no interleaving */
659
    for(i=0;i<nb_frames;i++) {
660
        if (enc->codec_id != CODEC_ID_RAWVIDEO) {
661
            AVFrame big_picture;
662
            
663
            memset(&big_picture, 0, sizeof(AVFrame));
664
            *(AVPicture*)&big_picture= *final_picture;
665
                        
666
            /* handles sameq here. This is not correct because it may
667
               not be a global option */
668
            if (same_quality) {
669
                big_picture.quality = ist->st->quality;
670
            }else
671
                big_picture.quality = ost->st->quality;
672
            
673
            ret = avcodec_encode_video(enc, 
674
                                       video_buffer, VIDEO_BUFFER_SIZE,
675
                                       &big_picture);
676
            //enc->frame_number = enc->real_pict_num;
677
            av_write_frame(s, ost->index, video_buffer, ret);
678
            *frame_size = ret;
679
            //fprintf(stderr,"\nFrame: %3d %3d size: %5d type: %d",
680
            //        enc->frame_number-1, enc->real_pict_num, ret,
681
            //        enc->pict_type);
682
            /* if two pass, output log */
683
            if (ost->logfile && enc->stats_out) {
684
                fprintf(ost->logfile, "%s", enc->stats_out);
685
            }
686
        } else {
687
            if (s->oformat->flags & AVFMT_RAWPICTURE) {
688
                /* raw pictures are written as AVPicture structure to
689
                   avoid any copies. We support temorarily the older
690
                   method. */
691
                av_write_frame(s, ost->index, 
692
                               (uint8_t *)final_picture, sizeof(AVPicture));
693
            } else {
694
                write_picture(s, ost->index, final_picture, enc->pix_fmt, 
695
                              enc->width, enc->height);
696
            }
697
        }
698
        ost->frame_number++;
699
    }
700
 the_end:
701
    av_free(buf);
702
    av_free(buf1);
703
}
704

    
705
static double psnr(double d){
706
    if(d==0) return INFINITY;
707
    return -10.0*log(d)/log(10.0);
708
}
709

    
710
static void do_video_stats(AVFormatContext *os, AVOutputStream *ost, 
711
                           int frame_size)
712
{
713
    static FILE *fvstats=NULL;
714
    static int64_t total_size = 0;
715
    char filename[40];
716
    time_t today2;
717
    struct tm *today;
718
    AVCodecContext *enc;
719
    int frame_number;
720
    int64_t ti;
721
    double ti1, bitrate, avg_bitrate;
722
    
723
    if (!fvstats) {
724
        today2 = time(NULL);
725
        today = localtime(&today2);
726
        sprintf(filename, "vstats_%02d%02d%02d.log", today->tm_hour,
727
                                               today->tm_min,
728
                                               today->tm_sec);
729
        fvstats = fopen(filename,"w");
730
        if (!fvstats) {
731
            perror("fopen");
732
            exit(1);
733
        }
734
    }
735
    
736
    ti = MAXINT64;
737
    enc = &ost->st->codec;
738
    total_size += frame_size;
739
    if (enc->codec_type == CODEC_TYPE_VIDEO) {
740
        frame_number = ost->frame_number;
741
        fprintf(fvstats, "frame= %5d q= %2.1f ", frame_number, enc->coded_frame->quality);
742
        if (enc->flags&CODEC_FLAG_PSNR)
743
            fprintf(fvstats, "PSNR= %6.2f ", psnr(enc->coded_frame->error[0]/(enc->width*enc->height*255.0*255.0)));
744
        
745
        fprintf(fvstats,"f_size= %6d ", frame_size);
746
        /* compute pts value */
747
        ti1 = (double)ost->st->pts.val * os->pts_num / os->pts_den;
748
        if (ti1 < 0.01)
749
            ti1 = 0.01;
750
    
751
        bitrate = (double)(frame_size * 8) * enc->frame_rate / enc->frame_rate_base / 1000.0;
752
        avg_bitrate = (double)(total_size * 8) / ti1 / 1000.0;
753
        fprintf(fvstats, "s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
754
            (double)total_size / 1024, ti1, bitrate, avg_bitrate);
755
        fprintf(fvstats,"type= %s\n", enc->coded_frame->key_frame == 1 ? "I" : "P");        
756
    }
757
}
758

    
759
static void print_report(AVFormatContext **output_files,
760
                         AVOutputStream **ost_table, int nb_ostreams,
761
                         int is_last_report)
762
{
763
    char buf[1024];
764
    AVOutputStream *ost;
765
    AVFormatContext *oc, *os;
766
    int64_t total_size;
767
    AVCodecContext *enc;
768
    int frame_number, vid, i;
769
    double bitrate, ti1, pts;
770
    static int64_t last_time = -1;
771
    
772
    if (!is_last_report) {
773
        int64_t cur_time;
774
        /* display the report every 0.5 seconds */
775
        cur_time = av_gettime();
776
        if (last_time == -1) {
777
            last_time = cur_time;
778
            return;
779
        } 
780
        if ((cur_time - last_time) < 500000)
781
            return;
782
        last_time = cur_time;
783
    }
784

    
785

    
786
    oc = output_files[0];
787

    
788
    total_size = url_ftell(&oc->pb);
789
    
790
    buf[0] = '\0';
791
    ti1 = 1e10;
792
    vid = 0;
793
    for(i=0;i<nb_ostreams;i++) {
794
        ost = ost_table[i];
795
        os = output_files[ost->file_index];
796
        enc = &ost->st->codec;
797
        if (vid && enc->codec_type == CODEC_TYPE_VIDEO) {
798
            sprintf(buf + strlen(buf), "q=%2.1f ",
799
                    enc->coded_frame->quality);
800
        }
801
        if (!vid && enc->codec_type == CODEC_TYPE_VIDEO) {
802
            frame_number = ost->frame_number;
803
            sprintf(buf + strlen(buf), "frame=%5d q=%2.1f ",
804
                    frame_number, enc->coded_frame ? enc->coded_frame->quality : 0);
805
            if (enc->flags&CODEC_FLAG_PSNR)
806
                sprintf(buf + strlen(buf), "PSNR= %6.2f ", psnr(enc->coded_frame->error[0]/(enc->width*enc->height*255.0*255.0)));
807
            vid = 1;
808
        }
809
        /* compute min output value */
810
        pts = (double)ost->st->pts.val * os->pts_num / os->pts_den;
811
        if ((pts < ti1) && (pts > 0))
812
            ti1 = pts;
813
    }
814
    if (ti1 < 0.01)
815
        ti1 = 0.01;
816
    bitrate = (double)(total_size * 8) / ti1 / 1000.0;
817
    
818
    sprintf(buf + strlen(buf), 
819
            "size=%8.0fkB time=%0.1f bitrate=%6.1fkbits/s",
820
            (double)total_size / 1024, ti1, bitrate);
821
    
822
    fprintf(stderr, "%s   ", buf);
823
    
824
    if (is_last_report) {
825
        fprintf(stderr, "\n");
826
    } else {
827
        fprintf(stderr, "\r");
828
        fflush(stderr);
829
    }
830
}
831

    
832
/*
833
 * The following code is the main loop of the file converter
834
 */
835
static int av_encode(AVFormatContext **output_files,
836
                     int nb_output_files,
837
                     AVFormatContext **input_files,
838
                     int nb_input_files,
839
                     AVStreamMap *stream_maps, int nb_stream_maps)
840
{
841
    int ret, i, j, k, n, nb_istreams = 0, nb_ostreams = 0, pts_set;
842
    AVFormatContext *is, *os;
843
    AVCodecContext *codec, *icodec;
844
    AVOutputStream *ost, **ost_table = NULL;
845
    AVInputStream *ist, **ist_table = NULL;
846
    AVInputFile *file_table;
847
    AVFormatContext *stream_no_data;
848
    int key;
849

    
850
    file_table= (AVInputFile*) av_mallocz(nb_input_files * sizeof(AVInputFile));
851
    if (!file_table)
852
        goto fail;
853

    
854
    /* input stream init */
855
    j = 0;
856
    for(i=0;i<nb_input_files;i++) {
857
        is = input_files[i];
858
        file_table[i].ist_index = j;
859
        file_table[i].nb_streams = is->nb_streams;
860
        j += is->nb_streams;
861
    }
862
    nb_istreams = j;
863

    
864
    ist_table = av_mallocz(nb_istreams * sizeof(AVInputStream *));
865
    if (!ist_table)
866
        goto fail;
867
    
868
    for(i=0;i<nb_istreams;i++) {
869
        ist = av_mallocz(sizeof(AVInputStream));
870
        if (!ist)
871
            goto fail;
872
        ist_table[i] = ist;
873
    }
874
    j = 0;
875
    for(i=0;i<nb_input_files;i++) {
876
        is = input_files[i];
877
        for(k=0;k<is->nb_streams;k++) {
878
            ist = ist_table[j++];
879
            ist->st = is->streams[k];
880
            ist->file_index = i;
881
            ist->index = k;
882
            ist->discard = 1; /* the stream is discarded by default
883
                                 (changed later) */
884

    
885
            if (ist->st->codec.rate_emu) {
886
                ist->start = av_gettime();
887
                ist->frame = 0;
888
            }
889
        }
890
    }
891

    
892
    /* output stream init */
893
    nb_ostreams = 0;
894
    for(i=0;i<nb_output_files;i++) {
895
        os = output_files[i];
896
        nb_ostreams += os->nb_streams;
897
    }
898
    if (nb_stream_maps > 0 && nb_stream_maps != nb_ostreams) {
899
        fprintf(stderr, "Number of stream maps must match number of output streams\n");
900
        exit(1);
901
    }
902

    
903
    ost_table = av_mallocz(sizeof(AVOutputStream *) * nb_ostreams);
904
    if (!ost_table)
905
        goto fail;
906
    for(i=0;i<nb_ostreams;i++) {
907
        ost = av_mallocz(sizeof(AVOutputStream));
908
        if (!ost)
909
            goto fail;
910
        ost_table[i] = ost;
911
    }
912
    
913
    n = 0;
914
    for(k=0;k<nb_output_files;k++) {
915
        os = output_files[k];
916
        for(i=0;i<os->nb_streams;i++) {
917
            int found;
918
            ost = ost_table[n++];
919
            ost->file_index = k;
920
            ost->index = i;
921
            ost->st = os->streams[i];
922
            if (nb_stream_maps > 0) {
923
                ost->source_index = file_table[stream_maps[n-1].file_index].ist_index + 
924
                    stream_maps[n-1].stream_index;
925
            } else {
926
                /* get corresponding input stream index : we select the first one with the right type */
927
                found = 0;
928
                for(j=0;j<nb_istreams;j++) {
929
                    ist = ist_table[j];
930
                    if (ist->discard && 
931
                        ist->st->codec.codec_type == ost->st->codec.codec_type) {
932
                        ost->source_index = j;
933
                        found = 1;
934
                    }
935
                }
936
                
937
                if (!found) {
938
                    /* try again and reuse existing stream */
939
                    for(j=0;j<nb_istreams;j++) {
940
                        ist = ist_table[j];
941
                        if (ist->st->codec.codec_type == ost->st->codec.codec_type) {
942
                            ost->source_index = j;
943
                            found = 1;
944
                        }
945
                    }
946
                    if (!found) {
947
                        fprintf(stderr, "Could not find input stream matching output stream #%d.%d\n",
948
                                ost->file_index, ost->index);
949
                        exit(1);
950
                    }
951
                }
952
            }
953
            ist = ist_table[ost->source_index];
954
            ist->discard = 0;
955
        }
956
    }
957

    
958
    /* for each output stream, we compute the right encoding parameters */
959
    for(i=0;i<nb_ostreams;i++) {
960
        ost = ost_table[i];
961
        ist = ist_table[ost->source_index];
962

    
963
        codec = &ost->st->codec;
964
        icodec = &ist->st->codec;
965

    
966
        if (ost->st->stream_copy) {
967
            /* if stream_copy is selected, no need to decode or encode */
968
            codec->codec_id = icodec->codec_id;
969
            codec->codec_type = icodec->codec_type;
970
            codec->codec_tag = icodec->codec_tag;
971
            codec->bit_rate = icodec->bit_rate;
972
            switch(codec->codec_type) {
973
            case CODEC_TYPE_AUDIO:
974
                codec->sample_rate = icodec->sample_rate;
975
                codec->channels = icodec->channels;
976
                break;
977
            case CODEC_TYPE_VIDEO:
978
                codec->frame_rate = icodec->frame_rate;
979
                codec->frame_rate_base = icodec->frame_rate_base;
980
                codec->width = icodec->width;
981
                codec->height = icodec->height;
982
                break;
983
            default:
984
                av_abort();
985
            }
986
        } else {
987
            switch(codec->codec_type) {
988
            case CODEC_TYPE_AUDIO:
989
                if (fifo_init(&ost->fifo, 2 * MAX_AUDIO_PACKET_SIZE))
990
                    goto fail;
991
                
992
                if (codec->channels == icodec->channels &&
993
                    codec->sample_rate == icodec->sample_rate) {
994
                    ost->audio_resample = 0;
995
                } else {
996
                    if (codec->channels != icodec->channels &&
997
                        icodec->codec_id == CODEC_ID_AC3) {
998
                        /* Special case for 5:1 AC3 input */
999
                        /* and mono or stereo output      */
1000
                        /* Request specific number of channels */
1001
                        icodec->channels = codec->channels;
1002
                        if (codec->sample_rate == icodec->sample_rate)
1003
                            ost->audio_resample = 0;
1004
                        else {
1005
                            ost->audio_resample = 1;
1006
                            ost->resample = audio_resample_init(codec->channels, icodec->channels,
1007
                                                        codec->sample_rate, 
1008
                                                        icodec->sample_rate);
1009
                        }
1010
                        /* Request specific number of channels */
1011
                        icodec->channels = codec->channels;
1012
                    } else {
1013
                        ost->audio_resample = 1; 
1014
                        ost->resample = audio_resample_init(codec->channels, icodec->channels,
1015
                                                        codec->sample_rate, 
1016
                                                        icodec->sample_rate);
1017
                    }
1018
                }
1019
                ist->decoding_needed = 1;
1020
                ost->encoding_needed = 1;
1021
                break;
1022
            case CODEC_TYPE_VIDEO:
1023
                if (codec->width == icodec->width &&
1024
                    codec->height == icodec->height &&
1025
                    frame_topBand == 0 &&
1026
                    frame_bottomBand == 0 &&
1027
                    frame_leftBand == 0 &&
1028
                    frame_rightBand == 0)
1029
                {
1030
                    ost->video_resample = 0;
1031
                    ost->video_crop = 0;
1032
                } else if ((codec->width == icodec->width -
1033
                                (frame_leftBand + frame_rightBand)) &&
1034
                        (codec->height == icodec->height -
1035
                                (frame_topBand  + frame_bottomBand)))
1036
                {
1037
                    ost->video_resample = 0;
1038
                    ost->video_crop = 1;
1039
                    ost->topBand = frame_topBand;
1040
                    ost->leftBand = frame_leftBand;
1041
                } else {
1042
                    uint8_t *buf;
1043
                    ost->video_resample = 1;
1044
                    ost->video_crop = 0; // cropping is handled as part of resample
1045
                    buf = av_malloc((codec->width * codec->height * 3) / 2);
1046
                    if (!buf)
1047
                        goto fail;
1048
                    ost->pict_tmp.data[0] = buf;
1049
                    ost->pict_tmp.data[1] = ost->pict_tmp.data[0] + (codec->width * codec->height);
1050
                    ost->pict_tmp.data[2] = ost->pict_tmp.data[1] + (codec->width * codec->height) / 4;
1051
                    ost->pict_tmp.linesize[0] = codec->width;
1052
                    ost->pict_tmp.linesize[1] = codec->width / 2;
1053
                    ost->pict_tmp.linesize[2] = codec->width / 2;
1054

    
1055
                    ost->img_resample_ctx = img_resample_full_init( 
1056
                                      ost->st->codec.width, ost->st->codec.height,
1057
                                      ist->st->codec.width, ist->st->codec.height,
1058
                                      frame_topBand, frame_bottomBand,
1059
                                      frame_leftBand, frame_rightBand);
1060
                }
1061
                ost->encoding_needed = 1;
1062
                ist->decoding_needed = 1;
1063
                break;
1064
            default:
1065
                av_abort();
1066
            }
1067
            /* two pass mode */
1068
            if (ost->encoding_needed && 
1069
                (codec->flags & (CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2))) {
1070
                char logfilename[1024];
1071
                FILE *f;
1072
                int size;
1073
                char *logbuffer;
1074
                
1075
                snprintf(logfilename, sizeof(logfilename), "%s-%d.log", 
1076
                         pass_logfilename ? 
1077
                         pass_logfilename : DEFAULT_PASS_LOGFILENAME, i);
1078
                if (codec->flags & CODEC_FLAG_PASS1) {
1079
                    f = fopen(logfilename, "w");
1080
                    if (!f) {
1081
                        perror(logfilename);
1082
                        exit(1);
1083
                    }
1084
                    ost->logfile = f;
1085
                } else {
1086
                    /* read the log file */
1087
                    f = fopen(logfilename, "r");
1088
                    if (!f) {
1089
                        perror(logfilename);
1090
                        exit(1);
1091
                    }
1092
                    fseek(f, 0, SEEK_END);
1093
                    size = ftell(f);
1094
                    fseek(f, 0, SEEK_SET);
1095
                    logbuffer = av_malloc(size + 1);
1096
                    if (!logbuffer) {
1097
                        fprintf(stderr, "Could not allocate log buffer\n");
1098
                        exit(1);
1099
                    }
1100
                    fread(logbuffer, 1, size, f);
1101
                    fclose(f);
1102
                    logbuffer[size] = '\0';
1103
                    codec->stats_in = logbuffer;
1104
                }
1105
            }
1106
        }
1107
    }
1108

    
1109
    /* dump the file output parameters - cannot be done before in case
1110
       of stream copy */
1111
    for(i=0;i<nb_output_files;i++) {
1112
        dump_format(output_files[i], i, output_files[i]->filename, 1);
1113
    }
1114

    
1115
    /* dump the stream mapping */
1116
    fprintf(stderr, "Stream mapping:\n");
1117
    for(i=0;i<nb_ostreams;i++) {
1118
        ost = ost_table[i];
1119
        fprintf(stderr, "  Stream #%d.%d -> #%d.%d\n",
1120
                ist_table[ost->source_index]->file_index,
1121
                ist_table[ost->source_index]->index,
1122
                ost->file_index, 
1123
                ost->index);
1124
    }
1125

    
1126
    /* open each encoder */
1127
    for(i=0;i<nb_ostreams;i++) {
1128
        ost = ost_table[i];
1129
        if (ost->encoding_needed) {
1130
            AVCodec *codec;
1131
            codec = avcodec_find_encoder(ost->st->codec.codec_id);
1132
            if (!codec) {
1133
                fprintf(stderr, "Unsupported codec for output stream #%d.%d\n", 
1134
                        ost->file_index, ost->index);
1135
                exit(1);
1136
            }
1137
            if (avcodec_open(&ost->st->codec, codec) < 0) {
1138
                fprintf(stderr, "Error while opening codec for stream #%d.%d - maybe incorrect parameters such as bit_rate, rate, width or height\n", 
1139
                        ost->file_index, ost->index);
1140
                exit(1);
1141
            }
1142
        }
1143
    }
1144

    
1145
    /* open each decoder */
1146
    for(i=0;i<nb_istreams;i++) {
1147
        ist = ist_table[i];
1148
        if (ist->decoding_needed) {
1149
            AVCodec *codec;
1150
            codec = avcodec_find_decoder(ist->st->codec.codec_id);
1151
            if (!codec) {
1152
                fprintf(stderr, "Unsupported codec (id=%d) for input stream #%d.%d\n", 
1153
                        ist->st->codec.codec_id, ist->file_index, ist->index);
1154
                exit(1);
1155
            }
1156
            if (avcodec_open(&ist->st->codec, codec) < 0) {
1157
                fprintf(stderr, "Error while opening codec for input stream #%d.%d\n", 
1158
                        ist->file_index, ist->index);
1159
                exit(1);
1160
            }
1161
            //if (ist->st->codec.codec_type == CODEC_TYPE_VIDEO)
1162
            //    ist->st->codec.flags |= CODEC_FLAG_REPEAT_FIELD;
1163
            ist->frame_decoded = 1;
1164
        }
1165
    }
1166

    
1167
    /* init pts */
1168
    for(i=0;i<nb_istreams;i++) {
1169
        ist = ist_table[i];
1170
    }
1171
    
1172
    /* compute buffer size max (should use a complete heuristic) */
1173
    for(i=0;i<nb_input_files;i++) {
1174
        file_table[i].buffer_size_max = 2048;
1175
    }
1176

    
1177
    /* open files and write file headers */
1178
    for(i=0;i<nb_output_files;i++) {
1179
        os = output_files[i];
1180
        if (av_write_header(os) < 0) {
1181
            fprintf(stderr, "Could not write header for output file #%d (incorrect codec paramters ?)\n", i);
1182
            ret = -EINVAL;
1183
            goto fail;
1184
        }
1185
    }
1186

    
1187
#ifndef CONFIG_WIN32
1188
    if (!do_play) {
1189
        fprintf(stderr, "Press [q] to stop encoding\n");
1190
    } else {
1191
        fprintf(stderr, "Press [q] to stop playing\n");
1192
    }
1193
#endif
1194
    term_init();
1195

    
1196
    stream_no_data = 0;
1197
    key = -1;
1198

    
1199
    for(;;) {
1200
        int file_index, ist_index;
1201
        AVPacket pkt;
1202
        uint8_t *ptr;
1203
        int len;
1204
        uint8_t *data_buf;
1205
        int data_size, got_picture;
1206
        AVPicture picture;
1207
        short samples[AVCODEC_MAX_AUDIO_FRAME_SIZE / 2];
1208
        void *buffer_to_free;
1209
        double pts_min;
1210
        
1211
    redo:
1212
        /* if 'q' pressed, exits */
1213
        if (key) {
1214
            /* read_key() returns 0 on EOF */
1215
            key = read_key();
1216
            if (key == 'q')
1217
                break;
1218
        }
1219

    
1220
        /* select the stream that we must read now by looking at the
1221
           smallest output pts */
1222
        file_index = -1;
1223
        pts_min = 1e10;
1224
        for(i=0;i<nb_ostreams;i++) {
1225
            double pts;
1226
            ost = ost_table[i];
1227
            os = output_files[ost->file_index];
1228
            ist = ist_table[ost->source_index];
1229
            pts = (double)ost->st->pts.val * os->pts_num / os->pts_den;
1230
            if (!file_table[ist->file_index].eof_reached && 
1231
                pts < pts_min) {
1232
                pts_min = pts;
1233
                file_index = ist->file_index;
1234
            }
1235
        }
1236
        /* if none, if is finished */
1237
        if (file_index < 0) {
1238
            break;
1239
        }
1240

    
1241
        /* finish if recording time exhausted */
1242
        if (recording_time > 0 && pts_min >= (recording_time / 1000000.0))
1243
            break;
1244

    
1245
        /* read a packet from it and output it in the fifo */
1246
        is = input_files[file_index];
1247
        if (av_read_packet(is, &pkt) < 0) {
1248
            file_table[file_index].eof_reached = 1;
1249
            continue;
1250
        }
1251
        if (!pkt.size) {
1252
            stream_no_data = is;
1253
        } else {
1254
            stream_no_data = 0;
1255
        }
1256
        if (do_hex_dump) {
1257
            printf("stream #%d, size=%d:\n", pkt.stream_index, pkt.size);
1258
            av_hex_dump(pkt.data, pkt.size);
1259
        }
1260
        /* the following test is needed in case new streams appear
1261
           dynamically in stream : we ignore them */
1262
        if (pkt.stream_index >= file_table[file_index].nb_streams)
1263
            goto discard_packet;
1264
        ist_index = file_table[file_index].ist_index + pkt.stream_index;
1265
        ist = ist_table[ist_index];
1266
        if (ist->discard)
1267
            goto discard_packet;
1268

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

    
1271
        len = pkt.size;
1272
        ptr = pkt.data;
1273
        pts_set = 0;
1274
        while (len > 0) {
1275
            int64_t ipts;
1276

    
1277
            ipts = AV_NOPTS_VALUE;
1278

    
1279
            /* decode the packet if needed */
1280
            data_buf = NULL; /* fail safe */
1281
            data_size = 0;
1282
            if (ist->decoding_needed) {
1283
                /* NOTE1: we only take into account the PTS if a new
1284
                   frame has begun (MPEG semantics) */
1285
                /* NOTE2: even if the fraction is not initialized,
1286
                   av_frac_set can be used to set the integer part */
1287
                if (ist->frame_decoded && 
1288
                    pkt.pts != AV_NOPTS_VALUE && 
1289
                    !pts_set) {
1290
                    ipts = pkt.pts;
1291
                    ist->frame_decoded = 0;
1292
                    pts_set = 1;
1293
                }
1294

    
1295
                switch(ist->st->codec.codec_type) {
1296
                case CODEC_TYPE_AUDIO:
1297
                    /* XXX: could avoid copy if PCM 16 bits with same
1298
                       endianness as CPU */
1299
                    ret = avcodec_decode_audio(&ist->st->codec, samples, &data_size,
1300
                                               ptr, len);
1301
                    if (ret < 0)
1302
                        goto fail_decode;
1303
                    /* Some bug in mpeg audio decoder gives */
1304
                    /* data_size < 0, it seems they are overflows */
1305
                    if (data_size <= 0) {
1306
                        /* no audio frame */
1307
                        ptr += ret;
1308
                        len -= ret;
1309
                        continue;
1310
                    }
1311
                    data_buf = (uint8_t *)samples;
1312
                    break;
1313
                case CODEC_TYPE_VIDEO:
1314
                    if (ist->st->codec.codec_id == CODEC_ID_RAWVIDEO) {
1315
                        int size;
1316

    
1317
                        size = (ist->st->codec.width * ist->st->codec.height);
1318
                        avpicture_fill(&picture, ptr, 
1319
                                     ist->st->codec.pix_fmt,
1320
                                     ist->st->codec.width,
1321
                                     ist->st->codec.height);
1322
                        ret = len;
1323
                    } else {
1324
                        AVFrame big_picture;
1325

    
1326
                        data_size = (ist->st->codec.width * ist->st->codec.height * 3) / 2;
1327
                        ret = avcodec_decode_video(&ist->st->codec, 
1328
                                                   &big_picture, &got_picture, ptr, len);
1329
                        picture= *(AVPicture*)&big_picture;
1330
                        ist->st->quality= big_picture.quality;
1331
                        if (ret < 0) {
1332
                        fail_decode:
1333
                            fprintf(stderr, "Error while decoding stream #%d.%d\n",
1334
                                    ist->file_index, ist->index);
1335
                            av_free_packet(&pkt);
1336
                            goto redo;
1337
                        }
1338
                        if (!got_picture) {
1339
                            /* no picture yet */
1340
                            ptr += ret;
1341
                            len -= ret;
1342
                            continue;
1343
                        }
1344
                                  
1345
                    }
1346
                    break;
1347
                default:
1348
                    goto fail_decode;
1349
                }
1350
            } else {
1351
                data_buf = ptr;
1352
                data_size = len;
1353
                ret = len;
1354
            }
1355
            ptr += ret;
1356
            len -= ret;
1357

    
1358
            buffer_to_free = 0;
1359
            if (ist->st->codec.codec_type == CODEC_TYPE_VIDEO) {
1360
                pre_process_video_frame(ist, &picture, &buffer_to_free);
1361
            }
1362

    
1363
            ist->frame_decoded = 1;
1364

    
1365
            /* frame rate emulation */
1366
            if (ist->st->codec.rate_emu) {
1367
                int64_t pts = av_rescale((int64_t) ist->frame * ist->st->codec.frame_rate_base, 1000000, ist->st->codec.frame_rate);
1368
                int64_t now = av_gettime() - ist->start;
1369
                if (pts > now)
1370
                    usleep(pts - now);
1371

    
1372
                ist->frame++;
1373
            }
1374

    
1375
#if 0
1376
            /* mpeg PTS deordering : if it is a P or I frame, the PTS
1377
               is the one of the next displayed one */
1378
            /* XXX: add mpeg4 too ? */
1379
            if (ist->st->codec.codec_id == CODEC_ID_MPEG1VIDEO) {
1380
                if (ist->st->codec.pict_type != B_TYPE) {
1381
                    int64_t tmp;
1382
                    tmp = ist->last_ip_pts;
1383
                    ist->last_ip_pts  = ist->frac_pts.val;
1384
                    ist->frac_pts.val = tmp;
1385
                }
1386
            }
1387
#endif
1388
            /* transcode raw format, encode packets and output them */
1389

    
1390
            for(i=0;i<nb_ostreams;i++) {
1391
                int frame_size;
1392

    
1393
                ost = ost_table[i];
1394
                if (ost->source_index == ist_index) {
1395
                    os = output_files[ost->file_index];
1396

    
1397
                    if (ipts != AV_NOPTS_VALUE) {
1398
#if 0
1399
                        printf("%d: got pts=%f %f\n", 
1400
                               i, pkt.pts / 90000.0, 
1401
                               (ipts - ost->st->pts.val) / 90000.0);
1402
#endif
1403
                        /* set the input output pts pairs */
1404
                        ost->sync_ipts = (double)ipts * is->pts_num / 
1405
                            is->pts_den;
1406
                        /* XXX: take into account the various fifos,
1407
                           in particular for audio */
1408
                        ost->sync_opts = ost->st->pts.val;
1409
                        //printf("ipts=%lld sync_ipts=%f sync_opts=%lld pts.val=%lld pkt.pts=%lld\n", ipts, ost->sync_ipts, ost->sync_opts, ost->st->pts.val, pkt.pts); 
1410
                    } else {
1411
                        //printf("pts.val=%lld\n", ost->st->pts.val); 
1412
                        ost->sync_ipts = AV_NOPTS_VALUE;
1413
                    }
1414

    
1415
                    if (ost->encoding_needed) {
1416
                        switch(ost->st->codec.codec_type) {
1417
                        case CODEC_TYPE_AUDIO:
1418
                            do_audio_out(os, ost, ist, data_buf, data_size);
1419
                            break;
1420
                        case CODEC_TYPE_VIDEO:
1421
                            /* find an audio stream for synchro */
1422
                            {
1423
                                int i;
1424
                                AVOutputStream *audio_sync, *ost1;
1425
                                audio_sync = NULL;
1426
                                for(i=0;i<nb_ostreams;i++) {
1427
                                    ost1 = ost_table[i];
1428
                                    if (ost1->file_index == ost->file_index &&
1429
                                        ost1->st->codec.codec_type == CODEC_TYPE_AUDIO) {
1430
                                        audio_sync = ost1;
1431
                                        break;
1432
                                    }
1433
                                }
1434

    
1435
                                do_video_out(os, ost, ist, &picture, &frame_size, audio_sync);
1436
                                if (do_vstats && frame_size)
1437
                                    do_video_stats(os, ost, frame_size);
1438
                            }
1439
                            break;
1440
                        default:
1441
                            av_abort();
1442
                        }
1443
                    } else {
1444
                        AVFrame avframe;
1445
                                                
1446
                        /* no reencoding needed : output the packet directly */
1447
                        /* force the input stream PTS */
1448
                        
1449
                        //XXX/FIXME set keyframe flag from demuxer (or optionally from decoder)
1450
                        memset(&avframe, 0, sizeof(AVFrame));
1451
                        ost->st->codec.coded_frame= &avframe;
1452
                        
1453
                        av_write_frame(os, ost->index, data_buf, data_size);
1454
                        ost->st->codec.frame_number++;
1455
                        ost->frame_number++;
1456
                    }
1457
                }
1458
            }
1459
            av_free(buffer_to_free);
1460
            ipts = AV_NOPTS_VALUE;
1461
        }
1462
    discard_packet:
1463
        av_free_packet(&pkt);
1464
        
1465
        /* dump report by using the output first video and audio streams */
1466
        print_report(output_files, ost_table, nb_ostreams, 0);
1467
    }
1468
    term_exit();
1469

    
1470
    /* dump report by using the first video and audio streams */
1471
    print_report(output_files, ost_table, nb_ostreams, 1);
1472

    
1473
    /* close each encoder */
1474
    for(i=0;i<nb_ostreams;i++) {
1475
        ost = ost_table[i];
1476
        if (ost->encoding_needed) {
1477
            av_freep(&ost->st->codec.stats_in);
1478
            avcodec_close(&ost->st->codec);
1479
        }
1480
    }
1481
    
1482
    /* close each decoder */
1483
    for(i=0;i<nb_istreams;i++) {
1484
        ist = ist_table[i];
1485
        if (ist->decoding_needed) {
1486
            avcodec_close(&ist->st->codec);
1487
        }
1488
    }
1489
    
1490

    
1491
    /* write the trailer if needed and close file */
1492
    for(i=0;i<nb_output_files;i++) {
1493
        os = output_files[i];
1494
        av_write_trailer(os);
1495
    }
1496
    /* finished ! */
1497
    
1498
    ret = 0;
1499
 fail1:
1500
    av_free(file_table);
1501

    
1502
    if (ist_table) {
1503
        for(i=0;i<nb_istreams;i++) {
1504
            ist = ist_table[i];
1505
            av_free(ist);
1506
        }
1507
        av_free(ist_table);
1508
    }
1509
    if (ost_table) {
1510
        for(i=0;i<nb_ostreams;i++) {
1511
            ost = ost_table[i];
1512
            if (ost) {
1513
                if (ost->logfile) {
1514
                    fclose(ost->logfile);
1515
                    ost->logfile = NULL;
1516
                }
1517
                fifo_free(&ost->fifo); /* works even if fifo is not
1518
                                          initialized but set to zero */
1519
                av_free(ost->pict_tmp.data[0]);
1520
                if (ost->video_resample)
1521
                    img_resample_close(ost->img_resample_ctx);
1522
                if (ost->audio_resample)
1523
                    audio_resample_close(ost->resample);
1524
                av_free(ost);
1525
            }
1526
        }
1527
        av_free(ost_table);
1528
    }
1529
    return ret;
1530
 fail:
1531
    ret = -ENOMEM;
1532
    goto fail1;
1533
}
1534

    
1535
#if 0
1536
int file_read(const char *filename)
1537
{
1538
    URLContext *h;
1539
    unsigned char buffer[1024];
1540
    int len, i;
1541

1542
    if (url_open(&h, filename, O_RDONLY) < 0) {
1543
        printf("could not open '%s'\n", filename);
1544
        return -1;
1545
    }
1546
    for(;;) {
1547
        len = url_read(h, buffer, sizeof(buffer));
1548
        if (len <= 0)
1549
            break;
1550
        for(i=0;i<len;i++) putchar(buffer[i]);
1551
    }
1552
    url_close(h);
1553
    return 0;
1554
}
1555
#endif
1556

    
1557
static void show_licence(void)
1558
{
1559
    printf(
1560
    "ffmpeg version " FFMPEG_VERSION "\n"
1561
    "Copyright (c) 2000, 2001, 2002 Fabrice Bellard\n"
1562
    "This library is free software; you can redistribute it and/or\n"
1563
    "modify it under the terms of the GNU Lesser General Public\n"
1564
    "License as published by the Free Software Foundation; either\n"
1565
    "version 2 of the License, or (at your option) any later version.\n"
1566
    "\n"
1567
    "This library is distributed in the hope that it will be useful,\n"
1568
    "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
1569
    "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n"
1570
    "Lesser General Public License for more details.\n"
1571
    "\n"
1572
    "You should have received a copy of the GNU Lesser General Public\n"
1573
    "License along with this library; if not, write to the Free Software\n"
1574
    "Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n"
1575
    );
1576
    exit(1);
1577
}
1578

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

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

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

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

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

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

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

    
1630
static void opt_video_buffer_size(const char *arg)
1631
{
1632
    video_rc_buffer_size = atoi(arg) * 1000;
1633
}
1634

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

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

    
1645

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

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

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

    
1661

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

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

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

    
1677
static void opt_frame_rate(const char *arg)
1678
{
1679
    frame_rate_base = DEFAULT_FRAME_RATE_BASE; //FIXME not optimal
1680
    frame_rate = (int)(strtod(arg, 0) * frame_rate_base + 0.5);
1681
    //FIXME parse fractions 
1682
}
1683

    
1684

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

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

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

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

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

    
1770
static void opt_gop_size(const char *arg)
1771
{
1772
    gop_size = atoi(arg);
1773
}
1774

    
1775
static void opt_b_frames(const char *arg)
1776
{
1777
    b_frames = atoi(arg);
1778
    if (b_frames > FF_MAX_B_FRAMES) {
1779
        fprintf(stderr, "\nCannot have more than %d B frames, increase FF_MAX_B_FRAMES.\n", FF_MAX_B_FRAMES);
1780
        exit(1);
1781
    } else if (b_frames < 1) {
1782
        fprintf(stderr, "\nNumber of B frames must be higher than 0\n");
1783
        exit(1);
1784
    }
1785
}
1786

    
1787
static void opt_qscale(const char *arg)
1788
{
1789
    video_qscale = atoi(arg);
1790
    if (video_qscale < 0 ||
1791
        video_qscale > 31) {
1792
        fprintf(stderr, "qscale must be >= 1 and <= 31\n");
1793
        exit(1);
1794
    }
1795
}
1796

    
1797
static void opt_qmin(const char *arg)
1798
{
1799
    video_qmin = atoi(arg);
1800
    if (video_qmin < 0 ||
1801
        video_qmin > 31) {
1802
        fprintf(stderr, "qmin must be >= 1 and <= 31\n");
1803
        exit(1);
1804
    }
1805
}
1806

    
1807
static void opt_qmax(const char *arg)
1808
{
1809
    video_qmax = atoi(arg);
1810
    if (video_qmax < 0 ||
1811
        video_qmax > 31) {
1812
        fprintf(stderr, "qmax must be >= 1 and <= 31\n");
1813
        exit(1);
1814
    }
1815
}
1816

    
1817
static void opt_mb_qmin(const char *arg)
1818
{
1819
    video_mb_qmin = atoi(arg);
1820
    if (video_mb_qmin < 0 ||
1821
        video_mb_qmin > 31) {
1822
        fprintf(stderr, "qmin must be >= 1 and <= 31\n");
1823
        exit(1);
1824
    }
1825
}
1826

    
1827
static void opt_mb_qmax(const char *arg)
1828
{
1829
    video_mb_qmax = atoi(arg);
1830
    if (video_mb_qmax < 0 ||
1831
        video_mb_qmax > 31) {
1832
        fprintf(stderr, "qmax must be >= 1 and <= 31\n");
1833
        exit(1);
1834
    }
1835
}
1836

    
1837
static void opt_qdiff(const char *arg)
1838
{
1839
    video_qdiff = atoi(arg);
1840
    if (video_qdiff < 0 ||
1841
        video_qdiff > 31) {
1842
        fprintf(stderr, "qdiff must be >= 1 and <= 31\n");
1843
        exit(1);
1844
    }
1845
}
1846

    
1847
static void opt_qblur(const char *arg)
1848
{
1849
    video_qblur = atof(arg);
1850
}
1851

    
1852
static void opt_qcomp(const char *arg)
1853
{
1854
    video_qcomp = atof(arg);
1855
}
1856

    
1857
static void opt_rc_initial_cplx(const char *arg)
1858
{
1859
    video_rc_initial_cplx = atof(arg);
1860
}
1861
static void opt_b_qfactor(const char *arg)
1862
{
1863
    video_b_qfactor = atof(arg);
1864
}
1865
static void opt_i_qfactor(const char *arg)
1866
{
1867
    video_i_qfactor = atof(arg);
1868
}
1869
static void opt_b_qoffset(const char *arg)
1870
{
1871
    video_b_qoffset = atof(arg);
1872
}
1873
static void opt_i_qoffset(const char *arg)
1874
{
1875
    video_i_qoffset = atof(arg);
1876
}
1877

    
1878
static void opt_packet_size(const char *arg)
1879
{
1880
    packet_size= atoi(arg);
1881
}
1882

    
1883
static void opt_strict(const char *arg)
1884
{
1885
    strict= atoi(arg);
1886
}
1887

    
1888
static void opt_audio_bitrate(const char *arg)
1889
{
1890
    audio_bit_rate = atoi(arg) * 1000;
1891
}
1892

    
1893
static void opt_audio_rate(const char *arg)
1894
{
1895
    audio_sample_rate = atoi(arg);
1896
}
1897

    
1898
static void opt_audio_channels(const char *arg)
1899
{
1900
    audio_channels = atoi(arg);
1901
}
1902

    
1903
static void opt_video_device(const char *arg)
1904
{
1905
    video_device = av_strdup(arg);
1906
}
1907

    
1908
static void opt_video_channel(const char *arg)
1909
{
1910
    video_channel = strtol(arg, NULL, 0);
1911
}
1912

    
1913
static void opt_audio_device(const char *arg)
1914
{
1915
    audio_device = av_strdup(arg);
1916
}
1917

    
1918
static void opt_dv1394(const char *arg)
1919
{
1920
    video_grab_format = "dv1394";
1921
    audio_grab_format = NULL;
1922
}
1923

    
1924
static void opt_audio_codec(const char *arg)
1925
{
1926
    AVCodec *p;
1927

    
1928
    if (!strcmp(arg, "copy")) {
1929
        audio_stream_copy = 1;
1930
    } else {
1931
        p = first_avcodec;
1932
        while (p) {
1933
            if (!strcmp(p->name, arg) && p->type == CODEC_TYPE_AUDIO)
1934
                break;
1935
            p = p->next;
1936
        }
1937
        if (p == NULL) {
1938
            fprintf(stderr, "Unknown audio codec '%s'\n", arg);
1939
            exit(1);
1940
        } else {
1941
            audio_codec_id = p->id;
1942
        }
1943
    }
1944
}
1945

    
1946
static void add_frame_hooker(const char *arg)
1947
{
1948
    int argc = 0;
1949
    char *argv[64];
1950
    int i;
1951
    char *args = av_strdup(arg);
1952

    
1953
    argv[0] = strtok(args, " ");
1954
    while (argc < 62 && (argv[++argc] = strtok(NULL, " "))) {
1955
    }
1956

    
1957
    i = frame_hook_add(argc, argv);
1958

    
1959
    if (i != 0) {
1960
        fprintf(stderr, "Failed to add video hook function: %s\n", arg);
1961
        exit(1);
1962
    }
1963
}
1964

    
1965
const char *motion_str[] = {
1966
    "zero",
1967
    "full",
1968
    "log",
1969
    "phods",
1970
    "epzs",
1971
    "x1",
1972
    NULL,
1973
};
1974

    
1975
static void opt_motion_estimation(const char *arg)
1976
{
1977
    const char **p;
1978
    p = motion_str;
1979
    for(;;) {
1980
        if (!*p) {
1981
            fprintf(stderr, "Unknown motion estimation method '%s'\n", arg);
1982
            exit(1);
1983
        }
1984
        if (!strcmp(*p, arg))
1985
            break;
1986
        p++;
1987
    }
1988
    me_method = (p - motion_str) + 1;
1989
}
1990

    
1991
static void opt_video_codec(const char *arg)
1992
{
1993
    AVCodec *p;
1994

    
1995
    if (!strcmp(arg, "copy")) {
1996
        video_stream_copy = 1;
1997
    } else {
1998
        p = first_avcodec;
1999
        while (p) {
2000
            if (!strcmp(p->name, arg) && p->type == CODEC_TYPE_VIDEO)
2001
                break;
2002
            p = p->next;
2003
        }
2004
        if (p == NULL) {
2005
            fprintf(stderr, "Unknown video codec '%s'\n", arg);
2006
            exit(1);
2007
        } else {
2008
            video_codec_id = p->id;
2009
        }
2010
    }
2011
}
2012

    
2013
static void opt_map(const char *arg)
2014
{
2015
    AVStreamMap *m;
2016
    const char *p;
2017

    
2018
    p = arg;
2019
    m = &stream_maps[nb_stream_maps++];
2020

    
2021
    m->file_index = strtol(arg, (char **)&p, 0);
2022
    if (*p)
2023
        p++;
2024

    
2025
    m->stream_index = strtol(p, (char **)&p, 0);
2026
}
2027

    
2028
static void opt_recording_time(const char *arg)
2029
{
2030
    recording_time = parse_date(arg, 1);
2031
}
2032

    
2033
static void print_error(const char *filename, int err)
2034
{
2035
    switch(err) {
2036
    case AVERROR_NUMEXPECTED:
2037
        fprintf(stderr, "%s: Incorrect image filename syntax.\n"
2038
                "Use '%%d' to specify the image number:\n"
2039
                "  for img1.jpg, img2.jpg, ..., use 'img%%d.jpg';\n"
2040
                "  for img001.jpg, img002.jpg, ..., use 'img%%03d.jpg'.\n", 
2041
                filename);
2042
        break;
2043
    case AVERROR_INVALIDDATA:
2044
        fprintf(stderr, "%s: Error while parsing header\n", filename);
2045
        break;
2046
    case AVERROR_NOFMT:
2047
        fprintf(stderr, "%s: Unknown format\n", filename);
2048
        break;
2049
    default:
2050
        fprintf(stderr, "%s: Error while opening file\n", filename);
2051
        break;
2052
    }
2053
}
2054

    
2055
static void opt_input_file(const char *filename)
2056
{
2057
    AVFormatContext *ic;
2058
    AVFormatParameters params, *ap = &params;
2059
    int err, i, ret, rfps, rfps_base;
2060

    
2061
    if (!strcmp(filename, "-"))
2062
        filename = "pipe:";
2063

    
2064
    /* get default parameters from command line */
2065
    memset(ap, 0, sizeof(*ap));
2066
    ap->sample_rate = audio_sample_rate;
2067
    ap->channels = audio_channels;
2068
    ap->frame_rate = frame_rate;
2069
    ap->frame_rate_base = frame_rate_base;
2070
    ap->width = frame_width;
2071
    ap->height = frame_height;
2072
    ap->image_format = image_format;
2073

    
2074
    /* open the input file with generic libav function */
2075
    err = av_open_input_file(&ic, filename, file_iformat, 0, ap);
2076
    if (err < 0) {
2077
        print_error(filename, err);
2078
        exit(1);
2079
    }
2080
    
2081
    /* If not enough info to get the stream parameters, we decode the
2082
       first frames to get it. (used in mpeg case for example) */
2083
    ret = av_find_stream_info(ic);
2084
    if (ret < 0) {
2085
        fprintf(stderr, "%s: could not find codec parameters\n", filename);
2086
        exit(1);
2087
    }
2088

    
2089
    /* update the current parameters so that they match the one of the input stream */
2090
    for(i=0;i<ic->nb_streams;i++) {
2091
        AVCodecContext *enc = &ic->streams[i]->codec;
2092
        switch(enc->codec_type) {
2093
        case CODEC_TYPE_AUDIO:
2094
            //fprintf(stderr, "\nInput Audio channels: %d", enc->channels);
2095
            audio_channels = enc->channels;
2096
            audio_sample_rate = enc->sample_rate;
2097
            break;
2098
        case CODEC_TYPE_VIDEO:
2099
            frame_height = enc->height;
2100
            frame_width = enc->width;
2101
            rfps      = ic->streams[i]->r_frame_rate;
2102
            rfps_base = ic->streams[i]->r_frame_rate_base;
2103
            enc->workaround_bugs = workaround_bugs;
2104
            enc->error_resilience = error_resilience; 
2105
            enc->error_concealment = error_concealment; 
2106
            enc->idct_algo= idct_algo;
2107
            enc->debug= debug;
2108
/*            if(enc->codec->capabilities & CODEC_CAP_TRUNCATED)
2109
                enc->flags|= CODEC_FLAG_TRUNCATED; */
2110
            if(/*enc->codec_id==CODEC_ID_MPEG4 || */enc->codec_id==CODEC_ID_MPEG1VIDEO)
2111
                enc->flags|= CODEC_FLAG_TRUNCATED;
2112
            
2113
            if(bitexact)
2114
                enc->flags|= CODEC_FLAG_BITEXACT;
2115

    
2116
            assert(enc->frame_rate_base == rfps_base); // should be true for now
2117
            if (enc->frame_rate != rfps) { 
2118
                fprintf(stderr,"\nSeems that stream %d comes from film source: %2.2f->%2.2f\n",
2119
                    i, (float)enc->frame_rate / enc->frame_rate_base,
2120
                    (float)rfps / rfps_base);
2121
            }
2122
            /* update the current frame rate to match the stream frame rate */
2123
            frame_rate      = rfps;
2124
            frame_rate_base = rfps_base;
2125

    
2126
            enc->rate_emu = rate_emu;
2127
            break;
2128
        default:
2129
            av_abort();
2130
        }
2131
    }
2132
    
2133
    input_files[nb_input_files] = ic;
2134
    /* dump the file content */
2135
    dump_format(ic, nb_input_files, filename, 0);
2136
    nb_input_files++;
2137
    file_iformat = NULL;
2138
    file_oformat = NULL;
2139
    image_format = NULL;
2140

    
2141
    rate_emu = 0;
2142
}
2143

    
2144
static void check_audio_video_inputs(int *has_video_ptr, int *has_audio_ptr)
2145
{
2146
    int has_video, has_audio, i, j;
2147
    AVFormatContext *ic;
2148

    
2149
    has_video = 0;
2150
    has_audio = 0;
2151
    for(j=0;j<nb_input_files;j++) {
2152
        ic = input_files[j];
2153
        for(i=0;i<ic->nb_streams;i++) {
2154
            AVCodecContext *enc = &ic->streams[i]->codec;
2155
            switch(enc->codec_type) {
2156
            case CODEC_TYPE_AUDIO:
2157
                has_audio = 1;
2158
                break;
2159
            case CODEC_TYPE_VIDEO:
2160
                has_video = 1;
2161
                break;
2162
            default:
2163
                av_abort();
2164
            }
2165
        }
2166
    }
2167
    *has_video_ptr = has_video;
2168
    *has_audio_ptr = has_audio;
2169
}
2170

    
2171
static void opt_output_file(const char *filename)
2172
{
2173
    AVStream *st;
2174
    AVFormatContext *oc;
2175
    int use_video, use_audio, nb_streams, input_has_video, input_has_audio;
2176
    int codec_id;
2177
    AVFormatParameters params, *ap = &params;
2178

    
2179
    if (!strcmp(filename, "-"))
2180
        filename = "pipe:";
2181

    
2182
    oc = av_mallocz(sizeof(AVFormatContext));
2183

    
2184
    if (!file_oformat) {
2185
        file_oformat = guess_format(NULL, filename, NULL);
2186
        if (!file_oformat) {
2187
            fprintf(stderr, "Unable for find a suitable output format for '%s'\n",
2188
                    filename);
2189
            exit(1);
2190
        }
2191
    }
2192
    
2193
    oc->oformat = file_oformat;
2194

    
2195
    if (!strcmp(file_oformat->name, "ffm") && 
2196
        strstart(filename, "http:", NULL)) {
2197
        /* special case for files sent to ffserver: we get the stream
2198
           parameters from ffserver */
2199
        if (read_ffserver_streams(oc, filename) < 0) {
2200
            fprintf(stderr, "Could not read stream parameters from '%s'\n", filename);
2201
            exit(1);
2202
        }
2203
    } else {
2204
        use_video = file_oformat->video_codec != CODEC_ID_NONE;
2205
        use_audio = file_oformat->audio_codec != CODEC_ID_NONE;
2206

    
2207
        /* disable if no corresponding type found and at least one
2208
           input file */
2209
        if (nb_input_files > 0) {
2210
            check_audio_video_inputs(&input_has_video, &input_has_audio);
2211
            if (!input_has_video)
2212
                use_video = 0;
2213
            if (!input_has_audio)
2214
                use_audio = 0;
2215
        }
2216

    
2217
        /* manual disable */
2218
        if (audio_disable) {
2219
            use_audio = 0;
2220
        }
2221
        if (video_disable) {
2222
            use_video = 0;
2223
        }
2224
        
2225
        nb_streams = 0;
2226
        if (use_video) {
2227
            AVCodecContext *video_enc;
2228
            
2229
            st = av_mallocz(sizeof(AVStream));
2230
            if (!st) {
2231
                fprintf(stderr, "Could not alloc stream\n");
2232
                exit(1);
2233
            }
2234
            avcodec_get_context_defaults(&st->codec);
2235

    
2236
            video_enc = &st->codec;
2237
            if (video_stream_copy) {
2238
                st->stream_copy = 1;
2239
                video_enc->codec_type = CODEC_TYPE_VIDEO;
2240
            } else {
2241
                char *p;
2242
                int i;
2243
            
2244
                codec_id = file_oformat->video_codec;
2245
                if (video_codec_id != CODEC_ID_NONE)
2246
                    codec_id = video_codec_id;
2247
                
2248
                video_enc->codec_id = codec_id;
2249
                
2250
                video_enc->bit_rate = video_bit_rate;
2251
                video_enc->bit_rate_tolerance = video_bit_rate_tolerance;
2252
                video_enc->frame_rate = frame_rate; 
2253
                video_enc->frame_rate_base = frame_rate_base; 
2254
                
2255
                video_enc->width = frame_width;
2256
                video_enc->height = frame_height;
2257

    
2258
                if (!intra_only)
2259
                    video_enc->gop_size = gop_size;
2260
                else
2261
                    video_enc->gop_size = 0;
2262
                if (video_qscale || same_quality) {
2263
                    video_enc->flags |= CODEC_FLAG_QSCALE;
2264
                    st->quality = video_qscale;
2265
                }
2266
                
2267
                if(bitexact)
2268
                    video_enc->flags |= CODEC_FLAG_BITEXACT;
2269

    
2270
                if (use_hq) {
2271
                    video_enc->flags |= CODEC_FLAG_HQ;
2272
                }
2273
                   /* Fx */ 
2274
                if (use_umv) {
2275
                    video_enc->flags |= CODEC_FLAG_H263P_UMV;
2276
                }
2277
                   if (use_aic) {
2278
                    video_enc->flags |= CODEC_FLAG_H263P_AIC;
2279
                }
2280
                   /* /Fx */ 
2281
                if (use_4mv) {
2282
                    video_enc->flags |= CODEC_FLAG_HQ;
2283
                    video_enc->flags |= CODEC_FLAG_4MV;
2284
                }
2285
            
2286
                if(use_part)
2287
                    video_enc->flags |= CODEC_FLAG_PART;
2288
               
2289
            
2290
                if (b_frames) {
2291
                    video_enc->max_b_frames = b_frames;
2292
                    video_enc->b_frame_strategy = 0;
2293
                    video_enc->b_quant_factor = 2.0;
2294
                }
2295
            
2296
                video_enc->qmin = video_qmin;
2297
                video_enc->qmax = video_qmax;
2298
                video_enc->mb_qmin = video_mb_qmin;
2299
                video_enc->mb_qmax = video_mb_qmax;
2300
                video_enc->max_qdiff = video_qdiff;
2301
                video_enc->qblur = video_qblur;
2302
                video_enc->qcompress = video_qcomp;
2303
                video_enc->rc_eq = video_rc_eq;
2304
                video_enc->debug= debug;
2305
                
2306
                p= video_rc_override_string;
2307
                for(i=0; p; i++){
2308
                    int start, end, q;
2309
                    int e=sscanf(p, "%d,%d,%d", &start, &end, &q);
2310
                    if(e!=3){
2311
                        fprintf(stderr, "error parsing rc_override\n");
2312
                        exit(1);
2313
                    }
2314
                    video_enc->rc_override= 
2315
                        av_realloc(video_enc->rc_override, 
2316
                                   sizeof(RcOverride)*(i+1));
2317
                    video_enc->rc_override[i].start_frame= start;
2318
                    video_enc->rc_override[i].end_frame  = end;
2319
                    if(q>0){
2320
                        video_enc->rc_override[i].qscale= q;
2321
                        video_enc->rc_override[i].quality_factor= 1.0;
2322
                    }
2323
                    else{
2324
                        video_enc->rc_override[i].qscale= 0;
2325
                        video_enc->rc_override[i].quality_factor= -q/100.0;
2326
                    }
2327
                    p= strchr(p, '/');
2328
                    if(p) p++;
2329
                }
2330
                video_enc->rc_override_count=i;
2331

    
2332
                video_enc->rc_max_rate = video_rc_max_rate;
2333
                video_enc->rc_min_rate = video_rc_min_rate;
2334
                video_enc->rc_buffer_size = video_rc_buffer_size;
2335
                video_enc->rc_buffer_aggressivity= video_rc_buffer_aggressivity;
2336
                video_enc->rc_initial_cplx= video_rc_initial_cplx;
2337
                video_enc->i_quant_factor = video_i_qfactor;
2338
                video_enc->b_quant_factor = video_b_qfactor;
2339
                video_enc->i_quant_offset = video_i_qoffset;
2340
                video_enc->b_quant_offset = video_b_qoffset;
2341
                video_enc->dct_algo = dct_algo;
2342
                video_enc->idct_algo = idct_algo;
2343
                video_enc->strict_std_compliance = strict;
2344
                if(packet_size){
2345
                    video_enc->rtp_mode= 1;
2346
                    video_enc->rtp_payload_size= packet_size;
2347
                }
2348
            
2349
                if (do_psnr)
2350
                    video_enc->flags|= CODEC_FLAG_PSNR;
2351
            
2352
                video_enc->me_method = me_method;
2353

    
2354
                /* two pass mode */
2355
                if (do_pass) {
2356
                    if (do_pass == 1) {
2357
                        video_enc->flags |= CODEC_FLAG_PASS1;
2358
                    } else {
2359
                        video_enc->flags |= CODEC_FLAG_PASS2;
2360
                    }
2361
                }
2362
            }
2363
            oc->streams[nb_streams] = st;
2364
            nb_streams++;
2365
        }
2366
    
2367
        if (use_audio) {
2368
            AVCodecContext *audio_enc;
2369

    
2370
            st = av_mallocz(sizeof(AVStream));
2371
            if (!st) {
2372
                fprintf(stderr, "Could not alloc stream\n");
2373
                exit(1);
2374
            }
2375
            avcodec_get_context_defaults(&st->codec);
2376

    
2377
            audio_enc = &st->codec;
2378
            audio_enc->codec_type = CODEC_TYPE_AUDIO;
2379
            if (audio_stream_copy) {
2380
                st->stream_copy = 1;
2381
            } else {
2382
                codec_id = file_oformat->audio_codec;
2383
                if (audio_codec_id != CODEC_ID_NONE)
2384
                    codec_id = audio_codec_id;
2385
                audio_enc->codec_id = codec_id;
2386
                
2387
                audio_enc->bit_rate = audio_bit_rate;
2388
                audio_enc->sample_rate = audio_sample_rate;
2389
                /* For audio codecs other than AC3 we limit */
2390
                /* the number of coded channels to stereo   */
2391
                if (audio_channels > 2 && codec_id != CODEC_ID_AC3) {
2392
                    audio_enc->channels = 2;
2393
                } else
2394
                    audio_enc->channels = audio_channels;
2395
            }
2396
            oc->streams[nb_streams] = st;
2397
            nb_streams++;
2398
        }
2399

    
2400
        oc->nb_streams = nb_streams;
2401

    
2402
        if (!nb_streams) {
2403
            fprintf(stderr, "No audio or video streams available\n");
2404
            exit(1);
2405
        }
2406

    
2407
        if (str_title)
2408
            pstrcpy(oc->title, sizeof(oc->title), str_title);
2409
        if (str_author)
2410
            pstrcpy(oc->author, sizeof(oc->author), str_author);
2411
        if (str_copyright)
2412
            pstrcpy(oc->copyright, sizeof(oc->copyright), str_copyright);
2413
        if (str_comment)
2414
            pstrcpy(oc->comment, sizeof(oc->comment), str_comment);
2415
    }
2416

    
2417
    output_files[nb_output_files++] = oc;
2418

    
2419
    strcpy(oc->filename, filename);
2420

    
2421
    /* check filename in case of an image number is expected */
2422
    if (oc->oformat->flags & AVFMT_NEEDNUMBER) {
2423
        if (filename_number_test(oc->filename) < 0) {
2424
            print_error(oc->filename, AVERROR_NUMEXPECTED);
2425
            exit(1);
2426
        }
2427
    }
2428

    
2429
    if (!(oc->oformat->flags & AVFMT_NOFILE)) {
2430
        /* test if it already exists to avoid loosing precious files */
2431
        if (!file_overwrite && 
2432
            (strchr(filename, ':') == NULL ||
2433
             strstart(filename, "file:", NULL))) {
2434
            if (url_exist(filename)) {
2435
                int c;
2436
                
2437
                printf("File '%s' already exists. Overwrite ? [y/N] ", filename);
2438
                fflush(stdout);
2439
                c = getchar();
2440
                if (toupper(c) != 'Y') {
2441
                    fprintf(stderr, "Not overwriting - exiting\n");
2442
                    exit(1);
2443
                }
2444
            }
2445
        }
2446
        
2447
        /* open the file */
2448
        if (url_fopen(&oc->pb, filename, URL_WRONLY) < 0) {
2449
            fprintf(stderr, "Could not open '%s'\n", filename);
2450
            exit(1);
2451
        }
2452
    }
2453

    
2454
    memset(ap, 0, sizeof(*ap));
2455
    ap->image_format = image_format;
2456
    if (av_set_parameters(oc, ap) < 0) {
2457
        fprintf(stderr, "%s: Invalid encoding parameters\n",
2458
                oc->filename);
2459
        exit(1);
2460
    }
2461

    
2462
    /* reset some options */
2463
    file_oformat = NULL;
2464
    file_iformat = NULL;
2465
    image_format = NULL;
2466
    audio_disable = 0;
2467
    video_disable = 0;
2468
    audio_codec_id = CODEC_ID_NONE;
2469
    video_codec_id = CODEC_ID_NONE;
2470
    audio_stream_copy = 0;
2471
    video_stream_copy = 0;
2472
}
2473

    
2474
/* prepare dummy protocols for grab */
2475
static void prepare_grab(void)
2476
{
2477
    int has_video, has_audio, i, j;
2478
    AVFormatContext *oc;
2479
    AVFormatContext *ic;
2480
    AVFormatParameters vp1, *vp = &vp1;
2481
    AVFormatParameters ap1, *ap = &ap1;
2482
    
2483
    /* see if audio/video inputs are needed */
2484
    has_video = 0;
2485
    has_audio = 0;
2486
    memset(ap, 0, sizeof(*ap));
2487
    memset(vp, 0, sizeof(*vp));
2488
    for(j=0;j<nb_output_files;j++) {
2489
        oc = output_files[j];
2490
        for(i=0;i<oc->nb_streams;i++) {
2491
            AVCodecContext *enc = &oc->streams[i]->codec;
2492
            switch(enc->codec_type) {
2493
            case CODEC_TYPE_AUDIO:
2494
                if (enc->sample_rate > ap->sample_rate)
2495
                    ap->sample_rate = enc->sample_rate;
2496
                if (enc->channels > ap->channels)
2497
                    ap->channels = enc->channels;
2498
                has_audio = 1;
2499
                break;
2500
            case CODEC_TYPE_VIDEO:
2501
                if (enc->width > vp->width)
2502
                    vp->width = enc->width;
2503
                if (enc->height > vp->height)
2504
                    vp->height = enc->height;
2505
                
2506
                assert(enc->frame_rate_base == DEFAULT_FRAME_RATE_BASE);
2507
                if (enc->frame_rate > vp->frame_rate){
2508
                    vp->frame_rate      = enc->frame_rate;
2509
                    vp->frame_rate_base = enc->frame_rate_base;
2510
                }
2511
                has_video = 1;
2512
                break;
2513
            default:
2514
                av_abort();
2515
            }
2516
        }
2517
    }
2518
    
2519
    if (has_video == 0 && has_audio == 0) {
2520
        fprintf(stderr, "Output file must have at least one audio or video stream\n");
2521
        exit(1);
2522
    }
2523
    
2524
    if (has_video) {
2525
        AVInputFormat *fmt1;
2526
        fmt1 = av_find_input_format(video_grab_format);
2527
        vp->device  = video_device;
2528
        vp->channel = video_channel;
2529
        if (av_open_input_file(&ic, "", fmt1, 0, vp) < 0) {
2530
            fprintf(stderr, "Could not find video grab device\n");
2531
            exit(1);
2532
        }
2533
        /* by now video grab has one stream */
2534
        ic->streams[0]->r_frame_rate      = vp->frame_rate;
2535
        ic->streams[0]->r_frame_rate_base = vp->frame_rate_base;
2536
        input_files[nb_input_files] = ic;
2537
        dump_format(ic, nb_input_files, "", 0);
2538
        nb_input_files++;
2539
    }
2540
    if (has_audio && audio_grab_format) {
2541
        AVInputFormat *fmt1;
2542
        fmt1 = av_find_input_format(audio_grab_format);
2543
        ap->device = audio_device;
2544
        if (av_open_input_file(&ic, "", fmt1, 0, ap) < 0) {
2545
            fprintf(stderr, "Could not find audio grab device\n");
2546
            exit(1);
2547
        }
2548
        input_files[nb_input_files] = ic;
2549
        dump_format(ic, nb_input_files, "", 0);
2550
        nb_input_files++;
2551
    }
2552
}
2553

    
2554
/* open the necessary output devices for playing */
2555
static void prepare_play(void)
2556
{
2557
    int has_video, has_audio;
2558
    
2559
    check_audio_video_inputs(&has_video, &has_audio);
2560
        
2561
    /* manual disable */
2562
    if (audio_disable) {
2563
        has_audio = 0;
2564
    }
2565
    if (video_disable) {
2566
        has_video = 0;
2567
    }
2568
        
2569
    if (has_audio) {
2570
        file_oformat = guess_format("audio_device", NULL, NULL);
2571
        if (!file_oformat) {
2572
            fprintf(stderr, "Could not find audio device\n");
2573
            exit(1);
2574
        }
2575
        opt_output_file(audio_device?audio_device:"/dev/dsp");
2576
    }
2577

    
2578
    if (has_video) {
2579
        file_oformat = guess_format("framebuffer_device", NULL, NULL);
2580
        if (!file_oformat) {
2581
            fprintf(stderr, "Could not find framebuffer device\n");
2582
            exit(1);
2583
        }
2584
        opt_output_file("");
2585
    }
2586
}
2587

    
2588
/* same option as mencoder */
2589
static void opt_pass(const char *pass_str)
2590
{
2591
    int pass;
2592
    pass = atoi(pass_str);
2593
    if (pass != 1 && pass != 2) {
2594
        fprintf(stderr, "pass number can be only 1 or 2\n");
2595
        exit(1);
2596
    }
2597
    do_pass = pass;
2598
}
2599

    
2600
#if defined(CONFIG_WIN32) || defined(CONFIG_OS2)
2601
static int64_t getutime(void)
2602
{
2603
  return av_gettime();
2604
}
2605
#else
2606
static int64_t getutime(void)
2607
{
2608
    struct rusage rusage;
2609

    
2610
    getrusage(RUSAGE_SELF, &rusage);
2611
    return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
2612
}
2613
#endif
2614

    
2615
extern int ffm_nopts;
2616

    
2617
static void opt_bitexact(void)
2618
{
2619
    bitexact=1;
2620
    /* disable generate of real time pts in ffm (need to be supressed anyway) */
2621
    ffm_nopts = 1;
2622
}
2623

    
2624
static void show_formats(void)
2625
{
2626
    AVInputFormat *ifmt;
2627
    AVOutputFormat *ofmt;
2628
    AVImageFormat *image_fmt;
2629
    URLProtocol *up;
2630
    AVCodec *p;
2631
    const char **pp;
2632

    
2633
    printf("Output audio/video file formats:");
2634
    for(ofmt = first_oformat; ofmt != NULL; ofmt = ofmt->next) {
2635
        printf(" %s", ofmt->name);
2636
    }
2637
    printf("\n");
2638

    
2639
    printf("Input audio/video file formats:");
2640
    for(ifmt = first_iformat; ifmt != NULL; ifmt = ifmt->next) {
2641
        printf(" %s", ifmt->name);
2642
    }
2643
    printf("\n");
2644

    
2645
    printf("Output image formats:");
2646
    for(image_fmt = first_image_format; image_fmt != NULL; 
2647
        image_fmt = image_fmt->next) {
2648
        if (image_fmt->img_write)
2649
            printf(" %s", image_fmt->name);
2650
    }
2651
    printf("\n");
2652

    
2653
    printf("Input image formats:");
2654
    for(image_fmt = first_image_format; image_fmt != NULL; 
2655
        image_fmt = image_fmt->next) {
2656
        if (image_fmt->img_read)
2657
            printf(" %s", image_fmt->name);
2658
    }
2659
    printf("\n");
2660

    
2661
    printf("Codecs:\n");
2662
    printf("  Encoders:");
2663
    for(p = first_avcodec; p != NULL; p = p->next) {
2664
        if (p->encode)
2665
            printf(" %s", p->name);
2666
    }
2667
    printf("\n");
2668

    
2669
    printf("  Decoders:");
2670
    for(p = first_avcodec; p != NULL; p = p->next) {
2671
        if (p->decode)
2672
            printf(" %s", p->name);
2673
    }
2674
    printf("\n");
2675

    
2676
    printf("Supported file protocols:");
2677
    for(up = first_protocol; up != NULL; up = up->next)
2678
        printf(" %s:", up->name);
2679
    printf("\n");
2680
    
2681
    printf("Frame size abbreviations: sqcif qcif cif 4cif\n");
2682
    printf("Motion estimation methods:");
2683
    pp = motion_str;
2684
    while (*pp) {
2685
        printf(" %s", *pp);
2686
        if ((pp - motion_str + 1) == ME_ZERO) 
2687
            printf("(fastest)");
2688
        else if ((pp - motion_str + 1) == ME_FULL) 
2689
            printf("(slowest)");
2690
        else if ((pp - motion_str + 1) == ME_EPZS) 
2691
            printf("(default)");
2692
        pp++;
2693
    }
2694
    printf("\n");
2695
    exit(1);
2696
}
2697

    
2698
void show_help(void)
2699
{
2700
    const char *prog;
2701
    const OptionDef *po;
2702
    int i, expert;
2703
    
2704
    prog = do_play ? "ffplay" : "ffmpeg";
2705

    
2706
    printf("%s version " FFMPEG_VERSION ", Copyright (c) 2000, 2001, 2002 Fabrice Bellard\n",
2707
           prog);
2708
    
2709
    if (!do_play) {
2710
        printf("usage: ffmpeg [[options] -i input_file]... {[options] outfile}...\n"
2711
               "Hyper fast MPEG1/MPEG4/H263/RV and AC3/MPEG audio encoder\n");
2712
    } else {
2713
        printf("usage: ffplay [options] input_file...\n"
2714
               "Simple audio player\n");
2715
    }
2716
           
2717
    printf("\n"
2718
           "Main options are:\n");
2719
    for(i=0;i<2;i++) {
2720
        if (i == 1)
2721
            printf("\nAdvanced options are:\n");
2722
        for(po = options; po->name != NULL; po++) {
2723
            char buf[64];
2724
            expert = (po->flags & OPT_EXPERT) != 0;
2725
            if (expert == i) {
2726
                strcpy(buf, po->name);
2727
                if (po->flags & HAS_ARG) {
2728
                    strcat(buf, " ");
2729
                    strcat(buf, po->argname);
2730
                }
2731
                printf("-%-17s  %s\n", buf, po->help);
2732
            }
2733
        }
2734
    }
2735

    
2736
    exit(1);
2737
}
2738

    
2739
const OptionDef options[] = {
2740
    { "L", 0, {(void*)show_licence}, "show license" },
2741
    { "h", 0, {(void*)show_help}, "show help" },
2742
    { "formats", 0, {(void*)show_formats}, "show available formats, codecs, protocols, ..." },
2743
    { "f", HAS_ARG, {(void*)opt_format}, "force format", "fmt" },
2744
    { "img", HAS_ARG, {(void*)opt_image_format}, "force image format", "img_fmt" },
2745
    { "i", HAS_ARG, {(void*)opt_input_file}, "input file name", "filename" },
2746
    { "y", OPT_BOOL, {(void*)&file_overwrite}, "overwrite output files" },
2747
    { "map", HAS_ARG | OPT_EXPERT, {(void*)opt_map}, "set input stream mapping", "file:stream" },
2748
    { "t", HAS_ARG, {(void*)opt_recording_time}, "set the recording time", "duration" },
2749
    { "title", HAS_ARG | OPT_STRING, {(void*)&str_title}, "set the title", "string" },
2750
    { "author", HAS_ARG | OPT_STRING, {(void*)&str_author}, "set the author", "string" },
2751
    { "copyright", HAS_ARG | OPT_STRING, {(void*)&str_copyright}, "set the copyright", "string" },
2752
    { "comment", HAS_ARG | OPT_STRING, {(void*)&str_comment}, "set the comment", "string" },
2753
    { "pass", HAS_ARG, {(void*)&opt_pass}, "select the pass number (1 or 2)", "n" },
2754
    { "passlogfile", HAS_ARG | OPT_STRING, {(void*)&pass_logfilename}, "select two pass log file name", "file" },
2755
    /* video options */
2756
    { "b", HAS_ARG, {(void*)opt_video_bitrate}, "set video bitrate (in kbit/s)", "bitrate" },
2757
    { "r", HAS_ARG, {(void*)opt_frame_rate}, "set frame rate (in Hz)", "rate" },
2758
    { "re", OPT_BOOL|OPT_EXPERT, {(void*)&rate_emu}, "read input at native frame rate" },
2759
    { "s", HAS_ARG, {(void*)opt_frame_size}, "set frame size (WxH or abbreviation)", "size" },
2760
    { "croptop", HAS_ARG, {(void*)opt_frame_crop_top}, "set top crop band size (in pixels)", "size" },
2761
    { "cropbottom", HAS_ARG, {(void*)opt_frame_crop_bottom}, "set bottom crop band size (in pixels)", "size" },
2762
    { "cropleft", HAS_ARG, {(void*)opt_frame_crop_left}, "set left crop band size (in pixels)", "size" },
2763
    { "cropright", HAS_ARG, {(void*)opt_frame_crop_right}, "set right crop band size (in pixels)", "size" },
2764
    { "g", HAS_ARG | OPT_EXPERT, {(void*)opt_gop_size}, "set the group of picture size", "gop_size" },
2765
    { "intra", OPT_BOOL | OPT_EXPERT, {(void*)&intra_only}, "use only intra frames"},
2766
    { "vn", OPT_BOOL, {(void*)&video_disable}, "disable video" },
2767
    { "qscale", HAS_ARG | OPT_EXPERT, {(void*)opt_qscale}, "use fixed video quantiser scale (VBR)", "q" },
2768
    { "qmin", HAS_ARG | OPT_EXPERT, {(void*)opt_qmin}, "min video quantiser scale (VBR)", "q" },
2769
    { "qmax", HAS_ARG | OPT_EXPERT, {(void*)opt_qmax}, "max video quantiser scale (VBR)", "q" },
2770
    { "mbqmin", HAS_ARG | OPT_EXPERT, {(void*)opt_mb_qmin}, "min macroblock quantiser scale (VBR)", "q" },
2771
    { "mbqmax", HAS_ARG | OPT_EXPERT, {(void*)opt_mb_qmax}, "max macroblock quantiser scale (VBR)", "q" },
2772
    { "qdiff", HAS_ARG | OPT_EXPERT, {(void*)opt_qdiff}, "max difference between the quantiser scale (VBR)", "q" },
2773
    { "qblur", HAS_ARG | OPT_EXPERT, {(void*)opt_qblur}, "video quantiser scale blur (VBR)", "blur" },
2774
    { "qcomp", HAS_ARG | OPT_EXPERT, {(void*)opt_qcomp}, "video quantiser scale compression (VBR)", "compression" },
2775
    { "rc_init_cplx", HAS_ARG | OPT_EXPERT, {(void*)opt_rc_initial_cplx}, "initial complexity for 1-pass encoding", "complexity" },
2776
    { "b_qfactor", HAS_ARG | OPT_EXPERT, {(void*)opt_b_qfactor}, "qp factor between p and b frames", "factor" },
2777
    { "i_qfactor", HAS_ARG | OPT_EXPERT, {(void*)opt_i_qfactor}, "qp factor between p and i frames", "factor" },
2778
    { "b_qoffset", HAS_ARG | OPT_EXPERT, {(void*)opt_b_qoffset}, "qp offset between p and b frames", "offset" },
2779
    { "i_qoffset", HAS_ARG | OPT_EXPERT, {(void*)opt_i_qoffset}, "qp offset between p and i frames", "offset" },
2780
//    { "b_strategy", HAS_ARG | OPT_EXPERT, {(void*)opt_b_strategy}, "dynamic b frame selection strategy", "strategy" },
2781
    { "rc_eq", HAS_ARG | OPT_EXPERT, {(void*)opt_video_rc_eq}, "", "equation" },
2782
    { "rc_override", HAS_ARG | OPT_EXPERT, {(void*)opt_video_rc_override_string}, "Rate control override", "qualities for specific intervals" },
2783
    { "bt", HAS_ARG, {(void*)opt_video_bitrate_tolerance}, "set video bitrate tolerance (in kbit/s)", "tolerance" },
2784
    { "maxrate", HAS_ARG, {(void*)opt_video_bitrate_max}, "set max video bitrate tolerance (in kbit/s)", "bitrate" },
2785
    { "minrate", HAS_ARG, {(void*)opt_video_bitrate_min}, "set min video bitrate tolerance (in kbit/s)", "bitrate" },
2786
    { "bufsize", HAS_ARG, {(void*)opt_video_buffer_size}, "set ratecontrol buffere size (in kbit)", "size" },
2787
    { "vd", HAS_ARG | OPT_EXPERT, {(void*)opt_video_device}, "set video grab device", "device" },
2788
    { "vc", HAS_ARG | OPT_EXPERT, {(void*)opt_video_channel}, "set video grab channel (DV1394 only)", "channel" },
2789
    { "dv1394", OPT_EXPERT, {(void*)opt_dv1394}, "set DV1394 grab", "" },
2790
    { "vcodec", HAS_ARG | OPT_EXPERT, {(void*)opt_video_codec}, "force video codec ('copy' to copy stream)", "codec" },
2791
    { "me", HAS_ARG | OPT_EXPERT, {(void*)opt_motion_estimation}, "set motion estimation method", 
2792
      "method" },
2793
    { "dct_algo", HAS_ARG | OPT_EXPERT, {(void*)opt_dct_algo}, "set dct algo",  "algo" },
2794
    { "idct_algo", HAS_ARG | OPT_EXPERT, {(void*)opt_idct_algo}, "set idct algo",  "algo" },
2795
    { "er", HAS_ARG | OPT_EXPERT, {(void*)opt_error_resilience}, "set error resilience",  "" },
2796
    { "ec", HAS_ARG | OPT_EXPERT, {(void*)opt_error_concealment}, "set error concealment",  "" },
2797
    { "bf", HAS_ARG | OPT_EXPERT, {(void*)opt_b_frames}, "use 'frames' B frames (only MPEG-4)", "frames" },
2798
    { "hq", OPT_BOOL | OPT_EXPERT, {(void*)&use_hq}, "activate high quality settings" },
2799
    { "4mv", OPT_BOOL | OPT_EXPERT, {(void*)&use_4mv}, "use four motion vector by macroblock (only MPEG-4)" },
2800
    { "part", OPT_BOOL | OPT_EXPERT, {(void*)&use_part}, "use data partitioning (only MPEG-4)" },
2801
    { "bug", HAS_ARG | OPT_EXPERT, {(void*)opt_workaround_bugs}, "workaround not auto detected encoder bugs", "param" },
2802
    { "ps", HAS_ARG | OPT_EXPERT, {(void*)opt_packet_size}, "packet size", "size in bits" },
2803
    { "strict", HAS_ARG | OPT_EXPERT, {(void*)opt_strict}, "strictness", "how strictly to follow the standarts" },
2804
    { "sameq", OPT_BOOL, {(void*)&same_quality}, 
2805
      "use same video quality as source (implies VBR)" },
2806
    { "debug", HAS_ARG | OPT_EXPERT, {(void*)opt_debug}, "print specific debug info", "" },
2807
    /* audio options */
2808
    { "ab", HAS_ARG, {(void*)opt_audio_bitrate}, "set audio bitrate (in kbit/s)", "bitrate", },
2809
    { "ar", HAS_ARG, {(void*)opt_audio_rate}, "set audio sampling rate (in Hz)", "rate" },
2810
    { "ac", HAS_ARG, {(void*)opt_audio_channels}, "set number of audio channels", "channels" },
2811
    { "an", OPT_BOOL, {(void*)&audio_disable}, "disable audio" },
2812
    { "ad", HAS_ARG | OPT_EXPERT, {(void*)opt_audio_device}, "set audio device", "device" },
2813
    { "acodec", HAS_ARG | OPT_EXPERT, {(void*)opt_audio_codec}, "force audio codec ('copy' to copy stream)", "codec" },
2814
    { "deinterlace", OPT_BOOL | OPT_EXPERT, {(void*)&do_deinterlace}, 
2815
      "deinterlace pictures" },
2816
    { "benchmark", OPT_BOOL | OPT_EXPERT, {(void*)&do_benchmark}, 
2817
      "add timings for benchmarking" },
2818
    { "hex", OPT_BOOL | OPT_EXPERT, {(void*)&do_hex_dump}, 
2819
      "dump each input packet" },
2820
    { "psnr", OPT_BOOL | OPT_EXPERT, {(void*)&do_psnr}, "calculate PSNR of compressed frames" },
2821
    { "vstats", OPT_BOOL | OPT_EXPERT, {(void*)&do_vstats}, "dump video coding statistics to file" }, 
2822
    { "bitexact", OPT_EXPERT, {(void*)opt_bitexact}, "only use bit exact algorithms (for codec testing)" }, 
2823
    { "vhook", HAS_ARG | OPT_EXPERT, {(void*)add_frame_hooker}, "insert video processing module", "module name and parameters" },
2824
    /* Fx */
2825
    { "aic", OPT_BOOL | OPT_EXPERT, {(void*)&use_aic}, "enable Advanced intra coding (h263+)" },
2826
    { "umv", OPT_BOOL | OPT_EXPERT, {(void*)&use_umv}, "enable Unlimited Motion Vector (h263+)" },
2827
    /* /Fx */
2828
    { NULL, },
2829
};
2830

    
2831
int main(int argc, char **argv)
2832
{
2833
    int optindex, i;
2834
    const char *opt, *arg;
2835
    const OptionDef *po;
2836
    int64_t ti;
2837

    
2838
    av_register_all();
2839

    
2840
    /* detect if invoked as player */
2841
    i = strlen(argv[0]);
2842
    if (i >= 6 && !strcmp(argv[0] + i - 6, "ffplay"))
2843
        do_play = 1;
2844

    
2845
    if (argc <= 1)
2846
        show_help();
2847
    
2848
    /* parse options */
2849
    optindex = 1;
2850
    while (optindex < argc) {
2851
        opt = argv[optindex++];
2852
        
2853
        if (opt[0] == '-' && opt[1] != '\0') {
2854
            po = options;
2855
            while (po->name != NULL) {
2856
                if (!strcmp(opt + 1, po->name))
2857
                    break;
2858
                po++;
2859
            }
2860
            if (!po->name) {
2861
                fprintf(stderr, "%s: unrecognized option '%s'\n", argv[0], opt);
2862
                exit(1);
2863
            }
2864
            arg = NULL;
2865
            if (po->flags & HAS_ARG) {
2866
                arg = argv[optindex++];
2867
                if (!arg) {
2868
                    fprintf(stderr, "%s: missing argument for option '%s'\n", argv[0], opt);
2869
                    exit(1);
2870
                }
2871
            }
2872
            if (po->flags & OPT_STRING) {
2873
                char *str;
2874
                str = av_strdup(arg);
2875
                *po->u.str_arg = str;
2876
            } else if (po->flags & OPT_BOOL) {
2877
                *po->u.int_arg = 1;
2878
            } else {
2879
                po->u.func_arg(arg);
2880
            }
2881
        } else {
2882
            if (!do_play) {
2883
                opt_output_file(opt);
2884
            } else {
2885
                opt_input_file(opt);
2886
            }
2887
        }
2888
    }
2889

    
2890

    
2891
    if (!do_play) {
2892
        /* file converter / grab */
2893
        if (nb_output_files <= 0) {
2894
            fprintf(stderr, "Must supply at least one output file\n");
2895
            exit(1);
2896
        }
2897
        
2898
        if (nb_input_files == 0) {
2899
            prepare_grab();
2900
        }
2901
    } else {
2902
        /* player */
2903
        if (nb_input_files <= 0) {
2904
            fprintf(stderr, "Must supply at least one input file\n");
2905
            exit(1);
2906
        }
2907
        prepare_play();
2908
    }
2909

    
2910
    ti = getutime();
2911
    av_encode(output_files, nb_output_files, input_files, nb_input_files, 
2912
              stream_maps, nb_stream_maps);
2913
    ti = getutime() - ti;
2914
    if (do_benchmark) {
2915
        printf("bench: utime=%0.3fs\n", ti / 1000000.0);
2916
    }
2917

    
2918
    /* close files */
2919
    for(i=0;i<nb_output_files;i++) {
2920
        /* maybe av_close_output_file ??? */
2921
        AVFormatContext *s = output_files[i];
2922
        int j;
2923
        if (!(s->oformat->flags & AVFMT_NOFILE))
2924
            url_fclose(&s->pb);
2925
        for(j=0;j<s->nb_streams;j++)
2926
            av_free(s->streams[j]);
2927
        av_free(s);
2928
    }
2929
    for(i=0;i<nb_input_files;i++)
2930
        av_close_input_file(input_files[i]);
2931

    
2932
    av_free_static();
2933

    
2934
    
2935
#ifdef POWERPC_TBL_PERFORMANCE_REPORT
2936
    extern void powerpc_display_perf_report(void);
2937
    powerpc_display_perf_report();
2938
#endif /* POWERPC_TBL_PERFORMANCE_REPORT */
2939

    
2940
    return 0;
2941
}