cmdutils.c 44 KB

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