cmdutils.c 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155
  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 <stdint.h>
  23. #include <stdlib.h>
  24. #include <errno.h>
  25. #include <math.h>
  26. /* Include only the enabled headers since some compilers (namely, Sun
  27. Studio) will not omit unused inline functions and create undefined
  28. references to libraries that are not being built. */
  29. #include "config.h"
  30. #include "compat/va_copy.h"
  31. #include "libavformat/avformat.h"
  32. #include "libswscale/swscale.h"
  33. #include "libswscale/version.h"
  34. #include "libswresample/swresample.h"
  35. #include "libavutil/avassert.h"
  36. #include "libavutil/avstring.h"
  37. #include "libavutil/bprint.h"
  38. #include "libavutil/channel_layout.h"
  39. #include "libavutil/display.h"
  40. #include "libavutil/getenv_utf8.h"
  41. #include "libavutil/mathematics.h"
  42. #include "libavutil/imgutils.h"
  43. #include "libavutil/libm.h"
  44. #include "libavutil/parseutils.h"
  45. #include "libavutil/eval.h"
  46. #include "libavutil/dict.h"
  47. #include "libavutil/opt.h"
  48. #include "cmdutils.h"
  49. #include "fopen_utf8.h"
  50. #include "opt_common.h"
  51. #ifdef _WIN32
  52. #include <windows.h>
  53. #include "compat/w32dlfcn.h"
  54. #endif
  55. AVDictionary *sws_dict;
  56. AVDictionary *swr_opts;
  57. AVDictionary *format_opts, *codec_opts;
  58. int hide_banner = 0;
  59. void uninit_opts(void)
  60. {
  61. av_dict_free(&swr_opts);
  62. av_dict_free(&sws_dict);
  63. av_dict_free(&format_opts);
  64. av_dict_free(&codec_opts);
  65. }
  66. void log_callback_help(void *ptr, int level, const char *fmt, va_list vl)
  67. {
  68. vfprintf(stdout, fmt, vl);
  69. }
  70. void init_dynload(void)
  71. {
  72. #if HAVE_SETDLLDIRECTORY && defined(_WIN32)
  73. /* Calling SetDllDirectory with the empty string (but not NULL) removes the
  74. * current working directory from the DLL search path as a security pre-caution. */
  75. SetDllDirectory("");
  76. #endif
  77. }
  78. int parse_number(const char *context, const char *numstr, enum OptionType type,
  79. double min, double max, double *dst)
  80. {
  81. char *tail;
  82. const char *error;
  83. double d = av_strtod(numstr, &tail);
  84. if (*tail)
  85. error = "Expected number for %s but found: %s\n";
  86. else if (d < min || d > max)
  87. error = "The value for %s was %s which is not within %f - %f\n";
  88. else if (type == OPT_TYPE_INT64 && (int64_t)d != d)
  89. error = "Expected int64 for %s but found %s\n";
  90. else if (type == OPT_TYPE_INT && (int)d != d)
  91. error = "Expected int for %s but found %s\n";
  92. else {
  93. *dst = d;
  94. return 0;
  95. }
  96. av_log(NULL, AV_LOG_FATAL, error, context, numstr, min, max);
  97. return AVERROR(EINVAL);
  98. }
  99. void show_help_options(const OptionDef *options, const char *msg, int req_flags,
  100. int rej_flags)
  101. {
  102. const OptionDef *po;
  103. int first;
  104. first = 1;
  105. for (po = options; po->name; po++) {
  106. char buf[128];
  107. if (((po->flags & req_flags) != req_flags) ||
  108. (po->flags & rej_flags))
  109. continue;
  110. if (first) {
  111. printf("%s\n", msg);
  112. first = 0;
  113. }
  114. av_strlcpy(buf, po->name, sizeof(buf));
  115. if (po->flags & OPT_FLAG_PERSTREAM)
  116. av_strlcat(buf, "[:<stream_spec>]", sizeof(buf));
  117. else if (po->flags & OPT_FLAG_SPEC)
  118. av_strlcat(buf, "[:<spec>]", sizeof(buf));
  119. if (po->argname)
  120. av_strlcatf(buf, sizeof(buf), " <%s>", po->argname);
  121. printf("-%-17s %s\n", buf, po->help);
  122. }
  123. printf("\n");
  124. }
  125. void show_help_children(const AVClass *class, int flags)
  126. {
  127. void *iter = NULL;
  128. const AVClass *child;
  129. if (class->option) {
  130. av_opt_show2(&class, NULL, flags, 0);
  131. printf("\n");
  132. }
  133. while (child = av_opt_child_class_iterate(class, &iter))
  134. show_help_children(child, flags);
  135. }
  136. static const OptionDef *find_option(const OptionDef *po, const char *name)
  137. {
  138. if (*name == '/')
  139. name++;
  140. while (po->name) {
  141. const char *end;
  142. if (av_strstart(name, po->name, &end) && (!*end || *end == ':'))
  143. break;
  144. po++;
  145. }
  146. return po;
  147. }
  148. /* _WIN32 means using the windows libc - cygwin doesn't define that
  149. * by default. HAVE_COMMANDLINETOARGVW is true on cygwin, while
  150. * it doesn't provide the actual command line via GetCommandLineW(). */
  151. #if HAVE_COMMANDLINETOARGVW && defined(_WIN32)
  152. #include <shellapi.h>
  153. /* Will be leaked on exit */
  154. static char** win32_argv_utf8 = NULL;
  155. static int win32_argc = 0;
  156. /**
  157. * Prepare command line arguments for executable.
  158. * For Windows - perform wide-char to UTF-8 conversion.
  159. * Input arguments should be main() function arguments.
  160. * @param argc_ptr Arguments number (including executable)
  161. * @param argv_ptr Arguments list.
  162. */
  163. static void prepare_app_arguments(int *argc_ptr, char ***argv_ptr)
  164. {
  165. char *argstr_flat;
  166. wchar_t **argv_w;
  167. int i, buffsize = 0, offset = 0;
  168. if (win32_argv_utf8) {
  169. *argc_ptr = win32_argc;
  170. *argv_ptr = win32_argv_utf8;
  171. return;
  172. }
  173. win32_argc = 0;
  174. argv_w = CommandLineToArgvW(GetCommandLineW(), &win32_argc);
  175. if (win32_argc <= 0 || !argv_w)
  176. return;
  177. /* determine the UTF-8 buffer size (including NULL-termination symbols) */
  178. for (i = 0; i < win32_argc; i++)
  179. buffsize += WideCharToMultiByte(CP_UTF8, 0, argv_w[i], -1,
  180. NULL, 0, NULL, NULL);
  181. win32_argv_utf8 = av_mallocz(sizeof(char *) * (win32_argc + 1) + buffsize);
  182. argstr_flat = (char *)win32_argv_utf8 + sizeof(char *) * (win32_argc + 1);
  183. if (!win32_argv_utf8) {
  184. LocalFree(argv_w);
  185. return;
  186. }
  187. for (i = 0; i < win32_argc; i++) {
  188. win32_argv_utf8[i] = &argstr_flat[offset];
  189. offset += WideCharToMultiByte(CP_UTF8, 0, argv_w[i], -1,
  190. &argstr_flat[offset],
  191. buffsize - offset, NULL, NULL);
  192. }
  193. win32_argv_utf8[i] = NULL;
  194. LocalFree(argv_w);
  195. *argc_ptr = win32_argc;
  196. *argv_ptr = win32_argv_utf8;
  197. }
  198. #else
  199. static inline void prepare_app_arguments(int *argc_ptr, char ***argv_ptr)
  200. {
  201. /* nothing to do */
  202. }
  203. #endif /* HAVE_COMMANDLINETOARGVW */
  204. static int opt_has_arg(const OptionDef *o)
  205. {
  206. if (o->type == OPT_TYPE_BOOL)
  207. return 0;
  208. if (o->type == OPT_TYPE_FUNC)
  209. return !!(o->flags & OPT_FUNC_ARG);
  210. return 1;
  211. }
  212. static int write_option(void *optctx, const OptionDef *po, const char *opt,
  213. const char *arg, const OptionDef *defs)
  214. {
  215. /* new-style options contain an offset into optctx, old-style address of
  216. * a global var*/
  217. void *dst = po->flags & OPT_FLAG_OFFSET ?
  218. (uint8_t *)optctx + po->u.off : po->u.dst_ptr;
  219. char *arg_allocated = NULL;
  220. SpecifierOptList *sol = NULL;
  221. double num;
  222. int ret = 0;
  223. if (*opt == '/') {
  224. opt++;
  225. if (po->type == OPT_TYPE_BOOL) {
  226. av_log(NULL, AV_LOG_FATAL,
  227. "Requested to load an argument from file for a bool option '%s'\n",
  228. po->name);
  229. return AVERROR(EINVAL);
  230. }
  231. arg_allocated = file_read(arg);
  232. if (!arg_allocated) {
  233. av_log(NULL, AV_LOG_FATAL,
  234. "Error reading the value for option '%s' from file: %s\n",
  235. opt, arg);
  236. return AVERROR(EINVAL);
  237. }
  238. arg = arg_allocated;
  239. }
  240. if (po->flags & OPT_FLAG_SPEC) {
  241. char *p = strchr(opt, ':');
  242. char *str;
  243. sol = dst;
  244. ret = GROW_ARRAY(sol->opt, sol->nb_opt);
  245. if (ret < 0)
  246. goto finish;
  247. str = av_strdup(p ? p + 1 : "");
  248. if (!str) {
  249. ret = AVERROR(ENOMEM);
  250. goto finish;
  251. }
  252. sol->opt[sol->nb_opt - 1].specifier = str;
  253. dst = &sol->opt[sol->nb_opt - 1].u;
  254. }
  255. if (po->type == OPT_TYPE_STRING) {
  256. char *str;
  257. if (arg_allocated) {
  258. str = arg_allocated;
  259. arg_allocated = NULL;
  260. } else
  261. str = av_strdup(arg);
  262. av_freep(dst);
  263. if (!str) {
  264. ret = AVERROR(ENOMEM);
  265. goto finish;
  266. }
  267. *(char **)dst = str;
  268. } else if (po->type == OPT_TYPE_BOOL || po->type == OPT_TYPE_INT) {
  269. ret = parse_number(opt, arg, OPT_TYPE_INT64, INT_MIN, INT_MAX, &num);
  270. if (ret < 0)
  271. goto finish;
  272. *(int *)dst = num;
  273. } else if (po->type == OPT_TYPE_INT64) {
  274. ret = parse_number(opt, arg, OPT_TYPE_INT64, INT64_MIN, INT64_MAX, &num);
  275. if (ret < 0)
  276. goto finish;
  277. *(int64_t *)dst = num;
  278. } else if (po->type == OPT_TYPE_TIME) {
  279. ret = av_parse_time(dst, arg, 1);
  280. if (ret < 0) {
  281. av_log(NULL, AV_LOG_ERROR, "Invalid duration for option %s: %s\n",
  282. opt, arg);
  283. goto finish;
  284. }
  285. } else if (po->type == OPT_TYPE_FLOAT) {
  286. ret = parse_number(opt, arg, OPT_TYPE_FLOAT, -INFINITY, INFINITY, &num);
  287. if (ret < 0)
  288. goto finish;
  289. *(float *)dst = num;
  290. } else if (po->type == OPT_TYPE_DOUBLE) {
  291. ret = parse_number(opt, arg, OPT_TYPE_DOUBLE, -INFINITY, INFINITY, &num);
  292. if (ret < 0)
  293. goto finish;
  294. *(double *)dst = num;
  295. } else {
  296. av_assert0(po->type == OPT_TYPE_FUNC && po->u.func_arg);
  297. ret = po->u.func_arg(optctx, opt, arg);
  298. if (ret < 0) {
  299. av_log(NULL, AV_LOG_ERROR,
  300. "Failed to set value '%s' for option '%s': %s\n",
  301. arg, opt, av_err2str(ret));
  302. goto finish;
  303. }
  304. }
  305. if (po->flags & OPT_EXIT) {
  306. ret = AVERROR_EXIT;
  307. goto finish;
  308. }
  309. if (sol) {
  310. sol->type = po->type;
  311. sol->opt_canon = (po->flags & OPT_HAS_CANON) ?
  312. find_option(defs, po->u1.name_canon) : po;
  313. }
  314. finish:
  315. av_freep(&arg_allocated);
  316. return ret;
  317. }
  318. int parse_option(void *optctx, const char *opt, const char *arg,
  319. const OptionDef *options)
  320. {
  321. static const OptionDef opt_avoptions = {
  322. .name = "AVOption passthrough",
  323. .type = OPT_TYPE_FUNC,
  324. .flags = OPT_FUNC_ARG,
  325. .u.func_arg = opt_default,
  326. };
  327. const OptionDef *po;
  328. int ret;
  329. po = find_option(options, opt);
  330. if (!po->name && opt[0] == 'n' && opt[1] == 'o') {
  331. /* handle 'no' bool option */
  332. po = find_option(options, opt + 2);
  333. if ((po->name && po->type == OPT_TYPE_BOOL))
  334. arg = "0";
  335. } else if (po->type == OPT_TYPE_BOOL)
  336. arg = "1";
  337. if (!po->name)
  338. po = &opt_avoptions;
  339. if (!po->name) {
  340. av_log(NULL, AV_LOG_ERROR, "Unrecognized option '%s'\n", opt);
  341. return AVERROR(EINVAL);
  342. }
  343. if (opt_has_arg(po) && !arg) {
  344. av_log(NULL, AV_LOG_ERROR, "Missing argument for option '%s'\n", opt);
  345. return AVERROR(EINVAL);
  346. }
  347. ret = write_option(optctx, po, opt, arg, options);
  348. if (ret < 0)
  349. return ret;
  350. return opt_has_arg(po);
  351. }
  352. int parse_options(void *optctx, int argc, char **argv, const OptionDef *options,
  353. int (*parse_arg_function)(void *, const char*))
  354. {
  355. const char *opt;
  356. int optindex, handleoptions = 1, ret;
  357. /* perform system-dependent conversions for arguments list */
  358. prepare_app_arguments(&argc, &argv);
  359. /* parse options */
  360. optindex = 1;
  361. while (optindex < argc) {
  362. opt = argv[optindex++];
  363. if (handleoptions && opt[0] == '-' && opt[1] != '\0') {
  364. if (opt[1] == '-' && opt[2] == '\0') {
  365. handleoptions = 0;
  366. continue;
  367. }
  368. opt++;
  369. if ((ret = parse_option(optctx, opt, argv[optindex], options)) < 0)
  370. return ret;
  371. optindex += ret;
  372. } else {
  373. if (parse_arg_function) {
  374. ret = parse_arg_function(optctx, opt);
  375. if (ret < 0)
  376. return ret;
  377. }
  378. }
  379. }
  380. return 0;
  381. }
  382. int parse_optgroup(void *optctx, OptionGroup *g, const OptionDef *defs)
  383. {
  384. int i, ret;
  385. av_log(NULL, AV_LOG_DEBUG, "Parsing a group of options: %s %s.\n",
  386. g->group_def->name, g->arg);
  387. for (i = 0; i < g->nb_opts; i++) {
  388. Option *o = &g->opts[i];
  389. if (g->group_def->flags &&
  390. !(g->group_def->flags & o->opt->flags)) {
  391. av_log(NULL, AV_LOG_ERROR, "Option %s (%s) cannot be applied to "
  392. "%s %s -- you are trying to apply an input option to an "
  393. "output file or vice versa. Move this option before the "
  394. "file it belongs to.\n", o->key, o->opt->help,
  395. g->group_def->name, g->arg);
  396. return AVERROR(EINVAL);
  397. }
  398. av_log(NULL, AV_LOG_DEBUG, "Applying option %s (%s) with argument %s.\n",
  399. o->key, o->opt->help, o->val);
  400. ret = write_option(optctx, o->opt, o->key, o->val, defs);
  401. if (ret < 0)
  402. return ret;
  403. }
  404. av_log(NULL, AV_LOG_DEBUG, "Successfully parsed a group of options.\n");
  405. return 0;
  406. }
  407. int locate_option(int argc, char **argv, const OptionDef *options,
  408. const char *optname)
  409. {
  410. const OptionDef *po;
  411. int i;
  412. for (i = 1; i < argc; i++) {
  413. const char *cur_opt = argv[i];
  414. if (*cur_opt++ != '-')
  415. continue;
  416. po = find_option(options, cur_opt);
  417. if (!po->name && cur_opt[0] == 'n' && cur_opt[1] == 'o')
  418. po = find_option(options, cur_opt + 2);
  419. if ((!po->name && !strcmp(cur_opt, optname)) ||
  420. (po->name && !strcmp(optname, po->name)))
  421. return i;
  422. if (!po->name || opt_has_arg(po))
  423. i++;
  424. }
  425. return 0;
  426. }
  427. static void dump_argument(FILE *report_file, const char *a)
  428. {
  429. const unsigned char *p;
  430. for (p = a; *p; p++)
  431. if (!((*p >= '+' && *p <= ':') || (*p >= '@' && *p <= 'Z') ||
  432. *p == '_' || (*p >= 'a' && *p <= 'z')))
  433. break;
  434. if (!*p) {
  435. fputs(a, report_file);
  436. return;
  437. }
  438. fputc('"', report_file);
  439. for (p = a; *p; p++) {
  440. if (*p == '\\' || *p == '"' || *p == '$' || *p == '`')
  441. fprintf(report_file, "\\%c", *p);
  442. else if (*p < ' ' || *p > '~')
  443. fprintf(report_file, "\\x%02x", *p);
  444. else
  445. fputc(*p, report_file);
  446. }
  447. fputc('"', report_file);
  448. }
  449. static void check_options(const OptionDef *po)
  450. {
  451. while (po->name) {
  452. if (po->flags & OPT_PERFILE)
  453. av_assert0(po->flags & (OPT_INPUT | OPT_OUTPUT | OPT_DECODER));
  454. if (po->type == OPT_TYPE_FUNC)
  455. av_assert0(!(po->flags & (OPT_FLAG_OFFSET | OPT_FLAG_SPEC)));
  456. // OPT_FUNC_ARG can only be ser for OPT_TYPE_FUNC
  457. av_assert0((po->type == OPT_TYPE_FUNC) || !(po->flags & OPT_FUNC_ARG));
  458. po++;
  459. }
  460. }
  461. void parse_loglevel(int argc, char **argv, const OptionDef *options)
  462. {
  463. int idx = locate_option(argc, argv, options, "loglevel");
  464. char *env;
  465. check_options(options);
  466. if (!idx)
  467. idx = locate_option(argc, argv, options, "v");
  468. if (idx && argv[idx + 1])
  469. opt_loglevel(NULL, "loglevel", argv[idx + 1]);
  470. idx = locate_option(argc, argv, options, "report");
  471. env = getenv_utf8("FFREPORT");
  472. if (env || idx) {
  473. FILE *report_file = NULL;
  474. init_report(env, &report_file);
  475. if (report_file) {
  476. int i;
  477. fprintf(report_file, "Command line:\n");
  478. for (i = 0; i < argc; i++) {
  479. dump_argument(report_file, argv[i]);
  480. fputc(i < argc - 1 ? ' ' : '\n', report_file);
  481. }
  482. fflush(report_file);
  483. }
  484. }
  485. freeenv_utf8(env);
  486. idx = locate_option(argc, argv, options, "hide_banner");
  487. if (idx)
  488. hide_banner = 1;
  489. }
  490. static const AVOption *opt_find(void *obj, const char *name, const char *unit,
  491. int opt_flags, int search_flags)
  492. {
  493. const AVOption *o = av_opt_find(obj, name, unit, opt_flags, search_flags);
  494. if(o && !o->flags)
  495. return NULL;
  496. return o;
  497. }
  498. #define FLAGS (o->type == AV_OPT_TYPE_FLAGS && (arg[0]=='-' || arg[0]=='+')) ? AV_DICT_APPEND : 0
  499. int opt_default(void *optctx, const char *opt, const char *arg)
  500. {
  501. const AVOption *o;
  502. int consumed = 0;
  503. char opt_stripped[128];
  504. const char *p;
  505. const AVClass *cc = avcodec_get_class(), *fc = avformat_get_class();
  506. #if CONFIG_SWSCALE
  507. const AVClass *sc = sws_get_class();
  508. #endif
  509. #if CONFIG_SWRESAMPLE
  510. const AVClass *swr_class = swr_get_class();
  511. #endif
  512. if (!strcmp(opt, "debug") || !strcmp(opt, "fdebug"))
  513. av_log_set_level(AV_LOG_DEBUG);
  514. if (!(p = strchr(opt, ':')))
  515. p = opt + strlen(opt);
  516. av_strlcpy(opt_stripped, opt, FFMIN(sizeof(opt_stripped), p - opt + 1));
  517. if ((o = opt_find(&cc, opt_stripped, NULL, 0,
  518. AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ)) ||
  519. ((opt[0] == 'v' || opt[0] == 'a' || opt[0] == 's') &&
  520. (o = opt_find(&cc, opt + 1, NULL, 0, AV_OPT_SEARCH_FAKE_OBJ)))) {
  521. av_dict_set(&codec_opts, opt, arg, FLAGS);
  522. consumed = 1;
  523. }
  524. if ((o = opt_find(&fc, opt, NULL, 0,
  525. AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ))) {
  526. av_dict_set(&format_opts, opt, arg, FLAGS);
  527. if (consumed)
  528. av_log(NULL, AV_LOG_VERBOSE, "Routing option %s to both codec and muxer layer\n", opt);
  529. consumed = 1;
  530. }
  531. #if CONFIG_SWSCALE
  532. if (!consumed && (o = opt_find(&sc, opt, NULL, 0,
  533. AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ))) {
  534. if (!strcmp(opt, "srcw") || !strcmp(opt, "srch") ||
  535. !strcmp(opt, "dstw") || !strcmp(opt, "dsth") ||
  536. !strcmp(opt, "src_format") || !strcmp(opt, "dst_format")) {
  537. av_log(NULL, AV_LOG_ERROR, "Directly using swscale dimensions/format options is not supported, please use the -s or -pix_fmt options\n");
  538. return AVERROR(EINVAL);
  539. }
  540. av_dict_set(&sws_dict, opt, arg, FLAGS);
  541. consumed = 1;
  542. }
  543. #else
  544. if (!consumed && !strcmp(opt, "sws_flags")) {
  545. av_log(NULL, AV_LOG_WARNING, "Ignoring %s %s, due to disabled swscale\n", opt, arg);
  546. consumed = 1;
  547. }
  548. #endif
  549. #if CONFIG_SWRESAMPLE
  550. if (!consumed && (o=opt_find(&swr_class, opt, NULL, 0,
  551. AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ))) {
  552. av_dict_set(&swr_opts, opt, arg, FLAGS);
  553. consumed = 1;
  554. }
  555. #endif
  556. if (consumed)
  557. return 0;
  558. return AVERROR_OPTION_NOT_FOUND;
  559. }
  560. /*
  561. * Check whether given option is a group separator.
  562. *
  563. * @return index of the group definition that matched or -1 if none
  564. */
  565. static int match_group_separator(const OptionGroupDef *groups, int nb_groups,
  566. const char *opt)
  567. {
  568. int i;
  569. for (i = 0; i < nb_groups; i++) {
  570. const OptionGroupDef *p = &groups[i];
  571. if (p->sep && !strcmp(p->sep, opt))
  572. return i;
  573. }
  574. return -1;
  575. }
  576. /*
  577. * Finish parsing an option group.
  578. *
  579. * @param group_idx which group definition should this group belong to
  580. * @param arg argument of the group delimiting option
  581. */
  582. static int finish_group(OptionParseContext *octx, int group_idx,
  583. const char *arg)
  584. {
  585. OptionGroupList *l = &octx->groups[group_idx];
  586. OptionGroup *g;
  587. int ret;
  588. ret = GROW_ARRAY(l->groups, l->nb_groups);
  589. if (ret < 0)
  590. return ret;
  591. g = &l->groups[l->nb_groups - 1];
  592. *g = octx->cur_group;
  593. g->arg = arg;
  594. g->group_def = l->group_def;
  595. g->sws_dict = sws_dict;
  596. g->swr_opts = swr_opts;
  597. g->codec_opts = codec_opts;
  598. g->format_opts = format_opts;
  599. codec_opts = NULL;
  600. format_opts = NULL;
  601. sws_dict = NULL;
  602. swr_opts = NULL;
  603. memset(&octx->cur_group, 0, sizeof(octx->cur_group));
  604. return ret;
  605. }
  606. /*
  607. * Add an option instance to currently parsed group.
  608. */
  609. static int add_opt(OptionParseContext *octx, const OptionDef *opt,
  610. const char *key, const char *val)
  611. {
  612. int global = !(opt->flags & OPT_PERFILE);
  613. OptionGroup *g = global ? &octx->global_opts : &octx->cur_group;
  614. int ret;
  615. ret = GROW_ARRAY(g->opts, g->nb_opts);
  616. if (ret < 0)
  617. return ret;
  618. g->opts[g->nb_opts - 1].opt = opt;
  619. g->opts[g->nb_opts - 1].key = key;
  620. g->opts[g->nb_opts - 1].val = val;
  621. return 0;
  622. }
  623. static int init_parse_context(OptionParseContext *octx,
  624. const OptionGroupDef *groups, int nb_groups)
  625. {
  626. static const OptionGroupDef global_group = { "global" };
  627. int i;
  628. memset(octx, 0, sizeof(*octx));
  629. octx->groups = av_calloc(nb_groups, sizeof(*octx->groups));
  630. if (!octx->groups)
  631. return AVERROR(ENOMEM);
  632. octx->nb_groups = nb_groups;
  633. for (i = 0; i < octx->nb_groups; i++)
  634. octx->groups[i].group_def = &groups[i];
  635. octx->global_opts.group_def = &global_group;
  636. octx->global_opts.arg = "";
  637. return 0;
  638. }
  639. void uninit_parse_context(OptionParseContext *octx)
  640. {
  641. int i, j;
  642. for (i = 0; i < octx->nb_groups; i++) {
  643. OptionGroupList *l = &octx->groups[i];
  644. for (j = 0; j < l->nb_groups; j++) {
  645. av_freep(&l->groups[j].opts);
  646. av_dict_free(&l->groups[j].codec_opts);
  647. av_dict_free(&l->groups[j].format_opts);
  648. av_dict_free(&l->groups[j].sws_dict);
  649. av_dict_free(&l->groups[j].swr_opts);
  650. }
  651. av_freep(&l->groups);
  652. }
  653. av_freep(&octx->groups);
  654. av_freep(&octx->cur_group.opts);
  655. av_freep(&octx->global_opts.opts);
  656. uninit_opts();
  657. }
  658. int split_commandline(OptionParseContext *octx, int argc, char *argv[],
  659. const OptionDef *options,
  660. const OptionGroupDef *groups, int nb_groups)
  661. {
  662. int ret;
  663. int optindex = 1;
  664. int dashdash = -2;
  665. /* perform system-dependent conversions for arguments list */
  666. prepare_app_arguments(&argc, &argv);
  667. ret = init_parse_context(octx, groups, nb_groups);
  668. if (ret < 0)
  669. return ret;
  670. av_log(NULL, AV_LOG_DEBUG, "Splitting the commandline.\n");
  671. while (optindex < argc) {
  672. const char *opt = argv[optindex++], *arg;
  673. const OptionDef *po;
  674. int ret, group_idx;
  675. av_log(NULL, AV_LOG_DEBUG, "Reading option '%s' ...", opt);
  676. if (opt[0] == '-' && opt[1] == '-' && !opt[2]) {
  677. dashdash = optindex;
  678. continue;
  679. }
  680. /* unnamed group separators, e.g. output filename */
  681. if (opt[0] != '-' || !opt[1] || dashdash+1 == optindex) {
  682. ret = finish_group(octx, 0, opt);
  683. if (ret < 0)
  684. return ret;
  685. av_log(NULL, AV_LOG_DEBUG, " matched as %s.\n", groups[0].name);
  686. continue;
  687. }
  688. opt++;
  689. #define GET_ARG(arg) \
  690. do { \
  691. arg = argv[optindex++]; \
  692. if (!arg) { \
  693. av_log(NULL, AV_LOG_ERROR, "Missing argument for option '%s'.\n", opt);\
  694. return AVERROR(EINVAL); \
  695. } \
  696. } while (0)
  697. /* named group separators, e.g. -i */
  698. group_idx = match_group_separator(groups, nb_groups, opt);
  699. if (group_idx >= 0) {
  700. GET_ARG(arg);
  701. ret = finish_group(octx, group_idx, arg);
  702. if (ret < 0)
  703. return ret;
  704. av_log(NULL, AV_LOG_DEBUG, " matched as %s with argument '%s'.\n",
  705. groups[group_idx].name, arg);
  706. continue;
  707. }
  708. /* normal options */
  709. po = find_option(options, opt);
  710. if (po->name) {
  711. if (po->flags & OPT_EXIT) {
  712. /* optional argument, e.g. -h */
  713. arg = argv[optindex++];
  714. } else if (opt_has_arg(po)) {
  715. GET_ARG(arg);
  716. } else {
  717. arg = "1";
  718. }
  719. ret = add_opt(octx, po, opt, arg);
  720. if (ret < 0)
  721. return ret;
  722. av_log(NULL, AV_LOG_DEBUG, " matched as option '%s' (%s) with "
  723. "argument '%s'.\n", po->name, po->help, arg);
  724. continue;
  725. }
  726. /* AVOptions */
  727. if (argv[optindex]) {
  728. ret = opt_default(NULL, opt, argv[optindex]);
  729. if (ret >= 0) {
  730. av_log(NULL, AV_LOG_DEBUG, " matched as AVOption '%s' with "
  731. "argument '%s'.\n", opt, argv[optindex]);
  732. optindex++;
  733. continue;
  734. } else if (ret != AVERROR_OPTION_NOT_FOUND) {
  735. av_log(NULL, AV_LOG_ERROR, "Error parsing option '%s' "
  736. "with argument '%s'.\n", opt, argv[optindex]);
  737. return ret;
  738. }
  739. }
  740. /* boolean -nofoo options */
  741. if (opt[0] == 'n' && opt[1] == 'o' &&
  742. (po = find_option(options, opt + 2)) &&
  743. po->name && po->type == OPT_TYPE_BOOL) {
  744. ret = add_opt(octx, po, opt, "0");
  745. if (ret < 0)
  746. return ret;
  747. av_log(NULL, AV_LOG_DEBUG, " matched as option '%s' (%s) with "
  748. "argument 0.\n", po->name, po->help);
  749. continue;
  750. }
  751. av_log(NULL, AV_LOG_ERROR, "Unrecognized option '%s'.\n", opt);
  752. return AVERROR_OPTION_NOT_FOUND;
  753. }
  754. if (octx->cur_group.nb_opts || codec_opts || format_opts)
  755. av_log(NULL, AV_LOG_WARNING, "Trailing option(s) found in the "
  756. "command: may be ignored.\n");
  757. av_log(NULL, AV_LOG_DEBUG, "Finished splitting the commandline.\n");
  758. return 0;
  759. }
  760. int read_yesno(void)
  761. {
  762. int c = getchar();
  763. int yesno = (av_toupper(c) == 'Y');
  764. while (c != '\n' && c != EOF)
  765. c = getchar();
  766. return yesno;
  767. }
  768. FILE *get_preset_file(char *filename, size_t filename_size,
  769. const char *preset_name, int is_path,
  770. const char *codec_name)
  771. {
  772. FILE *f = NULL;
  773. int i;
  774. #if HAVE_GETMODULEHANDLE && defined(_WIN32)
  775. char *datadir = NULL;
  776. #endif
  777. char *env_home = getenv_utf8("HOME");
  778. char *env_ffmpeg_datadir = getenv_utf8("FFMPEG_DATADIR");
  779. const char *base[3] = { env_ffmpeg_datadir,
  780. env_home, /* index=1(HOME) is special: search in a .ffmpeg subfolder */
  781. FFMPEG_DATADIR, };
  782. if (is_path) {
  783. av_strlcpy(filename, preset_name, filename_size);
  784. f = fopen_utf8(filename, "r");
  785. } else {
  786. #if HAVE_GETMODULEHANDLE && defined(_WIN32)
  787. wchar_t *datadir_w = get_module_filename(NULL);
  788. base[2] = NULL;
  789. if (wchartoutf8(datadir_w, &datadir))
  790. datadir = NULL;
  791. av_free(datadir_w);
  792. if (datadir)
  793. {
  794. char *ls;
  795. for (ls = datadir; *ls; ls++)
  796. if (*ls == '\\') *ls = '/';
  797. if (ls = strrchr(datadir, '/'))
  798. {
  799. ptrdiff_t datadir_len = ls - datadir;
  800. size_t desired_size = datadir_len + strlen("/ffpresets") + 1;
  801. char *new_datadir = av_realloc_array(
  802. datadir, desired_size, sizeof *datadir);
  803. if (new_datadir) {
  804. datadir = new_datadir;
  805. datadir[datadir_len] = 0;
  806. strncat(datadir, "/ffpresets", desired_size - 1 - datadir_len);
  807. base[2] = datadir;
  808. }
  809. }
  810. }
  811. #endif
  812. for (i = 0; i < 3 && !f; i++) {
  813. if (!base[i])
  814. continue;
  815. snprintf(filename, filename_size, "%s%s/%s.ffpreset", base[i],
  816. i != 1 ? "" : "/.ffmpeg", preset_name);
  817. f = fopen_utf8(filename, "r");
  818. if (!f && codec_name) {
  819. snprintf(filename, filename_size,
  820. "%s%s/%s-%s.ffpreset",
  821. base[i], i != 1 ? "" : "/.ffmpeg", codec_name,
  822. preset_name);
  823. f = fopen_utf8(filename, "r");
  824. }
  825. }
  826. }
  827. #if HAVE_GETMODULEHANDLE && defined(_WIN32)
  828. av_free(datadir);
  829. #endif
  830. freeenv_utf8(env_ffmpeg_datadir);
  831. freeenv_utf8(env_home);
  832. return f;
  833. }
  834. int check_stream_specifier(AVFormatContext *s, AVStream *st, const char *spec)
  835. {
  836. int ret = avformat_match_stream_specifier(s, st, spec);
  837. if (ret < 0)
  838. av_log(s, AV_LOG_ERROR, "Invalid stream specifier: %s.\n", spec);
  839. return ret;
  840. }
  841. int filter_codec_opts(const AVDictionary *opts, enum AVCodecID codec_id,
  842. AVFormatContext *s, AVStream *st, const AVCodec *codec,
  843. AVDictionary **dst)
  844. {
  845. AVDictionary *ret = NULL;
  846. const AVDictionaryEntry *t = NULL;
  847. int flags = s->oformat ? AV_OPT_FLAG_ENCODING_PARAM
  848. : AV_OPT_FLAG_DECODING_PARAM;
  849. char prefix = 0;
  850. const AVClass *cc = avcodec_get_class();
  851. if (!codec)
  852. codec = s->oformat ? avcodec_find_encoder(codec_id)
  853. : avcodec_find_decoder(codec_id);
  854. switch (st->codecpar->codec_type) {
  855. case AVMEDIA_TYPE_VIDEO:
  856. prefix = 'v';
  857. flags |= AV_OPT_FLAG_VIDEO_PARAM;
  858. break;
  859. case AVMEDIA_TYPE_AUDIO:
  860. prefix = 'a';
  861. flags |= AV_OPT_FLAG_AUDIO_PARAM;
  862. break;
  863. case AVMEDIA_TYPE_SUBTITLE:
  864. prefix = 's';
  865. flags |= AV_OPT_FLAG_SUBTITLE_PARAM;
  866. break;
  867. }
  868. while (t = av_dict_iterate(opts, t)) {
  869. const AVClass *priv_class;
  870. char *p = strchr(t->key, ':');
  871. /* check stream specification in opt name */
  872. if (p) {
  873. int err = check_stream_specifier(s, st, p + 1);
  874. if (err < 0) {
  875. av_dict_free(&ret);
  876. return err;
  877. } else if (!err)
  878. continue;
  879. *p = 0;
  880. }
  881. if (av_opt_find(&cc, t->key, NULL, flags, AV_OPT_SEARCH_FAKE_OBJ) ||
  882. !codec ||
  883. ((priv_class = codec->priv_class) &&
  884. av_opt_find(&priv_class, t->key, NULL, flags,
  885. AV_OPT_SEARCH_FAKE_OBJ)))
  886. av_dict_set(&ret, t->key, t->value, 0);
  887. else if (t->key[0] == prefix &&
  888. av_opt_find(&cc, t->key + 1, NULL, flags,
  889. AV_OPT_SEARCH_FAKE_OBJ))
  890. av_dict_set(&ret, t->key + 1, t->value, 0);
  891. if (p)
  892. *p = ':';
  893. }
  894. *dst = ret;
  895. return 0;
  896. }
  897. int setup_find_stream_info_opts(AVFormatContext *s,
  898. AVDictionary *codec_opts,
  899. AVDictionary ***dst)
  900. {
  901. int ret;
  902. AVDictionary **opts;
  903. *dst = NULL;
  904. if (!s->nb_streams)
  905. return 0;
  906. opts = av_calloc(s->nb_streams, sizeof(*opts));
  907. if (!opts)
  908. return AVERROR(ENOMEM);
  909. for (int i = 0; i < s->nb_streams; i++) {
  910. ret = filter_codec_opts(codec_opts, s->streams[i]->codecpar->codec_id,
  911. s, s->streams[i], NULL, &opts[i]);
  912. if (ret < 0)
  913. goto fail;
  914. }
  915. *dst = opts;
  916. return 0;
  917. fail:
  918. for (int i = 0; i < s->nb_streams; i++)
  919. av_dict_free(&opts[i]);
  920. av_freep(&opts);
  921. return ret;
  922. }
  923. int grow_array(void **array, int elem_size, int *size, int new_size)
  924. {
  925. if (new_size >= INT_MAX / elem_size) {
  926. av_log(NULL, AV_LOG_ERROR, "Array too big.\n");
  927. return AVERROR(ERANGE);
  928. }
  929. if (*size < new_size) {
  930. uint8_t *tmp = av_realloc_array(*array, new_size, elem_size);
  931. if (!tmp)
  932. return AVERROR(ENOMEM);
  933. memset(tmp + *size*elem_size, 0, (new_size-*size) * elem_size);
  934. *size = new_size;
  935. *array = tmp;
  936. return 0;
  937. }
  938. return 0;
  939. }
  940. void *allocate_array_elem(void *ptr, size_t elem_size, int *nb_elems)
  941. {
  942. void *new_elem;
  943. if (!(new_elem = av_mallocz(elem_size)) ||
  944. av_dynarray_add_nofree(ptr, nb_elems, new_elem) < 0)
  945. return NULL;
  946. return new_elem;
  947. }
  948. double get_rotation(const int32_t *displaymatrix)
  949. {
  950. double theta = 0;
  951. if (displaymatrix)
  952. theta = -round(av_display_rotation_get(displaymatrix));
  953. theta -= 360*floor(theta/360 + 0.9/360);
  954. if (fabs(theta - 90*round(theta/90)) > 2)
  955. av_log(NULL, AV_LOG_WARNING, "Odd rotation angle.\n"
  956. "If you want to help, upload a sample "
  957. "of this file to https://streams.videolan.org/upload/ "
  958. "and contact the ffmpeg-devel mailing list. (ffmpeg-devel@ffmpeg.org)");
  959. return theta;
  960. }
  961. /* read file contents into a string */
  962. char *file_read(const char *filename)
  963. {
  964. AVIOContext *pb = NULL;
  965. int ret = avio_open(&pb, filename, AVIO_FLAG_READ);
  966. AVBPrint bprint;
  967. char *str;
  968. if (ret < 0) {
  969. av_log(NULL, AV_LOG_ERROR, "Error opening file %s.\n", filename);
  970. return NULL;
  971. }
  972. av_bprint_init(&bprint, 0, AV_BPRINT_SIZE_UNLIMITED);
  973. ret = avio_read_to_bprint(pb, &bprint, SIZE_MAX);
  974. avio_closep(&pb);
  975. if (ret < 0) {
  976. av_bprint_finalize(&bprint, NULL);
  977. return NULL;
  978. }
  979. ret = av_bprint_finalize(&bprint, &str);
  980. if (ret < 0)
  981. return NULL;
  982. return str;
  983. }