]> git.sesse.net Git - ffmpeg/blob - ffmpeg_opt.c
ffmpeg_opt: add missing space in error message
[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
32 #include "libavutil/avassert.h"
33 #include "libavutil/avstring.h"
34 #include "libavutil/avutil.h"
35 #include "libavutil/channel_layout.h"
36 #include "libavutil/intreadwrite.h"
37 #include "libavutil/fifo.h"
38 #include "libavutil/mathematics.h"
39 #include "libavutil/opt.h"
40 #include "libavutil/parseutils.h"
41 #include "libavutil/pixdesc.h"
42 #include "libavutil/pixfmt.h"
43
44 #define MATCH_PER_STREAM_OPT(name, type, outvar, fmtctx, st)\
45 {\
46     int i, ret;\
47     for (i = 0; i < o->nb_ ## name; i++) {\
48         char *spec = o->name[i].specifier;\
49         if ((ret = check_stream_specifier(fmtctx, st, spec)) > 0)\
50             outvar = o->name[i].u.type;\
51         else if (ret < 0)\
52             exit_program(1);\
53     }\
54 }
55
56 #define MATCH_PER_TYPE_OPT(name, type, outvar, fmtctx, mediatype)\
57 {\
58     int i;\
59     for (i = 0; i < o->nb_ ## name; i++) {\
60         char *spec = o->name[i].specifier;\
61         if (!strcmp(spec, mediatype))\
62             outvar = o->name[i].u.type;\
63     }\
64 }
65
66 const HWAccel hwaccels[] = {
67 #if HAVE_VDPAU_X11
68     { "vdpau", vdpau_init, HWACCEL_VDPAU, AV_PIX_FMT_VDPAU },
69 #endif
70 #if HAVE_DXVA2_LIB
71     { "dxva2", dxva2_init, HWACCEL_DXVA2, AV_PIX_FMT_DXVA2_VLD },
72 #endif
73 #if CONFIG_VDA
74     { "vda",   vda_init,   HWACCEL_VDA,   AV_PIX_FMT_VDA },
75 #endif
76     { 0 },
77 };
78
79 char *vstats_filename;
80 char *sdp_filename;
81
82 float audio_drift_threshold = 0.1;
83 float dts_delta_threshold   = 10;
84 float dts_error_threshold   = 3600*30;
85
86 int audio_volume      = 256;
87 int audio_sync_method = 0;
88 int video_sync_method = VSYNC_AUTO;
89 float frame_drop_threshold = 0;
90 int do_deinterlace    = 0;
91 int do_benchmark      = 0;
92 int do_benchmark_all  = 0;
93 int do_hex_dump       = 0;
94 int do_pkt_dump       = 0;
95 int copy_ts           = 0;
96 int start_at_zero     = 0;
97 int copy_tb           = -1;
98 int debug_ts          = 0;
99 int exit_on_error     = 0;
100 int print_stats       = -1;
101 int qp_hist           = 0;
102 int stdin_interaction = 1;
103 int frame_bits_per_raw_sample = 0;
104 float max_error_rate  = 2.0/3;
105
106
107 static int intra_only         = 0;
108 static int file_overwrite     = 0;
109 static int no_file_overwrite  = 0;
110 static int do_psnr            = 0;
111 static int input_sync;
112 static int override_ffserver  = 0;
113 static int input_stream_potentially_available = 0;
114 static int ignore_unknown_streams = 0;
115
116 static void uninit_options(OptionsContext *o)
117 {
118     const OptionDef *po = options;
119     int i;
120
121     /* all OPT_SPEC and OPT_STRING can be freed in generic way */
122     while (po->name) {
123         void *dst = (uint8_t*)o + po->u.off;
124
125         if (po->flags & OPT_SPEC) {
126             SpecifierOpt **so = dst;
127             int i, *count = (int*)(so + 1);
128             for (i = 0; i < *count; i++) {
129                 av_freep(&(*so)[i].specifier);
130                 if (po->flags & OPT_STRING)
131                     av_freep(&(*so)[i].u.str);
132             }
133             av_freep(so);
134             *count = 0;
135         } else if (po->flags & OPT_OFFSET && po->flags & OPT_STRING)
136             av_freep(dst);
137         po++;
138     }
139
140     for (i = 0; i < o->nb_stream_maps; i++)
141         av_freep(&o->stream_maps[i].linklabel);
142     av_freep(&o->stream_maps);
143     av_freep(&o->audio_channel_maps);
144     av_freep(&o->streamid_map);
145     av_freep(&o->attachments);
146 }
147
148 static void init_options(OptionsContext *o)
149 {
150     memset(o, 0, sizeof(*o));
151
152     o->stop_time = INT64_MAX;
153     o->mux_max_delay  = 0.7;
154     o->start_time     = AV_NOPTS_VALUE;
155     o->recording_time = INT64_MAX;
156     o->limit_filesize = UINT64_MAX;
157     o->chapters_input_file = INT_MAX;
158     o->accurate_seek  = 1;
159 }
160
161 /* return a copy of the input with the stream specifiers removed from the keys */
162 static AVDictionary *strip_specifiers(AVDictionary *dict)
163 {
164     AVDictionaryEntry *e = NULL;
165     AVDictionary    *ret = NULL;
166
167     while ((e = av_dict_get(dict, "", e, AV_DICT_IGNORE_SUFFIX))) {
168         char *p = strchr(e->key, ':');
169
170         if (p)
171             *p = 0;
172         av_dict_set(&ret, e->key, e->value, 0);
173         if (p)
174             *p = ':';
175     }
176     return ret;
177 }
178
179 static int opt_sameq(void *optctx, const char *opt, const char *arg)
180 {
181     av_log(NULL, AV_LOG_ERROR, "Option '%s' was removed. "
182            "If you are looking for an option to preserve the quality (which is not "
183            "what -%s was for), use -qscale 0 or an equivalent quality factor option.\n",
184            opt, opt);
185     return AVERROR(EINVAL);
186 }
187
188 static int opt_video_channel(void *optctx, const char *opt, const char *arg)
189 {
190     av_log(NULL, AV_LOG_WARNING, "This option is deprecated, use -channel.\n");
191     return opt_default(optctx, "channel", arg);
192 }
193
194 static int opt_video_standard(void *optctx, const char *opt, const char *arg)
195 {
196     av_log(NULL, AV_LOG_WARNING, "This option is deprecated, use -standard.\n");
197     return opt_default(optctx, "standard", arg);
198 }
199
200 static int opt_audio_codec(void *optctx, const char *opt, const char *arg)
201 {
202     OptionsContext *o = optctx;
203     return parse_option(o, "codec:a", arg, options);
204 }
205
206 static int opt_video_codec(void *optctx, const char *opt, const char *arg)
207 {
208     OptionsContext *o = optctx;
209     return parse_option(o, "codec:v", arg, options);
210 }
211
212 static int opt_subtitle_codec(void *optctx, const char *opt, const char *arg)
213 {
214     OptionsContext *o = optctx;
215     return parse_option(o, "codec:s", arg, options);
216 }
217
218 static int opt_data_codec(void *optctx, const char *opt, const char *arg)
219 {
220     OptionsContext *o = optctx;
221     return parse_option(o, "codec:d", arg, options);
222 }
223
224 static int opt_map(void *optctx, const char *opt, const char *arg)
225 {
226     OptionsContext *o = optctx;
227     StreamMap *m = NULL;
228     int i, negative = 0, file_idx;
229     int sync_file_idx = -1, sync_stream_idx = 0;
230     char *p, *sync;
231     char *map;
232
233     if (*arg == '-') {
234         negative = 1;
235         arg++;
236     }
237     map = av_strdup(arg);
238     if (!map)
239         return AVERROR(ENOMEM);
240
241     /* parse sync stream first, just pick first matching stream */
242     if (sync = strchr(map, ',')) {
243         *sync = 0;
244         sync_file_idx = strtol(sync + 1, &sync, 0);
245         if (sync_file_idx >= nb_input_files || sync_file_idx < 0) {
246             av_log(NULL, AV_LOG_FATAL, "Invalid sync file index: %d.\n", sync_file_idx);
247             exit_program(1);
248         }
249         if (*sync)
250             sync++;
251         for (i = 0; i < input_files[sync_file_idx]->nb_streams; i++)
252             if (check_stream_specifier(input_files[sync_file_idx]->ctx,
253                                        input_files[sync_file_idx]->ctx->streams[i], sync) == 1) {
254                 sync_stream_idx = i;
255                 break;
256             }
257         if (i == input_files[sync_file_idx]->nb_streams) {
258             av_log(NULL, AV_LOG_FATAL, "Sync stream specification in map %s does not "
259                                        "match any streams.\n", arg);
260             exit_program(1);
261         }
262     }
263
264
265     if (map[0] == '[') {
266         /* this mapping refers to lavfi output */
267         const char *c = map + 1;
268         GROW_ARRAY(o->stream_maps, o->nb_stream_maps);
269         m = &o->stream_maps[o->nb_stream_maps - 1];
270         m->linklabel = av_get_token(&c, "]");
271         if (!m->linklabel) {
272             av_log(NULL, AV_LOG_ERROR, "Invalid output link label: %s.\n", map);
273             exit_program(1);
274         }
275     } else {
276         file_idx = strtol(map, &p, 0);
277         if (file_idx >= nb_input_files || file_idx < 0) {
278             av_log(NULL, AV_LOG_FATAL, "Invalid input file index: %d.\n", file_idx);
279             exit_program(1);
280         }
281         if (negative)
282             /* disable some already defined maps */
283             for (i = 0; i < o->nb_stream_maps; i++) {
284                 m = &o->stream_maps[i];
285                 if (file_idx == m->file_index &&
286                     check_stream_specifier(input_files[m->file_index]->ctx,
287                                            input_files[m->file_index]->ctx->streams[m->stream_index],
288                                            *p == ':' ? p + 1 : p) > 0)
289                     m->disabled = 1;
290             }
291         else
292             for (i = 0; i < input_files[file_idx]->nb_streams; i++) {
293                 if (check_stream_specifier(input_files[file_idx]->ctx, input_files[file_idx]->ctx->streams[i],
294                             *p == ':' ? p + 1 : p) <= 0)
295                     continue;
296                 GROW_ARRAY(o->stream_maps, o->nb_stream_maps);
297                 m = &o->stream_maps[o->nb_stream_maps - 1];
298
299                 m->file_index   = file_idx;
300                 m->stream_index = i;
301
302                 if (sync_file_idx >= 0) {
303                     m->sync_file_index   = sync_file_idx;
304                     m->sync_stream_index = sync_stream_idx;
305                 } else {
306                     m->sync_file_index   = file_idx;
307                     m->sync_stream_index = i;
308                 }
309             }
310     }
311
312     if (!m) {
313         av_log(NULL, AV_LOG_FATAL, "Stream map '%s' matches no streams.\n", arg);
314         exit_program(1);
315     }
316
317     av_freep(&map);
318     return 0;
319 }
320
321 static int opt_attach(void *optctx, const char *opt, const char *arg)
322 {
323     OptionsContext *o = optctx;
324     GROW_ARRAY(o->attachments, o->nb_attachments);
325     o->attachments[o->nb_attachments - 1] = arg;
326     return 0;
327 }
328
329 static int opt_map_channel(void *optctx, const char *opt, const char *arg)
330 {
331     OptionsContext *o = optctx;
332     int n;
333     AVStream *st;
334     AudioChannelMap *m;
335
336     GROW_ARRAY(o->audio_channel_maps, o->nb_audio_channel_maps);
337     m = &o->audio_channel_maps[o->nb_audio_channel_maps - 1];
338
339     /* muted channel syntax */
340     n = sscanf(arg, "%d:%d.%d", &m->channel_idx, &m->ofile_idx, &m->ostream_idx);
341     if ((n == 1 || n == 3) && m->channel_idx == -1) {
342         m->file_idx = m->stream_idx = -1;
343         if (n == 1)
344             m->ofile_idx = m->ostream_idx = -1;
345         return 0;
346     }
347
348     /* normal syntax */
349     n = sscanf(arg, "%d.%d.%d:%d.%d",
350                &m->file_idx,  &m->stream_idx, &m->channel_idx,
351                &m->ofile_idx, &m->ostream_idx);
352
353     if (n != 3 && n != 5) {
354         av_log(NULL, AV_LOG_FATAL, "Syntax error, mapchan usage: "
355                "[file.stream.channel|-1][:syncfile:syncstream]\n");
356         exit_program(1);
357     }
358
359     if (n != 5) // only file.stream.channel specified
360         m->ofile_idx = m->ostream_idx = -1;
361
362     /* check input */
363     if (m->file_idx < 0 || m->file_idx >= nb_input_files) {
364         av_log(NULL, AV_LOG_FATAL, "mapchan: invalid input file index: %d\n",
365                m->file_idx);
366         exit_program(1);
367     }
368     if (m->stream_idx < 0 ||
369         m->stream_idx >= input_files[m->file_idx]->nb_streams) {
370         av_log(NULL, AV_LOG_FATAL, "mapchan: invalid input file stream index #%d.%d\n",
371                m->file_idx, m->stream_idx);
372         exit_program(1);
373     }
374     st = input_files[m->file_idx]->ctx->streams[m->stream_idx];
375     if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO) {
376         av_log(NULL, AV_LOG_FATAL, "mapchan: stream #%d.%d is not an audio stream.\n",
377                m->file_idx, m->stream_idx);
378         exit_program(1);
379     }
380     if (m->channel_idx < 0 || m->channel_idx >= st->codec->channels) {
381         av_log(NULL, AV_LOG_FATAL, "mapchan: invalid audio channel #%d.%d.%d\n",
382                m->file_idx, m->stream_idx, m->channel_idx);
383         exit_program(1);
384     }
385     return 0;
386 }
387
388 static int opt_sdp_file(void *optctx, const char *opt, const char *arg)
389 {
390     av_free(sdp_filename);
391     sdp_filename = av_strdup(arg);
392     return 0;
393 }
394
395 /**
396  * Parse a metadata specifier passed as 'arg' parameter.
397  * @param arg  metadata string to parse
398  * @param type metadata type is written here -- g(lobal)/s(tream)/c(hapter)/p(rogram)
399  * @param index for type c/p, chapter/program index is written here
400  * @param stream_spec for type s, the stream specifier is written here
401  */
402 static void parse_meta_type(char *arg, char *type, int *index, const char **stream_spec)
403 {
404     if (*arg) {
405         *type = *arg;
406         switch (*arg) {
407         case 'g':
408             break;
409         case 's':
410             if (*(++arg) && *arg != ':') {
411                 av_log(NULL, AV_LOG_FATAL, "Invalid metadata specifier %s.\n", arg);
412                 exit_program(1);
413             }
414             *stream_spec = *arg == ':' ? arg + 1 : "";
415             break;
416         case 'c':
417         case 'p':
418             if (*(++arg) == ':')
419                 *index = strtol(++arg, NULL, 0);
420             break;
421         default:
422             av_log(NULL, AV_LOG_FATAL, "Invalid metadata type %c.\n", *arg);
423             exit_program(1);
424         }
425     } else
426         *type = 'g';
427 }
428
429 static int copy_metadata(char *outspec, char *inspec, AVFormatContext *oc, AVFormatContext *ic, OptionsContext *o)
430 {
431     AVDictionary **meta_in = NULL;
432     AVDictionary **meta_out = NULL;
433     int i, ret = 0;
434     char type_in, type_out;
435     const char *istream_spec = NULL, *ostream_spec = NULL;
436     int idx_in = 0, idx_out = 0;
437
438     parse_meta_type(inspec,  &type_in,  &idx_in,  &istream_spec);
439     parse_meta_type(outspec, &type_out, &idx_out, &ostream_spec);
440
441     if (!ic) {
442         if (type_out == 'g' || !*outspec)
443             o->metadata_global_manual = 1;
444         if (type_out == 's' || !*outspec)
445             o->metadata_streams_manual = 1;
446         if (type_out == 'c' || !*outspec)
447             o->metadata_chapters_manual = 1;
448         return 0;
449     }
450
451     if (type_in == 'g' || type_out == 'g')
452         o->metadata_global_manual = 1;
453     if (type_in == 's' || type_out == 's')
454         o->metadata_streams_manual = 1;
455     if (type_in == 'c' || type_out == 'c')
456         o->metadata_chapters_manual = 1;
457
458     /* ic is NULL when just disabling automatic mappings */
459     if (!ic)
460         return 0;
461
462 #define METADATA_CHECK_INDEX(index, nb_elems, desc)\
463     if ((index) < 0 || (index) >= (nb_elems)) {\
464         av_log(NULL, AV_LOG_FATAL, "Invalid %s index %d while processing metadata maps.\n",\
465                 (desc), (index));\
466         exit_program(1);\
467     }
468
469 #define SET_DICT(type, meta, context, index)\
470         switch (type) {\
471         case 'g':\
472             meta = &context->metadata;\
473             break;\
474         case 'c':\
475             METADATA_CHECK_INDEX(index, context->nb_chapters, "chapter")\
476             meta = &context->chapters[index]->metadata;\
477             break;\
478         case 'p':\
479             METADATA_CHECK_INDEX(index, context->nb_programs, "program")\
480             meta = &context->programs[index]->metadata;\
481             break;\
482         case 's':\
483             break; /* handled separately below */ \
484         default: av_assert0(0);\
485         }\
486
487     SET_DICT(type_in, meta_in, ic, idx_in);
488     SET_DICT(type_out, meta_out, oc, idx_out);
489
490     /* for input streams choose first matching stream */
491     if (type_in == 's') {
492         for (i = 0; i < ic->nb_streams; i++) {
493             if ((ret = check_stream_specifier(ic, ic->streams[i], istream_spec)) > 0) {
494                 meta_in = &ic->streams[i]->metadata;
495                 break;
496             } else if (ret < 0)
497                 exit_program(1);
498         }
499         if (!meta_in) {
500             av_log(NULL, AV_LOG_FATAL, "Stream specifier %s does not match  any streams.\n", istream_spec);
501             exit_program(1);
502         }
503     }
504
505     if (type_out == 's') {
506         for (i = 0; i < oc->nb_streams; i++) {
507             if ((ret = check_stream_specifier(oc, oc->streams[i], ostream_spec)) > 0) {
508                 meta_out = &oc->streams[i]->metadata;
509                 av_dict_copy(meta_out, *meta_in, AV_DICT_DONT_OVERWRITE);
510             } else if (ret < 0)
511                 exit_program(1);
512         }
513     } else
514         av_dict_copy(meta_out, *meta_in, AV_DICT_DONT_OVERWRITE);
515
516     return 0;
517 }
518
519 static int opt_recording_timestamp(void *optctx, const char *opt, const char *arg)
520 {
521     OptionsContext *o = optctx;
522     char buf[128];
523     int64_t recording_timestamp = parse_time_or_die(opt, arg, 0) / 1E6;
524     struct tm time = *gmtime((time_t*)&recording_timestamp);
525     if (!strftime(buf, sizeof(buf), "creation_time=%Y-%m-%dT%H:%M:%S%z", &time))
526         return -1;
527     parse_option(o, "metadata", buf, options);
528
529     av_log(NULL, AV_LOG_WARNING, "%s is deprecated, set the 'creation_time' metadata "
530                                  "tag instead.\n", opt);
531     return 0;
532 }
533
534 static AVCodec *find_codec_or_die(const char *name, enum AVMediaType type, int encoder)
535 {
536     const AVCodecDescriptor *desc;
537     const char *codec_string = encoder ? "encoder" : "decoder";
538     AVCodec *codec;
539
540     codec = encoder ?
541         avcodec_find_encoder_by_name(name) :
542         avcodec_find_decoder_by_name(name);
543
544     if (!codec && (desc = avcodec_descriptor_get_by_name(name))) {
545         codec = encoder ? avcodec_find_encoder(desc->id) :
546                           avcodec_find_decoder(desc->id);
547         if (codec)
548             av_log(NULL, AV_LOG_VERBOSE, "Matched %s '%s' for codec '%s'.\n",
549                    codec_string, codec->name, desc->name);
550     }
551
552     if (!codec) {
553         av_log(NULL, AV_LOG_FATAL, "Unknown %s '%s'\n", codec_string, name);
554         exit_program(1);
555     }
556     if (codec->type != type) {
557         av_log(NULL, AV_LOG_FATAL, "Invalid %s type '%s'\n", codec_string, name);
558         exit_program(1);
559     }
560     return codec;
561 }
562
563 static AVCodec *choose_decoder(OptionsContext *o, AVFormatContext *s, AVStream *st)
564 {
565     char *codec_name = NULL;
566
567     MATCH_PER_STREAM_OPT(codec_names, str, codec_name, s, st);
568     if (codec_name) {
569         AVCodec *codec = find_codec_or_die(codec_name, st->codec->codec_type, 0);
570         st->codec->codec_id = codec->id;
571         return codec;
572     } else
573         return avcodec_find_decoder(st->codec->codec_id);
574 }
575
576 /* Add all the streams from the given input file to the global
577  * list of input streams. */
578 static void add_input_streams(OptionsContext *o, AVFormatContext *ic)
579 {
580     int i, ret;
581
582     for (i = 0; i < ic->nb_streams; i++) {
583         AVStream *st = ic->streams[i];
584         AVCodecContext *dec = st->codec;
585         InputStream *ist = av_mallocz(sizeof(*ist));
586         char *framerate = NULL, *hwaccel = NULL, *hwaccel_device = NULL;
587         char *codec_tag = NULL;
588         char *next;
589         char *discard_str = NULL;
590         const AVOption *discard_opt = av_opt_find(dec, "skip_frame", NULL, 0, 0);
591
592         if (!ist)
593             exit_program(1);
594
595         GROW_ARRAY(input_streams, nb_input_streams);
596         input_streams[nb_input_streams - 1] = ist;
597
598         ist->st = st;
599         ist->file_index = nb_input_files;
600         ist->discard = 1;
601         st->discard  = AVDISCARD_ALL;
602
603         ist->ts_scale = 1.0;
604         MATCH_PER_STREAM_OPT(ts_scale, dbl, ist->ts_scale, ic, st);
605
606         ist->autorotate = 1;
607         MATCH_PER_STREAM_OPT(autorotate, i, ist->autorotate, ic, st);
608
609         MATCH_PER_STREAM_OPT(codec_tags, str, codec_tag, ic, st);
610         if (codec_tag) {
611             uint32_t tag = strtol(codec_tag, &next, 0);
612             if (*next)
613                 tag = AV_RL32(codec_tag);
614             st->codec->codec_tag = tag;
615         }
616
617         ist->dec = choose_decoder(o, ic, st);
618         ist->decoder_opts = filter_codec_opts(o->g->codec_opts, ist->st->codec->codec_id, ic, st, ist->dec);
619
620         ist->reinit_filters = -1;
621         MATCH_PER_STREAM_OPT(reinit_filters, i, ist->reinit_filters, ic, st);
622
623         MATCH_PER_STREAM_OPT(discard, str, discard_str, ic, st);
624         ist->user_set_discard = AVDISCARD_NONE;
625         if (discard_str && av_opt_eval_int(dec, discard_opt, discard_str, &ist->user_set_discard) < 0) {
626             av_log(NULL, AV_LOG_ERROR, "Error parsing discard %s.\n",
627                     discard_str);
628             exit_program(1);
629         }
630
631         ist->filter_in_rescale_delta_last = AV_NOPTS_VALUE;
632
633         ist->dec_ctx = avcodec_alloc_context3(ist->dec);
634         if (!ist->dec_ctx) {
635             av_log(NULL, AV_LOG_ERROR, "Error allocating the decoder context.\n");
636             exit_program(1);
637         }
638
639         ret = avcodec_copy_context(ist->dec_ctx, dec);
640         if (ret < 0) {
641             av_log(NULL, AV_LOG_ERROR, "Error initializing the decoder context.\n");
642             exit_program(1);
643         }
644
645         switch (dec->codec_type) {
646         case AVMEDIA_TYPE_VIDEO:
647             if(!ist->dec)
648                 ist->dec = avcodec_find_decoder(dec->codec_id);
649             if (av_codec_get_lowres(dec)) {
650                 dec->flags |= CODEC_FLAG_EMU_EDGE;
651             }
652
653             ist->resample_height  = ist->dec_ctx->height;
654             ist->resample_width   = ist->dec_ctx->width;
655             ist->resample_pix_fmt = ist->dec_ctx->pix_fmt;
656
657             MATCH_PER_STREAM_OPT(frame_rates, str, framerate, ic, st);
658             if (framerate && av_parse_video_rate(&ist->framerate,
659                                                  framerate) < 0) {
660                 av_log(NULL, AV_LOG_ERROR, "Error parsing framerate %s.\n",
661                        framerate);
662                 exit_program(1);
663             }
664
665             ist->top_field_first = -1;
666             MATCH_PER_STREAM_OPT(top_field_first, i, ist->top_field_first, ic, st);
667
668             MATCH_PER_STREAM_OPT(hwaccels, str, hwaccel, ic, st);
669             if (hwaccel) {
670                 if (!strcmp(hwaccel, "none"))
671                     ist->hwaccel_id = HWACCEL_NONE;
672                 else if (!strcmp(hwaccel, "auto"))
673                     ist->hwaccel_id = HWACCEL_AUTO;
674                 else {
675                     int i;
676                     for (i = 0; hwaccels[i].name; i++) {
677                         if (!strcmp(hwaccels[i].name, hwaccel)) {
678                             ist->hwaccel_id = hwaccels[i].id;
679                             break;
680                         }
681                     }
682
683                     if (!ist->hwaccel_id) {
684                         av_log(NULL, AV_LOG_FATAL, "Unrecognized hwaccel: %s.\n",
685                                hwaccel);
686                         av_log(NULL, AV_LOG_FATAL, "Supported hwaccels: ");
687                         for (i = 0; hwaccels[i].name; i++)
688                             av_log(NULL, AV_LOG_FATAL, "%s ", hwaccels[i].name);
689                         av_log(NULL, AV_LOG_FATAL, "\n");
690                         exit_program(1);
691                     }
692                 }
693             }
694
695             MATCH_PER_STREAM_OPT(hwaccel_devices, str, hwaccel_device, ic, st);
696             if (hwaccel_device) {
697                 ist->hwaccel_device = av_strdup(hwaccel_device);
698                 if (!ist->hwaccel_device)
699                     exit_program(1);
700             }
701             ist->hwaccel_pix_fmt = AV_PIX_FMT_NONE;
702
703             break;
704         case AVMEDIA_TYPE_AUDIO:
705             ist->guess_layout_max = INT_MAX;
706             MATCH_PER_STREAM_OPT(guess_layout_max, i, ist->guess_layout_max, ic, st);
707             guess_input_channel_layout(ist);
708
709             ist->resample_sample_fmt     = ist->dec_ctx->sample_fmt;
710             ist->resample_sample_rate    = ist->dec_ctx->sample_rate;
711             ist->resample_channels       = ist->dec_ctx->channels;
712             ist->resample_channel_layout = ist->dec_ctx->channel_layout;
713
714             break;
715         case AVMEDIA_TYPE_DATA:
716         case AVMEDIA_TYPE_SUBTITLE: {
717             char *canvas_size = NULL;
718             if(!ist->dec)
719                 ist->dec = avcodec_find_decoder(dec->codec_id);
720             MATCH_PER_STREAM_OPT(fix_sub_duration, i, ist->fix_sub_duration, ic, st);
721             MATCH_PER_STREAM_OPT(canvas_sizes, str, canvas_size, ic, st);
722             if (canvas_size &&
723                 av_parse_video_size(&ist->dec_ctx->width, &ist->dec_ctx->height, canvas_size) < 0) {
724                 av_log(NULL, AV_LOG_FATAL, "Invalid canvas size: %s.\n", canvas_size);
725                 exit_program(1);
726             }
727             break;
728         }
729         case AVMEDIA_TYPE_ATTACHMENT:
730         case AVMEDIA_TYPE_UNKNOWN:
731             break;
732         default:
733             abort();
734         }
735     }
736 }
737
738 static void assert_file_overwrite(const char *filename)
739 {
740     if (file_overwrite && no_file_overwrite) {
741         fprintf(stderr, "Error, both -y and -n supplied. Exiting.\n");
742         exit_program(1);
743     }
744
745     if (!file_overwrite) {
746         const char *proto_name = avio_find_protocol_name(filename);
747         if (proto_name && !strcmp(proto_name, "file") && avio_check(filename, 0) == 0) {
748             if (stdin_interaction && !no_file_overwrite) {
749                 fprintf(stderr,"File '%s' already exists. Overwrite ? [y/N] ", filename);
750                 fflush(stderr);
751                 term_exit();
752                 signal(SIGINT, SIG_DFL);
753                 if (!read_yesno()) {
754                     av_log(NULL, AV_LOG_FATAL, "Not overwriting - exiting\n");
755                     exit_program(1);
756                 }
757                 term_init();
758             }
759             else {
760                 av_log(NULL, AV_LOG_FATAL, "File '%s' already exists. Exiting.\n", filename);
761                 exit_program(1);
762             }
763         }
764     }
765 }
766
767 static void dump_attachment(AVStream *st, const char *filename)
768 {
769     int ret;
770     AVIOContext *out = NULL;
771     AVDictionaryEntry *e;
772
773     if (!st->codec->extradata_size) {
774         av_log(NULL, AV_LOG_WARNING, "No extradata to dump in stream #%d:%d.\n",
775                nb_input_files - 1, st->index);
776         return;
777     }
778     if (!*filename && (e = av_dict_get(st->metadata, "filename", NULL, 0)))
779         filename = e->value;
780     if (!*filename) {
781         av_log(NULL, AV_LOG_FATAL, "No filename specified and no 'filename' tag"
782                "in stream #%d:%d.\n", nb_input_files - 1, st->index);
783         exit_program(1);
784     }
785
786     assert_file_overwrite(filename);
787
788     if ((ret = avio_open2(&out, filename, AVIO_FLAG_WRITE, &int_cb, NULL)) < 0) {
789         av_log(NULL, AV_LOG_FATAL, "Could not open file %s for writing.\n",
790                filename);
791         exit_program(1);
792     }
793
794     avio_write(out, st->codec->extradata, st->codec->extradata_size);
795     avio_flush(out);
796     avio_close(out);
797 }
798
799 static int open_input_file(OptionsContext *o, const char *filename)
800 {
801     InputFile *f;
802     AVFormatContext *ic;
803     AVInputFormat *file_iformat = NULL;
804     int err, i, ret;
805     int64_t timestamp;
806     AVDictionary **opts;
807     AVDictionary *unused_opts = NULL;
808     AVDictionaryEntry *e = NULL;
809     int orig_nb_streams;                     // number of streams before avformat_find_stream_info
810     char *   video_codec_name = NULL;
811     char *   audio_codec_name = NULL;
812     char *subtitle_codec_name = NULL;
813     char *    data_codec_name = NULL;
814     int scan_all_pmts_set = 0;
815
816     if (o->format) {
817         if (!(file_iformat = av_find_input_format(o->format))) {
818             av_log(NULL, AV_LOG_FATAL, "Unknown input format: '%s'\n", o->format);
819             exit_program(1);
820         }
821     }
822
823     if (!strcmp(filename, "-"))
824         filename = "pipe:";
825
826     stdin_interaction &= strncmp(filename, "pipe:", 5) &&
827                          strcmp(filename, "/dev/stdin");
828
829     /* get default parameters from command line */
830     ic = avformat_alloc_context();
831     if (!ic) {
832         print_error(filename, AVERROR(ENOMEM));
833         exit_program(1);
834     }
835     if (o->nb_audio_sample_rate) {
836         av_dict_set_int(&o->g->format_opts, "sample_rate", o->audio_sample_rate[o->nb_audio_sample_rate - 1].u.i, 0);
837     }
838     if (o->nb_audio_channels) {
839         /* because we set audio_channels based on both the "ac" and
840          * "channel_layout" options, we need to check that the specified
841          * demuxer actually has the "channels" option before setting it */
842         if (file_iformat && file_iformat->priv_class &&
843             av_opt_find(&file_iformat->priv_class, "channels", NULL, 0,
844                         AV_OPT_SEARCH_FAKE_OBJ)) {
845             av_dict_set_int(&o->g->format_opts, "channels", o->audio_channels[o->nb_audio_channels - 1].u.i, 0);
846         }
847     }
848     if (o->nb_frame_rates) {
849         /* set the format-level framerate option;
850          * this is important for video grabbers, e.g. x11 */
851         if (file_iformat && file_iformat->priv_class &&
852             av_opt_find(&file_iformat->priv_class, "framerate", NULL, 0,
853                         AV_OPT_SEARCH_FAKE_OBJ)) {
854             av_dict_set(&o->g->format_opts, "framerate",
855                         o->frame_rates[o->nb_frame_rates - 1].u.str, 0);
856         }
857     }
858     if (o->nb_frame_sizes) {
859         av_dict_set(&o->g->format_opts, "video_size", o->frame_sizes[o->nb_frame_sizes - 1].u.str, 0);
860     }
861     if (o->nb_frame_pix_fmts)
862         av_dict_set(&o->g->format_opts, "pixel_format", o->frame_pix_fmts[o->nb_frame_pix_fmts - 1].u.str, 0);
863
864     MATCH_PER_TYPE_OPT(codec_names, str,    video_codec_name, ic, "v");
865     MATCH_PER_TYPE_OPT(codec_names, str,    audio_codec_name, ic, "a");
866     MATCH_PER_TYPE_OPT(codec_names, str, subtitle_codec_name, ic, "s");
867     MATCH_PER_TYPE_OPT(codec_names, str,     data_codec_name, ic, "d");
868
869     ic->video_codec_id   = video_codec_name ?
870         find_codec_or_die(video_codec_name   , AVMEDIA_TYPE_VIDEO   , 0)->id : AV_CODEC_ID_NONE;
871     ic->audio_codec_id   = audio_codec_name ?
872         find_codec_or_die(audio_codec_name   , AVMEDIA_TYPE_AUDIO   , 0)->id : AV_CODEC_ID_NONE;
873     ic->subtitle_codec_id= subtitle_codec_name ?
874         find_codec_or_die(subtitle_codec_name, AVMEDIA_TYPE_SUBTITLE, 0)->id : AV_CODEC_ID_NONE;
875     ic->data_codec_id    = data_codec_name ?
876         find_codec_or_die(data_codec_name, AVMEDIA_TYPE_DATA, 0)->id : AV_CODEC_ID_NONE;
877
878     if (video_codec_name)
879         av_format_set_video_codec   (ic, find_codec_or_die(video_codec_name   , AVMEDIA_TYPE_VIDEO   , 0));
880     if (audio_codec_name)
881         av_format_set_audio_codec   (ic, find_codec_or_die(audio_codec_name   , AVMEDIA_TYPE_AUDIO   , 0));
882     if (subtitle_codec_name)
883         av_format_set_subtitle_codec(ic, find_codec_or_die(subtitle_codec_name, AVMEDIA_TYPE_SUBTITLE, 0));
884     if (data_codec_name)
885         av_format_set_data_codec(ic, find_codec_or_die(data_codec_name, AVMEDIA_TYPE_DATA, 0));
886
887     ic->flags |= AVFMT_FLAG_NONBLOCK;
888     ic->interrupt_callback = int_cb;
889
890     if (!av_dict_get(o->g->format_opts, "scan_all_pmts", NULL, AV_DICT_MATCH_CASE)) {
891         av_dict_set(&o->g->format_opts, "scan_all_pmts", "1", AV_DICT_DONT_OVERWRITE);
892         scan_all_pmts_set = 1;
893     }
894     /* open the input file with generic avformat function */
895     err = avformat_open_input(&ic, filename, file_iformat, &o->g->format_opts);
896     if (err < 0) {
897         print_error(filename, err);
898         exit_program(1);
899     }
900     if (scan_all_pmts_set)
901         av_dict_set(&o->g->format_opts, "scan_all_pmts", NULL, AV_DICT_MATCH_CASE);
902     remove_avoptions(&o->g->format_opts, o->g->codec_opts);
903     assert_avoptions(o->g->format_opts);
904
905     /* apply forced codec ids */
906     for (i = 0; i < ic->nb_streams; i++)
907         choose_decoder(o, ic, ic->streams[i]);
908
909     /* Set AVCodecContext options for avformat_find_stream_info */
910     opts = setup_find_stream_info_opts(ic, o->g->codec_opts);
911     orig_nb_streams = ic->nb_streams;
912
913     /* If not enough info to get the stream parameters, we decode the
914        first frames to get it. (used in mpeg case for example) */
915     ret = avformat_find_stream_info(ic, opts);
916     if (ret < 0) {
917         av_log(NULL, AV_LOG_FATAL, "%s: could not find codec parameters\n", filename);
918         if (ic->nb_streams == 0) {
919             avformat_close_input(&ic);
920             exit_program(1);
921         }
922     }
923
924     timestamp = (o->start_time == AV_NOPTS_VALUE) ? 0 : o->start_time;
925     /* add the stream start time */
926     if (!o->seek_timestamp && ic->start_time != AV_NOPTS_VALUE)
927         timestamp += ic->start_time;
928
929     /* if seeking requested, we execute it */
930     if (o->start_time != AV_NOPTS_VALUE) {
931         int64_t seek_timestamp = timestamp;
932
933         if (!(ic->iformat->flags & AVFMT_SEEK_TO_PTS)) {
934             int dts_heuristic = 0;
935             for (i=0; i<ic->nb_streams; i++) {
936                 AVCodecContext *avctx = ic->streams[i]->codec;
937                 if (avctx->has_b_frames)
938                     dts_heuristic = 1;
939             }
940             if (dts_heuristic) {
941                 seek_timestamp -= 3*AV_TIME_BASE / 23;
942             }
943         }
944         ret = avformat_seek_file(ic, -1, INT64_MIN, seek_timestamp, seek_timestamp, 0);
945         if (ret < 0) {
946             av_log(NULL, AV_LOG_WARNING, "%s: could not seek to position %0.3f\n",
947                    filename, (double)timestamp / AV_TIME_BASE);
948         }
949     }
950
951     /* update the current parameters so that they match the one of the input stream */
952     add_input_streams(o, ic);
953
954     /* dump the file content */
955     av_dump_format(ic, nb_input_files, filename, 0);
956
957     GROW_ARRAY(input_files, nb_input_files);
958     f = av_mallocz(sizeof(*f));
959     if (!f)
960         exit_program(1);
961     input_files[nb_input_files - 1] = f;
962
963     f->ctx        = ic;
964     f->ist_index  = nb_input_streams - ic->nb_streams;
965     f->start_time = o->start_time;
966     f->recording_time = o->recording_time;
967     f->input_ts_offset = o->input_ts_offset;
968     f->ts_offset  = o->input_ts_offset - (copy_ts ? (start_at_zero && ic->start_time != AV_NOPTS_VALUE ? ic->start_time : 0) : timestamp);
969     f->nb_streams = ic->nb_streams;
970     f->rate_emu   = o->rate_emu;
971     f->accurate_seek = o->accurate_seek;
972 #if HAVE_PTHREADS
973     f->thread_queue_size = o->thread_queue_size > 0 ? o->thread_queue_size : 8;
974 #endif
975
976     /* check if all codec options have been used */
977     unused_opts = strip_specifiers(o->g->codec_opts);
978     for (i = f->ist_index; i < nb_input_streams; i++) {
979         e = NULL;
980         while ((e = av_dict_get(input_streams[i]->decoder_opts, "", e,
981                                 AV_DICT_IGNORE_SUFFIX)))
982             av_dict_set(&unused_opts, e->key, NULL, 0);
983     }
984
985     e = NULL;
986     while ((e = av_dict_get(unused_opts, "", e, AV_DICT_IGNORE_SUFFIX))) {
987         const AVClass *class = avcodec_get_class();
988         const AVOption *option = av_opt_find(&class, e->key, NULL, 0,
989                                              AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ);
990         const AVClass *fclass = avformat_get_class();
991         const AVOption *foption = av_opt_find(&fclass, e->key, NULL, 0,
992                                              AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ);
993         if (!option || foption)
994             continue;
995
996
997         if (!(option->flags & AV_OPT_FLAG_DECODING_PARAM)) {
998             av_log(NULL, AV_LOG_ERROR, "Codec AVOption %s (%s) specified for "
999                    "input file #%d (%s) is not a decoding option.\n", e->key,
1000                    option->help ? option->help : "", nb_input_files - 1,
1001                    filename);
1002             exit_program(1);
1003         }
1004
1005         av_log(NULL, AV_LOG_WARNING, "Codec AVOption %s (%s) specified for "
1006                "input file #%d (%s) has not been used for any stream. The most "
1007                "likely reason is either wrong type (e.g. a video option with "
1008                "no video streams) or that it is a private option of some decoder "
1009                "which was not actually used for any stream.\n", e->key,
1010                option->help ? option->help : "", nb_input_files - 1, filename);
1011     }
1012     av_dict_free(&unused_opts);
1013
1014     for (i = 0; i < o->nb_dump_attachment; i++) {
1015         int j;
1016
1017         for (j = 0; j < ic->nb_streams; j++) {
1018             AVStream *st = ic->streams[j];
1019
1020             if (check_stream_specifier(ic, st, o->dump_attachment[i].specifier) == 1)
1021                 dump_attachment(st, o->dump_attachment[i].u.str);
1022         }
1023     }
1024
1025     for (i = 0; i < orig_nb_streams; i++)
1026         av_dict_free(&opts[i]);
1027     av_freep(&opts);
1028
1029     input_stream_potentially_available = 1;
1030
1031     return 0;
1032 }
1033
1034 static uint8_t *get_line(AVIOContext *s)
1035 {
1036     AVIOContext *line;
1037     uint8_t *buf;
1038     char c;
1039
1040     if (avio_open_dyn_buf(&line) < 0) {
1041         av_log(NULL, AV_LOG_FATAL, "Could not alloc buffer for reading preset.\n");
1042         exit_program(1);
1043     }
1044
1045     while ((c = avio_r8(s)) && c != '\n')
1046         avio_w8(line, c);
1047     avio_w8(line, 0);
1048     avio_close_dyn_buf(line, &buf);
1049
1050     return buf;
1051 }
1052
1053 static int get_preset_file_2(const char *preset_name, const char *codec_name, AVIOContext **s)
1054 {
1055     int i, ret = -1;
1056     char filename[1000];
1057     const char *base[3] = { getenv("AVCONV_DATADIR"),
1058                             getenv("HOME"),
1059                             AVCONV_DATADIR,
1060                             };
1061
1062     for (i = 0; i < FF_ARRAY_ELEMS(base) && ret < 0; i++) {
1063         if (!base[i])
1064             continue;
1065         if (codec_name) {
1066             snprintf(filename, sizeof(filename), "%s%s/%s-%s.avpreset", base[i],
1067                      i != 1 ? "" : "/.avconv", codec_name, preset_name);
1068             ret = avio_open2(s, filename, AVIO_FLAG_READ, &int_cb, NULL);
1069         }
1070         if (ret < 0) {
1071             snprintf(filename, sizeof(filename), "%s%s/%s.avpreset", base[i],
1072                      i != 1 ? "" : "/.avconv", preset_name);
1073             ret = avio_open2(s, filename, AVIO_FLAG_READ, &int_cb, NULL);
1074         }
1075     }
1076     return ret;
1077 }
1078
1079 static void choose_encoder(OptionsContext *o, AVFormatContext *s, OutputStream *ost)
1080 {
1081     char *codec_name = NULL;
1082
1083     MATCH_PER_STREAM_OPT(codec_names, str, codec_name, s, ost->st);
1084     if (!codec_name) {
1085         ost->st->codec->codec_id = av_guess_codec(s->oformat, NULL, s->filename,
1086                                                   NULL, ost->st->codec->codec_type);
1087         ost->enc = avcodec_find_encoder(ost->st->codec->codec_id);
1088     } else if (!strcmp(codec_name, "copy"))
1089         ost->stream_copy = 1;
1090     else {
1091         ost->enc = find_codec_or_die(codec_name, ost->st->codec->codec_type, 1);
1092         ost->st->codec->codec_id = ost->enc->id;
1093     }
1094 }
1095
1096 static OutputStream *new_output_stream(OptionsContext *o, AVFormatContext *oc, enum AVMediaType type, int source_index)
1097 {
1098     OutputStream *ost;
1099     AVStream *st = avformat_new_stream(oc, NULL);
1100     int idx      = oc->nb_streams - 1, ret = 0;
1101     char *bsf = NULL, *next, *codec_tag = NULL;
1102     AVBitStreamFilterContext *bsfc, *bsfc_prev = NULL;
1103     double qscale = -1;
1104     int i;
1105
1106     if (!st) {
1107         av_log(NULL, AV_LOG_FATAL, "Could not alloc stream.\n");
1108         exit_program(1);
1109     }
1110
1111     if (oc->nb_streams - 1 < o->nb_streamid_map)
1112         st->id = o->streamid_map[oc->nb_streams - 1];
1113
1114     GROW_ARRAY(output_streams, nb_output_streams);
1115     if (!(ost = av_mallocz(sizeof(*ost))))
1116         exit_program(1);
1117     output_streams[nb_output_streams - 1] = ost;
1118
1119     ost->file_index = nb_output_files - 1;
1120     ost->index      = idx;
1121     ost->st         = st;
1122     st->codec->codec_type = type;
1123     choose_encoder(o, oc, ost);
1124
1125     ost->enc_ctx = avcodec_alloc_context3(ost->enc);
1126     if (!ost->enc_ctx) {
1127         av_log(NULL, AV_LOG_ERROR, "Error allocating the encoding context.\n");
1128         exit_program(1);
1129     }
1130     ost->enc_ctx->codec_type = type;
1131
1132     if (ost->enc) {
1133         AVIOContext *s = NULL;
1134         char *buf = NULL, *arg = NULL, *preset = NULL;
1135
1136         ost->encoder_opts  = filter_codec_opts(o->g->codec_opts, ost->enc->id, oc, st, ost->enc);
1137
1138         MATCH_PER_STREAM_OPT(presets, str, preset, oc, st);
1139         if (preset && (!(ret = get_preset_file_2(preset, ost->enc->name, &s)))) {
1140             do  {
1141                 buf = get_line(s);
1142                 if (!buf[0] || buf[0] == '#') {
1143                     av_free(buf);
1144                     continue;
1145                 }
1146                 if (!(arg = strchr(buf, '='))) {
1147                     av_log(NULL, AV_LOG_FATAL, "Invalid line found in the preset file.\n");
1148                     exit_program(1);
1149                 }
1150                 *arg++ = 0;
1151                 av_dict_set(&ost->encoder_opts, buf, arg, AV_DICT_DONT_OVERWRITE);
1152                 av_free(buf);
1153             } while (!s->eof_reached);
1154             avio_closep(&s);
1155         }
1156         if (ret) {
1157             av_log(NULL, AV_LOG_FATAL,
1158                    "Preset %s specified for stream %d:%d, but could not be opened.\n",
1159                    preset, ost->file_index, ost->index);
1160             exit_program(1);
1161         }
1162     } else {
1163         ost->encoder_opts = filter_codec_opts(o->g->codec_opts, AV_CODEC_ID_NONE, oc, st, NULL);
1164     }
1165
1166     ost->max_frames = INT64_MAX;
1167     MATCH_PER_STREAM_OPT(max_frames, i64, ost->max_frames, oc, st);
1168     for (i = 0; i<o->nb_max_frames; i++) {
1169         char *p = o->max_frames[i].specifier;
1170         if (!*p && type != AVMEDIA_TYPE_VIDEO) {
1171             av_log(NULL, AV_LOG_WARNING, "Applying unspecific -frames to non video streams, maybe you meant -vframes ?\n");
1172             break;
1173         }
1174     }
1175
1176     ost->copy_prior_start = -1;
1177     MATCH_PER_STREAM_OPT(copy_prior_start, i, ost->copy_prior_start, oc ,st);
1178
1179     MATCH_PER_STREAM_OPT(bitstream_filters, str, bsf, oc, st);
1180     while (bsf) {
1181         char *arg = NULL;
1182         if (next = strchr(bsf, ','))
1183             *next++ = 0;
1184         if (arg = strchr(bsf, '='))
1185             *arg++ = 0;
1186         if (!(bsfc = av_bitstream_filter_init(bsf))) {
1187             av_log(NULL, AV_LOG_FATAL, "Unknown bitstream filter %s\n", bsf);
1188             exit_program(1);
1189         }
1190         if (bsfc_prev)
1191             bsfc_prev->next = bsfc;
1192         else
1193             ost->bitstream_filters = bsfc;
1194         av_dict_set(&ost->bsf_args, bsfc->filter->name, arg, 0);
1195
1196         bsfc_prev = bsfc;
1197         bsf       = next;
1198     }
1199
1200     MATCH_PER_STREAM_OPT(codec_tags, str, codec_tag, oc, st);
1201     if (codec_tag) {
1202         uint32_t tag = strtol(codec_tag, &next, 0);
1203         if (*next)
1204             tag = AV_RL32(codec_tag);
1205         ost->enc_ctx->codec_tag = tag;
1206     }
1207
1208     MATCH_PER_STREAM_OPT(qscale, dbl, qscale, oc, st);
1209     if (qscale >= 0) {
1210         ost->enc_ctx->flags |= CODEC_FLAG_QSCALE;
1211         ost->enc_ctx->global_quality = FF_QP2LAMBDA * qscale;
1212     }
1213
1214     MATCH_PER_STREAM_OPT(disposition, str, ost->disposition, oc, st);
1215     ost->disposition = av_strdup(ost->disposition);
1216
1217     if (oc->oformat->flags & AVFMT_GLOBALHEADER)
1218         ost->enc_ctx->flags |= CODEC_FLAG_GLOBAL_HEADER;
1219
1220     av_opt_get_int(o->g->sws_opts, "sws_flags", 0, &ost->sws_flags);
1221
1222     av_dict_copy(&ost->swr_opts, o->g->swr_opts, 0);
1223     if (ost->enc && av_get_exact_bits_per_sample(ost->enc->id) == 24)
1224         av_dict_set(&ost->swr_opts, "output_sample_bits", "24", 0);
1225
1226     av_dict_copy(&ost->resample_opts, o->g->resample_opts, 0);
1227
1228     ost->source_index = source_index;
1229     if (source_index >= 0) {
1230         ost->sync_ist = input_streams[source_index];
1231         input_streams[source_index]->discard = 0;
1232         input_streams[source_index]->st->discard = input_streams[source_index]->user_set_discard;
1233     }
1234     ost->last_mux_dts = AV_NOPTS_VALUE;
1235
1236     return ost;
1237 }
1238
1239 static void parse_matrix_coeffs(uint16_t *dest, const char *str)
1240 {
1241     int i;
1242     const char *p = str;
1243     for (i = 0;; i++) {
1244         dest[i] = atoi(p);
1245         if (i == 63)
1246             break;
1247         p = strchr(p, ',');
1248         if (!p) {
1249             av_log(NULL, AV_LOG_FATAL, "Syntax error in matrix \"%s\" at coeff %d\n", str, i);
1250             exit_program(1);
1251         }
1252         p++;
1253     }
1254 }
1255
1256 /* read file contents into a string */
1257 static uint8_t *read_file(const char *filename)
1258 {
1259     AVIOContext *pb      = NULL;
1260     AVIOContext *dyn_buf = NULL;
1261     int ret = avio_open(&pb, filename, AVIO_FLAG_READ);
1262     uint8_t buf[1024], *str;
1263
1264     if (ret < 0) {
1265         av_log(NULL, AV_LOG_ERROR, "Error opening file %s.\n", filename);
1266         return NULL;
1267     }
1268
1269     ret = avio_open_dyn_buf(&dyn_buf);
1270     if (ret < 0) {
1271         avio_closep(&pb);
1272         return NULL;
1273     }
1274     while ((ret = avio_read(pb, buf, sizeof(buf))) > 0)
1275         avio_write(dyn_buf, buf, ret);
1276     avio_w8(dyn_buf, 0);
1277     avio_closep(&pb);
1278
1279     ret = avio_close_dyn_buf(dyn_buf, &str);
1280     if (ret < 0)
1281         return NULL;
1282     return str;
1283 }
1284
1285 static char *get_ost_filters(OptionsContext *o, AVFormatContext *oc,
1286                              OutputStream *ost)
1287 {
1288     AVStream *st = ost->st;
1289
1290     if (ost->filters_script && ost->filters) {
1291         av_log(NULL, AV_LOG_ERROR, "Both -filter and -filter_script set for "
1292                "output stream #%d:%d.\n", nb_output_files, st->index);
1293         exit_program(1);
1294     }
1295
1296     if (ost->filters_script)
1297         return read_file(ost->filters_script);
1298     else if (ost->filters)
1299         return av_strdup(ost->filters);
1300
1301     return av_strdup(st->codec->codec_type == AVMEDIA_TYPE_VIDEO ?
1302                      "null" : "anull");
1303 }
1304
1305 static void check_streamcopy_filters(OptionsContext *o, AVFormatContext *oc,
1306                                      const OutputStream *ost, enum AVMediaType type)
1307 {
1308     if (ost->filters_script || ost->filters) {
1309         av_log(NULL, AV_LOG_ERROR,
1310                "%s '%s' was defined for %s output stream %d:%d but codec copy was selected.\n"
1311                "Filtering and streamcopy cannot be used together.\n",
1312                ost->filters ? "Filtergraph" : "Filtergraph script",
1313                ost->filters ? ost->filters : ost->filters_script,
1314                av_get_media_type_string(type), ost->file_index, ost->index);
1315         exit_program(1);
1316     }
1317 }
1318
1319 static OutputStream *new_video_stream(OptionsContext *o, AVFormatContext *oc, int source_index)
1320 {
1321     AVStream *st;
1322     OutputStream *ost;
1323     AVCodecContext *video_enc;
1324     char *frame_rate = NULL, *frame_aspect_ratio = NULL;
1325
1326     ost = new_output_stream(o, oc, AVMEDIA_TYPE_VIDEO, source_index);
1327     st  = ost->st;
1328     video_enc = ost->enc_ctx;
1329
1330     MATCH_PER_STREAM_OPT(frame_rates, str, frame_rate, oc, st);
1331     if (frame_rate && av_parse_video_rate(&ost->frame_rate, frame_rate) < 0) {
1332         av_log(NULL, AV_LOG_FATAL, "Invalid framerate value: %s\n", frame_rate);
1333         exit_program(1);
1334     }
1335     if (frame_rate && video_sync_method == VSYNC_PASSTHROUGH)
1336         av_log(NULL, AV_LOG_ERROR, "Using -vsync 0 and -r can produce invalid output files\n");
1337
1338     MATCH_PER_STREAM_OPT(frame_aspect_ratios, str, frame_aspect_ratio, oc, st);
1339     if (frame_aspect_ratio) {
1340         AVRational q;
1341         if (av_parse_ratio(&q, frame_aspect_ratio, 255, 0, NULL) < 0 ||
1342             q.num <= 0 || q.den <= 0) {
1343             av_log(NULL, AV_LOG_FATAL, "Invalid aspect ratio: %s\n", frame_aspect_ratio);
1344             exit_program(1);
1345         }
1346         ost->frame_aspect_ratio = q;
1347     }
1348
1349     MATCH_PER_STREAM_OPT(filter_scripts, str, ost->filters_script, oc, st);
1350     MATCH_PER_STREAM_OPT(filters,        str, ost->filters,        oc, st);
1351
1352     if (!ost->stream_copy) {
1353         const char *p = NULL;
1354         char *frame_size = NULL;
1355         char *frame_pix_fmt = NULL;
1356         char *intra_matrix = NULL, *inter_matrix = NULL;
1357         char *chroma_intra_matrix = NULL;
1358         int do_pass = 0;
1359         int i;
1360
1361         MATCH_PER_STREAM_OPT(frame_sizes, str, frame_size, oc, st);
1362         if (frame_size && av_parse_video_size(&video_enc->width, &video_enc->height, frame_size) < 0) {
1363             av_log(NULL, AV_LOG_FATAL, "Invalid frame size: %s.\n", frame_size);
1364             exit_program(1);
1365         }
1366
1367         video_enc->bits_per_raw_sample = frame_bits_per_raw_sample;
1368         MATCH_PER_STREAM_OPT(frame_pix_fmts, str, frame_pix_fmt, oc, st);
1369         if (frame_pix_fmt && *frame_pix_fmt == '+') {
1370             ost->keep_pix_fmt = 1;
1371             if (!*++frame_pix_fmt)
1372                 frame_pix_fmt = NULL;
1373         }
1374         if (frame_pix_fmt && (video_enc->pix_fmt = av_get_pix_fmt(frame_pix_fmt)) == AV_PIX_FMT_NONE) {
1375             av_log(NULL, AV_LOG_FATAL, "Unknown pixel format requested: %s.\n", frame_pix_fmt);
1376             exit_program(1);
1377         }
1378         st->sample_aspect_ratio = video_enc->sample_aspect_ratio;
1379
1380         if (intra_only)
1381             video_enc->gop_size = 0;
1382         MATCH_PER_STREAM_OPT(intra_matrices, str, intra_matrix, oc, st);
1383         if (intra_matrix) {
1384             if (!(video_enc->intra_matrix = av_mallocz(sizeof(*video_enc->intra_matrix) * 64))) {
1385                 av_log(NULL, AV_LOG_FATAL, "Could not allocate memory for intra matrix.\n");
1386                 exit_program(1);
1387             }
1388             parse_matrix_coeffs(video_enc->intra_matrix, intra_matrix);
1389         }
1390         MATCH_PER_STREAM_OPT(chroma_intra_matrices, str, chroma_intra_matrix, oc, st);
1391         if (chroma_intra_matrix) {
1392             uint16_t *p = av_mallocz(sizeof(*video_enc->chroma_intra_matrix) * 64);
1393             if (!p) {
1394                 av_log(NULL, AV_LOG_FATAL, "Could not allocate memory for intra matrix.\n");
1395                 exit_program(1);
1396             }
1397             av_codec_set_chroma_intra_matrix(video_enc, p);
1398             parse_matrix_coeffs(p, chroma_intra_matrix);
1399         }
1400         MATCH_PER_STREAM_OPT(inter_matrices, str, inter_matrix, oc, st);
1401         if (inter_matrix) {
1402             if (!(video_enc->inter_matrix = av_mallocz(sizeof(*video_enc->inter_matrix) * 64))) {
1403                 av_log(NULL, AV_LOG_FATAL, "Could not allocate memory for inter matrix.\n");
1404                 exit_program(1);
1405             }
1406             parse_matrix_coeffs(video_enc->inter_matrix, inter_matrix);
1407         }
1408
1409         MATCH_PER_STREAM_OPT(rc_overrides, str, p, oc, st);
1410         for (i = 0; p; i++) {
1411             int start, end, q;
1412             int e = sscanf(p, "%d,%d,%d", &start, &end, &q);
1413             if (e != 3) {
1414                 av_log(NULL, AV_LOG_FATAL, "error parsing rc_override\n");
1415                 exit_program(1);
1416             }
1417             video_enc->rc_override =
1418                 av_realloc_array(video_enc->rc_override,
1419                                  i + 1, sizeof(RcOverride));
1420             if (!video_enc->rc_override) {
1421                 av_log(NULL, AV_LOG_FATAL, "Could not (re)allocate memory for rc_override.\n");
1422                 exit_program(1);
1423             }
1424             video_enc->rc_override[i].start_frame = start;
1425             video_enc->rc_override[i].end_frame   = end;
1426             if (q > 0) {
1427                 video_enc->rc_override[i].qscale         = q;
1428                 video_enc->rc_override[i].quality_factor = 1.0;
1429             }
1430             else {
1431                 video_enc->rc_override[i].qscale         = 0;
1432                 video_enc->rc_override[i].quality_factor = -q/100.0;
1433             }
1434             p = strchr(p, '/');
1435             if (p) p++;
1436         }
1437         video_enc->rc_override_count = i;
1438
1439         if (do_psnr)
1440             video_enc->flags|= CODEC_FLAG_PSNR;
1441
1442         /* two pass mode */
1443         MATCH_PER_STREAM_OPT(pass, i, do_pass, oc, st);
1444         if (do_pass) {
1445             if (do_pass & 1) {
1446                 video_enc->flags |= CODEC_FLAG_PASS1;
1447                 av_dict_set(&ost->encoder_opts, "flags", "+pass1", AV_DICT_APPEND);
1448             }
1449             if (do_pass & 2) {
1450                 video_enc->flags |= CODEC_FLAG_PASS2;
1451                 av_dict_set(&ost->encoder_opts, "flags", "+pass2", AV_DICT_APPEND);
1452             }
1453         }
1454
1455         MATCH_PER_STREAM_OPT(passlogfiles, str, ost->logfile_prefix, oc, st);
1456         if (ost->logfile_prefix &&
1457             !(ost->logfile_prefix = av_strdup(ost->logfile_prefix)))
1458             exit_program(1);
1459
1460         MATCH_PER_STREAM_OPT(forced_key_frames, str, ost->forced_keyframes, oc, st);
1461         if (ost->forced_keyframes)
1462             ost->forced_keyframes = av_strdup(ost->forced_keyframes);
1463
1464         MATCH_PER_STREAM_OPT(force_fps, i, ost->force_fps, oc, st);
1465
1466         ost->top_field_first = -1;
1467         MATCH_PER_STREAM_OPT(top_field_first, i, ost->top_field_first, oc, st);
1468
1469
1470         ost->avfilter = get_ost_filters(o, oc, ost);
1471         if (!ost->avfilter)
1472             exit_program(1);
1473     } else {
1474         MATCH_PER_STREAM_OPT(copy_initial_nonkeyframes, i, ost->copy_initial_nonkeyframes, oc ,st);
1475     }
1476
1477     if (ost->stream_copy)
1478         check_streamcopy_filters(o, oc, ost, AVMEDIA_TYPE_VIDEO);
1479
1480     return ost;
1481 }
1482
1483 static OutputStream *new_audio_stream(OptionsContext *o, AVFormatContext *oc, int source_index)
1484 {
1485     int n;
1486     AVStream *st;
1487     OutputStream *ost;
1488     AVCodecContext *audio_enc;
1489
1490     ost = new_output_stream(o, oc, AVMEDIA_TYPE_AUDIO, source_index);
1491     st  = ost->st;
1492
1493     audio_enc = ost->enc_ctx;
1494     audio_enc->codec_type = AVMEDIA_TYPE_AUDIO;
1495
1496     MATCH_PER_STREAM_OPT(filter_scripts, str, ost->filters_script, oc, st);
1497     MATCH_PER_STREAM_OPT(filters,        str, ost->filters,        oc, st);
1498
1499     if (!ost->stream_copy) {
1500         char *sample_fmt = NULL;
1501
1502         MATCH_PER_STREAM_OPT(audio_channels, i, audio_enc->channels, oc, st);
1503
1504         MATCH_PER_STREAM_OPT(sample_fmts, str, sample_fmt, oc, st);
1505         if (sample_fmt &&
1506             (audio_enc->sample_fmt = av_get_sample_fmt(sample_fmt)) == AV_SAMPLE_FMT_NONE) {
1507             av_log(NULL, AV_LOG_FATAL, "Invalid sample format '%s'\n", sample_fmt);
1508             exit_program(1);
1509         }
1510
1511         MATCH_PER_STREAM_OPT(audio_sample_rate, i, audio_enc->sample_rate, oc, st);
1512
1513         MATCH_PER_STREAM_OPT(apad, str, ost->apad, oc, st);
1514         ost->apad = av_strdup(ost->apad);
1515
1516         ost->avfilter = get_ost_filters(o, oc, ost);
1517         if (!ost->avfilter)
1518             exit_program(1);
1519
1520         /* check for channel mapping for this audio stream */
1521         for (n = 0; n < o->nb_audio_channel_maps; n++) {
1522             AudioChannelMap *map = &o->audio_channel_maps[n];
1523             if ((map->ofile_idx   == -1 || ost->file_index == map->ofile_idx) &&
1524                 (map->ostream_idx == -1 || ost->st->index  == map->ostream_idx)) {
1525                 InputStream *ist;
1526
1527                 if (map->channel_idx == -1) {
1528                     ist = NULL;
1529                 } else if (ost->source_index < 0) {
1530                     av_log(NULL, AV_LOG_FATAL, "Cannot determine input stream for channel mapping %d.%d\n",
1531                            ost->file_index, ost->st->index);
1532                     continue;
1533                 } else {
1534                     ist = input_streams[ost->source_index];
1535                 }
1536
1537                 if (!ist || (ist->file_index == map->file_idx && ist->st->index == map->stream_idx)) {
1538                     if (av_reallocp_array(&ost->audio_channels_map,
1539                                           ost->audio_channels_mapped + 1,
1540                                           sizeof(*ost->audio_channels_map)
1541                                           ) < 0 )
1542                         exit_program(1);
1543
1544                     ost->audio_channels_map[ost->audio_channels_mapped++] = map->channel_idx;
1545                 }
1546             }
1547         }
1548     }
1549
1550     if (ost->stream_copy)
1551         check_streamcopy_filters(o, oc, ost, AVMEDIA_TYPE_AUDIO);
1552
1553     return ost;
1554 }
1555
1556 static OutputStream *new_data_stream(OptionsContext *o, AVFormatContext *oc, int source_index)
1557 {
1558     OutputStream *ost;
1559
1560     ost = new_output_stream(o, oc, AVMEDIA_TYPE_DATA, source_index);
1561     if (!ost->stream_copy) {
1562         av_log(NULL, AV_LOG_FATAL, "Data stream encoding not supported yet (only streamcopy)\n");
1563         exit_program(1);
1564     }
1565
1566     return ost;
1567 }
1568
1569 static OutputStream *new_attachment_stream(OptionsContext *o, AVFormatContext *oc, int source_index)
1570 {
1571     OutputStream *ost = new_output_stream(o, oc, AVMEDIA_TYPE_ATTACHMENT, source_index);
1572     ost->stream_copy = 1;
1573     ost->finished    = 1;
1574     return ost;
1575 }
1576
1577 static OutputStream *new_subtitle_stream(OptionsContext *o, AVFormatContext *oc, int source_index)
1578 {
1579     AVStream *st;
1580     OutputStream *ost;
1581     AVCodecContext *subtitle_enc;
1582
1583     ost = new_output_stream(o, oc, AVMEDIA_TYPE_SUBTITLE, source_index);
1584     st  = ost->st;
1585     subtitle_enc = ost->enc_ctx;
1586
1587     subtitle_enc->codec_type = AVMEDIA_TYPE_SUBTITLE;
1588
1589     MATCH_PER_STREAM_OPT(copy_initial_nonkeyframes, i, ost->copy_initial_nonkeyframes, oc, st);
1590
1591     if (!ost->stream_copy) {
1592         char *frame_size = NULL;
1593
1594         MATCH_PER_STREAM_OPT(frame_sizes, str, frame_size, oc, st);
1595         if (frame_size && av_parse_video_size(&subtitle_enc->width, &subtitle_enc->height, frame_size) < 0) {
1596             av_log(NULL, AV_LOG_FATAL, "Invalid frame size: %s.\n", frame_size);
1597             exit_program(1);
1598         }
1599     }
1600
1601     return ost;
1602 }
1603
1604 /* arg format is "output-stream-index:streamid-value". */
1605 static int opt_streamid(void *optctx, const char *opt, const char *arg)
1606 {
1607     OptionsContext *o = optctx;
1608     int idx;
1609     char *p;
1610     char idx_str[16];
1611
1612     av_strlcpy(idx_str, arg, sizeof(idx_str));
1613     p = strchr(idx_str, ':');
1614     if (!p) {
1615         av_log(NULL, AV_LOG_FATAL,
1616                "Invalid value '%s' for option '%s', required syntax is 'index:value'\n",
1617                arg, opt);
1618         exit_program(1);
1619     }
1620     *p++ = '\0';
1621     idx = parse_number_or_die(opt, idx_str, OPT_INT, 0, MAX_STREAMS-1);
1622     o->streamid_map = grow_array(o->streamid_map, sizeof(*o->streamid_map), &o->nb_streamid_map, idx+1);
1623     o->streamid_map[idx] = parse_number_or_die(opt, p, OPT_INT, 0, INT_MAX);
1624     return 0;
1625 }
1626
1627 static int copy_chapters(InputFile *ifile, OutputFile *ofile, int copy_metadata)
1628 {
1629     AVFormatContext *is = ifile->ctx;
1630     AVFormatContext *os = ofile->ctx;
1631     AVChapter **tmp;
1632     int i;
1633
1634     tmp = av_realloc_f(os->chapters, is->nb_chapters + os->nb_chapters, sizeof(*os->chapters));
1635     if (!tmp)
1636         return AVERROR(ENOMEM);
1637     os->chapters = tmp;
1638
1639     for (i = 0; i < is->nb_chapters; i++) {
1640         AVChapter *in_ch = is->chapters[i], *out_ch;
1641         int64_t start_time = (ofile->start_time == AV_NOPTS_VALUE) ? 0 : ofile->start_time;
1642         int64_t ts_off   = av_rescale_q(start_time - ifile->ts_offset,
1643                                        AV_TIME_BASE_Q, in_ch->time_base);
1644         int64_t rt       = (ofile->recording_time == INT64_MAX) ? INT64_MAX :
1645                            av_rescale_q(ofile->recording_time, AV_TIME_BASE_Q, in_ch->time_base);
1646
1647
1648         if (in_ch->end < ts_off)
1649             continue;
1650         if (rt != INT64_MAX && in_ch->start > rt + ts_off)
1651             break;
1652
1653         out_ch = av_mallocz(sizeof(AVChapter));
1654         if (!out_ch)
1655             return AVERROR(ENOMEM);
1656
1657         out_ch->id        = in_ch->id;
1658         out_ch->time_base = in_ch->time_base;
1659         out_ch->start     = FFMAX(0,  in_ch->start - ts_off);
1660         out_ch->end       = FFMIN(rt, in_ch->end   - ts_off);
1661
1662         if (copy_metadata)
1663             av_dict_copy(&out_ch->metadata, in_ch->metadata, 0);
1664
1665         os->chapters[os->nb_chapters++] = out_ch;
1666     }
1667     return 0;
1668 }
1669
1670 static int read_ffserver_streams(OptionsContext *o, AVFormatContext *s, const char *filename)
1671 {
1672     int i, err;
1673     AVFormatContext *ic = avformat_alloc_context();
1674
1675     ic->interrupt_callback = int_cb;
1676     err = avformat_open_input(&ic, filename, NULL, NULL);
1677     if (err < 0)
1678         return err;
1679     /* copy stream format */
1680     for(i=0;i<ic->nb_streams;i++) {
1681         AVStream *st;
1682         OutputStream *ost;
1683         AVCodec *codec;
1684         const char *enc_config;
1685
1686         codec = avcodec_find_encoder(ic->streams[i]->codec->codec_id);
1687         if (!codec) {
1688             av_log(s, AV_LOG_ERROR, "no encoder found for codec id %i\n", ic->streams[i]->codec->codec_id);
1689             return AVERROR(EINVAL);
1690         }
1691         if (codec->type == AVMEDIA_TYPE_AUDIO)
1692             opt_audio_codec(o, "c:a", codec->name);
1693         else if (codec->type == AVMEDIA_TYPE_VIDEO)
1694             opt_video_codec(o, "c:v", codec->name);
1695         ost   = new_output_stream(o, s, codec->type, -1);
1696         st    = ost->st;
1697
1698         avcodec_get_context_defaults3(st->codec, codec);
1699         enc_config = av_stream_get_recommended_encoder_configuration(ic->streams[i]);
1700         if (enc_config) {
1701             AVDictionary *opts = NULL;
1702             av_dict_parse_string(&opts, enc_config, "=", ",", 0);
1703             av_opt_set_dict2(st->codec, &opts, AV_OPT_SEARCH_CHILDREN);
1704             av_dict_free(&opts);
1705         }
1706
1707         if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO && !ost->stream_copy)
1708             choose_sample_fmt(st, codec);
1709         else if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO && !ost->stream_copy)
1710             choose_pixel_fmt(st, st->codec, codec, st->codec->pix_fmt);
1711         avcodec_copy_context(ost->enc_ctx, st->codec);
1712         if (enc_config)
1713             av_dict_parse_string(&ost->encoder_opts, enc_config, "=", ",", 0);
1714     }
1715
1716     avformat_close_input(&ic);
1717     return err;
1718 }
1719
1720 static void init_output_filter(OutputFilter *ofilter, OptionsContext *o,
1721                                AVFormatContext *oc)
1722 {
1723     OutputStream *ost;
1724
1725     switch (avfilter_pad_get_type(ofilter->out_tmp->filter_ctx->output_pads,
1726                                   ofilter->out_tmp->pad_idx)) {
1727     case AVMEDIA_TYPE_VIDEO: ost = new_video_stream(o, oc, -1); break;
1728     case AVMEDIA_TYPE_AUDIO: ost = new_audio_stream(o, oc, -1); break;
1729     default:
1730         av_log(NULL, AV_LOG_FATAL, "Only video and audio filters are supported "
1731                "currently.\n");
1732         exit_program(1);
1733     }
1734
1735     ost->source_index = -1;
1736     ost->filter       = ofilter;
1737
1738     ofilter->ost      = ost;
1739
1740     if (ost->stream_copy) {
1741         av_log(NULL, AV_LOG_ERROR, "Streamcopy requested for output stream %d:%d, "
1742                "which is fed from a complex filtergraph. Filtering and streamcopy "
1743                "cannot be used together.\n", ost->file_index, ost->index);
1744         exit_program(1);
1745     }
1746
1747     if (ost->avfilter && (ost->filters || ost->filters_script)) {
1748         const char *opt = ost->filters ? "-vf/-af/-filter" : "-filter_script";
1749         av_log(NULL, AV_LOG_ERROR,
1750                "%s '%s' was specified through the %s option "
1751                "for output stream %d:%d, which is fed from a complex filtergraph.\n"
1752                "%s and -filter_complex cannot be used together for the same stream.\n",
1753                ost->filters ? "Filtergraph" : "Filtergraph script",
1754                ost->filters ? ost->filters : ost->filters_script,
1755                opt, ost->file_index, ost->index, opt);
1756         exit_program(1);
1757     }
1758
1759     if (configure_output_filter(ofilter->graph, ofilter, ofilter->out_tmp) < 0) {
1760         av_log(NULL, AV_LOG_FATAL, "Error configuring filter.\n");
1761         exit_program(1);
1762     }
1763     avfilter_inout_free(&ofilter->out_tmp);
1764 }
1765
1766 static int configure_complex_filters(void)
1767 {
1768     int i, ret = 0;
1769
1770     for (i = 0; i < nb_filtergraphs; i++)
1771         if (!filtergraphs[i]->graph &&
1772             (ret = configure_filtergraph(filtergraphs[i])) < 0)
1773             return ret;
1774     return 0;
1775 }
1776
1777 static int open_output_file(OptionsContext *o, const char *filename)
1778 {
1779     AVFormatContext *oc;
1780     int i, j, err;
1781     AVOutputFormat *file_oformat;
1782     OutputFile *of;
1783     OutputStream *ost;
1784     InputStream  *ist;
1785     AVDictionary *unused_opts = NULL;
1786     AVDictionaryEntry *e = NULL;
1787
1788     if (configure_complex_filters() < 0) {
1789         av_log(NULL, AV_LOG_FATAL, "Error configuring filters.\n");
1790         exit_program(1);
1791     }
1792
1793     if (o->stop_time != INT64_MAX && o->recording_time != INT64_MAX) {
1794         o->stop_time = INT64_MAX;
1795         av_log(NULL, AV_LOG_WARNING, "-t and -to cannot be used together; using -t.\n");
1796     }
1797
1798     if (o->stop_time != INT64_MAX && o->recording_time == INT64_MAX) {
1799         int64_t start_time = o->start_time == AV_NOPTS_VALUE ? 0 : o->start_time;
1800         if (o->stop_time <= start_time) {
1801             av_log(NULL, AV_LOG_ERROR, "-to value smaller than -ss; aborting.\n");
1802             exit_program(1);
1803         } else {
1804             o->recording_time = o->stop_time - start_time;
1805         }
1806     }
1807
1808     GROW_ARRAY(output_files, nb_output_files);
1809     of = av_mallocz(sizeof(*of));
1810     if (!of)
1811         exit_program(1);
1812     output_files[nb_output_files - 1] = of;
1813
1814     of->ost_index      = nb_output_streams;
1815     of->recording_time = o->recording_time;
1816     of->start_time     = o->start_time;
1817     of->limit_filesize = o->limit_filesize;
1818     of->shortest       = o->shortest;
1819     av_dict_copy(&of->opts, o->g->format_opts, 0);
1820
1821     if (!strcmp(filename, "-"))
1822         filename = "pipe:";
1823
1824     err = avformat_alloc_output_context2(&oc, NULL, o->format, filename);
1825     if (!oc) {
1826         print_error(filename, err);
1827         exit_program(1);
1828     }
1829
1830     of->ctx = oc;
1831     if (o->recording_time != INT64_MAX)
1832         oc->duration = o->recording_time;
1833
1834     file_oformat= oc->oformat;
1835     oc->interrupt_callback = int_cb;
1836
1837     /* create streams for all unlabeled output pads */
1838     for (i = 0; i < nb_filtergraphs; i++) {
1839         FilterGraph *fg = filtergraphs[i];
1840         for (j = 0; j < fg->nb_outputs; j++) {
1841             OutputFilter *ofilter = fg->outputs[j];
1842
1843             if (!ofilter->out_tmp || ofilter->out_tmp->name)
1844                 continue;
1845
1846             switch (avfilter_pad_get_type(ofilter->out_tmp->filter_ctx->output_pads,
1847                                           ofilter->out_tmp->pad_idx)) {
1848             case AVMEDIA_TYPE_VIDEO:    o->video_disable    = 1; break;
1849             case AVMEDIA_TYPE_AUDIO:    o->audio_disable    = 1; break;
1850             case AVMEDIA_TYPE_SUBTITLE: o->subtitle_disable = 1; break;
1851             }
1852             init_output_filter(ofilter, o, oc);
1853         }
1854     }
1855
1856     /* ffserver seeking with date=... needs a date reference */
1857     if (!strcmp(file_oformat->name, "ffm") &&
1858         av_strstart(filename, "http:", NULL)) {
1859         int err = parse_option(o, "metadata", "creation_time=now", options);
1860         if (err < 0) {
1861             print_error(filename, err);
1862             exit_program(1);
1863         }
1864     }
1865
1866     if (!strcmp(file_oformat->name, "ffm") && !override_ffserver &&
1867         av_strstart(filename, "http:", NULL)) {
1868         int j;
1869         /* special case for files sent to ffserver: we get the stream
1870            parameters from ffserver */
1871         int err = read_ffserver_streams(o, oc, filename);
1872         if (err < 0) {
1873             print_error(filename, err);
1874             exit_program(1);
1875         }
1876         for(j = nb_output_streams - oc->nb_streams; j < nb_output_streams; j++) {
1877             ost = output_streams[j];
1878             for (i = 0; i < nb_input_streams; i++) {
1879                 ist = input_streams[i];
1880                 if(ist->st->codec->codec_type == ost->st->codec->codec_type){
1881                     ost->sync_ist= ist;
1882                     ost->source_index= i;
1883                     if(ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO) ost->avfilter = av_strdup("anull");
1884                     if(ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO) ost->avfilter = av_strdup("null");
1885                     ist->discard = 0;
1886                     ist->st->discard = ist->user_set_discard;
1887                     break;
1888                 }
1889             }
1890             if(!ost->sync_ist){
1891                 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));
1892                 exit_program(1);
1893             }
1894         }
1895     } else if (!o->nb_stream_maps) {
1896         char *subtitle_codec_name = NULL;
1897         /* pick the "best" stream of each type */
1898
1899         /* video: highest resolution */
1900         if (!o->video_disable && av_guess_codec(oc->oformat, NULL, filename, NULL, AVMEDIA_TYPE_VIDEO) != AV_CODEC_ID_NONE) {
1901             int area = 0, idx = -1;
1902             int qcr = avformat_query_codec(oc->oformat, oc->oformat->video_codec, 0);
1903             for (i = 0; i < nb_input_streams; i++) {
1904                 int new_area;
1905                 ist = input_streams[i];
1906                 new_area = ist->st->codec->width * ist->st->codec->height;
1907                 if((qcr!=MKTAG('A', 'P', 'I', 'C')) && (ist->st->disposition & AV_DISPOSITION_ATTACHED_PIC))
1908                     new_area = 1;
1909                 if (ist->st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
1910                     new_area > area) {
1911                     if((qcr==MKTAG('A', 'P', 'I', 'C')) && !(ist->st->disposition & AV_DISPOSITION_ATTACHED_PIC))
1912                         continue;
1913                     area = new_area;
1914                     idx = i;
1915                 }
1916             }
1917             if (idx >= 0)
1918                 new_video_stream(o, oc, idx);
1919         }
1920
1921         /* audio: most channels */
1922         if (!o->audio_disable && av_guess_codec(oc->oformat, NULL, filename, NULL, AVMEDIA_TYPE_AUDIO) != AV_CODEC_ID_NONE) {
1923             int channels = 0, idx = -1;
1924             for (i = 0; i < nb_input_streams; i++) {
1925                 ist = input_streams[i];
1926                 if (ist->st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
1927                     ist->st->codec->channels > channels) {
1928                     channels = ist->st->codec->channels;
1929                     idx = i;
1930                 }
1931             }
1932             if (idx >= 0)
1933                 new_audio_stream(o, oc, idx);
1934         }
1935
1936         /* subtitles: pick first */
1937         MATCH_PER_TYPE_OPT(codec_names, str, subtitle_codec_name, oc, "s");
1938         if (!o->subtitle_disable && (avcodec_find_encoder(oc->oformat->subtitle_codec) || subtitle_codec_name)) {
1939             for (i = 0; i < nb_input_streams; i++)
1940                 if (input_streams[i]->st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
1941                     AVCodecDescriptor const *input_descriptor =
1942                         avcodec_descriptor_get(input_streams[i]->st->codec->codec_id);
1943                     AVCodecDescriptor const *output_descriptor = NULL;
1944                     AVCodec const *output_codec =
1945                         avcodec_find_encoder(oc->oformat->subtitle_codec);
1946                     int input_props = 0, output_props = 0;
1947                     if (output_codec)
1948                         output_descriptor = avcodec_descriptor_get(output_codec->id);
1949                     if (input_descriptor)
1950                         input_props = input_descriptor->props & (AV_CODEC_PROP_TEXT_SUB | AV_CODEC_PROP_BITMAP_SUB);
1951                     if (output_descriptor)
1952                         output_props = output_descriptor->props & (AV_CODEC_PROP_TEXT_SUB | AV_CODEC_PROP_BITMAP_SUB);
1953                     if (subtitle_codec_name ||
1954                         input_props & output_props ||
1955                         // Map dvb teletext which has neither property to any output subtitle encoder
1956                         input_descriptor && output_descriptor &&
1957                         (!input_descriptor->props ||
1958                          !output_descriptor->props)) {
1959                         new_subtitle_stream(o, oc, i);
1960                         break;
1961                     }
1962                 }
1963         }
1964         /* Data only if codec id match */
1965         if (!o->data_disable ) {
1966             enum AVCodecID codec_id = av_guess_codec(oc->oformat, NULL, filename, NULL, AVMEDIA_TYPE_DATA);
1967             for (i = 0; codec_id != AV_CODEC_ID_NONE && i < nb_input_streams; i++) {
1968                 if (input_streams[i]->st->codec->codec_type == AVMEDIA_TYPE_DATA
1969                     && input_streams[i]->st->codec->codec_id == codec_id )
1970                     new_data_stream(o, oc, i);
1971             }
1972         }
1973     } else {
1974         for (i = 0; i < o->nb_stream_maps; i++) {
1975             StreamMap *map = &o->stream_maps[i];
1976
1977             if (map->disabled)
1978                 continue;
1979
1980             if (map->linklabel) {
1981                 FilterGraph *fg;
1982                 OutputFilter *ofilter = NULL;
1983                 int j, k;
1984
1985                 for (j = 0; j < nb_filtergraphs; j++) {
1986                     fg = filtergraphs[j];
1987                     for (k = 0; k < fg->nb_outputs; k++) {
1988                         AVFilterInOut *out = fg->outputs[k]->out_tmp;
1989                         if (out && !strcmp(out->name, map->linklabel)) {
1990                             ofilter = fg->outputs[k];
1991                             goto loop_end;
1992                         }
1993                     }
1994                 }
1995 loop_end:
1996                 if (!ofilter) {
1997                     av_log(NULL, AV_LOG_FATAL, "Output with label '%s' does not exist "
1998                            "in any defined filter graph, or was already used elsewhere.\n", map->linklabel);
1999                     exit_program(1);
2000                 }
2001                 init_output_filter(ofilter, o, oc);
2002             } else {
2003                 int src_idx = input_files[map->file_index]->ist_index + map->stream_index;
2004
2005                 ist = input_streams[input_files[map->file_index]->ist_index + map->stream_index];
2006                 if(o->subtitle_disable && ist->st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE)
2007                     continue;
2008                 if(o->   audio_disable && ist->st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
2009                     continue;
2010                 if(o->   video_disable && ist->st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
2011                     continue;
2012                 if(o->    data_disable && ist->st->codec->codec_type == AVMEDIA_TYPE_DATA)
2013                     continue;
2014
2015                 switch (ist->st->codec->codec_type) {
2016                 case AVMEDIA_TYPE_VIDEO:      ost = new_video_stream     (o, oc, src_idx); break;
2017                 case AVMEDIA_TYPE_AUDIO:      ost = new_audio_stream     (o, oc, src_idx); break;
2018                 case AVMEDIA_TYPE_SUBTITLE:   ost = new_subtitle_stream  (o, oc, src_idx); break;
2019                 case AVMEDIA_TYPE_DATA:       ost = new_data_stream      (o, oc, src_idx); break;
2020                 case AVMEDIA_TYPE_ATTACHMENT: ost = new_attachment_stream(o, oc, src_idx); break;
2021                 default:
2022                     av_log(NULL, ignore_unknown_streams ? AV_LOG_WARNING : AV_LOG_FATAL,
2023                            "Cannot map stream #%d:%d - unsupported type.\n",
2024                            map->file_index, map->stream_index);
2025                     if (!ignore_unknown_streams) {
2026                         av_log(NULL, AV_LOG_FATAL,
2027                                "If you want unsupported types ignored instead "
2028                                "of failing, please use the -ignore_unknown option\n");
2029                         exit_program(1);
2030                     }
2031                 }
2032             }
2033         }
2034     }
2035
2036     /* handle attached files */
2037     for (i = 0; i < o->nb_attachments; i++) {
2038         AVIOContext *pb;
2039         uint8_t *attachment;
2040         const char *p;
2041         int64_t len;
2042
2043         if ((err = avio_open2(&pb, o->attachments[i], AVIO_FLAG_READ, &int_cb, NULL)) < 0) {
2044             av_log(NULL, AV_LOG_FATAL, "Could not open attachment file %s.\n",
2045                    o->attachments[i]);
2046             exit_program(1);
2047         }
2048         if ((len = avio_size(pb)) <= 0) {
2049             av_log(NULL, AV_LOG_FATAL, "Could not get size of the attachment %s.\n",
2050                    o->attachments[i]);
2051             exit_program(1);
2052         }
2053         if (!(attachment = av_malloc(len))) {
2054             av_log(NULL, AV_LOG_FATAL, "Attachment %s too large to fit into memory.\n",
2055                    o->attachments[i]);
2056             exit_program(1);
2057         }
2058         avio_read(pb, attachment, len);
2059
2060         ost = new_attachment_stream(o, oc, -1);
2061         ost->stream_copy               = 0;
2062         ost->attachment_filename       = o->attachments[i];
2063         ost->finished                  = 1;
2064         ost->st->codec->extradata      = attachment;
2065         ost->st->codec->extradata_size = len;
2066
2067         p = strrchr(o->attachments[i], '/');
2068         av_dict_set(&ost->st->metadata, "filename", (p && *p) ? p + 1 : o->attachments[i], AV_DICT_DONT_OVERWRITE);
2069         avio_closep(&pb);
2070     }
2071
2072     for (i = nb_output_streams - oc->nb_streams; i < nb_output_streams; i++) { //for all streams of this output file
2073         AVDictionaryEntry *e;
2074         ost = output_streams[i];
2075
2076         if ((ost->stream_copy || ost->attachment_filename)
2077             && (e = av_dict_get(o->g->codec_opts, "flags", NULL, AV_DICT_IGNORE_SUFFIX))
2078             && (!e->key[5] || check_stream_specifier(oc, ost->st, e->key+6)))
2079             if (av_opt_set(ost->st->codec, "flags", e->value, 0) < 0)
2080                 exit_program(1);
2081     }
2082
2083     /* check if all codec options have been used */
2084     unused_opts = strip_specifiers(o->g->codec_opts);
2085     for (i = of->ost_index; i < nb_output_streams; i++) {
2086         e = NULL;
2087         while ((e = av_dict_get(output_streams[i]->encoder_opts, "", e,
2088                                 AV_DICT_IGNORE_SUFFIX)))
2089             av_dict_set(&unused_opts, e->key, NULL, 0);
2090     }
2091
2092     e = NULL;
2093     while ((e = av_dict_get(unused_opts, "", e, AV_DICT_IGNORE_SUFFIX))) {
2094         const AVClass *class = avcodec_get_class();
2095         const AVOption *option = av_opt_find(&class, e->key, NULL, 0,
2096                                              AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ);
2097         const AVClass *fclass = avformat_get_class();
2098         const AVOption *foption = av_opt_find(&fclass, e->key, NULL, 0,
2099                                               AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ);
2100         if (!option || foption)
2101             continue;
2102
2103
2104         if (!(option->flags & AV_OPT_FLAG_ENCODING_PARAM)) {
2105             av_log(NULL, AV_LOG_ERROR, "Codec AVOption %s (%s) specified for "
2106                    "output file #%d (%s) is not an encoding option.\n", e->key,
2107                    option->help ? option->help : "", nb_output_files - 1,
2108                    filename);
2109             exit_program(1);
2110         }
2111
2112         // gop_timecode is injected by generic code but not always used
2113         if (!strcmp(e->key, "gop_timecode"))
2114             continue;
2115
2116         av_log(NULL, AV_LOG_WARNING, "Codec AVOption %s (%s) specified for "
2117                "output file #%d (%s) has not been used for any stream. The most "
2118                "likely reason is either wrong type (e.g. a video option with "
2119                "no video streams) or that it is a private option of some encoder "
2120                "which was not actually used for any stream.\n", e->key,
2121                option->help ? option->help : "", nb_output_files - 1, filename);
2122     }
2123     av_dict_free(&unused_opts);
2124
2125     /* check filename in case of an image number is expected */
2126     if (oc->oformat->flags & AVFMT_NEEDNUMBER) {
2127         if (!av_filename_number_test(oc->filename)) {
2128             print_error(oc->filename, AVERROR(EINVAL));
2129             exit_program(1);
2130         }
2131     }
2132
2133     if (!(oc->oformat->flags & AVFMT_NOSTREAMS) && !input_stream_potentially_available) {
2134         av_log(NULL, AV_LOG_ERROR,
2135                "No input streams but output needs an input stream\n");
2136         exit_program(1);
2137     }
2138
2139     if (!(oc->oformat->flags & AVFMT_NOFILE)) {
2140         /* test if it already exists to avoid losing precious files */
2141         assert_file_overwrite(filename);
2142
2143         /* open the file */
2144         if ((err = avio_open2(&oc->pb, filename, AVIO_FLAG_WRITE,
2145                               &oc->interrupt_callback,
2146                               &of->opts)) < 0) {
2147             print_error(filename, err);
2148             exit_program(1);
2149         }
2150     } else if (strcmp(oc->oformat->name, "image2")==0 && !av_filename_number_test(filename))
2151         assert_file_overwrite(filename);
2152
2153     if (o->mux_preload) {
2154         av_dict_set_int(&of->opts, "preload", o->mux_preload*AV_TIME_BASE, 0);
2155     }
2156     oc->max_delay = (int)(o->mux_max_delay * AV_TIME_BASE);
2157
2158     /* copy metadata */
2159     for (i = 0; i < o->nb_metadata_map; i++) {
2160         char *p;
2161         int in_file_index = strtol(o->metadata_map[i].u.str, &p, 0);
2162
2163         if (in_file_index >= nb_input_files) {
2164             av_log(NULL, AV_LOG_FATAL, "Invalid input file index %d while processing metadata maps\n", in_file_index);
2165             exit_program(1);
2166         }
2167         copy_metadata(o->metadata_map[i].specifier, *p ? p + 1 : p, oc,
2168                       in_file_index >= 0 ?
2169                       input_files[in_file_index]->ctx : NULL, o);
2170     }
2171
2172     /* copy chapters */
2173     if (o->chapters_input_file >= nb_input_files) {
2174         if (o->chapters_input_file == INT_MAX) {
2175             /* copy chapters from the first input file that has them*/
2176             o->chapters_input_file = -1;
2177             for (i = 0; i < nb_input_files; i++)
2178                 if (input_files[i]->ctx->nb_chapters) {
2179                     o->chapters_input_file = i;
2180                     break;
2181                 }
2182         } else {
2183             av_log(NULL, AV_LOG_FATAL, "Invalid input file index %d in chapter mapping.\n",
2184                    o->chapters_input_file);
2185             exit_program(1);
2186         }
2187     }
2188     if (o->chapters_input_file >= 0)
2189         copy_chapters(input_files[o->chapters_input_file], of,
2190                       !o->metadata_chapters_manual);
2191
2192     /* copy global metadata by default */
2193     if (!o->metadata_global_manual && nb_input_files){
2194         av_dict_copy(&oc->metadata, input_files[0]->ctx->metadata,
2195                      AV_DICT_DONT_OVERWRITE);
2196         if(o->recording_time != INT64_MAX)
2197             av_dict_set(&oc->metadata, "duration", NULL, 0);
2198         av_dict_set(&oc->metadata, "creation_time", NULL, 0);
2199     }
2200     if (!o->metadata_streams_manual)
2201         for (i = of->ost_index; i < nb_output_streams; i++) {
2202             InputStream *ist;
2203             if (output_streams[i]->source_index < 0)         /* this is true e.g. for attached files */
2204                 continue;
2205             ist = input_streams[output_streams[i]->source_index];
2206             av_dict_copy(&output_streams[i]->st->metadata, ist->st->metadata, AV_DICT_DONT_OVERWRITE);
2207             if (!output_streams[i]->stream_copy) {
2208                 av_dict_set(&output_streams[i]->st->metadata, "encoder", NULL, 0);
2209                 if (ist->autorotate)
2210                     av_dict_set(&output_streams[i]->st->metadata, "rotate", NULL, 0);
2211             }
2212         }
2213
2214     /* process manually set metadata */
2215     for (i = 0; i < o->nb_metadata; i++) {
2216         AVDictionary **m;
2217         char type, *val;
2218         const char *stream_spec;
2219         int index = 0, j, ret = 0;
2220
2221         val = strchr(o->metadata[i].u.str, '=');
2222         if (!val) {
2223             av_log(NULL, AV_LOG_FATAL, "No '=' character in metadata string %s.\n",
2224                    o->metadata[i].u.str);
2225             exit_program(1);
2226         }
2227         *val++ = 0;
2228
2229         parse_meta_type(o->metadata[i].specifier, &type, &index, &stream_spec);
2230         if (type == 's') {
2231             for (j = 0; j < oc->nb_streams; j++) {
2232                 ost = output_streams[nb_output_streams - oc->nb_streams + j];
2233                 if ((ret = check_stream_specifier(oc, oc->streams[j], stream_spec)) > 0) {
2234                     av_dict_set(&oc->streams[j]->metadata, o->metadata[i].u.str, *val ? val : NULL, 0);
2235                     if (!strcmp(o->metadata[i].u.str, "rotate")) {
2236                         ost->rotate_overridden = 1;
2237                     }
2238                 } else if (ret < 0)
2239                     exit_program(1);
2240             }
2241         }
2242         else {
2243             switch (type) {
2244             case 'g':
2245                 m = &oc->metadata;
2246                 break;
2247             case 'c':
2248                 if (index < 0 || index >= oc->nb_chapters) {
2249                     av_log(NULL, AV_LOG_FATAL, "Invalid chapter index %d in metadata specifier.\n", index);
2250                     exit_program(1);
2251                 }
2252                 m = &oc->chapters[index]->metadata;
2253                 break;
2254             default:
2255                 av_log(NULL, AV_LOG_FATAL, "Invalid metadata specifier %s.\n", o->metadata[i].specifier);
2256                 exit_program(1);
2257             }
2258             av_dict_set(m, o->metadata[i].u.str, *val ? val : NULL, 0);
2259         }
2260     }
2261
2262     return 0;
2263 }
2264
2265 static int opt_target(void *optctx, const char *opt, const char *arg)
2266 {
2267     OptionsContext *o = optctx;
2268     enum { PAL, NTSC, FILM, UNKNOWN } norm = UNKNOWN;
2269     static const char *const frame_rates[] = { "25", "30000/1001", "24000/1001" };
2270
2271     if (!strncmp(arg, "pal-", 4)) {
2272         norm = PAL;
2273         arg += 4;
2274     } else if (!strncmp(arg, "ntsc-", 5)) {
2275         norm = NTSC;
2276         arg += 5;
2277     } else if (!strncmp(arg, "film-", 5)) {
2278         norm = FILM;
2279         arg += 5;
2280     } else {
2281         /* Try to determine PAL/NTSC by peeking in the input files */
2282         if (nb_input_files) {
2283             int i, j, fr;
2284             for (j = 0; j < nb_input_files; j++) {
2285                 for (i = 0; i < input_files[j]->nb_streams; i++) {
2286                     AVCodecContext *c = input_files[j]->ctx->streams[i]->codec;
2287                     if (c->codec_type != AVMEDIA_TYPE_VIDEO ||
2288                         !c->time_base.num)
2289                         continue;
2290                     fr = c->time_base.den * 1000 / c->time_base.num;
2291                     if (fr == 25000) {
2292                         norm = PAL;
2293                         break;
2294                     } else if ((fr == 29970) || (fr == 23976)) {
2295                         norm = NTSC;
2296                         break;
2297                     }
2298                 }
2299                 if (norm != UNKNOWN)
2300                     break;
2301             }
2302         }
2303         if (norm != UNKNOWN)
2304             av_log(NULL, AV_LOG_INFO, "Assuming %s for target.\n", norm == PAL ? "PAL" : "NTSC");
2305     }
2306
2307     if (norm == UNKNOWN) {
2308         av_log(NULL, AV_LOG_FATAL, "Could not determine norm (PAL/NTSC/NTSC-Film) for target.\n");
2309         av_log(NULL, AV_LOG_FATAL, "Please prefix target with \"pal-\", \"ntsc-\" or \"film-\",\n");
2310         av_log(NULL, AV_LOG_FATAL, "or set a framerate with \"-r xxx\".\n");
2311         exit_program(1);
2312     }
2313
2314     if (!strcmp(arg, "vcd")) {
2315         opt_video_codec(o, "c:v", "mpeg1video");
2316         opt_audio_codec(o, "c:a", "mp2");
2317         parse_option(o, "f", "vcd", options);
2318
2319         parse_option(o, "s", norm == PAL ? "352x288" : "352x240", options);
2320         parse_option(o, "r", frame_rates[norm], options);
2321         opt_default(NULL, "g", norm == PAL ? "15" : "18");
2322
2323         opt_default(NULL, "b:v", "1150000");
2324         opt_default(NULL, "maxrate", "1150000");
2325         opt_default(NULL, "minrate", "1150000");
2326         opt_default(NULL, "bufsize", "327680"); // 40*1024*8;
2327
2328         opt_default(NULL, "b:a", "224000");
2329         parse_option(o, "ar", "44100", options);
2330         parse_option(o, "ac", "2", options);
2331
2332         opt_default(NULL, "packetsize", "2324");
2333         opt_default(NULL, "muxrate", "1411200"); // 2352 * 75 * 8;
2334
2335         /* We have to offset the PTS, so that it is consistent with the SCR.
2336            SCR starts at 36000, but the first two packs contain only padding
2337            and the first pack from the other stream, respectively, may also have
2338            been written before.
2339            So the real data starts at SCR 36000+3*1200. */
2340         o->mux_preload = (36000 + 3 * 1200) / 90000.0; // 0.44
2341     } else if (!strcmp(arg, "svcd")) {
2342
2343         opt_video_codec(o, "c:v", "mpeg2video");
2344         opt_audio_codec(o, "c:a", "mp2");
2345         parse_option(o, "f", "svcd", options);
2346
2347         parse_option(o, "s", norm == PAL ? "480x576" : "480x480", options);
2348         parse_option(o, "r", frame_rates[norm], options);
2349         parse_option(o, "pix_fmt", "yuv420p", options);
2350         opt_default(NULL, "g", norm == PAL ? "15" : "18");
2351
2352         opt_default(NULL, "b:v", "2040000");
2353         opt_default(NULL, "maxrate", "2516000");
2354         opt_default(NULL, "minrate", "0"); // 1145000;
2355         opt_default(NULL, "bufsize", "1835008"); // 224*1024*8;
2356         opt_default(NULL, "scan_offset", "1");
2357
2358         opt_default(NULL, "b:a", "224000");
2359         parse_option(o, "ar", "44100", options);
2360
2361         opt_default(NULL, "packetsize", "2324");
2362
2363     } else if (!strcmp(arg, "dvd")) {
2364
2365         opt_video_codec(o, "c:v", "mpeg2video");
2366         opt_audio_codec(o, "c:a", "ac3");
2367         parse_option(o, "f", "dvd", options);
2368
2369         parse_option(o, "s", norm == PAL ? "720x576" : "720x480", options);
2370         parse_option(o, "r", frame_rates[norm], options);
2371         parse_option(o, "pix_fmt", "yuv420p", options);
2372         opt_default(NULL, "g", norm == PAL ? "15" : "18");
2373
2374         opt_default(NULL, "b:v", "6000000");
2375         opt_default(NULL, "maxrate", "9000000");
2376         opt_default(NULL, "minrate", "0"); // 1500000;
2377         opt_default(NULL, "bufsize", "1835008"); // 224*1024*8;
2378
2379         opt_default(NULL, "packetsize", "2048");  // from www.mpucoder.com: DVD sectors contain 2048 bytes of data, this is also the size of one pack.
2380         opt_default(NULL, "muxrate", "10080000"); // from mplex project: data_rate = 1260000. mux_rate = data_rate * 8
2381
2382         opt_default(NULL, "b:a", "448000");
2383         parse_option(o, "ar", "48000", options);
2384
2385     } else if (!strncmp(arg, "dv", 2)) {
2386
2387         parse_option(o, "f", "dv", options);
2388
2389         parse_option(o, "s", norm == PAL ? "720x576" : "720x480", options);
2390         parse_option(o, "pix_fmt", !strncmp(arg, "dv50", 4) ? "yuv422p" :
2391                           norm == PAL ? "yuv420p" : "yuv411p", options);
2392         parse_option(o, "r", frame_rates[norm], options);
2393
2394         parse_option(o, "ar", "48000", options);
2395         parse_option(o, "ac", "2", options);
2396
2397     } else {
2398         av_log(NULL, AV_LOG_ERROR, "Unknown target: %s\n", arg);
2399         return AVERROR(EINVAL);
2400     }
2401
2402     av_dict_copy(&o->g->codec_opts,  codec_opts, AV_DICT_DONT_OVERWRITE);
2403     av_dict_copy(&o->g->format_opts, format_opts, AV_DICT_DONT_OVERWRITE);
2404
2405     return 0;
2406 }
2407
2408 static int opt_vstats_file(void *optctx, const char *opt, const char *arg)
2409 {
2410     av_free (vstats_filename);
2411     vstats_filename = av_strdup (arg);
2412     return 0;
2413 }
2414
2415 static int opt_vstats(void *optctx, const char *opt, const char *arg)
2416 {
2417     char filename[40];
2418     time_t today2 = time(NULL);
2419     struct tm *today = localtime(&today2);
2420
2421     snprintf(filename, sizeof(filename), "vstats_%02d%02d%02d.log", today->tm_hour, today->tm_min,
2422              today->tm_sec);
2423     return opt_vstats_file(NULL, opt, filename);
2424 }
2425
2426 static int opt_video_frames(void *optctx, const char *opt, const char *arg)
2427 {
2428     OptionsContext *o = optctx;
2429     return parse_option(o, "frames:v", arg, options);
2430 }
2431
2432 static int opt_audio_frames(void *optctx, const char *opt, const char *arg)
2433 {
2434     OptionsContext *o = optctx;
2435     return parse_option(o, "frames:a", arg, options);
2436 }
2437
2438 static int opt_data_frames(void *optctx, const char *opt, const char *arg)
2439 {
2440     OptionsContext *o = optctx;
2441     return parse_option(o, "frames:d", arg, options);
2442 }
2443
2444 static int opt_default_new(OptionsContext *o, const char *opt, const char *arg)
2445 {
2446     int ret;
2447     AVDictionary *cbak = codec_opts;
2448     AVDictionary *fbak = format_opts;
2449     codec_opts = NULL;
2450     format_opts = NULL;
2451
2452     ret = opt_default(NULL, opt, arg);
2453
2454     av_dict_copy(&o->g->codec_opts , codec_opts, 0);
2455     av_dict_copy(&o->g->format_opts, format_opts, 0);
2456     av_dict_free(&codec_opts);
2457     av_dict_free(&format_opts);
2458     codec_opts = cbak;
2459     format_opts = fbak;
2460
2461     return ret;
2462 }
2463
2464 static int opt_preset(void *optctx, const char *opt, const char *arg)
2465 {
2466     OptionsContext *o = optctx;
2467     FILE *f=NULL;
2468     char filename[1000], line[1000], tmp_line[1000];
2469     const char *codec_name = NULL;
2470
2471     tmp_line[0] = *opt;
2472     tmp_line[1] = 0;
2473     MATCH_PER_TYPE_OPT(codec_names, str, codec_name, NULL, tmp_line);
2474
2475     if (!(f = get_preset_file(filename, sizeof(filename), arg, *opt == 'f', codec_name))) {
2476         if(!strncmp(arg, "libx264-lossless", strlen("libx264-lossless"))){
2477             av_log(NULL, AV_LOG_FATAL, "Please use -preset <speed> -qp 0\n");
2478         }else
2479             av_log(NULL, AV_LOG_FATAL, "File for preset '%s' not found\n", arg);
2480         exit_program(1);
2481     }
2482
2483     while (fgets(line, sizeof(line), f)) {
2484         char *key = tmp_line, *value, *endptr;
2485
2486         if (strcspn(line, "#\n\r") == 0)
2487             continue;
2488         av_strlcpy(tmp_line, line, sizeof(tmp_line));
2489         if (!av_strtok(key,   "=",    &value) ||
2490             !av_strtok(value, "\r\n", &endptr)) {
2491             av_log(NULL, AV_LOG_FATAL, "%s: Invalid syntax: '%s'\n", filename, line);
2492             exit_program(1);
2493         }
2494         av_log(NULL, AV_LOG_DEBUG, "ffpreset[%s]: set '%s' = '%s'\n", filename, key, value);
2495
2496         if      (!strcmp(key, "acodec")) opt_audio_codec   (o, key, value);
2497         else if (!strcmp(key, "vcodec")) opt_video_codec   (o, key, value);
2498         else if (!strcmp(key, "scodec")) opt_subtitle_codec(o, key, value);
2499         else if (!strcmp(key, "dcodec")) opt_data_codec    (o, key, value);
2500         else if (opt_default_new(o, key, value) < 0) {
2501             av_log(NULL, AV_LOG_FATAL, "%s: Invalid option or argument: '%s', parsed as '%s' = '%s'\n",
2502                    filename, line, key, value);
2503             exit_program(1);
2504         }
2505     }
2506
2507     fclose(f);
2508
2509     return 0;
2510 }
2511
2512 static int opt_old2new(void *optctx, const char *opt, const char *arg)
2513 {
2514     OptionsContext *o = optctx;
2515     char *s = av_asprintf("%s:%c", opt + 1, *opt);
2516     int ret = parse_option(o, s, arg, options);
2517     av_free(s);
2518     return ret;
2519 }
2520
2521 static int opt_bitrate(void *optctx, const char *opt, const char *arg)
2522 {
2523     OptionsContext *o = optctx;
2524
2525     if(!strcmp(opt, "ab")){
2526         av_dict_set(&o->g->codec_opts, "b:a", arg, 0);
2527         return 0;
2528     } else if(!strcmp(opt, "b")){
2529         av_log(NULL, AV_LOG_WARNING, "Please use -b:a or -b:v, -b is ambiguous\n");
2530         av_dict_set(&o->g->codec_opts, "b:v", arg, 0);
2531         return 0;
2532     }
2533     av_dict_set(&o->g->codec_opts, opt, arg, 0);
2534     return 0;
2535 }
2536
2537 static int opt_qscale(void *optctx, const char *opt, const char *arg)
2538 {
2539     OptionsContext *o = optctx;
2540     char *s;
2541     int ret;
2542     if(!strcmp(opt, "qscale")){
2543         av_log(NULL, AV_LOG_WARNING, "Please use -q:a or -q:v, -qscale is ambiguous\n");
2544         return parse_option(o, "q:v", arg, options);
2545     }
2546     s = av_asprintf("q%s", opt + 6);
2547     ret = parse_option(o, s, arg, options);
2548     av_free(s);
2549     return ret;
2550 }
2551
2552 static int opt_profile(void *optctx, const char *opt, const char *arg)
2553 {
2554     OptionsContext *o = optctx;
2555     if(!strcmp(opt, "profile")){
2556         av_log(NULL, AV_LOG_WARNING, "Please use -profile:a or -profile:v, -profile is ambiguous\n");
2557         av_dict_set(&o->g->codec_opts, "profile:v", arg, 0);
2558         return 0;
2559     }
2560     av_dict_set(&o->g->codec_opts, opt, arg, 0);
2561     return 0;
2562 }
2563
2564 static int opt_video_filters(void *optctx, const char *opt, const char *arg)
2565 {
2566     OptionsContext *o = optctx;
2567     return parse_option(o, "filter:v", arg, options);
2568 }
2569
2570 static int opt_audio_filters(void *optctx, const char *opt, const char *arg)
2571 {
2572     OptionsContext *o = optctx;
2573     return parse_option(o, "filter:a", arg, options);
2574 }
2575
2576 static int opt_vsync(void *optctx, const char *opt, const char *arg)
2577 {
2578     if      (!av_strcasecmp(arg, "cfr"))         video_sync_method = VSYNC_CFR;
2579     else if (!av_strcasecmp(arg, "vfr"))         video_sync_method = VSYNC_VFR;
2580     else if (!av_strcasecmp(arg, "passthrough")) video_sync_method = VSYNC_PASSTHROUGH;
2581     else if (!av_strcasecmp(arg, "drop"))        video_sync_method = VSYNC_DROP;
2582
2583     if (video_sync_method == VSYNC_AUTO)
2584         video_sync_method = parse_number_or_die("vsync", arg, OPT_INT, VSYNC_AUTO, VSYNC_VFR);
2585     return 0;
2586 }
2587
2588 static int opt_timecode(void *optctx, const char *opt, const char *arg)
2589 {
2590     OptionsContext *o = optctx;
2591     char *tcr = av_asprintf("timecode=%s", arg);
2592     int ret = parse_option(o, "metadata:g", tcr, options);
2593     if (ret >= 0)
2594         ret = av_dict_set(&o->g->codec_opts, "gop_timecode", arg, 0);
2595     av_free(tcr);
2596     return 0;
2597 }
2598
2599 static int opt_channel_layout(void *optctx, const char *opt, const char *arg)
2600 {
2601     OptionsContext *o = optctx;
2602     char layout_str[32];
2603     char *stream_str;
2604     char *ac_str;
2605     int ret, channels, ac_str_size;
2606     uint64_t layout;
2607
2608     layout = av_get_channel_layout(arg);
2609     if (!layout) {
2610         av_log(NULL, AV_LOG_ERROR, "Unknown channel layout: %s\n", arg);
2611         return AVERROR(EINVAL);
2612     }
2613     snprintf(layout_str, sizeof(layout_str), "%"PRIu64, layout);
2614     ret = opt_default_new(o, opt, layout_str);
2615     if (ret < 0)
2616         return ret;
2617
2618     /* set 'ac' option based on channel layout */
2619     channels = av_get_channel_layout_nb_channels(layout);
2620     snprintf(layout_str, sizeof(layout_str), "%d", channels);
2621     stream_str = strchr(opt, ':');
2622     ac_str_size = 3 + (stream_str ? strlen(stream_str) : 0);
2623     ac_str = av_mallocz(ac_str_size);
2624     if (!ac_str)
2625         return AVERROR(ENOMEM);
2626     av_strlcpy(ac_str, "ac", 3);
2627     if (stream_str)
2628         av_strlcat(ac_str, stream_str, ac_str_size);
2629     ret = parse_option(o, ac_str, layout_str, options);
2630     av_free(ac_str);
2631
2632     return ret;
2633 }
2634
2635 static int opt_audio_qscale(void *optctx, const char *opt, const char *arg)
2636 {
2637     OptionsContext *o = optctx;
2638     return parse_option(o, "q:a", arg, options);
2639 }
2640
2641 static int opt_filter_complex(void *optctx, const char *opt, const char *arg)
2642 {
2643     GROW_ARRAY(filtergraphs, nb_filtergraphs);
2644     if (!(filtergraphs[nb_filtergraphs - 1] = av_mallocz(sizeof(*filtergraphs[0]))))
2645         return AVERROR(ENOMEM);
2646     filtergraphs[nb_filtergraphs - 1]->index      = nb_filtergraphs - 1;
2647     filtergraphs[nb_filtergraphs - 1]->graph_desc = av_strdup(arg);
2648     if (!filtergraphs[nb_filtergraphs - 1]->graph_desc)
2649         return AVERROR(ENOMEM);
2650
2651     input_stream_potentially_available = 1;
2652
2653     return 0;
2654 }
2655
2656 static int opt_filter_complex_script(void *optctx, const char *opt, const char *arg)
2657 {
2658     uint8_t *graph_desc = read_file(arg);
2659     if (!graph_desc)
2660         return AVERROR(EINVAL);
2661
2662     GROW_ARRAY(filtergraphs, nb_filtergraphs);
2663     if (!(filtergraphs[nb_filtergraphs - 1] = av_mallocz(sizeof(*filtergraphs[0]))))
2664         return AVERROR(ENOMEM);
2665     filtergraphs[nb_filtergraphs - 1]->index      = nb_filtergraphs - 1;
2666     filtergraphs[nb_filtergraphs - 1]->graph_desc = graph_desc;
2667
2668     input_stream_potentially_available = 1;
2669
2670     return 0;
2671 }
2672
2673 void show_help_default(const char *opt, const char *arg)
2674 {
2675     /* per-file options have at least one of those set */
2676     const int per_file = OPT_SPEC | OPT_OFFSET | OPT_PERFILE;
2677     int show_advanced = 0, show_avoptions = 0;
2678
2679     if (opt && *opt) {
2680         if (!strcmp(opt, "long"))
2681             show_advanced = 1;
2682         else if (!strcmp(opt, "full"))
2683             show_advanced = show_avoptions = 1;
2684         else
2685             av_log(NULL, AV_LOG_ERROR, "Unknown help option '%s'.\n", opt);
2686     }
2687
2688     show_usage();
2689
2690     printf("Getting help:\n"
2691            "    -h      -- print basic options\n"
2692            "    -h long -- print more options\n"
2693            "    -h full -- print all options (including all format and codec specific options, very long)\n"
2694            "    See man %s for detailed description of the options.\n"
2695            "\n", program_name);
2696
2697     show_help_options(options, "Print help / information / capabilities:",
2698                       OPT_EXIT, 0, 0);
2699
2700     show_help_options(options, "Global options (affect whole program "
2701                       "instead of just one file:",
2702                       0, per_file | OPT_EXIT | OPT_EXPERT, 0);
2703     if (show_advanced)
2704         show_help_options(options, "Advanced global options:", OPT_EXPERT,
2705                           per_file | OPT_EXIT, 0);
2706
2707     show_help_options(options, "Per-file main options:", 0,
2708                       OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_SUBTITLE |
2709                       OPT_EXIT, per_file);
2710     if (show_advanced)
2711         show_help_options(options, "Advanced per-file options:",
2712                           OPT_EXPERT, OPT_AUDIO | OPT_VIDEO | OPT_SUBTITLE, per_file);
2713
2714     show_help_options(options, "Video options:",
2715                       OPT_VIDEO, OPT_EXPERT | OPT_AUDIO, 0);
2716     if (show_advanced)
2717         show_help_options(options, "Advanced Video options:",
2718                           OPT_EXPERT | OPT_VIDEO, OPT_AUDIO, 0);
2719
2720     show_help_options(options, "Audio options:",
2721                       OPT_AUDIO, OPT_EXPERT | OPT_VIDEO, 0);
2722     if (show_advanced)
2723         show_help_options(options, "Advanced Audio options:",
2724                           OPT_EXPERT | OPT_AUDIO, OPT_VIDEO, 0);
2725     show_help_options(options, "Subtitle options:",
2726                       OPT_SUBTITLE, 0, 0);
2727     printf("\n");
2728
2729     if (show_avoptions) {
2730         int flags = AV_OPT_FLAG_DECODING_PARAM | AV_OPT_FLAG_ENCODING_PARAM;
2731         show_help_children(avcodec_get_class(), flags);
2732         show_help_children(avformat_get_class(), flags);
2733 #if CONFIG_SWSCALE
2734         show_help_children(sws_get_class(), flags);
2735 #endif
2736         show_help_children(swr_get_class(), AV_OPT_FLAG_AUDIO_PARAM);
2737         show_help_children(avfilter_get_class(), AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_FILTERING_PARAM);
2738     }
2739 }
2740
2741 void show_usage(void)
2742 {
2743     av_log(NULL, AV_LOG_INFO, "Hyper fast Audio and Video encoder\n");
2744     av_log(NULL, AV_LOG_INFO, "usage: %s [options] [[infile options] -i infile]... {[outfile options] outfile}...\n", program_name);
2745     av_log(NULL, AV_LOG_INFO, "\n");
2746 }
2747
2748 enum OptGroup {
2749     GROUP_OUTFILE,
2750     GROUP_INFILE,
2751 };
2752
2753 static const OptionGroupDef groups[] = {
2754     [GROUP_OUTFILE] = { "output file",  NULL, OPT_OUTPUT },
2755     [GROUP_INFILE]  = { "input file",   "i",  OPT_INPUT },
2756 };
2757
2758 static int open_files(OptionGroupList *l, const char *inout,
2759                       int (*open_file)(OptionsContext*, const char*))
2760 {
2761     int i, ret;
2762
2763     for (i = 0; i < l->nb_groups; i++) {
2764         OptionGroup *g = &l->groups[i];
2765         OptionsContext o;
2766
2767         init_options(&o);
2768         o.g = g;
2769
2770         ret = parse_optgroup(&o, g);
2771         if (ret < 0) {
2772             av_log(NULL, AV_LOG_ERROR, "Error parsing options for %s file "
2773                    "%s.\n", inout, g->arg);
2774             return ret;
2775         }
2776
2777         av_log(NULL, AV_LOG_DEBUG, "Opening an %s file: %s.\n", inout, g->arg);
2778         ret = open_file(&o, g->arg);
2779         uninit_options(&o);
2780         if (ret < 0) {
2781             av_log(NULL, AV_LOG_ERROR, "Error opening %s file %s.\n",
2782                    inout, g->arg);
2783             return ret;
2784         }
2785         av_log(NULL, AV_LOG_DEBUG, "Successfully opened the file.\n");
2786     }
2787
2788     return 0;
2789 }
2790
2791 int ffmpeg_parse_options(int argc, char **argv)
2792 {
2793     OptionParseContext octx;
2794     uint8_t error[128];
2795     int ret;
2796
2797     memset(&octx, 0, sizeof(octx));
2798
2799     /* split the commandline into an internal representation */
2800     ret = split_commandline(&octx, argc, argv, options, groups,
2801                             FF_ARRAY_ELEMS(groups));
2802     if (ret < 0) {
2803         av_log(NULL, AV_LOG_FATAL, "Error splitting the argument list: ");
2804         goto fail;
2805     }
2806
2807     /* apply global options */
2808     ret = parse_optgroup(NULL, &octx.global_opts);
2809     if (ret < 0) {
2810         av_log(NULL, AV_LOG_FATAL, "Error parsing global options: ");
2811         goto fail;
2812     }
2813
2814     /* open input files */
2815     ret = open_files(&octx.groups[GROUP_INFILE], "input", open_input_file);
2816     if (ret < 0) {
2817         av_log(NULL, AV_LOG_FATAL, "Error opening input files: ");
2818         goto fail;
2819     }
2820
2821     /* open output files */
2822     ret = open_files(&octx.groups[GROUP_OUTFILE], "output", open_output_file);
2823     if (ret < 0) {
2824         av_log(NULL, AV_LOG_FATAL, "Error opening output files: ");
2825         goto fail;
2826     }
2827
2828 fail:
2829     uninit_parse_context(&octx);
2830     if (ret < 0) {
2831         av_strerror(ret, error, sizeof(error));
2832         av_log(NULL, AV_LOG_FATAL, "%s\n", error);
2833     }
2834     return ret;
2835 }
2836
2837 static int opt_progress(void *optctx, const char *opt, const char *arg)
2838 {
2839     AVIOContext *avio = NULL;
2840     int ret;
2841
2842     if (!strcmp(arg, "-"))
2843         arg = "pipe:";
2844     ret = avio_open2(&avio, arg, AVIO_FLAG_WRITE, &int_cb, NULL);
2845     if (ret < 0) {
2846         av_log(NULL, AV_LOG_ERROR, "Failed to open progress URL \"%s\": %s\n",
2847                arg, av_err2str(ret));
2848         return ret;
2849     }
2850     progress_avio = avio;
2851     return 0;
2852 }
2853
2854 #define OFFSET(x) offsetof(OptionsContext, x)
2855 const OptionDef options[] = {
2856     /* main options */
2857 #include "cmdutils_common_opts.h"
2858     { "f",              HAS_ARG | OPT_STRING | OPT_OFFSET |
2859                         OPT_INPUT | OPT_OUTPUT,                      { .off       = OFFSET(format) },
2860         "force format", "fmt" },
2861     { "y",              OPT_BOOL,                                    {              &file_overwrite },
2862         "overwrite output files" },
2863     { "n",              OPT_BOOL,                                    {              &no_file_overwrite },
2864         "never overwrite output files" },
2865     { "ignore_unknown", OPT_BOOL,                                    {              &ignore_unknown_streams },
2866         "Ignore unknown stream types" },
2867     { "c",              HAS_ARG | OPT_STRING | OPT_SPEC |
2868                         OPT_INPUT | OPT_OUTPUT,                      { .off       = OFFSET(codec_names) },
2869         "codec name", "codec" },
2870     { "codec",          HAS_ARG | OPT_STRING | OPT_SPEC |
2871                         OPT_INPUT | OPT_OUTPUT,                      { .off       = OFFSET(codec_names) },
2872         "codec name", "codec" },
2873     { "pre",            HAS_ARG | OPT_STRING | OPT_SPEC |
2874                         OPT_OUTPUT,                                  { .off       = OFFSET(presets) },
2875         "preset name", "preset" },
2876     { "map",            HAS_ARG | OPT_EXPERT | OPT_PERFILE |
2877                         OPT_OUTPUT,                                  { .func_arg = opt_map },
2878         "set input stream mapping",
2879         "[-]input_file_id[:stream_specifier][,sync_file_id[:stream_specifier]]" },
2880     { "map_channel",    HAS_ARG | OPT_EXPERT | OPT_PERFILE | OPT_OUTPUT, { .func_arg = opt_map_channel },
2881         "map an audio channel from one stream to another", "file.stream.channel[:syncfile.syncstream]" },
2882     { "map_metadata",   HAS_ARG | OPT_STRING | OPT_SPEC |
2883                         OPT_OUTPUT,                                  { .off       = OFFSET(metadata_map) },
2884         "set metadata information of outfile from infile",
2885         "outfile[,metadata]:infile[,metadata]" },
2886     { "map_chapters",   HAS_ARG | OPT_INT | OPT_EXPERT | OPT_OFFSET |
2887                         OPT_OUTPUT,                                  { .off = OFFSET(chapters_input_file) },
2888         "set chapters mapping", "input_file_index" },
2889     { "t",              HAS_ARG | OPT_TIME | OPT_OFFSET |
2890                         OPT_INPUT | OPT_OUTPUT,                      { .off = OFFSET(recording_time) },
2891         "record or transcode \"duration\" seconds of audio/video",
2892         "duration" },
2893     { "to",             HAS_ARG | OPT_TIME | OPT_OFFSET | OPT_OUTPUT,  { .off = OFFSET(stop_time) },
2894         "record or transcode stop time", "time_stop" },
2895     { "fs",             HAS_ARG | OPT_INT64 | OPT_OFFSET | OPT_OUTPUT, { .off = OFFSET(limit_filesize) },
2896         "set the limit file size in bytes", "limit_size" },
2897     { "ss",             HAS_ARG | OPT_TIME | OPT_OFFSET |
2898                         OPT_INPUT | OPT_OUTPUT,                      { .off = OFFSET(start_time) },
2899         "set the start time offset", "time_off" },
2900     { "seek_timestamp", HAS_ARG | OPT_INT | OPT_OFFSET |
2901                         OPT_INPUT,                                   { .off = OFFSET(seek_timestamp) },
2902         "enable/disable seeking by timestamp with -ss" },
2903     { "accurate_seek",  OPT_BOOL | OPT_OFFSET | OPT_EXPERT |
2904                         OPT_INPUT,                                   { .off = OFFSET(accurate_seek) },
2905         "enable/disable accurate seeking with -ss" },
2906     { "itsoffset",      HAS_ARG | OPT_TIME | OPT_OFFSET |
2907                         OPT_EXPERT | OPT_INPUT,                      { .off = OFFSET(input_ts_offset) },
2908         "set the input ts offset", "time_off" },
2909     { "itsscale",       HAS_ARG | OPT_DOUBLE | OPT_SPEC |
2910                         OPT_EXPERT | OPT_INPUT,                      { .off = OFFSET(ts_scale) },
2911         "set the input ts scale", "scale" },
2912     { "timestamp",      HAS_ARG | OPT_PERFILE | OPT_OUTPUT,          { .func_arg = opt_recording_timestamp },
2913         "set the recording timestamp ('now' to set the current time)", "time" },
2914     { "metadata",       HAS_ARG | OPT_STRING | OPT_SPEC | OPT_OUTPUT, { .off = OFFSET(metadata) },
2915         "add metadata", "string=string" },
2916     { "dframes",        HAS_ARG | OPT_PERFILE | OPT_EXPERT |
2917                         OPT_OUTPUT,                                  { .func_arg = opt_data_frames },
2918         "set the number of data frames to output", "number" },
2919     { "benchmark",      OPT_BOOL | OPT_EXPERT,                       { &do_benchmark },
2920         "add timings for benchmarking" },
2921     { "benchmark_all",  OPT_BOOL | OPT_EXPERT,                       { &do_benchmark_all },
2922       "add timings for each task" },
2923     { "progress",       HAS_ARG | OPT_EXPERT,                        { .func_arg = opt_progress },
2924       "write program-readable progress information", "url" },
2925     { "stdin",          OPT_BOOL | OPT_EXPERT,                       { &stdin_interaction },
2926       "enable or disable interaction on standard input" },
2927     { "timelimit",      HAS_ARG | OPT_EXPERT,                        { .func_arg = opt_timelimit },
2928         "set max runtime in seconds", "limit" },
2929     { "dump",           OPT_BOOL | OPT_EXPERT,                       { &do_pkt_dump },
2930         "dump each input packet" },
2931     { "hex",            OPT_BOOL | OPT_EXPERT,                       { &do_hex_dump },
2932         "when dumping packets, also dump the payload" },
2933     { "re",             OPT_BOOL | OPT_EXPERT | OPT_OFFSET |
2934                         OPT_INPUT,                                   { .off = OFFSET(rate_emu) },
2935         "read input at native frame rate", "" },
2936     { "target",         HAS_ARG | OPT_PERFILE | OPT_OUTPUT,          { .func_arg = opt_target },
2937         "specify target file type (\"vcd\", \"svcd\", \"dvd\","
2938         " \"dv\", \"dv50\", \"pal-vcd\", \"ntsc-svcd\", ...)", "type" },
2939     { "vsync",          HAS_ARG | OPT_EXPERT,                        { opt_vsync },
2940         "video sync method", "" },
2941     { "frame_drop_threshold", HAS_ARG | OPT_FLOAT | OPT_EXPERT,      { &frame_drop_threshold },
2942         "frame drop threshold", "" },
2943     { "async",          HAS_ARG | OPT_INT | OPT_EXPERT,              { &audio_sync_method },
2944         "audio sync method", "" },
2945     { "adrift_threshold", HAS_ARG | OPT_FLOAT | OPT_EXPERT,          { &audio_drift_threshold },
2946         "audio drift threshold", "threshold" },
2947     { "copyts",         OPT_BOOL | OPT_EXPERT,                       { &copy_ts },
2948         "copy timestamps" },
2949     { "start_at_zero",  OPT_BOOL | OPT_EXPERT,                       { &start_at_zero },
2950         "shift input timestamps to start at 0 when using copyts" },
2951     { "copytb",         HAS_ARG | OPT_INT | OPT_EXPERT,              { &copy_tb },
2952         "copy input stream time base when stream copying", "mode" },
2953     { "shortest",       OPT_BOOL | OPT_EXPERT | OPT_OFFSET |
2954                         OPT_OUTPUT,                                  { .off = OFFSET(shortest) },
2955         "finish encoding within shortest input" },
2956     { "apad",           OPT_STRING | HAS_ARG | OPT_SPEC |
2957                         OPT_OUTPUT,                                  { .off = OFFSET(apad) },
2958         "audio pad", "" },
2959     { "dts_delta_threshold", HAS_ARG | OPT_FLOAT | OPT_EXPERT,       { &dts_delta_threshold },
2960         "timestamp discontinuity delta threshold", "threshold" },
2961     { "dts_error_threshold", HAS_ARG | OPT_FLOAT | OPT_EXPERT,       { &dts_error_threshold },
2962         "timestamp error delta threshold", "threshold" },
2963     { "xerror",         OPT_BOOL | OPT_EXPERT,                       { &exit_on_error },
2964         "exit on error", "error" },
2965     { "copyinkf",       OPT_BOOL | OPT_EXPERT | OPT_SPEC |
2966                         OPT_OUTPUT,                                  { .off = OFFSET(copy_initial_nonkeyframes) },
2967         "copy initial non-keyframes" },
2968     { "copypriorss",    OPT_INT | HAS_ARG | OPT_EXPERT | OPT_SPEC | OPT_OUTPUT,   { .off = OFFSET(copy_prior_start) },
2969         "copy or discard frames before start time" },
2970     { "frames",         OPT_INT64 | HAS_ARG | OPT_SPEC | OPT_OUTPUT, { .off = OFFSET(max_frames) },
2971         "set the number of frames to output", "number" },
2972     { "tag",            OPT_STRING | HAS_ARG | OPT_SPEC |
2973                         OPT_EXPERT | OPT_OUTPUT | OPT_INPUT,         { .off = OFFSET(codec_tags) },
2974         "force codec tag/fourcc", "fourcc/tag" },
2975     { "q",              HAS_ARG | OPT_EXPERT | OPT_DOUBLE |
2976                         OPT_SPEC | OPT_OUTPUT,                       { .off = OFFSET(qscale) },
2977         "use fixed quality scale (VBR)", "q" },
2978     { "qscale",         HAS_ARG | OPT_EXPERT | OPT_PERFILE |
2979                         OPT_OUTPUT,                                  { .func_arg = opt_qscale },
2980         "use fixed quality scale (VBR)", "q" },
2981     { "profile",        HAS_ARG | OPT_EXPERT | OPT_PERFILE | OPT_OUTPUT, { .func_arg = opt_profile },
2982         "set profile", "profile" },
2983     { "filter",         HAS_ARG | OPT_STRING | OPT_SPEC | OPT_OUTPUT, { .off = OFFSET(filters) },
2984         "set stream filtergraph", "filter_graph" },
2985     { "filter_script",  HAS_ARG | OPT_STRING | OPT_SPEC | OPT_OUTPUT, { .off = OFFSET(filter_scripts) },
2986         "read stream filtergraph description from a file", "filename" },
2987     { "reinit_filter",  HAS_ARG | OPT_INT | OPT_SPEC | OPT_INPUT,    { .off = OFFSET(reinit_filters) },
2988         "reinit filtergraph on input parameter changes", "" },
2989     { "filter_complex", HAS_ARG | OPT_EXPERT,                        { .func_arg = opt_filter_complex },
2990         "create a complex filtergraph", "graph_description" },
2991     { "lavfi",          HAS_ARG | OPT_EXPERT,                        { .func_arg = opt_filter_complex },
2992         "create a complex filtergraph", "graph_description" },
2993     { "filter_complex_script", HAS_ARG | OPT_EXPERT,                 { .func_arg = opt_filter_complex_script },
2994         "read complex filtergraph description from a file", "filename" },
2995     { "stats",          OPT_BOOL,                                    { &print_stats },
2996         "print progress report during encoding", },
2997     { "attach",         HAS_ARG | OPT_PERFILE | OPT_EXPERT |
2998                         OPT_OUTPUT,                                  { .func_arg = opt_attach },
2999         "add an attachment to the output file", "filename" },
3000     { "dump_attachment", HAS_ARG | OPT_STRING | OPT_SPEC |
3001                          OPT_EXPERT | OPT_INPUT,                     { .off = OFFSET(dump_attachment) },
3002         "extract an attachment into a file", "filename" },
3003     { "debug_ts",       OPT_BOOL | OPT_EXPERT,                       { &debug_ts },
3004         "print timestamp debugging info" },
3005     { "max_error_rate",  HAS_ARG | OPT_FLOAT,                        { &max_error_rate },
3006         "maximum error rate", "ratio of errors (0.0: no errors, 1.0: 100% errors) above which ffmpeg returns an error instead of success." },
3007     { "discard",        OPT_STRING | HAS_ARG | OPT_SPEC |
3008                         OPT_INPUT,                                   { .off = OFFSET(discard) },
3009         "discard", "" },
3010     { "disposition",    OPT_STRING | HAS_ARG | OPT_SPEC |
3011                         OPT_OUTPUT,                                  { .off = OFFSET(disposition) },
3012         "disposition", "" },
3013     { "thread_queue_size", HAS_ARG | OPT_INT | OPT_OFFSET | OPT_EXPERT | OPT_INPUT,
3014                                                                      { .off = OFFSET(thread_queue_size) },
3015         "set the maximum number of queued packets from the demuxer" },
3016
3017     /* video options */
3018     { "vframes",      OPT_VIDEO | HAS_ARG  | OPT_PERFILE | OPT_OUTPUT,           { .func_arg = opt_video_frames },
3019         "set the number of video frames to output", "number" },
3020     { "r",            OPT_VIDEO | HAS_ARG  | OPT_STRING | OPT_SPEC |
3021                       OPT_INPUT | OPT_OUTPUT,                                    { .off = OFFSET(frame_rates) },
3022         "set frame rate (Hz value, fraction or abbreviation)", "rate" },
3023     { "s",            OPT_VIDEO | HAS_ARG | OPT_SUBTITLE | OPT_STRING | OPT_SPEC |
3024                       OPT_INPUT | OPT_OUTPUT,                                    { .off = OFFSET(frame_sizes) },
3025         "set frame size (WxH or abbreviation)", "size" },
3026     { "aspect",       OPT_VIDEO | HAS_ARG  | OPT_STRING | OPT_SPEC |
3027                       OPT_OUTPUT,                                                { .off = OFFSET(frame_aspect_ratios) },
3028         "set aspect ratio (4:3, 16:9 or 1.3333, 1.7777)", "aspect" },
3029     { "pix_fmt",      OPT_VIDEO | HAS_ARG | OPT_EXPERT  | OPT_STRING | OPT_SPEC |
3030                       OPT_INPUT | OPT_OUTPUT,                                    { .off = OFFSET(frame_pix_fmts) },
3031         "set pixel format", "format" },
3032     { "bits_per_raw_sample", OPT_VIDEO | OPT_INT | HAS_ARG,                      { &frame_bits_per_raw_sample },
3033         "set the number of bits per raw sample", "number" },
3034     { "intra",        OPT_VIDEO | OPT_BOOL | OPT_EXPERT,                         { &intra_only },
3035         "deprecated use -g 1" },
3036     { "vn",           OPT_VIDEO | OPT_BOOL  | OPT_OFFSET | OPT_INPUT | OPT_OUTPUT,{ .off = OFFSET(video_disable) },
3037         "disable video" },
3038     { "rc_override",  OPT_VIDEO | HAS_ARG | OPT_EXPERT  | OPT_STRING | OPT_SPEC |
3039                       OPT_OUTPUT,                                                { .off = OFFSET(rc_overrides) },
3040         "rate control override for specific intervals", "override" },
3041     { "vcodec",       OPT_VIDEO | HAS_ARG  | OPT_PERFILE | OPT_INPUT |
3042                       OPT_OUTPUT,                                                { .func_arg = opt_video_codec },
3043         "force video codec ('copy' to copy stream)", "codec" },
3044     { "sameq",        OPT_VIDEO | OPT_EXPERT ,                                   { .func_arg = opt_sameq },
3045         "Removed" },
3046     { "same_quant",   OPT_VIDEO | OPT_EXPERT ,                                   { .func_arg = opt_sameq },
3047         "Removed" },
3048     { "timecode",     OPT_VIDEO | HAS_ARG | OPT_PERFILE | OPT_OUTPUT,            { .func_arg = opt_timecode },
3049         "set initial TimeCode value.", "hh:mm:ss[:;.]ff" },
3050     { "pass",         OPT_VIDEO | HAS_ARG | OPT_SPEC | OPT_INT | OPT_OUTPUT,     { .off = OFFSET(pass) },
3051         "select the pass number (1 to 3)", "n" },
3052     { "passlogfile",  OPT_VIDEO | HAS_ARG | OPT_STRING | OPT_EXPERT | OPT_SPEC |
3053                       OPT_OUTPUT,                                                { .off = OFFSET(passlogfiles) },
3054         "select two pass log file name prefix", "prefix" },
3055     { "deinterlace",  OPT_VIDEO | OPT_BOOL | OPT_EXPERT,                         { &do_deinterlace },
3056         "this option is deprecated, use the yadif filter instead" },
3057     { "psnr",         OPT_VIDEO | OPT_BOOL | OPT_EXPERT,                         { &do_psnr },
3058         "calculate PSNR of compressed frames" },
3059     { "vstats",       OPT_VIDEO | OPT_EXPERT ,                                   { &opt_vstats },
3060         "dump video coding statistics to file" },
3061     { "vstats_file",  OPT_VIDEO | HAS_ARG | OPT_EXPERT ,                         { opt_vstats_file },
3062         "dump video coding statistics to file", "file" },
3063     { "vf",           OPT_VIDEO | HAS_ARG  | OPT_PERFILE | OPT_OUTPUT,           { .func_arg = opt_video_filters },
3064         "set video filters", "filter_graph" },
3065     { "intra_matrix", OPT_VIDEO | HAS_ARG | OPT_EXPERT  | OPT_STRING | OPT_SPEC |
3066                       OPT_OUTPUT,                                                { .off = OFFSET(intra_matrices) },
3067         "specify intra matrix coeffs", "matrix" },
3068     { "inter_matrix", OPT_VIDEO | HAS_ARG | OPT_EXPERT  | OPT_STRING | OPT_SPEC |
3069                       OPT_OUTPUT,                                                { .off = OFFSET(inter_matrices) },
3070         "specify inter matrix coeffs", "matrix" },
3071     { "chroma_intra_matrix", OPT_VIDEO | HAS_ARG | OPT_EXPERT  | OPT_STRING | OPT_SPEC |
3072                       OPT_OUTPUT,                                                { .off = OFFSET(chroma_intra_matrices) },
3073         "specify intra matrix coeffs", "matrix" },
3074     { "top",          OPT_VIDEO | HAS_ARG | OPT_EXPERT  | OPT_INT| OPT_SPEC |
3075                       OPT_INPUT | OPT_OUTPUT,                                    { .off = OFFSET(top_field_first) },
3076         "top=1/bottom=0/auto=-1 field first", "" },
3077     { "vtag",         OPT_VIDEO | HAS_ARG | OPT_EXPERT  | OPT_PERFILE |
3078                       OPT_INPUT | OPT_OUTPUT,                                    { .func_arg = opt_old2new },
3079         "force video tag/fourcc", "fourcc/tag" },
3080     { "qphist",       OPT_VIDEO | OPT_BOOL | OPT_EXPERT ,                        { &qp_hist },
3081         "show QP histogram" },
3082     { "force_fps",    OPT_VIDEO | OPT_BOOL | OPT_EXPERT  | OPT_SPEC |
3083                       OPT_OUTPUT,                                                { .off = OFFSET(force_fps) },
3084         "force the selected framerate, disable the best supported framerate selection" },
3085     { "streamid",     OPT_VIDEO | HAS_ARG | OPT_EXPERT | OPT_PERFILE |
3086                       OPT_OUTPUT,                                                { .func_arg = opt_streamid },
3087         "set the value of an outfile streamid", "streamIndex:value" },
3088     { "force_key_frames", OPT_VIDEO | OPT_STRING | HAS_ARG | OPT_EXPERT |
3089                           OPT_SPEC | OPT_OUTPUT,                                 { .off = OFFSET(forced_key_frames) },
3090         "force key frames at specified timestamps", "timestamps" },
3091     { "ab",           OPT_VIDEO | HAS_ARG | OPT_PERFILE | OPT_OUTPUT,            { .func_arg = opt_bitrate },
3092         "audio bitrate (please use -b:a)", "bitrate" },
3093     { "b",            OPT_VIDEO | HAS_ARG | OPT_PERFILE | OPT_OUTPUT,            { .func_arg = opt_bitrate },
3094         "video bitrate (please use -b:v)", "bitrate" },
3095     { "hwaccel",          OPT_VIDEO | OPT_STRING | HAS_ARG | OPT_EXPERT |
3096                           OPT_SPEC | OPT_INPUT,                                  { .off = OFFSET(hwaccels) },
3097         "use HW accelerated decoding", "hwaccel name" },
3098     { "hwaccel_device",   OPT_VIDEO | OPT_STRING | HAS_ARG | OPT_EXPERT |
3099                           OPT_SPEC | OPT_INPUT,                                  { .off = OFFSET(hwaccel_devices) },
3100         "select a device for HW acceleration" "devicename" },
3101 #if HAVE_VDPAU_X11
3102     { "vdpau_api_ver", HAS_ARG | OPT_INT | OPT_EXPERT, { &vdpau_api_ver }, "" },
3103 #endif
3104     { "autorotate",       HAS_ARG | OPT_BOOL | OPT_SPEC |
3105                           OPT_EXPERT | OPT_INPUT,                                { .off = OFFSET(autorotate) },
3106         "automatically insert correct rotate filters" },
3107
3108     /* audio options */
3109     { "aframes",        OPT_AUDIO | HAS_ARG  | OPT_PERFILE | OPT_OUTPUT,           { .func_arg = opt_audio_frames },
3110         "set the number of audio frames to output", "number" },
3111     { "aq",             OPT_AUDIO | HAS_ARG  | OPT_PERFILE | OPT_OUTPUT,           { .func_arg = opt_audio_qscale },
3112         "set audio quality (codec-specific)", "quality", },
3113     { "ar",             OPT_AUDIO | HAS_ARG  | OPT_INT | OPT_SPEC |
3114                         OPT_INPUT | OPT_OUTPUT,                                    { .off = OFFSET(audio_sample_rate) },
3115         "set audio sampling rate (in Hz)", "rate" },
3116     { "ac",             OPT_AUDIO | HAS_ARG  | OPT_INT | OPT_SPEC |
3117                         OPT_INPUT | OPT_OUTPUT,                                    { .off = OFFSET(audio_channels) },
3118         "set number of audio channels", "channels" },
3119     { "an",             OPT_AUDIO | OPT_BOOL | OPT_OFFSET | OPT_INPUT | OPT_OUTPUT,{ .off = OFFSET(audio_disable) },
3120         "disable audio" },
3121     { "acodec",         OPT_AUDIO | HAS_ARG  | OPT_PERFILE |
3122                         OPT_INPUT | OPT_OUTPUT,                                    { .func_arg = opt_audio_codec },
3123         "force audio codec ('copy' to copy stream)", "codec" },
3124     { "atag",           OPT_AUDIO | HAS_ARG  | OPT_EXPERT | OPT_PERFILE |
3125                         OPT_OUTPUT,                                                { .func_arg = opt_old2new },
3126         "force audio tag/fourcc", "fourcc/tag" },
3127     { "vol",            OPT_AUDIO | HAS_ARG  | OPT_INT,                            { &audio_volume },
3128         "change audio volume (256=normal)" , "volume" },
3129     { "sample_fmt",     OPT_AUDIO | HAS_ARG  | OPT_EXPERT | OPT_SPEC |
3130                         OPT_STRING | OPT_INPUT | OPT_OUTPUT,                       { .off = OFFSET(sample_fmts) },
3131         "set sample format", "format" },
3132     { "channel_layout", OPT_AUDIO | HAS_ARG  | OPT_EXPERT | OPT_PERFILE |
3133                         OPT_INPUT | OPT_OUTPUT,                                    { .func_arg = opt_channel_layout },
3134         "set channel layout", "layout" },
3135     { "af",             OPT_AUDIO | HAS_ARG  | OPT_PERFILE | OPT_OUTPUT,           { .func_arg = opt_audio_filters },
3136         "set audio filters", "filter_graph" },
3137     { "guess_layout_max", OPT_AUDIO | HAS_ARG | OPT_INT | OPT_SPEC | OPT_EXPERT | OPT_INPUT, { .off = OFFSET(guess_layout_max) },
3138       "set the maximum number of channels to try to guess the channel layout" },
3139
3140     /* subtitle options */
3141     { "sn",     OPT_SUBTITLE | OPT_BOOL | OPT_OFFSET | OPT_INPUT | OPT_OUTPUT, { .off = OFFSET(subtitle_disable) },
3142         "disable subtitle" },
3143     { "scodec", OPT_SUBTITLE | HAS_ARG  | OPT_PERFILE | OPT_INPUT | OPT_OUTPUT, { .func_arg = opt_subtitle_codec },
3144         "force subtitle codec ('copy' to copy stream)", "codec" },
3145     { "stag",   OPT_SUBTITLE | HAS_ARG  | OPT_EXPERT  | OPT_PERFILE | OPT_OUTPUT, { .func_arg = opt_old2new }
3146         , "force subtitle tag/fourcc", "fourcc/tag" },
3147     { "fix_sub_duration", OPT_BOOL | OPT_EXPERT | OPT_SUBTITLE | OPT_SPEC | OPT_INPUT, { .off = OFFSET(fix_sub_duration) },
3148         "fix subtitles duration" },
3149     { "canvas_size", OPT_SUBTITLE | HAS_ARG | OPT_STRING | OPT_SPEC | OPT_INPUT, { .off = OFFSET(canvas_sizes) },
3150         "set canvas size (WxH or abbreviation)", "size" },
3151
3152     /* grab options */
3153     { "vc", HAS_ARG | OPT_EXPERT | OPT_VIDEO, { .func_arg = opt_video_channel },
3154         "deprecated, use -channel", "channel" },
3155     { "tvstd", HAS_ARG | OPT_EXPERT | OPT_VIDEO, { .func_arg = opt_video_standard },
3156         "deprecated, use -standard", "standard" },
3157     { "isync", OPT_BOOL | OPT_EXPERT, { &input_sync }, "this option is deprecated and does nothing", "" },
3158
3159     /* muxer options */
3160     { "muxdelay",   OPT_FLOAT | HAS_ARG | OPT_EXPERT | OPT_OFFSET | OPT_OUTPUT, { .off = OFFSET(mux_max_delay) },
3161         "set the maximum demux-decode delay", "seconds" },
3162     { "muxpreload", OPT_FLOAT | HAS_ARG | OPT_EXPERT | OPT_OFFSET | OPT_OUTPUT, { .off = OFFSET(mux_preload) },
3163         "set the initial demux-decode delay", "seconds" },
3164     { "override_ffserver", OPT_BOOL | OPT_EXPERT | OPT_OUTPUT, { &override_ffserver },
3165         "override the options from ffserver", "" },
3166     { "sdp_file", HAS_ARG | OPT_EXPERT | OPT_OUTPUT, { opt_sdp_file },
3167         "specify a file in which to print sdp information", "file" },
3168
3169     { "bsf", HAS_ARG | OPT_STRING | OPT_SPEC | OPT_EXPERT | OPT_OUTPUT, { .off = OFFSET(bitstream_filters) },
3170         "A comma-separated list of bitstream filters", "bitstream_filters" },
3171     { "absf", HAS_ARG | OPT_AUDIO | OPT_EXPERT| OPT_PERFILE | OPT_OUTPUT, { .func_arg = opt_old2new },
3172         "deprecated", "audio bitstream_filters" },
3173     { "vbsf", OPT_VIDEO | HAS_ARG | OPT_EXPERT| OPT_PERFILE | OPT_OUTPUT, { .func_arg = opt_old2new },
3174         "deprecated", "video bitstream_filters" },
3175
3176     { "apre", HAS_ARG | OPT_AUDIO | OPT_EXPERT| OPT_PERFILE | OPT_OUTPUT,    { .func_arg = opt_preset },
3177         "set the audio options to the indicated preset", "preset" },
3178     { "vpre", OPT_VIDEO | HAS_ARG | OPT_EXPERT| OPT_PERFILE | OPT_OUTPUT,    { .func_arg = opt_preset },
3179         "set the video options to the indicated preset", "preset" },
3180     { "spre", HAS_ARG | OPT_SUBTITLE | OPT_EXPERT| OPT_PERFILE | OPT_OUTPUT, { .func_arg = opt_preset },
3181         "set the subtitle options to the indicated preset", "preset" },
3182     { "fpre", HAS_ARG | OPT_EXPERT| OPT_PERFILE | OPT_OUTPUT,                { .func_arg = opt_preset },
3183         "set options from indicated preset file", "filename" },
3184     /* data codec support */
3185     { "dcodec", HAS_ARG | OPT_DATA | OPT_PERFILE | OPT_EXPERT | OPT_INPUT | OPT_OUTPUT, { .func_arg = opt_data_codec },
3186         "force data codec ('copy' to copy stream)", "codec" },
3187     { "dn", OPT_BOOL | OPT_VIDEO | OPT_OFFSET | OPT_INPUT | OPT_OUTPUT, { .off = OFFSET(data_disable) },
3188         "disable data" },
3189
3190     { NULL, },
3191 };