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.

1842 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': %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. for (i = 0; i < FF_ARRAY_ELEMS(log_levels); i++) {
  691. if (!strcmp(log_levels[i].name, arg)) {
  692. av_log_set_level(log_levels[i].level);
  693. return 0;
  694. }
  695. }
  696. level = strtol(arg, &tail, 10);
  697. if (*tail) {
  698. av_log(NULL, AV_LOG_FATAL, "Invalid loglevel \"%s\". "
  699. "Possible levels are numbers or:\n", arg);
  700. for (i = 0; i < FF_ARRAY_ELEMS(log_levels); i++)
  701. av_log(NULL, AV_LOG_FATAL, "\"%s\"\n", log_levels[i].name);
  702. exit(1);
  703. }
  704. av_log_set_level(level);
  705. return 0;
  706. }
  707. static void expand_filename_template(AVBPrint *bp, const char *template,
  708. struct tm *tm)
  709. {
  710. int c;
  711. while ((c = *(template++))) {
  712. if (c == '%') {
  713. if (!(c = *(template++)))
  714. break;
  715. switch (c) {
  716. case 'p':
  717. av_bprintf(bp, "%s", program_name);
  718. break;
  719. case 't':
  720. av_bprintf(bp, "%04d%02d%02d-%02d%02d%02d",
  721. tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday,
  722. tm->tm_hour, tm->tm_min, tm->tm_sec);
  723. break;
  724. case '%':
  725. av_bprint_chars(bp, c, 1);
  726. break;
  727. }
  728. } else {
  729. av_bprint_chars(bp, c, 1);
  730. }
  731. }
  732. }
  733. static int init_report(const char *env)
  734. {
  735. char *filename_template = NULL;
  736. char *key, *val;
  737. int ret, count = 0;
  738. time_t now;
  739. struct tm *tm;
  740. AVBPrint filename;
  741. if (report_file) /* already opened */
  742. return 0;
  743. time(&now);
  744. tm = localtime(&now);
  745. while (env && *env) {
  746. if ((ret = av_opt_get_key_value(&env, "=", ":", 0, &key, &val)) < 0) {
  747. if (count)
  748. av_log(NULL, AV_LOG_ERROR,
  749. "Failed to parse FFREPORT environment variable: %s\n",
  750. av_err2str(ret));
  751. break;
  752. }
  753. if (*env)
  754. env++;
  755. count++;
  756. if (!strcmp(key, "file")) {
  757. av_free(filename_template);
  758. filename_template = val;
  759. val = NULL;
  760. } else {
  761. av_log(NULL, AV_LOG_ERROR, "Unknown key '%s' in FFREPORT\n", key);
  762. }
  763. av_free(val);
  764. av_free(key);
  765. }
  766. av_bprint_init(&filename, 0, 1);
  767. expand_filename_template(&filename,
  768. av_x_if_null(filename_template, "%p-%t.log"), tm);
  769. av_free(filename_template);
  770. if (!av_bprint_is_complete(&filename)) {
  771. av_log(NULL, AV_LOG_ERROR, "Out of memory building report file name\n");
  772. return AVERROR(ENOMEM);
  773. }
  774. report_file = fopen(filename.str, "w");
  775. if (!report_file) {
  776. av_log(NULL, AV_LOG_ERROR, "Failed to open report \"%s\": %s\n",
  777. filename.str, strerror(errno));
  778. return AVERROR(errno);
  779. }
  780. av_log_set_callback(log_callback_report);
  781. av_log(NULL, AV_LOG_INFO,
  782. "%s started on %04d-%02d-%02d at %02d:%02d:%02d\n"
  783. "Report written to \"%s\"\n",
  784. program_name,
  785. tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday,
  786. tm->tm_hour, tm->tm_min, tm->tm_sec,
  787. filename.str);
  788. av_log_set_level(FFMAX(av_log_get_level(), AV_LOG_VERBOSE));
  789. av_bprint_finalize(&filename, NULL);
  790. return 0;
  791. }
  792. int opt_report(const char *opt)
  793. {
  794. return init_report(NULL);
  795. }
  796. int opt_max_alloc(void *optctx, const char *opt, const char *arg)
  797. {
  798. char *tail;
  799. size_t max;
  800. max = strtol(arg, &tail, 10);
  801. if (*tail) {
  802. av_log(NULL, AV_LOG_FATAL, "Invalid max_alloc \"%s\".\n", arg);
  803. exit(1);
  804. }
  805. av_max_alloc(max);
  806. return 0;
  807. }
  808. int opt_cpuflags(void *optctx, const char *opt, const char *arg)
  809. {
  810. int ret;
  811. unsigned flags = av_get_cpu_flags();
  812. if ((ret = av_parse_cpu_caps(&flags, arg)) < 0)
  813. return ret;
  814. av_force_cpu_flags(flags);
  815. return 0;
  816. }
  817. int opt_timelimit(void *optctx, const char *opt, const char *arg)
  818. {
  819. #if HAVE_SETRLIMIT
  820. int lim = parse_number_or_die(opt, arg, OPT_INT64, 0, INT_MAX);
  821. struct rlimit rl = { lim, lim + 1 };
  822. if (setrlimit(RLIMIT_CPU, &rl))
  823. perror("setrlimit");
  824. #else
  825. av_log(NULL, AV_LOG_WARNING, "-%s not implemented on this OS\n", opt);
  826. #endif
  827. return 0;
  828. }
  829. void print_error(const char *filename, int err)
  830. {
  831. char errbuf[128];
  832. const char *errbuf_ptr = errbuf;
  833. if (av_strerror(err, errbuf, sizeof(errbuf)) < 0)
  834. errbuf_ptr = strerror(AVUNERROR(err));
  835. av_log(NULL, AV_LOG_ERROR, "%s: %s\n", filename, errbuf_ptr);
  836. }
  837. static int warned_cfg = 0;
  838. #define INDENT 1
  839. #define SHOW_VERSION 2
  840. #define SHOW_CONFIG 4
  841. #define SHOW_COPYRIGHT 8
  842. #define PRINT_LIB_INFO(libname, LIBNAME, flags, level) \
  843. if (CONFIG_##LIBNAME) { \
  844. const char *indent = flags & INDENT? " " : ""; \
  845. if (flags & SHOW_VERSION) { \
  846. unsigned int version = libname##_version(); \
  847. av_log(NULL, level, \
  848. "%slib%-11s %2d.%3d.%3d / %2d.%3d.%3d\n", \
  849. indent, #libname, \
  850. LIB##LIBNAME##_VERSION_MAJOR, \
  851. LIB##LIBNAME##_VERSION_MINOR, \
  852. LIB##LIBNAME##_VERSION_MICRO, \
  853. version >> 16, version >> 8 & 0xff, version & 0xff); \
  854. } \
  855. if (flags & SHOW_CONFIG) { \
  856. const char *cfg = libname##_configuration(); \
  857. if (strcmp(FFMPEG_CONFIGURATION, cfg)) { \
  858. if (!warned_cfg) { \
  859. av_log(NULL, level, \
  860. "%sWARNING: library configuration mismatch\n", \
  861. indent); \
  862. warned_cfg = 1; \
  863. } \
  864. av_log(NULL, level, "%s%-11s configuration: %s\n", \
  865. indent, #libname, cfg); \
  866. } \
  867. } \
  868. } \
  869. static void print_all_libs_info(int flags, int level)
  870. {
  871. PRINT_LIB_INFO(avutil, AVUTIL, flags, level);
  872. PRINT_LIB_INFO(avcodec, AVCODEC, flags, level);
  873. PRINT_LIB_INFO(avformat, AVFORMAT, flags, level);
  874. PRINT_LIB_INFO(avdevice, AVDEVICE, flags, level);
  875. PRINT_LIB_INFO(avfilter, AVFILTER, flags, level);
  876. PRINT_LIB_INFO(avresample, AVRESAMPLE, flags, level);
  877. PRINT_LIB_INFO(swscale, SWSCALE, flags, level);
  878. PRINT_LIB_INFO(swresample,SWRESAMPLE, flags, level);
  879. PRINT_LIB_INFO(postproc, POSTPROC, flags, level);
  880. }
  881. static void print_program_info(int flags, int level)
  882. {
  883. const char *indent = flags & INDENT? " " : "";
  884. av_log(NULL, level, "%s version " FFMPEG_VERSION, program_name);
  885. if (flags & SHOW_COPYRIGHT)
  886. av_log(NULL, level, " Copyright (c) %d-%d the FFmpeg developers",
  887. program_birth_year, this_year);
  888. av_log(NULL, level, "\n");
  889. av_log(NULL, level, "%sbuilt on %s %s with %s\n",
  890. indent, __DATE__, __TIME__, CC_IDENT);
  891. av_log(NULL, level, "%sconfiguration: " FFMPEG_CONFIGURATION "\n", indent);
  892. }
  893. void show_banner(int argc, char **argv, const OptionDef *options)
  894. {
  895. int idx = locate_option(argc, argv, options, "version");
  896. if (idx)
  897. return;
  898. print_program_info (INDENT|SHOW_COPYRIGHT, AV_LOG_INFO);
  899. print_all_libs_info(INDENT|SHOW_CONFIG, AV_LOG_INFO);
  900. print_all_libs_info(INDENT|SHOW_VERSION, AV_LOG_INFO);
  901. }
  902. int show_version(void *optctx, const char *opt, const char *arg)
  903. {
  904. av_log_set_callback(log_callback_help);
  905. print_program_info (0 , AV_LOG_INFO);
  906. print_all_libs_info(SHOW_VERSION, AV_LOG_INFO);
  907. return 0;
  908. }
  909. int show_license(void *optctx, const char *opt, const char *arg)
  910. {
  911. #if CONFIG_NONFREE
  912. printf(
  913. "This version of %s has nonfree parts compiled in.\n"
  914. "Therefore it is not legally redistributable.\n",
  915. program_name );
  916. #elif CONFIG_GPLV3
  917. printf(
  918. "%s is free software; you can redistribute it and/or modify\n"
  919. "it under the terms of the GNU General Public License as published by\n"
  920. "the Free Software Foundation; either version 3 of the License, or\n"
  921. "(at your option) any later version.\n"
  922. "\n"
  923. "%s is distributed in the hope that it will be useful,\n"
  924. "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
  925. "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n"
  926. "GNU General Public License for more details.\n"
  927. "\n"
  928. "You should have received a copy of the GNU General Public License\n"
  929. "along with %s. If not, see <http://www.gnu.org/licenses/>.\n",
  930. program_name, program_name, program_name );
  931. #elif CONFIG_GPL
  932. printf(
  933. "%s is free software; you can redistribute it and/or modify\n"
  934. "it under the terms of the GNU General Public License as published by\n"
  935. "the Free Software Foundation; either version 2 of the License, or\n"
  936. "(at your option) any later version.\n"
  937. "\n"
  938. "%s is distributed in the hope that it will be useful,\n"
  939. "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
  940. "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n"
  941. "GNU General Public License for more details.\n"
  942. "\n"
  943. "You should have received a copy of the GNU General Public License\n"
  944. "along with %s; if not, write to the Free Software\n"
  945. "Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n",
  946. program_name, program_name, program_name );
  947. #elif CONFIG_LGPLV3
  948. printf(
  949. "%s is free software; you can redistribute it and/or modify\n"
  950. "it under the terms of the GNU Lesser General Public License as published by\n"
  951. "the Free Software Foundation; either version 3 of the License, or\n"
  952. "(at your option) any later version.\n"
  953. "\n"
  954. "%s is distributed in the hope that it will be useful,\n"
  955. "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
  956. "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n"
  957. "GNU Lesser General Public License for more details.\n"
  958. "\n"
  959. "You should have received a copy of the GNU Lesser General Public License\n"
  960. "along with %s. If not, see <http://www.gnu.org/licenses/>.\n",
  961. program_name, program_name, program_name );
  962. #else
  963. printf(
  964. "%s is free software; you can redistribute it and/or\n"
  965. "modify it under the terms of the GNU Lesser General Public\n"
  966. "License as published by the Free Software Foundation; either\n"
  967. "version 2.1 of the License, or (at your option) any later version.\n"
  968. "\n"
  969. "%s is distributed in the hope that it will be useful,\n"
  970. "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
  971. "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n"
  972. "Lesser General Public License for more details.\n"
  973. "\n"
  974. "You should have received a copy of the GNU Lesser General Public\n"
  975. "License along with %s; if not, write to the Free Software\n"
  976. "Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n",
  977. program_name, program_name, program_name );
  978. #endif
  979. return 0;
  980. }
  981. int show_formats(void *optctx, const char *opt, const char *arg)
  982. {
  983. AVInputFormat *ifmt = NULL;
  984. AVOutputFormat *ofmt = NULL;
  985. const char *last_name;
  986. printf("File formats:\n"
  987. " D. = Demuxing supported\n"
  988. " .E = Muxing supported\n"
  989. " --\n");
  990. last_name = "000";
  991. for (;;) {
  992. int decode = 0;
  993. int encode = 0;
  994. const char *name = NULL;
  995. const char *long_name = NULL;
  996. while ((ofmt = av_oformat_next(ofmt))) {
  997. if ((name == NULL || strcmp(ofmt->name, name) < 0) &&
  998. strcmp(ofmt->name, last_name) > 0) {
  999. name = ofmt->name;
  1000. long_name = ofmt->long_name;
  1001. encode = 1;
  1002. }
  1003. }
  1004. while ((ifmt = av_iformat_next(ifmt))) {
  1005. if ((name == NULL || strcmp(ifmt->name, name) < 0) &&
  1006. strcmp(ifmt->name, last_name) > 0) {
  1007. name = ifmt->name;
  1008. long_name = ifmt->long_name;
  1009. encode = 0;
  1010. }
  1011. if (name && strcmp(ifmt->name, name) == 0)
  1012. decode = 1;
  1013. }
  1014. if (name == NULL)
  1015. break;
  1016. last_name = name;
  1017. printf(" %s%s %-15s %s\n",
  1018. decode ? "D" : " ",
  1019. encode ? "E" : " ",
  1020. name,
  1021. long_name ? long_name:" ");
  1022. }
  1023. return 0;
  1024. }
  1025. #define PRINT_CODEC_SUPPORTED(codec, field, type, list_name, term, get_name) \
  1026. if (codec->field) { \
  1027. const type *p = codec->field; \
  1028. \
  1029. printf(" Supported " list_name ":"); \
  1030. while (*p != term) { \
  1031. get_name(*p); \
  1032. printf(" %s", name); \
  1033. p++; \
  1034. } \
  1035. printf("\n"); \
  1036. } \
  1037. static void print_codec(const AVCodec *c)
  1038. {
  1039. int encoder = av_codec_is_encoder(c);
  1040. printf("%s %s [%s]:\n", encoder ? "Encoder" : "Decoder", c->name,
  1041. c->long_name ? c->long_name : "");
  1042. if (c->type == AVMEDIA_TYPE_VIDEO) {
  1043. printf(" Threading capabilities: ");
  1044. switch (c->capabilities & (CODEC_CAP_FRAME_THREADS |
  1045. CODEC_CAP_SLICE_THREADS)) {
  1046. case CODEC_CAP_FRAME_THREADS |
  1047. CODEC_CAP_SLICE_THREADS: printf("frame and slice"); break;
  1048. case CODEC_CAP_FRAME_THREADS: printf("frame"); break;
  1049. case CODEC_CAP_SLICE_THREADS: printf("slice"); break;
  1050. default: printf("no"); break;
  1051. }
  1052. printf("\n");
  1053. }
  1054. if (c->supported_framerates) {
  1055. const AVRational *fps = c->supported_framerates;
  1056. printf(" Supported framerates:");
  1057. while (fps->num) {
  1058. printf(" %d/%d", fps->num, fps->den);
  1059. fps++;
  1060. }
  1061. printf("\n");
  1062. }
  1063. PRINT_CODEC_SUPPORTED(c, pix_fmts, enum AVPixelFormat, "pixel formats",
  1064. AV_PIX_FMT_NONE, GET_PIX_FMT_NAME);
  1065. PRINT_CODEC_SUPPORTED(c, supported_samplerates, int, "sample rates", 0,
  1066. GET_SAMPLE_RATE_NAME);
  1067. PRINT_CODEC_SUPPORTED(c, sample_fmts, enum AVSampleFormat, "sample formats",
  1068. AV_SAMPLE_FMT_NONE, GET_SAMPLE_FMT_NAME);
  1069. PRINT_CODEC_SUPPORTED(c, channel_layouts, uint64_t, "channel layouts",
  1070. 0, GET_CH_LAYOUT_DESC);
  1071. if (c->priv_class) {
  1072. show_help_children(c->priv_class,
  1073. AV_OPT_FLAG_ENCODING_PARAM |
  1074. AV_OPT_FLAG_DECODING_PARAM);
  1075. }
  1076. }
  1077. static char get_media_type_char(enum AVMediaType type)
  1078. {
  1079. switch (type) {
  1080. case AVMEDIA_TYPE_VIDEO: return 'V';
  1081. case AVMEDIA_TYPE_AUDIO: return 'A';
  1082. case AVMEDIA_TYPE_DATA: return 'D';
  1083. case AVMEDIA_TYPE_SUBTITLE: return 'S';
  1084. case AVMEDIA_TYPE_ATTACHMENT:return 'T';
  1085. default: return '?';
  1086. }
  1087. }
  1088. static const AVCodec *next_codec_for_id(enum AVCodecID id, const AVCodec *prev,
  1089. int encoder)
  1090. {
  1091. while ((prev = av_codec_next(prev))) {
  1092. if (prev->id == id &&
  1093. (encoder ? av_codec_is_encoder(prev) : av_codec_is_decoder(prev)))
  1094. return prev;
  1095. }
  1096. return NULL;
  1097. }
  1098. static int compare_codec_desc(const void *a, const void *b)
  1099. {
  1100. const AVCodecDescriptor * const *da = a;
  1101. const AVCodecDescriptor * const *db = b;
  1102. return (*da)->type != (*db)->type ? (*da)->type - (*db)->type :
  1103. strcmp((*da)->name, (*db)->name);
  1104. }
  1105. static unsigned get_codecs_sorted(const AVCodecDescriptor ***rcodecs)
  1106. {
  1107. const AVCodecDescriptor *desc = NULL;
  1108. const AVCodecDescriptor **codecs;
  1109. unsigned nb_codecs = 0, i = 0;
  1110. while ((desc = avcodec_descriptor_next(desc)))
  1111. nb_codecs++;
  1112. if (!(codecs = av_calloc(nb_codecs, sizeof(*codecs)))) {
  1113. av_log(NULL, AV_LOG_ERROR, "Out of memory\n");
  1114. exit(1);
  1115. }
  1116. desc = NULL;
  1117. while ((desc = avcodec_descriptor_next(desc)))
  1118. codecs[i++] = desc;
  1119. av_assert0(i == nb_codecs);
  1120. qsort(codecs, nb_codecs, sizeof(*codecs), compare_codec_desc);
  1121. *rcodecs = codecs;
  1122. return nb_codecs;
  1123. }
  1124. static void print_codecs_for_id(enum AVCodecID id, int encoder)
  1125. {
  1126. const AVCodec *codec = NULL;
  1127. printf(" (%s: ", encoder ? "encoders" : "decoders");
  1128. while ((codec = next_codec_for_id(id, codec, encoder)))
  1129. printf("%s ", codec->name);
  1130. printf(")");
  1131. }
  1132. int show_codecs(void *optctx, const char *opt, const char *arg)
  1133. {
  1134. const AVCodecDescriptor **codecs;
  1135. unsigned i, nb_codecs = get_codecs_sorted(&codecs);
  1136. printf("Codecs:\n"
  1137. " D..... = Decoding supported\n"
  1138. " .E.... = Encoding supported\n"
  1139. " ..V... = Video codec\n"
  1140. " ..A... = Audio codec\n"
  1141. " ..S... = Subtitle codec\n"
  1142. " ...I.. = Intra frame-only codec\n"
  1143. " ....L. = Lossy compression\n"
  1144. " .....S = Lossless compression\n"
  1145. " -------\n");
  1146. for (i = 0; i < nb_codecs; i++) {
  1147. const AVCodecDescriptor *desc = codecs[i];
  1148. const AVCodec *codec = NULL;
  1149. printf(" ");
  1150. printf(avcodec_find_decoder(desc->id) ? "D" : ".");
  1151. printf(avcodec_find_encoder(desc->id) ? "E" : ".");
  1152. printf("%c", get_media_type_char(desc->type));
  1153. printf((desc->props & AV_CODEC_PROP_INTRA_ONLY) ? "I" : ".");
  1154. printf((desc->props & AV_CODEC_PROP_LOSSY) ? "L" : ".");
  1155. printf((desc->props & AV_CODEC_PROP_LOSSLESS) ? "S" : ".");
  1156. printf(" %-20s %s", desc->name, desc->long_name ? desc->long_name : "");
  1157. /* print decoders/encoders when there's more than one or their
  1158. * names are different from codec name */
  1159. while ((codec = next_codec_for_id(desc->id, codec, 0))) {
  1160. if (strcmp(codec->name, desc->name)) {
  1161. print_codecs_for_id(desc->id, 0);
  1162. break;
  1163. }
  1164. }
  1165. codec = NULL;
  1166. while ((codec = next_codec_for_id(desc->id, codec, 1))) {
  1167. if (strcmp(codec->name, desc->name)) {
  1168. print_codecs_for_id(desc->id, 1);
  1169. break;
  1170. }
  1171. }
  1172. printf("\n");
  1173. }
  1174. av_free(codecs);
  1175. return 0;
  1176. }
  1177. static void print_codecs(int encoder)
  1178. {
  1179. const AVCodecDescriptor **codecs;
  1180. unsigned i, nb_codecs = get_codecs_sorted(&codecs);
  1181. printf("%s:\n"
  1182. " V..... = Video\n"
  1183. " A..... = Audio\n"
  1184. " S..... = Subtitle\n"
  1185. " .F.... = Frame-level multithreading\n"
  1186. " ..S... = Slice-level multithreading\n"
  1187. " ...X.. = Codec is experimental\n"
  1188. " ....B. = Supports draw_horiz_band\n"
  1189. " .....D = Supports direct rendering method 1\n"
  1190. " ------\n",
  1191. encoder ? "Encoders" : "Decoders");
  1192. for (i = 0; i < nb_codecs; i++) {
  1193. const AVCodecDescriptor *desc = codecs[i];
  1194. const AVCodec *codec = NULL;
  1195. while ((codec = next_codec_for_id(desc->id, codec, encoder))) {
  1196. printf(" %c", get_media_type_char(desc->type));
  1197. printf((codec->capabilities & CODEC_CAP_FRAME_THREADS) ? "F" : ".");
  1198. printf((codec->capabilities & CODEC_CAP_SLICE_THREADS) ? "S" : ".");
  1199. printf((codec->capabilities & CODEC_CAP_EXPERIMENTAL) ? "X" : ".");
  1200. printf((codec->capabilities & CODEC_CAP_DRAW_HORIZ_BAND)?"B" : ".");
  1201. printf((codec->capabilities & CODEC_CAP_DR1) ? "D" : ".");
  1202. printf(" %-20s %s", codec->name, codec->long_name ? codec->long_name : "");
  1203. if (strcmp(codec->name, desc->name))
  1204. printf(" (codec %s)", desc->name);
  1205. printf("\n");
  1206. }
  1207. }
  1208. av_free(codecs);
  1209. }
  1210. int show_decoders(void *optctx, const char *opt, const char *arg)
  1211. {
  1212. print_codecs(0);
  1213. return 0;
  1214. }
  1215. int show_encoders(void *optctx, const char *opt, const char *arg)
  1216. {
  1217. print_codecs(1);
  1218. return 0;
  1219. }
  1220. int show_bsfs(void *optctx, const char *opt, const char *arg)
  1221. {
  1222. AVBitStreamFilter *bsf = NULL;
  1223. printf("Bitstream filters:\n");
  1224. while ((bsf = av_bitstream_filter_next(bsf)))
  1225. printf("%s\n", bsf->name);
  1226. printf("\n");
  1227. return 0;
  1228. }
  1229. int show_protocols(void *optctx, const char *opt, const char *arg)
  1230. {
  1231. void *opaque = NULL;
  1232. const char *name;
  1233. printf("Supported file protocols:\n"
  1234. "Input:\n");
  1235. while ((name = avio_enum_protocols(&opaque, 0)))
  1236. printf("%s\n", name);
  1237. printf("Output:\n");
  1238. while ((name = avio_enum_protocols(&opaque, 1)))
  1239. printf("%s\n", name);
  1240. return 0;
  1241. }
  1242. int show_filters(void *optctx, const char *opt, const char *arg)
  1243. {
  1244. AVFilter av_unused(**filter) = NULL;
  1245. char descr[64], *descr_cur;
  1246. int i, j;
  1247. const AVFilterPad *pad;
  1248. printf("Filters:\n");
  1249. #if CONFIG_AVFILTER
  1250. while ((filter = av_filter_next(filter)) && *filter) {
  1251. descr_cur = descr;
  1252. for (i = 0; i < 2; i++) {
  1253. if (i) {
  1254. *(descr_cur++) = '-';
  1255. *(descr_cur++) = '>';
  1256. }
  1257. pad = i ? (*filter)->outputs : (*filter)->inputs;
  1258. for (j = 0; pad && pad[j].name; j++) {
  1259. if (descr_cur >= descr + sizeof(descr) - 4)
  1260. break;
  1261. *(descr_cur++) = get_media_type_char(pad[j].type);
  1262. }
  1263. if (!j)
  1264. *(descr_cur++) = '|';
  1265. }
  1266. *descr_cur = 0;
  1267. printf("%-16s %-10s %s\n", (*filter)->name, descr, (*filter)->description);
  1268. }
  1269. #endif
  1270. return 0;
  1271. }
  1272. int show_pix_fmts(void *optctx, const char *opt, const char *arg)
  1273. {
  1274. const AVPixFmtDescriptor *pix_desc = NULL;
  1275. printf("Pixel formats:\n"
  1276. "I.... = Supported Input format for conversion\n"
  1277. ".O... = Supported Output format for conversion\n"
  1278. "..H.. = Hardware accelerated format\n"
  1279. "...P. = Paletted format\n"
  1280. "....B = Bitstream format\n"
  1281. "FLAGS NAME NB_COMPONENTS BITS_PER_PIXEL\n"
  1282. "-----\n");
  1283. #if !CONFIG_SWSCALE
  1284. # define sws_isSupportedInput(x) 0
  1285. # define sws_isSupportedOutput(x) 0
  1286. #endif
  1287. while ((pix_desc = av_pix_fmt_desc_next(pix_desc))) {
  1288. enum AVPixelFormat pix_fmt = av_pix_fmt_desc_get_id(pix_desc);
  1289. printf("%c%c%c%c%c %-16s %d %2d\n",
  1290. sws_isSupportedInput (pix_fmt) ? 'I' : '.',
  1291. sws_isSupportedOutput(pix_fmt) ? 'O' : '.',
  1292. pix_desc->flags & PIX_FMT_HWACCEL ? 'H' : '.',
  1293. pix_desc->flags & PIX_FMT_PAL ? 'P' : '.',
  1294. pix_desc->flags & PIX_FMT_BITSTREAM ? 'B' : '.',
  1295. pix_desc->name,
  1296. pix_desc->nb_components,
  1297. av_get_bits_per_pixel(pix_desc));
  1298. }
  1299. return 0;
  1300. }
  1301. int show_layouts(void *optctx, const char *opt, const char *arg)
  1302. {
  1303. int i = 0;
  1304. uint64_t layout, j;
  1305. const char *name, *descr;
  1306. printf("Individual channels:\n"
  1307. "NAME DESCRIPTION\n");
  1308. for (i = 0; i < 63; i++) {
  1309. name = av_get_channel_name((uint64_t)1 << i);
  1310. if (!name)
  1311. continue;
  1312. descr = av_get_channel_description((uint64_t)1 << i);
  1313. printf("%-12s%s\n", name, descr);
  1314. }
  1315. printf("\nStandard channel layouts:\n"
  1316. "NAME DECOMPOSITION\n");
  1317. for (i = 0; !av_get_standard_channel_layout(i, &layout, &name); i++) {
  1318. if (name) {
  1319. printf("%-12s", name);
  1320. for (j = 1; j; j <<= 1)
  1321. if ((layout & j))
  1322. printf("%s%s", (layout & (j - 1)) ? "+" : "", av_get_channel_name(j));
  1323. printf("\n");
  1324. }
  1325. }
  1326. return 0;
  1327. }
  1328. int show_sample_fmts(void *optctx, const char *opt, const char *arg)
  1329. {
  1330. int i;
  1331. char fmt_str[128];
  1332. for (i = -1; i < AV_SAMPLE_FMT_NB; i++)
  1333. printf("%s\n", av_get_sample_fmt_string(fmt_str, sizeof(fmt_str), i));
  1334. return 0;
  1335. }
  1336. static void show_help_codec(const char *name, int encoder)
  1337. {
  1338. const AVCodecDescriptor *desc;
  1339. const AVCodec *codec;
  1340. if (!name) {
  1341. av_log(NULL, AV_LOG_ERROR, "No codec name specified.\n");
  1342. return;
  1343. }
  1344. codec = encoder ? avcodec_find_encoder_by_name(name) :
  1345. avcodec_find_decoder_by_name(name);
  1346. if (codec)
  1347. print_codec(codec);
  1348. else if ((desc = avcodec_descriptor_get_by_name(name))) {
  1349. int printed = 0;
  1350. while ((codec = next_codec_for_id(desc->id, codec, encoder))) {
  1351. printed = 1;
  1352. print_codec(codec);
  1353. }
  1354. if (!printed) {
  1355. av_log(NULL, AV_LOG_ERROR, "Codec '%s' is known to FFmpeg, "
  1356. "but no %s for it are available. FFmpeg might need to be "
  1357. "recompiled with additional external libraries.\n",
  1358. name, encoder ? "encoders" : "decoders");
  1359. }
  1360. } else {
  1361. av_log(NULL, AV_LOG_ERROR, "Codec '%s' is not recognized by FFmpeg.\n",
  1362. name);
  1363. }
  1364. }
  1365. static void show_help_demuxer(const char *name)
  1366. {
  1367. const AVInputFormat *fmt = av_find_input_format(name);
  1368. if (!fmt) {
  1369. av_log(NULL, AV_LOG_ERROR, "Unknown format '%s'.\n", name);
  1370. return;
  1371. }
  1372. printf("Demuxer %s [%s]:\n", fmt->name, fmt->long_name);
  1373. if (fmt->extensions)
  1374. printf(" Common extensions: %s.\n", fmt->extensions);
  1375. if (fmt->priv_class)
  1376. show_help_children(fmt->priv_class, AV_OPT_FLAG_DECODING_PARAM);
  1377. }
  1378. static void show_help_muxer(const char *name)
  1379. {
  1380. const AVCodecDescriptor *desc;
  1381. const AVOutputFormat *fmt = av_guess_format(name, NULL, NULL);
  1382. if (!fmt) {
  1383. av_log(NULL, AV_LOG_ERROR, "Unknown format '%s'.\n", name);
  1384. return;
  1385. }
  1386. printf("Muxer %s [%s]:\n", fmt->name, fmt->long_name);
  1387. if (fmt->extensions)
  1388. printf(" Common extensions: %s.\n", fmt->extensions);
  1389. if (fmt->mime_type)
  1390. printf(" Mime type: %s.\n", fmt->mime_type);
  1391. if (fmt->video_codec != AV_CODEC_ID_NONE &&
  1392. (desc = avcodec_descriptor_get(fmt->video_codec))) {
  1393. printf(" Default video codec: %s.\n", desc->name);
  1394. }
  1395. if (fmt->audio_codec != AV_CODEC_ID_NONE &&
  1396. (desc = avcodec_descriptor_get(fmt->audio_codec))) {
  1397. printf(" Default audio codec: %s.\n", desc->name);
  1398. }
  1399. if (fmt->subtitle_codec != AV_CODEC_ID_NONE &&
  1400. (desc = avcodec_descriptor_get(fmt->subtitle_codec))) {
  1401. printf(" Default subtitle codec: %s.\n", desc->name);
  1402. }
  1403. if (fmt->priv_class)
  1404. show_help_children(fmt->priv_class, AV_OPT_FLAG_ENCODING_PARAM);
  1405. }
  1406. int show_help(void *optctx, const char *opt, const char *arg)
  1407. {
  1408. char *topic, *par;
  1409. av_log_set_callback(log_callback_help);
  1410. topic = av_strdup(arg ? arg : "");
  1411. par = strchr(topic, '=');
  1412. if (par)
  1413. *par++ = 0;
  1414. if (!*topic) {
  1415. show_help_default(topic, par);
  1416. } else if (!strcmp(topic, "decoder")) {
  1417. show_help_codec(par, 0);
  1418. } else if (!strcmp(topic, "encoder")) {
  1419. show_help_codec(par, 1);
  1420. } else if (!strcmp(topic, "demuxer")) {
  1421. show_help_demuxer(par);
  1422. } else if (!strcmp(topic, "muxer")) {
  1423. show_help_muxer(par);
  1424. } else {
  1425. show_help_default(topic, par);
  1426. }
  1427. av_freep(&topic);
  1428. return 0;
  1429. }
  1430. int read_yesno(void)
  1431. {
  1432. int c = getchar();
  1433. int yesno = (av_toupper(c) == 'Y');
  1434. while (c != '\n' && c != EOF)
  1435. c = getchar();
  1436. return yesno;
  1437. }
  1438. int cmdutils_read_file(const char *filename, char **bufptr, size_t *size)
  1439. {
  1440. int ret;
  1441. FILE *f = fopen(filename, "rb");
  1442. if (!f) {
  1443. av_log(NULL, AV_LOG_ERROR, "Cannot read file '%s': %s\n", filename,
  1444. strerror(errno));
  1445. return AVERROR(errno);
  1446. }
  1447. fseek(f, 0, SEEK_END);
  1448. *size = ftell(f);
  1449. fseek(f, 0, SEEK_SET);
  1450. if (*size == (size_t)-1) {
  1451. av_log(NULL, AV_LOG_ERROR, "IO error: %s\n", strerror(errno));
  1452. fclose(f);
  1453. return AVERROR(errno);
  1454. }
  1455. *bufptr = av_malloc(*size + 1);
  1456. if (!*bufptr) {
  1457. av_log(NULL, AV_LOG_ERROR, "Could not allocate file buffer\n");
  1458. fclose(f);
  1459. return AVERROR(ENOMEM);
  1460. }
  1461. ret = fread(*bufptr, 1, *size, f);
  1462. if (ret < *size) {
  1463. av_free(*bufptr);
  1464. if (ferror(f)) {
  1465. av_log(NULL, AV_LOG_ERROR, "Error while reading file '%s': %s\n",
  1466. filename, strerror(errno));
  1467. ret = AVERROR(errno);
  1468. } else
  1469. ret = AVERROR_EOF;
  1470. } else {
  1471. ret = 0;
  1472. (*bufptr)[(*size)++] = '\0';
  1473. }
  1474. fclose(f);
  1475. return ret;
  1476. }
  1477. FILE *get_preset_file(char *filename, size_t filename_size,
  1478. const char *preset_name, int is_path,
  1479. const char *codec_name)
  1480. {
  1481. FILE *f = NULL;
  1482. int i;
  1483. const char *base[3] = { getenv("FFMPEG_DATADIR"),
  1484. getenv("HOME"),
  1485. FFMPEG_DATADIR, };
  1486. if (is_path) {
  1487. av_strlcpy(filename, preset_name, filename_size);
  1488. f = fopen(filename, "r");
  1489. } else {
  1490. #ifdef _WIN32
  1491. char datadir[MAX_PATH], *ls;
  1492. base[2] = NULL;
  1493. if (GetModuleFileNameA(GetModuleHandleA(NULL), datadir, sizeof(datadir) - 1))
  1494. {
  1495. for (ls = datadir; ls < datadir + strlen(datadir); ls++)
  1496. if (*ls == '\\') *ls = '/';
  1497. if (ls = strrchr(datadir, '/'))
  1498. {
  1499. *ls = 0;
  1500. strncat(datadir, "/ffpresets", sizeof(datadir) - 1 - strlen(datadir));
  1501. base[2] = datadir;
  1502. }
  1503. }
  1504. #endif
  1505. for (i = 0; i < 3 && !f; i++) {
  1506. if (!base[i])
  1507. continue;
  1508. snprintf(filename, filename_size, "%s%s/%s.ffpreset", base[i],
  1509. i != 1 ? "" : "/.ffmpeg", preset_name);
  1510. f = fopen(filename, "r");
  1511. if (!f && codec_name) {
  1512. snprintf(filename, filename_size,
  1513. "%s%s/%s-%s.ffpreset",
  1514. base[i], i != 1 ? "" : "/.ffmpeg", codec_name,
  1515. preset_name);
  1516. f = fopen(filename, "r");
  1517. }
  1518. }
  1519. }
  1520. return f;
  1521. }
  1522. int check_stream_specifier(AVFormatContext *s, AVStream *st, const char *spec)
  1523. {
  1524. int ret = avformat_match_stream_specifier(s, st, spec);
  1525. if (ret < 0)
  1526. av_log(s, AV_LOG_ERROR, "Invalid stream specifier: %s.\n", spec);
  1527. return ret;
  1528. }
  1529. AVDictionary *filter_codec_opts(AVDictionary *opts, enum AVCodecID codec_id,
  1530. AVFormatContext *s, AVStream *st, AVCodec *codec)
  1531. {
  1532. AVDictionary *ret = NULL;
  1533. AVDictionaryEntry *t = NULL;
  1534. int flags = s->oformat ? AV_OPT_FLAG_ENCODING_PARAM
  1535. : AV_OPT_FLAG_DECODING_PARAM;
  1536. char prefix = 0;
  1537. const AVClass *cc = avcodec_get_class();
  1538. if (!codec)
  1539. codec = s->oformat ? avcodec_find_encoder(codec_id)
  1540. : avcodec_find_decoder(codec_id);
  1541. switch (st->codec->codec_type) {
  1542. case AVMEDIA_TYPE_VIDEO:
  1543. prefix = 'v';
  1544. flags |= AV_OPT_FLAG_VIDEO_PARAM;
  1545. break;
  1546. case AVMEDIA_TYPE_AUDIO:
  1547. prefix = 'a';
  1548. flags |= AV_OPT_FLAG_AUDIO_PARAM;
  1549. break;
  1550. case AVMEDIA_TYPE_SUBTITLE:
  1551. prefix = 's';
  1552. flags |= AV_OPT_FLAG_SUBTITLE_PARAM;
  1553. break;
  1554. }
  1555. while (t = av_dict_get(opts, "", t, AV_DICT_IGNORE_SUFFIX)) {
  1556. char *p = strchr(t->key, ':');
  1557. /* check stream specification in opt name */
  1558. if (p)
  1559. switch (check_stream_specifier(s, st, p + 1)) {
  1560. case 1: *p = 0; break;
  1561. case 0: continue;
  1562. default: return NULL;
  1563. }
  1564. if (av_opt_find(&cc, t->key, NULL, flags, AV_OPT_SEARCH_FAKE_OBJ) ||
  1565. (codec && codec->priv_class &&
  1566. av_opt_find(&codec->priv_class, t->key, NULL, flags,
  1567. AV_OPT_SEARCH_FAKE_OBJ)))
  1568. av_dict_set(&ret, t->key, t->value, 0);
  1569. else if (t->key[0] == prefix &&
  1570. av_opt_find(&cc, t->key + 1, NULL, flags,
  1571. AV_OPT_SEARCH_FAKE_OBJ))
  1572. av_dict_set(&ret, t->key + 1, t->value, 0);
  1573. if (p)
  1574. *p = ':';
  1575. }
  1576. return ret;
  1577. }
  1578. AVDictionary **setup_find_stream_info_opts(AVFormatContext *s,
  1579. AVDictionary *codec_opts)
  1580. {
  1581. int i;
  1582. AVDictionary **opts;
  1583. if (!s->nb_streams)
  1584. return NULL;
  1585. opts = av_mallocz(s->nb_streams * sizeof(*opts));
  1586. if (!opts) {
  1587. av_log(NULL, AV_LOG_ERROR,
  1588. "Could not alloc memory for stream options.\n");
  1589. return NULL;
  1590. }
  1591. for (i = 0; i < s->nb_streams; i++)
  1592. opts[i] = filter_codec_opts(codec_opts, s->streams[i]->codec->codec_id,
  1593. s, s->streams[i], NULL);
  1594. return opts;
  1595. }
  1596. void *grow_array(void *array, int elem_size, int *size, int new_size)
  1597. {
  1598. if (new_size >= INT_MAX / elem_size) {
  1599. av_log(NULL, AV_LOG_ERROR, "Array too big.\n");
  1600. exit(1);
  1601. }
  1602. if (*size < new_size) {
  1603. uint8_t *tmp = av_realloc(array, new_size*elem_size);
  1604. if (!tmp) {
  1605. av_log(NULL, AV_LOG_ERROR, "Could not alloc buffer.\n");
  1606. exit(1);
  1607. }
  1608. memset(tmp + *size*elem_size, 0, (new_size-*size) * elem_size);
  1609. *size = new_size;
  1610. return tmp;
  1611. }
  1612. return array;
  1613. }