avconv: fix memleaks due to not freeing the AVFrame for audio
[libav.git] / avconv.c
CommitLineData
6291d7e4
AK
1/*
2 * avconv main
3 * Copyright (c) 2000-2011 The libav developers.
4 *
5 * This file is part of Libav.
6 *
7 * Libav is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
11 *
12 * Libav is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
16 *
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with Libav; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20 */
21
22#include "config.h"
23#include <ctype.h>
24#include <string.h>
25#include <math.h>
26#include <stdlib.h>
27#include <errno.h>
28#include <signal.h>
29#include <limits.h>
30#include <unistd.h>
31#include "libavformat/avformat.h"
32#include "libavdevice/avdevice.h"
33#include "libswscale/swscale.h"
34#include "libavutil/opt.h"
35#include "libavcodec/audioconvert.h"
36#include "libavutil/audioconvert.h"
37#include "libavutil/parseutils.h"
38#include "libavutil/samplefmt.h"
39#include "libavutil/colorspace.h"
40#include "libavutil/fifo.h"
41#include "libavutil/intreadwrite.h"
42#include "libavutil/dict.h"
43#include "libavutil/mathematics.h"
44#include "libavutil/pixdesc.h"
45#include "libavutil/avstring.h"
46#include "libavutil/libm.h"
47#include "libavformat/os_support.h"
48
49#if CONFIG_AVFILTER
50# include "libavfilter/avfilter.h"
51# include "libavfilter/avfiltergraph.h"
52# include "libavfilter/vsrc_buffer.h"
53#endif
54
55#if HAVE_SYS_RESOURCE_H
56#include <sys/types.h>
57#include <sys/time.h>
58#include <sys/resource.h>
59#elif HAVE_GETPROCESSTIMES
60#include <windows.h>
61#endif
62#if HAVE_GETPROCESSMEMORYINFO
63#include <windows.h>
64#include <psapi.h>
65#endif
66
67#if HAVE_SYS_SELECT_H
68#include <sys/select.h>
69#endif
70
71#include <time.h>
72
73#include "cmdutils.h"
74
75#include "libavutil/avassert.h"
76
77const char program_name[] = "avconv";
78const int program_birth_year = 2000;
79
80/* select an input stream for an output stream */
81typedef struct StreamMap {
8d2e4a7e 82 int disabled; /** 1 is this mapping is disabled by a negative map */
6291d7e4
AK
83 int file_index;
84 int stream_index;
85 int sync_file_index;
86 int sync_stream_index;
87} StreamMap;
88
89/**
90 * select an input file for an output file
91 */
92typedef struct MetadataMap {
02494787
DB
93 int file; ///< file index
94 char type; ///< type of metadata to copy -- (g)lobal, (s)tream, (c)hapter or (p)rogram
95 int index; ///< stream/chapter/program number
6291d7e4
AK
96} MetadataMap;
97
6291d7e4
AK
98static const OptionDef options[];
99
6291d7e4 100static int video_discard = 0;
f4ad238c 101static int same_quant = 0;
6291d7e4 102static int do_deinterlace = 0;
6291d7e4 103static int intra_dc_precision = 8;
6291d7e4 104static int qp_hist = 0;
6291d7e4 105
6291d7e4 106static int file_overwrite = 0;
6291d7e4
AK
107static int do_benchmark = 0;
108static int do_hex_dump = 0;
109static int do_pkt_dump = 0;
6291d7e4
AK
110static int do_pass = 0;
111static char *pass_logfilename_prefix = NULL;
6291d7e4
AK
112static int video_sync_method= -1;
113static int audio_sync_method= 0;
114static float audio_drift_threshold= 0.1;
115static int copy_ts= 0;
7bb3e625 116static int copy_tb = 1;
6291d7e4
AK
117static int opt_shortest = 0;
118static char *vstats_filename;
119static FILE *vstats_file;
6291d7e4 120
6291d7e4
AK
121static int audio_volume = 256;
122
123static int exit_on_error = 0;
124static int using_stdin = 0;
6291d7e4
AK
125static int64_t video_size = 0;
126static int64_t audio_size = 0;
127static int64_t extra_size = 0;
128static int nb_frames_dup = 0;
129static int nb_frames_drop = 0;
130static int input_sync;
6291d7e4
AK
131
132static float dts_delta_threshold = 10;
133
3460dd8a
AK
134static int print_stats = 1;
135
6291d7e4
AK
136static uint8_t *audio_buf;
137static uint8_t *audio_out;
138static unsigned int allocated_audio_out_size, allocated_audio_buf_size;
139
6291d7e4
AK
140#define DEFAULT_PASS_LOGFILENAME_PREFIX "av2pass"
141
6494c001
AK
142typedef struct InputStream {
143 int file_index;
144 AVStream *st;
145 int discard; /* true if stream data should be discarded */
146 int decoding_needed; /* true if the packets must be decoded in 'raw_fifo' */
147 AVCodec *dec;
148
149 int64_t start; /* time when read started */
150 int64_t next_pts; /* synthetic pts for cases where pkt.pts
151 is not defined */
152 int64_t pts; /* current pts */
153 PtsCorrectionContext pts_ctx;
154 double ts_scale;
155 int is_start; /* is 1 at the start and after a discontinuity */
156 int showed_multi_packet_warning;
157 AVDictionary *opts;
158} InputStream;
159
160typedef struct InputFile {
161 AVFormatContext *ctx;
162 int eof_reached; /* true if eof reached */
163 int ist_index; /* index of first stream in ist_table */
164 int buffer_size; /* current total buffer size */
165 int64_t ts_offset;
ed5b1326
AK
166 int nb_streams; /* number of stream that avconv is aware of; may be different
167 from ctx.nb_streams if new streams appear during av_read_frame() */
f4805328 168 int rate_emu;
6494c001 169} InputFile;
6291d7e4
AK
170
171typedef struct OutputStream {
172 int file_index; /* file index */
173 int index; /* stream index in the output file */
174 int source_index; /* InputStream index */
175 AVStream *st; /* stream in the output file */
176 int encoding_needed; /* true if encoding needed for this stream */
177 int frame_number;
178 /* input pts and corresponding output pts
179 for A/V sync */
180 //double sync_ipts; /* dts from the AVPacket of the demuxer in second units */
181 struct InputStream *sync_ist; /* input stream to sync against */
182 int64_t sync_opts; /* output frame counter, could be changed to some true timestamp */ //FIXME look at frame_number
183 AVBitStreamFilterContext *bitstream_filters;
184 AVCodec *enc;
96139b5e 185 int64_t max_frames;
6291d7e4
AK
186
187 /* video only */
188 int video_resample;
189 AVFrame pict_tmp; /* temporary image for resampling */
190 struct SwsContext *img_resample_ctx; /* for image resampling */
191 int resample_height;
192 int resample_width;
193 int resample_pix_fmt;
194 AVRational frame_rate;
bef737a7 195 int force_fps;
828e0bcb 196 int top_field_first;
6291d7e4
AK
197
198 float frame_aspect_ratio;
199
200 /* forced key frames */
201 int64_t *forced_kf_pts;
202 int forced_kf_count;
203 int forced_kf_index;
204
205 /* audio only */
206 int audio_resample;
207 ReSampleContext *resample; /* for audio resampling */
208 int resample_sample_fmt;
209 int resample_channels;
210 int resample_sample_rate;
211 int reformat_pair;
212 AVAudioConvert *reformat_ctx;
213 AVFifoBuffer *fifo; /* for compression: one audio fifo per codec */
214 FILE *logfile;
215
216#if CONFIG_AVFILTER
217 AVFilterContext *output_video_filter;
218 AVFilterContext *input_video_filter;
219 AVFilterBufferRef *picref;
220 char *avfilter;
221 AVFilterGraph *graph;
222#endif
223
f8c314c8
AK
224 int64_t sws_flags;
225 AVDictionary *opts;
226 int is_past_recording_time;
227 int stream_copy;
228 const char *attachment_filename;
229 int copy_initial_nonkeyframes;
6291d7e4
AK
230} OutputStream;
231
6291d7e4 232
af70aa45
AK
233typedef struct OutputFile {
234 AVFormatContext *ctx;
235 AVDictionary *opts;
4288e031 236 int ost_index; /* index of the first stream in output_streams */
ef44a607 237 int64_t recording_time; /* desired length of the resulting file in microseconds */
ea065176 238 int64_t start_time; /* start time in microseconds */
f21f294e 239 uint64_t limit_filesize;
af70aa45
AK
240} OutputFile;
241
6291d7e4
AK
242static InputStream *input_streams = NULL;
243static int nb_input_streams = 0;
244static InputFile *input_files = NULL;
245static int nb_input_files = 0;
246
4288e031
AK
247static OutputStream *output_streams = NULL;
248static int nb_output_streams = 0;
af70aa45
AK
249static OutputFile *output_files = NULL;
250static int nb_output_files = 0;
251
575ec4e1 252typedef struct OptionsContext {
6b779ccc
AK
253 /* input/output options */
254 int64_t start_time;
7041bb3b 255 const char *format;
6b779ccc 256
35e6f8c1
AK
257 SpecifierOpt *codec_names;
258 int nb_codec_names;
6a11686d
AK
259 SpecifierOpt *audio_channels;
260 int nb_audio_channels;
e2469ccf
AK
261 SpecifierOpt *audio_sample_rate;
262 int nb_audio_sample_rate;
91ea4811
AK
263 SpecifierOpt *frame_rates;
264 int nb_frame_rates;
d4397b03
AK
265 SpecifierOpt *frame_sizes;
266 int nb_frame_sizes;
b2254d83
AK
267 SpecifierOpt *frame_pix_fmts;
268 int nb_frame_pix_fmts;
35e6f8c1 269
6b779ccc
AK
270 /* input options */
271 int64_t input_ts_offset;
f4805328 272 int rate_emu;
6b779ccc 273
33f75d72
AK
274 SpecifierOpt *ts_scale;
275 int nb_ts_scale;
a2c0b830
AK
276 SpecifierOpt *dump_attachment;
277 int nb_dump_attachment;
33f75d72 278
575ec4e1
AK
279 /* output options */
280 StreamMap *stream_maps;
281 int nb_stream_maps;
847529f8
AK
282 /* first item specifies output metadata, second is input */
283 MetadataMap (*meta_data_maps)[2];
284 int nb_meta_data_maps;
285 int metadata_global_manual;
286 int metadata_streams_manual;
287 int metadata_chapters_manual;
4dbc6cee
AK
288 const char **attachments;
289 int nb_attachments;
6b779ccc 290
c5bb372e
AK
291 int chapters_input_file;
292
6b779ccc 293 int64_t recording_time;
13ccba50 294 uint64_t limit_filesize;
dc26318c
AK
295 float mux_preload;
296 float mux_max_delay;
039267f1 297
2130981a
AK
298 int video_disable;
299 int audio_disable;
300 int subtitle_disable;
301 int data_disable;
302
495ecfd1
AK
303 /* indexed by output file stream index */
304 int *streamid_map;
305 int nb_streamid_map;
306
039267f1
AK
307 SpecifierOpt *metadata;
308 int nb_metadata;
96139b5e
AK
309 SpecifierOpt *max_frames;
310 int nb_max_frames;
d821cbe2
AK
311 SpecifierOpt *bitstream_filters;
312 int nb_bitstream_filters;
013887eb
AK
313 SpecifierOpt *codec_tags;
314 int nb_codec_tags;
05bffc12
AK
315 SpecifierOpt *sample_fmts;
316 int nb_sample_fmts;
77d9c454
AK
317 SpecifierOpt *qscale;
318 int nb_qscale;
7c029672
AK
319 SpecifierOpt *forced_key_frames;
320 int nb_forced_key_frames;
bef737a7
AK
321 SpecifierOpt *force_fps;
322 int nb_force_fps;
ca46fde7
AK
323 SpecifierOpt *frame_aspect_ratios;
324 int nb_frame_aspect_ratios;
0e68c783
AK
325 SpecifierOpt *rc_overrides;
326 int nb_rc_overrides;
2c2cff16
AK
327 SpecifierOpt *intra_matrices;
328 int nb_intra_matrices;
329 SpecifierOpt *inter_matrices;
330 int nb_inter_matrices;
828e0bcb
AK
331 SpecifierOpt *top_field_first;
332 int nb_top_field_first;
3ec34462
AK
333 SpecifierOpt *presets;
334 int nb_presets;
a2aeeb22
AK
335 SpecifierOpt *copy_initial_nonkeyframes;
336 int nb_copy_initial_nonkeyframes;
8e5ce590
AK
337#if CONFIG_AVFILTER
338 SpecifierOpt *filters;
339 int nb_filters;
340#endif
575ec4e1
AK
341} OptionsContext;
342
35e6f8c1
AK
343#define MATCH_PER_STREAM_OPT(name, type, outvar, fmtctx, st)\
344{\
345 int i, ret;\
346 for (i = 0; i < o->nb_ ## name; i++) {\
347 char *spec = o->name[i].specifier;\
348 if ((ret = check_stream_specifier(fmtctx, st, spec)) > 0)\
349 outvar = o->name[i].u.type;\
350 else if (ret < 0)\
351 exit_program(1);\
352 }\
353}
354
575ec4e1
AK
355static void reset_options(OptionsContext *o)
356{
357 const OptionDef *po = options;
358
359 /* all OPT_SPEC and OPT_STRING can be freed in generic way */
360 while (po->name) {
361 void *dst = (uint8_t*)o + po->u.off;
362
363 if (po->flags & OPT_SPEC) {
364 SpecifierOpt **so = dst;
365 int i, *count = (int*)(so + 1);
366 for (i = 0; i < *count; i++) {
367 av_freep(&(*so)[i].specifier);
368 if (po->flags & OPT_STRING)
369 av_freep(&(*so)[i].u.str);
370 }
371 av_freep(so);
372 *count = 0;
373 } else if (po->flags & OPT_OFFSET && po->flags & OPT_STRING)
374 av_freep(dst);
375 po++;
376 }
377
378 av_freep(&o->stream_maps);
847529f8 379 av_freep(&o->meta_data_maps);
495ecfd1 380 av_freep(&o->streamid_map);
575ec4e1
AK
381
382 memset(o, 0, sizeof(*o));
6b779ccc 383
dc26318c 384 o->mux_max_delay = 0.7;
6b779ccc 385 o->recording_time = INT64_MAX;
13ccba50 386 o->limit_filesize = UINT64_MAX;
c5bb372e 387 o->chapters_input_file = INT_MAX;
6b779ccc 388
575ec4e1
AK
389 uninit_opts();
390 init_opts();
391}
392
6291d7e4
AK
393#if CONFIG_AVFILTER
394
395static int configure_video_filters(InputStream *ist, OutputStream *ost)
396{
397 AVFilterContext *last_filter, *filter;
398 /** filter graph containing all filters including input & output */
399 AVCodecContext *codec = ost->st->codec;
400 AVCodecContext *icodec = ist->st->codec;
401 FFSinkContext ffsink_ctx = { .pix_fmt = codec->pix_fmt };
402 AVRational sample_aspect_ratio;
403 char args[255];
404 int ret;
405
406 ost->graph = avfilter_graph_alloc();
407
408 if (ist->st->sample_aspect_ratio.num){
409 sample_aspect_ratio = ist->st->sample_aspect_ratio;
410 }else
411 sample_aspect_ratio = ist->st->codec->sample_aspect_ratio;
412
413 snprintf(args, 255, "%d:%d:%d:%d:%d:%d:%d", ist->st->codec->width,
414 ist->st->codec->height, ist->st->codec->pix_fmt, 1, AV_TIME_BASE,
415 sample_aspect_ratio.num, sample_aspect_ratio.den);
416
417 ret = avfilter_graph_create_filter(&ost->input_video_filter, avfilter_get_by_name("buffer"),
418 "src", args, NULL, ost->graph);
419 if (ret < 0)
420 return ret;
421 ret = avfilter_graph_create_filter(&ost->output_video_filter, &ffsink,
422 "out", NULL, &ffsink_ctx, ost->graph);
423 if (ret < 0)
424 return ret;
425 last_filter = ost->input_video_filter;
426
427 if (codec->width != icodec->width || codec->height != icodec->height) {
428 snprintf(args, 255, "%d:%d:flags=0x%X",
429 codec->width,
430 codec->height,
3b3ea346 431 (unsigned)ost->sws_flags);
6291d7e4
AK
432 if ((ret = avfilter_graph_create_filter(&filter, avfilter_get_by_name("scale"),
433 NULL, args, NULL, ost->graph)) < 0)
434 return ret;
435 if ((ret = avfilter_link(last_filter, 0, filter, 0)) < 0)
436 return ret;
437 last_filter = filter;
438 }
439
3b3ea346 440 snprintf(args, sizeof(args), "flags=0x%X", (unsigned)ost->sws_flags);
6291d7e4
AK
441 ost->graph->scale_sws_opts = av_strdup(args);
442
443 if (ost->avfilter) {
444 AVFilterInOut *outputs = av_malloc(sizeof(AVFilterInOut));
445 AVFilterInOut *inputs = av_malloc(sizeof(AVFilterInOut));
446
447 outputs->name = av_strdup("in");
448 outputs->filter_ctx = last_filter;
449 outputs->pad_idx = 0;
450 outputs->next = NULL;
451
452 inputs->name = av_strdup("out");
453 inputs->filter_ctx = ost->output_video_filter;
454 inputs->pad_idx = 0;
455 inputs->next = NULL;
456
457 if ((ret = avfilter_graph_parse(ost->graph, ost->avfilter, inputs, outputs, NULL)) < 0)
458 return ret;
459 av_freep(&ost->avfilter);
460 } else {
461 if ((ret = avfilter_link(last_filter, 0, ost->output_video_filter, 0)) < 0)
462 return ret;
463 }
464
465 if ((ret = avfilter_graph_config(ost->graph, NULL)) < 0)
466 return ret;
467
468 codec->width = ost->output_video_filter->inputs[0]->w;
469 codec->height = ost->output_video_filter->inputs[0]->h;
470 codec->sample_aspect_ratio = ost->st->sample_aspect_ratio =
bb337b4f 471 ost->frame_aspect_ratio ? // overridden by the -aspect cli option
6291d7e4
AK
472 av_d2q(ost->frame_aspect_ratio*codec->height/codec->width, 255) :
473 ost->output_video_filter->inputs[0]->sample_aspect_ratio;
474
475 return 0;
476}
477#endif /* CONFIG_AVFILTER */
478
479static void term_exit(void)
480{
481 av_log(NULL, AV_LOG_QUIET, "");
482}
483
484static volatile int received_sigterm = 0;
485static volatile int received_nb_signals = 0;
486
487static void
488sigterm_handler(int sig)
489{
490 received_sigterm = sig;
491 received_nb_signals++;
492 term_exit();
493}
494
495static void term_init(void)
496{
497 signal(SIGINT , sigterm_handler); /* Interrupt (ANSI). */
498 signal(SIGTERM, sigterm_handler); /* Termination (ANSI). */
499#ifdef SIGXCPU
500 signal(SIGXCPU, sigterm_handler);
501#endif
502}
503
2abe947a 504static int decode_interrupt_cb(void *ctx)
6291d7e4
AK
505{
506 return received_nb_signals > 1;
507}
508
2abe947a
MS
509static const AVIOInterruptCB int_cb = { decode_interrupt_cb, NULL };
510
dad09ff9 511void exit_program(int ret)
6291d7e4
AK
512{
513 int i;
514
515 /* close files */
516 for(i=0;i<nb_output_files;i++) {
af70aa45 517 AVFormatContext *s = output_files[i].ctx;
6291d7e4
AK
518 if (!(s->oformat->flags & AVFMT_NOFILE) && s->pb)
519 avio_close(s->pb);
520 avformat_free_context(s);
af70aa45 521 av_dict_free(&output_files[i].opts);
6291d7e4
AK
522 }
523 for(i=0;i<nb_input_files;i++) {
524 av_close_input_file(input_files[i].ctx);
525 }
526 for (i = 0; i < nb_input_streams; i++)
527 av_dict_free(&input_streams[i].opts);
528
6291d7e4
AK
529 if (vstats_file)
530 fclose(vstats_file);
531 av_free(vstats_filename);
532
6291d7e4
AK
533 av_freep(&input_streams);
534 av_freep(&input_files);
4288e031 535 av_freep(&output_streams);
af70aa45 536 av_freep(&output_files);
6291d7e4 537
6291d7e4
AK
538 uninit_opts();
539 av_free(audio_buf);
540 av_free(audio_out);
541 allocated_audio_buf_size= allocated_audio_out_size= 0;
6291d7e4
AK
542
543#if CONFIG_AVFILTER
544 avfilter_uninit();
545#endif
776f2bb9 546 avformat_network_deinit();
6291d7e4
AK
547
548 if (received_sigterm) {
e3245b26
AK
549 av_log(NULL, AV_LOG_INFO, "Received signal %d: terminating.\n",
550 (int) received_sigterm);
6291d7e4
AK
551 exit (255);
552 }
553
554 exit(ret); /* not all OS-es handle main() return value */
6291d7e4
AK
555}
556
557static void assert_avoptions(AVDictionary *m)
558{
559 AVDictionaryEntry *t;
560 if ((t = av_dict_get(m, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
f24facd3 561 av_log(NULL, AV_LOG_FATAL, "Option %s not found.\n", t->key);
6291d7e4
AK
562 exit_program(1);
563 }
564}
565
566static void assert_codec_experimental(AVCodecContext *c, int encoder)
567{
568 const char *codec_string = encoder ? "encoder" : "decoder";
569 AVCodec *codec;
570 if (c->codec->capabilities & CODEC_CAP_EXPERIMENTAL &&
571 c->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
f24facd3 572 av_log(NULL, AV_LOG_FATAL, "%s '%s' is experimental and might produce bad "
6291d7e4
AK
573 "results.\nAdd '-strict experimental' if you want to use it.\n",
574 codec_string, c->codec->name);
575 codec = encoder ? avcodec_find_encoder(c->codec->id) : avcodec_find_decoder(c->codec->id);
576 if (!(codec->capabilities & CODEC_CAP_EXPERIMENTAL))
f24facd3 577 av_log(NULL, AV_LOG_FATAL, "Or use the non experimental %s '%s'.\n",
6291d7e4
AK
578 codec_string, codec->name);
579 exit_program(1);
580 }
581}
582
6291d7e4
AK
583static void choose_sample_fmt(AVStream *st, AVCodec *codec)
584{
585 if(codec && codec->sample_fmts){
586 const enum AVSampleFormat *p= codec->sample_fmts;
587 for(; *p!=-1; p++){
588 if(*p == st->codec->sample_fmt)
589 break;
590 }
591 if (*p == -1) {
592 av_log(NULL, AV_LOG_WARNING,
593 "Incompatible sample format '%s' for codec '%s', auto-selecting format '%s'\n",
594 av_get_sample_fmt_name(st->codec->sample_fmt),
595 codec->name,
596 av_get_sample_fmt_name(codec->sample_fmts[0]));
597 st->codec->sample_fmt = codec->sample_fmts[0];
598 }
599 }
600}
601
602/**
603 * Update the requested input sample format based on the output sample format.
604 * This is currently only used to request float output from decoders which
605 * support multiple sample formats, one of which is AV_SAMPLE_FMT_FLT.
606 * Ideally this will be removed in the future when decoders do not do format
607 * conversion and only output in their native format.
608 */
609static void update_sample_fmt(AVCodecContext *dec, AVCodec *dec_codec,
610 AVCodecContext *enc)
611{
612 /* if sample formats match or a decoder sample format has already been
613 requested, just return */
614 if (enc->sample_fmt == dec->sample_fmt ||
615 dec->request_sample_fmt > AV_SAMPLE_FMT_NONE)
616 return;
617
618 /* if decoder supports more than one output format */
619 if (dec_codec && dec_codec->sample_fmts &&
620 dec_codec->sample_fmts[0] != AV_SAMPLE_FMT_NONE &&
621 dec_codec->sample_fmts[1] != AV_SAMPLE_FMT_NONE) {
622 const enum AVSampleFormat *p;
623 int min_dec = -1, min_inc = -1;
624
625 /* find a matching sample format in the encoder */
626 for (p = dec_codec->sample_fmts; *p != AV_SAMPLE_FMT_NONE; p++) {
627 if (*p == enc->sample_fmt) {
628 dec->request_sample_fmt = *p;
629 return;
630 } else if (*p > enc->sample_fmt) {
631 min_inc = FFMIN(min_inc, *p - enc->sample_fmt);
632 } else
633 min_dec = FFMIN(min_dec, enc->sample_fmt - *p);
634 }
635
636 /* if none match, provide the one that matches quality closest */
637 dec->request_sample_fmt = min_inc > 0 ? enc->sample_fmt + min_inc :
638 enc->sample_fmt - min_dec;
639 }
640}
641
642static void choose_sample_rate(AVStream *st, AVCodec *codec)
643{
644 if(codec && codec->supported_samplerates){
645 const int *p= codec->supported_samplerates;
646 int best=0;
647 int best_dist=INT_MAX;
648 for(; *p; p++){
649 int dist= abs(st->codec->sample_rate - *p);
650 if(dist < best_dist){
651 best_dist= dist;
652 best= *p;
653 }
654 }
655 if(best_dist){
656 av_log(st->codec, AV_LOG_WARNING, "Requested sampling rate unsupported using closest supported (%d)\n", best);
657 }
658 st->codec->sample_rate= best;
659 }
660}
661
662static void choose_pixel_fmt(AVStream *st, AVCodec *codec)
663{
664 if(codec && codec->pix_fmts){
665 const enum PixelFormat *p= codec->pix_fmts;
666 if(st->codec->strict_std_compliance <= FF_COMPLIANCE_UNOFFICIAL){
667 if(st->codec->codec_id==CODEC_ID_MJPEG){
668 p= (const enum PixelFormat[]){PIX_FMT_YUVJ420P, PIX_FMT_YUVJ422P, PIX_FMT_YUV420P, PIX_FMT_YUV422P, PIX_FMT_NONE};
669 }else if(st->codec->codec_id==CODEC_ID_LJPEG){
670 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};
671 }
672 }
105ab61c 673 for (; *p != PIX_FMT_NONE; p++) {
6291d7e4
AK
674 if(*p == st->codec->pix_fmt)
675 break;
676 }
105ab61c 677 if (*p == PIX_FMT_NONE) {
6291d7e4
AK
678 if(st->codec->pix_fmt != PIX_FMT_NONE)
679 av_log(NULL, AV_LOG_WARNING,
680 "Incompatible pixel format '%s' for codec '%s', auto-selecting format '%s'\n",
681 av_pix_fmt_descriptors[st->codec->pix_fmt].name,
682 codec->name,
683 av_pix_fmt_descriptors[codec->pix_fmts[0]].name);
684 st->codec->pix_fmt = codec->pix_fmts[0];
685 }
686 }
687}
688
6291d7e4
AK
689static double
690get_sync_ipts(const OutputStream *ost)
691{
692 const InputStream *ist = ost->sync_ist;
ea065176
AK
693 OutputFile *of = &output_files[ost->file_index];
694 return (double)(ist->pts - of->start_time)/AV_TIME_BASE;
6291d7e4
AK
695}
696
697static void write_frame(AVFormatContext *s, AVPacket *pkt, AVCodecContext *avctx, AVBitStreamFilterContext *bsfc){
698 int ret;
699
700 while(bsfc){
701 AVPacket new_pkt= *pkt;
702 int a= av_bitstream_filter_filter(bsfc, avctx, NULL,
703 &new_pkt.data, &new_pkt.size,
704 pkt->data, pkt->size,
705 pkt->flags & AV_PKT_FLAG_KEY);
706 if(a>0){
707 av_free_packet(pkt);
708 new_pkt.destruct= av_destruct_packet;
709 } else if(a<0){
e3245b26
AK
710 av_log(NULL, AV_LOG_ERROR, "%s failed for stream %d, codec %s",
711 bsfc->filter->name, pkt->stream_index,
712 avctx->codec ? avctx->codec->name : "copy");
6291d7e4
AK
713 print_error("", a);
714 if (exit_on_error)
715 exit_program(1);
716 }
717 *pkt= new_pkt;
718
719 bsfc= bsfc->next;
720 }
721
722 ret= av_interleaved_write_frame(s, pkt);
723 if(ret < 0){
724 print_error("av_interleaved_write_frame()", ret);
725 exit_program(1);
726 }
727}
728
fdab793a
AC
729static void generate_silence(uint8_t* buf, enum AVSampleFormat sample_fmt, size_t size)
730{
731 int fill_char = 0x00;
732 if (sample_fmt == AV_SAMPLE_FMT_U8)
733 fill_char = 0x80;
734 memset(buf, fill_char, size);
735}
736
d1241ff3
JR
737static void do_audio_out(AVFormatContext *s, OutputStream *ost,
738 InputStream *ist, AVFrame *decoded_frame)
6291d7e4
AK
739{
740 uint8_t *buftmp;
741 int64_t audio_out_size, audio_buf_size;
6291d7e4
AK
742
743 int size_out, frame_bytes, ret, resample_changed;
744 AVCodecContext *enc= ost->st->codec;
745 AVCodecContext *dec= ist->st->codec;
746 int osize = av_get_bytes_per_sample(enc->sample_fmt);
747 int isize = av_get_bytes_per_sample(dec->sample_fmt);
748 const int coded_bps = av_get_bits_per_sample(enc->codec->id);
d1241ff3
JR
749 uint8_t *buf = decoded_frame->data[0];
750 int size = decoded_frame->nb_samples * dec->channels * isize;
751 int64_t allocated_for_size = size;
6291d7e4
AK
752
753need_realloc:
754 audio_buf_size= (allocated_for_size + isize*dec->channels - 1) / (isize*dec->channels);
755 audio_buf_size= (audio_buf_size*enc->sample_rate + dec->sample_rate) / dec->sample_rate;
756 audio_buf_size= audio_buf_size*2 + 10000; //safety factors for the deprecated resampling API
757 audio_buf_size= FFMAX(audio_buf_size, enc->frame_size);
758 audio_buf_size*= osize*enc->channels;
759
760 audio_out_size= FFMAX(audio_buf_size, enc->frame_size * osize * enc->channels);
761 if(coded_bps > 8*osize)
762 audio_out_size= audio_out_size * coded_bps / (8*osize);
763 audio_out_size += FF_MIN_BUFFER_SIZE;
764
765 if(audio_out_size > INT_MAX || audio_buf_size > INT_MAX){
e3245b26 766 av_log(NULL, AV_LOG_FATAL, "Buffer sizes too large\n");
6291d7e4
AK
767 exit_program(1);
768 }
769
770 av_fast_malloc(&audio_buf, &allocated_audio_buf_size, audio_buf_size);
771 av_fast_malloc(&audio_out, &allocated_audio_out_size, audio_out_size);
772 if (!audio_buf || !audio_out){
e3245b26 773 av_log(NULL, AV_LOG_FATAL, "Out of memory in do_audio_out\n");
6291d7e4
AK
774 exit_program(1);
775 }
776
777 if (enc->channels != dec->channels || enc->sample_rate != dec->sample_rate)
778 ost->audio_resample = 1;
779
780 resample_changed = ost->resample_sample_fmt != dec->sample_fmt ||
781 ost->resample_channels != dec->channels ||
782 ost->resample_sample_rate != dec->sample_rate;
783
784 if ((ost->audio_resample && !ost->resample) || resample_changed) {
785 if (resample_changed) {
9a414d89 786 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",
6291d7e4
AK
787 ist->file_index, ist->st->index,
788 ost->resample_sample_rate, av_get_sample_fmt_name(ost->resample_sample_fmt), ost->resample_channels,
789 dec->sample_rate, av_get_sample_fmt_name(dec->sample_fmt), dec->channels);
790 ost->resample_sample_fmt = dec->sample_fmt;
791 ost->resample_channels = dec->channels;
792 ost->resample_sample_rate = dec->sample_rate;
793 if (ost->resample)
794 audio_resample_close(ost->resample);
795 }
796 /* if audio_sync_method is >1 the resampler is needed for audio drift compensation */
797 if (audio_sync_method <= 1 &&
798 ost->resample_sample_fmt == enc->sample_fmt &&
799 ost->resample_channels == enc->channels &&
800 ost->resample_sample_rate == enc->sample_rate) {
801 ost->resample = NULL;
802 ost->audio_resample = 0;
803 } else if (ost->audio_resample) {
804 if (dec->sample_fmt != AV_SAMPLE_FMT_S16)
e3245b26 805 av_log(NULL, AV_LOG_WARNING, "Using s16 intermediate sample format for resampling\n");
6291d7e4
AK
806 ost->resample = av_audio_resample_init(enc->channels, dec->channels,
807 enc->sample_rate, dec->sample_rate,
808 enc->sample_fmt, dec->sample_fmt,
809 16, 10, 0, 0.8);
810 if (!ost->resample) {
e3245b26
AK
811 av_log(NULL, AV_LOG_FATAL, "Can not resample %d channels @ %d Hz to %d channels @ %d Hz\n",
812 dec->channels, dec->sample_rate,
813 enc->channels, enc->sample_rate);
6291d7e4
AK
814 exit_program(1);
815 }
816 }
817 }
818
819#define MAKE_SFMT_PAIR(a,b) ((a)+AV_SAMPLE_FMT_NB*(b))
820 if (!ost->audio_resample && dec->sample_fmt!=enc->sample_fmt &&
821 MAKE_SFMT_PAIR(enc->sample_fmt,dec->sample_fmt)!=ost->reformat_pair) {
822 if (ost->reformat_ctx)
823 av_audio_convert_free(ost->reformat_ctx);
824 ost->reformat_ctx = av_audio_convert_alloc(enc->sample_fmt, 1,
825 dec->sample_fmt, 1, NULL, 0);
826 if (!ost->reformat_ctx) {
e3245b26
AK
827 av_log(NULL, AV_LOG_FATAL, "Cannot convert %s sample format to %s sample format\n",
828 av_get_sample_fmt_name(dec->sample_fmt),
829 av_get_sample_fmt_name(enc->sample_fmt));
6291d7e4
AK
830 exit_program(1);
831 }
832 ost->reformat_pair=MAKE_SFMT_PAIR(enc->sample_fmt,dec->sample_fmt);
833 }
834
835 if(audio_sync_method){
836 double delta = get_sync_ipts(ost) * enc->sample_rate - ost->sync_opts
fdab793a
AC
837 - av_fifo_size(ost->fifo)/(enc->channels * osize);
838 int idelta = delta * dec->sample_rate / enc->sample_rate;
839 int byte_delta = idelta * isize * dec->channels;
6291d7e4
AK
840
841 //FIXME resample delay
842 if(fabs(delta) > 50){
843 if(ist->is_start || fabs(delta) > audio_drift_threshold*enc->sample_rate){
844 if(byte_delta < 0){
845 byte_delta= FFMAX(byte_delta, -size);
846 size += byte_delta;
847 buf -= byte_delta;
fdab793a
AC
848 av_log(NULL, AV_LOG_VERBOSE, "discarding %d audio samples\n",
849 -byte_delta / (isize * dec->channels));
6291d7e4
AK
850 if(!size)
851 return;
852 ist->is_start=0;
853 }else{
854 static uint8_t *input_tmp= NULL;
855 input_tmp= av_realloc(input_tmp, byte_delta + size);
856
857 if(byte_delta > allocated_for_size - size){
858 allocated_for_size= byte_delta + (int64_t)size;
859 goto need_realloc;
860 }
861 ist->is_start=0;
862
fdab793a 863 generate_silence(input_tmp, dec->sample_fmt, byte_delta);
6291d7e4
AK
864 memcpy(input_tmp + byte_delta, buf, size);
865 buf= input_tmp;
866 size += byte_delta;
fdab793a 867 av_log(NULL, AV_LOG_VERBOSE, "adding %d audio samples of silence\n", idelta);
6291d7e4
AK
868 }
869 }else if(audio_sync_method>1){
870 int comp= av_clip(delta, -audio_sync_method, audio_sync_method);
871 av_assert0(ost->audio_resample);
e3245b26
AK
872 av_log(NULL, AV_LOG_VERBOSE, "compensating audio timestamp drift:%f compensation:%d in:%d\n",
873 delta, comp, enc->sample_rate);
6291d7e4
AK
874// 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));
875 av_resample_compensate(*(struct AVResampleContext**)ost->resample, comp, enc->sample_rate);
876 }
877 }
878 }else
879 ost->sync_opts= lrintf(get_sync_ipts(ost) * enc->sample_rate)
fdab793a 880 - av_fifo_size(ost->fifo)/(enc->channels * osize); //FIXME wrong
6291d7e4
AK
881
882 if (ost->audio_resample) {
883 buftmp = audio_buf;
884 size_out = audio_resample(ost->resample,
885 (short *)buftmp, (short *)buf,
886 size / (dec->channels * isize));
887 size_out = size_out * enc->channels * osize;
888 } else {
889 buftmp = buf;
890 size_out = size;
891 }
892
893 if (!ost->audio_resample && dec->sample_fmt!=enc->sample_fmt) {
894 const void *ibuf[6]= {buftmp};
895 void *obuf[6]= {audio_buf};
896 int istride[6]= {isize};
897 int ostride[6]= {osize};
898 int len= size_out/istride[0];
899 if (av_audio_convert(ost->reformat_ctx, obuf, ostride, ibuf, istride, len)<0) {
900 printf("av_audio_convert() failed\n");
901 if (exit_on_error)
902 exit_program(1);
903 return;
904 }
905 buftmp = audio_buf;
906 size_out = len*osize;
907 }
908
909 /* now encode as many frames as possible */
910 if (enc->frame_size > 1) {
911 /* output resampled raw samples */
912 if (av_fifo_realloc2(ost->fifo, av_fifo_size(ost->fifo) + size_out) < 0) {
e3245b26 913 av_log(NULL, AV_LOG_FATAL, "av_fifo_realloc2() failed\n");
6291d7e4
AK
914 exit_program(1);
915 }
916 av_fifo_generic_write(ost->fifo, buftmp, size_out, NULL);
917
918 frame_bytes = enc->frame_size * osize * enc->channels;
919
920 while (av_fifo_size(ost->fifo) >= frame_bytes) {
921 AVPacket pkt;
922 av_init_packet(&pkt);
923
924 av_fifo_generic_read(ost->fifo, audio_buf, frame_bytes, NULL);
925
926 //FIXME pass ost->sync_opts as AVFrame.pts in avcodec_encode_audio()
927
928 ret = avcodec_encode_audio(enc, audio_out, audio_out_size,
929 (short *)audio_buf);
930 if (ret < 0) {
e3245b26 931 av_log(NULL, AV_LOG_FATAL, "Audio encoding failed\n");
6291d7e4
AK
932 exit_program(1);
933 }
934 audio_size += ret;
935 pkt.stream_index= ost->index;
936 pkt.data= audio_out;
937 pkt.size= ret;
938 if(enc->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)
939 pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
940 pkt.flags |= AV_PKT_FLAG_KEY;
941 write_frame(s, &pkt, enc, ost->bitstream_filters);
942
943 ost->sync_opts += enc->frame_size;
944 }
945 } else {
946 AVPacket pkt;
947 av_init_packet(&pkt);
948
949 ost->sync_opts += size_out / (osize * enc->channels);
950
951 /* output a pcm frame */
952 /* determine the size of the coded buffer */
953 size_out /= osize;
954 if (coded_bps)
955 size_out = size_out*coded_bps/8;
956
957 if(size_out > audio_out_size){
e3245b26 958 av_log(NULL, AV_LOG_FATAL, "Internal error, buffer size too small\n");
6291d7e4
AK
959 exit_program(1);
960 }
961
962 //FIXME pass ost->sync_opts as AVFrame.pts in avcodec_encode_audio()
963 ret = avcodec_encode_audio(enc, audio_out, size_out,
964 (short *)buftmp);
965 if (ret < 0) {
e3245b26 966 av_log(NULL, AV_LOG_FATAL, "Audio encoding failed\n");
6291d7e4
AK
967 exit_program(1);
968 }
969 audio_size += ret;
970 pkt.stream_index= ost->index;
971 pkt.data= audio_out;
972 pkt.size= ret;
973 if(enc->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)
974 pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
975 pkt.flags |= AV_PKT_FLAG_KEY;
976 write_frame(s, &pkt, enc, ost->bitstream_filters);
977 }
978}
979
980static void pre_process_video_frame(InputStream *ist, AVPicture *picture, void **bufp)
981{
982 AVCodecContext *dec;
983 AVPicture *picture2;
984 AVPicture picture_tmp;
985 uint8_t *buf = 0;
986
987 dec = ist->st->codec;
988
989 /* deinterlace : must be done before any resize */
990 if (do_deinterlace) {
991 int size;
992
993 /* create temporary picture */
994 size = avpicture_get_size(dec->pix_fmt, dec->width, dec->height);
995 buf = av_malloc(size);
996 if (!buf)
997 return;
998
999 picture2 = &picture_tmp;
1000 avpicture_fill(picture2, buf, dec->pix_fmt, dec->width, dec->height);
1001
1002 if(avpicture_deinterlace(picture2, picture,
1003 dec->pix_fmt, dec->width, dec->height) < 0) {
1004 /* if error, do not deinterlace */
e3245b26 1005 av_log(NULL, AV_LOG_WARNING, "Deinterlacing failed\n");
6291d7e4
AK
1006 av_free(buf);
1007 buf = NULL;
1008 picture2 = picture;
1009 }
1010 } else {
1011 picture2 = picture;
1012 }
1013
1014 if (picture != picture2)
1015 *picture = *picture2;
1016 *bufp = buf;
1017}
1018
6291d7e4
AK
1019static void do_subtitle_out(AVFormatContext *s,
1020 OutputStream *ost,
1021 InputStream *ist,
1022 AVSubtitle *sub,
1023 int64_t pts)
1024{
1025 static uint8_t *subtitle_out = NULL;
1026 int subtitle_out_max_size = 1024 * 1024;
1027 int subtitle_out_size, nb, i;
1028 AVCodecContext *enc;
1029 AVPacket pkt;
1030
1031 if (pts == AV_NOPTS_VALUE) {
e3245b26 1032 av_log(NULL, AV_LOG_ERROR, "Subtitle packets must have a pts\n");
6291d7e4
AK
1033 if (exit_on_error)
1034 exit_program(1);
1035 return;
1036 }
1037
1038 enc = ost->st->codec;
1039
1040 if (!subtitle_out) {
1041 subtitle_out = av_malloc(subtitle_out_max_size);
1042 }
1043
1044 /* Note: DVB subtitle need one packet to draw them and one other
1045 packet to clear them */
1046 /* XXX: signal it in the codec context ? */
1047 if (enc->codec_id == CODEC_ID_DVB_SUBTITLE)
1048 nb = 2;
1049 else
1050 nb = 1;
1051
1052 for(i = 0; i < nb; i++) {
1053 sub->pts = av_rescale_q(pts, ist->st->time_base, AV_TIME_BASE_Q);
1054 // start_display_time is required to be 0
1055 sub->pts += av_rescale_q(sub->start_display_time, (AVRational){1, 1000}, AV_TIME_BASE_Q);
1056 sub->end_display_time -= sub->start_display_time;
1057 sub->start_display_time = 0;
1058 subtitle_out_size = avcodec_encode_subtitle(enc, subtitle_out,
1059 subtitle_out_max_size, sub);
1060 if (subtitle_out_size < 0) {
e3245b26 1061 av_log(NULL, AV_LOG_FATAL, "Subtitle encoding failed\n");
6291d7e4
AK
1062 exit_program(1);
1063 }
1064
1065 av_init_packet(&pkt);
1066 pkt.stream_index = ost->index;
1067 pkt.data = subtitle_out;
1068 pkt.size = subtitle_out_size;
1069 pkt.pts = av_rescale_q(sub->pts, AV_TIME_BASE_Q, ost->st->time_base);
1070 if (enc->codec_id == CODEC_ID_DVB_SUBTITLE) {
1071 /* XXX: the pts correction is handled here. Maybe handling
1072 it in the codec would be better */
1073 if (i == 0)
1074 pkt.pts += 90 * sub->start_display_time;
1075 else
1076 pkt.pts += 90 * sub->end_display_time;
1077 }
1078 write_frame(s, &pkt, ost->st->codec, ost->bitstream_filters);
1079 }
1080}
1081
1082static int bit_buffer_size= 1024*256;
1083static uint8_t *bit_buffer= NULL;
1084
87ef060c
AC
1085static void do_video_resample(OutputStream *ost,
1086 InputStream *ist,
1087 AVFrame *in_picture,
1088 AVFrame **out_picture)
6291d7e4 1089{
87ef060c
AC
1090 int resample_changed = 0;
1091 AVCodecContext *dec = ist->st->codec;
1092 *out_picture = in_picture;
6291d7e4
AK
1093
1094 resample_changed = ost->resample_width != dec->width ||
1095 ost->resample_height != dec->height ||
1096 ost->resample_pix_fmt != dec->pix_fmt;
1097
1098 if (resample_changed) {
1099 av_log(NULL, AV_LOG_INFO,
9a414d89 1100 "Input stream #%d:%d frame changed from size:%dx%d fmt:%s to size:%dx%d fmt:%s\n",
6291d7e4
AK
1101 ist->file_index, ist->st->index,
1102 ost->resample_width, ost->resample_height, av_get_pix_fmt_name(ost->resample_pix_fmt),
1103 dec->width , dec->height , av_get_pix_fmt_name(dec->pix_fmt));
1104 if(!ost->video_resample)
5c59fa56 1105 ost->video_resample = 1;
6291d7e4
AK
1106 }
1107
1108#if !CONFIG_AVFILTER
1109 if (ost->video_resample) {
87ef060c 1110 *out_picture = &ost->pict_tmp;
6291d7e4
AK
1111 if (resample_changed) {
1112 /* initialize a new scaler context */
1113 sws_freeContext(ost->img_resample_ctx);
1114 ost->img_resample_ctx = sws_getContext(
1115 ist->st->codec->width,
1116 ist->st->codec->height,
1117 ist->st->codec->pix_fmt,
1118 ost->st->codec->width,
1119 ost->st->codec->height,
1120 ost->st->codec->pix_fmt,
1121 ost->sws_flags, NULL, NULL, NULL);
1122 if (ost->img_resample_ctx == NULL) {
e3245b26 1123 av_log(NULL, AV_LOG_FATAL, "Cannot get resampling context\n");
6291d7e4
AK
1124 exit_program(1);
1125 }
1126 }
87ef060c
AC
1127 sws_scale(ost->img_resample_ctx, in_picture->data, in_picture->linesize,
1128 0, ost->resample_height, (*out_picture)->data, (*out_picture)->linesize);
6291d7e4 1129 }
428c59d9
K
1130#else
1131 if (resample_changed) {
1132 avfilter_graph_free(&ost->graph);
1133 if (configure_video_filters(ist, ost)) {
e3245b26 1134 av_log(NULL, AV_LOG_FATAL, "Error reinitializing filters!\n");
428c59d9
K
1135 exit_program(1);
1136 }
1137 }
6291d7e4 1138#endif
428c59d9
K
1139 if (resample_changed) {
1140 ost->resample_width = dec->width;
1141 ost->resample_height = dec->height;
1142 ost->resample_pix_fmt = dec->pix_fmt;
1143 }
87ef060c
AC
1144}
1145
1146
1147static void do_video_out(AVFormatContext *s,
1148 OutputStream *ost,
1149 InputStream *ist,
1150 AVFrame *in_picture,
1151 int *frame_size, float quality)
1152{
553735f5 1153 int nb_frames, i, ret, format_video_sync;
87ef060c 1154 AVFrame *final_picture;
f593628e 1155 AVCodecContext *enc;
87ef060c
AC
1156 double sync_ipts;
1157
1158 enc = ost->st->codec;
87ef060c
AC
1159
1160 sync_ipts = get_sync_ipts(ost) / av_q2d(enc->time_base);
1161
1162 /* by default, we output a single frame */
1163 nb_frames = 1;
1164
1165 *frame_size = 0;
1166
553735f5
AC
1167 format_video_sync = video_sync_method;
1168 if (format_video_sync < 0)
e1edfbcb
AK
1169 format_video_sync = (s->oformat->flags & AVFMT_NOTIMESTAMPS) ? 0 :
1170 (s->oformat->flags & AVFMT_VARIABLE_FPS) ? 2 : 1;
553735f5
AC
1171
1172 if (format_video_sync) {
87ef060c
AC
1173 double vdelta = sync_ipts - ost->sync_opts;
1174 //FIXME set to 0.5 after we fix some dts/pts bugs like in avidec.c
1175 if (vdelta < -1.1)
1176 nb_frames = 0;
553735f5 1177 else if (format_video_sync == 2) {
87ef060c
AC
1178 if(vdelta<=-0.6){
1179 nb_frames=0;
1180 }else if(vdelta>0.6)
1181 ost->sync_opts= lrintf(sync_ipts);
1182 }else if (vdelta > 1.1)
1183 nb_frames = lrintf(vdelta);
1184//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);
1185 if (nb_frames == 0){
1186 ++nb_frames_drop;
e3245b26 1187 av_log(NULL, AV_LOG_VERBOSE, "*** drop!\n");
87ef060c
AC
1188 }else if (nb_frames > 1) {
1189 nb_frames_dup += nb_frames - 1;
e3245b26 1190 av_log(NULL, AV_LOG_VERBOSE, "*** %d dup!\n", nb_frames-1);
87ef060c
AC
1191 }
1192 }else
1193 ost->sync_opts= lrintf(sync_ipts);
1194
96139b5e 1195 nb_frames = FFMIN(nb_frames, ost->max_frames - ost->frame_number);
87ef060c
AC
1196 if (nb_frames <= 0)
1197 return;
1198
1199 do_video_resample(ost, ist, in_picture, &final_picture);
6291d7e4
AK
1200
1201 /* duplicates frame if needed */
1202 for(i=0;i<nb_frames;i++) {
1203 AVPacket pkt;
1204 av_init_packet(&pkt);
1205 pkt.stream_index= ost->index;
1206
150ddbc1
MR
1207 if (s->oformat->flags & AVFMT_RAWPICTURE &&
1208 enc->codec->id == CODEC_ID_RAWVIDEO) {
6291d7e4 1209 /* raw pictures are written as AVPicture structure to
bb337b4f 1210 avoid any copies. We support temporarily the older
6291d7e4 1211 method. */
f593628e
AC
1212 enc->coded_frame->interlaced_frame = in_picture->interlaced_frame;
1213 enc->coded_frame->top_field_first = in_picture->top_field_first;
6291d7e4
AK
1214 pkt.data= (uint8_t *)final_picture;
1215 pkt.size= sizeof(AVPicture);
1216 pkt.pts= av_rescale_q(ost->sync_opts, enc->time_base, ost->st->time_base);
1217 pkt.flags |= AV_PKT_FLAG_KEY;
1218
1219 write_frame(s, &pkt, ost->st->codec, ost->bitstream_filters);
6291d7e4
AK
1220 } else {
1221 AVFrame big_picture;
1222
1223 big_picture= *final_picture;
1224 /* better than nothing: use input picture interlaced
1225 settings */
1226 big_picture.interlaced_frame = in_picture->interlaced_frame;
1227 if (ost->st->codec->flags & (CODEC_FLAG_INTERLACED_DCT|CODEC_FLAG_INTERLACED_ME)) {
828e0bcb 1228 if (ost->top_field_first == -1)
6291d7e4
AK
1229 big_picture.top_field_first = in_picture->top_field_first;
1230 else
828e0bcb 1231 big_picture.top_field_first = !!ost->top_field_first;
6291d7e4
AK
1232 }
1233
f4ad238c 1234 /* handles same_quant here. This is not correct because it may
6291d7e4
AK
1235 not be a global option */
1236 big_picture.quality = quality;
d242d80e 1237 if (!enc->me_threshold)
6291d7e4
AK
1238 big_picture.pict_type = 0;
1239// big_picture.pts = AV_NOPTS_VALUE;
1240 big_picture.pts= ost->sync_opts;
1241// big_picture.pts= av_rescale(ost->sync_opts, AV_TIME_BASE*(int64_t)enc->time_base.num, enc->time_base.den);
1242//av_log(NULL, AV_LOG_DEBUG, "%"PRId64" -> encoder\n", ost->sync_opts);
1243 if (ost->forced_kf_index < ost->forced_kf_count &&
1244 big_picture.pts >= ost->forced_kf_pts[ost->forced_kf_index]) {
1245 big_picture.pict_type = AV_PICTURE_TYPE_I;
1246 ost->forced_kf_index++;
1247 }
1248 ret = avcodec_encode_video(enc,
1249 bit_buffer, bit_buffer_size,
1250 &big_picture);
1251 if (ret < 0) {
e3245b26 1252 av_log(NULL, AV_LOG_FATAL, "Video encoding failed\n");
6291d7e4
AK
1253 exit_program(1);
1254 }
1255
1256 if(ret>0){
1257 pkt.data= bit_buffer;
1258 pkt.size= ret;
1259 if(enc->coded_frame->pts != AV_NOPTS_VALUE)
1260 pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
1261/*av_log(NULL, AV_LOG_DEBUG, "encoder -> %"PRId64"/%"PRId64"\n",
1262 pkt.pts != AV_NOPTS_VALUE ? av_rescale(pkt.pts, enc->time_base.den, AV_TIME_BASE*(int64_t)enc->time_base.num) : -1,
1263 pkt.dts != AV_NOPTS_VALUE ? av_rescale(pkt.dts, enc->time_base.den, AV_TIME_BASE*(int64_t)enc->time_base.num) : -1);*/
1264
1265 if(enc->coded_frame->key_frame)
1266 pkt.flags |= AV_PKT_FLAG_KEY;
1267 write_frame(s, &pkt, ost->st->codec, ost->bitstream_filters);
1268 *frame_size = ret;
1269 video_size += ret;
1270 //fprintf(stderr,"\nFrame: %3d size: %5d type: %d",
1271 // enc->frame_number-1, ret, enc->pict_type);
1272 /* if two pass, output log */
1273 if (ost->logfile && enc->stats_out) {
1274 fprintf(ost->logfile, "%s", enc->stats_out);
1275 }
1276 }
1277 }
1278 ost->sync_opts++;
1279 ost->frame_number++;
1280 }
1281}
1282
1283static double psnr(double d){
1284 return -10.0*log(d)/log(10.0);
1285}
1286
1287static void do_video_stats(AVFormatContext *os, OutputStream *ost,
1288 int frame_size)
1289{
1290 AVCodecContext *enc;
1291 int frame_number;
1292 double ti1, bitrate, avg_bitrate;
1293
1294 /* this is executed just the first time do_video_stats is called */
1295 if (!vstats_file) {
1296 vstats_file = fopen(vstats_filename, "w");
1297 if (!vstats_file) {
1298 perror("fopen");
1299 exit_program(1);
1300 }
1301 }
1302
1303 enc = ost->st->codec;
1304 if (enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1305 frame_number = ost->frame_number;
1306 fprintf(vstats_file, "frame= %5d q= %2.1f ", frame_number, enc->coded_frame->quality/(float)FF_QP2LAMBDA);
1307 if (enc->flags&CODEC_FLAG_PSNR)
1308 fprintf(vstats_file, "PSNR= %6.2f ", psnr(enc->coded_frame->error[0]/(enc->width*enc->height*255.0*255.0)));
1309
1310 fprintf(vstats_file,"f_size= %6d ", frame_size);
1311 /* compute pts value */
1312 ti1 = ost->sync_opts * av_q2d(enc->time_base);
1313 if (ti1 < 0.01)
1314 ti1 = 0.01;
1315
1316 bitrate = (frame_size * 8) / av_q2d(enc->time_base) / 1000.0;
1317 avg_bitrate = (double)(video_size * 8) / ti1 / 1000.0;
1318 fprintf(vstats_file, "s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
1319 (double)video_size / 1024, ti1, bitrate, avg_bitrate);
1320 fprintf(vstats_file, "type= %c\n", av_get_picture_type_char(enc->coded_frame->pict_type));
1321 }
1322}
1323
af70aa45 1324static void print_report(OutputFile *output_files,
4288e031 1325 OutputStream *ost_table, int nb_ostreams,
c5ad2c2c 1326 int is_last_report, int64_t timer_start)
6291d7e4
AK
1327{
1328 char buf[1024];
1329 OutputStream *ost;
1330 AVFormatContext *oc;
1331 int64_t total_size;
1332 AVCodecContext *enc;
1333 int frame_number, vid, i;
1334 double bitrate, ti1, pts;
1335 static int64_t last_time = -1;
1336 static int qp_histogram[52];
1337
3460dd8a
AK
1338 if (!print_stats && !is_last_report)
1339 return;
1340
6291d7e4
AK
1341 if (!is_last_report) {
1342 int64_t cur_time;
1343 /* display the report every 0.5 seconds */
1344 cur_time = av_gettime();
1345 if (last_time == -1) {
1346 last_time = cur_time;
1347 return;
1348 }
1349 if ((cur_time - last_time) < 500000)
1350 return;
1351 last_time = cur_time;
1352 }
1353
1354
af70aa45 1355 oc = output_files[0].ctx;
6291d7e4
AK
1356
1357 total_size = avio_size(oc->pb);
1358 if(total_size<0) // FIXME improve avio_size() so it works with non seekable output too
1359 total_size= avio_tell(oc->pb);
1360
1361 buf[0] = '\0';
1362 ti1 = 1e10;
1363 vid = 0;
1364 for(i=0;i<nb_ostreams;i++) {
1365 float q = -1;
4288e031 1366 ost = &ost_table[i];
6291d7e4 1367 enc = ost->st->codec;
3d813e4c 1368 if (!ost->stream_copy && enc->coded_frame)
6291d7e4
AK
1369 q = enc->coded_frame->quality/(float)FF_QP2LAMBDA;
1370 if (vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1371 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "q=%2.1f ", q);
1372 }
1373 if (!vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1374 float t = (av_gettime()-timer_start) / 1000000.0;
1375
1376 frame_number = ost->frame_number;
1377 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "frame=%5d fps=%3d q=%3.1f ",
1378 frame_number, (t>1)?(int)(frame_number/t+0.5) : 0, q);
1379 if(is_last_report)
1380 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "L");
1381 if(qp_hist){
1382 int j;
1383 int qp = lrintf(q);
1384 if(qp>=0 && qp<FF_ARRAY_ELEMS(qp_histogram))
1385 qp_histogram[qp]++;
1386 for(j=0; j<32; j++)
1387 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%X", (int)lrintf(log(qp_histogram[j]+1)/log(2)));
1388 }
1389 if (enc->flags&CODEC_FLAG_PSNR){
1390 int j;
1391 double error, error_sum=0;
1392 double scale, scale_sum=0;
1393 char type[3]= {'Y','U','V'};
1394 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "PSNR=");
1395 for(j=0; j<3; j++){
1396 if(is_last_report){
1397 error= enc->error[j];
1398 scale= enc->width*enc->height*255.0*255.0*frame_number;
1399 }else{
1400 error= enc->coded_frame->error[j];
1401 scale= enc->width*enc->height*255.0*255.0;
1402 }
1403 if(j) scale/=4;
1404 error_sum += error;
1405 scale_sum += scale;
1406 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%c:%2.2f ", type[j], psnr(error/scale));
1407 }
1408 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "*:%2.2f ", psnr(error_sum/scale_sum));
1409 }
1410 vid = 1;
1411 }
1412 /* compute min output value */
1413 pts = (double)ost->st->pts.val * av_q2d(ost->st->time_base);
1414 if ((pts < ti1) && (pts > 0))
1415 ti1 = pts;
1416 }
1417 if (ti1 < 0.01)
1418 ti1 = 0.01;
1419
e3245b26 1420 bitrate = (double)(total_size * 8) / ti1 / 1000.0;
6291d7e4 1421
e3245b26 1422 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
6291d7e4
AK
1423 "size=%8.0fkB time=%0.2f bitrate=%6.1fkbits/s",
1424 (double)total_size / 1024, ti1, bitrate);
1425
e3245b26
AK
1426 if (nb_frames_dup || nb_frames_drop)
1427 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), " dup=%d drop=%d",
1428 nb_frames_dup, nb_frames_drop);
6291d7e4 1429
f5646a32 1430 av_log(NULL, AV_LOG_INFO, "%s \r", buf);
6291d7e4 1431
e3245b26 1432 fflush(stderr);
6291d7e4 1433
e3245b26 1434 if (is_last_report) {
6291d7e4 1435 int64_t raw= audio_size + video_size + extra_size;
e3245b26
AK
1436 av_log(NULL, AV_LOG_INFO, "\n");
1437 av_log(NULL, AV_LOG_INFO, "video:%1.0fkB audio:%1.0fkB global headers:%1.0fkB muxing overhead %f%%\n",
1438 video_size/1024.0,
1439 audio_size/1024.0,
1440 extra_size/1024.0,
1441 100.0*(total_size - raw)/raw
6291d7e4
AK
1442 );
1443 }
1444}
1445
b62b5cb6 1446static void flush_encoders(OutputStream *ost_table, int nb_ostreams)
4a4ce2e7
AK
1447{
1448 int i, ret;
1449
1450 for (i = 0; i < nb_ostreams; i++) {
6f1c66d5
AK
1451 OutputStream *ost = &ost_table[i];
1452 AVCodecContext *enc = ost->st->codec;
1453 AVFormatContext *os = output_files[ost->file_index].ctx;
1454
b62b5cb6 1455 if (!ost->encoding_needed)
6f1c66d5
AK
1456 continue;
1457
1458 if (ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO && enc->frame_size <=1)
1459 continue;
150ddbc1 1460 if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO && (os->oformat->flags & AVFMT_RAWPICTURE) && enc->codec->id == CODEC_ID_RAWVIDEO)
6f1c66d5
AK
1461 continue;
1462
1463 for(;;) {
1464 AVPacket pkt;
1465 int fifo_bytes;
1466 av_init_packet(&pkt);
1467 pkt.stream_index= ost->index;
1468
1469 switch (ost->st->codec->codec_type) {
1470 case AVMEDIA_TYPE_AUDIO:
1471 fifo_bytes = av_fifo_size(ost->fifo);
1472 ret = 0;
1473 /* encode any samples remaining in fifo */
1474 if (fifo_bytes > 0) {
1475 int osize = av_get_bytes_per_sample(enc->sample_fmt);
1476 int fs_tmp = enc->frame_size;
1477
1478 av_fifo_generic_read(ost->fifo, audio_buf, fifo_bytes, NULL);
1479 if (enc->codec->capabilities & CODEC_CAP_SMALL_LAST_FRAME) {
1480 enc->frame_size = fifo_bytes / (osize * enc->channels);
1481 } else { /* pad */
1482 int frame_bytes = enc->frame_size*osize*enc->channels;
1483 if (allocated_audio_buf_size < frame_bytes)
4a4ce2e7 1484 exit_program(1);
6f1c66d5 1485 generate_silence(audio_buf+fifo_bytes, enc->sample_fmt, frame_bytes - fifo_bytes);
4a4ce2e7
AK
1486 }
1487
6f1c66d5
AK
1488 ret = avcodec_encode_audio(enc, bit_buffer, bit_buffer_size, (short *)audio_buf);
1489 pkt.duration = av_rescale((int64_t)enc->frame_size*ost->st->time_base.den,
1490 ost->st->time_base.num, enc->sample_rate);
1491 enc->frame_size = fs_tmp;
1492 }
1493 if (ret <= 0) {
1494 ret = avcodec_encode_audio(enc, bit_buffer, bit_buffer_size, NULL);
4a4ce2e7 1495 }
6f1c66d5 1496 if (ret < 0) {
e3245b26 1497 av_log(NULL, AV_LOG_FATAL, "Audio encoding failed\n");
6f1c66d5
AK
1498 exit_program(1);
1499 }
1500 audio_size += ret;
1501 pkt.flags |= AV_PKT_FLAG_KEY;
1502 break;
1503 case AVMEDIA_TYPE_VIDEO:
1504 ret = avcodec_encode_video(enc, bit_buffer, bit_buffer_size, NULL);
1505 if (ret < 0) {
e3245b26 1506 av_log(NULL, AV_LOG_FATAL, "Video encoding failed\n");
6f1c66d5
AK
1507 exit_program(1);
1508 }
1509 video_size += ret;
1510 if(enc->coded_frame && enc->coded_frame->key_frame)
1511 pkt.flags |= AV_PKT_FLAG_KEY;
1512 if (ost->logfile && enc->stats_out) {
1513 fprintf(ost->logfile, "%s", enc->stats_out);
1514 }
1515 break;
1516 default:
1517 ret=-1;
4a4ce2e7 1518 }
6f1c66d5
AK
1519
1520 if (ret <= 0)
1521 break;
1522 pkt.data = bit_buffer;
1523 pkt.size = ret;
1524 if (enc->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)
1525 pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
1526 write_frame(os, &pkt, ost->st->codec, ost->bitstream_filters);
4a4ce2e7
AK
1527 }
1528 }
1529}
1530
7204ec1a
AK
1531/*
1532 * Check whether a packet from ist should be written into ost at this time
1533 */
1534static int check_output_constraints(InputStream *ist, OutputStream *ost)
1535{
1536 OutputFile *of = &output_files[ost->file_index];
1537 int ist_index = ist - input_streams;
1538
1539 if (ost->source_index != ist_index)
1540 return 0;
1541
1542 if (of->start_time && ist->pts < of->start_time)
1543 return 0;
1544
1545 if (of->recording_time != INT64_MAX &&
1546 av_compare_ts(ist->pts, AV_TIME_BASE_Q, of->recording_time + of->start_time,
1547 (AVRational){1, 1000000}) >= 0) {
1548 ost->is_past_recording_time = 1;
1549 return 0;
1550 }
1551
1552 return 1;
1553}
1554
1555static void do_streamcopy(InputStream *ist, OutputStream *ost, const AVPacket *pkt)
1556{
1557 OutputFile *of = &output_files[ost->file_index];
1558 int64_t ost_tb_start_time = av_rescale_q(of->start_time, AV_TIME_BASE_Q, ost->st->time_base);
1559 AVPacket opkt;
1560
1561 av_init_packet(&opkt);
1562
1563 if ((!ost->frame_number && !(pkt->flags & AV_PKT_FLAG_KEY)) &&
1564 !ost->copy_initial_nonkeyframes)
1565 return;
1566
1567 /* force the input stream PTS */
1568 if (ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
1569 audio_size += pkt->size;
1570 else if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
1571 video_size += pkt->size;
1572 ost->sync_opts++;
1573 }
1574
1575 opkt.stream_index = ost->index;
1576 if (pkt->pts != AV_NOPTS_VALUE)
1577 opkt.pts = av_rescale_q(pkt->pts, ist->st->time_base, ost->st->time_base) - ost_tb_start_time;
1578 else
1579 opkt.pts = AV_NOPTS_VALUE;
1580
1581 if (pkt->dts == AV_NOPTS_VALUE)
1582 opkt.dts = av_rescale_q(ist->pts, AV_TIME_BASE_Q, ost->st->time_base);
1583 else
1584 opkt.dts = av_rescale_q(pkt->dts, ist->st->time_base, ost->st->time_base);
1585 opkt.dts -= ost_tb_start_time;
1586
1587 opkt.duration = av_rescale_q(pkt->duration, ist->st->time_base, ost->st->time_base);
1588 opkt.flags = pkt->flags;
1589
1590 //FIXME remove the following 2 lines they shall be replaced by the bitstream filters
1591 if( ost->st->codec->codec_id != CODEC_ID_H264
1592 && ost->st->codec->codec_id != CODEC_ID_MPEG1VIDEO
1593 && ost->st->codec->codec_id != CODEC_ID_MPEG2VIDEO
1594 ) {
1595 if (av_parser_change(ist->st->parser, ost->st->codec, &opkt.data, &opkt.size, pkt->data, pkt->size, pkt->flags & AV_PKT_FLAG_KEY))
1596 opkt.destruct = av_destruct_packet;
1597 } else {
1598 opkt.data = pkt->data;
1599 opkt.size = pkt->size;
1600 }
1601
1602 write_frame(of->ctx, &opkt, ost->st->codec, ost->bitstream_filters);
1603 ost->st->codec->frame_number++;
1604 ost->frame_number++;
1605 av_free_packet(&opkt);
1606}
1607
2a651b71
AK
1608static void rate_emu_sleep(InputStream *ist)
1609{
1610 if (input_files[ist->file_index].rate_emu) {
1611 int64_t pts = av_rescale(ist->pts, 1000000, AV_TIME_BASE);
1612 int64_t now = av_gettime() - ist->start;
1613 if (pts > now)
1614 usleep(pts - now);
1615 }
1616}
1617
ded28ba3
AK
1618static int transcode_audio(InputStream *ist, AVPacket *pkt, int *got_output)
1619{
d1241ff3
JR
1620 AVFrame *decoded_frame;
1621 AVCodecContext *avctx = ist->st->codec;
ded28ba3 1622 int bps = av_get_bytes_per_sample(ist->st->codec->sample_fmt);
ded28ba3
AK
1623 int i, ret;
1624
d1241ff3
JR
1625 if (!(decoded_frame = avcodec_alloc_frame()))
1626 return AVERROR(ENOMEM);
ded28ba3 1627
d1241ff3
JR
1628 ret = avcodec_decode_audio4(avctx, decoded_frame, got_output, pkt);
1629 if (ret < 0) {
1630 av_freep(&decoded_frame);
ded28ba3 1631 return ret;
d1241ff3 1632 }
ded28ba3 1633
ded28ba3
AK
1634 if (!*got_output) {
1635 /* no audio frame */
110d2af2 1636 av_freep(&decoded_frame);
af8ad892 1637 return ret;
ded28ba3
AK
1638 }
1639
d1241ff3
JR
1640 /* if the decoder provides a pts, use it instead of the last packet pts.
1641 the decoder could be delaying output by a packet or more. */
1642 if (decoded_frame->pts != AV_NOPTS_VALUE)
1643 ist->next_pts = decoded_frame->pts;
1644
1645 /* increment next_pts to use for the case where the input stream does not
1646 have timestamps or there are multiple frames in the packet */
1647 ist->next_pts += ((int64_t)AV_TIME_BASE * decoded_frame->nb_samples) /
1648 avctx->sample_rate;
ded28ba3
AK
1649
1650 // preprocess audio (volume)
1651 if (audio_volume != 256) {
d1241ff3
JR
1652 int decoded_data_size = decoded_frame->nb_samples * avctx->channels * bps;
1653 void *samples = decoded_frame->data[0];
1654 switch (avctx->sample_fmt) {
ded28ba3
AK
1655 case AV_SAMPLE_FMT_U8:
1656 {
1657 uint8_t *volp = samples;
1658 for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
1659 int v = (((*volp - 128) * audio_volume + 128) >> 8) + 128;
1660 *volp++ = av_clip_uint8(v);
1661 }
1662 break;
1663 }
1664 case AV_SAMPLE_FMT_S16:
1665 {
1666 int16_t *volp = samples;
1667 for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
1668 int v = ((*volp) * audio_volume + 128) >> 8;
1669 *volp++ = av_clip_int16(v);
1670 }
1671 break;
1672 }
1673 case AV_SAMPLE_FMT_S32:
1674 {
1675 int32_t *volp = samples;
1676 for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
1677 int64_t v = (((int64_t)*volp * audio_volume + 128) >> 8);
1678 *volp++ = av_clipl_int32(v);
1679 }
1680 break;
1681 }
1682 case AV_SAMPLE_FMT_FLT:
1683 {
1684 float *volp = samples;
1685 float scale = audio_volume / 256.f;
1686 for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
1687 *volp++ *= scale;
1688 }
1689 break;
1690 }
1691 case AV_SAMPLE_FMT_DBL:
1692 {
1693 double *volp = samples;
1694 double scale = audio_volume / 256.;
1695 for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
1696 *volp++ *= scale;
1697 }
1698 break;
1699 }
1700 default:
1701 av_log(NULL, AV_LOG_FATAL,
1702 "Audio volume adjustment on sample format %s is not supported.\n",
1703 av_get_sample_fmt_name(ist->st->codec->sample_fmt));
110d2af2 1704 av_freep(&decoded_frame);
ded28ba3
AK
1705 exit_program(1);
1706 }
1707 }
1708
1709 rate_emu_sleep(ist);
1710
1711 for (i = 0; i < nb_output_streams; i++) {
1712 OutputStream *ost = &output_streams[i];
1713
1714 if (!check_output_constraints(ist, ost) || !ost->encoding_needed)
1715 continue;
d1241ff3 1716 do_audio_out(output_files[ost->file_index].ctx, ost, ist, decoded_frame);
ded28ba3 1717 }
110d2af2
JR
1718
1719 av_freep(&decoded_frame);
af8ad892 1720 return ret;
ded28ba3
AK
1721}
1722
45d4b66f
AK
1723static int transcode_video(InputStream *ist, AVPacket *pkt, int *got_output, int64_t *pkt_pts)
1724{
1725 AVFrame *decoded_frame, *filtered_frame = NULL;
1726 void *buffer_to_free = NULL;
1727 int i, ret = 0;
1728 float quality;
1729#if CONFIG_AVFILTER
1730 int frame_available = 1;
1731#endif
1732
1733 if (!(decoded_frame = avcodec_alloc_frame()))
1734 return AVERROR(ENOMEM);
1735 pkt->pts = *pkt_pts;
1736 pkt->dts = ist->pts;
1737 *pkt_pts = AV_NOPTS_VALUE;
1738
1739 ret = avcodec_decode_video2(ist->st->codec,
1740 decoded_frame, got_output, pkt);
1741 if (ret < 0)
1742 goto fail;
1743
1744 quality = same_quant ? decoded_frame->quality : 0;
1745 if (!*got_output) {
1746 /* no picture yet */
1747 av_freep(&decoded_frame);
af8ad892 1748 return ret;
45d4b66f
AK
1749 }
1750 ist->next_pts = ist->pts = guess_correct_pts(&ist->pts_ctx, decoded_frame->pkt_pts,
1751 decoded_frame->pkt_dts);
741a05a2
AK
1752 if (pkt->duration)
1753 ist->next_pts += av_rescale_q(pkt->duration, ist->st->time_base, AV_TIME_BASE_Q);
1754 else if (ist->st->codec->time_base.num != 0) {
45d4b66f
AK
1755 int ticks = ist->st->parser ? ist->st->parser->repeat_pict + 1 :
1756 ist->st->codec->ticks_per_frame;
1757 ist->next_pts += ((int64_t)AV_TIME_BASE *
1758 ist->st->codec->time_base.num * ticks) /
1759 ist->st->codec->time_base.den;
1760 }
1761 pkt->size = 0;
1762 pre_process_video_frame(ist, (AVPicture *)decoded_frame, &buffer_to_free);
1763
1764 rate_emu_sleep(ist);
1765
1766 for (i = 0; i < nb_output_streams; i++) {
1767 OutputStream *ost = &output_streams[i];
1768 int frame_size;
1769
1770 if (!check_output_constraints(ist, ost) || !ost->encoding_needed)
1771 continue;
1772
1773#if CONFIG_AVFILTER
1774 if (ost->input_video_filter) {
1775 AVRational sar;
1776 if (ist->st->sample_aspect_ratio.num)
1777 sar = ist->st->sample_aspect_ratio;
1778 else
1779 sar = ist->st->codec->sample_aspect_ratio;
1780 av_vsrc_buffer_add_frame(ost->input_video_filter, decoded_frame, ist->pts, sar);
1781 if (!(filtered_frame = avcodec_alloc_frame())) {
1782 ret = AVERROR(ENOMEM);
1783 goto fail;
1784 }
1785 frame_available = avfilter_poll_frame(ost->output_video_filter->inputs[0]);
1786 }
1787 while (frame_available) {
1788 AVRational ist_pts_tb;
1789 if (ost->output_video_filter)
1790 get_filtered_video_frame(ost->output_video_filter, filtered_frame, &ost->picref, &ist_pts_tb);
1791 if (ost->picref)
1792 ist->pts = av_rescale_q(ost->picref->pts, ist_pts_tb, AV_TIME_BASE_Q);
1793 if (ost->picref->video && !ost->frame_aspect_ratio)
1794 ost->st->codec->sample_aspect_ratio = ost->picref->video->pixel_aspect;
1795#else
1796 filtered_frame = decoded_frame;
1797#endif
1798
1799 do_video_out(output_files[ost->file_index].ctx, ost, ist, filtered_frame, &frame_size,
1800 same_quant ? quality : ost->st->codec->global_quality);
1801 if (vstats_filename && frame_size)
1802 do_video_stats(output_files[ost->file_index].ctx, ost, frame_size);
1803#if CONFIG_AVFILTER
1804 frame_available = ost->output_video_filter && avfilter_poll_frame(ost->output_video_filter->inputs[0]);
1805 if (ost->picref)
1806 avfilter_unref_buffer(ost->picref);
1807 }
1808 av_freep(&filtered_frame);
1809#endif
1810 }
1811
1812fail:
1813 av_free(buffer_to_free);
1814 av_freep(&decoded_frame);
1815 return ret;
1816}
1817
9595234c
AK
1818static int transcode_subtitles(InputStream *ist, AVPacket *pkt, int *got_output)
1819{
1820 AVSubtitle subtitle;
1821 int i, ret = avcodec_decode_subtitle2(ist->st->codec,
1822 &subtitle, got_output, pkt);
1823 if (ret < 0)
1824 return ret;
1825 if (!*got_output)
af8ad892 1826 return ret;
9595234c
AK
1827
1828 rate_emu_sleep(ist);
1829
1830 for (i = 0; i < nb_output_streams; i++) {
1831 OutputStream *ost = &output_streams[i];
1832
1833 if (!check_output_constraints(ist, ost) || !ost->encoding_needed)
1834 continue;
1835
1836 do_subtitle_out(output_files[ost->file_index].ctx, ost, ist, &subtitle, pkt->pts);
1837 }
1838
1839 avsubtitle_free(&subtitle);
af8ad892 1840 return ret;
9595234c
AK
1841}
1842
6291d7e4 1843/* pkt = NULL means EOF (needed to flush decoder buffers) */
06d4e2fa 1844static int output_packet(InputStream *ist,
4288e031 1845 OutputStream *ost_table, int nb_ostreams,
6291d7e4
AK
1846 const AVPacket *pkt)
1847{
ffa0674e 1848 int i;
6291d7e4 1849 int got_output;
6291d7e4 1850 int64_t pkt_pts = AV_NOPTS_VALUE;
6291d7e4 1851 AVPacket avpkt;
6291d7e4 1852
8b0268a8
AK
1853 if (ist->next_pts == AV_NOPTS_VALUE)
1854 ist->next_pts = ist->pts;
6291d7e4
AK
1855
1856 if (pkt == NULL) {
1857 /* EOF handling */
1858 av_init_packet(&avpkt);
1859 avpkt.data = NULL;
1860 avpkt.size = 0;
1861 goto handle_eof;
1862 } else {
1863 avpkt = *pkt;
1864 }
1865
1866 if(pkt->dts != AV_NOPTS_VALUE)
1867 ist->next_pts = ist->pts = av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);
1868 if(pkt->pts != AV_NOPTS_VALUE)
1869 pkt_pts = av_rescale_q(pkt->pts, ist->st->time_base, AV_TIME_BASE_Q);
1870
1871 //while we have more to decode or while the decoder did output something on EOF
2a651b71 1872 while (ist->decoding_needed && (avpkt.size > 0 || (!pkt && got_output))) {
ffa0674e 1873 int ret = 0;
6291d7e4 1874 handle_eof:
6291d7e4 1875
8b0268a8
AK
1876 ist->pts = ist->next_pts;
1877
1878 if (avpkt.size && avpkt.size != pkt->size) {
e3245b26
AK
1879 av_log(NULL, ist->showed_multi_packet_warning ? AV_LOG_VERBOSE : AV_LOG_WARNING,
1880 "Multiple frames in a packet from stream %d\n", pkt->stream_index);
8b0268a8
AK
1881 ist->showed_multi_packet_warning = 1;
1882 }
6291d7e4 1883
78162b4e 1884 switch(ist->st->codec->codec_type) {
82963f8f
AK
1885 case AVMEDIA_TYPE_AUDIO:
1886 ret = transcode_audio (ist, &avpkt, &got_output);
1887 break;
1888 case AVMEDIA_TYPE_VIDEO:
1889 ret = transcode_video (ist, &avpkt, &got_output, &pkt_pts);
1890 break;
1891 case AVMEDIA_TYPE_SUBTITLE:
1892 ret = transcode_subtitles(ist, &avpkt, &got_output);
1893 break;
78162b4e
AK
1894 default:
1895 return -1;
1896 }
6291d7e4 1897
d3c1d37a
AK
1898 if (ret < 0)
1899 return ret;
aa38cff2
JG
1900 // touch data and size only if not EOF
1901 if (pkt) {
1902 avpkt.data += ret;
1903 avpkt.size -= ret;
1904 }
82963f8f 1905 if (!got_output) {
af8ad892 1906 continue;
82963f8f 1907 }
6291d7e4 1908 }
6291d7e4 1909
7204ec1a 1910 /* handle stream copy */
2a651b71
AK
1911 if (!ist->decoding_needed) {
1912 rate_emu_sleep(ist);
91b412e7 1913 ist->pts = ist->next_pts;
2a651b71
AK
1914 switch (ist->st->codec->codec_type) {
1915 case AVMEDIA_TYPE_AUDIO:
1916 ist->next_pts += ((int64_t)AV_TIME_BASE * ist->st->codec->frame_size) /
1917 ist->st->codec->sample_rate;
1918 break;
1919 case AVMEDIA_TYPE_VIDEO:
1920 if (ist->st->codec->time_base.num != 0) {
1921 int ticks = ist->st->parser ? ist->st->parser->repeat_pict+1 : ist->st->codec->ticks_per_frame;
1922 ist->next_pts += ((int64_t)AV_TIME_BASE *
1923 ist->st->codec->time_base.num * ticks) /
1924 ist->st->codec->time_base.den;
1925 }
1926 break;
1927 }
1928 }
7204ec1a 1929 for (i = 0; pkt && i < nb_ostreams; i++) {
ffa0674e 1930 OutputStream *ost = &ost_table[i];
7204ec1a
AK
1931
1932 if (!check_output_constraints(ist, ost) || ost->encoding_needed)
1933 continue;
1934
1935 do_streamcopy(ist, ost, pkt);
1936 }
1937
6291d7e4
AK
1938 return 0;
1939}
1940
af70aa45 1941static void print_sdp(OutputFile *output_files, int n)
6291d7e4
AK
1942{
1943 char sdp[2048];
af70aa45
AK
1944 int i;
1945 AVFormatContext **avc = av_malloc(sizeof(*avc)*n);
1946
1947 if (!avc)
1948 exit_program(1);
1949 for (i = 0; i < n; i++)
1950 avc[i] = output_files[i].ctx;
6291d7e4
AK
1951
1952 av_sdp_create(avc, n, sdp, sizeof(sdp));
1953 printf("SDP:\n%s\n", sdp);
1954 fflush(stdout);
af70aa45 1955 av_freep(&avc);
6291d7e4
AK
1956}
1957
630902a1
AK
1958static int init_input_stream(int ist_index, OutputStream *output_streams, int nb_output_streams,
1959 char *error, int error_len)
1960{
1961 int i;
1962 InputStream *ist = &input_streams[ist_index];
1963 if (ist->decoding_needed) {
1964 AVCodec *codec = ist->dec;
630902a1 1965 if (!codec) {
9a414d89 1966 snprintf(error, error_len, "Decoder (codec id %d) not found for input stream #%d:%d",
630902a1
AK
1967 ist->st->codec->codec_id, ist->file_index, ist->st->index);
1968 return AVERROR(EINVAL);
1969 }
1970
1971 /* update requested sample format for the decoder based on the
1972 corresponding encoder sample format */
1973 for (i = 0; i < nb_output_streams; i++) {
1974 OutputStream *ost = &output_streams[i];
1975 if (ost->source_index == ist_index) {
1976 update_sample_fmt(ist->st->codec, codec, ost->st->codec);
1977 break;
1978 }
1979 }
1980
1981 if (avcodec_open2(ist->st->codec, codec, &ist->opts) < 0) {
9a414d89 1982 snprintf(error, error_len, "Error while opening decoder for input stream #%d:%d",
630902a1
AK
1983 ist->file_index, ist->st->index);
1984 return AVERROR(EINVAL);
1985 }
1986 assert_codec_experimental(ist->st->codec, 0);
1987 assert_avoptions(ist->opts);
1988 }
1989
1990 ist->pts = ist->st->avg_frame_rate.num ? - ist->st->codec->has_b_frames*AV_TIME_BASE / av_q2d(ist->st->avg_frame_rate) : 0;
1991 ist->next_pts = AV_NOPTS_VALUE;
1992 init_pts_correction(&ist->pts_ctx);
1993 ist->is_start = 1;
1994
1995 return 0;
1996}
1997
eaf2d37a
AC
1998static int transcode_init(OutputFile *output_files,
1999 int nb_output_files,
2000 InputFile *input_files,
2001 int nb_input_files)
6291d7e4 2002{
2c474ddb 2003 int ret = 0, i, j, k;
1bb77e51 2004 AVFormatContext *oc;
6291d7e4 2005 AVCodecContext *codec, *icodec;
4288e031 2006 OutputStream *ost;
6291d7e4
AK
2007 InputStream *ist;
2008 char error[1024];
2009 int want_sdp = 1;
b0c9e8e0 2010
f4805328
AK
2011 /* init framerate emulation */
2012 for (i = 0; i < nb_input_files; i++) {
2013 InputFile *ifile = &input_files[i];
2014 if (ifile->rate_emu)
2015 for (j = 0; j < ifile->nb_streams; j++)
2016 input_streams[j + ifile->ist_index].start = av_gettime();
2017 }
6291d7e4
AK
2018
2019 /* output stream init */
03f30c83 2020 for (i = 0; i < nb_output_files; i++) {
1bb77e51
AK
2021 oc = output_files[i].ctx;
2022 if (!oc->nb_streams && !(oc->oformat->flags & AVFMT_NOSTREAMS)) {
2023 av_dump_format(oc, i, oc->filename, 1);
e3245b26 2024 av_log(NULL, AV_LOG_ERROR, "Output file #%d does not contain any stream\n", i);
eaf2d37a 2025 return AVERROR(EINVAL);
6291d7e4 2026 }
6291d7e4
AK
2027 }
2028
2029 /* for each output stream, we compute the right encoding parameters */
4288e031
AK
2030 for (i = 0; i < nb_output_streams; i++) {
2031 ost = &output_streams[i];
03f30c83 2032 oc = output_files[ost->file_index].ctx;
6291d7e4
AK
2033 ist = &input_streams[ost->source_index];
2034
4dbc6cee
AK
2035 if (ost->attachment_filename)
2036 continue;
2037
03f30c83 2038 codec = ost->st->codec;
6291d7e4
AK
2039 icodec = ist->st->codec;
2040
03f30c83
AK
2041 ost->st->disposition = ist->st->disposition;
2042 codec->bits_per_raw_sample = icodec->bits_per_raw_sample;
6291d7e4
AK
2043 codec->chroma_sample_location = icodec->chroma_sample_location;
2044
3d813e4c 2045 if (ost->stream_copy) {
6291d7e4
AK
2046 uint64_t extra_size = (uint64_t)icodec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE;
2047
e6d2b737 2048 if (extra_size > INT_MAX) {
eaf2d37a 2049 return AVERROR(EINVAL);
e6d2b737 2050 }
6291d7e4
AK
2051
2052 /* if stream_copy is selected, no need to decode or encode */
03f30c83 2053 codec->codec_id = icodec->codec_id;
6291d7e4
AK
2054 codec->codec_type = icodec->codec_type;
2055
03f30c83
AK
2056 if (!codec->codec_tag) {
2057 if (!oc->oformat->codec_tag ||
2058 av_codec_get_id (oc->oformat->codec_tag, icodec->codec_tag) == codec->codec_id ||
2059 av_codec_get_tag(oc->oformat->codec_tag, icodec->codec_id) <= 0)
6291d7e4
AK
2060 codec->codec_tag = icodec->codec_tag;
2061 }
2062
03f30c83 2063 codec->bit_rate = icodec->bit_rate;
6291d7e4
AK
2064 codec->rc_max_rate = icodec->rc_max_rate;
2065 codec->rc_buffer_size = icodec->rc_buffer_size;
03f30c83 2066 codec->extradata = av_mallocz(extra_size);
e6d2b737 2067 if (!codec->extradata) {
eaf2d37a 2068 return AVERROR(ENOMEM);
e6d2b737 2069 }
6291d7e4 2070 memcpy(codec->extradata, icodec->extradata, icodec->extradata_size);
03f30c83 2071 codec->extradata_size = icodec->extradata_size;
7bb3e625 2072 if (!copy_tb) {
03f30c83 2073 codec->time_base = icodec->time_base;
6291d7e4
AK
2074 codec->time_base.num *= icodec->ticks_per_frame;
2075 av_reduce(&codec->time_base.num, &codec->time_base.den,
2076 codec->time_base.num, codec->time_base.den, INT_MAX);
03f30c83 2077 } else
6291d7e4 2078 codec->time_base = ist->st->time_base;
03f30c83 2079
6291d7e4
AK
2080 switch(codec->codec_type) {
2081 case AVMEDIA_TYPE_AUDIO:
2082 if(audio_volume != 256) {
e3245b26 2083 av_log(NULL, AV_LOG_FATAL, "-acodec copy and -vol are incompatible (frames are not decoded)\n");
6291d7e4
AK
2084 exit_program(1);
2085 }
03f30c83
AK
2086 codec->channel_layout = icodec->channel_layout;
2087 codec->sample_rate = icodec->sample_rate;
2088 codec->channels = icodec->channels;
2089 codec->frame_size = icodec->frame_size;
6291d7e4 2090 codec->audio_service_type = icodec->audio_service_type;
03f30c83 2091 codec->block_align = icodec->block_align;
6291d7e4
AK
2092 break;
2093 case AVMEDIA_TYPE_VIDEO:
03f30c83
AK
2094 codec->pix_fmt = icodec->pix_fmt;
2095 codec->width = icodec->width;
2096 codec->height = icodec->height;
2097 codec->has_b_frames = icodec->has_b_frames;
6291d7e4 2098 if (!codec->sample_aspect_ratio.num) {
03f30c83 2099 codec->sample_aspect_ratio =
6291d7e4
AK
2100 ost->st->sample_aspect_ratio =
2101 ist->st->sample_aspect_ratio.num ? ist->st->sample_aspect_ratio :
2102 ist->st->codec->sample_aspect_ratio.num ?
2103 ist->st->codec->sample_aspect_ratio : (AVRational){0, 1};
2104 }
2105 break;
2106 case AVMEDIA_TYPE_SUBTITLE:
03f30c83 2107 codec->width = icodec->width;
6291d7e4
AK
2108 codec->height = icodec->height;
2109 break;
2110 case AVMEDIA_TYPE_DATA:
3ccd1580 2111 case AVMEDIA_TYPE_ATTACHMENT:
6291d7e4
AK
2112 break;
2113 default:
2114 abort();
2115 }
2116 } else {
2117 if (!ost->enc)
2118 ost->enc = avcodec_find_encoder(ost->st->codec->codec_id);
03f30c83 2119
11fdb7e1
AK
2120 ist->decoding_needed = 1;
2121 ost->encoding_needed = 1;
03f30c83 2122
6291d7e4
AK
2123 switch(codec->codec_type) {
2124 case AVMEDIA_TYPE_AUDIO:
03f30c83 2125 ost->fifo = av_fifo_alloc(1024);
e6d2b737 2126 if (!ost->fifo) {
eaf2d37a 2127 return AVERROR(ENOMEM);
e6d2b737 2128 }
6291d7e4 2129 ost->reformat_pair = MAKE_SFMT_PAIR(AV_SAMPLE_FMT_NONE,AV_SAMPLE_FMT_NONE);
03f30c83 2130
d0a19696 2131 if (!codec->sample_rate)
6291d7e4 2132 codec->sample_rate = icodec->sample_rate;
6291d7e4
AK
2133 choose_sample_rate(ost->st, ost->enc);
2134 codec->time_base = (AVRational){1, codec->sample_rate};
03f30c83 2135
6291d7e4
AK
2136 if (codec->sample_fmt == AV_SAMPLE_FMT_NONE)
2137 codec->sample_fmt = icodec->sample_fmt;
2138 choose_sample_fmt(ost->st, ost->enc);
03f30c83 2139
6291d7e4
AK
2140 if (!codec->channels)
2141 codec->channels = icodec->channels;
2142 codec->channel_layout = icodec->channel_layout;
2143 if (av_get_channel_layout_nb_channels(codec->channel_layout) != codec->channels)
2144 codec->channel_layout = 0;
03f30c83
AK
2145
2146 ost->audio_resample = codec-> sample_rate != icodec->sample_rate || audio_sync_method > 1;
2147 icodec->request_channels = codec-> channels;
6291d7e4
AK
2148 ost->resample_sample_fmt = icodec->sample_fmt;
2149 ost->resample_sample_rate = icodec->sample_rate;
2150 ost->resample_channels = icodec->channels;
2151 break;
2152 case AVMEDIA_TYPE_VIDEO:
2153 if (codec->pix_fmt == PIX_FMT_NONE)
2154 codec->pix_fmt = icodec->pix_fmt;
2155 choose_pixel_fmt(ost->st, ost->enc);
2156
2157 if (ost->st->codec->pix_fmt == PIX_FMT_NONE) {
e3245b26 2158 av_log(NULL, AV_LOG_FATAL, "Video pixel format is unknown, stream cannot be encoded\n");
6291d7e4
AK
2159 exit_program(1);
2160 }
2161
2162 if (!codec->width || !codec->height) {
2163 codec->width = icodec->width;
2164 codec->height = icodec->height;
2165 }
2166
2167 ost->video_resample = codec->width != icodec->width ||
2168 codec->height != icodec->height ||
2169 codec->pix_fmt != icodec->pix_fmt;
2170 if (ost->video_resample) {
2171#if !CONFIG_AVFILTER
2172 avcodec_get_frame_defaults(&ost->pict_tmp);
2173 if(avpicture_alloc((AVPicture*)&ost->pict_tmp, codec->pix_fmt,
2174 codec->width, codec->height)) {
e3245b26 2175 av_log(NULL, AV_LOG_FATAL, "Cannot allocate temp picture, check pix fmt\n");
6291d7e4
AK
2176 exit_program(1);
2177 }
2178 ost->img_resample_ctx = sws_getContext(
2179 icodec->width,
2180 icodec->height,
2181 icodec->pix_fmt,
2182 codec->width,
2183 codec->height,
2184 codec->pix_fmt,
2185 ost->sws_flags, NULL, NULL, NULL);
2186 if (ost->img_resample_ctx == NULL) {
e3245b26 2187 av_log(NULL, AV_LOG_FATAL, "Cannot get resampling context\n");
6291d7e4
AK
2188 exit_program(1);
2189 }
2190#endif
2191 codec->bits_per_raw_sample= 0;
2192 }
2193
03f30c83
AK
2194 ost->resample_height = icodec->height;
2195 ost->resample_width = icodec->width;
2196 ost->resample_pix_fmt = icodec->pix_fmt;
6291d7e4
AK
2197
2198 if (!ost->frame_rate.num)
2199 ost->frame_rate = ist->st->r_frame_rate.num ? ist->st->r_frame_rate : (AVRational){25,1};
bef737a7 2200 if (ost->enc && ost->enc->supported_framerates && !ost->force_fps) {
6291d7e4
AK
2201 int idx = av_find_nearest_q_idx(ost->frame_rate, ost->enc->supported_framerates);
2202 ost->frame_rate = ost->enc->supported_framerates[idx];
2203 }
2204 codec->time_base = (AVRational){ost->frame_rate.den, ost->frame_rate.num};
2205
2206#if CONFIG_AVFILTER
2207 if (configure_video_filters(ist, ost)) {
e3245b26 2208 av_log(NULL, AV_LOG_FATAL, "Error opening filters!\n");
6291d7e4
AK
2209 exit(1);
2210 }
2211#endif
2212 break;
2213 case AVMEDIA_TYPE_SUBTITLE:
6291d7e4
AK
2214 break;
2215 default:
2216 abort();
2217 break;
2218 }
2219 /* two pass mode */
515901fa 2220 if ((codec->flags & (CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2))) {
6291d7e4
AK
2221 char logfilename[1024];
2222 FILE *f;
2223
2224 snprintf(logfilename, sizeof(logfilename), "%s-%d.log",
2225 pass_logfilename_prefix ? pass_logfilename_prefix : DEFAULT_PASS_LOGFILENAME_PREFIX,
2226 i);
2227 if (codec->flags & CODEC_FLAG_PASS1) {
2228 f = fopen(logfilename, "wb");
2229 if (!f) {
e3245b26
AK
2230 av_log(NULL, AV_LOG_FATAL, "Cannot write log file '%s' for pass-1 encoding: %s\n",
2231 logfilename, strerror(errno));
6291d7e4
AK
2232 exit_program(1);
2233 }
2234 ost->logfile = f;
2235 } else {
2236 char *logbuffer;
2237 size_t logbuffer_size;
02170990 2238 if (cmdutils_read_file(logfilename, &logbuffer, &logbuffer_size) < 0) {
e3245b26
AK
2239 av_log(NULL, AV_LOG_FATAL, "Error reading log file '%s' for pass-2 encoding\n",
2240 logfilename);
6291d7e4
AK
2241 exit_program(1);
2242 }
2243 codec->stats_in = logbuffer;
2244 }
2245 }
2246 }
2247 if(codec->codec_type == AVMEDIA_TYPE_VIDEO){
03f30c83
AK
2248 int size = codec->width * codec->height;
2249 bit_buffer_size = FFMAX(bit_buffer_size, 6*size + 200);
6291d7e4
AK
2250 }
2251 }
2252
2253 if (!bit_buffer)
2254 bit_buffer = av_malloc(bit_buffer_size);
2255 if (!bit_buffer) {
e3245b26
AK
2256 av_log(NULL, AV_LOG_ERROR, "Cannot allocate %d bytes output buffer\n",
2257 bit_buffer_size);
eaf2d37a 2258 return AVERROR(ENOMEM);
6291d7e4
AK
2259 }
2260
2261 /* open each encoder */
4288e031
AK
2262 for (i = 0; i < nb_output_streams; i++) {
2263 ost = &output_streams[i];
6291d7e4 2264 if (ost->encoding_needed) {
03f30c83 2265 AVCodec *codec = ost->enc;
6291d7e4
AK
2266 AVCodecContext *dec = input_streams[ost->source_index].st->codec;
2267 if (!codec) {
9a414d89 2268 snprintf(error, sizeof(error), "Encoder (codec id %d) not found for output stream #%d:%d",
6291d7e4
AK
2269 ost->st->codec->codec_id, ost->file_index, ost->index);
2270 ret = AVERROR(EINVAL);
2271 goto dump_format;
2272 }
2273 if (dec->subtitle_header) {
2274 ost->st->codec->subtitle_header = av_malloc(dec->subtitle_header_size);
2275 if (!ost->st->codec->subtitle_header) {
2276 ret = AVERROR(ENOMEM);
2277 goto dump_format;
2278 }
2279 memcpy(ost->st->codec->subtitle_header, dec->subtitle_header, dec->subtitle_header_size);
2280 ost->st->codec->subtitle_header_size = dec->subtitle_header_size;
2281 }
2282 if (avcodec_open2(ost->st->codec, codec, &ost->opts) < 0) {
9a414d89 2283 snprintf(error, sizeof(error), "Error while opening encoder for output stream #%d:%d - maybe incorrect parameters such as bit_rate, rate, width or height",
6291d7e4
AK
2284 ost->file_index, ost->index);
2285 ret = AVERROR(EINVAL);
2286 goto dump_format;
2287 }
2288 assert_codec_experimental(ost->st->codec, 1);
2289 assert_avoptions(ost->opts);
2290 if (ost->st->codec->bit_rate && ost->st->codec->bit_rate < 1000)
2291 av_log(NULL, AV_LOG_WARNING, "The bitrate parameter is set too low."
2292 "It takes bits/s as argument, not kbits/s\n");
2293 extra_size += ost->st->codec->extradata_size;
d242d80e
AK
2294
2295 if (ost->st->codec->me_threshold)
2296 input_streams[ost->source_index].st->codec->debug |= FF_DEBUG_MV;
6291d7e4
AK
2297 }
2298 }
2299
630902a1
AK
2300 /* init input streams */
2301 for (i = 0; i < nb_input_streams; i++)
62486948 2302 if ((ret = init_input_stream(i, output_streams, nb_output_streams, error, sizeof(error))) < 0)
630902a1 2303 goto dump_format;
6291d7e4 2304
2c474ddb
AK
2305 /* discard unused programs */
2306 for (i = 0; i < nb_input_files; i++) {
2307 InputFile *ifile = &input_files[i];
2308 for (j = 0; j < ifile->ctx->nb_programs; j++) {
2309 AVProgram *p = ifile->ctx->programs[j];
2310 int discard = AVDISCARD_ALL;
2311
2312 for (k = 0; k < p->nb_stream_indexes; k++)
2313 if (!input_streams[ifile->ist_index + p->stream_index[k]].discard) {
2314 discard = AVDISCARD_DEFAULT;
2315 break;
2316 }
2317 p->discard = discard;
2318 }
2319 }
2320
6291d7e4 2321 /* open files and write file headers */
af70aa45 2322 for (i = 0; i < nb_output_files; i++) {
1bb77e51
AK
2323 oc = output_files[i].ctx;
2324 oc->interrupt_callback = int_cb;
2325 if (avformat_write_header(oc, &output_files[i].opts) < 0) {
6291d7e4
AK
2326 snprintf(error, sizeof(error), "Could not write header for output file #%d (incorrect codec parameters ?)", i);
2327 ret = AVERROR(EINVAL);
2328 goto dump_format;
2329 }
af70aa45 2330 assert_avoptions(output_files[i].opts);
1bb77e51 2331 if (strcmp(oc->oformat->name, "rtp")) {
6291d7e4
AK
2332 want_sdp = 0;
2333 }
2334 }
2335
2336 dump_format:
2337 /* dump the file output parameters - cannot be done before in case
2338 of stream copy */
03f30c83 2339 for (i = 0; i < nb_output_files; i++) {
af70aa45 2340 av_dump_format(output_files[i].ctx, i, output_files[i].ctx->filename, 1);
6291d7e4
AK
2341 }
2342
2343 /* dump the stream mapping */
e3245b26
AK
2344 av_log(NULL, AV_LOG_INFO, "Stream mapping:\n");
2345 for (i = 0; i < nb_output_streams; i++) {
2346 ost = &output_streams[i];
4dbc6cee
AK
2347
2348 if (ost->attachment_filename) {
2349 /* an attached file */
2350 av_log(NULL, AV_LOG_INFO, " File %s -> Stream #%d:%d\n",
2351 ost->attachment_filename, ost->file_index, ost->index);
2352 continue;
2353 }
9a414d89 2354 av_log(NULL, AV_LOG_INFO, " Stream #%d:%d -> #%d:%d",
e3245b26
AK
2355 input_streams[ost->source_index].file_index,
2356 input_streams[ost->source_index].st->index,
2357 ost->file_index,
2358 ost->index);
2359 if (ost->sync_ist != &input_streams[ost->source_index])
9a414d89 2360 av_log(NULL, AV_LOG_INFO, " [sync #%d:%d]",
e3245b26
AK
2361 ost->sync_ist->file_index,
2362 ost->sync_ist->st->index);
3d813e4c 2363 if (ost->stream_copy)
e3245b26
AK
2364 av_log(NULL, AV_LOG_INFO, " (copy)");
2365 else
2366 av_log(NULL, AV_LOG_INFO, " (%s -> %s)", input_streams[ost->source_index].dec ?
2367 input_streams[ost->source_index].dec->name : "?",
2368 ost->enc ? ost->enc->name : "?");
2369 av_log(NULL, AV_LOG_INFO, "\n");
6291d7e4
AK
2370 }
2371
2372 if (ret) {
e3245b26 2373 av_log(NULL, AV_LOG_ERROR, "%s\n", error);
eaf2d37a 2374 return ret;
6291d7e4
AK
2375 }
2376
2377 if (want_sdp) {
2378 print_sdp(output_files, nb_output_files);
2379 }
2380
eaf2d37a
AC
2381 return 0;
2382}
2383
2384/*
2385 * The following code is the main loop of the file converter
2386 */
2387static int transcode(OutputFile *output_files,
2388 int nb_output_files,
2389 InputFile *input_files,
2390 int nb_input_files)
2391{
2392 int ret, i;
2393 AVFormatContext *is, *os;
2394 OutputStream *ost;
2395 InputStream *ist;
2396 uint8_t *no_packet;
2397 int no_packet_count=0;
2398 int64_t timer_start;
2399
2400 if (!(no_packet = av_mallocz(nb_input_files)))
2401 exit_program(1);
2402
2403 ret = transcode_init(output_files, nb_output_files, input_files, nb_input_files);
2404 if (ret < 0)
2405 goto fail;
2406
e3245b26 2407 av_log(NULL, AV_LOG_INFO, "Press ctrl-c to stop encoding\n");
6291d7e4
AK
2408 term_init();
2409
2410 timer_start = av_gettime();
2411
2412 for(; received_sigterm == 0;) {
2413 int file_index, ist_index;
2414 AVPacket pkt;
9be3c124 2415 int64_t ipts_min;
6291d7e4
AK
2416 double opts_min;
2417
9be3c124 2418 ipts_min = INT64_MAX;
6291d7e4
AK
2419 opts_min= 1e100;
2420
2421 /* select the stream that we must read now by looking at the
2422 smallest output pts */
2423 file_index = -1;
4288e031 2424 for (i = 0; i < nb_output_streams; i++) {
f21f294e 2425 OutputFile *of;
9be3c124
AC
2426 int64_t ipts;
2427 double opts;
4288e031 2428 ost = &output_streams[i];
f21f294e 2429 of = &output_files[ost->file_index];
af70aa45 2430 os = output_files[ost->file_index].ctx;
6291d7e4 2431 ist = &input_streams[ost->source_index];
f21f294e
AK
2432 if (ost->is_past_recording_time || no_packet[ist->file_index] ||
2433 (os->pb && avio_tell(os->pb) >= of->limit_filesize))
6291d7e4 2434 continue;
c0931508 2435 opts = ost->st->pts.val * av_q2d(ost->st->time_base);
9be3c124 2436 ipts = ist->pts;
6291d7e4
AK
2437 if (!input_files[ist->file_index].eof_reached){
2438 if(ipts < ipts_min) {
2439 ipts_min = ipts;
2440 if(input_sync ) file_index = ist->file_index;
2441 }
2442 if(opts < opts_min) {
2443 opts_min = opts;
2444 if(!input_sync) file_index = ist->file_index;
2445 }
2446 }
96139b5e
AK
2447 if (ost->frame_number >= ost->max_frames) {
2448 int j;
9b921a82
AK
2449 for (j = 0; j < of->ctx->nb_streams; j++)
2450 output_streams[of->ost_index + j].is_past_recording_time = 1;
96139b5e 2451 continue;
6291d7e4
AK
2452 }
2453 }
2454 /* if none, if is finished */
2455 if (file_index < 0) {
2456 if(no_packet_count){
2457 no_packet_count=0;
b0c9e8e0 2458 memset(no_packet, 0, nb_input_files);
6291d7e4
AK
2459 usleep(10000);
2460 continue;
2461 }
2462 break;
2463 }
2464
6291d7e4
AK
2465 /* read a frame from it and output it in the fifo */
2466 is = input_files[file_index].ctx;
2467 ret= av_read_frame(is, &pkt);
2468 if(ret == AVERROR(EAGAIN)){
2469 no_packet[file_index]=1;
2470 no_packet_count++;
2471 continue;
2472 }
2473 if (ret < 0) {
2474 input_files[file_index].eof_reached = 1;
2475 if (opt_shortest)
2476 break;
2477 else
2478 continue;
2479 }
2480
2481 no_packet_count=0;
b0c9e8e0 2482 memset(no_packet, 0, nb_input_files);
6291d7e4
AK
2483
2484 if (do_pkt_dump) {
2485 av_pkt_dump_log2(NULL, AV_LOG_DEBUG, &pkt, do_hex_dump,
2486 is->streams[pkt.stream_index]);
2487 }
2488 /* the following test is needed in case new streams appear
2489 dynamically in stream : we ignore them */
ed5b1326 2490 if (pkt.stream_index >= input_files[file_index].nb_streams)
6291d7e4
AK
2491 goto discard_packet;
2492 ist_index = input_files[file_index].ist_index + pkt.stream_index;
2493 ist = &input_streams[ist_index];
2494 if (ist->discard)
2495 goto discard_packet;
2496
2497 if (pkt.dts != AV_NOPTS_VALUE)
2498 pkt.dts += av_rescale_q(input_files[ist->file_index].ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
2499 if (pkt.pts != AV_NOPTS_VALUE)
2500 pkt.pts += av_rescale_q(input_files[ist->file_index].ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
2501
33f75d72
AK
2502 if(pkt.pts != AV_NOPTS_VALUE)
2503 pkt.pts *= ist->ts_scale;
2504 if(pkt.dts != AV_NOPTS_VALUE)
2505 pkt.dts *= ist->ts_scale;
6291d7e4
AK
2506
2507// fprintf(stderr, "next:%"PRId64" dts:%"PRId64" off:%"PRId64" %d\n", ist->next_pts, pkt.dts, input_files[ist->file_index].ts_offset, ist->st->codec->codec_type);
2508 if (pkt.dts != AV_NOPTS_VALUE && ist->next_pts != AV_NOPTS_VALUE
2509 && (is->iformat->flags & AVFMT_TS_DISCONT)) {
2510 int64_t pkt_dts= av_rescale_q(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q);
2511 int64_t delta= pkt_dts - ist->next_pts;
2512 if((FFABS(delta) > 1LL*dts_delta_threshold*AV_TIME_BASE || pkt_dts+1<ist->pts)&& !copy_ts){
2513 input_files[ist->file_index].ts_offset -= delta;
e3245b26
AK
2514 av_log(NULL, AV_LOG_DEBUG, "timestamp discontinuity %"PRId64", new offset= %"PRId64"\n",
2515 delta, input_files[ist->file_index].ts_offset);
6291d7e4
AK
2516 pkt.dts-= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
2517 if(pkt.pts != AV_NOPTS_VALUE)
2518 pkt.pts-= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
2519 }
2520 }
2521
6291d7e4 2522 //fprintf(stderr,"read #%d.%d size=%d\n", ist->file_index, ist->st->index, pkt.size);
06d4e2fa 2523 if (output_packet(ist, output_streams, nb_output_streams, &pkt) < 0) {
6291d7e4 2524
9a414d89 2525 av_log(NULL, AV_LOG_ERROR, "Error while decoding stream #%d:%d\n",
e3245b26 2526 ist->file_index, ist->st->index);
6291d7e4
AK
2527 if (exit_on_error)
2528 exit_program(1);
2529 av_free_packet(&pkt);
b9630bcf 2530 continue;
6291d7e4
AK
2531 }
2532
2533 discard_packet:
2534 av_free_packet(&pkt);
2535
2536 /* dump report by using the output first video and audio streams */
c5ad2c2c 2537 print_report(output_files, output_streams, nb_output_streams, 0, timer_start);
6291d7e4
AK
2538 }
2539
2540 /* at the end of stream, we must flush the decoder buffers */
2541 for (i = 0; i < nb_input_streams; i++) {
2542 ist = &input_streams[i];
2543 if (ist->decoding_needed) {
06d4e2fa 2544 output_packet(ist, output_streams, nb_output_streams, NULL);
6291d7e4
AK
2545 }
2546 }
b62b5cb6 2547 flush_encoders(output_streams, nb_output_streams);
6291d7e4
AK
2548
2549 term_exit();
2550
2551 /* write the trailer if needed and close file */
2552 for(i=0;i<nb_output_files;i++) {
af70aa45 2553 os = output_files[i].ctx;
6291d7e4
AK
2554 av_write_trailer(os);
2555 }
2556
2557 /* dump report by using the first video and audio streams */
c5ad2c2c 2558 print_report(output_files, output_streams, nb_output_streams, 1, timer_start);
6291d7e4
AK
2559
2560 /* close each encoder */
4288e031
AK
2561 for (i = 0; i < nb_output_streams; i++) {
2562 ost = &output_streams[i];
6291d7e4
AK
2563 if (ost->encoding_needed) {
2564 av_freep(&ost->st->codec->stats_in);
2565 avcodec_close(ost->st->codec);
2566 }
2567#if CONFIG_AVFILTER
2568 avfilter_graph_free(&ost->graph);
2569#endif
2570 }
2571
2572 /* close each decoder */
2573 for (i = 0; i < nb_input_streams; i++) {
2574 ist = &input_streams[i];
2575 if (ist->decoding_needed) {
2576 avcodec_close(ist->st->codec);
2577 }
2578 }
2579
2580 /* finished ! */
2581 ret = 0;
2582
2583 fail:
2584 av_freep(&bit_buffer);
b0c9e8e0 2585 av_freep(&no_packet);
6291d7e4 2586
4288e031
AK
2587 if (output_streams) {
2588 for (i = 0; i < nb_output_streams; i++) {
2589 ost = &output_streams[i];
6291d7e4 2590 if (ost) {
3d813e4c 2591 if (ost->stream_copy)
6291d7e4
AK
2592 av_freep(&ost->st->codec->extradata);
2593 if (ost->logfile) {
2594 fclose(ost->logfile);
2595 ost->logfile = NULL;
2596 }
2597 av_fifo_free(ost->fifo); /* works even if fifo is not
2598 initialized but set to zero */
2599 av_freep(&ost->st->codec->subtitle_header);
2600 av_free(ost->pict_tmp.data[0]);
2601 av_free(ost->forced_kf_pts);
2602 if (ost->video_resample)
2603 sws_freeContext(ost->img_resample_ctx);
2604 if (ost->resample)
2605 audio_resample_close(ost->resample);
2606 if (ost->reformat_ctx)
2607 av_audio_convert_free(ost->reformat_ctx);
2608 av_dict_free(&ost->opts);
6291d7e4
AK
2609 }
2610 }
6291d7e4
AK
2611 }
2612 return ret;
2613}
2614
ca46fde7 2615static double parse_frame_aspect_ratio(const char *arg)
6291d7e4
AK
2616{
2617 int x = 0, y = 0;
2618 double ar = 0;
2619 const char *p;
2620 char *end;
2621
2622 p = strchr(arg, ':');
2623 if (p) {
2624 x = strtol(arg, &end, 10);
2625 if (end == p)
2626 y = strtol(end+1, &end, 10);
2627 if (x > 0 && y > 0)
2628 ar = (double)x / (double)y;
2629 } else
2630 ar = strtod(arg, NULL);
2631
2632 if (!ar) {
e3245b26 2633 av_log(NULL, AV_LOG_FATAL, "Incorrect aspect ratio specification.\n");
ca46fde7 2634 exit_program(1);
6291d7e4 2635 }
ca46fde7 2636 return ar;
6291d7e4
AK
2637}
2638
35e6f8c1 2639static int opt_audio_codec(OptionsContext *o, const char *opt, const char *arg)
6291d7e4 2640{
35e6f8c1 2641 return parse_option(o, "codec:a", arg, options);
6291d7e4
AK
2642}
2643
35e6f8c1 2644static int opt_video_codec(OptionsContext *o, const char *opt, const char *arg)
6291d7e4 2645{
35e6f8c1 2646 return parse_option(o, "codec:v", arg, options);
6291d7e4
AK
2647}
2648
35e6f8c1 2649static int opt_subtitle_codec(OptionsContext *o, const char *opt, const char *arg)
6291d7e4 2650{
35e6f8c1 2651 return parse_option(o, "codec:s", arg, options);
6291d7e4
AK
2652}
2653
35e6f8c1 2654static int opt_data_codec(OptionsContext *o, const char *opt, const char *arg)
6291d7e4 2655{
35e6f8c1 2656 return parse_option(o, "codec:d", arg, options);
6291d7e4
AK
2657}
2658
575ec4e1 2659static int opt_map(OptionsContext *o, const char *opt, const char *arg)
6291d7e4 2660{
8d2e4a7e
AK
2661 StreamMap *m = NULL;
2662 int i, negative = 0, file_idx;
2663 int sync_file_idx = -1, sync_stream_idx;
2664 char *p, *sync;
2665 char *map;
6291d7e4 2666
8d2e4a7e
AK
2667 if (*arg == '-') {
2668 negative = 1;
2669 arg++;
2670 }
2671 map = av_strdup(arg);
6291d7e4 2672
8d2e4a7e
AK
2673 /* parse sync stream first, just pick first matching stream */
2674 if (sync = strchr(map, ',')) {
2675 *sync = 0;
2676 sync_file_idx = strtol(sync + 1, &sync, 0);
2677 if (sync_file_idx >= nb_input_files || sync_file_idx < 0) {
f24facd3 2678 av_log(NULL, AV_LOG_FATAL, "Invalid sync file index: %d.\n", sync_file_idx);
8d2e4a7e
AK
2679 exit_program(1);
2680 }
2681 if (*sync)
2682 sync++;
ed5b1326 2683 for (i = 0; i < input_files[sync_file_idx].nb_streams; i++)
8d2e4a7e
AK
2684 if (check_stream_specifier(input_files[sync_file_idx].ctx,
2685 input_files[sync_file_idx].ctx->streams[i], sync) == 1) {
2686 sync_stream_idx = i;
2687 break;
2688 }
ed5b1326 2689 if (i == input_files[sync_file_idx].nb_streams) {
f24facd3 2690 av_log(NULL, AV_LOG_FATAL, "Sync stream specification in map %s does not "
8d2e4a7e
AK
2691 "match any streams.\n", arg);
2692 exit_program(1);
2693 }
2694 }
6291d7e4 2695
8d2e4a7e
AK
2696
2697 file_idx = strtol(map, &p, 0);
2698 if (file_idx >= nb_input_files || file_idx < 0) {
f24facd3 2699 av_log(NULL, AV_LOG_FATAL, "Invalid input file index: %d.\n", file_idx);
8d2e4a7e 2700 exit_program(1);
6291d7e4 2701 }
8d2e4a7e
AK
2702 if (negative)
2703 /* disable some already defined maps */
575ec4e1
AK
2704 for (i = 0; i < o->nb_stream_maps; i++) {
2705 m = &o->stream_maps[i];
e6674f68
AK
2706 if (file_idx == m->file_index &&
2707 check_stream_specifier(input_files[m->file_index].ctx,
8d2e4a7e
AK
2708 input_files[m->file_index].ctx->streams[m->stream_index],
2709 *p == ':' ? p + 1 : p) > 0)
2710 m->disabled = 1;
2711 }
2712 else
ed5b1326 2713 for (i = 0; i < input_files[file_idx].nb_streams; i++) {
8d2e4a7e
AK
2714 if (check_stream_specifier(input_files[file_idx].ctx, input_files[file_idx].ctx->streams[i],
2715 *p == ':' ? p + 1 : p) <= 0)
2716 continue;
575ec4e1
AK
2717 o->stream_maps = grow_array(o->stream_maps, sizeof(*o->stream_maps),
2718 &o->nb_stream_maps, o->nb_stream_maps + 1);
2719 m = &o->stream_maps[o->nb_stream_maps - 1];
8d2e4a7e
AK
2720
2721 m->file_index = file_idx;
2722 m->stream_index = i;
2723
2724 if (sync_file_idx >= 0) {
2725 m->sync_file_index = sync_file_idx;
2726 m->sync_stream_index = sync_stream_idx;
2727 } else {
2728 m->sync_file_index = file_idx;
2729 m->sync_stream_index = i;
2730 }
2731 }
2732
2733 if (!m) {
f24facd3 2734 av_log(NULL, AV_LOG_FATAL, "Stream map '%s' matches no streams.\n", arg);
8d2e4a7e
AK
2735 exit_program(1);
2736 }
2737
2738 av_freep(&map);
6291d7e4
AK
2739 return 0;
2740}
2741
4dbc6cee
AK
2742static int opt_attach(OptionsContext *o, const char *opt, const char *arg)
2743{
2744 o->attachments = grow_array(o->attachments, sizeof(*o->attachments),
2745 &o->nb_attachments, o->nb_attachments + 1);
2746 o->attachments[o->nb_attachments - 1] = arg;
2747 return 0;
2748}
2749
e6e6060c 2750static void parse_meta_type(char *arg, char *type, int *index)
6291d7e4 2751{
039267f1 2752 if (*arg) {
a2a38d96 2753 *type = *arg;
6291d7e4
AK
2754 switch (*arg) {
2755 case 'g':
2756 break;
2757 case 's':
2758 case 'c':
2759 case 'p':
e6e6060c
AK
2760 if (*(++arg) == ':')
2761 *index = strtol(++arg, NULL, 0);
6291d7e4
AK
2762 break;
2763 default:
e3245b26 2764 av_log(NULL, AV_LOG_FATAL, "Invalid metadata type %c.\n", *arg);
6291d7e4
AK
2765 exit_program(1);
2766 }
2767 } else
2768 *type = 'g';
2769}
2770
847529f8 2771static int opt_map_metadata(OptionsContext *o, const char *opt, const char *arg)
6291d7e4
AK
2772{
2773 MetadataMap *m, *m1;
2774 char *p;
2775
847529f8
AK
2776 o->meta_data_maps = grow_array(o->meta_data_maps, sizeof(*o->meta_data_maps),
2777 &o->nb_meta_data_maps, o->nb_meta_data_maps + 1);
6291d7e4 2778
847529f8 2779 m = &o->meta_data_maps[o->nb_meta_data_maps - 1][1];
6291d7e4 2780 m->file = strtol(arg, &p, 0);
039267f1 2781 parse_meta_type(*p ? p + 1 : p, &m->type, &m->index);
6291d7e4 2782
847529f8 2783 m1 = &o->meta_data_maps[o->nb_meta_data_maps - 1][0];
e6e6060c 2784 if (p = strchr(opt, ':'))
039267f1 2785 parse_meta_type(p + 1, &m1->type, &m1->index);
e6e6060c
AK
2786 else
2787 m1->type = 'g';
6291d7e4
AK
2788
2789 if (m->type == 'g' || m1->type == 'g')
847529f8 2790 o->metadata_global_manual = 1;
6291d7e4 2791 if (m->type == 's' || m1->type == 's')
847529f8 2792 o->metadata_streams_manual = 1;
6291d7e4 2793 if (m->type == 'c' || m1->type == 'c')
847529f8 2794 o->metadata_chapters_manual = 1;
6291d7e4
AK
2795
2796 return 0;
2797}
2798
1b648c7c 2799static AVCodec *find_codec_or_die(const char *name, enum AVMediaType type, int encoder)
169f0647
AK
2800{
2801 const char *codec_string = encoder ? "encoder" : "decoder";
2802 AVCodec *codec;
2803
169f0647
AK
2804 codec = encoder ?
2805 avcodec_find_encoder_by_name(name) :
2806 avcodec_find_decoder_by_name(name);
2807 if(!codec) {
f24facd3 2808 av_log(NULL, AV_LOG_FATAL, "Unknown %s '%s'\n", codec_string, name);
169f0647
AK
2809 exit_program(1);
2810 }
2811 if(codec->type != type) {
f24facd3 2812 av_log(NULL, AV_LOG_FATAL, "Invalid %s type '%s'\n", codec_string, name);
169f0647
AK
2813 exit_program(1);
2814 }
1b648c7c 2815 return codec;
169f0647
AK
2816}
2817
1b648c7c 2818static AVCodec *choose_decoder(OptionsContext *o, AVFormatContext *s, AVStream *st)
169f0647 2819{
169f0647 2820 char *codec_name = NULL;
169f0647 2821
35e6f8c1 2822 MATCH_PER_STREAM_OPT(codec_names, str, codec_name, s, st);
1b648c7c
AK
2823 if (codec_name) {
2824 AVCodec *codec = find_codec_or_die(codec_name, st->codec->codec_type, 0);
2825 st->codec->codec_id = codec->id;
2826 return codec;
2827 } else
2828 return avcodec_find_decoder(st->codec->codec_id);
169f0647 2829}
6291d7e4 2830
88867844
AK
2831/**
2832 * Add all the streams from the given input file to the global
2833 * list of input streams.
2834 */
35e6f8c1 2835static void add_input_streams(OptionsContext *o, AVFormatContext *ic)
88867844 2836{
33f75d72 2837 int i, rfps, rfps_base;
88867844
AK
2838
2839 for (i = 0; i < ic->nb_streams; i++) {
2840 AVStream *st = ic->streams[i];
2841 AVCodecContext *dec = st->codec;
2842 InputStream *ist;
2843
88867844
AK
2844 input_streams = grow_array(input_streams, sizeof(*input_streams), &nb_input_streams, nb_input_streams + 1);
2845 ist = &input_streams[nb_input_streams - 1];
2846 ist->st = st;
2847 ist->file_index = nb_input_files;
2848 ist->discard = 1;
2849 ist->opts = filter_codec_opts(codec_opts, ist->st->codec->codec_id, ic, st);
2850
059fb8c8
AK
2851 ist->ts_scale = 1.0;
2852 MATCH_PER_STREAM_OPT(ts_scale, dbl, ist->ts_scale, ic, st);
88867844 2853
1b648c7c 2854 ist->dec = choose_decoder(o, ic, st);
88867844
AK
2855
2856 switch (dec->codec_type) {
2857 case AVMEDIA_TYPE_AUDIO:
2130981a 2858 if (o->audio_disable)
88867844
AK
2859 st->discard= AVDISCARD_ALL;
2860 break;
2861 case AVMEDIA_TYPE_VIDEO:
2862 rfps = ic->streams[i]->r_frame_rate.num;
2863 rfps_base = ic->streams[i]->r_frame_rate.den;
2864 if (dec->lowres) {
2865 dec->flags |= CODEC_FLAG_EMU_EDGE;
2866 dec->height >>= dec->lowres;
2867 dec->width >>= dec->lowres;
2868 }
88867844
AK
2869
2870 if (dec->time_base.den != rfps*dec->ticks_per_frame || dec->time_base.num != rfps_base) {
2871
e3245b26
AK
2872 av_log(NULL, AV_LOG_INFO,"\nSeems stream %d codec frame rate differs from container frame rate: %2.2f (%d/%d) -> %2.2f (%d/%d)\n",
2873 i, (float)dec->time_base.den / dec->time_base.num, dec->time_base.den, dec->time_base.num,
2874 (float)rfps / rfps_base, rfps, rfps_base);
88867844
AK
2875 }
2876
2130981a 2877 if (o->video_disable)
88867844
AK
2878 st->discard= AVDISCARD_ALL;
2879 else if(video_discard)
2880 st->discard= video_discard;
2881 break;
2882 case AVMEDIA_TYPE_DATA:
2883 break;
2884 case AVMEDIA_TYPE_SUBTITLE:
2130981a 2885 if (o->subtitle_disable)
88867844
AK
2886 st->discard = AVDISCARD_ALL;
2887 break;
2888 case AVMEDIA_TYPE_ATTACHMENT:
2889 case AVMEDIA_TYPE_UNKNOWN:
2890 break;
2891 default:
2892 abort();
2893 }
2894 }
2895}
2896
a2c0b830
AK
2897static void assert_file_overwrite(const char *filename)
2898{
2899 if (!file_overwrite &&
2900 (strchr(filename, ':') == NULL || filename[1] == ':' ||
2901 av_strstart(filename, "file:", NULL))) {
2902 if (avio_check(filename, 0) == 0) {
2903 if (!using_stdin) {
2904 fprintf(stderr,"File '%s' already exists. Overwrite ? [y/N] ", filename);
2905 fflush(stderr);
2906 if (!read_yesno()) {
2907 fprintf(stderr, "Not overwriting - exiting\n");
2908 exit_program(1);
2909 }
2910 }
2911 else {
2912 fprintf(stderr,"File '%s' already exists. Exiting.\n", filename);
2913 exit_program(1);
2914 }
2915 }
2916 }
2917}
2918
2919static void dump_attachment(AVStream *st, const char *filename)
2920{
2921 int ret;
2922 AVIOContext *out = NULL;
2923 AVDictionaryEntry *e;
2924
2925 if (!st->codec->extradata_size) {
2926 av_log(NULL, AV_LOG_WARNING, "No extradata to dump in stream #%d:%d.\n",
2927 nb_input_files - 1, st->index);
2928 return;
2929 }
2930 if (!*filename && (e = av_dict_get(st->metadata, "filename", NULL, 0)))
2931 filename = e->value;
2932 if (!*filename) {
2933 av_log(NULL, AV_LOG_FATAL, "No filename specified and no 'filename' tag"
2934 "in stream #%d:%d.\n", nb_input_files - 1, st->index);
2935 exit_program(1);
2936 }
2937
2938 assert_file_overwrite(filename);
2939
2abe947a 2940 if ((ret = avio_open2(&out, filename, AVIO_FLAG_WRITE, &int_cb, NULL)) < 0) {
a2c0b830
AK
2941 av_log(NULL, AV_LOG_FATAL, "Could not open file %s for writing.\n",
2942 filename);
2943 exit_program(1);
2944 }
2945
2946 avio_write(out, st->codec->extradata, st->codec->extradata_size);
2947 avio_flush(out);
2948 avio_close(out);
2949}
2950
575ec4e1 2951static int opt_input_file(OptionsContext *o, const char *opt, const char *filename)
6291d7e4
AK
2952{
2953 AVFormatContext *ic;
2954 AVInputFormat *file_iformat = NULL;
88867844 2955 int err, i, ret;
6291d7e4
AK
2956 int64_t timestamp;
2957 uint8_t buf[128];
2958 AVDictionary **opts;
2959 int orig_nb_streams; // number of streams before avformat_find_stream_info
2960
7041bb3b
AK
2961 if (o->format) {
2962 if (!(file_iformat = av_find_input_format(o->format))) {
e3245b26 2963 av_log(NULL, AV_LOG_FATAL, "Unknown input format: '%s'\n", o->format);
6291d7e4
AK
2964 exit_program(1);
2965 }
6291d7e4
AK
2966 }
2967
2968 if (!strcmp(filename, "-"))
2969 filename = "pipe:";
2970
2971 using_stdin |= !strncmp(filename, "pipe:", 5) ||
2972 !strcmp(filename, "/dev/stdin");
2973
2974 /* get default parameters from command line */
2975 ic = avformat_alloc_context();
2976 if (!ic) {
2977 print_error(filename, AVERROR(ENOMEM));
2978 exit_program(1);
2979 }
e2469ccf
AK
2980 if (o->nb_audio_sample_rate) {
2981 snprintf(buf, sizeof(buf), "%d", o->audio_sample_rate[o->nb_audio_sample_rate - 1].u.i);
6291d7e4
AK
2982 av_dict_set(&format_opts, "sample_rate", buf, 0);
2983 }
6a11686d
AK
2984 if (o->nb_audio_channels) {
2985 snprintf(buf, sizeof(buf), "%d", o->audio_channels[o->nb_audio_channels - 1].u.i);
6291d7e4
AK
2986 av_dict_set(&format_opts, "channels", buf, 0);
2987 }
91ea4811
AK
2988 if (o->nb_frame_rates) {
2989 av_dict_set(&format_opts, "framerate", o->frame_rates[o->nb_frame_rates - 1].u.str, 0);
6291d7e4 2990 }
d4397b03
AK
2991 if (o->nb_frame_sizes) {
2992 av_dict_set(&format_opts, "video_size", o->frame_sizes[o->nb_frame_sizes - 1].u.str, 0);
6291d7e4 2993 }
b2254d83
AK
2994 if (o->nb_frame_pix_fmts)
2995 av_dict_set(&format_opts, "pixel_format", o->frame_pix_fmts[o->nb_frame_pix_fmts - 1].u.str, 0);
6291d7e4 2996
6291d7e4 2997 ic->flags |= AVFMT_FLAG_NONBLOCK;
2abe947a 2998 ic->interrupt_callback = int_cb;
6291d7e4
AK
2999
3000 /* open the input file with generic libav function */
3001 err = avformat_open_input(&ic, filename, file_iformat, &format_opts);
3002 if (err < 0) {
3003 print_error(filename, err);
3004 exit_program(1);
3005 }
3006 assert_avoptions(format_opts);
3007
92f1940e
AK
3008 /* apply forced codec ids */
3009 for (i = 0; i < ic->nb_streams; i++)
1b648c7c 3010 choose_decoder(o, ic, ic->streams[i]);
92f1940e 3011
6291d7e4
AK
3012 /* Set AVCodecContext options for avformat_find_stream_info */
3013 opts = setup_find_stream_info_opts(ic, codec_opts);
3014 orig_nb_streams = ic->nb_streams;
3015
3016 /* If not enough info to get the stream parameters, we decode the
3017 first frames to get it. (used in mpeg case for example) */
3018 ret = avformat_find_stream_info(ic, opts);
e3245b26
AK
3019 if (ret < 0) {
3020 av_log(NULL, AV_LOG_FATAL, "%s: could not find codec parameters\n", filename);
6291d7e4
AK
3021 av_close_input_file(ic);
3022 exit_program(1);
3023 }
3024
6b779ccc 3025 timestamp = o->start_time;
6291d7e4
AK
3026 /* add the stream start time */
3027 if (ic->start_time != AV_NOPTS_VALUE)
3028 timestamp += ic->start_time;
3029
3030 /* if seeking requested, we execute it */
6b779ccc 3031 if (o->start_time != 0) {
6291d7e4
AK
3032 ret = av_seek_frame(ic, -1, timestamp, AVSEEK_FLAG_BACKWARD);
3033 if (ret < 0) {
e3245b26
AK
3034 av_log(NULL, AV_LOG_WARNING, "%s: could not seek to position %0.3f\n",
3035 filename, (double)timestamp / AV_TIME_BASE);
6291d7e4 3036 }
6291d7e4
AK
3037 }
3038
3039 /* update the current parameters so that they match the one of the input stream */
35e6f8c1 3040 add_input_streams(o, ic);
6291d7e4
AK
3041
3042 /* dump the file content */
e3245b26 3043 av_dump_format(ic, nb_input_files, filename, 0);
6291d7e4
AK
3044
3045 input_files = grow_array(input_files, sizeof(*input_files), &nb_input_files, nb_input_files + 1);
3046 input_files[nb_input_files - 1].ctx = ic;
3047 input_files[nb_input_files - 1].ist_index = nb_input_streams - ic->nb_streams;
6b779ccc 3048 input_files[nb_input_files - 1].ts_offset = o->input_ts_offset - (copy_ts ? 0 : timestamp);
ed5b1326 3049 input_files[nb_input_files - 1].nb_streams = ic->nb_streams;
dc3e76f3 3050 input_files[nb_input_files - 1].rate_emu = o->rate_emu;
6291d7e4 3051
a2c0b830
AK
3052 for (i = 0; i < o->nb_dump_attachment; i++) {
3053 int j;
3054
3055 for (j = 0; j < ic->nb_streams; j++) {
3056 AVStream *st = ic->streams[j];
3057
3058 if (check_stream_specifier(ic, st, o->dump_attachment[i].specifier) == 1)
3059 dump_attachment(st, o->dump_attachment[i].u.str);
3060 }
3061 }
3062
6291d7e4
AK
3063 for (i = 0; i < orig_nb_streams; i++)
3064 av_dict_free(&opts[i]);
3065 av_freep(&opts);
575ec4e1
AK
3066
3067 reset_options(o);
6291d7e4
AK
3068 return 0;
3069}
3070
f233cfed
AK
3071static void parse_forced_key_frames(char *kf, OutputStream *ost,
3072 AVCodecContext *avctx)
3073{
3074 char *p;
3075 int n = 1, i;
3076 int64_t t;
3077
3078 for (p = kf; *p; p++)
3079 if (*p == ',')
3080 n++;
3081 ost->forced_kf_count = n;
3082 ost->forced_kf_pts = av_malloc(sizeof(*ost->forced_kf_pts) * n);
3083 if (!ost->forced_kf_pts) {
3084 av_log(NULL, AV_LOG_FATAL, "Could not allocate forced key frames array.\n");
3085 exit_program(1);
3086 }
3087 for (i = 0; i < n; i++) {
3088 p = i ? strchr(p, ',') + 1 : kf;
3089 t = parse_time_or_die("force_key_frames", p, 1);
3090 ost->forced_kf_pts[i] = av_rescale_q(t, AV_TIME_BASE_Q, avctx->time_base);
3091 }
3092}
3093
3ec34462
AK
3094static uint8_t *get_line(AVIOContext *s)
3095{
3096 AVIOContext *line;
3097 uint8_t *buf;
3098 char c;
3099
3100 if (avio_open_dyn_buf(&line) < 0) {
3101 av_log(NULL, AV_LOG_FATAL, "Could not alloc buffer for reading preset.\n");
3102 exit_program(1);
3103 }
3104
3105 while ((c = avio_r8(s)) && c != '\n')
3106 avio_w8(line, c);
3107 avio_w8(line, 0);
3108 avio_close_dyn_buf(line, &buf);
3109
3110 return buf;
3111}
3112
3113static int get_preset_file_2(const char *preset_name, const char *codec_name, AVIOContext **s)
3114{
3115 int i, ret = 1;
3116 char filename[1000];
3117 const char *base[3] = { getenv("AVCONV_DATADIR"),
3118 getenv("HOME"),
3119 AVCONV_DATADIR,
3120 };
3121
3122 for (i = 0; i < FF_ARRAY_ELEMS(base) && ret; i++) {
3123 if (!base[i])
3124 continue;
3125 if (codec_name) {
3126 snprintf(filename, sizeof(filename), "%s%s/%s-%s.avpreset", base[i],
3127 i != 1 ? "" : "/.avconv", codec_name, preset_name);
2abe947a 3128 ret = avio_open2(s, filename, AVIO_FLAG_READ, &int_cb, NULL);
3ec34462
AK
3129 }
3130 if (ret) {
3131 snprintf(filename, sizeof(filename), "%s%s/%s.avpreset", base[i],
3132 i != 1 ? "" : "/.avconv", preset_name);
2abe947a 3133 ret = avio_open2(s, filename, AVIO_FLAG_READ, &int_cb, NULL);
3ec34462
AK
3134 }
3135 }
3136 return ret;
3137}
3138
1b648c7c
AK
3139static void choose_encoder(OptionsContext *o, AVFormatContext *s, OutputStream *ost)
3140{
3141 char *codec_name = NULL;
3142
3143 MATCH_PER_STREAM_OPT(codec_names, str, codec_name, s, ost->st);
3144 if (!codec_name) {
3145 ost->st->codec->codec_id = av_guess_codec(s->oformat, NULL, s->filename,
3146 NULL, ost->st->codec->codec_type);
3147 ost->enc = avcodec_find_encoder(ost->st->codec->codec_id);
3148 } else if (!strcmp(codec_name, "copy"))
3d813e4c 3149 ost->stream_copy = 1;
1b648c7c
AK
3150 else {
3151 ost->enc = find_codec_or_die(codec_name, ost->st->codec->codec_type, 1);
3152 ost->st->codec->codec_id = ost->enc->id;
3153 }
3154}
3155
35e6f8c1 3156static OutputStream *new_output_stream(OptionsContext *o, AVFormatContext *oc, enum AVMediaType type)
169f0647
AK
3157{
3158 OutputStream *ost;
84ad31ff 3159 AVStream *st = avformat_new_stream(oc, NULL);
3ec34462 3160 int idx = oc->nb_streams - 1, ret = 0;
013887eb 3161 char *bsf = NULL, *next, *codec_tag = NULL;
d821cbe2 3162 AVBitStreamFilterContext *bsfc, *bsfc_prev = NULL;
77d9c454 3163 double qscale = -1;
3ec34462
AK
3164 char *buf = NULL, *arg = NULL, *preset = NULL;
3165 AVIOContext *s = NULL;
169f0647
AK
3166
3167 if (!st) {
f24facd3 3168 av_log(NULL, AV_LOG_FATAL, "Could not alloc stream.\n");
169f0647
AK
3169 exit_program(1);
3170 }
3171
84ad31ff
AK
3172 if (oc->nb_streams - 1 < o->nb_streamid_map)
3173 st->id = o->streamid_map[oc->nb_streams - 1];
3174
4288e031
AK
3175 output_streams = grow_array(output_streams, sizeof(*output_streams), &nb_output_streams,
3176 nb_output_streams + 1);
3177 ost = &output_streams[nb_output_streams - 1];
40fc2810 3178 ost->file_index = nb_output_files;
169f0647
AK
3179 ost->index = idx;
3180 ost->st = st;
3181 st->codec->codec_type = type;
1b648c7c 3182 choose_encoder(o, oc, ost);
169f0647
AK
3183 if (ost->enc) {
3184 ost->opts = filter_codec_opts(codec_opts, ost->enc->id, oc, st);
3185 }
3186
3187 avcodec_get_context_defaults3(st->codec, ost->enc);
3188 st->codec->codec_type = type; // XXX hack, avcodec_get_context_defaults2() sets type to unknown for stream copy
3189
3ec34462
AK
3190 MATCH_PER_STREAM_OPT(presets, str, preset, oc, st);
3191 if (preset && (!(ret = get_preset_file_2(preset, ost->enc->name, &s)))) {
3192 do {
3193 buf = get_line(s);
3194 if (!buf[0] || buf[0] == '#') {
3195 av_free(buf);
3196 continue;
3197 }
3198 if (!(arg = strchr(buf, '='))) {
3199 av_log(NULL, AV_LOG_FATAL, "Invalid line found in the preset file.\n");
3200 exit_program(1);
3201 }
3202 *arg++ = 0;
3203 av_dict_set(&ost->opts, buf, arg, AV_DICT_DONT_OVERWRITE);
3204 av_free(buf);
3205 } while (!s->eof_reached);
3206 avio_close(s);
3207 }
3208 if (ret) {
3209 av_log(NULL, AV_LOG_FATAL,
3210 "Preset %s specified for stream %d:%d, but could not be opened.\n",
3211 preset, ost->file_index, ost->index);
3212 exit_program(1);
3213 }
3214
059fb8c8
AK
3215 ost->max_frames = INT64_MAX;
3216 MATCH_PER_STREAM_OPT(max_frames, i64, ost->max_frames, oc, st);
96139b5e 3217
d821cbe2
AK
3218 MATCH_PER_STREAM_OPT(bitstream_filters, str, bsf, oc, st);
3219 while (bsf) {
3220 if (next = strchr(bsf, ','))
3221 *next++ = 0;
3222 if (!(bsfc = av_bitstream_filter_init(bsf))) {
f24facd3 3223 av_log(NULL, AV_LOG_FATAL, "Unknown bitstream filter %s\n", bsf);
d821cbe2
AK
3224 exit_program(1);
3225 }
3226 if (bsfc_prev)
3227 bsfc_prev->next = bsfc;
3228 else
3229 ost->bitstream_filters = bsfc;
3230
3231 bsfc_prev = bsfc;
3232 bsf = next;
3233 }
3234
013887eb
AK
3235 MATCH_PER_STREAM_OPT(codec_tags, str, codec_tag, oc, st);
3236 if (codec_tag) {
3237 uint32_t tag = strtol(codec_tag, &next, 0);
3238 if (*next)
3239 tag = AV_RL32(codec_tag);
3240 st->codec->codec_tag = tag;
3241 }
3242
77d9c454
AK
3243 MATCH_PER_STREAM_OPT(qscale, dbl, qscale, oc, st);
3244 if (qscale >= 0 || same_quant) {
3245 st->codec->flags |= CODEC_FLAG_QSCALE;
3246 st->codec->global_quality = FF_QP2LAMBDA * qscale;
3247 }
3248
becdce99
AK
3249 if (oc->oformat->flags & AVFMT_GLOBALHEADER)
3250 st->codec->flags |= CODEC_FLAG_GLOBAL_HEADER;
3251
3b3ea346 3252 av_opt_get_int(sws_opts, "sws_flags", 0, &ost->sws_flags);
169f0647
AK
3253 return ost;
3254}
3255
2c2cff16
AK
3256static void parse_matrix_coeffs(uint16_t *dest, const char *str)
3257{
3258 int i;
3259 const char *p = str;
3260 for(i = 0;; i++) {
3261 dest[i] = atoi(p);
3262 if(i == 63)
3263 break;
3264 p = strchr(p, ',');
3265 if(!p) {
e3245b26 3266 av_log(NULL, AV_LOG_FATAL, "Syntax error in matrix \"%s\" at coeff %d\n", str, i);
2c2cff16
AK
3267 exit_program(1);
3268 }
3269 p++;
3270 }
3271}
3272
35e6f8c1 3273static OutputStream *new_video_stream(OptionsContext *o, AVFormatContext *oc)
6291d7e4
AK
3274{
3275 AVStream *st;
3276 OutputStream *ost;
3277 AVCodecContext *video_enc;
6291d7e4 3278
35e6f8c1 3279 ost = new_output_stream(o, oc, AVMEDIA_TYPE_VIDEO);
6291d7e4 3280 st = ost->st;
6291d7e4
AK
3281 video_enc = st->codec;
3282
3d813e4c 3283 if (!ost->stream_copy) {
0e68c783 3284 const char *p = NULL;
d4397b03 3285 char *forced_key_frames = NULL, *frame_rate = NULL, *frame_size = NULL;
b2254d83 3286 char *frame_aspect_ratio = NULL, *frame_pix_fmt = NULL;
8e5ce590 3287 char *intra_matrix = NULL, *inter_matrix = NULL, *filters = NULL;
059fb8c8 3288 int i;
6291d7e4 3289
91ea4811
AK
3290 MATCH_PER_STREAM_OPT(frame_rates, str, frame_rate, oc, st);
3291 if (frame_rate && av_parse_video_rate(&ost->frame_rate, frame_rate) < 0) {
f24facd3 3292 av_log(NULL, AV_LOG_FATAL, "Invalid framerate value: %s\n", frame_rate);
91ea4811
AK
3293 exit_program(1);
3294 }
6291d7e4 3295
d4397b03
AK
3296 MATCH_PER_STREAM_OPT(frame_sizes, str, frame_size, oc, st);
3297 if (frame_size && av_parse_video_size(&video_enc->width, &video_enc->height, frame_size) < 0) {
f24facd3 3298 av_log(NULL, AV_LOG_FATAL, "Invalid frame size: %s.\n", frame_size);
d4397b03
AK
3299 exit_program(1);
3300 }
3301
ca46fde7
AK
3302 MATCH_PER_STREAM_OPT(frame_aspect_ratios, str, frame_aspect_ratio, oc, st);
3303 if (frame_aspect_ratio)
3304 ost->frame_aspect_ratio = parse_frame_aspect_ratio(frame_aspect_ratio);
3305
b2254d83
AK
3306 MATCH_PER_STREAM_OPT(frame_pix_fmts, str, frame_pix_fmt, oc, st);
3307 if (frame_pix_fmt && (video_enc->pix_fmt = av_get_pix_fmt(frame_pix_fmt)) == PIX_FMT_NONE) {
f24facd3 3308 av_log(NULL, AV_LOG_FATAL, "Unknown pixel format requested: %s.\n", frame_pix_fmt);
b2254d83
AK
3309 exit_program(1);
3310 }
6291d7e4
AK
3311 st->sample_aspect_ratio = video_enc->sample_aspect_ratio;
3312
2c2cff16
AK
3313 MATCH_PER_STREAM_OPT(intra_matrices, str, intra_matrix, oc, st);
3314 if (intra_matrix) {
3315 if (!(video_enc->intra_matrix = av_mallocz(sizeof(*video_enc->intra_matrix) * 64))) {
f24facd3 3316 av_log(NULL, AV_LOG_FATAL, "Could not allocate memory for intra matrix.\n");
2c2cff16
AK
3317 exit_program(1);
3318 }
3319 parse_matrix_coeffs(video_enc->intra_matrix, intra_matrix);
3320 }
3321 MATCH_PER_STREAM_OPT(inter_matrices, str, inter_matrix, oc, st);
3322 if (inter_matrix) {
3323 if (!(video_enc->inter_matrix = av_mallocz(sizeof(*video_enc->inter_matrix) * 64))) {
f24facd3 3324 av_log(NULL, AV_LOG_FATAL, "Could not allocate memory for inter matrix.\n");
2c2cff16
AK
3325 exit_program(1);
3326 }
3327 parse_matrix_coeffs(video_enc->inter_matrix, inter_matrix);
3328 }
6291d7e4 3329
0e68c783 3330 MATCH_PER_STREAM_OPT(rc_overrides, str, p, oc, st);
6291d7e4
AK
3331 for(i=0; p; i++){
3332 int start, end, q;
3333 int e=sscanf(p, "%d,%d,%d", &start, &end, &q);
3334 if(e!=3){
e3245b26 3335 av_log(NULL, AV_LOG_FATAL, "error parsing rc_override\n");
6291d7e4
AK
3336 exit_program(1);
3337 }
3338 video_enc->rc_override=
3339 av_realloc(video_enc->rc_override,
3340 sizeof(RcOverride)*(i+1));
3341 video_enc->rc_override[i].start_frame= start;
3342 video_enc->rc_override[i].end_frame = end;
3343 if(q>0){
3344 video_enc->rc_override[i].qscale= q;
3345 video_enc->rc_override[i].quality_factor= 1.0;
3346 }
3347 else{
3348 video_enc->rc_override[i].qscale= 0;
3349 video_enc->rc_override[i].quality_factor= -q/100.0;
3350 }
3351 p= strchr(p, '/');
3352 if(p) p++;
3353 }
3354 video_enc->rc_override_count=i;
3355 if (!video_enc->rc_initial_buffer_occupancy)
3356 video_enc->rc_initial_buffer_occupancy = video_enc->rc_buffer_size*3/4;
6291d7e4
AK
3357 video_enc->intra_dc_precision= intra_dc_precision - 8;
3358
6291d7e4
AK
3359 /* two pass mode */
3360 if (do_pass) {
3361 if (do_pass == 1) {
3362 video_enc->flags |= CODEC_FLAG_PASS1;
3363 } else {
3364 video_enc->flags |= CODEC_FLAG_PASS2;
3365 }
3366 }
3367
7c029672 3368 MATCH_PER_STREAM_OPT(forced_key_frames, str, forced_key_frames, oc, st);
6291d7e4
AK
3369 if (forced_key_frames)
3370 parse_forced_key_frames(forced_key_frames, ost, video_enc);
bef737a7 3371
059fb8c8 3372 MATCH_PER_STREAM_OPT(force_fps, i, ost->force_fps, oc, st);
828e0bcb 3373
059fb8c8
AK
3374 ost->top_field_first = -1;
3375 MATCH_PER_STREAM_OPT(top_field_first, i, ost->top_field_first, oc, st);
8e5ce590 3376
a2aeeb22
AK
3377 MATCH_PER_STREAM_OPT(copy_initial_nonkeyframes, i, ost->copy_initial_nonkeyframes, oc ,st);
3378
8e5ce590
AK
3379#if CONFIG_AVFILTER
3380 MATCH_PER_STREAM_OPT(filters, str, filters, oc, st);
3381 if (filters)
3382 ost->avfilter = av_strdup(filters);
3383#endif
6291d7e4 3384 }
6291d7e4 3385
3d4f0dab 3386 return ost;
6291d7e4
AK
3387}
3388
35e6f8c1 3389static OutputStream *new_audio_stream(OptionsContext *o, AVFormatContext *oc)
6291d7e4
AK
3390{
3391 AVStream *st;
3392 OutputStream *ost;
6291d7e4 3393 AVCodecContext *audio_enc;
6291d7e4 3394
35e6f8c1 3395 ost = new_output_stream(o, oc, AVMEDIA_TYPE_AUDIO);
6291d7e4
AK
3396 st = ost->st;
3397
6291d7e4
AK
3398 audio_enc = st->codec;
3399 audio_enc->codec_type = AVMEDIA_TYPE_AUDIO;
3400
3d813e4c 3401 if (!ost->stream_copy) {
05bffc12
AK
3402 char *sample_fmt = NULL;
3403
6a11686d
AK
3404 MATCH_PER_STREAM_OPT(audio_channels, i, audio_enc->channels, oc, st);
3405
05bffc12
AK
3406 MATCH_PER_STREAM_OPT(sample_fmts, str, sample_fmt, oc, st);
3407 if (sample_fmt &&
3408 (audio_enc->sample_fmt = av_get_sample_fmt(sample_fmt)) == AV_SAMPLE_FMT_NONE) {
f24facd3 3409 av_log(NULL, AV_LOG_FATAL, "Invalid sample format '%s'\n", sample_fmt);
05bffc12
AK
3410 exit_program(1);
3411 }
3412
e2469ccf 3413 MATCH_PER_STREAM_OPT(audio_sample_rate, i, audio_enc->sample_rate, oc, st);
6291d7e4 3414 }
6291d7e4 3415
3d4f0dab 3416 return ost;
6291d7e4
AK
3417}
3418
35e6f8c1 3419static OutputStream *new_data_stream(OptionsContext *o, AVFormatContext *oc)
6291d7e4 3420{
6291d7e4 3421 OutputStream *ost;
6291d7e4 3422
35e6f8c1 3423 ost = new_output_stream(o, oc, AVMEDIA_TYPE_DATA);
3d813e4c 3424 if (!ost->stream_copy) {
e3245b26 3425 av_log(NULL, AV_LOG_FATAL, "Data stream encoding not supported yet (only streamcopy)\n");
6291d7e4
AK
3426 exit_program(1);
3427 }
3428
3d4f0dab 3429 return ost;
6291d7e4
AK
3430}
3431
3ccd1580
AK
3432static OutputStream *new_attachment_stream(OptionsContext *o, AVFormatContext *oc)
3433{
3434 OutputStream *ost = new_output_stream(o, oc, AVMEDIA_TYPE_ATTACHMENT);
3d813e4c 3435 ost->stream_copy = 1;
3ccd1580
AK
3436 return ost;
3437}
3438
35e6f8c1 3439static OutputStream *new_subtitle_stream(OptionsContext *o, AVFormatContext *oc)
6291d7e4
AK
3440{
3441 AVStream *st;
3442 OutputStream *ost;
6291d7e4 3443 AVCodecContext *subtitle_enc;
6291d7e4 3444
35e6f8c1 3445 ost = new_output_stream(o, oc, AVMEDIA_TYPE_SUBTITLE);
6291d7e4
AK
3446 st = ost->st;
3447 subtitle_enc = st->codec;
3448
6291d7e4
AK
3449 subtitle_enc->codec_type = AVMEDIA_TYPE_SUBTITLE;
3450
3d4f0dab 3451 return ost;
6291d7e4
AK
3452}
3453
3454/* arg format is "output-stream-index:streamid-value". */
495ecfd1 3455static int opt_streamid(OptionsContext *o, const char *opt, const char *arg)
6291d7e4
AK
3456{
3457 int idx;
3458 char *p;
3459 char idx_str[16];
3460
3461 av_strlcpy(idx_str, arg, sizeof(idx_str));
3462 p = strchr(idx_str, ':');
3463 if (!p) {
e3245b26
AK
3464 av_log(NULL, AV_LOG_FATAL,
3465 "Invalid value '%s' for option '%s', required syntax is 'index:value'\n",
3466 arg, opt);
6291d7e4
AK
3467 exit_program(1);
3468 }
3469 *p++ = '\0';
3470 idx = parse_number_or_die(opt, idx_str, OPT_INT, 0, INT_MAX);
495ecfd1
AK
3471 o->streamid_map = grow_array(o->streamid_map, sizeof(*o->streamid_map), &o->nb_streamid_map, idx+1);
3472 o->streamid_map[idx] = parse_number_or_die(opt, p, OPT_INT, 0, INT_MAX);
6291d7e4
AK
3473 return 0;
3474}
3475
847529f8 3476static int copy_chapters(InputFile *ifile, OutputFile *ofile, int copy_metadata)
86530f41 3477{
6b779ccc
AK
3478 AVFormatContext *is = ifile->ctx;
3479 AVFormatContext *os = ofile->ctx;
86530f41
AK
3480 int i;
3481
3482 for (i = 0; i < is->nb_chapters; i++) {
3483 AVChapter *in_ch = is->chapters[i], *out_ch;
6b779ccc 3484 int64_t ts_off = av_rescale_q(ofile->start_time - ifile->ts_offset,
86530f41 3485 AV_TIME_BASE_Q, in_ch->time_base);
6b779ccc
AK
3486 int64_t rt = (ofile->recording_time == INT64_MAX) ? INT64_MAX :
3487 av_rescale_q(ofile->recording_time, AV_TIME_BASE_Q, in_ch->time_base);
86530f41
AK
3488
3489
3490 if (in_ch->end < ts_off)
3491 continue;
3492 if (rt != INT64_MAX && in_ch->start > rt + ts_off)
3493 break;
3494
3495 out_ch = av_mallocz(sizeof(AVChapter));
3496 if (!out_ch)
3497 return AVERROR(ENOMEM);
3498
3499 out_ch->id = in_ch->id;
3500 out_ch->time_base = in_ch->time_base;
3501 out_ch->start = FFMAX(0, in_ch->start - ts_off);
3502 out_ch->end = FFMIN(rt, in_ch->end - ts_off);
3503
847529f8 3504 if (copy_metadata)
86530f41
AK
3505 av_dict_copy(&out_ch->metadata, in_ch->metadata, 0);
3506
3507 os->nb_chapters++;
3508 os->chapters = av_realloc(os->chapters, sizeof(AVChapter)*os->nb_chapters);
3509 if (!os->chapters)
3510 return AVERROR(ENOMEM);
3511 os->chapters[os->nb_chapters - 1] = out_ch;
3512 }
3513 return 0;
3514}
3515
35e6f8c1 3516static int read_avserver_streams(OptionsContext *o, AVFormatContext *s, const char *filename)
169f0647
AK
3517{
3518 int i, err;
2abe947a 3519 AVFormatContext *ic = avformat_alloc_context();
169f0647 3520
2abe947a 3521 ic->interrupt_callback = int_cb;
169f0647
AK
3522 err = avformat_open_input(&ic, filename, NULL, NULL);
3523 if (err < 0)
3524 return err;
3525 /* copy stream format */
3526 for(i=0;i<ic->nb_streams;i++) {
3527 AVStream *st;
3528 OutputStream *ost;
3529 AVCodec *codec;
3530
3531 codec = avcodec_find_encoder(ic->streams[i]->codec->codec_id);
35e6f8c1 3532 ost = new_output_stream(o, s, codec->type);
169f0647
AK
3533 st = ost->st;
3534
3535 // FIXME: a more elegant solution is needed
3536 memcpy(st, ic->streams[i], sizeof(AVStream));
3537 st->info = NULL;
3538 avcodec_copy_context(st->codec, ic->streams[i]->codec);
3539
3d813e4c 3540 if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO && !ost->stream_copy)
169f0647 3541 choose_sample_fmt(st, codec);
3d813e4c 3542 else if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO && !ost->stream_copy)
169f0647 3543 choose_pixel_fmt(st, codec);
169f0647
AK
3544 }
3545
3546 av_close_input_file(ic);
3547 return 0;
3548}
3549
7cc8d638 3550static void opt_output_file(void *optctx, const char *filename)
6291d7e4 3551{
575ec4e1 3552 OptionsContext *o = optctx;
6291d7e4 3553 AVFormatContext *oc;
3d4f0dab 3554 int i, err;
6291d7e4 3555 AVOutputFormat *file_oformat;
3d4f0dab
AK
3556 OutputStream *ost;
3557 InputStream *ist;
6291d7e4
AK
3558
3559 if (!strcmp(filename, "-"))
3560 filename = "pipe:";
3561
3562 oc = avformat_alloc_context();
3563 if (!oc) {
3564 print_error(filename, AVERROR(ENOMEM));
3565 exit_program(1);
3566 }
3567
7041bb3b
AK
3568 if (o->format) {
3569 file_oformat = av_guess_format(o->format, NULL, NULL);
6291d7e4 3570 if (!file_oformat) {
e3245b26 3571 av_log(NULL, AV_LOG_FATAL, "Requested output format '%s' is not a suitable output format\n", o->format);
6291d7e4
AK
3572 exit_program(1);
3573 }
6291d7e4
AK
3574 } else {
3575 file_oformat = av_guess_format(NULL, filename, NULL);
3576 if (!file_oformat) {
e3245b26
AK
3577 av_log(NULL, AV_LOG_FATAL, "Unable to find a suitable output format for '%s'\n",
3578 filename);
6291d7e4
AK
3579 exit_program(1);
3580 }
3581 }
3582
3583 oc->oformat = file_oformat;
2abe947a 3584 oc->interrupt_callback = int_cb;
6291d7e4
AK
3585 av_strlcpy(oc->filename, filename, sizeof(oc->filename));
3586
3587 if (!strcmp(file_oformat->name, "ffm") &&
3588 av_strstart(filename, "http:", NULL)) {
3589 /* special case for files sent to avserver: we get the stream
3590 parameters from avserver */
35e6f8c1 3591 int err = read_avserver_streams(o, oc, filename);
6291d7e4
AK
3592 if (err < 0) {
3593 print_error(filename, err);
3594 exit_program(1);
3595 }
575ec4e1 3596 } else if (!o->nb_stream_maps) {
3d4f0dab
AK
3597 /* pick the "best" stream of each type */
3598#define NEW_STREAM(type, index)\
3599 if (index >= 0) {\
35e6f8c1 3600 ost = new_ ## type ## _stream(o, oc);\
3d4f0dab
AK
3601 ost->source_index = index;\
3602 ost->sync_ist = &input_streams[index];\
3603 input_streams[index].discard = 0;\
3604 }
3605
3606 /* video: highest resolution */
2130981a 3607 if (!o->video_disable && oc->oformat->video_codec != CODEC_ID_NONE) {
3d4f0dab
AK
3608 int area = 0, idx = -1;
3609 for (i = 0; i < nb_input_streams; i++) {
3610 ist = &input_streams[i];
3611 if (ist->st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
3612 ist->st->codec->width * ist->st->codec->height > area) {
3613 area = ist->st->codec->width * ist->st->codec->height;
3614 idx = i;
3615 }
3616 }
3617 NEW_STREAM(video, idx);
3618 }
3619
3620 /* audio: most channels */
2130981a 3621 if (!o->audio_disable && oc->oformat->audio_codec != CODEC_ID_NONE) {
3d4f0dab
AK
3622 int channels = 0, idx = -1;
3623 for (i = 0; i < nb_input_streams; i++) {
3624 ist = &input_streams[i];
3625 if (ist->st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
3626 ist->st->codec->channels > channels) {
3627 channels = ist->st->codec->channels;
3628 idx = i;
3629 }
3630 }
3631 NEW_STREAM(audio, idx);
3632 }
3633
3634 /* subtitles: pick first */
2130981a 3635 if (!o->subtitle_disable && oc->oformat->subtitle_codec != CODEC_ID_NONE) {
3d4f0dab
AK
3636 for (i = 0; i < nb_input_streams; i++)
3637 if (input_streams[i].st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
3638 NEW_STREAM(subtitle, i);
3639 break;
3640 }
3641 }
3642 /* do something with data? */
6291d7e4 3643 } else {
575ec4e1
AK
3644 for (i = 0; i < o->nb_stream_maps; i++) {
3645 StreamMap *map = &o->stream_maps[i];
3d4f0dab