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