cmdutils.c 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536
  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. enum OptionType so_type = po->type;
  218. SpecifierOptList *sol = NULL;
  219. double num;
  220. int ret = 0;
  221. if (*opt == '/') {
  222. opt++;
  223. if (po->type == OPT_TYPE_BOOL) {
  224. av_log(NULL, AV_LOG_FATAL,
  225. "Requested to load an argument from file for a bool option '%s'\n",
  226. po->name);
  227. return AVERROR(EINVAL);
  228. }
  229. arg_allocated = file_read(arg);
  230. if (!arg_allocated) {
  231. av_log(NULL, AV_LOG_FATAL,
  232. "Error reading the value for option '%s' from file: %s\n",
  233. opt, arg);
  234. return AVERROR(EINVAL);
  235. }
  236. arg = arg_allocated;
  237. }
  238. if (po->flags & OPT_FLAG_SPEC) {
  239. char *p = strchr(opt, ':');
  240. char *str;
  241. sol = dst;
  242. ret = GROW_ARRAY(sol->opt, sol->nb_opt);
  243. if (ret < 0)
  244. goto finish;
  245. str = av_strdup(p ? p + 1 : "");
  246. if (!str) {
  247. ret = AVERROR(ENOMEM);
  248. goto finish;
  249. }
  250. sol->opt[sol->nb_opt - 1].specifier = str;
  251. if (po->flags & OPT_FLAG_PERSTREAM) {
  252. ret = stream_specifier_parse(&sol->opt[sol->nb_opt - 1].stream_spec,
  253. str, 0, NULL);
  254. if (ret < 0)
  255. goto finish;
  256. }
  257. dst = &sol->opt[sol->nb_opt - 1].u;
  258. }
  259. if (po->type == OPT_TYPE_STRING) {
  260. char *str;
  261. if (arg_allocated) {
  262. str = arg_allocated;
  263. arg_allocated = NULL;
  264. } else
  265. str = av_strdup(arg);
  266. av_freep(dst);
  267. if (!str) {
  268. ret = AVERROR(ENOMEM);
  269. goto finish;
  270. }
  271. *(char **)dst = str;
  272. } else if (po->type == OPT_TYPE_BOOL || po->type == OPT_TYPE_INT) {
  273. ret = parse_number(opt, arg, OPT_TYPE_INT64, INT_MIN, INT_MAX, &num);
  274. if (ret < 0)
  275. goto finish;
  276. *(int *)dst = num;
  277. so_type = OPT_TYPE_INT;
  278. } else if (po->type == OPT_TYPE_INT64) {
  279. ret = parse_number(opt, arg, OPT_TYPE_INT64, INT64_MIN, (double)INT64_MAX, &num);
  280. if (ret < 0)
  281. goto finish;
  282. *(int64_t *)dst = num;
  283. } else if (po->type == OPT_TYPE_TIME) {
  284. ret = av_parse_time(dst, arg, 1);
  285. if (ret < 0) {
  286. av_log(NULL, AV_LOG_ERROR, "Invalid duration for option %s: %s\n",
  287. opt, arg);
  288. goto finish;
  289. }
  290. so_type = OPT_TYPE_INT64;
  291. } else if (po->type == OPT_TYPE_FLOAT) {
  292. ret = parse_number(opt, arg, OPT_TYPE_FLOAT, -INFINITY, INFINITY, &num);
  293. if (ret < 0)
  294. goto finish;
  295. *(float *)dst = num;
  296. } else if (po->type == OPT_TYPE_DOUBLE) {
  297. ret = parse_number(opt, arg, OPT_TYPE_DOUBLE, -INFINITY, INFINITY, &num);
  298. if (ret < 0)
  299. goto finish;
  300. *(double *)dst = num;
  301. } else {
  302. av_assert0(po->type == OPT_TYPE_FUNC && po->u.func_arg);
  303. ret = po->u.func_arg(optctx, opt, arg);
  304. if (ret < 0) {
  305. av_log(NULL, AV_LOG_ERROR,
  306. "Failed to set value '%s' for option '%s': %s\n",
  307. arg, opt, av_err2str(ret));
  308. goto finish;
  309. }
  310. }
  311. if (po->flags & OPT_EXIT) {
  312. ret = AVERROR_EXIT;
  313. goto finish;
  314. }
  315. if (sol) {
  316. sol->type = so_type;
  317. sol->opt_canon = (po->flags & OPT_HAS_CANON) ?
  318. find_option(defs, po->u1.name_canon) : po;
  319. }
  320. finish:
  321. av_freep(&arg_allocated);
  322. return ret;
  323. }
  324. int parse_option(void *optctx, const char *opt, const char *arg,
  325. const OptionDef *options)
  326. {
  327. static const OptionDef opt_avoptions = {
  328. .name = "AVOption passthrough",
  329. .type = OPT_TYPE_FUNC,
  330. .flags = OPT_FUNC_ARG,
  331. .u.func_arg = opt_default,
  332. };
  333. const OptionDef *po;
  334. int ret;
  335. po = find_option(options, opt);
  336. if (!po->name && opt[0] == 'n' && opt[1] == 'o') {
  337. /* handle 'no' bool option */
  338. po = find_option(options, opt + 2);
  339. if ((po->name && po->type == OPT_TYPE_BOOL))
  340. arg = "0";
  341. } else if (po->type == OPT_TYPE_BOOL)
  342. arg = "1";
  343. if (!po->name)
  344. po = &opt_avoptions;
  345. if (!po->name) {
  346. av_log(NULL, AV_LOG_ERROR, "Unrecognized option '%s'\n", opt);
  347. return AVERROR(EINVAL);
  348. }
  349. if (opt_has_arg(po) && !arg) {
  350. av_log(NULL, AV_LOG_ERROR, "Missing argument for option '%s'\n", opt);
  351. return AVERROR(EINVAL);
  352. }
  353. ret = write_option(optctx, po, opt, arg, options);
  354. if (ret < 0)
  355. return ret;
  356. return opt_has_arg(po);
  357. }
  358. int parse_options(void *optctx, int argc, char **argv, const OptionDef *options,
  359. int (*parse_arg_function)(void *, const char*))
  360. {
  361. const char *opt;
  362. int optindex, handleoptions = 1, ret;
  363. /* perform system-dependent conversions for arguments list */
  364. prepare_app_arguments(&argc, &argv);
  365. /* parse options */
  366. optindex = 1;
  367. while (optindex < argc) {
  368. opt = argv[optindex++];
  369. if (handleoptions && opt[0] == '-' && opt[1] != '\0') {
  370. if (opt[1] == '-' && opt[2] == '\0') {
  371. handleoptions = 0;
  372. continue;
  373. }
  374. opt++;
  375. if ((ret = parse_option(optctx, opt, argv[optindex], options)) < 0)
  376. return ret;
  377. optindex += ret;
  378. } else {
  379. if (parse_arg_function) {
  380. ret = parse_arg_function(optctx, opt);
  381. if (ret < 0)
  382. return ret;
  383. }
  384. }
  385. }
  386. return 0;
  387. }
  388. int parse_optgroup(void *optctx, OptionGroup *g, const OptionDef *defs)
  389. {
  390. int i, ret;
  391. av_log(NULL, AV_LOG_DEBUG, "Parsing a group of options: %s %s.\n",
  392. g->group_def->name, g->arg);
  393. for (i = 0; i < g->nb_opts; i++) {
  394. Option *o = &g->opts[i];
  395. if (g->group_def->flags &&
  396. !(g->group_def->flags & o->opt->flags)) {
  397. av_log(NULL, AV_LOG_ERROR, "Option %s (%s) cannot be applied to "
  398. "%s %s -- you are trying to apply an input option to an "
  399. "output file or vice versa. Move this option before the "
  400. "file it belongs to.\n", o->key, o->opt->help,
  401. g->group_def->name, g->arg);
  402. return AVERROR(EINVAL);
  403. }
  404. av_log(NULL, AV_LOG_DEBUG, "Applying option %s (%s) with argument %s.\n",
  405. o->key, o->opt->help, o->val);
  406. ret = write_option(optctx, o->opt, o->key, o->val, defs);
  407. if (ret < 0)
  408. return ret;
  409. }
  410. av_log(NULL, AV_LOG_DEBUG, "Successfully parsed a group of options.\n");
  411. return 0;
  412. }
  413. int locate_option(int argc, char **argv, const OptionDef *options,
  414. const char *optname)
  415. {
  416. const OptionDef *po;
  417. int i;
  418. for (i = 1; i < argc; i++) {
  419. const char *cur_opt = argv[i];
  420. if (*cur_opt++ != '-')
  421. continue;
  422. po = find_option(options, cur_opt);
  423. if (!po->name && cur_opt[0] == 'n' && cur_opt[1] == 'o')
  424. po = find_option(options, cur_opt + 2);
  425. if ((!po->name && !strcmp(cur_opt, optname)) ||
  426. (po->name && !strcmp(optname, po->name)))
  427. return i;
  428. if (!po->name || opt_has_arg(po))
  429. i++;
  430. }
  431. return 0;
  432. }
  433. static void dump_argument(FILE *report_file, const char *a)
  434. {
  435. const unsigned char *p;
  436. for (p = a; *p; p++)
  437. if (!((*p >= '+' && *p <= ':') || (*p >= '@' && *p <= 'Z') ||
  438. *p == '_' || (*p >= 'a' && *p <= 'z')))
  439. break;
  440. if (!*p) {
  441. fputs(a, report_file);
  442. return;
  443. }
  444. fputc('"', report_file);
  445. for (p = a; *p; p++) {
  446. if (*p == '\\' || *p == '"' || *p == '$' || *p == '`')
  447. fprintf(report_file, "\\%c", *p);
  448. else if (*p < ' ' || *p > '~')
  449. fprintf(report_file, "\\x%02x", *p);
  450. else
  451. fputc(*p, report_file);
  452. }
  453. fputc('"', report_file);
  454. }
  455. static void check_options(const OptionDef *po)
  456. {
  457. while (po->name) {
  458. if (po->flags & OPT_PERFILE)
  459. av_assert0(po->flags & (OPT_INPUT | OPT_OUTPUT | OPT_DECODER));
  460. if (po->type == OPT_TYPE_FUNC)
  461. av_assert0(!(po->flags & (OPT_FLAG_OFFSET | OPT_FLAG_SPEC)));
  462. // OPT_FUNC_ARG can only be ser for OPT_TYPE_FUNC
  463. av_assert0((po->type == OPT_TYPE_FUNC) || !(po->flags & OPT_FUNC_ARG));
  464. po++;
  465. }
  466. }
  467. void parse_loglevel(int argc, char **argv, const OptionDef *options)
  468. {
  469. int idx = locate_option(argc, argv, options, "loglevel");
  470. char *env;
  471. check_options(options);
  472. if (!idx)
  473. idx = locate_option(argc, argv, options, "v");
  474. if (idx && argv[idx + 1])
  475. opt_loglevel(NULL, "loglevel", argv[idx + 1]);
  476. idx = locate_option(argc, argv, options, "report");
  477. env = getenv_utf8("FFREPORT");
  478. if (env || idx) {
  479. FILE *report_file = NULL;
  480. init_report(env, &report_file);
  481. if (report_file) {
  482. int i;
  483. fprintf(report_file, "Command line:\n");
  484. for (i = 0; i < argc; i++) {
  485. dump_argument(report_file, argv[i]);
  486. fputc(i < argc - 1 ? ' ' : '\n', report_file);
  487. }
  488. fflush(report_file);
  489. }
  490. }
  491. freeenv_utf8(env);
  492. idx = locate_option(argc, argv, options, "hide_banner");
  493. if (idx)
  494. hide_banner = 1;
  495. }
  496. static const AVOption *opt_find(void *obj, const char *name, const char *unit,
  497. int opt_flags, int search_flags)
  498. {
  499. const AVOption *o = av_opt_find(obj, name, unit, opt_flags, search_flags);
  500. if(o && !o->flags)
  501. return NULL;
  502. return o;
  503. }
  504. #define FLAGS ((o->type == AV_OPT_TYPE_FLAGS && (arg[0]=='-' || arg[0]=='+')) ? AV_DICT_APPEND : 0)
  505. int opt_default(void *optctx, const char *opt, const char *arg)
  506. {
  507. const AVOption *o;
  508. int consumed = 0;
  509. char opt_stripped[128];
  510. const char *p;
  511. const AVClass *cc = avcodec_get_class(), *fc = avformat_get_class();
  512. #if CONFIG_SWSCALE
  513. const AVClass *sc = sws_get_class();
  514. #endif
  515. #if CONFIG_SWRESAMPLE
  516. const AVClass *swr_class = swr_get_class();
  517. #endif
  518. if (!strcmp(opt, "debug") || !strcmp(opt, "fdebug"))
  519. av_log_set_level(AV_LOG_DEBUG);
  520. if (!(p = strchr(opt, ':')))
  521. p = opt + strlen(opt);
  522. av_strlcpy(opt_stripped, opt, FFMIN(sizeof(opt_stripped), p - opt + 1));
  523. if ((o = opt_find(&cc, opt_stripped, NULL, 0,
  524. AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ)) ||
  525. ((opt[0] == 'v' || opt[0] == 'a' || opt[0] == 's') &&
  526. (o = opt_find(&cc, opt + 1, NULL, 0, AV_OPT_SEARCH_FAKE_OBJ)))) {
  527. av_dict_set(&codec_opts, opt, arg, FLAGS);
  528. consumed = 1;
  529. }
  530. if ((o = opt_find(&fc, opt, NULL, 0,
  531. AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ))) {
  532. av_dict_set(&format_opts, opt, arg, FLAGS);
  533. if (consumed)
  534. av_log(NULL, AV_LOG_VERBOSE, "Routing option %s to both codec and muxer layer\n", opt);
  535. consumed = 1;
  536. }
  537. #if CONFIG_SWSCALE
  538. if (!consumed && (o = opt_find(&sc, opt, NULL, 0,
  539. AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ))) {
  540. if (!strcmp(opt, "srcw") || !strcmp(opt, "srch") ||
  541. !strcmp(opt, "dstw") || !strcmp(opt, "dsth") ||
  542. !strcmp(opt, "src_format") || !strcmp(opt, "dst_format")) {
  543. av_log(NULL, AV_LOG_ERROR, "Directly using swscale dimensions/format options is not supported, please use the -s or -pix_fmt options\n");
  544. return AVERROR(EINVAL);
  545. }
  546. av_dict_set(&sws_dict, opt, arg, FLAGS);
  547. consumed = 1;
  548. }
  549. #else
  550. if (!consumed && !strcmp(opt, "sws_flags")) {
  551. av_log(NULL, AV_LOG_WARNING, "Ignoring %s %s, due to disabled swscale\n", opt, arg);
  552. consumed = 1;
  553. }
  554. #endif
  555. #if CONFIG_SWRESAMPLE
  556. if (!consumed && (o=opt_find(&swr_class, opt, NULL, 0,
  557. AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ))) {
  558. av_dict_set(&swr_opts, opt, arg, FLAGS);
  559. consumed = 1;
  560. }
  561. #endif
  562. if (consumed)
  563. return 0;
  564. return AVERROR_OPTION_NOT_FOUND;
  565. }
  566. /*
  567. * Check whether given option is a group separator.
  568. *
  569. * @return index of the group definition that matched or -1 if none
  570. */
  571. static int match_group_separator(const OptionGroupDef *groups, int nb_groups,
  572. const char *opt)
  573. {
  574. int i;
  575. for (i = 0; i < nb_groups; i++) {
  576. const OptionGroupDef *p = &groups[i];
  577. if (p->sep && !strcmp(p->sep, opt))
  578. return i;
  579. }
  580. return -1;
  581. }
  582. /*
  583. * Finish parsing an option group.
  584. *
  585. * @param group_idx which group definition should this group belong to
  586. * @param arg argument of the group delimiting option
  587. */
  588. static int finish_group(OptionParseContext *octx, int group_idx,
  589. const char *arg)
  590. {
  591. OptionGroupList *l = &octx->groups[group_idx];
  592. OptionGroup *g;
  593. int ret;
  594. ret = GROW_ARRAY(l->groups, l->nb_groups);
  595. if (ret < 0)
  596. return ret;
  597. g = &l->groups[l->nb_groups - 1];
  598. *g = octx->cur_group;
  599. g->arg = arg;
  600. g->group_def = l->group_def;
  601. g->sws_dict = sws_dict;
  602. g->swr_opts = swr_opts;
  603. g->codec_opts = codec_opts;
  604. g->format_opts = format_opts;
  605. codec_opts = NULL;
  606. format_opts = NULL;
  607. sws_dict = NULL;
  608. swr_opts = NULL;
  609. memset(&octx->cur_group, 0, sizeof(octx->cur_group));
  610. return ret;
  611. }
  612. /*
  613. * Add an option instance to currently parsed group.
  614. */
  615. static int add_opt(OptionParseContext *octx, const OptionDef *opt,
  616. const char *key, const char *val)
  617. {
  618. int global = !(opt->flags & OPT_PERFILE);
  619. OptionGroup *g = global ? &octx->global_opts : &octx->cur_group;
  620. int ret;
  621. ret = GROW_ARRAY(g->opts, g->nb_opts);
  622. if (ret < 0)
  623. return ret;
  624. g->opts[g->nb_opts - 1].opt = opt;
  625. g->opts[g->nb_opts - 1].key = key;
  626. g->opts[g->nb_opts - 1].val = val;
  627. return 0;
  628. }
  629. static int init_parse_context(OptionParseContext *octx,
  630. const OptionGroupDef *groups, int nb_groups)
  631. {
  632. static const OptionGroupDef global_group = { "global" };
  633. int i;
  634. memset(octx, 0, sizeof(*octx));
  635. octx->groups = av_calloc(nb_groups, sizeof(*octx->groups));
  636. if (!octx->groups)
  637. return AVERROR(ENOMEM);
  638. octx->nb_groups = nb_groups;
  639. for (i = 0; i < octx->nb_groups; i++)
  640. octx->groups[i].group_def = &groups[i];
  641. octx->global_opts.group_def = &global_group;
  642. octx->global_opts.arg = "";
  643. return 0;
  644. }
  645. void uninit_parse_context(OptionParseContext *octx)
  646. {
  647. int i, j;
  648. for (i = 0; i < octx->nb_groups; i++) {
  649. OptionGroupList *l = &octx->groups[i];
  650. for (j = 0; j < l->nb_groups; j++) {
  651. av_freep(&l->groups[j].opts);
  652. av_dict_free(&l->groups[j].codec_opts);
  653. av_dict_free(&l->groups[j].format_opts);
  654. av_dict_free(&l->groups[j].sws_dict);
  655. av_dict_free(&l->groups[j].swr_opts);
  656. }
  657. av_freep(&l->groups);
  658. }
  659. av_freep(&octx->groups);
  660. av_freep(&octx->cur_group.opts);
  661. av_freep(&octx->global_opts.opts);
  662. uninit_opts();
  663. }
  664. int split_commandline(OptionParseContext *octx, int argc, char *argv[],
  665. const OptionDef *options,
  666. const OptionGroupDef *groups, int nb_groups)
  667. {
  668. int ret;
  669. int optindex = 1;
  670. int dashdash = -2;
  671. /* perform system-dependent conversions for arguments list */
  672. prepare_app_arguments(&argc, &argv);
  673. ret = init_parse_context(octx, groups, nb_groups);
  674. if (ret < 0)
  675. return ret;
  676. av_log(NULL, AV_LOG_DEBUG, "Splitting the commandline.\n");
  677. while (optindex < argc) {
  678. const char *opt = argv[optindex++], *arg;
  679. const OptionDef *po;
  680. int group_idx;
  681. av_log(NULL, AV_LOG_DEBUG, "Reading option '%s' ...", opt);
  682. if (opt[0] == '-' && opt[1] == '-' && !opt[2]) {
  683. dashdash = optindex;
  684. continue;
  685. }
  686. /* unnamed group separators, e.g. output filename */
  687. if (opt[0] != '-' || !opt[1] || dashdash+1 == optindex) {
  688. ret = finish_group(octx, 0, opt);
  689. if (ret < 0)
  690. return ret;
  691. av_log(NULL, AV_LOG_DEBUG, " matched as %s.\n", groups[0].name);
  692. continue;
  693. }
  694. opt++;
  695. #define GET_ARG(arg) \
  696. do { \
  697. arg = argv[optindex++]; \
  698. if (!arg) { \
  699. av_log(NULL, AV_LOG_ERROR, "Missing argument for option '%s'.\n", opt);\
  700. return AVERROR(EINVAL); \
  701. } \
  702. } while (0)
  703. /* named group separators, e.g. -i */
  704. group_idx = match_group_separator(groups, nb_groups, opt);
  705. if (group_idx >= 0) {
  706. GET_ARG(arg);
  707. ret = finish_group(octx, group_idx, arg);
  708. if (ret < 0)
  709. return ret;
  710. av_log(NULL, AV_LOG_DEBUG, " matched as %s with argument '%s'.\n",
  711. groups[group_idx].name, arg);
  712. continue;
  713. }
  714. /* normal options */
  715. po = find_option(options, opt);
  716. if (po->name) {
  717. if (po->flags & OPT_EXIT) {
  718. /* optional argument, e.g. -h */
  719. arg = argv[optindex++];
  720. } else if (opt_has_arg(po)) {
  721. GET_ARG(arg);
  722. } else {
  723. arg = "1";
  724. }
  725. ret = add_opt(octx, po, opt, arg);
  726. if (ret < 0)
  727. return ret;
  728. av_log(NULL, AV_LOG_DEBUG, " matched as option '%s' (%s) with "
  729. "argument '%s'.\n", po->name, po->help, arg);
  730. continue;
  731. }
  732. /* AVOptions */
  733. if (argv[optindex]) {
  734. ret = opt_default(NULL, opt, argv[optindex]);
  735. if (ret >= 0) {
  736. av_log(NULL, AV_LOG_DEBUG, " matched as AVOption '%s' with "
  737. "argument '%s'.\n", opt, argv[optindex]);
  738. optindex++;
  739. continue;
  740. } else if (ret != AVERROR_OPTION_NOT_FOUND) {
  741. av_log(NULL, AV_LOG_ERROR, "Error parsing option '%s' "
  742. "with argument '%s'.\n", opt, argv[optindex]);
  743. return ret;
  744. }
  745. }
  746. /* boolean -nofoo options */
  747. if (opt[0] == 'n' && opt[1] == 'o' &&
  748. (po = find_option(options, opt + 2)) &&
  749. po->name && po->type == OPT_TYPE_BOOL) {
  750. ret = add_opt(octx, po, opt, "0");
  751. if (ret < 0)
  752. return ret;
  753. av_log(NULL, AV_LOG_DEBUG, " matched as option '%s' (%s) with "
  754. "argument 0.\n", po->name, po->help);
  755. continue;
  756. }
  757. av_log(NULL, AV_LOG_ERROR, "Unrecognized option '%s'.\n", opt);
  758. return AVERROR_OPTION_NOT_FOUND;
  759. }
  760. if (octx->cur_group.nb_opts || codec_opts || format_opts)
  761. av_log(NULL, AV_LOG_WARNING, "Trailing option(s) found in the "
  762. "command: may be ignored.\n");
  763. av_log(NULL, AV_LOG_DEBUG, "Finished splitting the commandline.\n");
  764. return 0;
  765. }
  766. int read_yesno(void)
  767. {
  768. int c = getchar();
  769. int yesno = (av_toupper(c) == 'Y');
  770. while (c != '\n' && c != EOF)
  771. c = getchar();
  772. return yesno;
  773. }
  774. FILE *get_preset_file(char *filename, size_t filename_size,
  775. const char *preset_name, int is_path,
  776. const char *codec_name)
  777. {
  778. FILE *f = NULL;
  779. int i;
  780. #if HAVE_GETMODULEHANDLE && defined(_WIN32)
  781. char *datadir = NULL;
  782. #endif
  783. char *env_home = getenv_utf8("HOME");
  784. char *env_ffmpeg_datadir = getenv_utf8("FFMPEG_DATADIR");
  785. const char *base[3] = { env_ffmpeg_datadir,
  786. env_home, /* index=1(HOME) is special: search in a .ffmpeg subfolder */
  787. FFMPEG_DATADIR, };
  788. if (is_path) {
  789. av_strlcpy(filename, preset_name, filename_size);
  790. f = fopen_utf8(filename, "r");
  791. } else {
  792. #if HAVE_GETMODULEHANDLE && defined(_WIN32)
  793. wchar_t *datadir_w = get_module_filename(NULL);
  794. base[2] = NULL;
  795. if (wchartoutf8(datadir_w, &datadir))
  796. datadir = NULL;
  797. av_free(datadir_w);
  798. if (datadir)
  799. {
  800. char *ls;
  801. for (ls = datadir; *ls; ls++)
  802. if (*ls == '\\') *ls = '/';
  803. if (ls = strrchr(datadir, '/'))
  804. {
  805. ptrdiff_t datadir_len = ls - datadir;
  806. size_t desired_size = datadir_len + strlen("/ffpresets") + 1;
  807. char *new_datadir = av_realloc_array(
  808. datadir, desired_size, sizeof *datadir);
  809. if (new_datadir) {
  810. datadir = new_datadir;
  811. datadir[datadir_len] = 0;
  812. strncat(datadir, "/ffpresets", desired_size - 1 - datadir_len);
  813. base[2] = datadir;
  814. }
  815. }
  816. }
  817. #endif
  818. for (i = 0; i < 3 && !f; i++) {
  819. if (!base[i])
  820. continue;
  821. snprintf(filename, filename_size, "%s%s/%s.ffpreset", base[i],
  822. i != 1 ? "" : "/.ffmpeg", preset_name);
  823. f = fopen_utf8(filename, "r");
  824. if (!f && codec_name) {
  825. snprintf(filename, filename_size,
  826. "%s%s/%s-%s.ffpreset",
  827. base[i], i != 1 ? "" : "/.ffmpeg", codec_name,
  828. preset_name);
  829. f = fopen_utf8(filename, "r");
  830. }
  831. }
  832. }
  833. #if HAVE_GETMODULEHANDLE && defined(_WIN32)
  834. av_free(datadir);
  835. #endif
  836. freeenv_utf8(env_ffmpeg_datadir);
  837. freeenv_utf8(env_home);
  838. return f;
  839. }
  840. int cmdutils_isalnum(char c)
  841. {
  842. return (c >= '0' && c <= '9') ||
  843. (c >= 'A' && c <= 'Z') ||
  844. (c >= 'a' && c <= 'z');
  845. }
  846. void stream_specifier_uninit(StreamSpecifier *ss)
  847. {
  848. av_freep(&ss->meta_key);
  849. av_freep(&ss->meta_val);
  850. av_freep(&ss->remainder);
  851. memset(ss, 0, sizeof(*ss));
  852. }
  853. int stream_specifier_parse(StreamSpecifier *ss, const char *spec,
  854. int allow_remainder, void *logctx)
  855. {
  856. char *endptr;
  857. int ret;
  858. memset(ss, 0, sizeof(*ss));
  859. ss->idx = -1;
  860. ss->media_type = AVMEDIA_TYPE_UNKNOWN;
  861. ss->stream_list = STREAM_LIST_ALL;
  862. av_log(logctx, AV_LOG_TRACE, "Parsing stream specifier: %s\n", spec);
  863. while (*spec) {
  864. if (*spec <= '9' && *spec >= '0') { /* opt:index */
  865. ss->idx = strtol(spec, &endptr, 0);
  866. av_assert0(endptr > spec);
  867. spec = endptr;
  868. av_log(logctx, AV_LOG_TRACE,
  869. "Parsed index: %d; remainder: %s\n", ss->idx, spec);
  870. // this terminates the specifier
  871. break;
  872. } else if ((*spec == 'v' || *spec == 'a' || *spec == 's' ||
  873. *spec == 'd' || *spec == 't' || *spec == 'V') &&
  874. !cmdutils_isalnum(*(spec + 1))) { /* opt:[vasdtV] */
  875. if (ss->media_type != AVMEDIA_TYPE_UNKNOWN) {
  876. av_log(logctx, AV_LOG_ERROR, "Stream type specified multiple times\n");
  877. ret = AVERROR(EINVAL);
  878. goto fail;
  879. }
  880. switch (*spec++) {
  881. case 'v': ss->media_type = AVMEDIA_TYPE_VIDEO; break;
  882. case 'a': ss->media_type = AVMEDIA_TYPE_AUDIO; break;
  883. case 's': ss->media_type = AVMEDIA_TYPE_SUBTITLE; break;
  884. case 'd': ss->media_type = AVMEDIA_TYPE_DATA; break;
  885. case 't': ss->media_type = AVMEDIA_TYPE_ATTACHMENT; break;
  886. case 'V': ss->media_type = AVMEDIA_TYPE_VIDEO;
  887. ss->no_apic = 1; break;
  888. default: av_assert0(0);
  889. }
  890. av_log(logctx, AV_LOG_TRACE, "Parsed media type: %s; remainder: %s\n",
  891. av_get_media_type_string(ss->media_type), spec);
  892. } else if (*spec == 'g' && *(spec + 1) == ':') {
  893. if (ss->stream_list != STREAM_LIST_ALL)
  894. goto multiple_stream_lists;
  895. spec += 2;
  896. if (*spec == '#' || (*spec == 'i' && *(spec + 1) == ':')) {
  897. ss->stream_list = STREAM_LIST_GROUP_ID;
  898. spec += 1 + (*spec == 'i');
  899. } else
  900. ss->stream_list = STREAM_LIST_GROUP_IDX;
  901. ss->list_id = strtol(spec, &endptr, 0);
  902. if (spec == endptr) {
  903. av_log(logctx, AV_LOG_ERROR, "Expected stream group idx/ID, got: %s\n", spec);
  904. ret = AVERROR(EINVAL);
  905. goto fail;
  906. }
  907. spec = endptr;
  908. av_log(logctx, AV_LOG_TRACE, "Parsed stream group %s: %"PRId64"; remainder: %s\n",
  909. ss->stream_list == STREAM_LIST_GROUP_ID ? "ID" : "index", ss->list_id, spec);
  910. } else if (*spec == 'p' && *(spec + 1) == ':') {
  911. if (ss->stream_list != STREAM_LIST_ALL)
  912. goto multiple_stream_lists;
  913. ss->stream_list = STREAM_LIST_PROGRAM;
  914. spec += 2;
  915. ss->list_id = strtol(spec, &endptr, 0);
  916. if (spec == endptr) {
  917. av_log(logctx, AV_LOG_ERROR, "Expected program ID, got: %s\n", spec);
  918. ret = AVERROR(EINVAL);
  919. goto fail;
  920. }
  921. spec = endptr;
  922. av_log(logctx, AV_LOG_TRACE,
  923. "Parsed program ID: %"PRId64"; remainder: %s\n", ss->list_id, spec);
  924. } else if (!strncmp(spec, "disp:", 5)) {
  925. const AVClass *st_class = av_stream_get_class();
  926. const AVOption *o = av_opt_find(&st_class, "disposition", NULL, 0, AV_OPT_SEARCH_FAKE_OBJ);
  927. char *disp = NULL;
  928. size_t len;
  929. av_assert0(o);
  930. if (ss->disposition) {
  931. av_log(logctx, AV_LOG_ERROR, "Multiple disposition specifiers\n");
  932. ret = AVERROR(EINVAL);
  933. goto fail;
  934. }
  935. spec += 5;
  936. for (len = 0; cmdutils_isalnum(spec[len]) ||
  937. spec[len] == '_' || spec[len] == '+'; len++)
  938. continue;
  939. disp = av_strndup(spec, len);
  940. if (!disp) {
  941. ret = AVERROR(ENOMEM);
  942. goto fail;
  943. }
  944. ret = av_opt_eval_flags(&st_class, o, disp, &ss->disposition);
  945. av_freep(&disp);
  946. if (ret < 0) {
  947. av_log(logctx, AV_LOG_ERROR, "Invalid disposition specifier\n");
  948. goto fail;
  949. }
  950. spec += len;
  951. av_log(logctx, AV_LOG_TRACE,
  952. "Parsed disposition: 0x%x; remainder: %s\n", ss->disposition, spec);
  953. } else if (*spec == '#' ||
  954. (*spec == 'i' && *(spec + 1) == ':')) {
  955. if (ss->stream_list != STREAM_LIST_ALL)
  956. goto multiple_stream_lists;
  957. ss->stream_list = STREAM_LIST_STREAM_ID;
  958. spec += 1 + (*spec == 'i');
  959. ss->list_id = strtol(spec, &endptr, 0);
  960. if (spec == endptr) {
  961. av_log(logctx, AV_LOG_ERROR, "Expected stream ID, got: %s\n", spec);
  962. ret = AVERROR(EINVAL);
  963. goto fail;
  964. }
  965. spec = endptr;
  966. av_log(logctx, AV_LOG_TRACE,
  967. "Parsed stream ID: %"PRId64"; remainder: %s\n", ss->list_id, spec);
  968. // this terminates the specifier
  969. break;
  970. } else if (*spec == 'm' && *(spec + 1) == ':') {
  971. av_assert0(!ss->meta_key && !ss->meta_val);
  972. spec += 2;
  973. ss->meta_key = av_get_token(&spec, ":");
  974. if (!ss->meta_key) {
  975. ret = AVERROR(ENOMEM);
  976. goto fail;
  977. }
  978. if (*spec == ':') {
  979. spec++;
  980. ss->meta_val = av_get_token(&spec, ":");
  981. if (!ss->meta_val) {
  982. ret = AVERROR(ENOMEM);
  983. goto fail;
  984. }
  985. }
  986. av_log(logctx, AV_LOG_TRACE,
  987. "Parsed metadata: %s:%s; remainder: %s", ss->meta_key,
  988. ss->meta_val ? ss->meta_val : "<any value>", spec);
  989. // this terminates the specifier
  990. break;
  991. } else if (*spec == 'u' && (*(spec + 1) == '\0' || *(spec + 1) == ':')) {
  992. ss->usable_only = 1;
  993. spec++;
  994. av_log(logctx, AV_LOG_ERROR, "Parsed 'usable only'\n");
  995. // this terminates the specifier
  996. break;
  997. } else
  998. break;
  999. if (*spec == ':')
  1000. spec++;
  1001. }
  1002. if (*spec) {
  1003. if (!allow_remainder) {
  1004. av_log(logctx, AV_LOG_ERROR,
  1005. "Trailing garbage at the end of a stream specifier: %s\n",
  1006. spec);
  1007. ret = AVERROR(EINVAL);
  1008. goto fail;
  1009. }
  1010. if (*spec == ':')
  1011. spec++;
  1012. ss->remainder = av_strdup(spec);
  1013. if (!ss->remainder) {
  1014. ret = AVERROR(EINVAL);
  1015. goto fail;
  1016. }
  1017. }
  1018. return 0;
  1019. multiple_stream_lists:
  1020. av_log(logctx, AV_LOG_ERROR,
  1021. "Cannot combine multiple program/group designators in a "
  1022. "single stream specifier");
  1023. ret = AVERROR(EINVAL);
  1024. fail:
  1025. stream_specifier_uninit(ss);
  1026. return ret;
  1027. }
  1028. unsigned stream_specifier_match(const StreamSpecifier *ss,
  1029. const AVFormatContext *s, const AVStream *st,
  1030. void *logctx)
  1031. {
  1032. const AVStreamGroup *g = NULL;
  1033. const AVProgram *p = NULL;
  1034. int start_stream = 0, nb_streams;
  1035. int nb_matched = 0;
  1036. switch (ss->stream_list) {
  1037. case STREAM_LIST_STREAM_ID:
  1038. // <n-th> stream with given ID makes no sense and should be impossible to request
  1039. av_assert0(ss->idx < 0);
  1040. // return early if we know for sure the stream does not match
  1041. if (st->id != ss->list_id)
  1042. return 0;
  1043. start_stream = st->index;
  1044. nb_streams = st->index + 1;
  1045. break;
  1046. case STREAM_LIST_ALL:
  1047. start_stream = ss->idx >= 0 ? 0 : st->index;
  1048. nb_streams = st->index + 1;
  1049. break;
  1050. case STREAM_LIST_PROGRAM:
  1051. for (unsigned i = 0; i < s->nb_programs; i++) {
  1052. if (s->programs[i]->id == ss->list_id) {
  1053. p = s->programs[i];
  1054. break;
  1055. }
  1056. }
  1057. if (!p) {
  1058. av_log(logctx, AV_LOG_WARNING, "No program with ID %"PRId64" exists,"
  1059. " stream specifier can never match\n", ss->list_id);
  1060. return 0;
  1061. }
  1062. nb_streams = p->nb_stream_indexes;
  1063. break;
  1064. case STREAM_LIST_GROUP_ID:
  1065. for (unsigned i = 0; i < s->nb_stream_groups; i++) {
  1066. if (ss->list_id == s->stream_groups[i]->id) {
  1067. g = s->stream_groups[i];
  1068. break;
  1069. }
  1070. }
  1071. // fall-through
  1072. case STREAM_LIST_GROUP_IDX:
  1073. if (ss->stream_list == STREAM_LIST_GROUP_IDX &&
  1074. ss->list_id >= 0 && ss->list_id < s->nb_stream_groups)
  1075. g = s->stream_groups[ss->list_id];
  1076. if (!g) {
  1077. av_log(logctx, AV_LOG_WARNING, "No stream group with group %s %"
  1078. PRId64" exists, stream specifier can never match\n",
  1079. ss->stream_list == STREAM_LIST_GROUP_ID ? "ID" : "index",
  1080. ss->list_id);
  1081. return 0;
  1082. }
  1083. nb_streams = g->nb_streams;
  1084. break;
  1085. default: av_assert0(0);
  1086. }
  1087. for (int i = start_stream; i < nb_streams; i++) {
  1088. const AVStream *candidate = s->streams[g ? g->streams[i]->index :
  1089. p ? p->stream_index[i] : i];
  1090. if (ss->media_type != AVMEDIA_TYPE_UNKNOWN &&
  1091. (ss->media_type != candidate->codecpar->codec_type ||
  1092. (ss->no_apic && (candidate->disposition & AV_DISPOSITION_ATTACHED_PIC))))
  1093. continue;
  1094. if (ss->meta_key) {
  1095. const AVDictionaryEntry *tag = av_dict_get(candidate->metadata,
  1096. ss->meta_key, NULL, 0);
  1097. if (!tag)
  1098. continue;
  1099. if (ss->meta_val && strcmp(tag->value, ss->meta_val))
  1100. continue;
  1101. }
  1102. if (ss->usable_only) {
  1103. const AVCodecParameters *par = candidate->codecpar;
  1104. switch (par->codec_type) {
  1105. case AVMEDIA_TYPE_AUDIO:
  1106. if (!par->sample_rate || !par->ch_layout.nb_channels ||
  1107. par->format == AV_SAMPLE_FMT_NONE)
  1108. continue;
  1109. break;
  1110. case AVMEDIA_TYPE_VIDEO:
  1111. if (!par->width || !par->height || par->format == AV_PIX_FMT_NONE)
  1112. continue;
  1113. break;
  1114. case AVMEDIA_TYPE_UNKNOWN:
  1115. continue;
  1116. }
  1117. }
  1118. if (ss->disposition &&
  1119. (candidate->disposition & ss->disposition) != ss->disposition)
  1120. continue;
  1121. if (st == candidate)
  1122. return ss->idx < 0 || ss->idx == nb_matched;
  1123. nb_matched++;
  1124. }
  1125. return 0;
  1126. }
  1127. int check_stream_specifier(AVFormatContext *s, AVStream *st, const char *spec)
  1128. {
  1129. StreamSpecifier ss;
  1130. int ret;
  1131. ret = stream_specifier_parse(&ss, spec, 0, NULL);
  1132. if (ret < 0)
  1133. return ret;
  1134. ret = stream_specifier_match(&ss, s, st, NULL);
  1135. stream_specifier_uninit(&ss);
  1136. return ret;
  1137. }
  1138. int filter_codec_opts(const AVDictionary *opts, enum AVCodecID codec_id,
  1139. AVFormatContext *s, AVStream *st, const AVCodec *codec,
  1140. AVDictionary **dst, AVDictionary **opts_used)
  1141. {
  1142. AVDictionary *ret = NULL;
  1143. const AVDictionaryEntry *t = NULL;
  1144. int flags = s->oformat ? AV_OPT_FLAG_ENCODING_PARAM
  1145. : AV_OPT_FLAG_DECODING_PARAM;
  1146. char prefix = 0;
  1147. const AVClass *cc = avcodec_get_class();
  1148. switch (st->codecpar->codec_type) {
  1149. case AVMEDIA_TYPE_VIDEO:
  1150. prefix = 'v';
  1151. flags |= AV_OPT_FLAG_VIDEO_PARAM;
  1152. break;
  1153. case AVMEDIA_TYPE_AUDIO:
  1154. prefix = 'a';
  1155. flags |= AV_OPT_FLAG_AUDIO_PARAM;
  1156. break;
  1157. case AVMEDIA_TYPE_SUBTITLE:
  1158. prefix = 's';
  1159. flags |= AV_OPT_FLAG_SUBTITLE_PARAM;
  1160. break;
  1161. }
  1162. while (t = av_dict_iterate(opts, t)) {
  1163. const AVClass *priv_class;
  1164. char *p = strchr(t->key, ':');
  1165. int used = 0;
  1166. /* check stream specification in opt name */
  1167. if (p) {
  1168. int err = check_stream_specifier(s, st, p + 1);
  1169. if (err < 0) {
  1170. av_dict_free(&ret);
  1171. return err;
  1172. } else if (!err)
  1173. continue;
  1174. *p = 0;
  1175. }
  1176. if (av_opt_find(&cc, t->key, NULL, flags, AV_OPT_SEARCH_FAKE_OBJ) ||
  1177. !codec ||
  1178. ((priv_class = codec->priv_class) &&
  1179. av_opt_find(&priv_class, t->key, NULL, flags,
  1180. AV_OPT_SEARCH_FAKE_OBJ))) {
  1181. av_dict_set(&ret, t->key, t->value, 0);
  1182. used = 1;
  1183. } else if (t->key[0] == prefix &&
  1184. av_opt_find(&cc, t->key + 1, NULL, flags,
  1185. AV_OPT_SEARCH_FAKE_OBJ)) {
  1186. av_dict_set(&ret, t->key + 1, t->value, 0);
  1187. used = 1;
  1188. }
  1189. if (p)
  1190. *p = ':';
  1191. if (used && opts_used)
  1192. av_dict_set(opts_used, t->key, "", 0);
  1193. }
  1194. *dst = ret;
  1195. return 0;
  1196. }
  1197. int setup_find_stream_info_opts(AVFormatContext *s,
  1198. AVDictionary *local_codec_opts,
  1199. AVDictionary ***dst)
  1200. {
  1201. int ret;
  1202. AVDictionary **opts;
  1203. *dst = NULL;
  1204. if (!s->nb_streams)
  1205. return 0;
  1206. opts = av_calloc(s->nb_streams, sizeof(*opts));
  1207. if (!opts)
  1208. return AVERROR(ENOMEM);
  1209. for (int i = 0; i < s->nb_streams; i++) {
  1210. ret = filter_codec_opts(local_codec_opts, s->streams[i]->codecpar->codec_id,
  1211. s, s->streams[i], NULL, &opts[i], NULL);
  1212. if (ret < 0)
  1213. goto fail;
  1214. }
  1215. *dst = opts;
  1216. return 0;
  1217. fail:
  1218. for (int i = 0; i < s->nb_streams; i++)
  1219. av_dict_free(&opts[i]);
  1220. av_freep(&opts);
  1221. return ret;
  1222. }
  1223. int grow_array(void **array, int elem_size, int *size, int new_size)
  1224. {
  1225. if (new_size >= INT_MAX / elem_size) {
  1226. av_log(NULL, AV_LOG_ERROR, "Array too big.\n");
  1227. return AVERROR(ERANGE);
  1228. }
  1229. if (*size < new_size) {
  1230. uint8_t *tmp = av_realloc_array(*array, new_size, elem_size);
  1231. if (!tmp)
  1232. return AVERROR(ENOMEM);
  1233. memset(tmp + *size*elem_size, 0, (new_size-*size) * elem_size);
  1234. *size = new_size;
  1235. *array = tmp;
  1236. return 0;
  1237. }
  1238. return 0;
  1239. }
  1240. void *allocate_array_elem(void *ptr, size_t elem_size, int *nb_elems)
  1241. {
  1242. void *new_elem;
  1243. if (!(new_elem = av_mallocz(elem_size)) ||
  1244. av_dynarray_add_nofree(ptr, nb_elems, new_elem) < 0)
  1245. return NULL;
  1246. return new_elem;
  1247. }
  1248. double get_rotation(const int32_t *displaymatrix)
  1249. {
  1250. double theta = 0;
  1251. if (displaymatrix)
  1252. theta = -round(av_display_rotation_get(displaymatrix));
  1253. theta -= 360*floor(theta/360 + 0.9/360);
  1254. if (fabs(theta - 90*round(theta/90)) > 2)
  1255. av_log(NULL, AV_LOG_WARNING, "Odd rotation angle.\n"
  1256. "If you want to help, upload a sample "
  1257. "of this file to https://streams.videolan.org/upload/ "
  1258. "and contact the ffmpeg-devel mailing list. (ffmpeg-devel@ffmpeg.org)");
  1259. return theta;
  1260. }
  1261. /* read file contents into a string */
  1262. char *file_read(const char *filename)
  1263. {
  1264. AVIOContext *pb = NULL;
  1265. int ret = avio_open(&pb, filename, AVIO_FLAG_READ);
  1266. AVBPrint bprint;
  1267. char *str;
  1268. if (ret < 0) {
  1269. av_log(NULL, AV_LOG_ERROR, "Error opening file %s.\n", filename);
  1270. return NULL;
  1271. }
  1272. av_bprint_init(&bprint, 0, AV_BPRINT_SIZE_UNLIMITED);
  1273. ret = avio_read_to_bprint(pb, &bprint, SIZE_MAX);
  1274. avio_closep(&pb);
  1275. if (ret < 0) {
  1276. av_bprint_finalize(&bprint, NULL);
  1277. return NULL;
  1278. }
  1279. ret = av_bprint_finalize(&bprint, &str);
  1280. if (ret < 0)
  1281. return NULL;
  1282. return str;
  1283. }
  1284. void remove_avoptions(AVDictionary **a, AVDictionary *b)
  1285. {
  1286. const AVDictionaryEntry *t = NULL;
  1287. while ((t = av_dict_iterate(b, t))) {
  1288. av_dict_set(a, t->key, NULL, AV_DICT_MATCH_CASE);
  1289. }
  1290. }
  1291. int check_avoptions(AVDictionary *m)
  1292. {
  1293. const AVDictionaryEntry *t = av_dict_iterate(m, NULL);
  1294. if (t) {
  1295. av_log(NULL, AV_LOG_FATAL, "Option %s not found.\n", t->key);
  1296. return AVERROR_OPTION_NOT_FOUND;
  1297. }
  1298. return 0;
  1299. }