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;
  54. static const int this_year = 2012;
  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, const char *opt)
  387. {
  388. const OptionGroupDef *p = groups;
  389. while (p->name) {
  390. if (p->sep && !strcmp(p->sep, opt))
  391. return p - groups;
  392. p++;
  393. }
  394. return -1;
  395. }
  396. /*
  397. * Finish parsing an option group.
  398. *
  399. * @param group_idx which group definition should this group belong to
  400. * @param arg argument of the group delimiting option
  401. */
  402. static void finish_group(OptionParseContext *octx, int group_idx,
  403. const char *arg)
  404. {
  405. OptionGroupList *l = &octx->groups[group_idx];
  406. OptionGroup *g;
  407. GROW_ARRAY(l->groups, l->nb_groups);
  408. g = &l->groups[l->nb_groups - 1];
  409. *g = octx->cur_group;
  410. g->arg = arg;
  411. g->group_def = l->group_def;
  412. #if CONFIG_SWSCALE
  413. g->sws_opts = sws_opts;
  414. #endif
  415. g->codec_opts = codec_opts;
  416. g->format_opts = format_opts;
  417. codec_opts = NULL;
  418. format_opts = NULL;
  419. #if CONFIG_SWSCALE
  420. sws_opts = NULL;
  421. #endif
  422. init_opts();
  423. memset(&octx->cur_group, 0, sizeof(octx->cur_group));
  424. }
  425. /*
  426. * Add an option instance to currently parsed group.
  427. */
  428. static void add_opt(OptionParseContext *octx, const OptionDef *opt,
  429. const char *key, const char *val)
  430. {
  431. int global = !(opt->flags & (OPT_PERFILE | OPT_SPEC | OPT_OFFSET));
  432. OptionGroup *g = global ? &octx->global_opts : &octx->cur_group;
  433. GROW_ARRAY(g->opts, g->nb_opts);
  434. g->opts[g->nb_opts - 1].opt = opt;
  435. g->opts[g->nb_opts - 1].key = key;
  436. g->opts[g->nb_opts - 1].val = val;
  437. }
  438. static void init_parse_context(OptionParseContext *octx,
  439. const OptionGroupDef *groups)
  440. {
  441. static const OptionGroupDef global_group = { "global" };
  442. const OptionGroupDef *g = groups;
  443. int i;
  444. memset(octx, 0, sizeof(*octx));
  445. while (g->name)
  446. g++;
  447. octx->nb_groups = g - groups;
  448. octx->groups = av_mallocz(sizeof(*octx->groups) * octx->nb_groups);
  449. if (!octx->groups)
  450. exit(1);
  451. for (i = 0; i < octx->nb_groups; i++)
  452. octx->groups[i].group_def = &groups[i];
  453. octx->global_opts.group_def = &global_group;
  454. octx->global_opts.arg = "";
  455. init_opts();
  456. }
  457. void uninit_parse_context(OptionParseContext *octx)
  458. {
  459. int i, j;
  460. for (i = 0; i < octx->nb_groups; i++) {
  461. OptionGroupList *l = &octx->groups[i];
  462. for (j = 0; j < l->nb_groups; j++) {
  463. av_freep(&l->groups[j].opts);
  464. av_dict_free(&l->groups[j].codec_opts);
  465. av_dict_free(&l->groups[j].format_opts);
  466. #if CONFIG_SWSCALE
  467. sws_freeContext(l->groups[j].sws_opts);
  468. #endif
  469. }
  470. av_freep(&l->groups);
  471. }
  472. av_freep(&octx->groups);
  473. av_freep(&octx->cur_group.opts);
  474. av_freep(&octx->global_opts.opts);
  475. uninit_opts();
  476. }
  477. int split_commandline(OptionParseContext *octx, int argc, char *argv[],
  478. const OptionDef *options,
  479. const OptionGroupDef *groups)
  480. {
  481. int optindex = 1;
  482. /* perform system-dependent conversions for arguments list */
  483. prepare_app_arguments(&argc, &argv);
  484. init_parse_context(octx, groups);
  485. av_log(NULL, AV_LOG_DEBUG, "Splitting the commandline.\n");
  486. while (optindex < argc) {
  487. const char *opt = argv[optindex++], *arg;
  488. const OptionDef *po;
  489. int ret;
  490. av_log(NULL, AV_LOG_DEBUG, "Reading option '%s' ...", opt);
  491. /* unnamed group separators, e.g. output filename */
  492. if (opt[0] != '-' || !opt[1]) {
  493. finish_group(octx, 0, opt);
  494. av_log(NULL, AV_LOG_DEBUG, " matched as %s.\n", groups[0].name);
  495. continue;
  496. }
  497. opt++;
  498. #define GET_ARG(arg) \
  499. do { \
  500. arg = argv[optindex++]; \
  501. if (!arg) { \
  502. av_log(NULL, AV_LOG_ERROR, "Missing argument for option '%s'.\n", opt);\
  503. return AVERROR(EINVAL); \
  504. } \
  505. } while (0)
  506. /* named group separators, e.g. -i */
  507. if ((ret = match_group_separator(groups, opt)) >= 0) {
  508. GET_ARG(arg);
  509. finish_group(octx, ret, arg);
  510. av_log(NULL, AV_LOG_DEBUG, " matched as %s with argument '%s'.\n",
  511. groups[ret].name, arg);
  512. continue;
  513. }
  514. /* normal options */
  515. po = find_option(options, opt);
  516. if (po->name) {
  517. if (po->flags & OPT_EXIT) {
  518. /* optional argument, e.g. -h */
  519. arg = argv[optindex++];
  520. } else if (po->flags & HAS_ARG) {
  521. GET_ARG(arg);
  522. } else {
  523. arg = "1";
  524. }
  525. add_opt(octx, po, opt, arg);
  526. av_log(NULL, AV_LOG_DEBUG, " matched as option '%s' (%s) with "
  527. "argument '%s'.\n", po->name, po->help, arg);
  528. continue;
  529. }
  530. /* AVOptions */
  531. if (argv[optindex]) {
  532. ret = opt_default(NULL, opt, argv[optindex]);
  533. if (ret >= 0) {
  534. av_log(NULL, AV_LOG_DEBUG, " matched as AVOption '%s' with "
  535. "argument '%s'.\n", opt, argv[optindex]);
  536. optindex++;
  537. continue;
  538. } else if (ret != AVERROR_OPTION_NOT_FOUND) {
  539. av_log(NULL, AV_LOG_ERROR, "Error parsing option '%s' "
  540. "with argument '%s'.\n", opt, argv[optindex]);
  541. return ret;
  542. }
  543. }
  544. /* boolean -nofoo options */
  545. if (opt[0] == 'n' && opt[1] == 'o' &&
  546. (po = find_option(options, opt + 2)) &&
  547. po->name && po->flags & OPT_BOOL) {
  548. add_opt(octx, po, opt, "0");
  549. av_log(NULL, AV_LOG_DEBUG, " matched as option '%s' (%s) with "
  550. "argument 0.\n", po->name, po->help);
  551. continue;
  552. }
  553. av_log(NULL, AV_LOG_ERROR, "Unrecognized option '%s'.\n", opt);
  554. return AVERROR_OPTION_NOT_FOUND;
  555. }
  556. if (octx->cur_group.nb_opts || codec_opts || format_opts)
  557. av_log(NULL, AV_LOG_WARNING, "Trailing options were found on the "
  558. "commandline.\n");
  559. av_log(NULL, AV_LOG_DEBUG, "Finished splitting the commandline.\n");
  560. return 0;
  561. }
  562. int opt_loglevel(void *optctx, const char *opt, const char *arg)
  563. {
  564. const struct { const char *name; int level; } log_levels[] = {
  565. { "quiet" , AV_LOG_QUIET },
  566. { "panic" , AV_LOG_PANIC },
  567. { "fatal" , AV_LOG_FATAL },
  568. { "error" , AV_LOG_ERROR },
  569. { "warning", AV_LOG_WARNING },
  570. { "info" , AV_LOG_INFO },
  571. { "verbose", AV_LOG_VERBOSE },
  572. { "debug" , AV_LOG_DEBUG },
  573. };
  574. char *tail;
  575. int level;
  576. int i;
  577. for (i = 0; i < FF_ARRAY_ELEMS(log_levels); i++) {
  578. if (!strcmp(log_levels[i].name, arg)) {
  579. av_log_set_level(log_levels[i].level);
  580. return 0;
  581. }
  582. }
  583. level = strtol(arg, &tail, 10);
  584. if (*tail) {
  585. av_log(NULL, AV_LOG_FATAL, "Invalid loglevel \"%s\". "
  586. "Possible levels are numbers or:\n", arg);
  587. for (i = 0; i < FF_ARRAY_ELEMS(log_levels); i++)
  588. av_log(NULL, AV_LOG_FATAL, "\"%s\"\n", log_levels[i].name);
  589. exit(1);
  590. }
  591. av_log_set_level(level);
  592. return 0;
  593. }
  594. int opt_timelimit(void *optctx, const char *opt, const char *arg)
  595. {
  596. #if HAVE_SETRLIMIT
  597. int lim = parse_number_or_die(opt, arg, OPT_INT64, 0, INT_MAX);
  598. struct rlimit rl = { lim, lim + 1 };
  599. if (setrlimit(RLIMIT_CPU, &rl))
  600. perror("setrlimit");
  601. #else
  602. av_log(NULL, AV_LOG_WARNING, "-%s not implemented on this OS\n", opt);
  603. #endif
  604. return 0;
  605. }
  606. void print_error(const char *filename, int err)
  607. {
  608. char errbuf[128];
  609. const char *errbuf_ptr = errbuf;
  610. if (av_strerror(err, errbuf, sizeof(errbuf)) < 0)
  611. errbuf_ptr = strerror(AVUNERROR(err));
  612. av_log(NULL, AV_LOG_ERROR, "%s: %s\n", filename, errbuf_ptr);
  613. }
  614. static int warned_cfg = 0;
  615. #define INDENT 1
  616. #define SHOW_VERSION 2
  617. #define SHOW_CONFIG 4
  618. #define PRINT_LIB_INFO(libname, LIBNAME, flags, level) \
  619. if (CONFIG_##LIBNAME) { \
  620. const char *indent = flags & INDENT? " " : ""; \
  621. if (flags & SHOW_VERSION) { \
  622. unsigned int version = libname##_version(); \
  623. av_log(NULL, level, \
  624. "%slib%-10s %2d.%3d.%2d / %2d.%3d.%2d\n", \
  625. indent, #libname, \
  626. LIB##LIBNAME##_VERSION_MAJOR, \
  627. LIB##LIBNAME##_VERSION_MINOR, \
  628. LIB##LIBNAME##_VERSION_MICRO, \
  629. version >> 16, version >> 8 & 0xff, version & 0xff); \
  630. } \
  631. if (flags & SHOW_CONFIG) { \
  632. const char *cfg = libname##_configuration(); \
  633. if (strcmp(LIBAV_CONFIGURATION, cfg)) { \
  634. if (!warned_cfg) { \
  635. av_log(NULL, level, \
  636. "%sWARNING: library configuration mismatch\n", \
  637. indent); \
  638. warned_cfg = 1; \
  639. } \
  640. av_log(NULL, level, "%s%-11s configuration: %s\n", \
  641. indent, #libname, cfg); \
  642. } \
  643. } \
  644. } \
  645. static void print_all_libs_info(int flags, int level)
  646. {
  647. PRINT_LIB_INFO(avutil, AVUTIL, flags, level);
  648. PRINT_LIB_INFO(avcodec, AVCODEC, flags, level);
  649. PRINT_LIB_INFO(avformat, AVFORMAT, flags, level);
  650. PRINT_LIB_INFO(avdevice, AVDEVICE, flags, level);
  651. PRINT_LIB_INFO(avfilter, AVFILTER, flags, level);
  652. PRINT_LIB_INFO(avresample, AVRESAMPLE, flags, level);
  653. PRINT_LIB_INFO(swscale, SWSCALE, flags, level);
  654. }
  655. void show_banner(void)
  656. {
  657. av_log(NULL, AV_LOG_INFO,
  658. "%s version " LIBAV_VERSION ", Copyright (c) %d-%d the Libav developers\n",
  659. program_name, program_birth_year, this_year);
  660. av_log(NULL, AV_LOG_INFO, " built on %s %s with %s\n",
  661. __DATE__, __TIME__, CC_IDENT);
  662. av_log(NULL, AV_LOG_VERBOSE, " configuration: " LIBAV_CONFIGURATION "\n");
  663. print_all_libs_info(INDENT|SHOW_CONFIG, AV_LOG_VERBOSE);
  664. print_all_libs_info(INDENT|SHOW_VERSION, AV_LOG_VERBOSE);
  665. }
  666. int show_version(void *optctx, const char *opt, const char *arg)
  667. {
  668. av_log_set_callback(log_callback_help);
  669. printf("%s " LIBAV_VERSION "\n", program_name);
  670. print_all_libs_info(SHOW_VERSION, AV_LOG_INFO);
  671. return 0;
  672. }
  673. int show_license(void *optctx, const char *opt, const char *arg)
  674. {
  675. printf(
  676. #if CONFIG_NONFREE
  677. "This version of %s has nonfree parts compiled in.\n"
  678. "Therefore it is not legally redistributable.\n",
  679. program_name
  680. #elif CONFIG_GPLV3
  681. "%s is free software; you can redistribute it and/or modify\n"
  682. "it under the terms of the GNU General Public License as published by\n"
  683. "the Free Software Foundation; either version 3 of the License, or\n"
  684. "(at your option) any later version.\n"
  685. "\n"
  686. "%s is distributed in the hope that it will be useful,\n"
  687. "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
  688. "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n"
  689. "GNU General Public License for more details.\n"
  690. "\n"
  691. "You should have received a copy of the GNU General Public License\n"
  692. "along with %s. If not, see <http://www.gnu.org/licenses/>.\n",
  693. program_name, program_name, program_name
  694. #elif CONFIG_GPL
  695. "%s is free software; you can redistribute it and/or modify\n"
  696. "it under the terms of the GNU General Public License as published by\n"
  697. "the Free Software Foundation; either version 2 of the License, or\n"
  698. "(at your option) any later version.\n"
  699. "\n"
  700. "%s is distributed in the hope that it will be useful,\n"
  701. "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
  702. "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n"
  703. "GNU General Public License for more details.\n"
  704. "\n"
  705. "You should have received a copy of the GNU General Public License\n"
  706. "along with %s; if not, write to the Free Software\n"
  707. "Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n",
  708. program_name, program_name, program_name
  709. #elif CONFIG_LGPLV3
  710. "%s is free software; you can redistribute it and/or modify\n"
  711. "it under the terms of the GNU Lesser General Public License as published by\n"
  712. "the Free Software Foundation; either version 3 of the License, or\n"
  713. "(at your option) any later version.\n"
  714. "\n"
  715. "%s is distributed in the hope that it will be useful,\n"
  716. "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
  717. "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n"
  718. "GNU Lesser General Public License for more details.\n"
  719. "\n"
  720. "You should have received a copy of the GNU Lesser General Public License\n"
  721. "along with %s. If not, see <http://www.gnu.org/licenses/>.\n",
  722. program_name, program_name, program_name
  723. #else
  724. "%s is free software; you can redistribute it and/or\n"
  725. "modify it under the terms of the GNU Lesser General Public\n"
  726. "License as published by the Free Software Foundation; either\n"
  727. "version 2.1 of the License, or (at your option) any later version.\n"
  728. "\n"
  729. "%s is distributed in the hope that it will be useful,\n"
  730. "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
  731. "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n"
  732. "Lesser General Public License for more details.\n"
  733. "\n"
  734. "You should have received a copy of the GNU Lesser General Public\n"
  735. "License along with %s; if not, write to the Free Software\n"
  736. "Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n",
  737. program_name, program_name, program_name
  738. #endif
  739. );
  740. return 0;
  741. }
  742. int show_formats(void *optctx, const char *opt, const char *arg)
  743. {
  744. AVInputFormat *ifmt = NULL;
  745. AVOutputFormat *ofmt = NULL;
  746. const char *last_name;
  747. printf("File formats:\n"
  748. " D. = Demuxing supported\n"
  749. " .E = Muxing supported\n"
  750. " --\n");
  751. last_name = "000";
  752. for (;;) {
  753. int decode = 0;
  754. int encode = 0;
  755. const char *name = NULL;
  756. const char *long_name = NULL;
  757. while ((ofmt = av_oformat_next(ofmt))) {
  758. if ((name == NULL || strcmp(ofmt->name, name) < 0) &&
  759. strcmp(ofmt->name, last_name) > 0) {
  760. name = ofmt->name;
  761. long_name = ofmt->long_name;
  762. encode = 1;
  763. }
  764. }
  765. while ((ifmt = av_iformat_next(ifmt))) {
  766. if ((name == NULL || strcmp(ifmt->name, name) < 0) &&
  767. strcmp(ifmt->name, last_name) > 0) {
  768. name = ifmt->name;
  769. long_name = ifmt->long_name;
  770. encode = 0;
  771. }
  772. if (name && strcmp(ifmt->name, name) == 0)
  773. decode = 1;
  774. }
  775. if (name == NULL)
  776. break;
  777. last_name = name;
  778. printf(" %s%s %-15s %s\n",
  779. decode ? "D" : " ",
  780. encode ? "E" : " ",
  781. name,
  782. long_name ? long_name:" ");
  783. }
  784. return 0;
  785. }
  786. #define PRINT_CODEC_SUPPORTED(codec, field, type, list_name, term, get_name) \
  787. if (codec->field) { \
  788. const type *p = c->field; \
  789. \
  790. printf(" Supported " list_name ":"); \
  791. while (*p != term) { \
  792. get_name(*p); \
  793. printf(" %s", name); \
  794. p++; \
  795. } \
  796. printf("\n"); \
  797. } \
  798. static void print_codec(const AVCodec *c)
  799. {
  800. int encoder = av_codec_is_encoder(c);
  801. printf("%s %s [%s]:\n", encoder ? "Encoder" : "Decoder", c->name,
  802. c->long_name ? c->long_name : "");
  803. if (c->type == AVMEDIA_TYPE_VIDEO) {
  804. printf(" Threading capabilities: ");
  805. switch (c->capabilities & (CODEC_CAP_FRAME_THREADS |
  806. CODEC_CAP_SLICE_THREADS)) {
  807. case CODEC_CAP_FRAME_THREADS |
  808. CODEC_CAP_SLICE_THREADS: printf("frame and slice"); break;
  809. case CODEC_CAP_FRAME_THREADS: printf("frame"); break;
  810. case CODEC_CAP_SLICE_THREADS: printf("slice"); break;
  811. default: printf("no"); break;
  812. }
  813. printf("\n");
  814. }
  815. if (c->supported_framerates) {
  816. const AVRational *fps = c->supported_framerates;
  817. printf(" Supported framerates:");
  818. while (fps->num) {
  819. printf(" %d/%d", fps->num, fps->den);
  820. fps++;
  821. }
  822. printf("\n");
  823. }
  824. PRINT_CODEC_SUPPORTED(c, pix_fmts, enum AVPixelFormat, "pixel formats",
  825. AV_PIX_FMT_NONE, GET_PIX_FMT_NAME);
  826. PRINT_CODEC_SUPPORTED(c, supported_samplerates, int, "sample rates", 0,
  827. GET_SAMPLE_RATE_NAME);
  828. PRINT_CODEC_SUPPORTED(c, sample_fmts, enum AVSampleFormat, "sample formats",
  829. AV_SAMPLE_FMT_NONE, GET_SAMPLE_FMT_NAME);
  830. PRINT_CODEC_SUPPORTED(c, channel_layouts, uint64_t, "channel layouts",
  831. 0, GET_CH_LAYOUT_DESC);
  832. if (c->priv_class) {
  833. show_help_children(c->priv_class,
  834. AV_OPT_FLAG_ENCODING_PARAM |
  835. AV_OPT_FLAG_DECODING_PARAM);
  836. }
  837. }
  838. static char get_media_type_char(enum AVMediaType type)
  839. {
  840. switch (type) {
  841. case AVMEDIA_TYPE_VIDEO: return 'V';
  842. case AVMEDIA_TYPE_AUDIO: return 'A';
  843. case AVMEDIA_TYPE_SUBTITLE: return 'S';
  844. default: return '?';
  845. }
  846. }
  847. static const AVCodec *next_codec_for_id(enum AVCodecID id, const AVCodec *prev,
  848. int encoder)
  849. {
  850. while ((prev = av_codec_next(prev))) {
  851. if (prev->id == id &&
  852. (encoder ? av_codec_is_encoder(prev) : av_codec_is_decoder(prev)))
  853. return prev;
  854. }
  855. return NULL;
  856. }
  857. static void print_codecs_for_id(enum AVCodecID id, int encoder)
  858. {
  859. const AVCodec *codec = NULL;
  860. printf(" (%s: ", encoder ? "encoders" : "decoders");
  861. while ((codec = next_codec_for_id(id, codec, encoder)))
  862. printf("%s ", codec->name);
  863. printf(")");
  864. }
  865. int show_codecs(void *optctx, const char *opt, const char *arg)
  866. {
  867. const AVCodecDescriptor *desc = NULL;
  868. printf("Codecs:\n"
  869. " D..... = Decoding supported\n"
  870. " .E.... = Encoding supported\n"
  871. " ..V... = Video codec\n"
  872. " ..A... = Audio codec\n"
  873. " ..S... = Subtitle codec\n"
  874. " ...I.. = Intra frame-only codec\n"
  875. " ....L. = Lossy compression\n"
  876. " .....S = Lossless compression\n"
  877. " -------\n");
  878. while ((desc = avcodec_descriptor_next(desc))) {
  879. const AVCodec *codec = NULL;
  880. printf(avcodec_find_decoder(desc->id) ? "D" : ".");
  881. printf(avcodec_find_encoder(desc->id) ? "E" : ".");
  882. printf("%c", get_media_type_char(desc->type));
  883. printf((desc->props & AV_CODEC_PROP_INTRA_ONLY) ? "I" : ".");
  884. printf((desc->props & AV_CODEC_PROP_LOSSY) ? "L" : ".");
  885. printf((desc->props & AV_CODEC_PROP_LOSSLESS) ? "S" : ".");
  886. printf(" %-20s %s", desc->name, desc->long_name ? desc->long_name : "");
  887. /* print decoders/encoders when there's more than one or their
  888. * names are different from codec name */
  889. while ((codec = next_codec_for_id(desc->id, codec, 0))) {
  890. if (strcmp(codec->name, desc->name)) {
  891. print_codecs_for_id(desc->id, 0);
  892. break;
  893. }
  894. }
  895. codec = NULL;
  896. while ((codec = next_codec_for_id(desc->id, codec, 1))) {
  897. if (strcmp(codec->name, desc->name)) {
  898. print_codecs_for_id(desc->id, 1);
  899. break;
  900. }
  901. }
  902. printf("\n");
  903. }
  904. return 0;
  905. }
  906. static void print_codecs(int encoder)
  907. {
  908. const AVCodecDescriptor *desc = NULL;
  909. printf("%s:\n"
  910. " V... = Video\n"
  911. " A... = Audio\n"
  912. " S... = Subtitle\n"
  913. " .F.. = Frame-level multithreading\n"
  914. " ..S. = Slice-level multithreading\n"
  915. " ...X = Codec is experimental\n"
  916. " ---\n",
  917. encoder ? "Encoders" : "Decoders");
  918. while ((desc = avcodec_descriptor_next(desc))) {
  919. const AVCodec *codec = NULL;
  920. while ((codec = next_codec_for_id(desc->id, codec, encoder))) {
  921. printf("%c", get_media_type_char(desc->type));
  922. printf((codec->capabilities & CODEC_CAP_FRAME_THREADS) ? "F" : ".");
  923. printf((codec->capabilities & CODEC_CAP_SLICE_THREADS) ? "S" : ".");
  924. printf((codec->capabilities & CODEC_CAP_EXPERIMENTAL) ? "X" : ".");
  925. printf(" %-20s %s", codec->name, codec->long_name ? codec->long_name : "");
  926. if (strcmp(codec->name, desc->name))
  927. printf(" (codec %s)", desc->name);
  928. printf("\n");
  929. }
  930. }
  931. }
  932. int show_decoders(void *optctx, const char *opt, const char *arg)
  933. {
  934. print_codecs(0);
  935. return 0;
  936. }
  937. int show_encoders(void *optctx, const char *opt, const char *arg)
  938. {
  939. print_codecs(1);
  940. return 0;
  941. }
  942. int show_bsfs(void *optctx, const char *opt, const char *arg)
  943. {
  944. AVBitStreamFilter *bsf = NULL;
  945. printf("Bitstream filters:\n");
  946. while ((bsf = av_bitstream_filter_next(bsf)))
  947. printf("%s\n", bsf->name);
  948. printf("\n");
  949. return 0;
  950. }
  951. int show_protocols(void *optctx, const char *opt, const char *arg)
  952. {
  953. void *opaque = NULL;
  954. const char *name;
  955. printf("Supported file protocols:\n"
  956. "Input:\n");
  957. while ((name = avio_enum_protocols(&opaque, 0)))
  958. printf("%s\n", name);
  959. printf("Output:\n");
  960. while ((name = avio_enum_protocols(&opaque, 1)))
  961. printf("%s\n", name);
  962. return 0;
  963. }
  964. int show_filters(void *optctx, const char *opt, const char *arg)
  965. {
  966. AVFilter av_unused(**filter) = NULL;
  967. printf("Filters:\n");
  968. #if CONFIG_AVFILTER
  969. while ((filter = av_filter_next(filter)) && *filter)
  970. printf("%-16s %s\n", (*filter)->name, (*filter)->description);
  971. #endif
  972. return 0;
  973. }
  974. int show_pix_fmts(void *optctx, const char *opt, const char *arg)
  975. {
  976. const AVPixFmtDescriptor *pix_desc = NULL;
  977. printf("Pixel formats:\n"
  978. "I.... = Supported Input format for conversion\n"
  979. ".O... = Supported Output format for conversion\n"
  980. "..H.. = Hardware accelerated format\n"
  981. "...P. = Paletted format\n"
  982. "....B = Bitstream format\n"
  983. "FLAGS NAME NB_COMPONENTS BITS_PER_PIXEL\n"
  984. "-----\n");
  985. #if !CONFIG_SWSCALE
  986. # define sws_isSupportedInput(x) 0
  987. # define sws_isSupportedOutput(x) 0
  988. #endif
  989. while ((pix_desc = av_pix_fmt_desc_next(pix_desc))) {
  990. enum AVPixelFormat pix_fmt = av_pix_fmt_desc_get_id(pix_desc);
  991. printf("%c%c%c%c%c %-16s %d %2d\n",
  992. sws_isSupportedInput (pix_fmt) ? 'I' : '.',
  993. sws_isSupportedOutput(pix_fmt) ? 'O' : '.',
  994. pix_desc->flags & PIX_FMT_HWACCEL ? 'H' : '.',
  995. pix_desc->flags & PIX_FMT_PAL ? 'P' : '.',
  996. pix_desc->flags & PIX_FMT_BITSTREAM ? 'B' : '.',
  997. pix_desc->name,
  998. pix_desc->nb_components,
  999. av_get_bits_per_pixel(pix_desc));
  1000. }
  1001. return 0;
  1002. }
  1003. int show_sample_fmts(void *optctx, const char *opt, const char *arg)
  1004. {
  1005. int i;
  1006. char fmt_str[128];
  1007. for (i = -1; i < AV_SAMPLE_FMT_NB; i++)
  1008. printf("%s\n", av_get_sample_fmt_string(fmt_str, sizeof(fmt_str), i));
  1009. return 0;
  1010. }
  1011. static void show_help_codec(const char *name, int encoder)
  1012. {
  1013. const AVCodecDescriptor *desc;
  1014. const AVCodec *codec;
  1015. if (!name) {
  1016. av_log(NULL, AV_LOG_ERROR, "No codec name specified.\n");
  1017. return;
  1018. }
  1019. codec = encoder ? avcodec_find_encoder_by_name(name) :
  1020. avcodec_find_decoder_by_name(name);
  1021. if (codec)
  1022. print_codec(codec);
  1023. else if ((desc = avcodec_descriptor_get_by_name(name))) {
  1024. int printed = 0;
  1025. while ((codec = next_codec_for_id(desc->id, codec, encoder))) {
  1026. printed = 1;
  1027. print_codec(codec);
  1028. }
  1029. if (!printed) {
  1030. av_log(NULL, AV_LOG_ERROR, "Codec '%s' is known to Libav, "
  1031. "but no %s for it are available. Libav might need to be "
  1032. "recompiled with additional external libraries.\n",
  1033. name, encoder ? "encoders" : "decoders");
  1034. }
  1035. } else {
  1036. av_log(NULL, AV_LOG_ERROR, "Codec '%s' is not recognized by Libav.\n",
  1037. name);
  1038. }
  1039. }
  1040. static void show_help_demuxer(const char *name)
  1041. {
  1042. const AVInputFormat *fmt = av_find_input_format(name);
  1043. if (!fmt) {
  1044. av_log(NULL, AV_LOG_ERROR, "Unknown format '%s'.\n", name);
  1045. return;
  1046. }
  1047. printf("Demuxer %s [%s]:\n", fmt->name, fmt->long_name);
  1048. if (fmt->extensions)
  1049. printf(" Common extensions: %s.\n", fmt->extensions);
  1050. if (fmt->priv_class)
  1051. show_help_children(fmt->priv_class, AV_OPT_FLAG_DECODING_PARAM);
  1052. }
  1053. static void show_help_muxer(const char *name)
  1054. {
  1055. const AVCodecDescriptor *desc;
  1056. const AVOutputFormat *fmt = av_guess_format(name, NULL, NULL);
  1057. if (!fmt) {
  1058. av_log(NULL, AV_LOG_ERROR, "Unknown format '%s'.\n", name);
  1059. return;
  1060. }
  1061. printf("Muxer %s [%s]:\n", fmt->name, fmt->long_name);
  1062. if (fmt->extensions)
  1063. printf(" Common extensions: %s.\n", fmt->extensions);
  1064. if (fmt->mime_type)
  1065. printf(" Mime type: %s.\n", fmt->mime_type);
  1066. if (fmt->video_codec != AV_CODEC_ID_NONE &&
  1067. (desc = avcodec_descriptor_get(fmt->video_codec))) {
  1068. printf(" Default video codec: %s.\n", desc->name);
  1069. }
  1070. if (fmt->audio_codec != AV_CODEC_ID_NONE &&
  1071. (desc = avcodec_descriptor_get(fmt->audio_codec))) {
  1072. printf(" Default audio codec: %s.\n", desc->name);
  1073. }
  1074. if (fmt->subtitle_codec != AV_CODEC_ID_NONE &&
  1075. (desc = avcodec_descriptor_get(fmt->subtitle_codec))) {
  1076. printf(" Default subtitle codec: %s.\n", desc->name);
  1077. }
  1078. if (fmt->priv_class)
  1079. show_help_children(fmt->priv_class, AV_OPT_FLAG_ENCODING_PARAM);
  1080. }
  1081. int show_help(void *optctx, const char *opt, const char *arg)
  1082. {
  1083. char *topic, *par;
  1084. av_log_set_callback(log_callback_help);
  1085. topic = av_strdup(arg ? arg : "");
  1086. par = strchr(topic, '=');
  1087. if (par)
  1088. *par++ = 0;
  1089. if (!*topic) {
  1090. show_help_default(topic, par);
  1091. } else if (!strcmp(topic, "decoder")) {
  1092. show_help_codec(par, 0);
  1093. } else if (!strcmp(topic, "encoder")) {
  1094. show_help_codec(par, 1);
  1095. } else if (!strcmp(topic, "demuxer")) {
  1096. show_help_demuxer(par);
  1097. } else if (!strcmp(topic, "muxer")) {
  1098. show_help_muxer(par);
  1099. } else {
  1100. show_help_default(topic, par);
  1101. }
  1102. av_freep(&topic);
  1103. return 0;
  1104. }
  1105. int read_yesno(void)
  1106. {
  1107. int c = getchar();
  1108. int yesno = (toupper(c) == 'Y');
  1109. while (c != '\n' && c != EOF)
  1110. c = getchar();
  1111. return yesno;
  1112. }
  1113. int cmdutils_read_file(const char *filename, char **bufptr, size_t *size)
  1114. {
  1115. int ret;
  1116. FILE *f = fopen(filename, "rb");
  1117. if (!f) {
  1118. av_log(NULL, AV_LOG_ERROR, "Cannot read file '%s': %s\n", filename,
  1119. strerror(errno));
  1120. return AVERROR(errno);
  1121. }
  1122. fseek(f, 0, SEEK_END);
  1123. *size = ftell(f);
  1124. fseek(f, 0, SEEK_SET);
  1125. *bufptr = av_malloc(*size + 1);
  1126. if (!*bufptr) {
  1127. av_log(NULL, AV_LOG_ERROR, "Could not allocate file buffer\n");
  1128. fclose(f);
  1129. return AVERROR(ENOMEM);
  1130. }
  1131. ret = fread(*bufptr, 1, *size, f);
  1132. if (ret < *size) {
  1133. av_free(*bufptr);
  1134. if (ferror(f)) {
  1135. av_log(NULL, AV_LOG_ERROR, "Error while reading file '%s': %s\n",
  1136. filename, strerror(errno));
  1137. ret = AVERROR(errno);
  1138. } else
  1139. ret = AVERROR_EOF;
  1140. } else {
  1141. ret = 0;
  1142. (*bufptr)[(*size)++] = '\0';
  1143. }
  1144. fclose(f);
  1145. return ret;
  1146. }
  1147. void init_pts_correction(PtsCorrectionContext *ctx)
  1148. {
  1149. ctx->num_faulty_pts = ctx->num_faulty_dts = 0;
  1150. ctx->last_pts = ctx->last_dts = INT64_MIN;
  1151. }
  1152. int64_t guess_correct_pts(PtsCorrectionContext *ctx, int64_t reordered_pts,
  1153. int64_t dts)
  1154. {
  1155. int64_t pts = AV_NOPTS_VALUE;
  1156. if (dts != AV_NOPTS_VALUE) {
  1157. ctx->num_faulty_dts += dts <= ctx->last_dts;
  1158. ctx->last_dts = dts;
  1159. }
  1160. if (reordered_pts != AV_NOPTS_VALUE) {
  1161. ctx->num_faulty_pts += reordered_pts <= ctx->last_pts;
  1162. ctx->last_pts = reordered_pts;
  1163. }
  1164. if ((ctx->num_faulty_pts<=ctx->num_faulty_dts || dts == AV_NOPTS_VALUE)
  1165. && reordered_pts != AV_NOPTS_VALUE)
  1166. pts = reordered_pts;
  1167. else
  1168. pts = dts;
  1169. return pts;
  1170. }
  1171. FILE *get_preset_file(char *filename, size_t filename_size,
  1172. const char *preset_name, int is_path,
  1173. const char *codec_name)
  1174. {
  1175. FILE *f = NULL;
  1176. int i;
  1177. const char *base[3] = { getenv("AVCONV_DATADIR"),
  1178. getenv("HOME"),
  1179. AVCONV_DATADIR, };
  1180. if (is_path) {
  1181. av_strlcpy(filename, preset_name, filename_size);
  1182. f = fopen(filename, "r");
  1183. } else {
  1184. for (i = 0; i < 3 && !f; i++) {
  1185. if (!base[i])
  1186. continue;
  1187. snprintf(filename, filename_size, "%s%s/%s.avpreset", base[i],
  1188. i != 1 ? "" : "/.avconv", preset_name);
  1189. f = fopen(filename, "r");
  1190. if (!f && codec_name) {
  1191. snprintf(filename, filename_size,
  1192. "%s%s/%s-%s.avpreset",
  1193. base[i], i != 1 ? "" : "/.avconv", codec_name,
  1194. preset_name);
  1195. f = fopen(filename, "r");
  1196. }
  1197. }
  1198. }
  1199. return f;
  1200. }
  1201. int check_stream_specifier(AVFormatContext *s, AVStream *st, const char *spec)
  1202. {
  1203. if (*spec <= '9' && *spec >= '0') /* opt:index */
  1204. return strtol(spec, NULL, 0) == st->index;
  1205. else if (*spec == 'v' || *spec == 'a' || *spec == 's' || *spec == 'd' ||
  1206. *spec == 't') { /* opt:[vasdt] */
  1207. enum AVMediaType type;
  1208. switch (*spec++) {
  1209. case 'v': type = AVMEDIA_TYPE_VIDEO; break;
  1210. case 'a': type = AVMEDIA_TYPE_AUDIO; break;
  1211. case 's': type = AVMEDIA_TYPE_SUBTITLE; break;
  1212. case 'd': type = AVMEDIA_TYPE_DATA; break;
  1213. case 't': type = AVMEDIA_TYPE_ATTACHMENT; break;
  1214. default: av_assert0(0);
  1215. }
  1216. if (type != st->codec->codec_type)
  1217. return 0;
  1218. if (*spec++ == ':') { /* possibly followed by :index */
  1219. int i, index = strtol(spec, NULL, 0);
  1220. for (i = 0; i < s->nb_streams; i++)
  1221. if (s->streams[i]->codec->codec_type == type && index-- == 0)
  1222. return i == st->index;
  1223. return 0;
  1224. }
  1225. return 1;
  1226. } else if (*spec == 'p' && *(spec + 1) == ':') {
  1227. int prog_id, i, j;
  1228. char *endptr;
  1229. spec += 2;
  1230. prog_id = strtol(spec, &endptr, 0);
  1231. for (i = 0; i < s->nb_programs; i++) {
  1232. if (s->programs[i]->id != prog_id)
  1233. continue;
  1234. if (*endptr++ == ':') {
  1235. int stream_idx = strtol(endptr, NULL, 0);
  1236. return stream_idx >= 0 &&
  1237. stream_idx < s->programs[i]->nb_stream_indexes &&
  1238. st->index == s->programs[i]->stream_index[stream_idx];
  1239. }
  1240. for (j = 0; j < s->programs[i]->nb_stream_indexes; j++)
  1241. if (st->index == s->programs[i]->stream_index[j])
  1242. return 1;
  1243. }
  1244. return 0;
  1245. } else if (!*spec) /* empty specifier, matches everything */
  1246. return 1;
  1247. av_log(s, AV_LOG_ERROR, "Invalid stream specifier: %s.\n", spec);
  1248. return AVERROR(EINVAL);
  1249. }
  1250. AVDictionary *filter_codec_opts(AVDictionary *opts, enum AVCodecID codec_id,
  1251. AVFormatContext *s, AVStream *st, AVCodec *codec)
  1252. {
  1253. AVDictionary *ret = NULL;
  1254. AVDictionaryEntry *t = NULL;
  1255. int flags = s->oformat ? AV_OPT_FLAG_ENCODING_PARAM
  1256. : AV_OPT_FLAG_DECODING_PARAM;
  1257. char prefix = 0;
  1258. const AVClass *cc = avcodec_get_class();
  1259. if (!codec)
  1260. codec = s->oformat ? avcodec_find_encoder(codec_id)
  1261. : avcodec_find_decoder(codec_id);
  1262. if (!codec)
  1263. return NULL;
  1264. switch (codec->type) {
  1265. case AVMEDIA_TYPE_VIDEO:
  1266. prefix = 'v';
  1267. flags |= AV_OPT_FLAG_VIDEO_PARAM;
  1268. break;
  1269. case AVMEDIA_TYPE_AUDIO:
  1270. prefix = 'a';
  1271. flags |= AV_OPT_FLAG_AUDIO_PARAM;
  1272. break;
  1273. case AVMEDIA_TYPE_SUBTITLE:
  1274. prefix = 's';
  1275. flags |= AV_OPT_FLAG_SUBTITLE_PARAM;
  1276. break;
  1277. }
  1278. while (t = av_dict_get(opts, "", t, AV_DICT_IGNORE_SUFFIX)) {
  1279. char *p = strchr(t->key, ':');
  1280. /* check stream specification in opt name */
  1281. if (p)
  1282. switch (check_stream_specifier(s, st, p + 1)) {
  1283. case 1: *p = 0; break;
  1284. case 0: continue;
  1285. default: return NULL;
  1286. }
  1287. if (av_opt_find(&cc, t->key, NULL, flags, AV_OPT_SEARCH_FAKE_OBJ) ||
  1288. (codec && codec->priv_class &&
  1289. av_opt_find(&codec->priv_class, t->key, NULL, flags,
  1290. AV_OPT_SEARCH_FAKE_OBJ)))
  1291. av_dict_set(&ret, t->key, t->value, 0);
  1292. else if (t->key[0] == prefix &&
  1293. av_opt_find(&cc, t->key + 1, NULL, flags,
  1294. AV_OPT_SEARCH_FAKE_OBJ))
  1295. av_dict_set(&ret, t->key + 1, t->value, 0);
  1296. if (p)
  1297. *p = ':';
  1298. }
  1299. return ret;
  1300. }
  1301. AVDictionary **setup_find_stream_info_opts(AVFormatContext *s,
  1302. AVDictionary *codec_opts)
  1303. {
  1304. int i;
  1305. AVDictionary **opts;
  1306. if (!s->nb_streams)
  1307. return NULL;
  1308. opts = av_mallocz(s->nb_streams * sizeof(*opts));
  1309. if (!opts) {
  1310. av_log(NULL, AV_LOG_ERROR,
  1311. "Could not alloc memory for stream options.\n");
  1312. return NULL;
  1313. }
  1314. for (i = 0; i < s->nb_streams; i++)
  1315. opts[i] = filter_codec_opts(codec_opts, s->streams[i]->codec->codec_id,
  1316. s, s->streams[i], NULL);
  1317. return opts;
  1318. }
  1319. void *grow_array(void *array, int elem_size, int *size, int new_size)
  1320. {
  1321. if (new_size >= INT_MAX / elem_size) {
  1322. av_log(NULL, AV_LOG_ERROR, "Array too big.\n");
  1323. exit(1);
  1324. }
  1325. if (*size < new_size) {
  1326. uint8_t *tmp = av_realloc(array, new_size*elem_size);
  1327. if (!tmp) {
  1328. av_log(NULL, AV_LOG_ERROR, "Could not alloc buffer.\n");
  1329. exit(1);
  1330. }
  1331. memset(tmp + *size*elem_size, 0, (new_size-*size) * elem_size);
  1332. *size = new_size;
  1333. return tmp;
  1334. }
  1335. return array;
  1336. }
  1337. static int alloc_buffer(FrameBuffer **pool, AVCodecContext *s, FrameBuffer **pbuf)
  1338. {
  1339. const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(s->pix_fmt);
  1340. FrameBuffer *buf;
  1341. int i, ret;
  1342. int pixel_size;
  1343. int h_chroma_shift, v_chroma_shift;
  1344. int edge = 32; // XXX should be avcodec_get_edge_width(), but that fails on svq1
  1345. int w = s->width, h = s->height;
  1346. if (!desc)
  1347. return AVERROR(EINVAL);
  1348. pixel_size = desc->comp[0].step_minus1 + 1;
  1349. buf = av_mallocz(sizeof(*buf));
  1350. if (!buf)
  1351. return AVERROR(ENOMEM);
  1352. if (!(s->flags & CODEC_FLAG_EMU_EDGE)) {
  1353. w += 2*edge;
  1354. h += 2*edge;
  1355. }
  1356. avcodec_align_dimensions(s, &w, &h);
  1357. if ((ret = av_image_alloc(buf->base, buf->linesize, w, h,
  1358. s->pix_fmt, 32)) < 0) {
  1359. av_freep(&buf);
  1360. return ret;
  1361. }
  1362. /* XXX this shouldn't be needed, but some tests break without this line
  1363. * those decoders are buggy and need to be fixed.
  1364. * the following tests fail:
  1365. * cdgraphics, ansi, aasc, fraps-v1, qtrle-1bit
  1366. */
  1367. memset(buf->base[0], 128, ret);
  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. }