Statistics
| Branch: | Revision:

ffmpeg / ffmpeg.c @ 6580d5e3

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