cmdutils.c 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012
  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/channel_layout.h"
  38. #include "libavutil/display.h"
  39. #include "libavutil/getenv_utf8.h"
  40. #include "libavutil/mathematics.h"
  41. #include "libavutil/imgutils.h"
  42. #include "libavutil/libm.h"
  43. #include "libavutil/parseutils.h"
  44. #include "libavutil/eval.h"
  45. #include "libavutil/dict.h"
  46. #include "libavutil/opt.h"
  47. #include "cmdutils.h"
  48. #include "fopen_utf8.h"
  49. #include "opt_common.h"
  50. #ifdef _WIN32
  51. #include <windows.h>
  52. #include "compat/w32dlfcn.h"
  53. #endif
  54. AVDictionary *sws_dict;
  55. AVDictionary *swr_opts;
  56. AVDictionary *format_opts, *codec_opts;
  57. int hide_banner = 0;
  58. void uninit_opts(void)
  59. {
  60. av_dict_free(&swr_opts);
  61. av_dict_free(&sws_dict);
  62. av_dict_free(&format_opts);
  63. av_dict_free(&codec_opts);
  64. }
  65. void log_callback_help(void *ptr, int level, const char *fmt, va_list vl)
  66. {
  67. vfprintf(stdout, fmt, vl);
  68. }
  69. void init_dynload(void)
  70. {
  71. #if HAVE_SETDLLDIRECTORY && defined(_WIN32)
  72. /* Calling SetDllDirectory with the empty string (but not NULL) removes the
  73. * current working directory from the DLL search path as a security pre-caution. */
  74. SetDllDirectory("");
  75. #endif
  76. }
  77. static void (*program_exit)(int ret);
  78. void register_exit(void (*cb)(int ret))
  79. {
  80. program_exit = cb;
  81. }
  82. void report_and_exit(int ret)
  83. {
  84. av_log(NULL, AV_LOG_FATAL, "%s\n", av_err2str(ret));
  85. exit_program(AVUNERROR(ret));
  86. }
  87. void exit_program(int ret)
  88. {
  89. if (program_exit)
  90. program_exit(ret);
  91. exit(ret);
  92. }
  93. double parse_number_or_die(const char *context, const char *numstr, int type,
  94. double min, double max)
  95. {
  96. char *tail;
  97. const char *error;
  98. double d = av_strtod(numstr, &tail);
  99. if (*tail)
  100. error = "Expected number for %s but found: %s\n";
  101. else if (d < min || d > max)
  102. error = "The value for %s was %s which is not within %f - %f\n";
  103. else if (type == OPT_INT64 && (int64_t)d != d)
  104. error = "Expected int64 for %s but found %s\n";
  105. else if (type == OPT_INT && (int)d != d)
  106. error = "Expected int for %s but found %s\n";
  107. else
  108. return d;
  109. av_log(NULL, AV_LOG_FATAL, error, context, numstr, min, max);
  110. exit_program(1);
  111. return 0;
  112. }
  113. int64_t parse_time_or_die(const char *context, const char *timestr,
  114. int is_duration)
  115. {
  116. int64_t us;
  117. if (av_parse_time(&us, timestr, is_duration) < 0) {
  118. av_log(NULL, AV_LOG_FATAL, "Invalid %s specification for %s: %s\n",
  119. is_duration ? "duration" : "date", context, timestr);
  120. exit_program(1);
  121. }
  122. return us;
  123. }
  124. void show_help_options(const OptionDef *options, const char *msg, int req_flags,
  125. int rej_flags, int alt_flags)
  126. {
  127. const OptionDef *po;
  128. int first;
  129. first = 1;
  130. for (po = options; po->name; po++) {
  131. char buf[128];
  132. if (((po->flags & req_flags) != req_flags) ||
  133. (alt_flags && !(po->flags & alt_flags)) ||
  134. (po->flags & rej_flags))
  135. continue;
  136. if (first) {
  137. printf("%s\n", msg);
  138. first = 0;
  139. }
  140. av_strlcpy(buf, po->name, sizeof(buf));
  141. if (po->argname) {
  142. av_strlcat(buf, " ", sizeof(buf));
  143. av_strlcat(buf, po->argname, sizeof(buf));
  144. }
  145. printf("-%-17s %s\n", buf, po->help);
  146. }
  147. printf("\n");
  148. }
  149. void show_help_children(const AVClass *class, int flags)
  150. {
  151. void *iter = NULL;
  152. const AVClass *child;
  153. if (class->option) {
  154. av_opt_show2(&class, NULL, flags, 0);
  155. printf("\n");
  156. }
  157. while (child = av_opt_child_class_iterate(class, &iter))
  158. show_help_children(child, flags);
  159. }
  160. static const OptionDef *find_option(const OptionDef *po, const char *name)
  161. {
  162. while (po->name) {
  163. const char *end;
  164. if (av_strstart(name, po->name, &end) && (!*end || *end == ':'))
  165. break;
  166. po++;
  167. }
  168. return po;
  169. }
  170. /* _WIN32 means using the windows libc - cygwin doesn't define that
  171. * by default. HAVE_COMMANDLINETOARGVW is true on cygwin, while
  172. * it doesn't provide the actual command line via GetCommandLineW(). */
  173. #if HAVE_COMMANDLINETOARGVW && defined(_WIN32)
  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) {
  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. char *str;
  238. dstcount = (int *)(so + 1);
  239. *so = grow_array(*so, sizeof(**so), dstcount, *dstcount + 1);
  240. str = av_strdup(p ? p + 1 : "");
  241. if (!str)
  242. return AVERROR(ENOMEM);
  243. (*so)[*dstcount - 1].specifier = str;
  244. dst = &(*so)[*dstcount - 1].u;
  245. }
  246. if (po->flags & OPT_STRING) {
  247. char *str;
  248. str = av_strdup(arg);
  249. av_freep(dst);
  250. if (!str)
  251. return AVERROR(ENOMEM);
  252. *(char **)dst = str;
  253. } else if (po->flags & OPT_BOOL || po->flags & OPT_INT) {
  254. *(int *)dst = parse_number_or_die(opt, arg, OPT_INT64, INT_MIN, INT_MAX);
  255. } else if (po->flags & OPT_INT64) {
  256. *(int64_t *)dst = parse_number_or_die(opt, arg, OPT_INT64, INT64_MIN, INT64_MAX);
  257. } else if (po->flags & OPT_TIME) {
  258. *(int64_t *)dst = parse_time_or_die(opt, arg, 1);
  259. } else if (po->flags & OPT_FLOAT) {
  260. *(float *)dst = parse_number_or_die(opt, arg, OPT_FLOAT, -INFINITY, INFINITY);
  261. } else if (po->flags & OPT_DOUBLE) {
  262. *(double *)dst = parse_number_or_die(opt, arg, OPT_DOUBLE, -INFINITY, INFINITY);
  263. } else if (po->u.func_arg) {
  264. int ret = po->u.func_arg(optctx, opt, arg);
  265. if (ret < 0) {
  266. av_log(NULL, AV_LOG_ERROR,
  267. "Failed to set value '%s' for option '%s': %s\n",
  268. arg, opt, av_err2str(ret));
  269. return ret;
  270. }
  271. }
  272. if (po->flags & OPT_EXIT)
  273. exit_program(0);
  274. return 0;
  275. }
  276. int parse_option(void *optctx, const char *opt, const char *arg,
  277. const OptionDef *options)
  278. {
  279. static const OptionDef opt_avoptions = {
  280. .name = "AVOption passthrough",
  281. .flags = HAS_ARG,
  282. .u.func_arg = opt_default,
  283. };
  284. const OptionDef *po;
  285. int ret;
  286. po = find_option(options, opt);
  287. if (!po->name && opt[0] == 'n' && opt[1] == 'o') {
  288. /* handle 'no' bool option */
  289. po = find_option(options, opt + 2);
  290. if ((po->name && (po->flags & OPT_BOOL)))
  291. arg = "0";
  292. } else if (po->flags & OPT_BOOL)
  293. arg = "1";
  294. if (!po->name)
  295. po = &opt_avoptions;
  296. if (!po->name) {
  297. av_log(NULL, AV_LOG_ERROR, "Unrecognized option '%s'\n", opt);
  298. return AVERROR(EINVAL);
  299. }
  300. if (po->flags & HAS_ARG && !arg) {
  301. av_log(NULL, AV_LOG_ERROR, "Missing argument for option '%s'\n", opt);
  302. return AVERROR(EINVAL);
  303. }
  304. ret = write_option(optctx, po, opt, arg);
  305. if (ret < 0)
  306. return ret;
  307. return !!(po->flags & HAS_ARG);
  308. }
  309. void parse_options(void *optctx, int argc, char **argv, const OptionDef *options,
  310. void (*parse_arg_function)(void *, const char*))
  311. {
  312. const char *opt;
  313. int optindex, handleoptions = 1, ret;
  314. /* perform system-dependent conversions for arguments list */
  315. prepare_app_arguments(&argc, &argv);
  316. /* parse options */
  317. optindex = 1;
  318. while (optindex < argc) {
  319. opt = argv[optindex++];
  320. if (handleoptions && opt[0] == '-' && opt[1] != '\0') {
  321. if (opt[1] == '-' && opt[2] == '\0') {
  322. handleoptions = 0;
  323. continue;
  324. }
  325. opt++;
  326. if ((ret = parse_option(optctx, opt, argv[optindex], options)) < 0)
  327. exit_program(1);
  328. optindex += ret;
  329. } else {
  330. if (parse_arg_function)
  331. parse_arg_function(optctx, opt);
  332. }
  333. }
  334. }
  335. int parse_optgroup(void *optctx, OptionGroup *g)
  336. {
  337. int i, ret;
  338. av_log(NULL, AV_LOG_DEBUG, "Parsing a group of options: %s %s.\n",
  339. g->group_def->name, g->arg);
  340. for (i = 0; i < g->nb_opts; i++) {
  341. Option *o = &g->opts[i];
  342. if (g->group_def->flags &&
  343. !(g->group_def->flags & o->opt->flags)) {
  344. av_log(NULL, AV_LOG_ERROR, "Option %s (%s) cannot be applied to "
  345. "%s %s -- you are trying to apply an input option to an "
  346. "output file or vice versa. Move this option before the "
  347. "file it belongs to.\n", o->key, o->opt->help,
  348. g->group_def->name, g->arg);
  349. return AVERROR(EINVAL);
  350. }
  351. av_log(NULL, AV_LOG_DEBUG, "Applying option %s (%s) with argument %s.\n",
  352. o->key, o->opt->help, o->val);
  353. ret = write_option(optctx, o->opt, o->key, o->val);
  354. if (ret < 0)
  355. return ret;
  356. }
  357. av_log(NULL, AV_LOG_DEBUG, "Successfully parsed a group of options.\n");
  358. return 0;
  359. }
  360. int locate_option(int argc, char **argv, const OptionDef *options,
  361. const char *optname)
  362. {
  363. const OptionDef *po;
  364. int i;
  365. for (i = 1; i < argc; i++) {
  366. const char *cur_opt = argv[i];
  367. if (*cur_opt++ != '-')
  368. continue;
  369. po = find_option(options, cur_opt);
  370. if (!po->name && cur_opt[0] == 'n' && cur_opt[1] == 'o')
  371. po = find_option(options, cur_opt + 2);
  372. if ((!po->name && !strcmp(cur_opt, optname)) ||
  373. (po->name && !strcmp(optname, po->name)))
  374. return i;
  375. if (!po->name || po->flags & HAS_ARG)
  376. i++;
  377. }
  378. return 0;
  379. }
  380. static void dump_argument(FILE *report_file, const char *a)
  381. {
  382. const unsigned char *p;
  383. for (p = a; *p; p++)
  384. if (!((*p >= '+' && *p <= ':') || (*p >= '@' && *p <= 'Z') ||
  385. *p == '_' || (*p >= 'a' && *p <= 'z')))
  386. break;
  387. if (!*p) {
  388. fputs(a, report_file);
  389. return;
  390. }
  391. fputc('"', report_file);
  392. for (p = a; *p; p++) {
  393. if (*p == '\\' || *p == '"' || *p == '$' || *p == '`')
  394. fprintf(report_file, "\\%c", *p);
  395. else if (*p < ' ' || *p > '~')
  396. fprintf(report_file, "\\x%02x", *p);
  397. else
  398. fputc(*p, report_file);
  399. }
  400. fputc('"', report_file);
  401. }
  402. static void check_options(const OptionDef *po)
  403. {
  404. while (po->name) {
  405. if (po->flags & OPT_PERFILE)
  406. av_assert0(po->flags & (OPT_INPUT | OPT_OUTPUT));
  407. po++;
  408. }
  409. }
  410. void parse_loglevel(int argc, char **argv, const OptionDef *options)
  411. {
  412. int idx = locate_option(argc, argv, options, "loglevel");
  413. char *env;
  414. check_options(options);
  415. if (!idx)
  416. idx = locate_option(argc, argv, options, "v");
  417. if (idx && argv[idx + 1])
  418. opt_loglevel(NULL, "loglevel", argv[idx + 1]);
  419. idx = locate_option(argc, argv, options, "report");
  420. env = getenv_utf8("FFREPORT");
  421. if (env || idx) {
  422. FILE *report_file = NULL;
  423. init_report(env, &report_file);
  424. if (report_file) {
  425. int i;
  426. fprintf(report_file, "Command line:\n");
  427. for (i = 0; i < argc; i++) {
  428. dump_argument(report_file, argv[i]);
  429. fputc(i < argc - 1 ? ' ' : '\n', report_file);
  430. }
  431. fflush(report_file);
  432. }
  433. }
  434. freeenv_utf8(env);
  435. idx = locate_option(argc, argv, options, "hide_banner");
  436. if (idx)
  437. hide_banner = 1;
  438. }
  439. static const AVOption *opt_find(void *obj, const char *name, const char *unit,
  440. int opt_flags, int search_flags)
  441. {
  442. const AVOption *o = av_opt_find(obj, name, unit, opt_flags, search_flags);
  443. if(o && !o->flags)
  444. return NULL;
  445. return o;
  446. }
  447. #define FLAGS (o->type == AV_OPT_TYPE_FLAGS && (arg[0]=='-' || arg[0]=='+')) ? AV_DICT_APPEND : 0
  448. int opt_default(void *optctx, const char *opt, const char *arg)
  449. {
  450. const AVOption *o;
  451. int consumed = 0;
  452. char opt_stripped[128];
  453. const char *p;
  454. const AVClass *cc = avcodec_get_class(), *fc = avformat_get_class();
  455. #if CONFIG_SWSCALE
  456. const AVClass *sc = sws_get_class();
  457. #endif
  458. #if CONFIG_SWRESAMPLE
  459. const AVClass *swr_class = swr_get_class();
  460. #endif
  461. if (!strcmp(opt, "debug") || !strcmp(opt, "fdebug"))
  462. av_log_set_level(AV_LOG_DEBUG);
  463. if (!(p = strchr(opt, ':')))
  464. p = opt + strlen(opt);
  465. av_strlcpy(opt_stripped, opt, FFMIN(sizeof(opt_stripped), p - opt + 1));
  466. if ((o = opt_find(&cc, opt_stripped, NULL, 0,
  467. AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ)) ||
  468. ((opt[0] == 'v' || opt[0] == 'a' || opt[0] == 's') &&
  469. (o = opt_find(&cc, opt + 1, NULL, 0, AV_OPT_SEARCH_FAKE_OBJ)))) {
  470. av_dict_set(&codec_opts, opt, arg, FLAGS);
  471. consumed = 1;
  472. }
  473. if ((o = opt_find(&fc, opt, NULL, 0,
  474. AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ))) {
  475. av_dict_set(&format_opts, opt, arg, FLAGS);
  476. if (consumed)
  477. av_log(NULL, AV_LOG_VERBOSE, "Routing option %s to both codec and muxer layer\n", opt);
  478. consumed = 1;
  479. }
  480. #if CONFIG_SWSCALE
  481. if (!consumed && (o = opt_find(&sc, opt, NULL, 0,
  482. AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ))) {
  483. if (!strcmp(opt, "srcw") || !strcmp(opt, "srch") ||
  484. !strcmp(opt, "dstw") || !strcmp(opt, "dsth") ||
  485. !strcmp(opt, "src_format") || !strcmp(opt, "dst_format")) {
  486. av_log(NULL, AV_LOG_ERROR, "Directly using swscale dimensions/format options is not supported, please use the -s or -pix_fmt options\n");
  487. return AVERROR(EINVAL);
  488. }
  489. av_dict_set(&sws_dict, opt, arg, FLAGS);
  490. consumed = 1;
  491. }
  492. #else
  493. if (!consumed && !strcmp(opt, "sws_flags")) {
  494. av_log(NULL, AV_LOG_WARNING, "Ignoring %s %s, due to disabled swscale\n", opt, arg);
  495. consumed = 1;
  496. }
  497. #endif
  498. #if CONFIG_SWRESAMPLE
  499. if (!consumed && (o=opt_find(&swr_class, opt, NULL, 0,
  500. AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ))) {
  501. av_dict_set(&swr_opts, opt, arg, FLAGS);
  502. consumed = 1;
  503. }
  504. #endif
  505. if (consumed)
  506. return 0;
  507. return AVERROR_OPTION_NOT_FOUND;
  508. }
  509. /*
  510. * Check whether given option is a group separator.
  511. *
  512. * @return index of the group definition that matched or -1 if none
  513. */
  514. static int match_group_separator(const OptionGroupDef *groups, int nb_groups,
  515. const char *opt)
  516. {
  517. int i;
  518. for (i = 0; i < nb_groups; i++) {
  519. const OptionGroupDef *p = &groups[i];
  520. if (p->sep && !strcmp(p->sep, opt))
  521. return i;
  522. }
  523. return -1;
  524. }
  525. /*
  526. * Finish parsing an option group.
  527. *
  528. * @param group_idx which group definition should this group belong to
  529. * @param arg argument of the group delimiting option
  530. */
  531. static void finish_group(OptionParseContext *octx, int group_idx,
  532. const char *arg)
  533. {
  534. OptionGroupList *l = &octx->groups[group_idx];
  535. OptionGroup *g;
  536. GROW_ARRAY(l->groups, l->nb_groups);
  537. g = &l->groups[l->nb_groups - 1];
  538. *g = octx->cur_group;
  539. g->arg = arg;
  540. g->group_def = l->group_def;
  541. g->sws_dict = sws_dict;
  542. g->swr_opts = swr_opts;
  543. g->codec_opts = codec_opts;
  544. g->format_opts = format_opts;
  545. codec_opts = NULL;
  546. format_opts = NULL;
  547. sws_dict = NULL;
  548. swr_opts = NULL;
  549. memset(&octx->cur_group, 0, sizeof(octx->cur_group));
  550. }
  551. /*
  552. * Add an option instance to currently parsed group.
  553. */
  554. static void add_opt(OptionParseContext *octx, const OptionDef *opt,
  555. const char *key, const char *val)
  556. {
  557. int global = !(opt->flags & (OPT_PERFILE | OPT_SPEC | OPT_OFFSET));
  558. OptionGroup *g = global ? &octx->global_opts : &octx->cur_group;
  559. GROW_ARRAY(g->opts, g->nb_opts);
  560. g->opts[g->nb_opts - 1].opt = opt;
  561. g->opts[g->nb_opts - 1].key = key;
  562. g->opts[g->nb_opts - 1].val = val;
  563. }
  564. static void init_parse_context(OptionParseContext *octx,
  565. const OptionGroupDef *groups, int nb_groups)
  566. {
  567. static const OptionGroupDef global_group = { "global" };
  568. int i;
  569. memset(octx, 0, sizeof(*octx));
  570. octx->nb_groups = nb_groups;
  571. octx->groups = av_calloc(octx->nb_groups, sizeof(*octx->groups));
  572. if (!octx->groups)
  573. report_and_exit(AVERROR(ENOMEM));
  574. for (i = 0; i < octx->nb_groups; i++)
  575. octx->groups[i].group_def = &groups[i];
  576. octx->global_opts.group_def = &global_group;
  577. octx->global_opts.arg = "";
  578. }
  579. void uninit_parse_context(OptionParseContext *octx)
  580. {
  581. int i, j;
  582. for (i = 0; i < octx->nb_groups; i++) {
  583. OptionGroupList *l = &octx->groups[i];
  584. for (j = 0; j < l->nb_groups; j++) {
  585. av_freep(&l->groups[j].opts);
  586. av_dict_free(&l->groups[j].codec_opts);
  587. av_dict_free(&l->groups[j].format_opts);
  588. av_dict_free(&l->groups[j].sws_dict);
  589. av_dict_free(&l->groups[j].swr_opts);
  590. }
  591. av_freep(&l->groups);
  592. }
  593. av_freep(&octx->groups);
  594. av_freep(&octx->cur_group.opts);
  595. av_freep(&octx->global_opts.opts);
  596. uninit_opts();
  597. }
  598. int split_commandline(OptionParseContext *octx, int argc, char *argv[],
  599. const OptionDef *options,
  600. const OptionGroupDef *groups, int nb_groups)
  601. {
  602. int optindex = 1;
  603. int dashdash = -2;
  604. /* perform system-dependent conversions for arguments list */
  605. prepare_app_arguments(&argc, &argv);
  606. init_parse_context(octx, groups, nb_groups);
  607. av_log(NULL, AV_LOG_DEBUG, "Splitting the commandline.\n");
  608. while (optindex < argc) {
  609. const char *opt = argv[optindex++], *arg;
  610. const OptionDef *po;
  611. int ret;
  612. av_log(NULL, AV_LOG_DEBUG, "Reading option '%s' ...", opt);
  613. if (opt[0] == '-' && opt[1] == '-' && !opt[2]) {
  614. dashdash = optindex;
  615. continue;
  616. }
  617. /* unnamed group separators, e.g. output filename */
  618. if (opt[0] != '-' || !opt[1] || dashdash+1 == optindex) {
  619. finish_group(octx, 0, opt);
  620. av_log(NULL, AV_LOG_DEBUG, " matched as %s.\n", groups[0].name);
  621. continue;
  622. }
  623. opt++;
  624. #define GET_ARG(arg) \
  625. do { \
  626. arg = argv[optindex++]; \
  627. if (!arg) { \
  628. av_log(NULL, AV_LOG_ERROR, "Missing argument for option '%s'.\n", opt);\
  629. return AVERROR(EINVAL); \
  630. } \
  631. } while (0)
  632. /* named group separators, e.g. -i */
  633. if ((ret = match_group_separator(groups, nb_groups, opt)) >= 0) {
  634. GET_ARG(arg);
  635. finish_group(octx, ret, arg);
  636. av_log(NULL, AV_LOG_DEBUG, " matched as %s with argument '%s'.\n",
  637. groups[ret].name, arg);
  638. continue;
  639. }
  640. /* normal options */
  641. po = find_option(options, opt);
  642. if (po->name) {
  643. if (po->flags & OPT_EXIT) {
  644. /* optional argument, e.g. -h */
  645. arg = argv[optindex++];
  646. } else if (po->flags & HAS_ARG) {
  647. GET_ARG(arg);
  648. } else {
  649. arg = "1";
  650. }
  651. add_opt(octx, po, opt, arg);
  652. av_log(NULL, AV_LOG_DEBUG, " matched as option '%s' (%s) with "
  653. "argument '%s'.\n", po->name, po->help, arg);
  654. continue;
  655. }
  656. /* AVOptions */
  657. if (argv[optindex]) {
  658. ret = opt_default(NULL, opt, argv[optindex]);
  659. if (ret >= 0) {
  660. av_log(NULL, AV_LOG_DEBUG, " matched as AVOption '%s' with "
  661. "argument '%s'.\n", opt, argv[optindex]);
  662. optindex++;
  663. continue;
  664. } else if (ret != AVERROR_OPTION_NOT_FOUND) {
  665. av_log(NULL, AV_LOG_ERROR, "Error parsing option '%s' "
  666. "with argument '%s'.\n", opt, argv[optindex]);
  667. return ret;
  668. }
  669. }
  670. /* boolean -nofoo options */
  671. if (opt[0] == 'n' && opt[1] == 'o' &&
  672. (po = find_option(options, opt + 2)) &&
  673. po->name && po->flags & OPT_BOOL) {
  674. add_opt(octx, po, opt, "0");
  675. av_log(NULL, AV_LOG_DEBUG, " matched as option '%s' (%s) with "
  676. "argument 0.\n", po->name, po->help);
  677. continue;
  678. }
  679. av_log(NULL, AV_LOG_ERROR, "Unrecognized option '%s'.\n", opt);
  680. return AVERROR_OPTION_NOT_FOUND;
  681. }
  682. if (octx->cur_group.nb_opts || codec_opts || format_opts)
  683. av_log(NULL, AV_LOG_WARNING, "Trailing option(s) found in the "
  684. "command: may be ignored.\n");
  685. av_log(NULL, AV_LOG_DEBUG, "Finished splitting the commandline.\n");
  686. return 0;
  687. }
  688. void print_error(const char *filename, int err)
  689. {
  690. av_log(NULL, AV_LOG_ERROR, "%s: %s\n", filename, av_err2str(err));
  691. }
  692. int read_yesno(void)
  693. {
  694. int c = getchar();
  695. int yesno = (av_toupper(c) == 'Y');
  696. while (c != '\n' && c != EOF)
  697. c = getchar();
  698. return yesno;
  699. }
  700. FILE *get_preset_file(char *filename, size_t filename_size,
  701. const char *preset_name, int is_path,
  702. const char *codec_name)
  703. {
  704. FILE *f = NULL;
  705. int i;
  706. #if HAVE_GETMODULEHANDLE && defined(_WIN32)
  707. char *datadir = NULL;
  708. #endif
  709. char *env_home = getenv_utf8("HOME");
  710. char *env_ffmpeg_datadir = getenv_utf8("FFMPEG_DATADIR");
  711. const char *base[3] = { env_ffmpeg_datadir,
  712. env_home, /* index=1(HOME) is special: search in a .ffmpeg subfolder */
  713. FFMPEG_DATADIR, };
  714. if (is_path) {
  715. av_strlcpy(filename, preset_name, filename_size);
  716. f = fopen_utf8(filename, "r");
  717. } else {
  718. #if HAVE_GETMODULEHANDLE && defined(_WIN32)
  719. wchar_t *datadir_w = get_module_filename(NULL);
  720. base[2] = NULL;
  721. if (wchartoutf8(datadir_w, &datadir))
  722. datadir = NULL;
  723. av_free(datadir_w);
  724. if (datadir)
  725. {
  726. char *ls;
  727. for (ls = datadir; *ls; ls++)
  728. if (*ls == '\\') *ls = '/';
  729. if (ls = strrchr(datadir, '/'))
  730. {
  731. ptrdiff_t datadir_len = ls - datadir;
  732. size_t desired_size = datadir_len + strlen("/ffpresets") + 1;
  733. char *new_datadir = av_realloc_array(
  734. datadir, desired_size, sizeof *datadir);
  735. if (new_datadir) {
  736. datadir = new_datadir;
  737. datadir[datadir_len] = 0;
  738. strncat(datadir, "/ffpresets", desired_size - 1 - datadir_len);
  739. base[2] = datadir;
  740. }
  741. }
  742. }
  743. #endif
  744. for (i = 0; i < 3 && !f; i++) {
  745. if (!base[i])
  746. continue;
  747. snprintf(filename, filename_size, "%s%s/%s.ffpreset", base[i],
  748. i != 1 ? "" : "/.ffmpeg", preset_name);
  749. f = fopen_utf8(filename, "r");
  750. if (!f && codec_name) {
  751. snprintf(filename, filename_size,
  752. "%s%s/%s-%s.ffpreset",
  753. base[i], i != 1 ? "" : "/.ffmpeg", codec_name,
  754. preset_name);
  755. f = fopen_utf8(filename, "r");
  756. }
  757. }
  758. }
  759. #if HAVE_GETMODULEHANDLE && defined(_WIN32)
  760. av_free(datadir);
  761. #endif
  762. freeenv_utf8(env_ffmpeg_datadir);
  763. freeenv_utf8(env_home);
  764. return f;
  765. }
  766. int check_stream_specifier(AVFormatContext *s, AVStream *st, const char *spec)
  767. {
  768. int ret = avformat_match_stream_specifier(s, st, spec);
  769. if (ret < 0)
  770. av_log(s, AV_LOG_ERROR, "Invalid stream specifier: %s.\n", spec);
  771. return ret;
  772. }
  773. AVDictionary *filter_codec_opts(AVDictionary *opts, enum AVCodecID codec_id,
  774. AVFormatContext *s, AVStream *st, const AVCodec *codec)
  775. {
  776. AVDictionary *ret = NULL;
  777. const AVDictionaryEntry *t = NULL;
  778. int flags = s->oformat ? AV_OPT_FLAG_ENCODING_PARAM
  779. : AV_OPT_FLAG_DECODING_PARAM;
  780. char prefix = 0;
  781. const AVClass *cc = avcodec_get_class();
  782. if (!codec)
  783. codec = s->oformat ? avcodec_find_encoder(codec_id)
  784. : avcodec_find_decoder(codec_id);
  785. switch (st->codecpar->codec_type) {
  786. case AVMEDIA_TYPE_VIDEO:
  787. prefix = 'v';
  788. flags |= AV_OPT_FLAG_VIDEO_PARAM;
  789. break;
  790. case AVMEDIA_TYPE_AUDIO:
  791. prefix = 'a';
  792. flags |= AV_OPT_FLAG_AUDIO_PARAM;
  793. break;
  794. case AVMEDIA_TYPE_SUBTITLE:
  795. prefix = 's';
  796. flags |= AV_OPT_FLAG_SUBTITLE_PARAM;
  797. break;
  798. }
  799. while (t = av_dict_iterate(opts, t)) {
  800. const AVClass *priv_class;
  801. char *p = strchr(t->key, ':');
  802. /* check stream specification in opt name */
  803. if (p)
  804. switch (check_stream_specifier(s, st, p + 1)) {
  805. case 1: *p = 0; break;
  806. case 0: continue;
  807. default: exit_program(1);
  808. }
  809. if (av_opt_find(&cc, t->key, NULL, flags, AV_OPT_SEARCH_FAKE_OBJ) ||
  810. !codec ||
  811. ((priv_class = codec->priv_class) &&
  812. av_opt_find(&priv_class, t->key, NULL, flags,
  813. AV_OPT_SEARCH_FAKE_OBJ)))
  814. av_dict_set(&ret, t->key, t->value, 0);
  815. else if (t->key[0] == prefix &&
  816. av_opt_find(&cc, t->key + 1, NULL, flags,
  817. AV_OPT_SEARCH_FAKE_OBJ))
  818. av_dict_set(&ret, t->key + 1, t->value, 0);
  819. if (p)
  820. *p = ':';
  821. }
  822. return ret;
  823. }
  824. AVDictionary **setup_find_stream_info_opts(AVFormatContext *s,
  825. AVDictionary *codec_opts)
  826. {
  827. int i;
  828. AVDictionary **opts;
  829. if (!s->nb_streams)
  830. return NULL;
  831. opts = av_calloc(s->nb_streams, sizeof(*opts));
  832. if (!opts)
  833. report_and_exit(AVERROR(ENOMEM));
  834. for (i = 0; i < s->nb_streams; i++)
  835. opts[i] = filter_codec_opts(codec_opts, s->streams[i]->codecpar->codec_id,
  836. s, s->streams[i], NULL);
  837. return opts;
  838. }
  839. void *grow_array(void *array, int elem_size, int *size, int new_size)
  840. {
  841. if (new_size >= INT_MAX / elem_size) {
  842. av_log(NULL, AV_LOG_ERROR, "Array too big.\n");
  843. exit_program(1);
  844. }
  845. if (*size < new_size) {
  846. uint8_t *tmp = av_realloc_array(array, new_size, elem_size);
  847. if (!tmp)
  848. report_and_exit(AVERROR(ENOMEM));
  849. memset(tmp + *size*elem_size, 0, (new_size-*size) * elem_size);
  850. *size = new_size;
  851. return tmp;
  852. }
  853. return array;
  854. }
  855. void *allocate_array_elem(void *ptr, size_t elem_size, int *nb_elems)
  856. {
  857. void *new_elem;
  858. if (!(new_elem = av_mallocz(elem_size)) ||
  859. av_dynarray_add_nofree(ptr, nb_elems, new_elem) < 0)
  860. report_and_exit(AVERROR(ENOMEM));
  861. return new_elem;
  862. }
  863. double get_rotation(int32_t *displaymatrix)
  864. {
  865. double theta = 0;
  866. if (displaymatrix)
  867. theta = -round(av_display_rotation_get((int32_t*) displaymatrix));
  868. theta -= 360*floor(theta/360 + 0.9/360);
  869. if (fabs(theta - 90*round(theta/90)) > 2)
  870. av_log(NULL, AV_LOG_WARNING, "Odd rotation angle.\n"
  871. "If you want to help, upload a sample "
  872. "of this file to https://streams.videolan.org/upload/ "
  873. "and contact the ffmpeg-devel mailing list. (ffmpeg-devel@ffmpeg.org)");
  874. return theta;
  875. }