cmdutils.c 31 KB

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