Statistics
| Branch: | Revision:

ffmpeg / ffmpeg.c @ 647148c6

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

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