You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1229 lines
39KB

  1. /*
  2. * Various utilities for command line tools
  3. * Copyright (c) 2000-2003 Fabrice Bellard
  4. *
  5. * This file is part of Libav.
  6. *
  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.
  11. *
  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.
  16. *
  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
  20. */
  21. #include <string.h>
  22. #include <stdlib.h>
  23. #include <errno.h>
  24. #include <math.h>
  25. /* Include only the enabled headers since some compilers (namely, Sun
  26. Studio) will not omit unused inline functions and create undefined
  27. references to libraries that are not being built. */
  28. #include "config.h"
  29. #include "libavformat/avformat.h"
  30. #include "libavfilter/avfilter.h"
  31. #include "libavdevice/avdevice.h"
  32. #include "libavresample/avresample.h"
  33. #include "libswscale/swscale.h"
  34. #include "libavutil/avassert.h"
  35. #include "libavutil/avstring.h"
  36. #include "libavutil/mathematics.h"
  37. #include "libavutil/imgutils.h"
  38. #include "libavutil/parseutils.h"
  39. #include "libavutil/pixdesc.h"
  40. #include "libavutil/eval.h"
  41. #include "libavutil/dict.h"
  42. #include "libavutil/opt.h"
  43. #include "cmdutils.h"
  44. #include "version.h"
  45. #if CONFIG_NETWORK
  46. #include "libavformat/network.h"
  47. #endif
  48. #if HAVE_SYS_RESOURCE_H
  49. #include <sys/resource.h>
  50. #endif
  51. struct SwsContext *sws_opts;
  52. AVDictionary *format_opts, *codec_opts;
  53. static const int this_year = 2012;
  54. void init_opts(void)
  55. {
  56. #if CONFIG_SWSCALE
  57. sws_opts = sws_getContext(16, 16, 0, 16, 16, 0, SWS_BICUBIC,
  58. NULL, NULL, NULL);
  59. #endif
  60. }
  61. void uninit_opts(void)
  62. {
  63. #if CONFIG_SWSCALE
  64. sws_freeContext(sws_opts);
  65. sws_opts = NULL;
  66. #endif
  67. av_dict_free(&format_opts);
  68. av_dict_free(&codec_opts);
  69. }
  70. void log_callback_help(void *ptr, int level, const char *fmt, va_list vl)
  71. {
  72. vfprintf(stdout, fmt, vl);
  73. }
  74. double parse_number_or_die(const char *context, const char *numstr, int type,
  75. double min, double max)
  76. {
  77. char *tail;
  78. const char *error;
  79. double d = av_strtod(numstr, &tail);
  80. if (*tail)
  81. error = "Expected number for %s but found: %s\n";
  82. else if (d < min || d > max)
  83. error = "The value for %s was %s which is not within %f - %f\n";
  84. else if (type == OPT_INT64 && (int64_t)d != d)
  85. error = "Expected int64 for %s but found %s\n";
  86. else if (type == OPT_INT && (int)d != d)
  87. error = "Expected int for %s but found %s\n";
  88. else
  89. return d;
  90. av_log(NULL, AV_LOG_FATAL, error, context, numstr, min, max);
  91. exit_program(1);
  92. return 0;
  93. }
  94. int64_t parse_time_or_die(const char *context, const char *timestr,
  95. int is_duration)
  96. {
  97. int64_t us;
  98. if (av_parse_time(&us, timestr, is_duration) < 0) {
  99. av_log(NULL, AV_LOG_FATAL, "Invalid %s specification for %s: %s\n",
  100. is_duration ? "duration" : "date", context, timestr);
  101. exit_program(1);
  102. }
  103. return us;
  104. }
  105. void show_help_options(const OptionDef *options, const char *msg, int mask,
  106. int value)
  107. {
  108. const OptionDef *po;
  109. int first;
  110. first = 1;
  111. for (po = options; po->name != NULL; po++) {
  112. char buf[64];
  113. if ((po->flags & mask) == value) {
  114. if (first) {
  115. printf("%s", msg);
  116. first = 0;
  117. }
  118. av_strlcpy(buf, po->name, sizeof(buf));
  119. if (po->flags & HAS_ARG) {
  120. av_strlcat(buf, " ", sizeof(buf));
  121. av_strlcat(buf, po->argname, sizeof(buf));
  122. }
  123. printf("-%-17s %s\n", buf, po->help);
  124. }
  125. }
  126. }
  127. void show_help_children(const AVClass *class, int flags)
  128. {
  129. const AVClass *child = NULL;
  130. av_opt_show2(&class, NULL, flags, 0);
  131. printf("\n");
  132. while (child = av_opt_child_class_next(class, child))
  133. show_help_children(child, flags);
  134. }
  135. static const OptionDef *find_option(const OptionDef *po, const char *name)
  136. {
  137. const char *p = strchr(name, ':');
  138. int len = p ? p - name : strlen(name);
  139. while (po->name != NULL) {
  140. if (!strncmp(name, po->name, len) && strlen(po->name) == len)
  141. break;
  142. po++;
  143. }
  144. return po;
  145. }
  146. #if defined(_WIN32) && !defined(__MINGW32CE__)
  147. #include <windows.h>
  148. #include <shellapi.h>
  149. /* Will be leaked on exit */
  150. static char** win32_argv_utf8 = NULL;
  151. static int win32_argc = 0;
  152. /**
  153. * Prepare command line arguments for executable.
  154. * For Windows - perform wide-char to UTF-8 conversion.
  155. * Input arguments should be main() function arguments.
  156. * @param argc_ptr Arguments number (including executable)
  157. * @param argv_ptr Arguments list.
  158. */
  159. static void prepare_app_arguments(int *argc_ptr, char ***argv_ptr)
  160. {
  161. char *argstr_flat;
  162. wchar_t **argv_w;
  163. int i, buffsize = 0, offset = 0;
  164. if (win32_argv_utf8) {
  165. *argc_ptr = win32_argc;
  166. *argv_ptr = win32_argv_utf8;
  167. return;
  168. }
  169. win32_argc = 0;
  170. argv_w = CommandLineToArgvW(GetCommandLineW(), &win32_argc);
  171. if (win32_argc <= 0 || !argv_w)
  172. return;
  173. /* determine the UTF-8 buffer size (including NULL-termination symbols) */
  174. for (i = 0; i < win32_argc; i++)
  175. buffsize += WideCharToMultiByte(CP_UTF8, 0, argv_w[i], -1,
  176. NULL, 0, NULL, NULL);
  177. win32_argv_utf8 = av_mallocz(sizeof(char *) * (win32_argc + 1) + buffsize);
  178. argstr_flat = (char *)win32_argv_utf8 + sizeof(char *) * (win32_argc + 1);
  179. if (win32_argv_utf8 == NULL) {
  180. LocalFree(argv_w);
  181. return;
  182. }
  183. for (i = 0; i < win32_argc; i++) {
  184. win32_argv_utf8[i] = &argstr_flat[offset];
  185. offset += WideCharToMultiByte(CP_UTF8, 0, argv_w[i], -1,
  186. &argstr_flat[offset],
  187. buffsize - offset, NULL, NULL);
  188. }
  189. win32_argv_utf8[i] = NULL;
  190. LocalFree(argv_w);
  191. *argc_ptr = win32_argc;
  192. *argv_ptr = win32_argv_utf8;
  193. }
  194. #else
  195. static inline void prepare_app_arguments(int *argc_ptr, char ***argv_ptr)
  196. {
  197. /* nothing to do */
  198. }
  199. #endif /* WIN32 && !__MINGW32CE__ */
  200. int parse_option(void *optctx, const char *opt, const char *arg,
  201. const OptionDef *options)
  202. {
  203. const OptionDef *po;
  204. int bool_val = 1;
  205. int *dstcount;
  206. void *dst;
  207. po = find_option(options, opt);
  208. if (!po->name && opt[0] == 'n' && opt[1] == 'o') {
  209. /* handle 'no' bool option */
  210. po = find_option(options, opt + 2);
  211. if ((po->name && (po->flags & OPT_BOOL)))
  212. bool_val = 0;
  213. }
  214. if (!po->name)
  215. po = find_option(options, "default");
  216. if (!po->name) {
  217. av_log(NULL, AV_LOG_ERROR, "Unrecognized option '%s'\n", opt);
  218. return AVERROR(EINVAL);
  219. }
  220. if (po->flags & HAS_ARG && !arg) {
  221. av_log(NULL, AV_LOG_ERROR, "Missing argument for option '%s'\n", opt);
  222. return AVERROR(EINVAL);
  223. }
  224. /* new-style options contain an offset into optctx, old-style address of
  225. * a global var*/
  226. dst = po->flags & (OPT_OFFSET | OPT_SPEC) ? (uint8_t *)optctx + po->u.off
  227. : po->u.dst_ptr;
  228. if (po->flags & OPT_SPEC) {
  229. SpecifierOpt **so = dst;
  230. char *p = strchr(opt, ':');
  231. dstcount = (int *)(so + 1);
  232. *so = grow_array(*so, sizeof(**so), dstcount, *dstcount + 1);
  233. (*so)[*dstcount - 1].specifier = av_strdup(p ? p + 1 : "");
  234. dst = &(*so)[*dstcount - 1].u;
  235. }
  236. if (po->flags & OPT_STRING) {
  237. char *str;
  238. str = av_strdup(arg);
  239. *(char **)dst = str;
  240. } else if (po->flags & OPT_BOOL) {
  241. *(int *)dst = bool_val;
  242. } else if (po->flags & OPT_INT) {
  243. *(int *)dst = parse_number_or_die(opt, arg, OPT_INT64, INT_MIN, INT_MAX);
  244. } else if (po->flags & OPT_INT64) {
  245. *(int64_t *)dst = parse_number_or_die(opt, arg, OPT_INT64, INT64_MIN, INT64_MAX);
  246. } else if (po->flags & OPT_TIME) {
  247. *(int64_t *)dst = parse_time_or_die(opt, arg, 1);
  248. } else if (po->flags & OPT_FLOAT) {
  249. *(float *)dst = parse_number_or_die(opt, arg, OPT_FLOAT, -INFINITY, INFINITY);
  250. } else if (po->flags & OPT_DOUBLE) {
  251. *(double *)dst = parse_number_or_die(opt, arg, OPT_DOUBLE, -INFINITY, INFINITY);
  252. } else if (po->u.func_arg) {
  253. int ret = po->flags & OPT_FUNC2 ? po->u.func2_arg(optctx, opt, arg)
  254. : po->u.func_arg(opt, arg);
  255. if (ret < 0) {
  256. av_log(NULL, AV_LOG_ERROR,
  257. "Failed to set value '%s' for option '%s'\n", arg, opt);
  258. return ret;
  259. }
  260. }
  261. if (po->flags & OPT_EXIT)
  262. exit_program(0);
  263. return !!(po->flags & HAS_ARG);
  264. }
  265. void parse_options(void *optctx, int argc, char **argv, const OptionDef *options,
  266. void (*parse_arg_function)(void *, const char*))
  267. {
  268. const char *opt;
  269. int optindex, handleoptions = 1, ret;
  270. /* perform system-dependent conversions for arguments list */
  271. prepare_app_arguments(&argc, &argv);
  272. /* parse options */
  273. optindex = 1;
  274. while (optindex < argc) {
  275. opt = argv[optindex++];
  276. if (handleoptions && opt[0] == '-' && opt[1] != '\0') {
  277. if (opt[1] == '-' && opt[2] == '\0') {
  278. handleoptions = 0;
  279. continue;
  280. }
  281. opt++;
  282. if ((ret = parse_option(optctx, opt, argv[optindex], options)) < 0)
  283. exit_program(1);
  284. optindex += ret;
  285. } else {
  286. if (parse_arg_function)
  287. parse_arg_function(optctx, opt);
  288. }
  289. }
  290. }
  291. int locate_option(int argc, char **argv, const OptionDef *options,
  292. const char *optname)
  293. {
  294. const OptionDef *po;
  295. int i;
  296. for (i = 1; i < argc; i++) {
  297. const char *cur_opt = argv[i];
  298. if (*cur_opt++ != '-')
  299. continue;
  300. po = find_option(options, cur_opt);
  301. if (!po->name && cur_opt[0] == 'n' && cur_opt[1] == 'o')
  302. po = find_option(options, cur_opt + 2);
  303. if ((!po->name && !strcmp(cur_opt, optname)) ||
  304. (po->name && !strcmp(optname, po->name)))
  305. return i;
  306. if (!po || po->flags & HAS_ARG)
  307. i++;
  308. }
  309. return 0;
  310. }
  311. void parse_loglevel(int argc, char **argv, const OptionDef *options)
  312. {
  313. int idx = locate_option(argc, argv, options, "loglevel");
  314. if (!idx)
  315. idx = locate_option(argc, argv, options, "v");
  316. if (idx && argv[idx + 1])
  317. opt_loglevel("loglevel", argv[idx + 1]);
  318. }
  319. #define FLAGS (o->type == AV_OPT_TYPE_FLAGS) ? AV_DICT_APPEND : 0
  320. int opt_default(const char *opt, const char *arg)
  321. {
  322. const AVOption *o;
  323. char opt_stripped[128];
  324. const char *p;
  325. const AVClass *cc = avcodec_get_class(), *fc = avformat_get_class(), *sc = sws_get_class();
  326. if (!(p = strchr(opt, ':')))
  327. p = opt + strlen(opt);
  328. av_strlcpy(opt_stripped, opt, FFMIN(sizeof(opt_stripped), p - opt + 1));
  329. if ((o = av_opt_find(&cc, opt_stripped, NULL, 0,
  330. AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ)) ||
  331. ((opt[0] == 'v' || opt[0] == 'a' || opt[0] == 's') &&
  332. (o = av_opt_find(&cc, opt + 1, NULL, 0, AV_OPT_SEARCH_FAKE_OBJ))))
  333. av_dict_set(&codec_opts, opt, arg, FLAGS);
  334. else if ((o = av_opt_find(&fc, opt, NULL, 0,
  335. AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ)))
  336. av_dict_set(&format_opts, opt, arg, FLAGS);
  337. else if ((o = av_opt_find(&sc, opt, NULL, 0,
  338. AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ))) {
  339. // XXX we only support sws_flags, not arbitrary sws options
  340. int ret = av_opt_set(sws_opts, opt, arg, 0);
  341. if (ret < 0) {
  342. av_log(NULL, AV_LOG_ERROR, "Error setting option %s.\n", opt);
  343. return ret;
  344. }
  345. }
  346. if (o)
  347. return 0;
  348. av_log(NULL, AV_LOG_ERROR, "Unrecognized option '%s'\n", opt);
  349. return AVERROR_OPTION_NOT_FOUND;
  350. }
  351. int opt_loglevel(const char *opt, const char *arg)
  352. {
  353. const struct { const char *name; int level; } log_levels[] = {
  354. { "quiet" , AV_LOG_QUIET },
  355. { "panic" , AV_LOG_PANIC },
  356. { "fatal" , AV_LOG_FATAL },
  357. { "error" , AV_LOG_ERROR },
  358. { "warning", AV_LOG_WARNING },
  359. { "info" , AV_LOG_INFO },
  360. { "verbose", AV_LOG_VERBOSE },
  361. { "debug" , AV_LOG_DEBUG },
  362. };
  363. char *tail;
  364. int level;
  365. int i;
  366. for (i = 0; i < FF_ARRAY_ELEMS(log_levels); i++) {
  367. if (!strcmp(log_levels[i].name, arg)) {
  368. av_log_set_level(log_levels[i].level);
  369. return 0;
  370. }
  371. }
  372. level = strtol(arg, &tail, 10);
  373. if (*tail) {
  374. av_log(NULL, AV_LOG_FATAL, "Invalid loglevel \"%s\". "
  375. "Possible levels are numbers or:\n", arg);
  376. for (i = 0; i < FF_ARRAY_ELEMS(log_levels); i++)
  377. av_log(NULL, AV_LOG_FATAL, "\"%s\"\n", log_levels[i].name);
  378. exit_program(1);
  379. }
  380. av_log_set_level(level);
  381. return 0;
  382. }
  383. int opt_timelimit(const char *opt, const char *arg)
  384. {
  385. #if HAVE_SETRLIMIT
  386. int lim = parse_number_or_die(opt, arg, OPT_INT64, 0, INT_MAX);
  387. struct rlimit rl = { lim, lim + 1 };
  388. if (setrlimit(RLIMIT_CPU, &rl))
  389. perror("setrlimit");
  390. #else
  391. av_log(NULL, AV_LOG_WARNING, "-%s not implemented on this OS\n", opt);
  392. #endif
  393. return 0;
  394. }
  395. void print_error(const char *filename, int err)
  396. {
  397. char errbuf[128];
  398. const char *errbuf_ptr = errbuf;
  399. if (av_strerror(err, errbuf, sizeof(errbuf)) < 0)
  400. errbuf_ptr = strerror(AVUNERROR(err));
  401. av_log(NULL, AV_LOG_ERROR, "%s: %s\n", filename, errbuf_ptr);
  402. }
  403. static int warned_cfg = 0;
  404. #define INDENT 1
  405. #define SHOW_VERSION 2
  406. #define SHOW_CONFIG 4
  407. #define PRINT_LIB_INFO(libname, LIBNAME, flags, level) \
  408. if (CONFIG_##LIBNAME) { \
  409. const char *indent = flags & INDENT? " " : ""; \
  410. if (flags & SHOW_VERSION) { \
  411. unsigned int version = libname##_version(); \
  412. av_log(NULL, level, \
  413. "%slib%-10s %2d.%3d.%2d / %2d.%3d.%2d\n", \
  414. indent, #libname, \
  415. LIB##LIBNAME##_VERSION_MAJOR, \
  416. LIB##LIBNAME##_VERSION_MINOR, \
  417. LIB##LIBNAME##_VERSION_MICRO, \
  418. version >> 16, version >> 8 & 0xff, version & 0xff); \
  419. } \
  420. if (flags & SHOW_CONFIG) { \
  421. const char *cfg = libname##_configuration(); \
  422. if (strcmp(LIBAV_CONFIGURATION, cfg)) { \
  423. if (!warned_cfg) { \
  424. av_log(NULL, level, \
  425. "%sWARNING: library configuration mismatch\n", \
  426. indent); \
  427. warned_cfg = 1; \
  428. } \
  429. av_log(NULL, level, "%s%-11s configuration: %s\n", \
  430. indent, #libname, cfg); \
  431. } \
  432. } \
  433. } \
  434. static void print_all_libs_info(int flags, int level)
  435. {
  436. PRINT_LIB_INFO(avutil, AVUTIL, flags, level);
  437. PRINT_LIB_INFO(avcodec, AVCODEC, flags, level);
  438. PRINT_LIB_INFO(avformat, AVFORMAT, flags, level);
  439. PRINT_LIB_INFO(avdevice, AVDEVICE, flags, level);
  440. PRINT_LIB_INFO(avfilter, AVFILTER, flags, level);
  441. PRINT_LIB_INFO(avresample, AVRESAMPLE, flags, level);
  442. PRINT_LIB_INFO(swscale, SWSCALE, flags, level);
  443. }
  444. void show_banner(void)
  445. {
  446. av_log(NULL, AV_LOG_INFO,
  447. "%s version " LIBAV_VERSION ", Copyright (c) %d-%d the Libav developers\n",
  448. program_name, program_birth_year, this_year);
  449. av_log(NULL, AV_LOG_INFO, " built on %s %s with %s\n",
  450. __DATE__, __TIME__, CC_IDENT);
  451. av_log(NULL, AV_LOG_VERBOSE, " configuration: " LIBAV_CONFIGURATION "\n");
  452. print_all_libs_info(INDENT|SHOW_CONFIG, AV_LOG_VERBOSE);
  453. print_all_libs_info(INDENT|SHOW_VERSION, AV_LOG_VERBOSE);
  454. }
  455. int show_version(const char *opt, const char *arg)
  456. {
  457. av_log_set_callback(log_callback_help);
  458. printf("%s " LIBAV_VERSION "\n", program_name);
  459. print_all_libs_info(SHOW_VERSION, AV_LOG_INFO);
  460. return 0;
  461. }
  462. int show_license(const char *opt, const char *arg)
  463. {
  464. printf(
  465. #if CONFIG_NONFREE
  466. "This version of %s has nonfree parts compiled in.\n"
  467. "Therefore it is not legally redistributable.\n",
  468. program_name
  469. #elif CONFIG_GPLV3
  470. "%s is free software; you can redistribute it and/or modify\n"
  471. "it under the terms of the GNU General Public License as published by\n"
  472. "the Free Software Foundation; either version 3 of the License, or\n"
  473. "(at your option) any later version.\n"
  474. "\n"
  475. "%s is distributed in the hope that it will be useful,\n"
  476. "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
  477. "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n"
  478. "GNU General Public License for more details.\n"
  479. "\n"
  480. "You should have received a copy of the GNU General Public License\n"
  481. "along with %s. If not, see <http://www.gnu.org/licenses/>.\n",
  482. program_name, program_name, program_name
  483. #elif CONFIG_GPL
  484. "%s is free software; you can redistribute it and/or modify\n"
  485. "it under the terms of the GNU General Public License as published by\n"
  486. "the Free Software Foundation; either version 2 of the License, or\n"
  487. "(at your option) any later version.\n"
  488. "\n"
  489. "%s is distributed in the hope that it will be useful,\n"
  490. "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
  491. "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n"
  492. "GNU General Public License for more details.\n"
  493. "\n"
  494. "You should have received a copy of the GNU General Public License\n"
  495. "along with %s; if not, write to the Free Software\n"
  496. "Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n",
  497. program_name, program_name, program_name
  498. #elif CONFIG_LGPLV3
  499. "%s is free software; you can redistribute it and/or modify\n"
  500. "it under the terms of the GNU Lesser General Public License as published by\n"
  501. "the Free Software Foundation; either version 3 of the License, or\n"
  502. "(at your option) any later version.\n"
  503. "\n"
  504. "%s is distributed in the hope that it will be useful,\n"
  505. "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
  506. "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n"
  507. "GNU Lesser General Public License for more details.\n"
  508. "\n"
  509. "You should have received a copy of the GNU Lesser General Public License\n"
  510. "along with %s. If not, see <http://www.gnu.org/licenses/>.\n",
  511. program_name, program_name, program_name
  512. #else
  513. "%s is free software; you can redistribute it and/or\n"
  514. "modify it under the terms of the GNU Lesser General Public\n"
  515. "License as published by the Free Software Foundation; either\n"
  516. "version 2.1 of the License, or (at your option) any later version.\n"
  517. "\n"
  518. "%s is distributed in the hope that it will be useful,\n"
  519. "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
  520. "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n"
  521. "Lesser General Public License for more details.\n"
  522. "\n"
  523. "You should have received a copy of the GNU Lesser General Public\n"
  524. "License along with %s; if not, write to the Free Software\n"
  525. "Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n",
  526. program_name, program_name, program_name
  527. #endif
  528. );
  529. return 0;
  530. }
  531. int show_formats(const char *opt, const char *arg)
  532. {
  533. AVInputFormat *ifmt = NULL;
  534. AVOutputFormat *ofmt = NULL;
  535. const char *last_name;
  536. printf("File formats:\n"
  537. " D. = Demuxing supported\n"
  538. " .E = Muxing supported\n"
  539. " --\n");
  540. last_name = "000";
  541. for (;;) {
  542. int decode = 0;
  543. int encode = 0;
  544. const char *name = NULL;
  545. const char *long_name = NULL;
  546. while ((ofmt = av_oformat_next(ofmt))) {
  547. if ((name == NULL || strcmp(ofmt->name, name) < 0) &&
  548. strcmp(ofmt->name, last_name) > 0) {
  549. name = ofmt->name;
  550. long_name = ofmt->long_name;
  551. encode = 1;
  552. }
  553. }
  554. while ((ifmt = av_iformat_next(ifmt))) {
  555. if ((name == NULL || strcmp(ifmt->name, name) < 0) &&
  556. strcmp(ifmt->name, last_name) > 0) {
  557. name = ifmt->name;
  558. long_name = ifmt->long_name;
  559. encode = 0;
  560. }
  561. if (name && strcmp(ifmt->name, name) == 0)
  562. decode = 1;
  563. }
  564. if (name == NULL)
  565. break;
  566. last_name = name;
  567. printf(" %s%s %-15s %s\n",
  568. decode ? "D" : " ",
  569. encode ? "E" : " ",
  570. name,
  571. long_name ? long_name:" ");
  572. }
  573. return 0;
  574. }
  575. static char get_media_type_char(enum AVMediaType type)
  576. {
  577. switch (type) {
  578. case AVMEDIA_TYPE_VIDEO: return 'V';
  579. case AVMEDIA_TYPE_AUDIO: return 'A';
  580. case AVMEDIA_TYPE_SUBTITLE: return 'S';
  581. default: return '?';
  582. }
  583. }
  584. static const AVCodec *next_codec_for_id(enum AVCodecID id, const AVCodec *prev,
  585. int encoder)
  586. {
  587. while ((prev = av_codec_next(prev))) {
  588. if (prev->id == id &&
  589. (encoder ? av_codec_is_encoder(prev) : av_codec_is_decoder(prev)))
  590. return prev;
  591. }
  592. return NULL;
  593. }
  594. static void print_codecs_for_id(enum AVCodecID id, int encoder)
  595. {
  596. const AVCodec *codec = NULL;
  597. printf(" (%s: ", encoder ? "encoders" : "decoders");
  598. while ((codec = next_codec_for_id(id, codec, encoder)))
  599. printf("%s ", codec->name);
  600. printf(")");
  601. }
  602. int show_codecs(const char *opt, const char *arg)
  603. {
  604. const AVCodecDescriptor *desc = NULL;
  605. printf("Codecs:\n"
  606. " D... = Decoding supported\n"
  607. " .E.. = Encoding supported\n"
  608. " ..V. = Video codec\n"
  609. " ..A. = Audio codec\n"
  610. " ..S. = Subtitle codec\n"
  611. " ...I = Intra frame-only codec\n"
  612. " -----\n");
  613. while ((desc = avcodec_descriptor_next(desc))) {
  614. const AVCodec *codec = NULL;
  615. printf(avcodec_find_decoder(desc->id) ? "D" : ".");
  616. printf(avcodec_find_encoder(desc->id) ? "E" : ".");
  617. printf("%c", get_media_type_char(desc->type));
  618. printf((desc->props & AV_CODEC_PROP_INTRA_ONLY) ? "I" : ".");
  619. printf(" %-20s %s", desc->name, desc->long_name ? desc->long_name : "");
  620. /* print decoders/encoders when there's more than one or their
  621. * names are different from codec name */
  622. while ((codec = next_codec_for_id(desc->id, codec, 0))) {
  623. if (strcmp(codec->name, desc->name)) {
  624. print_codecs_for_id(desc->id, 0);
  625. break;
  626. }
  627. }
  628. codec = NULL;
  629. while ((codec = next_codec_for_id(desc->id, codec, 1))) {
  630. if (strcmp(codec->name, desc->name)) {
  631. print_codecs_for_id(desc->id, 1);
  632. break;
  633. }
  634. }
  635. printf("\n");
  636. }
  637. return 0;
  638. }
  639. static void print_codecs(int encoder)
  640. {
  641. const AVCodecDescriptor *desc = NULL;
  642. printf("%s:\n"
  643. " V... = Video\n"
  644. " A... = Audio\n"
  645. " S... = Subtitle\n"
  646. " .F.. = Frame-level multithreading\n"
  647. " ..S. = Slice-level multithreading\n"
  648. " ...X = Codec is experimental\n"
  649. " ---\n",
  650. encoder ? "Encoders" : "Decoders");
  651. while ((desc = avcodec_descriptor_next(desc))) {
  652. const AVCodec *codec = NULL;
  653. while ((codec = next_codec_for_id(desc->id, codec, encoder))) {
  654. printf("%c", get_media_type_char(desc->type));
  655. printf((codec->capabilities & CODEC_CAP_FRAME_THREADS) ? "F" : ".");
  656. printf((codec->capabilities & CODEC_CAP_SLICE_THREADS) ? "S" : ".");
  657. printf((codec->capabilities & CODEC_CAP_EXPERIMENTAL) ? "X" : ".");
  658. printf(" %-20s %s", codec->name, codec->long_name ? codec->long_name : "");
  659. if (strcmp(codec->name, desc->name))
  660. printf(" (codec %s)", desc->name);
  661. printf("\n");
  662. }
  663. }
  664. }
  665. int show_decoders(const char *opt, const char *arg)
  666. {
  667. print_codecs(0);
  668. return 0;
  669. }
  670. int show_encoders(const char *opt, const char *arg)
  671. {
  672. print_codecs(1);
  673. return 0;
  674. }
  675. int show_bsfs(const char *opt, const char *arg)
  676. {
  677. AVBitStreamFilter *bsf = NULL;
  678. printf("Bitstream filters:\n");
  679. while ((bsf = av_bitstream_filter_next(bsf)))
  680. printf("%s\n", bsf->name);
  681. printf("\n");
  682. return 0;
  683. }
  684. int show_protocols(const char *opt, const char *arg)
  685. {
  686. void *opaque = NULL;
  687. const char *name;
  688. printf("Supported file protocols:\n"
  689. "Input:\n");
  690. while ((name = avio_enum_protocols(&opaque, 0)))
  691. printf("%s\n", name);
  692. printf("Output:\n");
  693. while ((name = avio_enum_protocols(&opaque, 1)))
  694. printf("%s\n", name);
  695. return 0;
  696. }
  697. int show_filters(const char *opt, const char *arg)
  698. {
  699. AVFilter av_unused(**filter) = NULL;
  700. printf("Filters:\n");
  701. #if CONFIG_AVFILTER
  702. while ((filter = av_filter_next(filter)) && *filter)
  703. printf("%-16s %s\n", (*filter)->name, (*filter)->description);
  704. #endif
  705. return 0;
  706. }
  707. int show_pix_fmts(const char *opt, const char *arg)
  708. {
  709. enum PixelFormat pix_fmt;
  710. printf("Pixel formats:\n"
  711. "I.... = Supported Input format for conversion\n"
  712. ".O... = Supported Output format for conversion\n"
  713. "..H.. = Hardware accelerated format\n"
  714. "...P. = Paletted format\n"
  715. "....B = Bitstream format\n"
  716. "FLAGS NAME NB_COMPONENTS BITS_PER_PIXEL\n"
  717. "-----\n");
  718. #if !CONFIG_SWSCALE
  719. # define sws_isSupportedInput(x) 0
  720. # define sws_isSupportedOutput(x) 0
  721. #endif
  722. for (pix_fmt = 0; pix_fmt < PIX_FMT_NB; pix_fmt++) {
  723. const AVPixFmtDescriptor *pix_desc = &av_pix_fmt_descriptors[pix_fmt];
  724. printf("%c%c%c%c%c %-16s %d %2d\n",
  725. sws_isSupportedInput (pix_fmt) ? 'I' : '.',
  726. sws_isSupportedOutput(pix_fmt) ? 'O' : '.',
  727. pix_desc->flags & PIX_FMT_HWACCEL ? 'H' : '.',
  728. pix_desc->flags & PIX_FMT_PAL ? 'P' : '.',
  729. pix_desc->flags & PIX_FMT_BITSTREAM ? 'B' : '.',
  730. pix_desc->name,
  731. pix_desc->nb_components,
  732. av_get_bits_per_pixel(pix_desc));
  733. }
  734. return 0;
  735. }
  736. int show_sample_fmts(const char *opt, const char *arg)
  737. {
  738. int i;
  739. char fmt_str[128];
  740. for (i = -1; i < AV_SAMPLE_FMT_NB; i++)
  741. printf("%s\n", av_get_sample_fmt_string(fmt_str, sizeof(fmt_str), i));
  742. return 0;
  743. }
  744. int read_yesno(void)
  745. {
  746. int c = getchar();
  747. int yesno = (toupper(c) == 'Y');
  748. while (c != '\n' && c != EOF)
  749. c = getchar();
  750. return yesno;
  751. }
  752. int cmdutils_read_file(const char *filename, char **bufptr, size_t *size)
  753. {
  754. int ret;
  755. FILE *f = fopen(filename, "rb");
  756. if (!f) {
  757. av_log(NULL, AV_LOG_ERROR, "Cannot read file '%s': %s\n", filename,
  758. strerror(errno));
  759. return AVERROR(errno);
  760. }
  761. fseek(f, 0, SEEK_END);
  762. *size = ftell(f);
  763. fseek(f, 0, SEEK_SET);
  764. *bufptr = av_malloc(*size + 1);
  765. if (!*bufptr) {
  766. av_log(NULL, AV_LOG_ERROR, "Could not allocate file buffer\n");
  767. fclose(f);
  768. return AVERROR(ENOMEM);
  769. }
  770. ret = fread(*bufptr, 1, *size, f);
  771. if (ret < *size) {
  772. av_free(*bufptr);
  773. if (ferror(f)) {
  774. av_log(NULL, AV_LOG_ERROR, "Error while reading file '%s': %s\n",
  775. filename, strerror(errno));
  776. ret = AVERROR(errno);
  777. } else
  778. ret = AVERROR_EOF;
  779. } else {
  780. ret = 0;
  781. (*bufptr)[*size++] = '\0';
  782. }
  783. fclose(f);
  784. return ret;
  785. }
  786. void init_pts_correction(PtsCorrectionContext *ctx)
  787. {
  788. ctx->num_faulty_pts = ctx->num_faulty_dts = 0;
  789. ctx->last_pts = ctx->last_dts = INT64_MIN;
  790. }
  791. int64_t guess_correct_pts(PtsCorrectionContext *ctx, int64_t reordered_pts,
  792. int64_t dts)
  793. {
  794. int64_t pts = AV_NOPTS_VALUE;
  795. if (dts != AV_NOPTS_VALUE) {
  796. ctx->num_faulty_dts += dts <= ctx->last_dts;
  797. ctx->last_dts = dts;
  798. }
  799. if (reordered_pts != AV_NOPTS_VALUE) {
  800. ctx->num_faulty_pts += reordered_pts <= ctx->last_pts;
  801. ctx->last_pts = reordered_pts;
  802. }
  803. if ((ctx->num_faulty_pts<=ctx->num_faulty_dts || dts == AV_NOPTS_VALUE)
  804. && reordered_pts != AV_NOPTS_VALUE)
  805. pts = reordered_pts;
  806. else
  807. pts = dts;
  808. return pts;
  809. }
  810. FILE *get_preset_file(char *filename, size_t filename_size,
  811. const char *preset_name, int is_path,
  812. const char *codec_name)
  813. {
  814. FILE *f = NULL;
  815. int i;
  816. const char *base[3] = { getenv("AVCONV_DATADIR"),
  817. getenv("HOME"),
  818. AVCONV_DATADIR, };
  819. if (is_path) {
  820. av_strlcpy(filename, preset_name, filename_size);
  821. f = fopen(filename, "r");
  822. } else {
  823. for (i = 0; i < 3 && !f; i++) {
  824. if (!base[i])
  825. continue;
  826. snprintf(filename, filename_size, "%s%s/%s.avpreset", base[i],
  827. i != 1 ? "" : "/.avconv", preset_name);
  828. f = fopen(filename, "r");
  829. if (!f && codec_name) {
  830. snprintf(filename, filename_size,
  831. "%s%s/%s-%s.avpreset",
  832. base[i], i != 1 ? "" : "/.avconv", codec_name,
  833. preset_name);
  834. f = fopen(filename, "r");
  835. }
  836. }
  837. }
  838. return f;
  839. }
  840. int check_stream_specifier(AVFormatContext *s, AVStream *st, const char *spec)
  841. {
  842. if (*spec <= '9' && *spec >= '0') /* opt:index */
  843. return strtol(spec, NULL, 0) == st->index;
  844. else if (*spec == 'v' || *spec == 'a' || *spec == 's' || *spec == 'd' ||
  845. *spec == 't') { /* opt:[vasdt] */
  846. enum AVMediaType type;
  847. switch (*spec++) {
  848. case 'v': type = AVMEDIA_TYPE_VIDEO; break;
  849. case 'a': type = AVMEDIA_TYPE_AUDIO; break;
  850. case 's': type = AVMEDIA_TYPE_SUBTITLE; break;
  851. case 'd': type = AVMEDIA_TYPE_DATA; break;
  852. case 't': type = AVMEDIA_TYPE_ATTACHMENT; break;
  853. default: av_assert0(0);
  854. }
  855. if (type != st->codec->codec_type)
  856. return 0;
  857. if (*spec++ == ':') { /* possibly followed by :index */
  858. int i, index = strtol(spec, NULL, 0);
  859. for (i = 0; i < s->nb_streams; i++)
  860. if (s->streams[i]->codec->codec_type == type && index-- == 0)
  861. return i == st->index;
  862. return 0;
  863. }
  864. return 1;
  865. } else if (*spec == 'p' && *(spec + 1) == ':') {
  866. int prog_id, i, j;
  867. char *endptr;
  868. spec += 2;
  869. prog_id = strtol(spec, &endptr, 0);
  870. for (i = 0; i < s->nb_programs; i++) {
  871. if (s->programs[i]->id != prog_id)
  872. continue;
  873. if (*endptr++ == ':') {
  874. int stream_idx = strtol(endptr, NULL, 0);
  875. return stream_idx >= 0 &&
  876. stream_idx < s->programs[i]->nb_stream_indexes &&
  877. st->index == s->programs[i]->stream_index[stream_idx];
  878. }
  879. for (j = 0; j < s->programs[i]->nb_stream_indexes; j++)
  880. if (st->index == s->programs[i]->stream_index[j])
  881. return 1;
  882. }
  883. return 0;
  884. } else if (!*spec) /* empty specifier, matches everything */
  885. return 1;
  886. av_log(s, AV_LOG_ERROR, "Invalid stream specifier: %s.\n", spec);
  887. return AVERROR(EINVAL);
  888. }
  889. AVDictionary *filter_codec_opts(AVDictionary *opts, enum AVCodecID codec_id,
  890. AVFormatContext *s, AVStream *st, AVCodec *codec)
  891. {
  892. AVDictionary *ret = NULL;
  893. AVDictionaryEntry *t = NULL;
  894. int flags = s->oformat ? AV_OPT_FLAG_ENCODING_PARAM
  895. : AV_OPT_FLAG_DECODING_PARAM;
  896. char prefix = 0;
  897. const AVClass *cc = avcodec_get_class();
  898. if (!codec)
  899. codec = s->oformat ? avcodec_find_encoder(codec_id)
  900. : avcodec_find_decoder(codec_id);
  901. if (!codec)
  902. return NULL;
  903. switch (codec->type) {
  904. case AVMEDIA_TYPE_VIDEO:
  905. prefix = 'v';
  906. flags |= AV_OPT_FLAG_VIDEO_PARAM;
  907. break;
  908. case AVMEDIA_TYPE_AUDIO:
  909. prefix = 'a';
  910. flags |= AV_OPT_FLAG_AUDIO_PARAM;
  911. break;
  912. case AVMEDIA_TYPE_SUBTITLE:
  913. prefix = 's';
  914. flags |= AV_OPT_FLAG_SUBTITLE_PARAM;
  915. break;
  916. }
  917. while (t = av_dict_get(opts, "", t, AV_DICT_IGNORE_SUFFIX)) {
  918. char *p = strchr(t->key, ':');
  919. /* check stream specification in opt name */
  920. if (p)
  921. switch (check_stream_specifier(s, st, p + 1)) {
  922. case 1: *p = 0; break;
  923. case 0: continue;
  924. default: return NULL;
  925. }
  926. if (av_opt_find(&cc, t->key, NULL, flags, AV_OPT_SEARCH_FAKE_OBJ) ||
  927. (codec && codec->priv_class &&
  928. av_opt_find(&codec->priv_class, t->key, NULL, flags,
  929. AV_OPT_SEARCH_FAKE_OBJ)))
  930. av_dict_set(&ret, t->key, t->value, 0);
  931. else if (t->key[0] == prefix &&
  932. av_opt_find(&cc, t->key + 1, NULL, flags,
  933. AV_OPT_SEARCH_FAKE_OBJ))
  934. av_dict_set(&ret, t->key + 1, t->value, 0);
  935. if (p)
  936. *p = ':';
  937. }
  938. return ret;
  939. }
  940. AVDictionary **setup_find_stream_info_opts(AVFormatContext *s,
  941. AVDictionary *codec_opts)
  942. {
  943. int i;
  944. AVDictionary **opts;
  945. if (!s->nb_streams)
  946. return NULL;
  947. opts = av_mallocz(s->nb_streams * sizeof(*opts));
  948. if (!opts) {
  949. av_log(NULL, AV_LOG_ERROR,
  950. "Could not alloc memory for stream options.\n");
  951. return NULL;
  952. }
  953. for (i = 0; i < s->nb_streams; i++)
  954. opts[i] = filter_codec_opts(codec_opts, s->streams[i]->codec->codec_id,
  955. s, s->streams[i], NULL);
  956. return opts;
  957. }
  958. void *grow_array(void *array, int elem_size, int *size, int new_size)
  959. {
  960. if (new_size >= INT_MAX / elem_size) {
  961. av_log(NULL, AV_LOG_ERROR, "Array too big.\n");
  962. exit_program(1);
  963. }
  964. if (*size < new_size) {
  965. uint8_t *tmp = av_realloc(array, new_size*elem_size);
  966. if (!tmp) {
  967. av_log(NULL, AV_LOG_ERROR, "Could not alloc buffer.\n");
  968. exit_program(1);
  969. }
  970. memset(tmp + *size*elem_size, 0, (new_size-*size) * elem_size);
  971. *size = new_size;
  972. return tmp;
  973. }
  974. return array;
  975. }
  976. static int alloc_buffer(FrameBuffer **pool, AVCodecContext *s, FrameBuffer **pbuf)
  977. {
  978. FrameBuffer *buf = av_mallocz(sizeof(*buf));
  979. int i, ret;
  980. const int pixel_size = av_pix_fmt_descriptors[s->pix_fmt].comp[0].step_minus1+1;
  981. int h_chroma_shift, v_chroma_shift;
  982. int edge = 32; // XXX should be avcodec_get_edge_width(), but that fails on svq1
  983. int w = s->width, h = s->height;
  984. if (!buf)
  985. return AVERROR(ENOMEM);
  986. if (!(s->flags & CODEC_FLAG_EMU_EDGE)) {
  987. w += 2*edge;
  988. h += 2*edge;
  989. }
  990. avcodec_align_dimensions(s, &w, &h);
  991. if ((ret = av_image_alloc(buf->base, buf->linesize, w, h,
  992. s->pix_fmt, 32)) < 0) {
  993. av_freep(&buf);
  994. return ret;
  995. }
  996. /* XXX this shouldn't be needed, but some tests break without this line
  997. * those decoders are buggy and need to be fixed.
  998. * the following tests fail:
  999. * cdgraphics, ansi, aasc, fraps-v1, qtrle-1bit
  1000. */
  1001. memset(buf->base[0], 128, ret);
  1002. avcodec_get_chroma_sub_sample(s->pix_fmt, &h_chroma_shift, &v_chroma_shift);
  1003. for (i = 0; i < FF_ARRAY_ELEMS(buf->data); i++) {
  1004. const int h_shift = i==0 ? 0 : h_chroma_shift;
  1005. const int v_shift = i==0 ? 0 : v_chroma_shift;
  1006. if (s->flags & CODEC_FLAG_EMU_EDGE)
  1007. buf->data[i] = buf->base[i];
  1008. else
  1009. buf->data[i] = buf->base[i] +
  1010. FFALIGN((buf->linesize[i]*edge >> v_shift) +
  1011. (pixel_size*edge >> h_shift), 32);
  1012. }
  1013. buf->w = s->width;
  1014. buf->h = s->height;
  1015. buf->pix_fmt = s->pix_fmt;
  1016. buf->pool = pool;
  1017. *pbuf = buf;
  1018. return 0;
  1019. }
  1020. int codec_get_buffer(AVCodecContext *s, AVFrame *frame)
  1021. {
  1022. FrameBuffer **pool = s->opaque;
  1023. FrameBuffer *buf;
  1024. int ret, i;
  1025. if (!*pool && (ret = alloc_buffer(pool, s, pool)) < 0)
  1026. return ret;
  1027. buf = *pool;
  1028. *pool = buf->next;
  1029. buf->next = NULL;
  1030. if (buf->w != s->width || buf->h != s->height || buf->pix_fmt != s->pix_fmt) {
  1031. av_freep(&buf->base[0]);
  1032. av_free(buf);
  1033. if ((ret = alloc_buffer(pool, s, &buf)) < 0)
  1034. return ret;
  1035. }
  1036. buf->refcount++;
  1037. frame->opaque = buf;
  1038. frame->type = FF_BUFFER_TYPE_USER;
  1039. frame->extended_data = frame->data;
  1040. frame->pkt_pts = s->pkt ? s->pkt->pts : AV_NOPTS_VALUE;
  1041. frame->width = buf->w;
  1042. frame->height = buf->h;
  1043. frame->format = buf->pix_fmt;
  1044. frame->sample_aspect_ratio = s->sample_aspect_ratio;
  1045. for (i = 0; i < FF_ARRAY_ELEMS(buf->data); i++) {
  1046. frame->base[i] = buf->base[i]; // XXX h264.c uses base though it shouldn't
  1047. frame->data[i] = buf->data[i];
  1048. frame->linesize[i] = buf->linesize[i];
  1049. }
  1050. return 0;
  1051. }
  1052. static void unref_buffer(FrameBuffer *buf)
  1053. {
  1054. FrameBuffer **pool = buf->pool;
  1055. av_assert0(buf->refcount);
  1056. buf->refcount--;
  1057. if (!buf->refcount) {
  1058. buf->next = *pool;
  1059. *pool = buf;
  1060. }
  1061. }
  1062. void codec_release_buffer(AVCodecContext *s, AVFrame *frame)
  1063. {
  1064. FrameBuffer *buf = frame->opaque;
  1065. int i;
  1066. for (i = 0; i < FF_ARRAY_ELEMS(frame->data); i++)
  1067. frame->data[i] = NULL;
  1068. unref_buffer(buf);
  1069. }
  1070. void filter_release_buffer(AVFilterBuffer *fb)
  1071. {
  1072. FrameBuffer *buf = fb->priv;
  1073. av_free(fb);
  1074. unref_buffer(buf);
  1075. }
  1076. void free_buffer_pool(FrameBuffer **pool)
  1077. {
  1078. FrameBuffer *buf = *pool;
  1079. while (buf) {
  1080. *pool = buf->next;
  1081. av_freep(&buf->base[0]);
  1082. av_free(buf);
  1083. buf = *pool;
  1084. }
  1085. }