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;
59 static const int this_year = 2012;
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);
79 void log_callback_help(void *ptr, int level, const char *fmt, va_list vl)
81 vfprintf(stdout, fmt, vl);
84 double parse_number_or_die(const char *context, const char *numstr, int type,
85 double min, double max)
89 double d = av_strtod(numstr, &tail);
91 error = "Expected number for %s but found: %s\n";
92 else if (d < min || d > max)
93 error = "The value for %s was %s which is not within %f - %f\n";
94 else if (type == OPT_INT64 && (int64_t)d != d)
95 error = "Expected int64 for %s but found %s\n";
96 else if (type == OPT_INT && (int)d != d)
97 error = "Expected int for %s but found %s\n";
100 av_log(NULL, AV_LOG_FATAL, error, context, numstr, min, max);
105 int64_t parse_time_or_die(const char *context, const char *timestr,
109 if (av_parse_time(&us, timestr, is_duration) < 0) {
110 av_log(NULL, AV_LOG_FATAL, "Invalid %s specification for %s: %s\n",
111 is_duration ? "duration" : "date", context, timestr);
117 void show_help_options(const OptionDef *options, const char *msg, int req_flags,
118 int rej_flags, int alt_flags)
124 for (po = options; po->name != NULL; po++) {
127 if (((po->flags & req_flags) != req_flags) ||
128 (alt_flags && !(po->flags & alt_flags)) ||
129 (po->flags & rej_flags))
136 av_strlcpy(buf, po->name, sizeof(buf));
138 av_strlcat(buf, " ", sizeof(buf));
139 av_strlcat(buf, po->argname, sizeof(buf));
141 printf("-%-17s %s\n", buf, po->help);
146 void show_help_children(const AVClass *class, int flags)
148 const AVClass *child = NULL;
149 av_opt_show2(&class, NULL, flags, 0);
152 while (child = av_opt_child_class_next(class, child))
153 show_help_children(child, flags);
156 static const OptionDef *find_option(const OptionDef *po, const char *name)
158 const char *p = strchr(name, ':');
159 int len = p ? p - name : strlen(name);
161 while (po->name != NULL) {
162 if (!strncmp(name, po->name, len) && strlen(po->name) == len)
169 #if defined(_WIN32) && !defined(__MINGW32CE__)
171 #include <shellapi.h>
172 /* Will be leaked on exit */
173 static char** win32_argv_utf8 = NULL;
174 static int win32_argc = 0;
177 * Prepare command line arguments for executable.
178 * For Windows - perform wide-char to UTF-8 conversion.
179 * Input arguments should be main() function arguments.
180 * @param argc_ptr Arguments number (including executable)
181 * @param argv_ptr Arguments list.
183 static void prepare_app_arguments(int *argc_ptr, char ***argv_ptr)
187 int i, buffsize = 0, offset = 0;
189 if (win32_argv_utf8) {
190 *argc_ptr = win32_argc;
191 *argv_ptr = win32_argv_utf8;
196 argv_w = CommandLineToArgvW(GetCommandLineW(), &win32_argc);
197 if (win32_argc <= 0 || !argv_w)
200 /* determine the UTF-8 buffer size (including NULL-termination symbols) */
201 for (i = 0; i < win32_argc; i++)
202 buffsize += WideCharToMultiByte(CP_UTF8, 0, argv_w[i], -1,
203 NULL, 0, NULL, NULL);
205 win32_argv_utf8 = av_mallocz(sizeof(char *) * (win32_argc + 1) + buffsize);
206 argstr_flat = (char *)win32_argv_utf8 + sizeof(char *) * (win32_argc + 1);
207 if (win32_argv_utf8 == NULL) {
212 for (i = 0; i < win32_argc; i++) {
213 win32_argv_utf8[i] = &argstr_flat[offset];
214 offset += WideCharToMultiByte(CP_UTF8, 0, argv_w[i], -1,
215 &argstr_flat[offset],
216 buffsize - offset, NULL, NULL);
218 win32_argv_utf8[i] = NULL;
221 *argc_ptr = win32_argc;
222 *argv_ptr = win32_argv_utf8;
225 static inline void prepare_app_arguments(int *argc_ptr, char ***argv_ptr)
229 #endif /* WIN32 && !__MINGW32CE__ */
231 int parse_option(void *optctx, const char *opt, const char *arg,
232 const OptionDef *options)
239 po = find_option(options, opt);
240 if (!po->name && opt[0] == 'n' && opt[1] == 'o') {
241 /* handle 'no' bool option */
242 po = find_option(options, opt + 2);
243 if ((po->name && (po->flags & OPT_BOOL)))
247 po = find_option(options, "default");
249 av_log(NULL, AV_LOG_ERROR, "Unrecognized option '%s'\n", opt);
250 return AVERROR(EINVAL);
252 if (po->flags & HAS_ARG && !arg) {
253 av_log(NULL, AV_LOG_ERROR, "Missing argument for option '%s'\n", opt);
254 return AVERROR(EINVAL);
257 /* new-style options contain an offset into optctx, old-style address of
259 dst = po->flags & (OPT_OFFSET | OPT_SPEC) ? (uint8_t *)optctx + po->u.off
262 if (po->flags & OPT_SPEC) {
263 SpecifierOpt **so = dst;
264 char *p = strchr(opt, ':');
266 dstcount = (int *)(so + 1);
267 *so = grow_array(*so, sizeof(**so), dstcount, *dstcount + 1);
268 (*so)[*dstcount - 1].specifier = av_strdup(p ? p + 1 : "");
269 dst = &(*so)[*dstcount - 1].u;
272 if (po->flags & OPT_STRING) {
274 str = av_strdup(arg);
277 } else if (po->flags & OPT_BOOL) {
278 *(int *)dst = bool_val;
279 } else if (po->flags & OPT_INT) {
280 *(int *)dst = parse_number_or_die(opt, arg, OPT_INT64, INT_MIN, INT_MAX);
281 } else if (po->flags & OPT_INT64) {
282 *(int64_t *)dst = parse_number_or_die(opt, arg, OPT_INT64, INT64_MIN, INT64_MAX);
283 } else if (po->flags & OPT_TIME) {
284 *(int64_t *)dst = parse_time_or_die(opt, arg, 1);
285 } else if (po->flags & OPT_FLOAT) {
286 *(float *)dst = parse_number_or_die(opt, arg, OPT_FLOAT, -INFINITY, INFINITY);
287 } else if (po->flags & OPT_DOUBLE) {
288 *(double *)dst = parse_number_or_die(opt, arg, OPT_DOUBLE, -INFINITY, INFINITY);
289 } else if (po->u.func_arg) {
290 int ret = po->u.func_arg(optctx, opt, arg);
292 av_log(NULL, AV_LOG_ERROR,
293 "Failed to set value '%s' for option '%s'\n", arg, opt);
297 if (po->flags & OPT_EXIT)
299 return !!(po->flags & HAS_ARG);
302 void parse_options(void *optctx, int argc, char **argv, const OptionDef *options,
303 void (*parse_arg_function)(void *, const char*))
306 int optindex, handleoptions = 1, ret;
308 /* perform system-dependent conversions for arguments list */
309 prepare_app_arguments(&argc, &argv);
313 while (optindex < argc) {
314 opt = argv[optindex++];
316 if (handleoptions && opt[0] == '-' && opt[1] != '\0') {
317 if (opt[1] == '-' && opt[2] == '\0') {
323 if ((ret = parse_option(optctx, opt, argv[optindex], options)) < 0)
327 if (parse_arg_function)
328 parse_arg_function(optctx, opt);
333 int locate_option(int argc, char **argv, const OptionDef *options,
339 for (i = 1; i < argc; i++) {
340 const char *cur_opt = argv[i];
342 if (*cur_opt++ != '-')
345 po = find_option(options, cur_opt);
346 if (!po->name && cur_opt[0] == 'n' && cur_opt[1] == 'o')
347 po = find_option(options, cur_opt + 2);
349 if ((!po->name && !strcmp(cur_opt, optname)) ||
350 (po->name && !strcmp(optname, po->name)))
353 if (!po || po->flags & HAS_ARG)
359 void parse_loglevel(int argc, char **argv, const OptionDef *options)
361 int idx = locate_option(argc, argv, options, "loglevel");
363 idx = locate_option(argc, argv, options, "v");
364 if (idx && argv[idx + 1])
365 opt_loglevel(NULL, "loglevel", argv[idx + 1]);
368 #define FLAGS (o->type == AV_OPT_TYPE_FLAGS) ? AV_DICT_APPEND : 0
369 int opt_default(void *optctx, const char *opt, const char *arg)
372 char opt_stripped[128];
374 const AVClass *cc = avcodec_get_class(), *fc = avformat_get_class();
376 const AVClass *sc = sws_get_class();
379 if (!(p = strchr(opt, ':')))
380 p = opt + strlen(opt);
381 av_strlcpy(opt_stripped, opt, FFMIN(sizeof(opt_stripped), p - opt + 1));
383 if ((o = av_opt_find(&cc, opt_stripped, NULL, 0,
384 AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ)) ||
385 ((opt[0] == 'v' || opt[0] == 'a' || opt[0] == 's') &&
386 (o = av_opt_find(&cc, opt + 1, NULL, 0, AV_OPT_SEARCH_FAKE_OBJ))))
387 av_dict_set(&codec_opts, opt, arg, FLAGS);
388 else if ((o = av_opt_find(&fc, opt, NULL, 0,
389 AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ)))
390 av_dict_set(&format_opts, opt, arg, FLAGS);
392 else if ((o = av_opt_find(&sc, opt, NULL, 0,
393 AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ))) {
394 // XXX we only support sws_flags, not arbitrary sws options
395 int ret = av_opt_set(sws_opts, opt, arg, 0);
397 av_log(NULL, AV_LOG_ERROR, "Error setting option %s.\n", opt);
405 av_log(NULL, AV_LOG_ERROR, "Unrecognized option '%s'\n", opt);
406 return AVERROR_OPTION_NOT_FOUND;
409 int opt_loglevel(void *optctx, const char *opt, const char *arg)
411 const struct { const char *name; int level; } log_levels[] = {
412 { "quiet" , AV_LOG_QUIET },
413 { "panic" , AV_LOG_PANIC },
414 { "fatal" , AV_LOG_FATAL },
415 { "error" , AV_LOG_ERROR },
416 { "warning", AV_LOG_WARNING },
417 { "info" , AV_LOG_INFO },
418 { "verbose", AV_LOG_VERBOSE },
419 { "debug" , AV_LOG_DEBUG },
425 for (i = 0; i < FF_ARRAY_ELEMS(log_levels); i++) {
426 if (!strcmp(log_levels[i].name, arg)) {
427 av_log_set_level(log_levels[i].level);
432 level = strtol(arg, &tail, 10);
434 av_log(NULL, AV_LOG_FATAL, "Invalid loglevel \"%s\". "
435 "Possible levels are numbers or:\n", arg);
436 for (i = 0; i < FF_ARRAY_ELEMS(log_levels); i++)
437 av_log(NULL, AV_LOG_FATAL, "\"%s\"\n", log_levels[i].name);
440 av_log_set_level(level);
444 int opt_timelimit(void *optctx, const char *opt, const char *arg)
447 int lim = parse_number_or_die(opt, arg, OPT_INT64, 0, INT_MAX);
448 struct rlimit rl = { lim, lim + 1 };
449 if (setrlimit(RLIMIT_CPU, &rl))
452 av_log(NULL, AV_LOG_WARNING, "-%s not implemented on this OS\n", opt);
457 void print_error(const char *filename, int err)
460 const char *errbuf_ptr = errbuf;
462 if (av_strerror(err, errbuf, sizeof(errbuf)) < 0)
463 errbuf_ptr = strerror(AVUNERROR(err));
464 av_log(NULL, AV_LOG_ERROR, "%s: %s\n", filename, errbuf_ptr);
467 static int warned_cfg = 0;
470 #define SHOW_VERSION 2
471 #define SHOW_CONFIG 4
473 #define PRINT_LIB_INFO(libname, LIBNAME, flags, level) \
474 if (CONFIG_##LIBNAME) { \
475 const char *indent = flags & INDENT? " " : ""; \
476 if (flags & SHOW_VERSION) { \
477 unsigned int version = libname##_version(); \
478 av_log(NULL, level, \
479 "%slib%-10s %2d.%3d.%2d / %2d.%3d.%2d\n", \
481 LIB##LIBNAME##_VERSION_MAJOR, \
482 LIB##LIBNAME##_VERSION_MINOR, \
483 LIB##LIBNAME##_VERSION_MICRO, \
484 version >> 16, version >> 8 & 0xff, version & 0xff); \
486 if (flags & SHOW_CONFIG) { \
487 const char *cfg = libname##_configuration(); \
488 if (strcmp(LIBAV_CONFIGURATION, cfg)) { \
490 av_log(NULL, level, \
491 "%sWARNING: library configuration mismatch\n", \
495 av_log(NULL, level, "%s%-11s configuration: %s\n", \
496 indent, #libname, cfg); \
501 static void print_all_libs_info(int flags, int level)
503 PRINT_LIB_INFO(avutil, AVUTIL, flags, level);
504 PRINT_LIB_INFO(avcodec, AVCODEC, flags, level);
505 PRINT_LIB_INFO(avformat, AVFORMAT, flags, level);
506 PRINT_LIB_INFO(avdevice, AVDEVICE, flags, level);
507 PRINT_LIB_INFO(avfilter, AVFILTER, flags, level);
508 PRINT_LIB_INFO(avresample, AVRESAMPLE, flags, level);
509 PRINT_LIB_INFO(swscale, SWSCALE, flags, level);
512 void show_banner(void)
514 av_log(NULL, AV_LOG_INFO,
515 "%s version " LIBAV_VERSION ", Copyright (c) %d-%d the Libav developers\n",
516 program_name, program_birth_year, this_year);
517 av_log(NULL, AV_LOG_INFO, " built on %s %s with %s\n",
518 __DATE__, __TIME__, CC_IDENT);
519 av_log(NULL, AV_LOG_VERBOSE, " configuration: " LIBAV_CONFIGURATION "\n");
520 print_all_libs_info(INDENT|SHOW_CONFIG, AV_LOG_VERBOSE);
521 print_all_libs_info(INDENT|SHOW_VERSION, AV_LOG_VERBOSE);
524 int show_version(void *optctx, const char *opt, const char *arg)
526 av_log_set_callback(log_callback_help);
527 printf("%s " LIBAV_VERSION "\n", program_name);
528 print_all_libs_info(SHOW_VERSION, AV_LOG_INFO);
533 int show_license(void *optctx, const char *opt, const char *arg)
537 "This version of %s has nonfree parts compiled in.\n"
538 "Therefore it is not legally redistributable.\n",
541 "%s is free software; you can redistribute it and/or modify\n"
542 "it under the terms of the GNU General Public License as published by\n"
543 "the Free Software Foundation; either version 3 of the License, or\n"
544 "(at your option) any later version.\n"
546 "%s is distributed in the hope that it will be useful,\n"
547 "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
548 "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n"
549 "GNU General Public License for more details.\n"
551 "You should have received a copy of the GNU General Public License\n"
552 "along with %s. If not, see <http://www.gnu.org/licenses/>.\n",
553 program_name, program_name, program_name
555 "%s is free software; you can redistribute it and/or modify\n"
556 "it under the terms of the GNU General Public License as published by\n"
557 "the Free Software Foundation; either version 2 of the License, or\n"
558 "(at your option) any later version.\n"
560 "%s is distributed in the hope that it will be useful,\n"
561 "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
562 "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n"
563 "GNU General Public License for more details.\n"
565 "You should have received a copy of the GNU General Public License\n"
566 "along with %s; if not, write to the Free Software\n"
567 "Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n",
568 program_name, program_name, program_name
570 "%s is free software; you can redistribute it and/or modify\n"
571 "it under the terms of the GNU Lesser General Public License as published by\n"
572 "the Free Software Foundation; either version 3 of the License, or\n"
573 "(at your option) any later version.\n"
575 "%s is distributed in the hope that it will be useful,\n"
576 "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
577 "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n"
578 "GNU Lesser General Public License for more details.\n"
580 "You should have received a copy of the GNU Lesser General Public License\n"
581 "along with %s. If not, see <http://www.gnu.org/licenses/>.\n",
582 program_name, program_name, program_name
584 "%s is free software; you can redistribute it and/or\n"
585 "modify it under the terms of the GNU Lesser General Public\n"
586 "License as published by the Free Software Foundation; either\n"
587 "version 2.1 of the License, or (at your option) any later version.\n"
589 "%s is distributed in the hope that it will be useful,\n"
590 "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
591 "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n"
592 "Lesser General Public License for more details.\n"
594 "You should have received a copy of the GNU Lesser General Public\n"
595 "License along with %s; if not, write to the Free Software\n"
596 "Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n",
597 program_name, program_name, program_name
604 int show_formats(void *optctx, const char *opt, const char *arg)
606 AVInputFormat *ifmt = NULL;
607 AVOutputFormat *ofmt = NULL;
608 const char *last_name;
610 printf("File formats:\n"
611 " D. = Demuxing supported\n"
612 " .E = Muxing supported\n"
618 const char *name = NULL;
619 const char *long_name = NULL;
621 while ((ofmt = av_oformat_next(ofmt))) {
622 if ((name == NULL || strcmp(ofmt->name, name) < 0) &&
623 strcmp(ofmt->name, last_name) > 0) {
625 long_name = ofmt->long_name;
629 while ((ifmt = av_iformat_next(ifmt))) {
630 if ((name == NULL || strcmp(ifmt->name, name) < 0) &&
631 strcmp(ifmt->name, last_name) > 0) {
633 long_name = ifmt->long_name;
636 if (name && strcmp(ifmt->name, name) == 0)
643 printf(" %s%s %-15s %s\n",
647 long_name ? long_name:" ");
652 #define PRINT_CODEC_SUPPORTED(codec, field, type, list_name, term, get_name) \
653 if (codec->field) { \
654 const type *p = c->field; \
656 printf(" Supported " list_name ":"); \
657 while (*p != term) { \
659 printf(" %s", name); \
665 static void print_codec(const AVCodec *c)
667 int encoder = av_codec_is_encoder(c);
669 printf("%s %s [%s]:\n", encoder ? "Encoder" : "Decoder", c->name,
670 c->long_name ? c->long_name : "");
672 if (c->type == AVMEDIA_TYPE_VIDEO) {
673 printf(" Threading capabilities: ");
674 switch (c->capabilities & (CODEC_CAP_FRAME_THREADS |
675 CODEC_CAP_SLICE_THREADS)) {
676 case CODEC_CAP_FRAME_THREADS |
677 CODEC_CAP_SLICE_THREADS: printf("frame and slice"); break;
678 case CODEC_CAP_FRAME_THREADS: printf("frame"); break;
679 case CODEC_CAP_SLICE_THREADS: printf("slice"); break;
680 default: printf("no"); break;
685 if (c->supported_framerates) {
686 const AVRational *fps = c->supported_framerates;
688 printf(" Supported framerates:");
690 printf(" %d/%d", fps->num, fps->den);
695 PRINT_CODEC_SUPPORTED(c, pix_fmts, enum AVPixelFormat, "pixel formats",
696 AV_PIX_FMT_NONE, GET_PIX_FMT_NAME);
697 PRINT_CODEC_SUPPORTED(c, supported_samplerates, int, "sample rates", 0,
698 GET_SAMPLE_RATE_NAME);
699 PRINT_CODEC_SUPPORTED(c, sample_fmts, enum AVSampleFormat, "sample formats",
700 AV_SAMPLE_FMT_NONE, GET_SAMPLE_FMT_NAME);
701 PRINT_CODEC_SUPPORTED(c, channel_layouts, uint64_t, "channel layouts",
702 0, GET_CH_LAYOUT_DESC);
705 show_help_children(c->priv_class,
706 AV_OPT_FLAG_ENCODING_PARAM |
707 AV_OPT_FLAG_DECODING_PARAM);
711 static char get_media_type_char(enum AVMediaType type)
714 case AVMEDIA_TYPE_VIDEO: return 'V';
715 case AVMEDIA_TYPE_AUDIO: return 'A';
716 case AVMEDIA_TYPE_SUBTITLE: return 'S';
721 static const AVCodec *next_codec_for_id(enum AVCodecID id, const AVCodec *prev,
724 while ((prev = av_codec_next(prev))) {
725 if (prev->id == id &&
726 (encoder ? av_codec_is_encoder(prev) : av_codec_is_decoder(prev)))
732 static void print_codecs_for_id(enum AVCodecID id, int encoder)
734 const AVCodec *codec = NULL;
736 printf(" (%s: ", encoder ? "encoders" : "decoders");
738 while ((codec = next_codec_for_id(id, codec, encoder)))
739 printf("%s ", codec->name);
744 int show_codecs(void *optctx, const char *opt, const char *arg)
746 const AVCodecDescriptor *desc = NULL;
749 " D..... = Decoding supported\n"
750 " .E.... = Encoding supported\n"
751 " ..V... = Video codec\n"
752 " ..A... = Audio codec\n"
753 " ..S... = Subtitle codec\n"
754 " ...I.. = Intra frame-only codec\n"
755 " ....L. = Lossy compression\n"
756 " .....S = Lossless compression\n"
758 while ((desc = avcodec_descriptor_next(desc))) {
759 const AVCodec *codec = NULL;
761 printf(avcodec_find_decoder(desc->id) ? "D" : ".");
762 printf(avcodec_find_encoder(desc->id) ? "E" : ".");
764 printf("%c", get_media_type_char(desc->type));
765 printf((desc->props & AV_CODEC_PROP_INTRA_ONLY) ? "I" : ".");
766 printf((desc->props & AV_CODEC_PROP_LOSSY) ? "L" : ".");
767 printf((desc->props & AV_CODEC_PROP_LOSSLESS) ? "S" : ".");
769 printf(" %-20s %s", desc->name, desc->long_name ? desc->long_name : "");
771 /* print decoders/encoders when there's more than one or their
772 * names are different from codec name */
773 while ((codec = next_codec_for_id(desc->id, codec, 0))) {
774 if (strcmp(codec->name, desc->name)) {
775 print_codecs_for_id(desc->id, 0);
780 while ((codec = next_codec_for_id(desc->id, codec, 1))) {
781 if (strcmp(codec->name, desc->name)) {
782 print_codecs_for_id(desc->id, 1);
792 static void print_codecs(int encoder)
794 const AVCodecDescriptor *desc = NULL;
800 " .F.. = Frame-level multithreading\n"
801 " ..S. = Slice-level multithreading\n"
802 " ...X = Codec is experimental\n"
804 encoder ? "Encoders" : "Decoders");
805 while ((desc = avcodec_descriptor_next(desc))) {
806 const AVCodec *codec = NULL;
808 while ((codec = next_codec_for_id(desc->id, codec, encoder))) {
809 printf("%c", get_media_type_char(desc->type));
810 printf((codec->capabilities & CODEC_CAP_FRAME_THREADS) ? "F" : ".");
811 printf((codec->capabilities & CODEC_CAP_SLICE_THREADS) ? "S" : ".");
812 printf((codec->capabilities & CODEC_CAP_EXPERIMENTAL) ? "X" : ".");
814 printf(" %-20s %s", codec->name, codec->long_name ? codec->long_name : "");
815 if (strcmp(codec->name, desc->name))
816 printf(" (codec %s)", desc->name);
823 int show_decoders(void *optctx, const char *opt, const char *arg)
829 int show_encoders(void *optctx, const char *opt, const char *arg)
835 int show_bsfs(void *optctx, const char *opt, const char *arg)
837 AVBitStreamFilter *bsf = NULL;
839 printf("Bitstream filters:\n");
840 while ((bsf = av_bitstream_filter_next(bsf)))
841 printf("%s\n", bsf->name);
846 int show_protocols(void *optctx, const char *opt, const char *arg)
851 printf("Supported file protocols:\n"
853 while ((name = avio_enum_protocols(&opaque, 0)))
854 printf("%s\n", name);
856 while ((name = avio_enum_protocols(&opaque, 1)))
857 printf("%s\n", name);
861 int show_filters(void *optctx, const char *opt, const char *arg)
863 AVFilter av_unused(**filter) = NULL;
865 printf("Filters:\n");
867 while ((filter = av_filter_next(filter)) && *filter)
868 printf("%-16s %s\n", (*filter)->name, (*filter)->description);
873 int show_pix_fmts(void *optctx, const char *opt, const char *arg)
875 const AVPixFmtDescriptor *pix_desc = NULL;
877 printf("Pixel formats:\n"
878 "I.... = Supported Input format for conversion\n"
879 ".O... = Supported Output format for conversion\n"
880 "..H.. = Hardware accelerated format\n"
881 "...P. = Paletted format\n"
882 "....B = Bitstream format\n"
883 "FLAGS NAME NB_COMPONENTS BITS_PER_PIXEL\n"
887 # define sws_isSupportedInput(x) 0
888 # define sws_isSupportedOutput(x) 0
891 while ((pix_desc = av_pix_fmt_desc_next(pix_desc))) {
892 enum AVPixelFormat pix_fmt = av_pix_fmt_desc_get_id(pix_desc);
893 printf("%c%c%c%c%c %-16s %d %2d\n",
894 sws_isSupportedInput (pix_fmt) ? 'I' : '.',
895 sws_isSupportedOutput(pix_fmt) ? 'O' : '.',
896 pix_desc->flags & PIX_FMT_HWACCEL ? 'H' : '.',
897 pix_desc->flags & PIX_FMT_PAL ? 'P' : '.',
898 pix_desc->flags & PIX_FMT_BITSTREAM ? 'B' : '.',
900 pix_desc->nb_components,
901 av_get_bits_per_pixel(pix_desc));
906 int show_sample_fmts(void *optctx, const char *opt, const char *arg)
910 for (i = -1; i < AV_SAMPLE_FMT_NB; i++)
911 printf("%s\n", av_get_sample_fmt_string(fmt_str, sizeof(fmt_str), i));
915 static void show_help_codec(const char *name, int encoder)
917 const AVCodecDescriptor *desc;
918 const AVCodec *codec;
921 av_log(NULL, AV_LOG_ERROR, "No codec name specified.\n");
925 codec = encoder ? avcodec_find_encoder_by_name(name) :
926 avcodec_find_decoder_by_name(name);
930 else if ((desc = avcodec_descriptor_get_by_name(name))) {
933 while ((codec = next_codec_for_id(desc->id, codec, encoder))) {
939 av_log(NULL, AV_LOG_ERROR, "Codec '%s' is known to Libav, "
940 "but no %s for it are available. Libav might need to be "
941 "recompiled with additional external libraries.\n",
942 name, encoder ? "encoders" : "decoders");
945 av_log(NULL, AV_LOG_ERROR, "Codec '%s' is not recognized by Libav.\n",
950 static void show_help_demuxer(const char *name)
952 const AVInputFormat *fmt = av_find_input_format(name);
955 av_log(NULL, AV_LOG_ERROR, "Unknown format '%s'.\n", name);
959 printf("Demuxer %s [%s]:\n", fmt->name, fmt->long_name);
962 printf(" Common extensions: %s.\n", fmt->extensions);
965 show_help_children(fmt->priv_class, AV_OPT_FLAG_DECODING_PARAM);
968 static void show_help_muxer(const char *name)
970 const AVCodecDescriptor *desc;
971 const AVOutputFormat *fmt = av_guess_format(name, NULL, NULL);
974 av_log(NULL, AV_LOG_ERROR, "Unknown format '%s'.\n", name);
978 printf("Muxer %s [%s]:\n", fmt->name, fmt->long_name);
981 printf(" Common extensions: %s.\n", fmt->extensions);
983 printf(" Mime type: %s.\n", fmt->mime_type);
984 if (fmt->video_codec != AV_CODEC_ID_NONE &&
985 (desc = avcodec_descriptor_get(fmt->video_codec))) {
986 printf(" Default video codec: %s.\n", desc->name);
988 if (fmt->audio_codec != AV_CODEC_ID_NONE &&
989 (desc = avcodec_descriptor_get(fmt->audio_codec))) {
990 printf(" Default audio codec: %s.\n", desc->name);
992 if (fmt->subtitle_codec != AV_CODEC_ID_NONE &&
993 (desc = avcodec_descriptor_get(fmt->subtitle_codec))) {
994 printf(" Default subtitle codec: %s.\n", desc->name);
998 show_help_children(fmt->priv_class, AV_OPT_FLAG_ENCODING_PARAM);
1001 int show_help(void *optctx, const char *opt, const char *arg)
1004 av_log_set_callback(log_callback_help);
1006 topic = av_strdup(arg ? arg : "");
1007 par = strchr(topic, '=');
1012 show_help_default(topic, par);
1013 } else if (!strcmp(topic, "decoder")) {
1014 show_help_codec(par, 0);
1015 } else if (!strcmp(topic, "encoder")) {
1016 show_help_codec(par, 1);
1017 } else if (!strcmp(topic, "demuxer")) {
1018 show_help_demuxer(par);
1019 } else if (!strcmp(topic, "muxer")) {
1020 show_help_muxer(par);
1022 show_help_default(topic, par);
1029 int read_yesno(void)
1032 int yesno = (toupper(c) == 'Y');
1034 while (c != '\n' && c != EOF)
1040 int cmdutils_read_file(const char *filename, char **bufptr, size_t *size)
1043 FILE *f = fopen(filename, "rb");
1046 av_log(NULL, AV_LOG_ERROR, "Cannot read file '%s': %s\n", filename,
1048 return AVERROR(errno);
1050 fseek(f, 0, SEEK_END);
1052 fseek(f, 0, SEEK_SET);
1053 *bufptr = av_malloc(*size + 1);
1055 av_log(NULL, AV_LOG_ERROR, "Could not allocate file buffer\n");
1057 return AVERROR(ENOMEM);
1059 ret = fread(*bufptr, 1, *size, f);
1063 av_log(NULL, AV_LOG_ERROR, "Error while reading file '%s': %s\n",
1064 filename, strerror(errno));
1065 ret = AVERROR(errno);
1070 (*bufptr)[(*size)++] = '\0';
1077 void init_pts_correction(PtsCorrectionContext *ctx)
1079 ctx->num_faulty_pts = ctx->num_faulty_dts = 0;
1080 ctx->last_pts = ctx->last_dts = INT64_MIN;
1083 int64_t guess_correct_pts(PtsCorrectionContext *ctx, int64_t reordered_pts,
1086 int64_t pts = AV_NOPTS_VALUE;
1088 if (dts != AV_NOPTS_VALUE) {
1089 ctx->num_faulty_dts += dts <= ctx->last_dts;
1090 ctx->last_dts = dts;
1092 if (reordered_pts != AV_NOPTS_VALUE) {
1093 ctx->num_faulty_pts += reordered_pts <= ctx->last_pts;
1094 ctx->last_pts = reordered_pts;
1096 if ((ctx->num_faulty_pts<=ctx->num_faulty_dts || dts == AV_NOPTS_VALUE)
1097 && reordered_pts != AV_NOPTS_VALUE)
1098 pts = reordered_pts;
1105 FILE *get_preset_file(char *filename, size_t filename_size,
1106 const char *preset_name, int is_path,
1107 const char *codec_name)
1111 const char *base[3] = { getenv("AVCONV_DATADIR"),
1116 av_strlcpy(filename, preset_name, filename_size);
1117 f = fopen(filename, "r");
1119 for (i = 0; i < 3 && !f; i++) {
1122 snprintf(filename, filename_size, "%s%s/%s.avpreset", base[i],
1123 i != 1 ? "" : "/.avconv", preset_name);
1124 f = fopen(filename, "r");
1125 if (!f && codec_name) {
1126 snprintf(filename, filename_size,
1127 "%s%s/%s-%s.avpreset",
1128 base[i], i != 1 ? "" : "/.avconv", codec_name,
1130 f = fopen(filename, "r");
1138 int check_stream_specifier(AVFormatContext *s, AVStream *st, const char *spec)
1140 if (*spec <= '9' && *spec >= '0') /* opt:index */
1141 return strtol(spec, NULL, 0) == st->index;
1142 else if (*spec == 'v' || *spec == 'a' || *spec == 's' || *spec == 'd' ||
1143 *spec == 't') { /* opt:[vasdt] */
1144 enum AVMediaType type;
1147 case 'v': type = AVMEDIA_TYPE_VIDEO; break;
1148 case 'a': type = AVMEDIA_TYPE_AUDIO; break;
1149 case 's': type = AVMEDIA_TYPE_SUBTITLE; break;
1150 case 'd': type = AVMEDIA_TYPE_DATA; break;
1151 case 't': type = AVMEDIA_TYPE_ATTACHMENT; break;
1152 default: av_assert0(0);
1154 if (type != st->codec->codec_type)
1156 if (*spec++ == ':') { /* possibly followed by :index */
1157 int i, index = strtol(spec, NULL, 0);
1158 for (i = 0; i < s->nb_streams; i++)
1159 if (s->streams[i]->codec->codec_type == type && index-- == 0)
1160 return i == st->index;
1164 } else if (*spec == 'p' && *(spec + 1) == ':') {
1168 prog_id = strtol(spec, &endptr, 0);
1169 for (i = 0; i < s->nb_programs; i++) {
1170 if (s->programs[i]->id != prog_id)
1173 if (*endptr++ == ':') {
1174 int stream_idx = strtol(endptr, NULL, 0);
1175 return stream_idx >= 0 &&
1176 stream_idx < s->programs[i]->nb_stream_indexes &&
1177 st->index == s->programs[i]->stream_index[stream_idx];
1180 for (j = 0; j < s->programs[i]->nb_stream_indexes; j++)
1181 if (st->index == s->programs[i]->stream_index[j])
1185 } else if (!*spec) /* empty specifier, matches everything */
1188 av_log(s, AV_LOG_ERROR, "Invalid stream specifier: %s.\n", spec);
1189 return AVERROR(EINVAL);
1192 AVDictionary *filter_codec_opts(AVDictionary *opts, enum AVCodecID codec_id,
1193 AVFormatContext *s, AVStream *st, AVCodec *codec)
1195 AVDictionary *ret = NULL;
1196 AVDictionaryEntry *t = NULL;
1197 int flags = s->oformat ? AV_OPT_FLAG_ENCODING_PARAM
1198 : AV_OPT_FLAG_DECODING_PARAM;
1200 const AVClass *cc = avcodec_get_class();
1203 codec = s->oformat ? avcodec_find_encoder(codec_id)
1204 : avcodec_find_decoder(codec_id);
1208 switch (codec->type) {
1209 case AVMEDIA_TYPE_VIDEO:
1211 flags |= AV_OPT_FLAG_VIDEO_PARAM;
1213 case AVMEDIA_TYPE_AUDIO:
1215 flags |= AV_OPT_FLAG_AUDIO_PARAM;
1217 case AVMEDIA_TYPE_SUBTITLE:
1219 flags |= AV_OPT_FLAG_SUBTITLE_PARAM;
1223 while (t = av_dict_get(opts, "", t, AV_DICT_IGNORE_SUFFIX)) {
1224 char *p = strchr(t->key, ':');
1226 /* check stream specification in opt name */
1228 switch (check_stream_specifier(s, st, p + 1)) {
1229 case 1: *p = 0; break;
1231 default: return NULL;
1234 if (av_opt_find(&cc, t->key, NULL, flags, AV_OPT_SEARCH_FAKE_OBJ) ||
1235 (codec && codec->priv_class &&
1236 av_opt_find(&codec->priv_class, t->key, NULL, flags,
1237 AV_OPT_SEARCH_FAKE_OBJ)))
1238 av_dict_set(&ret, t->key, t->value, 0);
1239 else if (t->key[0] == prefix &&
1240 av_opt_find(&cc, t->key + 1, NULL, flags,
1241 AV_OPT_SEARCH_FAKE_OBJ))
1242 av_dict_set(&ret, t->key + 1, t->value, 0);
1250 AVDictionary **setup_find_stream_info_opts(AVFormatContext *s,
1251 AVDictionary *codec_opts)
1254 AVDictionary **opts;
1258 opts = av_mallocz(s->nb_streams * sizeof(*opts));
1260 av_log(NULL, AV_LOG_ERROR,
1261 "Could not alloc memory for stream options.\n");
1264 for (i = 0; i < s->nb_streams; i++)
1265 opts[i] = filter_codec_opts(codec_opts, s->streams[i]->codec->codec_id,
1266 s, s->streams[i], NULL);
1270 void *grow_array(void *array, int elem_size, int *size, int new_size)
1272 if (new_size >= INT_MAX / elem_size) {
1273 av_log(NULL, AV_LOG_ERROR, "Array too big.\n");
1276 if (*size < new_size) {
1277 uint8_t *tmp = av_realloc(array, new_size*elem_size);
1279 av_log(NULL, AV_LOG_ERROR, "Could not alloc buffer.\n");
1282 memset(tmp + *size*elem_size, 0, (new_size-*size) * elem_size);
1289 static int alloc_buffer(FrameBuffer **pool, AVCodecContext *s, FrameBuffer **pbuf)
1291 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(s->pix_fmt);
1295 int h_chroma_shift, v_chroma_shift;
1296 int edge = 32; // XXX should be avcodec_get_edge_width(), but that fails on svq1
1297 int w = s->width, h = s->height;
1300 return AVERROR(EINVAL);
1301 pixel_size = desc->comp[0].step_minus1 + 1;
1303 buf = av_mallocz(sizeof(*buf));
1305 return AVERROR(ENOMEM);
1307 if (!(s->flags & CODEC_FLAG_EMU_EDGE)) {
1312 avcodec_align_dimensions(s, &w, &h);
1313 if ((ret = av_image_alloc(buf->base, buf->linesize, w, h,
1314 s->pix_fmt, 32)) < 0) {
1318 /* XXX this shouldn't be needed, but some tests break without this line
1319 * those decoders are buggy and need to be fixed.
1320 * the following tests fail:
1321 * cdgraphics, ansi, aasc, fraps-v1, qtrle-1bit
1323 memset(buf->base[0], 128, ret);
1325 avcodec_get_chroma_sub_sample(s->pix_fmt, &h_chroma_shift, &v_chroma_shift);
1326 for (i = 0; i < FF_ARRAY_ELEMS(buf->data); i++) {
1327 const int h_shift = i==0 ? 0 : h_chroma_shift;
1328 const int v_shift = i==0 ? 0 : v_chroma_shift;
1329 if (s->flags & CODEC_FLAG_EMU_EDGE)
1330 buf->data[i] = buf->base[i];
1331 else if (buf->base[i])
1332 buf->data[i] = buf->base[i] +
1333 FFALIGN((buf->linesize[i]*edge >> v_shift) +
1334 (pixel_size*edge >> h_shift), 32);
1338 buf->pix_fmt = s->pix_fmt;
1345 int codec_get_buffer(AVCodecContext *s, AVFrame *frame)
1347 FrameBuffer **pool = s->opaque;
1351 if (!*pool && (ret = alloc_buffer(pool, s, pool)) < 0)
1357 if (buf->w != s->width || buf->h != s->height || buf->pix_fmt != s->pix_fmt) {
1358 av_freep(&buf->base[0]);
1360 if ((ret = alloc_buffer(pool, s, &buf)) < 0)
1365 frame->opaque = buf;
1366 frame->type = FF_BUFFER_TYPE_USER;
1367 frame->extended_data = frame->data;
1368 frame->pkt_pts = s->pkt ? s->pkt->pts : AV_NOPTS_VALUE;
1369 frame->width = buf->w;
1370 frame->height = buf->h;
1371 frame->format = buf->pix_fmt;
1372 frame->sample_aspect_ratio = s->sample_aspect_ratio;
1374 for (i = 0; i < FF_ARRAY_ELEMS(buf->data); i++) {
1375 frame->base[i] = buf->base[i]; // XXX h264.c uses base though it shouldn't
1376 frame->data[i] = buf->data[i];
1377 frame->linesize[i] = buf->linesize[i];
1383 static void unref_buffer(FrameBuffer *buf)
1385 FrameBuffer **pool = buf->pool;
1387 av_assert0(buf->refcount);
1389 if (!buf->refcount) {
1395 void codec_release_buffer(AVCodecContext *s, AVFrame *frame)
1397 FrameBuffer *buf = frame->opaque;
1400 for (i = 0; i < FF_ARRAY_ELEMS(frame->data); i++)
1401 frame->data[i] = NULL;
1406 void filter_release_buffer(AVFilterBuffer *fb)
1408 FrameBuffer *buf = fb->priv;
1413 void free_buffer_pool(FrameBuffer **pool)
1415 FrameBuffer *buf = *pool;
1418 av_freep(&buf->base[0]);