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
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 "compat/va_copy.h"
33 #include "libavformat/avformat.h"
34 #include "libavfilter/avfilter.h"
35 #include "libavdevice/avdevice.h"
36 #include "libavresample/avresample.h"
37 #include "libswscale/swscale.h"
38 #include "libswresample/swresample.h"
40 #include "libpostproc/postprocess.h"
42 #include "libavutil/avassert.h"
43 #include "libavutil/avstring.h"
44 #include "libavutil/bprint.h"
45 #include "libavutil/mathematics.h"
46 #include "libavutil/imgutils.h"
47 #include "libavutil/parseutils.h"
48 #include "libavutil/pixdesc.h"
49 #include "libavutil/eval.h"
50 #include "libavutil/dict.h"
51 #include "libavutil/opt.h"
55 #include "libavformat/network.h"
57 #if HAVE_SYS_RESOURCE_H
59 #include <sys/resource.h>
62 static int init_report(const char *env);
64 struct SwsContext *sws_opts;
66 AVDictionary *format_opts, *codec_opts;
68 const int this_year = 2012;
70 static FILE *report_file;
76 sws_opts = sws_getContext(16, 16, 0, 16, 16, 0, SWS_BICUBIC,
80 swr_opts = swr_alloc();
83 void uninit_opts(void)
86 sws_freeContext(sws_opts);
93 av_dict_free(&format_opts);
94 av_dict_free(&codec_opts);
97 void log_callback_help(void *ptr, int level, const char *fmt, va_list vl)
99 vfprintf(stdout, fmt, vl);
102 static void log_callback_report(void *ptr, int level, const char *fmt, va_list vl)
106 static int print_prefix = 1;
109 av_log_default_callback(ptr, level, fmt, vl);
110 av_log_format_line(ptr, level, fmt, vl2, line, sizeof(line), &print_prefix);
112 fputs(line, report_file);
116 double parse_number_or_die(const char *context, const char *numstr, int type,
117 double min, double max)
121 double d = av_strtod(numstr, &tail);
123 error = "Expected number for %s but found: %s\n";
124 else if (d < min || d > max)
125 error = "The value for %s was %s which is not within %f - %f\n";
126 else if (type == OPT_INT64 && (int64_t)d != d)
127 error = "Expected int64 for %s but found %s\n";
128 else if (type == OPT_INT && (int)d != d)
129 error = "Expected int for %s but found %s\n";
132 av_log(NULL, AV_LOG_FATAL, error, context, numstr, min, max);
137 int64_t parse_time_or_die(const char *context, const char *timestr,
141 if (av_parse_time(&us, timestr, is_duration) < 0) {
142 av_log(NULL, AV_LOG_FATAL, "Invalid %s specification for %s: %s\n",
143 is_duration ? "duration" : "date", context, timestr);
149 void show_help_options(const OptionDef *options, const char *msg, int req_flags,
150 int rej_flags, int alt_flags)
156 for (po = options; po->name != NULL; po++) {
159 if (((po->flags & req_flags) != req_flags) ||
160 (alt_flags && !(po->flags & alt_flags)) ||
161 (po->flags & rej_flags))
168 av_strlcpy(buf, po->name, sizeof(buf));
170 av_strlcat(buf, " ", sizeof(buf));
171 av_strlcat(buf, po->argname, sizeof(buf));
173 printf("-%-17s %s\n", buf, po->help);
178 void show_help_children(const AVClass *class, int flags)
180 const AVClass *child = NULL;
182 av_opt_show2(&class, NULL, flags, 0);
186 while (child = av_opt_child_class_next(class, child))
187 show_help_children(child, flags);
190 static const OptionDef *find_option(const OptionDef *po, const char *name)
192 const char *p = strchr(name, ':');
193 int len = p ? p - name : strlen(name);
195 while (po->name != NULL) {
196 if (!strncmp(name, po->name, len) && strlen(po->name) == len)
203 #if HAVE_COMMANDLINETOARGVW
205 #include <shellapi.h>
206 /* Will be leaked on exit */
207 static char** win32_argv_utf8 = NULL;
208 static int win32_argc = 0;
211 * Prepare command line arguments for executable.
212 * For Windows - perform wide-char to UTF-8 conversion.
213 * Input arguments should be main() function arguments.
214 * @param argc_ptr Arguments number (including executable)
215 * @param argv_ptr Arguments list.
217 static void prepare_app_arguments(int *argc_ptr, char ***argv_ptr)
221 int i, buffsize = 0, offset = 0;
223 if (win32_argv_utf8) {
224 *argc_ptr = win32_argc;
225 *argv_ptr = win32_argv_utf8;
230 argv_w = CommandLineToArgvW(GetCommandLineW(), &win32_argc);
231 if (win32_argc <= 0 || !argv_w)
234 /* determine the UTF-8 buffer size (including NULL-termination symbols) */
235 for (i = 0; i < win32_argc; i++)
236 buffsize += WideCharToMultiByte(CP_UTF8, 0, argv_w[i], -1,
237 NULL, 0, NULL, NULL);
239 win32_argv_utf8 = av_mallocz(sizeof(char *) * (win32_argc + 1) + buffsize);
240 argstr_flat = (char *)win32_argv_utf8 + sizeof(char *) * (win32_argc + 1);
241 if (win32_argv_utf8 == NULL) {
246 for (i = 0; i < win32_argc; i++) {
247 win32_argv_utf8[i] = &argstr_flat[offset];
248 offset += WideCharToMultiByte(CP_UTF8, 0, argv_w[i], -1,
249 &argstr_flat[offset],
250 buffsize - offset, NULL, NULL);
252 win32_argv_utf8[i] = NULL;
255 *argc_ptr = win32_argc;
256 *argv_ptr = win32_argv_utf8;
259 static inline void prepare_app_arguments(int *argc_ptr, char ***argv_ptr)
263 #endif /* HAVE_COMMANDLINETOARGVW */
265 static int write_option(void *optctx, const OptionDef *po, const char *opt,
268 /* new-style options contain an offset into optctx, old-style address of
270 void *dst = po->flags & (OPT_OFFSET | OPT_SPEC) ?
271 (uint8_t *)optctx + po->u.off : po->u.dst_ptr;
274 if (po->flags & OPT_SPEC) {
275 SpecifierOpt **so = dst;
276 char *p = strchr(opt, ':');
278 dstcount = (int *)(so + 1);
279 *so = grow_array(*so, sizeof(**so), dstcount, *dstcount + 1);
280 (*so)[*dstcount - 1].specifier = av_strdup(p ? p + 1 : "");
281 dst = &(*so)[*dstcount - 1].u;
284 if (po->flags & OPT_STRING) {
286 str = av_strdup(arg);
289 } else if (po->flags & OPT_BOOL || po->flags & OPT_INT) {
290 *(int *)dst = parse_number_or_die(opt, arg, OPT_INT64, INT_MIN, INT_MAX);
291 } else if (po->flags & OPT_INT64) {
292 *(int64_t *)dst = parse_number_or_die(opt, arg, OPT_INT64, INT64_MIN, INT64_MAX);
293 } else if (po->flags & OPT_TIME) {
294 *(int64_t *)dst = parse_time_or_die(opt, arg, 1);
295 } else if (po->flags & OPT_FLOAT) {
296 *(float *)dst = parse_number_or_die(opt, arg, OPT_FLOAT, -INFINITY, INFINITY);
297 } else if (po->flags & OPT_DOUBLE) {
298 *(double *)dst = parse_number_or_die(opt, arg, OPT_DOUBLE, -INFINITY, INFINITY);
299 } else if (po->u.func_arg) {
300 int ret = po->u.func_arg(optctx, opt, arg);
302 av_log(NULL, AV_LOG_ERROR,
303 "Failed to set value '%s' for option '%s'\n", arg, opt);
307 if (po->flags & OPT_EXIT)
313 int parse_option(void *optctx, const char *opt, const char *arg,
314 const OptionDef *options)
319 po = find_option(options, opt);
320 if (!po->name && opt[0] == 'n' && opt[1] == 'o') {
321 /* handle 'no' bool option */
322 po = find_option(options, opt + 2);
323 if ((po->name && (po->flags & OPT_BOOL)))
325 } else if (po->flags & OPT_BOOL)
329 po = find_option(options, "default");
331 av_log(NULL, AV_LOG_ERROR, "Unrecognized option '%s'\n", opt);
332 return AVERROR(EINVAL);
334 if (po->flags & HAS_ARG && !arg) {
335 av_log(NULL, AV_LOG_ERROR, "Missing argument for option '%s'\n", opt);
336 return AVERROR(EINVAL);
339 ret = write_option(optctx, po, opt, arg);
343 return !!(po->flags & HAS_ARG);
346 void parse_options(void *optctx, int argc, char **argv, const OptionDef *options,
347 void (*parse_arg_function)(void *, const char*))
350 int optindex, handleoptions = 1, ret;
352 /* perform system-dependent conversions for arguments list */
353 prepare_app_arguments(&argc, &argv);
357 while (optindex < argc) {
358 opt = argv[optindex++];
360 if (handleoptions && opt[0] == '-' && opt[1] != '\0') {
361 if (opt[1] == '-' && opt[2] == '\0') {
367 if ((ret = parse_option(optctx, opt, argv[optindex], options)) < 0)
371 if (parse_arg_function)
372 parse_arg_function(optctx, opt);
377 int parse_optgroup(void *optctx, OptionGroup *g)
381 av_log(NULL, AV_LOG_DEBUG, "Parsing a group of options: %s %s.\n",
382 g->group_def->name, g->arg);
384 for (i = 0; i < g->nb_opts; i++) {
385 Option *o = &g->opts[i];
387 av_log(NULL, AV_LOG_DEBUG, "Applying option %s (%s) with argument %s.\n",
388 o->key, o->opt->help, o->val);
390 ret = write_option(optctx, o->opt, o->key, o->val);
395 av_log(NULL, AV_LOG_DEBUG, "Successfully parsed a group of options.\n");
400 int locate_option(int argc, char **argv, const OptionDef *options,
406 for (i = 1; i < argc; i++) {
407 const char *cur_opt = argv[i];
409 if (*cur_opt++ != '-')
412 po = find_option(options, cur_opt);
413 if (!po->name && cur_opt[0] == 'n' && cur_opt[1] == 'o')
414 po = find_option(options, cur_opt + 2);
416 if ((!po->name && !strcmp(cur_opt, optname)) ||
417 (po->name && !strcmp(optname, po->name)))
420 if (po->flags & HAS_ARG)
426 static void dump_argument(const char *a)
428 const unsigned char *p;
431 if (!((*p >= '+' && *p <= ':') || (*p >= '@' && *p <= 'Z') ||
432 *p == '_' || (*p >= 'a' && *p <= 'z')))
435 fputs(a, report_file);
438 fputc('"', report_file);
439 for (p = a; *p; p++) {
440 if (*p == '\\' || *p == '"' || *p == '$' || *p == '`')
441 fprintf(report_file, "\\%c", *p);
442 else if (*p < ' ' || *p > '~')
443 fprintf(report_file, "\\x%02x", *p);
445 fputc(*p, report_file);
447 fputc('"', report_file);
450 void parse_loglevel(int argc, char **argv, const OptionDef *options)
452 int idx = locate_option(argc, argv, options, "loglevel");
455 idx = locate_option(argc, argv, options, "v");
456 if (idx && argv[idx + 1])
457 opt_loglevel(NULL, "loglevel", argv[idx + 1]);
458 idx = locate_option(argc, argv, options, "report");
459 if ((env = getenv("FFREPORT")) || idx) {
463 fprintf(report_file, "Command line:\n");
464 for (i = 0; i < argc; i++) {
465 dump_argument(argv[i]);
466 fputc(i < argc - 1 ? ' ' : '\n', report_file);
473 #define FLAGS (o->type == AV_OPT_TYPE_FLAGS) ? AV_DICT_APPEND : 0
474 int opt_default(void *optctx, const char *opt, const char *arg)
478 char opt_stripped[128];
480 const AVClass *cc = avcodec_get_class(), *fc = avformat_get_class();
481 const AVClass *sc, *swr_class;
483 if (!strcmp(opt, "debug") || !strcmp(opt, "fdebug"))
484 av_log_set_level(AV_LOG_DEBUG);
486 if (!(p = strchr(opt, ':')))
487 p = opt + strlen(opt);
488 av_strlcpy(opt_stripped, opt, FFMIN(sizeof(opt_stripped), p - opt + 1));
490 if ((o = av_opt_find(&cc, opt_stripped, NULL, 0,
491 AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ)) ||
492 ((opt[0] == 'v' || opt[0] == 'a' || opt[0] == 's') &&
493 (o = av_opt_find(&cc, opt + 1, NULL, 0, AV_OPT_SEARCH_FAKE_OBJ)))) {
494 av_dict_set(&codec_opts, opt, arg, FLAGS);
497 if ((o = av_opt_find(&fc, opt, NULL, 0,
498 AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ))) {
499 av_dict_set(&format_opts, opt, arg, FLAGS);
501 av_log(NULL, AV_LOG_VERBOSE, "Routing %s to codec and muxer layer\n", opt);
505 sc = sws_get_class();
506 if (!consumed && av_opt_find(&sc, opt, NULL, 0,
507 AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ)) {
508 // XXX we only support sws_flags, not arbitrary sws options
509 int ret = av_opt_set(sws_opts, opt, arg, 0);
511 av_log(NULL, AV_LOG_ERROR, "Error setting option %s.\n", opt);
517 #if CONFIG_SWRESAMPLE
518 swr_class = swr_get_class();
519 if (!consumed && av_opt_find(&swr_class, opt, NULL, 0,
520 AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ)) {
521 int ret = av_opt_set(swr_opts, opt, arg, 0);
523 av_log(NULL, AV_LOG_ERROR, "Error setting option %s.\n", opt);
532 return AVERROR_OPTION_NOT_FOUND;
536 * Check whether given option is a group separator.
538 * @return index of the group definition that matched or -1 if none
540 static int match_group_separator(const OptionGroupDef *groups, int nb_groups,
545 for (i = 0; i < nb_groups; i++) {
546 const OptionGroupDef *p = &groups[i];
547 if (p->sep && !strcmp(p->sep, opt))
555 * Finish parsing an option group.
557 * @param group_idx which group definition should this group belong to
558 * @param arg argument of the group delimiting option
560 static void finish_group(OptionParseContext *octx, int group_idx,
563 OptionGroupList *l = &octx->groups[group_idx];
566 GROW_ARRAY(l->groups, l->nb_groups);
567 g = &l->groups[l->nb_groups - 1];
569 *g = octx->cur_group;
571 g->group_def = l->group_def;
573 g->sws_opts = sws_opts;
575 g->swr_opts = swr_opts;
576 g->codec_opts = codec_opts;
577 g->format_opts = format_opts;
587 memset(&octx->cur_group, 0, sizeof(octx->cur_group));
591 * Add an option instance to currently parsed group.
593 static void add_opt(OptionParseContext *octx, const OptionDef *opt,
594 const char *key, const char *val)
596 int global = !(opt->flags & (OPT_PERFILE | OPT_SPEC | OPT_OFFSET));
597 OptionGroup *g = global ? &octx->global_opts : &octx->cur_group;
599 GROW_ARRAY(g->opts, g->nb_opts);
600 g->opts[g->nb_opts - 1].opt = opt;
601 g->opts[g->nb_opts - 1].key = key;
602 g->opts[g->nb_opts - 1].val = val;
605 static void init_parse_context(OptionParseContext *octx,
606 const OptionGroupDef *groups, int nb_groups)
608 static const OptionGroupDef global_group = { "global" };
611 memset(octx, 0, sizeof(*octx));
613 octx->nb_groups = nb_groups;
614 octx->groups = av_mallocz(sizeof(*octx->groups) * octx->nb_groups);
618 for (i = 0; i < octx->nb_groups; i++)
619 octx->groups[i].group_def = &groups[i];
621 octx->global_opts.group_def = &global_group;
622 octx->global_opts.arg = "";
627 void uninit_parse_context(OptionParseContext *octx)
631 for (i = 0; i < octx->nb_groups; i++) {
632 OptionGroupList *l = &octx->groups[i];
634 for (j = 0; j < l->nb_groups; j++) {
635 av_freep(&l->groups[j].opts);
636 av_dict_free(&l->groups[j].codec_opts);
637 av_dict_free(&l->groups[j].format_opts);
639 sws_freeContext(l->groups[j].sws_opts);
641 if(CONFIG_SWRESAMPLE)
642 swr_free(&l->groups[j].swr_opts);
644 av_freep(&l->groups);
646 av_freep(&octx->groups);
648 av_freep(&octx->cur_group.opts);
649 av_freep(&octx->global_opts.opts);
654 int split_commandline(OptionParseContext *octx, int argc, char *argv[],
655 const OptionDef *options,
656 const OptionGroupDef *groups, int nb_groups)
660 /* perform system-dependent conversions for arguments list */
661 prepare_app_arguments(&argc, &argv);
663 init_parse_context(octx, groups, nb_groups);
664 av_log(NULL, AV_LOG_DEBUG, "Splitting the commandline.\n");
666 while (optindex < argc) {
667 const char *opt = argv[optindex++], *arg;
671 av_log(NULL, AV_LOG_DEBUG, "Reading option '%s' ...", opt);
673 /* unnamed group separators, e.g. output filename */
674 if (opt[0] != '-' || !opt[1]) {
675 finish_group(octx, 0, opt);
676 av_log(NULL, AV_LOG_DEBUG, " matched as %s.\n", groups[0].name);
681 #define GET_ARG(arg) \
683 arg = argv[optindex++]; \
685 av_log(NULL, AV_LOG_ERROR, "Missing argument for option '%s'.\n", opt);\
686 return AVERROR(EINVAL); \
690 /* named group separators, e.g. -i */
691 if ((ret = match_group_separator(groups, nb_groups, opt)) >= 0) {
693 finish_group(octx, ret, arg);
694 av_log(NULL, AV_LOG_DEBUG, " matched as %s with argument '%s'.\n",
695 groups[ret].name, arg);
700 po = find_option(options, opt);
702 if (po->flags & OPT_EXIT) {
703 /* optional argument, e.g. -h */
704 arg = argv[optindex++];
705 } else if (po->flags & HAS_ARG) {
711 add_opt(octx, po, opt, arg);
712 av_log(NULL, AV_LOG_DEBUG, " matched as option '%s' (%s) with "
713 "argument '%s'.\n", po->name, po->help, arg);
718 if (argv[optindex]) {
719 ret = opt_default(NULL, opt, argv[optindex]);
721 av_log(NULL, AV_LOG_DEBUG, " matched as AVOption '%s' with "
722 "argument '%s'.\n", opt, argv[optindex]);
725 } else if (ret != AVERROR_OPTION_NOT_FOUND) {
726 av_log(NULL, AV_LOG_ERROR, "Error parsing option '%s' "
727 "with argument '%s'.\n", opt, argv[optindex]);
732 /* boolean -nofoo options */
733 if (opt[0] == 'n' && opt[1] == 'o' &&
734 (po = find_option(options, opt + 2)) &&
735 po->name && po->flags & OPT_BOOL) {
736 add_opt(octx, po, opt, "0");
737 av_log(NULL, AV_LOG_DEBUG, " matched as option '%s' (%s) with "
738 "argument 0.\n", po->name, po->help);
742 av_log(NULL, AV_LOG_ERROR, "Unrecognized option '%s'.\n", opt);
743 return AVERROR_OPTION_NOT_FOUND;
746 if (octx->cur_group.nb_opts || codec_opts || format_opts)
747 av_log(NULL, AV_LOG_WARNING, "Trailing options were found on the "
750 av_log(NULL, AV_LOG_DEBUG, "Finished splitting the commandline.\n");
755 int opt_loglevel(void *optctx, const char *opt, const char *arg)
757 const struct { const char *name; int level; } log_levels[] = {
758 { "quiet" , AV_LOG_QUIET },
759 { "panic" , AV_LOG_PANIC },
760 { "fatal" , AV_LOG_FATAL },
761 { "error" , AV_LOG_ERROR },
762 { "warning", AV_LOG_WARNING },
763 { "info" , AV_LOG_INFO },
764 { "verbose", AV_LOG_VERBOSE },
765 { "debug" , AV_LOG_DEBUG },
771 for (i = 0; i < FF_ARRAY_ELEMS(log_levels); i++) {
772 if (!strcmp(log_levels[i].name, arg)) {
773 av_log_set_level(log_levels[i].level);
778 level = strtol(arg, &tail, 10);
780 av_log(NULL, AV_LOG_FATAL, "Invalid loglevel \"%s\". "
781 "Possible levels are numbers or:\n", arg);
782 for (i = 0; i < FF_ARRAY_ELEMS(log_levels); i++)
783 av_log(NULL, AV_LOG_FATAL, "\"%s\"\n", log_levels[i].name);
786 av_log_set_level(level);
790 static void expand_filename_template(AVBPrint *bp, const char *template,
795 while ((c = *(template++))) {
797 if (!(c = *(template++)))
801 av_bprintf(bp, "%s", program_name);
804 av_bprintf(bp, "%04d%02d%02d-%02d%02d%02d",
805 tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday,
806 tm->tm_hour, tm->tm_min, tm->tm_sec);
809 av_bprint_chars(bp, c, 1);
813 av_bprint_chars(bp, c, 1);
818 static int init_report(const char *env)
820 char *filename_template = NULL;
827 if (report_file) /* already opened */
830 tm = localtime(&now);
832 while (env && *env) {
833 if ((ret = av_opt_get_key_value(&env, "=", ":", 0, &key, &val)) < 0) {
835 av_log(NULL, AV_LOG_ERROR,
836 "Failed to parse FFREPORT environment variable: %s\n",
843 if (!strcmp(key, "file")) {
844 av_free(filename_template);
845 filename_template = val;
848 av_log(NULL, AV_LOG_ERROR, "Unknown key '%s' in FFREPORT\n", key);
854 av_bprint_init(&filename, 0, 1);
855 expand_filename_template(&filename,
856 av_x_if_null(filename_template, "%p-%t.log"), tm);
857 av_free(filename_template);
858 if (!av_bprint_is_complete(&filename)) {
859 av_log(NULL, AV_LOG_ERROR, "Out of memory building report file name\n");
860 return AVERROR(ENOMEM);
863 report_file = fopen(filename.str, "w");
865 av_log(NULL, AV_LOG_ERROR, "Failed to open report \"%s\": %s\n",
866 filename.str, strerror(errno));
867 return AVERROR(errno);
869 av_log_set_callback(log_callback_report);
870 av_log(NULL, AV_LOG_INFO,
871 "%s started on %04d-%02d-%02d at %02d:%02d:%02d\n"
872 "Report written to \"%s\"\n",
874 tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday,
875 tm->tm_hour, tm->tm_min, tm->tm_sec,
877 av_log_set_level(FFMAX(av_log_get_level(), AV_LOG_VERBOSE));
878 av_bprint_finalize(&filename, NULL);
882 int opt_report(const char *opt)
884 return init_report(NULL);
887 int opt_max_alloc(void *optctx, const char *opt, const char *arg)
892 max = strtol(arg, &tail, 10);
894 av_log(NULL, AV_LOG_FATAL, "Invalid max_alloc \"%s\".\n", arg);
901 int opt_cpuflags(void *optctx, const char *opt, const char *arg)
904 unsigned flags = av_get_cpu_flags();
906 if ((ret = av_parse_cpu_caps(&flags, arg)) < 0)
909 av_force_cpu_flags(flags);
913 int opt_timelimit(void *optctx, const char *opt, const char *arg)
916 int lim = parse_number_or_die(opt, arg, OPT_INT64, 0, INT_MAX);
917 struct rlimit rl = { lim, lim + 1 };
918 if (setrlimit(RLIMIT_CPU, &rl))
921 av_log(NULL, AV_LOG_WARNING, "-%s not implemented on this OS\n", opt);
926 void print_error(const char *filename, int err)
929 const char *errbuf_ptr = errbuf;
931 if (av_strerror(err, errbuf, sizeof(errbuf)) < 0)
932 errbuf_ptr = strerror(AVUNERROR(err));
933 av_log(NULL, AV_LOG_ERROR, "%s: %s\n", filename, errbuf_ptr);
936 static int warned_cfg = 0;
939 #define SHOW_VERSION 2
940 #define SHOW_CONFIG 4
941 #define SHOW_COPYRIGHT 8
943 #define PRINT_LIB_INFO(libname, LIBNAME, flags, level) \
944 if (CONFIG_##LIBNAME) { \
945 const char *indent = flags & INDENT? " " : ""; \
946 if (flags & SHOW_VERSION) { \
947 unsigned int version = libname##_version(); \
948 av_log(NULL, level, \
949 "%slib%-11s %2d.%3d.%3d / %2d.%3d.%3d\n", \
951 LIB##LIBNAME##_VERSION_MAJOR, \
952 LIB##LIBNAME##_VERSION_MINOR, \
953 LIB##LIBNAME##_VERSION_MICRO, \
954 version >> 16, version >> 8 & 0xff, version & 0xff); \
956 if (flags & SHOW_CONFIG) { \
957 const char *cfg = libname##_configuration(); \
958 if (strcmp(FFMPEG_CONFIGURATION, cfg)) { \
960 av_log(NULL, level, \
961 "%sWARNING: library configuration mismatch\n", \
965 av_log(NULL, level, "%s%-11s configuration: %s\n", \
966 indent, #libname, cfg); \
971 static void print_all_libs_info(int flags, int level)
973 PRINT_LIB_INFO(avutil, AVUTIL, flags, level);
974 PRINT_LIB_INFO(avcodec, AVCODEC, flags, level);
975 PRINT_LIB_INFO(avformat, AVFORMAT, flags, level);
976 PRINT_LIB_INFO(avdevice, AVDEVICE, flags, level);
977 PRINT_LIB_INFO(avfilter, AVFILTER, flags, level);
978 // PRINT_LIB_INFO(avresample, AVRESAMPLE, flags, level);
979 PRINT_LIB_INFO(swscale, SWSCALE, flags, level);
980 PRINT_LIB_INFO(swresample,SWRESAMPLE, flags, level);
982 PRINT_LIB_INFO(postproc, POSTPROC, flags, level);
986 static void print_program_info(int flags, int level)
988 const char *indent = flags & INDENT? " " : "";
990 av_log(NULL, level, "%s version " FFMPEG_VERSION, program_name);
991 if (flags & SHOW_COPYRIGHT)
992 av_log(NULL, level, " Copyright (c) %d-%d the FFmpeg developers",
993 program_birth_year, this_year);
994 av_log(NULL, level, "\n");
995 av_log(NULL, level, "%sbuilt on %s %s with %s\n",
996 indent, __DATE__, __TIME__, CC_IDENT);
998 av_log(NULL, level, "%sconfiguration: " FFMPEG_CONFIGURATION "\n", indent);
1001 void show_banner(int argc, char **argv, const OptionDef *options)
1003 int idx = locate_option(argc, argv, options, "version");
1007 print_program_info (INDENT|SHOW_COPYRIGHT, AV_LOG_INFO);
1008 print_all_libs_info(INDENT|SHOW_CONFIG, AV_LOG_INFO);
1009 print_all_libs_info(INDENT|SHOW_VERSION, AV_LOG_INFO);
1012 int show_version(void *optctx, const char *opt, const char *arg)
1014 av_log_set_callback(log_callback_help);
1015 print_program_info (0 , AV_LOG_INFO);
1016 print_all_libs_info(SHOW_VERSION, AV_LOG_INFO);
1021 int show_license(void *optctx, const char *opt, const char *arg)
1025 "This version of %s has nonfree parts compiled in.\n"
1026 "Therefore it is not legally redistributable.\n",
1030 "%s is free software; you can redistribute it and/or modify\n"
1031 "it under the terms of the GNU General Public License as published by\n"
1032 "the Free Software Foundation; either version 3 of the License, or\n"
1033 "(at your option) any later version.\n"
1035 "%s is distributed in the hope that it will be useful,\n"
1036 "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
1037 "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n"
1038 "GNU General Public License for more details.\n"
1040 "You should have received a copy of the GNU General Public License\n"
1041 "along with %s. If not, see <http://www.gnu.org/licenses/>.\n",
1042 program_name, program_name, program_name );
1045 "%s is free software; you can redistribute it and/or modify\n"
1046 "it under the terms of the GNU General Public License as published by\n"
1047 "the Free Software Foundation; either version 2 of the License, or\n"
1048 "(at your option) any later version.\n"
1050 "%s is distributed in the hope that it will be useful,\n"
1051 "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
1052 "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n"
1053 "GNU General Public License for more details.\n"
1055 "You should have received a copy of the GNU General Public License\n"
1056 "along with %s; if not, write to the Free Software\n"
1057 "Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n",
1058 program_name, program_name, program_name );
1061 "%s is free software; you can redistribute it and/or modify\n"
1062 "it under the terms of the GNU Lesser General Public License as published by\n"
1063 "the Free Software Foundation; either version 3 of the License, or\n"
1064 "(at your option) any later version.\n"
1066 "%s is distributed in the hope that it will be useful,\n"
1067 "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
1068 "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n"
1069 "GNU Lesser General Public License for more details.\n"
1071 "You should have received a copy of the GNU Lesser General Public License\n"
1072 "along with %s. If not, see <http://www.gnu.org/licenses/>.\n",
1073 program_name, program_name, program_name );
1076 "%s is free software; you can redistribute it and/or\n"
1077 "modify it under the terms of the GNU Lesser General Public\n"
1078 "License as published by the Free Software Foundation; either\n"
1079 "version 2.1 of the License, or (at your option) any later version.\n"
1081 "%s is distributed in the hope that it will be useful,\n"
1082 "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
1083 "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n"
1084 "Lesser General Public License for more details.\n"
1086 "You should have received a copy of the GNU Lesser General Public\n"
1087 "License along with %s; if not, write to the Free Software\n"
1088 "Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n",
1089 program_name, program_name, program_name );
1095 int show_formats(void *optctx, const char *opt, const char *arg)
1097 AVInputFormat *ifmt = NULL;
1098 AVOutputFormat *ofmt = NULL;
1099 const char *last_name;
1101 printf("File formats:\n"
1102 " D. = Demuxing supported\n"
1103 " .E = Muxing supported\n"
1109 const char *name = NULL;
1110 const char *long_name = NULL;
1112 while ((ofmt = av_oformat_next(ofmt))) {
1113 if ((name == NULL || strcmp(ofmt->name, name) < 0) &&
1114 strcmp(ofmt->name, last_name) > 0) {
1116 long_name = ofmt->long_name;
1120 while ((ifmt = av_iformat_next(ifmt))) {
1121 if ((name == NULL || strcmp(ifmt->name, name) < 0) &&
1122 strcmp(ifmt->name, last_name) > 0) {
1124 long_name = ifmt->long_name;
1127 if (name && strcmp(ifmt->name, name) == 0)
1134 printf(" %s%s %-15s %s\n",
1138 long_name ? long_name:" ");
1143 #define PRINT_CODEC_SUPPORTED(codec, field, type, list_name, term, get_name) \
1144 if (codec->field) { \
1145 const type *p = codec->field; \
1147 printf(" Supported " list_name ":"); \
1148 while (*p != term) { \
1150 printf(" %s", name); \
1156 static void print_codec(const AVCodec *c)
1158 int encoder = av_codec_is_encoder(c);
1160 printf("%s %s [%s]:\n", encoder ? "Encoder" : "Decoder", c->name,
1161 c->long_name ? c->long_name : "");
1163 if (c->type == AVMEDIA_TYPE_VIDEO) {
1164 printf(" Threading capabilities: ");
1165 switch (c->capabilities & (CODEC_CAP_FRAME_THREADS |
1166 CODEC_CAP_SLICE_THREADS)) {
1167 case CODEC_CAP_FRAME_THREADS |
1168 CODEC_CAP_SLICE_THREADS: printf("frame and slice"); break;
1169 case CODEC_CAP_FRAME_THREADS: printf("frame"); break;
1170 case CODEC_CAP_SLICE_THREADS: printf("slice"); break;
1171 default: printf("no"); break;
1176 if (c->supported_framerates) {
1177 const AVRational *fps = c->supported_framerates;
1179 printf(" Supported framerates:");
1181 printf(" %d/%d", fps->num, fps->den);
1186 PRINT_CODEC_SUPPORTED(c, pix_fmts, enum AVPixelFormat, "pixel formats",
1187 AV_PIX_FMT_NONE, GET_PIX_FMT_NAME);
1188 PRINT_CODEC_SUPPORTED(c, supported_samplerates, int, "sample rates", 0,
1189 GET_SAMPLE_RATE_NAME);
1190 PRINT_CODEC_SUPPORTED(c, sample_fmts, enum AVSampleFormat, "sample formats",
1191 AV_SAMPLE_FMT_NONE, GET_SAMPLE_FMT_NAME);
1192 PRINT_CODEC_SUPPORTED(c, channel_layouts, uint64_t, "channel layouts",
1193 0, GET_CH_LAYOUT_DESC);
1195 if (c->priv_class) {
1196 show_help_children(c->priv_class,
1197 AV_OPT_FLAG_ENCODING_PARAM |
1198 AV_OPT_FLAG_DECODING_PARAM);
1202 static char get_media_type_char(enum AVMediaType type)
1205 case AVMEDIA_TYPE_VIDEO: return 'V';
1206 case AVMEDIA_TYPE_AUDIO: return 'A';
1207 case AVMEDIA_TYPE_DATA: return 'D';
1208 case AVMEDIA_TYPE_SUBTITLE: return 'S';
1209 case AVMEDIA_TYPE_ATTACHMENT:return 'T';
1210 default: return '?';
1214 static const AVCodec *next_codec_for_id(enum AVCodecID id, const AVCodec *prev,
1217 while ((prev = av_codec_next(prev))) {
1218 if (prev->id == id &&
1219 (encoder ? av_codec_is_encoder(prev) : av_codec_is_decoder(prev)))
1225 static int compare_codec_desc(const void *a, const void *b)
1227 const AVCodecDescriptor * const *da = a;
1228 const AVCodecDescriptor * const *db = b;
1230 return (*da)->type != (*db)->type ? (*da)->type - (*db)->type :
1231 strcmp((*da)->name, (*db)->name);
1234 static unsigned get_codecs_sorted(const AVCodecDescriptor ***rcodecs)
1236 const AVCodecDescriptor *desc = NULL;
1237 const AVCodecDescriptor **codecs;
1238 unsigned nb_codecs = 0, i = 0;
1240 while ((desc = avcodec_descriptor_next(desc)))
1242 if (!(codecs = av_calloc(nb_codecs, sizeof(*codecs)))) {
1243 av_log(NULL, AV_LOG_ERROR, "Out of memory\n");
1247 while ((desc = avcodec_descriptor_next(desc)))
1249 av_assert0(i == nb_codecs);
1250 qsort(codecs, nb_codecs, sizeof(*codecs), compare_codec_desc);
1255 static void print_codecs_for_id(enum AVCodecID id, int encoder)
1257 const AVCodec *codec = NULL;
1259 printf(" (%s: ", encoder ? "encoders" : "decoders");
1261 while ((codec = next_codec_for_id(id, codec, encoder)))
1262 printf("%s ", codec->name);
1267 int show_codecs(void *optctx, const char *opt, const char *arg)
1269 const AVCodecDescriptor **codecs;
1270 unsigned i, nb_codecs = get_codecs_sorted(&codecs);
1273 " D..... = Decoding supported\n"
1274 " .E.... = Encoding supported\n"
1275 " ..V... = Video codec\n"
1276 " ..A... = Audio codec\n"
1277 " ..S... = Subtitle codec\n"
1278 " ...I.. = Intra frame-only codec\n"
1279 " ....L. = Lossy compression\n"
1280 " .....S = Lossless compression\n"
1282 for (i = 0; i < nb_codecs; i++) {
1283 const AVCodecDescriptor *desc = codecs[i];
1284 const AVCodec *codec = NULL;
1287 printf(avcodec_find_decoder(desc->id) ? "D" : ".");
1288 printf(avcodec_find_encoder(desc->id) ? "E" : ".");
1290 printf("%c", get_media_type_char(desc->type));
1291 printf((desc->props & AV_CODEC_PROP_INTRA_ONLY) ? "I" : ".");
1292 printf((desc->props & AV_CODEC_PROP_LOSSY) ? "L" : ".");
1293 printf((desc->props & AV_CODEC_PROP_LOSSLESS) ? "S" : ".");
1295 printf(" %-20s %s", desc->name, desc->long_name ? desc->long_name : "");
1297 /* print decoders/encoders when there's more than one or their
1298 * names are different from codec name */
1299 while ((codec = next_codec_for_id(desc->id, codec, 0))) {
1300 if (strcmp(codec->name, desc->name)) {
1301 print_codecs_for_id(desc->id, 0);
1306 while ((codec = next_codec_for_id(desc->id, codec, 1))) {
1307 if (strcmp(codec->name, desc->name)) {
1308 print_codecs_for_id(desc->id, 1);
1319 static void print_codecs(int encoder)
1321 const AVCodecDescriptor **codecs;
1322 unsigned i, nb_codecs = get_codecs_sorted(&codecs);
1327 " S..... = Subtitle\n"
1328 " .F.... = Frame-level multithreading\n"
1329 " ..S... = Slice-level multithreading\n"
1330 " ...X.. = Codec is experimental\n"
1331 " ....B. = Supports draw_horiz_band\n"
1332 " .....D = Supports direct rendering method 1\n"
1334 encoder ? "Encoders" : "Decoders");
1335 for (i = 0; i < nb_codecs; i++) {
1336 const AVCodecDescriptor *desc = codecs[i];
1337 const AVCodec *codec = NULL;
1339 while ((codec = next_codec_for_id(desc->id, codec, encoder))) {
1340 printf(" %c", get_media_type_char(desc->type));
1341 printf((codec->capabilities & CODEC_CAP_FRAME_THREADS) ? "F" : ".");
1342 printf((codec->capabilities & CODEC_CAP_SLICE_THREADS) ? "S" : ".");
1343 printf((codec->capabilities & CODEC_CAP_EXPERIMENTAL) ? "X" : ".");
1344 printf((codec->capabilities & CODEC_CAP_DRAW_HORIZ_BAND)?"B" : ".");
1345 printf((codec->capabilities & CODEC_CAP_DR1) ? "D" : ".");
1347 printf(" %-20s %s", codec->name, codec->long_name ? codec->long_name : "");
1348 if (strcmp(codec->name, desc->name))
1349 printf(" (codec %s)", desc->name);
1357 int show_decoders(void *optctx, const char *opt, const char *arg)
1363 int show_encoders(void *optctx, const char *opt, const char *arg)
1369 int show_bsfs(void *optctx, const char *opt, const char *arg)
1371 AVBitStreamFilter *bsf = NULL;
1373 printf("Bitstream filters:\n");
1374 while ((bsf = av_bitstream_filter_next(bsf)))
1375 printf("%s\n", bsf->name);
1380 int show_protocols(void *optctx, const char *opt, const char *arg)
1382 void *opaque = NULL;
1385 printf("Supported file protocols:\n"
1387 while ((name = avio_enum_protocols(&opaque, 0)))
1388 printf("%s\n", name);
1389 printf("Output:\n");
1390 while ((name = avio_enum_protocols(&opaque, 1)))
1391 printf("%s\n", name);
1395 int show_filters(void *optctx, const char *opt, const char *arg)
1397 AVFilter av_unused(**filter) = NULL;
1398 char descr[64], *descr_cur;
1400 const AVFilterPad *pad;
1402 printf("Filters:\n");
1404 while ((filter = av_filter_next(filter)) && *filter) {
1406 for (i = 0; i < 2; i++) {
1408 *(descr_cur++) = '-';
1409 *(descr_cur++) = '>';
1411 pad = i ? (*filter)->outputs : (*filter)->inputs;
1412 for (j = 0; pad && pad[j].name; j++) {
1413 if (descr_cur >= descr + sizeof(descr) - 4)
1415 *(descr_cur++) = get_media_type_char(pad[j].type);
1418 *(descr_cur++) = '|';
1421 printf("%-16s %-10s %s\n", (*filter)->name, descr, (*filter)->description);
1427 int show_pix_fmts(void *optctx, const char *opt, const char *arg)
1429 const AVPixFmtDescriptor *pix_desc = NULL;
1431 printf("Pixel formats:\n"
1432 "I.... = Supported Input format for conversion\n"
1433 ".O... = Supported Output format for conversion\n"
1434 "..H.. = Hardware accelerated format\n"
1435 "...P. = Paletted format\n"
1436 "....B = Bitstream format\n"
1437 "FLAGS NAME NB_COMPONENTS BITS_PER_PIXEL\n"
1441 # define sws_isSupportedInput(x) 0
1442 # define sws_isSupportedOutput(x) 0
1445 while ((pix_desc = av_pix_fmt_desc_next(pix_desc))) {
1446 enum AVPixelFormat pix_fmt = av_pix_fmt_desc_get_id(pix_desc);
1447 printf("%c%c%c%c%c %-16s %d %2d\n",
1448 sws_isSupportedInput (pix_fmt) ? 'I' : '.',
1449 sws_isSupportedOutput(pix_fmt) ? 'O' : '.',
1450 pix_desc->flags & PIX_FMT_HWACCEL ? 'H' : '.',
1451 pix_desc->flags & PIX_FMT_PAL ? 'P' : '.',
1452 pix_desc->flags & PIX_FMT_BITSTREAM ? 'B' : '.',
1454 pix_desc->nb_components,
1455 av_get_bits_per_pixel(pix_desc));
1460 int show_layouts(void *optctx, const char *opt, const char *arg)
1464 const char *name, *descr;
1466 printf("Individual channels:\n"
1467 "NAME DESCRIPTION\n");
1468 for (i = 0; i < 63; i++) {
1469 name = av_get_channel_name((uint64_t)1 << i);
1472 descr = av_get_channel_description((uint64_t)1 << i);
1473 printf("%-12s%s\n", name, descr);
1475 printf("\nStandard channel layouts:\n"
1476 "NAME DECOMPOSITION\n");
1477 for (i = 0; !av_get_standard_channel_layout(i, &layout, &name); i++) {
1479 printf("%-12s", name);
1480 for (j = 1; j; j <<= 1)
1482 printf("%s%s", (layout & (j - 1)) ? "+" : "", av_get_channel_name(j));
1489 int show_sample_fmts(void *optctx, const char *opt, const char *arg)
1493 for (i = -1; i < AV_SAMPLE_FMT_NB; i++)
1494 printf("%s\n", av_get_sample_fmt_string(fmt_str, sizeof(fmt_str), i));
1498 static void show_help_codec(const char *name, int encoder)
1500 const AVCodecDescriptor *desc;
1501 const AVCodec *codec;
1504 av_log(NULL, AV_LOG_ERROR, "No codec name specified.\n");
1508 codec = encoder ? avcodec_find_encoder_by_name(name) :
1509 avcodec_find_decoder_by_name(name);
1513 else if ((desc = avcodec_descriptor_get_by_name(name))) {
1516 while ((codec = next_codec_for_id(desc->id, codec, encoder))) {
1522 av_log(NULL, AV_LOG_ERROR, "Codec '%s' is known to FFmpeg, "
1523 "but no %s for it are available. FFmpeg might need to be "
1524 "recompiled with additional external libraries.\n",
1525 name, encoder ? "encoders" : "decoders");
1528 av_log(NULL, AV_LOG_ERROR, "Codec '%s' is not recognized by FFmpeg.\n",
1533 static void show_help_demuxer(const char *name)
1535 const AVInputFormat *fmt = av_find_input_format(name);
1538 av_log(NULL, AV_LOG_ERROR, "Unknown format '%s'.\n", name);
1542 printf("Demuxer %s [%s]:\n", fmt->name, fmt->long_name);
1544 if (fmt->extensions)
1545 printf(" Common extensions: %s.\n", fmt->extensions);
1547 if (fmt->priv_class)
1548 show_help_children(fmt->priv_class, AV_OPT_FLAG_DECODING_PARAM);
1551 static void show_help_muxer(const char *name)
1553 const AVCodecDescriptor *desc;
1554 const AVOutputFormat *fmt = av_guess_format(name, NULL, NULL);
1557 av_log(NULL, AV_LOG_ERROR, "Unknown format '%s'.\n", name);
1561 printf("Muxer %s [%s]:\n", fmt->name, fmt->long_name);
1563 if (fmt->extensions)
1564 printf(" Common extensions: %s.\n", fmt->extensions);
1566 printf(" Mime type: %s.\n", fmt->mime_type);
1567 if (fmt->video_codec != AV_CODEC_ID_NONE &&
1568 (desc = avcodec_descriptor_get(fmt->video_codec))) {
1569 printf(" Default video codec: %s.\n", desc->name);
1571 if (fmt->audio_codec != AV_CODEC_ID_NONE &&
1572 (desc = avcodec_descriptor_get(fmt->audio_codec))) {
1573 printf(" Default audio codec: %s.\n", desc->name);
1575 if (fmt->subtitle_codec != AV_CODEC_ID_NONE &&
1576 (desc = avcodec_descriptor_get(fmt->subtitle_codec))) {
1577 printf(" Default subtitle codec: %s.\n", desc->name);
1580 if (fmt->priv_class)
1581 show_help_children(fmt->priv_class, AV_OPT_FLAG_ENCODING_PARAM);
1584 int show_help(void *optctx, const char *opt, const char *arg)
1587 av_log_set_callback(log_callback_help);
1589 topic = av_strdup(arg ? arg : "");
1590 par = strchr(topic, '=');
1595 show_help_default(topic, par);
1596 } else if (!strcmp(topic, "decoder")) {
1597 show_help_codec(par, 0);
1598 } else if (!strcmp(topic, "encoder")) {
1599 show_help_codec(par, 1);
1600 } else if (!strcmp(topic, "demuxer")) {
1601 show_help_demuxer(par);
1602 } else if (!strcmp(topic, "muxer")) {
1603 show_help_muxer(par);
1605 show_help_default(topic, par);
1612 int read_yesno(void)
1615 int yesno = (toupper(c) == 'Y');
1617 while (c != '\n' && c != EOF)
1623 int cmdutils_read_file(const char *filename, char **bufptr, size_t *size)
1626 FILE *f = fopen(filename, "rb");
1629 av_log(NULL, AV_LOG_ERROR, "Cannot read file '%s': %s\n", filename,
1631 return AVERROR(errno);
1633 fseek(f, 0, SEEK_END);
1635 fseek(f, 0, SEEK_SET);
1636 if (*size == (size_t)-1) {
1637 av_log(NULL, AV_LOG_ERROR, "IO error: %s\n", strerror(errno));
1639 return AVERROR(errno);
1641 *bufptr = av_malloc(*size + 1);
1643 av_log(NULL, AV_LOG_ERROR, "Could not allocate file buffer\n");
1645 return AVERROR(ENOMEM);
1647 ret = fread(*bufptr, 1, *size, f);
1651 av_log(NULL, AV_LOG_ERROR, "Error while reading file '%s': %s\n",
1652 filename, strerror(errno));
1653 ret = AVERROR(errno);
1658 (*bufptr)[(*size)++] = '\0';
1665 FILE *get_preset_file(char *filename, size_t filename_size,
1666 const char *preset_name, int is_path,
1667 const char *codec_name)
1671 const char *base[3] = { getenv("FFMPEG_DATADIR"),
1676 av_strlcpy(filename, preset_name, filename_size);
1677 f = fopen(filename, "r");
1680 char datadir[MAX_PATH], *ls;
1683 if (GetModuleFileNameA(GetModuleHandleA(NULL), datadir, sizeof(datadir) - 1))
1685 for (ls = datadir; ls < datadir + strlen(datadir); ls++)
1686 if (*ls == '\\') *ls = '/';
1688 if (ls = strrchr(datadir, '/'))
1691 strncat(datadir, "/ffpresets", sizeof(datadir) - 1 - strlen(datadir));
1696 for (i = 0; i < 3 && !f; i++) {
1699 snprintf(filename, filename_size, "%s%s/%s.ffpreset", base[i],
1700 i != 1 ? "" : "/.ffmpeg", preset_name);
1701 f = fopen(filename, "r");
1702 if (!f && codec_name) {
1703 snprintf(filename, filename_size,
1704 "%s%s/%s-%s.ffpreset",
1705 base[i], i != 1 ? "" : "/.ffmpeg", codec_name,
1707 f = fopen(filename, "r");
1715 int check_stream_specifier(AVFormatContext *s, AVStream *st, const char *spec)
1717 int ret = avformat_match_stream_specifier(s, st, spec);
1719 av_log(s, AV_LOG_ERROR, "Invalid stream specifier: %s.\n", spec);
1723 AVDictionary *filter_codec_opts(AVDictionary *opts, enum AVCodecID codec_id,
1724 AVFormatContext *s, AVStream *st, AVCodec *codec)
1726 AVDictionary *ret = NULL;
1727 AVDictionaryEntry *t = NULL;
1728 int flags = s->oformat ? AV_OPT_FLAG_ENCODING_PARAM
1729 : AV_OPT_FLAG_DECODING_PARAM;
1731 const AVClass *cc = avcodec_get_class();
1734 codec = s->oformat ? avcodec_find_encoder(codec_id)
1735 : avcodec_find_decoder(codec_id);
1739 switch (codec->type) {
1740 case AVMEDIA_TYPE_VIDEO:
1742 flags |= AV_OPT_FLAG_VIDEO_PARAM;
1744 case AVMEDIA_TYPE_AUDIO:
1746 flags |= AV_OPT_FLAG_AUDIO_PARAM;
1748 case AVMEDIA_TYPE_SUBTITLE:
1750 flags |= AV_OPT_FLAG_SUBTITLE_PARAM;
1754 while (t = av_dict_get(opts, "", t, AV_DICT_IGNORE_SUFFIX)) {
1755 char *p = strchr(t->key, ':');
1757 /* check stream specification in opt name */
1759 switch (check_stream_specifier(s, st, p + 1)) {
1760 case 1: *p = 0; break;
1762 default: return NULL;
1765 if (av_opt_find(&cc, t->key, NULL, flags, AV_OPT_SEARCH_FAKE_OBJ) ||
1766 (codec && codec->priv_class &&
1767 av_opt_find(&codec->priv_class, t->key, NULL, flags,
1768 AV_OPT_SEARCH_FAKE_OBJ)))
1769 av_dict_set(&ret, t->key, t->value, 0);
1770 else if (t->key[0] == prefix &&
1771 av_opt_find(&cc, t->key + 1, NULL, flags,
1772 AV_OPT_SEARCH_FAKE_OBJ))
1773 av_dict_set(&ret, t->key + 1, t->value, 0);
1781 AVDictionary **setup_find_stream_info_opts(AVFormatContext *s,
1782 AVDictionary *codec_opts)
1785 AVDictionary **opts;
1789 opts = av_mallocz(s->nb_streams * sizeof(*opts));
1791 av_log(NULL, AV_LOG_ERROR,
1792 "Could not alloc memory for stream options.\n");
1795 for (i = 0; i < s->nb_streams; i++)
1796 opts[i] = filter_codec_opts(codec_opts, s->streams[i]->codec->codec_id,
1797 s, s->streams[i], NULL);
1801 void *grow_array(void *array, int elem_size, int *size, int new_size)
1803 if (new_size >= INT_MAX / elem_size) {
1804 av_log(NULL, AV_LOG_ERROR, "Array too big.\n");
1807 if (*size < new_size) {
1808 uint8_t *tmp = av_realloc(array, new_size*elem_size);
1810 av_log(NULL, AV_LOG_ERROR, "Could not alloc buffer.\n");
1813 memset(tmp + *size*elem_size, 0, (new_size-*size) * elem_size);
1820 static int alloc_buffer(FrameBuffer **pool, AVCodecContext *s, FrameBuffer **pbuf)
1822 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(s->pix_fmt);
1826 int h_chroma_shift, v_chroma_shift;
1827 int edge = 32; // XXX should be avcodec_get_edge_width(), but that fails on svq1
1828 int w = s->width, h = s->height;
1831 return AVERROR(EINVAL);
1832 pixel_size = desc->comp[0].step_minus1 + 1;
1834 buf = av_mallocz(sizeof(*buf));
1836 return AVERROR(ENOMEM);
1838 avcodec_align_dimensions(s, &w, &h);
1840 if (!(s->flags & CODEC_FLAG_EMU_EDGE)) {
1845 if ((ret = av_image_alloc(buf->base, buf->linesize, w, h,
1846 s->pix_fmt, 32)) < 0) {
1848 av_log(s, AV_LOG_ERROR, "alloc_buffer: av_image_alloc() failed\n");
1851 /* XXX this shouldn't be needed, but some tests break without this line
1852 * those decoders are buggy and need to be fixed.
1853 * the following tests fail:
1854 * cdgraphics, ansi, aasc, fraps-v1, qtrle-1bit
1856 memset(buf->base[0], 128, ret);
1858 avcodec_get_chroma_sub_sample(s->pix_fmt, &h_chroma_shift, &v_chroma_shift);
1859 for (i = 0; i < FF_ARRAY_ELEMS(buf->data); i++) {
1860 const int h_shift = i==0 ? 0 : h_chroma_shift;
1861 const int v_shift = i==0 ? 0 : v_chroma_shift;
1862 if ((s->flags & CODEC_FLAG_EMU_EDGE) || !buf->linesize[i] || !buf->base[i])
1863 buf->data[i] = buf->base[i];
1865 buf->data[i] = buf->base[i] +
1866 FFALIGN((buf->linesize[i]*edge >> v_shift) +
1867 (pixel_size*edge >> h_shift), 32);
1871 buf->pix_fmt = s->pix_fmt;
1878 int codec_get_buffer(AVCodecContext *s, AVFrame *frame)
1880 FrameBuffer **pool = s->opaque;
1884 if(av_image_check_size(s->width, s->height, 0, s) || s->pix_fmt<0) {
1885 av_log(s, AV_LOG_ERROR, "codec_get_buffer: image parameters invalid\n");
1889 if (!*pool && (ret = alloc_buffer(pool, s, pool)) < 0)
1895 if (buf->w != s->width || buf->h != s->height || buf->pix_fmt != s->pix_fmt) {
1896 av_freep(&buf->base[0]);
1898 if ((ret = alloc_buffer(pool, s, &buf)) < 0)
1901 av_assert0(!buf->refcount);
1904 frame->opaque = buf;
1905 frame->type = FF_BUFFER_TYPE_USER;
1906 frame->extended_data = frame->data;
1908 for (i = 0; i < FF_ARRAY_ELEMS(buf->data); i++) {
1909 frame->base[i] = buf->base[i]; // XXX h264.c uses base though it shouldn't
1910 frame->data[i] = buf->data[i];
1911 frame->linesize[i] = buf->linesize[i];
1917 static void unref_buffer(FrameBuffer *buf)
1919 FrameBuffer **pool = buf->pool;
1921 av_assert0(buf->refcount > 0);
1923 if (!buf->refcount) {
1925 for(tmp= *pool; tmp; tmp= tmp->next)
1926 av_assert1(tmp != buf);
1933 void codec_release_buffer(AVCodecContext *s, AVFrame *frame)
1935 FrameBuffer *buf = frame->opaque;
1938 if(frame->type!=FF_BUFFER_TYPE_USER) {
1939 avcodec_default_release_buffer(s, frame);
1943 for (i = 0; i < FF_ARRAY_ELEMS(frame->data); i++)
1944 frame->data[i] = NULL;
1949 void filter_release_buffer(AVFilterBuffer *fb)
1951 FrameBuffer *buf = fb->priv;
1956 void free_buffer_pool(FrameBuffer **pool)
1958 FrameBuffer *buf = *pool;
1961 av_freep(&buf->base[0]);