Statistics
| Branch: | Revision:

ffmpeg / ffmpeg.c @ 81b060fa

History | View | Annotate | Download (138 KB)

1 85f07f22 Fabrice Bellard
/*
2 115329f1 Diego Biurrun
 * FFmpeg main
3 01310af2 Fabrice Bellard
 * Copyright (c) 2000-2003 Fabrice Bellard
4 85f07f22 Fabrice Bellard
 *
5 b78e7197 Diego Biurrun
 * This file is part of FFmpeg.
6
 *
7
 * FFmpeg is free software; you can redistribute it and/or
8 bf5af568 Fabrice Bellard
 * modify it under the terms of the GNU Lesser General Public
9
 * License as published by the Free Software Foundation; either
10 b78e7197 Diego Biurrun
 * version 2.1 of the License, or (at your option) any later version.
11 85f07f22 Fabrice Bellard
 *
12 b78e7197 Diego Biurrun
 * FFmpeg is distributed in the hope that it will be useful,
13 85f07f22 Fabrice Bellard
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 bf5af568 Fabrice Bellard
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15
 * Lesser General Public License for more details.
16 85f07f22 Fabrice Bellard
 *
17 bf5af568 Fabrice Bellard
 * You should have received a copy of the GNU Lesser General Public
18 b78e7197 Diego Biurrun
 * License along with FFmpeg; if not, write to the Free Software
19 5509bffa Diego Biurrun
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20 85f07f22 Fabrice Bellard
 */
21 364a9607 Diego Biurrun
22 0f4e8165 Ronald S. Bultje
#include "config.h"
23
#include <ctype.h>
24
#include <string.h>
25
#include <math.h>
26
#include <stdlib.h>
27
#include <errno.h>
28 d86b83f8 Ramiro Polla
#include <signal.h>
29 22f7a060 Michael Niedermayer
#include <limits.h>
30 245976da Diego Biurrun
#include "libavformat/avformat.h"
31
#include "libavdevice/avdevice.h"
32
#include "libswscale/swscale.h"
33
#include "libavformat/framehook.h"
34
#include "libavcodec/opt.h"
35 ce1ee094 Peter Ross
#include "libavcodec/audioconvert.h"
36 245976da Diego Biurrun
#include "libavutil/fifo.h"
37
#include "libavutil/avstring.h"
38
#include "libavformat/os_support.h"
39 daf8e955 Fabrice Bellard
40 b091aa44 Ramiro Polla
#ifdef HAVE_SYS_RESOURCE_H
41 0a1b29de Dave Yeo
#include <sys/types.h>
42 b091aa44 Ramiro Polla
#include <sys/resource.h>
43
#elif defined(HAVE_GETPROCESSTIMES)
44 7495c306 Ramiro Polla
#include <windows.h>
45
#endif
46
47 4b54c6d0 Ramiro Polla
#if defined(HAVE_TERMIOS_H)
48 85f07f22 Fabrice Bellard
#include <unistd.h>
49
#include <fcntl.h>
50
#include <sys/ioctl.h>
51
#include <sys/time.h>
52
#include <termios.h>
53 4b54c6d0 Ramiro Polla
#elif defined(HAVE_CONIO_H)
54
#include <conio.h>
55 bdc4796f Fabrice Bellard
#endif
56 64c020a8 Michael Niedermayer
#undef time //needed because HAVE_AV_CONFIG_H is defined on top
57 bf5af568 Fabrice Bellard
#include <time.h>
58 85f07f22 Fabrice Bellard
59 01310af2 Fabrice Bellard
#include "cmdutils.h"
60
61 2b18dcd0 Michael Niedermayer
#undef NDEBUG
62
#include <assert.h>
63
64 c367d067 Michael Niedermayer
#undef exit
65
66 64555bd9 Michael Niedermayer
const char program_name[] = "FFmpeg";
67 ea9c581f Stefano Sabatini
const int program_birth_year = 2000;
68 86074ed1 Stefano Sabatini
69 85f07f22 Fabrice Bellard
/* select an input stream for an output stream */
70
typedef struct AVStreamMap {
71
    int file_index;
72
    int stream_index;
73 b4a3389e Wolfram Gloger
    int sync_file_index;
74
    int sync_stream_index;
75 85f07f22 Fabrice Bellard
} AVStreamMap;
76
77 0a38bafd Patrice Bensoussan
/** select an input file for an output file */
78
typedef struct AVMetaDataMap {
79
    int out_file;
80
    int in_file;
81
} AVMetaDataMap;
82
83 580a6c57 Diego Pettenò
static const OptionDef options[];
84 85f07f22 Fabrice Bellard
85
#define MAX_FILES 20
86
87
static AVFormatContext *input_files[MAX_FILES];
88 a6a92a9a Wolfram Gloger
static int64_t input_files_ts_offset[MAX_FILES];
89 8833f375 Michael Niedermayer
static double input_files_ts_scale[MAX_FILES][MAX_STREAMS];
90 85f07f22 Fabrice Bellard
static int nb_input_files = 0;
91
92
static AVFormatContext *output_files[MAX_FILES];
93
static int nb_output_files = 0;
94
95 f44fd374 Stefano Sabatini
static AVStreamMap stream_maps[MAX_FILES*MAX_STREAMS];
96 85f07f22 Fabrice Bellard
static int nb_stream_maps;
97
98 0a38bafd Patrice Bensoussan
static AVMetaDataMap meta_data_maps[MAX_FILES];
99
static int nb_meta_data_maps;
100
101 79fdaa4c Fabrice Bellard
static AVInputFormat *file_iformat;
102
static AVOutputFormat *file_oformat;
103 55cf1959 Michael Niedermayer
static int frame_width  = 0;
104
static int frame_height = 0;
105 880e8ba7 Roman Shaposhnik
static float frame_aspect_ratio = 0;
106 644a9262 Michael Niedermayer
static enum PixelFormat frame_pix_fmt = PIX_FMT_NONE;
107 ce1ee094 Peter Ross
static enum SampleFormat audio_sample_fmt = SAMPLE_FMT_NONE;
108 1ff93ffc Todd Kirby
static int frame_padtop  = 0;
109
static int frame_padbottom = 0;
110
static int frame_padleft  = 0;
111
static int frame_padright = 0;
112
static int padcolor[3] = {16,128,128}; /* default to black */
113 ab6d194a Michael Niedermayer
static int frame_topBand  = 0;
114
static int frame_bottomBand = 0;
115
static int frame_leftBand  = 0;
116
static int frame_rightBand = 0;
117 cf7fc795 Fabrice Bellard
static int max_frames[4] = {INT_MAX, INT_MAX, INT_MAX, INT_MAX};
118 89129c6b Diego Biurrun
static AVRational frame_rate;
119 158c7f05 Michael Niedermayer
static float video_qscale = 0;
120 84f608f4 Vidar Madsen
static uint16_t *intra_matrix = NULL;
121
static uint16_t *inter_matrix = NULL;
122 ac2830ec Michael Niedermayer
#if 0 //experimental, (can be removed)
123 3aa102be Michael Niedermayer
static float video_rc_qsquish=1.0;
124
static float video_rc_qmod_amp=0;
125
static int video_rc_qmod_freq=0;
126 ac2830ec Michael Niedermayer
#endif
127 464a631c Morten Hustveit
static const char *video_rc_override_string=NULL;
128 85f07f22 Fabrice Bellard
static int video_disable = 0;
129 f3356e9c Michael Niedermayer
static int video_discard = 0;
130 4a897224 Nicolas George
static char *video_codec_name = NULL;
131 b2a2197e Michael Niedermayer
static int video_codec_tag = 0;
132 85f07f22 Fabrice Bellard
static int same_quality = 0;
133 cfcf0ffd Fabrice Bellard
static int do_deinterlace = 0;
134 bb198e19 Michael Niedermayer
static int top_field_first = -1;
135 f4f3223f Michael Niedermayer
static int me_threshold = 0;
136 1a11cbcc Michael Niedermayer
static int intra_dc_precision = 8;
137 5894e1bb Víctor Paesa
static int loop_input = 0;
138 8108551a Todd Kirby
static int loop_output = AVFMT_NOOUTPUTLOOP;
139 0888fd22 Michael Niedermayer
static int qp_hist = 0;
140 85f07f22 Fabrice Bellard
141
static int intra_only = 0;
142
static int audio_sample_rate = 44100;
143 c57c770d Justin Ruggles
#define QSCALE_NONE -99999
144
static float audio_qscale = QSCALE_NONE;
145 85f07f22 Fabrice Bellard
static int audio_disable = 0;
146
static int audio_channels = 1;
147 4a897224 Nicolas George
static char  *audio_codec_name = NULL;
148 b2a2197e Michael Niedermayer
static int audio_codec_tag = 0;
149 cf7fc795 Fabrice Bellard
static char *audio_language = NULL;
150
151 11bf3847 Aurelien Jacobs
static int subtitle_disable = 0;
152 4a897224 Nicolas George
static char *subtitle_codec_name = NULL;
153 cf7fc795 Fabrice Bellard
static char *subtitle_language = NULL;
154 85f07f22 Fabrice Bellard
155 17c88cb0 Michael Niedermayer
static float mux_preload= 0.5;
156
static float mux_max_delay= 0.7;
157 2db3c638 Michael Niedermayer
158 fc7ad2af Stefano Sabatini
static int64_t recording_time = INT64_MAX;
159 8831db5c Michael Niedermayer
static int64_t start_time = 0;
160 4568325a Roman Shaposhnik
static int64_t rec_timestamp = 0;
161 a6a92a9a Wolfram Gloger
static int64_t input_ts_offset = 0;
162 85f07f22 Fabrice Bellard
static int file_overwrite = 0;
163
static char *str_title = NULL;
164
static char *str_author = NULL;
165
static char *str_copyright = NULL;
166
static char *str_comment = NULL;
167 ab759f6e kweiner@spamcop.net
static char *str_genre = NULL;
168 63d5075c Panagiotis Issaris
static char *str_album = NULL;
169 5727b222 Fabrice Bellard
static int do_benchmark = 0;
170 a0663ba4 Fabrice Bellard
static int do_hex_dump = 0;
171 254abc2e Fabrice Bellard
static int do_pkt_dump = 0;
172 43f1708f Juanjo
static int do_psnr = 0;
173 5abdb4b1 Fabrice Bellard
static int do_pass = 0;
174
static char *pass_logfilename = NULL;
175 1629626f Fabrice Bellard
static int audio_stream_copy = 0;
176
static int video_stream_copy = 0;
177 cf7fc795 Fabrice Bellard
static int subtitle_stream_copy = 0;
178 8858816d Michael Niedermayer
static int video_sync_method= -1;
179 986ebcdb Michael Niedermayer
static int audio_sync_method= 0;
180 d4d226a8 Michael Niedermayer
static float audio_drift_threshold= 0.1;
181 72bd8100 Michael Niedermayer
static int copy_ts= 0;
182 ca80810b Calcium
static int opt_shortest = 0; //
183 90ad92b3 Michael Niedermayer
static int video_global_header = 0;
184 b60d1379 Stefano Sabatini
static char *vstats_filename;
185 032aa7df Stefano Sabatini
static FILE *vstats_file;
186 50e143c4 Nico Sabbi
static int opt_programid = 0;
187 5abdb4b1 Fabrice Bellard
188 bdfcbbed Max Krasnyansky
static int rate_emu = 0;
189
190 a5df11ab Fabrice Bellard
static int  video_channel = 0;
191 df0cecdd Luca Abeni
static char *video_standard;
192 79a7c268 Fabrice Bellard
193 a9aa3467 Michael Niedermayer
static int audio_volume = 256;
194 8aa3ee32 Max Krasnyansky
195 d9a916e2 Charles Yates
static int using_stdin = 0;
196 bee0d9e5 Charles Yates
static int using_vhook = 0;
197 f068206e Bill Eldridge
static int verbose = 1;
198 9c3d33d6 Michael Niedermayer
static int thread_count= 1;
199 b51469a0 Leon van Stuivenberg
static int q_pressed = 0;
200 1008ceb3 Michael Niedermayer
static int64_t video_size = 0;
201
static int64_t audio_size = 0;
202
static int64_t extra_size = 0;
203 a6a92a9a Wolfram Gloger
static int nb_frames_dup = 0;
204
static int nb_frames_drop = 0;
205 6e454c38 Luca Abeni
static int input_sync;
206 85ad1b0e Baptiste Coudurier
static uint64_t limit_filesize = 0; //
207 d9a916e2 Charles Yates
208 5b6d5596 Michael Niedermayer
static int pgmyuv_compatibility_hack=0;
209 a8482aab Michael Niedermayer
static float dts_delta_threshold = 10;
210 5b6d5596 Michael Niedermayer
211 e60da588 Michael Niedermayer
static unsigned int sws_flags = SWS_BICUBIC;
212 18a54b04 Luca Abeni
213 29cc1c23 Benoit Fouet
static const char **opt_names;
214
static int opt_name_count;
215
static AVCodecContext *avctx_opts[CODEC_TYPE_NB];
216
static AVFormatContext *avformat_opts;
217
static struct SwsContext *sws_opts;
218
static int64_t timer_start;
219 8bbf6db9 Michael Niedermayer
220 748c2fca Michael Niedermayer
static AVBitStreamFilterContext *video_bitstream_filters=NULL;
221
static AVBitStreamFilterContext *audio_bitstream_filters=NULL;
222 e1cc8339 Reimar Döffinger
static AVBitStreamFilterContext *subtitle_bitstream_filters=NULL;
223 748c2fca Michael Niedermayer
static AVBitStreamFilterContext *bitstream_filters[MAX_FILES][MAX_STREAMS];
224 5b6d5596 Michael Niedermayer
225 5abdb4b1 Fabrice Bellard
#define DEFAULT_PASS_LOGFILENAME "ffmpeg2pass"
226 85f07f22 Fabrice Bellard
227 b4a3389e Wolfram Gloger
struct AVInputStream;
228
229 85f07f22 Fabrice Bellard
typedef struct AVOutputStream {
230
    int file_index;          /* file index */
231
    int index;               /* stream index in the output file */
232
    int source_index;        /* AVInputStream index */
233
    AVStream *st;            /* stream in the output file */
234 ec5517d5 Fabrice Bellard
    int encoding_needed;     /* true if encoding needed for this stream */
235
    int frame_number;
236
    /* input pts and corresponding output pts
237
       for A/V sync */
238 b4a3389e Wolfram Gloger
    //double sync_ipts;        /* dts from the AVPacket of the demuxer in second units */
239
    struct AVInputStream *sync_ist; /* input stream to sync against */
240 e928649b Michael Niedermayer
    int64_t sync_opts;       /* output frame counter, could be changed to some true timestamp */ //FIXME look at frame_number
241 85f07f22 Fabrice Bellard
    /* video only */
242 07d0cdfc Luca Abeni
    int video_resample;
243 a4d36c11 Michael Niedermayer
    AVFrame pict_tmp;      /* temporary image for resampling */
244 18a54b04 Luca Abeni
    struct SwsContext *img_resample_ctx; /* for image resampling */
245
    int resample_height;
246 34b10a57 Dieter
247 07d0cdfc Luca Abeni
    int video_crop;
248 34b10a57 Dieter
    int topBand;             /* cropping area sizes */
249
    int leftBand;
250 115329f1 Diego Biurrun
251 07d0cdfc Luca Abeni
    int video_pad;
252 1ff93ffc Todd Kirby
    int padtop;              /* padding area sizes */
253
    int padbottom;
254
    int padleft;
255
    int padright;
256 115329f1 Diego Biurrun
257 85f07f22 Fabrice Bellard
    /* audio only */
258
    int audio_resample;
259
    ReSampleContext *resample; /* for audio resampling */
260 a79db0f7 Peter Ross
    int reformat_pair;
261
    AVAudioConvert *reformat_ctx;
262 f5a478f6 Roman Shaposhnik
    AVFifoBuffer fifo;     /* for compression: one audio fifo per codec */
263 5abdb4b1 Fabrice Bellard
    FILE *logfile;
264 85f07f22 Fabrice Bellard
} AVOutputStream;
265
266
typedef struct AVInputStream {
267
    int file_index;
268
    int index;
269
    AVStream *st;
270
    int discard;             /* true if stream data should be discarded */
271
    int decoding_needed;     /* true if the packets must be decoded in 'raw_fifo' */
272 0c1a9eda Zdenek Kabelac
    int64_t sample_index;      /* current sample */
273 bdfcbbed Max Krasnyansky
274
    int64_t       start;     /* time when read started */
275
    unsigned long frame;     /* current frame */
276 254abc2e Fabrice Bellard
    int64_t       next_pts;  /* synthetic pts for cases where pkt.pts
277
                                is not defined */
278 e7d0374f Roman Shaposhnik
    int64_t       pts;       /* current pts */
279 ff4905a5 Michael Niedermayer
    int is_start;            /* is 1 at the start and after a discontinuity */
280 85f07f22 Fabrice Bellard
} AVInputStream;
281
282
typedef struct AVInputFile {
283
    int eof_reached;      /* true if eof reached */
284
    int ist_index;        /* index of first stream in ist_table */
285
    int buffer_size;      /* current total buffer size */
286 79fdaa4c Fabrice Bellard
    int nb_streams;       /* nb streams we are aware of */
287 85f07f22 Fabrice Bellard
} AVInputFile;
288
289 e16e49ac Ramiro Polla
#ifdef HAVE_TERMIOS_H
290 bdc4796f Fabrice Bellard
291 85f07f22 Fabrice Bellard
/* init terminal so that we can grab keys */
292
static struct termios oldtty;
293 d86b83f8 Ramiro Polla
#endif
294 85f07f22 Fabrice Bellard
295
static void term_exit(void)
296
{
297 e16e49ac Ramiro Polla
#ifdef HAVE_TERMIOS_H
298 85f07f22 Fabrice Bellard
    tcsetattr (0, TCSANOW, &oldtty);
299 d86b83f8 Ramiro Polla
#endif
300 85f07f22 Fabrice Bellard
}
301
302 9680a722 Roumen Petrov
static volatile sig_atomic_t received_sigterm = 0;
303
304
static void
305
sigterm_handler(int sig)
306
{
307
    received_sigterm = sig;
308
    term_exit();
309
}
310
311 85f07f22 Fabrice Bellard
static void term_init(void)
312
{
313 e16e49ac Ramiro Polla
#ifdef HAVE_TERMIOS_H
314 85f07f22 Fabrice Bellard
    struct termios tty;
315
316
    tcgetattr (0, &tty);
317
    oldtty = tty;
318
319
    tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
320
                          |INLCR|IGNCR|ICRNL|IXON);
321
    tty.c_oflag |= OPOST;
322
    tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
323
    tty.c_cflag &= ~(CSIZE|PARENB);
324
    tty.c_cflag |= CS8;
325
    tty.c_cc[VMIN] = 1;
326
    tty.c_cc[VTIME] = 0;
327 115329f1 Diego Biurrun
328 85f07f22 Fabrice Bellard
    tcsetattr (0, TCSANOW, &tty);
329 d86b83f8 Ramiro Polla
    signal(SIGQUIT, sigterm_handler); /* Quit (POSIX).  */
330
#endif
331 85f07f22 Fabrice Bellard
332 9680a722 Roumen Petrov
    signal(SIGINT , sigterm_handler); /* Interrupt (ANSI).  */
333
    signal(SIGTERM, sigterm_handler); /* Termination (ANSI).  */
334
    /*
335
    register a function to be called at normal program termination
336
    */
337 85f07f22 Fabrice Bellard
    atexit(term_exit);
338 9ddd71fc François Revol
#ifdef CONFIG_BEOS_NETSERVER
339
    fcntl(0, F_SETFL, fcntl(0, F_GETFL) | O_NONBLOCK);
340
#endif
341 85f07f22 Fabrice Bellard
}
342
343
/* read a key without blocking */
344
static int read_key(void)
345
{
346 4b54c6d0 Ramiro Polla
#if defined(HAVE_TERMIOS_H)
347 9ddd71fc François Revol
    int n = 1;
348 85f07f22 Fabrice Bellard
    unsigned char ch;
349 9ddd71fc François Revol
#ifndef CONFIG_BEOS_NETSERVER
350
    struct timeval tv;
351 85f07f22 Fabrice Bellard
    fd_set rfds;
352
353
    FD_ZERO(&rfds);
354
    FD_SET(0, &rfds);
355
    tv.tv_sec = 0;
356
    tv.tv_usec = 0;
357
    n = select(1, &rfds, NULL, NULL, &tv);
358 9ddd71fc François Revol
#endif
359 85f07f22 Fabrice Bellard
    if (n > 0) {
360 cb09b2ed Philip Gladstone
        n = read(0, &ch, 1);
361
        if (n == 1)
362 85f07f22 Fabrice Bellard
            return ch;
363 cb09b2ed Philip Gladstone
364
        return n;
365 85f07f22 Fabrice Bellard
    }
366 4b54c6d0 Ramiro Polla
#elif defined(HAVE_CONIO_H)
367
    if(kbhit())
368
        return(getch());
369 d86b83f8 Ramiro Polla
#endif
370 85f07f22 Fabrice Bellard
    return -1;
371
}
372
373 b51469a0 Leon van Stuivenberg
static int decode_interrupt_cb(void)
374
{
375
    return q_pressed || (q_pressed = read_key() == 'q');
376
}
377
378 296df4e7 Ramiro Polla
static int av_exit(int ret)
379 e5295c0d Ramiro Polla
{
380
    int i;
381
382
    /* close files */
383
    for(i=0;i<nb_output_files;i++) {
384
        /* maybe av_close_output_file ??? */
385
        AVFormatContext *s = output_files[i];
386
        int j;
387 8767060c Ramiro Polla
        if (!(s->oformat->flags & AVFMT_NOFILE) && s->pb)
388 e5295c0d Ramiro Polla
            url_fclose(s->pb);
389
        for(j=0;j<s->nb_streams;j++) {
390
            av_free(s->streams[j]->codec);
391
            av_free(s->streams[j]);
392
        }
393
        av_free(s);
394
    }
395
    for(i=0;i<nb_input_files;i++)
396
        av_close_input_file(input_files[i]);
397
398
    av_free(intra_matrix);
399
    av_free(inter_matrix);
400
401
    if (vstats_file)
402
        fclose(vstats_file);
403
    av_free(vstats_filename);
404
405
    av_free(opt_names);
406
407
    av_free(video_codec_name);
408
    av_free(audio_codec_name);
409
    av_free(subtitle_codec_name);
410
411
    av_free(video_standard);
412
413
#ifdef CONFIG_POWERPC_PERF
414
    extern void powerpc_display_perf_report(void);
415
    powerpc_display_perf_report();
416
#endif /* CONFIG_POWERPC_PERF */
417
418
    if (received_sigterm) {
419
        fprintf(stderr,
420
            "Received signal %d: terminating.\n",
421
            (int) received_sigterm);
422
        exit (255);
423
    }
424
425 296df4e7 Ramiro Polla
    exit(ret); /* not all OS-es handle main() return value */
426
    return ret;
427 e5295c0d Ramiro Polla
}
428
429 b29f97d1 Zdenek Kabelac
static int read_ffserver_streams(AVFormatContext *s, const char *filename)
430 85f07f22 Fabrice Bellard
{
431 79fdaa4c Fabrice Bellard
    int i, err;
432 85f07f22 Fabrice Bellard
    AVFormatContext *ic;
433 3438d82d Baptiste Coudurier
    int nopts = 0;
434 85f07f22 Fabrice Bellard
435 79fdaa4c Fabrice Bellard
    err = av_open_input_file(&ic, filename, NULL, FFM_PACKET_SIZE, NULL);
436
    if (err < 0)
437
        return err;
438 85f07f22 Fabrice Bellard
    /* copy stream format */
439
    s->nb_streams = ic->nb_streams;
440
    for(i=0;i<ic->nb_streams;i++) {
441
        AVStream *st;
442 1e491e29 Michael Niedermayer
443 f37f8d4c Alex Beregszaszi
        // FIXME: a more elegant solution is needed
444 e1031171 Alex Beregszaszi
        st = av_mallocz(sizeof(AVStream));
445 85f07f22 Fabrice Bellard
        memcpy(st, ic->streams[i], sizeof(AVStream));
446 f37f8d4c Alex Beregszaszi
        st->codec = avcodec_alloc_context();
447
        memcpy(st->codec, ic->streams[i]->codec, sizeof(AVCodecContext));
448 85f07f22 Fabrice Bellard
        s->streams[i] = st;
449 837d248d Baptiste Coudurier
450
        if (st->codec->codec_type == CODEC_TYPE_AUDIO && audio_stream_copy)
451
            st->stream_copy = 1;
452
        else if (st->codec->codec_type == CODEC_TYPE_VIDEO && video_stream_copy)
453
            st->stream_copy = 1;
454
455 dbedf2aa Baptiste Coudurier
        if(!st->codec->thread_count)
456
            st->codec->thread_count = 1;
457
        if(st->codec->thread_count>1)
458
            avcodec_thread_init(st->codec, st->codec->thread_count);
459
460 3438d82d Baptiste Coudurier
        if(st->codec->flags & CODEC_FLAG_BITEXACT)
461
            nopts = 1;
462 85f07f22 Fabrice Bellard
    }
463
464 3438d82d Baptiste Coudurier
    if (!nopts)
465
        s->timestamp = av_gettime();
466
467 85f07f22 Fabrice Bellard
    av_close_input_file(ic);
468
    return 0;
469
}
470
471 b4a3389e Wolfram Gloger
static double
472
get_sync_ipts(const AVOutputStream *ost)
473
{
474
    const AVInputStream *ist = ost->sync_ist;
475 fec401f7 Michael Niedermayer
    return (double)(ist->pts - start_time)/AV_TIME_BASE;
476 b4a3389e Wolfram Gloger
}
477
478 748c2fca Michael Niedermayer
static void write_frame(AVFormatContext *s, AVPacket *pkt, AVCodecContext *avctx, AVBitStreamFilterContext *bsfc){
479 0ac07031 Michael Niedermayer
    int ret;
480
481 748c2fca Michael Niedermayer
    while(bsfc){
482
        AVPacket new_pkt= *pkt;
483
        int a= av_bitstream_filter_filter(bsfc, avctx, NULL,
484
                                          &new_pkt.data, &new_pkt.size,
485
                                          pkt->data, pkt->size,
486
                                          pkt->flags & PKT_FLAG_KEY);
487 7055cdac Benoit Fouet
        if(a>0){
488 748c2fca Michael Niedermayer
            av_free_packet(pkt);
489
            new_pkt.destruct= av_destruct_packet;
490 7055cdac Benoit Fouet
        } else if(a<0){
491 1f8e32cd Diego Biurrun
            fprintf(stderr, "%s failed for stream %d, codec %s",
492
                    bsfc->filter->name, pkt->stream_index,
493
                    avctx->codec ? avctx->codec->name : "copy");
494 7055cdac Benoit Fouet
            print_error("", a);
495 748c2fca Michael Niedermayer
        }
496
        *pkt= new_pkt;
497
498
        bsfc= bsfc->next;
499
    }
500
501 0ac07031 Michael Niedermayer
    ret= av_interleaved_write_frame(s, pkt);
502
    if(ret < 0){
503
        print_error("av_interleaved_write_frame()", ret);
504 296df4e7 Ramiro Polla
        av_exit(1);
505 0ac07031 Michael Niedermayer
    }
506 748c2fca Michael Niedermayer
}
507
508 817b23ff Fabrice Bellard
#define MAX_AUDIO_PACKET_SIZE (128 * 1024)
509 85f07f22 Fabrice Bellard
510 115329f1 Diego Biurrun
static void do_audio_out(AVFormatContext *s,
511
                         AVOutputStream *ost,
512 85f07f22 Fabrice Bellard
                         AVInputStream *ist,
513
                         unsigned char *buf, int size)
514
{
515 0c1a9eda Zdenek Kabelac
    uint8_t *buftmp;
516 d66c7abc Sylvain Corré
    static uint8_t *audio_buf = NULL;
517
    static uint8_t *audio_out = NULL;
518 a79db0f7 Peter Ross
    static uint8_t *audio_out2 = NULL;
519 558eae03 Michael Niedermayer
    const int audio_out_size= 4*MAX_AUDIO_PACKET_SIZE;
520 d66c7abc Sylvain Corré
521 85f07f22 Fabrice Bellard
    int size_out, frame_bytes, ret;
522 01f4895c Michael Niedermayer
    AVCodecContext *enc= ost->st->codec;
523 2886f311 Andreas Öman
    AVCodecContext *dec= ist->st->codec;
524 85f07f22 Fabrice Bellard
525 d66c7abc Sylvain Corré
    /* SC: dynamic allocation of buffers */
526
    if (!audio_buf)
527
        audio_buf = av_malloc(2*MAX_AUDIO_PACKET_SIZE);
528
    if (!audio_out)
529 558eae03 Michael Niedermayer
        audio_out = av_malloc(audio_out_size);
530 d66c7abc Sylvain Corré
    if (!audio_buf || !audio_out)
531
        return;               /* Should signal an error ! */
532
533 2886f311 Andreas Öman
    if (enc->channels != dec->channels)
534
        ost->audio_resample = 1;
535
536
    if (ost->audio_resample && !ost->resample) {
537
        ost->resample = audio_resample_init(enc->channels,    dec->channels,
538
                                            enc->sample_rate, dec->sample_rate);
539
        if (!ost->resample) {
540
            fprintf(stderr, "Can not resample %d channels @ %d Hz to %d channels @ %d Hz\n",
541
                    dec->channels, dec->sample_rate,
542
                    enc->channels, enc->sample_rate);
543 296df4e7 Ramiro Polla
            av_exit(1);
544 2886f311 Andreas Öman
        }
545
    }
546
547 a79db0f7 Peter Ross
#define MAKE_SFMT_PAIR(a,b) ((a)+SAMPLE_FMT_NB*(b))
548
    if (dec->sample_fmt!=enc->sample_fmt &&
549
        MAKE_SFMT_PAIR(enc->sample_fmt,dec->sample_fmt)!=ost->reformat_pair) {
550
        if (!audio_out2)
551
            audio_out2 = av_malloc(audio_out_size);
552
        if (!audio_out2)
553
            av_exit(1);
554
        if (ost->reformat_ctx)
555
            av_audio_convert_free(ost->reformat_ctx);
556
        ost->reformat_ctx = av_audio_convert_alloc(enc->sample_fmt, 1,
557
                                                   dec->sample_fmt, 1, NULL, 0);
558
        if (!ost->reformat_ctx) {
559
            fprintf(stderr, "Cannot convert %s sample format to %s sample format\n",
560
                avcodec_get_sample_fmt_name(dec->sample_fmt),
561
                avcodec_get_sample_fmt_name(enc->sample_fmt));
562
            av_exit(1);
563
        }
564
        ost->reformat_pair=MAKE_SFMT_PAIR(enc->sample_fmt,dec->sample_fmt);
565
    }
566
567 986ebcdb Michael Niedermayer
    if(audio_sync_method){
568 115329f1 Diego Biurrun
        double delta = get_sync_ipts(ost) * enc->sample_rate - ost->sync_opts
569 f5a478f6 Roman Shaposhnik
                - av_fifo_size(&ost->fifo)/(ost->st->codec->channels * 2);
570 01f4895c Michael Niedermayer
        double idelta= delta*ist->st->codec->sample_rate / enc->sample_rate;
571
        int byte_delta= ((int)idelta)*2*ist->st->codec->channels;
572 ff4905a5 Michael Niedermayer
573 986ebcdb Michael Niedermayer
        //FIXME resample delay
574
        if(fabs(delta) > 50){
575 d4d226a8 Michael Niedermayer
            if(ist->is_start || fabs(delta) > audio_drift_threshold*enc->sample_rate){
576 ff4905a5 Michael Niedermayer
                if(byte_delta < 0){
577 f41dd5aa Michael Niedermayer
                    byte_delta= FFMAX(byte_delta, -size);
578 ff4905a5 Michael Niedermayer
                    size += byte_delta;
579
                    buf  -= byte_delta;
580
                    if(verbose > 2)
581
                        fprintf(stderr, "discarding %d audio samples\n", (int)-delta);
582
                    if(!size)
583
                        return;
584
                    ist->is_start=0;
585
                }else{
586
                    static uint8_t *input_tmp= NULL;
587
                    input_tmp= av_realloc(input_tmp, byte_delta + size);
588
589
                    if(byte_delta + size <= MAX_AUDIO_PACKET_SIZE)
590
                        ist->is_start=0;
591
                    else
592
                        byte_delta= MAX_AUDIO_PACKET_SIZE - size;
593
594
                    memset(input_tmp, 0, byte_delta);
595
                    memcpy(input_tmp + byte_delta, buf, size);
596
                    buf= input_tmp;
597
                    size += byte_delta;
598
                    if(verbose > 2)
599
                        fprintf(stderr, "adding %d audio samples of silence\n", (int)delta);
600
                }
601
            }else if(audio_sync_method>1){
602 f66e4f5f Reimar Döffinger
                int comp= av_clip(delta, -audio_sync_method, audio_sync_method);
603 ff4905a5 Michael Niedermayer
                assert(ost->audio_resample);
604
                if(verbose > 2)
605
                    fprintf(stderr, "compensating audio timestamp drift:%f compensation:%d in:%d\n", delta, comp, enc->sample_rate);
606 949b1a13 Steve L'Homme
//                fprintf(stderr, "drift:%f len:%d opts:%"PRId64" ipts:%"PRId64" fifo:%d\n", delta, -1, ost->sync_opts, (int64_t)(get_sync_ipts(ost) * enc->sample_rate), av_fifo_size(&ost->fifo)/(ost->st->codec->channels * 2));
607 ff4905a5 Michael Niedermayer
                av_resample_compensate(*(struct AVResampleContext**)ost->resample, comp, enc->sample_rate);
608
            }
609 115329f1 Diego Biurrun
        }
610 986ebcdb Michael Niedermayer
    }else
611 b4a3389e Wolfram Gloger
        ost->sync_opts= lrintf(get_sync_ipts(ost) * enc->sample_rate)
612 f5a478f6 Roman Shaposhnik
                        - av_fifo_size(&ost->fifo)/(ost->st->codec->channels * 2); //FIXME wrong
613 85f07f22 Fabrice Bellard
614
    if (ost->audio_resample) {
615
        buftmp = audio_buf;
616 115329f1 Diego Biurrun
        size_out = audio_resample(ost->resample,
617 85f07f22 Fabrice Bellard
                                  (short *)buftmp, (short *)buf,
618 01f4895c Michael Niedermayer
                                  size / (ist->st->codec->channels * 2));
619 85f07f22 Fabrice Bellard
        size_out = size_out * enc->channels * 2;
620
    } else {
621
        buftmp = buf;
622
        size_out = size;
623
    }
624
625 a79db0f7 Peter Ross
    if (dec->sample_fmt!=enc->sample_fmt) {
626
        const void *ibuf[6]= {buftmp};
627
        void *obuf[6]= {audio_out2};
628
        int istride[6]= {av_get_bits_per_sample_format(dec->sample_fmt)/8};
629
        int ostride[6]= {av_get_bits_per_sample_format(enc->sample_fmt)/8};
630
        int len= size_out/istride[0];
631
        if (av_audio_convert(ost->reformat_ctx, obuf, ostride, ibuf, istride, len)<0) {
632
            printf("av_audio_convert() failed\n");
633
            return;
634
        }
635
        buftmp = audio_out2;
636
        /* FIXME: existing code assume that size_out equals framesize*channels*2
637
                  remove this legacy cruft */
638
        size_out = len*2;
639
    }
640
641 85f07f22 Fabrice Bellard
    /* now encode as many frames as possible */
642 a0663ba4 Fabrice Bellard
    if (enc->frame_size > 1) {
643 85f07f22 Fabrice Bellard
        /* output resampled raw samples */
644 fa3b9818 Michael Niedermayer
        av_fifo_realloc(&ost->fifo, av_fifo_size(&ost->fifo) + size_out);
645 1234da4c Baptiste Coudurier
        av_fifo_generic_write(&ost->fifo, buftmp, size_out, NULL);
646 85f07f22 Fabrice Bellard
647
        frame_bytes = enc->frame_size * 2 * enc->channels;
648 115329f1 Diego Biurrun
649 0871ae1a Michael Niedermayer
        while (av_fifo_size(&ost->fifo) >= frame_bytes) {
650 e928649b Michael Niedermayer
            AVPacket pkt;
651
            av_init_packet(&pkt);
652
653 0871ae1a Michael Niedermayer
            av_fifo_read(&ost->fifo, audio_buf, frame_bytes);
654
655 5bc440e7 Michael Niedermayer
            //FIXME pass ost->sync_opts as AVFrame.pts in avcodec_encode_audio()
656
657 115329f1 Diego Biurrun
            ret = avcodec_encode_audio(enc, audio_out, audio_out_size,
658 a0663ba4 Fabrice Bellard
                                       (short *)audio_buf);
659 1008ceb3 Michael Niedermayer
            audio_size += ret;
660 e928649b Michael Niedermayer
            pkt.stream_index= ost->index;
661
            pkt.data= audio_out;
662
            pkt.size= ret;
663 e7902f20 Michael Niedermayer
            if(enc->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)
664 c0df9d75 Michael Niedermayer
                pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
665 e928649b Michael Niedermayer
            pkt.flags |= PKT_FLAG_KEY;
666 748c2fca Michael Niedermayer
            write_frame(s, &pkt, ost->st->codec, bitstream_filters[ost->file_index][pkt.stream_index]);
667 115329f1 Diego Biurrun
668 986ebcdb Michael Niedermayer
            ost->sync_opts += enc->frame_size;
669 85f07f22 Fabrice Bellard
        }
670
    } else {
671 e928649b Michael Niedermayer
        AVPacket pkt;
672
        av_init_packet(&pkt);
673 986ebcdb Michael Niedermayer
674 c43042a7 Michael Niedermayer
        ost->sync_opts += size_out / (2 * enc->channels);
675 986ebcdb Michael Niedermayer
676 a0663ba4 Fabrice Bellard
        /* output a pcm frame */
677
        /* XXX: change encoding codec API to avoid this ? */
678
        switch(enc->codec->id) {
679 b461b3bc Reimar Döffinger
        case CODEC_ID_PCM_S32LE:
680
        case CODEC_ID_PCM_S32BE:
681
        case CODEC_ID_PCM_U32LE:
682
        case CODEC_ID_PCM_U32BE:
683 aa29709e Peter Ross
        case CODEC_ID_PCM_F32BE:
684 b461b3bc Reimar Döffinger
            size_out = size_out << 1;
685
            break;
686
        case CODEC_ID_PCM_S24LE:
687
        case CODEC_ID_PCM_S24BE:
688
        case CODEC_ID_PCM_U24LE:
689
        case CODEC_ID_PCM_U24BE:
690
        case CODEC_ID_PCM_S24DAUD:
691
            size_out = size_out / 2 * 3;
692
            break;
693 a0663ba4 Fabrice Bellard
        case CODEC_ID_PCM_S16LE:
694
        case CODEC_ID_PCM_S16BE:
695
        case CODEC_ID_PCM_U16LE:
696
        case CODEC_ID_PCM_U16BE:
697
            break;
698
        default:
699
            size_out = size_out >> 1;
700
            break;
701
        }
702 5bc440e7 Michael Niedermayer
        //FIXME pass ost->sync_opts as AVFrame.pts in avcodec_encode_audio()
703 115329f1 Diego Biurrun
        ret = avcodec_encode_audio(enc, audio_out, size_out,
704 bb270c08 Diego Biurrun
                                   (short *)buftmp);
705 1008ceb3 Michael Niedermayer
        audio_size += ret;
706 e928649b Michael Niedermayer
        pkt.stream_index= ost->index;
707
        pkt.data= audio_out;
708
        pkt.size= ret;
709 e7902f20 Michael Niedermayer
        if(enc->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)
710 c0df9d75 Michael Niedermayer
            pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
711 e928649b Michael Niedermayer
        pkt.flags |= PKT_FLAG_KEY;
712 748c2fca Michael Niedermayer
        write_frame(s, &pkt, ost->st->codec, bitstream_filters[ost->file_index][pkt.stream_index]);
713 85f07f22 Fabrice Bellard
    }
714
}
715
716 10d104e4 Philip Gladstone
static void pre_process_video_frame(AVInputStream *ist, AVPicture *picture, void **bufp)
717
{
718
    AVCodecContext *dec;
719
    AVPicture *picture2;
720
    AVPicture picture_tmp;
721 0c1a9eda Zdenek Kabelac
    uint8_t *buf = 0;
722 10d104e4 Philip Gladstone
723 01f4895c Michael Niedermayer
    dec = ist->st->codec;
724 10d104e4 Philip Gladstone
725
    /* deinterlace : must be done before any resize */
726 bee0d9e5 Charles Yates
    if (do_deinterlace || using_vhook) {
727 10d104e4 Philip Gladstone
        int size;
728
729
        /* create temporary picture */
730
        size = avpicture_get_size(dec->pix_fmt, dec->width, dec->height);
731
        buf = av_malloc(size);
732
        if (!buf)
733
            return;
734 115329f1 Diego Biurrun
735 10d104e4 Philip Gladstone
        picture2 = &picture_tmp;
736
        avpicture_fill(picture2, buf, dec->pix_fmt, dec->width, dec->height);
737
738 dafc3856 Michael Niedermayer
        if (do_deinterlace){
739 115329f1 Diego Biurrun
            if(avpicture_deinterlace(picture2, picture,
740 dafc3856 Michael Niedermayer
                                     dec->pix_fmt, dec->width, dec->height) < 0) {
741
                /* if error, do not deinterlace */
742
                av_free(buf);
743
                buf = NULL;
744
                picture2 = picture;
745
            }
746
        } else {
747 636d6a4a Panagiotis Issaris
            av_picture_copy(picture2, picture, dec->pix_fmt, dec->width, dec->height);
748 bee0d9e5 Charles Yates
        }
749 10d104e4 Philip Gladstone
    } else {
750
        picture2 = picture;
751
    }
752
753 d0f596b4 Diego Biurrun
    if (ENABLE_VHOOK)
754 390d5a7c Diego Biurrun
        frame_hook_process(picture2, dec->pix_fmt, dec->width, dec->height,
755
                           1000000 * ist->pts / AV_TIME_BASE);
756 10d104e4 Philip Gladstone
757
    if (picture != picture2)
758
        *picture = *picture2;
759
    *bufp = buf;
760
}
761
762 ec5517d5 Fabrice Bellard
/* we begin to correct av delay at this threshold */
763
#define AV_DELAY_MAX 0.100
764 85f07f22 Fabrice Bellard
765 115329f1 Diego Biurrun
static void do_subtitle_out(AVFormatContext *s,
766
                            AVOutputStream *ost,
767 cf7fc795 Fabrice Bellard
                            AVInputStream *ist,
768
                            AVSubtitle *sub,
769
                            int64_t pts)
770
{
771
    static uint8_t *subtitle_out = NULL;
772
    int subtitle_out_max_size = 65536;
773
    int subtitle_out_size, nb, i;
774
    AVCodecContext *enc;
775
    AVPacket pkt;
776
777
    if (pts == AV_NOPTS_VALUE) {
778
        fprintf(stderr, "Subtitle packets must have a pts\n");
779
        return;
780
    }
781
782 01f4895c Michael Niedermayer
    enc = ost->st->codec;
783 cf7fc795 Fabrice Bellard
784
    if (!subtitle_out) {
785
        subtitle_out = av_malloc(subtitle_out_max_size);
786
    }
787
788
    /* Note: DVB subtitle need one packet to draw them and one other
789
       packet to clear them */
790
    /* XXX: signal it in the codec context ? */
791
    if (enc->codec_id == CODEC_ID_DVB_SUBTITLE)
792
        nb = 2;
793
    else
794
        nb = 1;
795
796
    for(i = 0; i < nb; i++) {
797 115329f1 Diego Biurrun
        subtitle_out_size = avcodec_encode_subtitle(enc, subtitle_out,
798 cf7fc795 Fabrice Bellard
                                                    subtitle_out_max_size, sub);
799 115329f1 Diego Biurrun
800 cf7fc795 Fabrice Bellard
        av_init_packet(&pkt);
801
        pkt.stream_index = ost->index;
802
        pkt.data = subtitle_out;
803
        pkt.size = subtitle_out_size;
804 fec401f7 Michael Niedermayer
        pkt.pts = av_rescale_q(pts, ist->st->time_base, ost->st->time_base);
805 cf7fc795 Fabrice Bellard
        if (enc->codec_id == CODEC_ID_DVB_SUBTITLE) {
806
            /* XXX: the pts correction is handled here. Maybe handling
807
               it in the codec would be better */
808
            if (i == 0)
809
                pkt.pts += 90 * sub->start_display_time;
810
            else
811
                pkt.pts += 90 * sub->end_display_time;
812
        }
813 748c2fca Michael Niedermayer
        write_frame(s, &pkt, ost->st->codec, bitstream_filters[ost->file_index][pkt.stream_index]);
814 cf7fc795 Fabrice Bellard
    }
815
}
816
817 8a6cb114 Michael Niedermayer
static int bit_buffer_size= 1024*256;
818 27537106 Michael Niedermayer
static uint8_t *bit_buffer= NULL;
819 1ff93ffc Todd Kirby
820 115329f1 Diego Biurrun
static void do_video_out(AVFormatContext *s,
821
                         AVOutputStream *ost,
822 85f07f22 Fabrice Bellard
                         AVInputStream *ist,
823 7a0f9d7e Fabrice Bellard
                         AVFrame *in_picture,
824 986ebcdb Michael Niedermayer
                         int *frame_size)
825 85f07f22 Fabrice Bellard
{
826 ec5517d5 Fabrice Bellard
    int nb_frames, i, ret;
827 07d0cdfc Luca Abeni
    AVFrame *final_picture, *formatted_picture, *resampling_dst, *padding_src;
828 18a54b04 Luca Abeni
    AVFrame picture_crop_temp, picture_pad_temp;
829 cfcf0ffd Fabrice Bellard
    AVCodecContext *enc, *dec;
830 115329f1 Diego Biurrun
831 a4d36c11 Michael Niedermayer
    avcodec_get_frame_defaults(&picture_crop_temp);
832 07d0cdfc Luca Abeni
    avcodec_get_frame_defaults(&picture_pad_temp);
833 a4d36c11 Michael Niedermayer
834 01f4895c Michael Niedermayer
    enc = ost->st->codec;
835
    dec = ist->st->codec;
836 85f07f22 Fabrice Bellard
837 ec5517d5 Fabrice Bellard
    /* by default, we output a single frame */
838
    nb_frames = 1;
839
840 204c0f48 Philip Gladstone
    *frame_size = 0;
841
842 8858816d Michael Niedermayer
    if(video_sync_method>0 || (video_sync_method && av_q2d(enc->time_base) > 0.001)){
843 10d104e4 Philip Gladstone
        double vdelta;
844 b4a3389e Wolfram Gloger
        vdelta = get_sync_ipts(ost) / av_q2d(enc->time_base) - ost->sync_opts;
845 e928649b Michael Niedermayer
        //FIXME set to 0.5 after we fix some dts/pts bugs like in avidec.c
846
        if (vdelta < -1.1)
847
            nb_frames = 0;
848 880add37 Michael Niedermayer
        else if (video_sync_method == 2)
849
            ost->sync_opts= lrintf(get_sync_ipts(ost) / av_q2d(enc->time_base));
850 e928649b Michael Niedermayer
        else if (vdelta > 1.1)
851 70122f29 Michael Niedermayer
            nb_frames = lrintf(vdelta);
852 949b1a13 Steve L'Homme
//fprintf(stderr, "vdelta:%f, ost->sync_opts:%"PRId64", ost->sync_ipts:%f nb_frames:%d\n", vdelta, ost->sync_opts, ost->sync_ipts, nb_frames);
853 50c3dd32 Michael Niedermayer
        if (nb_frames == 0){
854
            ++nb_frames_drop;
855
            if (verbose>2)
856
                fprintf(stderr, "*** drop!\n");
857 8300609b Michael Niedermayer
        }else if (nb_frames > 1) {
858
            nb_frames_dup += nb_frames;
859 50c3dd32 Michael Niedermayer
            if (verbose>2)
860 8300609b Michael Niedermayer
                fprintf(stderr, "*** %d dup!\n", nb_frames-1);
861 50c3dd32 Michael Niedermayer
        }
862
    }else
863 b4a3389e Wolfram Gloger
        ost->sync_opts= lrintf(get_sync_ipts(ost) / av_q2d(enc->time_base));
864 445f1b83 Roman Shaposhnik
865 7ca60994 Michael Niedermayer
    nb_frames= FFMIN(nb_frames, max_frames[CODEC_TYPE_VIDEO] - ost->frame_number);
866 115329f1 Diego Biurrun
    if (nb_frames <= 0)
867 85f07f22 Fabrice Bellard
        return;
868 ce7c56c2 Juanjo
869 07d0cdfc Luca Abeni
    if (ost->video_crop) {
870 636d6a4a Panagiotis Issaris
        if (av_picture_crop((AVPicture *)&picture_crop_temp, (AVPicture *)in_picture, dec->pix_fmt, ost->topBand, ost->leftBand) < 0) {
871 07d0cdfc Luca Abeni
            av_log(NULL, AV_LOG_ERROR, "error cropping picture\n");
872 4e780252 Limin Wang
            return;
873 07d0cdfc Luca Abeni
        }
874
        formatted_picture = &picture_crop_temp;
875 18a54b04 Luca Abeni
    } else {
876
        formatted_picture = in_picture;
877 07d0cdfc Luca Abeni
    }
878
879
    final_picture = formatted_picture;
880
    padding_src = formatted_picture;
881
    resampling_dst = &ost->pict_tmp;
882
    if (ost->video_pad) {
883
        final_picture = &ost->pict_tmp;
884
        if (ost->video_resample) {
885 636d6a4a Panagiotis Issaris
            if (av_picture_crop((AVPicture *)&picture_pad_temp, (AVPicture *)final_picture, enc->pix_fmt, ost->padtop, ost->padleft) < 0) {
886 07d0cdfc Luca Abeni
                av_log(NULL, AV_LOG_ERROR, "error padding picture\n");
887 4e780252 Limin Wang
                return;
888 07d0cdfc Luca Abeni
            }
889
            resampling_dst = &picture_pad_temp;
890
        }
891
    }
892
893 85f07f22 Fabrice Bellard
    if (ost->video_resample) {
894 07d0cdfc Luca Abeni
        padding_src = NULL;
895 34b10a57 Dieter
        final_picture = &ost->pict_tmp;
896 18a54b04 Luca Abeni
        sws_scale(ost->img_resample_ctx, formatted_picture->data, formatted_picture->linesize,
897
              0, ost->resample_height, resampling_dst->data, resampling_dst->linesize);
898 f122deb4 Luca Abeni
    }
899 07d0cdfc Luca Abeni
900
    if (ost->video_pad) {
901 636d6a4a Panagiotis Issaris
        av_picture_pad((AVPicture*)final_picture, (AVPicture *)padding_src,
902 07d0cdfc Luca Abeni
                enc->height, enc->width, enc->pix_fmt,
903
                ost->padtop, ost->padbottom, ost->padleft, ost->padright, padcolor);
904 85f07f22 Fabrice Bellard
    }
905 07d0cdfc Luca Abeni
906 85f07f22 Fabrice Bellard
    /* duplicates frame if needed */
907 ec5517d5 Fabrice Bellard
    for(i=0;i<nb_frames;i++) {
908 e928649b Michael Niedermayer
        AVPacket pkt;
909
        av_init_packet(&pkt);
910
        pkt.stream_index= ost->index;
911
912 e8750b00 Fred Rothganger
        if (s->oformat->flags & AVFMT_RAWPICTURE) {
913
            /* raw pictures are written as AVPicture structure to
914
               avoid any copies. We support temorarily the older
915
               method. */
916 2744ca9a Roman Shaposhnik
            AVFrame* old_frame = enc->coded_frame;
917 bb270c08 Diego Biurrun
            enc->coded_frame = dec->coded_frame; //FIXME/XXX remove this hack
918 e928649b Michael Niedermayer
            pkt.data= (uint8_t *)final_picture;
919
            pkt.size=  sizeof(AVPicture);
920 b4dba580 Michael Niedermayer
            pkt.pts= av_rescale_q(ost->sync_opts, enc->time_base, ost->st->time_base);
921
            pkt.flags |= PKT_FLAG_KEY;
922 e928649b Michael Niedermayer
923 748c2fca Michael Niedermayer
            write_frame(s, &pkt, ost->st->codec, bitstream_filters[ost->file_index][pkt.stream_index]);
924 bb270c08 Diego Biurrun
            enc->coded_frame = old_frame;
925 e8750b00 Fred Rothganger
        } else {
926 492cd3a9 Michael Niedermayer
            AVFrame big_picture;
927 a4d36c11 Michael Niedermayer
928
            big_picture= *final_picture;
929 7a0f9d7e Fabrice Bellard
            /* better than nothing: use input picture interlaced
930
               settings */
931
            big_picture.interlaced_frame = in_picture->interlaced_frame;
932 23b254fb Benoit Fouet
            if(avctx_opts[CODEC_TYPE_VIDEO]->flags & (CODEC_FLAG_INTERLACED_DCT|CODEC_FLAG_INTERLACED_ME)){
933 bb198e19 Michael Niedermayer
                if(top_field_first == -1)
934
                    big_picture.top_field_first = in_picture->top_field_first;
935
                else
936 2a8edc5d Michael Niedermayer
                    big_picture.top_field_first = top_field_first;
937 bb198e19 Michael Niedermayer
            }
938 7a0f9d7e Fabrice Bellard
939 85f07f22 Fabrice Bellard
            /* handles sameq here. This is not correct because it may
940
               not be a global option */
941
            if (same_quality) {
942 1e491e29 Michael Niedermayer
                big_picture.quality = ist->st->quality;
943
            }else
944
                big_picture.quality = ost->st->quality;
945 f4f3223f Michael Niedermayer
            if(!me_threshold)
946
                big_picture.pict_type = 0;
947 50c3dd32 Michael Niedermayer
//            big_picture.pts = AV_NOPTS_VALUE;
948 c0df9d75 Michael Niedermayer
            big_picture.pts= ost->sync_opts;
949
//            big_picture.pts= av_rescale(ost->sync_opts, AV_TIME_BASE*(int64_t)enc->time_base.num, enc->time_base.den);
950 949b1a13 Steve L'Homme
//av_log(NULL, AV_LOG_DEBUG, "%"PRId64" -> encoder\n", ost->sync_opts);
951 115329f1 Diego Biurrun
            ret = avcodec_encode_video(enc,
952 8a6cb114 Michael Niedermayer
                                       bit_buffer, bit_buffer_size,
953 1e491e29 Michael Niedermayer
                                       &big_picture);
954 4156a436 Panagiotis Issaris
            if (ret == -1) {
955
                fprintf(stderr, "Video encoding failed\n");
956 296df4e7 Ramiro Polla
                av_exit(1);
957 4156a436 Panagiotis Issaris
            }
958 44429457 Juanjo
            //enc->frame_number = enc->real_pict_num;
959 4bbc6260 Michael Niedermayer
            if(ret>0){
960 27537106 Michael Niedermayer
                pkt.data= bit_buffer;
961 e928649b Michael Niedermayer
                pkt.size= ret;
962 e6b4e4ff Michael Niedermayer
                if(enc->coded_frame->pts != AV_NOPTS_VALUE)
963 c0df9d75 Michael Niedermayer
                    pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
964 949b1a13 Steve L'Homme
/*av_log(NULL, AV_LOG_DEBUG, "encoder -> %"PRId64"/%"PRId64"\n",
965 c0df9d75 Michael Niedermayer
   pkt.pts != AV_NOPTS_VALUE ? av_rescale(pkt.pts, enc->time_base.den, AV_TIME_BASE*(int64_t)enc->time_base.num) : -1,
966
   pkt.dts != AV_NOPTS_VALUE ? av_rescale(pkt.dts, enc->time_base.den, AV_TIME_BASE*(int64_t)enc->time_base.num) : -1);*/
967 50c3dd32 Michael Niedermayer
968 e6b4e4ff Michael Niedermayer
                if(enc->coded_frame->key_frame)
969 e928649b Michael Niedermayer
                    pkt.flags |= PKT_FLAG_KEY;
970 748c2fca Michael Niedermayer
                write_frame(s, &pkt, ost->st->codec, bitstream_filters[ost->file_index][pkt.stream_index]);
971 e928649b Michael Niedermayer
                *frame_size = ret;
972 44eb047a Michael Niedermayer
                video_size += ret;
973 e928649b Michael Niedermayer
                //fprintf(stderr,"\nFrame: %3d %3d size: %5d type: %d",
974
                //        enc->frame_number-1, enc->real_pict_num, ret,
975
                //        enc->pict_type);
976
                /* if two pass, output log */
977
                if (ost->logfile && enc->stats_out) {
978
                    fprintf(ost->logfile, "%s", enc->stats_out);
979
                }
980 5abdb4b1 Fabrice Bellard
            }
981 85f07f22 Fabrice Bellard
        }
982 50c3dd32 Michael Niedermayer
        ost->sync_opts++;
983 ec5517d5 Fabrice Bellard
        ost->frame_number++;
984 85f07f22 Fabrice Bellard
    }
985
}
986
987 140cb663 Michael Niedermayer
static double psnr(double d){
988 b29f97d1 Zdenek Kabelac
    return -10.0*log(d)/log(10.0);
989 140cb663 Michael Niedermayer
}
990
991 115329f1 Diego Biurrun
static void do_video_stats(AVFormatContext *os, AVOutputStream *ost,
992 ec5517d5 Fabrice Bellard
                           int frame_size)
993 ce7c56c2 Juanjo
{
994
    AVCodecContext *enc;
995
    int frame_number;
996
    double ti1, bitrate, avg_bitrate;
997 115329f1 Diego Biurrun
998 b60d1379 Stefano Sabatini
    /* this is executed just the first time do_video_stats is called */
999 032aa7df Stefano Sabatini
    if (!vstats_file) {
1000
        vstats_file = fopen(vstats_filename, "w");
1001
        if (!vstats_file) {
1002 4bd0c2b1 Benoit Fouet
            perror("fopen");
1003 296df4e7 Ramiro Polla
            av_exit(1);
1004 4bd0c2b1 Benoit Fouet
        }
1005
    }
1006
1007 01f4895c Michael Niedermayer
    enc = ost->st->codec;
1008 ce7c56c2 Juanjo
    if (enc->codec_type == CODEC_TYPE_VIDEO) {
1009 ec5517d5 Fabrice Bellard
        frame_number = ost->frame_number;
1010 032aa7df Stefano Sabatini
        fprintf(vstats_file, "frame= %5d q= %2.1f ", frame_number, enc->coded_frame->quality/(float)FF_QP2LAMBDA);
1011 140cb663 Michael Niedermayer
        if (enc->flags&CODEC_FLAG_PSNR)
1012 032aa7df Stefano Sabatini
            fprintf(vstats_file, "PSNR= %6.2f ", psnr(enc->coded_frame->error[0]/(enc->width*enc->height*255.0*255.0)));
1013 115329f1 Diego Biurrun
1014 032aa7df Stefano Sabatini
        fprintf(vstats_file,"f_size= %6d ", frame_size);
1015 ec5517d5 Fabrice Bellard
        /* compute pts value */
1016 c0df9d75 Michael Niedermayer
        ti1 = ost->sync_opts * av_q2d(enc->time_base);
1017 ce7c56c2 Juanjo
        if (ti1 < 0.01)
1018
            ti1 = 0.01;
1019 115329f1 Diego Biurrun
1020 c0df9d75 Michael Niedermayer
        bitrate = (frame_size * 8) / av_q2d(enc->time_base) / 1000.0;
1021 1008ceb3 Michael Niedermayer
        avg_bitrate = (double)(video_size * 8) / ti1 / 1000.0;
1022 032aa7df Stefano Sabatini
        fprintf(vstats_file, "s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
1023 1008ceb3 Michael Niedermayer
            (double)video_size / 1024, ti1, bitrate, avg_bitrate);
1024 032aa7df Stefano Sabatini
        fprintf(vstats_file,"type= %c\n", av_get_pict_type_char(enc->coded_frame->pict_type));
1025 ce7c56c2 Juanjo
    }
1026 ec5517d5 Fabrice Bellard
}
1027
1028 b29f97d1 Zdenek Kabelac
static void print_report(AVFormatContext **output_files,
1029 bb270c08 Diego Biurrun
                         AVOutputStream **ost_table, int nb_ostreams,
1030
                         int is_last_report)
1031 ec5517d5 Fabrice Bellard
{
1032
    char buf[1024];
1033
    AVOutputStream *ost;
1034
    AVFormatContext *oc, *os;
1035 0c1a9eda Zdenek Kabelac
    int64_t total_size;
1036 ec5517d5 Fabrice Bellard
    AVCodecContext *enc;
1037
    int frame_number, vid, i;
1038
    double bitrate, ti1, pts;
1039 0c1a9eda Zdenek Kabelac
    static int64_t last_time = -1;
1040 0888fd22 Michael Niedermayer
    static int qp_histogram[52];
1041 115329f1 Diego Biurrun
1042 ec5517d5 Fabrice Bellard
    if (!is_last_report) {
1043 0c1a9eda Zdenek Kabelac
        int64_t cur_time;
1044 ec5517d5 Fabrice Bellard
        /* display the report every 0.5 seconds */
1045
        cur_time = av_gettime();
1046
        if (last_time == -1) {
1047
            last_time = cur_time;
1048
            return;
1049 115329f1 Diego Biurrun
        }
1050 ec5517d5 Fabrice Bellard
        if ((cur_time - last_time) < 500000)
1051
            return;
1052
        last_time = cur_time;
1053
    }
1054
1055 ce7c56c2 Juanjo
1056 ec5517d5 Fabrice Bellard
    oc = output_files[0];
1057
1058 899681cd Björn Axelsson
    total_size = url_fsize(oc->pb);
1059 859d95ba Michael Niedermayer
    if(total_size<0) // FIXME improve url_fsize() so it works with non seekable output too
1060 899681cd Björn Axelsson
        total_size= url_ftell(oc->pb);
1061 115329f1 Diego Biurrun
1062 ec5517d5 Fabrice Bellard
    buf[0] = '\0';
1063
    ti1 = 1e10;
1064
    vid = 0;
1065
    for(i=0;i<nb_ostreams;i++) {
1066
        ost = ost_table[i];
1067
        os = output_files[ost->file_index];
1068 01f4895c Michael Niedermayer
        enc = ost->st->codec;
1069 10d104e4 Philip Gladstone
        if (vid && enc->codec_type == CODEC_TYPE_VIDEO) {
1070 0ecca7a4 Michael Niedermayer
            snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "q=%2.1f ",
1071 e6b4e4ff Michael Niedermayer
                     !ost->st->stream_copy ?
1072 99fb79b5 Baptiste Coudurier
                     enc->coded_frame->quality/(float)FF_QP2LAMBDA : -1);
1073 10d104e4 Philip Gladstone
        }
1074 ec5517d5 Fabrice Bellard
        if (!vid && enc->codec_type == CODEC_TYPE_VIDEO) {
1075 7fc98937 Limin Wang
            float t = (av_gettime()-timer_start) / 1000000.0;
1076
1077 ec5517d5 Fabrice Bellard
            frame_number = ost->frame_number;
1078 7fc98937 Limin Wang
            snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "frame=%5d fps=%3d q=%3.1f ",
1079
                     frame_number, (t>1)?(int)(frame_number/t+0.5) : 0,
1080 e6b4e4ff Michael Niedermayer
                     !ost->st->stream_copy ?
1081 99fb79b5 Baptiste Coudurier
                     enc->coded_frame->quality/(float)FF_QP2LAMBDA : -1);
1082 890972be Michael Niedermayer
            if(is_last_report)
1083 0ecca7a4 Michael Niedermayer
                snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "L");
1084 e6b4e4ff Michael Niedermayer
            if(qp_hist){
1085 0888fd22 Michael Niedermayer
                int j;
1086
                int qp= lrintf(enc->coded_frame->quality/(float)FF_QP2LAMBDA);
1087
                if(qp>=0 && qp<sizeof(qp_histogram)/sizeof(int))
1088
                    qp_histogram[qp]++;
1089
                for(j=0; j<32; j++)
1090
                    snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%X", (int)lrintf(log(qp_histogram[j]+1)/log(2)));
1091
            }
1092 890972be Michael Niedermayer
            if (enc->flags&CODEC_FLAG_PSNR){
1093
                int j;
1094
                double error, error_sum=0;
1095
                double scale, scale_sum=0;
1096
                char type[3]= {'Y','U','V'};
1097 0ecca7a4 Michael Niedermayer
                snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "PSNR=");
1098 890972be Michael Niedermayer
                for(j=0; j<3; j++){
1099
                    if(is_last_report){
1100
                        error= enc->error[j];
1101
                        scale= enc->width*enc->height*255.0*255.0*frame_number;
1102
                    }else{
1103
                        error= enc->coded_frame->error[j];
1104
                        scale= enc->width*enc->height*255.0*255.0;
1105
                    }
1106
                    if(j) scale/=4;
1107
                    error_sum += error;
1108
                    scale_sum += scale;
1109 0ecca7a4 Michael Niedermayer
                    snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%c:%2.2f ", type[j], psnr(error/scale));
1110 890972be Michael Niedermayer
                }
1111 0ecca7a4 Michael Niedermayer
                snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "*:%2.2f ", psnr(error_sum/scale_sum));
1112 890972be Michael Niedermayer
            }
1113 ec5517d5 Fabrice Bellard
            vid = 1;
1114
        }
1115
        /* compute min output value */
1116 43924f01 Alex Beregszaszi
        pts = (double)ost->st->pts.val * av_q2d(ost->st->time_base);
1117 5d9827bc Kareila
        if ((pts < ti1) && (pts > 0))
1118 ec5517d5 Fabrice Bellard
            ti1 = pts;
1119
    }
1120
    if (ti1 < 0.01)
1121
        ti1 = 0.01;
1122 115329f1 Diego Biurrun
1123 f068206e Bill Eldridge
    if (verbose || is_last_report) {
1124
        bitrate = (double)(total_size * 8) / ti1 / 1000.0;
1125 115329f1 Diego Biurrun
1126
        snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1127 475f4d8d David Bolt
            "size=%8.0fkB time=%0.2f bitrate=%6.1fkbits/s",
1128 ec5517d5 Fabrice Bellard
            (double)total_size / 1024, ti1, bitrate);
1129 a6a92a9a Wolfram Gloger
1130 bb270c08 Diego Biurrun
        if (verbose > 1)
1131
          snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), " dup=%d drop=%d",
1132
                  nb_frames_dup, nb_frames_drop);
1133 115329f1 Diego Biurrun
1134 d8019eb5 Allen Day
        if (verbose >= 0)
1135
            fprintf(stderr, "%s    \r", buf);
1136
1137 ec5517d5 Fabrice Bellard
        fflush(stderr);
1138
    }
1139 115329f1 Diego Biurrun
1140 1008ceb3 Michael Niedermayer
    if (is_last_report && verbose >= 0){
1141
        int64_t raw= audio_size + video_size + extra_size;
1142 f068206e Bill Eldridge
        fprintf(stderr, "\n");
1143 1008ceb3 Michael Niedermayer
        fprintf(stderr, "video:%1.0fkB audio:%1.0fkB global headers:%1.0fkB muxing overhead %f%%\n",
1144
                video_size/1024.0,
1145
                audio_size/1024.0,
1146
                extra_size/1024.0,
1147
                100.0*(total_size - raw)/raw
1148
        );
1149
    }
1150 ce7c56c2 Juanjo
}
1151
1152 a700a6ae Fabrice Bellard
/* pkt = NULL means EOF (needed to flush decoder buffers) */
1153
static int output_packet(AVInputStream *ist, int ist_index,
1154
                         AVOutputStream **ost_table, int nb_ostreams,
1155 4b85a28f Wolfram Gloger
                         const AVPacket *pkt)
1156 a700a6ae Fabrice Bellard
{
1157
    AVFormatContext *os;
1158
    AVOutputStream *ost;
1159
    uint8_t *ptr;
1160
    int len, ret, i;
1161
    uint8_t *data_buf;
1162
    int data_size, got_picture;
1163
    AVFrame picture;
1164
    void *buffer_to_free;
1165 f038fe8b Diego Biurrun
    static unsigned int samples_size= 0;
1166 78953e62 Michael Niedermayer
    static short *samples= NULL;
1167 cf7fc795 Fabrice Bellard
    AVSubtitle subtitle, *subtitle_to_free;
1168
    int got_subtitle;
1169 115329f1 Diego Biurrun
1170 ed923859 Michael Niedermayer
    if(ist->next_pts == AV_NOPTS_VALUE)
1171
        ist->next_pts= ist->pts;
1172
1173 a700a6ae Fabrice Bellard
    if (pkt == NULL) {
1174
        /* EOF handling */
1175
        ptr = NULL;
1176
        len = 0;
1177
        goto handle_eof;
1178
    }
1179
1180 b1b818fc Michael Niedermayer
    if(pkt->dts != AV_NOPTS_VALUE)
1181
        ist->next_pts = ist->pts = av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);
1182
1183 a700a6ae Fabrice Bellard
    len = pkt->size;
1184
    ptr = pkt->data;
1185 bd6754aa Michael Niedermayer
1186
    //while we have more to decode or while the decoder did output something on EOF
1187
    while (len > 0 || (!pkt && ist->next_pts != ist->pts)) {
1188 a700a6ae Fabrice Bellard
    handle_eof:
1189 b1b818fc Michael Niedermayer
        ist->pts= ist->next_pts;
1190 19d5da50 Michael Niedermayer
1191 40cb57a2 Michael Niedermayer
        if(len && len != pkt->size && verbose>0)
1192
            fprintf(stderr, "Multiple frames in a packet from stream %d\n", pkt->stream_index);
1193
1194 a700a6ae Fabrice Bellard
        /* decode the packet if needed */
1195
        data_buf = NULL; /* fail safe */
1196
        data_size = 0;
1197 cf7fc795 Fabrice Bellard
        subtitle_to_free = NULL;
1198 a700a6ae Fabrice Bellard
        if (ist->decoding_needed) {
1199 01f4895c Michael Niedermayer
            switch(ist->st->codec->codec_type) {
1200 df84ac2e Michael Niedermayer
            case CODEC_TYPE_AUDIO:{
1201 81b060fa Loren Merritt
                if(pkt && samples_size < FFMAX(pkt->size*sizeof(*samples), AVCODEC_MAX_AUDIO_FRAME_SIZE)) {
1202
                    samples_size = FFMAX(pkt->size*sizeof(*samples), AVCODEC_MAX_AUDIO_FRAME_SIZE);
1203
                    av_free(samples);
1204
                    samples= av_malloc(samples_size);
1205
                }
1206 5d55e966 Michael Niedermayer
                data_size= samples_size;
1207 a700a6ae Fabrice Bellard
                    /* XXX: could avoid copy if PCM 16 bits with same
1208
                       endianness as CPU */
1209 5d55e966 Michael Niedermayer
                ret = avcodec_decode_audio2(ist->st->codec, samples, &data_size,
1210 a700a6ae Fabrice Bellard
                                           ptr, len);
1211
                if (ret < 0)
1212
                    goto fail_decode;
1213
                ptr += ret;
1214
                len -= ret;
1215
                /* Some bug in mpeg audio decoder gives */
1216
                /* data_size < 0, it seems they are overflows */
1217
                if (data_size <= 0) {
1218
                    /* no audio frame */
1219
                    continue;
1220
                }
1221
                data_buf = (uint8_t *)samples;
1222 115329f1 Diego Biurrun
                ist->next_pts += ((int64_t)AV_TIME_BASE/2 * data_size) /
1223 01f4895c Michael Niedermayer
                    (ist->st->codec->sample_rate * ist->st->codec->channels);
1224 df84ac2e Michael Niedermayer
                break;}
1225 a700a6ae Fabrice Bellard
            case CODEC_TYPE_VIDEO:
1226 01f4895c Michael Niedermayer
                    data_size = (ist->st->codec->width * ist->st->codec->height * 3) / 2;
1227 a700a6ae Fabrice Bellard
                    /* XXX: allocate picture correctly */
1228 9740beff Michael Niedermayer
                    avcodec_get_frame_defaults(&picture);
1229
1230 115329f1 Diego Biurrun
                    ret = avcodec_decode_video(ist->st->codec,
1231 a700a6ae Fabrice Bellard
                                               &picture, &got_picture, ptr, len);
1232
                    ist->st->quality= picture.quality;
1233 115329f1 Diego Biurrun
                    if (ret < 0)
1234 a700a6ae Fabrice Bellard
                        goto fail_decode;
1235
                    if (!got_picture) {
1236
                        /* no picture yet */
1237
                        goto discard_packet;
1238
                    }
1239 01f4895c Michael Niedermayer
                    if (ist->st->codec->time_base.num != 0) {
1240 115329f1 Diego Biurrun
                        ist->next_pts += ((int64_t)AV_TIME_BASE *
1241 01f4895c Michael Niedermayer
                                          ist->st->codec->time_base.num) /
1242
                            ist->st->codec->time_base.den;
1243 a700a6ae Fabrice Bellard
                    }
1244
                    len = 0;
1245
                    break;
1246 cf7fc795 Fabrice Bellard
            case CODEC_TYPE_SUBTITLE:
1247 115329f1 Diego Biurrun
                ret = avcodec_decode_subtitle(ist->st->codec,
1248 cf7fc795 Fabrice Bellard
                                              &subtitle, &got_subtitle, ptr, len);
1249
                if (ret < 0)
1250 a700a6ae Fabrice Bellard
                    goto fail_decode;
1251 cf7fc795 Fabrice Bellard
                if (!got_subtitle) {
1252
                    goto discard_packet;
1253 a700a6ae Fabrice Bellard
                }
1254 cf7fc795 Fabrice Bellard
                subtitle_to_free = &subtitle;
1255
                len = 0;
1256
                break;
1257
            default:
1258
                goto fail_decode;
1259
            }
1260
        } else {
1261 bde0705c Limin Wang
            switch(ist->st->codec->codec_type) {
1262
            case CODEC_TYPE_AUDIO:
1263
                ist->next_pts += ((int64_t)AV_TIME_BASE * ist->st->codec->frame_size) /
1264 1c715415 Michael Niedermayer
                    ist->st->codec->sample_rate;
1265 bde0705c Limin Wang
                break;
1266
            case CODEC_TYPE_VIDEO:
1267
                if (ist->st->codec->time_base.num != 0) {
1268
                    ist->next_pts += ((int64_t)AV_TIME_BASE *
1269
                                      ist->st->codec->time_base.num) /
1270
                        ist->st->codec->time_base.den;
1271 2fef0bdf Michael Niedermayer
                }
1272 bde0705c Limin Wang
                break;
1273 a700a6ae Fabrice Bellard
            }
1274 bde0705c Limin Wang
            data_buf = ptr;
1275
            data_size = len;
1276
            ret = len;
1277
            len = 0;
1278
        }
1279 a700a6ae Fabrice Bellard
1280 bde0705c Limin Wang
        buffer_to_free = NULL;
1281
        if (ist->st->codec->codec_type == CODEC_TYPE_VIDEO) {
1282
            pre_process_video_frame(ist, (AVPicture *)&picture,
1283
                                    &buffer_to_free);
1284
        }
1285 a700a6ae Fabrice Bellard
1286 bde0705c Limin Wang
        // preprocess audio (volume)
1287
        if (ist->st->codec->codec_type == CODEC_TYPE_AUDIO) {
1288
            if (audio_volume != 256) {
1289
                short *volp;
1290
                volp = samples;
1291
                for(i=0;i<(data_size / sizeof(short));i++) {
1292
                    int v = ((*volp) * audio_volume + 128) >> 8;
1293
                    if (v < -32768) v = -32768;
1294
                    if (v >  32767) v = 32767;
1295
                    *volp++ = v;
1296 7e987c33 Calcium
                }
1297
            }
1298 bde0705c Limin Wang
        }
1299 7e987c33 Calcium
1300 bde0705c Limin Wang
        /* frame rate emulation */
1301
        if (ist->st->codec->rate_emu) {
1302
            int64_t pts = av_rescale((int64_t) ist->frame * ist->st->codec->time_base.num, 1000000, ist->st->codec->time_base.den);
1303
            int64_t now = av_gettime() - ist->start;
1304
            if (pts > now)
1305
                usleep(pts - now);
1306 a700a6ae Fabrice Bellard
1307 bde0705c Limin Wang
            ist->frame++;
1308
        }
1309 a700a6ae Fabrice Bellard
1310
#if 0
1311 bde0705c Limin Wang
        /* mpeg PTS deordering : if it is a P or I frame, the PTS
1312
           is the one of the next displayed one */
1313
        /* XXX: add mpeg4 too ? */
1314
        if (ist->st->codec->codec_id == CODEC_ID_MPEG1VIDEO) {
1315
            if (ist->st->codec->pict_type != B_TYPE) {
1316
                int64_t tmp;
1317
                tmp = ist->last_ip_pts;
1318
                ist->last_ip_pts  = ist->frac_pts.val;
1319
                ist->frac_pts.val = tmp;
1320 a700a6ae Fabrice Bellard
            }
1321 bde0705c Limin Wang
        }
1322 a700a6ae Fabrice Bellard
#endif
1323 bde0705c Limin Wang
        /* if output time reached then transcode raw format,
1324
           encode packets and output them */
1325
        if (start_time == 0 || ist->pts >= start_time)
1326
            for(i=0;i<nb_ostreams;i++) {
1327
                int frame_size;
1328 a700a6ae Fabrice Bellard
1329 bde0705c Limin Wang
                ost = ost_table[i];
1330
                if (ost->source_index == ist_index) {
1331
                    os = output_files[ost->file_index];
1332 a700a6ae Fabrice Bellard
1333
#if 0
1334 bde0705c Limin Wang
                    printf("%d: got pts=%0.3f %0.3f\n", i,
1335
                           (double)pkt->pts / AV_TIME_BASE,
1336
                           ((double)ist->pts / AV_TIME_BASE) -
1337
                           ((double)ost->st->pts.val * ost->st->time_base.num / ost->st->time_base.den));
1338 a700a6ae Fabrice Bellard
#endif
1339 bde0705c Limin Wang
                    /* set the input output pts pairs */
1340
                    //ost->sync_ipts = (double)(ist->pts + input_files_ts_offset[ist->file_index] - start_time)/ AV_TIME_BASE;
1341
1342
                    if (ost->encoding_needed) {
1343
                        switch(ost->st->codec->codec_type) {
1344
                        case CODEC_TYPE_AUDIO:
1345
                            do_audio_out(os, ost, ist, data_buf, data_size);
1346
                            break;
1347
                        case CODEC_TYPE_VIDEO:
1348
                            do_video_out(os, ost, ist, &picture, &frame_size);
1349 b60d1379 Stefano Sabatini
                            if (vstats_filename && frame_size)
1350 bde0705c Limin Wang
                                do_video_stats(os, ost, frame_size);
1351
                            break;
1352
                        case CODEC_TYPE_SUBTITLE:
1353
                            do_subtitle_out(os, ost, ist, &subtitle,
1354
                                            pkt->pts);
1355
                            break;
1356
                        default:
1357 0f4e8165 Ronald S. Bultje
                            abort();
1358 bde0705c Limin Wang
                        }
1359
                    } else {
1360
                        AVFrame avframe; //FIXME/XXX remove this
1361
                        AVPacket opkt;
1362
                        av_init_packet(&opkt);
1363
1364 7cacf1e8 Michael Niedermayer
                        if (!ost->frame_number && !(pkt->flags & PKT_FLAG_KEY))
1365
                            continue;
1366
1367 bde0705c Limin Wang
                        /* no reencoding needed : output the packet directly */
1368
                        /* force the input stream PTS */
1369
1370
                        avcodec_get_frame_defaults(&avframe);
1371
                        ost->st->codec->coded_frame= &avframe;
1372
                        avframe.key_frame = pkt->flags & PKT_FLAG_KEY;
1373
1374
                        if(ost->st->codec->codec_type == CODEC_TYPE_AUDIO)
1375
                            audio_size += data_size;
1376
                        else if (ost->st->codec->codec_type == CODEC_TYPE_VIDEO) {
1377
                            video_size += data_size;
1378
                            ost->sync_opts++;
1379
                        }
1380
1381
                        opkt.stream_index= ost->index;
1382
                        if(pkt->pts != AV_NOPTS_VALUE)
1383 fec401f7 Michael Niedermayer
                            opkt.pts= av_rescale_q(pkt->pts, ist->st->time_base, ost->st->time_base);
1384 bde0705c Limin Wang
                        else
1385
                            opkt.pts= AV_NOPTS_VALUE;
1386
1387 d2ce2f5e Baptiste Coudurier
                        if (pkt->dts == AV_NOPTS_VALUE)
1388 181782ae Michael Niedermayer
                            opkt.dts = av_rescale_q(ist->pts, AV_TIME_BASE_Q, ost->st->time_base);
1389 d2ce2f5e Baptiste Coudurier
                        else
1390
                            opkt.dts = av_rescale_q(pkt->dts, ist->st->time_base, ost->st->time_base);
1391 c0dd7b7c Michael Niedermayer
1392 a03d59b7 Aurelien Jacobs
                        opkt.duration = av_rescale_q(pkt->duration, ist->st->time_base, ost->st->time_base);
1393 bde0705c Limin Wang
                        opkt.flags= pkt->flags;
1394
1395
                        //FIXME remove the following 2 lines they shall be replaced by the bitstream filters
1396
                        if(av_parser_change(ist->st->parser, ost->st->codec, &opkt.data, &opkt.size, data_buf, data_size, pkt->flags & PKT_FLAG_KEY))
1397
                            opkt.destruct= av_destruct_packet;
1398
1399 8b389f15 Andreas Öman
                        write_frame(os, &opkt, ost->st->codec, bitstream_filters[ost->file_index][opkt.stream_index]);
1400 bde0705c Limin Wang
                        ost->st->codec->frame_number++;
1401
                        ost->frame_number++;
1402
                        av_free_packet(&opkt);
1403 a700a6ae Fabrice Bellard
                    }
1404
                }
1405 bde0705c Limin Wang
            }
1406
        av_free(buffer_to_free);
1407
        /* XXX: allocate the subtitles in the codec ? */
1408
        if (subtitle_to_free) {
1409
            if (subtitle_to_free->rects != NULL) {
1410
                for (i = 0; i < subtitle_to_free->num_rects; i++) {
1411
                    av_free(subtitle_to_free->rects[i].bitmap);
1412
                    av_free(subtitle_to_free->rects[i].rgba_palette);
1413 c6ec28b1 Michael Niedermayer
                }
1414 bde0705c Limin Wang
                av_freep(&subtitle_to_free->rects);
1415 cf7fc795 Fabrice Bellard
            }
1416 bde0705c Limin Wang
            subtitle_to_free->num_rects = 0;
1417
            subtitle_to_free = NULL;
1418 a700a6ae Fabrice Bellard
        }
1419 bde0705c Limin Wang
    }
1420 a700a6ae Fabrice Bellard
 discard_packet:
1421 6f824977 Michael Niedermayer
    if (pkt == NULL) {
1422
        /* EOF handling */
1423 115329f1 Diego Biurrun
1424 6f824977 Michael Niedermayer
        for(i=0;i<nb_ostreams;i++) {
1425
            ost = ost_table[i];
1426
            if (ost->source_index == ist_index) {
1427 01f4895c Michael Niedermayer
                AVCodecContext *enc= ost->st->codec;
1428 6f824977 Michael Niedermayer
                os = output_files[ost->file_index];
1429 115329f1 Diego Biurrun
1430 01f4895c Michael Niedermayer
                if(ost->st->codec->codec_type == CODEC_TYPE_AUDIO && enc->frame_size <=1)
1431 6f824977 Michael Niedermayer
                    continue;
1432 01f4895c Michael Niedermayer
                if(ost->st->codec->codec_type == CODEC_TYPE_VIDEO && (os->oformat->flags & AVFMT_RAWPICTURE))
1433 6f824977 Michael Niedermayer
                    continue;
1434
1435
                if (ost->encoding_needed) {
1436
                    for(;;) {
1437
                        AVPacket pkt;
1438 cef7cc72 Justin Ruggles
                        int fifo_bytes;
1439 6f824977 Michael Niedermayer
                        av_init_packet(&pkt);
1440
                        pkt.stream_index= ost->index;
1441 115329f1 Diego Biurrun
1442 01f4895c Michael Niedermayer
                        switch(ost->st->codec->codec_type) {
1443 115329f1 Diego Biurrun
                        case CODEC_TYPE_AUDIO:
1444 f5a478f6 Roman Shaposhnik
                            fifo_bytes = av_fifo_size(&ost->fifo);
1445 cef7cc72 Justin Ruggles
                            ret = 0;
1446
                            /* encode any samples remaining in fifo */
1447
                            if(fifo_bytes > 0 && enc->codec->capabilities & CODEC_CAP_SMALL_LAST_FRAME) {
1448
                                int fs_tmp = enc->frame_size;
1449
                                enc->frame_size = fifo_bytes / (2 * enc->channels);
1450 0871ae1a Michael Niedermayer
                                av_fifo_read(&ost->fifo, (uint8_t *)samples, fifo_bytes);
1451 cef7cc72 Justin Ruggles
                                    ret = avcodec_encode_audio(enc, bit_buffer, bit_buffer_size, samples);
1452
                                enc->frame_size = fs_tmp;
1453 9e0db7d5 Michael Niedermayer
                            }
1454
                            if(ret <= 0) {
1455 cef7cc72 Justin Ruggles
                                ret = avcodec_encode_audio(enc, bit_buffer, bit_buffer_size, NULL);
1456
                            }
1457 6f824977 Michael Niedermayer
                            audio_size += ret;
1458
                            pkt.flags |= PKT_FLAG_KEY;
1459
                            break;
1460
                        case CODEC_TYPE_VIDEO:
1461 8a6cb114 Michael Niedermayer
                            ret = avcodec_encode_video(enc, bit_buffer, bit_buffer_size, NULL);
1462 6f824977 Michael Niedermayer
                            video_size += ret;
1463
                            if(enc->coded_frame && enc->coded_frame->key_frame)
1464
                                pkt.flags |= PKT_FLAG_KEY;
1465
                            if (ost->logfile && enc->stats_out) {
1466
                                fprintf(ost->logfile, "%s", enc->stats_out);
1467
                            }
1468
                            break;
1469
                        default:
1470
                            ret=-1;
1471
                        }
1472 115329f1 Diego Biurrun
1473 6f824977 Michael Niedermayer
                        if(ret<=0)
1474
                            break;
1475 27537106 Michael Niedermayer
                        pkt.data= bit_buffer;
1476 6f824977 Michael Niedermayer
                        pkt.size= ret;
1477 e7902f20 Michael Niedermayer
                        if(enc->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)
1478 c0df9d75 Michael Niedermayer
                            pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
1479 748c2fca Michael Niedermayer
                        write_frame(os, &pkt, ost->st->codec, bitstream_filters[ost->file_index][pkt.stream_index]);
1480 6f824977 Michael Niedermayer
                    }
1481
                }
1482
            }
1483
        }
1484
    }
1485 115329f1 Diego Biurrun
1486 a700a6ae Fabrice Bellard
    return 0;
1487
 fail_decode:
1488
    return -1;
1489
}
1490
1491 6d1ba1ac Luca Abeni
static void print_sdp(AVFormatContext **avc, int n)
1492
{
1493
    char sdp[2048];
1494
1495
    avf_sdp_create(avc, n, sdp, sizeof(sdp));
1496
    printf("SDP:\n%s\n", sdp);
1497
}
1498 a700a6ae Fabrice Bellard
1499 50e143c4 Nico Sabbi
static int stream_index_from_inputs(AVFormatContext **input_files,
1500
                                    int nb_input_files,
1501
                                    AVInputFile *file_table,
1502
                                    AVInputStream **ist_table,
1503
                                    enum CodecType type,
1504
                                    int programid)
1505
{
1506 c1a4cdf9 Nico Sabbi
    int p, q, z;
1507 50e143c4 Nico Sabbi
    for(z=0; z<nb_input_files; z++) {
1508
        AVFormatContext *ic = input_files[z];
1509
        for(p=0; p<ic->nb_programs; p++) {
1510
            AVProgram *program = ic->programs[p];
1511
            if(program->id != programid)
1512
                continue;
1513
            for(q=0; q<program->nb_stream_indexes; q++) {
1514
                int sidx = program->stream_index[q];
1515
                int ris = file_table[z].ist_index + sidx;
1516
                if(ist_table[ris]->discard && ic->streams[sidx]->codec->codec_type == type)
1517
                    return ris;
1518
            }
1519
        }
1520
    }
1521
1522
    return -1;
1523
}
1524
1525 85f07f22 Fabrice Bellard
/*
1526
 * The following code is the main loop of the file converter
1527
 */
1528
static int av_encode(AVFormatContext **output_files,
1529
                     int nb_output_files,
1530
                     AVFormatContext **input_files,
1531
                     int nb_input_files,
1532
                     AVStreamMap *stream_maps, int nb_stream_maps)
1533
{
1534 445f1b83 Roman Shaposhnik
    int ret, i, j, k, n, nb_istreams = 0, nb_ostreams = 0;
1535 85f07f22 Fabrice Bellard
    AVFormatContext *is, *os;
1536
    AVCodecContext *codec, *icodec;
1537
    AVOutputStream *ost, **ost_table = NULL;
1538
    AVInputStream *ist, **ist_table = NULL;
1539 bdc4796f Fabrice Bellard
    AVInputFile *file_table;
1540 cb09b2ed Philip Gladstone
    int key;
1541 6d1ba1ac Luca Abeni
    int want_sdp = 1;
1542 bdc4796f Fabrice Bellard
1543 90901860 Michael Niedermayer
    file_table= av_mallocz(nb_input_files * sizeof(AVInputFile));
1544 bdc4796f Fabrice Bellard
    if (!file_table)
1545
        goto fail;
1546 115329f1 Diego Biurrun
1547 85f07f22 Fabrice Bellard
    /* input stream init */
1548
    j = 0;
1549
    for(i=0;i<nb_input_files;i++) {
1550
        is = input_files[i];
1551
        file_table[i].ist_index = j;
1552 79fdaa4c Fabrice Bellard
        file_table[i].nb_streams = is->nb_streams;
1553 85f07f22 Fabrice Bellard
        j += is->nb_streams;
1554
    }
1555
    nb_istreams = j;
1556
1557
    ist_table = av_mallocz(nb_istreams * sizeof(AVInputStream *));
1558
    if (!ist_table)
1559 bdc4796f Fabrice Bellard
        goto fail;
1560 115329f1 Diego Biurrun
1561 85f07f22 Fabrice Bellard
    for(i=0;i<nb_istreams;i++) {
1562
        ist = av_mallocz(sizeof(AVInputStream));
1563
        if (!ist)
1564
            goto fail;
1565
        ist_table[i] = ist;
1566
    }
1567
    j = 0;
1568
    for(i=0;i<nb_input_files;i++) {
1569
        is = input_files[i];
1570
        for(k=0;k<is->nb_streams;k++) {
1571
            ist = ist_table[j++];
1572
            ist->st = is->streams[k];
1573
            ist->file_index = i;
1574
            ist->index = k;
1575
            ist->discard = 1; /* the stream is discarded by default
1576
                                 (changed later) */
1577 bdfcbbed Max Krasnyansky
1578 01f4895c Michael Niedermayer
            if (ist->st->codec->rate_emu) {
1579 bdfcbbed Max Krasnyansky
                ist->start = av_gettime();
1580
                ist->frame = 0;
1581
            }
1582 85f07f22 Fabrice Bellard
        }
1583
    }
1584
1585
    /* output stream init */
1586
    nb_ostreams = 0;
1587
    for(i=0;i<nb_output_files;i++) {
1588
        os = output_files[i];
1589 8a7bde1c Baptiste Coudurier
        if (!os->nb_streams) {
1590
            fprintf(stderr, "Output file does not contain any stream\n");
1591 296df4e7 Ramiro Polla
            av_exit(1);
1592 8a7bde1c Baptiste Coudurier
        }
1593 85f07f22 Fabrice Bellard
        nb_ostreams += os->nb_streams;
1594
    }
1595
    if (nb_stream_maps > 0 && nb_stream_maps != nb_ostreams) {
1596
        fprintf(stderr, "Number of stream maps must match number of output streams\n");
1597 296df4e7 Ramiro Polla
        av_exit(1);
1598 85f07f22 Fabrice Bellard
    }
1599
1600 bd073980 Brian Foley
    /* Sanity check the mapping args -- do the input files & streams exist? */
1601
    for(i=0;i<nb_stream_maps;i++) {
1602
        int fi = stream_maps[i].file_index;
1603
        int si = stream_maps[i].stream_index;
1604 115329f1 Diego Biurrun
1605 bd073980 Brian Foley
        if (fi < 0 || fi > nb_input_files - 1 ||
1606
            si < 0 || si > file_table[fi].nb_streams - 1) {
1607
            fprintf(stderr,"Could not find input stream #%d.%d\n", fi, si);
1608 296df4e7 Ramiro Polla
            av_exit(1);
1609 bd073980 Brian Foley
        }
1610 b4a3389e Wolfram Gloger
        fi = stream_maps[i].sync_file_index;
1611
        si = stream_maps[i].sync_stream_index;
1612
        if (fi < 0 || fi > nb_input_files - 1 ||
1613
            si < 0 || si > file_table[fi].nb_streams - 1) {
1614
            fprintf(stderr,"Could not find sync stream #%d.%d\n", fi, si);
1615 296df4e7 Ramiro Polla
            av_exit(1);
1616 b4a3389e Wolfram Gloger
        }
1617 bd073980 Brian Foley
    }
1618 115329f1 Diego Biurrun
1619 85f07f22 Fabrice Bellard
    ost_table = av_mallocz(sizeof(AVOutputStream *) * nb_ostreams);
1620
    if (!ost_table)
1621
        goto fail;
1622
    for(i=0;i<nb_ostreams;i++) {
1623
        ost = av_mallocz(sizeof(AVOutputStream));
1624
        if (!ost)
1625
            goto fail;
1626
        ost_table[i] = ost;
1627
    }
1628 115329f1 Diego Biurrun
1629 85f07f22 Fabrice Bellard
    n = 0;
1630
    for(k=0;k<nb_output_files;k++) {
1631
        os = output_files[k];
1632
        for(i=0;i<os->nb_streams;i++) {
1633
            int found;
1634
            ost = ost_table[n++];
1635
            ost->file_index = k;
1636
            ost->index = i;
1637
            ost->st = os->streams[i];
1638
            if (nb_stream_maps > 0) {
1639 115329f1 Diego Biurrun
                ost->source_index = file_table[stream_maps[n-1].file_index].ist_index +
1640 85f07f22 Fabrice Bellard
                    stream_maps[n-1].stream_index;
1641 115329f1 Diego Biurrun
1642 bd073980 Brian Foley
                /* Sanity check that the stream types match */
1643 01f4895c Michael Niedermayer
                if (ist_table[ost->source_index]->st->codec->codec_type != ost->st->codec->codec_type) {
1644 150d5a25 Stefano Sabatini
                    int i= ost->file_index;
1645
                    dump_format(output_files[i], i, output_files[i]->filename, 1);
1646 bd073980 Brian Foley
                    fprintf(stderr, "Codec type mismatch for mapping #%d.%d -> #%d.%d\n",
1647
                        stream_maps[n-1].file_index, stream_maps[n-1].stream_index,
1648
                        ost->file_index, ost->index);
1649 296df4e7 Ramiro Polla
                    av_exit(1);
1650 bd073980 Brian Foley
                }
1651 115329f1 Diego Biurrun
1652 85f07f22 Fabrice Bellard
            } else {
1653 50e143c4 Nico Sabbi
                if(opt_programid) {
1654
                    found = 0;
1655
                    j = stream_index_from_inputs(input_files, nb_input_files, file_table, ist_table, ost->st->codec->codec_type, opt_programid);
1656
                    if(j != -1) {
1657
                        ost->source_index = j;
1658
                        found = 1;
1659
                    }
1660
                } else {
1661 a15bc651 Nico Sabbi
                    /* get corresponding input stream index : we select the first one with the right type */
1662
                    found = 0;
1663 85f07f22 Fabrice Bellard
                    for(j=0;j<nb_istreams;j++) {
1664
                        ist = ist_table[j];
1665 a15bc651 Nico Sabbi
                        if (ist->discard &&
1666
                            ist->st->codec->codec_type == ost->st->codec->codec_type) {
1667 85f07f22 Fabrice Bellard
                            ost->source_index = j;
1668
                            found = 1;
1669 a15bc651 Nico Sabbi
                            break;
1670 85f07f22 Fabrice Bellard
                        }
1671
                    }
1672 a15bc651 Nico Sabbi
                }
1673
1674
                if (!found) {
1675
                    if(! opt_programid) {
1676
                        /* try again and reuse existing stream */
1677
                        for(j=0;j<nb_istreams;j++) {
1678
                            ist = ist_table[j];
1679
                            if (ist->st->codec->codec_type == ost->st->codec->codec_type) {
1680
                                ost->source_index = j;
1681
                                found = 1;
1682
                            }
1683
                        }
1684 50e143c4 Nico Sabbi
                    }
1685 85f07f22 Fabrice Bellard
                    if (!found) {
1686 462cca10 Stefano Sabatini
                        int i= ost->file_index;
1687
                        dump_format(output_files[i], i, output_files[i]->filename, 1);
1688 85f07f22 Fabrice Bellard
                        fprintf(stderr, "Could not find input stream matching output stream #%d.%d\n",
1689
                                ost->file_index, ost->index);
1690 296df4e7 Ramiro Polla
                        av_exit(1);
1691 85f07f22 Fabrice Bellard
                    }
1692
                }
1693
            }
1694
            ist = ist_table[ost->source_index];
1695
            ist->discard = 0;
1696 b4a3389e Wolfram Gloger
            ost->sync_ist = (nb_stream_maps > 0) ?
1697
                ist_table[file_table[stream_maps[n-1].sync_file_index].ist_index +
1698
                         stream_maps[n-1].sync_stream_index] : ist;
1699 85f07f22 Fabrice Bellard
        }
1700
    }
1701
1702
    /* for each output stream, we compute the right encoding parameters */
1703
    for(i=0;i<nb_ostreams;i++) {
1704
        ost = ost_table[i];
1705 365515ac Michael Niedermayer
        os = output_files[ost->file_index];
1706 85f07f22 Fabrice Bellard
        ist = ist_table[ost->source_index];
1707
1708 01f4895c Michael Niedermayer
        codec = ost->st->codec;
1709
        icodec = ist->st->codec;
1710 85f07f22 Fabrice Bellard
1711 8e0d882b Aurelien Jacobs
        if (!ost->st->language[0])
1712
            av_strlcpy(ost->st->language, ist->st->language,
1713
                       sizeof(ost->st->language));
1714
1715 90c2295b Evgeniy Stepanov
        ost->st->disposition = ist->st->disposition;
1716
1717 1629626f Fabrice Bellard
        if (ost->st->stream_copy) {
1718
            /* if stream_copy is selected, no need to decode or encode */
1719
            codec->codec_id = icodec->codec_id;
1720
            codec->codec_type = icodec->codec_type;
1721 365515ac Michael Niedermayer
1722
            if(!codec->codec_tag){
1723
                if(   !os->oformat->codec_tag
1724
                   || av_codec_get_id (os->oformat->codec_tag, icodec->codec_tag) > 0
1725
                   || av_codec_get_tag(os->oformat->codec_tag, icodec->codec_id) <= 0)
1726
                    codec->codec_tag = icodec->codec_tag;
1727
            }
1728
1729 1629626f Fabrice Bellard
            codec->bit_rate = icodec->bit_rate;
1730 dffbfd06 Michael Niedermayer
            codec->extradata= icodec->extradata;
1731
            codec->extradata_size= icodec->extradata_size;
1732 4408e75e Michael Niedermayer
            if(av_q2d(icodec->time_base) > av_q2d(ist->st->time_base) && av_q2d(ist->st->time_base) < 1.0/1000)
1733 d29de719 Michael Niedermayer
                codec->time_base = icodec->time_base;
1734
            else
1735
                codec->time_base = ist->st->time_base;
1736 1629626f Fabrice Bellard
            switch(codec->codec_type) {
1737
            case CODEC_TYPE_AUDIO:
1738 d08e3e91 Ramiro Polla
                if(audio_volume != 256) {
1739
                    fprintf(stderr,"-acodec copy and -vol are incompatible (frames are not decoded)\n");
1740
                    av_exit(1);
1741
                }
1742 1629626f Fabrice Bellard
                codec->sample_rate = icodec->sample_rate;
1743
                codec->channels = icodec->channels;
1744 0a3b0447 Michael Niedermayer
                codec->frame_size = icodec->frame_size;
1745 c1344911 Michael Niedermayer
                codec->block_align= icodec->block_align;
1746 4efd6f58 Michael Niedermayer
                if(codec->block_align == 1 && codec->codec_id == CODEC_ID_MP3)
1747
                    codec->block_align= 0;
1748 bcbd328e Michael Niedermayer
                if(codec->codec_id == CODEC_ID_AC3)
1749
                    codec->block_align= 0;
1750 1629626f Fabrice Bellard
                break;
1751
            case CODEC_TYPE_VIDEO:
1752 8d74e55b Matthijs Douze
                if(using_vhook) {
1753
                    fprintf(stderr,"-vcodec copy and -vhook are incompatible (frames are not decoded)\n");
1754 296df4e7 Ramiro Polla
                    av_exit(1);
1755 8d74e55b Matthijs Douze
                }
1756 9df3437f Baptiste Coudurier
                codec->pix_fmt = icodec->pix_fmt;
1757 1629626f Fabrice Bellard
                codec->width = icodec->width;
1758
                codec->height = icodec->height;
1759 ff8cc24b Michael Niedermayer
                codec->has_b_frames = icodec->has_b_frames;
1760 1629626f Fabrice Bellard
                break;
1761 cf7fc795 Fabrice Bellard
            case CODEC_TYPE_SUBTITLE:
1762
                break;
1763 1629626f Fabrice Bellard
            default:
1764 0f4e8165 Ronald S. Bultje
                abort();
1765 1629626f Fabrice Bellard
            }
1766
        } else {
1767
            switch(codec->codec_type) {
1768
            case CODEC_TYPE_AUDIO:
1769 10e7fc7c Michael Niedermayer
                if (av_fifo_init(&ost->fifo, 1024))
1770 85f07f22 Fabrice Bellard
                    goto fail;
1771 a79db0f7 Peter Ross
                ost->reformat_pair = MAKE_SFMT_PAIR(SAMPLE_FMT_NONE,SAMPLE_FMT_NONE);
1772 2886f311 Andreas Öman
                ost->audio_resample = codec->sample_rate != icodec->sample_rate || audio_sync_method > 1;
1773
                icodec->request_channels = codec->channels;
1774 85f07f22 Fabrice Bellard
                ist->decoding_needed = 1;
1775
                ost->encoding_needed = 1;
1776 1629626f Fabrice Bellard
                break;
1777
            case CODEC_TYPE_VIDEO:
1778 c3f11d19 Luca Abeni
                ost->video_crop = ((frame_leftBand + frame_rightBand + frame_topBand + frame_bottomBand) != 0);
1779
                ost->video_pad = ((frame_padleft + frame_padright + frame_padtop + frame_padbottom) != 0);
1780
                ost->video_resample = ((codec->width != icodec->width -
1781
                                (frame_leftBand + frame_rightBand) +
1782
                                (frame_padleft + frame_padright)) ||
1783
                        (codec->height != icodec->height -
1784
                                (frame_topBand  + frame_bottomBand) +
1785 18a54b04 Luca Abeni
                                (frame_padtop + frame_padbottom)) ||
1786
                        (codec->pix_fmt != icodec->pix_fmt));
1787 c3f11d19 Luca Abeni
                if (ost->video_crop) {
1788 34b10a57 Dieter
                    ost->topBand = frame_topBand;
1789
                    ost->leftBand = frame_leftBand;
1790 c3f11d19 Luca Abeni
                }
1791
                if (ost->video_pad) {
1792 1ff93ffc Todd Kirby
                    ost->padtop = frame_padtop;
1793
                    ost->padleft = frame_padleft;
1794
                    ost->padbottom = frame_padbottom;
1795
                    ost->padright = frame_padright;
1796 c3f11d19 Luca Abeni
                    if (!ost->video_resample) {
1797
                        avcodec_get_frame_defaults(&ost->pict_tmp);
1798 9d58e0a9 Baptiste Coudurier
                        if(avpicture_alloc((AVPicture*)&ost->pict_tmp, codec->pix_fmt,
1799
                                         codec->width, codec->height))
1800 c3f11d19 Luca Abeni
                            goto fail;
1801
                    }
1802
                }
1803
                if (ost->video_resample) {
1804 2de28abb Michael Niedermayer
                    avcodec_get_frame_defaults(&ost->pict_tmp);
1805 9d58e0a9 Baptiste Coudurier
                    if(avpicture_alloc((AVPicture*)&ost->pict_tmp, codec->pix_fmt,
1806
                                         codec->width, codec->height)) {
1807 eddc482d Baptiste Coudurier
                        fprintf(stderr, "Cannot allocate temp picture, check pix fmt\n");
1808 296df4e7 Ramiro Polla
                        av_exit(1);
1809 eddc482d Baptiste Coudurier
                    }
1810 9de8e6ac Ronald S. Bultje
                    sws_flags = av_get_int(sws_opts, "sws_flags", NULL);
1811 18a54b04 Luca Abeni
                    ost->img_resample_ctx = sws_getContext(
1812
                            icodec->width - (frame_leftBand + frame_rightBand),
1813
                            icodec->height - (frame_topBand + frame_bottomBand),
1814
                            icodec->pix_fmt,
1815 07d0cdfc Luca Abeni
                            codec->width - (frame_padleft + frame_padright),
1816
                            codec->height - (frame_padtop + frame_padbottom),
1817 18a54b04 Luca Abeni
                            codec->pix_fmt,
1818
                            sws_flags, NULL, NULL, NULL);
1819 0b50ac8a Luca Abeni
                    if (ost->img_resample_ctx == NULL) {
1820
                        fprintf(stderr, "Cannot get resampling context\n");
1821 296df4e7 Ramiro Polla
                        av_exit(1);
1822 0b50ac8a Luca Abeni
                    }
1823 18a54b04 Luca Abeni
                    ost->resample_height = icodec->height - (frame_topBand + frame_bottomBand);
1824 85f07f22 Fabrice Bellard
                }
1825
                ost->encoding_needed = 1;
1826
                ist->decoding_needed = 1;
1827 1629626f Fabrice Bellard
                break;
1828 cf7fc795 Fabrice Bellard
            case CODEC_TYPE_SUBTITLE:
1829
                ost->encoding_needed = 1;
1830
                ist->decoding_needed = 1;
1831
                break;
1832 1629626f Fabrice Bellard
            default:
1833 0f4e8165 Ronald S. Bultje
                abort();
1834 cf7fc795 Fabrice Bellard
                break;
1835 85f07f22 Fabrice Bellard
            }
1836 1629626f Fabrice Bellard
            /* two pass mode */
1837 115329f1 Diego Biurrun
            if (ost->encoding_needed &&
1838 1629626f Fabrice Bellard
                (codec->flags & (CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2))) {
1839
                char logfilename[1024];
1840
                FILE *f;
1841
                int size;
1842
                char *logbuffer;
1843 115329f1 Diego Biurrun
1844
                snprintf(logfilename, sizeof(logfilename), "%s-%d.log",
1845
                         pass_logfilename ?
1846 1629626f Fabrice Bellard
                         pass_logfilename : DEFAULT_PASS_LOGFILENAME, i);
1847
                if (codec->flags & CODEC_FLAG_PASS1) {
1848
                    f = fopen(logfilename, "w");
1849
                    if (!f) {
1850
                        perror(logfilename);
1851 296df4e7 Ramiro Polla
                        av_exit(1);
1852 1629626f Fabrice Bellard
                    }
1853
                    ost->logfile = f;
1854
                } else {
1855
                    /* read the log file */
1856
                    f = fopen(logfilename, "r");
1857
                    if (!f) {
1858
                        perror(logfilename);
1859 296df4e7 Ramiro Polla
                        av_exit(1);
1860 1629626f Fabrice Bellard
                    }
1861
                    fseek(f, 0, SEEK_END);
1862
                    size = ftell(f);
1863
                    fseek(f, 0, SEEK_SET);
1864
                    logbuffer = av_malloc(size + 1);
1865
                    if (!logbuffer) {
1866
                        fprintf(stderr, "Could not allocate log buffer\n");
1867 296df4e7 Ramiro Polla
                        av_exit(1);
1868 1629626f Fabrice Bellard
                    }
1869 4776fa92 Gael Chardon
                    size = fread(logbuffer, 1, size, f);
1870 1629626f Fabrice Bellard
                    fclose(f);
1871
                    logbuffer[size] = '\0';
1872
                    codec->stats_in = logbuffer;
1873 5abdb4b1 Fabrice Bellard
                }
1874
            }
1875
        }
1876 8a6cb114 Michael Niedermayer
        if(codec->codec_type == CODEC_TYPE_VIDEO){
1877
            int size= codec->width * codec->height;
1878
            bit_buffer_size= FFMAX(bit_buffer_size, 4*size);
1879
        }
1880 85f07f22 Fabrice Bellard
    }
1881
1882 8a6cb114 Michael Niedermayer
    if (!bit_buffer)
1883
        bit_buffer = av_malloc(bit_buffer_size);
1884
    if (!bit_buffer)
1885
        goto fail;
1886
1887 1629626f Fabrice Bellard
    /* dump the file output parameters - cannot be done before in case
1888
       of stream copy */
1889
    for(i=0;i<nb_output_files;i++) {
1890
        dump_format(output_files[i], i, output_files[i]->filename, 1);
1891
    }
1892
1893
    /* dump the stream mapping */
1894 d8019eb5 Allen Day
    if (verbose >= 0) {
1895
        fprintf(stderr, "Stream mapping:\n");
1896
        for(i=0;i<nb_ostreams;i++) {
1897
            ost = ost_table[i];
1898 b4a3389e Wolfram Gloger
            fprintf(stderr, "  Stream #%d.%d -> #%d.%d",
1899 d8019eb5 Allen Day
                    ist_table[ost->source_index]->file_index,
1900
                    ist_table[ost->source_index]->index,
1901 115329f1 Diego Biurrun
                    ost->file_index,
1902 d8019eb5 Allen Day
                    ost->index);
1903 b4a3389e Wolfram Gloger
            if (ost->sync_ist != ist_table[ost->source_index])
1904
                fprintf(stderr, " [sync #%d.%d]",
1905
                        ost->sync_ist->file_index,
1906
                        ost->sync_ist->index);
1907
            fprintf(stderr, "\n");
1908 d8019eb5 Allen Day
        }
1909 1629626f Fabrice Bellard
    }
1910
1911 85f07f22 Fabrice Bellard
    /* open each encoder */
1912
    for(i=0;i<nb_ostreams;i++) {
1913
        ost = ost_table[i];
1914
        if (ost->encoding_needed) {
1915
            AVCodec *codec;
1916 01f4895c Michael Niedermayer
            codec = avcodec_find_encoder(ost->st->codec->codec_id);
1917 85f07f22 Fabrice Bellard
            if (!codec) {
1918 115329f1 Diego Biurrun
                fprintf(stderr, "Unsupported codec for output stream #%d.%d\n",
1919 85f07f22 Fabrice Bellard
                        ost->file_index, ost->index);
1920 296df4e7 Ramiro Polla
                av_exit(1);
1921 85f07f22 Fabrice Bellard
            }
1922 01f4895c Michael Niedermayer
            if (avcodec_open(ost->st->codec, codec) < 0) {
1923 115329f1 Diego Biurrun
                fprintf(stderr, "Error while opening codec for output stream #%d.%d - maybe incorrect parameters such as bit_rate, rate, width or height\n",
1924 85f07f22 Fabrice Bellard
                        ost->file_index, ost->index);
1925 296df4e7 Ramiro Polla
                av_exit(1);
1926 85f07f22 Fabrice Bellard
            }
1927 01f4895c Michael Niedermayer
            extra_size += ost->st->codec->extradata_size;
1928 85f07f22 Fabrice Bellard
        }
1929
    }
1930
1931
    /* open each decoder */
1932
    for(i=0;i<nb_istreams;i++) {
1933
        ist = ist_table[i];
1934
        if (ist->decoding_needed) {
1935
            AVCodec *codec;
1936 01f4895c Michael Niedermayer
            codec = avcodec_find_decoder(ist->st->codec->codec_id);
1937 85f07f22 Fabrice Bellard
            if (!codec) {
1938 115329f1 Diego Biurrun
                fprintf(stderr, "Unsupported codec (id=%d) for input stream #%d.%d\n",
1939 01f4895c Michael Niedermayer
                        ist->st->codec->codec_id, ist->file_index, ist->index);
1940 296df4e7 Ramiro Polla
                av_exit(1);
1941 85f07f22 Fabrice Bellard
            }
1942 01f4895c Michael Niedermayer
            if (avcodec_open(ist->st->codec, codec) < 0) {
1943 115329f1 Diego Biurrun
                fprintf(stderr, "Error while opening codec for input stream #%d.%d\n",
1944 85f07f22 Fabrice Bellard
                        ist->file_index, ist->index);
1945 296df4e7 Ramiro Polla
                av_exit(1);
1946 85f07f22 Fabrice Bellard
            }
1947 01f4895c Michael Niedermayer
            //if (ist->st->codec->codec_type == CODEC_TYPE_VIDEO)
1948
            //    ist->st->codec->flags |= CODEC_FLAG_REPEAT_FIELD;
1949 85f07f22 Fabrice Bellard
        }
1950
    }
1951
1952
    /* init pts */
1953
    for(i=0;i<nb_istreams;i++) {
1954
        ist = ist_table[i];
1955 bb270c08 Diego Biurrun
        is = input_files[ist->file_index];
1956 e7d0374f Roman Shaposhnik
        ist->pts = 0;
1957 48291040 Michael Niedermayer
        ist->next_pts = AV_NOPTS_VALUE;
1958 ff4905a5 Michael Niedermayer
        ist->is_start = 1;
1959 85f07f22 Fabrice Bellard
    }
1960 bd1b79a1 Michael Niedermayer
1961 0a38bafd Patrice Bensoussan
    /* set meta data information from input file if required */
1962
    for (i=0;i<nb_meta_data_maps;i++) {
1963
        AVFormatContext *out_file;
1964
        AVFormatContext *in_file;
1965
1966
        int out_file_index = meta_data_maps[i].out_file;
1967
        int in_file_index = meta_data_maps[i].in_file;
1968 9d58e0a9 Baptiste Coudurier
        if (out_file_index < 0 || out_file_index >= nb_output_files) {
1969 0a38bafd Patrice Bensoussan
            fprintf(stderr, "Invalid output file index %d map_meta_data(%d,%d)\n", out_file_index, out_file_index, in_file_index);
1970 8fa36ae0 François Revol
            ret = AVERROR(EINVAL);
1971 0a38bafd Patrice Bensoussan
            goto fail;
1972
        }
1973 9d58e0a9 Baptiste Coudurier
        if (in_file_index < 0 || in_file_index >= nb_input_files) {
1974 0a38bafd Patrice Bensoussan
            fprintf(stderr, "Invalid input file index %d map_meta_data(%d,%d)\n", in_file_index, out_file_index, in_file_index);
1975 8fa36ae0 François Revol
            ret = AVERROR(EINVAL);
1976 0a38bafd Patrice Bensoussan
            goto fail;
1977 115329f1 Diego Biurrun
        }
1978
1979 0a38bafd Patrice Bensoussan
        out_file = output_files[out_file_index];
1980
        in_file = input_files[in_file_index];
1981
1982
        strcpy(out_file->title, in_file->title);
1983
        strcpy(out_file->author, in_file->author);
1984
        strcpy(out_file->copyright, in_file->copyright);
1985
        strcpy(out_file->comment, in_file->comment);
1986
        strcpy(out_file->album, in_file->album);
1987
        out_file->year = in_file->year;
1988
        out_file->track = in_file->track;
1989
        strcpy(out_file->genre, in_file->genre);
1990
    }
1991 115329f1 Diego Biurrun
1992 85f07f22 Fabrice Bellard
    /* open files and write file headers */
1993
    for(i=0;i<nb_output_files;i++) {
1994
        os = output_files[i];
1995 79fdaa4c Fabrice Bellard
        if (av_write_header(os) < 0) {
1996 65bf3c53 Michael Niedermayer
            fprintf(stderr, "Could not write header for output file #%d (incorrect codec parameters ?)\n", i);
1997 8fa36ae0 François Revol
            ret = AVERROR(EINVAL);
1998 a38469e1 Fabrice Bellard
            goto fail;
1999
        }
2000 6d1ba1ac Luca Abeni
        if (strcmp(output_files[i]->oformat->name, "rtp")) {
2001
            want_sdp = 0;
2002
        }
2003
    }
2004
    if (want_sdp) {
2005
        print_sdp(output_files, nb_output_files);
2006 85f07f22 Fabrice Bellard
    }
2007
2008 9d58e0a9 Baptiste Coudurier
    if (!using_stdin && verbose >= 0) {
2009 d9a916e2 Charles Yates
        fprintf(stderr, "Press [q] to stop encoding\n");
2010 b51469a0 Leon van Stuivenberg
        url_set_interrupt_cb(decode_interrupt_cb);
2011
    }
2012 a38469e1 Fabrice Bellard
    term_init();
2013
2014 cb09b2ed Philip Gladstone
    key = -1;
2015 7fc98937 Limin Wang
    timer_start = av_gettime();
2016 51bd4565 Philip Gladstone
2017 d9a916e2 Charles Yates
    for(; received_sigterm == 0;) {
2018 85f07f22 Fabrice Bellard
        int file_index, ist_index;
2019
        AVPacket pkt;
2020 a9aeda81 Patrice Bensoussan
        double ipts_min;
2021
        double opts_min;
2022 23ffe323 Michael Niedermayer
2023 85f07f22 Fabrice Bellard
    redo:
2024 a9aeda81 Patrice Bensoussan
        ipts_min= 1e100;
2025
        opts_min= 1e100;
2026 a38469e1 Fabrice Bellard
        /* if 'q' pressed, exits */
2027 d9a916e2 Charles Yates
        if (!using_stdin) {
2028 b51469a0 Leon van Stuivenberg
            if (q_pressed)
2029
                break;
2030 cb09b2ed Philip Gladstone
            /* read_key() returns 0 on EOF */
2031
            key = read_key();
2032
            if (key == 'q')
2033
                break;
2034
        }
2035 a38469e1 Fabrice Bellard
2036 ec5517d5 Fabrice Bellard
        /* select the stream that we must read now by looking at the
2037
           smallest output pts */
2038 85f07f22 Fabrice Bellard
        file_index = -1;
2039 ec5517d5 Fabrice Bellard
        for(i=0;i<nb_ostreams;i++) {
2040 23ffe323 Michael Niedermayer
            double ipts, opts;
2041 ec5517d5 Fabrice Bellard
            ost = ost_table[i];
2042
            os = output_files[ost->file_index];
2043
            ist = ist_table[ost->source_index];
2044 01f4895c Michael Niedermayer
            if(ost->st->codec->codec_type == CODEC_TYPE_VIDEO)
2045
                opts = ost->sync_opts * av_q2d(ost->st->codec->time_base);
2046 23ffe323 Michael Niedermayer
            else
2047 c0df9d75 Michael Niedermayer
                opts = ost->st->pts.val * av_q2d(ost->st->time_base);
2048 23ffe323 Michael Niedermayer
            ipts = (double)ist->pts;
2049
            if (!file_table[ist->file_index].eof_reached){
2050
                if(ipts < ipts_min) {
2051
                    ipts_min = ipts;
2052
                    if(input_sync ) file_index = ist->file_index;
2053
                }
2054
                if(opts < opts_min) {
2055
                    opts_min = opts;
2056
                    if(!input_sync) file_index = ist->file_index;
2057
                }
2058 85f07f22 Fabrice Bellard
            }
2059 01f4895c Michael Niedermayer
            if(ost->frame_number >= max_frames[ost->st->codec->codec_type]){
2060 7ca60994 Michael Niedermayer
                file_index= -1;
2061
                break;
2062
            }
2063 85f07f22 Fabrice Bellard
        }
2064
        /* if none, if is finished */
2065 51bd4565 Philip Gladstone
        if (file_index < 0) {
2066 85f07f22 Fabrice Bellard
            break;
2067 ec5517d5 Fabrice Bellard
        }
2068
2069 85f07f22 Fabrice Bellard
        /* finish if recording time exhausted */
2070 fc7ad2af Stefano Sabatini
        if (opts_min >= (recording_time / 1000000.0))
2071 85f07f22 Fabrice Bellard
            break;
2072 ec5517d5 Fabrice Bellard
2073 b6e16b86 Calcium
        /* finish if limit size exhausted */
2074 899681cd Björn Axelsson
        if (limit_filesize != 0 && limit_filesize < url_ftell(output_files[0]->pb))
2075 b6e16b86 Calcium
            break;
2076
2077 254abc2e Fabrice Bellard
        /* read a frame from it and output it in the fifo */
2078 85f07f22 Fabrice Bellard
        is = input_files[file_index];
2079 254abc2e Fabrice Bellard
        if (av_read_frame(is, &pkt) < 0) {
2080 85f07f22 Fabrice Bellard
            file_table[file_index].eof_reached = 1;
2081 d24ce947 Alex Beregszaszi
            if (opt_shortest)
2082
                break;
2083
            else
2084
                continue;
2085 85f07f22 Fabrice Bellard
        }
2086 303e50e6 Michael Niedermayer
2087 254abc2e Fabrice Bellard
        if (do_pkt_dump) {
2088 750f0e1f Panagiotis Issaris
            av_pkt_dump_log(NULL, AV_LOG_DEBUG, &pkt, do_hex_dump);
2089 817b23ff Fabrice Bellard
        }
2090 79fdaa4c Fabrice Bellard
        /* the following test is needed in case new streams appear
2091
           dynamically in stream : we ignore them */
2092
        if (pkt.stream_index >= file_table[file_index].nb_streams)
2093 bf5af568 Fabrice Bellard
            goto discard_packet;
2094 85f07f22 Fabrice Bellard
        ist_index = file_table[file_index].ist_index + pkt.stream_index;
2095
        ist = ist_table[ist_index];
2096 bf5af568 Fabrice Bellard
        if (ist->discard)
2097
            goto discard_packet;
2098 85f07f22 Fabrice Bellard
2099 fec401f7 Michael Niedermayer
        if (pkt.dts != AV_NOPTS_VALUE)
2100
            pkt.dts += av_rescale_q(input_files_ts_offset[ist->file_index], AV_TIME_BASE_Q, ist->st->time_base);
2101
        if (pkt.pts != AV_NOPTS_VALUE)
2102
            pkt.pts += av_rescale_q(input_files_ts_offset[ist->file_index], AV_TIME_BASE_Q, ist->st->time_base);
2103
2104 8833f375 Michael Niedermayer
        if(input_files_ts_scale[file_index][pkt.stream_index]){
2105
            if(pkt.pts != AV_NOPTS_VALUE)
2106
                pkt.pts *= input_files_ts_scale[file_index][pkt.stream_index];
2107
            if(pkt.dts != AV_NOPTS_VALUE)
2108
                pkt.dts *= input_files_ts_scale[file_index][pkt.stream_index];
2109
        }
2110
2111 949b1a13 Steve L'Homme
//        fprintf(stderr, "next:%"PRId64" dts:%"PRId64" off:%"PRId64" %d\n", ist->next_pts, pkt.dts, input_files_ts_offset[ist->file_index], ist->st->codec->codec_type);
2112 fdb86eb1 Michael Niedermayer
        if (pkt.dts != AV_NOPTS_VALUE && ist->next_pts != AV_NOPTS_VALUE) {
2113 81d6d520 Michael Niedermayer
            int64_t pkt_dts= av_rescale_q(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q);
2114
            int64_t delta= pkt_dts - ist->next_pts;
2115
            if((FFABS(delta) > 1LL*dts_delta_threshold*AV_TIME_BASE || pkt_dts+1<ist->pts)&& !copy_ts){
2116 72bd8100 Michael Niedermayer
                input_files_ts_offset[ist->file_index]-= delta;
2117
                if (verbose > 2)
2118 4733abcb Måns Rullgård
                    fprintf(stderr, "timestamp discontinuity %"PRId64", new offset= %"PRId64"\n", delta, input_files_ts_offset[ist->file_index]);
2119 fec401f7 Michael Niedermayer
                pkt.dts-= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
2120
                if(pkt.pts != AV_NOPTS_VALUE)
2121
                    pkt.pts-= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
2122 72bd8100 Michael Niedermayer
            }
2123
        }
2124
2125 8831db5c Michael Niedermayer
        //fprintf(stderr,"read #%d.%d size=%d\n", ist->file_index, ist->index, pkt.size);
2126 a700a6ae Fabrice Bellard
        if (output_packet(ist, ist_index, ost_table, nb_ostreams, &pkt) < 0) {
2127 d8019eb5 Allen Day
2128
            if (verbose >= 0)
2129
                fprintf(stderr, "Error while decoding stream #%d.%d\n",
2130
                        ist->file_index, ist->index);
2131
2132 a700a6ae Fabrice Bellard
            av_free_packet(&pkt);
2133
            goto redo;
2134 fe08925f Michael Niedermayer
        }
2135 cf7fc795 Fabrice Bellard
2136 bf5af568 Fabrice Bellard
    discard_packet:
2137 85f07f22 Fabrice Bellard
        av_free_packet(&pkt);
2138 115329f1 Diego Biurrun
2139 ec5517d5 Fabrice Bellard
        /* dump report by using the output first video and audio streams */
2140
        print_report(output_files, ost_table, nb_ostreams, 0);
2141 85f07f22 Fabrice Bellard
    }
2142 a700a6ae Fabrice Bellard
2143
    /* at the end of stream, we must flush the decoder buffers */
2144
    for(i=0;i<nb_istreams;i++) {
2145
        ist = ist_table[i];
2146
        if (ist->decoding_needed) {
2147
            output_packet(ist, i, ost_table, nb_ostreams, NULL);
2148
        }
2149
    }
2150
2151 a38469e1 Fabrice Bellard
    term_exit();
2152 85f07f22 Fabrice Bellard
2153 c4e37247 Michael Niedermayer
    /* write the trailer if needed and close file */
2154
    for(i=0;i<nb_output_files;i++) {
2155
        os = output_files[i];
2156
        av_write_trailer(os);
2157
    }
2158
2159 37f5cd5a Michael Niedermayer
    /* dump report by using the first video and audio streams */
2160
    print_report(output_files, ost_table, nb_ostreams, 1);
2161
2162 85f07f22 Fabrice Bellard
    /* close each encoder */
2163
    for(i=0;i<nb_ostreams;i++) {
2164
        ost = ost_table[i];
2165
        if (ost->encoding_needed) {
2166 01f4895c Michael Niedermayer
            av_freep(&ost->st->codec->stats_in);
2167
            avcodec_close(ost->st->codec);
2168 85f07f22 Fabrice Bellard
        }
2169
    }
2170 115329f1 Diego Biurrun
2171 85f07f22 Fabrice Bellard
    /* close each decoder */
2172
    for(i=0;i<nb_istreams;i++) {
2173
        ist = ist_table[i];
2174
        if (ist->decoding_needed) {
2175 01f4895c Michael Niedermayer
            avcodec_close(ist->st->codec);
2176 85f07f22 Fabrice Bellard
        }
2177
    }
2178
2179
    /* finished ! */
2180 115329f1 Diego Biurrun
2181 85f07f22 Fabrice Bellard
    ret = 0;
2182
 fail1:
2183 83b07470 Michael Niedermayer
    av_freep(&bit_buffer);
2184 0f1578af Fabrice Bellard
    av_free(file_table);
2185 bdc4796f Fabrice Bellard
2186 85f07f22 Fabrice Bellard
    if (ist_table) {
2187
        for(i=0;i<nb_istreams;i++) {
2188
            ist = ist_table[i];
2189 0f1578af Fabrice Bellard
            av_free(ist);
2190 85f07f22 Fabrice Bellard
        }
2191 0f1578af Fabrice Bellard
        av_free(ist_table);
2192 85f07f22 Fabrice Bellard
    }
2193
    if (ost_table) {
2194
        for(i=0;i<nb_ostreams;i++) {
2195
            ost = ost_table[i];
2196
            if (ost) {
2197 5abdb4b1 Fabrice Bellard
                if (ost->logfile) {
2198
                    fclose(ost->logfile);
2199
                    ost->logfile = NULL;
2200
                }
2201 f5a478f6 Roman Shaposhnik
                av_fifo_free(&ost->fifo); /* works even if fifo is not
2202
                                             initialized but set to zero */
2203 0f1578af Fabrice Bellard
                av_free(ost->pict_tmp.data[0]);
2204 85f07f22 Fabrice Bellard
                if (ost->video_resample)
2205 18a54b04 Luca Abeni
                    sws_freeContext(ost->img_resample_ctx);
2206 8e4270c5 Andreas Öman
                if (ost->resample)
2207 85f07f22 Fabrice Bellard
                    audio_resample_close(ost->resample);
2208 a79db0f7 Peter Ross
                if (ost->reformat_ctx)
2209
                    av_audio_convert_free(ost->reformat_ctx);
2210 0f1578af Fabrice Bellard
                av_free(ost);
2211 85f07f22 Fabrice Bellard
            }
2212
        }
2213 0f1578af Fabrice Bellard
        av_free(ost_table);
2214 85f07f22 Fabrice Bellard
    }
2215
    return ret;
2216
 fail:
2217 8fa36ae0 François Revol
    ret = AVERROR(ENOMEM);
2218 85f07f22 Fabrice Bellard
    goto fail1;
2219
}
2220
2221
#if 0
2222
int file_read(const char *filename)
2223
{
2224
    URLContext *h;
2225
    unsigned char buffer[1024];
2226
    int len, i;
2227

2228
    if (url_open(&h, filename, O_RDONLY) < 0) {
2229
        printf("could not open '%s'\n", filename);
2230
        return -1;
2231
    }
2232
    for(;;) {
2233
        len = url_read(h, buffer, sizeof(buffer));
2234
        if (len <= 0)
2235
            break;
2236
        for(i=0;i<len;i++) putchar(buffer[i]);
2237
    }
2238
    url_close(h);
2239
    return 0;
2240
}
2241
#endif
2242
2243 b29f97d1 Zdenek Kabelac
static void opt_format(const char *arg)
2244 85f07f22 Fabrice Bellard
{
2245 817b23ff Fabrice Bellard
    /* compatibility stuff for pgmyuv */
2246
    if (!strcmp(arg, "pgmyuv")) {
2247 5b6d5596 Michael Niedermayer
        pgmyuv_compatibility_hack=1;
2248 9286699a Michael Niedermayer
//        opt_image_format(arg);
2249 5b6d5596 Michael Niedermayer
        arg = "image2";
2250 17ceb4f9 Baptiste Coudurier
        fprintf(stderr, "pgmyuv format is deprecated, use image2\n");
2251 817b23ff Fabrice Bellard
    }
2252
2253 79fdaa4c Fabrice Bellard
    file_iformat = av_find_input_format(arg);
2254
    file_oformat = guess_format(arg, NULL, NULL);
2255
    if (!file_iformat && !file_oformat) {
2256
        fprintf(stderr, "Unknown input or output format: %s\n", arg);
2257 296df4e7 Ramiro Polla
        av_exit(1);
2258 85f07f22 Fabrice Bellard
    }
2259
}
2260
2261 3b855466 Diego Biurrun
static int opt_default(const char *opt, const char *arg){
2262
    int type;
2263
    const AVOption *o= NULL;
2264
    int opt_types[]={AV_OPT_FLAG_VIDEO_PARAM, AV_OPT_FLAG_AUDIO_PARAM, 0, AV_OPT_FLAG_SUBTITLE_PARAM, 0};
2265
2266
    for(type=0; type<CODEC_TYPE_NB; type++){
2267
        const AVOption *o2 = av_find_opt(avctx_opts[0], opt, NULL, opt_types[type], opt_types[type]);
2268
        if(o2)
2269 8dbee653 Michael Niedermayer
            o = av_set_string2(avctx_opts[type], opt, arg, 1);
2270 3b855466 Diego Biurrun
    }
2271
    if(!o)
2272 8dbee653 Michael Niedermayer
        o = av_set_string2(avformat_opts, opt, arg, 1);
2273 3b855466 Diego Biurrun
    if(!o)
2274 8dbee653 Michael Niedermayer
        o = av_set_string2(sws_opts, opt, arg, 1);
2275 3b855466 Diego Biurrun
    if(!o){
2276
        if(opt[0] == 'a')
2277 8dbee653 Michael Niedermayer
            o = av_set_string2(avctx_opts[CODEC_TYPE_AUDIO], opt+1, arg, 1);
2278 3b855466 Diego Biurrun
        else if(opt[0] == 'v')
2279 8dbee653 Michael Niedermayer
            o = av_set_string2(avctx_opts[CODEC_TYPE_VIDEO], opt+1, arg, 1);
2280 3b855466 Diego Biurrun
        else if(opt[0] == 's')
2281 8dbee653 Michael Niedermayer
            o = av_set_string2(avctx_opts[CODEC_TYPE_SUBTITLE], opt+1, arg, 1);
2282 3b855466 Diego Biurrun
    }
2283
    if(!o)
2284
        return -1;
2285
2286
//    av_log(NULL, AV_LOG_ERROR, "%s:%s: %f 0x%0X\n", opt, arg, av_get_double(avctx_opts, opt, NULL), (int)av_get_int(avctx_opts, opt, NULL));
2287
2288 e16190fa Diego Biurrun
    //FIXME we should always use avctx_opts, ... for storing options so there will not be any need to keep track of what i set over this
2289 3b855466 Diego Biurrun
    opt_names= av_realloc(opt_names, sizeof(void*)*(opt_name_count+1));
2290
    opt_names[opt_name_count++]= o->name;
2291
2292 6dfafe10 Baptiste Coudurier
    if(avctx_opts[0]->debug || avformat_opts->debug)
2293 a309073b Måns Rullgård
        av_log_set_level(AV_LOG_DEBUG);
2294 3b855466 Diego Biurrun
    return 0;
2295
}
2296
2297 464a631c Morten Hustveit
static void opt_video_rc_override_string(const char *arg)
2298 ac2830ec Michael Niedermayer
{
2299
    video_rc_override_string = arg;
2300
}
2301
2302 c48da33c Stefano Sabatini
static int opt_me_threshold(const char *opt, const char *arg)
2303 f4f3223f Michael Niedermayer
{
2304 c48da33c Stefano Sabatini
    me_threshold = parse_number_or_die(opt, arg, OPT_INT64, INT_MIN, INT_MAX);
2305
    return 0;
2306 f4f3223f Michael Niedermayer
}
2307
2308 c48da33c Stefano Sabatini
static int opt_verbose(const char *opt, const char *arg)
2309 f068206e Bill Eldridge
{
2310 46eab093 Michael Niedermayer
    verbose = parse_number_or_die(opt, arg, OPT_INT64, -10, 10);
2311 b3574faa Stefano Sabatini
    av_log_set_level(verbose);
2312 c48da33c Stefano Sabatini
    return 0;
2313 f068206e Bill Eldridge
}
2314
2315 b29f97d1 Zdenek Kabelac
static void opt_frame_rate(const char *arg)
2316 85f07f22 Fabrice Bellard
{
2317 b33ece16 Stefano Sabatini
    if (av_parse_video_frame_rate(&frame_rate, arg) < 0) {
2318 445f1b83 Roman Shaposhnik
        fprintf(stderr, "Incorrect frame rate\n");
2319 296df4e7 Ramiro Polla
        av_exit(1);
2320 445f1b83 Roman Shaposhnik
    }
2321 85f07f22 Fabrice Bellard
}
2322
2323 ebde2a2c Morten Hustveit
static int opt_bitrate(const char *opt, const char *arg)
2324 1b1656c6 Ramiro Polla
{
2325
    int codec_type = opt[0]=='a' ? CODEC_TYPE_AUDIO : CODEC_TYPE_VIDEO;
2326
2327
    opt_default(opt, arg);
2328
2329
    if (av_get_int(avctx_opts[codec_type], "b", NULL) < 1000)
2330
        fprintf(stderr, "WARNING: The bitrate parameter is set too low. It takes bits/s as argument, not kbits/s\n");
2331 ebde2a2c Morten Hustveit
2332
    return 0;
2333 1b1656c6 Ramiro Polla
}
2334
2335 b29f97d1 Zdenek Kabelac
static void opt_frame_crop_top(const char *arg)
2336 ab6d194a Michael Niedermayer
{
2337 115329f1 Diego Biurrun
    frame_topBand = atoi(arg);
2338 ab6d194a Michael Niedermayer
    if (frame_topBand < 0) {
2339
        fprintf(stderr, "Incorrect top crop size\n");
2340 296df4e7 Ramiro Polla
        av_exit(1);
2341 ab6d194a Michael Niedermayer
    }
2342
    if ((frame_topBand % 2) != 0) {
2343
        fprintf(stderr, "Top crop size must be a multiple of 2\n");
2344 296df4e7 Ramiro Polla
        av_exit(1);
2345 ab6d194a Michael Niedermayer
    }
2346
    if ((frame_topBand) >= frame_height){
2347 bb270c08 Diego Biurrun
        fprintf(stderr, "Vertical crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
2348 296df4e7 Ramiro Polla
        av_exit(1);
2349 ab6d194a Michael Niedermayer
    }
2350
    frame_height -= frame_topBand;
2351
}
2352
2353 b29f97d1 Zdenek Kabelac
static void opt_frame_crop_bottom(const char *arg)
2354 ab6d194a Michael Niedermayer
{
2355
    frame_bottomBand = atoi(arg);
2356
    if (frame_bottomBand < 0) {
2357
        fprintf(stderr, "Incorrect bottom crop size\n");
2358 296df4e7 Ramiro Polla
        av_exit(1);
2359 ab6d194a Michael Niedermayer
    }
2360
    if ((frame_bottomBand % 2) != 0) {
2361
        fprintf(stderr, "Bottom crop size must be a multiple of 2\n");
2362 296df4e7 Ramiro Polla
        av_exit(1);
2363 ab6d194a Michael Niedermayer
    }
2364
    if ((frame_bottomBand) >= frame_height){
2365 bb270c08 Diego Biurrun
        fprintf(stderr, "Vertical crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
2366 296df4e7 Ramiro Polla
        av_exit(1);
2367 ab6d194a Michael Niedermayer
    }
2368
    frame_height -= frame_bottomBand;
2369
}
2370
2371 b29f97d1 Zdenek Kabelac
static void opt_frame_crop_left(const char *arg)
2372 ab6d194a Michael Niedermayer
{
2373
    frame_leftBand = atoi(arg);
2374
    if (frame_leftBand < 0) {
2375
        fprintf(stderr, "Incorrect left crop size\n");
2376 296df4e7 Ramiro Polla
        av_exit(1);
2377 ab6d194a Michael Niedermayer
    }
2378
    if ((frame_leftBand % 2) != 0) {
2379
        fprintf(stderr, "Left crop size must be a multiple of 2\n");
2380 296df4e7 Ramiro Polla
        av_exit(1);
2381 ab6d194a Michael Niedermayer
    }
2382
    if ((frame_leftBand) >= frame_width){
2383 bb270c08 Diego Biurrun
        fprintf(stderr, "Horizontal crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
2384 296df4e7 Ramiro Polla
        av_exit(1);
2385 ab6d194a Michael Niedermayer
    }
2386
    frame_width -= frame_leftBand;
2387
}
2388
2389 b29f97d1 Zdenek Kabelac
static void opt_frame_crop_right(const char *arg)
2390 ab6d194a Michael Niedermayer
{
2391
    frame_rightBand = atoi(arg);
2392
    if (frame_rightBand < 0) {
2393
        fprintf(stderr, "Incorrect right crop size\n");
2394 296df4e7 Ramiro Polla
        av_exit(1);
2395 ab6d194a Michael Niedermayer
    }
2396
    if ((frame_rightBand % 2) != 0) {
2397
        fprintf(stderr, "Right crop size must be a multiple of 2\n");
2398 296df4e7 Ramiro Polla
        av_exit(1);
2399 ab6d194a Michael Niedermayer
    }
2400
    if ((frame_rightBand) >= frame_width){
2401 bb270c08 Diego Biurrun
        fprintf(stderr, "Horizontal crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
2402 296df4e7 Ramiro Polla
        av_exit(1);
2403 ab6d194a Michael Niedermayer
    }
2404
    frame_width -= frame_rightBand;
2405
}
2406
2407 b29f97d1 Zdenek Kabelac
static void opt_frame_size(const char *arg)
2408 85f07f22 Fabrice Bellard
{
2409 b33ece16 Stefano Sabatini
    if (av_parse_video_frame_size(&frame_width, &frame_height, arg) < 0) {
2410 85f07f22 Fabrice Bellard
        fprintf(stderr, "Incorrect frame size\n");
2411 296df4e7 Ramiro Polla
        av_exit(1);
2412 85f07f22 Fabrice Bellard
    }
2413
    if ((frame_width % 2) != 0 || (frame_height % 2) != 0) {
2414
        fprintf(stderr, "Frame size must be a multiple of 2\n");
2415 296df4e7 Ramiro Polla
        av_exit(1);
2416 85f07f22 Fabrice Bellard
    }
2417
}
2418
2419 1ff93ffc Todd Kirby
2420
#define SCALEBITS 10
2421
#define ONE_HALF  (1 << (SCALEBITS - 1))
2422 bb270c08 Diego Biurrun
#define FIX(x)    ((int) ((x) * (1<<SCALEBITS) + 0.5))
2423 1ff93ffc Todd Kirby
2424
#define RGB_TO_Y(r, g, b) \
2425
((FIX(0.29900) * (r) + FIX(0.58700) * (g) + \
2426
  FIX(0.11400) * (b) + ONE_HALF) >> SCALEBITS)
2427
2428
#define RGB_TO_U(r1, g1, b1, shift)\
2429
(((- FIX(0.16874) * r1 - FIX(0.33126) * g1 +         \
2430
     FIX(0.50000) * b1 + (ONE_HALF << shift) - 1) >> (SCALEBITS + shift)) + 128)
2431
2432
#define RGB_TO_V(r1, g1, b1, shift)\
2433
(((FIX(0.50000) * r1 - FIX(0.41869) * g1 -           \
2434
   FIX(0.08131) * b1 + (ONE_HALF << shift) - 1) >> (SCALEBITS + shift)) + 128)
2435
2436
static void opt_pad_color(const char *arg) {
2437
    /* Input is expected to be six hex digits similar to
2438
       how colors are expressed in html tags (but without the #) */
2439
    int rgb = strtol(arg, NULL, 16);
2440
    int r,g,b;
2441 115329f1 Diego Biurrun
2442
    r = (rgb >> 16);
2443 1ff93ffc Todd Kirby
    g = ((rgb >> 8) & 255);
2444
    b = (rgb & 255);
2445
2446
    padcolor[0] = RGB_TO_Y(r,g,b);
2447
    padcolor[1] = RGB_TO_U(r,g,b,0);
2448
    padcolor[2] = RGB_TO_V(r,g,b,0);
2449
}
2450
2451
static void opt_frame_pad_top(const char *arg)
2452
{
2453 115329f1 Diego Biurrun
    frame_padtop = atoi(arg);
2454 1ff93ffc Todd Kirby
    if (frame_padtop < 0) {
2455
        fprintf(stderr, "Incorrect top pad size\n");
2456 296df4e7 Ramiro Polla
        av_exit(1);
2457 1ff93ffc Todd Kirby
    }
2458
    if ((frame_padtop % 2) != 0) {
2459
        fprintf(stderr, "Top pad size must be a multiple of 2\n");
2460 296df4e7 Ramiro Polla
        av_exit(1);
2461 1ff93ffc Todd Kirby
    }
2462
}
2463
2464
static void opt_frame_pad_bottom(const char *arg)
2465
{
2466 115329f1 Diego Biurrun
    frame_padbottom = atoi(arg);
2467 1ff93ffc Todd Kirby
    if (frame_padbottom < 0) {
2468
        fprintf(stderr, "Incorrect bottom pad size\n");
2469 296df4e7 Ramiro Polla
        av_exit(1);
2470 1ff93ffc Todd Kirby
    }
2471
    if ((frame_padbottom % 2) != 0) {
2472
        fprintf(stderr, "Bottom pad size must be a multiple of 2\n");
2473 296df4e7 Ramiro Polla
        av_exit(1);
2474 1ff93ffc Todd Kirby
    }
2475
}
2476
2477
2478
static void opt_frame_pad_left(const char *arg)
2479
{
2480 115329f1 Diego Biurrun
    frame_padleft = atoi(arg);
2481 1ff93ffc Todd Kirby
    if (frame_padleft < 0) {
2482
        fprintf(stderr, "Incorrect left pad size\n");
2483 296df4e7 Ramiro Polla
        av_exit(1);
2484 1ff93ffc Todd Kirby
    }
2485
    if ((frame_padleft % 2) != 0) {
2486
        fprintf(stderr, "Left pad size must be a multiple of 2\n");
2487 296df4e7 Ramiro Polla
        av_exit(1);
2488 1ff93ffc Todd Kirby
    }
2489
}
2490
2491
2492
static void opt_frame_pad_right(const char *arg)
2493
{
2494 115329f1 Diego Biurrun
    frame_padright = atoi(arg);
2495 1ff93ffc Todd Kirby
    if (frame_padright < 0) {
2496
        fprintf(stderr, "Incorrect right pad size\n");
2497 296df4e7 Ramiro Polla
        av_exit(1);
2498 1ff93ffc Todd Kirby
    }
2499
    if ((frame_padright % 2) != 0) {
2500
        fprintf(stderr, "Right pad size must be a multiple of 2\n");
2501 296df4e7 Ramiro Polla
        av_exit(1);
2502 1ff93ffc Todd Kirby
    }
2503
}
2504
2505 ce1ee094 Peter Ross
static void list_fmts(void (*get_fmt_string)(char *buf, int buf_size, int fmt), int nb_fmts)
2506 c3b95b1d Stefano Sabatini
{
2507
    int i;
2508 ce1ee094 Peter Ross
    char fmt_str[128];
2509
    for (i=-1; i < nb_fmts; i++) {
2510
        get_fmt_string (fmt_str, sizeof(fmt_str), i);
2511
        fprintf(stdout, "%s\n", fmt_str);
2512 c3b95b1d Stefano Sabatini
    }
2513
}
2514 1ff93ffc Todd Kirby
2515 63167088 Roman Shaposhnik
static void opt_frame_pix_fmt(const char *arg)
2516
{
2517 c3b95b1d Stefano Sabatini
    if (strcmp(arg, "list"))
2518
        frame_pix_fmt = avcodec_get_pix_fmt(arg);
2519
    else {
2520 ce1ee094 Peter Ross
        list_fmts(avcodec_pix_fmt_string, PIX_FMT_NB);
2521 296df4e7 Ramiro Polla
        av_exit(0);
2522 c3b95b1d Stefano Sabatini
    }
2523 63167088 Roman Shaposhnik
}
2524
2525 5fe03e38 Roman Shaposhnik
static void opt_frame_aspect_ratio(const char *arg)
2526
{
2527
    int x = 0, y = 0;
2528
    double ar = 0;
2529
    const char *p;
2530 815f98cc Aurelien Jacobs
    char *end;
2531 115329f1 Diego Biurrun
2532 5fe03e38 Roman Shaposhnik
    p = strchr(arg, ':');
2533
    if (p) {
2534 815f98cc Aurelien Jacobs
        x = strtol(arg, &end, 10);
2535
        if (end == p)
2536
            y = strtol(end+1, &end, 10);
2537 bb270c08 Diego Biurrun
        if (x > 0 && y > 0)
2538
            ar = (double)x / (double)y;
2539 5fe03e38 Roman Shaposhnik
    } else
2540 815f98cc Aurelien Jacobs
        ar = strtod(arg, NULL);
2541 5fe03e38 Roman Shaposhnik
2542
    if (!ar) {
2543
        fprintf(stderr, "Incorrect aspect ratio specification.\n");
2544 296df4e7 Ramiro Polla
        av_exit(1);
2545 5fe03e38 Roman Shaposhnik
    }
2546
    frame_aspect_ratio = ar;
2547
}
2548
2549 b29f97d1 Zdenek Kabelac
static void opt_qscale(const char *arg)
2550 85f07f22 Fabrice Bellard
{
2551 158c7f05 Michael Niedermayer
    video_qscale = atof(arg);
2552 4e64bead Loren Merritt
    if (video_qscale <= 0 ||
2553 158c7f05 Michael Niedermayer
        video_qscale > 255) {
2554 4e64bead Loren Merritt
        fprintf(stderr, "qscale must be > 0.0 and <= 255\n");
2555 296df4e7 Ramiro Polla
        av_exit(1);
2556 85f07f22 Fabrice Bellard
    }
2557
}
2558
2559 bb198e19 Michael Niedermayer
static void opt_top_field_first(const char *arg)
2560
{
2561
    top_field_first= atoi(arg);
2562
}
2563
2564 d18811bb Stefano Sabatini
static int opt_thread_count(const char *opt, const char *arg)
2565 9c3d33d6 Michael Niedermayer
{
2566 d18811bb Stefano Sabatini
    thread_count= parse_number_or_die(opt, arg, OPT_INT64, 0, INT_MAX);
2567 2450cff2 François Revol
#if !defined(HAVE_THREADS)
2568 d8019eb5 Allen Day
    if (verbose >= 0)
2569
        fprintf(stderr, "Warning: not compiled with thread support, using thread emulation\n");
2570 842b556a Michael Niedermayer
#endif
2571 d18811bb Stefano Sabatini
    return 0;
2572 9c3d33d6 Michael Niedermayer
}
2573
2574 ce1ee094 Peter Ross
static void opt_audio_sample_fmt(const char *arg)
2575
{
2576
    if (strcmp(arg, "list"))
2577
        audio_sample_fmt = avcodec_get_sample_fmt(arg);
2578
    else {
2579
        list_fmts(avcodec_sample_fmt_string, SAMPLE_FMT_NB);
2580
        av_exit(0);
2581
    }
2582
}
2583
2584 c48da33c Stefano Sabatini
static int opt_audio_rate(const char *opt, const char *arg)
2585 85f07f22 Fabrice Bellard
{
2586 c48da33c Stefano Sabatini
    audio_sample_rate = parse_number_or_die(opt, arg, OPT_INT64, 0, INT_MAX);
2587
    return 0;
2588 85f07f22 Fabrice Bellard
}
2589
2590 c48da33c Stefano Sabatini
static int opt_audio_channels(const char *opt, const char *arg)
2591 85f07f22 Fabrice Bellard
{
2592 c48da33c Stefano Sabatini
    audio_channels = parse_number_or_die(opt, arg, OPT_INT64, 0, INT_MAX);
2593
    return 0;
2594 85f07f22 Fabrice Bellard
}
2595
2596 b29f97d1 Zdenek Kabelac
static void opt_video_channel(const char *arg)
2597 a5df11ab Fabrice Bellard
{
2598
    video_channel = strtol(arg, NULL, 0);
2599
}
2600
2601 e3ee3283 Alex Beregszaszi
static void opt_video_standard(const char *arg)
2602
{
2603
    video_standard = av_strdup(arg);
2604
}
2605
2606 4a897224 Nicolas George
static void opt_codec(int *pstream_copy, char **pcodec_name,
2607 cf7fc795 Fabrice Bellard
                      int codec_type, const char *arg)
2608 85f07f22 Fabrice Bellard
{
2609 4a897224 Nicolas George
    av_freep(pcodec_name);
2610 1629626f Fabrice Bellard
    if (!strcmp(arg, "copy")) {
2611 cf7fc795 Fabrice Bellard
        *pstream_copy = 1;
2612 85f07f22 Fabrice Bellard
    } else {
2613 4a897224 Nicolas George
        *pcodec_name = av_strdup(arg);
2614 85f07f22 Fabrice Bellard
    }
2615
}
2616
2617 cf7fc795 Fabrice Bellard
static void opt_audio_codec(const char *arg)
2618
{
2619