Statistics
| Branch: | Revision:

ffmpeg / ffmpeg.c @ 6b1c886b

History | View | Annotate | Download (163 KB)

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