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