Statistics
| Branch: | Revision:

ffmpeg / ffmpeg.c @ ffcc6e24

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