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.

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