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.

1670 lines
53KB

  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/time.h>
  50. #include <sys/resource.h>
  51. #endif
  52. struct SwsContext *sws_opts;
  53. AVDictionary *format_opts, *codec_opts, *resample_opts;
  54. static const int this_year = 2013;
  55. void init_opts(void)
  56. {
  57. #if CONFIG_SWSCALE
  58. sws_opts = sws_getContext(16, 16, 0, 16, 16, 0, SWS_BICUBIC,
  59. NULL, NULL, NULL);
  60. #endif
  61. }
  62. void uninit_opts(void)
  63. {
  64. #if CONFIG_SWSCALE
  65. sws_freeContext(sws_opts);
  66. sws_opts = NULL;
  67. #endif
  68. av_dict_free(&format_opts);
  69. av_dict_free(&codec_opts);
  70. av_dict_free(&resample_opts);
  71. }
  72. void log_callback_help(void *ptr, int level, const char *fmt, va_list vl)
  73. {
  74. vfprintf(stdout, fmt, vl);
  75. }
  76. double parse_number_or_die(const char *context, const char *numstr, int type,
  77. double min, double max)
  78. {
  79. char *tail;
  80. const char *error;
  81. double d = av_strtod(numstr, &tail);
  82. if (*tail)
  83. error = "Expected number for %s but found: %s\n";
  84. else if (d < min || d > max)
  85. error = "The value for %s was %s which is not within %f - %f\n";
  86. else if (type == OPT_INT64 && (int64_t)d != d)
  87. error = "Expected int64 for %s but found %s\n";
  88. else if (type == OPT_INT && (int)d != d)
  89. error = "Expected int for %s but found %s\n";
  90. else
  91. return d;
  92. av_log(NULL, AV_LOG_FATAL, error, context, numstr, min, max);
  93. exit(1);
  94. return 0;
  95. }
  96. int64_t parse_time_or_die(const char *context, const char *timestr,
  97. int is_duration)
  98. {
  99. int64_t us;
  100. if (av_parse_time(&us, timestr, is_duration) < 0) {
  101. av_log(NULL, AV_LOG_FATAL, "Invalid %s specification for %s: %s\n",
  102. is_duration ? "duration" : "date", context, timestr);
  103. exit(1);
  104. }
  105. return us;
  106. }
  107. void show_help_options(const OptionDef *options, const char *msg, int req_flags,
  108. int rej_flags, int alt_flags)
  109. {
  110. const OptionDef *po;
  111. int first;
  112. first = 1;
  113. for (po = options; po->name != NULL; po++) {
  114. char buf[64];
  115. if (((po->flags & req_flags) != req_flags) ||
  116. (alt_flags && !(po->flags & alt_flags)) ||
  117. (po->flags & rej_flags))
  118. continue;
  119. if (first) {
  120. printf("%s\n", msg);
  121. first = 0;
  122. }
  123. av_strlcpy(buf, po->name, sizeof(buf));
  124. if (po->argname) {
  125. av_strlcat(buf, " ", sizeof(buf));
  126. av_strlcat(buf, po->argname, sizeof(buf));
  127. }
  128. printf("-%-17s %s\n", buf, po->help);
  129. }
  130. printf("\n");
  131. }
  132. void show_help_children(const AVClass *class, int flags)
  133. {
  134. const AVClass *child = NULL;
  135. av_opt_show2(&class, NULL, flags, 0);
  136. printf("\n");
  137. while (child = av_opt_child_class_next(class, child))
  138. show_help_children(child, flags);
  139. }
  140. static const OptionDef *find_option(const OptionDef *po, const char *name)
  141. {
  142. const char *p = strchr(name, ':');
  143. int len = p ? p - name : strlen(name);
  144. while (po->name != NULL) {
  145. if (!strncmp(name, po->name, len) && strlen(po->name) == len)
  146. break;
  147. po++;
  148. }
  149. return po;
  150. }
  151. #if HAVE_COMMANDLINETOARGVW
  152. #include <windows.h>
  153. #include <shellapi.h>
  154. /* Will be leaked on exit */
  155. static char** win32_argv_utf8 = NULL;
  156. static int win32_argc = 0;
  157. /**
  158. * Prepare command line arguments for executable.
  159. * For Windows - perform wide-char to UTF-8 conversion.
  160. * Input arguments should be main() function arguments.
  161. * @param argc_ptr Arguments number (including executable)
  162. * @param argv_ptr Arguments list.
  163. */
  164. static void prepare_app_arguments(int *argc_ptr, char ***argv_ptr)
  165. {
  166. char *argstr_flat;
  167. wchar_t **argv_w;
  168. int i, buffsize = 0, offset = 0;
  169. if (win32_argv_utf8) {
  170. *argc_ptr = win32_argc;
  171. *argv_ptr = win32_argv_utf8;
  172. return;
  173. }
  174. win32_argc = 0;
  175. argv_w = CommandLineToArgvW(GetCommandLineW(), &win32_argc);
  176. if (win32_argc <= 0 || !argv_w)
  177. return;
  178. /* determine the UTF-8 buffer size (including NULL-termination symbols) */
  179. for (i = 0; i < win32_argc; i++)
  180. buffsize += WideCharToMultiByte(CP_UTF8, 0, argv_w[i], -1,
  181. NULL, 0, NULL, NULL);
  182. win32_argv_utf8 = av_mallocz(sizeof(char *) * (win32_argc + 1) + buffsize);
  183. argstr_flat = (char *)win32_argv_utf8 + sizeof(char *) * (win32_argc + 1);
  184. if (win32_argv_utf8 == NULL) {
  185. LocalFree(argv_w);
  186. return;
  187. }
  188. for (i = 0; i < win32_argc; i++) {
  189. win32_argv_utf8[i] = &argstr_flat[offset];
  190. offset += WideCharToMultiByte(CP_UTF8, 0, argv_w[i], -1,
  191. &argstr_flat[offset],
  192. buffsize - offset, NULL, NULL);
  193. }
  194. win32_argv_utf8[i] = NULL;
  195. LocalFree(argv_w);
  196. *argc_ptr = win32_argc;
  197. *argv_ptr = win32_argv_utf8;
  198. }
  199. #else
  200. static inline void prepare_app_arguments(int *argc_ptr, char ***argv_ptr)
  201. {
  202. /* nothing to do */
  203. }
  204. #endif /* HAVE_COMMANDLINETOARGVW */
  205. static int write_option(void *optctx, const OptionDef *po, const char *opt,
  206. const char *arg)
  207. {
  208. /* new-style options contain an offset into optctx, old-style address of
  209. * a global var*/
  210. void *dst = po->flags & (OPT_OFFSET | OPT_SPEC) ?
  211. (uint8_t *)optctx + po->u.off : po->u.dst_ptr;
  212. int *dstcount;
  213. if (po->flags & OPT_SPEC) {
  214. SpecifierOpt **so = dst;
  215. char *p = strchr(opt, ':');
  216. dstcount = (int *)(so + 1);
  217. *so = grow_array(*so, sizeof(**so), dstcount, *dstcount + 1);
  218. (*so)[*dstcount - 1].specifier = av_strdup(p ? p + 1 : "");
  219. dst = &(*so)[*dstcount - 1].u;
  220. }
  221. if (po->flags & OPT_STRING) {
  222. char *str;
  223. str = av_strdup(arg);
  224. av_freep(dst);
  225. *(char **)dst = str;
  226. } else if (po->flags & OPT_BOOL || po->flags & OPT_INT) {
  227. *(int *)dst = parse_number_or_die(opt, arg, OPT_INT64, INT_MIN, INT_MAX);
  228. } else if (po->flags & OPT_INT64) {
  229. *(int64_t *)dst = parse_number_or_die(opt, arg, OPT_INT64, INT64_MIN, INT64_MAX);
  230. } else if (po->flags & OPT_TIME) {
  231. *(int64_t *)dst = parse_time_or_die(opt, arg, 1);
  232. } else if (po->flags & OPT_FLOAT) {
  233. *(float *)dst = parse_number_or_die(opt, arg, OPT_FLOAT, -INFINITY, INFINITY);
  234. } else if (po->flags & OPT_DOUBLE) {
  235. *(double *)dst = parse_number_or_die(opt, arg, OPT_DOUBLE, -INFINITY, INFINITY);
  236. } else if (po->u.func_arg) {
  237. int ret = po->u.func_arg(optctx, opt, arg);
  238. if (ret < 0) {
  239. av_log(NULL, AV_LOG_ERROR,
  240. "Failed to set value '%s' for option '%s'\n", arg, opt);
  241. return ret;
  242. }
  243. }
  244. if (po->flags & OPT_EXIT)
  245. exit(0);
  246. return 0;
  247. }
  248. int parse_option(void *optctx, const char *opt, const char *arg,
  249. const OptionDef *options)
  250. {
  251. const OptionDef *po;
  252. int ret;
  253. po = find_option(options, opt);
  254. if (!po->name && opt[0] == 'n' && opt[1] == 'o') {
  255. /* handle 'no' bool option */
  256. po = find_option(options, opt + 2);
  257. if ((po->name && (po->flags & OPT_BOOL)))
  258. arg = "0";
  259. } else if (po->flags & OPT_BOOL)
  260. arg = "1";
  261. if (!po->name)
  262. po = find_option(options, "default");
  263. if (!po->name) {
  264. av_log(NULL, AV_LOG_ERROR, "Unrecognized option '%s'\n", opt);
  265. return AVERROR(EINVAL);
  266. }
  267. if (po->flags & HAS_ARG && !arg) {
  268. av_log(NULL, AV_LOG_ERROR, "Missing argument for option '%s'\n", opt);
  269. return AVERROR(EINVAL);
  270. }
  271. ret = write_option(optctx, po, opt, arg);
  272. if (ret < 0)
  273. return ret;
  274. return !!(po->flags & HAS_ARG);
  275. }
  276. void parse_options(void *optctx, int argc, char **argv, const OptionDef *options,
  277. void (*parse_arg_function)(void *, const char*))
  278. {
  279. const char *opt;
  280. int optindex, handleoptions = 1, ret;
  281. /* perform system-dependent conversions for arguments list */
  282. prepare_app_arguments(&argc, &argv);
  283. /* parse options */
  284. optindex = 1;
  285. while (optindex < argc) {
  286. opt = argv[optindex++];
  287. if (handleoptions && opt[0] == '-' && opt[1] != '\0') {
  288. if (opt[1] == '-' && opt[2] == '\0') {
  289. handleoptions = 0;
  290. continue;
  291. }
  292. opt++;
  293. if ((ret = parse_option(optctx, opt, argv[optindex], options)) < 0)
  294. exit(1);
  295. optindex += ret;
  296. } else {
  297. if (parse_arg_function)
  298. parse_arg_function(optctx, opt);
  299. }
  300. }
  301. }
  302. int parse_optgroup(void *optctx, OptionGroup *g)
  303. {
  304. int i, ret;
  305. av_log(NULL, AV_LOG_DEBUG, "Parsing a group of options: %s %s.\n",
  306. g->group_def->name, g->arg);
  307. for (i = 0; i < g->nb_opts; i++) {
  308. Option *o = &g->opts[i];
  309. av_log(NULL, AV_LOG_DEBUG, "Applying option %s (%s) with argument %s.\n",
  310. o->key, o->opt->help, o->val);
  311. ret = write_option(optctx, o->opt, o->key, o->val);
  312. if (ret < 0)
  313. return ret;
  314. }
  315. av_log(NULL, AV_LOG_DEBUG, "Successfully parsed a group of options.\n");
  316. return 0;
  317. }
  318. int locate_option(int argc, char **argv, const OptionDef *options,
  319. const char *optname)
  320. {
  321. const OptionDef *po;
  322. int i;
  323. for (i = 1; i < argc; i++) {
  324. const char *cur_opt = argv[i];
  325. if (*cur_opt++ != '-')
  326. continue;
  327. po = find_option(options, cur_opt);
  328. if (!po->name && cur_opt[0] == 'n' && cur_opt[1] == 'o')
  329. po = find_option(options, cur_opt + 2);
  330. if ((!po->name && !strcmp(cur_opt, optname)) ||
  331. (po->name && !strcmp(optname, po->name)))
  332. return i;
  333. if (!po || po->flags & HAS_ARG)
  334. i++;
  335. }
  336. return 0;
  337. }
  338. void parse_loglevel(int argc, char **argv, const OptionDef *options)
  339. {
  340. int idx = locate_option(argc, argv, options, "loglevel");
  341. if (!idx)
  342. idx = locate_option(argc, argv, options, "v");
  343. if (idx && argv[idx + 1])
  344. opt_loglevel(NULL, "loglevel", argv[idx + 1]);
  345. }
  346. #define FLAGS (o->type == AV_OPT_TYPE_FLAGS) ? AV_DICT_APPEND : 0
  347. int opt_default(void *optctx, const char *opt, const char *arg)
  348. {
  349. const AVOption *o;
  350. char opt_stripped[128];
  351. const char *p;
  352. const AVClass *cc = avcodec_get_class(), *fc = avformat_get_class();
  353. const AVClass *rc = avresample_get_class();
  354. #if CONFIG_SWSCALE
  355. const AVClass *sc = sws_get_class();
  356. #endif
  357. if (!(p = strchr(opt, ':')))
  358. p = opt + strlen(opt);
  359. av_strlcpy(opt_stripped, opt, FFMIN(sizeof(opt_stripped), p - opt + 1));
  360. if ((o = av_opt_find(&cc, opt_stripped, NULL, 0,
  361. AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ)) ||
  362. ((opt[0] == 'v' || opt[0] == 'a' || opt[0] == 's') &&
  363. (o = av_opt_find(&cc, opt + 1, NULL, 0, AV_OPT_SEARCH_FAKE_OBJ))))
  364. av_dict_set(&codec_opts, opt, arg, FLAGS);
  365. else if ((o = av_opt_find(&fc, opt, NULL, 0,
  366. AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ)))
  367. av_dict_set(&format_opts, opt, arg, FLAGS);
  368. else if ((o = av_opt_find(&rc, opt, NULL, 0,
  369. AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ)))
  370. av_dict_set(&resample_opts, opt, arg, FLAGS);
  371. #if CONFIG_SWSCALE
  372. else if ((o = av_opt_find(&sc, opt, NULL, 0,
  373. AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ))) {
  374. // XXX we only support sws_flags, not arbitrary sws options
  375. int ret = av_opt_set(sws_opts, opt, arg, 0);
  376. if (ret < 0) {
  377. av_log(NULL, AV_LOG_ERROR, "Error setting option %s.\n", opt);
  378. return ret;
  379. }
  380. }
  381. #endif
  382. if (o)
  383. return 0;
  384. return AVERROR_OPTION_NOT_FOUND;
  385. }
  386. /*
  387. * Check whether given option is a group separator.
  388. *
  389. * @return index of the group definition that matched or -1 if none
  390. */
  391. static int match_group_separator(const OptionGroupDef *groups, int nb_groups,
  392. const char *opt)
  393. {
  394. int i;
  395. for (i = 0; i < nb_groups; i++) {
  396. const OptionGroupDef *p = &groups[i];
  397. if (p->sep && !strcmp(p->sep, opt))
  398. return i;
  399. }
  400. return -1;
  401. }
  402. /*
  403. * Finish parsing an option group.
  404. *
  405. * @param group_idx which group definition should this group belong to
  406. * @param arg argument of the group delimiting option
  407. */
  408. static void finish_group(OptionParseContext *octx, int group_idx,
  409. const char *arg)
  410. {
  411. OptionGroupList *l = &octx->groups[group_idx];
  412. OptionGroup *g;
  413. GROW_ARRAY(l->groups, l->nb_groups);
  414. g = &l->groups[l->nb_groups - 1];
  415. *g = octx->cur_group;
  416. g->arg = arg;
  417. g->group_def = l->group_def;
  418. #if CONFIG_SWSCALE
  419. g->sws_opts = sws_opts;
  420. #endif
  421. g->codec_opts = codec_opts;
  422. g->format_opts = format_opts;
  423. g->resample_opts = resample_opts;
  424. codec_opts = NULL;
  425. format_opts = NULL;
  426. resample_opts = NULL;
  427. #if CONFIG_SWSCALE
  428. sws_opts = NULL;
  429. #endif
  430. init_opts();
  431. memset(&octx->cur_group, 0, sizeof(octx->cur_group));
  432. }
  433. /*
  434. * Add an option instance to currently parsed group.
  435. */
  436. static void add_opt(OptionParseContext *octx, const OptionDef *opt,
  437. const char *key, const char *val)
  438. {
  439. int global = !(opt->flags & (OPT_PERFILE | OPT_SPEC | OPT_OFFSET));
  440. OptionGroup *g = global ? &octx->global_opts : &octx->cur_group;
  441. GROW_ARRAY(g->opts, g->nb_opts);
  442. g->opts[g->nb_opts - 1].opt = opt;
  443. g->opts[g->nb_opts - 1].key = key;
  444. g->opts[g->nb_opts - 1].val = val;
  445. }
  446. static void init_parse_context(OptionParseContext *octx,
  447. const OptionGroupDef *groups, int nb_groups)
  448. {
  449. static const OptionGroupDef global_group = { "global" };
  450. int i;
  451. memset(octx, 0, sizeof(*octx));
  452. octx->nb_groups = nb_groups;
  453. octx->groups = av_mallocz(sizeof(*octx->groups) * octx->nb_groups);
  454. if (!octx->groups)
  455. exit(1);
  456. for (i = 0; i < octx->nb_groups; i++)
  457. octx->groups[i].group_def = &groups[i];
  458. octx->global_opts.group_def = &global_group;
  459. octx->global_opts.arg = "";
  460. init_opts();
  461. }
  462. void uninit_parse_context(OptionParseContext *octx)
  463. {
  464. int i, j;
  465. for (i = 0; i < octx->nb_groups; i++) {
  466. OptionGroupList *l = &octx->groups[i];
  467. for (j = 0; j < l->nb_groups; j++) {
  468. av_freep(&l->groups[j].opts);
  469. av_dict_free(&l->groups[j].codec_opts);
  470. av_dict_free(&l->groups[j].format_opts);
  471. av_dict_free(&l->groups[j].resample_opts);
  472. #if CONFIG_SWSCALE
  473. sws_freeContext(l->groups[j].sws_opts);
  474. #endif
  475. }
  476. av_freep(&l->groups);
  477. }
  478. av_freep(&octx->groups);
  479. av_freep(&octx->cur_group.opts);
  480. av_freep(&octx->global_opts.opts);
  481. uninit_opts();
  482. }
  483. int split_commandline(OptionParseContext *octx, int argc, char *argv[],
  484. const OptionDef *options,
  485. const OptionGroupDef *groups, int nb_groups)
  486. {
  487. int optindex = 1;
  488. /* perform system-dependent conversions for arguments list */
  489. prepare_app_arguments(&argc, &argv);
  490. init_parse_context(octx, groups, nb_groups);
  491. av_log(NULL, AV_LOG_DEBUG, "Splitting the commandline.\n");
  492. while (optindex < argc) {
  493. const char *opt = argv[optindex++], *arg;
  494. const OptionDef *po;
  495. int ret;
  496. av_log(NULL, AV_LOG_DEBUG, "Reading option '%s' ...", opt);
  497. /* unnamed group separators, e.g. output filename */
  498. if (opt[0] != '-' || !opt[1]) {
  499. finish_group(octx, 0, opt);
  500. av_log(NULL, AV_LOG_DEBUG, " matched as %s.\n", groups[0].name);
  501. continue;
  502. }
  503. opt++;
  504. #define GET_ARG(arg) \
  505. do { \
  506. arg = argv[optindex++]; \
  507. if (!arg) { \
  508. av_log(NULL, AV_LOG_ERROR, "Missing argument for option '%s'.\n", opt);\
  509. return AVERROR(EINVAL); \
  510. } \
  511. } while (0)
  512. /* named group separators, e.g. -i */
  513. if ((ret = match_group_separator(groups, nb_groups, opt)) >= 0) {
  514. GET_ARG(arg);
  515. finish_group(octx, ret, arg);
  516. av_log(NULL, AV_LOG_DEBUG, " matched as %s with argument '%s'.\n",
  517. groups[ret].name, arg);
  518. continue;
  519. }
  520. /* normal options */
  521. po = find_option(options, opt);
  522. if (po->name) {
  523. if (po->flags & OPT_EXIT) {
  524. /* optional argument, e.g. -h */
  525. arg = argv[optindex++];
  526. } else if (po->flags & HAS_ARG) {
  527. GET_ARG(arg);
  528. } else {
  529. arg = "1";
  530. }
  531. add_opt(octx, po, opt, arg);
  532. av_log(NULL, AV_LOG_DEBUG, " matched as option '%s' (%s) with "
  533. "argument '%s'.\n", po->name, po->help, arg);
  534. continue;
  535. }
  536. /* AVOptions */
  537. if (argv[optindex]) {
  538. ret = opt_default(NULL, opt, argv[optindex]);
  539. if (ret >= 0) {
  540. av_log(NULL, AV_LOG_DEBUG, " matched as AVOption '%s' with "
  541. "argument '%s'.\n", opt, argv[optindex]);
  542. optindex++;
  543. continue;
  544. } else if (ret != AVERROR_OPTION_NOT_FOUND) {
  545. av_log(NULL, AV_LOG_ERROR, "Error parsing option '%s' "
  546. "with argument '%s'.\n", opt, argv[optindex]);
  547. return ret;
  548. }
  549. }
  550. /* boolean -nofoo options */
  551. if (opt[0] == 'n' && opt[1] == 'o' &&
  552. (po = find_option(options, opt + 2)) &&
  553. po->name && po->flags & OPT_BOOL) {
  554. add_opt(octx, po, opt, "0");
  555. av_log(NULL, AV_LOG_DEBUG, " matched as option '%s' (%s) with "
  556. "argument 0.\n", po->name, po->help);
  557. continue;
  558. }
  559. av_log(NULL, AV_LOG_ERROR, "Unrecognized option '%s'.\n", opt);
  560. return AVERROR_OPTION_NOT_FOUND;
  561. }
  562. if (octx->cur_group.nb_opts || codec_opts || format_opts || resample_opts)
  563. av_log(NULL, AV_LOG_WARNING, "Trailing options were found on the "
  564. "commandline.\n");
  565. av_log(NULL, AV_LOG_DEBUG, "Finished splitting the commandline.\n");
  566. return 0;
  567. }
  568. int opt_loglevel(void *optctx, const char *opt, const char *arg)
  569. {
  570. const struct { const char *name; int level; } log_levels[] = {
  571. { "quiet" , AV_LOG_QUIET },
  572. { "panic" , AV_LOG_PANIC },
  573. { "fatal" , AV_LOG_FATAL },
  574. { "error" , AV_LOG_ERROR },
  575. { "warning", AV_LOG_WARNING },
  576. { "info" , AV_LOG_INFO },
  577. { "verbose", AV_LOG_VERBOSE },
  578. { "debug" , AV_LOG_DEBUG },
  579. };
  580. char *tail;
  581. int level;
  582. int i;
  583. for (i = 0; i < FF_ARRAY_ELEMS(log_levels); i++) {
  584. if (!strcmp(log_levels[i].name, arg)) {
  585. av_log_set_level(log_levels[i].level);
  586. return 0;
  587. }
  588. }
  589. level = strtol(arg, &tail, 10);
  590. if (*tail) {
  591. av_log(NULL, AV_LOG_FATAL, "Invalid loglevel \"%s\". "
  592. "Possible levels are numbers or:\n", arg);
  593. for (i = 0; i < FF_ARRAY_ELEMS(log_levels); i++)
  594. av_log(NULL, AV_LOG_FATAL, "\"%s\"\n", log_levels[i].name);
  595. exit(1);
  596. }
  597. av_log_set_level(level);
  598. return 0;
  599. }
  600. int opt_timelimit(void *optctx, const char *opt, const char *arg)
  601. {
  602. #if HAVE_SETRLIMIT
  603. int lim = parse_number_or_die(opt, arg, OPT_INT64, 0, INT_MAX);
  604. struct rlimit rl = { lim, lim + 1 };
  605. if (setrlimit(RLIMIT_CPU, &rl))
  606. perror("setrlimit");
  607. #else
  608. av_log(NULL, AV_LOG_WARNING, "-%s not implemented on this OS\n", opt);
  609. #endif
  610. return 0;
  611. }
  612. void print_error(const char *filename, int err)
  613. {
  614. char errbuf[128];
  615. const char *errbuf_ptr = errbuf;
  616. if (av_strerror(err, errbuf, sizeof(errbuf)) < 0)
  617. errbuf_ptr = strerror(AVUNERROR(err));
  618. av_log(NULL, AV_LOG_ERROR, "%s: %s\n", filename, errbuf_ptr);
  619. }
  620. static int warned_cfg = 0;
  621. #define INDENT 1
  622. #define SHOW_VERSION 2
  623. #define SHOW_CONFIG 4
  624. #define PRINT_LIB_INFO(libname, LIBNAME, flags, level) \
  625. if (CONFIG_##LIBNAME) { \
  626. const char *indent = flags & INDENT? " " : ""; \
  627. if (flags & SHOW_VERSION) { \
  628. unsigned int version = libname##_version(); \
  629. av_log(NULL, level, \
  630. "%slib%-10s %2d.%3d.%2d / %2d.%3d.%2d\n", \
  631. indent, #libname, \
  632. LIB##LIBNAME##_VERSION_MAJOR, \
  633. LIB##LIBNAME##_VERSION_MINOR, \
  634. LIB##LIBNAME##_VERSION_MICRO, \
  635. version >> 16, version >> 8 & 0xff, version & 0xff); \
  636. } \
  637. if (flags & SHOW_CONFIG) { \
  638. const char *cfg = libname##_configuration(); \
  639. if (strcmp(LIBAV_CONFIGURATION, cfg)) { \
  640. if (!warned_cfg) { \
  641. av_log(NULL, level, \
  642. "%sWARNING: library configuration mismatch\n", \
  643. indent); \
  644. warned_cfg = 1; \
  645. } \
  646. av_log(NULL, level, "%s%-11s configuration: %s\n", \
  647. indent, #libname, cfg); \
  648. } \
  649. } \
  650. } \
  651. static void print_all_libs_info(int flags, int level)
  652. {
  653. PRINT_LIB_INFO(avutil, AVUTIL, flags, level);
  654. PRINT_LIB_INFO(avcodec, AVCODEC, flags, level);
  655. PRINT_LIB_INFO(avformat, AVFORMAT, flags, level);
  656. PRINT_LIB_INFO(avdevice, AVDEVICE, flags, level);
  657. PRINT_LIB_INFO(avfilter, AVFILTER, flags, level);
  658. PRINT_LIB_INFO(avresample, AVRESAMPLE, flags, level);
  659. PRINT_LIB_INFO(swscale, SWSCALE, flags, level);
  660. }
  661. void show_banner(void)
  662. {
  663. av_log(NULL, AV_LOG_INFO,
  664. "%s version " LIBAV_VERSION ", Copyright (c) %d-%d the Libav developers\n",
  665. program_name, program_birth_year, this_year);
  666. av_log(NULL, AV_LOG_INFO, " built on %s %s with %s\n",
  667. __DATE__, __TIME__, CC_IDENT);
  668. av_log(NULL, AV_LOG_VERBOSE, " configuration: " LIBAV_CONFIGURATION "\n");
  669. print_all_libs_info(INDENT|SHOW_CONFIG, AV_LOG_VERBOSE);
  670. print_all_libs_info(INDENT|SHOW_VERSION, AV_LOG_VERBOSE);
  671. }
  672. int show_version(void *optctx, const char *opt, const char *arg)
  673. {
  674. av_log_set_callback(log_callback_help);
  675. printf("%s " LIBAV_VERSION "\n", program_name);
  676. print_all_libs_info(SHOW_VERSION, AV_LOG_INFO);
  677. return 0;
  678. }
  679. int show_license(void *optctx, const char *opt, const char *arg)
  680. {
  681. printf(
  682. #if CONFIG_NONFREE
  683. "This version of %s has nonfree parts compiled in.\n"
  684. "Therefore it is not legally redistributable.\n",
  685. program_name
  686. #elif CONFIG_GPLV3
  687. "%s is free software; you can redistribute it and/or modify\n"
  688. "it under the terms of the GNU General Public License as published by\n"
  689. "the Free Software Foundation; either version 3 of the License, or\n"
  690. "(at your option) any later version.\n"
  691. "\n"
  692. "%s is distributed in the hope that it will be useful,\n"
  693. "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
  694. "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n"
  695. "GNU General Public License for more details.\n"
  696. "\n"
  697. "You should have received a copy of the GNU General Public License\n"
  698. "along with %s. If not, see <http://www.gnu.org/licenses/>.\n",
  699. program_name, program_name, program_name
  700. #elif CONFIG_GPL
  701. "%s is free software; you can redistribute it and/or modify\n"
  702. "it under the terms of the GNU General Public License as published by\n"
  703. "the Free Software Foundation; either version 2 of the License, or\n"
  704. "(at your option) any later version.\n"
  705. "\n"
  706. "%s is distributed in the hope that it will be useful,\n"
  707. "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
  708. "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n"
  709. "GNU General Public License for more details.\n"
  710. "\n"
  711. "You should have received a copy of the GNU General Public License\n"
  712. "along with %s; if not, write to the Free Software\n"
  713. "Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n",
  714. program_name, program_name, program_name
  715. #elif CONFIG_LGPLV3
  716. "%s is free software; you can redistribute it and/or modify\n"
  717. "it under the terms of the GNU Lesser General Public License as published by\n"
  718. "the Free Software Foundation; either version 3 of the License, or\n"
  719. "(at your option) any later version.\n"
  720. "\n"
  721. "%s is distributed in the hope that it will be useful,\n"
  722. "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
  723. "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n"
  724. "GNU Lesser General Public License for more details.\n"
  725. "\n"
  726. "You should have received a copy of the GNU Lesser General Public License\n"
  727. "along with %s. If not, see <http://www.gnu.org/licenses/>.\n",
  728. program_name, program_name, program_name
  729. #else
  730. "%s is free software; you can redistribute it and/or\n"
  731. "modify it under the terms of the GNU Lesser General Public\n"
  732. "License as published by the Free Software Foundation; either\n"
  733. "version 2.1 of the License, or (at your option) any later version.\n"
  734. "\n"
  735. "%s is distributed in the hope that it will be useful,\n"
  736. "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
  737. "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n"
  738. "Lesser General Public License for more details.\n"
  739. "\n"
  740. "You should have received a copy of the GNU Lesser General Public\n"
  741. "License along with %s; if not, write to the Free Software\n"
  742. "Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n",
  743. program_name, program_name, program_name
  744. #endif
  745. );
  746. return 0;
  747. }
  748. int show_formats(void *optctx, const char *opt, const char *arg)
  749. {
  750. AVInputFormat *ifmt = NULL;
  751. AVOutputFormat *ofmt = NULL;
  752. const char *last_name;
  753. printf("File formats:\n"
  754. " D. = Demuxing supported\n"
  755. " .E = Muxing supported\n"
  756. " --\n");
  757. last_name = "000";
  758. for (;;) {
  759. int decode = 0;
  760. int encode = 0;
  761. const char *name = NULL;
  762. const char *long_name = NULL;
  763. while ((ofmt = av_oformat_next(ofmt))) {
  764. if ((name == NULL || strcmp(ofmt->name, name) < 0) &&
  765. strcmp(ofmt->name, last_name) > 0) {
  766. name = ofmt->name;
  767. long_name = ofmt->long_name;
  768. encode = 1;
  769. }
  770. }
  771. while ((ifmt = av_iformat_next(ifmt))) {
  772. if ((name == NULL || strcmp(ifmt->name, name) < 0) &&
  773. strcmp(ifmt->name, last_name) > 0) {
  774. name = ifmt->name;
  775. long_name = ifmt->long_name;
  776. encode = 0;
  777. }
  778. if (name && strcmp(ifmt->name, name) == 0)
  779. decode = 1;
  780. }
  781. if (name == NULL)
  782. break;
  783. last_name = name;
  784. printf(" %s%s %-15s %s\n",
  785. decode ? "D" : " ",
  786. encode ? "E" : " ",
  787. name,
  788. long_name ? long_name:" ");
  789. }
  790. return 0;
  791. }
  792. #define PRINT_CODEC_SUPPORTED(codec, field, type, list_name, term, get_name) \
  793. if (codec->field) { \
  794. const type *p = c->field; \
  795. \
  796. printf(" Supported " list_name ":"); \
  797. while (*p != term) { \
  798. get_name(*p); \
  799. printf(" %s", name); \
  800. p++; \
  801. } \
  802. printf("\n"); \
  803. } \
  804. static void print_codec(const AVCodec *c)
  805. {
  806. int encoder = av_codec_is_encoder(c);
  807. printf("%s %s [%s]:\n", encoder ? "Encoder" : "Decoder", c->name,
  808. c->long_name ? c->long_name : "");
  809. if (c->type == AVMEDIA_TYPE_VIDEO) {
  810. printf(" Threading capabilities: ");
  811. switch (c->capabilities & (CODEC_CAP_FRAME_THREADS |
  812. CODEC_CAP_SLICE_THREADS)) {
  813. case CODEC_CAP_FRAME_THREADS |
  814. CODEC_CAP_SLICE_THREADS: printf("frame and slice"); break;
  815. case CODEC_CAP_FRAME_THREADS: printf("frame"); break;
  816. case CODEC_CAP_SLICE_THREADS: printf("slice"); break;
  817. default: printf("no"); break;
  818. }
  819. printf("\n");
  820. }
  821. if (c->supported_framerates) {
  822. const AVRational *fps = c->supported_framerates;
  823. printf(" Supported framerates:");
  824. while (fps->num) {
  825. printf(" %d/%d", fps->num, fps->den);
  826. fps++;
  827. }
  828. printf("\n");
  829. }
  830. PRINT_CODEC_SUPPORTED(c, pix_fmts, enum AVPixelFormat, "pixel formats",
  831. AV_PIX_FMT_NONE, GET_PIX_FMT_NAME);
  832. PRINT_CODEC_SUPPORTED(c, supported_samplerates, int, "sample rates", 0,
  833. GET_SAMPLE_RATE_NAME);
  834. PRINT_CODEC_SUPPORTED(c, sample_fmts, enum AVSampleFormat, "sample formats",
  835. AV_SAMPLE_FMT_NONE, GET_SAMPLE_FMT_NAME);
  836. PRINT_CODEC_SUPPORTED(c, channel_layouts, uint64_t, "channel layouts",
  837. 0, GET_CH_LAYOUT_DESC);
  838. if (c->priv_class) {
  839. show_help_children(c->priv_class,
  840. AV_OPT_FLAG_ENCODING_PARAM |
  841. AV_OPT_FLAG_DECODING_PARAM);
  842. }
  843. }
  844. static char get_media_type_char(enum AVMediaType type)
  845. {
  846. switch (type) {
  847. case AVMEDIA_TYPE_VIDEO: return 'V';
  848. case AVMEDIA_TYPE_AUDIO: return 'A';
  849. case AVMEDIA_TYPE_SUBTITLE: return 'S';
  850. default: return '?';
  851. }
  852. }
  853. static const AVCodec *next_codec_for_id(enum AVCodecID id, const AVCodec *prev,
  854. int encoder)
  855. {
  856. while ((prev = av_codec_next(prev))) {
  857. if (prev->id == id &&
  858. (encoder ? av_codec_is_encoder(prev) : av_codec_is_decoder(prev)))
  859. return prev;
  860. }
  861. return NULL;
  862. }
  863. static void print_codecs_for_id(enum AVCodecID id, int encoder)
  864. {
  865. const AVCodec *codec = NULL;
  866. printf(" (%s: ", encoder ? "encoders" : "decoders");
  867. while ((codec = next_codec_for_id(id, codec, encoder)))
  868. printf("%s ", codec->name);
  869. printf(")");
  870. }
  871. int show_codecs(void *optctx, const char *opt, const char *arg)
  872. {
  873. const AVCodecDescriptor *desc = NULL;
  874. printf("Codecs:\n"
  875. " D..... = Decoding supported\n"
  876. " .E.... = Encoding supported\n"
  877. " ..V... = Video codec\n"
  878. " ..A... = Audio codec\n"
  879. " ..S... = Subtitle codec\n"
  880. " ...I.. = Intra frame-only codec\n"
  881. " ....L. = Lossy compression\n"
  882. " .....S = Lossless compression\n"
  883. " -------\n");
  884. while ((desc = avcodec_descriptor_next(desc))) {
  885. const AVCodec *codec = NULL;
  886. printf(avcodec_find_decoder(desc->id) ? "D" : ".");
  887. printf(avcodec_find_encoder(desc->id) ? "E" : ".");
  888. printf("%c", get_media_type_char(desc->type));
  889. printf((desc->props & AV_CODEC_PROP_INTRA_ONLY) ? "I" : ".");
  890. printf((desc->props & AV_CODEC_PROP_LOSSY) ? "L" : ".");
  891. printf((desc->props & AV_CODEC_PROP_LOSSLESS) ? "S" : ".");
  892. printf(" %-20s %s", desc->name, desc->long_name ? desc->long_name : "");
  893. /* print decoders/encoders when there's more than one or their
  894. * names are different from codec name */
  895. while ((codec = next_codec_for_id(desc->id, codec, 0))) {
  896. if (strcmp(codec->name, desc->name)) {
  897. print_codecs_for_id(desc->id, 0);
  898. break;
  899. }
  900. }
  901. codec = NULL;
  902. while ((codec = next_codec_for_id(desc->id, codec, 1))) {
  903. if (strcmp(codec->name, desc->name)) {
  904. print_codecs_for_id(desc->id, 1);
  905. break;
  906. }
  907. }
  908. printf("\n");
  909. }
  910. return 0;
  911. }
  912. static void print_codecs(int encoder)
  913. {
  914. const AVCodecDescriptor *desc = NULL;
  915. printf("%s:\n"
  916. " V... = Video\n"
  917. " A... = Audio\n"
  918. " S... = Subtitle\n"
  919. " .F.. = Frame-level multithreading\n"
  920. " ..S. = Slice-level multithreading\n"
  921. " ...X = Codec is experimental\n"
  922. " ---\n",
  923. encoder ? "Encoders" : "Decoders");
  924. while ((desc = avcodec_descriptor_next(desc))) {
  925. const AVCodec *codec = NULL;
  926. while ((codec = next_codec_for_id(desc->id, codec, encoder))) {
  927. printf("%c", get_media_type_char(desc->type));
  928. printf((codec->capabilities & CODEC_CAP_FRAME_THREADS) ? "F" : ".");
  929. printf((codec->capabilities & CODEC_CAP_SLICE_THREADS) ? "S" : ".");
  930. printf((codec->capabilities & CODEC_CAP_EXPERIMENTAL) ? "X" : ".");
  931. printf(" %-20s %s", codec->name, codec->long_name ? codec->long_name : "");
  932. if (strcmp(codec->name, desc->name))
  933. printf(" (codec %s)", desc->name);
  934. printf("\n");
  935. }
  936. }
  937. }
  938. int show_decoders(void *optctx, const char *opt, const char *arg)
  939. {
  940. print_codecs(0);
  941. return 0;
  942. }
  943. int show_encoders(void *optctx, const char *opt, const char *arg)
  944. {
  945. print_codecs(1);
  946. return 0;
  947. }
  948. int show_bsfs(void *optctx, const char *opt, const char *arg)
  949. {
  950. AVBitStreamFilter *bsf = NULL;
  951. printf("Bitstream filters:\n");
  952. while ((bsf = av_bitstream_filter_next(bsf)))
  953. printf("%s\n", bsf->name);
  954. printf("\n");
  955. return 0;
  956. }
  957. int show_protocols(void *optctx, const char *opt, const char *arg)
  958. {
  959. void *opaque = NULL;
  960. const char *name;
  961. printf("Supported file protocols:\n"
  962. "Input:\n");
  963. while ((name = avio_enum_protocols(&opaque, 0)))
  964. printf("%s\n", name);
  965. printf("Output:\n");
  966. while ((name = avio_enum_protocols(&opaque, 1)))
  967. printf("%s\n", name);
  968. return 0;
  969. }
  970. int show_filters(void *optctx, const char *opt, const char *arg)
  971. {
  972. AVFilter av_unused(**filter) = NULL;
  973. printf("Filters:\n");
  974. #if CONFIG_AVFILTER
  975. while ((filter = av_filter_next(filter)) && *filter)
  976. printf("%-16s %s\n", (*filter)->name, (*filter)->description);
  977. #endif
  978. return 0;
  979. }
  980. int show_pix_fmts(void *optctx, const char *opt, const char *arg)
  981. {
  982. const AVPixFmtDescriptor *pix_desc = NULL;
  983. printf("Pixel formats:\n"
  984. "I.... = Supported Input format for conversion\n"
  985. ".O... = Supported Output format for conversion\n"
  986. "..H.. = Hardware accelerated format\n"
  987. "...P. = Paletted format\n"
  988. "....B = Bitstream format\n"
  989. "FLAGS NAME NB_COMPONENTS BITS_PER_PIXEL\n"
  990. "-----\n");
  991. #if !CONFIG_SWSCALE
  992. # define sws_isSupportedInput(x) 0
  993. # define sws_isSupportedOutput(x) 0
  994. #endif
  995. while ((pix_desc = av_pix_fmt_desc_next(pix_desc))) {
  996. enum AVPixelFormat pix_fmt = av_pix_fmt_desc_get_id(pix_desc);
  997. printf("%c%c%c%c%c %-16s %d %2d\n",
  998. sws_isSupportedInput (pix_fmt) ? 'I' : '.',
  999. sws_isSupportedOutput(pix_fmt) ? 'O' : '.',
  1000. pix_desc->flags & PIX_FMT_HWACCEL ? 'H' : '.',
  1001. pix_desc->flags & PIX_FMT_PAL ? 'P' : '.',
  1002. pix_desc->flags & PIX_FMT_BITSTREAM ? 'B' : '.',
  1003. pix_desc->name,
  1004. pix_desc->nb_components,
  1005. av_get_bits_per_pixel(pix_desc));
  1006. }
  1007. return 0;
  1008. }
  1009. int show_sample_fmts(void *optctx, const char *opt, const char *arg)
  1010. {
  1011. int i;
  1012. char fmt_str[128];
  1013. for (i = -1; i < AV_SAMPLE_FMT_NB; i++)
  1014. printf("%s\n", av_get_sample_fmt_string(fmt_str, sizeof(fmt_str), i));
  1015. return 0;
  1016. }
  1017. static void show_help_codec(const char *name, int encoder)
  1018. {
  1019. const AVCodecDescriptor *desc;
  1020. const AVCodec *codec;
  1021. if (!name) {
  1022. av_log(NULL, AV_LOG_ERROR, "No codec name specified.\n");
  1023. return;
  1024. }
  1025. codec = encoder ? avcodec_find_encoder_by_name(name) :
  1026. avcodec_find_decoder_by_name(name);
  1027. if (codec)
  1028. print_codec(codec);
  1029. else if ((desc = avcodec_descriptor_get_by_name(name))) {
  1030. int printed = 0;
  1031. while ((codec = next_codec_for_id(desc->id, codec, encoder))) {
  1032. printed = 1;
  1033. print_codec(codec);
  1034. }
  1035. if (!printed) {
  1036. av_log(NULL, AV_LOG_ERROR, "Codec '%s' is known to Libav, "
  1037. "but no %s for it are available. Libav might need to be "
  1038. "recompiled with additional external libraries.\n",
  1039. name, encoder ? "encoders" : "decoders");
  1040. }
  1041. } else {
  1042. av_log(NULL, AV_LOG_ERROR, "Codec '%s' is not recognized by Libav.\n",
  1043. name);
  1044. }
  1045. }
  1046. static void show_help_demuxer(const char *name)
  1047. {
  1048. const AVInputFormat *fmt = av_find_input_format(name);
  1049. if (!fmt) {
  1050. av_log(NULL, AV_LOG_ERROR, "Unknown format '%s'.\n", name);
  1051. return;
  1052. }
  1053. printf("Demuxer %s [%s]:\n", fmt->name, fmt->long_name);
  1054. if (fmt->extensions)
  1055. printf(" Common extensions: %s.\n", fmt->extensions);
  1056. if (fmt->priv_class)
  1057. show_help_children(fmt->priv_class, AV_OPT_FLAG_DECODING_PARAM);
  1058. }
  1059. static void show_help_muxer(const char *name)
  1060. {
  1061. const AVCodecDescriptor *desc;
  1062. const AVOutputFormat *fmt = av_guess_format(name, NULL, NULL);
  1063. if (!fmt) {
  1064. av_log(NULL, AV_LOG_ERROR, "Unknown format '%s'.\n", name);
  1065. return;
  1066. }
  1067. printf("Muxer %s [%s]:\n", fmt->name, fmt->long_name);
  1068. if (fmt->extensions)
  1069. printf(" Common extensions: %s.\n", fmt->extensions);
  1070. if (fmt->mime_type)
  1071. printf(" Mime type: %s.\n", fmt->mime_type);
  1072. if (fmt->video_codec != AV_CODEC_ID_NONE &&
  1073. (desc = avcodec_descriptor_get(fmt->video_codec))) {
  1074. printf(" Default video codec: %s.\n", desc->name);
  1075. }
  1076. if (fmt->audio_codec != AV_CODEC_ID_NONE &&
  1077. (desc = avcodec_descriptor_get(fmt->audio_codec))) {
  1078. printf(" Default audio codec: %s.\n", desc->name);
  1079. }
  1080. if (fmt->subtitle_codec != AV_CODEC_ID_NONE &&
  1081. (desc = avcodec_descriptor_get(fmt->subtitle_codec))) {
  1082. printf(" Default subtitle codec: %s.\n", desc->name);
  1083. }
  1084. if (fmt->priv_class)
  1085. show_help_children(fmt->priv_class, AV_OPT_FLAG_ENCODING_PARAM);
  1086. }
  1087. int show_help(void *optctx, const char *opt, const char *arg)
  1088. {
  1089. char *topic, *par;
  1090. av_log_set_callback(log_callback_help);
  1091. topic = av_strdup(arg ? arg : "");
  1092. par = strchr(topic, '=');
  1093. if (par)
  1094. *par++ = 0;
  1095. if (!*topic) {
  1096. show_help_default(topic, par);
  1097. } else if (!strcmp(topic, "decoder")) {
  1098. show_help_codec(par, 0);
  1099. } else if (!strcmp(topic, "encoder")) {
  1100. show_help_codec(par, 1);
  1101. } else if (!strcmp(topic, "demuxer")) {
  1102. show_help_demuxer(par);
  1103. } else if (!strcmp(topic, "muxer")) {
  1104. show_help_muxer(par);
  1105. } else {
  1106. show_help_default(topic, par);
  1107. }
  1108. av_freep(&topic);
  1109. return 0;
  1110. }
  1111. int read_yesno(void)
  1112. {
  1113. int c = getchar();
  1114. int yesno = (toupper(c) == 'Y');
  1115. while (c != '\n' && c != EOF)
  1116. c = getchar();
  1117. return yesno;
  1118. }
  1119. int cmdutils_read_file(const char *filename, char **bufptr, size_t *size)
  1120. {
  1121. int ret;
  1122. FILE *f = fopen(filename, "rb");
  1123. if (!f) {
  1124. av_log(NULL, AV_LOG_ERROR, "Cannot read file '%s': %s\n", filename,
  1125. strerror(errno));
  1126. return AVERROR(errno);
  1127. }
  1128. fseek(f, 0, SEEK_END);
  1129. *size = ftell(f);
  1130. fseek(f, 0, SEEK_SET);
  1131. *bufptr = av_malloc(*size + 1);
  1132. if (!*bufptr) {
  1133. av_log(NULL, AV_LOG_ERROR, "Could not allocate file buffer\n");
  1134. fclose(f);
  1135. return AVERROR(ENOMEM);
  1136. }
  1137. ret = fread(*bufptr, 1, *size, f);
  1138. if (ret < *size) {
  1139. av_free(*bufptr);
  1140. if (ferror(f)) {
  1141. av_log(NULL, AV_LOG_ERROR, "Error while reading file '%s': %s\n",
  1142. filename, strerror(errno));
  1143. ret = AVERROR(errno);
  1144. } else
  1145. ret = AVERROR_EOF;
  1146. } else {
  1147. ret = 0;
  1148. (*bufptr)[(*size)++] = '\0';
  1149. }
  1150. fclose(f);
  1151. return ret;
  1152. }
  1153. void init_pts_correction(PtsCorrectionContext *ctx)
  1154. {
  1155. ctx->num_faulty_pts = ctx->num_faulty_dts = 0;
  1156. ctx->last_pts = ctx->last_dts = INT64_MIN;
  1157. }
  1158. int64_t guess_correct_pts(PtsCorrectionContext *ctx, int64_t reordered_pts,
  1159. int64_t dts)
  1160. {
  1161. int64_t pts = AV_NOPTS_VALUE;
  1162. if (dts != AV_NOPTS_VALUE) {
  1163. ctx->num_faulty_dts += dts <= ctx->last_dts;
  1164. ctx->last_dts = dts;
  1165. }
  1166. if (reordered_pts != AV_NOPTS_VALUE) {
  1167. ctx->num_faulty_pts += reordered_pts <= ctx->last_pts;
  1168. ctx->last_pts = reordered_pts;
  1169. }
  1170. if ((ctx->num_faulty_pts<=ctx->num_faulty_dts || dts == AV_NOPTS_VALUE)
  1171. && reordered_pts != AV_NOPTS_VALUE)
  1172. pts = reordered_pts;
  1173. else
  1174. pts = dts;
  1175. return pts;
  1176. }
  1177. FILE *get_preset_file(char *filename, size_t filename_size,
  1178. const char *preset_name, int is_path,
  1179. const char *codec_name)
  1180. {
  1181. FILE *f = NULL;
  1182. int i;
  1183. const char *base[3] = { getenv("AVCONV_DATADIR"),
  1184. getenv("HOME"),
  1185. AVCONV_DATADIR, };
  1186. if (is_path) {
  1187. av_strlcpy(filename, preset_name, filename_size);
  1188. f = fopen(filename, "r");
  1189. } else {
  1190. for (i = 0; i < 3 && !f; i++) {
  1191. if (!base[i])
  1192. continue;
  1193. snprintf(filename, filename_size, "%s%s/%s.avpreset", base[i],
  1194. i != 1 ? "" : "/.avconv", preset_name);
  1195. f = fopen(filename, "r");
  1196. if (!f && codec_name) {
  1197. snprintf(filename, filename_size,
  1198. "%s%s/%s-%s.avpreset",
  1199. base[i], i != 1 ? "" : "/.avconv", codec_name,
  1200. preset_name);
  1201. f = fopen(filename, "r");
  1202. }
  1203. }
  1204. }
  1205. return f;
  1206. }
  1207. int check_stream_specifier(AVFormatContext *s, AVStream *st, const char *spec)
  1208. {
  1209. if (*spec <= '9' && *spec >= '0') /* opt:index */
  1210. return strtol(spec, NULL, 0) == st->index;
  1211. else if (*spec == 'v' || *spec == 'a' || *spec == 's' || *spec == 'd' ||
  1212. *spec == 't') { /* opt:[vasdt] */
  1213. enum AVMediaType type;
  1214. switch (*spec++) {
  1215. case 'v': type = AVMEDIA_TYPE_VIDEO; break;
  1216. case 'a': type = AVMEDIA_TYPE_AUDIO; break;
  1217. case 's': type = AVMEDIA_TYPE_SUBTITLE; break;
  1218. case 'd': type = AVMEDIA_TYPE_DATA; break;
  1219. case 't': type = AVMEDIA_TYPE_ATTACHMENT; break;
  1220. default: av_assert0(0);
  1221. }
  1222. if (type != st->codec->codec_type)
  1223. return 0;
  1224. if (*spec++ == ':') { /* possibly followed by :index */
  1225. int i, index = strtol(spec, NULL, 0);
  1226. for (i = 0; i < s->nb_streams; i++)
  1227. if (s->streams[i]->codec->codec_type == type && index-- == 0)
  1228. return i == st->index;
  1229. return 0;
  1230. }
  1231. return 1;
  1232. } else if (*spec == 'p' && *(spec + 1) == ':') {
  1233. int prog_id, i, j;
  1234. char *endptr;
  1235. spec += 2;
  1236. prog_id = strtol(spec, &endptr, 0);
  1237. for (i = 0; i < s->nb_programs; i++) {
  1238. if (s->programs[i]->id != prog_id)
  1239. continue;
  1240. if (*endptr++ == ':') {
  1241. int stream_idx = strtol(endptr, NULL, 0);
  1242. return stream_idx >= 0 &&
  1243. stream_idx < s->programs[i]->nb_stream_indexes &&
  1244. st->index == s->programs[i]->stream_index[stream_idx];
  1245. }
  1246. for (j = 0; j < s->programs[i]->nb_stream_indexes; j++)
  1247. if (st->index == s->programs[i]->stream_index[j])
  1248. return 1;
  1249. }
  1250. return 0;
  1251. } else if (!*spec) /* empty specifier, matches everything */
  1252. return 1;
  1253. av_log(s, AV_LOG_ERROR, "Invalid stream specifier: %s.\n", spec);
  1254. return AVERROR(EINVAL);
  1255. }
  1256. AVDictionary *filter_codec_opts(AVDictionary *opts, enum AVCodecID codec_id,
  1257. AVFormatContext *s, AVStream *st, AVCodec *codec)
  1258. {
  1259. AVDictionary *ret = NULL;
  1260. AVDictionaryEntry *t = NULL;
  1261. int flags = s->oformat ? AV_OPT_FLAG_ENCODING_PARAM
  1262. : AV_OPT_FLAG_DECODING_PARAM;
  1263. char prefix = 0;
  1264. const AVClass *cc = avcodec_get_class();
  1265. if (!codec)
  1266. codec = s->oformat ? avcodec_find_encoder(codec_id)
  1267. : avcodec_find_decoder(codec_id);
  1268. if (!codec)
  1269. return NULL;
  1270. switch (codec->type) {
  1271. case AVMEDIA_TYPE_VIDEO:
  1272. prefix = 'v';
  1273. flags |= AV_OPT_FLAG_VIDEO_PARAM;
  1274. break;
  1275. case AVMEDIA_TYPE_AUDIO:
  1276. prefix = 'a';
  1277. flags |= AV_OPT_FLAG_AUDIO_PARAM;
  1278. break;
  1279. case AVMEDIA_TYPE_SUBTITLE:
  1280. prefix = 's';
  1281. flags |= AV_OPT_FLAG_SUBTITLE_PARAM;
  1282. break;
  1283. }
  1284. while (t = av_dict_get(opts, "", t, AV_DICT_IGNORE_SUFFIX)) {
  1285. char *p = strchr(t->key, ':');
  1286. /* check stream specification in opt name */
  1287. if (p)
  1288. switch (check_stream_specifier(s, st, p + 1)) {
  1289. case 1: *p = 0; break;
  1290. case 0: continue;
  1291. default: return NULL;
  1292. }
  1293. if (av_opt_find(&cc, t->key, NULL, flags, AV_OPT_SEARCH_FAKE_OBJ) ||
  1294. (codec && codec->priv_class &&
  1295. av_opt_find(&codec->priv_class, t->key, NULL, flags,
  1296. AV_OPT_SEARCH_FAKE_OBJ)))
  1297. av_dict_set(&ret, t->key, t->value, 0);
  1298. else if (t->key[0] == prefix &&
  1299. av_opt_find(&cc, t->key + 1, NULL, flags,
  1300. AV_OPT_SEARCH_FAKE_OBJ))
  1301. av_dict_set(&ret, t->key + 1, t->value, 0);
  1302. if (p)
  1303. *p = ':';
  1304. }
  1305. return ret;
  1306. }
  1307. AVDictionary **setup_find_stream_info_opts(AVFormatContext *s,
  1308. AVDictionary *codec_opts)
  1309. {
  1310. int i;
  1311. AVDictionary **opts;
  1312. if (!s->nb_streams)
  1313. return NULL;
  1314. opts = av_mallocz(s->nb_streams * sizeof(*opts));
  1315. if (!opts) {
  1316. av_log(NULL, AV_LOG_ERROR,
  1317. "Could not alloc memory for stream options.\n");
  1318. return NULL;
  1319. }
  1320. for (i = 0; i < s->nb_streams; i++)
  1321. opts[i] = filter_codec_opts(codec_opts, s->streams[i]->codec->codec_id,
  1322. s, s->streams[i], NULL);
  1323. return opts;
  1324. }
  1325. void *grow_array(void *array, int elem_size, int *size, int new_size)
  1326. {
  1327. if (new_size >= INT_MAX / elem_size) {
  1328. av_log(NULL, AV_LOG_ERROR, "Array too big.\n");
  1329. exit(1);
  1330. }
  1331. if (*size < new_size) {
  1332. uint8_t *tmp = av_realloc(array, new_size*elem_size);
  1333. if (!tmp) {
  1334. av_log(NULL, AV_LOG_ERROR, "Could not alloc buffer.\n");
  1335. exit(1);
  1336. }
  1337. memset(tmp + *size*elem_size, 0, (new_size-*size) * elem_size);
  1338. *size = new_size;
  1339. return tmp;
  1340. }
  1341. return array;
  1342. }
  1343. static int alloc_buffer(FrameBuffer **pool, AVCodecContext *s, FrameBuffer **pbuf)
  1344. {
  1345. const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(s->pix_fmt);
  1346. FrameBuffer *buf;
  1347. int i, ret;
  1348. int pixel_size;
  1349. int h_chroma_shift, v_chroma_shift;
  1350. int edge = 32; // XXX should be avcodec_get_edge_width(), but that fails on svq1
  1351. int w = s->width, h = s->height;
  1352. if (!desc)
  1353. return AVERROR(EINVAL);
  1354. pixel_size = desc->comp[0].step_minus1 + 1;
  1355. buf = av_mallocz(sizeof(*buf));
  1356. if (!buf)
  1357. return AVERROR(ENOMEM);
  1358. if (!(s->flags & CODEC_FLAG_EMU_EDGE)) {
  1359. w += 2*edge;
  1360. h += 2*edge;
  1361. }
  1362. avcodec_align_dimensions(s, &w, &h);
  1363. if ((ret = av_image_alloc(buf->base, buf->linesize, w, h,
  1364. s->pix_fmt, 32)) < 0) {
  1365. av_freep(&buf);
  1366. return ret;
  1367. }
  1368. av_pix_fmt_get_chroma_sub_sample(s->pix_fmt,
  1369. &h_chroma_shift, &v_chroma_shift);
  1370. for (i = 0; i < FF_ARRAY_ELEMS(buf->data); i++) {
  1371. const int h_shift = i==0 ? 0 : h_chroma_shift;
  1372. const int v_shift = i==0 ? 0 : v_chroma_shift;
  1373. if (s->flags & CODEC_FLAG_EMU_EDGE)
  1374. buf->data[i] = buf->base[i];
  1375. else if (buf->base[i])
  1376. buf->data[i] = buf->base[i] +
  1377. FFALIGN((buf->linesize[i]*edge >> v_shift) +
  1378. (pixel_size*edge >> h_shift), 32);
  1379. }
  1380. buf->w = s->width;
  1381. buf->h = s->height;
  1382. buf->pix_fmt = s->pix_fmt;
  1383. buf->pool = pool;
  1384. *pbuf = buf;
  1385. return 0;
  1386. }
  1387. int codec_get_buffer(AVCodecContext *s, AVFrame *frame)
  1388. {
  1389. FrameBuffer **pool = s->opaque;
  1390. FrameBuffer *buf;
  1391. int ret, i;
  1392. if (!*pool && (ret = alloc_buffer(pool, s, pool)) < 0)
  1393. return ret;
  1394. buf = *pool;
  1395. *pool = buf->next;
  1396. buf->next = NULL;
  1397. if (buf->w != s->width || buf->h != s->height || buf->pix_fmt != s->pix_fmt) {
  1398. av_freep(&buf->base[0]);
  1399. av_free(buf);
  1400. if ((ret = alloc_buffer(pool, s, &buf)) < 0)
  1401. return ret;
  1402. }
  1403. buf->refcount++;
  1404. frame->opaque = buf;
  1405. frame->type = FF_BUFFER_TYPE_USER;
  1406. frame->extended_data = frame->data;
  1407. for (i = 0; i < FF_ARRAY_ELEMS(buf->data); i++) {
  1408. frame->base[i] = buf->base[i]; // XXX h264.c uses base though it shouldn't
  1409. frame->data[i] = buf->data[i];
  1410. frame->linesize[i] = buf->linesize[i];
  1411. }
  1412. return 0;
  1413. }
  1414. static void unref_buffer(FrameBuffer *buf)
  1415. {
  1416. FrameBuffer **pool = buf->pool;
  1417. av_assert0(buf->refcount);
  1418. buf->refcount--;
  1419. if (!buf->refcount) {
  1420. buf->next = *pool;
  1421. *pool = buf;
  1422. }
  1423. }
  1424. void codec_release_buffer(AVCodecContext *s, AVFrame *frame)
  1425. {
  1426. FrameBuffer *buf = frame->opaque;
  1427. int i;
  1428. for (i = 0; i < FF_ARRAY_ELEMS(frame->data); i++)
  1429. frame->data[i] = NULL;
  1430. unref_buffer(buf);
  1431. }
  1432. void filter_release_buffer(AVFilterBuffer *fb)
  1433. {
  1434. FrameBuffer *buf = fb->priv;
  1435. av_free(fb);
  1436. unref_buffer(buf);
  1437. }
  1438. void free_buffer_pool(FrameBuffer **pool)
  1439. {
  1440. FrameBuffer *buf = *pool;
  1441. while (buf) {
  1442. *pool = buf->next;
  1443. av_freep(&buf->base[0]);
  1444. av_free(buf);
  1445. buf = *pool;
  1446. }
  1447. }