2 * Various utilities for command line tools
3 * Copyright (c) 2000-2003 Fabrice Bellard
5 * This file is part of FFmpeg.
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.
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.
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
28 /* Include only the enabled headers since some compilers (namely, Sun
29 Studio) will not omit unused inline functions and create undefined
30 references to libraries that are not being built. */
33 #include "compat/va_copy.h"
34 #include "libavformat/avformat.h"
35 #include "libswscale/swscale.h"
36 #include "libswresample/swresample.h"
37 #include "libavutil/avassert.h"
38 #include "libavutil/avstring.h"
39 #include "libavutil/bprint.h"
40 #include "libavutil/display.h"
41 #include "libavutil/getenv_utf8.h"
42 #include "libavutil/libm.h"
43 #include "libavutil/mem.h"
44 #include "libavutil/parseutils.h"
45 #include "libavutil/eval.h"
46 #include "libavutil/dict.h"
47 #include "libavutil/opt.h"
49 #include "fopen_utf8.h"
50 #include "opt_common.h"
53 #include "compat/w32dlfcn.h"
56 AVDictionary
*sws_dict
;
57 AVDictionary
*swr_opts
;
58 AVDictionary
*format_opts
, *codec_opts
;
62 void uninit_opts(void)
64 av_dict_free(&swr_opts
);
65 av_dict_free(&sws_dict
);
66 av_dict_free(&format_opts
);
67 av_dict_free(&codec_opts
);
70 void log_callback_help(void *ptr
, int level
, const char *fmt
, va_list vl
)
72 vfprintf(stdout
, fmt
, vl
);
75 void init_dynload(void)
77 #if HAVE_SETDLLDIRECTORY && defined(_WIN32)
78 /* Calling SetDllDirectory with the empty string (but not NULL) removes the
79 * current working directory from the DLL search path as a security pre-caution. */
84 int parse_number(const char *context
, const char *numstr
, enum OptionType type
,
85 double min
, double max
, double *dst
)
89 double d
= av_strtod(numstr
, &tail
);
91 error
= "Expected number for %s but found: %s\n";
92 else if (d
< min
|| d
> max
)
93 error
= "The value for %s was %s which is not within %f - %f\n";
94 else if (type
== OPT_TYPE_INT64
&& (int64_t)d
!= d
)
95 error
= "Expected int64 for %s but found %s\n";
96 else if (type
== OPT_TYPE_INT
&& (int)d
!= d
)
97 error
= "Expected int for %s but found %s\n";
103 av_log(NULL
, AV_LOG_FATAL
, error
, context
, numstr
, min
, max
);
104 return AVERROR(EINVAL
);
107 void show_help_options(const OptionDef
*options
, const char *msg
, int req_flags
,
114 for (po
= options
; po
->name
; po
++) {
117 if (((po
->flags
& req_flags
) != req_flags
) ||
118 (po
->flags
& rej_flags
))
125 av_strlcpy(buf
, po
->name
, sizeof(buf
));
127 if (po
->flags
& OPT_FLAG_PERSTREAM
)
128 av_strlcat(buf
, "[:<stream_spec>]", sizeof(buf
));
129 else if (po
->flags
& OPT_FLAG_SPEC
)
130 av_strlcat(buf
, "[:<spec>]", sizeof(buf
));
133 av_strlcatf(buf
, sizeof(buf
), " <%s>", po
->argname
);
135 printf("-%-17s %s\n", buf
, po
->help
);
140 void show_help_children(const AVClass
*class, int flags
)
143 const AVClass
*child
;
145 av_opt_show2(&class, NULL
, flags
, 0);
149 while (child
= av_opt_child_class_iterate(class, &iter
))
150 show_help_children(child
, flags
);
153 static const OptionDef
*find_option(const OptionDef
*po
, const char *name
)
160 if (av_strstart(name
, po
->name
, &end
) && (!*end
|| *end
== ':'))
167 /* _WIN32 means using the windows libc - cygwin doesn't define that
168 * by default. HAVE_COMMANDLINETOARGVW is true on cygwin, while
169 * it doesn't provide the actual command line via GetCommandLineW(). */
170 #if HAVE_COMMANDLINETOARGVW && defined(_WIN32)
171 #include <shellapi.h>
172 /* Will be leaked on exit */
173 static char** win32_argv_utf8
= NULL
;
174 static int win32_argc
= 0;
177 * Prepare command line arguments for executable.
178 * For Windows - perform wide-char to UTF-8 conversion.
179 * Input arguments should be main() function arguments.
180 * @param argc_ptr Arguments number (including executable)
181 * @param argv_ptr Arguments list.
183 static void prepare_app_arguments(int *argc_ptr
, char ***argv_ptr
)
187 int i
, buffsize
= 0, offset
= 0;
189 if (win32_argv_utf8
) {
190 *argc_ptr
= win32_argc
;
191 *argv_ptr
= win32_argv_utf8
;
196 argv_w
= CommandLineToArgvW(GetCommandLineW(), &win32_argc
);
197 if (win32_argc
<= 0 || !argv_w
)
200 /* determine the UTF-8 buffer size (including NULL-termination symbols) */
201 for (i
= 0; i
< win32_argc
; i
++)
202 buffsize
+= WideCharToMultiByte(CP_UTF8
, 0, argv_w
[i
], -1,
203 NULL
, 0, NULL
, NULL
);
205 win32_argv_utf8
= av_mallocz(sizeof(char *) * (win32_argc
+ 1) + buffsize
);
206 argstr_flat
= (char *)win32_argv_utf8
+ sizeof(char *) * (win32_argc
+ 1);
207 if (!win32_argv_utf8
) {
212 for (i
= 0; i
< win32_argc
; i
++) {
213 win32_argv_utf8
[i
] = &argstr_flat
[offset
];
214 offset
+= WideCharToMultiByte(CP_UTF8
, 0, argv_w
[i
], -1,
215 &argstr_flat
[offset
],
216 buffsize
- offset
, NULL
, NULL
);
218 win32_argv_utf8
[i
] = NULL
;
221 *argc_ptr
= win32_argc
;
222 *argv_ptr
= win32_argv_utf8
;
225 static inline void prepare_app_arguments(int *argc_ptr
, char ***argv_ptr
)
229 #endif /* HAVE_COMMANDLINETOARGVW */
231 static int opt_has_arg(const OptionDef
*o
)
233 if (o
->type
== OPT_TYPE_BOOL
)
235 if (o
->type
== OPT_TYPE_FUNC
)
236 return !!(o
->flags
& OPT_FUNC_ARG
);
240 static int write_option(void *optctx
, const OptionDef
*po
, const char *opt
,
241 const char *arg
, const OptionDef
*defs
)
243 /* new-style options contain an offset into optctx, old-style address of
245 void *dst
= po
->flags
& OPT_FLAG_OFFSET
?
246 (uint8_t *)optctx
+ po
->u
.off
: po
->u
.dst_ptr
;
247 char *arg_allocated
= NULL
;
249 enum OptionType so_type
= po
->type
;
251 SpecifierOptList
*sol
= NULL
;
258 if (po
->type
== OPT_TYPE_BOOL
) {
259 av_log(NULL
, AV_LOG_FATAL
,
260 "Requested to load an argument from file for a bool option '%s'\n",
262 return AVERROR(EINVAL
);
265 arg_allocated
= file_read(arg
);
266 if (!arg_allocated
) {
267 av_log(NULL
, AV_LOG_FATAL
,
268 "Error reading the value for option '%s' from file: %s\n",
270 return AVERROR(EINVAL
);
276 if (po
->flags
& OPT_FLAG_SPEC
) {
277 char *p
= strchr(opt
, ':');
281 ret
= GROW_ARRAY(sol
->opt
, sol
->nb_opt
);
285 str
= av_strdup(p
? p
+ 1 : "");
287 ret
= AVERROR(ENOMEM
);
290 sol
->opt
[sol
->nb_opt
- 1].specifier
= str
;
292 if (po
->flags
& OPT_FLAG_PERSTREAM
) {
293 ret
= stream_specifier_parse(&sol
->opt
[sol
->nb_opt
- 1].stream_spec
,
299 dst
= &sol
->opt
[sol
->nb_opt
- 1].u
;
302 if (po
->type
== OPT_TYPE_STRING
) {
306 arg_allocated
= NULL
;
308 str
= av_strdup(arg
);
312 ret
= AVERROR(ENOMEM
);
317 } else if (po
->type
== OPT_TYPE_BOOL
|| po
->type
== OPT_TYPE_INT
) {
318 ret
= parse_number(opt
, arg
, OPT_TYPE_INT64
, INT_MIN
, INT_MAX
, &num
);
323 so_type
= OPT_TYPE_INT
;
324 } else if (po
->type
== OPT_TYPE_INT64
) {
325 ret
= parse_number(opt
, arg
, OPT_TYPE_INT64
, INT64_MIN
, (double)INT64_MAX
, &num
);
329 *(int64_t *)dst
= num
;
330 } else if (po
->type
== OPT_TYPE_TIME
) {
331 ret
= av_parse_time(dst
, arg
, 1);
333 av_log(NULL
, AV_LOG_ERROR
, "Invalid duration for option %s: %s\n",
337 so_type
= OPT_TYPE_INT64
;
338 } else if (po
->type
== OPT_TYPE_FLOAT
) {
339 ret
= parse_number(opt
, arg
, OPT_TYPE_FLOAT
, -INFINITY
, INFINITY
, &num
);
344 } else if (po
->type
== OPT_TYPE_DOUBLE
) {
345 ret
= parse_number(opt
, arg
, OPT_TYPE_DOUBLE
, -INFINITY
, INFINITY
, &num
);
349 *(double *)dst
= num
;
351 av_assert0(po
->type
== OPT_TYPE_FUNC
&& po
->u
.func_arg
);
353 ret
= po
->u
.func_arg(optctx
, opt
, arg
);
355 av_log(NULL
, AV_LOG_ERROR
,
356 "Failed to set value '%s' for option '%s': %s\n",
357 arg
, opt
, av_err2str(ret
));
361 if (po
->flags
& OPT_EXIT
) {
368 sol
->opt_canon
= (po
->flags
& OPT_HAS_CANON
) ?
369 find_option(defs
, po
->u1
.name_canon
) : po
;
373 av_freep(&arg_allocated
);
377 int parse_option(void *optctx
, const char *opt
, const char *arg
,
378 const OptionDef
*options
)
380 static const OptionDef opt_avoptions
= {
381 .name
= "AVOption passthrough",
382 .type
= OPT_TYPE_FUNC
,
383 .flags
= OPT_FUNC_ARG
,
384 .u
.func_arg
= opt_default
,
390 po
= find_option(options
, opt
);
391 if (!po
->name
&& opt
[0] == 'n' && opt
[1] == 'o') {
392 /* handle 'no' bool option */
393 po
= find_option(options
, opt
+ 2);
394 if ((po
->name
&& po
->type
== OPT_TYPE_BOOL
))
396 } else if (po
->type
== OPT_TYPE_BOOL
)
402 av_log(NULL
, AV_LOG_ERROR
, "Unrecognized option '%s'\n", opt
);
403 return AVERROR(EINVAL
);
405 if (opt_has_arg(po
) && !arg
) {
406 av_log(NULL
, AV_LOG_ERROR
, "Missing argument for option '%s'\n", opt
);
407 return AVERROR(EINVAL
);
410 ret
= write_option(optctx
, po
, opt
, arg
, options
);
414 return opt_has_arg(po
);
417 int parse_options(void *optctx
, int argc
, char **argv
, const OptionDef
*options
,
418 int (*parse_arg_function
)(void *, const char*))
421 int optindex
, handleoptions
= 1, ret
;
423 /* perform system-dependent conversions for arguments list */
424 prepare_app_arguments(&argc
, &argv
);
428 while (optindex
< argc
) {
429 opt
= argv
[optindex
++];
431 if (handleoptions
&& opt
[0] == '-' && opt
[1] != '\0') {
432 if (opt
[1] == '-' && opt
[2] == '\0') {
438 if ((ret
= parse_option(optctx
, opt
, argv
[optindex
], options
)) < 0)
442 if (parse_arg_function
) {
443 ret
= parse_arg_function(optctx
, opt
);
453 int parse_optgroup(void *optctx
, OptionGroup
*g
, const OptionDef
*defs
)
457 av_log(NULL
, AV_LOG_DEBUG
, "Parsing a group of options: %s %s.\n",
458 g
->group_def
->name
, g
->arg
);
460 for (i
= 0; i
< g
->nb_opts
; i
++) {
461 Option
*o
= &g
->opts
[i
];
463 if (g
->group_def
->flags
&&
464 !(g
->group_def
->flags
& o
->opt
->flags
)) {
465 av_log(NULL
, AV_LOG_ERROR
, "Option %s (%s) cannot be applied to "
466 "%s %s -- you are trying to apply an input option to an "
467 "output file or vice versa. Move this option before the "
468 "file it belongs to.\n", o
->key
, o
->opt
->help
,
469 g
->group_def
->name
, g
->arg
);
470 return AVERROR(EINVAL
);
473 av_log(NULL
, AV_LOG_DEBUG
, "Applying option %s (%s) with argument %s.\n",
474 o
->key
, o
->opt
->help
, o
->val
);
476 ret
= write_option(optctx
, o
->opt
, o
->key
, o
->val
, defs
);
481 av_log(NULL
, AV_LOG_DEBUG
, "Successfully parsed a group of options.\n");
486 int locate_option(int argc
, char **argv
, const OptionDef
*options
,
492 for (i
= 1; i
< argc
; i
++) {
493 const char *cur_opt
= argv
[i
];
495 if (!(cur_opt
[0] == '-' && cur_opt
[1]))
499 po
= find_option(options
, cur_opt
);
500 if (!po
->name
&& cur_opt
[0] == 'n' && cur_opt
[1] == 'o')
501 po
= find_option(options
, cur_opt
+ 2);
503 if ((!po
->name
&& !strcmp(cur_opt
, optname
)) ||
504 (po
->name
&& !strcmp(optname
, po
->name
)))
507 if (!po
->name
|| opt_has_arg(po
))
513 static void dump_argument(FILE *report_file
, const char *a
)
515 const unsigned char *p
;
518 if (!((*p
>= '+' && *p
<= ':') || (*p
>= '@' && *p
<= 'Z') ||
519 *p
== '_' || (*p
>= 'a' && *p
<= 'z')))
522 fputs(a
, report_file
);
525 fputc('"', report_file
);
526 for (p
= a
; *p
; p
++) {
527 if (*p
== '\\' || *p
== '"' || *p
== '$' || *p
== '`')
528 fprintf(report_file
, "\\%c", *p
);
529 else if (*p
< ' ' || *p
> '~')
530 fprintf(report_file
, "\\x%02x", *p
);
532 fputc(*p
, report_file
);
534 fputc('"', report_file
);
537 static void check_options(const OptionDef
*po
)
540 if (po
->flags
& OPT_PERFILE
)
541 av_assert0(po
->flags
& (OPT_INPUT
| OPT_OUTPUT
| OPT_DECODER
));
543 if (po
->type
== OPT_TYPE_FUNC
)
544 av_assert0(!(po
->flags
& (OPT_FLAG_OFFSET
| OPT_FLAG_SPEC
)));
546 // OPT_FUNC_ARG can only be ser for OPT_TYPE_FUNC
547 av_assert0((po
->type
== OPT_TYPE_FUNC
) || !(po
->flags
& OPT_FUNC_ARG
));
553 void parse_loglevel(int argc
, char **argv
, const OptionDef
*options
)
558 check_options(options
);
560 idx
= locate_option(argc
, argv
, options
, "loglevel");
562 idx
= locate_option(argc
, argv
, options
, "v");
563 if (idx
&& argv
[idx
+ 1])
564 opt_loglevel(NULL
, "loglevel", argv
[idx
+ 1]);
565 idx
= locate_option(argc
, argv
, options
, "report");
566 env
= getenv_utf8("FFREPORT");
568 FILE *report_file
= NULL
;
569 init_report(env
, &report_file
);
572 fprintf(report_file
, "Command line:\n");
573 for (i
= 0; i
< argc
; i
++) {
574 dump_argument(report_file
, argv
[i
]);
575 fputc(i
< argc
- 1 ? ' ' : '\n', report_file
);
581 idx
= locate_option(argc
, argv
, options
, "hide_banner");
586 static const AVOption
*opt_find(void *obj
, const char *name
, const char *unit
,
587 int opt_flags
, int search_flags
)
589 const AVOption
*o
= av_opt_find(obj
, name
, unit
, opt_flags
, search_flags
);
595 #define FLAGS ((o->type == AV_OPT_TYPE_FLAGS && (arg[0]=='-' || arg[0]=='+')) ? AV_DICT_APPEND : 0)
596 int opt_default(void *optctx
, const char *opt
, const char *arg
)
600 char opt_stripped
[128];
602 const AVClass
*cc
= avcodec_get_class(), *fc
= avformat_get_class();
604 const AVClass
*sc
= sws_get_class();
606 #if CONFIG_SWRESAMPLE
607 const AVClass
*swr_class
= swr_get_class();
610 if (!strcmp(opt
, "debug") || !strcmp(opt
, "fdebug"))
611 av_log_set_level(AV_LOG_DEBUG
);
613 if (!(p
= strchr(opt
, ':')))
614 p
= opt
+ strlen(opt
);
615 av_strlcpy(opt_stripped
, opt
, FFMIN(sizeof(opt_stripped
), p
- opt
+ 1));
617 if ((o
= opt_find(&cc
, opt_stripped
, NULL
, 0,
618 AV_OPT_SEARCH_CHILDREN
| AV_OPT_SEARCH_FAKE_OBJ
)) ||
619 ((opt
[0] == 'v' || opt
[0] == 'a' || opt
[0] == 's') &&
620 (o
= opt_find(&cc
, opt
+ 1, NULL
, 0, AV_OPT_SEARCH_FAKE_OBJ
)))) {
621 av_dict_set(&codec_opts
, opt
, arg
, FLAGS
);
624 if ((o
= opt_find(&fc
, opt
, NULL
, 0,
625 AV_OPT_SEARCH_CHILDREN
| AV_OPT_SEARCH_FAKE_OBJ
))) {
626 av_dict_set(&format_opts
, opt
, arg
, FLAGS
);
628 av_log(NULL
, AV_LOG_VERBOSE
, "Routing option %s to both codec and muxer layer\n", opt
);
632 if (!consumed
&& (o
= opt_find(&sc
, opt
, NULL
, 0,
633 AV_OPT_SEARCH_CHILDREN
| AV_OPT_SEARCH_FAKE_OBJ
))) {
634 if (!strcmp(opt
, "srcw") || !strcmp(opt
, "srch") ||
635 !strcmp(opt
, "dstw") || !strcmp(opt
, "dsth") ||
636 !strcmp(opt
, "src_format") || !strcmp(opt
, "dst_format")) {
637 av_log(NULL
, AV_LOG_ERROR
, "Directly using swscale dimensions/format options is not supported, please use the -s or -pix_fmt options\n");
638 return AVERROR(EINVAL
);
640 av_dict_set(&sws_dict
, opt
, arg
, FLAGS
);
645 if (!consumed
&& !strcmp(opt
, "sws_flags")) {
646 av_log(NULL
, AV_LOG_WARNING
, "Ignoring %s %s, due to disabled swscale\n", opt
, arg
);
650 #if CONFIG_SWRESAMPLE
651 if (!consumed
&& (o
=opt_find(&swr_class
, opt
, NULL
, 0,
652 AV_OPT_SEARCH_CHILDREN
| AV_OPT_SEARCH_FAKE_OBJ
))) {
653 av_dict_set(&swr_opts
, opt
, arg
, FLAGS
);
660 return AVERROR_OPTION_NOT_FOUND
;
664 * Check whether given option is a group separator.
666 * @return index of the group definition that matched or -1 if none
668 static int match_group_separator(const OptionGroupDef
*groups
, int nb_groups
,
673 for (i
= 0; i
< nb_groups
; i
++) {
674 const OptionGroupDef
*p
= &groups
[i
];
675 if (p
->sep
&& !strcmp(p
->sep
, opt
))
683 * Finish parsing an option group.
685 * @param group_idx which group definition should this group belong to
686 * @param arg argument of the group delimiting option
688 static int finish_group(OptionParseContext
*octx
, int group_idx
,
691 OptionGroupList
*l
= &octx
->groups
[group_idx
];
695 ret
= GROW_ARRAY(l
->groups
, l
->nb_groups
);
699 g
= &l
->groups
[l
->nb_groups
- 1];
701 *g
= octx
->cur_group
;
703 g
->group_def
= l
->group_def
;
704 g
->sws_dict
= sws_dict
;
705 g
->swr_opts
= swr_opts
;
706 g
->codec_opts
= codec_opts
;
707 g
->format_opts
= format_opts
;
714 memset(&octx
->cur_group
, 0, sizeof(octx
->cur_group
));
720 * Add an option instance to currently parsed group.
722 static int add_opt(OptionParseContext
*octx
, const OptionDef
*opt
,
723 const char *key
, const char *val
)
725 int global
= !(opt
->flags
& OPT_PERFILE
);
726 OptionGroup
*g
= global
? &octx
->global_opts
: &octx
->cur_group
;
729 ret
= GROW_ARRAY(g
->opts
, g
->nb_opts
);
733 g
->opts
[g
->nb_opts
- 1].opt
= opt
;
734 g
->opts
[g
->nb_opts
- 1].key
= key
;
735 g
->opts
[g
->nb_opts
- 1].val
= val
;
740 static int init_parse_context(OptionParseContext
*octx
,
741 const OptionGroupDef
*groups
, int nb_groups
)
743 static const OptionGroupDef global_group
= { "global" };
746 memset(octx
, 0, sizeof(*octx
));
748 octx
->groups
= av_calloc(nb_groups
, sizeof(*octx
->groups
));
750 return AVERROR(ENOMEM
);
751 octx
->nb_groups
= nb_groups
;
753 for (i
= 0; i
< octx
->nb_groups
; i
++)
754 octx
->groups
[i
].group_def
= &groups
[i
];
756 octx
->global_opts
.group_def
= &global_group
;
757 octx
->global_opts
.arg
= "";
762 void uninit_parse_context(OptionParseContext
*octx
)
766 for (i
= 0; i
< octx
->nb_groups
; i
++) {
767 OptionGroupList
*l
= &octx
->groups
[i
];
769 for (j
= 0; j
< l
->nb_groups
; j
++) {
770 av_freep(&l
->groups
[j
].opts
);
771 av_dict_free(&l
->groups
[j
].codec_opts
);
772 av_dict_free(&l
->groups
[j
].format_opts
);
774 av_dict_free(&l
->groups
[j
].sws_dict
);
775 av_dict_free(&l
->groups
[j
].swr_opts
);
777 av_freep(&l
->groups
);
779 av_freep(&octx
->groups
);
781 av_freep(&octx
->cur_group
.opts
);
782 av_freep(&octx
->global_opts
.opts
);
787 int split_commandline(OptionParseContext
*octx
, int argc
, char *argv
[],
788 const OptionDef
*options
,
789 const OptionGroupDef
*groups
, int nb_groups
)
795 /* perform system-dependent conversions for arguments list */
796 prepare_app_arguments(&argc
, &argv
);
798 ret
= init_parse_context(octx
, groups
, nb_groups
);
802 av_log(NULL
, AV_LOG_DEBUG
, "Splitting the commandline.\n");
804 while (optindex
< argc
) {
805 const char *opt
= argv
[optindex
++], *arg
;
809 av_log(NULL
, AV_LOG_DEBUG
, "Reading option '%s' ...", opt
);
811 if (opt
[0] == '-' && opt
[1] == '-' && !opt
[2]) {
815 /* unnamed group separators, e.g. output filename */
816 if (opt
[0] != '-' || !opt
[1] || dashdash
+1 == optindex
) {
817 ret
= finish_group(octx
, 0, opt
);
821 av_log(NULL
, AV_LOG_DEBUG
, " matched as %s.\n", groups
[0].name
);
826 #define GET_ARG(arg) \
828 arg = argv[optindex++]; \
830 av_log(NULL, AV_LOG_ERROR, "Missing argument for option '%s'.\n", opt);\
831 return AVERROR(EINVAL); \
835 /* named group separators, e.g. -i */
836 group_idx
= match_group_separator(groups
, nb_groups
, opt
);
837 if (group_idx
>= 0) {
839 ret
= finish_group(octx
, group_idx
, arg
);
843 av_log(NULL
, AV_LOG_DEBUG
, " matched as %s with argument '%s'.\n",
844 groups
[group_idx
].name
, arg
);
849 po
= find_option(options
, opt
);
851 if (po
->flags
& OPT_EXIT
) {
852 /* optional argument, e.g. -h */
853 arg
= argv
[optindex
++];
854 } else if (opt_has_arg(po
)) {
860 ret
= add_opt(octx
, po
, opt
, arg
);
864 av_log(NULL
, AV_LOG_DEBUG
, " matched as option '%s' (%s) with "
865 "argument '%s'.\n", po
->name
, po
->help
, arg
);
870 if (argv
[optindex
]) {
871 ret
= opt_default(NULL
, opt
, argv
[optindex
]);
873 av_log(NULL
, AV_LOG_DEBUG
, " matched as AVOption '%s' with "
874 "argument '%s'.\n", opt
, argv
[optindex
]);
877 } else if (ret
!= AVERROR_OPTION_NOT_FOUND
) {
878 av_log(NULL
, AV_LOG_ERROR
, "Error parsing option '%s' "
879 "with argument '%s'.\n", opt
, argv
[optindex
]);
884 /* boolean -nofoo options */
885 if (opt
[0] == 'n' && opt
[1] == 'o' &&
886 (po
= find_option(options
, opt
+ 2)) &&
887 po
->name
&& po
->type
== OPT_TYPE_BOOL
) {
888 ret
= add_opt(octx
, po
, opt
, "0");
892 av_log(NULL
, AV_LOG_DEBUG
, " matched as option '%s' (%s) with "
893 "argument 0.\n", po
->name
, po
->help
);
897 av_log(NULL
, AV_LOG_ERROR
, "Unrecognized option '%s'.\n", opt
);
898 return AVERROR_OPTION_NOT_FOUND
;
901 if (octx
->cur_group
.nb_opts
|| codec_opts
|| format_opts
)
902 av_log(NULL
, AV_LOG_WARNING
, "Trailing option(s) found in the "
903 "command: may be ignored.\n");
905 av_log(NULL
, AV_LOG_DEBUG
, "Finished splitting the commandline.\n");
913 int yesno
= (av_toupper(c
) == 'Y');
915 while (c
!= '\n' && c
!= EOF
)
921 FILE *get_preset_file(char *filename
, size_t filename_size
,
922 const char *preset_name
, int is_path
,
923 const char *codec_name
)
927 #if HAVE_GETMODULEHANDLE && defined(_WIN32)
928 char *datadir
= NULL
;
930 char *env_home
= getenv_utf8("HOME");
931 char *env_ffmpeg_datadir
= getenv_utf8("FFMPEG_DATADIR");
932 const char *base
[3] = { env_ffmpeg_datadir
,
933 env_home
, /* index=1(HOME) is special: search in a .ffmpeg subfolder */
937 av_strlcpy(filename
, preset_name
, filename_size
);
938 f
= fopen_utf8(filename
, "r");
940 #if HAVE_GETMODULEHANDLE && defined(_WIN32)
941 wchar_t *datadir_w
= get_module_filename(NULL
);
944 if (wchartoutf8(datadir_w
, &datadir
))
951 for (ls
= datadir
; *ls
; ls
++)
952 if (*ls
== '\\') *ls
= '/';
954 if (ls
= strrchr(datadir
, '/'))
956 ptrdiff_t datadir_len
= ls
- datadir
;
957 size_t desired_size
= datadir_len
+ strlen("/ffpresets") + 1;
958 char *new_datadir
= av_realloc_array(
959 datadir
, desired_size
, sizeof *datadir
);
961 datadir
= new_datadir
;
962 datadir
[datadir_len
] = 0;
963 strncat(datadir
, "/ffpresets", desired_size
- 1 - datadir_len
);
969 for (i
= 0; i
< 3 && !f
; i
++) {
972 snprintf(filename
, filename_size
, "%s%s/%s.ffpreset", base
[i
],
973 i
!= 1 ? "" : "/.ffmpeg", preset_name
);
974 f
= fopen_utf8(filename
, "r");
975 if (!f
&& codec_name
) {
976 snprintf(filename
, filename_size
,
977 "%s%s/%s-%s.ffpreset",
978 base
[i
], i
!= 1 ? "" : "/.ffmpeg", codec_name
,
980 f
= fopen_utf8(filename
, "r");
985 #if HAVE_GETMODULEHANDLE && defined(_WIN32)
988 freeenv_utf8(env_ffmpeg_datadir
);
989 freeenv_utf8(env_home
);
993 int cmdutils_isalnum(char c
)
995 return (c
>= '0' && c
<= '9') ||
996 (c
>= 'A' && c
<= 'Z') ||
997 (c
>= 'a' && c
<= 'z');
1000 void stream_specifier_uninit(StreamSpecifier
*ss
)
1002 av_freep(&ss
->meta_key
);
1003 av_freep(&ss
->meta_val
);
1004 av_freep(&ss
->remainder
);
1006 memset(ss
, 0, sizeof(*ss
));
1009 int stream_specifier_parse(StreamSpecifier
*ss
, const char *spec
,
1010 int allow_remainder
, void *logctx
)
1015 memset(ss
, 0, sizeof(*ss
));
1018 ss
->media_type
= AVMEDIA_TYPE_UNKNOWN
;
1019 ss
->stream_list
= STREAM_LIST_ALL
;
1021 av_log(logctx
, AV_LOG_TRACE
, "Parsing stream specifier: %s\n", spec
);
1024 if (*spec
<= '9' && *spec
>= '0') { /* opt:index */
1025 ss
->idx
= strtol(spec
, &endptr
, 0);
1027 av_assert0(endptr
> spec
);
1030 av_log(logctx
, AV_LOG_TRACE
,
1031 "Parsed index: %d; remainder: %s\n", ss
->idx
, spec
);
1033 // this terminates the specifier
1035 } else if ((*spec
== 'v' || *spec
== 'a' || *spec
== 's' ||
1036 *spec
== 'd' || *spec
== 't' || *spec
== 'V') &&
1037 !cmdutils_isalnum(*(spec
+ 1))) { /* opt:[vasdtV] */
1038 if (ss
->media_type
!= AVMEDIA_TYPE_UNKNOWN
) {
1039 av_log(logctx
, AV_LOG_ERROR
, "Stream type specified multiple times\n");
1040 ret
= AVERROR(EINVAL
);
1045 case 'v': ss
->media_type
= AVMEDIA_TYPE_VIDEO
; break;
1046 case 'a': ss
->media_type
= AVMEDIA_TYPE_AUDIO
; break;
1047 case 's': ss
->media_type
= AVMEDIA_TYPE_SUBTITLE
; break;
1048 case 'd': ss
->media_type
= AVMEDIA_TYPE_DATA
; break;
1049 case 't': ss
->media_type
= AVMEDIA_TYPE_ATTACHMENT
; break;
1050 case 'V': ss
->media_type
= AVMEDIA_TYPE_VIDEO
;
1051 ss
->no_apic
= 1; break;
1052 default: av_assert0(0);
1055 av_log(logctx
, AV_LOG_TRACE
, "Parsed media type: %s; remainder: %s\n",
1056 av_get_media_type_string(ss
->media_type
), spec
);
1057 } else if (*spec
== 'g' && *(spec
+ 1) == ':') {
1058 if (ss
->stream_list
!= STREAM_LIST_ALL
)
1059 goto multiple_stream_lists
;
1062 if (*spec
== '#' || (*spec
== 'i' && *(spec
+ 1) == ':')) {
1063 ss
->stream_list
= STREAM_LIST_GROUP_ID
;
1065 spec
+= 1 + (*spec
== 'i');
1067 ss
->stream_list
= STREAM_LIST_GROUP_IDX
;
1069 ss
->list_id
= strtol(spec
, &endptr
, 0);
1070 if (spec
== endptr
) {
1071 av_log(logctx
, AV_LOG_ERROR
, "Expected stream group idx/ID, got: %s\n", spec
);
1072 ret
= AVERROR(EINVAL
);
1077 av_log(logctx
, AV_LOG_TRACE
, "Parsed stream group %s: %"PRId64
"; remainder: %s\n",
1078 ss
->stream_list
== STREAM_LIST_GROUP_ID
? "ID" : "index", ss
->list_id
, spec
);
1079 } else if (*spec
== 'p' && *(spec
+ 1) == ':') {
1080 if (ss
->stream_list
!= STREAM_LIST_ALL
)
1081 goto multiple_stream_lists
;
1083 ss
->stream_list
= STREAM_LIST_PROGRAM
;
1086 ss
->list_id
= strtol(spec
, &endptr
, 0);
1087 if (spec
== endptr
) {
1088 av_log(logctx
, AV_LOG_ERROR
, "Expected program ID, got: %s\n", spec
);
1089 ret
= AVERROR(EINVAL
);
1094 av_log(logctx
, AV_LOG_TRACE
,
1095 "Parsed program ID: %"PRId64
"; remainder: %s\n", ss
->list_id
, spec
);
1096 } else if (!strncmp(spec
, "disp:", 5)) {
1097 const AVClass
*st_class
= av_stream_get_class();
1098 const AVOption
*o
= av_opt_find(&st_class
, "disposition", NULL
, 0, AV_OPT_SEARCH_FAKE_OBJ
);
1104 if (ss
->disposition
) {
1105 av_log(logctx
, AV_LOG_ERROR
, "Multiple disposition specifiers\n");
1106 ret
= AVERROR(EINVAL
);
1112 for (len
= 0; cmdutils_isalnum(spec
[len
]) ||
1113 spec
[len
] == '_' || spec
[len
] == '+'; len
++)
1116 disp
= av_strndup(spec
, len
);
1118 ret
= AVERROR(ENOMEM
);
1122 ret
= av_opt_eval_flags(&st_class
, o
, disp
, &ss
->disposition
);
1125 av_log(logctx
, AV_LOG_ERROR
, "Invalid disposition specifier\n");
1131 av_log(logctx
, AV_LOG_TRACE
,
1132 "Parsed disposition: 0x%x; remainder: %s\n", ss
->disposition
, spec
);
1133 } else if (*spec
== '#' ||
1134 (*spec
== 'i' && *(spec
+ 1) == ':')) {
1135 if (ss
->stream_list
!= STREAM_LIST_ALL
)
1136 goto multiple_stream_lists
;
1138 ss
->stream_list
= STREAM_LIST_STREAM_ID
;
1140 spec
+= 1 + (*spec
== 'i');
1141 ss
->list_id
= strtol(spec
, &endptr
, 0);
1142 if (spec
== endptr
) {
1143 av_log(logctx
, AV_LOG_ERROR
, "Expected stream ID, got: %s\n", spec
);
1144 ret
= AVERROR(EINVAL
);
1149 av_log(logctx
, AV_LOG_TRACE
,
1150 "Parsed stream ID: %"PRId64
"; remainder: %s\n", ss
->list_id
, spec
);
1152 // this terminates the specifier
1154 } else if (*spec
== 'm' && *(spec
+ 1) == ':') {
1155 av_assert0(!ss
->meta_key
&& !ss
->meta_val
);
1158 ss
->meta_key
= av_get_token(&spec
, ":");
1159 if (!ss
->meta_key
) {
1160 ret
= AVERROR(ENOMEM
);
1165 ss
->meta_val
= av_get_token(&spec
, ":");
1166 if (!ss
->meta_val
) {
1167 ret
= AVERROR(ENOMEM
);
1172 av_log(logctx
, AV_LOG_TRACE
,
1173 "Parsed metadata: %s:%s; remainder: %s", ss
->meta_key
,
1174 ss
->meta_val
? ss
->meta_val
: "<any value>", spec
);
1176 // this terminates the specifier
1178 } else if (*spec
== 'u' && (*(spec
+ 1) == '\0' || *(spec
+ 1) == ':')) {
1179 ss
->usable_only
= 1;
1181 av_log(logctx
, AV_LOG_ERROR
, "Parsed 'usable only'\n");
1183 // this terminates the specifier
1193 if (!allow_remainder
) {
1194 av_log(logctx
, AV_LOG_ERROR
,
1195 "Trailing garbage at the end of a stream specifier: %s\n",
1197 ret
= AVERROR(EINVAL
);
1204 ss
->remainder
= av_strdup(spec
);
1205 if (!ss
->remainder
) {
1206 ret
= AVERROR(EINVAL
);
1213 multiple_stream_lists
:
1214 av_log(logctx
, AV_LOG_ERROR
,
1215 "Cannot combine multiple program/group designators in a "
1216 "single stream specifier");
1217 ret
= AVERROR(EINVAL
);
1220 stream_specifier_uninit(ss
);
1224 unsigned stream_specifier_match(const StreamSpecifier
*ss
,
1225 const AVFormatContext
*s
, const AVStream
*st
,
1228 const AVStreamGroup
*g
= NULL
;
1229 const AVProgram
*p
= NULL
;
1230 int start_stream
= 0, nb_streams
;
1233 switch (ss
->stream_list
) {
1234 case STREAM_LIST_STREAM_ID
:
1235 // <n-th> stream with given ID makes no sense and should be impossible to request
1236 av_assert0(ss
->idx
< 0);
1237 // return early if we know for sure the stream does not match
1238 if (st
->id
!= ss
->list_id
)
1240 start_stream
= st
->index
;
1241 nb_streams
= st
->index
+ 1;
1243 case STREAM_LIST_ALL
:
1244 start_stream
= ss
->idx
>= 0 ? 0 : st
->index
;
1245 nb_streams
= st
->index
+ 1;
1247 case STREAM_LIST_PROGRAM
:
1248 for (unsigned i
= 0; i
< s
->nb_programs
; i
++) {
1249 if (s
->programs
[i
]->id
== ss
->list_id
) {
1255 av_log(logctx
, AV_LOG_WARNING
, "No program with ID %"PRId64
" exists,"
1256 " stream specifier can never match\n", ss
->list_id
);
1259 nb_streams
= p
->nb_stream_indexes
;
1261 case STREAM_LIST_GROUP_ID
:
1262 for (unsigned i
= 0; i
< s
->nb_stream_groups
; i
++) {
1263 if (ss
->list_id
== s
->stream_groups
[i
]->id
) {
1264 g
= s
->stream_groups
[i
];
1269 case STREAM_LIST_GROUP_IDX
:
1270 if (ss
->stream_list
== STREAM_LIST_GROUP_IDX
&&
1271 ss
->list_id
>= 0 && ss
->list_id
< s
->nb_stream_groups
)
1272 g
= s
->stream_groups
[ss
->list_id
];
1275 av_log(logctx
, AV_LOG_WARNING
, "No stream group with group %s %"
1276 PRId64
" exists, stream specifier can never match\n",
1277 ss
->stream_list
== STREAM_LIST_GROUP_ID
? "ID" : "index",
1281 nb_streams
= g
->nb_streams
;
1283 default: av_assert0(0);
1286 for (int i
= start_stream
; i
< nb_streams
; i
++) {
1287 const AVStream
*candidate
= s
->streams
[g
? g
->streams
[i
]->index
:
1288 p
? p
->stream_index
[i
] : i
];
1290 if (ss
->media_type
!= AVMEDIA_TYPE_UNKNOWN
&&
1291 (ss
->media_type
!= candidate
->codecpar
->codec_type
||
1292 (ss
->no_apic
&& (candidate
->disposition
& AV_DISPOSITION_ATTACHED_PIC
))))
1296 const AVDictionaryEntry
*tag
= av_dict_get(candidate
->metadata
,
1297 ss
->meta_key
, NULL
, 0);
1301 if (ss
->meta_val
&& strcmp(tag
->value
, ss
->meta_val
))
1305 if (ss
->usable_only
) {
1306 const AVCodecParameters
*par
= candidate
->codecpar
;
1308 switch (par
->codec_type
) {
1309 case AVMEDIA_TYPE_AUDIO
:
1310 if (!par
->sample_rate
|| !par
->ch_layout
.nb_channels
||
1311 par
->format
== AV_SAMPLE_FMT_NONE
)
1314 case AVMEDIA_TYPE_VIDEO
:
1315 if (!par
->width
|| !par
->height
|| par
->format
== AV_PIX_FMT_NONE
)
1318 case AVMEDIA_TYPE_UNKNOWN
:
1323 if (ss
->disposition
&&
1324 (candidate
->disposition
& ss
->disposition
) != ss
->disposition
)
1327 if (st
== candidate
)
1328 return ss
->idx
< 0 || ss
->idx
== nb_matched
;
1336 int check_stream_specifier(AVFormatContext
*s
, AVStream
*st
, const char *spec
)
1341 ret
= stream_specifier_parse(&ss
, spec
, 0, NULL
);
1345 ret
= stream_specifier_match(&ss
, s
, st
, NULL
);
1346 stream_specifier_uninit(&ss
);
1350 int filter_codec_opts(const AVDictionary
*opts
, enum AVCodecID codec_id
,
1351 AVFormatContext
*s
, AVStream
*st
, const AVCodec
*codec
,
1352 AVDictionary
**dst
, AVDictionary
**opts_used
)
1354 AVDictionary
*ret
= NULL
;
1355 const AVDictionaryEntry
*t
= NULL
;
1356 int flags
= s
->oformat
? AV_OPT_FLAG_ENCODING_PARAM
1357 : AV_OPT_FLAG_DECODING_PARAM
;
1359 const AVClass
*cc
= avcodec_get_class();
1361 switch (st
->codecpar
->codec_type
) {
1362 case AVMEDIA_TYPE_VIDEO
:
1364 flags
|= AV_OPT_FLAG_VIDEO_PARAM
;
1366 case AVMEDIA_TYPE_AUDIO
:
1368 flags
|= AV_OPT_FLAG_AUDIO_PARAM
;
1370 case AVMEDIA_TYPE_SUBTITLE
:
1372 flags
|= AV_OPT_FLAG_SUBTITLE_PARAM
;
1376 while (t
= av_dict_iterate(opts
, t
)) {
1377 const AVClass
*priv_class
;
1378 char *p
= strchr(t
->key
, ':');
1381 /* check stream specification in opt name */
1383 int err
= check_stream_specifier(s
, st
, p
+ 1);
1393 if (av_opt_find(&cc
, t
->key
, NULL
, flags
, AV_OPT_SEARCH_FAKE_OBJ
) ||
1395 ((priv_class
= codec
->priv_class
) &&
1396 av_opt_find(&priv_class
, t
->key
, NULL
, flags
,
1397 AV_OPT_SEARCH_FAKE_OBJ
))) {
1398 av_dict_set(&ret
, t
->key
, t
->value
, 0);
1400 } else if (t
->key
[0] == prefix
&&
1401 av_opt_find(&cc
, t
->key
+ 1, NULL
, flags
,
1402 AV_OPT_SEARCH_FAKE_OBJ
)) {
1403 av_dict_set(&ret
, t
->key
+ 1, t
->value
, 0);
1410 if (used
&& opts_used
)
1411 av_dict_set(opts_used
, t
->key
, "", 0);
1418 int setup_find_stream_info_opts(AVFormatContext
*s
,
1419 AVDictionary
*local_codec_opts
,
1420 AVDictionary
***dst
)
1423 AVDictionary
**opts
;
1430 opts
= av_calloc(s
->nb_streams
, sizeof(*opts
));
1432 return AVERROR(ENOMEM
);
1434 for (int i
= 0; i
< s
->nb_streams
; i
++) {
1435 ret
= filter_codec_opts(local_codec_opts
, s
->streams
[i
]->codecpar
->codec_id
,
1436 s
, s
->streams
[i
], NULL
, &opts
[i
], NULL
);
1443 for (int i
= 0; i
< s
->nb_streams
; i
++)
1444 av_dict_free(&opts
[i
]);
1449 int grow_array(void **array
, int elem_size
, int *size
, int new_size
)
1451 if (new_size
>= INT_MAX
/ elem_size
) {
1452 av_log(NULL
, AV_LOG_ERROR
, "Array too big.\n");
1453 return AVERROR(ERANGE
);
1455 if (*size
< new_size
) {
1456 uint8_t *tmp
= av_realloc_array(*array
, new_size
, elem_size
);
1458 return AVERROR(ENOMEM
);
1459 memset(tmp
+ *size
*elem_size
, 0, (new_size
-*size
) * elem_size
);
1467 void *allocate_array_elem(void *ptr
, size_t elem_size
, int *nb_elems
)
1471 if (!(new_elem
= av_mallocz(elem_size
)) ||
1472 av_dynarray_add_nofree(ptr
, nb_elems
, new_elem
) < 0)
1477 double get_rotation(const int32_t *displaymatrix
)
1481 theta
= -round(av_display_rotation_get(displaymatrix
));
1483 theta
-= 360*floor(theta
/360 + 0.9/360);
1485 if (fabs(theta
- 90*round(theta
/90)) > 2)
1486 av_log(NULL
, AV_LOG_WARNING
, "Odd rotation angle.\n"
1487 "If you want to help, upload a sample "
1488 "of this file to https://streams.videolan.org/upload/ "
1489 "and contact the ffmpeg-devel mailing list. (ffmpeg-devel@ffmpeg.org)");
1494 /* read file contents into a string */
1495 char *file_read(const char *filename
)
1497 AVIOContext
*pb
= NULL
;
1498 int ret
= avio_open(&pb
, filename
, AVIO_FLAG_READ
);
1503 av_log(NULL
, AV_LOG_ERROR
, "Error opening file %s.\n", filename
);
1507 av_bprint_init(&bprint
, 0, AV_BPRINT_SIZE_UNLIMITED
);
1508 ret
= avio_read_to_bprint(pb
, &bprint
, SIZE_MAX
);
1511 av_bprint_finalize(&bprint
, NULL
);
1514 ret
= av_bprint_finalize(&bprint
, &str
);
1520 void remove_avoptions(AVDictionary
**a
, AVDictionary
*b
)
1522 const AVDictionaryEntry
*t
= NULL
;
1524 while ((t
= av_dict_iterate(b
, t
))) {
1525 av_dict_set(a
, t
->key
, NULL
, AV_DICT_MATCH_CASE
);
1529 int check_avoptions(AVDictionary
*m
)
1531 const AVDictionaryEntry
*t
= av_dict_iterate(m
, NULL
);
1533 av_log(NULL
, AV_LOG_FATAL
, "Option %s not found.\n", t
->key
);
1534 return AVERROR_OPTION_NOT_FOUND
;