Statistics
| Branch: | Revision:

ffmpeg / ffmpeg.c @ 5c20c81b

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