2 * Various utilities for command line tools
3 * Copyright (c) 2000-2003 Fabrice Bellard
5 * This file is part of Libav.
7 * Libav 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 * Libav 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 Libav; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
27 /* Include only the enabled headers since some compilers (namely, Sun
28 Studio) will not omit unused inline functions and create undefined
29 references to libraries that are not being built. */
32 #include "libavformat/avformat.h"
33 #include "libavfilter/avfilter.h"
34 #include "libavdevice/avdevice.h"
35 #include "libavresample/avresample.h"
36 #include "libswscale/swscale.h"
37 #include "libavutil/avassert.h"
38 #include "libavutil/avstring.h"
39 #include "libavutil/mathematics.h"
40 #include "libavutil/imgutils.h"
41 #include "libavutil/parseutils.h"
42 #include "libavutil/pixdesc.h"
43 #include "libavutil/eval.h"
44 #include "libavutil/dict.h"
45 #include "libavutil/opt.h"
49 #include "libavformat/network.h"
51 #if HAVE_SYS_RESOURCE_H
53 #include <sys/resource.h>
56 struct SwsContext *sws_opts;
57 AVDictionary *format_opts, *codec_opts, *resample_opts;
59 static const int this_year = 2013;
64 sws_opts = sws_getContext(16, 16, 0, 16, 16, 0, SWS_BICUBIC,
69 void uninit_opts(void)
72 sws_freeContext(sws_opts);
75 av_dict_free(&format_opts);
76 av_dict_free(&codec_opts);
77 av_dict_free(&resample_opts);
80 void log_callback_help(void *ptr, int level, const char *fmt, va_list vl)
82 vfprintf(stdout, fmt, vl);
85 double parse_number_or_die(const char *context, const char *numstr, int type,
86 double min, double max)
90 double d = av_strtod(numstr, &tail);
92 error = "Expected number for %s but found: %s\n";
93 else if (d < min || d > max)
94 error = "The value for %s was %s which is not within %f - %f\n";
95 else if (type == OPT_INT64 && (int64_t)d != d)
96 error = "Expected int64 for %s but found %s\n";
97 else if (type == OPT_INT && (int)d != d)
98 error = "Expected int for %s but found %s\n";
101 av_log(NULL, AV_LOG_FATAL, error, context, numstr, min, max);
106 int64_t parse_time_or_die(const char *context, const char *timestr,
110 if (av_parse_time(&us, timestr, is_duration) < 0) {
111 av_log(NULL, AV_LOG_FATAL, "Invalid %s specification for %s: %s\n",
112 is_duration ? "duration" : "date", context, timestr);
118 void show_help_options(const OptionDef *options, const char *msg, int req_flags,
119 int rej_flags, int alt_flags)
125 for (po = options; po->name != NULL; po++) {
128 if (((po->flags & req_flags) != req_flags) ||
129 (alt_flags && !(po->flags & alt_flags)) ||
130 (po->flags & rej_flags))
137 av_strlcpy(buf, po->name, sizeof(buf));
139 av_strlcat(buf, " ", sizeof(buf));
140 av_strlcat(buf, po->argname, sizeof(buf));
142 printf("-%-17s %s\n", buf, po->help);
147 void show_help_children(const AVClass *class, int flags)
149 const AVClass *child = NULL;
150 av_opt_show2(&class, NULL, flags, 0);
153 while (child = av_opt_child_class_next(class, child))
154 show_help_children(child, flags);
157 static const OptionDef *find_option(const OptionDef *po, const char *name)
159 const char *p = strchr(name, ':');
160 int len = p ? p - name : strlen(name);
162 while (po->name != NULL) {
163 if (!strncmp(name, po->name, len) && strlen(po->name) == len)
170 #if HAVE_COMMANDLINETOARGVW
172 #include <shellapi.h>
173 /* Will be leaked on exit */
174 static char** win32_argv_utf8 = NULL;
175 static int win32_argc = 0;
178 * Prepare command line arguments for executable.
179 * For Windows - perform wide-char to UTF-8 conversion.
180 * Input arguments should be main() function arguments.
181 * @param argc_ptr Arguments number (including executable)
182 * @param argv_ptr Arguments list.
184 static void prepare_app_arguments(int *argc_ptr, char ***argv_ptr)
188 int i, buffsize = 0, offset = 0;
190 if (win32_argv_utf8) {
191 *argc_ptr = win32_argc;
192 *argv_ptr = win32_argv_utf8;
197 argv_w = CommandLineToArgvW(GetCommandLineW(), &win32_argc);
198 if (win32_argc <= 0 || !argv_w)
201 /* determine the UTF-8 buffer size (including NULL-termination symbols) */
202 for (i = 0; i < win32_argc; i++)
203 buffsize += WideCharToMultiByte(CP_UTF8, 0, argv_w[i], -1,
204 NULL, 0, NULL, NULL);
206 win32_argv_utf8 = av_mallocz(sizeof(char *) * (win32_argc + 1) + buffsize);
207 argstr_flat = (char *)win32_argv_utf8 + sizeof(char *) * (win32_argc + 1);
208 if (win32_argv_utf8 == NULL) {
213 for (i = 0; i < win32_argc; i++) {
214 win32_argv_utf8[i] = &argstr_flat[offset];
215 offset += WideCharToMultiByte(CP_UTF8, 0, argv_w[i], -1,
216 &argstr_flat[offset],
217 buffsize - offset, NULL, NULL);
219 win32_argv_utf8[i] = NULL;
222 *argc_ptr = win32_argc;
223 *argv_ptr = win32_argv_utf8;
226 static inline void prepare_app_arguments(int *argc_ptr, char ***argv_ptr)
230 #endif /* HAVE_COMMANDLINETOARGVW */
232 static int write_option(void *optctx, const OptionDef *po, const char *opt,
235 /* new-style options contain an offset into optctx, old-style address of
237 void *dst = po->flags & (OPT_OFFSET | OPT_SPEC) ?
238 (uint8_t *)optctx + po->u.off : po->u.dst_ptr;
241 if (po->flags & OPT_SPEC) {
242 SpecifierOpt **so = dst;
243 char *p = strchr(opt, ':');
245 dstcount = (int *)(so + 1);
246 *so = grow_array(*so, sizeof(**so), dstcount, *dstcount + 1);
247 (*so)[*dstcount - 1].specifier = av_strdup(p ? p + 1 : "");
248 dst = &(*so)[*dstcount - 1].u;
251 if (po->flags & OPT_STRING) {
253 str = av_strdup(arg);
256 } else if (po->flags & OPT_BOOL || po->flags & OPT_INT) {
257 *(int *)dst = parse_number_or_die(opt, arg, OPT_INT64, INT_MIN, INT_MAX);
258 } else if (po->flags & OPT_INT64) {
259 *(int64_t *)dst = parse_number_or_die(opt, arg, OPT_INT64, INT64_MIN, INT64_MAX);
260 } else if (po->flags & OPT_TIME) {
261 *(int64_t *)dst = parse_time_or_die(opt, arg, 1);
262 } else if (po->flags & OPT_FLOAT) {
263 *(float *)dst = parse_number_or_die(opt, arg, OPT_FLOAT, -INFINITY, INFINITY);
264 } else if (po->flags & OPT_DOUBLE) {
265 *(double *)dst = parse_number_or_die(opt, arg, OPT_DOUBLE, -INFINITY, INFINITY);
266 } else if (po->u.func_arg) {
267 int ret = po->u.func_arg(optctx, opt, arg);
269 av_log(NULL, AV_LOG_ERROR,
270 "Failed to set value '%s' for option '%s'\n", arg, opt);
274 if (po->flags & OPT_EXIT)
280 int parse_option(void *optctx, const char *opt, const char *arg,
281 const OptionDef *options)
286 po = find_option(options, opt);
287 if (!po->name && opt[0] == 'n' && opt[1] == 'o') {
288 /* handle 'no' bool option */
289 po = find_option(options, opt + 2);
290 if ((po->name && (po->flags & OPT_BOOL)))
292 } else if (po->flags & OPT_BOOL)
296 po = find_option(options, "default");
298 av_log(NULL, AV_LOG_ERROR, "Unrecognized option '%s'\n", opt);
299 return AVERROR(EINVAL);
301 if (po->flags & HAS_ARG && !arg) {
302 av_log(NULL, AV_LOG_ERROR, "Missing argument for option '%s'\n", opt);
303 return AVERROR(EINVAL);
306 ret = write_option(optctx, po, opt, arg);
310 return !!(po->flags & HAS_ARG);
313 void parse_options(void *optctx, int argc, char **argv, const OptionDef *options,
314 void (*parse_arg_function)(void *, const char*))
317 int optindex, handleoptions = 1, ret;
319 /* perform system-dependent conversions for arguments list */
320 prepare_app_arguments(&argc, &argv);
324 while (optindex < argc) {
325 opt = argv[optindex++];
327 if (handleoptions && opt[0] == '-' && opt[1] != '\0') {
328 if (opt[1] == '-' && opt[2] == '\0') {
334 if ((ret = parse_option(optctx, opt, argv[optindex], options)) < 0)
338 if (parse_arg_function)
339 parse_arg_function(optctx, opt);
344 int parse_optgroup(void *optctx, OptionGroup *g)
348 av_log(NULL, AV_LOG_DEBUG, "Parsing a group of options: %s %s.\n",
349 g->group_def->name, g->arg);
351 for (i = 0; i < g->nb_opts; i++) {
352 Option *o = &g->opts[i];
354 if (g->group_def->flags &&
355 !(g->group_def->flags & o->opt->flags)) {
356 av_log(NULL, AV_LOG_ERROR, "Option %s (%s) cannot be applied to "
357 "%s %s -- you are trying to apply an input option to an "
358 "output file or vice versa. Move this option before the "
359 "file it belongs to.\n", o->key, o->opt->help,
360 g->group_def->name, g->arg);
361 return AVERROR(EINVAL);
364 av_log(NULL, AV_LOG_DEBUG, "Applying option %s (%s) with argument %s.\n",
365 o->key, o->opt->help, o->val);
367 ret = write_option(optctx, o->opt, o->key, o->val);
372 av_log(NULL, AV_LOG_DEBUG, "Successfully parsed a group of options.\n");
377 int locate_option(int argc, char **argv, const OptionDef *options,
383 for (i = 1; i < argc; i++) {
384 const char *cur_opt = argv[i];
386 if (*cur_opt++ != '-')
389 po = find_option(options, cur_opt);
390 if (!po->name && cur_opt[0] == 'n' && cur_opt[1] == 'o')
391 po = find_option(options, cur_opt + 2);
393 if ((!po->name && !strcmp(cur_opt, optname)) ||
394 (po->name && !strcmp(optname, po->name)))
397 if (!po || po->flags & HAS_ARG)
403 void parse_loglevel(int argc, char **argv, const OptionDef *options)
405 int idx = locate_option(argc, argv, options, "loglevel");
407 idx = locate_option(argc, argv, options, "v");
408 if (idx && argv[idx + 1])
409 opt_loglevel(NULL, "loglevel", argv[idx + 1]);
412 #define FLAGS (o->type == AV_OPT_TYPE_FLAGS) ? AV_DICT_APPEND : 0
413 int opt_default(void *optctx, const char *opt, const char *arg)
416 char opt_stripped[128];
418 const AVClass *cc = avcodec_get_class(), *fc = avformat_get_class();
419 #if CONFIG_AVRESAMPLE
420 const AVClass *rc = avresample_get_class();
423 const AVClass *sc = sws_get_class();
426 if (!(p = strchr(opt, ':')))
427 p = opt + strlen(opt);
428 av_strlcpy(opt_stripped, opt, FFMIN(sizeof(opt_stripped), p - opt + 1));
430 if ((o = av_opt_find(&cc, opt_stripped, NULL, 0,
431 AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ)) ||
432 ((opt[0] == 'v' || opt[0] == 'a' || opt[0] == 's') &&
433 (o = av_opt_find(&cc, opt + 1, NULL, 0, AV_OPT_SEARCH_FAKE_OBJ))))
434 av_dict_set(&codec_opts, opt, arg, FLAGS);
435 else if ((o = av_opt_find(&fc, opt, NULL, 0,
436 AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ)))
437 av_dict_set(&format_opts, opt, arg, FLAGS);
438 #if CONFIG_AVRESAMPLE
439 else if ((o = av_opt_find(&rc, opt, NULL, 0,
440 AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ)))
441 av_dict_set(&resample_opts, opt, arg, FLAGS);
444 else if ((o = av_opt_find(&sc, opt, NULL, 0,
445 AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ))) {
446 // XXX we only support sws_flags, not arbitrary sws options
447 int ret = av_opt_set(sws_opts, opt, arg, 0);
449 av_log(NULL, AV_LOG_ERROR, "Error setting option %s.\n", opt);
457 return AVERROR_OPTION_NOT_FOUND;
461 * Check whether given option is a group separator.
463 * @return index of the group definition that matched or -1 if none
465 static int match_group_separator(const OptionGroupDef *groups, int nb_groups,
470 for (i = 0; i < nb_groups; i++) {
471 const OptionGroupDef *p = &groups[i];
472 if (p->sep && !strcmp(p->sep, opt))
480 * Finish parsing an option group.
482 * @param group_idx which group definition should this group belong to
483 * @param arg argument of the group delimiting option
485 static void finish_group(OptionParseContext *octx, int group_idx,
488 OptionGroupList *l = &octx->groups[group_idx];
491 GROW_ARRAY(l->groups, l->nb_groups);
492 g = &l->groups[l->nb_groups - 1];
494 *g = octx->cur_group;
496 g->group_def = l->group_def;
498 g->sws_opts = sws_opts;
500 g->codec_opts = codec_opts;
501 g->format_opts = format_opts;
502 g->resample_opts = resample_opts;
506 resample_opts = NULL;
512 memset(&octx->cur_group, 0, sizeof(octx->cur_group));
516 * Add an option instance to currently parsed group.
518 static void add_opt(OptionParseContext *octx, const OptionDef *opt,
519 const char *key, const char *val)
521 int global = !(opt->flags & (OPT_PERFILE | OPT_SPEC | OPT_OFFSET));
522 OptionGroup *g = global ? &octx->global_opts : &octx->cur_group;
524 GROW_ARRAY(g->opts, g->nb_opts);
525 g->opts[g->nb_opts - 1].opt = opt;
526 g->opts[g->nb_opts - 1].key = key;
527 g->opts[g->nb_opts - 1].val = val;
530 static void init_parse_context(OptionParseContext *octx,
531 const OptionGroupDef *groups, int nb_groups)
533 static const OptionGroupDef global_group = { "global" };
536 memset(octx, 0, sizeof(*octx));
538 octx->nb_groups = nb_groups;
539 octx->groups = av_mallocz(sizeof(*octx->groups) * octx->nb_groups);
543 for (i = 0; i < octx->nb_groups; i++)
544 octx->groups[i].group_def = &groups[i];
546 octx->global_opts.group_def = &global_group;
547 octx->global_opts.arg = "";
552 void uninit_parse_context(OptionParseContext *octx)
556 for (i = 0; i < octx->nb_groups; i++) {
557 OptionGroupList *l = &octx->groups[i];
559 for (j = 0; j < l->nb_groups; j++) {
560 av_freep(&l->groups[j].opts);
561 av_dict_free(&l->groups[j].codec_opts);
562 av_dict_free(&l->groups[j].format_opts);
563 av_dict_free(&l->groups[j].resample_opts);
565 sws_freeContext(l->groups[j].sws_opts);
568 av_freep(&l->groups);
570 av_freep(&octx->groups);
572 av_freep(&octx->cur_group.opts);
573 av_freep(&octx->global_opts.opts);
578 int split_commandline(OptionParseContext *octx, int argc, char *argv[],
579 const OptionDef *options,
580 const OptionGroupDef *groups, int nb_groups)
584 /* perform system-dependent conversions for arguments list */
585 prepare_app_arguments(&argc, &argv);
587 init_parse_context(octx, groups, nb_groups);
588 av_log(NULL, AV_LOG_DEBUG, "Splitting the commandline.\n");
590 while (optindex < argc) {
591 const char *opt = argv[optindex++], *arg;
595 av_log(NULL, AV_LOG_DEBUG, "Reading option '%s' ...", opt);
597 /* unnamed group separators, e.g. output filename */
598 if (opt[0] != '-' || !opt[1]) {
599 finish_group(octx, 0, opt);
600 av_log(NULL, AV_LOG_DEBUG, " matched as %s.\n", groups[0].name);
605 #define GET_ARG(arg) \
607 arg = argv[optindex++]; \
609 av_log(NULL, AV_LOG_ERROR, "Missing argument for option '%s'.\n", opt);\
610 return AVERROR(EINVAL); \
614 /* named group separators, e.g. -i */
615 if ((ret = match_group_separator(groups, nb_groups, opt)) >= 0) {
617 finish_group(octx, ret, arg);
618 av_log(NULL, AV_LOG_DEBUG, " matched as %s with argument '%s'.\n",
619 groups[ret].name, arg);
624 po = find_option(options, opt);
626 if (po->flags & OPT_EXIT) {
627 /* optional argument, e.g. -h */
628 arg = argv[optindex++];
629 } else if (po->flags & HAS_ARG) {
635 add_opt(octx, po, opt, arg);
636 av_log(NULL, AV_LOG_DEBUG, " matched as option '%s' (%s) with "
637 "argument '%s'.\n", po->name, po->help, arg);
642 if (argv[optindex]) {
643 ret = opt_default(NULL, opt, argv[optindex]);
645 av_log(NULL, AV_LOG_DEBUG, " matched as AVOption '%s' with "
646 "argument '%s'.\n", opt, argv[optindex]);
649 } else if (ret != AVERROR_OPTION_NOT_FOUND) {
650 av_log(NULL, AV_LOG_ERROR, "Error parsing option '%s' "
651 "with argument '%s'.\n", opt, argv[optindex]);
656 /* boolean -nofoo options */
657 if (opt[0] == 'n' && opt[1] == 'o' &&
658 (po = find_option(options, opt + 2)) &&
659 po->name && po->flags & OPT_BOOL) {
660 add_opt(octx, po, opt, "0");
661 av_log(NULL, AV_LOG_DEBUG, " matched as option '%s' (%s) with "
662 "argument 0.\n", po->name, po->help);
666 av_log(NULL, AV_LOG_ERROR, "Unrecognized option '%s'.\n", opt);
667 return AVERROR_OPTION_NOT_FOUND;
670 if (octx->cur_group.nb_opts || codec_opts || format_opts || resample_opts)
671 av_log(NULL, AV_LOG_WARNING, "Trailing options were found on the "
674 av_log(NULL, AV_LOG_DEBUG, "Finished splitting the commandline.\n");
679 int opt_loglevel(void *optctx, const char *opt, const char *arg)
681 const struct { const char *name; int level; } log_levels[] = {
682 { "quiet" , AV_LOG_QUIET },
683 { "panic" , AV_LOG_PANIC },
684 { "fatal" , AV_LOG_FATAL },
685 { "error" , AV_LOG_ERROR },
686 { "warning", AV_LOG_WARNING },
687 { "info" , AV_LOG_INFO },
688 { "verbose", AV_LOG_VERBOSE },
689 { "debug" , AV_LOG_DEBUG },
695 for (i = 0; i < FF_ARRAY_ELEMS(log_levels); i++) {
696 if (!strcmp(log_levels[i].name, arg)) {
697 av_log_set_level(log_levels[i].level);
702 level = strtol(arg, &tail, 10);
704 av_log(NULL, AV_LOG_FATAL, "Invalid loglevel \"%s\". "
705 "Possible levels are numbers or:\n", arg);
706 for (i = 0; i < FF_ARRAY_ELEMS(log_levels); i++)
707 av_log(NULL, AV_LOG_FATAL, "\"%s\"\n", log_levels[i].name);
710 av_log_set_level(level);
714 int opt_timelimit(void *optctx, const char *opt, const char *arg)
717 int lim = parse_number_or_die(opt, arg, OPT_INT64, 0, INT_MAX);
718 struct rlimit rl = { lim, lim + 1 };
719 if (setrlimit(RLIMIT_CPU, &rl))
722 av_log(NULL, AV_LOG_WARNING, "-%s not implemented on this OS\n", opt);
727 void print_error(const char *filename, int err)
730 const char *errbuf_ptr = errbuf;
732 if (av_strerror(err, errbuf, sizeof(errbuf)) < 0)
733 errbuf_ptr = strerror(AVUNERROR(err));
734 av_log(NULL, AV_LOG_ERROR, "%s: %s\n", filename, errbuf_ptr);
737 static int warned_cfg = 0;
740 #define SHOW_VERSION 2
741 #define SHOW_CONFIG 4
743 #define PRINT_LIB_INFO(libname, LIBNAME, flags, level) \
744 if (CONFIG_##LIBNAME) { \
745 const char *indent = flags & INDENT? " " : ""; \
746 if (flags & SHOW_VERSION) { \
747 unsigned int version = libname##_version(); \
748 av_log(NULL, level, \
749 "%slib%-10s %2d.%3d.%2d / %2d.%3d.%2d\n", \
751 LIB##LIBNAME##_VERSION_MAJOR, \
752 LIB##LIBNAME##_VERSION_MINOR, \
753 LIB##LIBNAME##_VERSION_MICRO, \
754 version >> 16, version >> 8 & 0xff, version & 0xff); \
756 if (flags & SHOW_CONFIG) { \
757 const char *cfg = libname##_configuration(); \
758 if (strcmp(LIBAV_CONFIGURATION, cfg)) { \
760 av_log(NULL, level, \
761 "%sWARNING: library configuration mismatch\n", \
765 av_log(NULL, level, "%s%-11s configuration: %s\n", \
766 indent, #libname, cfg); \
771 static void print_all_libs_info(int flags, int level)
773 PRINT_LIB_INFO(avutil, AVUTIL, flags, level);
774 PRINT_LIB_INFO(avcodec, AVCODEC, flags, level);
775 PRINT_LIB_INFO(avformat, AVFORMAT, flags, level);
776 PRINT_LIB_INFO(avdevice, AVDEVICE, flags, level);
777 PRINT_LIB_INFO(avfilter, AVFILTER, flags, level);
778 PRINT_LIB_INFO(avresample, AVRESAMPLE, flags, level);
779 PRINT_LIB_INFO(swscale, SWSCALE, flags, level);
782 void show_banner(void)
784 av_log(NULL, AV_LOG_INFO,
785 "%s version " LIBAV_VERSION ", Copyright (c) %d-%d the Libav developers\n",
786 program_name, program_birth_year, this_year);
787 av_log(NULL, AV_LOG_INFO, " built on %s %s with %s\n",
788 __DATE__, __TIME__, CC_IDENT);
789 av_log(NULL, AV_LOG_VERBOSE, " configuration: " LIBAV_CONFIGURATION "\n");
790 print_all_libs_info(INDENT|SHOW_CONFIG, AV_LOG_VERBOSE);
791 print_all_libs_info(INDENT|SHOW_VERSION, AV_LOG_VERBOSE);
794 int show_version(void *optctx, const char *opt, const char *arg)
796 av_log_set_callback(log_callback_help);
797 printf("%s " LIBAV_VERSION "\n", program_name);
798 print_all_libs_info(SHOW_VERSION, AV_LOG_INFO);
803 int show_license(void *optctx, const char *opt, const char *arg)
807 "This version of %s has nonfree parts compiled in.\n"
808 "Therefore it is not legally redistributable.\n",
811 "%s is free software; you can redistribute it and/or modify\n"
812 "it under the terms of the GNU General Public License as published by\n"
813 "the Free Software Foundation; either version 3 of the License, or\n"
814 "(at your option) any later version.\n"
816 "%s is distributed in the hope that it will be useful,\n"
817 "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
818 "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n"
819 "GNU General Public License for more details.\n"
821 "You should have received a copy of the GNU General Public License\n"
822 "along with %s. If not, see <http://www.gnu.org/licenses/>.\n",
823 program_name, program_name, program_name
825 "%s is free software; you can redistribute it and/or modify\n"
826 "it under the terms of the GNU General Public License as published by\n"
827 "the Free Software Foundation; either version 2 of the License, or\n"
828 "(at your option) any later version.\n"
830 "%s is distributed in the hope that it will be useful,\n"
831 "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
832 "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n"
833 "GNU General Public License for more details.\n"
835 "You should have received a copy of the GNU General Public License\n"
836 "along with %s; if not, write to the Free Software\n"
837 "Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n",
838 program_name, program_name, program_name
840 "%s is free software; you can redistribute it and/or modify\n"
841 "it under the terms of the GNU Lesser General Public License as published by\n"
842 "the Free Software Foundation; either version 3 of the License, or\n"
843 "(at your option) any later version.\n"
845 "%s is distributed in the hope that it will be useful,\n"
846 "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
847 "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n"
848 "GNU Lesser General Public License for more details.\n"
850 "You should have received a copy of the GNU Lesser General Public License\n"
851 "along with %s. If not, see <http://www.gnu.org/licenses/>.\n",
852 program_name, program_name, program_name
854 "%s is free software; you can redistribute it and/or\n"
855 "modify it under the terms of the GNU Lesser General Public\n"
856 "License as published by the Free Software Foundation; either\n"
857 "version 2.1 of the License, or (at your option) any later version.\n"
859 "%s is distributed in the hope that it will be useful,\n"
860 "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
861 "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n"
862 "Lesser General Public License for more details.\n"
864 "You should have received a copy of the GNU Lesser General Public\n"
865 "License along with %s; if not, write to the Free Software\n"
866 "Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n",
867 program_name, program_name, program_name
874 int show_formats(void *optctx, const char *opt, const char *arg)
876 AVInputFormat *ifmt = NULL;
877 AVOutputFormat *ofmt = NULL;
878 const char *last_name;
880 printf("File formats:\n"
881 " D. = Demuxing supported\n"
882 " .E = Muxing supported\n"
888 const char *name = NULL;
889 const char *long_name = NULL;
891 while ((ofmt = av_oformat_next(ofmt))) {
892 if ((name == NULL || strcmp(ofmt->name, name) < 0) &&
893 strcmp(ofmt->name, last_name) > 0) {
895 long_name = ofmt->long_name;
899 while ((ifmt = av_iformat_next(ifmt))) {
900 if ((name == NULL || strcmp(ifmt->name, name) < 0) &&
901 strcmp(ifmt->name, last_name) > 0) {
903 long_name = ifmt->long_name;
906 if (name && strcmp(ifmt->name, name) == 0)
913 printf(" %s%s %-15s %s\n",
917 long_name ? long_name:" ");
922 #define PRINT_CODEC_SUPPORTED(codec, field, type, list_name, term, get_name) \
923 if (codec->field) { \
924 const type *p = c->field; \
926 printf(" Supported " list_name ":"); \
927 while (*p != term) { \
929 printf(" %s", name); \
935 static void print_codec(const AVCodec *c)
937 int encoder = av_codec_is_encoder(c);
939 printf("%s %s [%s]:\n", encoder ? "Encoder" : "Decoder", c->name,
940 c->long_name ? c->long_name : "");
942 if (c->type == AVMEDIA_TYPE_VIDEO) {
943 printf(" Threading capabilities: ");
944 switch (c->capabilities & (CODEC_CAP_FRAME_THREADS |
945 CODEC_CAP_SLICE_THREADS)) {
946 case CODEC_CAP_FRAME_THREADS |
947 CODEC_CAP_SLICE_THREADS: printf("frame and slice"); break;
948 case CODEC_CAP_FRAME_THREADS: printf("frame"); break;
949 case CODEC_CAP_SLICE_THREADS: printf("slice"); break;
950 default: printf("no"); break;
955 if (c->supported_framerates) {
956 const AVRational *fps = c->supported_framerates;
958 printf(" Supported framerates:");
960 printf(" %d/%d", fps->num, fps->den);
965 PRINT_CODEC_SUPPORTED(c, pix_fmts, enum AVPixelFormat, "pixel formats",
966 AV_PIX_FMT_NONE, GET_PIX_FMT_NAME);
967 PRINT_CODEC_SUPPORTED(c, supported_samplerates, int, "sample rates", 0,
968 GET_SAMPLE_RATE_NAME);
969 PRINT_CODEC_SUPPORTED(c, sample_fmts, enum AVSampleFormat, "sample formats",
970 AV_SAMPLE_FMT_NONE, GET_SAMPLE_FMT_NAME);
971 PRINT_CODEC_SUPPORTED(c, channel_layouts, uint64_t, "channel layouts",
972 0, GET_CH_LAYOUT_DESC);
975 show_help_children(c->priv_class,
976 AV_OPT_FLAG_ENCODING_PARAM |
977 AV_OPT_FLAG_DECODING_PARAM);
981 static char get_media_type_char(enum AVMediaType type)
984 case AVMEDIA_TYPE_VIDEO: return 'V';
985 case AVMEDIA_TYPE_AUDIO: return 'A';
986 case AVMEDIA_TYPE_SUBTITLE: return 'S';
991 static const AVCodec *next_codec_for_id(enum AVCodecID id, const AVCodec *prev,
994 while ((prev = av_codec_next(prev))) {
995 if (prev->id == id &&
996 (encoder ? av_codec_is_encoder(prev) : av_codec_is_decoder(prev)))
1002 static void print_codecs_for_id(enum AVCodecID id, int encoder)
1004 const AVCodec *codec = NULL;
1006 printf(" (%s: ", encoder ? "encoders" : "decoders");
1008 while ((codec = next_codec_for_id(id, codec, encoder)))
1009 printf("%s ", codec->name);
1014 int show_codecs(void *optctx, const char *opt, const char *arg)
1016 const AVCodecDescriptor *desc = NULL;
1019 " D..... = Decoding supported\n"
1020 " .E.... = Encoding supported\n"
1021 " ..V... = Video codec\n"
1022 " ..A... = Audio codec\n"
1023 " ..S... = Subtitle codec\n"
1024 " ...I.. = Intra frame-only codec\n"
1025 " ....L. = Lossy compression\n"
1026 " .....S = Lossless compression\n"
1028 while ((desc = avcodec_descriptor_next(desc))) {
1029 const AVCodec *codec = NULL;
1031 printf(avcodec_find_decoder(desc->id) ? "D" : ".");
1032 printf(avcodec_find_encoder(desc->id) ? "E" : ".");
1034 printf("%c", get_media_type_char(desc->type));
1035 printf((desc->props & AV_CODEC_PROP_INTRA_ONLY) ? "I" : ".");
1036 printf((desc->props & AV_CODEC_PROP_LOSSY) ? "L" : ".");
1037 printf((desc->props & AV_CODEC_PROP_LOSSLESS) ? "S" : ".");
1039 printf(" %-20s %s", desc->name, desc->long_name ? desc->long_name : "");
1041 /* print decoders/encoders when there's more than one or their
1042 * names are different from codec name */
1043 while ((codec = next_codec_for_id(desc->id, codec, 0))) {
1044 if (strcmp(codec->name, desc->name)) {
1045 print_codecs_for_id(desc->id, 0);
1050 while ((codec = next_codec_for_id(desc->id, codec, 1))) {
1051 if (strcmp(codec->name, desc->name)) {
1052 print_codecs_for_id(desc->id, 1);
1062 static void print_codecs(int encoder)
1064 const AVCodecDescriptor *desc = NULL;
1069 " S... = Subtitle\n"
1070 " .F.. = Frame-level multithreading\n"
1071 " ..S. = Slice-level multithreading\n"
1072 " ...X = Codec is experimental\n"
1074 encoder ? "Encoders" : "Decoders");
1075 while ((desc = avcodec_descriptor_next(desc))) {
1076 const AVCodec *codec = NULL;
1078 while ((codec = next_codec_for_id(desc->id, codec, encoder))) {
1079 printf("%c", get_media_type_char(desc->type));
1080 printf((codec->capabilities & CODEC_CAP_FRAME_THREADS) ? "F" : ".");
1081 printf((codec->capabilities & CODEC_CAP_SLICE_THREADS) ? "S" : ".");
1082 printf((codec->capabilities & CODEC_CAP_EXPERIMENTAL) ? "X" : ".");
1084 printf(" %-20s %s", codec->name, codec->long_name ? codec->long_name : "");
1085 if (strcmp(codec->name, desc->name))
1086 printf(" (codec %s)", desc->name);
1093 int show_decoders(void *optctx, const char *opt, const char *arg)
1099 int show_encoders(void *optctx, const char *opt, const char *arg)
1105 int show_bsfs(void *optctx, const char *opt, const char *arg)
1107 AVBitStreamFilter *bsf = NULL;
1109 printf("Bitstream filters:\n");
1110 while ((bsf = av_bitstream_filter_next(bsf)))
1111 printf("%s\n", bsf->name);
1116 int show_protocols(void *optctx, const char *opt, const char *arg)
1118 void *opaque = NULL;
1121 printf("Supported file protocols:\n"
1123 while ((name = avio_enum_protocols(&opaque, 0)))
1124 printf("%s\n", name);
1125 printf("Output:\n");
1126 while ((name = avio_enum_protocols(&opaque, 1)))
1127 printf("%s\n", name);
1131 int show_filters(void *optctx, const char *opt, const char *arg)
1133 AVFilter av_unused(**filter) = NULL;
1135 printf("Filters:\n");
1137 while ((filter = av_filter_next(filter)) && *filter)
1138 printf("%-16s %s\n", (*filter)->name, (*filter)->description);
1143 int show_pix_fmts(void *optctx, const char *opt, const char *arg)
1145 const AVPixFmtDescriptor *pix_desc = NULL;
1147 printf("Pixel formats:\n"
1148 "I.... = Supported Input format for conversion\n"
1149 ".O... = Supported Output format for conversion\n"
1150 "..H.. = Hardware accelerated format\n"
1151 "...P. = Paletted format\n"
1152 "....B = Bitstream format\n"
1153 "FLAGS NAME NB_COMPONENTS BITS_PER_PIXEL\n"
1157 # define sws_isSupportedInput(x) 0
1158 # define sws_isSupportedOutput(x) 0
1161 while ((pix_desc = av_pix_fmt_desc_next(pix_desc))) {
1162 enum AVPixelFormat pix_fmt = av_pix_fmt_desc_get_id(pix_desc);
1163 printf("%c%c%c%c%c %-16s %d %2d\n",
1164 sws_isSupportedInput (pix_fmt) ? 'I' : '.',
1165 sws_isSupportedOutput(pix_fmt) ? 'O' : '.',
1166 pix_desc->flags & PIX_FMT_HWACCEL ? 'H' : '.',
1167 pix_desc->flags & PIX_FMT_PAL ? 'P' : '.',
1168 pix_desc->flags & PIX_FMT_BITSTREAM ? 'B' : '.',
1170 pix_desc->nb_components,
1171 av_get_bits_per_pixel(pix_desc));
1176 int show_sample_fmts(void *optctx, const char *opt, const char *arg)
1180 for (i = -1; i < AV_SAMPLE_FMT_NB; i++)
1181 printf("%s\n", av_get_sample_fmt_string(fmt_str, sizeof(fmt_str), i));
1185 static void show_help_codec(const char *name, int encoder)
1187 const AVCodecDescriptor *desc;
1188 const AVCodec *codec;
1191 av_log(NULL, AV_LOG_ERROR, "No codec name specified.\n");
1195 codec = encoder ? avcodec_find_encoder_by_name(name) :
1196 avcodec_find_decoder_by_name(name);
1200 else if ((desc = avcodec_descriptor_get_by_name(name))) {
1203 while ((codec = next_codec_for_id(desc->id, codec, encoder))) {
1209 av_log(NULL, AV_LOG_ERROR, "Codec '%s' is known to Libav, "
1210 "but no %s for it are available. Libav might need to be "
1211 "recompiled with additional external libraries.\n",
1212 name, encoder ? "encoders" : "decoders");
1215 av_log(NULL, AV_LOG_ERROR, "Codec '%s' is not recognized by Libav.\n",
1220 static void show_help_demuxer(const char *name)
1222 const AVInputFormat *fmt = av_find_input_format(name);
1225 av_log(NULL, AV_LOG_ERROR, "Unknown format '%s'.\n", name);
1229 printf("Demuxer %s [%s]:\n", fmt->name, fmt->long_name);
1231 if (fmt->extensions)
1232 printf(" Common extensions: %s.\n", fmt->extensions);
1234 if (fmt->priv_class)
1235 show_help_children(fmt->priv_class, AV_OPT_FLAG_DECODING_PARAM);
1238 static void show_help_muxer(const char *name)
1240 const AVCodecDescriptor *desc;
1241 const AVOutputFormat *fmt = av_guess_format(name, NULL, NULL);
1244 av_log(NULL, AV_LOG_ERROR, "Unknown format '%s'.\n", name);
1248 printf("Muxer %s [%s]:\n", fmt->name, fmt->long_name);
1250 if (fmt->extensions)
1251 printf(" Common extensions: %s.\n", fmt->extensions);
1253 printf(" Mime type: %s.\n", fmt->mime_type);
1254 if (fmt->video_codec != AV_CODEC_ID_NONE &&
1255 (desc = avcodec_descriptor_get(fmt->video_codec))) {
1256 printf(" Default video codec: %s.\n", desc->name);
1258 if (fmt->audio_codec != AV_CODEC_ID_NONE &&
1259 (desc = avcodec_descriptor_get(fmt->audio_codec))) {
1260 printf(" Default audio codec: %s.\n", desc->name);
1262 if (fmt->subtitle_codec != AV_CODEC_ID_NONE &&
1263 (desc = avcodec_descriptor_get(fmt->subtitle_codec))) {
1264 printf(" Default subtitle codec: %s.\n", desc->name);
1267 if (fmt->priv_class)
1268 show_help_children(fmt->priv_class, AV_OPT_FLAG_ENCODING_PARAM);
1271 int show_help(void *optctx, const char *opt, const char *arg)
1274 av_log_set_callback(log_callback_help);
1276 topic = av_strdup(arg ? arg : "");
1277 par = strchr(topic, '=');
1282 show_help_default(topic, par);
1283 } else if (!strcmp(topic, "decoder")) {
1284 show_help_codec(par, 0);
1285 } else if (!strcmp(topic, "encoder")) {
1286 show_help_codec(par, 1);
1287 } else if (!strcmp(topic, "demuxer")) {
1288 show_help_demuxer(par);
1289 } else if (!strcmp(topic, "muxer")) {
1290 show_help_muxer(par);
1292 show_help_default(topic, par);
1299 int read_yesno(void)
1302 int yesno = (av_toupper(c) == 'Y');
1304 while (c != '\n' && c != EOF)
1310 int cmdutils_read_file(const char *filename, char **bufptr, size_t *size)
1313 FILE *f = fopen(filename, "rb");
1316 av_log(NULL, AV_LOG_ERROR, "Cannot read file '%s': %s\n", filename,
1318 return AVERROR(errno);
1320 fseek(f, 0, SEEK_END);
1322 fseek(f, 0, SEEK_SET);
1323 *bufptr = av_malloc(*size + 1);
1325 av_log(NULL, AV_LOG_ERROR, "Could not allocate file buffer\n");
1327 return AVERROR(ENOMEM);
1329 ret = fread(*bufptr, 1, *size, f);
1333 av_log(NULL, AV_LOG_ERROR, "Error while reading file '%s': %s\n",
1334 filename, strerror(errno));
1335 ret = AVERROR(errno);
1340 (*bufptr)[(*size)++] = '\0';
1347 void init_pts_correction(PtsCorrectionContext *ctx)
1349 ctx->num_faulty_pts = ctx->num_faulty_dts = 0;
1350 ctx->last_pts = ctx->last_dts = INT64_MIN;
1353 int64_t guess_correct_pts(PtsCorrectionContext *ctx, int64_t reordered_pts,
1356 int64_t pts = AV_NOPTS_VALUE;
1358 if (dts != AV_NOPTS_VALUE) {
1359 ctx->num_faulty_dts += dts <= ctx->last_dts;
1360 ctx->last_dts = dts;
1362 if (reordered_pts != AV_NOPTS_VALUE) {
1363 ctx->num_faulty_pts += reordered_pts <= ctx->last_pts;
1364 ctx->last_pts = reordered_pts;
1366 if ((ctx->num_faulty_pts<=ctx->num_faulty_dts || dts == AV_NOPTS_VALUE)
1367 && reordered_pts != AV_NOPTS_VALUE)
1368 pts = reordered_pts;
1375 FILE *get_preset_file(char *filename, size_t filename_size,
1376 const char *preset_name, int is_path,
1377 const char *codec_name)
1381 const char *base[3] = { getenv("AVCONV_DATADIR"),
1386 av_strlcpy(filename, preset_name, filename_size);
1387 f = fopen(filename, "r");
1389 for (i = 0; i < 3 && !f; i++) {
1392 snprintf(filename, filename_size, "%s%s/%s.avpreset", base[i],
1393 i != 1 ? "" : "/.avconv", preset_name);
1394 f = fopen(filename, "r");
1395 if (!f && codec_name) {
1396 snprintf(filename, filename_size,
1397 "%s%s/%s-%s.avpreset",
1398 base[i], i != 1 ? "" : "/.avconv", codec_name,
1400 f = fopen(filename, "r");
1408 int check_stream_specifier(AVFormatContext *s, AVStream *st, const char *spec)
1410 if (*spec <= '9' && *spec >= '0') /* opt:index */
1411 return strtol(spec, NULL, 0) == st->index;
1412 else if (*spec == 'v' || *spec == 'a' || *spec == 's' || *spec == 'd' ||
1413 *spec == 't') { /* opt:[vasdt] */
1414 enum AVMediaType type;
1417 case 'v': type = AVMEDIA_TYPE_VIDEO; break;
1418 case 'a': type = AVMEDIA_TYPE_AUDIO; break;
1419 case 's': type = AVMEDIA_TYPE_SUBTITLE; break;
1420 case 'd': type = AVMEDIA_TYPE_DATA; break;
1421 case 't': type = AVMEDIA_TYPE_ATTACHMENT; break;
1422 default: av_assert0(0);
1424 if (type != st->codec->codec_type)
1426 if (*spec++ == ':') { /* possibly followed by :index */
1427 int i, index = strtol(spec, NULL, 0);
1428 for (i = 0; i < s->nb_streams; i++)
1429 if (s->streams[i]->codec->codec_type == type && index-- == 0)
1430 return i == st->index;
1434 } else if (*spec == 'p' && *(spec + 1) == ':') {
1438 prog_id = strtol(spec, &endptr, 0);
1439 for (i = 0; i < s->nb_programs; i++) {
1440 if (s->programs[i]->id != prog_id)
1443 if (*endptr++ == ':') {
1444 int stream_idx = strtol(endptr, NULL, 0);
1445 return stream_idx >= 0 &&
1446 stream_idx < s->programs[i]->nb_stream_indexes &&
1447 st->index == s->programs[i]->stream_index[stream_idx];
1450 for (j = 0; j < s->programs[i]->nb_stream_indexes; j++)
1451 if (st->index == s->programs[i]->stream_index[j])
1455 } else if (!*spec) /* empty specifier, matches everything */
1458 av_log(s, AV_LOG_ERROR, "Invalid stream specifier: %s.\n", spec);
1459 return AVERROR(EINVAL);
1462 AVDictionary *filter_codec_opts(AVDictionary *opts, enum AVCodecID codec_id,
1463 AVFormatContext *s, AVStream *st, AVCodec *codec)
1465 AVDictionary *ret = NULL;
1466 AVDictionaryEntry *t = NULL;
1467 int flags = s->oformat ? AV_OPT_FLAG_ENCODING_PARAM
1468 : AV_OPT_FLAG_DECODING_PARAM;
1470 const AVClass *cc = avcodec_get_class();
1473 codec = s->oformat ? avcodec_find_encoder(codec_id)
1474 : avcodec_find_decoder(codec_id);
1476 switch (st->codec->codec_type) {
1477 case AVMEDIA_TYPE_VIDEO:
1479 flags |= AV_OPT_FLAG_VIDEO_PARAM;
1481 case AVMEDIA_TYPE_AUDIO:
1483 flags |= AV_OPT_FLAG_AUDIO_PARAM;
1485 case AVMEDIA_TYPE_SUBTITLE:
1487 flags |= AV_OPT_FLAG_SUBTITLE_PARAM;
1491 while (t = av_dict_get(opts, "", t, AV_DICT_IGNORE_SUFFIX)) {
1492 char *p = strchr(t->key, ':');
1494 /* check stream specification in opt name */
1496 switch (check_stream_specifier(s, st, p + 1)) {
1497 case 1: *p = 0; break;
1499 default: return NULL;
1502 if (av_opt_find(&cc, t->key, NULL, flags, AV_OPT_SEARCH_FAKE_OBJ) ||
1503 (codec && codec->priv_class &&
1504 av_opt_find(&codec->priv_class, t->key, NULL, flags,
1505 AV_OPT_SEARCH_FAKE_OBJ)))
1506 av_dict_set(&ret, t->key, t->value, 0);
1507 else if (t->key[0] == prefix &&
1508 av_opt_find(&cc, t->key + 1, NULL, flags,
1509 AV_OPT_SEARCH_FAKE_OBJ))
1510 av_dict_set(&ret, t->key + 1, t->value, 0);
1518 AVDictionary **setup_find_stream_info_opts(AVFormatContext *s,
1519 AVDictionary *codec_opts)
1522 AVDictionary **opts;
1526 opts = av_mallocz(s->nb_streams * sizeof(*opts));
1528 av_log(NULL, AV_LOG_ERROR,
1529 "Could not alloc memory for stream options.\n");
1532 for (i = 0; i < s->nb_streams; i++)
1533 opts[i] = filter_codec_opts(codec_opts, s->streams[i]->codec->codec_id,
1534 s, s->streams[i], NULL);
1538 void *grow_array(void *array, int elem_size, int *size, int new_size)
1540 if (new_size >= INT_MAX / elem_size) {
1541 av_log(NULL, AV_LOG_ERROR, "Array too big.\n");
1544 if (*size < new_size) {
1545 uint8_t *tmp = av_realloc(array, new_size*elem_size);
1547 av_log(NULL, AV_LOG_ERROR, "Could not alloc buffer.\n");
1550 memset(tmp + *size*elem_size, 0, (new_size-*size) * elem_size);