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