cmdutils.c 31 KB

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