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.

2255 lines
70KB

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