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