cmdutils.c 46 KB

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