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