Statistics
| Branch: | Revision:

ffmpeg / ffmpeg.c @ 4618637a

History | View | Annotate | Download (159 KB)

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