You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2076 lines
65KB

  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 "libavfilter/avfilter.h"
  33. #include "libavdevice/avdevice.h"
  34. #include "libavresample/avresample.h"
  35. #include "libswscale/swscale.h"
  36. #include "libswresample/swresample.h"
  37. #include "libpostproc/postprocess.h"
  38. #include "libavutil/avassert.h"
  39. #include "libavutil/avstring.h"
  40. #include "libavutil/bprint.h"
  41. #include "libavutil/mathematics.h"
  42. #include "libavutil/imgutils.h"
  43. #include "libavutil/parseutils.h"
  44. #include "libavutil/pixdesc.h"
  45. #include "libavutil/eval.h"
  46. #include "libavutil/dict.h"
  47. #include "libavutil/opt.h"
  48. #include "libavutil/cpu.h"
  49. #include "libavutil/ffversion.h"
  50. #include "cmdutils.h"
  51. #if CONFIG_NETWORK
  52. #include "libavformat/network.h"
  53. #endif
  54. #if HAVE_SYS_RESOURCE_H
  55. #include <sys/time.h>
  56. #include <sys/resource.h>
  57. #endif
  58. static int init_report(const char *env);
  59. struct SwsContext *sws_opts;
  60. AVDictionary *swr_opts;
  61. AVDictionary *format_opts, *codec_opts, *resample_opts;
  62. static FILE *report_file;
  63. static int report_file_level = AV_LOG_DEBUG;
  64. int hide_banner = 0;
  65. void init_opts(void)
  66. {
  67. if(CONFIG_SWSCALE)
  68. sws_opts = sws_getContext(16, 16, 0, 16, 16, 0, SWS_BICUBIC,
  69. NULL, NULL, NULL);
  70. }
  71. void uninit_opts(void)
  72. {
  73. #if CONFIG_SWSCALE
  74. sws_freeContext(sws_opts);
  75. sws_opts = NULL;
  76. #endif
  77. av_dict_free(&swr_opts);
  78. av_dict_free(&format_opts);
  79. av_dict_free(&codec_opts);
  80. av_dict_free(&resample_opts);
  81. }
  82. void log_callback_help(void *ptr, int level, const char *fmt, va_list vl)
  83. {
  84. vfprintf(stdout, fmt, vl);
  85. }
  86. static void log_callback_report(void *ptr, int level, const char *fmt, va_list vl)
  87. {
  88. va_list vl2;
  89. char line[1024];
  90. static int print_prefix = 1;
  91. va_copy(vl2, vl);
  92. av_log_default_callback(ptr, level, fmt, vl);
  93. av_log_format_line(ptr, level, fmt, vl2, line, sizeof(line), &print_prefix);
  94. va_end(vl2);
  95. if (report_file_level >= level) {
  96. fputs(line, report_file);
  97. fflush(report_file);
  98. }
  99. }
  100. void init_dynload(void)
  101. {
  102. #if HAVE_SETDLLDIRECTORY
  103. /* Calling SetDllDirectory with the empty string (but not NULL) removes the
  104. * current working directory from the DLL search path as a security pre-caution. */
  105. SetDllDirectory("");
  106. #endif
  107. }
  108. static void (*program_exit)(int ret);
  109. void register_exit(void (*cb)(int ret))
  110. {
  111. program_exit = cb;
  112. }
  113. void exit_program(int ret)
  114. {
  115. if (program_exit)
  116. program_exit(ret);
  117. exit(ret);
  118. }
  119. double parse_number_or_die(const char *context, const char *numstr, int type,
  120. double min, double max)
  121. {
  122. char *tail;
  123. const char *error;
  124. double d = av_strtod(numstr, &tail);
  125. if (*tail)
  126. error = "Expected number for %s but found: %s\n";
  127. else if (d < min || d > max)
  128. error = "The value for %s was %s which is not within %f - %f\n";
  129. else if (type == OPT_INT64 && (int64_t)d != d)
  130. error = "Expected int64 for %s but found %s\n";
  131. else if (type == OPT_INT && (int)d != d)
  132. error = "Expected int for %s but found %s\n";
  133. else
  134. return d;
  135. av_log(NULL, AV_LOG_FATAL, error, context, numstr, min, max);
  136. exit_program(1);
  137. return 0;
  138. }
  139. int64_t parse_time_or_die(const char *context, const char *timestr,
  140. int is_duration)
  141. {
  142. int64_t us;
  143. if (av_parse_time(&us, timestr, is_duration) < 0) {
  144. av_log(NULL, AV_LOG_FATAL, "Invalid %s specification for %s: %s\n",
  145. is_duration ? "duration" : "date", context, timestr);
  146. exit_program(1);
  147. }
  148. return us;
  149. }
  150. void show_help_options(const OptionDef *options, const char *msg, int req_flags,
  151. int rej_flags, int alt_flags)
  152. {
  153. const OptionDef *po;
  154. int first;
  155. first = 1;
  156. for (po = options; po->name; po++) {
  157. char buf[64];
  158. if (((po->flags & req_flags) != req_flags) ||
  159. (alt_flags && !(po->flags & alt_flags)) ||
  160. (po->flags & rej_flags))
  161. continue;
  162. if (first) {
  163. printf("%s\n", msg);
  164. first = 0;
  165. }
  166. av_strlcpy(buf, po->name, sizeof(buf));
  167. if (po->argname) {
  168. av_strlcat(buf, " ", sizeof(buf));
  169. av_strlcat(buf, po->argname, sizeof(buf));
  170. }
  171. printf("-%-17s %s\n", buf, po->help);
  172. }
  173. printf("\n");
  174. }
  175. void show_help_children(const AVClass *class, int flags)
  176. {
  177. const AVClass *child = NULL;
  178. if (class->option) {
  179. av_opt_show2(&class, NULL, flags, 0);
  180. printf("\n");
  181. }
  182. while (child = av_opt_child_class_next(class, child))
  183. show_help_children(child, flags);
  184. }
  185. static const OptionDef *find_option(const OptionDef *po, const char *name)
  186. {
  187. const char *p = strchr(name, ':');
  188. int len = p ? p - name : strlen(name);
  189. while (po->name) {
  190. if (!strncmp(name, po->name, len) && strlen(po->name) == len)
  191. break;
  192. po++;
  193. }
  194. return po;
  195. }
  196. /* _WIN32 means using the windows libc - cygwin doesn't define that
  197. * by default. HAVE_COMMANDLINETOARGVW is true on cygwin, while
  198. * it doesn't provide the actual command line via GetCommandLineW(). */
  199. #if HAVE_COMMANDLINETOARGVW && defined(_WIN32)
  200. #include <windows.h>
  201. #include <shellapi.h>
  202. /* Will be leaked on exit */
  203. static char** win32_argv_utf8 = NULL;
  204. static int win32_argc = 0;
  205. /**
  206. * Prepare command line arguments for executable.
  207. * For Windows - perform wide-char to UTF-8 conversion.
  208. * Input arguments should be main() function arguments.
  209. * @param argc_ptr Arguments number (including executable)
  210. * @param argv_ptr Arguments list.
  211. */
  212. static void prepare_app_arguments(int *argc_ptr, char ***argv_ptr)
  213. {
  214. char *argstr_flat;
  215. wchar_t **argv_w;
  216. int i, buffsize = 0, offset = 0;
  217. if (win32_argv_utf8) {
  218. *argc_ptr = win32_argc;
  219. *argv_ptr = win32_argv_utf8;
  220. return;
  221. }
  222. win32_argc = 0;
  223. argv_w = CommandLineToArgvW(GetCommandLineW(), &win32_argc);
  224. if (win32_argc <= 0 || !argv_w)
  225. return;
  226. /* determine the UTF-8 buffer size (including NULL-termination symbols) */
  227. for (i = 0; i < win32_argc; i++)
  228. buffsize += WideCharToMultiByte(CP_UTF8, 0, argv_w[i], -1,
  229. NULL, 0, NULL, NULL);
  230. win32_argv_utf8 = av_mallocz(sizeof(char *) * (win32_argc + 1) + buffsize);
  231. argstr_flat = (char *)win32_argv_utf8 + sizeof(char *) * (win32_argc + 1);
  232. if (!win32_argv_utf8) {
  233. LocalFree(argv_w);
  234. return;
  235. }
  236. for (i = 0; i < win32_argc; i++) {
  237. win32_argv_utf8[i] = &argstr_flat[offset];
  238. offset += WideCharToMultiByte(CP_UTF8, 0, argv_w[i], -1,
  239. &argstr_flat[offset],
  240. buffsize - offset, NULL, NULL);
  241. }
  242. win32_argv_utf8[i] = NULL;
  243. LocalFree(argv_w);
  244. *argc_ptr = win32_argc;
  245. *argv_ptr = win32_argv_utf8;
  246. }
  247. #else
  248. static inline void prepare_app_arguments(int *argc_ptr, char ***argv_ptr)
  249. {
  250. /* nothing to do */
  251. }
  252. #endif /* HAVE_COMMANDLINETOARGVW */
  253. static int write_option(void *optctx, const OptionDef *po, const char *opt,
  254. const char *arg)
  255. {
  256. /* new-style options contain an offset into optctx, old-style address of
  257. * a global var*/
  258. void *dst = po->flags & (OPT_OFFSET | OPT_SPEC) ?
  259. (uint8_t *)optctx + po->u.off : po->u.dst_ptr;
  260. int *dstcount;
  261. if (po->flags & OPT_SPEC) {
  262. SpecifierOpt **so = dst;
  263. char *p = strchr(opt, ':');
  264. dstcount = (int *)(so + 1);
  265. *so = grow_array(*so, sizeof(**so), dstcount, *dstcount + 1);
  266. (*so)[*dstcount - 1].specifier = av_strdup(p ? p + 1 : "");
  267. dst = &(*so)[*dstcount - 1].u;
  268. }
  269. if (po->flags & OPT_STRING) {
  270. char *str;
  271. str = av_strdup(arg);
  272. av_freep(dst);
  273. *(char **)dst = str;
  274. } else if (po->flags & OPT_BOOL || po->flags & OPT_INT) {
  275. *(int *)dst = parse_number_or_die(opt, arg, OPT_INT64, INT_MIN, INT_MAX);
  276. } else if (po->flags & OPT_INT64) {
  277. *(int64_t *)dst = parse_number_or_die(opt, arg, OPT_INT64, INT64_MIN, INT64_MAX);
  278. } else if (po->flags & OPT_TIME) {
  279. *(int64_t *)dst = parse_time_or_die(opt, arg, 1);
  280. } else if (po->flags & OPT_FLOAT) {
  281. *(float *)dst = parse_number_or_die(opt, arg, OPT_FLOAT, -INFINITY, INFINITY);
  282. } else if (po->flags & OPT_DOUBLE) {
  283. *(double *)dst = parse_number_or_die(opt, arg, OPT_DOUBLE, -INFINITY, INFINITY);
  284. } else if (po->u.func_arg) {
  285. int ret = po->u.func_arg(optctx, opt, arg);
  286. if (ret < 0) {
  287. av_log(NULL, AV_LOG_ERROR,
  288. "Failed to set value '%s' for option '%s': %s\n",
  289. arg, opt, av_err2str(ret));
  290. return ret;
  291. }
  292. }
  293. if (po->flags & OPT_EXIT)
  294. exit_program(0);
  295. return 0;
  296. }
  297. int parse_option(void *optctx, const char *opt, const char *arg,
  298. const OptionDef *options)
  299. {
  300. const OptionDef *po;
  301. int ret;
  302. po = find_option(options, opt);
  303. if (!po->name && opt[0] == 'n' && opt[1] == 'o') {
  304. /* handle 'no' bool option */
  305. po = find_option(options, opt + 2);
  306. if ((po->name && (po->flags & OPT_BOOL)))
  307. arg = "0";
  308. } else if (po->flags & OPT_BOOL)
  309. arg = "1";
  310. if (!po->name)
  311. po = find_option(options, "default");
  312. if (!po->name) {
  313. av_log(NULL, AV_LOG_ERROR, "Unrecognized option '%s'\n", opt);
  314. return AVERROR(EINVAL);
  315. }
  316. if (po->flags & HAS_ARG && !arg) {
  317. av_log(NULL, AV_LOG_ERROR, "Missing argument for option '%s'\n", opt);
  318. return AVERROR(EINVAL);
  319. }
  320. ret = write_option(optctx, po, opt, arg);
  321. if (ret < 0)
  322. return ret;
  323. return !!(po->flags & HAS_ARG);
  324. }
  325. void parse_options(void *optctx, int argc, char **argv, const OptionDef *options,
  326. void (*parse_arg_function)(void *, const char*))
  327. {
  328. const char *opt;
  329. int optindex, handleoptions = 1, ret;
  330. /* perform system-dependent conversions for arguments list */
  331. prepare_app_arguments(&argc, &argv);
  332. /* parse options */
  333. optindex = 1;
  334. while (optindex < argc) {
  335. opt = argv[optindex++];
  336. if (handleoptions && opt[0] == '-' && opt[1] != '\0') {
  337. if (opt[1] == '-' && opt[2] == '\0') {
  338. handleoptions = 0;
  339. continue;
  340. }
  341. opt++;
  342. if ((ret = parse_option(optctx, opt, argv[optindex], options)) < 0)
  343. exit_program(1);
  344. optindex += ret;
  345. } else {
  346. if (parse_arg_function)
  347. parse_arg_function(optctx, opt);
  348. }
  349. }
  350. }
  351. int parse_optgroup(void *optctx, OptionGroup *g)
  352. {
  353. int i, ret;
  354. av_log(NULL, AV_LOG_DEBUG, "Parsing a group of options: %s %s.\n",
  355. g->group_def->name, g->arg);
  356. for (i = 0; i < g->nb_opts; i++) {
  357. Option *o = &g->opts[i];
  358. if (g->group_def->flags &&
  359. !(g->group_def->flags & o->opt->flags)) {
  360. av_log(NULL, AV_LOG_ERROR, "Option %s (%s) cannot be applied to "
  361. "%s %s -- you are trying to apply an input option to an "
  362. "output file or vice versa. Move this option before the "
  363. "file it belongs to.\n", o->key, o->opt->help,
  364. g->group_def->name, g->arg);
  365. return AVERROR(EINVAL);
  366. }
  367. av_log(NULL, AV_LOG_DEBUG, "Applying option %s (%s) with argument %s.\n",
  368. o->key, o->opt->help, o->val);
  369. ret = write_option(optctx, o->opt, o->key, o->val);
  370. if (ret < 0)
  371. return ret;
  372. }
  373. av_log(NULL, AV_LOG_DEBUG, "Successfully parsed a group of options.\n");
  374. return 0;
  375. }
  376. int locate_option(int argc, char **argv, const OptionDef *options,
  377. const char *optname)
  378. {
  379. const OptionDef *po;
  380. int i;
  381. for (i = 1; i < argc; i++) {
  382. const char *cur_opt = argv[i];
  383. if (*cur_opt++ != '-')
  384. continue;
  385. po = find_option(options, cur_opt);
  386. if (!po->name && cur_opt[0] == 'n' && cur_opt[1] == 'o')
  387. po = find_option(options, cur_opt + 2);
  388. if ((!po->name && !strcmp(cur_opt, optname)) ||
  389. (po->name && !strcmp(optname, po->name)))
  390. return i;
  391. if (!po->name || po->flags & HAS_ARG)
  392. i++;
  393. }
  394. return 0;
  395. }
  396. static void dump_argument(const char *a)
  397. {
  398. const unsigned char *p;
  399. for (p = a; *p; p++)
  400. if (!((*p >= '+' && *p <= ':') || (*p >= '@' && *p <= 'Z') ||
  401. *p == '_' || (*p >= 'a' && *p <= 'z')))
  402. break;
  403. if (!*p) {
  404. fputs(a, report_file);
  405. return;
  406. }
  407. fputc('"', report_file);
  408. for (p = a; *p; p++) {
  409. if (*p == '\\' || *p == '"' || *p == '$' || *p == '`')
  410. fprintf(report_file, "\\%c", *p);
  411. else if (*p < ' ' || *p > '~')
  412. fprintf(report_file, "\\x%02x", *p);
  413. else
  414. fputc(*p, report_file);
  415. }
  416. fputc('"', report_file);
  417. }
  418. void parse_loglevel(int argc, char **argv, const OptionDef *options)
  419. {
  420. int idx = locate_option(argc, argv, options, "loglevel");
  421. const char *env;
  422. if (!idx)
  423. idx = locate_option(argc, argv, options, "v");
  424. if (idx && argv[idx + 1])
  425. opt_loglevel(NULL, "loglevel", argv[idx + 1]);
  426. idx = locate_option(argc, argv, options, "report");
  427. if ((env = getenv("FFREPORT")) || idx) {
  428. init_report(env);
  429. if (report_file) {
  430. int i;
  431. fprintf(report_file, "Command line:\n");
  432. for (i = 0; i < argc; i++) {
  433. dump_argument(argv[i]);
  434. fputc(i < argc - 1 ? ' ' : '\n', report_file);
  435. }
  436. fflush(report_file);
  437. }
  438. }
  439. idx = locate_option(argc, argv, options, "hide_banner");
  440. if (idx)
  441. hide_banner = 1;
  442. }
  443. static const AVOption *opt_find(void *obj, const char *name, const char *unit,
  444. int opt_flags, int search_flags)
  445. {
  446. const AVOption *o = av_opt_find(obj, name, unit, opt_flags, search_flags);
  447. if(o && !o->flags)
  448. return NULL;
  449. return o;
  450. }
  451. #define FLAGS (o->type == AV_OPT_TYPE_FLAGS) ? AV_DICT_APPEND : 0
  452. int opt_default(void *optctx, const char *opt, const char *arg)
  453. {
  454. const AVOption *o;
  455. int consumed = 0;
  456. char opt_stripped[128];
  457. const char *p;
  458. const AVClass *cc = avcodec_get_class(), *fc = avformat_get_class();
  459. #if CONFIG_AVRESAMPLE
  460. const AVClass *rc = avresample_get_class();
  461. #endif
  462. const AVClass *sc, *swr_class;
  463. if (!strcmp(opt, "debug") || !strcmp(opt, "fdebug"))
  464. av_log_set_level(AV_LOG_DEBUG);
  465. if (!(p = strchr(opt, ':')))
  466. p = opt + strlen(opt);
  467. av_strlcpy(opt_stripped, opt, FFMIN(sizeof(opt_stripped), p - opt + 1));
  468. if ((o = opt_find(&cc, opt_stripped, NULL, 0,
  469. AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ)) ||
  470. ((opt[0] == 'v' || opt[0] == 'a' || opt[0] == 's') &&
  471. (o = opt_find(&cc, opt + 1, NULL, 0, AV_OPT_SEARCH_FAKE_OBJ)))) {
  472. av_dict_set(&codec_opts, opt, arg, FLAGS);
  473. consumed = 1;
  474. }
  475. if ((o = opt_find(&fc, opt, NULL, 0,
  476. AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ))) {
  477. av_dict_set(&format_opts, opt, arg, FLAGS);
  478. if (consumed)
  479. av_log(NULL, AV_LOG_VERBOSE, "Routing option %s to both codec and muxer layer\n", opt);
  480. consumed = 1;
  481. }
  482. #if CONFIG_SWSCALE
  483. sc = sws_get_class();
  484. if (!consumed && opt_find(&sc, opt, NULL, 0,
  485. AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ)) {
  486. // XXX we only support sws_flags, not arbitrary sws options
  487. int ret = av_opt_set(sws_opts, opt, arg, 0);
  488. if (ret < 0) {
  489. av_log(NULL, AV_LOG_ERROR, "Error setting option %s.\n", opt);
  490. return ret;
  491. }
  492. consumed = 1;
  493. }
  494. #else
  495. if (!consumed && !strcmp(opt, "sws_flags")) {
  496. av_log(NULL, AV_LOG_WARNING, "Ignoring %s %s, due to disabled swscale\n", opt, arg);
  497. consumed = 1;
  498. }
  499. #endif
  500. #if CONFIG_SWRESAMPLE
  501. swr_class = swr_get_class();
  502. if (!consumed && (o=opt_find(&swr_class, opt, NULL, 0,
  503. AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ))) {
  504. struct SwrContext *swr = swr_alloc();
  505. int ret = av_opt_set(swr, opt, arg, 0);
  506. swr_free(&swr);
  507. if (ret < 0) {
  508. av_log(NULL, AV_LOG_ERROR, "Error setting option %s.\n", opt);
  509. return ret;
  510. }
  511. av_dict_set(&swr_opts, opt, arg, FLAGS);
  512. consumed = 1;
  513. }
  514. #endif
  515. #if CONFIG_AVRESAMPLE
  516. if ((o=opt_find(&rc, opt, NULL, 0,
  517. AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ))) {
  518. av_dict_set(&resample_opts, opt, arg, FLAGS);
  519. consumed = 1;
  520. }
  521. #endif
  522. if (consumed)
  523. return 0;
  524. return AVERROR_OPTION_NOT_FOUND;
  525. }
  526. /*
  527. * Check whether given option is a group separator.
  528. *
  529. * @return index of the group definition that matched or -1 if none
  530. */
  531. static int match_group_separator(const OptionGroupDef *groups, int nb_groups,
  532. const char *opt)
  533. {
  534. int i;
  535. for (i = 0; i < nb_groups; i++) {
  536. const OptionGroupDef *p = &groups[i];
  537. if (p->sep && !strcmp(p->sep, opt))
  538. return i;
  539. }
  540. return -1;
  541. }
  542. /*
  543. * Finish parsing an option group.
  544. *
  545. * @param group_idx which group definition should this group belong to
  546. * @param arg argument of the group delimiting option
  547. */
  548. static void finish_group(OptionParseContext *octx, int group_idx,
  549. const char *arg)
  550. {
  551. OptionGroupList *l = &octx->groups[group_idx];
  552. OptionGroup *g;
  553. GROW_ARRAY(l->groups, l->nb_groups);
  554. g = &l->groups[l->nb_groups - 1];
  555. *g = octx->cur_group;
  556. g->arg = arg;
  557. g->group_def = l->group_def;
  558. #if CONFIG_SWSCALE
  559. g->sws_opts = sws_opts;
  560. #endif
  561. g->swr_opts = swr_opts;
  562. g->codec_opts = codec_opts;
  563. g->format_opts = format_opts;
  564. g->resample_opts = resample_opts;
  565. codec_opts = NULL;
  566. format_opts = NULL;
  567. resample_opts = NULL;
  568. #if CONFIG_SWSCALE
  569. sws_opts = NULL;
  570. #endif
  571. swr_opts = NULL;
  572. init_opts();
  573. memset(&octx->cur_group, 0, sizeof(octx->cur_group));
  574. }
  575. /*
  576. * Add an option instance to currently parsed group.
  577. */
  578. static void add_opt(OptionParseContext *octx, const OptionDef *opt,
  579. const char *key, const char *val)
  580. {
  581. int global = !(opt->flags & (OPT_PERFILE | OPT_SPEC | OPT_OFFSET));
  582. OptionGroup *g = global ? &octx->global_opts : &octx->cur_group;
  583. GROW_ARRAY(g->opts, g->nb_opts);
  584. g->opts[g->nb_opts - 1].opt = opt;
  585. g->opts[g->nb_opts - 1].key = key;
  586. g->opts[g->nb_opts - 1].val = val;
  587. }
  588. static void init_parse_context(OptionParseContext *octx,
  589. const OptionGroupDef *groups, int nb_groups)
  590. {
  591. static const OptionGroupDef global_group = { "global" };
  592. int i;
  593. memset(octx, 0, sizeof(*octx));
  594. octx->nb_groups = nb_groups;
  595. octx->groups = av_mallocz_array(octx->nb_groups, sizeof(*octx->groups));
  596. if (!octx->groups)
  597. exit_program(1);
  598. for (i = 0; i < octx->nb_groups; i++)
  599. octx->groups[i].group_def = &groups[i];
  600. octx->global_opts.group_def = &global_group;
  601. octx->global_opts.arg = "";
  602. init_opts();
  603. }
  604. void uninit_parse_context(OptionParseContext *octx)
  605. {
  606. int i, j;
  607. for (i = 0; i < octx->nb_groups; i++) {
  608. OptionGroupList *l = &octx->groups[i];
  609. for (j = 0; j < l->nb_groups; j++) {
  610. av_freep(&l->groups[j].opts);
  611. av_dict_free(&l->groups[j].codec_opts);
  612. av_dict_free(&l->groups[j].format_opts);
  613. av_dict_free(&l->groups[j].resample_opts);
  614. #if CONFIG_SWSCALE
  615. sws_freeContext(l->groups[j].sws_opts);
  616. #endif
  617. av_dict_free(&l->groups[j].swr_opts);
  618. }
  619. av_freep(&l->groups);
  620. }
  621. av_freep(&octx->groups);
  622. av_freep(&octx->cur_group.opts);
  623. av_freep(&octx->global_opts.opts);
  624. uninit_opts();
  625. }
  626. int split_commandline(OptionParseContext *octx, int argc, char *argv[],
  627. const OptionDef *options,
  628. const OptionGroupDef *groups, int nb_groups)
  629. {
  630. int optindex = 1;
  631. int dashdash = -2;
  632. /* perform system-dependent conversions for arguments list */
  633. prepare_app_arguments(&argc, &argv);
  634. init_parse_context(octx, groups, nb_groups);
  635. av_log(NULL, AV_LOG_DEBUG, "Splitting the commandline.\n");
  636. while (optindex < argc) {
  637. const char *opt = argv[optindex++], *arg;
  638. const OptionDef *po;
  639. int ret;
  640. av_log(NULL, AV_LOG_DEBUG, "Reading option '%s' ...", opt);
  641. if (opt[0] == '-' && opt[1] == '-' && !opt[2]) {
  642. dashdash = optindex;
  643. continue;
  644. }
  645. /* unnamed group separators, e.g. output filename */
  646. if (opt[0] != '-' || !opt[1] || dashdash+1 == optindex) {
  647. finish_group(octx, 0, opt);
  648. av_log(NULL, AV_LOG_DEBUG, " matched as %s.\n", groups[0].name);
  649. continue;
  650. }
  651. opt++;
  652. #define GET_ARG(arg) \
  653. do { \
  654. arg = argv[optindex++]; \
  655. if (!arg) { \
  656. av_log(NULL, AV_LOG_ERROR, "Missing argument for option '%s'.\n", opt);\
  657. return AVERROR(EINVAL); \
  658. } \
  659. } while (0)
  660. /* named group separators, e.g. -i */
  661. if ((ret = match_group_separator(groups, nb_groups, opt)) >= 0) {
  662. GET_ARG(arg);
  663. finish_group(octx, ret, arg);
  664. av_log(NULL, AV_LOG_DEBUG, " matched as %s with argument '%s'.\n",
  665. groups[ret].name, arg);
  666. continue;
  667. }
  668. /* normal options */
  669. po = find_option(options, opt);
  670. if (po->name) {
  671. if (po->flags & OPT_EXIT) {
  672. /* optional argument, e.g. -h */
  673. arg = argv[optindex++];
  674. } else if (po->flags & HAS_ARG) {
  675. GET_ARG(arg);
  676. } else {
  677. arg = "1";
  678. }
  679. add_opt(octx, po, opt, arg);
  680. av_log(NULL, AV_LOG_DEBUG, " matched as option '%s' (%s) with "
  681. "argument '%s'.\n", po->name, po->help, arg);
  682. continue;
  683. }
  684. /* AVOptions */
  685. if (argv[optindex]) {
  686. ret = opt_default(NULL, opt, argv[optindex]);
  687. if (ret >= 0) {
  688. av_log(NULL, AV_LOG_DEBUG, " matched as AVOption '%s' with "
  689. "argument '%s'.\n", opt, argv[optindex]);
  690. optindex++;
  691. continue;
  692. } else if (ret != AVERROR_OPTION_NOT_FOUND) {
  693. av_log(NULL, AV_LOG_ERROR, "Error parsing option '%s' "
  694. "with argument '%s'.\n", opt, argv[optindex]);
  695. return ret;
  696. }
  697. }
  698. /* boolean -nofoo options */
  699. if (opt[0] == 'n' && opt[1] == 'o' &&
  700. (po = find_option(options, opt + 2)) &&
  701. po->name && po->flags & OPT_BOOL) {
  702. add_opt(octx, po, opt, "0");
  703. av_log(NULL, AV_LOG_DEBUG, " matched as option '%s' (%s) with "
  704. "argument 0.\n", po->name, po->help);
  705. continue;
  706. }
  707. av_log(NULL, AV_LOG_ERROR, "Unrecognized option '%s'.\n", opt);
  708. return AVERROR_OPTION_NOT_FOUND;
  709. }
  710. if (octx->cur_group.nb_opts || codec_opts || format_opts || resample_opts)
  711. av_log(NULL, AV_LOG_WARNING, "Trailing options were found on the "
  712. "commandline.\n");
  713. av_log(NULL, AV_LOG_DEBUG, "Finished splitting the commandline.\n");
  714. return 0;
  715. }
  716. int opt_cpuflags(void *optctx, const char *opt, const char *arg)
  717. {
  718. int ret;
  719. unsigned flags = av_get_cpu_flags();
  720. if ((ret = av_parse_cpu_caps(&flags, arg)) < 0)
  721. return ret;
  722. av_force_cpu_flags(flags);
  723. return 0;
  724. }
  725. int opt_loglevel(void *optctx, const char *opt, const char *arg)
  726. {
  727. const struct { const char *name; int level; } log_levels[] = {
  728. { "quiet" , AV_LOG_QUIET },
  729. { "panic" , AV_LOG_PANIC },
  730. { "fatal" , AV_LOG_FATAL },
  731. { "error" , AV_LOG_ERROR },
  732. { "warning", AV_LOG_WARNING },
  733. { "info" , AV_LOG_INFO },
  734. { "verbose", AV_LOG_VERBOSE },
  735. { "debug" , AV_LOG_DEBUG },
  736. };
  737. char *tail;
  738. int level;
  739. int flags;
  740. int i;
  741. flags = av_log_get_flags();
  742. tail = strstr(arg, "repeat");
  743. if (tail)
  744. flags &= ~AV_LOG_SKIP_REPEATED;
  745. else
  746. flags |= AV_LOG_SKIP_REPEATED;
  747. av_log_set_flags(flags);
  748. if (tail == arg)
  749. arg += 6 + (arg[6]=='+');
  750. if(tail && !*arg)
  751. return 0;
  752. for (i = 0; i < FF_ARRAY_ELEMS(log_levels); i++) {
  753. if (!strcmp(log_levels[i].name, arg)) {
  754. av_log_set_level(log_levels[i].level);
  755. return 0;
  756. }
  757. }
  758. level = strtol(arg, &tail, 10);
  759. if (*tail) {
  760. av_log(NULL, AV_LOG_FATAL, "Invalid loglevel \"%s\". "
  761. "Possible levels are numbers or:\n", arg);
  762. for (i = 0; i < FF_ARRAY_ELEMS(log_levels); i++)
  763. av_log(NULL, AV_LOG_FATAL, "\"%s\"\n", log_levels[i].name);
  764. exit_program(1);
  765. }
  766. av_log_set_level(level);
  767. return 0;
  768. }
  769. static void expand_filename_template(AVBPrint *bp, const char *template,
  770. struct tm *tm)
  771. {
  772. int c;
  773. while ((c = *(template++))) {
  774. if (c == '%') {
  775. if (!(c = *(template++)))
  776. break;
  777. switch (c) {
  778. case 'p':
  779. av_bprintf(bp, "%s", program_name);
  780. break;
  781. case 't':
  782. av_bprintf(bp, "%04d%02d%02d-%02d%02d%02d",
  783. tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday,
  784. tm->tm_hour, tm->tm_min, tm->tm_sec);
  785. break;
  786. case '%':
  787. av_bprint_chars(bp, c, 1);
  788. break;
  789. }
  790. } else {
  791. av_bprint_chars(bp, c, 1);
  792. }
  793. }
  794. }
  795. static int init_report(const char *env)
  796. {
  797. char *filename_template = NULL;
  798. char *key, *val;
  799. int ret, count = 0;
  800. time_t now;
  801. struct tm *tm;
  802. AVBPrint filename;
  803. if (report_file) /* already opened */
  804. return 0;
  805. time(&now);
  806. tm = localtime(&now);
  807. while (env && *env) {
  808. if ((ret = av_opt_get_key_value(&env, "=", ":", 0, &key, &val)) < 0) {
  809. if (count)
  810. av_log(NULL, AV_LOG_ERROR,
  811. "Failed to parse FFREPORT environment variable: %s\n",
  812. av_err2str(ret));
  813. break;
  814. }
  815. if (*env)
  816. env++;
  817. count++;
  818. if (!strcmp(key, "file")) {
  819. av_free(filename_template);
  820. filename_template = val;
  821. val = NULL;
  822. } else if (!strcmp(key, "level")) {
  823. char *tail;
  824. report_file_level = strtol(val, &tail, 10);
  825. if (*tail) {
  826. av_log(NULL, AV_LOG_FATAL, "Invalid report file level\n");
  827. exit_program(1);
  828. }
  829. } else {
  830. av_log(NULL, AV_LOG_ERROR, "Unknown key '%s' in FFREPORT\n", key);
  831. }
  832. av_free(val);
  833. av_free(key);
  834. }
  835. av_bprint_init(&filename, 0, 1);
  836. expand_filename_template(&filename,
  837. av_x_if_null(filename_template, "%p-%t.log"), tm);
  838. av_free(filename_template);
  839. if (!av_bprint_is_complete(&filename)) {
  840. av_log(NULL, AV_LOG_ERROR, "Out of memory building report file name\n");
  841. return AVERROR(ENOMEM);
  842. }
  843. report_file = fopen(filename.str, "w");
  844. if (!report_file) {
  845. av_log(NULL, AV_LOG_ERROR, "Failed to open report \"%s\": %s\n",
  846. filename.str, strerror(errno));
  847. return AVERROR(errno);
  848. }
  849. av_log_set_callback(log_callback_report);
  850. av_log(NULL, AV_LOG_INFO,
  851. "%s started on %04d-%02d-%02d at %02d:%02d:%02d\n"
  852. "Report written to \"%s\"\n",
  853. program_name,
  854. tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday,
  855. tm->tm_hour, tm->tm_min, tm->tm_sec,
  856. filename.str);
  857. av_bprint_finalize(&filename, NULL);
  858. return 0;
  859. }
  860. int opt_report(const char *opt)
  861. {
  862. return init_report(NULL);
  863. }
  864. int opt_max_alloc(void *optctx, const char *opt, const char *arg)
  865. {
  866. char *tail;
  867. size_t max;
  868. max = strtol(arg, &tail, 10);
  869. if (*tail) {
  870. av_log(NULL, AV_LOG_FATAL, "Invalid max_alloc \"%s\".\n", arg);
  871. exit_program(1);
  872. }
  873. av_max_alloc(max);
  874. return 0;
  875. }
  876. int opt_timelimit(void *optctx, const char *opt, const char *arg)
  877. {
  878. #if HAVE_SETRLIMIT
  879. int lim = parse_number_or_die(opt, arg, OPT_INT64, 0, INT_MAX);
  880. struct rlimit rl = { lim, lim + 1 };
  881. if (setrlimit(RLIMIT_CPU, &rl))
  882. perror("setrlimit");
  883. #else
  884. av_log(NULL, AV_LOG_WARNING, "-%s not implemented on this OS\n", opt);
  885. #endif
  886. return 0;
  887. }
  888. void print_error(const char *filename, int err)
  889. {
  890. char errbuf[128];
  891. const char *errbuf_ptr = errbuf;
  892. if (av_strerror(err, errbuf, sizeof(errbuf)) < 0)
  893. errbuf_ptr = strerror(AVUNERROR(err));
  894. av_log(NULL, AV_LOG_ERROR, "%s: %s\n", filename, errbuf_ptr);
  895. }
  896. static int warned_cfg = 0;
  897. #define INDENT 1
  898. #define SHOW_VERSION 2
  899. #define SHOW_CONFIG 4
  900. #define SHOW_COPYRIGHT 8
  901. #define PRINT_LIB_INFO(libname, LIBNAME, flags, level) \
  902. if (CONFIG_##LIBNAME) { \
  903. const char *indent = flags & INDENT? " " : ""; \
  904. if (flags & SHOW_VERSION) { \
  905. unsigned int version = libname##_version(); \
  906. av_log(NULL, level, \
  907. "%slib%-11s %2d.%3d.%3d / %2d.%3d.%3d\n", \
  908. indent, #libname, \
  909. LIB##LIBNAME##_VERSION_MAJOR, \
  910. LIB##LIBNAME##_VERSION_MINOR, \
  911. LIB##LIBNAME##_VERSION_MICRO, \
  912. version >> 16, version >> 8 & 0xff, version & 0xff); \
  913. } \
  914. if (flags & SHOW_CONFIG) { \
  915. const char *cfg = libname##_configuration(); \
  916. if (strcmp(FFMPEG_CONFIGURATION, cfg)) { \
  917. if (!warned_cfg) { \
  918. av_log(NULL, level, \
  919. "%sWARNING: library configuration mismatch\n", \
  920. indent); \
  921. warned_cfg = 1; \
  922. } \
  923. av_log(NULL, level, "%s%-11s configuration: %s\n", \
  924. indent, #libname, cfg); \
  925. } \
  926. } \
  927. } \
  928. static void print_all_libs_info(int flags, int level)
  929. {
  930. PRINT_LIB_INFO(avutil, AVUTIL, flags, level);
  931. PRINT_LIB_INFO(avcodec, AVCODEC, flags, level);
  932. PRINT_LIB_INFO(avformat, AVFORMAT, flags, level);
  933. PRINT_LIB_INFO(avdevice, AVDEVICE, flags, level);
  934. PRINT_LIB_INFO(avfilter, AVFILTER, flags, level);
  935. PRINT_LIB_INFO(avresample, AVRESAMPLE, flags, level);
  936. PRINT_LIB_INFO(swscale, SWSCALE, flags, level);
  937. PRINT_LIB_INFO(swresample,SWRESAMPLE, flags, level);
  938. PRINT_LIB_INFO(postproc, POSTPROC, flags, level);
  939. }
  940. static void print_program_info(int flags, int level)
  941. {
  942. const char *indent = flags & INDENT? " " : "";
  943. av_log(NULL, level, "%s version " FFMPEG_VERSION, program_name);
  944. if (flags & SHOW_COPYRIGHT)
  945. av_log(NULL, level, " Copyright (c) %d-%d the FFmpeg developers",
  946. program_birth_year, CONFIG_THIS_YEAR);
  947. av_log(NULL, level, "\n");
  948. av_log(NULL, level, "%sbuilt on %s %s with %s\n",
  949. indent, __DATE__, __TIME__, CC_IDENT);
  950. av_log(NULL, level, "%sconfiguration: " FFMPEG_CONFIGURATION "\n", indent);
  951. }
  952. static void print_buildconf(int flags, int level)
  953. {
  954. const char *indent = flags & INDENT ? " " : "";
  955. char str[] = { FFMPEG_CONFIGURATION };
  956. char *conflist, *remove_tilde, *splitconf;
  957. // Change all the ' --' strings to '~--' so that
  958. // they can be identified as tokens.
  959. while ((conflist = strstr(str, " --")) != NULL) {
  960. strncpy(conflist, "~--", 3);
  961. }
  962. // Compensate for the weirdness this would cause
  963. // when passing 'pkg-config --static'.
  964. while ((remove_tilde = strstr(str, "pkg-config~")) != NULL) {
  965. strncpy(remove_tilde, "pkg-config ", 11);
  966. }
  967. splitconf = strtok(str, "~");
  968. av_log(NULL, level, "\n%sconfiguration:\n", indent);
  969. while (splitconf != NULL) {
  970. av_log(NULL, level, "%s%s%s\n", indent, indent, splitconf);
  971. splitconf = strtok(NULL, "~");
  972. }
  973. }
  974. void show_banner(int argc, char **argv, const OptionDef *options)
  975. {
  976. int idx = locate_option(argc, argv, options, "version");
  977. if (hide_banner || idx)
  978. return;
  979. print_program_info (INDENT|SHOW_COPYRIGHT, AV_LOG_INFO);
  980. print_all_libs_info(INDENT|SHOW_CONFIG, AV_LOG_INFO);
  981. print_all_libs_info(INDENT|SHOW_VERSION, AV_LOG_INFO);
  982. }
  983. int show_version(void *optctx, const char *opt, const char *arg)
  984. {
  985. av_log_set_callback(log_callback_help);
  986. print_program_info (SHOW_COPYRIGHT, AV_LOG_INFO);
  987. print_all_libs_info(SHOW_VERSION, AV_LOG_INFO);
  988. return 0;
  989. }
  990. int show_buildconf(void *optctx, const char *opt, const char *arg)
  991. {
  992. av_log_set_callback(log_callback_help);
  993. print_buildconf (INDENT|0, AV_LOG_INFO);
  994. return 0;
  995. }
  996. int show_license(void *optctx, const char *opt, const char *arg)
  997. {
  998. #if CONFIG_NONFREE
  999. printf(
  1000. "This version of %s has nonfree parts compiled in.\n"
  1001. "Therefore it is not legally redistributable.\n",
  1002. program_name );
  1003. #elif CONFIG_GPLV3
  1004. printf(
  1005. "%s is free software; you can redistribute it and/or modify\n"
  1006. "it under the terms of the GNU General Public License as published by\n"
  1007. "the Free Software Foundation; either version 3 of the License, or\n"
  1008. "(at your option) any later version.\n"
  1009. "\n"
  1010. "%s is distributed in the hope that it will be useful,\n"
  1011. "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
  1012. "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n"
  1013. "GNU General Public License for more details.\n"
  1014. "\n"
  1015. "You should have received a copy of the GNU General Public License\n"
  1016. "along with %s. If not, see <http://www.gnu.org/licenses/>.\n",
  1017. program_name, program_name, program_name );
  1018. #elif CONFIG_GPL
  1019. printf(
  1020. "%s is free software; you can redistribute it and/or modify\n"
  1021. "it under the terms of the GNU General Public License as published by\n"
  1022. "the Free Software Foundation; either version 2 of the License, or\n"
  1023. "(at your option) any later version.\n"
  1024. "\n"
  1025. "%s is distributed in the hope that it will be useful,\n"
  1026. "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
  1027. "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n"
  1028. "GNU General Public License for more details.\n"
  1029. "\n"
  1030. "You should have received a copy of the GNU General Public License\n"
  1031. "along with %s; if not, write to the Free Software\n"
  1032. "Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n",
  1033. program_name, program_name, program_name );
  1034. #elif CONFIG_LGPLV3
  1035. printf(
  1036. "%s is free software; you can redistribute it and/or modify\n"
  1037. "it under the terms of the GNU Lesser General Public License as published by\n"
  1038. "the Free Software Foundation; either version 3 of the License, or\n"
  1039. "(at your option) any later version.\n"
  1040. "\n"
  1041. "%s is distributed in the hope that it will be useful,\n"
  1042. "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
  1043. "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n"
  1044. "GNU Lesser General Public License for more details.\n"
  1045. "\n"
  1046. "You should have received a copy of the GNU Lesser General Public License\n"
  1047. "along with %s. If not, see <http://www.gnu.org/licenses/>.\n",
  1048. program_name, program_name, program_name );
  1049. #else
  1050. printf(
  1051. "%s is free software; you can redistribute it and/or\n"
  1052. "modify it under the terms of the GNU Lesser General Public\n"
  1053. "License as published by the Free Software Foundation; either\n"
  1054. "version 2.1 of the License, or (at your option) any later version.\n"
  1055. "\n"
  1056. "%s is distributed in the hope that it will be useful,\n"
  1057. "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
  1058. "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n"
  1059. "Lesser General Public License for more details.\n"
  1060. "\n"
  1061. "You should have received a copy of the GNU Lesser General Public\n"
  1062. "License along with %s; if not, write to the Free Software\n"
  1063. "Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n",
  1064. program_name, program_name, program_name );
  1065. #endif
  1066. return 0;
  1067. }
  1068. static int is_device(const AVClass *avclass)
  1069. {
  1070. if (!avclass)
  1071. return 0;
  1072. return avclass->category == AV_CLASS_CATEGORY_DEVICE_VIDEO_OUTPUT ||
  1073. avclass->category == AV_CLASS_CATEGORY_DEVICE_VIDEO_INPUT ||
  1074. avclass->category == AV_CLASS_CATEGORY_DEVICE_AUDIO_OUTPUT ||
  1075. avclass->category == AV_CLASS_CATEGORY_DEVICE_AUDIO_INPUT ||
  1076. avclass->category == AV_CLASS_CATEGORY_DEVICE_OUTPUT ||
  1077. avclass->category == AV_CLASS_CATEGORY_DEVICE_INPUT;
  1078. }
  1079. static int show_formats_devices(void *optctx, const char *opt, const char *arg, int device_only)
  1080. {
  1081. AVInputFormat *ifmt = NULL;
  1082. AVOutputFormat *ofmt = NULL;
  1083. const char *last_name;
  1084. int is_dev;
  1085. printf("%s\n"
  1086. " D. = Demuxing supported\n"
  1087. " .E = Muxing supported\n"
  1088. " --\n", device_only ? "Devices:" : "File formats:");
  1089. last_name = "000";
  1090. for (;;) {
  1091. int decode = 0;
  1092. int encode = 0;
  1093. const char *name = NULL;
  1094. const char *long_name = NULL;
  1095. while ((ofmt = av_oformat_next(ofmt))) {
  1096. is_dev = is_device(ofmt->priv_class);
  1097. if (!is_dev && device_only)
  1098. continue;
  1099. if ((!name || strcmp(ofmt->name, name) < 0) &&
  1100. strcmp(ofmt->name, last_name) > 0) {
  1101. name = ofmt->name;
  1102. long_name = ofmt->long_name;
  1103. encode = 1;
  1104. }
  1105. }
  1106. while ((ifmt = av_iformat_next(ifmt))) {
  1107. is_dev = is_device(ifmt->priv_class);
  1108. if (!is_dev && device_only)
  1109. continue;
  1110. if ((!name || strcmp(ifmt->name, name) < 0) &&
  1111. strcmp(ifmt->name, last_name) > 0) {
  1112. name = ifmt->name;
  1113. long_name = ifmt->long_name;
  1114. encode = 0;
  1115. }
  1116. if (name && strcmp(ifmt->name, name) == 0)
  1117. decode = 1;
  1118. }
  1119. if (!name)
  1120. break;
  1121. last_name = name;
  1122. printf(" %s%s %-15s %s\n",
  1123. decode ? "D" : " ",
  1124. encode ? "E" : " ",
  1125. name,
  1126. long_name ? long_name:" ");
  1127. }
  1128. return 0;
  1129. }
  1130. int show_formats(void *optctx, const char *opt, const char *arg)
  1131. {
  1132. return show_formats_devices(optctx, opt, arg, 0);
  1133. }
  1134. int show_devices(void *optctx, const char *opt, const char *arg)
  1135. {
  1136. return show_formats_devices(optctx, opt, arg, 1);
  1137. }
  1138. #define PRINT_CODEC_SUPPORTED(codec, field, type, list_name, term, get_name) \
  1139. if (codec->field) { \
  1140. const type *p = codec->field; \
  1141. \
  1142. printf(" Supported " list_name ":"); \
  1143. while (*p != term) { \
  1144. get_name(*p); \
  1145. printf(" %s", name); \
  1146. p++; \
  1147. } \
  1148. printf("\n"); \
  1149. } \
  1150. static void print_codec(const AVCodec *c)
  1151. {
  1152. int encoder = av_codec_is_encoder(c);
  1153. printf("%s %s [%s]:\n", encoder ? "Encoder" : "Decoder", c->name,
  1154. c->long_name ? c->long_name : "");
  1155. if (c->type == AVMEDIA_TYPE_VIDEO ||
  1156. c->type == AVMEDIA_TYPE_AUDIO) {
  1157. printf(" Threading capabilities: ");
  1158. switch (c->capabilities & (CODEC_CAP_FRAME_THREADS |
  1159. CODEC_CAP_SLICE_THREADS)) {
  1160. case CODEC_CAP_FRAME_THREADS |
  1161. CODEC_CAP_SLICE_THREADS: printf("frame and slice"); break;
  1162. case CODEC_CAP_FRAME_THREADS: printf("frame"); break;
  1163. case CODEC_CAP_SLICE_THREADS: printf("slice"); break;
  1164. default: printf("no"); break;
  1165. }
  1166. printf("\n");
  1167. }
  1168. if (c->supported_framerates) {
  1169. const AVRational *fps = c->supported_framerates;
  1170. printf(" Supported framerates:");
  1171. while (fps->num) {
  1172. printf(" %d/%d", fps->num, fps->den);
  1173. fps++;
  1174. }
  1175. printf("\n");
  1176. }
  1177. PRINT_CODEC_SUPPORTED(c, pix_fmts, enum AVPixelFormat, "pixel formats",
  1178. AV_PIX_FMT_NONE, GET_PIX_FMT_NAME);
  1179. PRINT_CODEC_SUPPORTED(c, supported_samplerates, int, "sample rates", 0,
  1180. GET_SAMPLE_RATE_NAME);
  1181. PRINT_CODEC_SUPPORTED(c, sample_fmts, enum AVSampleFormat, "sample formats",
  1182. AV_SAMPLE_FMT_NONE, GET_SAMPLE_FMT_NAME);
  1183. PRINT_CODEC_SUPPORTED(c, channel_layouts, uint64_t, "channel layouts",
  1184. 0, GET_CH_LAYOUT_DESC);
  1185. if (c->priv_class) {
  1186. show_help_children(c->priv_class,
  1187. AV_OPT_FLAG_ENCODING_PARAM |
  1188. AV_OPT_FLAG_DECODING_PARAM);
  1189. }
  1190. }
  1191. static char get_media_type_char(enum AVMediaType type)
  1192. {
  1193. switch (type) {
  1194. case AVMEDIA_TYPE_VIDEO: return 'V';
  1195. case AVMEDIA_TYPE_AUDIO: return 'A';
  1196. case AVMEDIA_TYPE_DATA: return 'D';
  1197. case AVMEDIA_TYPE_SUBTITLE: return 'S';
  1198. case AVMEDIA_TYPE_ATTACHMENT:return 'T';
  1199. default: return '?';
  1200. }
  1201. }
  1202. static const AVCodec *next_codec_for_id(enum AVCodecID id, const AVCodec *prev,
  1203. int encoder)
  1204. {
  1205. while ((prev = av_codec_next(prev))) {
  1206. if (prev->id == id &&
  1207. (encoder ? av_codec_is_encoder(prev) : av_codec_is_decoder(prev)))
  1208. return prev;
  1209. }
  1210. return NULL;
  1211. }
  1212. static int compare_codec_desc(const void *a, const void *b)
  1213. {
  1214. const AVCodecDescriptor * const *da = a;
  1215. const AVCodecDescriptor * const *db = b;
  1216. return (*da)->type != (*db)->type ? (*da)->type - (*db)->type :
  1217. strcmp((*da)->name, (*db)->name);
  1218. }
  1219. static unsigned get_codecs_sorted(const AVCodecDescriptor ***rcodecs)
  1220. {
  1221. const AVCodecDescriptor *desc = NULL;
  1222. const AVCodecDescriptor **codecs;
  1223. unsigned nb_codecs = 0, i = 0;
  1224. while ((desc = avcodec_descriptor_next(desc)))
  1225. nb_codecs++;
  1226. if (!(codecs = av_calloc(nb_codecs, sizeof(*codecs)))) {
  1227. av_log(NULL, AV_LOG_ERROR, "Out of memory\n");
  1228. exit_program(1);
  1229. }
  1230. desc = NULL;
  1231. while ((desc = avcodec_descriptor_next(desc)))
  1232. codecs[i++] = desc;
  1233. av_assert0(i == nb_codecs);
  1234. qsort(codecs, nb_codecs, sizeof(*codecs), compare_codec_desc);
  1235. *rcodecs = codecs;
  1236. return nb_codecs;
  1237. }
  1238. static void print_codecs_for_id(enum AVCodecID id, int encoder)
  1239. {
  1240. const AVCodec *codec = NULL;
  1241. printf(" (%s: ", encoder ? "encoders" : "decoders");
  1242. while ((codec = next_codec_for_id(id, codec, encoder)))
  1243. printf("%s ", codec->name);
  1244. printf(")");
  1245. }
  1246. int show_codecs(void *optctx, const char *opt, const char *arg)
  1247. {
  1248. const AVCodecDescriptor **codecs;
  1249. unsigned i, nb_codecs = get_codecs_sorted(&codecs);
  1250. printf("Codecs:\n"
  1251. " D..... = Decoding supported\n"
  1252. " .E.... = Encoding supported\n"
  1253. " ..V... = Video codec\n"
  1254. " ..A... = Audio codec\n"
  1255. " ..S... = Subtitle codec\n"
  1256. " ...I.. = Intra frame-only codec\n"
  1257. " ....L. = Lossy compression\n"
  1258. " .....S = Lossless compression\n"
  1259. " -------\n");
  1260. for (i = 0; i < nb_codecs; i++) {
  1261. const AVCodecDescriptor *desc = codecs[i];
  1262. const AVCodec *codec = NULL;
  1263. if (strstr(desc->name, "_deprecated"))
  1264. continue;
  1265. printf(" ");
  1266. printf(avcodec_find_decoder(desc->id) ? "D" : ".");
  1267. printf(avcodec_find_encoder(desc->id) ? "E" : ".");
  1268. printf("%c", get_media_type_char(desc->type));
  1269. printf((desc->props & AV_CODEC_PROP_INTRA_ONLY) ? "I" : ".");
  1270. printf((desc->props & AV_CODEC_PROP_LOSSY) ? "L" : ".");
  1271. printf((desc->props & AV_CODEC_PROP_LOSSLESS) ? "S" : ".");
  1272. printf(" %-20s %s", desc->name, desc->long_name ? desc->long_name : "");
  1273. /* print decoders/encoders when there's more than one or their
  1274. * names are different from codec name */
  1275. while ((codec = next_codec_for_id(desc->id, codec, 0))) {
  1276. if (strcmp(codec->name, desc->name)) {
  1277. print_codecs_for_id(desc->id, 0);
  1278. break;
  1279. }
  1280. }
  1281. codec = NULL;
  1282. while ((codec = next_codec_for_id(desc->id, codec, 1))) {
  1283. if (strcmp(codec->name, desc->name)) {
  1284. print_codecs_for_id(desc->id, 1);
  1285. break;
  1286. }
  1287. }
  1288. printf("\n");
  1289. }
  1290. av_free(codecs);
  1291. return 0;
  1292. }
  1293. static void print_codecs(int encoder)
  1294. {
  1295. const AVCodecDescriptor **codecs;
  1296. unsigned i, nb_codecs = get_codecs_sorted(&codecs);
  1297. printf("%s:\n"
  1298. " V..... = Video\n"
  1299. " A..... = Audio\n"
  1300. " S..... = Subtitle\n"
  1301. " .F.... = Frame-level multithreading\n"
  1302. " ..S... = Slice-level multithreading\n"
  1303. " ...X.. = Codec is experimental\n"
  1304. " ....B. = Supports draw_horiz_band\n"
  1305. " .....D = Supports direct rendering method 1\n"
  1306. " ------\n",
  1307. encoder ? "Encoders" : "Decoders");
  1308. for (i = 0; i < nb_codecs; i++) {
  1309. const AVCodecDescriptor *desc = codecs[i];
  1310. const AVCodec *codec = NULL;
  1311. while ((codec = next_codec_for_id(desc->id, codec, encoder))) {
  1312. printf(" %c", get_media_type_char(desc->type));
  1313. printf((codec->capabilities & CODEC_CAP_FRAME_THREADS) ? "F" : ".");
  1314. printf((codec->capabilities & CODEC_CAP_SLICE_THREADS) ? "S" : ".");
  1315. printf((codec->capabilities & CODEC_CAP_EXPERIMENTAL) ? "X" : ".");
  1316. printf((codec->capabilities & CODEC_CAP_DRAW_HORIZ_BAND)?"B" : ".");
  1317. printf((codec->capabilities & CODEC_CAP_DR1) ? "D" : ".");
  1318. printf(" %-20s %s", codec->name, codec->long_name ? codec->long_name : "");
  1319. if (strcmp(codec->name, desc->name))
  1320. printf(" (codec %s)", desc->name);
  1321. printf("\n");
  1322. }
  1323. }
  1324. av_free(codecs);
  1325. }
  1326. int show_decoders(void *optctx, const char *opt, const char *arg)
  1327. {
  1328. print_codecs(0);
  1329. return 0;
  1330. }
  1331. int show_encoders(void *optctx, const char *opt, const char *arg)
  1332. {
  1333. print_codecs(1);
  1334. return 0;
  1335. }
  1336. int show_bsfs(void *optctx, const char *opt, const char *arg)
  1337. {
  1338. AVBitStreamFilter *bsf = NULL;
  1339. printf("Bitstream filters:\n");
  1340. while ((bsf = av_bitstream_filter_next(bsf)))
  1341. printf("%s\n", bsf->name);
  1342. printf("\n");
  1343. return 0;
  1344. }
  1345. int show_protocols(void *optctx, const char *opt, const char *arg)
  1346. {
  1347. void *opaque = NULL;
  1348. const char *name;
  1349. printf("Supported file protocols:\n"
  1350. "Input:\n");
  1351. while ((name = avio_enum_protocols(&opaque, 0)))
  1352. printf("%s\n", name);
  1353. printf("Output:\n");
  1354. while ((name = avio_enum_protocols(&opaque, 1)))
  1355. printf("%s\n", name);
  1356. return 0;
  1357. }
  1358. int show_filters(void *optctx, const char *opt, const char *arg)
  1359. {
  1360. const AVFilter av_unused(*filter) = NULL;
  1361. char descr[64], *descr_cur;
  1362. int i, j;
  1363. const AVFilterPad *pad;
  1364. printf("Filters:\n"
  1365. " T.. = Timeline support\n"
  1366. " .S. = Slice threading\n"
  1367. " ..C = Commmand support\n"
  1368. " A = Audio input/output\n"
  1369. " V = Video input/output\n"
  1370. " N = Dynamic number and/or type of input/output\n"
  1371. " | = Source or sink filter\n");
  1372. #if CONFIG_AVFILTER
  1373. while ((filter = avfilter_next(filter))) {
  1374. descr_cur = descr;
  1375. for (i = 0; i < 2; i++) {
  1376. if (i) {
  1377. *(descr_cur++) = '-';
  1378. *(descr_cur++) = '>';
  1379. }
  1380. pad = i ? filter->outputs : filter->inputs;
  1381. for (j = 0; pad && pad[j].name; j++) {
  1382. if (descr_cur >= descr + sizeof(descr) - 4)
  1383. break;
  1384. *(descr_cur++) = get_media_type_char(pad[j].type);
  1385. }
  1386. if (!j)
  1387. *(descr_cur++) = ((!i && (filter->flags & AVFILTER_FLAG_DYNAMIC_INPUTS)) ||
  1388. ( i && (filter->flags & AVFILTER_FLAG_DYNAMIC_OUTPUTS))) ? 'N' : '|';
  1389. }
  1390. *descr_cur = 0;
  1391. printf(" %c%c%c %-16s %-10s %s\n",
  1392. filter->flags & AVFILTER_FLAG_SUPPORT_TIMELINE ? 'T' : '.',
  1393. filter->flags & AVFILTER_FLAG_SLICE_THREADS ? 'S' : '.',
  1394. filter->process_command ? 'C' : '.',
  1395. filter->name, descr, filter->description);
  1396. }
  1397. #endif
  1398. return 0;
  1399. }
  1400. int show_colors(void *optctx, const char *opt, const char *arg)
  1401. {
  1402. const char *name;
  1403. const uint8_t *rgb;
  1404. int i;
  1405. printf("%-32s #RRGGBB\n", "name");
  1406. for (i = 0; name = av_get_known_color_name(i, &rgb); i++)
  1407. printf("%-32s #%02x%02x%02x\n", name, rgb[0], rgb[1], rgb[2]);
  1408. return 0;
  1409. }
  1410. int show_pix_fmts(void *optctx, const char *opt, const char *arg)
  1411. {
  1412. const AVPixFmtDescriptor *pix_desc = NULL;
  1413. printf("Pixel formats:\n"
  1414. "I.... = Supported Input format for conversion\n"
  1415. ".O... = Supported Output format for conversion\n"
  1416. "..H.. = Hardware accelerated format\n"
  1417. "...P. = Paletted format\n"
  1418. "....B = Bitstream format\n"
  1419. "FLAGS NAME NB_COMPONENTS BITS_PER_PIXEL\n"
  1420. "-----\n");
  1421. #if !CONFIG_SWSCALE
  1422. # define sws_isSupportedInput(x) 0
  1423. # define sws_isSupportedOutput(x) 0
  1424. #endif
  1425. while ((pix_desc = av_pix_fmt_desc_next(pix_desc))) {
  1426. enum AVPixelFormat pix_fmt = av_pix_fmt_desc_get_id(pix_desc);
  1427. printf("%c%c%c%c%c %-16s %d %2d\n",
  1428. sws_isSupportedInput (pix_fmt) ? 'I' : '.',
  1429. sws_isSupportedOutput(pix_fmt) ? 'O' : '.',
  1430. pix_desc->flags & AV_PIX_FMT_FLAG_HWACCEL ? 'H' : '.',
  1431. pix_desc->flags & AV_PIX_FMT_FLAG_PAL ? 'P' : '.',
  1432. pix_desc->flags & AV_PIX_FMT_FLAG_BITSTREAM ? 'B' : '.',
  1433. pix_desc->name,
  1434. pix_desc->nb_components,
  1435. av_get_bits_per_pixel(pix_desc));
  1436. }
  1437. return 0;
  1438. }
  1439. int show_layouts(void *optctx, const char *opt, const char *arg)
  1440. {
  1441. int i = 0;
  1442. uint64_t layout, j;
  1443. const char *name, *descr;
  1444. printf("Individual channels:\n"
  1445. "NAME DESCRIPTION\n");
  1446. for (i = 0; i < 63; i++) {
  1447. name = av_get_channel_name((uint64_t)1 << i);
  1448. if (!name)
  1449. continue;
  1450. descr = av_get_channel_description((uint64_t)1 << i);
  1451. printf("%-14s %s\n", name, descr);
  1452. }
  1453. printf("\nStandard channel layouts:\n"
  1454. "NAME DECOMPOSITION\n");
  1455. for (i = 0; !av_get_standard_channel_layout(i, &layout, &name); i++) {
  1456. if (name) {
  1457. printf("%-14s ", name);
  1458. for (j = 1; j; j <<= 1)
  1459. if ((layout & j))
  1460. printf("%s%s", (layout & (j - 1)) ? "+" : "", av_get_channel_name(j));
  1461. printf("\n");
  1462. }
  1463. }
  1464. return 0;
  1465. }
  1466. int show_sample_fmts(void *optctx, const char *opt, const char *arg)
  1467. {
  1468. int i;
  1469. char fmt_str[128];
  1470. for (i = -1; i < AV_SAMPLE_FMT_NB; i++)
  1471. printf("%s\n", av_get_sample_fmt_string(fmt_str, sizeof(fmt_str), i));
  1472. return 0;
  1473. }
  1474. static void show_help_codec(const char *name, int encoder)
  1475. {
  1476. const AVCodecDescriptor *desc;
  1477. const AVCodec *codec;
  1478. if (!name) {
  1479. av_log(NULL, AV_LOG_ERROR, "No codec name specified.\n");
  1480. return;
  1481. }
  1482. codec = encoder ? avcodec_find_encoder_by_name(name) :
  1483. avcodec_find_decoder_by_name(name);
  1484. if (codec)
  1485. print_codec(codec);
  1486. else if ((desc = avcodec_descriptor_get_by_name(name))) {
  1487. int printed = 0;
  1488. while ((codec = next_codec_for_id(desc->id, codec, encoder))) {
  1489. printed = 1;
  1490. print_codec(codec);
  1491. }
  1492. if (!printed) {
  1493. av_log(NULL, AV_LOG_ERROR, "Codec '%s' is known to FFmpeg, "
  1494. "but no %s for it are available. FFmpeg might need to be "
  1495. "recompiled with additional external libraries.\n",
  1496. name, encoder ? "encoders" : "decoders");
  1497. }
  1498. } else {
  1499. av_log(NULL, AV_LOG_ERROR, "Codec '%s' is not recognized by FFmpeg.\n",
  1500. name);
  1501. }
  1502. }
  1503. static void show_help_demuxer(const char *name)
  1504. {
  1505. const AVInputFormat *fmt = av_find_input_format(name);
  1506. if (!fmt) {
  1507. av_log(NULL, AV_LOG_ERROR, "Unknown format '%s'.\n", name);
  1508. return;
  1509. }
  1510. printf("Demuxer %s [%s]:\n", fmt->name, fmt->long_name);
  1511. if (fmt->extensions)
  1512. printf(" Common extensions: %s.\n", fmt->extensions);
  1513. if (fmt->priv_class)
  1514. show_help_children(fmt->priv_class, AV_OPT_FLAG_DECODING_PARAM);
  1515. }
  1516. static void show_help_muxer(const char *name)
  1517. {
  1518. const AVCodecDescriptor *desc;
  1519. const AVOutputFormat *fmt = av_guess_format(name, NULL, NULL);
  1520. if (!fmt) {
  1521. av_log(NULL, AV_LOG_ERROR, "Unknown format '%s'.\n", name);
  1522. return;
  1523. }
  1524. printf("Muxer %s [%s]:\n", fmt->name, fmt->long_name);
  1525. if (fmt->extensions)
  1526. printf(" Common extensions: %s.\n", fmt->extensions);
  1527. if (fmt->mime_type)
  1528. printf(" Mime type: %s.\n", fmt->mime_type);
  1529. if (fmt->video_codec != AV_CODEC_ID_NONE &&
  1530. (desc = avcodec_descriptor_get(fmt->video_codec))) {
  1531. printf(" Default video codec: %s.\n", desc->name);
  1532. }
  1533. if (fmt->audio_codec != AV_CODEC_ID_NONE &&
  1534. (desc = avcodec_descriptor_get(fmt->audio_codec))) {
  1535. printf(" Default audio codec: %s.\n", desc->name);
  1536. }
  1537. if (fmt->subtitle_codec != AV_CODEC_ID_NONE &&
  1538. (desc = avcodec_descriptor_get(fmt->subtitle_codec))) {
  1539. printf(" Default subtitle codec: %s.\n", desc->name);
  1540. }
  1541. if (fmt->priv_class)
  1542. show_help_children(fmt->priv_class, AV_OPT_FLAG_ENCODING_PARAM);
  1543. }
  1544. #if CONFIG_AVFILTER
  1545. static void show_help_filter(const char *name)
  1546. {
  1547. #if CONFIG_AVFILTER
  1548. const AVFilter *f = avfilter_get_by_name(name);
  1549. int i, count;
  1550. if (!name) {
  1551. av_log(NULL, AV_LOG_ERROR, "No filter name specified.\n");
  1552. return;
  1553. } else if (!f) {
  1554. av_log(NULL, AV_LOG_ERROR, "Unknown filter '%s'.\n", name);
  1555. return;
  1556. }
  1557. printf("Filter %s\n", f->name);
  1558. if (f->description)
  1559. printf(" %s\n", f->description);
  1560. if (f->flags & AVFILTER_FLAG_SLICE_THREADS)
  1561. printf(" slice threading supported\n");
  1562. printf(" Inputs:\n");
  1563. count = avfilter_pad_count(f->inputs);
  1564. for (i = 0; i < count; i++) {
  1565. printf(" #%d: %s (%s)\n", i, avfilter_pad_get_name(f->inputs, i),
  1566. media_type_string(avfilter_pad_get_type(f->inputs, i)));
  1567. }
  1568. if (f->flags & AVFILTER_FLAG_DYNAMIC_INPUTS)
  1569. printf(" dynamic (depending on the options)\n");
  1570. else if (!count)
  1571. printf(" none (source filter)\n");
  1572. printf(" Outputs:\n");
  1573. count = avfilter_pad_count(f->outputs);
  1574. for (i = 0; i < count; i++) {
  1575. printf(" #%d: %s (%s)\n", i, avfilter_pad_get_name(f->outputs, i),
  1576. media_type_string(avfilter_pad_get_type(f->outputs, i)));
  1577. }
  1578. if (f->flags & AVFILTER_FLAG_DYNAMIC_OUTPUTS)
  1579. printf(" dynamic (depending on the options)\n");
  1580. else if (!count)
  1581. printf(" none (sink filter)\n");
  1582. if (f->priv_class)
  1583. show_help_children(f->priv_class, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_FILTERING_PARAM |
  1584. AV_OPT_FLAG_AUDIO_PARAM);
  1585. if (f->flags & AVFILTER_FLAG_SUPPORT_TIMELINE)
  1586. printf("This filter has support for timeline through the 'enable' option.\n");
  1587. #else
  1588. av_log(NULL, AV_LOG_ERROR, "Build without libavfilter; "
  1589. "can not to satisfy request\n");
  1590. #endif
  1591. }
  1592. #endif
  1593. int show_help(void *optctx, const char *opt, const char *arg)
  1594. {
  1595. char *topic, *par;
  1596. av_log_set_callback(log_callback_help);
  1597. topic = av_strdup(arg ? arg : "");
  1598. par = strchr(topic, '=');
  1599. if (par)
  1600. *par++ = 0;
  1601. if (!*topic) {
  1602. show_help_default(topic, par);
  1603. } else if (!strcmp(topic, "decoder")) {
  1604. show_help_codec(par, 0);
  1605. } else if (!strcmp(topic, "encoder")) {
  1606. show_help_codec(par, 1);
  1607. } else if (!strcmp(topic, "demuxer")) {
  1608. show_help_demuxer(par);
  1609. } else if (!strcmp(topic, "muxer")) {
  1610. show_help_muxer(par);
  1611. #if CONFIG_AVFILTER
  1612. } else if (!strcmp(topic, "filter")) {
  1613. show_help_filter(par);
  1614. #endif
  1615. } else {
  1616. show_help_default(topic, par);
  1617. }
  1618. av_freep(&topic);
  1619. return 0;
  1620. }
  1621. int read_yesno(void)
  1622. {
  1623. int c = getchar();
  1624. int yesno = (av_toupper(c) == 'Y');
  1625. while (c != '\n' && c != EOF)
  1626. c = getchar();
  1627. return yesno;
  1628. }
  1629. int cmdutils_read_file(const char *filename, char **bufptr, size_t *size)
  1630. {
  1631. int64_t ret;
  1632. FILE *f = av_fopen_utf8(filename, "rb");
  1633. if (!f) {
  1634. av_log(NULL, AV_LOG_ERROR, "Cannot read file '%s': %s\n", filename,
  1635. strerror(errno));
  1636. return AVERROR(errno);
  1637. }
  1638. ret = fseek(f, 0, SEEK_END);
  1639. if (ret == -1) {
  1640. ret = AVERROR(errno);
  1641. goto out;
  1642. }
  1643. ret = ftell(f);
  1644. if (ret < 0) {
  1645. ret = AVERROR(errno);
  1646. goto out;
  1647. }
  1648. *size = ret;
  1649. ret = fseek(f, 0, SEEK_SET);
  1650. if (ret == -1) {
  1651. ret = AVERROR(errno);
  1652. goto out;
  1653. }
  1654. *bufptr = av_malloc(*size + 1);
  1655. if (!*bufptr) {
  1656. av_log(NULL, AV_LOG_ERROR, "Could not allocate file buffer\n");
  1657. ret = AVERROR(ENOMEM);
  1658. goto out;
  1659. }
  1660. ret = fread(*bufptr, 1, *size, f);
  1661. if (ret < *size) {
  1662. av_free(*bufptr);
  1663. if (ferror(f)) {
  1664. av_log(NULL, AV_LOG_ERROR, "Error while reading file '%s': %s\n",
  1665. filename, strerror(errno));
  1666. ret = AVERROR(errno);
  1667. } else
  1668. ret = AVERROR_EOF;
  1669. } else {
  1670. ret = 0;
  1671. (*bufptr)[(*size)++] = '\0';
  1672. }
  1673. out:
  1674. av_log(NULL, AV_LOG_ERROR, "IO error: %s\n", av_err2str(ret));
  1675. fclose(f);
  1676. return ret;
  1677. }
  1678. FILE *get_preset_file(char *filename, size_t filename_size,
  1679. const char *preset_name, int is_path,
  1680. const char *codec_name)
  1681. {
  1682. FILE *f = NULL;
  1683. int i;
  1684. const char *base[3] = { getenv("FFMPEG_DATADIR"),
  1685. getenv("HOME"),
  1686. FFMPEG_DATADIR, };
  1687. if (is_path) {
  1688. av_strlcpy(filename, preset_name, filename_size);
  1689. f = fopen(filename, "r");
  1690. } else {
  1691. #ifdef _WIN32
  1692. char datadir[MAX_PATH], *ls;
  1693. base[2] = NULL;
  1694. if (GetModuleFileNameA(GetModuleHandleA(NULL), datadir, sizeof(datadir) - 1))
  1695. {
  1696. for (ls = datadir; ls < datadir + strlen(datadir); ls++)
  1697. if (*ls == '\\') *ls = '/';
  1698. if (ls = strrchr(datadir, '/'))
  1699. {
  1700. *ls = 0;
  1701. strncat(datadir, "/ffpresets", sizeof(datadir) - 1 - strlen(datadir));
  1702. base[2] = datadir;
  1703. }
  1704. }
  1705. #endif
  1706. for (i = 0; i < 3 && !f; i++) {
  1707. if (!base[i])
  1708. continue;
  1709. snprintf(filename, filename_size, "%s%s/%s.ffpreset", base[i],
  1710. i != 1 ? "" : "/.ffmpeg", preset_name);
  1711. f = fopen(filename, "r");
  1712. if (!f && codec_name) {
  1713. snprintf(filename, filename_size,
  1714. "%s%s/%s-%s.ffpreset",
  1715. base[i], i != 1 ? "" : "/.ffmpeg", codec_name,
  1716. preset_name);
  1717. f = fopen(filename, "r");
  1718. }
  1719. }
  1720. }
  1721. return f;
  1722. }
  1723. int check_stream_specifier(AVFormatContext *s, AVStream *st, const char *spec)
  1724. {
  1725. int ret = avformat_match_stream_specifier(s, st, spec);
  1726. if (ret < 0)
  1727. av_log(s, AV_LOG_ERROR, "Invalid stream specifier: %s.\n", spec);
  1728. return ret;
  1729. }
  1730. AVDictionary *filter_codec_opts(AVDictionary *opts, enum AVCodecID codec_id,
  1731. AVFormatContext *s, AVStream *st, AVCodec *codec)
  1732. {
  1733. AVDictionary *ret = NULL;
  1734. AVDictionaryEntry *t = NULL;
  1735. int flags = s->oformat ? AV_OPT_FLAG_ENCODING_PARAM
  1736. : AV_OPT_FLAG_DECODING_PARAM;
  1737. char prefix = 0;
  1738. const AVClass *cc = avcodec_get_class();
  1739. if (!codec)
  1740. codec = s->oformat ? avcodec_find_encoder(codec_id)
  1741. : avcodec_find_decoder(codec_id);
  1742. switch (st->codec->codec_type) {
  1743. case AVMEDIA_TYPE_VIDEO:
  1744. prefix = 'v';
  1745. flags |= AV_OPT_FLAG_VIDEO_PARAM;
  1746. break;
  1747. case AVMEDIA_TYPE_AUDIO:
  1748. prefix = 'a';
  1749. flags |= AV_OPT_FLAG_AUDIO_PARAM;
  1750. break;
  1751. case AVMEDIA_TYPE_SUBTITLE:
  1752. prefix = 's';
  1753. flags |= AV_OPT_FLAG_SUBTITLE_PARAM;
  1754. break;
  1755. }
  1756. while (t = av_dict_get(opts, "", t, AV_DICT_IGNORE_SUFFIX)) {
  1757. char *p = strchr(t->key, ':');
  1758. /* check stream specification in opt name */
  1759. if (p)
  1760. switch (check_stream_specifier(s, st, p + 1)) {
  1761. case 1: *p = 0; break;
  1762. case 0: continue;
  1763. default: return NULL;
  1764. }
  1765. if (av_opt_find(&cc, t->key, NULL, flags, AV_OPT_SEARCH_FAKE_OBJ) ||
  1766. !codec ||
  1767. (codec->priv_class &&
  1768. av_opt_find(&codec->priv_class, t->key, NULL, flags,
  1769. AV_OPT_SEARCH_FAKE_OBJ)))
  1770. av_dict_set(&ret, t->key, t->value, 0);
  1771. else if (t->key[0] == prefix &&
  1772. av_opt_find(&cc, t->key + 1, NULL, flags,
  1773. AV_OPT_SEARCH_FAKE_OBJ))
  1774. av_dict_set(&ret, t->key + 1, t->value, 0);
  1775. if (p)
  1776. *p = ':';
  1777. }
  1778. return ret;
  1779. }
  1780. AVDictionary **setup_find_stream_info_opts(AVFormatContext *s,
  1781. AVDictionary *codec_opts)
  1782. {
  1783. int i;
  1784. AVDictionary **opts;
  1785. if (!s->nb_streams)
  1786. return NULL;
  1787. opts = av_mallocz_array(s->nb_streams, sizeof(*opts));
  1788. if (!opts) {
  1789. av_log(NULL, AV_LOG_ERROR,
  1790. "Could not alloc memory for stream options.\n");
  1791. return NULL;
  1792. }
  1793. for (i = 0; i < s->nb_streams; i++)
  1794. opts[i] = filter_codec_opts(codec_opts, s->streams[i]->codec->codec_id,
  1795. s, s->streams[i], NULL);
  1796. return opts;
  1797. }
  1798. void *grow_array(void *array, int elem_size, int *size, int new_size)
  1799. {
  1800. if (new_size >= INT_MAX / elem_size) {
  1801. av_log(NULL, AV_LOG_ERROR, "Array too big.\n");
  1802. exit_program(1);
  1803. }
  1804. if (*size < new_size) {
  1805. uint8_t *tmp = av_realloc(array, new_size*elem_size);
  1806. if (!tmp) {
  1807. av_log(NULL, AV_LOG_ERROR, "Could not alloc buffer.\n");
  1808. exit_program(1);
  1809. }
  1810. memset(tmp + *size*elem_size, 0, (new_size-*size) * elem_size);
  1811. *size = new_size;
  1812. return tmp;
  1813. }
  1814. return array;
  1815. }