]> git.sesse.net Git - ffmpeg/blob - ffmpeg_opt.c
Merge remote-tracking branch 'qatar/master'
[ffmpeg] / ffmpeg_opt.c
1 /*
2  * ffmpeg option parsing
3  *
4  * This file is part of FFmpeg.
5  *
6  * FFmpeg is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * FFmpeg is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with FFmpeg; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19  */
20
21 #include <stdint.h>
22
23 #include "ffmpeg.h"
24 #include "cmdutils.h"
25
26 #include "libavformat/avformat.h"
27
28 #include "libavcodec/avcodec.h"
29
30 #include "libavfilter/avfilter.h"
31 #include "libavfilter/avfiltergraph.h"
32
33 #include "libavutil/audioconvert.h"
34 #include "libavutil/avassert.h"
35 #include "libavutil/avstring.h"
36 #include "libavutil/avutil.h"
37 #include "libavutil/intreadwrite.h"
38 #include "libavutil/fifo.h"
39 #include "libavutil/mathematics.h"
40 #include "libavutil/opt.h"
41 #include "libavutil/parseutils.h"
42 #include "libavutil/pixdesc.h"
43 #include "libavutil/pixfmt.h"
44
45 #define MATCH_PER_STREAM_OPT(name, type, outvar, fmtctx, st)\
46 {\
47     int i, ret;\
48     for (i = 0; i < o->nb_ ## name; i++) {\
49         char *spec = o->name[i].specifier;\
50         if ((ret = check_stream_specifier(fmtctx, st, spec)) > 0)\
51             outvar = o->name[i].u.type;\
52         else if (ret < 0)\
53             exit_program(1);\
54     }\
55 }
56
57 const char *pass_logfilename_prefix;
58 char *vstats_filename;
59
60 float audio_drift_threshold = 0.1;
61 float dts_delta_threshold   = 10;
62 float dts_error_threshold   = 3600*30;
63
64 int audio_volume      = 256;
65 int audio_sync_method = 0;
66 int video_sync_method = VSYNC_AUTO;
67 int do_deinterlace    = 0;
68 int do_benchmark      = 0;
69 int do_benchmark_all  = 0;
70 int do_hex_dump       = 0;
71 int do_pkt_dump       = 0;
72 int copy_ts           = 0;
73 int copy_tb           = -1;
74 int debug_ts          = 0;
75 int exit_on_error     = 0;
76 int print_stats       = 1;
77 int qp_hist           = 0;
78 int same_quant        = 0;
79 int stdin_interaction = 1;
80 int frame_bits_per_raw_sample = 0;
81
82
83 static int intra_only         = 0;
84 static const char *video_codec_name    = NULL;
85 static const char *audio_codec_name    = NULL;
86 static const char *subtitle_codec_name = NULL;
87 static int file_overwrite     = 0;
88 static int no_file_overwrite  = 0;
89 static int video_discard      = 0;
90 static int intra_dc_precision = 8;
91 static int do_psnr            = 0;
92 static int do_pass            = 0;
93 static int input_sync;
94
95 void reset_options(OptionsContext *o, int is_input)
96 {
97     const OptionDef *po = options;
98     OptionsContext bak= *o;
99     int i;
100
101     /* all OPT_SPEC and OPT_STRING can be freed in generic way */
102     while (po->name) {
103         void *dst = (uint8_t*)o + po->u.off;
104
105         if (po->flags & OPT_SPEC) {
106             SpecifierOpt **so = dst;
107             int i, *count = (int*)(so + 1);
108             for (i = 0; i < *count; i++) {
109                 av_freep(&(*so)[i].specifier);
110                 if (po->flags & OPT_STRING)
111                     av_freep(&(*so)[i].u.str);
112             }
113             av_freep(so);
114             *count = 0;
115         } else if (po->flags & OPT_OFFSET && po->flags & OPT_STRING)
116             av_freep(dst);
117         po++;
118     }
119
120     for (i = 0; i < o->nb_stream_maps; i++)
121         av_freep(&o->stream_maps[i].linklabel);
122     av_freep(&o->stream_maps);
123     av_freep(&o->audio_channel_maps);
124     av_freep(&o->streamid_map);
125
126     memset(o, 0, sizeof(*o));
127
128     if (is_input) {
129         o->recording_time = bak.recording_time;
130         if (o->recording_time != INT64_MAX)
131             av_log(NULL, AV_LOG_WARNING,
132                    "-t is not an input option, keeping it for the next output;"
133                    " consider fixing your command line.\n");
134     } else
135     o->recording_time = INT64_MAX;
136     o->mux_max_delay  = 0.7;
137     o->limit_filesize = UINT64_MAX;
138     o->chapters_input_file = INT_MAX;
139
140     uninit_opts();
141     init_opts();
142 }
143
144
145 static int opt_frame_crop(const char *opt, const char *arg)
146 {
147     av_log(NULL, AV_LOG_FATAL, "Option '%s' has been removed, use the crop filter instead\n", opt);
148     return AVERROR(EINVAL);
149 }
150
151 static int opt_pad(const char *opt, const char *arg)
152 {
153     av_log(NULL, AV_LOG_FATAL, "Option '%s' has been removed, use the pad filter instead\n", opt);
154     return -1;
155 }
156
157 static int opt_video_channel(const char *opt, const char *arg)
158 {
159     av_log(NULL, AV_LOG_WARNING, "This option is deprecated, use -channel.\n");
160     return opt_default("channel", arg);
161     }
162
163 static int opt_video_standard(const char *opt, const char *arg)
164 {
165     av_log(NULL, AV_LOG_WARNING, "This option is deprecated, use -standard.\n");
166     return opt_default("standard", arg);
167 }
168
169 static int opt_audio_codec(void *optctx, const char *opt, const char *arg)
170 {
171     OptionsContext *o = optctx;
172     audio_codec_name = arg;
173     return parse_option(o, "codec:a", arg, options);
174 }
175
176 static int opt_video_codec(void *optctx, const char *opt, const char *arg)
177 {
178     OptionsContext *o = optctx;
179     video_codec_name = arg;
180     return parse_option(o, "codec:v", arg, options);
181 }
182
183 static int opt_subtitle_codec(void *optctx, const char *opt, const char *arg)
184 {
185     OptionsContext *o = optctx;
186     subtitle_codec_name = arg;
187     return parse_option(o, "codec:s", arg, options);
188 }
189
190 static int opt_data_codec(void *optctx, const char *opt, const char *arg)
191 {
192     OptionsContext *o = optctx;
193     return parse_option(o, "codec:d", arg, options);
194 }
195
196 static int opt_map(void *optctx, const char *opt, const char *arg)
197 {
198     OptionsContext *o = optctx;
199     StreamMap *m = NULL;
200     int i, negative = 0, file_idx;
201     int sync_file_idx = -1, sync_stream_idx = 0;
202     char *p, *sync;
203     char *map;
204
205     if (*arg == '-') {
206         negative = 1;
207         arg++;
208     }
209     map = av_strdup(arg);
210
211     /* parse sync stream first, just pick first matching stream */
212     if (sync = strchr(map, ',')) {
213         *sync = 0;
214         sync_file_idx = strtol(sync + 1, &sync, 0);
215         if (sync_file_idx >= nb_input_files || sync_file_idx < 0) {
216             av_log(NULL, AV_LOG_FATAL, "Invalid sync file index: %d.\n", sync_file_idx);
217             exit_program(1);
218         }
219         if (*sync)
220             sync++;
221         for (i = 0; i < input_files[sync_file_idx]->nb_streams; i++)
222             if (check_stream_specifier(input_files[sync_file_idx]->ctx,
223                                        input_files[sync_file_idx]->ctx->streams[i], sync) == 1) {
224                 sync_stream_idx = i;
225                 break;
226             }
227         if (i == input_files[sync_file_idx]->nb_streams) {
228             av_log(NULL, AV_LOG_FATAL, "Sync stream specification in map %s does not "
229                                        "match any streams.\n", arg);
230             exit_program(1);
231         }
232     }
233
234
235     if (map[0] == '[') {
236         /* this mapping refers to lavfi output */
237         const char *c = map + 1;
238         o->stream_maps = grow_array(o->stream_maps, sizeof(*o->stream_maps),
239                                     &o->nb_stream_maps, o->nb_stream_maps + 1);
240         m = &o->stream_maps[o->nb_stream_maps - 1];
241         m->linklabel = av_get_token(&c, "]");
242         if (!m->linklabel) {
243             av_log(NULL, AV_LOG_ERROR, "Invalid output link label: %s.\n", map);
244             exit_program(1);
245         }
246     } else {
247         file_idx = strtol(map, &p, 0);
248         if (file_idx >= nb_input_files || file_idx < 0) {
249             av_log(NULL, AV_LOG_FATAL, "Invalid input file index: %d.\n", file_idx);
250             exit_program(1);
251         }
252         if (negative)
253             /* disable some already defined maps */
254             for (i = 0; i < o->nb_stream_maps; i++) {
255                 m = &o->stream_maps[i];
256                 if (file_idx == m->file_index &&
257                     check_stream_specifier(input_files[m->file_index]->ctx,
258                                            input_files[m->file_index]->ctx->streams[m->stream_index],
259                                            *p == ':' ? p + 1 : p) > 0)
260                     m->disabled = 1;
261             }
262         else
263             for (i = 0; i < input_files[file_idx]->nb_streams; i++) {
264                 if (check_stream_specifier(input_files[file_idx]->ctx, input_files[file_idx]->ctx->streams[i],
265                             *p == ':' ? p + 1 : p) <= 0)
266                     continue;
267                 o->stream_maps = grow_array(o->stream_maps, sizeof(*o->stream_maps),
268                                             &o->nb_stream_maps, o->nb_stream_maps + 1);
269                 m = &o->stream_maps[o->nb_stream_maps - 1];
270
271                 m->file_index   = file_idx;
272                 m->stream_index = i;
273
274                 if (sync_file_idx >= 0) {
275                     m->sync_file_index   = sync_file_idx;
276                     m->sync_stream_index = sync_stream_idx;
277                 } else {
278                     m->sync_file_index   = file_idx;
279                     m->sync_stream_index = i;
280                 }
281             }
282     }
283
284     if (!m) {
285         av_log(NULL, AV_LOG_FATAL, "Stream map '%s' matches no streams.\n", arg);
286         exit_program(1);
287     }
288
289     av_freep(&map);
290     return 0;
291 }
292
293 static int opt_attach(void *optctx, const char *opt, const char *arg)
294 {
295     OptionsContext *o = optctx;
296     o->attachments = grow_array(o->attachments, sizeof(*o->attachments),
297                                 &o->nb_attachments, o->nb_attachments + 1);
298     o->attachments[o->nb_attachments - 1] = arg;
299     return 0;
300 }
301
302 static int opt_map_channel(void *optctx, const char *opt, const char *arg)
303 {
304     OptionsContext *o = optctx;
305     int n;
306     AVStream *st;
307     AudioChannelMap *m;
308
309     o->audio_channel_maps =
310         grow_array(o->audio_channel_maps, sizeof(*o->audio_channel_maps),
311                    &o->nb_audio_channel_maps, o->nb_audio_channel_maps + 1);
312     m = &o->audio_channel_maps[o->nb_audio_channel_maps - 1];
313
314     /* muted channel syntax */
315     n = sscanf(arg, "%d:%d.%d", &m->channel_idx, &m->ofile_idx, &m->ostream_idx);
316     if ((n == 1 || n == 3) && m->channel_idx == -1) {
317         m->file_idx = m->stream_idx = -1;
318         if (n == 1)
319             m->ofile_idx = m->ostream_idx = -1;
320         return 0;
321     }
322
323     /* normal syntax */
324     n = sscanf(arg, "%d.%d.%d:%d.%d",
325                &m->file_idx,  &m->stream_idx, &m->channel_idx,
326                &m->ofile_idx, &m->ostream_idx);
327
328     if (n != 3 && n != 5) {
329         av_log(NULL, AV_LOG_FATAL, "Syntax error, mapchan usage: "
330                "[file.stream.channel|-1][:syncfile:syncstream]\n");
331         exit_program(1);
332     }
333
334     if (n != 5) // only file.stream.channel specified
335         m->ofile_idx = m->ostream_idx = -1;
336
337     /* check input */
338     if (m->file_idx < 0 || m->file_idx >= nb_input_files) {
339         av_log(NULL, AV_LOG_FATAL, "mapchan: invalid input file index: %d\n",
340                m->file_idx);
341         exit_program(1);
342     }
343     if (m->stream_idx < 0 ||
344         m->stream_idx >= input_files[m->file_idx]->nb_streams) {
345         av_log(NULL, AV_LOG_FATAL, "mapchan: invalid input file stream index #%d.%d\n",
346                m->file_idx, m->stream_idx);
347         exit_program(1);
348     }
349     st = input_files[m->file_idx]->ctx->streams[m->stream_idx];
350     if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO) {
351         av_log(NULL, AV_LOG_FATAL, "mapchan: stream #%d.%d is not an audio stream.\n",
352                m->file_idx, m->stream_idx);
353         exit_program(1);
354     }
355     if (m->channel_idx < 0 || m->channel_idx >= st->codec->channels) {
356         av_log(NULL, AV_LOG_FATAL, "mapchan: invalid audio channel #%d.%d.%d\n",
357                m->file_idx, m->stream_idx, m->channel_idx);
358         exit_program(1);
359     }
360     return 0;
361 }
362
363 /**
364  * Parse a metadata specifier in arg.
365  * @param type metadata type is written here -- g(lobal)/s(tream)/c(hapter)/p(rogram)
366  * @param index for type c/p, chapter/program index is written here
367  * @param stream_spec for type s, the stream specifier is written here
368  */
369 static void parse_meta_type(char *arg, char *type, int *index, const char **stream_spec)
370 {
371     if (*arg) {
372         *type = *arg;
373         switch (*arg) {
374         case 'g':
375             break;
376         case 's':
377             if (*(++arg) && *arg != ':') {
378                 av_log(NULL, AV_LOG_FATAL, "Invalid metadata specifier %s.\n", arg);
379                 exit_program(1);
380             }
381             *stream_spec = *arg == ':' ? arg + 1 : "";
382             break;
383         case 'c':
384         case 'p':
385             if (*(++arg) == ':')
386                 *index = strtol(++arg, NULL, 0);
387             break;
388         default:
389             av_log(NULL, AV_LOG_FATAL, "Invalid metadata type %c.\n", *arg);
390             exit_program(1);
391         }
392     } else
393         *type = 'g';
394 }
395
396 static int copy_metadata(char *outspec, char *inspec, AVFormatContext *oc, AVFormatContext *ic, OptionsContext *o)
397 {
398     AVDictionary **meta_in = NULL;
399     AVDictionary **meta_out = NULL;
400     int i, ret = 0;
401     char type_in, type_out;
402     const char *istream_spec = NULL, *ostream_spec = NULL;
403     int idx_in = 0, idx_out = 0;
404
405     parse_meta_type(inspec,  &type_in,  &idx_in,  &istream_spec);
406     parse_meta_type(outspec, &type_out, &idx_out, &ostream_spec);
407
408     if (!ic) {
409         if (type_out == 'g' || !*outspec)
410             o->metadata_global_manual = 1;
411         if (type_out == 's' || !*outspec)
412             o->metadata_streams_manual = 1;
413         if (type_out == 'c' || !*outspec)
414             o->metadata_chapters_manual = 1;
415         return 0;
416     }
417
418     if (type_in == 'g' || type_out == 'g')
419         o->metadata_global_manual = 1;
420     if (type_in == 's' || type_out == 's')
421         o->metadata_streams_manual = 1;
422     if (type_in == 'c' || type_out == 'c')
423         o->metadata_chapters_manual = 1;
424
425 #define METADATA_CHECK_INDEX(index, nb_elems, desc)\
426     if ((index) < 0 || (index) >= (nb_elems)) {\
427         av_log(NULL, AV_LOG_FATAL, "Invalid %s index %d while processing metadata maps.\n",\
428                 (desc), (index));\
429         exit_program(1);\
430     }
431
432 #define SET_DICT(type, meta, context, index)\
433         switch (type) {\
434         case 'g':\
435             meta = &context->metadata;\
436             break;\
437         case 'c':\
438             METADATA_CHECK_INDEX(index, context->nb_chapters, "chapter")\
439             meta = &context->chapters[index]->metadata;\
440             break;\
441         case 'p':\
442             METADATA_CHECK_INDEX(index, context->nb_programs, "program")\
443             meta = &context->programs[index]->metadata;\
444             break;\
445         default: av_assert0(0);\
446         }\
447
448     SET_DICT(type_in, meta_in, ic, idx_in);
449     SET_DICT(type_out, meta_out, oc, idx_out);
450
451     /* for input streams choose first matching stream */
452     if (type_in == 's') {
453         for (i = 0; i < ic->nb_streams; i++) {
454             if ((ret = check_stream_specifier(ic, ic->streams[i], istream_spec)) > 0) {
455                 meta_in = &ic->streams[i]->metadata;
456                 break;
457             } else if (ret < 0)
458                 exit_program(1);
459         }
460         if (!meta_in) {
461             av_log(NULL, AV_LOG_FATAL, "Stream specifier %s does not match  any streams.\n", istream_spec);
462             exit_program(1);
463         }
464     }
465
466     if (type_out == 's') {
467         for (i = 0; i < oc->nb_streams; i++) {
468             if ((ret = check_stream_specifier(oc, oc->streams[i], ostream_spec)) > 0) {
469                 meta_out = &oc->streams[i]->metadata;
470                 av_dict_copy(meta_out, *meta_in, AV_DICT_DONT_OVERWRITE);
471             } else if (ret < 0)
472                 exit_program(1);
473         }
474     } else
475         av_dict_copy(meta_out, *meta_in, AV_DICT_DONT_OVERWRITE);
476
477     return 0;
478 }
479
480 static int opt_recording_timestamp(void *optctx, const char *opt, const char *arg)
481 {
482     OptionsContext *o = optctx;
483     char buf[128];
484     int64_t recording_timestamp = parse_time_or_die(opt, arg, 0) / 1E6;
485     struct tm time = *gmtime((time_t*)&recording_timestamp);
486     strftime(buf, sizeof(buf), "creation_time=%FT%T%z", &time);
487     parse_option(o, "metadata", buf, options);
488
489     av_log(NULL, AV_LOG_WARNING, "%s is deprecated, set the 'creation_time' metadata "
490                                  "tag instead.\n", opt);
491     return 0;
492 }
493
494 static AVCodec *find_codec_or_die(const char *name, enum AVMediaType type, int encoder)
495 {
496     const AVCodecDescriptor *desc;
497     const char *codec_string = encoder ? "encoder" : "decoder";
498     AVCodec *codec;
499
500     codec = encoder ?
501         avcodec_find_encoder_by_name(name) :
502         avcodec_find_decoder_by_name(name);
503
504     if (!codec && (desc = avcodec_descriptor_get_by_name(name))) {
505         codec = encoder ? avcodec_find_encoder(desc->id) :
506                           avcodec_find_decoder(desc->id);
507         if (codec)
508             av_log(NULL, AV_LOG_VERBOSE, "Matched %s '%s' for codec '%s'.\n",
509                    codec_string, codec->name, desc->name);
510     }
511
512     if (!codec) {
513         av_log(NULL, AV_LOG_FATAL, "Unknown %s '%s'\n", codec_string, name);
514         exit_program(1);
515     }
516     if (codec->type != type) {
517         av_log(NULL, AV_LOG_FATAL, "Invalid %s type '%s'\n", codec_string, name);
518         exit_program(1);
519     }
520     return codec;
521 }
522
523 static AVCodec *choose_decoder(OptionsContext *o, AVFormatContext *s, AVStream *st)
524 {
525     char *codec_name = NULL;
526
527     MATCH_PER_STREAM_OPT(codec_names, str, codec_name, s, st);
528     if (codec_name) {
529         AVCodec *codec = find_codec_or_die(codec_name, st->codec->codec_type, 0);
530         st->codec->codec_id = codec->id;
531         return codec;
532     } else
533         return avcodec_find_decoder(st->codec->codec_id);
534 }
535
536 /**
537  * Add all the streams from the given input file to the global
538  * list of input streams.
539  */
540 static void add_input_streams(OptionsContext *o, AVFormatContext *ic)
541 {
542     int i;
543     char *next, *codec_tag = NULL;
544
545     for (i = 0; i < ic->nb_streams; i++) {
546         AVStream *st = ic->streams[i];
547         AVCodecContext *dec = st->codec;
548         InputStream *ist = av_mallocz(sizeof(*ist));
549         char *framerate = NULL;
550
551         if (!ist)
552             exit_program(1);
553
554         input_streams = grow_array(input_streams, sizeof(*input_streams), &nb_input_streams, nb_input_streams + 1);
555         input_streams[nb_input_streams - 1] = ist;
556
557         ist->st = st;
558         ist->file_index = nb_input_files;
559         ist->discard = 1;
560         st->discard  = AVDISCARD_ALL;
561         ist->opts = filter_codec_opts(codec_opts, ist->st->codec->codec_id, ic, st, choose_decoder(o, ic, st));
562
563         ist->ts_scale = 1.0;
564         MATCH_PER_STREAM_OPT(ts_scale, dbl, ist->ts_scale, ic, st);
565
566         MATCH_PER_STREAM_OPT(codec_tags, str, codec_tag, ic, st);
567         if (codec_tag) {
568             uint32_t tag = strtol(codec_tag, &next, 0);
569             if (*next)
570                 tag = AV_RL32(codec_tag);
571             st->codec->codec_tag = tag;
572         }
573
574         ist->dec = choose_decoder(o, ic, st);
575
576         switch (dec->codec_type) {
577         case AVMEDIA_TYPE_VIDEO:
578             if(!ist->dec)
579                 ist->dec = avcodec_find_decoder(dec->codec_id);
580             if (dec->lowres) {
581                 dec->flags |= CODEC_FLAG_EMU_EDGE;
582             }
583
584             ist->resample_height  = dec->height;
585             ist->resample_width   = dec->width;
586             ist->resample_pix_fmt = dec->pix_fmt;
587
588             MATCH_PER_STREAM_OPT(frame_rates, str, framerate, ic, st);
589             if (framerate && av_parse_video_rate(&ist->framerate,
590                                                  framerate) < 0) {
591                 av_log(NULL, AV_LOG_ERROR, "Error parsing framerate %s.\n",
592                        framerate);
593                 exit_program(1);
594             }
595
596             ist->top_field_first = -1;
597             MATCH_PER_STREAM_OPT(top_field_first, i, ist->top_field_first, ic, st);
598
599             break;
600         case AVMEDIA_TYPE_AUDIO:
601             guess_input_channel_layout(ist);
602
603             ist->resample_sample_fmt     = dec->sample_fmt;
604             ist->resample_sample_rate    = dec->sample_rate;
605             ist->resample_channels       = dec->channels;
606             ist->resample_channel_layout = dec->channel_layout;
607
608             break;
609         case AVMEDIA_TYPE_DATA:
610         case AVMEDIA_TYPE_SUBTITLE:
611             if(!ist->dec)
612                 ist->dec = avcodec_find_decoder(dec->codec_id);
613             MATCH_PER_STREAM_OPT(fix_sub_duration, i, ist->fix_sub_duration, ic, st);
614             break;
615         case AVMEDIA_TYPE_ATTACHMENT:
616         case AVMEDIA_TYPE_UNKNOWN:
617             break;
618         default:
619             abort();
620         }
621     }
622 }
623
624 static void assert_file_overwrite(const char *filename)
625 {
626     if ((!file_overwrite || no_file_overwrite) &&
627         (strchr(filename, ':') == NULL || filename[1] == ':' ||
628          av_strstart(filename, "file:", NULL))) {
629         if (avio_check(filename, 0) == 0) {
630             if (stdin_interaction && (!no_file_overwrite || file_overwrite)) {
631                 fprintf(stderr,"File '%s' already exists. Overwrite ? [y/N] ", filename);
632                 fflush(stderr);
633                 term_exit();
634                 signal(SIGINT, SIG_DFL);
635                 if (!read_yesno()) {
636                     av_log(NULL, AV_LOG_FATAL, "Not overwriting - exiting\n");
637                     exit_program(1);
638                 }
639                 term_init();
640             }
641             else {
642                 av_log(NULL, AV_LOG_FATAL, "File '%s' already exists. Exiting.\n", filename);
643                 exit_program(1);
644             }
645         }
646     }
647 }
648
649 static void dump_attachment(AVStream *st, const char *filename)
650 {
651     int ret;
652     AVIOContext *out = NULL;
653     AVDictionaryEntry *e;
654
655     if (!st->codec->extradata_size) {
656         av_log(NULL, AV_LOG_WARNING, "No extradata to dump in stream #%d:%d.\n",
657                nb_input_files - 1, st->index);
658         return;
659     }
660     if (!*filename && (e = av_dict_get(st->metadata, "filename", NULL, 0)))
661         filename = e->value;
662     if (!*filename) {
663         av_log(NULL, AV_LOG_FATAL, "No filename specified and no 'filename' tag"
664                "in stream #%d:%d.\n", nb_input_files - 1, st->index);
665         exit_program(1);
666     }
667
668     assert_file_overwrite(filename);
669
670     if ((ret = avio_open2(&out, filename, AVIO_FLAG_WRITE, &int_cb, NULL)) < 0) {
671         av_log(NULL, AV_LOG_FATAL, "Could not open file %s for writing.\n",
672                filename);
673         exit_program(1);
674     }
675
676     avio_write(out, st->codec->extradata, st->codec->extradata_size);
677     avio_flush(out);
678     avio_close(out);
679 }
680
681 static int opt_input_file(void *optctx, const char *opt, const char *filename)
682 {
683     OptionsContext *o = optctx;
684     AVFormatContext *ic;
685     AVInputFormat *file_iformat = NULL;
686     int err, i, ret;
687     int64_t timestamp;
688     uint8_t buf[128];
689     AVDictionary **opts;
690     int orig_nb_streams;                     // number of streams before avformat_find_stream_info
691
692     if (o->format) {
693         if (!(file_iformat = av_find_input_format(o->format))) {
694             av_log(NULL, AV_LOG_FATAL, "Unknown input format: '%s'\n", o->format);
695             exit_program(1);
696         }
697     }
698
699     if (!strcmp(filename, "-"))
700         filename = "pipe:";
701
702     stdin_interaction &= strncmp(filename, "pipe:", 5) &&
703                          strcmp(filename, "/dev/stdin");
704
705     /* get default parameters from command line */
706     ic = avformat_alloc_context();
707     if (!ic) {
708         print_error(filename, AVERROR(ENOMEM));
709         exit_program(1);
710     }
711     if (o->nb_audio_sample_rate) {
712         snprintf(buf, sizeof(buf), "%d", o->audio_sample_rate[o->nb_audio_sample_rate - 1].u.i);
713         av_dict_set(&format_opts, "sample_rate", buf, 0);
714     }
715     if (o->nb_audio_channels) {
716         /* because we set audio_channels based on both the "ac" and
717          * "channel_layout" options, we need to check that the specified
718          * demuxer actually has the "channels" option before setting it */
719         if (file_iformat && file_iformat->priv_class &&
720             av_opt_find(&file_iformat->priv_class, "channels", NULL, 0,
721                         AV_OPT_SEARCH_FAKE_OBJ)) {
722             snprintf(buf, sizeof(buf), "%d",
723                      o->audio_channels[o->nb_audio_channels - 1].u.i);
724             av_dict_set(&format_opts, "channels", buf, 0);
725         }
726     }
727     if (o->nb_frame_rates) {
728         /* set the format-level framerate option;
729          * this is important for video grabbers, e.g. x11 */
730         if (file_iformat && file_iformat->priv_class &&
731             av_opt_find(&file_iformat->priv_class, "framerate", NULL, 0,
732                         AV_OPT_SEARCH_FAKE_OBJ)) {
733             av_dict_set(&format_opts, "framerate",
734                         o->frame_rates[o->nb_frame_rates - 1].u.str, 0);
735         }
736     }
737     if (o->nb_frame_sizes) {
738         av_dict_set(&format_opts, "video_size", o->frame_sizes[o->nb_frame_sizes - 1].u.str, 0);
739     }
740     if (o->nb_frame_pix_fmts)
741         av_dict_set(&format_opts, "pixel_format", o->frame_pix_fmts[o->nb_frame_pix_fmts - 1].u.str, 0);
742
743     ic->video_codec_id   = video_codec_name ?
744         find_codec_or_die(video_codec_name   , AVMEDIA_TYPE_VIDEO   , 0)->id : AV_CODEC_ID_NONE;
745     ic->audio_codec_id   = audio_codec_name ?
746         find_codec_or_die(audio_codec_name   , AVMEDIA_TYPE_AUDIO   , 0)->id : AV_CODEC_ID_NONE;
747     ic->subtitle_codec_id= subtitle_codec_name ?
748         find_codec_or_die(subtitle_codec_name, AVMEDIA_TYPE_SUBTITLE, 0)->id : AV_CODEC_ID_NONE;
749     ic->flags |= AVFMT_FLAG_NONBLOCK;
750     ic->interrupt_callback = int_cb;
751
752     /* open the input file with generic avformat function */
753     err = avformat_open_input(&ic, filename, file_iformat, &format_opts);
754     if (err < 0) {
755         print_error(filename, err);
756         exit_program(1);
757     }
758     assert_avoptions(format_opts);
759
760     /* apply forced codec ids */
761     for (i = 0; i < ic->nb_streams; i++)
762         choose_decoder(o, ic, ic->streams[i]);
763
764     /* Set AVCodecContext options for avformat_find_stream_info */
765     opts = setup_find_stream_info_opts(ic, codec_opts);
766     orig_nb_streams = ic->nb_streams;
767
768     /* If not enough info to get the stream parameters, we decode the
769        first frames to get it. (used in mpeg case for example) */
770     ret = avformat_find_stream_info(ic, opts);
771     if (ret < 0) {
772         av_log(NULL, AV_LOG_FATAL, "%s: could not find codec parameters\n", filename);
773         avformat_close_input(&ic);
774         exit_program(1);
775     }
776
777     timestamp = o->start_time;
778     /* add the stream start time */
779     if (ic->start_time != AV_NOPTS_VALUE)
780         timestamp += ic->start_time;
781
782     /* if seeking requested, we execute it */
783     if (o->start_time != 0) {
784         ret = av_seek_frame(ic, -1, timestamp, AVSEEK_FLAG_BACKWARD);
785         if (ret < 0) {
786             av_log(NULL, AV_LOG_WARNING, "%s: could not seek to position %0.3f\n",
787                    filename, (double)timestamp / AV_TIME_BASE);
788         }
789     }
790
791     /* update the current parameters so that they match the one of the input stream */
792     add_input_streams(o, ic);
793
794     /* dump the file content */
795     av_dump_format(ic, nb_input_files, filename, 0);
796
797     input_files = grow_array(input_files, sizeof(*input_files), &nb_input_files, nb_input_files + 1);
798     if (!(input_files[nb_input_files - 1] = av_mallocz(sizeof(*input_files[0]))))
799         exit_program(1);
800
801     input_files[nb_input_files - 1]->ctx        = ic;
802     input_files[nb_input_files - 1]->ist_index  = nb_input_streams - ic->nb_streams;
803     input_files[nb_input_files - 1]->ts_offset  = o->input_ts_offset - (copy_ts ? 0 : timestamp);
804     input_files[nb_input_files - 1]->nb_streams = ic->nb_streams;
805     input_files[nb_input_files - 1]->rate_emu   = o->rate_emu;
806
807     for (i = 0; i < o->nb_dump_attachment; i++) {
808         int j;
809
810         for (j = 0; j < ic->nb_streams; j++) {
811             AVStream *st = ic->streams[j];
812
813             if (check_stream_specifier(ic, st, o->dump_attachment[i].specifier) == 1)
814                 dump_attachment(st, o->dump_attachment[i].u.str);
815         }
816     }
817
818     for (i = 0; i < orig_nb_streams; i++)
819         av_dict_free(&opts[i]);
820     av_freep(&opts);
821
822     reset_options(o, 1);
823     return 0;
824 }
825
826 static uint8_t *get_line(AVIOContext *s)
827 {
828     AVIOContext *line;
829     uint8_t *buf;
830     char c;
831
832     if (avio_open_dyn_buf(&line) < 0) {
833         av_log(NULL, AV_LOG_FATAL, "Could not alloc buffer for reading preset.\n");
834         exit_program(1);
835     }
836
837     while ((c = avio_r8(s)) && c != '\n')
838         avio_w8(line, c);
839     avio_w8(line, 0);
840     avio_close_dyn_buf(line, &buf);
841
842     return buf;
843 }
844
845 static int get_preset_file_2(const char *preset_name, const char *codec_name, AVIOContext **s)
846 {
847     int i, ret = 1;
848     char filename[1000];
849     const char *base[3] = { getenv("AVCONV_DATADIR"),
850                             getenv("HOME"),
851                             AVCONV_DATADIR,
852                             };
853
854     for (i = 0; i < FF_ARRAY_ELEMS(base) && ret; i++) {
855         if (!base[i])
856             continue;
857         if (codec_name) {
858             snprintf(filename, sizeof(filename), "%s%s/%s-%s.avpreset", base[i],
859                      i != 1 ? "" : "/.avconv", codec_name, preset_name);
860             ret = avio_open2(s, filename, AVIO_FLAG_READ, &int_cb, NULL);
861         }
862         if (ret) {
863             snprintf(filename, sizeof(filename), "%s%s/%s.avpreset", base[i],
864                      i != 1 ? "" : "/.avconv", preset_name);
865             ret = avio_open2(s, filename, AVIO_FLAG_READ, &int_cb, NULL);
866         }
867     }
868     return ret;
869 }
870
871 static void choose_encoder(OptionsContext *o, AVFormatContext *s, OutputStream *ost)
872 {
873     char *codec_name = NULL;
874
875     MATCH_PER_STREAM_OPT(codec_names, str, codec_name, s, ost->st);
876     if (!codec_name) {
877         ost->st->codec->codec_id = av_guess_codec(s->oformat, NULL, s->filename,
878                                                   NULL, ost->st->codec->codec_type);
879         ost->enc = avcodec_find_encoder(ost->st->codec->codec_id);
880     } else if (!strcmp(codec_name, "copy"))
881         ost->stream_copy = 1;
882     else {
883         ost->enc = find_codec_or_die(codec_name, ost->st->codec->codec_type, 1);
884         ost->st->codec->codec_id = ost->enc->id;
885     }
886 }
887
888 static OutputStream *new_output_stream(OptionsContext *o, AVFormatContext *oc, enum AVMediaType type, int source_index)
889 {
890     OutputStream *ost;
891     AVStream *st = avformat_new_stream(oc, NULL);
892     int idx      = oc->nb_streams - 1, ret = 0;
893     char *bsf = NULL, *next, *codec_tag = NULL;
894     AVBitStreamFilterContext *bsfc, *bsfc_prev = NULL;
895     double qscale = -1;
896     char *buf = NULL, *arg = NULL, *preset = NULL;
897     AVIOContext *s = NULL;
898
899     if (!st) {
900         av_log(NULL, AV_LOG_FATAL, "Could not alloc stream.\n");
901         exit_program(1);
902     }
903
904     if (oc->nb_streams - 1 < o->nb_streamid_map)
905         st->id = o->streamid_map[oc->nb_streams - 1];
906
907     output_streams = grow_array(output_streams, sizeof(*output_streams), &nb_output_streams,
908                                 nb_output_streams + 1);
909     if (!(ost = av_mallocz(sizeof(*ost))))
910         exit_program(1);
911     output_streams[nb_output_streams - 1] = ost;
912
913     ost->file_index = nb_output_files;
914     ost->index      = idx;
915     ost->st         = st;
916     st->codec->codec_type = type;
917     choose_encoder(o, oc, ost);
918     if (ost->enc) {
919         ost->opts  = filter_codec_opts(codec_opts, ost->enc->id, oc, st, ost->enc);
920     }
921
922     avcodec_get_context_defaults3(st->codec, ost->enc);
923     st->codec->codec_type = type; // XXX hack, avcodec_get_context_defaults2() sets type to unknown for stream copy
924
925     MATCH_PER_STREAM_OPT(presets, str, preset, oc, st);
926     if (preset && (!(ret = get_preset_file_2(preset, ost->enc->name, &s)))) {
927         do  {
928             buf = get_line(s);
929             if (!buf[0] || buf[0] == '#') {
930                 av_free(buf);
931                 continue;
932             }
933             if (!(arg = strchr(buf, '='))) {
934                 av_log(NULL, AV_LOG_FATAL, "Invalid line found in the preset file.\n");
935                 exit_program(1);
936             }
937             *arg++ = 0;
938             av_dict_set(&ost->opts, buf, arg, AV_DICT_DONT_OVERWRITE);
939             av_free(buf);
940         } while (!s->eof_reached);
941         avio_close(s);
942     }
943     if (ret) {
944         av_log(NULL, AV_LOG_FATAL,
945                "Preset %s specified for stream %d:%d, but could not be opened.\n",
946                preset, ost->file_index, ost->index);
947         exit_program(1);
948     }
949
950     ost->max_frames = INT64_MAX;
951     MATCH_PER_STREAM_OPT(max_frames, i64, ost->max_frames, oc, st);
952
953     MATCH_PER_STREAM_OPT(bitstream_filters, str, bsf, oc, st);
954     while (bsf) {
955         if (next = strchr(bsf, ','))
956             *next++ = 0;
957         if (!(bsfc = av_bitstream_filter_init(bsf))) {
958             av_log(NULL, AV_LOG_FATAL, "Unknown bitstream filter %s\n", bsf);
959             exit_program(1);
960         }
961         if (bsfc_prev)
962             bsfc_prev->next = bsfc;
963         else
964             ost->bitstream_filters = bsfc;
965
966         bsfc_prev = bsfc;
967         bsf       = next;
968     }
969
970     MATCH_PER_STREAM_OPT(codec_tags, str, codec_tag, oc, st);
971     if (codec_tag) {
972         uint32_t tag = strtol(codec_tag, &next, 0);
973         if (*next)
974             tag = AV_RL32(codec_tag);
975         st->codec->codec_tag = tag;
976     }
977
978     MATCH_PER_STREAM_OPT(qscale, dbl, qscale, oc, st);
979     if (qscale >= 0 || same_quant) {
980         st->codec->flags |= CODEC_FLAG_QSCALE;
981         st->codec->global_quality = FF_QP2LAMBDA * qscale;
982     }
983
984     if (oc->oformat->flags & AVFMT_GLOBALHEADER)
985         st->codec->flags |= CODEC_FLAG_GLOBAL_HEADER;
986
987     av_opt_get_int(sws_opts, "sws_flags", 0, &ost->sws_flags);
988     av_opt_get_int   (swr_opts, "dither_method", 0, &ost->swr_dither_method);
989     av_opt_get_double(swr_opts, "dither_scale" , 0, &ost->swr_dither_scale);
990
991     ost->source_index = source_index;
992     if (source_index >= 0) {
993         ost->sync_ist = input_streams[source_index];
994         input_streams[source_index]->discard = 0;
995         input_streams[source_index]->st->discard = AVDISCARD_NONE;
996     }
997
998     return ost;
999 }
1000
1001 static void parse_matrix_coeffs(uint16_t *dest, const char *str)
1002 {
1003     int i;
1004     const char *p = str;
1005     for (i = 0;; i++) {
1006         dest[i] = atoi(p);
1007         if (i == 63)
1008             break;
1009         p = strchr(p, ',');
1010         if (!p) {
1011             av_log(NULL, AV_LOG_FATAL, "Syntax error in matrix \"%s\" at coeff %d\n", str, i);
1012             exit_program(1);
1013         }
1014         p++;
1015     }
1016 }
1017
1018 static OutputStream *new_video_stream(OptionsContext *o, AVFormatContext *oc, int source_index)
1019 {
1020     AVStream *st;
1021     OutputStream *ost;
1022     AVCodecContext *video_enc;
1023     char *frame_rate = NULL;
1024
1025     ost = new_output_stream(o, oc, AVMEDIA_TYPE_VIDEO, source_index);
1026     st  = ost->st;
1027     video_enc = st->codec;
1028
1029     MATCH_PER_STREAM_OPT(frame_rates, str, frame_rate, oc, st);
1030     if (frame_rate && av_parse_video_rate(&ost->frame_rate, frame_rate) < 0) {
1031         av_log(NULL, AV_LOG_FATAL, "Invalid framerate value: %s\n", frame_rate);
1032         exit_program(1);
1033     }
1034
1035     if (!ost->stream_copy) {
1036         const char *p = NULL;
1037         char *frame_size = NULL;
1038         char *frame_aspect_ratio = NULL, *frame_pix_fmt = NULL;
1039         char *intra_matrix = NULL, *inter_matrix = NULL;
1040         const char *filters = "null";
1041         int i;
1042
1043         MATCH_PER_STREAM_OPT(frame_sizes, str, frame_size, oc, st);
1044         if (frame_size && av_parse_video_size(&video_enc->width, &video_enc->height, frame_size) < 0) {
1045             av_log(NULL, AV_LOG_FATAL, "Invalid frame size: %s.\n", frame_size);
1046             exit_program(1);
1047         }
1048
1049         MATCH_PER_STREAM_OPT(frame_aspect_ratios, str, frame_aspect_ratio, oc, st);
1050         if (frame_aspect_ratio) {
1051             AVRational q;
1052             if (av_parse_ratio(&q, frame_aspect_ratio, 255, 0, NULL) < 0 ||
1053                 q.num <= 0 || q.den <= 0) {
1054                 av_log(NULL, AV_LOG_FATAL, "Invalid aspect ratio: %s\n", frame_aspect_ratio);
1055                 exit_program(1);
1056             }
1057             ost->frame_aspect_ratio = av_q2d(q);
1058         }
1059
1060         video_enc->bits_per_raw_sample = frame_bits_per_raw_sample;
1061         MATCH_PER_STREAM_OPT(frame_pix_fmts, str, frame_pix_fmt, oc, st);
1062         if (frame_pix_fmt && *frame_pix_fmt == '+') {
1063             ost->keep_pix_fmt = 1;
1064             if (!*++frame_pix_fmt)
1065                 frame_pix_fmt = NULL;
1066         }
1067         if (frame_pix_fmt && (video_enc->pix_fmt = av_get_pix_fmt(frame_pix_fmt)) == PIX_FMT_NONE) {
1068             av_log(NULL, AV_LOG_FATAL, "Unknown pixel format requested: %s.\n", frame_pix_fmt);
1069             exit_program(1);
1070         }
1071         st->sample_aspect_ratio = video_enc->sample_aspect_ratio;
1072
1073         if (intra_only)
1074             video_enc->gop_size = 0;
1075         MATCH_PER_STREAM_OPT(intra_matrices, str, intra_matrix, oc, st);
1076         if (intra_matrix) {
1077             if (!(video_enc->intra_matrix = av_mallocz(sizeof(*video_enc->intra_matrix) * 64))) {
1078                 av_log(NULL, AV_LOG_FATAL, "Could not allocate memory for intra matrix.\n");
1079                 exit_program(1);
1080             }
1081             parse_matrix_coeffs(video_enc->intra_matrix, intra_matrix);
1082         }
1083         MATCH_PER_STREAM_OPT(inter_matrices, str, inter_matrix, oc, st);
1084         if (inter_matrix) {
1085             if (!(video_enc->inter_matrix = av_mallocz(sizeof(*video_enc->inter_matrix) * 64))) {
1086                 av_log(NULL, AV_LOG_FATAL, "Could not allocate memory for inter matrix.\n");
1087                 exit_program(1);
1088             }
1089             parse_matrix_coeffs(video_enc->inter_matrix, inter_matrix);
1090         }
1091
1092         MATCH_PER_STREAM_OPT(rc_overrides, str, p, oc, st);
1093         for (i = 0; p; i++) {
1094             int start, end, q;
1095             int e = sscanf(p, "%d,%d,%d", &start, &end, &q);
1096             if (e != 3) {
1097                 av_log(NULL, AV_LOG_FATAL, "error parsing rc_override\n");
1098                 exit_program(1);
1099             }
1100             /* FIXME realloc failure */
1101             video_enc->rc_override =
1102                 av_realloc(video_enc->rc_override,
1103                            sizeof(RcOverride) * (i + 1));
1104             video_enc->rc_override[i].start_frame = start;
1105             video_enc->rc_override[i].end_frame   = end;
1106             if (q > 0) {
1107                 video_enc->rc_override[i].qscale         = q;
1108                 video_enc->rc_override[i].quality_factor = 1.0;
1109             }
1110             else {
1111                 video_enc->rc_override[i].qscale         = 0;
1112                 video_enc->rc_override[i].quality_factor = -q/100.0;
1113             }
1114             p = strchr(p, '/');
1115             if (p) p++;
1116         }
1117         video_enc->rc_override_count = i;
1118         if (!video_enc->rc_initial_buffer_occupancy)
1119             video_enc->rc_initial_buffer_occupancy = video_enc->rc_buffer_size * 3 / 4;
1120         video_enc->intra_dc_precision = intra_dc_precision - 8;
1121
1122         if (do_psnr)
1123             video_enc->flags|= CODEC_FLAG_PSNR;
1124
1125         /* two pass mode */
1126         if (do_pass) {
1127             if (do_pass & 1) {
1128                 video_enc->flags |= CODEC_FLAG_PASS1;
1129             }
1130             if (do_pass & 2) {
1131                 video_enc->flags |= CODEC_FLAG_PASS2;
1132             }
1133         }
1134
1135         MATCH_PER_STREAM_OPT(forced_key_frames, str, ost->forced_keyframes, oc, st);
1136         if (ost->forced_keyframes)
1137             ost->forced_keyframes = av_strdup(ost->forced_keyframes);
1138
1139         MATCH_PER_STREAM_OPT(force_fps, i, ost->force_fps, oc, st);
1140
1141         ost->top_field_first = -1;
1142         MATCH_PER_STREAM_OPT(top_field_first, i, ost->top_field_first, oc, st);
1143
1144         MATCH_PER_STREAM_OPT(filters, str, filters, oc, st);
1145         ost->avfilter = av_strdup(filters);
1146     } else {
1147         MATCH_PER_STREAM_OPT(copy_initial_nonkeyframes, i, ost->copy_initial_nonkeyframes, oc ,st);
1148     }
1149
1150     return ost;
1151 }
1152
1153 static OutputStream *new_audio_stream(OptionsContext *o, AVFormatContext *oc, int source_index)
1154 {
1155     int n;
1156     AVStream *st;
1157     OutputStream *ost;
1158     AVCodecContext *audio_enc;
1159
1160     ost = new_output_stream(o, oc, AVMEDIA_TYPE_AUDIO, source_index);
1161     st  = ost->st;
1162
1163     audio_enc = st->codec;
1164     audio_enc->codec_type = AVMEDIA_TYPE_AUDIO;
1165
1166     if (!ost->stream_copy) {
1167         char *sample_fmt = NULL;
1168         const char *filters = "anull";
1169
1170         MATCH_PER_STREAM_OPT(audio_channels, i, audio_enc->channels, oc, st);
1171
1172         MATCH_PER_STREAM_OPT(sample_fmts, str, sample_fmt, oc, st);
1173         if (sample_fmt &&
1174             (audio_enc->sample_fmt = av_get_sample_fmt(sample_fmt)) == AV_SAMPLE_FMT_NONE) {
1175             av_log(NULL, AV_LOG_FATAL, "Invalid sample format '%s'\n", sample_fmt);
1176             exit_program(1);
1177         }
1178
1179         MATCH_PER_STREAM_OPT(audio_sample_rate, i, audio_enc->sample_rate, oc, st);
1180
1181         MATCH_PER_STREAM_OPT(filters, str, filters, oc, st);
1182
1183         av_assert1(filters);
1184         ost->avfilter = av_strdup(filters);
1185
1186         /* check for channel mapping for this audio stream */
1187         for (n = 0; n < o->nb_audio_channel_maps; n++) {
1188             AudioChannelMap *map = &o->audio_channel_maps[n];
1189             InputStream *ist = input_streams[ost->source_index];
1190             if ((map->channel_idx == -1 || (ist->file_index == map->file_idx && ist->st->index == map->stream_idx)) &&
1191                 (map->ofile_idx   == -1 || ost->file_index == map->ofile_idx) &&
1192                 (map->ostream_idx == -1 || ost->st->index  == map->ostream_idx)) {
1193                 if (ost->audio_channels_mapped < FF_ARRAY_ELEMS(ost->audio_channels_map))
1194                     ost->audio_channels_map[ost->audio_channels_mapped++] = map->channel_idx;
1195                 else
1196                     av_log(NULL, AV_LOG_FATAL, "Max channel mapping for output %d.%d reached\n",
1197                            ost->file_index, ost->st->index);
1198             }
1199         }
1200     }
1201
1202     return ost;
1203 }
1204
1205 static OutputStream *new_data_stream(OptionsContext *o, AVFormatContext *oc, int source_index)
1206 {
1207     OutputStream *ost;
1208
1209     ost = new_output_stream(o, oc, AVMEDIA_TYPE_DATA, source_index);
1210     if (!ost->stream_copy) {
1211         av_log(NULL, AV_LOG_FATAL, "Data stream encoding not supported yet (only streamcopy)\n");
1212         exit_program(1);
1213     }
1214
1215     return ost;
1216 }
1217
1218 static OutputStream *new_attachment_stream(OptionsContext *o, AVFormatContext *oc, int source_index)
1219 {
1220     OutputStream *ost = new_output_stream(o, oc, AVMEDIA_TYPE_ATTACHMENT, source_index);
1221     ost->stream_copy = 1;
1222     return ost;
1223 }
1224
1225 static OutputStream *new_subtitle_stream(OptionsContext *o, AVFormatContext *oc, int source_index)
1226 {
1227     AVStream *st;
1228     OutputStream *ost;
1229     AVCodecContext *subtitle_enc;
1230
1231     ost = new_output_stream(o, oc, AVMEDIA_TYPE_SUBTITLE, source_index);
1232     st  = ost->st;
1233     subtitle_enc = st->codec;
1234
1235     subtitle_enc->codec_type = AVMEDIA_TYPE_SUBTITLE;
1236
1237     MATCH_PER_STREAM_OPT(copy_initial_nonkeyframes, i, ost->copy_initial_nonkeyframes, oc, st);
1238
1239     if (!ost->stream_copy) {
1240         char *frame_size = NULL;
1241
1242         MATCH_PER_STREAM_OPT(frame_sizes, str, frame_size, oc, st);
1243         if (frame_size && av_parse_video_size(&subtitle_enc->width, &subtitle_enc->height, frame_size) < 0) {
1244             av_log(NULL, AV_LOG_FATAL, "Invalid frame size: %s.\n", frame_size);
1245             exit_program(1);
1246         }
1247     }
1248
1249     return ost;
1250 }
1251
1252 /* arg format is "output-stream-index:streamid-value". */
1253 static int opt_streamid(void *optctx, const char *opt, const char *arg)
1254 {
1255     OptionsContext *o = optctx;
1256     int idx;
1257     char *p;
1258     char idx_str[16];
1259
1260     av_strlcpy(idx_str, arg, sizeof(idx_str));
1261     p = strchr(idx_str, ':');
1262     if (!p) {
1263         av_log(NULL, AV_LOG_FATAL,
1264                "Invalid value '%s' for option '%s', required syntax is 'index:value'\n",
1265                arg, opt);
1266         exit_program(1);
1267     }
1268     *p++ = '\0';
1269     idx = parse_number_or_die(opt, idx_str, OPT_INT, 0, MAX_STREAMS-1);
1270     o->streamid_map = grow_array(o->streamid_map, sizeof(*o->streamid_map), &o->nb_streamid_map, idx+1);
1271     o->streamid_map[idx] = parse_number_or_die(opt, p, OPT_INT, 0, INT_MAX);
1272     return 0;
1273 }
1274
1275 static int copy_chapters(InputFile *ifile, OutputFile *ofile, int copy_metadata)
1276 {
1277     AVFormatContext *is = ifile->ctx;
1278     AVFormatContext *os = ofile->ctx;
1279     int i;
1280
1281     for (i = 0; i < is->nb_chapters; i++) {
1282         AVChapter *in_ch = is->chapters[i], *out_ch;
1283         int64_t ts_off   = av_rescale_q(ofile->start_time - ifile->ts_offset,
1284                                        AV_TIME_BASE_Q, in_ch->time_base);
1285         int64_t rt       = (ofile->recording_time == INT64_MAX) ? INT64_MAX :
1286                            av_rescale_q(ofile->recording_time, AV_TIME_BASE_Q, in_ch->time_base);
1287
1288
1289         if (in_ch->end < ts_off)
1290             continue;
1291         if (rt != INT64_MAX && in_ch->start > rt + ts_off)
1292             break;
1293
1294         out_ch = av_mallocz(sizeof(AVChapter));
1295         if (!out_ch)
1296             return AVERROR(ENOMEM);
1297
1298         out_ch->id        = in_ch->id;
1299         out_ch->time_base = in_ch->time_base;
1300         out_ch->start     = FFMAX(0,  in_ch->start - ts_off);
1301         out_ch->end       = FFMIN(rt, in_ch->end   - ts_off);
1302
1303         if (copy_metadata)
1304             av_dict_copy(&out_ch->metadata, in_ch->metadata, 0);
1305
1306         os->nb_chapters++;
1307         os->chapters = av_realloc_f(os->chapters, os->nb_chapters, sizeof(AVChapter));
1308         if (!os->chapters)
1309             return AVERROR(ENOMEM);
1310         os->chapters[os->nb_chapters - 1] = out_ch;
1311     }
1312     return 0;
1313 }
1314
1315 static int read_ffserver_streams(OptionsContext *o, AVFormatContext *s, const char *filename)
1316 {
1317     int i, err;
1318     AVFormatContext *ic = avformat_alloc_context();
1319
1320     ic->interrupt_callback = int_cb;
1321     err = avformat_open_input(&ic, filename, NULL, NULL);
1322     if (err < 0)
1323         return err;
1324     /* copy stream format */
1325     for(i=0;i<ic->nb_streams;i++) {
1326         AVStream *st;
1327         OutputStream *ost;
1328         AVCodec *codec;
1329         AVCodecContext *avctx;
1330
1331         codec = avcodec_find_encoder(ic->streams[i]->codec->codec_id);
1332         ost   = new_output_stream(o, s, codec->type, -1);
1333         st    = ost->st;
1334         avctx = st->codec;
1335         ost->enc = codec;
1336
1337         // FIXME: a more elegant solution is needed
1338         memcpy(st, ic->streams[i], sizeof(AVStream));
1339         st->cur_dts = 0;
1340         st->info = av_malloc(sizeof(*st->info));
1341         memcpy(st->info, ic->streams[i]->info, sizeof(*st->info));
1342         st->codec= avctx;
1343         avcodec_copy_context(st->codec, ic->streams[i]->codec);
1344
1345         if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO && !ost->stream_copy)
1346             choose_sample_fmt(st, codec);
1347         else if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO && !ost->stream_copy)
1348             choose_pixel_fmt(st, codec, st->codec->pix_fmt);
1349     }
1350
1351     avformat_close_input(&ic);
1352     return 0;
1353 }
1354
1355 static void init_output_filter(OutputFilter *ofilter, OptionsContext *o,
1356                                AVFormatContext *oc)
1357 {
1358     OutputStream *ost;
1359
1360     switch (avfilter_pad_get_type(ofilter->out_tmp->filter_ctx->output_pads,
1361                                   ofilter->out_tmp->pad_idx)) {
1362     case AVMEDIA_TYPE_VIDEO: ost = new_video_stream(o, oc, -1); break;
1363     case AVMEDIA_TYPE_AUDIO: ost = new_audio_stream(o, oc, -1); break;
1364     default:
1365         av_log(NULL, AV_LOG_FATAL, "Only video and audio filters are supported "
1366                "currently.\n");
1367         exit_program(1);
1368     }
1369
1370     ost->source_index = -1;
1371     ost->filter       = ofilter;
1372
1373     ofilter->ost      = ost;
1374
1375     if (ost->stream_copy) {
1376         av_log(NULL, AV_LOG_ERROR, "Streamcopy requested for output stream %d:%d, "
1377                "which is fed from a complex filtergraph. Filtering and streamcopy "
1378                "cannot be used together.\n", ost->file_index, ost->index);
1379         exit_program(1);
1380     }
1381
1382     if (configure_output_filter(ofilter->graph, ofilter, ofilter->out_tmp) < 0) {
1383         av_log(NULL, AV_LOG_FATAL, "Error configuring filter.\n");
1384         exit_program(1);
1385     }
1386     avfilter_inout_free(&ofilter->out_tmp);
1387 }
1388
1389 static int configure_complex_filters(void)
1390 {
1391     int i, ret = 0;
1392
1393     for (i = 0; i < nb_filtergraphs; i++)
1394         if (!filtergraphs[i]->graph &&
1395             (ret = configure_filtergraph(filtergraphs[i])) < 0)
1396             return ret;
1397     return 0;
1398 }
1399
1400 void opt_output_file(void *optctx, const char *filename)
1401 {
1402     OptionsContext *o = optctx;
1403     AVFormatContext *oc;
1404     int i, j, err;
1405     AVOutputFormat *file_oformat;
1406     OutputStream *ost;
1407     InputStream  *ist;
1408
1409     if (configure_complex_filters() < 0) {
1410         av_log(NULL, AV_LOG_FATAL, "Error configuring filters.\n");
1411         exit_program(1);
1412     }
1413
1414     if (!strcmp(filename, "-"))
1415         filename = "pipe:";
1416
1417     err = avformat_alloc_output_context2(&oc, NULL, o->format, filename);
1418     if (!oc) {
1419         print_error(filename, err);
1420         exit_program(1);
1421     }
1422     file_oformat= oc->oformat;
1423     oc->interrupt_callback = int_cb;
1424
1425     /* create streams for all unlabeled output pads */
1426     for (i = 0; i < nb_filtergraphs; i++) {
1427         FilterGraph *fg = filtergraphs[i];
1428         for (j = 0; j < fg->nb_outputs; j++) {
1429             OutputFilter *ofilter = fg->outputs[j];
1430
1431             if (!ofilter->out_tmp || ofilter->out_tmp->name)
1432                 continue;
1433
1434             switch (avfilter_pad_get_type(ofilter->out_tmp->filter_ctx->output_pads,
1435                                           ofilter->out_tmp->pad_idx)) {
1436             case AVMEDIA_TYPE_VIDEO:    o->video_disable    = 1; break;
1437             case AVMEDIA_TYPE_AUDIO:    o->audio_disable    = 1; break;
1438             case AVMEDIA_TYPE_SUBTITLE: o->subtitle_disable = 1; break;
1439             }
1440             init_output_filter(ofilter, o, oc);
1441         }
1442     }
1443
1444     if (!strcmp(file_oformat->name, "ffm") &&
1445         av_strstart(filename, "http:", NULL)) {
1446         int j;
1447         /* special case for files sent to ffserver: we get the stream
1448            parameters from ffserver */
1449         int err = read_ffserver_streams(o, oc, filename);
1450         if (err < 0) {
1451             print_error(filename, err);
1452             exit_program(1);
1453         }
1454         for(j = nb_output_streams - oc->nb_streams; j < nb_output_streams; j++) {
1455             ost = output_streams[j];
1456             for (i = 0; i < nb_input_streams; i++) {
1457                 ist = input_streams[i];
1458                 if(ist->st->codec->codec_type == ost->st->codec->codec_type){
1459                     ost->sync_ist= ist;
1460                     ost->source_index= i;
1461                     if(ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO) ost->avfilter = av_strdup("anull");
1462                     if(ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO) ost->avfilter = av_strdup("null");
1463                     ist->discard = 0;
1464                     ist->st->discard = AVDISCARD_NONE;
1465                     break;
1466                 }
1467             }
1468             if(!ost->sync_ist){
1469                 av_log(NULL, AV_LOG_FATAL, "Missing %s stream which is required by this ffm\n", av_get_media_type_string(ost->st->codec->codec_type));
1470                 exit_program(1);
1471             }
1472         }
1473     } else if (!o->nb_stream_maps) {
1474         /* pick the "best" stream of each type */
1475
1476         /* video: highest resolution */
1477         if (!o->video_disable && oc->oformat->video_codec != AV_CODEC_ID_NONE) {
1478             int area = 0, idx = -1;
1479             int qcr = avformat_query_codec(oc->oformat, oc->oformat->video_codec, 0);
1480             for (i = 0; i < nb_input_streams; i++) {
1481                 ist = input_streams[i];
1482                 if (ist->st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
1483                     ist->st->codec->width * ist->st->codec->height > area) {
1484                     if((qcr==MKTAG('A', 'P', 'I', 'C')) && !(ist->st->disposition & AV_DISPOSITION_ATTACHED_PIC))
1485                         continue;
1486                     area = ist->st->codec->width * ist->st->codec->height;
1487                     idx = i;
1488                 }
1489             }
1490             if (idx >= 0)
1491                 new_video_stream(o, oc, idx);
1492         }
1493
1494         /* audio: most channels */
1495         if (!o->audio_disable && oc->oformat->audio_codec != AV_CODEC_ID_NONE) {
1496             int channels = 0, idx = -1;
1497             for (i = 0; i < nb_input_streams; i++) {
1498                 ist = input_streams[i];
1499                 if (ist->st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
1500                     ist->st->codec->channels > channels) {
1501                     channels = ist->st->codec->channels;
1502                     idx = i;
1503                 }
1504             }
1505             if (idx >= 0)
1506                 new_audio_stream(o, oc, idx);
1507         }
1508
1509         /* subtitles: pick first */
1510         if (!o->subtitle_disable && (oc->oformat->subtitle_codec != AV_CODEC_ID_NONE || subtitle_codec_name)) {
1511             for (i = 0; i < nb_input_streams; i++)
1512                 if (input_streams[i]->st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
1513                     new_subtitle_stream(o, oc, i);
1514                     break;
1515                 }
1516         }
1517         /* do something with data? */
1518     } else {
1519         for (i = 0; i < o->nb_stream_maps; i++) {
1520             StreamMap *map = &o->stream_maps[i];
1521             int src_idx = input_files[map->file_index]->ist_index + map->stream_index;
1522
1523             if (map->disabled)
1524                 continue;
1525
1526             if (map->linklabel) {
1527                 FilterGraph *fg;
1528                 OutputFilter *ofilter = NULL;
1529                 int j, k;
1530
1531                 for (j = 0; j < nb_filtergraphs; j++) {
1532                     fg = filtergraphs[j];
1533                     for (k = 0; k < fg->nb_outputs; k++) {
1534                         AVFilterInOut *out = fg->outputs[k]->out_tmp;
1535                         if (out && !strcmp(out->name, map->linklabel)) {
1536                             ofilter = fg->outputs[k];
1537                             goto loop_end;
1538                         }
1539                     }
1540                 }
1541 loop_end:
1542                 if (!ofilter) {
1543                     av_log(NULL, AV_LOG_FATAL, "Output with label '%s' does not exist "
1544                            "in any defined filter graph.\n", map->linklabel);
1545                     exit_program(1);
1546                 }
1547                 init_output_filter(ofilter, o, oc);
1548             } else {
1549                 ist = input_streams[input_files[map->file_index]->ist_index + map->stream_index];
1550                 if(o->subtitle_disable && ist->st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE)
1551                     continue;
1552                 if(o->   audio_disable && ist->st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
1553                     continue;
1554                 if(o->   video_disable && ist->st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
1555                     continue;
1556                 if(o->    data_disable && ist->st->codec->codec_type == AVMEDIA_TYPE_DATA)
1557                     continue;
1558
1559                 switch (ist->st->codec->codec_type) {
1560                 case AVMEDIA_TYPE_VIDEO:      ost = new_video_stream     (o, oc, src_idx); break;
1561                 case AVMEDIA_TYPE_AUDIO:      ost = new_audio_stream     (o, oc, src_idx); break;
1562                 case AVMEDIA_TYPE_SUBTITLE:   ost = new_subtitle_stream  (o, oc, src_idx); break;
1563                 case AVMEDIA_TYPE_DATA:       ost = new_data_stream      (o, oc, src_idx); break;
1564                 case AVMEDIA_TYPE_ATTACHMENT: ost = new_attachment_stream(o, oc, src_idx); break;
1565                 default:
1566                     av_log(NULL, AV_LOG_FATAL, "Cannot map stream #%d:%d - unsupported type.\n",
1567                            map->file_index, map->stream_index);
1568                     exit_program(1);
1569                 }
1570             }
1571         }
1572     }
1573
1574
1575     for (i = nb_output_streams - oc->nb_streams; i < nb_output_streams; i++) { //for all streams of this output file
1576         AVDictionaryEntry *e;
1577         ost = output_streams[i];
1578
1579         if (   ost->stream_copy
1580             && (e = av_dict_get(codec_opts, "flags", NULL, AV_DICT_IGNORE_SUFFIX))
1581             && (!e->key[5] || check_stream_specifier(oc, ost->st, e->key+6)))
1582             if (av_opt_set(ost->st->codec, "flags", e->value, 0) < 0)
1583                 exit_program(1);
1584     }
1585
1586     /* handle attached files */
1587     for (i = 0; i < o->nb_attachments; i++) {
1588         AVIOContext *pb;
1589         uint8_t *attachment;
1590         const char *p;
1591         int64_t len;
1592
1593         if ((err = avio_open2(&pb, o->attachments[i], AVIO_FLAG_READ, &int_cb, NULL)) < 0) {
1594             av_log(NULL, AV_LOG_FATAL, "Could not open attachment file %s.\n",
1595                    o->attachments[i]);
1596             exit_program(1);
1597         }
1598         if ((len = avio_size(pb)) <= 0) {
1599             av_log(NULL, AV_LOG_FATAL, "Could not get size of the attachment %s.\n",
1600                    o->attachments[i]);
1601             exit_program(1);
1602         }
1603         if (!(attachment = av_malloc(len))) {
1604             av_log(NULL, AV_LOG_FATAL, "Attachment %s too large to fit into memory.\n",
1605                    o->attachments[i]);
1606             exit_program(1);
1607         }
1608         avio_read(pb, attachment, len);
1609
1610         ost = new_attachment_stream(o, oc, -1);
1611         ost->stream_copy               = 0;
1612         ost->attachment_filename       = o->attachments[i];
1613         ost->st->codec->extradata      = attachment;
1614         ost->st->codec->extradata_size = len;
1615
1616         p = strrchr(o->attachments[i], '/');
1617         av_dict_set(&ost->st->metadata, "filename", (p && *p) ? p + 1 : o->attachments[i], AV_DICT_DONT_OVERWRITE);
1618         avio_close(pb);
1619     }
1620
1621     output_files = grow_array(output_files, sizeof(*output_files), &nb_output_files, nb_output_files + 1);
1622     if (!(output_files[nb_output_files - 1] = av_mallocz(sizeof(*output_files[0]))))
1623         exit_program(1);
1624
1625     output_files[nb_output_files - 1]->ctx            = oc;
1626     output_files[nb_output_files - 1]->ost_index      = nb_output_streams - oc->nb_streams;
1627     output_files[nb_output_files - 1]->recording_time = o->recording_time;
1628     if (o->recording_time != INT64_MAX)
1629         oc->duration = o->recording_time;
1630     output_files[nb_output_files - 1]->start_time     = o->start_time;
1631     output_files[nb_output_files - 1]->limit_filesize = o->limit_filesize;
1632     output_files[nb_output_files - 1]->shortest       = o->shortest;
1633     av_dict_copy(&output_files[nb_output_files - 1]->opts, format_opts, 0);
1634
1635     /* check filename in case of an image number is expected */
1636     if (oc->oformat->flags & AVFMT_NEEDNUMBER) {
1637         if (!av_filename_number_test(oc->filename)) {
1638             print_error(oc->filename, AVERROR(EINVAL));
1639             exit_program(1);
1640         }
1641     }
1642
1643     if (!(oc->oformat->flags & AVFMT_NOFILE)) {
1644         /* test if it already exists to avoid losing precious files */
1645         assert_file_overwrite(filename);
1646
1647         /* open the file */
1648         if ((err = avio_open2(&oc->pb, filename, AVIO_FLAG_WRITE,
1649                               &oc->interrupt_callback,
1650                               &output_files[nb_output_files - 1]->opts)) < 0) {
1651             print_error(filename, err);
1652             exit_program(1);
1653         }
1654     }
1655
1656     if (o->mux_preload) {
1657         uint8_t buf[64];
1658         snprintf(buf, sizeof(buf), "%d", (int)(o->mux_preload*AV_TIME_BASE));
1659         av_dict_set(&output_files[nb_output_files - 1]->opts, "preload", buf, 0);
1660     }
1661     oc->max_delay = (int)(o->mux_max_delay * AV_TIME_BASE);
1662
1663     /* copy metadata */
1664     for (i = 0; i < o->nb_metadata_map; i++) {
1665         char *p;
1666         int in_file_index = strtol(o->metadata_map[i].u.str, &p, 0);
1667
1668         if (in_file_index >= nb_input_files) {
1669             av_log(NULL, AV_LOG_FATAL, "Invalid input file index %d while processing metadata maps\n", in_file_index);
1670             exit_program(1);
1671         }
1672         copy_metadata(o->metadata_map[i].specifier, *p ? p + 1 : p, oc, in_file_index >= 0 ? input_files[in_file_index]->ctx : NULL, o);
1673     }
1674
1675     /* copy chapters */
1676     if (o->chapters_input_file >= nb_input_files) {
1677         if (o->chapters_input_file == INT_MAX) {
1678             /* copy chapters from the first input file that has them*/
1679             o->chapters_input_file = -1;
1680             for (i = 0; i < nb_input_files; i++)
1681                 if (input_files[i]->ctx->nb_chapters) {
1682                     o->chapters_input_file = i;
1683                     break;
1684                 }
1685         } else {
1686             av_log(NULL, AV_LOG_FATAL, "Invalid input file index %d in chapter mapping.\n",
1687                    o->chapters_input_file);
1688             exit_program(1);
1689         }
1690     }
1691     if (o->chapters_input_file >= 0)
1692         copy_chapters(input_files[o->chapters_input_file], output_files[nb_output_files - 1],
1693                       !o->metadata_chapters_manual);
1694
1695     /* copy global metadata by default */
1696     if (!o->metadata_global_manual && nb_input_files){
1697         av_dict_copy(&oc->metadata, input_files[0]->ctx->metadata,
1698                      AV_DICT_DONT_OVERWRITE);
1699         if(o->recording_time != INT64_MAX)
1700             av_dict_set(&oc->metadata, "duration", NULL, 0);
1701         av_dict_set(&oc->metadata, "creation_time", NULL, 0);
1702     }
1703     if (!o->metadata_streams_manual)
1704         for (i = output_files[nb_output_files - 1]->ost_index; i < nb_output_streams; i++) {
1705             InputStream *ist;
1706             if (output_streams[i]->source_index < 0)         /* this is true e.g. for attached files */
1707                 continue;
1708             ist = input_streams[output_streams[i]->source_index];
1709             av_dict_copy(&output_streams[i]->st->metadata, ist->st->metadata, AV_DICT_DONT_OVERWRITE);
1710         }
1711
1712     /* process manually set metadata */
1713     for (i = 0; i < o->nb_metadata; i++) {
1714         AVDictionary **m;
1715         char type, *val;
1716         const char *stream_spec;
1717         int index = 0, j, ret = 0;
1718
1719         val = strchr(o->metadata[i].u.str, '=');
1720         if (!val) {
1721             av_log(NULL, AV_LOG_FATAL, "No '=' character in metadata string %s.\n",
1722                    o->metadata[i].u.str);
1723             exit_program(1);
1724         }
1725         *val++ = 0;
1726
1727         parse_meta_type(o->metadata[i].specifier, &type, &index, &stream_spec);
1728         if (type == 's') {
1729             for (j = 0; j < oc->nb_streams; j++) {
1730                 if ((ret = check_stream_specifier(oc, oc->streams[j], stream_spec)) > 0) {
1731                     av_dict_set(&oc->streams[j]->metadata, o->metadata[i].u.str, *val ? val : NULL, 0);
1732                 } else if (ret < 0)
1733                     exit_program(1);
1734             }
1735         }
1736         else {
1737             switch (type) {
1738             case 'g':
1739                 m = &oc->metadata;
1740                 break;
1741             case 'c':
1742                 if (index < 0 || index >= oc->nb_chapters) {
1743                     av_log(NULL, AV_LOG_FATAL, "Invalid chapter index %d in metadata specifier.\n", index);
1744                     exit_program(1);
1745                 }
1746                 m = &oc->chapters[index]->metadata;
1747                 break;
1748             default:
1749                 av_log(NULL, AV_LOG_FATAL, "Invalid metadata specifier %s.\n", o->metadata[i].specifier);
1750                 exit_program(1);
1751             }
1752             av_dict_set(m, o->metadata[i].u.str, *val ? val : NULL, 0);
1753         }
1754     }
1755
1756     reset_options(o, 0);
1757 }
1758
1759 /* same option as mencoder */
1760 static int opt_pass(const char *opt, const char *arg)
1761 {
1762     do_pass = parse_number_or_die(opt, arg, OPT_INT, 1, 3);
1763     return 0;
1764 }
1765
1766
1767 static int opt_target(void *optctx, const char *opt, const char *arg)
1768 {
1769     OptionsContext *o = optctx;
1770     enum { PAL, NTSC, FILM, UNKNOWN } norm = UNKNOWN;
1771     static const char *const frame_rates[] = { "25", "30000/1001", "24000/1001" };
1772
1773     if (!strncmp(arg, "pal-", 4)) {
1774         norm = PAL;
1775         arg += 4;
1776     } else if (!strncmp(arg, "ntsc-", 5)) {
1777         norm = NTSC;
1778         arg += 5;
1779     } else if (!strncmp(arg, "film-", 5)) {
1780         norm = FILM;
1781         arg += 5;
1782     } else {
1783         /* Try to determine PAL/NTSC by peeking in the input files */
1784         if (nb_input_files) {
1785             int i, j, fr;
1786             for (j = 0; j < nb_input_files; j++) {
1787                 for (i = 0; i < input_files[j]->nb_streams; i++) {
1788                     AVCodecContext *c = input_files[j]->ctx->streams[i]->codec;
1789                     if (c->codec_type != AVMEDIA_TYPE_VIDEO)
1790                         continue;
1791                     fr = c->time_base.den * 1000 / c->time_base.num;
1792                     if (fr == 25000) {
1793                         norm = PAL;
1794                         break;
1795                     } else if ((fr == 29970) || (fr == 23976)) {
1796                         norm = NTSC;
1797                         break;
1798                     }
1799                 }
1800                 if (norm != UNKNOWN)
1801                     break;
1802             }
1803         }
1804         if (norm != UNKNOWN)
1805             av_log(NULL, AV_LOG_INFO, "Assuming %s for target.\n", norm == PAL ? "PAL" : "NTSC");
1806     }
1807
1808     if (norm == UNKNOWN) {
1809         av_log(NULL, AV_LOG_FATAL, "Could not determine norm (PAL/NTSC/NTSC-Film) for target.\n");
1810         av_log(NULL, AV_LOG_FATAL, "Please prefix target with \"pal-\", \"ntsc-\" or \"film-\",\n");
1811         av_log(NULL, AV_LOG_FATAL, "or set a framerate with \"-r xxx\".\n");
1812         exit_program(1);
1813     }
1814
1815     if (!strcmp(arg, "vcd")) {
1816         opt_video_codec(o, "c:v", "mpeg1video");
1817         opt_audio_codec(o, "c:a", "mp2");
1818         parse_option(o, "f", "vcd", options);
1819
1820         parse_option(o, "s", norm == PAL ? "352x288" : "352x240", options);
1821         parse_option(o, "r", frame_rates[norm], options);
1822         opt_default("g", norm == PAL ? "15" : "18");
1823
1824         opt_default("b:v", "1150000");
1825         opt_default("maxrate", "1150000");
1826         opt_default("minrate", "1150000");
1827         opt_default("bufsize", "327680"); // 40*1024*8;
1828
1829         opt_default("b:a", "224000");
1830         parse_option(o, "ar", "44100", options);
1831         parse_option(o, "ac", "2", options);
1832
1833         opt_default("packetsize", "2324");
1834         opt_default("muxrate", "1411200"); // 2352 * 75 * 8;
1835
1836         /* We have to offset the PTS, so that it is consistent with the SCR.
1837            SCR starts at 36000, but the first two packs contain only padding
1838            and the first pack from the other stream, respectively, may also have
1839            been written before.
1840            So the real data starts at SCR 36000+3*1200. */
1841         o->mux_preload = (36000 + 3 * 1200) / 90000.0; // 0.44
1842     } else if (!strcmp(arg, "svcd")) {
1843
1844         opt_video_codec(o, "c:v", "mpeg2video");
1845         opt_audio_codec(o, "c:a", "mp2");
1846         parse_option(o, "f", "svcd", options);
1847
1848         parse_option(o, "s", norm == PAL ? "480x576" : "480x480", options);
1849         parse_option(o, "r", frame_rates[norm], options);
1850         parse_option(o, "pix_fmt", "yuv420p", options);
1851         opt_default("g", norm == PAL ? "15" : "18");
1852
1853         opt_default("b:v", "2040000");
1854         opt_default("maxrate", "2516000");
1855         opt_default("minrate", "0"); // 1145000;
1856         opt_default("bufsize", "1835008"); // 224*1024*8;
1857         opt_default("scan_offset", "1");
1858
1859
1860         opt_default("b:a", "224000");
1861         parse_option(o, "ar", "44100", options);
1862
1863         opt_default("packetsize", "2324");
1864
1865     } else if (!strcmp(arg, "dvd")) {
1866
1867         opt_video_codec(o, "c:v", "mpeg2video");
1868         opt_audio_codec(o, "c:a", "ac3");
1869         parse_option(o, "f", "dvd", options);
1870
1871         parse_option(o, "s", norm == PAL ? "720x576" : "720x480", options);
1872         parse_option(o, "r", frame_rates[norm], options);
1873         parse_option(o, "pix_fmt", "yuv420p", options);
1874         opt_default("g", norm == PAL ? "15" : "18");
1875
1876         opt_default("b:v", "6000000");
1877         opt_default("maxrate", "9000000");
1878         opt_default("minrate", "0"); // 1500000;
1879         opt_default("bufsize", "1835008"); // 224*1024*8;
1880
1881         opt_default("packetsize", "2048");  // from www.mpucoder.com: DVD sectors contain 2048 bytes of data, this is also the size of one pack.
1882         opt_default("muxrate", "10080000"); // from mplex project: data_rate = 1260000. mux_rate = data_rate * 8
1883
1884         opt_default("b:a", "448000");
1885         parse_option(o, "ar", "48000", options);
1886
1887     } else if (!strncmp(arg, "dv", 2)) {
1888
1889         parse_option(o, "f", "dv", options);
1890
1891         parse_option(o, "s", norm == PAL ? "720x576" : "720x480", options);
1892         parse_option(o, "pix_fmt", !strncmp(arg, "dv50", 4) ? "yuv422p" :
1893                           norm == PAL ? "yuv420p" : "yuv411p", options);
1894         parse_option(o, "r", frame_rates[norm], options);
1895
1896         parse_option(o, "ar", "48000", options);
1897         parse_option(o, "ac", "2", options);
1898
1899     } else {
1900         av_log(NULL, AV_LOG_ERROR, "Unknown target: %s\n", arg);
1901         return AVERROR(EINVAL);
1902     }
1903     return 0;
1904 }
1905
1906 static int opt_vstats_file(const char *opt, const char *arg)
1907 {
1908     av_free (vstats_filename);
1909     vstats_filename = av_strdup (arg);
1910     return 0;
1911 }
1912
1913 static int opt_vstats(const char *opt, const char *arg)
1914 {
1915     char filename[40];
1916     time_t today2 = time(NULL);
1917     struct tm *today = localtime(&today2);
1918
1919     snprintf(filename, sizeof(filename), "vstats_%02d%02d%02d.log", today->tm_hour, today->tm_min,
1920              today->tm_sec);
1921     return opt_vstats_file(opt, filename);
1922 }
1923
1924 static int opt_video_frames(void *optctx, const char *opt, const char *arg)
1925 {
1926     OptionsContext *o = optctx;
1927     return parse_option(o, "frames:v", arg, options);
1928 }
1929
1930 static int opt_audio_frames(void *optctx, const char *opt, const char *arg)
1931 {
1932     OptionsContext *o = optctx;
1933     return parse_option(o, "frames:a", arg, options);
1934 }
1935
1936 static int opt_data_frames(void *optctx, const char *opt, const char *arg)
1937 {
1938     OptionsContext *o = optctx;
1939     return parse_option(o, "frames:d", arg, options);
1940 }
1941
1942 static int opt_preset(void *optctx, const char *opt, const char *arg)
1943 {
1944     OptionsContext *o = optctx;
1945     FILE *f=NULL;
1946     char filename[1000], line[1000], tmp_line[1000];
1947     const char *codec_name = *opt == 'v' ? video_codec_name :
1948                              *opt == 'a' ? audio_codec_name :
1949                                            subtitle_codec_name;
1950
1951     if (!(f = get_preset_file(filename, sizeof(filename), arg, *opt == 'f', codec_name))) {
1952         if(!strncmp(arg, "libx264-lossless", strlen("libx264-lossless"))){
1953             av_log(NULL, AV_LOG_FATAL, "Please use -preset <speed> -qp 0\n");
1954         }else
1955             av_log(NULL, AV_LOG_FATAL, "File for preset '%s' not found\n", arg);
1956         exit_program(1);
1957 }
1958
1959     while (fgets(line, sizeof(line), f)) {
1960         char *key = tmp_line, *value, *endptr;
1961
1962         if (strcspn(line, "#\n\r") == 0)
1963             continue;
1964         strcpy(tmp_line, line);
1965         if (!av_strtok(key,   "=",    &value) ||
1966             !av_strtok(value, "\r\n", &endptr)) {
1967             av_log(NULL, AV_LOG_FATAL, "%s: Invalid syntax: '%s'\n", filename, line);
1968             exit_program(1);
1969         }
1970         av_log(NULL, AV_LOG_DEBUG, "ffpreset[%s]: set '%s' = '%s'\n", filename, key, value);
1971
1972         if      (!strcmp(key, "acodec")) opt_audio_codec   (o, key, value);
1973         else if (!strcmp(key, "vcodec")) opt_video_codec   (o, key, value);
1974         else if (!strcmp(key, "scodec")) opt_subtitle_codec(o, key, value);
1975         else if (!strcmp(key, "dcodec")) opt_data_codec    (o, key, value);
1976         else if (opt_default(key, value) < 0) {
1977             av_log(NULL, AV_LOG_FATAL, "%s: Invalid option or argument: '%s', parsed as '%s' = '%s'\n",
1978                    filename, line, key, value);
1979             exit_program(1);
1980         }
1981     }
1982
1983     fclose(f);
1984
1985     return 0;
1986 }
1987
1988 static int opt_passlogfile(const char *opt, const char *arg)
1989 {
1990     pass_logfilename_prefix = arg;
1991 #if CONFIG_LIBX264_ENCODER
1992     return opt_default(opt, arg);
1993 #else
1994     return 0;
1995 #endif
1996 }
1997
1998 static int opt_old2new(void *optctx, const char *opt, const char *arg)
1999 {
2000     OptionsContext *o = optctx;
2001     char *s = av_asprintf("%s:%c", opt + 1, *opt);
2002     int ret = parse_option(o, s, arg, options);
2003     av_free(s);
2004     return ret;
2005 }
2006
2007 static int opt_bitrate(void *optctx, const char *opt, const char *arg)
2008 {
2009     OptionsContext *o = optctx;
2010     if(!strcmp(opt, "b")){
2011         av_log(NULL, AV_LOG_WARNING, "Please use -b:a or -b:v, -b is ambiguous\n");
2012         return parse_option(o, "b:v", arg, options);
2013     }
2014     return opt_default(opt, arg);
2015 }
2016
2017 static int opt_qscale(void *optctx, const char *opt, const char *arg)
2018 {
2019     OptionsContext *o = optctx;
2020     char *s;
2021     int ret;
2022     if(!strcmp(opt, "qscale")){
2023         av_log(NULL, AV_LOG_WARNING, "Please use -q:a or -q:v, -qscale is ambiguous\n");
2024         return parse_option(o, "q:v", arg, options);
2025     }
2026     s = av_asprintf("q%s", opt + 6);
2027     ret = parse_option(o, s, arg, options);
2028     av_free(s);
2029     return ret;
2030 }
2031
2032 static int opt_profile(void *optctx, const char *opt, const char *arg)
2033 {
2034     OptionsContext *o = optctx;
2035     if(!strcmp(opt, "profile")){
2036         av_log(NULL, AV_LOG_WARNING, "Please use -profile:a or -profile:v, -profile is ambiguous\n");
2037         return parse_option(o, "profile:v", arg, options);
2038     }
2039     return opt_default(opt, arg);
2040
2041 }
2042
2043 static int opt_video_filters(void *optctx, const char *opt, const char *arg)
2044 {
2045     OptionsContext *o = optctx;
2046     return parse_option(o, "filter:v", arg, options);
2047 }
2048
2049 static int opt_audio_filters(void *optctx, const char *opt, const char *arg)
2050 {
2051     OptionsContext *o = optctx;
2052     return parse_option(o, "filter:a", arg, options);
2053 }
2054
2055 static int opt_vsync(const char *opt, const char *arg)
2056 {
2057     if      (!av_strcasecmp(arg, "cfr"))         video_sync_method = VSYNC_CFR;
2058     else if (!av_strcasecmp(arg, "vfr"))         video_sync_method = VSYNC_VFR;
2059     else if (!av_strcasecmp(arg, "passthrough")) video_sync_method = VSYNC_PASSTHROUGH;
2060     else if (!av_strcasecmp(arg, "drop"))        video_sync_method = VSYNC_DROP;
2061
2062     if (video_sync_method == VSYNC_AUTO)
2063         video_sync_method = parse_number_or_die("vsync", arg, OPT_INT, VSYNC_AUTO, VSYNC_VFR);
2064     return 0;
2065 }
2066
2067 static int opt_deinterlace(const char *opt, const char *arg)
2068 {
2069     av_log(NULL, AV_LOG_WARNING, "-%s is deprecated, use -filter:v yadif instead\n", opt);
2070     do_deinterlace = 1;
2071     return 0;
2072 }
2073
2074 static int opt_timecode(void *optctx, const char *opt, const char *arg)
2075 {
2076     OptionsContext *o = optctx;
2077     char *tcr = av_asprintf("timecode=%s", arg);
2078     int ret = parse_option(o, "metadata:g", tcr, options);
2079     if (ret >= 0)
2080         ret = opt_default("gop_timecode", arg);
2081     av_free(tcr);
2082     return ret;
2083 }
2084
2085 static int opt_channel_layout(void *optctx, const char *opt, const char *arg)
2086 {
2087     OptionsContext *o = optctx;
2088     char layout_str[32];
2089     char *stream_str;
2090     char *ac_str;
2091     int ret, channels, ac_str_size;
2092     uint64_t layout;
2093
2094     layout = av_get_channel_layout(arg);
2095     if (!layout) {
2096         av_log(NULL, AV_LOG_ERROR, "Unknown channel layout: %s\n", arg);
2097         return AVERROR(EINVAL);
2098     }
2099     snprintf(layout_str, sizeof(layout_str), "%"PRIu64, layout);
2100     ret = opt_default(opt, layout_str);
2101     if (ret < 0)
2102         return ret;
2103
2104     /* set 'ac' option based on channel layout */
2105     channels = av_get_channel_layout_nb_channels(layout);
2106     snprintf(layout_str, sizeof(layout_str), "%d", channels);
2107     stream_str = strchr(opt, ':');
2108     ac_str_size = 3 + (stream_str ? strlen(stream_str) : 0);
2109     ac_str = av_mallocz(ac_str_size);
2110     if (!ac_str)
2111         return AVERROR(ENOMEM);
2112     av_strlcpy(ac_str, "ac", 3);
2113     if (stream_str)
2114         av_strlcat(ac_str, stream_str, ac_str_size);
2115     ret = parse_option(o, ac_str, layout_str, options);
2116     av_free(ac_str);
2117
2118     return ret;
2119 }
2120
2121 static int opt_audio_qscale(void *optctx, const char *opt, const char *arg)
2122 {
2123     OptionsContext *o = optctx;
2124     return parse_option(o, "q:a", arg, options);
2125 }
2126
2127 static int opt_filter_complex(const char *opt, const char *arg)
2128 {
2129     filtergraphs = grow_array(filtergraphs, sizeof(*filtergraphs),
2130                               &nb_filtergraphs, nb_filtergraphs + 1);
2131     if (!(filtergraphs[nb_filtergraphs - 1] = av_mallocz(sizeof(*filtergraphs[0]))))
2132         return AVERROR(ENOMEM);
2133     filtergraphs[nb_filtergraphs - 1]->index       = nb_filtergraphs - 1;
2134     filtergraphs[nb_filtergraphs - 1]->graph_desc = arg;
2135     return 0;
2136 }
2137
2138 void show_help_default(const char *opt, const char *arg)
2139 {
2140     /* per-file options have at least one of those set */
2141     const int per_file = OPT_SPEC | OPT_OFFSET | OPT_FUNC2;
2142     int show_advanced = 0, show_avoptions = 0;
2143
2144     if (opt) {
2145         if (!strcmp(opt, "long"))
2146             show_advanced = 1;
2147         else if (!strcmp(opt, "full"))
2148             show_advanced = show_avoptions = 1;
2149         else
2150             av_log(NULL, AV_LOG_ERROR, "Unknown help option '%s'.\n", opt);
2151     }
2152
2153     show_usage();
2154
2155     printf("Getting help:\n"
2156            "    -h      -- print basic options\n"
2157            "    -h long -- print more options\n"
2158            "    -h full -- print all options (including all format and codec specific options, very long)\n"
2159            "    See man %s for detailed description of the options.\n"
2160            "\n", program_name);
2161
2162     show_help_options(options, "Print help / information / capabilities:",
2163                       OPT_EXIT, 0, 0);
2164
2165     show_help_options(options, "Global options (affect whole program "
2166                       "instead of just one file:",
2167                       0, per_file | OPT_EXIT | OPT_EXPERT, 0);
2168     if (show_advanced)
2169         show_help_options(options, "Advanced global options:", OPT_EXPERT,
2170                           per_file | OPT_EXIT, 0);
2171
2172     show_help_options(options, "Per-file main options:", 0,
2173                       OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_SUBTITLE |
2174                       OPT_EXIT, per_file);
2175     if (show_advanced)
2176         show_help_options(options, "Advanced per-file options:",
2177                           OPT_EXPERT, OPT_AUDIO | OPT_VIDEO | OPT_SUBTITLE, per_file);
2178
2179     show_help_options(options, "Video options:",
2180                       OPT_VIDEO, OPT_EXPERT | OPT_AUDIO, 0);
2181     if (show_advanced)
2182         show_help_options(options, "Advanced Video options:",
2183                           OPT_EXPERT | OPT_VIDEO, OPT_AUDIO, 0);
2184
2185     show_help_options(options, "Audio options:",
2186                       OPT_AUDIO, OPT_EXPERT | OPT_VIDEO, 0);
2187     if (show_advanced)
2188         show_help_options(options, "Advanced Audio options:",
2189                           OPT_EXPERT | OPT_AUDIO, OPT_VIDEO, 0);
2190     show_help_options(options, "Subtitle options:",
2191                       OPT_SUBTITLE, 0, 0);
2192     printf("\n");
2193
2194     if (show_avoptions) {
2195         int flags = AV_OPT_FLAG_DECODING_PARAM | AV_OPT_FLAG_ENCODING_PARAM;
2196         show_help_children(avcodec_get_class(), flags);
2197         show_help_children(avformat_get_class(), flags);
2198         show_help_children(sws_get_class(), flags);
2199         show_help_children(swr_get_class(), AV_OPT_FLAG_AUDIO_PARAM);
2200         show_help_children(avfilter_get_class(), AV_OPT_FLAG_FILTERING_PARAM);
2201     }
2202 }
2203
2204 void show_usage(void)
2205 {
2206     av_log(NULL, AV_LOG_INFO, "Hyper fast Audio and Video encoder\n");
2207     av_log(NULL, AV_LOG_INFO, "usage: %s [options] [[infile options] -i infile]... {[outfile options] outfile}...\n", program_name);
2208     av_log(NULL, AV_LOG_INFO, "\n");
2209 }
2210
2211
2212 static int opt_progress(const char *opt, const char *arg)
2213 {
2214     AVIOContext *avio = NULL;
2215     int ret;
2216
2217     if (!strcmp(arg, "-"))
2218         arg = "pipe:";
2219     ret = avio_open2(&avio, arg, AVIO_FLAG_WRITE, &int_cb, NULL);
2220     if (ret < 0) {
2221         av_log(0, AV_LOG_ERROR, "Failed to open progress URL \"%s\": %s\n",
2222                arg, av_err2str(ret));
2223         return ret;
2224     }
2225     progress_avio = avio;
2226     return 0;
2227 }
2228
2229 #define OFFSET(x) offsetof(OptionsContext, x)
2230 const OptionDef options[] = {
2231     /* main options */
2232 #include "cmdutils_common_opts.h"
2233     { "f",              HAS_ARG | OPT_STRING | OPT_OFFSET,           { .off       = OFFSET(format) },
2234         "force format", "fmt" },
2235     { "i",              HAS_ARG | OPT_FUNC2,                         { .func2_arg = opt_input_file },
2236         "input file name", "filename" },
2237     { "y",              OPT_BOOL,                                    {              &file_overwrite },
2238         "overwrite output files" },
2239     { "n",              OPT_BOOL,                                    {              &no_file_overwrite },
2240         "do not overwrite output files" },
2241     { "c",              HAS_ARG | OPT_STRING | OPT_SPEC,             { .off       = OFFSET(codec_names) },
2242         "codec name", "codec" },
2243     { "codec",          HAS_ARG | OPT_STRING | OPT_SPEC,             { .off       = OFFSET(codec_names) },
2244         "codec name", "codec" },
2245     { "pre",            HAS_ARG | OPT_STRING | OPT_SPEC,             { .off       = OFFSET(presets) },
2246         "preset name", "preset" },
2247     { "map",            HAS_ARG | OPT_EXPERT | OPT_FUNC2,            { .func2_arg = opt_map },
2248         "set input stream mapping",
2249         "[-]input_file_id[:stream_specifier][,sync_file_id[:stream_specifier]]" },
2250     { "map_channel",    HAS_ARG | OPT_EXPERT | OPT_FUNC2,            { .func2_arg = opt_map_channel },
2251         "map an audio channel from one stream to another", "file.stream.channel[:syncfile.syncstream]" },
2252     { "map_metadata",   HAS_ARG | OPT_STRING | OPT_SPEC,             { .off       = OFFSET(metadata_map) },
2253         "set metadata information of outfile from infile",
2254         "outfile[,metadata]:infile[,metadata]" },
2255     { "map_chapters",   HAS_ARG | OPT_INT | OPT_EXPERT | OPT_OFFSET, { .off = OFFSET(chapters_input_file) },
2256         "set chapters mapping", "input_file_index" },
2257     { "t",              HAS_ARG | OPT_TIME | OPT_OFFSET,             { .off = OFFSET(recording_time) },
2258         "record or transcode \"duration\" seconds of audio/video",
2259         "duration" },
2260     { "fs",             HAS_ARG | OPT_INT64 | OPT_OFFSET,            { .off = OFFSET(limit_filesize) },
2261         "set the limit file size in bytes", "limit_size" },
2262     { "ss",             HAS_ARG | OPT_TIME | OPT_OFFSET,             { .off = OFFSET(start_time) },
2263         "set the start time offset", "time_off" },
2264     { "itsoffset",      HAS_ARG | OPT_TIME | OPT_OFFSET | OPT_EXPERT,{ .off = OFFSET(input_ts_offset) },
2265         "set the input ts offset", "time_off" },
2266     { "itsscale",       HAS_ARG | OPT_DOUBLE | OPT_SPEC | OPT_EXPERT,{ .off = OFFSET(ts_scale) },
2267         "set the input ts scale", "scale" },
2268     { "timestamp",      HAS_ARG | OPT_FUNC2,                         { .func2_arg = opt_recording_timestamp },
2269         "set the recording timestamp ('now' to set the current time)", "time" },
2270     { "metadata",       HAS_ARG | OPT_STRING | OPT_SPEC,             { .off = OFFSET(metadata) },
2271         "add metadata", "string=string" },
2272     { "dframes",        HAS_ARG | OPT_FUNC2 | OPT_EXPERT,            { .func2_arg = opt_data_frames },
2273         "set the number of data frames to record", "number" },
2274     { "benchmark",      OPT_BOOL | OPT_EXPERT,                       { &do_benchmark },
2275         "add timings for benchmarking" },
2276     { "benchmark_all",  OPT_BOOL | OPT_EXPERT,                       { &do_benchmark_all },
2277       "add timings for each task" },
2278     { "progress",       HAS_ARG | OPT_EXPERT,                        { .func_arg = opt_progress },
2279       "write program-readable progress information", "url" },
2280     { "stdin",          OPT_BOOL | OPT_EXPERT,                       { &stdin_interaction },
2281       "enable or disable interaction on standard input" },
2282     { "timelimit",      HAS_ARG | OPT_EXPERT,                        { .func_arg = opt_timelimit },
2283         "set max runtime in seconds", "limit" },
2284     { "dump",           OPT_BOOL | OPT_EXPERT,                       { &do_pkt_dump },
2285         "dump each input packet" },
2286     { "hex",            OPT_BOOL | OPT_EXPERT,                       { &do_hex_dump },
2287         "when dumping packets, also dump the payload" },
2288     { "re",             OPT_BOOL | OPT_EXPERT | OPT_OFFSET,          { .off = OFFSET(rate_emu) },
2289         "read input at native frame rate", "" },
2290     { "target",         HAS_ARG | OPT_FUNC2,                         { .func2_arg = opt_target },
2291         "specify target file type (\"vcd\", \"svcd\", \"dvd\","
2292         " \"dv\", \"dv50\", \"pal-vcd\", \"ntsc-svcd\", ...)", "type" },
2293     { "vsync",          HAS_ARG | OPT_EXPERT,                        { opt_vsync },
2294         "video sync method", "" },
2295     { "async",          HAS_ARG | OPT_INT | OPT_EXPERT,              { &audio_sync_method },
2296         "audio sync method", "" },
2297     { "adrift_threshold", HAS_ARG | OPT_FLOAT | OPT_EXPERT,          { &audio_drift_threshold },
2298         "audio drift threshold", "threshold" },
2299     { "copyts",         OPT_BOOL | OPT_EXPERT,                       { &copy_ts },
2300         "copy timestamps" },
2301     { "copytb",         HAS_ARG | OPT_INT | OPT_EXPERT,              { &copy_tb },
2302         "copy input stream time base when stream copying", "mode" },
2303     { "shortest",       OPT_BOOL | OPT_EXPERT | OPT_OFFSET,          { .off = OFFSET(shortest) },
2304         "finish encoding within shortest input" },
2305     { "dts_delta_threshold", HAS_ARG | OPT_FLOAT | OPT_EXPERT,       { &dts_delta_threshold },
2306         "timestamp discontinuity delta threshold", "threshold" },
2307     { "dts_error_threshold", HAS_ARG | OPT_FLOAT | OPT_EXPERT,       { &dts_error_threshold },
2308         "timestamp error delta threshold", "threshold" },
2309     { "xerror",         OPT_BOOL | OPT_EXPERT,                       { &exit_on_error },
2310         "exit on error", "error" },
2311     { "copyinkf",       OPT_BOOL | OPT_EXPERT | OPT_SPEC,            { .off = OFFSET(copy_initial_nonkeyframes) },
2312         "copy initial non-keyframes" },
2313     { "frames",         OPT_INT64 | HAS_ARG | OPT_SPEC,              { .off = OFFSET(max_frames) },
2314         "set the number of frames to record", "number" },
2315     { "tag",            OPT_STRING | HAS_ARG | OPT_SPEC | OPT_EXPERT,{ .off = OFFSET(codec_tags) },
2316         "force codec tag/fourcc", "fourcc/tag" },
2317     { "q",              HAS_ARG | OPT_EXPERT | OPT_DOUBLE | OPT_SPEC,{ .off = OFFSET(qscale) },
2318         "use fixed quality scale (VBR)", "q" },
2319     { "qscale",         HAS_ARG | OPT_EXPERT | OPT_FUNC2,            { .func2_arg = opt_qscale },
2320         "use fixed quality scale (VBR)", "q" },
2321     { "profile",        HAS_ARG | OPT_EXPERT | OPT_FUNC2,            { .func2_arg = opt_profile },
2322         "set profile", "profile" },
2323     { "filter",         HAS_ARG | OPT_STRING | OPT_SPEC,             { .off = OFFSET(filters) },
2324         "set stream filterchain", "filter_list" },
2325     { "filter_complex", HAS_ARG | OPT_EXPERT,                        { .func_arg = opt_filter_complex },
2326         "create a complex filtergraph", "graph_description" },
2327     { "stats",          OPT_BOOL,                                    { &print_stats },
2328         "print progress report during encoding", },
2329     { "attach",         HAS_ARG | OPT_FUNC2 | OPT_EXPERT,            { .func2_arg = opt_attach },
2330         "add an attachment to the output file", "filename" },
2331     { "dump_attachment", HAS_ARG | OPT_STRING | OPT_SPEC |OPT_EXPERT,{ .off = OFFSET(dump_attachment) },
2332         "extract an attachment into a file", "filename" },
2333     { "debug_ts",       OPT_BOOL | OPT_EXPERT,                       { &debug_ts },
2334         "print timestamp debugging info" },
2335
2336     /* video options */
2337     { "vframes",      OPT_VIDEO | HAS_ARG  | OPT_FUNC2,                          { .func2_arg = opt_video_frames },
2338         "set the number of video frames to record", "number" },
2339     { "r",            OPT_VIDEO | HAS_ARG  | OPT_STRING | OPT_SPEC,              { .off = OFFSET(frame_rates) },
2340         "set frame rate (Hz value, fraction or abbreviation)", "rate" },
2341     { "s",            OPT_VIDEO | HAS_ARG | OPT_SUBTITLE | OPT_STRING | OPT_SPEC,{ .off = OFFSET(frame_sizes) },
2342         "set frame size (WxH or abbreviation)", "size" },
2343     { "aspect",       OPT_VIDEO | HAS_ARG  | OPT_STRING | OPT_SPEC,              { .off = OFFSET(frame_aspect_ratios) },
2344         "set aspect ratio (4:3, 16:9 or 1.3333, 1.7777)", "aspect" },
2345     { "pix_fmt",      OPT_VIDEO | HAS_ARG | OPT_EXPERT  | OPT_STRING | OPT_SPEC, { .off = OFFSET(frame_pix_fmts) },
2346         "set pixel format", "format" },
2347     { "bits_per_raw_sample", OPT_VIDEO | OPT_INT | HAS_ARG,                      { &frame_bits_per_raw_sample },
2348         "set the number of bits per raw sample", "number" },
2349     { "croptop",      OPT_VIDEO | HAS_ARG,                                       { .func_arg = opt_frame_crop },
2350         "Removed, use the crop filter instead", "size" },
2351     { "cropbottom",   OPT_VIDEO | HAS_ARG,                                       { .func_arg = opt_frame_crop },
2352         "Removed, use the crop filter instead", "size" },
2353     { "cropleft",     OPT_VIDEO | HAS_ARG,                                       { .func_arg = opt_frame_crop },
2354         "Removed, use the crop filter instead", "size" },
2355     { "cropright",    OPT_VIDEO | HAS_ARG,                                       { .func_arg = opt_frame_crop },
2356         "Removed, use the crop filter instead", "size" },
2357     { "padtop",       OPT_VIDEO | HAS_ARG,                                       { .func_arg = opt_pad },
2358         "Removed, use the pad filter instead", "size" },
2359     { "padbottom",    OPT_VIDEO | HAS_ARG,                                       { .func_arg = opt_pad },
2360         "Removed, use the pad filter instead", "size" },
2361     { "padleft",      OPT_VIDEO | HAS_ARG,                                       { .func_arg = opt_pad },
2362         "Removed, use the pad filter instead", "size" },
2363     { "padright",     OPT_VIDEO | HAS_ARG,                                       { .func_arg = opt_pad },
2364         "Removed, use the pad filter instead", "size" },
2365     { "padcolor",     OPT_VIDEO | HAS_ARG,                                       { .func_arg = opt_pad },
2366         "Removed, use the pad filter instead", "color" },
2367     { "intra",        OPT_VIDEO | OPT_BOOL | OPT_EXPERT,                         { &intra_only },
2368         "deprecated use -g 1" },
2369     { "vn",           OPT_VIDEO | OPT_BOOL  | OPT_OFFSET,                        { .off = OFFSET(video_disable) },
2370         "disable video" },
2371     { "vdt",          OPT_VIDEO | OPT_INT | HAS_ARG | OPT_EXPERT ,               { &video_discard },
2372         "discard threshold", "n" },
2373     { "rc_override",  OPT_VIDEO | HAS_ARG | OPT_EXPERT  | OPT_STRING | OPT_SPEC, { .off = OFFSET(rc_overrides) },
2374         "rate control override for specific intervals", "override" },
2375     { "vcodec",       OPT_VIDEO | HAS_ARG  | OPT_FUNC2,                          { .func2_arg = opt_video_codec },
2376         "force video codec ('copy' to copy stream)", "codec" },
2377     { "sameq",        OPT_VIDEO | OPT_BOOL | OPT_EXPERT ,                        { &same_quant },
2378         "use same quantizer as source (implies VBR)" },
2379     { "same_quant",   OPT_VIDEO | OPT_BOOL | OPT_EXPERT,                         { &same_quant },
2380         "use same quantizer as source (implies VBR)" },
2381     { "timecode",     OPT_VIDEO | HAS_ARG | OPT_FUNC2,                           { .func2_arg = opt_timecode },
2382         "set initial TimeCode value.", "hh:mm:ss[:;.]ff" },
2383     { "pass",         OPT_VIDEO | HAS_ARG ,                                      { opt_pass },
2384         "select the pass number (1 or 2)", "n" },
2385     { "passlogfile",  OPT_VIDEO | HAS_ARG,                                       { .func_arg = &opt_passlogfile },
2386         "select two pass log file name prefix", "prefix" },
2387     { "deinterlace",  OPT_VIDEO | OPT_EXPERT ,                                   { .func_arg = opt_deinterlace },
2388         "this option is deprecated, use the yadif filter instead" },
2389     { "psnr",         OPT_VIDEO | OPT_BOOL | OPT_EXPERT,                         { &do_psnr },
2390         "calculate PSNR of compressed frames" },
2391     { "vstats",       OPT_VIDEO | OPT_EXPERT ,                                   { &opt_vstats },
2392         "dump video coding statistics to file" },
2393     { "vstats_file",  OPT_VIDEO | HAS_ARG | OPT_EXPERT ,                         { opt_vstats_file },
2394         "dump video coding statistics to file", "file" },
2395     { "vf",           OPT_VIDEO | HAS_ARG  | OPT_FUNC2,                          { .func2_arg = opt_video_filters },
2396         "video filters", "filter list" },
2397     { "intra_matrix", OPT_VIDEO | HAS_ARG | OPT_EXPERT  | OPT_STRING | OPT_SPEC, { .off = OFFSET(intra_matrices) },
2398         "specify intra matrix coeffs", "matrix" },
2399     { "inter_matrix", OPT_VIDEO | HAS_ARG | OPT_EXPERT  | OPT_STRING | OPT_SPEC, { .off = OFFSET(inter_matrices) },
2400         "specify inter matrix coeffs", "matrix" },
2401     { "top",          OPT_VIDEO | HAS_ARG | OPT_EXPERT  | OPT_INT| OPT_SPEC,     { .off = OFFSET(top_field_first) },
2402         "top=1/bottom=0/auto=-1 field first", "" },
2403     { "dc",           OPT_VIDEO | OPT_INT | HAS_ARG | OPT_EXPERT ,               { &intra_dc_precision },
2404         "intra_dc_precision", "precision" },
2405     { "vtag",         OPT_VIDEO | HAS_ARG | OPT_EXPERT  | OPT_FUNC2,             { .func2_arg = opt_old2new },
2406         "force video tag/fourcc", "fourcc/tag" },
2407     { "qphist",       OPT_VIDEO | OPT_BOOL | OPT_EXPERT ,                        { &qp_hist },
2408         "show QP histogram" },
2409     { "force_fps",    OPT_VIDEO | OPT_BOOL | OPT_EXPERT  | OPT_SPEC,             { .off = OFFSET(force_fps) },
2410         "force the selected framerate, disable the best supported framerate selection" },
2411     { "streamid",     OPT_VIDEO | HAS_ARG | OPT_EXPERT | OPT_FUNC2,              { .func2_arg = opt_streamid },
2412         "set the value of an outfile streamid", "streamIndex:value" },
2413     { "force_key_frames", OPT_VIDEO | OPT_STRING | HAS_ARG | OPT_EXPERT  | OPT_SPEC,
2414         { .off = OFFSET(forced_key_frames) },
2415         "force key frames at specified timestamps", "timestamps" },
2416     { "b",            OPT_VIDEO | HAS_ARG | OPT_FUNC2,                           { .func2_arg = opt_bitrate },
2417         "video bitrate (please use -b:v)", "bitrate" },
2418
2419     /* audio options */
2420     { "aframes",        OPT_AUDIO | HAS_ARG  | OPT_FUNC2,                          { .func2_arg = opt_audio_frames },
2421         "set the number of audio frames to record", "number" },
2422     { "aq",             OPT_AUDIO | HAS_ARG  | OPT_FUNC2,                          { .func2_arg = opt_audio_qscale },
2423         "set audio quality (codec-specific)", "quality", },
2424     { "ar",             OPT_AUDIO | HAS_ARG  | OPT_INT | OPT_SPEC,                 { .off = OFFSET(audio_sample_rate) },
2425         "set audio sampling rate (in Hz)", "rate" },
2426     { "ac",             OPT_AUDIO | HAS_ARG  | OPT_INT | OPT_SPEC,                 { .off = OFFSET(audio_channels) },
2427         "set number of audio channels", "channels" },
2428     { "an",             OPT_AUDIO | OPT_BOOL | OPT_OFFSET,                         { .off = OFFSET(audio_disable) },
2429         "disable audio" },
2430     { "acodec",         OPT_AUDIO | HAS_ARG  | OPT_FUNC2,                          { .func2_arg = opt_audio_codec },
2431         "force audio codec ('copy' to copy stream)", "codec" },
2432     { "atag",           OPT_AUDIO | HAS_ARG  | OPT_EXPERT | OPT_FUNC2,             { .func2_arg = opt_old2new },
2433         "force audio tag/fourcc", "fourcc/tag" },
2434     { "vol",            OPT_AUDIO | HAS_ARG  | OPT_INT,                            { &audio_volume },
2435         "change audio volume (256=normal)" , "volume" },
2436     { "sample_fmt",     OPT_AUDIO | HAS_ARG  | OPT_EXPERT | OPT_SPEC | OPT_STRING, { .off = OFFSET(sample_fmts) },
2437         "set sample format", "format" },
2438     { "channel_layout", OPT_AUDIO | HAS_ARG  | OPT_EXPERT | OPT_FUNC2,             { .func2_arg = opt_channel_layout },
2439         "set channel layout", "layout" },
2440     { "af",             OPT_AUDIO | HAS_ARG  | OPT_FUNC2,                          { .func2_arg = opt_audio_filters },
2441         "audio filters", "filter list" },
2442
2443     /* subtitle options */
2444     { "sn",     OPT_SUBTITLE | OPT_BOOL | OPT_OFFSET, { .off = OFFSET(subtitle_disable) },
2445         "disable subtitle" },
2446     { "scodec", OPT_SUBTITLE | HAS_ARG  | OPT_FUNC2,  { .func2_arg = opt_subtitle_codec },
2447         "force subtitle codec ('copy' to copy stream)", "codec" },
2448     { "stag", HAS_ARG | OPT_EXPERT | OPT_SUBTITLE | OPT_FUNC2, { .func2_arg = opt_old2new },
2449         "force subtitle tag/fourcc", "fourcc/tag" },
2450     { "fix_sub_duration", OPT_BOOL | OPT_EXPERT | OPT_SUBTITLE | OPT_SPEC, { .off = OFFSET(fix_sub_duration) },
2451         "fix subtitles duration" },
2452
2453     /* grab options */
2454     { "vc", HAS_ARG | OPT_EXPERT | OPT_VIDEO, { .func_arg = opt_video_channel },
2455         "deprecated, use -channel", "channel" },
2456     { "tvstd", HAS_ARG | OPT_EXPERT | OPT_VIDEO, { .func_arg = opt_video_standard },
2457         "deprecated, use -standard", "standard" },
2458     { "isync", OPT_BOOL | OPT_EXPERT, { &input_sync }, "this option is deprecated and does nothing", "" },
2459
2460     /* muxer options */
2461     { "muxdelay",   OPT_FLOAT | HAS_ARG | OPT_EXPERT | OPT_OFFSET, { .off = OFFSET(mux_max_delay) },
2462         "set the maximum demux-decode delay", "seconds" },
2463     { "muxpreload", OPT_FLOAT | HAS_ARG | OPT_EXPERT | OPT_OFFSET, { .off = OFFSET(mux_preload) },
2464         "set the initial demux-decode delay", "seconds" },
2465
2466     { "bsf", HAS_ARG | OPT_STRING | OPT_SPEC | OPT_EXPERT, { .off = OFFSET(bitstream_filters) },
2467         "A comma-separated list of bitstream filters", "bitstream_filters" },
2468     { "absf", HAS_ARG | OPT_AUDIO | OPT_EXPERT| OPT_FUNC2, { .func2_arg = opt_old2new },
2469         "deprecated", "audio bitstream_filters" },
2470     { "vbsf", OPT_VIDEO | HAS_ARG | OPT_EXPERT| OPT_FUNC2, { .func2_arg = opt_old2new },
2471         "deprecated", "video bitstream_filters" },
2472
2473     { "apre", HAS_ARG | OPT_AUDIO | OPT_EXPERT| OPT_FUNC2, { .func2_arg = opt_preset },
2474         "set the audio options to the indicated preset", "preset" },
2475     { "vpre", OPT_VIDEO | HAS_ARG | OPT_EXPERT| OPT_FUNC2, { .func2_arg = opt_preset },
2476         "set the video options to the indicated preset", "preset" },
2477     { "spre", HAS_ARG | OPT_SUBTITLE | OPT_EXPERT| OPT_FUNC2, { .func2_arg = opt_preset },
2478         "set the subtitle options to the indicated preset", "preset" },
2479     { "fpre", HAS_ARG | OPT_EXPERT| OPT_FUNC2, { .func2_arg = opt_preset },
2480         "set options from indicated preset file", "filename" },
2481     /* data codec support */
2482     { "dcodec", HAS_ARG | OPT_DATA | OPT_FUNC2 | OPT_EXPERT, { .func2_arg = opt_data_codec },
2483         "force data codec ('copy' to copy stream)", "codec" },
2484     { "dn", OPT_BOOL | OPT_VIDEO | OPT_OFFSET, { .off = OFFSET(data_disable) },
2485         "disable data" },
2486
2487     { "default", HAS_ARG | OPT_AUDIO | OPT_VIDEO | OPT_EXPERT, { .func_arg = opt_default },
2488         "generic catch all option", "" },
2489     { NULL, },
2490 };