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