]> git.sesse.net Git - ffmpeg/blob - avconv.c
Cosmetics: Replace -1 with PIX_FMT_NONE.
[ffmpeg] / avconv.c
1 /*
2  * ffmpeg main
3  * Copyright (c) 2000-2003 Fabrice Bellard
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg 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  * FFmpeg 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 FFmpeg; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21
22 #include "config.h"
23 #include <ctype.h>
24 #include <string.h>
25 #include <math.h>
26 #include <stdlib.h>
27 #include <errno.h>
28 #include <signal.h>
29 #include <limits.h>
30 #include <unistd.h>
31 #include "libavformat/avformat.h"
32 #include "libavdevice/avdevice.h"
33 #include "libswscale/swscale.h"
34 #include "libavutil/opt.h"
35 #include "libavcodec/audioconvert.h"
36 #include "libavutil/audioconvert.h"
37 #include "libavutil/parseutils.h"
38 #include "libavutil/samplefmt.h"
39 #include "libavutil/colorspace.h"
40 #include "libavutil/fifo.h"
41 #include "libavutil/intreadwrite.h"
42 #include "libavutil/dict.h"
43 #include "libavutil/mathematics.h"
44 #include "libavutil/pixdesc.h"
45 #include "libavutil/avstring.h"
46 #include "libavutil/libm.h"
47 #include "libavutil/imgutils.h"
48 #include "libavformat/os_support.h"
49
50 #include "libavformat/ffm.h" // not public API
51
52 #if CONFIG_AVFILTER
53 # include "libavfilter/avcodec.h"
54 # include "libavfilter/avfilter.h"
55 # include "libavfilter/avfiltergraph.h"
56 # include "libavfilter/buffersink.h"
57 # include "libavfilter/buffersrc.h"
58 # include "libavfilter/vsrc_buffer.h"
59 #endif
60
61 #if HAVE_SYS_RESOURCE_H
62 #include <sys/types.h>
63 #include <sys/time.h>
64 #include <sys/resource.h>
65 #elif HAVE_GETPROCESSTIMES
66 #include <windows.h>
67 #endif
68 #if HAVE_GETPROCESSMEMORYINFO
69 #include <windows.h>
70 #include <psapi.h>
71 #endif
72
73 #if HAVE_SYS_SELECT_H
74 #include <sys/select.h>
75 #endif
76
77 #if HAVE_TERMIOS_H
78 #include <fcntl.h>
79 #include <sys/ioctl.h>
80 #include <sys/time.h>
81 #include <termios.h>
82 #elif HAVE_KBHIT
83 #include <conio.h>
84 #endif
85 #include <time.h>
86
87 #include "cmdutils.h"
88
89 #include "libavutil/avassert.h"
90
91 const char program_name[] = "avconv";
92 const int program_birth_year = 2000;
93
94 /* select an input stream for an output stream */
95 typedef struct StreamMap {
96     int disabled;           /** 1 is this mapping is disabled by a negative map */
97     int file_index;
98     int stream_index;
99     int sync_file_index;
100     int sync_stream_index;
101 } StreamMap;
102
103 /**
104  * select an input file for an output file
105  */
106 typedef struct MetadataMap {
107     int  file;      ///< file index
108     char type;      ///< type of metadata to copy -- (g)lobal, (s)tream, (c)hapter or (p)rogram
109     int  index;     ///< stream/chapter/program number
110 } MetadataMap;
111
112 static const OptionDef options[];
113
114 #define MAX_STREAMS 1024    /* arbitrary sanity check value */
115
116 static int frame_bits_per_raw_sample = 0;
117 static int video_discard = 0;
118 static int same_quant = 0;
119 static int do_deinterlace = 0;
120 static int intra_dc_precision = 8;
121 static int qp_hist = 0;
122
123 static int file_overwrite = 0;
124 static int no_file_overwrite = 0;
125 static int do_benchmark = 0;
126 static int do_hex_dump = 0;
127 static int do_pkt_dump = 0;
128 static int do_pass = 0;
129 static const char *pass_logfilename_prefix;
130 static int video_sync_method = -1;
131 static int audio_sync_method = 0;
132 static float audio_drift_threshold = 0.1;
133 static int copy_ts = 0;
134 static int copy_tb = 1;
135 static int opt_shortest = 0;
136 static char *vstats_filename;
137 static FILE *vstats_file;
138
139 static int audio_volume = 256;
140
141 static int exit_on_error = 0;
142 static int using_stdin = 0;
143 static int run_as_daemon  = 0;
144 static int q_pressed = 0;
145 static int64_t video_size = 0;
146 static int64_t audio_size = 0;
147 static int64_t extra_size = 0;
148 static int nb_frames_dup = 0;
149 static int nb_frames_drop = 0;
150 static int input_sync;
151
152 static float dts_delta_threshold = 10;
153
154 static int print_stats = 1;
155
156 static uint8_t *audio_buf;
157 static uint8_t *audio_out;
158 static unsigned int allocated_audio_out_size, allocated_audio_buf_size;
159
160 #define DEFAULT_PASS_LOGFILENAME_PREFIX "av2pass"
161
162 typedef struct FrameBuffer {
163     uint8_t *base[4];
164     uint8_t *data[4];
165     int  linesize[4];
166
167     int h, w;
168     enum PixelFormat pix_fmt;
169
170     int refcount;
171     struct InputStream *ist;
172     struct FrameBuffer *next;
173 } FrameBuffer;
174
175 typedef struct InputStream {
176     int file_index;
177     AVStream *st;
178     int discard;             /* true if stream data should be discarded */
179     int decoding_needed;     /* true if the packets must be decoded in 'raw_fifo' */
180     AVCodec *dec;
181     AVFrame *decoded_frame;
182     AVFrame *filtered_frame;
183
184     int64_t       start;     /* time when read started */
185     int64_t       next_pts;  /* synthetic pts for cases where pkt.pts
186                                 is not defined */
187     int64_t       pts;       /* current pts */
188     double ts_scale;
189     int is_start;            /* is 1 at the start and after a discontinuity */
190     int showed_multi_packet_warning;
191     AVDictionary *opts;
192
193     /* a pool of free buffers for decoded data */
194     FrameBuffer *buffer_pool;
195 } InputStream;
196
197 typedef struct InputFile {
198     AVFormatContext *ctx;
199     int eof_reached;      /* true if eof reached */
200     int ist_index;        /* index of first stream in ist_table */
201     int buffer_size;      /* current total buffer size */
202     int64_t ts_offset;
203     int nb_streams;       /* number of stream that avconv is aware of; may be different
204                              from ctx.nb_streams if new streams appear during av_read_frame() */
205     int rate_emu;
206 } InputFile;
207
208 typedef struct OutputStream {
209     int file_index;          /* file index */
210     int index;               /* stream index in the output file */
211     int source_index;        /* InputStream index */
212     AVStream *st;            /* stream in the output file */
213     int encoding_needed;     /* true if encoding needed for this stream */
214     int frame_number;
215     /* input pts and corresponding output pts
216        for A/V sync */
217     // double sync_ipts;        /* dts from the AVPacket of the demuxer in second units */
218     struct InputStream *sync_ist; /* input stream to sync against */
219     int64_t sync_opts;       /* output frame counter, could be changed to some true timestamp */ // FIXME look at frame_number
220     AVBitStreamFilterContext *bitstream_filters;
221     AVCodec *enc;
222     int64_t max_frames;
223
224     /* video only */
225     int video_resample;
226     AVFrame resample_frame;              /* temporary frame for image resampling */
227     struct SwsContext *img_resample_ctx; /* for image resampling */
228     int resample_height;
229     int resample_width;
230     int resample_pix_fmt;
231     AVRational frame_rate;
232     int force_fps;
233     int top_field_first;
234
235     float frame_aspect_ratio;
236
237     /* forced key frames */
238     int64_t *forced_kf_pts;
239     int forced_kf_count;
240     int forced_kf_index;
241
242     /* audio only */
243     int audio_resample;
244     ReSampleContext *resample; /* for audio resampling */
245     int resample_sample_fmt;
246     int resample_channels;
247     int resample_sample_rate;
248     int reformat_pair;
249     AVAudioConvert *reformat_ctx;
250     AVFifoBuffer *fifo;     /* for compression: one audio fifo per codec */
251     FILE *logfile;
252
253 #if CONFIG_AVFILTER
254     AVFilterContext *output_video_filter;
255     AVFilterContext *input_video_filter;
256     AVFilterBufferRef *picref;
257     char *avfilter;
258     AVFilterGraph *graph;
259 #endif
260
261     int64_t sws_flags;
262     AVDictionary *opts;
263     int is_past_recording_time;
264     int stream_copy;
265     const char *attachment_filename;
266     int copy_initial_nonkeyframes;
267 } OutputStream;
268
269 #if HAVE_TERMIOS_H
270
271 /* init terminal so that we can grab keys */
272 static struct termios oldtty;
273 #endif
274
275 typedef struct OutputFile {
276     AVFormatContext *ctx;
277     AVDictionary *opts;
278     int ost_index;       /* index of the first stream in output_streams */
279     int64_t recording_time; /* desired length of the resulting file in microseconds */
280     int64_t start_time;     /* start time in microseconds */
281     uint64_t limit_filesize;
282 } OutputFile;
283
284 static InputStream *input_streams   = NULL;
285 static int         nb_input_streams = 0;
286 static InputFile   *input_files     = NULL;
287 static int         nb_input_files   = 0;
288
289 static OutputStream *output_streams = NULL;
290 static int        nb_output_streams = 0;
291 static OutputFile   *output_files   = NULL;
292 static int        nb_output_files   = 0;
293
294 typedef struct OptionsContext {
295     /* input/output options */
296     int64_t start_time;
297     const char *format;
298
299     SpecifierOpt *codec_names;
300     int        nb_codec_names;
301     SpecifierOpt *audio_channels;
302     int        nb_audio_channels;
303     SpecifierOpt *audio_sample_rate;
304     int        nb_audio_sample_rate;
305     SpecifierOpt *frame_rates;
306     int        nb_frame_rates;
307     SpecifierOpt *frame_sizes;
308     int        nb_frame_sizes;
309     SpecifierOpt *frame_pix_fmts;
310     int        nb_frame_pix_fmts;
311
312     /* input options */
313     int64_t input_ts_offset;
314     int rate_emu;
315
316     SpecifierOpt *ts_scale;
317     int        nb_ts_scale;
318     SpecifierOpt *dump_attachment;
319     int        nb_dump_attachment;
320
321     /* output options */
322     StreamMap *stream_maps;
323     int     nb_stream_maps;
324     /* first item specifies output metadata, second is input */
325     MetadataMap (*meta_data_maps)[2];
326     int nb_meta_data_maps;
327     int metadata_global_manual;
328     int metadata_streams_manual;
329     int metadata_chapters_manual;
330     const char **attachments;
331     int       nb_attachments;
332
333     int chapters_input_file;
334
335     int64_t recording_time;
336     uint64_t limit_filesize;
337     float mux_preload;
338     float mux_max_delay;
339
340     int video_disable;
341     int audio_disable;
342     int subtitle_disable;
343     int data_disable;
344
345     /* indexed by output file stream index */
346     int   *streamid_map;
347     int nb_streamid_map;
348
349     SpecifierOpt *metadata;
350     int        nb_metadata;
351     SpecifierOpt *max_frames;
352     int        nb_max_frames;
353     SpecifierOpt *bitstream_filters;
354     int        nb_bitstream_filters;
355     SpecifierOpt *codec_tags;
356     int        nb_codec_tags;
357     SpecifierOpt *sample_fmts;
358     int        nb_sample_fmts;
359     SpecifierOpt *qscale;
360     int        nb_qscale;
361     SpecifierOpt *forced_key_frames;
362     int        nb_forced_key_frames;
363     SpecifierOpt *force_fps;
364     int        nb_force_fps;
365     SpecifierOpt *frame_aspect_ratios;
366     int        nb_frame_aspect_ratios;
367     SpecifierOpt *rc_overrides;
368     int        nb_rc_overrides;
369     SpecifierOpt *intra_matrices;
370     int        nb_intra_matrices;
371     SpecifierOpt *inter_matrices;
372     int        nb_inter_matrices;
373     SpecifierOpt *top_field_first;
374     int        nb_top_field_first;
375     SpecifierOpt *metadata_map;
376     int        nb_metadata_map;
377     SpecifierOpt *presets;
378     int        nb_presets;
379     SpecifierOpt *copy_initial_nonkeyframes;
380     int        nb_copy_initial_nonkeyframes;
381 #if CONFIG_AVFILTER
382     SpecifierOpt *filters;
383     int        nb_filters;
384 #endif
385 } OptionsContext;
386
387 #define MATCH_PER_STREAM_OPT(name, type, outvar, fmtctx, st)\
388 {\
389     int i, ret;\
390     for (i = 0; i < o->nb_ ## name; i++) {\
391         char *spec = o->name[i].specifier;\
392         if ((ret = check_stream_specifier(fmtctx, st, spec)) > 0)\
393             outvar = o->name[i].u.type;\
394         else if (ret < 0)\
395             exit_program(1);\
396     }\
397 }
398
399 static void reset_options(OptionsContext *o)
400 {
401     const OptionDef *po = options;
402
403     /* all OPT_SPEC and OPT_STRING can be freed in generic way */
404     while (po->name) {
405         void *dst = (uint8_t*)o + po->u.off;
406
407         if (po->flags & OPT_SPEC) {
408             SpecifierOpt **so = dst;
409             int i, *count = (int*)(so + 1);
410             for (i = 0; i < *count; i++) {
411                 av_freep(&(*so)[i].specifier);
412                 if (po->flags & OPT_STRING)
413                     av_freep(&(*so)[i].u.str);
414             }
415             av_freep(so);
416             *count = 0;
417         } else if (po->flags & OPT_OFFSET && po->flags & OPT_STRING)
418             av_freep(dst);
419         po++;
420     }
421
422     av_freep(&o->stream_maps);
423     av_freep(&o->meta_data_maps);
424     av_freep(&o->streamid_map);
425
426     memset(o, 0, sizeof(*o));
427
428     o->mux_max_delay  = 0.7;
429     o->recording_time = INT64_MAX;
430     o->limit_filesize = UINT64_MAX;
431     o->chapters_input_file = INT_MAX;
432
433     uninit_opts();
434     init_opts();
435 }
436
437 static int alloc_buffer(InputStream *ist, FrameBuffer **pbuf)
438 {
439     AVCodecContext *s = ist->st->codec;
440     FrameBuffer  *buf = av_mallocz(sizeof(*buf));
441     int ret;
442     const int pixel_size = av_pix_fmt_descriptors[s->pix_fmt].comp[0].step_minus1+1;
443     int h_chroma_shift, v_chroma_shift;
444     int edge = 32; // XXX should be avcodec_get_edge_width(), but that fails on svq1
445     int w = s->width, h = s->height;
446
447     if (!buf)
448         return AVERROR(ENOMEM);
449
450     if (!(s->flags & CODEC_FLAG_EMU_EDGE)) {
451         w += 2*edge;
452         h += 2*edge;
453     }
454
455     avcodec_align_dimensions(s, &w, &h);
456     if ((ret = av_image_alloc(buf->base, buf->linesize, w, h,
457                               s->pix_fmt, 32)) < 0) {
458         av_freep(&buf);
459         return ret;
460     }
461     /* XXX this shouldn't be needed, but some tests break without this line
462      * those decoders are buggy and need to be fixed.
463      * the following tests fail:
464      * bethsoft-vid, cdgraphics, ansi, aasc, fraps-v1, qtrle-1bit
465      */
466     memset(buf->base[0], 128, ret);
467
468     avcodec_get_chroma_sub_sample(s->pix_fmt, &h_chroma_shift, &v_chroma_shift);
469     for (int i = 0; i < FF_ARRAY_ELEMS(buf->data); i++) {
470         const int h_shift = i==0 ? 0 : h_chroma_shift;
471         const int v_shift = i==0 ? 0 : v_chroma_shift;
472         if (s->flags & CODEC_FLAG_EMU_EDGE)
473             buf->data[i] = buf->base[i];
474         else
475             buf->data[i] = buf->base[i] +
476                            FFALIGN((buf->linesize[i]*edge >> v_shift) +
477                                    (pixel_size*edge >> h_shift), 32);
478     }
479     buf->w       = s->width;
480     buf->h       = s->height;
481     buf->pix_fmt = s->pix_fmt;
482     buf->ist     = ist;
483
484     *pbuf = buf;
485     return 0;
486 }
487
488 static void free_buffer_pool(InputStream *ist)
489 {
490     FrameBuffer *buf = ist->buffer_pool;
491     while (buf) {
492         ist->buffer_pool = buf->next;
493         av_freep(&buf->base[0]);
494         av_free(buf);
495         buf = ist->buffer_pool;
496     }
497 }
498
499 static void unref_buffer(InputStream *ist, FrameBuffer *buf)
500 {
501     av_assert0(buf->refcount);
502     buf->refcount--;
503     if (!buf->refcount) {
504         buf->next = ist->buffer_pool;
505         ist->buffer_pool = buf;
506     }
507 }
508
509 static int codec_get_buffer(AVCodecContext *s, AVFrame *frame)
510 {
511     InputStream *ist = s->opaque;
512     FrameBuffer *buf;
513     int ret, i;
514
515     if (!ist->buffer_pool && (ret = alloc_buffer(ist, &ist->buffer_pool)) < 0)
516         return ret;
517
518     buf              = ist->buffer_pool;
519     ist->buffer_pool = buf->next;
520     buf->next        = NULL;
521     if (buf->w != s->width || buf->h != s->height || buf->pix_fmt != s->pix_fmt) {
522         av_freep(&buf->base[0]);
523         av_free(buf);
524         if ((ret = alloc_buffer(ist, &buf)) < 0)
525             return ret;
526     }
527     buf->refcount++;
528
529     frame->opaque        = buf;
530     frame->type          = FF_BUFFER_TYPE_USER;
531     frame->extended_data = frame->data;
532     frame->pkt_pts       = s->pkt ? s->pkt->pts : AV_NOPTS_VALUE;
533
534     for (i = 0; i < FF_ARRAY_ELEMS(buf->data); i++) {
535         frame->base[i]     = buf->base[i];  // XXX h264.c uses base though it shouldn't
536         frame->data[i]     = buf->data[i];
537         frame->linesize[i] = buf->linesize[i];
538     }
539
540     return 0;
541 }
542
543 static void codec_release_buffer(AVCodecContext *s, AVFrame *frame)
544 {
545     InputStream *ist = s->opaque;
546     FrameBuffer *buf = frame->opaque;
547     int i;
548
549     for (i = 0; i < FF_ARRAY_ELEMS(frame->data); i++)
550         frame->data[i] = NULL;
551
552     unref_buffer(ist, buf);
553 }
554
555 static void filter_release_buffer(AVFilterBuffer *fb)
556 {
557     FrameBuffer *buf = fb->priv;
558     av_free(fb);
559     unref_buffer(buf->ist, buf);
560 }
561
562 #if CONFIG_AVFILTER
563
564 static int configure_video_filters(InputStream *ist, OutputStream *ost)
565 {
566     AVFilterContext *last_filter, *filter;
567     /** filter graph containing all filters including input & output */
568     AVCodecContext *codec = ost->st->codec;
569     AVCodecContext *icodec = ist->st->codec;
570     enum PixelFormat pix_fmts[] = { codec->pix_fmt, PIX_FMT_NONE };
571     AVBufferSinkParams *buffersink_params = av_buffersink_params_alloc();
572     AVRational sample_aspect_ratio;
573     char args[255];
574     int ret;
575
576     ost->graph = avfilter_graph_alloc();
577
578     if (ist->st->sample_aspect_ratio.num) {
579         sample_aspect_ratio = ist->st->sample_aspect_ratio;
580     } else
581         sample_aspect_ratio = ist->st->codec->sample_aspect_ratio;
582
583     snprintf(args, 255, "%d:%d:%d:%d:%d:%d:%d", ist->st->codec->width,
584              ist->st->codec->height, ist->st->codec->pix_fmt, 1, AV_TIME_BASE,
585              sample_aspect_ratio.num, sample_aspect_ratio.den);
586
587     ret = avfilter_graph_create_filter(&ost->input_video_filter, avfilter_get_by_name("buffer"),
588                                        "src", args, NULL, ost->graph);
589     if (ret < 0)
590         return ret;
591 #if FF_API_OLD_VSINK_API
592     ret = avfilter_graph_create_filter(&ost->output_video_filter, avfilter_get_by_name("buffersink"),
593                                        "out", NULL, pix_fmts, ost->graph);
594 #else
595     buffersink_params->pixel_fmts = pix_fmts;
596     ret = avfilter_graph_create_filter(&ost->output_video_filter, avfilter_get_by_name("buffersink"),
597                                        "out", NULL, buffersink_params, ost->graph);
598 #endif
599     av_freep(&buffersink_params);
600     if (ret < 0)
601         return ret;
602     last_filter = ost->input_video_filter;
603
604     if (codec->width != icodec->width || codec->height != icodec->height) {
605         snprintf(args, 255, "%d:%d:flags=0x%X",
606                  codec->width,
607                  codec->height,
608                  (unsigned)ost->sws_flags);
609         if ((ret = avfilter_graph_create_filter(&filter, avfilter_get_by_name("scale"),
610                                                 NULL, args, NULL, ost->graph)) < 0)
611             return ret;
612         if ((ret = avfilter_link(last_filter, 0, filter, 0)) < 0)
613             return ret;
614         last_filter = filter;
615     }
616
617     snprintf(args, sizeof(args), "flags=0x%X", (unsigned)ost->sws_flags);
618     ost->graph->scale_sws_opts = av_strdup(args);
619
620     if (ost->avfilter) {
621         AVFilterInOut *outputs = avfilter_inout_alloc();
622         AVFilterInOut *inputs  = avfilter_inout_alloc();
623
624         outputs->name    = av_strdup("in");
625         outputs->filter_ctx = last_filter;
626         outputs->pad_idx = 0;
627         outputs->next    = NULL;
628
629         inputs->name    = av_strdup("out");
630         inputs->filter_ctx = ost->output_video_filter;
631         inputs->pad_idx = 0;
632         inputs->next    = NULL;
633
634         if ((ret = avfilter_graph_parse(ost->graph, ost->avfilter, &inputs, &outputs, NULL)) < 0)
635             return ret;
636         av_freep(&ost->avfilter);
637     } else {
638         if ((ret = avfilter_link(last_filter, 0, ost->output_video_filter, 0)) < 0)
639             return ret;
640     }
641
642     if ((ret = avfilter_graph_config(ost->graph, NULL)) < 0)
643         return ret;
644
645     codec->width  = ost->output_video_filter->inputs[0]->w;
646     codec->height = ost->output_video_filter->inputs[0]->h;
647     codec->sample_aspect_ratio = ost->st->sample_aspect_ratio =
648         ost->frame_aspect_ratio ? // overridden by the -aspect cli option
649         av_d2q(ost->frame_aspect_ratio * codec->height/codec->width, 255) :
650         ost->output_video_filter->inputs[0]->sample_aspect_ratio;
651
652     return 0;
653 }
654 #endif /* CONFIG_AVFILTER */
655
656 static void term_exit(void)
657 {
658     av_log(NULL, AV_LOG_QUIET, "%s", "");
659 #if HAVE_TERMIOS_H
660     if(!run_as_daemon)
661         tcsetattr (0, TCSANOW, &oldtty);
662 #endif
663 }
664
665 static volatile int received_sigterm = 0;
666
667 static void
668 sigterm_handler(int sig)
669 {
670     received_sigterm = sig;
671     q_pressed++;
672     term_exit();
673 }
674
675 static void term_init(void)
676 {
677 #if HAVE_TERMIOS_H
678     if(!run_as_daemon){
679     struct termios tty;
680
681     tcgetattr (0, &tty);
682     oldtty = tty;
683     atexit(term_exit);
684
685     tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
686                           |INLCR|IGNCR|ICRNL|IXON);
687     tty.c_oflag |= OPOST;
688     tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
689     tty.c_cflag &= ~(CSIZE|PARENB);
690     tty.c_cflag |= CS8;
691     tty.c_cc[VMIN] = 1;
692     tty.c_cc[VTIME] = 0;
693
694     tcsetattr (0, TCSANOW, &tty);
695     signal(SIGQUIT, sigterm_handler); /* Quit (POSIX).  */
696     }
697 #endif
698
699     signal(SIGINT , sigterm_handler); /* Interrupt (ANSI).    */
700     signal(SIGTERM, sigterm_handler); /* Termination (ANSI).  */
701 #ifdef SIGXCPU
702     signal(SIGXCPU, sigterm_handler);
703 #endif
704 }
705
706 /* read a key without blocking */
707 static int read_key(void)
708 {
709 #if HAVE_TERMIOS_H
710     int n = 1;
711     unsigned char ch;
712     struct timeval tv;
713     fd_set rfds;
714
715     if(run_as_daemon)
716         return -1;
717
718     FD_ZERO(&rfds);
719     FD_SET(0, &rfds);
720     tv.tv_sec = 0;
721     tv.tv_usec = 0;
722     n = select(1, &rfds, NULL, NULL, &tv);
723     if (n > 0) {
724         n = read(0, &ch, 1);
725         if (n == 1)
726             return ch;
727
728         return n;
729     }
730 #elif HAVE_KBHIT
731     if(kbhit())
732         return(getch());
733 #endif
734     return -1;
735 }
736
737 static int decode_interrupt_cb(void *ctx)
738 {
739     q_pressed += read_key() == 'q';
740     return q_pressed > 1;
741 }
742
743 static const AVIOInterruptCB int_cb = { decode_interrupt_cb, NULL };
744
745 void exit_program(int ret)
746 {
747     int i;
748
749     /* close files */
750     for (i = 0; i < nb_output_files; i++) {
751         AVFormatContext *s = output_files[i].ctx;
752         if (!(s->oformat->flags & AVFMT_NOFILE) && s->pb)
753             avio_close(s->pb);
754         avformat_free_context(s);
755         av_dict_free(&output_files[i].opts);
756     }
757     for (i = 0; i < nb_input_files; i++) {
758         avformat_close_input(&input_files[i].ctx);
759     }
760     for (i = 0; i < nb_input_streams; i++) {
761         av_freep(&input_streams[i].decoded_frame);
762         av_freep(&input_streams[i].filtered_frame);
763         av_dict_free(&input_streams[i].opts);
764         free_buffer_pool(&input_streams[i]);
765     }
766
767     if (vstats_file)
768         fclose(vstats_file);
769     av_free(vstats_filename);
770
771     av_freep(&input_streams);
772     av_freep(&input_files);
773     av_freep(&output_streams);
774     av_freep(&output_files);
775
776     uninit_opts();
777     av_free(audio_buf);
778     av_free(audio_out);
779     allocated_audio_buf_size = allocated_audio_out_size = 0;
780
781 #if CONFIG_AVFILTER
782     avfilter_uninit();
783 #endif
784     avformat_network_deinit();
785
786     if (received_sigterm) {
787         av_log(NULL, AV_LOG_INFO, "Received signal %d: terminating.\n",
788                (int) received_sigterm);
789         exit (255);
790     }
791
792     exit(ret);
793 }
794
795 static void assert_avoptions(AVDictionary *m)
796 {
797     AVDictionaryEntry *t;
798     if ((t = av_dict_get(m, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
799         av_log(NULL, AV_LOG_FATAL, "Option %s not found.\n", t->key);
800         exit_program(1);
801     }
802 }
803
804 static void assert_codec_experimental(AVCodecContext *c, int encoder)
805 {
806     const char *codec_string = encoder ? "encoder" : "decoder";
807     AVCodec *codec;
808     if (c->codec->capabilities & CODEC_CAP_EXPERIMENTAL &&
809         c->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
810         av_log(NULL, AV_LOG_FATAL, "%s '%s' is experimental and might produce bad "
811                 "results.\nAdd '-strict experimental' if you want to use it.\n",
812                 codec_string, c->codec->name);
813         codec = encoder ? avcodec_find_encoder(c->codec->id) : avcodec_find_decoder(c->codec->id);
814         if (!(codec->capabilities & CODEC_CAP_EXPERIMENTAL))
815             av_log(NULL, AV_LOG_FATAL, "Or use the non experimental %s '%s'.\n",
816                    codec_string, codec->name);
817         exit_program(1);
818     }
819 }
820
821 static void choose_sample_fmt(AVStream *st, AVCodec *codec)
822 {
823     if (codec && codec->sample_fmts) {
824         const enum AVSampleFormat *p = codec->sample_fmts;
825         for (; *p != -1; p++) {
826             if (*p == st->codec->sample_fmt)
827                 break;
828         }
829         if (*p == -1) {
830             if((codec->capabilities & CODEC_CAP_LOSSLESS) && av_get_sample_fmt_name(st->codec->sample_fmt) > av_get_sample_fmt_name(codec->sample_fmts[0]))
831                 av_log(NULL, AV_LOG_ERROR, "Convertion will not be lossless'\n");
832             if(av_get_sample_fmt_name(st->codec->sample_fmt))
833             av_log(NULL, AV_LOG_WARNING,
834                    "Incompatible sample format '%s' for codec '%s', auto-selecting format '%s'\n",
835                    av_get_sample_fmt_name(st->codec->sample_fmt),
836                    codec->name,
837                    av_get_sample_fmt_name(codec->sample_fmts[0]));
838             st->codec->sample_fmt = codec->sample_fmts[0];
839         }
840     }
841 }
842
843 static void choose_sample_rate(AVStream *st, AVCodec *codec)
844 {
845     if (codec && codec->supported_samplerates) {
846         const int *p  = codec->supported_samplerates;
847         int best      = 0;
848         int best_dist = INT_MAX;
849         for (; *p; p++) {
850             int dist = abs(st->codec->sample_rate - *p);
851             if (dist < best_dist) {
852                 best_dist = dist;
853                 best      = *p;
854             }
855         }
856         if (best_dist) {
857             av_log(st->codec, AV_LOG_WARNING, "Requested sampling rate unsupported using closest supported (%d)\n", best);
858         }
859         st->codec->sample_rate = best;
860     }
861 }
862
863 static void choose_pixel_fmt(AVStream *st, AVCodec *codec)
864 {
865     if (codec && codec->pix_fmts) {
866         const enum PixelFormat *p = codec->pix_fmts;
867         if (st->codec->strict_std_compliance <= FF_COMPLIANCE_UNOFFICIAL) {
868             if (st->codec->codec_id == CODEC_ID_MJPEG) {
869                 p = (const enum PixelFormat[]) { PIX_FMT_YUVJ420P, PIX_FMT_YUVJ422P, PIX_FMT_YUV420P, PIX_FMT_YUV422P, PIX_FMT_NONE };
870             } else if (st->codec->codec_id == CODEC_ID_LJPEG) {
871                 p = (const enum PixelFormat[]) { PIX_FMT_YUVJ420P, PIX_FMT_YUVJ422P, PIX_FMT_YUVJ444P, PIX_FMT_YUV420P,
872                                                  PIX_FMT_YUV422P, PIX_FMT_YUV444P, PIX_FMT_BGRA, PIX_FMT_NONE };
873             }
874         }
875         for (; *p != PIX_FMT_NONE; p++) {
876             if (*p == st->codec->pix_fmt)
877                 break;
878         }
879         if (*p == PIX_FMT_NONE) {
880             if (st->codec->pix_fmt != PIX_FMT_NONE)
881                 av_log(NULL, AV_LOG_WARNING,
882                        "Incompatible pixel format '%s' for codec '%s', auto-selecting format '%s'\n",
883                        av_pix_fmt_descriptors[st->codec->pix_fmt].name,
884                        codec->name,
885                        av_pix_fmt_descriptors[codec->pix_fmts[0]].name);
886             st->codec->pix_fmt = codec->pix_fmts[0];
887         }
888     }
889 }
890
891 static double
892 get_sync_ipts(const OutputStream *ost)
893 {
894     const InputStream *ist = ost->sync_ist;
895     OutputFile *of = &output_files[ost->file_index];
896     return (double)(ist->pts - of->start_time) / AV_TIME_BASE;
897 }
898
899 static void write_frame(AVFormatContext *s, AVPacket *pkt, AVCodecContext *avctx, AVBitStreamFilterContext *bsfc)
900 {
901     int ret;
902
903     while (bsfc) {
904         AVPacket new_pkt = *pkt;
905         int a = av_bitstream_filter_filter(bsfc, avctx, NULL,
906                                            &new_pkt.data, &new_pkt.size,
907                                            pkt->data, pkt->size,
908                                            pkt->flags & AV_PKT_FLAG_KEY);
909         if (a > 0) {
910             av_free_packet(pkt);
911             new_pkt.destruct = av_destruct_packet;
912         } else if (a < 0) {
913             av_log(NULL, AV_LOG_ERROR, "%s failed for stream %d, codec %s",
914                    bsfc->filter->name, pkt->stream_index,
915                    avctx->codec ? avctx->codec->name : "copy");
916             print_error("", a);
917             if (exit_on_error)
918                 exit_program(1);
919         }
920         *pkt = new_pkt;
921
922         bsfc = bsfc->next;
923     }
924
925     ret = av_interleaved_write_frame(s, pkt);
926     if (ret < 0) {
927         print_error("av_interleaved_write_frame()", ret);
928         exit_program(1);
929     }
930 }
931
932 static void generate_silence(uint8_t* buf, enum AVSampleFormat sample_fmt, size_t size)
933 {
934     int fill_char = 0x00;
935     if (sample_fmt == AV_SAMPLE_FMT_U8)
936         fill_char = 0x80;
937     memset(buf, fill_char, size);
938 }
939
940 static void do_audio_out(AVFormatContext *s, OutputStream *ost,
941                          InputStream *ist, AVFrame *decoded_frame)
942 {
943     uint8_t *buftmp;
944     int64_t audio_out_size, audio_buf_size;
945
946     int size_out, frame_bytes, ret, resample_changed;
947     AVCodecContext *enc = ost->st->codec;
948     AVCodecContext *dec = ist->st->codec;
949     int osize = av_get_bytes_per_sample(enc->sample_fmt);
950     int isize = av_get_bytes_per_sample(dec->sample_fmt);
951     const int coded_bps = av_get_bits_per_sample(enc->codec->id);
952     uint8_t *buf = decoded_frame->data[0];
953     int size     = decoded_frame->nb_samples * dec->channels * isize;
954     int64_t allocated_for_size = size;
955
956 need_realloc:
957     audio_buf_size  = (allocated_for_size + isize * dec->channels - 1) / (isize * dec->channels);
958     audio_buf_size  = (audio_buf_size * enc->sample_rate + dec->sample_rate) / dec->sample_rate;
959     audio_buf_size  = audio_buf_size * 2 + 10000; // safety factors for the deprecated resampling API
960     audio_buf_size  = FFMAX(audio_buf_size, enc->frame_size);
961     audio_buf_size *= osize * enc->channels;
962
963     audio_out_size = FFMAX(audio_buf_size, enc->frame_size * osize * enc->channels);
964     if (coded_bps > 8 * osize)
965         audio_out_size = audio_out_size * coded_bps / (8*osize);
966     audio_out_size += FF_MIN_BUFFER_SIZE;
967
968     if (audio_out_size > INT_MAX || audio_buf_size > INT_MAX) {
969         av_log(NULL, AV_LOG_FATAL, "Buffer sizes too large\n");
970         exit_program(1);
971     }
972
973     av_fast_malloc(&audio_buf, &allocated_audio_buf_size, audio_buf_size);
974     av_fast_malloc(&audio_out, &allocated_audio_out_size, audio_out_size);
975     if (!audio_buf || !audio_out) {
976         av_log(NULL, AV_LOG_FATAL, "Out of memory in do_audio_out\n");
977         exit_program(1);
978     }
979
980     if (enc->channels != dec->channels)
981         ost->audio_resample = 1;
982
983     resample_changed = ost->resample_sample_fmt  != dec->sample_fmt ||
984                        ost->resample_channels    != dec->channels   ||
985                        ost->resample_sample_rate != dec->sample_rate;
986
987     if ((ost->audio_resample && !ost->resample) || resample_changed) {
988         if (resample_changed) {
989             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",
990                    ist->file_index, ist->st->index,
991                    ost->resample_sample_rate, av_get_sample_fmt_name(ost->resample_sample_fmt), ost->resample_channels,
992                    dec->sample_rate, av_get_sample_fmt_name(dec->sample_fmt), dec->channels);
993             ost->resample_sample_fmt  = dec->sample_fmt;
994             ost->resample_channels    = dec->channels;
995             ost->resample_sample_rate = dec->sample_rate;
996             if (ost->resample)
997                 audio_resample_close(ost->resample);
998         }
999         /* if audio_sync_method is >1 the resampler is needed for audio drift compensation */
1000         if (audio_sync_method <= 1 &&
1001             ost->resample_sample_fmt  == enc->sample_fmt &&
1002             ost->resample_channels    == enc->channels   &&
1003             ost->resample_sample_rate == enc->sample_rate) {
1004             ost->resample = NULL;
1005             ost->audio_resample = 0;
1006         } else {
1007             if (dec->sample_fmt != AV_SAMPLE_FMT_S16)
1008                 av_log(NULL, AV_LOG_WARNING, "Using s16 intermediate sample format for resampling\n");
1009             ost->resample = av_audio_resample_init(enc->channels,    dec->channels,
1010                                                    enc->sample_rate, dec->sample_rate,
1011                                                    enc->sample_fmt,  dec->sample_fmt,
1012                                                    16, 10, 0, 0.8);
1013             if (!ost->resample) {
1014                 av_log(NULL, AV_LOG_FATAL, "Can not resample %d channels @ %d Hz to %d channels @ %d Hz\n",
1015                        dec->channels, dec->sample_rate,
1016                        enc->channels, enc->sample_rate);
1017                 exit_program(1);
1018             }
1019         }
1020     }
1021
1022 #define MAKE_SFMT_PAIR(a,b) ((a)+AV_SAMPLE_FMT_NB*(b))
1023     if (!ost->audio_resample && dec->sample_fmt != enc->sample_fmt &&
1024         MAKE_SFMT_PAIR(enc->sample_fmt,dec->sample_fmt) != ost->reformat_pair) {
1025         if (ost->reformat_ctx)
1026             av_audio_convert_free(ost->reformat_ctx);
1027         ost->reformat_ctx = av_audio_convert_alloc(enc->sample_fmt, 1,
1028                                                    dec->sample_fmt, 1, NULL, 0);
1029         if (!ost->reformat_ctx) {
1030             av_log(NULL, AV_LOG_FATAL, "Cannot convert %s sample format to %s sample format\n",
1031                    av_get_sample_fmt_name(dec->sample_fmt),
1032                    av_get_sample_fmt_name(enc->sample_fmt));
1033             exit_program(1);
1034         }
1035         ost->reformat_pair = MAKE_SFMT_PAIR(enc->sample_fmt,dec->sample_fmt);
1036     }
1037
1038     if (audio_sync_method) {
1039         double delta = get_sync_ipts(ost) * enc->sample_rate - ost->sync_opts -
1040                        av_fifo_size(ost->fifo) / (enc->channels * osize);
1041         int idelta = delta * dec->sample_rate / enc->sample_rate;
1042         int byte_delta = idelta * isize * dec->channels;
1043
1044         // FIXME resample delay
1045         if (fabs(delta) > 50) {
1046             if (ist->is_start || fabs(delta) > audio_drift_threshold*enc->sample_rate) {
1047                 if (byte_delta < 0) {
1048                     byte_delta = FFMAX(byte_delta, -size);
1049                     size += byte_delta;
1050                     buf  -= byte_delta;
1051                     av_log(NULL, AV_LOG_VERBOSE, "discarding %d audio samples\n",
1052                            -byte_delta / (isize * dec->channels));
1053                     if (!size)
1054                         return;
1055                     ist->is_start = 0;
1056                 } else {
1057                     static uint8_t *input_tmp = NULL;
1058                     input_tmp = av_realloc(input_tmp, byte_delta + size);
1059
1060                     if (byte_delta > allocated_for_size - size) {
1061                         allocated_for_size = byte_delta + (int64_t)size;
1062                         goto need_realloc;
1063                     }
1064                     ist->is_start = 0;
1065
1066                     generate_silence(input_tmp, dec->sample_fmt, byte_delta);
1067                     memcpy(input_tmp + byte_delta, buf, size);
1068                     buf = input_tmp;
1069                     size += byte_delta;
1070                     av_log(NULL, AV_LOG_VERBOSE, "adding %d audio samples of silence\n", idelta);
1071                 }
1072             } else if (audio_sync_method > 1) {
1073                 int comp = av_clip(delta, -audio_sync_method, audio_sync_method);
1074                 av_assert0(ost->audio_resample);
1075                 av_log(NULL, AV_LOG_VERBOSE, "compensating audio timestamp drift:%f compensation:%d in:%d\n",
1076                        delta, comp, enc->sample_rate);
1077 //                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));
1078                 av_resample_compensate(*(struct AVResampleContext**)ost->resample, comp, enc->sample_rate);
1079             }
1080         }
1081     } else
1082         ost->sync_opts = lrintf(get_sync_ipts(ost) * enc->sample_rate) -
1083                                 av_fifo_size(ost->fifo) / (enc->channels * osize); // FIXME wrong
1084
1085     if (ost->audio_resample) {
1086         buftmp = audio_buf;
1087         size_out = audio_resample(ost->resample,
1088                                   (short *)buftmp, (short *)buf,
1089                                   size / (dec->channels * isize));
1090         size_out = size_out * enc->channels * osize;
1091     } else {
1092         buftmp = buf;
1093         size_out = size;
1094     }
1095
1096     if (!ost->audio_resample && dec->sample_fmt != enc->sample_fmt) {
1097         const void *ibuf[6] = { buftmp };
1098         void *obuf[6]  = { audio_buf };
1099         int istride[6] = { isize };
1100         int ostride[6] = { osize };
1101         int len = size_out / istride[0];
1102         if (av_audio_convert(ost->reformat_ctx, obuf, ostride, ibuf, istride, len) < 0) {
1103             printf("av_audio_convert() failed\n");
1104             if (exit_on_error)
1105                 exit_program(1);
1106             return;
1107         }
1108         buftmp = audio_buf;
1109         size_out = len * osize;
1110     }
1111
1112     /* now encode as many frames as possible */
1113     if (enc->frame_size > 1) {
1114         /* output resampled raw samples */
1115         if (av_fifo_realloc2(ost->fifo, av_fifo_size(ost->fifo) + size_out) < 0) {
1116             av_log(NULL, AV_LOG_FATAL, "av_fifo_realloc2() failed\n");
1117             exit_program(1);
1118         }
1119         av_fifo_generic_write(ost->fifo, buftmp, size_out, NULL);
1120
1121         frame_bytes = enc->frame_size * osize * enc->channels;
1122
1123         while (av_fifo_size(ost->fifo) >= frame_bytes) {
1124             AVPacket pkt;
1125             av_init_packet(&pkt);
1126
1127             av_fifo_generic_read(ost->fifo, audio_buf, frame_bytes, NULL);
1128
1129             // FIXME pass ost->sync_opts as AVFrame.pts in avcodec_encode_audio()
1130
1131             ret = avcodec_encode_audio(enc, audio_out, audio_out_size,
1132                                        (short *)audio_buf);
1133             if (ret < 0) {
1134                 av_log(NULL, AV_LOG_FATAL, "Audio encoding failed\n");
1135                 exit_program(1);
1136             }
1137             audio_size += ret;
1138             pkt.stream_index = ost->index;
1139             pkt.data = audio_out;
1140             pkt.size = ret;
1141             if (enc->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)
1142                 pkt.pts = av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
1143             pkt.flags |= AV_PKT_FLAG_KEY;
1144             write_frame(s, &pkt, enc, ost->bitstream_filters);
1145
1146             ost->sync_opts += enc->frame_size;
1147         }
1148     } else {
1149         AVPacket pkt;
1150         av_init_packet(&pkt);
1151
1152         ost->sync_opts += size_out / (osize * enc->channels);
1153
1154         /* output a pcm frame */
1155         /* determine the size of the coded buffer */
1156         size_out /= osize;
1157         if (coded_bps)
1158             size_out = size_out * coded_bps / 8;
1159
1160         if (size_out > audio_out_size) {
1161             av_log(NULL, AV_LOG_FATAL, "Internal error, buffer size too small\n");
1162             exit_program(1);
1163         }
1164
1165         // FIXME pass ost->sync_opts as AVFrame.pts in avcodec_encode_audio()
1166         ret = avcodec_encode_audio(enc, audio_out, size_out,
1167                                    (short *)buftmp);
1168         if (ret < 0) {
1169             av_log(NULL, AV_LOG_FATAL, "Audio encoding failed\n");
1170             exit_program(1);
1171         }
1172         audio_size += ret;
1173         pkt.stream_index = ost->index;
1174         pkt.data = audio_out;
1175         pkt.size = ret;
1176         if (enc->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)
1177             pkt.pts = av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
1178         pkt.flags |= AV_PKT_FLAG_KEY;
1179         write_frame(s, &pkt, enc, ost->bitstream_filters);
1180     }
1181 }
1182
1183 static void pre_process_video_frame(InputStream *ist, AVPicture *picture, void **bufp)
1184 {
1185     AVCodecContext *dec;
1186     AVPicture *picture2;
1187     AVPicture picture_tmp;
1188     uint8_t *buf = 0;
1189
1190     dec = ist->st->codec;
1191
1192     /* deinterlace : must be done before any resize */
1193     if (do_deinterlace) {
1194         int size;
1195
1196         /* create temporary picture */
1197         size = avpicture_get_size(dec->pix_fmt, dec->width, dec->height);
1198         buf  = av_malloc(size);
1199         if (!buf)
1200             return;
1201
1202         picture2 = &picture_tmp;
1203         avpicture_fill(picture2, buf, dec->pix_fmt, dec->width, dec->height);
1204
1205         if (avpicture_deinterlace(picture2, picture,
1206                                  dec->pix_fmt, dec->width, dec->height) < 0) {
1207             /* if error, do not deinterlace */
1208             av_log(NULL, AV_LOG_WARNING, "Deinterlacing failed\n");
1209             av_free(buf);
1210             buf = NULL;
1211             picture2 = picture;
1212         }
1213     } else {
1214         picture2 = picture;
1215     }
1216
1217     if (picture != picture2)
1218         *picture = *picture2;
1219     *bufp = buf;
1220 }
1221
1222 static void do_subtitle_out(AVFormatContext *s,
1223                             OutputStream *ost,
1224                             InputStream *ist,
1225                             AVSubtitle *sub,
1226                             int64_t pts)
1227 {
1228     static uint8_t *subtitle_out = NULL;
1229     int subtitle_out_max_size = 1024 * 1024;
1230     int subtitle_out_size, nb, i;
1231     AVCodecContext *enc;
1232     AVPacket pkt;
1233
1234     if (pts == AV_NOPTS_VALUE) {
1235         av_log(NULL, AV_LOG_ERROR, "Subtitle packets must have a pts\n");
1236         if (exit_on_error)
1237             exit_program(1);
1238         return;
1239     }
1240
1241     enc = ost->st->codec;
1242
1243     if (!subtitle_out) {
1244         subtitle_out = av_malloc(subtitle_out_max_size);
1245     }
1246
1247     /* Note: DVB subtitle need one packet to draw them and one other
1248        packet to clear them */
1249     /* XXX: signal it in the codec context ? */
1250     if (enc->codec_id == CODEC_ID_DVB_SUBTITLE)
1251         nb = 2;
1252     else
1253         nb = 1;
1254
1255     for (i = 0; i < nb; i++) {
1256         sub->pts = av_rescale_q(pts, ist->st->time_base, AV_TIME_BASE_Q);
1257         // start_display_time is required to be 0
1258         sub->pts               += av_rescale_q(sub->start_display_time, (AVRational){ 1, 1000 }, AV_TIME_BASE_Q);
1259         sub->end_display_time  -= sub->start_display_time;
1260         sub->start_display_time = 0;
1261         subtitle_out_size = avcodec_encode_subtitle(enc, subtitle_out,
1262                                                     subtitle_out_max_size, sub);
1263         if (subtitle_out_size < 0) {
1264             av_log(NULL, AV_LOG_FATAL, "Subtitle encoding failed\n");
1265             exit_program(1);
1266         }
1267
1268         av_init_packet(&pkt);
1269         pkt.stream_index = ost->index;
1270         pkt.data = subtitle_out;
1271         pkt.size = subtitle_out_size;
1272         pkt.pts  = av_rescale_q(sub->pts, AV_TIME_BASE_Q, ost->st->time_base);
1273         if (enc->codec_id == CODEC_ID_DVB_SUBTITLE) {
1274             /* XXX: the pts correction is handled here. Maybe handling
1275                it in the codec would be better */
1276             if (i == 0)
1277                 pkt.pts += 90 * sub->start_display_time;
1278             else
1279                 pkt.pts += 90 * sub->end_display_time;
1280         }
1281         write_frame(s, &pkt, ost->st->codec, ost->bitstream_filters);
1282     }
1283 }
1284
1285 static int bit_buffer_size = 1024 * 256;
1286 static uint8_t *bit_buffer = NULL;
1287
1288 static void do_video_resample(OutputStream *ost,
1289                               InputStream *ist,
1290                               AVFrame *in_picture,
1291                               AVFrame **out_picture)
1292 {
1293     int resample_changed = 0;
1294     AVCodecContext *dec = ist->st->codec;
1295     AVCodecContext *enc = ost->st->codec;
1296     *out_picture = in_picture;
1297
1298     resample_changed = ost->resample_width   != dec->width  ||
1299                        ost->resample_height  != dec->height ||
1300                        ost->resample_pix_fmt != dec->pix_fmt;
1301
1302 #if !CONFIG_AVFILTER
1303     if (resample_changed) {
1304         av_log(NULL, AV_LOG_INFO,
1305                "Input stream #%d:%d frame changed from size:%dx%d fmt:%s to size:%dx%d fmt:%s\n",
1306                ist->file_index, ist->st->index,
1307                ost->resample_width, ost->resample_height, av_get_pix_fmt_name(ost->resample_pix_fmt),
1308                dec->width         , dec->height         , av_get_pix_fmt_name(dec->pix_fmt));
1309         ost->resample_width   = dec->width;
1310         ost->resample_height  = dec->height;
1311         ost->resample_pix_fmt = dec->pix_fmt;
1312     }
1313
1314     ost->video_resample = dec->width   != enc->width  ||
1315                           dec->height  != enc->height ||
1316                           dec->pix_fmt != enc->pix_fmt;
1317
1318     if (ost->video_resample) {
1319         *out_picture = &ost->resample_frame;
1320         if (!ost->img_resample_ctx || resample_changed) {
1321             /* initialize the destination picture */
1322             if (!ost->resample_frame.data[0]) {
1323                 avcodec_get_frame_defaults(&ost->resample_frame);
1324                 if (avpicture_alloc((AVPicture *)&ost->resample_frame, enc->pix_fmt,
1325                                     enc->width, enc->height)) {
1326                     fprintf(stderr, "Cannot allocate temp picture, check pix fmt\n");
1327                     exit_program(1);
1328                 }
1329             }
1330             /* initialize a new scaler context */
1331             sws_freeContext(ost->img_resample_ctx);
1332             ost->img_resample_ctx = sws_getContext(dec->width, dec->height, dec->pix_fmt,
1333                                                    enc->width, enc->height, enc->pix_fmt,
1334                                                    ost->sws_flags, NULL, NULL, NULL);
1335             if (ost->img_resample_ctx == NULL) {
1336                 av_log(NULL, AV_LOG_FATAL, "Cannot get resampling context\n");
1337                 exit_program(1);
1338             }
1339         }
1340         sws_scale(ost->img_resample_ctx, in_picture->data, in_picture->linesize,
1341               0, ost->resample_height, (*out_picture)->data, (*out_picture)->linesize);
1342     }
1343 #else
1344     if (resample_changed) {
1345         avfilter_graph_free(&ost->graph);
1346         if (configure_video_filters(ist, ost)) {
1347             av_log(NULL, AV_LOG_FATAL, "Error reinitializing filters!\n");
1348             exit_program(1);
1349         }
1350     }
1351 #endif
1352     if (resample_changed) {
1353         ost->resample_width   = dec->width;
1354         ost->resample_height  = dec->height;
1355         ost->resample_pix_fmt = dec->pix_fmt;
1356     }
1357 }
1358
1359
1360 static void do_video_out(AVFormatContext *s,
1361                          OutputStream *ost,
1362                          InputStream *ist,
1363                          AVFrame *in_picture,
1364                          int *frame_size, float quality)
1365 {
1366     int nb_frames, i, ret, format_video_sync;
1367     AVFrame *final_picture;
1368     AVCodecContext *enc;
1369     double sync_ipts;
1370
1371     enc = ost->st->codec;
1372
1373     sync_ipts = get_sync_ipts(ost) / av_q2d(enc->time_base);
1374
1375     /* by default, we output a single frame */
1376     nb_frames = 1;
1377
1378     *frame_size = 0;
1379
1380     format_video_sync = video_sync_method;
1381     if (format_video_sync < 0)
1382         format_video_sync = (s->oformat->flags & AVFMT_NOTIMESTAMPS) ? 0 :
1383                             (s->oformat->flags & AVFMT_VARIABLE_FPS) ? 2 : 1;
1384
1385     if (format_video_sync) {
1386         double vdelta = sync_ipts - ost->sync_opts;
1387         // FIXME set to 0.5 after we fix some dts/pts bugs like in avidec.c
1388         if (vdelta < -1.1)
1389             nb_frames = 0;
1390         else if (format_video_sync == 2) {
1391             if (vdelta <= -0.6) {
1392                 nb_frames = 0;
1393             } else if (vdelta > 0.6)
1394                 ost->sync_opts = lrintf(sync_ipts);
1395         } else if (vdelta > 1.1)
1396             nb_frames = lrintf(vdelta);
1397 //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);
1398         if (nb_frames == 0) {
1399             ++nb_frames_drop;
1400             av_log(NULL, AV_LOG_VERBOSE, "*** drop!\n");
1401         } else if (nb_frames > 1) {
1402             nb_frames_dup += nb_frames - 1;
1403             av_log(NULL, AV_LOG_VERBOSE, "*** %d dup!\n", nb_frames - 1);
1404         }
1405     } else
1406         ost->sync_opts = lrintf(sync_ipts);
1407
1408     nb_frames = FFMIN(nb_frames, ost->max_frames - ost->frame_number);
1409     if (nb_frames <= 0)
1410         return;
1411
1412     do_video_resample(ost, ist, in_picture, &final_picture);
1413
1414     /* duplicates frame if needed */
1415     for (i = 0; i < nb_frames; i++) {
1416         AVPacket pkt;
1417         av_init_packet(&pkt);
1418         pkt.stream_index = ost->index;
1419
1420         if (s->oformat->flags & AVFMT_RAWPICTURE &&
1421             enc->codec->id == CODEC_ID_RAWVIDEO) {
1422             /* raw pictures are written as AVPicture structure to
1423                avoid any copies. We support temporarily the older
1424                method. */
1425             enc->coded_frame->interlaced_frame = in_picture->interlaced_frame;
1426             enc->coded_frame->top_field_first  = in_picture->top_field_first;
1427             pkt.data   = (uint8_t *)final_picture;
1428             pkt.size   =  sizeof(AVPicture);
1429             pkt.pts    = av_rescale_q(ost->sync_opts, enc->time_base, ost->st->time_base);
1430             pkt.flags |= AV_PKT_FLAG_KEY;
1431
1432             write_frame(s, &pkt, ost->st->codec, ost->bitstream_filters);
1433         } else {
1434             AVFrame big_picture;
1435
1436             big_picture = *final_picture;
1437             /* better than nothing: use input picture interlaced
1438                settings */
1439             big_picture.interlaced_frame = in_picture->interlaced_frame;
1440             if (ost->st->codec->flags & (CODEC_FLAG_INTERLACED_DCT|CODEC_FLAG_INTERLACED_ME)) {
1441                 if (ost->top_field_first == -1)
1442                     big_picture.top_field_first = in_picture->top_field_first;
1443                 else
1444                     big_picture.top_field_first = !!ost->top_field_first;
1445             }
1446
1447             /* handles same_quant here. This is not correct because it may
1448                not be a global option */
1449             big_picture.quality = quality;
1450             if (!enc->me_threshold)
1451                 big_picture.pict_type = 0;
1452 //            big_picture.pts = AV_NOPTS_VALUE;
1453             big_picture.pts = ost->sync_opts;
1454 //            big_picture.pts= av_rescale(ost->sync_opts, AV_TIME_BASE*(int64_t)enc->time_base.num, enc->time_base.den);
1455 // av_log(NULL, AV_LOG_DEBUG, "%"PRId64" -> encoder\n", ost->sync_opts);
1456             if (ost->forced_kf_index < ost->forced_kf_count &&
1457                 big_picture.pts >= ost->forced_kf_pts[ost->forced_kf_index]) {
1458                 big_picture.pict_type = AV_PICTURE_TYPE_I;
1459                 ost->forced_kf_index++;
1460             }
1461             ret = avcodec_encode_video(enc,
1462                                        bit_buffer, bit_buffer_size,
1463                                        &big_picture);
1464             if (ret < 0) {
1465                 av_log(NULL, AV_LOG_FATAL, "Video encoding failed\n");
1466                 exit_program(1);
1467             }
1468
1469             if (ret > 0) {
1470                 pkt.data = bit_buffer;
1471                 pkt.size = ret;
1472                 if (enc->coded_frame->pts != AV_NOPTS_VALUE)
1473                     pkt.pts = av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
1474 /*av_log(NULL, AV_LOG_DEBUG, "encoder -> %"PRId64"/%"PRId64"\n",
1475    pkt.pts != AV_NOPTS_VALUE ? av_rescale(pkt.pts, enc->time_base.den, AV_TIME_BASE*(int64_t)enc->time_base.num) : -1,
1476    pkt.dts != AV_NOPTS_VALUE ? av_rescale(pkt.dts, enc->time_base.den, AV_TIME_BASE*(int64_t)enc->time_base.num) : -1);*/
1477
1478                 if (enc->coded_frame->key_frame)
1479                     pkt.flags |= AV_PKT_FLAG_KEY;
1480                 write_frame(s, &pkt, ost->st->codec, ost->bitstream_filters);
1481                 *frame_size = ret;
1482                 video_size += ret;
1483                 // fprintf(stderr,"\nFrame: %3d size: %5d type: %d",
1484                 //         enc->frame_number-1, ret, enc->pict_type);
1485                 /* if two pass, output log */
1486                 if (ost->logfile && enc->stats_out) {
1487                     fprintf(ost->logfile, "%s", enc->stats_out);
1488                 }
1489             }
1490         }
1491         ost->sync_opts++;
1492         ost->frame_number++;
1493     }
1494 }
1495
1496 static double psnr(double d)
1497 {
1498     return -10.0 * log(d) / log(10.0);
1499 }
1500
1501 static void do_video_stats(AVFormatContext *os, OutputStream *ost,
1502                            int frame_size)
1503 {
1504     AVCodecContext *enc;
1505     int frame_number;
1506     double ti1, bitrate, avg_bitrate;
1507
1508     /* this is executed just the first time do_video_stats is called */
1509     if (!vstats_file) {
1510         vstats_file = fopen(vstats_filename, "w");
1511         if (!vstats_file) {
1512             perror("fopen");
1513             exit_program(1);
1514         }
1515     }
1516
1517     enc = ost->st->codec;
1518     if (enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1519         frame_number = ost->frame_number;
1520         fprintf(vstats_file, "frame= %5d q= %2.1f ", frame_number, enc->coded_frame->quality / (float)FF_QP2LAMBDA);
1521         if (enc->flags&CODEC_FLAG_PSNR)
1522             fprintf(vstats_file, "PSNR= %6.2f ", psnr(enc->coded_frame->error[0] / (enc->width * enc->height * 255.0 * 255.0)));
1523
1524         fprintf(vstats_file,"f_size= %6d ", frame_size);
1525         /* compute pts value */
1526         ti1 = ost->sync_opts * av_q2d(enc->time_base);
1527         if (ti1 < 0.01)
1528             ti1 = 0.01;
1529
1530         bitrate     = (frame_size * 8) / av_q2d(enc->time_base) / 1000.0;
1531         avg_bitrate = (double)(video_size * 8) / ti1 / 1000.0;
1532         fprintf(vstats_file, "s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
1533                (double)video_size / 1024, ti1, bitrate, avg_bitrate);
1534         fprintf(vstats_file, "type= %c\n", av_get_picture_type_char(enc->coded_frame->pict_type));
1535     }
1536 }
1537
1538 static void print_report(OutputFile *output_files,
1539                          OutputStream *ost_table, int nb_ostreams,
1540                          int is_last_report, int64_t timer_start)
1541 {
1542     char buf[1024];
1543     OutputStream *ost;
1544     AVFormatContext *oc;
1545     int64_t total_size;
1546     AVCodecContext *enc;
1547     int frame_number, vid, i;
1548     double bitrate;
1549     int64_t pts = INT64_MAX;
1550     static int64_t last_time = -1;
1551     static int qp_histogram[52];
1552     int hours, mins, secs, us;
1553
1554     if (!print_stats && !is_last_report)
1555         return;
1556
1557     if (!is_last_report) {
1558         int64_t cur_time;
1559         /* display the report every 0.5 seconds */
1560         cur_time = av_gettime();
1561         if (last_time == -1) {
1562             last_time = cur_time;
1563             return;
1564         }
1565         if ((cur_time - last_time) < 500000)
1566             return;
1567         last_time = cur_time;
1568     }
1569
1570
1571     oc = output_files[0].ctx;
1572
1573     total_size = avio_size(oc->pb);
1574     if (total_size < 0) // FIXME improve avio_size() so it works with non seekable output too
1575         total_size = avio_tell(oc->pb);
1576
1577     buf[0] = '\0';
1578     vid = 0;
1579     for (i = 0; i < nb_ostreams; i++) {
1580         float q = -1;
1581         ost = &ost_table[i];
1582         enc = ost->st->codec;
1583         if (!ost->stream_copy && enc->coded_frame)
1584             q = enc->coded_frame->quality / (float)FF_QP2LAMBDA;
1585         if (vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1586             snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "q=%2.1f ", q);
1587         }
1588         if (!vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1589             float t = (av_gettime() - timer_start) / 1000000.0;
1590
1591             frame_number = ost->frame_number;
1592             snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "frame=%5d fps=%3d q=%3.1f ",
1593                      frame_number, (t > 1) ? (int)(frame_number / t + 0.5) : 0, q);
1594             if (is_last_report)
1595                 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "L");
1596             if (qp_hist) {
1597                 int j;
1598                 int qp = lrintf(q);
1599                 if (qp >= 0 && qp < FF_ARRAY_ELEMS(qp_histogram))
1600                     qp_histogram[qp]++;
1601                 for (j = 0; j < 32; j++)
1602                     snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%X", (int)lrintf(log(qp_histogram[j] + 1) / log(2)));
1603             }
1604             if (enc->flags&CODEC_FLAG_PSNR) {
1605                 int j;
1606                 double error, error_sum = 0;
1607                 double scale, scale_sum = 0;
1608                 char type[3] = { 'Y','U','V' };
1609                 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "PSNR=");
1610                 for (j = 0; j < 3; j++) {
1611                     if (is_last_report) {
1612                         error = enc->error[j];
1613                         scale = enc->width * enc->height * 255.0 * 255.0 * frame_number;
1614                     } else {
1615                         error = enc->coded_frame->error[j];
1616                         scale = enc->width * enc->height * 255.0 * 255.0;
1617                     }
1618                     if (j)
1619                         scale /= 4;
1620                     error_sum += error;
1621                     scale_sum += scale;
1622                     snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%c:%2.2f ", type[j], psnr(error / scale));
1623                 }
1624                 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "*:%2.2f ", psnr(error_sum / scale_sum));
1625             }
1626             vid = 1;
1627         }
1628         /* compute min output value */
1629         pts = FFMIN(pts, av_rescale_q(ost->st->pts.val,
1630                                       ost->st->time_base, AV_TIME_BASE_Q));
1631     }
1632
1633     secs = pts / AV_TIME_BASE;
1634     us = pts % AV_TIME_BASE;
1635     mins = secs / 60;
1636     secs %= 60;
1637     hours = mins / 60;
1638     mins %= 60;
1639
1640     bitrate = pts ? total_size * 8 / (pts / 1000.0) : 0;
1641
1642     snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1643              "size=%8.0fkB time=", total_size / 1024.0);
1644     snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1645              "%02d:%02d:%02d.%02d ", hours, mins, secs,
1646              (100 * us) / AV_TIME_BASE);
1647     snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1648              "bitrate=%6.1fkbits/s", bitrate);
1649
1650     if (nb_frames_dup || nb_frames_drop)
1651         snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), " dup=%d drop=%d",
1652                 nb_frames_dup, nb_frames_drop);
1653
1654     av_log(NULL, AV_LOG_INFO, "%s    \r", buf);
1655
1656     fflush(stderr);
1657
1658     if (is_last_report) {
1659         int64_t raw= audio_size + video_size + extra_size;
1660         av_log(NULL, AV_LOG_INFO, "\n");
1661         av_log(NULL, AV_LOG_INFO, "video:%1.0fkB audio:%1.0fkB global headers:%1.0fkB muxing overhead %f%%\n",
1662                video_size / 1024.0,
1663                audio_size / 1024.0,
1664                extra_size / 1024.0,
1665                100.0 * (total_size - raw) / raw
1666         );
1667     }
1668 }
1669
1670 static void flush_encoders(OutputStream *ost_table, int nb_ostreams)
1671 {
1672     int i, ret;
1673
1674     for (i = 0; i < nb_ostreams; i++) {
1675         OutputStream   *ost = &ost_table[i];
1676         AVCodecContext *enc = ost->st->codec;
1677         AVFormatContext *os = output_files[ost->file_index].ctx;
1678
1679         if (!ost->encoding_needed)
1680             continue;
1681
1682         if (ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO && enc->frame_size <= 1)
1683             continue;
1684         if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO && (os->oformat->flags & AVFMT_RAWPICTURE) && enc->codec->id == CODEC_ID_RAWVIDEO)
1685             continue;
1686
1687         for (;;) {
1688             AVPacket pkt;
1689             int fifo_bytes;
1690             av_init_packet(&pkt);
1691             pkt.stream_index = ost->index;
1692
1693             switch (ost->st->codec->codec_type) {
1694             case AVMEDIA_TYPE_AUDIO:
1695                 fifo_bytes = av_fifo_size(ost->fifo);
1696                 ret = 0;
1697                 /* encode any samples remaining in fifo */
1698                 if (fifo_bytes > 0) {
1699                     int osize = av_get_bytes_per_sample(enc->sample_fmt);
1700                     int fs_tmp = enc->frame_size;
1701
1702                     av_fifo_generic_read(ost->fifo, audio_buf, fifo_bytes, NULL);
1703                     if (enc->codec->capabilities & CODEC_CAP_SMALL_LAST_FRAME) {
1704                         enc->frame_size = fifo_bytes / (osize * enc->channels);
1705                     } else { /* pad */
1706                         int frame_bytes = enc->frame_size*osize*enc->channels;
1707                         if (allocated_audio_buf_size < frame_bytes)
1708                             exit_program(1);
1709                         generate_silence(audio_buf+fifo_bytes, enc->sample_fmt, frame_bytes - fifo_bytes);
1710                     }
1711
1712                     ret = avcodec_encode_audio(enc, bit_buffer, bit_buffer_size, (short *)audio_buf);
1713                     pkt.duration = av_rescale((int64_t)enc->frame_size*ost->st->time_base.den,
1714                                               ost->st->time_base.num, enc->sample_rate);
1715                     enc->frame_size = fs_tmp;
1716                 }
1717                 if (ret <= 0) {
1718                     ret = avcodec_encode_audio(enc, bit_buffer, bit_buffer_size, NULL);
1719                 }
1720                 if (ret < 0) {
1721                     av_log(NULL, AV_LOG_FATAL, "Audio encoding failed\n");
1722                     exit_program(1);
1723                 }
1724                 audio_size += ret;
1725                 pkt.flags  |= AV_PKT_FLAG_KEY;
1726                 break;
1727             case AVMEDIA_TYPE_VIDEO:
1728                 ret = avcodec_encode_video(enc, bit_buffer, bit_buffer_size, NULL);
1729                 if (ret < 0) {
1730                     av_log(NULL, AV_LOG_FATAL, "Video encoding failed\n");
1731                     exit_program(1);
1732                 }
1733                 video_size += ret;
1734                 if (enc->coded_frame && enc->coded_frame->key_frame)
1735                     pkt.flags |= AV_PKT_FLAG_KEY;
1736                 if (ost->logfile && enc->stats_out) {
1737                     fprintf(ost->logfile, "%s", enc->stats_out);
1738                 }
1739                 break;
1740             default:
1741                 ret = -1;
1742             }
1743
1744             if (ret <= 0)
1745                 break;
1746             pkt.data = bit_buffer;
1747             pkt.size = ret;
1748             if (enc->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)
1749                 pkt.pts = av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
1750             write_frame(os, &pkt, ost->st->codec, ost->bitstream_filters);
1751         }
1752     }
1753 }
1754
1755 /*
1756  * Check whether a packet from ist should be written into ost at this time
1757  */
1758 static int check_output_constraints(InputStream *ist, OutputStream *ost)
1759 {
1760     OutputFile *of = &output_files[ost->file_index];
1761     int ist_index  = ist - input_streams;
1762
1763     if (ost->source_index != ist_index)
1764         return 0;
1765
1766     if (of->start_time && ist->pts < of->start_time)
1767         return 0;
1768
1769     if (of->recording_time != INT64_MAX &&
1770         av_compare_ts(ist->pts, AV_TIME_BASE_Q, of->recording_time + of->start_time,
1771                       (AVRational){ 1, 1000000 }) >= 0) {
1772         ost->is_past_recording_time = 1;
1773         return 0;
1774     }
1775
1776     return 1;
1777 }
1778
1779 static void do_streamcopy(InputStream *ist, OutputStream *ost, const AVPacket *pkt)
1780 {
1781     OutputFile *of = &output_files[ost->file_index];
1782     int64_t ost_tb_start_time = av_rescale_q(of->start_time, AV_TIME_BASE_Q, ost->st->time_base);
1783     AVPicture pict;
1784     AVPacket opkt;
1785
1786     av_init_packet(&opkt);
1787
1788     if ((!ost->frame_number && !(pkt->flags & AV_PKT_FLAG_KEY)) &&
1789         !ost->copy_initial_nonkeyframes)
1790         return;
1791
1792     /* force the input stream PTS */
1793     if (ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
1794         audio_size += pkt->size;
1795     else if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
1796         video_size += pkt->size;
1797         ost->sync_opts++;
1798     }
1799
1800     opkt.stream_index = ost->index;
1801     if (pkt->pts != AV_NOPTS_VALUE)
1802         opkt.pts = av_rescale_q(pkt->pts, ist->st->time_base, ost->st->time_base) - ost_tb_start_time;
1803     else
1804         opkt.pts = AV_NOPTS_VALUE;
1805
1806     if (pkt->dts == AV_NOPTS_VALUE)
1807         opkt.dts = av_rescale_q(ist->pts, AV_TIME_BASE_Q, ost->st->time_base);
1808     else
1809         opkt.dts = av_rescale_q(pkt->dts, ist->st->time_base, ost->st->time_base);
1810     opkt.dts -= ost_tb_start_time;
1811
1812     opkt.duration = av_rescale_q(pkt->duration, ist->st->time_base, ost->st->time_base);
1813     opkt.flags    = pkt->flags;
1814
1815     // FIXME remove the following 2 lines they shall be replaced by the bitstream filters
1816     if (  ost->st->codec->codec_id != CODEC_ID_H264
1817        && ost->st->codec->codec_id != CODEC_ID_MPEG1VIDEO
1818        && ost->st->codec->codec_id != CODEC_ID_MPEG2VIDEO
1819        ) {
1820         if (av_parser_change(ist->st->parser, ost->st->codec, &opkt.data, &opkt.size, pkt->data, pkt->size, pkt->flags & AV_PKT_FLAG_KEY))
1821             opkt.destruct = av_destruct_packet;
1822     } else {
1823         opkt.data = pkt->data;
1824         opkt.size = pkt->size;
1825     }
1826     if (of->ctx->oformat->flags & AVFMT_RAWPICTURE) {
1827         /* store AVPicture in AVPacket, as expected by the output format */
1828         avpicture_fill(&pict, opkt.data, ost->st->codec->pix_fmt, ost->st->codec->width, ost->st->codec->height);
1829         opkt.data = (uint8_t *)&pict;
1830         opkt.size = sizeof(AVPicture);
1831         opkt.flags |= AV_PKT_FLAG_KEY;
1832     }
1833
1834     write_frame(of->ctx, &opkt, ost->st->codec, ost->bitstream_filters);
1835     ost->st->codec->frame_number++;
1836     ost->frame_number++;
1837     av_free_packet(&opkt);
1838 }
1839
1840 static void rate_emu_sleep(InputStream *ist)
1841 {
1842     if (input_files[ist->file_index].rate_emu) {
1843         int64_t pts = av_rescale(ist->pts, 1000000, AV_TIME_BASE);
1844         int64_t now = av_gettime() - ist->start;
1845         if (pts > now)
1846             usleep(pts - now);
1847     }
1848 }
1849
1850 static int transcode_audio(InputStream *ist, AVPacket *pkt, int *got_output)
1851 {
1852     AVFrame *decoded_frame;
1853     AVCodecContext *avctx = ist->st->codec;
1854     int bps = av_get_bytes_per_sample(ist->st->codec->sample_fmt);
1855     int i, ret;
1856
1857     if (!ist->decoded_frame && !(ist->decoded_frame = avcodec_alloc_frame()))
1858         return AVERROR(ENOMEM);
1859     else
1860         avcodec_get_frame_defaults(ist->decoded_frame);
1861     decoded_frame = ist->decoded_frame;
1862
1863     ret = avcodec_decode_audio4(avctx, decoded_frame, got_output, pkt);
1864     if (ret < 0) {
1865         return ret;
1866     }
1867
1868     if (!*got_output) {
1869         /* no audio frame */
1870         return ret;
1871     }
1872
1873     /* if the decoder provides a pts, use it instead of the last packet pts.
1874        the decoder could be delaying output by a packet or more. */
1875     if (decoded_frame->pts != AV_NOPTS_VALUE)
1876         ist->next_pts = decoded_frame->pts;
1877
1878     /* increment next_pts to use for the case where the input stream does not
1879        have timestamps or there are multiple frames in the packet */
1880     ist->next_pts += ((int64_t)AV_TIME_BASE * decoded_frame->nb_samples) /
1881                      avctx->sample_rate;
1882
1883     // preprocess audio (volume)
1884     if (audio_volume != 256) {
1885         int decoded_data_size = decoded_frame->nb_samples * avctx->channels * bps;
1886         void *samples = decoded_frame->data[0];
1887         switch (avctx->sample_fmt) {
1888         case AV_SAMPLE_FMT_U8:
1889         {
1890             uint8_t *volp = samples;
1891             for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
1892                 int v = (((*volp - 128) * audio_volume + 128) >> 8) + 128;
1893                 *volp++ = av_clip_uint8(v);
1894             }
1895             break;
1896         }
1897         case AV_SAMPLE_FMT_S16:
1898         {
1899             int16_t *volp = samples;
1900             for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
1901                 int v = ((*volp) * audio_volume + 128) >> 8;
1902                 *volp++ = av_clip_int16(v);
1903             }
1904             break;
1905         }
1906         case AV_SAMPLE_FMT_S32:
1907         {
1908             int32_t *volp = samples;
1909             for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
1910                 int64_t v = (((int64_t)*volp * audio_volume + 128) >> 8);
1911                 *volp++ = av_clipl_int32(v);
1912             }
1913             break;
1914         }
1915         case AV_SAMPLE_FMT_FLT:
1916         {
1917             float *volp = samples;
1918             float scale = audio_volume / 256.f;
1919             for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
1920                 *volp++ *= scale;
1921             }
1922             break;
1923         }
1924         case AV_SAMPLE_FMT_DBL:
1925         {
1926             double *volp = samples;
1927             double scale = audio_volume / 256.;
1928             for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
1929                 *volp++ *= scale;
1930             }
1931             break;
1932         }
1933         default:
1934             av_log(NULL, AV_LOG_FATAL,
1935                    "Audio volume adjustment on sample format %s is not supported.\n",
1936                    av_get_sample_fmt_name(ist->st->codec->sample_fmt));
1937             exit_program(1);
1938         }
1939     }
1940
1941     rate_emu_sleep(ist);
1942
1943     for (i = 0; i < nb_output_streams; i++) {
1944         OutputStream *ost = &output_streams[i];
1945
1946         if (!check_output_constraints(ist, ost) || !ost->encoding_needed)
1947             continue;
1948         do_audio_out(output_files[ost->file_index].ctx, ost, ist, decoded_frame);
1949     }
1950
1951     return ret;
1952 }
1953
1954 static int transcode_video(InputStream *ist, AVPacket *pkt, int *got_output, int64_t *pkt_pts)
1955 {
1956     AVFrame *decoded_frame, *filtered_frame = NULL;
1957     void *buffer_to_free = NULL;
1958     int i, ret = 0;
1959     float quality;
1960 #if CONFIG_AVFILTER
1961     int frame_available = 1;
1962 #endif
1963
1964     if (!ist->decoded_frame && !(ist->decoded_frame = avcodec_alloc_frame()))
1965         return AVERROR(ENOMEM);
1966     else
1967         avcodec_get_frame_defaults(ist->decoded_frame);
1968     decoded_frame = ist->decoded_frame;
1969     pkt->pts  = *pkt_pts;
1970     pkt->dts  = ist->pts;
1971     *pkt_pts  = AV_NOPTS_VALUE;
1972
1973     ret = avcodec_decode_video2(ist->st->codec,
1974                                 decoded_frame, got_output, pkt);
1975     if (ret < 0)
1976         return ret;
1977
1978     quality = same_quant ? decoded_frame->quality : 0;
1979     if (!*got_output) {
1980         /* no picture yet */
1981         return ret;
1982     }
1983     ist->next_pts = ist->pts = decoded_frame->best_effort_timestamp;
1984     if (pkt->duration)
1985         ist->next_pts += av_rescale_q(pkt->duration, ist->st->time_base, AV_TIME_BASE_Q);
1986     else if (ist->st->codec->time_base.num != 0) {
1987         int ticks      = ist->st->parser ? ist->st->parser->repeat_pict + 1 :
1988                                            ist->st->codec->ticks_per_frame;
1989         ist->next_pts += ((int64_t)AV_TIME_BASE *
1990                           ist->st->codec->time_base.num * ticks) /
1991                           ist->st->codec->time_base.den;
1992     }
1993     pkt->size = 0;
1994     pre_process_video_frame(ist, (AVPicture *)decoded_frame, &buffer_to_free);
1995
1996     rate_emu_sleep(ist);
1997
1998     for (i = 0; i < nb_output_streams; i++) {
1999         OutputStream *ost = &output_streams[i];
2000         int frame_size;
2001
2002         if (!check_output_constraints(ist, ost) || !ost->encoding_needed)
2003             continue;
2004
2005 #if CONFIG_AVFILTER
2006         if (!decoded_frame->sample_aspect_ratio.num)
2007             decoded_frame->sample_aspect_ratio = ist->st->sample_aspect_ratio;
2008         decoded_frame->pts = ist->pts;
2009         if (ist->st->codec->codec->capabilities & CODEC_CAP_DR1) {
2010             FrameBuffer      *buf = decoded_frame->opaque;
2011             AVFilterBufferRef *fb = avfilter_get_video_buffer_ref_from_arrays(
2012                                         decoded_frame->data, decoded_frame->linesize,
2013                                         AV_PERM_READ | AV_PERM_PRESERVE,
2014                                         ist->st->codec->width, ist->st->codec->height,
2015                                         ist->st->codec->pix_fmt);
2016
2017             avfilter_copy_frame_props(fb, decoded_frame);
2018             fb->pts                 = ist->pts;
2019             fb->buf->priv           = buf;
2020             fb->buf->free           = filter_release_buffer;
2021
2022             buf->refcount++;
2023             av_buffersrc_buffer(ost->input_video_filter, fb);
2024         } else
2025             av_vsrc_buffer_add_frame(ost->input_video_filter, decoded_frame, AV_VSRC_BUF_FLAG_OVERWRITE);
2026
2027         if (!ist->filtered_frame && !(ist->filtered_frame = avcodec_alloc_frame())) {
2028             av_free(buffer_to_free);
2029             return AVERROR(ENOMEM);
2030         } else
2031             avcodec_get_frame_defaults(ist->filtered_frame);
2032         filtered_frame = ist->filtered_frame;
2033
2034         frame_available = avfilter_poll_frame(ost->output_video_filter->inputs[0]);
2035         while (frame_available) {
2036             if (ost->output_video_filter) {
2037                 AVRational ist_pts_tb = ost->output_video_filter->inputs[0]->time_base;
2038                 if (av_buffersink_get_buffer_ref(ost->output_video_filter, &ost->picref, 0) < 0)
2039                     goto cont;
2040                 if (ost->picref) {
2041                     avfilter_fill_frame_from_video_buffer_ref(filtered_frame, ost->picref);
2042                     ist->pts = av_rescale_q(ost->picref->pts, ist_pts_tb, AV_TIME_BASE_Q);
2043                 }
2044             }
2045             if (ost->picref->video && !ost->frame_aspect_ratio)
2046                 ost->st->codec->sample_aspect_ratio = ost->picref->video->sample_aspect_ratio;
2047 #else
2048             filtered_frame = decoded_frame;
2049 #endif
2050
2051             do_video_out(output_files[ost->file_index].ctx, ost, ist, filtered_frame, &frame_size,
2052                          same_quant ? quality : ost->st->codec->global_quality);
2053             if (vstats_filename && frame_size)
2054                 do_video_stats(output_files[ost->file_index].ctx, ost, frame_size);
2055 #if CONFIG_AVFILTER
2056             cont:
2057             frame_available = ost->output_video_filter && avfilter_poll_frame(ost->output_video_filter->inputs[0]);
2058             if (ost->picref)
2059                 avfilter_unref_buffer(ost->picref);
2060         }
2061 #endif
2062     }
2063
2064     av_free(buffer_to_free);
2065     return ret;
2066 }
2067
2068 static int transcode_subtitles(InputStream *ist, AVPacket *pkt, int *got_output)
2069 {
2070     AVSubtitle subtitle;
2071     int i, ret = avcodec_decode_subtitle2(ist->st->codec,
2072                                           &subtitle, got_output, pkt);
2073     if (ret < 0)
2074         return ret;
2075     if (!*got_output)
2076         return ret;
2077
2078     rate_emu_sleep(ist);
2079
2080     for (i = 0; i < nb_output_streams; i++) {
2081         OutputStream *ost = &output_streams[i];
2082
2083         if (!check_output_constraints(ist, ost) || !ost->encoding_needed)
2084             continue;
2085
2086         do_subtitle_out(output_files[ost->file_index].ctx, ost, ist, &subtitle, pkt->pts);
2087     }
2088
2089     avsubtitle_free(&subtitle);
2090     return ret;
2091 }
2092
2093 /* pkt = NULL means EOF (needed to flush decoder buffers) */
2094 static int output_packet(InputStream *ist,
2095                          OutputStream *ost_table, int nb_ostreams,
2096                          const AVPacket *pkt)
2097 {
2098     int i;
2099     int got_output;
2100     int64_t pkt_pts = AV_NOPTS_VALUE;
2101     AVPacket avpkt;
2102
2103     if (ist->next_pts == AV_NOPTS_VALUE)
2104         ist->next_pts = ist->pts;
2105
2106     if (pkt == NULL) {
2107         /* EOF handling */
2108         av_init_packet(&avpkt);
2109         avpkt.data = NULL;
2110         avpkt.size = 0;
2111         goto handle_eof;
2112     } else {
2113         avpkt = *pkt;
2114     }
2115
2116     if (pkt->dts != AV_NOPTS_VALUE)
2117         ist->next_pts = ist->pts = av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);
2118     if (pkt->pts != AV_NOPTS_VALUE)
2119         pkt_pts = av_rescale_q(pkt->pts, ist->st->time_base, AV_TIME_BASE_Q);
2120
2121     // while we have more to decode or while the decoder did output something on EOF
2122     while (ist->decoding_needed && (avpkt.size > 0 || (!pkt && got_output))) {
2123         int ret = 0;
2124     handle_eof:
2125
2126         ist->pts = ist->next_pts;
2127
2128         if (avpkt.size && avpkt.size != pkt->size) {
2129             av_log(NULL, ist->showed_multi_packet_warning ? AV_LOG_VERBOSE : AV_LOG_WARNING,
2130                    "Multiple frames in a packet from stream %d\n", pkt->stream_index);
2131             ist->showed_multi_packet_warning = 1;
2132         }
2133
2134         switch (ist->st->codec->codec_type) {
2135         case AVMEDIA_TYPE_AUDIO:
2136             ret = transcode_audio    (ist, &avpkt, &got_output);
2137             break;
2138         case AVMEDIA_TYPE_VIDEO:
2139             ret = transcode_video    (ist, &avpkt, &got_output, &pkt_pts);
2140             break;
2141         case AVMEDIA_TYPE_SUBTITLE:
2142             ret = transcode_subtitles(ist, &avpkt, &got_output);
2143             break;
2144         default:
2145             return -1;
2146         }
2147
2148         if (ret < 0)
2149             return ret;
2150         // touch data and size only if not EOF
2151         if (pkt) {
2152             avpkt.data += ret;
2153             avpkt.size -= ret;
2154         }
2155         if (!got_output) {
2156             continue;
2157         }
2158     }
2159
2160     /* handle stream copy */
2161     if (!ist->decoding_needed) {
2162         rate_emu_sleep(ist);
2163         ist->pts = ist->next_pts;
2164         switch (ist->st->codec->codec_type) {
2165         case AVMEDIA_TYPE_AUDIO:
2166             ist->next_pts += ((int64_t)AV_TIME_BASE * ist->st->codec->frame_size) /
2167                              ist->st->codec->sample_rate;
2168             break;
2169         case AVMEDIA_TYPE_VIDEO:
2170             if (ist->st->codec->time_base.num != 0) {
2171                 int ticks = ist->st->parser ? ist->st->parser->repeat_pict + 1 : ist->st->codec->ticks_per_frame;
2172                 ist->next_pts += ((int64_t)AV_TIME_BASE *
2173                                   ist->st->codec->time_base.num * ticks) /
2174                                   ist->st->codec->time_base.den;
2175             }
2176             break;
2177         }
2178     }
2179     for (i = 0; pkt && i < nb_ostreams; i++) {
2180         OutputStream *ost = &ost_table[i];
2181
2182         if (!check_output_constraints(ist, ost) || ost->encoding_needed)
2183             continue;
2184
2185         do_streamcopy(ist, ost, pkt);
2186     }
2187
2188     return 0;
2189 }
2190
2191 static void print_sdp(OutputFile *output_files, int n)
2192 {
2193     char sdp[2048];
2194     int i;
2195     AVFormatContext **avc = av_malloc(sizeof(*avc) * n);
2196
2197     if (!avc)
2198         exit_program(1);
2199     for (i = 0; i < n; i++)
2200         avc[i] = output_files[i].ctx;
2201
2202     av_sdp_create(avc, n, sdp, sizeof(sdp));
2203     printf("SDP:\n%s\n", sdp);
2204     fflush(stdout);
2205     av_freep(&avc);
2206 }
2207
2208 static int init_input_stream(int ist_index, OutputStream *output_streams, int nb_output_streams,
2209                              char *error, int error_len)
2210 {
2211     int i;
2212     InputStream *ist = &input_streams[ist_index];
2213     if (ist->decoding_needed) {
2214         AVCodec *codec = ist->dec;
2215         if (!codec) {
2216             snprintf(error, error_len, "Decoder (codec id %d) not found for input stream #%d:%d",
2217                     ist->st->codec->codec_id, ist->file_index, ist->st->index);
2218             return AVERROR(EINVAL);
2219         }
2220
2221         if (codec->type == AVMEDIA_TYPE_VIDEO && codec->capabilities & CODEC_CAP_DR1) {
2222             ist->st->codec->get_buffer     = codec_get_buffer;
2223             ist->st->codec->release_buffer = codec_release_buffer;
2224             ist->st->codec->opaque         = ist;
2225         }
2226
2227         if (avcodec_open2(ist->st->codec, codec, &ist->opts) < 0) {
2228             snprintf(error, error_len, "Error while opening decoder for input stream #%d:%d",
2229                     ist->file_index, ist->st->index);
2230             return AVERROR(EINVAL);
2231         }
2232         assert_codec_experimental(ist->st->codec, 0);
2233         assert_avoptions(ist->opts);
2234     }
2235
2236     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;
2237     ist->next_pts = AV_NOPTS_VALUE;
2238     ist->is_start = 1;
2239
2240     return 0;
2241 }
2242
2243 static int transcode_init(OutputFile *output_files,
2244                           int nb_output_files,
2245                           InputFile *input_files,
2246                           int nb_input_files)
2247 {
2248     int ret = 0, i, j, k;
2249     AVFormatContext *oc;
2250     AVCodecContext *codec, *icodec;
2251     OutputStream *ost;
2252     InputStream *ist;
2253     char error[1024];
2254     int want_sdp = 1;
2255
2256     /* init framerate emulation */
2257     for (i = 0; i < nb_input_files; i++) {
2258         InputFile *ifile = &input_files[i];
2259         if (ifile->rate_emu)
2260             for (j = 0; j < ifile->nb_streams; j++)
2261                 input_streams[j + ifile->ist_index].start = av_gettime();
2262     }
2263
2264     /* output stream init */
2265     for (i = 0; i < nb_output_files; i++) {
2266         oc = output_files[i].ctx;
2267         if (!oc->nb_streams && !(oc->oformat->flags & AVFMT_NOSTREAMS)) {
2268             av_dump_format(oc, i, oc->filename, 1);
2269             av_log(NULL, AV_LOG_ERROR, "Output file #%d does not contain any stream\n", i);
2270             return AVERROR(EINVAL);
2271         }
2272     }
2273
2274     /* for each output stream, we compute the right encoding parameters */
2275     for (i = 0; i < nb_output_streams; i++) {
2276         ost = &output_streams[i];
2277         oc  = output_files[ost->file_index].ctx;
2278         ist = &input_streams[ost->source_index];
2279
2280         if (ost->attachment_filename)
2281             continue;
2282
2283         codec  = ost->st->codec;
2284         icodec = ist->st->codec;
2285
2286         ost->st->disposition          = ist->st->disposition;
2287         codec->bits_per_raw_sample    = icodec->bits_per_raw_sample;
2288         codec->chroma_sample_location = icodec->chroma_sample_location;
2289
2290         if (ost->stream_copy) {
2291             uint64_t extra_size = (uint64_t)icodec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE;
2292
2293             if (extra_size > INT_MAX) {
2294                 return AVERROR(EINVAL);
2295             }
2296
2297             /* if stream_copy is selected, no need to decode or encode */
2298             codec->codec_id   = icodec->codec_id;
2299             codec->codec_type = icodec->codec_type;
2300
2301             if (!codec->codec_tag) {
2302                 if (!oc->oformat->codec_tag ||
2303                      av_codec_get_id (oc->oformat->codec_tag, icodec->codec_tag) == codec->codec_id ||
2304                      av_codec_get_tag(oc->oformat->codec_tag, icodec->codec_id) <= 0)
2305                     codec->codec_tag = icodec->codec_tag;
2306             }
2307
2308             codec->bit_rate       = icodec->bit_rate;
2309             codec->rc_max_rate    = icodec->rc_max_rate;
2310             codec->rc_buffer_size = icodec->rc_buffer_size;
2311             codec->field_order    = icodec->field_order;
2312             codec->extradata      = av_mallocz(extra_size);
2313             if (!codec->extradata) {
2314                 return AVERROR(ENOMEM);
2315             }
2316             memcpy(codec->extradata, icodec->extradata, icodec->extradata_size);
2317
2318             codec->extradata_size = icodec->extradata_size;
2319             if (!copy_tb) {
2320                 codec->time_base      = icodec->time_base;
2321                 codec->time_base.num *= icodec->ticks_per_frame;
2322                 av_reduce(&codec->time_base.num, &codec->time_base.den,
2323                           codec->time_base.num, codec->time_base.den, INT_MAX);
2324             } else
2325                 codec->time_base = ist->st->time_base;
2326
2327             switch (codec->codec_type) {
2328             case AVMEDIA_TYPE_AUDIO:
2329                 if (audio_volume != 256) {
2330                     av_log(NULL, AV_LOG_FATAL, "-acodec copy and -vol are incompatible (frames are not decoded)\n");
2331                     exit_program(1);
2332                 }
2333                 codec->channel_layout     = icodec->channel_layout;
2334                 codec->sample_rate        = icodec->sample_rate;
2335                 codec->channels           = icodec->channels;
2336                 codec->frame_size         = icodec->frame_size;
2337                 codec->audio_service_type = icodec->audio_service_type;
2338                 codec->block_align        = icodec->block_align;
2339                 break;
2340             case AVMEDIA_TYPE_VIDEO:
2341                 codec->pix_fmt            = icodec->pix_fmt;
2342                 codec->width              = icodec->width;
2343                 codec->height             = icodec->height;
2344                 codec->has_b_frames       = icodec->has_b_frames;
2345                 if (!codec->sample_aspect_ratio.num) {
2346                     codec->sample_aspect_ratio   =
2347                     ost->st->sample_aspect_ratio =
2348                         ist->st->sample_aspect_ratio.num ? ist->st->sample_aspect_ratio :
2349                         ist->st->codec->sample_aspect_ratio.num ?
2350                         ist->st->codec->sample_aspect_ratio : (AVRational){0, 1};
2351                 }
2352                 break;
2353             case AVMEDIA_TYPE_SUBTITLE:
2354                 codec->width  = icodec->width;
2355                 codec->height = icodec->height;
2356                 break;
2357             case AVMEDIA_TYPE_DATA:
2358             case AVMEDIA_TYPE_ATTACHMENT:
2359                 break;
2360             default:
2361                 abort();
2362             }
2363         } else {
2364             if (!ost->enc)
2365                 ost->enc = avcodec_find_encoder(ost->st->codec->codec_id);
2366
2367             ist->decoding_needed = 1;
2368             ost->encoding_needed = 1;
2369
2370             switch (codec->codec_type) {
2371             case AVMEDIA_TYPE_AUDIO:
2372                 ost->fifo = av_fifo_alloc(1024);
2373                 if (!ost->fifo) {
2374                     return AVERROR(ENOMEM);
2375                 }
2376                 ost->reformat_pair = MAKE_SFMT_PAIR(AV_SAMPLE_FMT_NONE,AV_SAMPLE_FMT_NONE);
2377
2378                 if (!codec->sample_rate)
2379                     codec->sample_rate = icodec->sample_rate;
2380                 choose_sample_rate(ost->st, ost->enc);
2381                 codec->time_base = (AVRational){ 1, codec->sample_rate };
2382
2383                 if (codec->sample_fmt == AV_SAMPLE_FMT_NONE)
2384                     codec->sample_fmt = icodec->sample_fmt;
2385                 choose_sample_fmt(ost->st, ost->enc);
2386
2387                 if (!codec->channels) {
2388                     codec->channels = icodec->channels;
2389                     codec->channel_layout = icodec->channel_layout;
2390                 }
2391                 if (av_get_channel_layout_nb_channels(codec->channel_layout) != codec->channels)
2392                     codec->channel_layout = 0;
2393
2394                 ost->audio_resample       = codec-> sample_rate != icodec->sample_rate || audio_sync_method > 1;
2395                 icodec->request_channels  = codec-> channels;
2396                 ost->resample_sample_fmt  = icodec->sample_fmt;
2397                 ost->resample_sample_rate = icodec->sample_rate;
2398                 ost->resample_channels    = icodec->channels;
2399                 break;
2400             case AVMEDIA_TYPE_VIDEO:
2401                 if (codec->pix_fmt == PIX_FMT_NONE)
2402                     codec->pix_fmt = icodec->pix_fmt;
2403                 choose_pixel_fmt(ost->st, ost->enc);
2404
2405                 if (ost->st->codec->pix_fmt == PIX_FMT_NONE) {
2406                     av_log(NULL, AV_LOG_FATAL, "Video pixel format is unknown, stream cannot be encoded\n");
2407                     exit_program(1);
2408                 }
2409
2410                 if (!codec->width || !codec->height) {
2411                     codec->width  = icodec->width;
2412                     codec->height = icodec->height;
2413                 }
2414
2415                 ost->video_resample = codec->width   != icodec->width  ||
2416                                       codec->height  != icodec->height ||
2417                                       codec->pix_fmt != icodec->pix_fmt;
2418                 if (ost->video_resample) {
2419                     codec->bits_per_raw_sample= frame_bits_per_raw_sample;
2420                 }
2421
2422                 ost->resample_height  = icodec->height;
2423                 ost->resample_width   = icodec->width;
2424                 ost->resample_pix_fmt = icodec->pix_fmt;
2425
2426                 if (!ost->frame_rate.num)
2427                     ost->frame_rate = ist->st->r_frame_rate.num ? ist->st->r_frame_rate : (AVRational) { 25, 1 };
2428                 if (ost->enc && ost->enc->supported_framerates && !ost->force_fps) {
2429                     int idx = av_find_nearest_q_idx(ost->frame_rate, ost->enc->supported_framerates);
2430                     ost->frame_rate = ost->enc->supported_framerates[idx];
2431                 }
2432                 codec->time_base = (AVRational){ost->frame_rate.den, ost->frame_rate.num};
2433                 if(   av_q2d(codec->time_base) < 0.001 && video_sync_method
2434                    && (video_sync_method==1 || (video_sync_method<0 && !(oc->oformat->flags & AVFMT_VARIABLE_FPS)))){
2435                     av_log(oc, AV_LOG_WARNING, "Frame rate very high for a muxer not effciciently supporting it.\n"
2436                                                "Please consider specifiying a lower framerate, a different muxer or -vsync 2\n");
2437                 }
2438
2439 #if CONFIG_AVFILTER
2440                 if (configure_video_filters(ist, ost)) {
2441                     av_log(NULL, AV_LOG_FATAL, "Error opening filters!\n");
2442                     exit(1);
2443                 }
2444 #endif
2445                 break;
2446             case AVMEDIA_TYPE_SUBTITLE:
2447                 break;
2448             default:
2449                 abort();
2450                 break;
2451             }
2452             /* two pass mode */
2453             if (codec->codec_id != CODEC_ID_H264 &&
2454                 (codec->flags & (CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2))) {
2455                 char logfilename[1024];
2456                 FILE *f;
2457
2458                 snprintf(logfilename, sizeof(logfilename), "%s-%d.log",
2459                          pass_logfilename_prefix ? pass_logfilename_prefix : DEFAULT_PASS_LOGFILENAME_PREFIX,
2460                          i);
2461                 if (codec->flags & CODEC_FLAG_PASS1) {
2462                     f = fopen(logfilename, "wb");
2463                     if (!f) {
2464                         av_log(NULL, AV_LOG_FATAL, "Cannot write log file '%s' for pass-1 encoding: %s\n",
2465                                logfilename, strerror(errno));
2466                         exit_program(1);
2467                     }
2468                     ost->logfile = f;
2469                 } else {
2470                     char  *logbuffer;
2471                     size_t logbuffer_size;
2472                     if (cmdutils_read_file(logfilename, &logbuffer, &logbuffer_size) < 0) {
2473                         av_log(NULL, AV_LOG_FATAL, "Error reading log file '%s' for pass-2 encoding\n",
2474                                logfilename);
2475                         exit_program(1);
2476                     }
2477                     codec->stats_in = logbuffer;
2478                 }
2479             }
2480         }
2481         if (codec->codec_type == AVMEDIA_TYPE_VIDEO) {
2482             /* maximum video buffer size is 6-bytes per pixel, plus DPX header size */
2483             int        size = codec->width * codec->height;
2484             bit_buffer_size = FFMAX(bit_buffer_size, 6 * size + 1664);
2485         }
2486     }
2487
2488     if (!bit_buffer)
2489         bit_buffer = av_malloc(bit_buffer_size);
2490     if (!bit_buffer) {
2491         av_log(NULL, AV_LOG_ERROR, "Cannot allocate %d bytes output buffer\n",
2492                bit_buffer_size);
2493         return AVERROR(ENOMEM);
2494     }
2495
2496     /* open each encoder */
2497     for (i = 0; i < nb_output_streams; i++) {
2498         ost = &output_streams[i];
2499         if (ost->encoding_needed) {
2500             AVCodec      *codec = ost->enc;
2501             AVCodecContext *dec = input_streams[ost->source_index].st->codec;
2502             if (!codec) {
2503                 snprintf(error, sizeof(error), "Encoder (codec id %d) not found for output stream #%d:%d",
2504                          ost->st->codec->codec_id, ost->file_index, ost->index);
2505                 ret = AVERROR(EINVAL);
2506                 goto dump_format;
2507             }
2508             if (dec->subtitle_header) {
2509                 ost->st->codec->subtitle_header = av_malloc(dec->subtitle_header_size);
2510                 if (!ost->st->codec->subtitle_header) {
2511                     ret = AVERROR(ENOMEM);
2512                     goto dump_format;
2513                 }
2514                 memcpy(ost->st->codec->subtitle_header, dec->subtitle_header, dec->subtitle_header_size);
2515                 ost->st->codec->subtitle_header_size = dec->subtitle_header_size;
2516             }
2517             if (avcodec_open2(ost->st->codec, codec, &ost->opts) < 0) {
2518                 snprintf(error, sizeof(error), "Error while opening encoder for output stream #%d:%d - maybe incorrect parameters such as bit_rate, rate, width or height",
2519                         ost->file_index, ost->index);
2520                 ret = AVERROR(EINVAL);
2521                 goto dump_format;
2522             }
2523             assert_codec_experimental(ost->st->codec, 1);
2524             assert_avoptions(ost->opts);
2525             if (ost->st->codec->bit_rate && ost->st->codec->bit_rate < 1000)
2526                 av_log(NULL, AV_LOG_WARNING, "The bitrate parameter is set too low."
2527                                              "It takes bits/s as argument, not kbits/s\n");
2528             extra_size += ost->st->codec->extradata_size;
2529
2530             if (ost->st->codec->me_threshold)
2531                 input_streams[ost->source_index].st->codec->debug |= FF_DEBUG_MV;
2532         }
2533     }
2534
2535     /* init input streams */
2536     for (i = 0; i < nb_input_streams; i++)
2537         if ((ret = init_input_stream(i, output_streams, nb_output_streams, error, sizeof(error))) < 0)
2538             goto dump_format;
2539
2540     /* discard unused programs */
2541     for (i = 0; i < nb_input_files; i++) {
2542         InputFile *ifile = &input_files[i];
2543         for (j = 0; j < ifile->ctx->nb_programs; j++) {
2544             AVProgram *p = ifile->ctx->programs[j];
2545             int discard  = AVDISCARD_ALL;
2546
2547             for (k = 0; k < p->nb_stream_indexes; k++)
2548                 if (!input_streams[ifile->ist_index + p->stream_index[k]].discard) {
2549                     discard = AVDISCARD_DEFAULT;
2550                     break;
2551                 }
2552             p->discard = discard;
2553         }
2554     }
2555
2556     /* open files and write file headers */
2557     for (i = 0; i < nb_output_files; i++) {
2558         oc = output_files[i].ctx;
2559         oc->interrupt_callback = int_cb;
2560         if (avformat_write_header(oc, &output_files[i].opts) < 0) {
2561             snprintf(error, sizeof(error), "Could not write header for output file #%d (incorrect codec parameters ?)", i);
2562             ret = AVERROR(EINVAL);
2563             goto dump_format;
2564         }
2565 //        assert_avoptions(output_files[i].opts);
2566         if (strcmp(oc->oformat->name, "rtp")) {
2567             want_sdp = 0;
2568         }
2569     }
2570
2571  dump_format:
2572     /* dump the file output parameters - cannot be done before in case
2573        of stream copy */
2574     for (i = 0; i < nb_output_files; i++) {
2575         av_dump_format(output_files[i].ctx, i, output_files[i].ctx->filename, 1);
2576     }
2577
2578     /* dump the stream mapping */
2579     av_log(NULL, AV_LOG_INFO, "Stream mapping:\n");
2580     for (i = 0; i < nb_output_streams; i++) {
2581         ost = &output_streams[i];
2582
2583         if (ost->attachment_filename) {
2584             /* an attached file */
2585             av_log(NULL, AV_LOG_INFO, "  File %s -> Stream #%d:%d\n",
2586                    ost->attachment_filename, ost->file_index, ost->index);
2587             continue;
2588         }
2589         av_log(NULL, AV_LOG_INFO, "  Stream #%d:%d -> #%d:%d",
2590                input_streams[ost->source_index].file_index,
2591                input_streams[ost->source_index].st->index,
2592                ost->file_index,
2593                ost->index);
2594         if (ost->sync_ist != &input_streams[ost->source_index])
2595             av_log(NULL, AV_LOG_INFO, " [sync #%d:%d]",
2596                    ost->sync_ist->file_index,
2597                    ost->sync_ist->st->index);
2598         if (ost->stream_copy)
2599             av_log(NULL, AV_LOG_INFO, " (copy)");
2600         else
2601             av_log(NULL, AV_LOG_INFO, " (%s -> %s)", input_streams[ost->source_index].dec ?
2602                    input_streams[ost->source_index].dec->name : "?",
2603                    ost->enc ? ost->enc->name : "?");
2604         av_log(NULL, AV_LOG_INFO, "\n");
2605     }
2606
2607     if (ret) {
2608         av_log(NULL, AV_LOG_ERROR, "%s\n", error);
2609         return ret;
2610     }
2611
2612     if (want_sdp) {
2613         print_sdp(output_files, nb_output_files);
2614     }
2615
2616     return 0;
2617 }
2618
2619 /*
2620  * The following code is the main loop of the file converter
2621  */
2622 static int transcode(OutputFile *output_files,
2623                      int nb_output_files,
2624                      InputFile *input_files,
2625                      int nb_input_files)
2626 {
2627     int ret, i;
2628     AVFormatContext *is, *os;
2629     OutputStream *ost;
2630     InputStream *ist;
2631     uint8_t *no_packet;
2632     int no_packet_count = 0;
2633     int64_t timer_start;
2634     int key;
2635
2636     if (!(no_packet = av_mallocz(nb_input_files)))
2637         exit_program(1);
2638
2639     ret = transcode_init(output_files, nb_output_files, input_files, nb_input_files);
2640     if (ret < 0)
2641         goto fail;
2642
2643     if (!using_stdin) {
2644         av_log(NULL, AV_LOG_INFO, "Press [q] to stop, [?] for help\n");
2645         avio_set_interrupt_cb(decode_interrupt_cb);
2646     }
2647     term_init();
2648
2649     timer_start = av_gettime();
2650
2651     for (; received_sigterm == 0;) {
2652         int file_index, ist_index;
2653         AVPacket pkt;
2654         int64_t ipts_min;
2655         double opts_min;
2656
2657         ipts_min = INT64_MAX;
2658         opts_min = 1e100;
2659         /* if 'q' pressed, exits */
2660         if (!using_stdin) {
2661             if (q_pressed)
2662                 break;
2663             /* read_key() returns 0 on EOF */
2664             key = read_key();
2665             if (key == 'q')
2666                 break;
2667             if (key == '+') av_log_set_level(av_log_get_level()+10);
2668             if (key == '-') av_log_set_level(av_log_get_level()-10);
2669             if (key == 's') qp_hist     ^= 1;
2670             if (key == 'h'){
2671                 if (do_hex_dump){
2672                     do_hex_dump = do_pkt_dump = 0;
2673                 } else if(do_pkt_dump){
2674                     do_hex_dump = 1;
2675                 } else
2676                     do_pkt_dump = 1;
2677                 av_log_set_level(AV_LOG_DEBUG);
2678             }
2679             if (key == 'd' || key == 'D'){
2680                 int debug=0;
2681                 if(key == 'D') {
2682                     debug = input_streams[0].st->codec->debug<<1;
2683                     if(!debug) debug = 1;
2684                     while(debug & (FF_DEBUG_DCT_COEFF|FF_DEBUG_VIS_QP|FF_DEBUG_VIS_MB_TYPE)) //unsupported, would just crash
2685                         debug += debug;
2686                 }else
2687                     scanf("%d", &debug);
2688                 for(i=0;i<nb_input_streams;i++) {
2689                     input_streams[i].st->codec->debug = debug;
2690                 }
2691                 for(i=0;i<nb_output_streams;i++) {
2692                     ost = &output_streams[i];
2693                     ost->st->codec->debug = debug;
2694                 }
2695                 if(debug) av_log_set_level(AV_LOG_DEBUG);
2696                 fprintf(stderr,"debug=%d\n", debug);
2697             }
2698             if (key == '?'){
2699                 fprintf(stderr, "key    function\n"
2700                                 "?      show this help\n"
2701                                 "+      increase verbosity\n"
2702                                 "-      decrease verbosity\n"
2703                                 "D      cycle through available debug modes\n"
2704                                 "h      dump packets/hex press to cycle through the 3 states\n"
2705                                 "q      quit\n"
2706                                 "s      Show QP histogram\n"
2707                 );
2708             }
2709         }
2710
2711         /* select the stream that we must read now by looking at the
2712            smallest output pts */
2713         file_index = -1;
2714         for (i = 0; i < nb_output_streams; i++) {
2715             OutputFile *of;
2716             int64_t ipts;
2717             double  opts;
2718             ost = &output_streams[i];
2719             of = &output_files[ost->file_index];
2720             os = output_files[ost->file_index].ctx;
2721             ist = &input_streams[ost->source_index];
2722             if (ost->is_past_recording_time || no_packet[ist->file_index] ||
2723                 (os->pb && avio_tell(os->pb) >= of->limit_filesize))
2724                 continue;
2725             opts = ost->st->pts.val * av_q2d(ost->st->time_base);
2726             ipts = ist->pts;
2727             if (!input_files[ist->file_index].eof_reached) {
2728                 if (ipts < ipts_min) {
2729                     ipts_min = ipts;
2730                     if (input_sync)
2731                         file_index = ist->file_index;
2732                 }
2733                 if (opts < opts_min) {
2734                     opts_min = opts;
2735                     if (!input_sync) file_index = ist->file_index;
2736                 }
2737             }
2738             if (ost->frame_number >= ost->max_frames) {
2739                 int j;
2740                 for (j = 0; j < of->ctx->nb_streams; j++)
2741                     output_streams[of->ost_index + j].is_past_recording_time = 1;
2742                 continue;
2743             }
2744         }
2745         /* if none, if is finished */
2746         if (file_index < 0) {
2747             if (no_packet_count) {
2748                 no_packet_count = 0;
2749                 memset(no_packet, 0, nb_input_files);
2750                 usleep(10000);
2751                 continue;
2752             }
2753             break;
2754         }
2755
2756         /* read a frame from it and output it in the fifo */
2757         is  = input_files[file_index].ctx;
2758         ret = av_read_frame(is, &pkt);
2759         if (ret == AVERROR(EAGAIN)) {
2760             no_packet[file_index] = 1;
2761             no_packet_count++;
2762             continue;
2763         }
2764         if (ret < 0) {
2765             input_files[file_index].eof_reached = 1;
2766             if (opt_shortest)
2767                 break;
2768             else
2769                 continue;
2770         }
2771
2772         no_packet_count = 0;
2773         memset(no_packet, 0, nb_input_files);
2774
2775         if (do_pkt_dump) {
2776             av_pkt_dump_log2(NULL, AV_LOG_DEBUG, &pkt, do_hex_dump,
2777                              is->streams[pkt.stream_index]);
2778         }
2779         /* the following test is needed in case new streams appear
2780            dynamically in stream : we ignore them */
2781         if (pkt.stream_index >= input_files[file_index].nb_streams)
2782             goto discard_packet;
2783         ist_index = input_files[file_index].ist_index + pkt.stream_index;
2784         ist = &input_streams[ist_index];
2785         if (ist->discard)
2786             goto discard_packet;
2787
2788         if (pkt.dts != AV_NOPTS_VALUE)
2789             pkt.dts += av_rescale_q(input_files[ist->file_index].ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
2790         if (pkt.pts != AV_NOPTS_VALUE)
2791             pkt.pts += av_rescale_q(input_files[ist->file_index].ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
2792
2793         if (pkt.pts != AV_NOPTS_VALUE)
2794             pkt.pts *= ist->ts_scale;
2795         if (pkt.dts != AV_NOPTS_VALUE)
2796             pkt.dts *= ist->ts_scale;
2797
2798         //fprintf(stderr, "next:%"PRId64" dts:%"PRId64" off:%"PRId64" %d\n",
2799         //        ist->next_pts,
2800         //        pkt.dts, input_files[ist->file_index].ts_offset,
2801         //        ist->st->codec->codec_type);
2802         if (pkt.dts != AV_NOPTS_VALUE && ist->next_pts != AV_NOPTS_VALUE
2803             && (is->iformat->flags & AVFMT_TS_DISCONT)) {
2804             int64_t pkt_dts = av_rescale_q(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q);
2805             int64_t delta   = pkt_dts - ist->next_pts;
2806             if ((FFABS(delta) > 1LL * dts_delta_threshold * AV_TIME_BASE || pkt_dts + 1 < ist->pts) && !copy_ts) {
2807                 input_files[ist->file_index].ts_offset -= delta;
2808                 av_log(NULL, AV_LOG_DEBUG,
2809                        "timestamp discontinuity %"PRId64", new offset= %"PRId64"\n",
2810                        delta, input_files[ist->file_index].ts_offset);
2811                 pkt.dts-= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
2812                 if (pkt.pts != AV_NOPTS_VALUE)
2813                     pkt.pts-= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
2814             }
2815         }
2816
2817         // fprintf(stderr,"read #%d.%d size=%d\n", ist->file_index, ist->st->index, pkt.size);
2818         if (output_packet(ist, output_streams, nb_output_streams, &pkt) < 0) {
2819
2820             av_log(NULL, AV_LOG_ERROR, "Error while decoding stream #%d:%d\n",
2821                    ist->file_index, ist->st->index);
2822             if (exit_on_error)
2823                 exit_program(1);
2824             av_free_packet(&pkt);
2825             continue;
2826         }
2827
2828     discard_packet:
2829         av_free_packet(&pkt);
2830
2831         /* dump report by using the output first video and audio streams */
2832         print_report(output_files, output_streams, nb_output_streams, 0, timer_start);
2833     }
2834
2835     /* at the end of stream, we must flush the decoder buffers */
2836     for (i = 0; i < nb_input_streams; i++) {
2837         ist = &input_streams[i];
2838         if (ist->decoding_needed) {
2839             output_packet(ist, output_streams, nb_output_streams, NULL);
2840         }
2841     }
2842     flush_encoders(output_streams, nb_output_streams);
2843
2844     term_exit();
2845
2846     /* write the trailer if needed and close file */
2847     for (i = 0; i < nb_output_files; i++) {
2848         os = output_files[i].ctx;
2849         av_write_trailer(os);
2850     }
2851
2852     /* dump report by using the first video and audio streams */
2853     print_report(output_files, output_streams, nb_output_streams, 1, timer_start);
2854
2855     /* close each encoder */
2856     for (i = 0; i < nb_output_streams; i++) {
2857         ost = &output_streams[i];
2858         if (ost->encoding_needed) {
2859             av_freep(&ost->st->codec->stats_in);
2860             avcodec_close(ost->st->codec);
2861         }
2862 #if CONFIG_AVFILTER
2863         avfilter_graph_free(&ost->graph);
2864 #endif
2865     }
2866
2867     /* close each decoder */
2868     for (i = 0; i < nb_input_streams; i++) {
2869         ist = &input_streams[i];
2870         if (ist->decoding_needed) {
2871             avcodec_close(ist->st->codec);
2872         }
2873     }
2874
2875     /* finished ! */
2876     ret = 0;
2877
2878  fail:
2879     av_freep(&bit_buffer);
2880     av_freep(&no_packet);
2881
2882     if (output_streams) {
2883         for (i = 0; i < nb_output_streams; i++) {
2884             ost = &output_streams[i];
2885             if (ost) {
2886                 if (ost->stream_copy)
2887                     av_freep(&ost->st->codec->extradata);
2888                 if (ost->logfile) {
2889                     fclose(ost->logfile);
2890                     ost->logfile = NULL;
2891                 }
2892                 av_fifo_free(ost->fifo); /* works even if fifo is not
2893                                              initialized but set to zero */
2894                 av_freep(&ost->st->codec->subtitle_header);
2895                 av_free(ost->resample_frame.data[0]);
2896                 av_free(ost->forced_kf_pts);
2897                 if (ost->video_resample)
2898                     sws_freeContext(ost->img_resample_ctx);
2899                 if (ost->resample)
2900                     audio_resample_close(ost->resample);
2901                 if (ost->reformat_ctx)
2902                     av_audio_convert_free(ost->reformat_ctx);
2903                 av_dict_free(&ost->opts);
2904             }
2905         }
2906     }
2907     return ret;
2908 }
2909
2910 static double parse_frame_aspect_ratio(const char *arg)
2911 {
2912     int x = 0, y = 0;
2913     double ar = 0;
2914     const char *p;
2915     char *end;
2916
2917     p = strchr(arg, ':');
2918     if (p) {
2919         x = strtol(arg, &end, 10);
2920         if (end == p)
2921             y = strtol(end + 1, &end, 10);
2922         if (x > 0 && y > 0)
2923             ar = (double)x / (double)y;
2924     } else
2925         ar = strtod(arg, NULL);
2926
2927     if (!ar) {
2928         av_log(NULL, AV_LOG_FATAL, "Incorrect aspect ratio specification.\n");
2929         exit_program(1);
2930     }
2931     return ar;
2932 }
2933
2934 static int opt_audio_codec(OptionsContext *o, const char *opt, const char *arg)
2935 {
2936     return parse_option(o, "codec:a", arg, options);
2937 }
2938
2939 static int opt_video_codec(OptionsContext *o, const char *opt, const char *arg)
2940 {
2941     return parse_option(o, "codec:v", arg, options);
2942 }
2943
2944 static int opt_subtitle_codec(OptionsContext *o, const char *opt, const char *arg)
2945 {
2946     return parse_option(o, "codec:s", arg, options);
2947 }
2948
2949 static int opt_data_codec(OptionsContext *o, const char *opt, const char *arg)
2950 {
2951     return parse_option(o, "codec:d", arg, options);
2952 }
2953
2954 static int opt_map(OptionsContext *o, const char *opt, const char *arg)
2955 {
2956     StreamMap *m = NULL;
2957     int i, negative = 0, file_idx;
2958     int sync_file_idx = -1, sync_stream_idx;
2959     char *p, *sync;
2960     char *map;
2961
2962     if (*arg == '-') {
2963         negative = 1;
2964         arg++;
2965     }
2966     map = av_strdup(arg);
2967
2968     /* parse sync stream first, just pick first matching stream */
2969     if (sync = strchr(map, ',')) {
2970         *sync = 0;
2971         sync_file_idx = strtol(sync + 1, &sync, 0);
2972         if (sync_file_idx >= nb_input_files || sync_file_idx < 0) {
2973             av_log(NULL, AV_LOG_FATAL, "Invalid sync file index: %d.\n", sync_file_idx);
2974             exit_program(1);
2975         }
2976         if (*sync)
2977             sync++;
2978         for (i = 0; i < input_files[sync_file_idx].nb_streams; i++)
2979             if (check_stream_specifier(input_files[sync_file_idx].ctx,
2980                                        input_files[sync_file_idx].ctx->streams[i], sync) == 1) {
2981                 sync_stream_idx = i;
2982                 break;
2983             }
2984         if (i == input_files[sync_file_idx].nb_streams) {
2985             av_log(NULL, AV_LOG_FATAL, "Sync stream specification in map %s does not "
2986                                        "match any streams.\n", arg);
2987             exit_program(1);
2988         }
2989     }
2990
2991
2992     file_idx = strtol(map, &p, 0);
2993     if (file_idx >= nb_input_files || file_idx < 0) {
2994         av_log(NULL, AV_LOG_FATAL, "Invalid input file index: %d.\n", file_idx);
2995         exit_program(1);
2996     }
2997     if (negative)
2998         /* disable some already defined maps */
2999         for (i = 0; i < o->nb_stream_maps; i++) {
3000             m = &o->stream_maps[i];
3001             if (file_idx == m->file_index &&
3002                 check_stream_specifier(input_files[m->file_index].ctx,
3003                                        input_files[m->file_index].ctx->streams[m->stream_index],
3004                                        *p == ':' ? p + 1 : p) > 0)
3005                 m->disabled = 1;
3006         }
3007     else
3008         for (i = 0; i < input_files[file_idx].nb_streams; i++) {
3009             if (check_stream_specifier(input_files[file_idx].ctx, input_files[file_idx].ctx->streams[i],
3010                         *p == ':' ? p + 1 : p) <= 0)
3011                 continue;
3012             o->stream_maps = grow_array(o->stream_maps, sizeof(*o->stream_maps),
3013                                         &o->nb_stream_maps, o->nb_stream_maps + 1);
3014             m = &o->stream_maps[o->nb_stream_maps - 1];
3015
3016             m->file_index   = file_idx;
3017             m->stream_index = i;
3018
3019             if (sync_file_idx >= 0) {
3020                 m->sync_file_index   = sync_file_idx;
3021                 m->sync_stream_index = sync_stream_idx;
3022             } else {
3023                 m->sync_file_index   = file_idx;
3024                 m->sync_stream_index = i;
3025             }
3026         }
3027
3028     if (!m) {
3029         av_log(NULL, AV_LOG_FATAL, "Stream map '%s' matches no streams.\n", arg);
3030         exit_program(1);
3031     }
3032
3033     av_freep(&map);
3034     return 0;
3035 }
3036
3037 static int opt_attach(OptionsContext *o, const char *opt, const char *arg)
3038 {
3039     o->attachments = grow_array(o->attachments, sizeof(*o->attachments),
3040                                 &o->nb_attachments, o->nb_attachments + 1);
3041     o->attachments[o->nb_attachments - 1] = arg;
3042     return 0;
3043 }
3044
3045 /**
3046  * Parse a metadata specifier in arg.
3047  * @param type metadata type is written here -- g(lobal)/s(tream)/c(hapter)/p(rogram)
3048  * @param index for type c/p, chapter/program index is written here
3049  * @param stream_spec for type s, the stream specifier is written here
3050  */
3051 static void parse_meta_type(char *arg, char *type, int *index, const char **stream_spec)
3052 {
3053     if (*arg) {
3054         *type = *arg;
3055         switch (*arg) {
3056         case 'g':
3057             break;
3058         case 's':
3059             if (*(++arg) && *arg != ':') {
3060                 av_log(NULL, AV_LOG_FATAL, "Invalid metadata specifier %s.\n", arg);
3061                 exit_program(1);
3062             }
3063             *stream_spec = *arg == ':' ? arg + 1 : "";
3064             break;
3065         case 'c':
3066         case 'p':
3067             if (*(++arg) == ':')
3068                 *index = strtol(++arg, NULL, 0);
3069             break;
3070         default:
3071             av_log(NULL, AV_LOG_FATAL, "Invalid metadata type %c.\n", *arg);
3072             exit_program(1);
3073         }
3074     } else
3075         *type = 'g';
3076 }
3077
3078 static int copy_metadata(char *outspec, char *inspec, AVFormatContext *oc, AVFormatContext *ic, OptionsContext *o)
3079 {
3080     AVDictionary **meta_in = NULL;
3081     AVDictionary **meta_out;
3082     int i, ret = 0;
3083     char type_in, type_out;
3084     const char *istream_spec = NULL, *ostream_spec = NULL;
3085     int idx_in = 0, idx_out = 0;
3086
3087     parse_meta_type(inspec,  &type_in,  &idx_in,  &istream_spec);
3088     parse_meta_type(outspec, &type_out, &idx_out, &ostream_spec);
3089
3090     if (type_in == 'g' || type_out == 'g')
3091         o->metadata_global_manual = 1;
3092     if (type_in == 's' || type_out == 's')
3093         o->metadata_streams_manual = 1;
3094     if (type_in == 'c' || type_out == 'c')
3095         o->metadata_chapters_manual = 1;
3096
3097 #define METADATA_CHECK_INDEX(index, nb_elems, desc)\
3098     if ((index) < 0 || (index) >= (nb_elems)) {\
3099         av_log(NULL, AV_LOG_FATAL, "Invalid %s index %d while processing metadata maps.\n",\
3100                 (desc), (index));\
3101         exit_program(1);\
3102     }
3103
3104 #define SET_DICT(type, meta, context, index)\
3105         switch (type) {\
3106         case 'g':\
3107             meta = &context->metadata;\
3108             break;\
3109         case 'c':\
3110             METADATA_CHECK_INDEX(index, context->nb_chapters, "chapter")\
3111             meta = &context->chapters[index]->metadata;\
3112             break;\
3113         case 'p':\
3114             METADATA_CHECK_INDEX(index, context->nb_programs, "program")\
3115             meta = &context->programs[index]->metadata;\
3116             break;\
3117         }\
3118
3119     SET_DICT(type_in, meta_in, ic, idx_in);
3120     SET_DICT(type_out, meta_out, oc, idx_out);
3121
3122     /* for input streams choose first matching stream */
3123     if (type_in == 's') {
3124         for (i = 0; i < ic->nb_streams; i++) {
3125             if ((ret = check_stream_specifier(ic, ic->streams[i], istream_spec)) > 0) {
3126                 meta_in = &ic->streams[i]->metadata;
3127                 break;
3128             } else if (ret < 0)
3129                 exit_program(1);
3130         }
3131         if (!meta_in) {
3132             av_log(NULL, AV_LOG_FATAL, "Stream specifier %s does not match  any streams.\n", istream_spec);
3133             exit_program(1);
3134         }
3135     }
3136
3137     if (type_out == 's') {
3138         for (i = 0; i < oc->nb_streams; i++) {
3139             if ((ret = check_stream_specifier(oc, oc->streams[i], ostream_spec)) > 0) {
3140                 meta_out = &oc->streams[i]->metadata;
3141                 av_dict_copy(meta_out, *meta_in, AV_DICT_DONT_OVERWRITE);
3142             } else if (ret < 0)
3143                 exit_program(1);
3144         }
3145     } else
3146         av_dict_copy(meta_out, *meta_in, AV_DICT_DONT_OVERWRITE);
3147
3148     return 0;
3149 }
3150
3151 static AVCodec *find_codec_or_die(const char *name, enum AVMediaType type, int encoder)
3152 {
3153     const char *codec_string = encoder ? "encoder" : "decoder";
3154     AVCodec *codec;
3155
3156     codec = encoder ?
3157         avcodec_find_encoder_by_name(name) :
3158         avcodec_find_decoder_by_name(name);
3159     if (!codec) {
3160         av_log(NULL, AV_LOG_FATAL, "Unknown %s '%s'\n", codec_string, name);
3161         exit_program(1);
3162     }
3163     if (codec->type != type) {
3164         av_log(NULL, AV_LOG_FATAL, "Invalid %s type '%s'\n", codec_string, name);
3165         exit_program(1);
3166     }
3167     return codec;
3168 }
3169
3170 static AVCodec *choose_decoder(OptionsContext *o, AVFormatContext *s, AVStream *st)
3171 {
3172     char *codec_name = NULL;
3173
3174     MATCH_PER_STREAM_OPT(codec_names, str, codec_name, s, st);
3175     if (codec_name) {
3176         AVCodec *codec = find_codec_or_die(codec_name, st->codec->codec_type, 0);
3177         st->codec->codec_id = codec->id;
3178         return codec;
3179     } else
3180         return avcodec_find_decoder(st->codec->codec_id);
3181 }
3182
3183 /**
3184  * Add all the streams from the given input file to the global
3185  * list of input streams.
3186  */
3187 static void add_input_streams(OptionsContext *o, AVFormatContext *ic)
3188 {
3189     int i, rfps, rfps_base;
3190
3191     for (i = 0; i < ic->nb_streams; i++) {
3192         AVStream *st = ic->streams[i];
3193         AVCodecContext *dec = st->codec;
3194         InputStream *ist;
3195
3196         input_streams = grow_array(input_streams, sizeof(*input_streams), &nb_input_streams, nb_input_streams + 1);
3197         ist = &input_streams[nb_input_streams - 1];
3198         ist->st = st;
3199         ist->file_index = nb_input_files;
3200         ist->discard = 1;
3201         ist->opts = filter_codec_opts(codec_opts, choose_decoder(o, ic, st), ic, st);
3202
3203         ist->ts_scale = 1.0;
3204         MATCH_PER_STREAM_OPT(ts_scale, dbl, ist->ts_scale, ic, st);
3205
3206         ist->dec = choose_decoder(o, ic, st);
3207
3208         switch (dec->codec_type) {
3209         case AVMEDIA_TYPE_AUDIO:
3210             if(!ist->dec)
3211                 ist->dec = avcodec_find_decoder(dec->codec_id);
3212             if(o->audio_disable)
3213                 st->discard = AVDISCARD_ALL;
3214             break;
3215         case AVMEDIA_TYPE_VIDEO:
3216             if(!ist->dec)
3217                 ist->dec = avcodec_find_decoder(dec->codec_id);
3218             rfps      = ic->streams[i]->r_frame_rate.num;
3219             rfps_base = ic->streams[i]->r_frame_rate.den;
3220             if (dec->lowres) {
3221                 dec->flags |= CODEC_FLAG_EMU_EDGE;
3222             }
3223
3224             if (dec->time_base.den != rfps * dec->ticks_per_frame || dec->time_base.num != rfps_base) {
3225
3226                 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",
3227                        i, (float)dec->time_base.den / dec->time_base.num, dec->time_base.den, dec->time_base.num,
3228                        (float)rfps / rfps_base, rfps, rfps_base);
3229             }
3230
3231             if (o->video_disable)
3232                 st->discard = AVDISCARD_ALL;
3233             else if (video_discard)
3234                 st->discard = video_discard;
3235             break;
3236         case AVMEDIA_TYPE_DATA:
3237             break;
3238         case AVMEDIA_TYPE_SUBTITLE:
3239             if(!ist->dec)
3240                 ist->dec = avcodec_find_decoder(dec->codec_id);
3241             if(o->subtitle_disable)
3242                 st->discard = AVDISCARD_ALL;
3243             break;
3244         case AVMEDIA_TYPE_ATTACHMENT:
3245         case AVMEDIA_TYPE_UNKNOWN:
3246             break;
3247         default:
3248             abort();
3249         }
3250     }
3251 }
3252
3253 static void assert_file_overwrite(const char *filename)
3254 {
3255     if ((!file_overwrite || no_file_overwrite) &&
3256         (strchr(filename, ':') == NULL || filename[1] == ':' ||
3257          av_strstart(filename, "file:", NULL))) {
3258         if (avio_check(filename, 0) == 0) {
3259             if (!using_stdin && (!no_file_overwrite || file_overwrite)) {
3260                 fprintf(stderr,"File '%s' already exists. Overwrite ? [y/N] ", filename);
3261                 fflush(stderr);
3262                 if (!read_yesno()) {
3263                     fprintf(stderr, "Not overwriting - exiting\n");
3264                     exit_program(1);
3265                 }
3266             }
3267             else {
3268                 fprintf(stderr,"File '%s' already exists. Exiting.\n", filename);
3269                 exit_program(1);
3270             }
3271         }
3272     }
3273 }
3274
3275 static void dump_attachment(AVStream *st, const char *filename)
3276 {
3277     int ret;
3278     AVIOContext *out = NULL;
3279     AVDictionaryEntry *e;
3280
3281     if (!st->codec->extradata_size) {
3282         av_log(NULL, AV_LOG_WARNING, "No extradata to dump in stream #%d:%d.\n",
3283                nb_input_files - 1, st->index);
3284         return;
3285     }
3286     if (!*filename && (e = av_dict_get(st->metadata, "filename", NULL, 0)))
3287         filename = e->value;
3288     if (!*filename) {
3289         av_log(NULL, AV_LOG_FATAL, "No filename specified and no 'filename' tag"
3290                "in stream #%d:%d.\n", nb_input_files - 1, st->index);
3291         exit_program(1);
3292     }
3293
3294     assert_file_overwrite(filename);
3295
3296     if ((ret = avio_open2(&out, filename, AVIO_FLAG_WRITE, &int_cb, NULL)) < 0) {
3297         av_log(NULL, AV_LOG_FATAL, "Could not open file %s for writing.\n",
3298                filename);
3299         exit_program(1);
3300     }
3301
3302     avio_write(out, st->codec->extradata, st->codec->extradata_size);
3303     avio_flush(out);
3304     avio_close(out);
3305 }
3306
3307 static int opt_input_file(OptionsContext *o, const char *opt, const char *filename)
3308 {
3309     AVFormatContext *ic;
3310     AVInputFormat *file_iformat = NULL;
3311     int err, i, ret;
3312     int64_t timestamp;
3313     uint8_t buf[128];
3314     AVDictionary **opts;
3315     int orig_nb_streams;                     // number of streams before avformat_find_stream_info
3316
3317     if (o->format) {
3318         if (!(file_iformat = av_find_input_format(o->format))) {
3319             av_log(NULL, AV_LOG_FATAL, "Unknown input format: '%s'\n", o->format);
3320             exit_program(1);
3321         }
3322     }
3323
3324     if (!strcmp(filename, "-"))
3325         filename = "pipe:";
3326
3327     using_stdin |= !strncmp(filename, "pipe:", 5) ||
3328                     !strcmp(filename, "/dev/stdin");
3329
3330     /* get default parameters from command line */
3331     ic = avformat_alloc_context();
3332     if (!ic) {
3333         print_error(filename, AVERROR(ENOMEM));
3334         exit_program(1);
3335     }
3336     if (o->nb_audio_sample_rate) {
3337         snprintf(buf, sizeof(buf), "%d", o->audio_sample_rate[o->nb_audio_sample_rate - 1].u.i);
3338         av_dict_set(&format_opts, "sample_rate", buf, 0);
3339     }
3340     if (o->nb_audio_channels) {
3341         snprintf(buf, sizeof(buf), "%d", o->audio_channels[o->nb_audio_channels - 1].u.i);
3342         av_dict_set(&format_opts, "channels", buf, 0);
3343     }
3344     if (o->nb_frame_rates) {
3345         av_dict_set(&format_opts, "framerate", o->frame_rates[o->nb_frame_rates - 1].u.str, 0);
3346     }
3347     if (o->nb_frame_sizes) {
3348         av_dict_set(&format_opts, "video_size", o->frame_sizes[o->nb_frame_sizes - 1].u.str, 0);
3349     }
3350     if (o->nb_frame_pix_fmts)
3351         av_dict_set(&format_opts, "pixel_format", o->frame_pix_fmts[o->nb_frame_pix_fmts - 1].u.str, 0);
3352
3353     ic->flags |= AVFMT_FLAG_NONBLOCK;
3354     ic->interrupt_callback = int_cb;
3355
3356     /* open the input file with generic avformat function */
3357     err = avformat_open_input(&ic, filename, file_iformat, &format_opts);
3358     if (err < 0) {
3359         print_error(filename, err);
3360         exit_program(1);
3361     }
3362     assert_avoptions(format_opts);
3363
3364     /* apply forced codec ids */
3365     for (i = 0; i < ic->nb_streams; i++)
3366         choose_decoder(o, ic, ic->streams[i]);
3367
3368     /* Set AVCodecContext options for avformat_find_stream_info */
3369     opts = setup_find_stream_info_opts(ic, codec_opts);
3370     orig_nb_streams = ic->nb_streams;
3371
3372     /* If not enough info to get the stream parameters, we decode the
3373        first frames to get it. (used in mpeg case for example) */
3374     ret = avformat_find_stream_info(ic, opts);
3375     if (ret < 0) {
3376         av_log(NULL, AV_LOG_FATAL, "%s: could not find codec parameters\n", filename);
3377         avformat_close_input(&ic);
3378         exit_program(1);
3379     }
3380
3381     timestamp = o->start_time;
3382     /* add the stream start time */
3383     if (ic->start_time != AV_NOPTS_VALUE)
3384         timestamp += ic->start_time;
3385
3386     /* if seeking requested, we execute it */
3387     if (o->start_time != 0) {
3388         ret = av_seek_frame(ic, -1, timestamp, AVSEEK_FLAG_BACKWARD);
3389         if (ret < 0) {
3390             av_log(NULL, AV_LOG_WARNING, "%s: could not seek to position %0.3f\n",
3391                    filename, (double)timestamp / AV_TIME_BASE);
3392         }
3393     }
3394
3395     /* update the current parameters so that they match the one of the input stream */
3396     add_input_streams(o, ic);
3397
3398     /* dump the file content */
3399     av_dump_format(ic, nb_input_files, filename, 0);
3400
3401     input_files = grow_array(input_files, sizeof(*input_files), &nb_input_files, nb_input_files + 1);
3402     input_files[nb_input_files - 1].ctx        = ic;
3403     input_files[nb_input_files - 1].ist_index  = nb_input_streams - ic->nb_streams;
3404     input_files[nb_input_files - 1].ts_offset  = o->input_ts_offset - (copy_ts ? 0 : timestamp);
3405     input_files[nb_input_files - 1].nb_streams = ic->nb_streams;
3406     input_files[nb_input_files - 1].rate_emu   = o->rate_emu;
3407
3408     for (i = 0; i < o->nb_dump_attachment; i++) {
3409         int j;
3410
3411         for (j = 0; j < ic->nb_streams; j++) {
3412             AVStream *st = ic->streams[j];
3413
3414             if (check_stream_specifier(ic, st, o->dump_attachment[i].specifier) == 1)
3415                 dump_attachment(st, o->dump_attachment[i].u.str);
3416         }
3417     }
3418
3419     for (i = 0; i < orig_nb_streams; i++)
3420         av_dict_free(&opts[i]);
3421     av_freep(&opts);
3422
3423     reset_options(o);
3424     return 0;
3425 }
3426
3427 static void parse_forced_key_frames(char *kf, OutputStream *ost,
3428                                     AVCodecContext *avctx)
3429 {
3430     char *p;
3431     int n = 1, i;
3432     int64_t t;
3433
3434     for (p = kf; *p; p++)
3435         if (*p == ',')
3436             n++;
3437     ost->forced_kf_count = n;
3438     ost->forced_kf_pts   = av_malloc(sizeof(*ost->forced_kf_pts) * n);
3439     if (!ost->forced_kf_pts) {
3440         av_log(NULL, AV_LOG_FATAL, "Could not allocate forced key frames array.\n");
3441         exit_program(1);
3442     }
3443     for (i = 0; i < n; i++) {
3444         p = i ? strchr(p, ',') + 1 : kf;
3445         t = parse_time_or_die("force_key_frames", p, 1);
3446         ost->forced_kf_pts[i] = av_rescale_q(t, AV_TIME_BASE_Q, avctx->time_base);
3447     }
3448 }
3449
3450 static uint8_t *get_line(AVIOContext *s)
3451 {
3452     AVIOContext *line;
3453     uint8_t *buf;
3454     char c;
3455
3456     if (avio_open_dyn_buf(&line) < 0) {
3457         av_log(NULL, AV_LOG_FATAL, "Could not alloc buffer for reading preset.\n");
3458         exit_program(1);
3459     }
3460
3461     while ((c = avio_r8(s)) && c != '\n')
3462         avio_w8(line, c);
3463     avio_w8(line, 0);
3464     avio_close_dyn_buf(line, &buf);
3465
3466     return buf;
3467 }
3468
3469 static int get_preset_file_2(const char *preset_name, const char *codec_name, AVIOContext **s)
3470 {
3471     int i, ret = 1;
3472     char filename[1000];
3473     const char *base[3] = { getenv("AVCONV_DATADIR"),
3474                             getenv("HOME"),
3475                             AVCONV_DATADIR,
3476                             };
3477
3478     for (i = 0; i < FF_ARRAY_ELEMS(base) && ret; i++) {
3479         if (!base[i])
3480             continue;
3481         if (codec_name) {
3482             snprintf(filename, sizeof(filename), "%s%s/%s-%s.avpreset", base[i],
3483                      i != 1 ? "" : "/.avconv", codec_name, preset_name);
3484             ret = avio_open2(s, filename, AVIO_FLAG_READ, &int_cb, NULL);
3485         }
3486         if (ret) {
3487             snprintf(filename, sizeof(filename), "%s%s/%s.avpreset", base[i],
3488                      i != 1 ? "" : "/.avconv", preset_name);
3489             ret = avio_open2(s, filename, AVIO_FLAG_READ, &int_cb, NULL);
3490         }
3491     }
3492     return ret;
3493 }
3494
3495 static void choose_encoder(OptionsContext *o, AVFormatContext *s, OutputStream *ost)
3496 {
3497     char *codec_name = NULL;
3498
3499     MATCH_PER_STREAM_OPT(codec_names, str, codec_name, s, ost->st);
3500     if (!codec_name) {
3501         ost->st->codec->codec_id = av_guess_codec(s->oformat, NULL, s->filename,
3502                                                   NULL, ost->st->codec->codec_type);
3503         ost->enc = avcodec_find_encoder(ost->st->codec->codec_id);
3504     } else if (!strcmp(codec_name, "copy"))
3505         ost->stream_copy = 1;
3506     else {
3507         ost->enc = find_codec_or_die(codec_name, ost->st->codec->codec_type, 1);
3508         ost->st->codec->codec_id = ost->enc->id;
3509     }
3510 }
3511
3512 static OutputStream *new_output_stream(OptionsContext *o, AVFormatContext *oc, enum AVMediaType type)
3513 {
3514     OutputStream *ost;
3515     AVStream *st = avformat_new_stream(oc, NULL);
3516     int idx      = oc->nb_streams - 1, ret = 0;
3517     char *bsf = NULL, *next, *codec_tag = NULL;
3518     AVBitStreamFilterContext *bsfc, *bsfc_prev = NULL;
3519     double qscale = -1;
3520     char *buf = NULL, *arg = NULL, *preset = NULL;
3521     AVIOContext *s = NULL;
3522
3523     if (!st) {
3524         av_log(NULL, AV_LOG_FATAL, "Could not alloc stream.\n");
3525         exit_program(1);
3526     }
3527
3528     if (oc->nb_streams - 1 < o->nb_streamid_map)
3529         st->id = o->streamid_map[oc->nb_streams - 1];
3530
3531     output_streams = grow_array(output_streams, sizeof(*output_streams), &nb_output_streams,
3532                                 nb_output_streams + 1);
3533     ost = &output_streams[nb_output_streams - 1];
3534     ost->file_index = nb_output_files;
3535     ost->index      = idx;
3536     ost->st         = st;
3537     st->codec->codec_type = type;
3538     choose_encoder(o, oc, ost);
3539     if (ost->enc) {
3540         ost->opts  = filter_codec_opts(codec_opts, ost->enc, oc, st);
3541     }
3542
3543     avcodec_get_context_defaults3(st->codec, ost->enc);
3544     st->codec->codec_type = type; // XXX hack, avcodec_get_context_defaults2() sets type to unknown for stream copy
3545
3546     MATCH_PER_STREAM_OPT(presets, str, preset, oc, st);
3547     if (preset && (!(ret = get_preset_file_2(preset, ost->enc->name, &s)))) {
3548         do  {
3549             buf = get_line(s);
3550             if (!buf[0] || buf[0] == '#') {
3551                 av_free(buf);
3552                 continue;
3553             }
3554             if (!(arg = strchr(buf, '='))) {
3555                 av_log(NULL, AV_LOG_FATAL, "Invalid line found in the preset file.\n");
3556                 exit_program(1);
3557             }
3558             *arg++ = 0;
3559             av_dict_set(&ost->opts, buf, arg, AV_DICT_DONT_OVERWRITE);
3560             av_free(buf);
3561         } while (!s->eof_reached);
3562         avio_close(s);
3563     }
3564     if (ret) {
3565         av_log(NULL, AV_LOG_FATAL,
3566                "Preset %s specified for stream %d:%d, but could not be opened.\n",
3567                preset, ost->file_index, ost->index);
3568         exit_program(1);
3569     }
3570
3571     ost->max_frames = INT64_MAX;
3572     MATCH_PER_STREAM_OPT(max_frames, i64, ost->max_frames, oc, st);
3573
3574     MATCH_PER_STREAM_OPT(bitstream_filters, str, bsf, oc, st);
3575     while (bsf) {
3576         if (next = strchr(bsf, ','))
3577             *next++ = 0;
3578         if (!(bsfc = av_bitstream_filter_init(bsf))) {
3579             av_log(NULL, AV_LOG_FATAL, "Unknown bitstream filter %s\n", bsf);
3580             exit_program(1);
3581         }
3582         if (bsfc_prev)
3583             bsfc_prev->next = bsfc;
3584         else
3585             ost->bitstream_filters = bsfc;
3586
3587         bsfc_prev = bsfc;
3588         bsf       = next;
3589     }
3590
3591     MATCH_PER_STREAM_OPT(codec_tags, str, codec_tag, oc, st);
3592     if (codec_tag) {
3593         uint32_t tag = strtol(codec_tag, &next, 0);
3594         if (*next)
3595             tag = AV_RL32(codec_tag);
3596         st->codec->codec_tag = tag;
3597     }
3598
3599     MATCH_PER_STREAM_OPT(qscale, dbl, qscale, oc, st);
3600     if (qscale >= 0 || same_quant) {
3601         st->codec->flags |= CODEC_FLAG_QSCALE;
3602         st->codec->global_quality = FF_QP2LAMBDA * qscale;
3603     }
3604
3605     if (oc->oformat->flags & AVFMT_GLOBALHEADER)
3606         st->codec->flags |= CODEC_FLAG_GLOBAL_HEADER;
3607
3608     av_opt_get_int(sws_opts, "sws_flags", 0, &ost->sws_flags);
3609     return ost;
3610 }
3611
3612 static void parse_matrix_coeffs(uint16_t *dest, const char *str)
3613 {
3614     int i;
3615     const char *p = str;
3616     for (i = 0;; i++) {
3617         dest[i] = atoi(p);
3618         if (i == 63)
3619             break;
3620         p = strchr(p, ',');
3621         if (!p) {
3622             av_log(NULL, AV_LOG_FATAL, "Syntax error in matrix \"%s\" at coeff %d\n", str, i);
3623             exit_program(1);
3624         }
3625         p++;
3626     }
3627 }
3628
3629 static OutputStream *new_video_stream(OptionsContext *o, AVFormatContext *oc)
3630 {
3631     AVStream *st;
3632     OutputStream *ost;
3633     AVCodecContext *video_enc;
3634
3635     ost = new_output_stream(o, oc, AVMEDIA_TYPE_VIDEO);
3636     st  = ost->st;
3637     video_enc = st->codec;
3638
3639     if (!ost->stream_copy) {
3640         const char *p = NULL;
3641         char *forced_key_frames = NULL, *frame_rate = NULL, *frame_size = NULL;
3642         char *frame_aspect_ratio = NULL, *frame_pix_fmt = NULL;
3643         char *intra_matrix = NULL, *inter_matrix = NULL, *filters = NULL;
3644         int i;
3645
3646         MATCH_PER_STREAM_OPT(frame_rates, str, frame_rate, oc, st);
3647         if (frame_rate && av_parse_video_rate(&ost->frame_rate, frame_rate) < 0) {
3648             av_log(NULL, AV_LOG_FATAL, "Invalid framerate value: %s\n", frame_rate);
3649             exit_program(1);
3650         }
3651
3652         MATCH_PER_STREAM_OPT(frame_sizes, str, frame_size, oc, st);
3653         if (frame_size && av_parse_video_size(&video_enc->width, &video_enc->height, frame_size) < 0) {
3654             av_log(NULL, AV_LOG_FATAL, "Invalid frame size: %s.\n", frame_size);
3655             exit_program(1);
3656         }
3657
3658         MATCH_PER_STREAM_OPT(frame_aspect_ratios, str, frame_aspect_ratio, oc, st);
3659         if (frame_aspect_ratio)
3660             ost->frame_aspect_ratio = parse_frame_aspect_ratio(frame_aspect_ratio);
3661
3662         MATCH_PER_STREAM_OPT(frame_pix_fmts, str, frame_pix_fmt, oc, st);
3663         if (frame_pix_fmt && (video_enc->pix_fmt = av_get_pix_fmt(frame_pix_fmt)) == PIX_FMT_NONE) {
3664             av_log(NULL, AV_LOG_FATAL, "Unknown pixel format requested: %s.\n", frame_pix_fmt);
3665             exit_program(1);
3666         }
3667         st->sample_aspect_ratio = video_enc->sample_aspect_ratio;
3668
3669         MATCH_PER_STREAM_OPT(intra_matrices, str, intra_matrix, oc, st);
3670         if (intra_matrix) {
3671             if (!(video_enc->intra_matrix = av_mallocz(sizeof(*video_enc->intra_matrix) * 64))) {
3672                 av_log(NULL, AV_LOG_FATAL, "Could not allocate memory for intra matrix.\n");
3673                 exit_program(1);
3674             }
3675             parse_matrix_coeffs(video_enc->intra_matrix, intra_matrix);
3676         }
3677         MATCH_PER_STREAM_OPT(inter_matrices, str, inter_matrix, oc, st);
3678         if (inter_matrix) {
3679             if (!(video_enc->inter_matrix = av_mallocz(sizeof(*video_enc->inter_matrix) * 64))) {
3680                 av_log(NULL, AV_LOG_FATAL, "Could not allocate memory for inter matrix.\n");
3681                 exit_program(1);
3682             }
3683             parse_matrix_coeffs(video_enc->inter_matrix, inter_matrix);
3684         }
3685
3686         MATCH_PER_STREAM_OPT(rc_overrides, str, p, oc, st);
3687         for (i = 0; p; i++) {
3688             int start, end, q;
3689             int e = sscanf(p, "%d,%d,%d", &start, &end, &q);
3690             if (e != 3) {
3691                 av_log(NULL, AV_LOG_FATAL, "error parsing rc_override\n");
3692                 exit_program(1);
3693             }
3694             video_enc->rc_override =
3695                 av_realloc(video_enc->rc_override,
3696                            sizeof(RcOverride) * (i + 1));
3697             video_enc->rc_override[i].start_frame = start;
3698             video_enc->rc_override[i].end_frame   = end;
3699             if (q > 0) {
3700                 video_enc->rc_override[i].qscale         = q;
3701                 video_enc->rc_override[i].quality_factor = 1.0;
3702             }
3703             else {
3704                 video_enc->rc_override[i].qscale         = 0;
3705                 video_enc->rc_override[i].quality_factor = -q/100.0;
3706             }
3707             p = strchr(p, '/');
3708             if (p) p++;
3709         }
3710         video_enc->rc_override_count = i;
3711         if (!video_enc->rc_initial_buffer_occupancy)
3712             video_enc->rc_initial_buffer_occupancy = video_enc->rc_buffer_size * 3 / 4;
3713         video_enc->intra_dc_precision = intra_dc_precision - 8;
3714
3715         /* two pass mode */
3716         if (do_pass) {
3717             if (do_pass == 1) {
3718                 video_enc->flags |= CODEC_FLAG_PASS1;
3719             } else {
3720                 video_enc->flags |= CODEC_FLAG_PASS2;
3721             }
3722         }
3723
3724         MATCH_PER_STREAM_OPT(forced_key_frames, str, forced_key_frames, oc, st);
3725         if (forced_key_frames)
3726             parse_forced_key_frames(forced_key_frames, ost, video_enc);
3727
3728         MATCH_PER_STREAM_OPT(force_fps, i, ost->force_fps, oc, st);
3729
3730         ost->top_field_first = -1;
3731         MATCH_PER_STREAM_OPT(top_field_first, i, ost->top_field_first, oc, st);
3732
3733         MATCH_PER_STREAM_OPT(copy_initial_nonkeyframes, i, ost->copy_initial_nonkeyframes, oc ,st);
3734
3735 #if CONFIG_AVFILTER
3736         MATCH_PER_STREAM_OPT(filters, str, filters, oc, st);
3737         if (filters)
3738             ost->avfilter = av_strdup(filters);
3739 #endif
3740     }
3741
3742     return ost;
3743 }
3744
3745 static OutputStream *new_audio_stream(OptionsContext *o, AVFormatContext *oc)
3746 {
3747     AVStream *st;
3748     OutputStream *ost;
3749     AVCodecContext *audio_enc;
3750
3751     ost = new_output_stream(o, oc, AVMEDIA_TYPE_AUDIO);
3752     st  = ost->st;
3753
3754     audio_enc = st->codec;
3755     audio_enc->codec_type = AVMEDIA_TYPE_AUDIO;
3756
3757     if (!ost->stream_copy) {
3758         char *sample_fmt = NULL;
3759
3760         MATCH_PER_STREAM_OPT(audio_channels, i, audio_enc->channels, oc, st);
3761
3762         MATCH_PER_STREAM_OPT(sample_fmts, str, sample_fmt, oc, st);
3763         if (sample_fmt &&
3764             (audio_enc->sample_fmt = av_get_sample_fmt(sample_fmt)) == AV_SAMPLE_FMT_NONE) {
3765             av_log(NULL, AV_LOG_FATAL, "Invalid sample format '%s'\n", sample_fmt);
3766             exit_program(1);
3767         }
3768
3769         MATCH_PER_STREAM_OPT(audio_sample_rate, i, audio_enc->sample_rate, oc, st);
3770     }
3771
3772     return ost;
3773 }
3774
3775 static OutputStream *new_data_stream(OptionsContext *o, AVFormatContext *oc)
3776 {
3777     OutputStream *ost;
3778
3779     ost = new_output_stream(o, oc, AVMEDIA_TYPE_DATA);
3780     if (!ost->stream_copy) {
3781         av_log(NULL, AV_LOG_FATAL, "Data stream encoding not supported yet (only streamcopy)\n");
3782         exit_program(1);
3783     }
3784
3785     return ost;
3786 }
3787
3788 static OutputStream *new_attachment_stream(OptionsContext *o, AVFormatContext *oc)
3789 {
3790     OutputStream *ost = new_output_stream(o, oc, AVMEDIA_TYPE_ATTACHMENT);
3791     ost->stream_copy = 1;
3792     return ost;
3793 }
3794
3795 static OutputStream *new_subtitle_stream(OptionsContext *o, AVFormatContext *oc)
3796 {
3797     AVStream *st;
3798     OutputStream *ost;
3799     AVCodecContext *subtitle_enc;
3800
3801     ost = new_output_stream(o, oc, AVMEDIA_TYPE_SUBTITLE);
3802     st  = ost->st;
3803     subtitle_enc = st->codec;
3804
3805     subtitle_enc->codec_type = AVMEDIA_TYPE_SUBTITLE;
3806
3807     return ost;
3808 }
3809
3810 /* arg format is "output-stream-index:streamid-value". */
3811 static int opt_streamid(OptionsContext *o, const char *opt, const char *arg)
3812 {
3813     int idx;
3814     char *p;
3815     char idx_str[16];
3816
3817     av_strlcpy(idx_str, arg, sizeof(idx_str));
3818     p = strchr(idx_str, ':');
3819     if (!p) {
3820         av_log(NULL, AV_LOG_FATAL,
3821                "Invalid value '%s' for option '%s', required syntax is 'index:value'\n",
3822                arg, opt);
3823         exit_program(1);
3824     }
3825     *p++ = '\0';
3826     idx = parse_number_or_die(opt, idx_str, OPT_INT, 0, MAX_STREAMS-1);
3827     o->streamid_map = grow_array(o->streamid_map, sizeof(*o->streamid_map), &o->nb_streamid_map, idx+1);
3828     o->streamid_map[idx] = parse_number_or_die(opt, p, OPT_INT, 0, INT_MAX);
3829     return 0;
3830 }
3831
3832 static int copy_chapters(InputFile *ifile, OutputFile *ofile, int copy_metadata)
3833 {
3834     AVFormatContext *is = ifile->ctx;
3835     AVFormatContext *os = ofile->ctx;
3836     int i;
3837
3838     for (i = 0; i < is->nb_chapters; i++) {
3839         AVChapter *in_ch = is->chapters[i], *out_ch;
3840         int64_t ts_off   = av_rescale_q(ofile->start_time - ifile->ts_offset,
3841                                        AV_TIME_BASE_Q, in_ch->time_base);
3842         int64_t rt       = (ofile->recording_time == INT64_MAX) ? INT64_MAX :
3843                            av_rescale_q(ofile->recording_time, AV_TIME_BASE_Q, in_ch->time_base);
3844
3845
3846         if (in_ch->end < ts_off)
3847             continue;
3848         if (rt != INT64_MAX && in_ch->start > rt + ts_off)
3849             break;
3850
3851         out_ch = av_mallocz(sizeof(AVChapter));
3852         if (!out_ch)
3853             return AVERROR(ENOMEM);
3854
3855         out_ch->id        = in_ch->id;
3856         out_ch->time_base = in_ch->time_base;
3857         out_ch->start     = FFMAX(0,  in_ch->start - ts_off);
3858         out_ch->end       = FFMIN(rt, in_ch->end   - ts_off);
3859
3860         if (copy_metadata)
3861             av_dict_copy(&out_ch->metadata, in_ch->metadata, 0);
3862
3863         os->nb_chapters++;
3864         os->chapters = av_realloc(os->chapters, sizeof(AVChapter) * os->nb_chapters);
3865         if (!os->chapters)
3866             return AVERROR(ENOMEM);
3867         os->chapters[os->nb_chapters - 1] = out_ch;
3868     }
3869     return 0;
3870 }
3871
3872 static void opt_output_file(void *optctx, const char *filename)
3873 {
3874     OptionsContext *o = optctx;
3875     AVFormatContext *oc;
3876     int i, err;
3877     AVOutputFormat *file_oformat;
3878     OutputStream *ost;
3879     InputStream  *ist;
3880
3881     if (!strcmp(filename, "-"))
3882         filename = "pipe:";
3883
3884     err = avformat_alloc_output_context2(&oc, NULL, o->format, filename);
3885     if (!oc) {
3886         print_error(filename, err);
3887         exit_program(1);
3888     }
3889
3890     file_oformat= oc->oformat;
3891     oc->interrupt_callback = int_cb;
3892
3893     if (!o->nb_stream_maps) {
3894         /* pick the "best" stream of each type */
3895 #define NEW_STREAM(type, index)\
3896         if (index >= 0) {\
3897             ost = new_ ## type ## _stream(o, oc);\
3898             ost->source_index = index;\
3899             ost->sync_ist     = &input_streams[index];\
3900             input_streams[index].discard = 0;\
3901         }
3902
3903         /* video: highest resolution */
3904         if (!o->video_disable && oc->oformat->video_codec != CODEC_ID_NONE) {
3905             int area = 0, idx = -1;
3906             for (i = 0; i < nb_input_streams; i++) {
3907                 ist = &input_streams[i];
3908                 if (ist->st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
3909                     ist->st->codec->width * ist->st->codec->height > area) {
3910                     area = ist->st->codec->width * ist->st->codec->height;
3911                     idx = i;
3912                 }
3913             }
3914             NEW_STREAM(video, idx);
3915         }
3916
3917         /* audio: most channels */
3918         if (!o->audio_disable && oc->oformat->audio_codec != CODEC_ID_NONE) {
3919             int channels = 0, idx = -1;
3920             for (i = 0; i < nb_input_streams; i++) {
3921                 ist = &input_streams[i];
3922                 if (ist->st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
3923                     ist->st->codec->channels > channels) {
3924                     channels = ist->st->codec->channels;
3925                     idx = i;
3926                 }
3927             }
3928             NEW_STREAM(audio, idx);
3929         }
3930
3931         /* subtitles: pick first */
3932         if (!o->subtitle_disable && oc->oformat->subtitle_codec != CODEC_ID_NONE) {
3933             for (i = 0; i < nb_input_streams; i++)
3934                 if (input_streams[i].st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
3935                     NEW_STREAM(subtitle, i);
3936                     break;
3937                 }
3938         }
3939         /* do something with data? */
3940     } else {
3941         for (i = 0; i < o->nb_stream_maps; i++) {
3942             StreamMap *map = &o->stream_maps[i];
3943
3944             if (map->disabled)
3945                 continue;
3946
3947             ist = &input_streams[input_files[map->file_index].ist_index + map->stream_index];
3948             switch (ist->st->codec->codec_type) {
3949             case AVMEDIA_TYPE_VIDEO:    ost = new_video_stream(o, oc);    break;
3950             case AVMEDIA_TYPE_AUDIO:    ost = new_audio_stream(o, oc);    break;
3951             case AVMEDIA_TYPE_SUBTITLE: ost = new_subtitle_stream(o, oc); break;
3952             case AVMEDIA_TYPE_DATA:     ost = new_data_stream(o, oc);     break;
3953             case AVMEDIA_TYPE_ATTACHMENT: ost = new_attachment_stream(o, oc); break;
3954             default:
3955                 av_log(NULL, AV_LOG_FATAL, "Cannot map stream #%d:%d - unsupported type.\n",
3956                        map->file_index, map->stream_index);
3957                 exit_program(1);
3958             }
3959
3960             ost->source_index = input_files[map->file_index].ist_index + map->stream_index;
3961             ost->sync_ist     = &input_streams[input_files[map->sync_file_index].ist_index +
3962                                            map->sync_stream_index];
3963             ist->discard = 0;
3964         }
3965     }
3966
3967     /* handle attached files */
3968     for (i = 0; i < o->nb_attachments; i++) {
3969         AVIOContext *pb;
3970         uint8_t *attachment;
3971         const char *p;
3972         int64_t len;
3973
3974         if ((err = avio_open2(&pb, o->attachments[i], AVIO_FLAG_READ, &int_cb, NULL)) < 0) {
3975             av_log(NULL, AV_LOG_FATAL, "Could not open attachment file %s.\n",
3976                    o->attachments[i]);
3977             exit_program(1);
3978         }
3979         if ((len = avio_size(pb)) <= 0) {
3980             av_log(NULL, AV_LOG_FATAL, "Could not get size of the attachment %s.\n",
3981                    o->attachments[i]);
3982             exit_program(1);
3983         }
3984         if (!(attachment = av_malloc(len))) {
3985             av_log(NULL, AV_LOG_FATAL, "Attachment %s too large to fit into memory.\n",
3986                    o->attachments[i]);
3987             exit_program(1);
3988         }
3989         avio_read(pb, attachment, len);
3990
3991         ost = new_attachment_stream(o, oc);
3992         ost->stream_copy               = 0;
3993         ost->source_index              = -1;
3994         ost->attachment_filename       = o->attachments[i];
3995         ost->st->codec->extradata      = attachment;
3996         ost->st->codec->extradata_size = len;
3997
3998         p = strrchr(o->attachments[i], '/');
3999         av_dict_set(&ost->st->metadata, "filename", (p && *p) ? p + 1 : o->attachments[i], AV_DICT_DONT_OVERWRITE);
4000         avio_close(pb);
4001     }
4002
4003     output_files = grow_array(output_files, sizeof(*output_files), &nb_output_files, nb_output_files + 1);
4004     output_files[nb_output_files - 1].ctx       = oc;
4005     output_files[nb_output_files - 1].ost_index = nb_output_streams - oc->nb_streams;
4006     output_files[nb_output_files - 1].recording_time = o->recording_time;
4007     output_files[nb_output_files - 1].start_time     = o->start_time;
4008     output_files[nb_output_files - 1].limit_filesize = o->limit_filesize;
4009     av_dict_copy(&output_files[nb_output_files - 1].opts, format_opts, 0);
4010
4011     /* check filename in case of an image number is expected */
4012     if (oc->oformat->flags & AVFMT_NEEDNUMBER) {
4013         if (!av_filename_number_test(oc->filename)) {
4014             print_error(oc->filename, AVERROR(EINVAL));
4015             exit_program(1);
4016         }
4017     }
4018
4019     if (!(oc->oformat->flags & AVFMT_NOFILE)) {
4020         /* test if it already exists to avoid losing precious files */
4021         assert_file_overwrite(filename);
4022
4023         /* open the file */
4024         if ((err = avio_open2(&oc->pb, filename, AVIO_FLAG_WRITE,
4025                               &oc->interrupt_callback,
4026                               &output_files[nb_output_files - 1].opts)) < 0) {
4027             print_error(filename, err);
4028             exit_program(1);
4029         }
4030     }
4031
4032     if (o->mux_preload) {
4033         uint8_t buf[64];
4034         snprintf(buf, sizeof(buf), "%d", (int)(o->mux_preload*AV_TIME_BASE));
4035         av_dict_set(&output_files[nb_output_files - 1].opts, "preload", buf, 0);
4036     }
4037     oc->max_delay = (int)(o->mux_max_delay * AV_TIME_BASE);
4038
4039     /* copy metadata */
4040     for (i = 0; i < o->nb_metadata_map; i++) {
4041         char *p;
4042         int in_file_index = strtol(o->metadata_map[i].u.str, &p, 0);
4043
4044         if (in_file_index < 0)
4045             continue;
4046         if (in_file_index >= nb_input_files) {
4047             av_log(NULL, AV_LOG_FATAL, "Invalid input file index %d while processing metadata maps\n", in_file_index);
4048             exit_program(1);
4049         }
4050         copy_metadata(o->metadata_map[i].specifier, *p ? p + 1 : p, oc, input_files[in_file_index].ctx, o);
4051     }
4052
4053     /* copy chapters */
4054     if (o->chapters_input_file >= nb_input_files) {
4055         if (o->chapters_input_file == INT_MAX) {
4056             /* copy chapters from the first input file that has them*/
4057             o->chapters_input_file = -1;
4058             for (i = 0; i < nb_input_files; i++)
4059                 if (input_files[i].ctx->nb_chapters) {
4060                     o->chapters_input_file = i;
4061                     break;
4062                 }
4063         } else {
4064             av_log(NULL, AV_LOG_FATAL, "Invalid input file index %d in chapter mapping.\n",
4065                    o->chapters_input_file);
4066             exit_program(1);
4067         }
4068     }
4069     if (o->chapters_input_file >= 0)
4070         copy_chapters(&input_files[o->chapters_input_file], &output_files[nb_output_files - 1],
4071                       !o->metadata_chapters_manual);
4072
4073     /* copy global metadata by default */
4074     if (!o->metadata_global_manual && nb_input_files)
4075         av_dict_copy(&oc->metadata, input_files[0].ctx->metadata,
4076                      AV_DICT_DONT_OVERWRITE);
4077     if (!o->metadata_streams_manual)
4078         for (i = output_files[nb_output_files - 1].ost_index; i < nb_output_streams; i++) {
4079             InputStream *ist;
4080             if (output_streams[i].source_index < 0)         /* this is true e.g. for attached files */
4081                 continue;
4082             ist = &input_streams[output_streams[i].source_index];
4083             av_dict_copy(&output_streams[i].st->metadata, ist->st->metadata, AV_DICT_DONT_OVERWRITE);
4084         }
4085
4086     /* process manually set metadata */
4087     for (i = 0; i < o->nb_metadata; i++) {
4088         AVDictionary **m;
4089         char type, *val;
4090         const char *stream_spec;
4091         int index = 0, j, ret;
4092
4093         val = strchr(o->metadata[i].u.str, '=');
4094         if (!val) {
4095             av_log(NULL, AV_LOG_FATAL, "No '=' character in metadata string %s.\n",
4096                    o->metadata[i].u.str);
4097             exit_program(1);
4098         }
4099         *val++ = 0;
4100
4101         parse_meta_type(o->metadata[i].specifier, &type, &index, &stream_spec);
4102         if (type == 's') {
4103             for (j = 0; j < oc->nb_streams; j++) {
4104                 if ((ret = check_stream_specifier(oc, oc->streams[j], stream_spec)) > 0) {
4105                     av_dict_set(&oc->streams[j]->metadata, o->metadata[i].u.str, *val ? val : NULL, 0);
4106                 } else if (ret < 0)
4107                     exit_program(1);
4108             }
4109             printf("ret %d, stream_spec %s\n", ret, stream_spec);
4110         }
4111         else {
4112             switch (type) {
4113             case 'g':
4114                 m = &oc->metadata;
4115                 break;
4116             case 'c':
4117                 if (index < 0 || index >= oc->nb_chapters) {
4118                     av_log(NULL, AV_LOG_FATAL, "Invalid chapter index %d in metadata specifier.\n", index);
4119                     exit_program(1);
4120                 }
4121                 m = &oc->chapters[index]->metadata;
4122                 break;
4123             default:
4124                 av_log(NULL, AV_LOG_FATAL, "Invalid metadata specifier %s.\n", o->metadata[i].specifier);
4125                 exit_program(1);
4126             }
4127             av_dict_set(m, o->metadata[i].u.str, *val ? val : NULL, 0);
4128         }
4129     }
4130
4131     reset_options(o);
4132 }
4133
4134 /* same option as mencoder */
4135 static int opt_pass(const char *opt, const char *arg)
4136 {
4137     do_pass = parse_number_or_die(opt, arg, OPT_INT, 1, 2);
4138     return 0;
4139 }
4140
4141 static int64_t getutime(void)
4142 {
4143 #if HAVE_GETRUSAGE
4144     struct rusage rusage;
4145
4146     getrusage(RUSAGE_SELF, &rusage);
4147     return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
4148 #elif HAVE_GETPROCESSTIMES
4149     HANDLE proc;
4150     FILETIME c, e, k, u;
4151     proc = GetCurrentProcess();
4152     GetProcessTimes(proc, &c, &e, &k, &u);
4153     return ((int64_t) u.dwHighDateTime << 32 | u.dwLowDateTime) / 10;
4154 #else
4155     return av_gettime();
4156 #endif
4157 }
4158
4159 static int64_t getmaxrss(void)
4160 {
4161 #if HAVE_GETRUSAGE && HAVE_STRUCT_RUSAGE_RU_MAXRSS
4162     struct rusage rusage;
4163     getrusage(RUSAGE_SELF, &rusage);
4164     return (int64_t)rusage.ru_maxrss * 1024;
4165 #elif HAVE_GETPROCESSMEMORYINFO
4166     HANDLE proc;
4167     PROCESS_MEMORY_COUNTERS memcounters;
4168     proc = GetCurrentProcess();
4169     memcounters.cb = sizeof(memcounters);
4170     GetProcessMemoryInfo(proc, &memcounters, sizeof(memcounters));
4171     return memcounters.PeakPagefileUsage;
4172 #else
4173     return 0;
4174 #endif
4175 }
4176
4177 static int opt_audio_qscale(OptionsContext *o, const char *opt, const char *arg)
4178 {
4179     return parse_option(o, "q:a", arg, options);
4180 }
4181
4182 static void show_usage(void)
4183 {
4184     printf("Hyper fast Audio and Video encoder\n");
4185     printf("usage: %s [options] [[infile options] -i infile]... {[outfile options] outfile}...\n", program_name);
4186     printf("\n");
4187 }
4188
4189 static int opt_help(const char *opt, const char *arg)
4190 {
4191     int flags = AV_OPT_FLAG_DECODING_PARAM | AV_OPT_FLAG_ENCODING_PARAM;
4192     av_log_set_callback(log_callback_help);
4193     show_usage();
4194     show_help_options(options, "Main options:\n",
4195                       OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_SUBTITLE | OPT_GRAB, 0);
4196     show_help_options(options, "\nAdvanced options:\n",
4197                       OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_SUBTITLE | OPT_GRAB,
4198                       OPT_EXPERT);
4199     show_help_options(options, "\nVideo options:\n",
4200                       OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
4201                       OPT_VIDEO);
4202     show_help_options(options, "\nAdvanced Video options:\n",
4203                       OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
4204                       OPT_VIDEO | OPT_EXPERT);
4205     show_help_options(options, "\nAudio options:\n",
4206                       OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
4207                       OPT_AUDIO);
4208     show_help_options(options, "\nAdvanced Audio options:\n",
4209                       OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
4210                       OPT_AUDIO | OPT_EXPERT);
4211     show_help_options(options, "\nSubtitle options:\n",
4212                       OPT_SUBTITLE | OPT_GRAB,
4213                       OPT_SUBTITLE);
4214     show_help_options(options, "\nAudio/Video grab options:\n",
4215                       OPT_GRAB,
4216                       OPT_GRAB);
4217     printf("\n");
4218     show_help_children(avcodec_get_class(), flags);
4219     show_help_children(avformat_get_class(), flags);
4220     show_help_children(sws_get_class(), flags);
4221
4222     return 0;
4223 }
4224
4225 static int opt_target(OptionsContext *o, const char *opt, const char *arg)
4226 {
4227     enum { PAL, NTSC, FILM, UNKNOWN } norm = UNKNOWN;
4228     static const char *const frame_rates[] = { "25", "30000/1001", "24000/1001" };
4229
4230     if (!strncmp(arg, "pal-", 4)) {
4231         norm = PAL;
4232         arg += 4;
4233     } else if (!strncmp(arg, "ntsc-", 5)) {
4234         norm = NTSC;
4235         arg += 5;
4236     } else if (!strncmp(arg, "film-", 5)) {
4237         norm = FILM;
4238         arg += 5;
4239     } else {
4240         /* Try to determine PAL/NTSC by peeking in the input files */
4241         if (nb_input_files) {
4242             int i, j, fr;
4243             for (j = 0; j < nb_input_files; j++) {
4244                 for (i = 0; i < input_files[j].nb_streams; i++) {
4245                     AVCodecContext *c = input_files[j].ctx->streams[i]->codec;
4246                     if (c->codec_type != AVMEDIA_TYPE_VIDEO)
4247                         continue;
4248                     fr = c->time_base.den * 1000 / c->time_base.num;
4249                     if (fr == 25000) {
4250                         norm = PAL;
4251                         break;
4252                     } else if ((fr == 29970) || (fr == 23976)) {
4253                         norm = NTSC;
4254                         break;
4255                     }
4256                 }
4257                 if (norm != UNKNOWN)
4258                     break;
4259             }
4260         }
4261         if (norm != UNKNOWN)
4262             av_log(NULL, AV_LOG_INFO, "Assuming %s for target.\n", norm == PAL ? "PAL" : "NTSC");
4263     }
4264
4265     if (norm == UNKNOWN) {
4266         av_log(NULL, AV_LOG_FATAL, "Could not determine norm (PAL/NTSC/NTSC-Film) for target.\n");
4267         av_log(NULL, AV_LOG_FATAL, "Please prefix target with \"pal-\", \"ntsc-\" or \"film-\",\n");
4268         av_log(NULL, AV_LOG_FATAL, "or set a framerate with \"-r xxx\".\n");
4269         exit_program(1);
4270     }
4271
4272     if (!strcmp(arg, "vcd")) {
4273         opt_video_codec(o, "c:v", "mpeg1video");
4274         opt_audio_codec(o, "c:a", "mp2");
4275         parse_option(o, "f", "vcd", options);
4276
4277         parse_option(o, "s", norm == PAL ? "352x288" : "352x240", options);
4278         parse_option(o, "r", frame_rates[norm], options);
4279         opt_default("g", norm == PAL ? "15" : "18");
4280
4281         opt_default("b", "1150000");
4282         opt_default("maxrate", "1150000");
4283         opt_default("minrate", "1150000");
4284         opt_default("bufsize", "327680"); // 40*1024*8;
4285
4286         opt_default("b:a", "224000");
4287         parse_option(o, "ar", "44100", options);
4288         parse_option(o, "ac", "2", options);
4289
4290         opt_default("packetsize", "2324");
4291         opt_default("muxrate", "1411200"); // 2352 * 75 * 8;
4292
4293         /* We have to offset the PTS, so that it is consistent with the SCR.
4294            SCR starts at 36000, but the first two packs contain only padding
4295            and the first pack from the other stream, respectively, may also have
4296            been written before.
4297            So the real data starts at SCR 36000+3*1200. */
4298         o->mux_preload = (36000 + 3 * 1200) / 90000.0; // 0.44
4299     } else if (!strcmp(arg, "svcd")) {
4300
4301         opt_video_codec(o, "c:v", "mpeg2video");
4302         opt_audio_codec(o, "c:a", "mp2");
4303         parse_option(o, "f", "svcd", options);
4304
4305         parse_option(o, "s", norm == PAL ? "480x576" : "480x480", options);
4306         parse_option(o, "r", frame_rates[norm], options);
4307         opt_default("g", norm == PAL ? "15" : "18");
4308
4309         opt_default("b", "2040000");
4310         opt_default("maxrate", "2516000");
4311         opt_default("minrate", "0"); // 1145000;
4312         opt_default("bufsize", "1835008"); // 224*1024*8;
4313         opt_default("flags", "+scan_offset");
4314
4315
4316         opt_default("b:a", "224000");
4317         parse_option(o, "ar", "44100", options);
4318
4319         opt_default("packetsize", "2324");
4320
4321     } else if (!strcmp(arg, "dvd")) {
4322
4323         opt_video_codec(o, "c:v", "mpeg2video");
4324         opt_audio_codec(o, "c:a", "ac3");
4325         parse_option(o, "f", "dvd", options);
4326
4327         parse_option(o, "s", norm == PAL ? "720x576" : "720x480", options);
4328         parse_option(o, "r", frame_rates[norm], options);
4329         opt_default("g", norm == PAL ? "15" : "18");
4330
4331         opt_default("b", "6000000");
4332         opt_default("maxrate", "9000000");
4333         opt_default("minrate", "0"); // 1500000;
4334         opt_default("bufsize", "1835008"); // 224*1024*8;
4335
4336         opt_default("packetsize", "2048");  // from www.mpucoder.com: DVD sectors contain 2048 bytes of data, this is also the size of one pack.
4337         opt_default("muxrate", "10080000"); // from mplex project: data_rate = 1260000. mux_rate = data_rate * 8
4338
4339         opt_default("b:a", "448000");
4340         parse_option(o, "ar", "48000", options);
4341
4342     } else if (!strncmp(arg, "dv", 2)) {
4343
4344         parse_option(o, "f", "dv", options);
4345
4346         parse_option(o, "s", norm == PAL ? "720x576" : "720x480", options);
4347         parse_option(o, "pix_fmt", !strncmp(arg, "dv50", 4) ? "yuv422p" :
4348                           norm == PAL ? "yuv420p" : "yuv411p", options);
4349         parse_option(o, "r", frame_rates[norm], options);
4350
4351         parse_option(o, "ar", "48000", options);
4352         parse_option(o, "ac", "2", options);
4353
4354     } else {
4355         av_log(NULL, AV_LOG_ERROR, "Unknown target: %s\n", arg);
4356         return AVERROR(EINVAL);
4357     }
4358     return 0;
4359 }
4360
4361 static int opt_vstats_file(const char *opt, const char *arg)
4362 {
4363     av_free (vstats_filename);
4364     vstats_filename = av_strdup (arg);
4365     return 0;
4366 }
4367
4368 static int opt_vstats(const char *opt, const char *arg)
4369 {
4370     char filename[40];
4371     time_t today2 = time(NULL);
4372     struct tm *today = localtime(&today2);
4373
4374     snprintf(filename, sizeof(filename), "vstats_%02d%02d%02d.log", today->tm_hour, today->tm_min,
4375              today->tm_sec);
4376     return opt_vstats_file(opt, filename);
4377 }
4378
4379 static int opt_video_frames(OptionsContext *o, const char *opt, const char *arg)
4380 {
4381     return parse_option(o, "frames:v", arg, options);
4382 }
4383
4384 static int opt_audio_frames(OptionsContext *o, const char *opt, const char *arg)
4385 {
4386     return parse_option(o, "frames:a", arg, options);
4387 }
4388
4389 static int opt_data_frames(OptionsContext *o, const char *opt, const char *arg)
4390 {
4391     return parse_option(o, "frames:d", arg, options);
4392 }
4393
4394 static void log_callback_null(void* ptr, int level, const char* fmt, va_list vl)
4395 {
4396 }
4397
4398 static int opt_passlogfile(const char *opt, const char *arg)
4399 {
4400     pass_logfilename_prefix = arg;
4401 #if CONFIG_LIBX264_ENCODER
4402     return opt_default("passlogfile", arg);
4403 #else
4404     return 0;
4405 #endif
4406 }
4407
4408 static int opt_video_tag(OptionsContext *o, const char *opt, const char *arg)
4409 {
4410     return parse_option(o, "tag:v", arg, options);
4411 }
4412
4413 static int opt_audio_tag(OptionsContext *o, const char *opt, const char *arg)
4414 {
4415     return parse_option(o, "tag:a", arg, options);
4416 }
4417
4418 static int opt_subtitle_tag(OptionsContext *o, const char *opt, const char *arg)
4419 {
4420     return parse_option(o, "tag:s", arg, options);
4421 }
4422
4423 static int opt_video_filters(OptionsContext *o, const char *opt, const char *arg)
4424 {
4425     return parse_option(o, "filter:v", arg, options);
4426 }
4427
4428 #define OFFSET(x) offsetof(OptionsContext, x)
4429 static const OptionDef options[] = {
4430     /* main options */
4431 #include "cmdutils_common_opts.h"
4432     { "f", HAS_ARG | OPT_STRING | OPT_OFFSET, {.off = OFFSET(format)}, "force format", "fmt" },
4433     { "i", HAS_ARG | OPT_FUNC2, {(void*)opt_input_file}, "input file name", "filename" },
4434     { "y", OPT_BOOL, {(void*)&file_overwrite}, "overwrite output files" },
4435     { "n", OPT_BOOL, {(void*)&no_file_overwrite}, "do not overwrite output files" },
4436     { "c", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(codec_names)}, "codec name", "codec" },
4437     { "codec", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(codec_names)}, "codec name", "codec" },
4438     { "pre", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(presets)}, "preset name", "preset" },
4439     { "map", HAS_ARG | OPT_EXPERT | OPT_FUNC2, {(void*)opt_map}, "set input stream mapping", "[-]input_file_id[:stream_specifier][,sync_file_id[:stream_specifier]]" },
4440     { "map_metadata", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(metadata_map)}, "set metadata information of outfile from infile",
4441       "outfile[,metadata]:infile[,metadata]" },
4442     { "map_chapters",  OPT_INT | HAS_ARG | OPT_EXPERT | OPT_OFFSET, {.off = OFFSET(chapters_input_file)},  "set chapters mapping", "input_file_index" },
4443     { "t", HAS_ARG | OPT_TIME | OPT_OFFSET, {.off = OFFSET(recording_time)}, "record or transcode \"duration\" seconds of audio/video", "duration" },
4444     { "fs", HAS_ARG | OPT_INT64 | OPT_OFFSET, {.off = OFFSET(limit_filesize)}, "set the limit file size in bytes", "limit_size" }, //
4445     { "ss", HAS_ARG | OPT_TIME | OPT_OFFSET, {.off = OFFSET(start_time)}, "set the start time offset", "time_off" },
4446     { "itsoffset", HAS_ARG | OPT_TIME | OPT_OFFSET, {.off = OFFSET(input_ts_offset)}, "set the input ts offset", "time_off" },
4447     { "itsscale", HAS_ARG | OPT_DOUBLE | OPT_SPEC, {.off = OFFSET(ts_scale)}, "set the input ts scale", "scale" },
4448     { "metadata", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(metadata)}, "add metadata", "string=string" },
4449     { "dframes", HAS_ARG | OPT_FUNC2, {(void*)opt_data_frames}, "set the number of data frames to record", "number" },
4450     { "benchmark", OPT_BOOL | OPT_EXPERT, {(void*)&do_benchmark},
4451       "add timings for benchmarking" },
4452     { "timelimit", HAS_ARG, {(void*)opt_timelimit}, "set max runtime in seconds", "limit" },
4453     { "dump", OPT_BOOL | OPT_EXPERT, {(void*)&do_pkt_dump},
4454       "dump each input packet" },
4455     { "hex", OPT_BOOL | OPT_EXPERT, {(void*)&do_hex_dump},
4456       "when dumping packets, also dump the payload" },
4457     { "re", OPT_BOOL | OPT_EXPERT | OPT_OFFSET, {.off = OFFSET(rate_emu)}, "read input at native frame rate", "" },
4458     { "target", HAS_ARG | OPT_FUNC2, {(void*)opt_target}, "specify target file type (\"vcd\", \"svcd\", \"dvd\", \"dv\", \"dv50\", \"pal-vcd\", \"ntsc-svcd\", ...)", "type" },
4459     { "vsync", HAS_ARG | OPT_INT | OPT_EXPERT, {(void*)&video_sync_method}, "video sync method", "" },
4460     { "async", HAS_ARG | OPT_INT | OPT_EXPERT, {(void*)&audio_sync_method}, "audio sync method", "" },
4461     { "adrift_threshold", HAS_ARG | OPT_FLOAT | OPT_EXPERT, {(void*)&audio_drift_threshold}, "audio drift threshold", "threshold" },
4462     { "copyts", OPT_BOOL | OPT_EXPERT, {(void*)&copy_ts}, "copy timestamps" },
4463     { "copytb", OPT_BOOL | OPT_EXPERT, {(void*)&copy_tb}, "copy input stream time base when stream copying" },
4464     { "shortest", OPT_BOOL | OPT_EXPERT, {(void*)&opt_shortest}, "finish encoding within shortest input" }, //
4465     { "dts_delta_threshold", HAS_ARG | OPT_FLOAT | OPT_EXPERT, {(void*)&dts_delta_threshold}, "timestamp discontinuity delta threshold", "threshold" },
4466     { "xerror", OPT_BOOL, {(void*)&exit_on_error}, "exit on error", "error" },
4467     { "copyinkf", OPT_BOOL | OPT_EXPERT | OPT_SPEC, {.off = OFFSET(copy_initial_nonkeyframes)}, "copy initial non-keyframes" },
4468     { "frames", OPT_INT64 | HAS_ARG | OPT_SPEC, {.off = OFFSET(max_frames)}, "set the number of frames to record", "number" },
4469     { "tag",   OPT_STRING | HAS_ARG | OPT_SPEC, {.off = OFFSET(codec_tags)}, "force codec tag/fourcc", "fourcc/tag" },
4470     { "q", HAS_ARG | OPT_EXPERT | OPT_DOUBLE | OPT_SPEC, {.off = OFFSET(qscale)}, "use fixed quality scale (VBR)", "q" },
4471     { "qscale", HAS_ARG | OPT_EXPERT | OPT_DOUBLE | OPT_SPEC, {.off = OFFSET(qscale)}, "use fixed quality scale (VBR)", "q" },
4472 #if CONFIG_AVFILTER
4473     { "filter", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(filters)}, "set stream filterchain", "filter_list" },
4474 #endif
4475     { "stats", OPT_BOOL, {&print_stats}, "print progress report during encoding", },
4476     { "attach", HAS_ARG | OPT_FUNC2, {(void*)opt_attach}, "add an attachment to the output file", "filename" },
4477     { "dump_attachment", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(dump_attachment)}, "extract an attachment into a file", "filename" },
4478
4479     /* video options */
4480     { "vframes", HAS_ARG | OPT_VIDEO | OPT_FUNC2, {(void*)opt_video_frames}, "set the number of video frames to record", "number" },
4481     { "r", HAS_ARG | OPT_VIDEO | OPT_STRING | OPT_SPEC, {.off = OFFSET(frame_rates)}, "set frame rate (Hz value, fraction or abbreviation)", "rate" },
4482     { "s", HAS_ARG | OPT_VIDEO | OPT_STRING | OPT_SPEC, {.off = OFFSET(frame_sizes)}, "set frame size (WxH or abbreviation)", "size" },
4483     { "aspect", HAS_ARG | OPT_VIDEO | OPT_STRING | OPT_SPEC, {.off = OFFSET(frame_aspect_ratios)}, "set aspect ratio (4:3, 16:9 or 1.3333, 1.7777)", "aspect" },
4484     { "pix_fmt", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_STRING | OPT_SPEC, {.off = OFFSET(frame_pix_fmts)}, "set pixel format", "format" },
4485     { "bits_per_raw_sample", OPT_INT | HAS_ARG | OPT_VIDEO, {(void*)&frame_bits_per_raw_sample}, "set the number of bits per raw sample", "number" },
4486     { "vn", OPT_BOOL | OPT_VIDEO | OPT_OFFSET, {.off = OFFSET(video_disable)}, "disable video" },
4487     { "vdt", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)&video_discard}, "discard threshold", "n" },
4488     { "rc_override", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_STRING | OPT_SPEC, {.off = OFFSET(rc_overrides)}, "rate control override for specific intervals", "override" },
4489     { "vcodec", HAS_ARG | OPT_VIDEO | OPT_FUNC2, {(void*)opt_video_codec}, "force video codec ('copy' to copy stream)", "codec" },
4490     { "same_quant", OPT_BOOL | OPT_VIDEO, {(void*)&same_quant},
4491       "use same quantizer as source (implies VBR)" },
4492     { "pass", HAS_ARG | OPT_VIDEO, {(void*)opt_pass}, "select the pass number (1 or 2)", "n" },
4493     { "passlogfile", HAS_ARG | OPT_VIDEO, {(void*)&opt_passlogfile}, "select two pass log file name prefix", "prefix" },
4494     { "deinterlace", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_deinterlace},
4495       "deinterlace pictures" },
4496     { "vstats", OPT_EXPERT | OPT_VIDEO, {(void*)&opt_vstats}, "dump video coding statistics to file" },
4497     { "vstats_file", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_vstats_file}, "dump video coding statistics to file", "file" },
4498 #if CONFIG_AVFILTER
4499     { "vf", HAS_ARG | OPT_VIDEO | OPT_FUNC2, {(void*)opt_video_filters}, "video filters", "filter list" },
4500 #endif
4501     { "intra_matrix", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_STRING | OPT_SPEC, {.off = OFFSET(intra_matrices)}, "specify intra matrix coeffs", "matrix" },
4502     { "inter_matrix", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_STRING | OPT_SPEC, {.off = OFFSET(inter_matrices)}, "specify inter matrix coeffs", "matrix" },
4503     { "top", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_INT| OPT_SPEC, {.off = OFFSET(top_field_first)}, "top=1/bottom=0/auto=-1 field first", "" },
4504     { "dc", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)&intra_dc_precision}, "intra_dc_precision", "precision" },
4505     { "vtag", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_FUNC2, {(void*)opt_video_tag}, "force video tag/fourcc", "fourcc/tag" },
4506     { "qphist", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, { (void *)&qp_hist }, "show QP histogram" },
4507     { "force_fps", OPT_BOOL | OPT_EXPERT | OPT_VIDEO | OPT_SPEC, {.off = OFFSET(force_fps)}, "force the selected framerate, disable the best supported framerate selection" },
4508     { "streamid", HAS_ARG | OPT_EXPERT | OPT_FUNC2, {(void*)opt_streamid}, "set the value of an outfile streamid", "streamIndex:value" },
4509     { "force_key_frames", OPT_STRING | HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_SPEC, {.off = OFFSET(forced_key_frames)}, "force key frames at specified timestamps", "timestamps" },
4510
4511     /* audio options */
4512     { "aframes", HAS_ARG | OPT_AUDIO | OPT_FUNC2, {(void*)opt_audio_frames}, "set the number of audio frames to record", "number" },
4513     { "aq", HAS_ARG | OPT_AUDIO | OPT_FUNC2, {(void*)opt_audio_qscale}, "set audio quality (codec-specific)", "quality", },
4514     { "ar", HAS_ARG | OPT_AUDIO | OPT_INT | OPT_SPEC, {.off = OFFSET(audio_sample_rate)}, "set audio sampling rate (in Hz)", "rate" },
4515     { "ac", HAS_ARG | OPT_AUDIO | OPT_INT | OPT_SPEC, {.off = OFFSET(audio_channels)}, "set number of audio channels", "channels" },
4516     { "an", OPT_BOOL | OPT_AUDIO | OPT_OFFSET, {.off = OFFSET(audio_disable)}, "disable audio" },
4517     { "acodec", HAS_ARG | OPT_AUDIO | OPT_FUNC2, {(void*)opt_audio_codec}, "force audio codec ('copy' to copy stream)", "codec" },
4518     { "atag", HAS_ARG | OPT_EXPERT | OPT_AUDIO | OPT_FUNC2, {(void*)opt_audio_tag}, "force audio tag/fourcc", "fourcc/tag" },
4519     { "vol", OPT_INT | HAS_ARG | OPT_AUDIO, {(void*)&audio_volume}, "change audio volume (256=normal)" , "volume" }, //
4520     { "sample_fmt", HAS_ARG | OPT_EXPERT | OPT_AUDIO | OPT_SPEC | OPT_STRING, {.off = OFFSET(sample_fmts)}, "set sample format", "format" },
4521
4522     /* subtitle options */
4523     { "sn", OPT_BOOL | OPT_SUBTITLE | OPT_OFFSET, {.off = OFFSET(subtitle_disable)}, "disable subtitle" },
4524     { "scodec", HAS_ARG | OPT_SUBTITLE | OPT_FUNC2, {(void*)opt_subtitle_codec}, "force subtitle codec ('copy' to copy stream)", "codec" },
4525     { "stag", HAS_ARG | OPT_EXPERT | OPT_SUBTITLE | OPT_FUNC2, {(void*)opt_subtitle_tag}, "force subtitle tag/fourcc", "fourcc/tag" },
4526
4527     /* grab options */
4528     { "isync", OPT_BOOL | OPT_EXPERT | OPT_GRAB, {(void*)&input_sync}, "sync read on input", "" },
4529
4530     /* muxer options */
4531     { "muxdelay", OPT_FLOAT | HAS_ARG | OPT_EXPERT   | OPT_OFFSET, {.off = OFFSET(mux_max_delay)}, "set the maximum demux-decode delay", "seconds" },
4532     { "muxpreload", OPT_FLOAT | HAS_ARG | OPT_EXPERT | OPT_OFFSET, {.off = OFFSET(mux_preload)},   "set the initial demux-decode delay", "seconds" },
4533
4534     { "bsf", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(bitstream_filters)}, "A comma-separated list of bitstream filters", "bitstream_filters" },
4535
4536     /* data codec support */
4537     { "dcodec", HAS_ARG | OPT_DATA | OPT_FUNC2, {(void*)opt_data_codec}, "force data codec ('copy' to copy stream)", "codec" },
4538
4539     { "default", HAS_ARG | OPT_AUDIO | OPT_VIDEO | OPT_EXPERT, {(void*)opt_default}, "generic catch all option", "" },
4540     { NULL, },
4541 };
4542
4543 int main(int argc, char **argv)
4544 {
4545     OptionsContext o = { 0 };
4546     int64_t ti;
4547
4548     reset_options(&o);
4549
4550     av_log_set_flags(AV_LOG_SKIP_REPEATED);
4551     parse_loglevel(argc, argv, options);
4552
4553     if(argc>1 && !strcmp(argv[1], "-d")){
4554         run_as_daemon=1;
4555         av_log_set_callback(log_callback_null);
4556         argc--;
4557         argv++;
4558     }
4559
4560     avcodec_register_all();
4561 #if CONFIG_AVDEVICE
4562     avdevice_register_all();
4563 #endif
4564 #if CONFIG_AVFILTER
4565     avfilter_register_all();
4566 #endif
4567     av_register_all();
4568     avformat_network_init();
4569
4570     show_banner(argc, argv, options);
4571
4572     /* parse options */
4573     parse_options(&o, argc, argv, options, opt_output_file);
4574
4575     if (nb_output_files <= 0 && nb_input_files == 0) {
4576         show_usage();
4577         av_log(NULL, AV_LOG_WARNING, "Use -h to get full help or, even better, run 'man %s'\n", program_name);
4578         exit_program(1);
4579     }
4580
4581     /* file converter / grab */
4582     if (nb_output_files <= 0) {
4583         fprintf(stderr, "At least one output file must be specified\n");
4584         exit_program(1);
4585     }
4586
4587     if (nb_input_files == 0) {
4588         av_log(NULL, AV_LOG_FATAL, "At least one input file must be specified\n");
4589         exit_program(1);
4590     }
4591
4592     ti = getutime();
4593     if (transcode(output_files, nb_output_files, input_files, nb_input_files) < 0)
4594         exit_program(1);
4595     ti = getutime() - ti;
4596     if (do_benchmark) {
4597         int maxrss = getmaxrss() / 1024;
4598         printf("bench: utime=%0.3fs maxrss=%ikB\n", ti / 1000000.0, maxrss);
4599     }
4600
4601     exit_program(0);
4602     return 0;
4603 }