cmdutils.c 34 KB

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