Statistics
| Branch: | Revision:

ffmpeg / ffmpeg.c @ 04d2540c

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