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.

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