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.

1873 lines
59KB

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