Statistics
| Branch: | Revision:

ffmpeg / ffmpeg.c @ 9a191b3a

History | View | Annotate | Download (155 KB)

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