Statistics
| Branch: | Revision:

ffmpeg / ffmpeg.c @ 03700d39

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