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
52 #include <sys/resource.h>
55 struct SwsContext *sws_opts;
56 AVDictionary *format_opts, *codec_opts;
58 static const int this_year = 2012;
63 sws_opts = sws_getContext(16, 16, 0, 16, 16, 0, SWS_BICUBIC,
68 void uninit_opts(void)
71 sws_freeContext(sws_opts);
74 av_dict_free(&format_opts);
75 av_dict_free(&codec_opts);
78 void log_callback_help(void *ptr, int level, const char *fmt, va_list vl)
80 vfprintf(stdout, fmt, vl);
83 double parse_number_or_die(const char *context, const char *numstr, int type,
84 double min, double max)
88 double d = av_strtod(numstr, &tail);
90 error = "Expected number for %s but found: %s\n";
91 else if (d < min || d > max)
92 error = "The value for %s was %s which is not within %f - %f\n";
93 else if (type == OPT_INT64 && (int64_t)d != d)
94 error = "Expected int64 for %s but found %s\n";
95 else if (type == OPT_INT && (int)d != d)
96 error = "Expected int for %s but found %s\n";
99 av_log(NULL, AV_LOG_FATAL, error, context, numstr, min, max);
104 int64_t parse_time_or_die(const char *context, const char *timestr,
108 if (av_parse_time(&us, timestr, is_duration) < 0) {
109 av_log(NULL, AV_LOG_FATAL, "Invalid %s specification for %s: %s\n",
110 is_duration ? "duration" : "date", context, timestr);
116 void show_help_options(const OptionDef *options, const char *msg, int req_flags,
117 int rej_flags, int alt_flags)
123 for (po = options; po->name != NULL; po++) {
126 if (((po->flags & req_flags) != req_flags) ||
127 (alt_flags && !(po->flags & alt_flags)) ||
128 (po->flags & rej_flags))
135 av_strlcpy(buf, po->name, sizeof(buf));
137 av_strlcat(buf, " ", sizeof(buf));
138 av_strlcat(buf, po->argname, sizeof(buf));
140 printf("-%-17s %s\n", buf, po->help);
145 void show_help_children(const AVClass *class, int flags)
147 const AVClass *child = NULL;
148 av_opt_show2(&class, NULL, flags, 0);
151 while (child = av_opt_child_class_next(class, child))
152 show_help_children(child, flags);
155 static const OptionDef *find_option(const OptionDef *po, const char *name)
157 const char *p = strchr(name, ':');
158 int len = p ? p - name : strlen(name);
160 while (po->name != NULL) {
161 if (!strncmp(name, po->name, len) && strlen(po->name) == len)
168 #if defined(_WIN32) && !defined(__MINGW32CE__)
170 #include <shellapi.h>
171 /* Will be leaked on exit */
172 static char** win32_argv_utf8 = NULL;
173 static int win32_argc = 0;
176 * Prepare command line arguments for executable.
177 * For Windows - perform wide-char to UTF-8 conversion.
178 * Input arguments should be main() function arguments.
179 * @param argc_ptr Arguments number (including executable)
180 * @param argv_ptr Arguments list.
182 static void prepare_app_arguments(int *argc_ptr, char ***argv_ptr)
186 int i, buffsize = 0, offset = 0;
188 if (win32_argv_utf8) {
189 *argc_ptr = win32_argc;
190 *argv_ptr = win32_argv_utf8;
195 argv_w = CommandLineToArgvW(GetCommandLineW(), &win32_argc);
196 if (win32_argc <= 0 || !argv_w)
199 /* determine the UTF-8 buffer size (including NULL-termination symbols) */
200 for (i = 0; i < win32_argc; i++)
201 buffsize += WideCharToMultiByte(CP_UTF8, 0, argv_w[i], -1,
202 NULL, 0, NULL, NULL);
204 win32_argv_utf8 = av_mallocz(sizeof(char *) * (win32_argc + 1) + buffsize);
205 argstr_flat = (char *)win32_argv_utf8 + sizeof(char *) * (win32_argc + 1);
206 if (win32_argv_utf8 == NULL) {
211 for (i = 0; i < win32_argc; i++) {
212 win32_argv_utf8[i] = &argstr_flat[offset];
213 offset += WideCharToMultiByte(CP_UTF8, 0, argv_w[i], -1,
214 &argstr_flat[offset],
215 buffsize - offset, NULL, NULL);
217 win32_argv_utf8[i] = NULL;
220 *argc_ptr = win32_argc;
221 *argv_ptr = win32_argv_utf8;
224 static inline void prepare_app_arguments(int *argc_ptr, char ***argv_ptr)
228 #endif /* WIN32 && !__MINGW32CE__ */
230 int parse_option(void *optctx, const char *opt, const char *arg,
231 const OptionDef *options)
238 po = find_option(options, opt);
239 if (!po->name && opt[0] == 'n' && opt[1] == 'o') {
240 /* handle 'no' bool option */
241 po = find_option(options, opt + 2);
242 if ((po->name && (po->flags & OPT_BOOL)))
246 po = find_option(options, "default");
248 av_log(NULL, AV_LOG_ERROR, "Unrecognized option '%s'\n", opt);
249 return AVERROR(EINVAL);
251 if (po->flags & HAS_ARG && !arg) {
252 av_log(NULL, AV_LOG_ERROR, "Missing argument for option '%s'\n", opt);
253 return AVERROR(EINVAL);
256 /* new-style options contain an offset into optctx, old-style address of
258 dst = po->flags & (OPT_OFFSET | OPT_SPEC) ? (uint8_t *)optctx + po->u.off
261 if (po->flags & OPT_SPEC) {
262 SpecifierOpt **so = dst;
263 char *p = strchr(opt, ':');
265 dstcount = (int *)(so + 1);
266 *so = grow_array(*so, sizeof(**so), dstcount, *dstcount + 1);
267 (*so)[*dstcount - 1].specifier = av_strdup(p ? p + 1 : "");
268 dst = &(*so)[*dstcount - 1].u;
271 if (po->flags & OPT_STRING) {
273 str = av_strdup(arg);
276 } else if (po->flags & OPT_BOOL) {
277 *(int *)dst = bool_val;
278 } else if (po->flags & OPT_INT) {
279 *(int *)dst = parse_number_or_die(opt, arg, OPT_INT64, INT_MIN, INT_MAX);
280 } else if (po->flags & OPT_INT64) {
281 *(int64_t *)dst = parse_number_or_die(opt, arg, OPT_INT64, INT64_MIN, INT64_MAX);
282 } else if (po->flags & OPT_TIME) {
283 *(int64_t *)dst = parse_time_or_die(opt, arg, 1);
284 } else if (po->flags & OPT_FLOAT) {
285 *(float *)dst = parse_number_or_die(opt, arg, OPT_FLOAT, -INFINITY, INFINITY);
286 } else if (po->flags & OPT_DOUBLE) {
287 *(double *)dst = parse_number_or_die(opt, arg, OPT_DOUBLE, -INFINITY, INFINITY);
288 } else if (po->u.func_arg) {
289 int ret = po->u.func_arg(optctx, opt, arg);
291 av_log(NULL, AV_LOG_ERROR,
292 "Failed to set value '%s' for option '%s'\n", arg, opt);
296 if (po->flags & OPT_EXIT)
298 return !!(po->flags & HAS_ARG);
301 void parse_options(void *optctx, int argc, char **argv, const OptionDef *options,
302 void (*parse_arg_function)(void *, const char*))
305 int optindex, handleoptions = 1, ret;
307 /* perform system-dependent conversions for arguments list */
308 prepare_app_arguments(&argc, &argv);
312 while (optindex < argc) {
313 opt = argv[optindex++];
315 if (handleoptions && opt[0] == '-' && opt[1] != '\0') {
316 if (opt[1] == '-' && opt[2] == '\0') {
322 if ((ret = parse_option(optctx, opt, argv[optindex], options)) < 0)
326 if (parse_arg_function)
327 parse_arg_function(optctx, opt);
332 int locate_option(int argc, char **argv, const OptionDef *options,
338 for (i = 1; i < argc; i++) {
339 const char *cur_opt = argv[i];
341 if (*cur_opt++ != '-')
344 po = find_option(options, cur_opt);
345 if (!po->name && cur_opt[0] == 'n' && cur_opt[1] == 'o')
346 po = find_option(options, cur_opt + 2);
348 if ((!po->name && !strcmp(cur_opt, optname)) ||
349 (po->name && !strcmp(optname, po->name)))
352 if (!po || po->flags & HAS_ARG)
358 void parse_loglevel(int argc, char **argv, const OptionDef *options)
360 int idx = locate_option(argc, argv, options, "loglevel");
362 idx = locate_option(argc, argv, options, "v");
363 if (idx && argv[idx + 1])
364 opt_loglevel(NULL, "loglevel", argv[idx + 1]);
367 #define FLAGS (o->type == AV_OPT_TYPE_FLAGS) ? AV_DICT_APPEND : 0
368 int opt_default(void *optctx, const char *opt, const char *arg)
371 char opt_stripped[128];
373 const AVClass *cc = avcodec_get_class(), *fc = avformat_get_class(), *sc = sws_get_class();
375 if (!(p = strchr(opt, ':')))
376 p = opt + strlen(opt);
377 av_strlcpy(opt_stripped, opt, FFMIN(sizeof(opt_stripped), p - opt + 1));
379 if ((o = av_opt_find(&cc, opt_stripped, NULL, 0,
380 AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ)) ||
381 ((opt[0] == 'v' || opt[0] == 'a' || opt[0] == 's') &&
382 (o = av_opt_find(&cc, opt + 1, NULL, 0, AV_OPT_SEARCH_FAKE_OBJ))))
383 av_dict_set(&codec_opts, opt, arg, FLAGS);
384 else if ((o = av_opt_find(&fc, opt, NULL, 0,
385 AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ)))
386 av_dict_set(&format_opts, opt, arg, FLAGS);
387 else if ((o = av_opt_find(&sc, opt, NULL, 0,
388 AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ))) {
389 // XXX we only support sws_flags, not arbitrary sws options
390 int ret = av_opt_set(sws_opts, opt, arg, 0);
392 av_log(NULL, AV_LOG_ERROR, "Error setting option %s.\n", opt);
399 av_log(NULL, AV_LOG_ERROR, "Unrecognized option '%s'\n", opt);
400 return AVERROR_OPTION_NOT_FOUND;
403 int opt_loglevel(void *optctx, const char *opt, const char *arg)
405 const struct { const char *name; int level; } log_levels[] = {
406 { "quiet" , AV_LOG_QUIET },
407 { "panic" , AV_LOG_PANIC },
408 { "fatal" , AV_LOG_FATAL },
409 { "error" , AV_LOG_ERROR },
410 { "warning", AV_LOG_WARNING },
411 { "info" , AV_LOG_INFO },
412 { "verbose", AV_LOG_VERBOSE },
413 { "debug" , AV_LOG_DEBUG },
419 for (i = 0; i < FF_ARRAY_ELEMS(log_levels); i++) {
420 if (!strcmp(log_levels[i].name, arg)) {
421 av_log_set_level(log_levels[i].level);
426 level = strtol(arg, &tail, 10);
428 av_log(NULL, AV_LOG_FATAL, "Invalid loglevel \"%s\". "
429 "Possible levels are numbers or:\n", arg);
430 for (i = 0; i < FF_ARRAY_ELEMS(log_levels); i++)
431 av_log(NULL, AV_LOG_FATAL, "\"%s\"\n", log_levels[i].name);
434 av_log_set_level(level);
438 int opt_timelimit(void *optctx, const char *opt, const char *arg)
441 int lim = parse_number_or_die(opt, arg, OPT_INT64, 0, INT_MAX);
442 struct rlimit rl = { lim, lim + 1 };
443 if (setrlimit(RLIMIT_CPU, &rl))
446 av_log(NULL, AV_LOG_WARNING, "-%s not implemented on this OS\n", opt);
451 void print_error(const char *filename, int err)
454 const char *errbuf_ptr = errbuf;
456 if (av_strerror(err, errbuf, sizeof(errbuf)) < 0)
457 errbuf_ptr = strerror(AVUNERROR(err));
458 av_log(NULL, AV_LOG_ERROR, "%s: %s\n", filename, errbuf_ptr);
461 static int warned_cfg = 0;
464 #define SHOW_VERSION 2
465 #define SHOW_CONFIG 4
467 #define PRINT_LIB_INFO(libname, LIBNAME, flags, level) \
468 if (CONFIG_##LIBNAME) { \
469 const char *indent = flags & INDENT? " " : ""; \
470 if (flags & SHOW_VERSION) { \
471 unsigned int version = libname##_version(); \
472 av_log(NULL, level, \
473 "%slib%-10s %2d.%3d.%2d / %2d.%3d.%2d\n", \
475 LIB##LIBNAME##_VERSION_MAJOR, \
476 LIB##LIBNAME##_VERSION_MINOR, \
477 LIB##LIBNAME##_VERSION_MICRO, \
478 version >> 16, version >> 8 & 0xff, version & 0xff); \
480 if (flags & SHOW_CONFIG) { \
481 const char *cfg = libname##_configuration(); \
482 if (strcmp(LIBAV_CONFIGURATION, cfg)) { \
484 av_log(NULL, level, \
485 "%sWARNING: library configuration mismatch\n", \
489 av_log(NULL, level, "%s%-11s configuration: %s\n", \
490 indent, #libname, cfg); \
495 static void print_all_libs_info(int flags, int level)
497 PRINT_LIB_INFO(avutil, AVUTIL, flags, level);
498 PRINT_LIB_INFO(avcodec, AVCODEC, flags, level);
499 PRINT_LIB_INFO(avformat, AVFORMAT, flags, level);
500 PRINT_LIB_INFO(avdevice, AVDEVICE, flags, level);
501 PRINT_LIB_INFO(avfilter, AVFILTER, flags, level);
502 PRINT_LIB_INFO(avresample, AVRESAMPLE, flags, level);
503 PRINT_LIB_INFO(swscale, SWSCALE, flags, level);
506 void show_banner(void)
508 av_log(NULL, AV_LOG_INFO,
509 "%s version " LIBAV_VERSION ", Copyright (c) %d-%d the Libav developers\n",
510 program_name, program_birth_year, this_year);
511 av_log(NULL, AV_LOG_INFO, " built on %s %s with %s\n",
512 __DATE__, __TIME__, CC_IDENT);
513 av_log(NULL, AV_LOG_VERBOSE, " configuration: " LIBAV_CONFIGURATION "\n");
514 print_all_libs_info(INDENT|SHOW_CONFIG, AV_LOG_VERBOSE);
515 print_all_libs_info(INDENT|SHOW_VERSION, AV_LOG_VERBOSE);
518 int show_version(void *optctx, const char *opt, const char *arg)
520 av_log_set_callback(log_callback_help);
521 printf("%s " LIBAV_VERSION "\n", program_name);
522 print_all_libs_info(SHOW_VERSION, AV_LOG_INFO);
527 int show_license(void *optctx, const char *opt, const char *arg)
531 "This version of %s has nonfree parts compiled in.\n"
532 "Therefore it is not legally redistributable.\n",
535 "%s is free software; you can redistribute it and/or modify\n"
536 "it under the terms of the GNU General Public License as published by\n"
537 "the Free Software Foundation; either version 3 of the License, or\n"
538 "(at your option) any later version.\n"
540 "%s is distributed in the hope that it will be useful,\n"
541 "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
542 "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n"
543 "GNU General Public License for more details.\n"
545 "You should have received a copy of the GNU General Public License\n"
546 "along with %s. If not, see <http://www.gnu.org/licenses/>.\n",
547 program_name, program_name, program_name
549 "%s is free software; you can redistribute it and/or modify\n"
550 "it under the terms of the GNU General Public License as published by\n"
551 "the Free Software Foundation; either version 2 of the License, or\n"
552 "(at your option) any later version.\n"
554 "%s is distributed in the hope that it will be useful,\n"
555 "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
556 "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n"
557 "GNU General Public License for more details.\n"
559 "You should have received a copy of the GNU General Public License\n"
560 "along with %s; if not, write to the Free Software\n"
561 "Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n",
562 program_name, program_name, program_name
564 "%s is free software; you can redistribute it and/or modify\n"
565 "it under the terms of the GNU Lesser General Public License as published by\n"
566 "the Free Software Foundation; either version 3 of the License, or\n"
567 "(at your option) any later version.\n"
569 "%s is distributed in the hope that it will be useful,\n"
570 "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
571 "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n"
572 "GNU Lesser General Public License for more details.\n"
574 "You should have received a copy of the GNU Lesser General Public License\n"
575 "along with %s. If not, see <http://www.gnu.org/licenses/>.\n",
576 program_name, program_name, program_name
578 "%s is free software; you can redistribute it and/or\n"
579 "modify it under the terms of the GNU Lesser General Public\n"
580 "License as published by the Free Software Foundation; either\n"
581 "version 2.1 of the License, or (at your option) any later version.\n"
583 "%s is distributed in the hope that it will be useful,\n"
584 "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
585 "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n"
586 "Lesser General Public License for more details.\n"
588 "You should have received a copy of the GNU Lesser General Public\n"
589 "License along with %s; if not, write to the Free Software\n"
590 "Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n",
591 program_name, program_name, program_name
598 int show_formats(void *optctx, const char *opt, const char *arg)
600 AVInputFormat *ifmt = NULL;
601 AVOutputFormat *ofmt = NULL;
602 const char *last_name;
604 printf("File formats:\n"
605 " D. = Demuxing supported\n"
606 " .E = Muxing supported\n"
612 const char *name = NULL;
613 const char *long_name = NULL;
615 while ((ofmt = av_oformat_next(ofmt))) {
616 if ((name == NULL || strcmp(ofmt->name, name) < 0) &&
617 strcmp(ofmt->name, last_name) > 0) {
619 long_name = ofmt->long_name;
623 while ((ifmt = av_iformat_next(ifmt))) {
624 if ((name == NULL || strcmp(ifmt->name, name) < 0) &&
625 strcmp(ifmt->name, last_name) > 0) {
627 long_name = ifmt->long_name;
630 if (name && strcmp(ifmt->name, name) == 0)
637 printf(" %s%s %-15s %s\n",
641 long_name ? long_name:" ");
646 #define PRINT_CODEC_SUPPORTED(codec, field, type, list_name, term, get_name) \
647 if (codec->field) { \
648 const type *p = c->field; \
650 printf(" Supported " list_name ":"); \
651 while (*p != term) { \
653 printf(" %s", name); \
659 static void print_codec(const AVCodec *c)
661 int encoder = av_codec_is_encoder(c);
663 printf("%s %s [%s]:\n", encoder ? "Encoder" : "Decoder", c->name,
664 c->long_name ? c->long_name : "");
666 if (c->type == AVMEDIA_TYPE_VIDEO) {
667 printf(" Threading capabilities: ");
668 switch (c->capabilities & (CODEC_CAP_FRAME_THREADS |
669 CODEC_CAP_SLICE_THREADS)) {
670 case CODEC_CAP_FRAME_THREADS |
671 CODEC_CAP_SLICE_THREADS: printf("frame and slice"); break;
672 case CODEC_CAP_FRAME_THREADS: printf("frame"); break;
673 case CODEC_CAP_SLICE_THREADS: printf("slice"); break;
674 default: printf("no"); break;
679 if (c->supported_framerates) {
680 const AVRational *fps = c->supported_framerates;
682 printf(" Supported framerates:");
684 printf(" %d/%d", fps->num, fps->den);
689 PRINT_CODEC_SUPPORTED(c, pix_fmts, enum PixelFormat, "pixel formats",
690 PIX_FMT_NONE, GET_PIX_FMT_NAME);
691 PRINT_CODEC_SUPPORTED(c, supported_samplerates, int, "sample rates", 0,
692 GET_SAMPLE_RATE_NAME);
693 PRINT_CODEC_SUPPORTED(c, sample_fmts, enum AVSampleFormat, "sample formats",
694 AV_SAMPLE_FMT_NONE, GET_SAMPLE_FMT_NAME);
695 PRINT_CODEC_SUPPORTED(c, channel_layouts, uint64_t, "channel layouts",
696 0, GET_CH_LAYOUT_DESC);
699 show_help_children(c->priv_class,
700 AV_OPT_FLAG_ENCODING_PARAM |
701 AV_OPT_FLAG_DECODING_PARAM);
705 static char get_media_type_char(enum AVMediaType type)
708 case AVMEDIA_TYPE_VIDEO: return 'V';
709 case AVMEDIA_TYPE_AUDIO: return 'A';
710 case AVMEDIA_TYPE_SUBTITLE: return 'S';
715 static const AVCodec *next_codec_for_id(enum AVCodecID id, const AVCodec *prev,
718 while ((prev = av_codec_next(prev))) {
719 if (prev->id == id &&
720 (encoder ? av_codec_is_encoder(prev) : av_codec_is_decoder(prev)))
726 static void print_codecs_for_id(enum AVCodecID id, int encoder)
728 const AVCodec *codec = NULL;
730 printf(" (%s: ", encoder ? "encoders" : "decoders");
732 while ((codec = next_codec_for_id(id, codec, encoder)))
733 printf("%s ", codec->name);
738 int show_codecs(void *optctx, const char *opt, const char *arg)
740 const AVCodecDescriptor *desc = NULL;
743 " D..... = Decoding supported\n"
744 " .E.... = Encoding supported\n"
745 " ..V... = Video codec\n"
746 " ..A... = Audio codec\n"
747 " ..S... = Subtitle codec\n"
748 " ...I.. = Intra frame-only codec\n"
749 " ....L. = Lossy compression\n"
750 " .....S = Lossless compression\n"
752 while ((desc = avcodec_descriptor_next(desc))) {
753 const AVCodec *codec = NULL;
755 printf(avcodec_find_decoder(desc->id) ? "D" : ".");
756 printf(avcodec_find_encoder(desc->id) ? "E" : ".");
758 printf("%c", get_media_type_char(desc->type));
759 printf((desc->props & AV_CODEC_PROP_INTRA_ONLY) ? "I" : ".");
760 printf((desc->props & AV_CODEC_PROP_LOSSY) ? "L" : ".");
761 printf((desc->props & AV_CODEC_PROP_LOSSLESS) ? "S" : ".");
763 printf(" %-20s %s", desc->name, desc->long_name ? desc->long_name : "");
765 /* print decoders/encoders when there's more than one or their
766 * names are different from codec name */
767 while ((codec = next_codec_for_id(desc->id, codec, 0))) {
768 if (strcmp(codec->name, desc->name)) {
769 print_codecs_for_id(desc->id, 0);
774 while ((codec = next_codec_for_id(desc->id, codec, 1))) {
775 if (strcmp(codec->name, desc->name)) {
776 print_codecs_for_id(desc->id, 1);
786 static void print_codecs(int encoder)
788 const AVCodecDescriptor *desc = NULL;
794 " .F.. = Frame-level multithreading\n"
795 " ..S. = Slice-level multithreading\n"
796 " ...X = Codec is experimental\n"
798 encoder ? "Encoders" : "Decoders");
799 while ((desc = avcodec_descriptor_next(desc))) {
800 const AVCodec *codec = NULL;
802 while ((codec = next_codec_for_id(desc->id, codec, encoder))) {
803 printf("%c", get_media_type_char(desc->type));
804 printf((codec->capabilities & CODEC_CAP_FRAME_THREADS) ? "F" : ".");
805 printf((codec->capabilities & CODEC_CAP_SLICE_THREADS) ? "S" : ".");
806 printf((codec->capabilities & CODEC_CAP_EXPERIMENTAL) ? "X" : ".");
808 printf(" %-20s %s", codec->name, codec->long_name ? codec->long_name : "");
809 if (strcmp(codec->name, desc->name))
810 printf(" (codec %s)", desc->name);
817 int show_decoders(void *optctx, const char *opt, const char *arg)
823 int show_encoders(void *optctx, const char *opt, const char *arg)
829 int show_bsfs(void *optctx, const char *opt, const char *arg)
831 AVBitStreamFilter *bsf = NULL;
833 printf("Bitstream filters:\n");
834 while ((bsf = av_bitstream_filter_next(bsf)))
835 printf("%s\n", bsf->name);
840 int show_protocols(void *optctx, const char *opt, const char *arg)
845 printf("Supported file protocols:\n"
847 while ((name = avio_enum_protocols(&opaque, 0)))
848 printf("%s\n", name);
850 while ((name = avio_enum_protocols(&opaque, 1)))
851 printf("%s\n", name);
855 int show_filters(void *optctx, const char *opt, const char *arg)
857 AVFilter av_unused(**filter) = NULL;
859 printf("Filters:\n");
861 while ((filter = av_filter_next(filter)) && *filter)
862 printf("%-16s %s\n", (*filter)->name, (*filter)->description);
867 int show_pix_fmts(void *optctx, const char *opt, const char *arg)
869 enum PixelFormat pix_fmt;
871 printf("Pixel formats:\n"
872 "I.... = Supported Input format for conversion\n"
873 ".O... = Supported Output format for conversion\n"
874 "..H.. = Hardware accelerated format\n"
875 "...P. = Paletted format\n"
876 "....B = Bitstream format\n"
877 "FLAGS NAME NB_COMPONENTS BITS_PER_PIXEL\n"
881 # define sws_isSupportedInput(x) 0
882 # define sws_isSupportedOutput(x) 0
885 for (pix_fmt = 0; pix_fmt < PIX_FMT_NB; pix_fmt++) {
886 const AVPixFmtDescriptor *pix_desc = &av_pix_fmt_descriptors[pix_fmt];
887 printf("%c%c%c%c%c %-16s %d %2d\n",
888 sws_isSupportedInput (pix_fmt) ? 'I' : '.',
889 sws_isSupportedOutput(pix_fmt) ? 'O' : '.',
890 pix_desc->flags & PIX_FMT_HWACCEL ? 'H' : '.',
891 pix_desc->flags & PIX_FMT_PAL ? 'P' : '.',
892 pix_desc->flags & PIX_FMT_BITSTREAM ? 'B' : '.',
894 pix_desc->nb_components,
895 av_get_bits_per_pixel(pix_desc));
900 int show_sample_fmts(void *optctx, const char *opt, const char *arg)
904 for (i = -1; i < AV_SAMPLE_FMT_NB; i++)
905 printf("%s\n", av_get_sample_fmt_string(fmt_str, sizeof(fmt_str), i));
909 static void show_help_codec(const char *name, int encoder)
911 const AVCodecDescriptor *desc;
912 const AVCodec *codec;
915 av_log(NULL, AV_LOG_ERROR, "No codec name specified.\n");
919 codec = encoder ? avcodec_find_encoder_by_name(name) :
920 avcodec_find_decoder_by_name(name);
924 else if ((desc = avcodec_descriptor_get_by_name(name))) {
927 while ((codec = next_codec_for_id(desc->id, codec, encoder))) {
933 av_log(NULL, AV_LOG_ERROR, "Codec '%s' is known to Libav, "
934 "but no %s for it are available. Libav might need to be "
935 "recompiled with additional external libraries.\n",
936 name, encoder ? "encoders" : "decoders");
939 av_log(NULL, AV_LOG_ERROR, "Codec '%s' is not recognized by Libav.\n",
944 static void show_help_demuxer(const char *name)
946 const AVInputFormat *fmt = av_find_input_format(name);
949 av_log(NULL, AV_LOG_ERROR, "Unknown format '%s'.\n", name);
953 printf("Demuxer %s [%s]:\n", fmt->name, fmt->long_name);
956 printf(" Common extensions: %s.\n", fmt->extensions);
959 show_help_children(fmt->priv_class, AV_OPT_FLAG_DECODING_PARAM);
962 static void show_help_muxer(const char *name)
964 const AVCodecDescriptor *desc;
965 const AVOutputFormat *fmt = av_guess_format(name, NULL, NULL);
968 av_log(NULL, AV_LOG_ERROR, "Unknown format '%s'.\n", name);
972 printf("Muxer %s [%s]:\n", fmt->name, fmt->long_name);
975 printf(" Common extensions: %s.\n", fmt->extensions);
977 printf(" Mime type: %s.\n", fmt->mime_type);
978 if (fmt->video_codec != AV_CODEC_ID_NONE &&
979 (desc = avcodec_descriptor_get(fmt->video_codec))) {
980 printf(" Default video codec: %s.\n", desc->name);
982 if (fmt->audio_codec != AV_CODEC_ID_NONE &&
983 (desc = avcodec_descriptor_get(fmt->audio_codec))) {
984 printf(" Default audio codec: %s.\n", desc->name);
986 if (fmt->subtitle_codec != AV_CODEC_ID_NONE &&
987 (desc = avcodec_descriptor_get(fmt->subtitle_codec))) {
988 printf(" Default subtitle codec: %s.\n", desc->name);
992 show_help_children(fmt->priv_class, AV_OPT_FLAG_ENCODING_PARAM);
995 int show_help(void *optctx, const char *opt, const char *arg)
998 av_log_set_callback(log_callback_help);
1000 topic = av_strdup(arg ? arg : "");
1001 par = strchr(topic, '=');
1006 show_help_default(topic, par);
1007 } else if (!strcmp(topic, "decoder")) {
1008 show_help_codec(par, 0);
1009 } else if (!strcmp(topic, "encoder")) {
1010 show_help_codec(par, 1);
1011 } else if (!strcmp(topic, "demuxer")) {
1012 show_help_demuxer(par);
1013 } else if (!strcmp(topic, "muxer")) {
1014 show_help_muxer(par);
1016 show_help_default(topic, par);
1023 int read_yesno(void)
1026 int yesno = (toupper(c) == 'Y');
1028 while (c != '\n' && c != EOF)
1034 int cmdutils_read_file(const char *filename, char **bufptr, size_t *size)
1037 FILE *f = fopen(filename, "rb");
1040 av_log(NULL, AV_LOG_ERROR, "Cannot read file '%s': %s\n", filename,
1042 return AVERROR(errno);
1044 fseek(f, 0, SEEK_END);
1046 fseek(f, 0, SEEK_SET);
1047 *bufptr = av_malloc(*size + 1);
1049 av_log(NULL, AV_LOG_ERROR, "Could not allocate file buffer\n");
1051 return AVERROR(ENOMEM);
1053 ret = fread(*bufptr, 1, *size, f);
1057 av_log(NULL, AV_LOG_ERROR, "Error while reading file '%s': %s\n",
1058 filename, strerror(errno));
1059 ret = AVERROR(errno);
1064 (*bufptr)[*size++] = '\0';
1071 void init_pts_correction(PtsCorrectionContext *ctx)
1073 ctx->num_faulty_pts = ctx->num_faulty_dts = 0;
1074 ctx->last_pts = ctx->last_dts = INT64_MIN;
1077 int64_t guess_correct_pts(PtsCorrectionContext *ctx, int64_t reordered_pts,
1080 int64_t pts = AV_NOPTS_VALUE;
1082 if (dts != AV_NOPTS_VALUE) {
1083 ctx->num_faulty_dts += dts <= ctx->last_dts;
1084 ctx->last_dts = dts;
1086 if (reordered_pts != AV_NOPTS_VALUE) {
1087 ctx->num_faulty_pts += reordered_pts <= ctx->last_pts;
1088 ctx->last_pts = reordered_pts;
1090 if ((ctx->num_faulty_pts<=ctx->num_faulty_dts || dts == AV_NOPTS_VALUE)
1091 && reordered_pts != AV_NOPTS_VALUE)
1092 pts = reordered_pts;
1099 FILE *get_preset_file(char *filename, size_t filename_size,
1100 const char *preset_name, int is_path,
1101 const char *codec_name)
1105 const char *base[3] = { getenv("AVCONV_DATADIR"),
1110 av_strlcpy(filename, preset_name, filename_size);
1111 f = fopen(filename, "r");
1113 for (i = 0; i < 3 && !f; i++) {
1116 snprintf(filename, filename_size, "%s%s/%s.avpreset", base[i],
1117 i != 1 ? "" : "/.avconv", preset_name);
1118 f = fopen(filename, "r");
1119 if (!f && codec_name) {
1120 snprintf(filename, filename_size,
1121 "%s%s/%s-%s.avpreset",
1122 base[i], i != 1 ? "" : "/.avconv", codec_name,
1124 f = fopen(filename, "r");
1132 int check_stream_specifier(AVFormatContext *s, AVStream *st, const char *spec)
1134 if (*spec <= '9' && *spec >= '0') /* opt:index */
1135 return strtol(spec, NULL, 0) == st->index;
1136 else if (*spec == 'v' || *spec == 'a' || *spec == 's' || *spec == 'd' ||
1137 *spec == 't') { /* opt:[vasdt] */
1138 enum AVMediaType type;
1141 case 'v': type = AVMEDIA_TYPE_VIDEO; break;
1142 case 'a': type = AVMEDIA_TYPE_AUDIO; break;
1143 case 's': type = AVMEDIA_TYPE_SUBTITLE; break;
1144 case 'd': type = AVMEDIA_TYPE_DATA; break;
1145 case 't': type = AVMEDIA_TYPE_ATTACHMENT; break;
1146 default: av_assert0(0);
1148 if (type != st->codec->codec_type)
1150 if (*spec++ == ':') { /* possibly followed by :index */
1151 int i, index = strtol(spec, NULL, 0);
1152 for (i = 0; i < s->nb_streams; i++)
1153 if (s->streams[i]->codec->codec_type == type && index-- == 0)
1154 return i == st->index;
1158 } else if (*spec == 'p' && *(spec + 1) == ':') {
1162 prog_id = strtol(spec, &endptr, 0);
1163 for (i = 0; i < s->nb_programs; i++) {
1164 if (s->programs[i]->id != prog_id)
1167 if (*endptr++ == ':') {
1168 int stream_idx = strtol(endptr, NULL, 0);
1169 return stream_idx >= 0 &&
1170 stream_idx < s->programs[i]->nb_stream_indexes &&
1171 st->index == s->programs[i]->stream_index[stream_idx];
1174 for (j = 0; j < s->programs[i]->nb_stream_indexes; j++)
1175 if (st->index == s->programs[i]->stream_index[j])
1179 } else if (!*spec) /* empty specifier, matches everything */
1182 av_log(s, AV_LOG_ERROR, "Invalid stream specifier: %s.\n", spec);
1183 return AVERROR(EINVAL);
1186 AVDictionary *filter_codec_opts(AVDictionary *opts, enum AVCodecID codec_id,
1187 AVFormatContext *s, AVStream *st, AVCodec *codec)
1189 AVDictionary *ret = NULL;
1190 AVDictionaryEntry *t = NULL;
1191 int flags = s->oformat ? AV_OPT_FLAG_ENCODING_PARAM
1192 : AV_OPT_FLAG_DECODING_PARAM;
1194 const AVClass *cc = avcodec_get_class();
1197 codec = s->oformat ? avcodec_find_encoder(codec_id)
1198 : avcodec_find_decoder(codec_id);
1202 switch (codec->type) {
1203 case AVMEDIA_TYPE_VIDEO:
1205 flags |= AV_OPT_FLAG_VIDEO_PARAM;
1207 case AVMEDIA_TYPE_AUDIO:
1209 flags |= AV_OPT_FLAG_AUDIO_PARAM;
1211 case AVMEDIA_TYPE_SUBTITLE:
1213 flags |= AV_OPT_FLAG_SUBTITLE_PARAM;
1217 while (t = av_dict_get(opts, "", t, AV_DICT_IGNORE_SUFFIX)) {
1218 char *p = strchr(t->key, ':');
1220 /* check stream specification in opt name */
1222 switch (check_stream_specifier(s, st, p + 1)) {
1223 case 1: *p = 0; break;
1225 default: return NULL;
1228 if (av_opt_find(&cc, t->key, NULL, flags, AV_OPT_SEARCH_FAKE_OBJ) ||
1229 (codec && codec->priv_class &&
1230 av_opt_find(&codec->priv_class, t->key, NULL, flags,
1231 AV_OPT_SEARCH_FAKE_OBJ)))
1232 av_dict_set(&ret, t->key, t->value, 0);
1233 else if (t->key[0] == prefix &&
1234 av_opt_find(&cc, t->key + 1, NULL, flags,
1235 AV_OPT_SEARCH_FAKE_OBJ))
1236 av_dict_set(&ret, t->key + 1, t->value, 0);
1244 AVDictionary **setup_find_stream_info_opts(AVFormatContext *s,
1245 AVDictionary *codec_opts)
1248 AVDictionary **opts;
1252 opts = av_mallocz(s->nb_streams * sizeof(*opts));
1254 av_log(NULL, AV_LOG_ERROR,
1255 "Could not alloc memory for stream options.\n");
1258 for (i = 0; i < s->nb_streams; i++)
1259 opts[i] = filter_codec_opts(codec_opts, s->streams[i]->codec->codec_id,
1260 s, s->streams[i], NULL);
1264 void *grow_array(void *array, int elem_size, int *size, int new_size)
1266 if (new_size >= INT_MAX / elem_size) {
1267 av_log(NULL, AV_LOG_ERROR, "Array too big.\n");
1270 if (*size < new_size) {
1271 uint8_t *tmp = av_realloc(array, new_size*elem_size);
1273 av_log(NULL, AV_LOG_ERROR, "Could not alloc buffer.\n");
1276 memset(tmp + *size*elem_size, 0, (new_size-*size) * elem_size);
1283 static int alloc_buffer(FrameBuffer **pool, AVCodecContext *s, FrameBuffer **pbuf)
1285 FrameBuffer *buf = av_mallocz(sizeof(*buf));
1287 const int pixel_size = av_pix_fmt_descriptors[s->pix_fmt].comp[0].step_minus1+1;
1288 int h_chroma_shift, v_chroma_shift;
1289 int edge = 32; // XXX should be avcodec_get_edge_width(), but that fails on svq1
1290 int w = s->width, h = s->height;
1293 return AVERROR(ENOMEM);
1295 if (!(s->flags & CODEC_FLAG_EMU_EDGE)) {
1300 avcodec_align_dimensions(s, &w, &h);
1301 if ((ret = av_image_alloc(buf->base, buf->linesize, w, h,
1302 s->pix_fmt, 32)) < 0) {
1306 /* XXX this shouldn't be needed, but some tests break without this line
1307 * those decoders are buggy and need to be fixed.
1308 * the following tests fail:
1309 * cdgraphics, ansi, aasc, fraps-v1, qtrle-1bit
1311 memset(buf->base[0], 128, ret);
1313 avcodec_get_chroma_sub_sample(s->pix_fmt, &h_chroma_shift, &v_chroma_shift);
1314 for (i = 0; i < FF_ARRAY_ELEMS(buf->data); i++) {
1315 const int h_shift = i==0 ? 0 : h_chroma_shift;
1316 const int v_shift = i==0 ? 0 : v_chroma_shift;
1317 if (s->flags & CODEC_FLAG_EMU_EDGE)
1318 buf->data[i] = buf->base[i];
1319 else if (buf->base[i])
1320 buf->data[i] = buf->base[i] +
1321 FFALIGN((buf->linesize[i]*edge >> v_shift) +
1322 (pixel_size*edge >> h_shift), 32);
1326 buf->pix_fmt = s->pix_fmt;
1333 int codec_get_buffer(AVCodecContext *s, AVFrame *frame)
1335 FrameBuffer **pool = s->opaque;
1339 if (!*pool && (ret = alloc_buffer(pool, s, pool)) < 0)
1345 if (buf->w != s->width || buf->h != s->height || buf->pix_fmt != s->pix_fmt) {
1346 av_freep(&buf->base[0]);
1348 if ((ret = alloc_buffer(pool, s, &buf)) < 0)
1353 frame->opaque = buf;
1354 frame->type = FF_BUFFER_TYPE_USER;
1355 frame->extended_data = frame->data;
1356 frame->pkt_pts = s->pkt ? s->pkt->pts : AV_NOPTS_VALUE;
1357 frame->width = buf->w;
1358 frame->height = buf->h;
1359 frame->format = buf->pix_fmt;
1360 frame->sample_aspect_ratio = s->sample_aspect_ratio;
1362 for (i = 0; i < FF_ARRAY_ELEMS(buf->data); i++) {
1363 frame->base[i] = buf->base[i]; // XXX h264.c uses base though it shouldn't
1364 frame->data[i] = buf->data[i];
1365 frame->linesize[i] = buf->linesize[i];
1371 static void unref_buffer(FrameBuffer *buf)
1373 FrameBuffer **pool = buf->pool;
1375 av_assert0(buf->refcount);
1377 if (!buf->refcount) {
1383 void codec_release_buffer(AVCodecContext *s, AVFrame *frame)
1385 FrameBuffer *buf = frame->opaque;
1388 for (i = 0; i < FF_ARRAY_ELEMS(frame->data); i++)
1389 frame->data[i] = NULL;
1394 void filter_release_buffer(AVFilterBuffer *fb)
1396 FrameBuffer *buf = fb->priv;
1401 void free_buffer_pool(FrameBuffer **pool)
1403 FrameBuffer *buf = *pool;
1406 av_freep(&buf->base[0]);