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.

1839 lines
58KB

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