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