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.

2260 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/display.h"
  42. #include "libavutil/mathematics.h"
  43. #include "libavutil/imgutils.h"
  44. #include "libavutil/libm.h"
  45. #include "libavutil/parseutils.h"
  46. #include "libavutil/pixdesc.h"
  47. #include "libavutil/eval.h"
  48. #include "libavutil/dict.h"
  49. #include "libavutil/opt.h"
  50. #include "libavutil/cpu.h"
  51. #include "libavutil/ffversion.h"
  52. #include "cmdutils.h"
  53. #if CONFIG_NETWORK
  54. #include "libavformat/network.h"
  55. #endif
  56. #if HAVE_SYS_RESOURCE_H
  57. #include <sys/time.h>
  58. #include <sys/resource.h>
  59. #endif
  60. static int init_report(const char *env);
  61. struct SwsContext *sws_opts;
  62. AVDictionary *swr_opts;
  63. AVDictionary *format_opts, *codec_opts, *resample_opts;
  64. static FILE *report_file;
  65. static int report_file_level = AV_LOG_DEBUG;
  66. int hide_banner = 0;
  67. void init_opts(void)
  68. {
  69. if(CONFIG_SWSCALE)
  70. sws_opts = sws_getContext(16, 16, 0, 16, 16, 0, SWS_BICUBIC,
  71. NULL, NULL, NULL);
  72. }
  73. void uninit_opts(void)
  74. {
  75. #if CONFIG_SWSCALE
  76. sws_freeContext(sws_opts);
  77. sws_opts = NULL;
  78. #endif
  79. av_dict_free(&swr_opts);
  80. av_dict_free(&format_opts);
  81. av_dict_free(&codec_opts);
  82. av_dict_free(&resample_opts);
  83. }
  84. void log_callback_help(void *ptr, int level, const char *fmt, va_list vl)
  85. {
  86. vfprintf(stdout, fmt, vl);
  87. }
  88. static void log_callback_report(void *ptr, int level, const char *fmt, va_list vl)
  89. {
  90. va_list vl2;
  91. char line[1024];
  92. static int print_prefix = 1;
  93. va_copy(vl2, vl);
  94. av_log_default_callback(ptr, level, fmt, vl);
  95. av_log_format_line(ptr, level, fmt, vl2, line, sizeof(line), &print_prefix);
  96. va_end(vl2);
  97. if (report_file_level >= level) {
  98. fputs(line, report_file);
  99. fflush(report_file);
  100. }
  101. }
  102. static void (*program_exit)(int ret);
  103. void register_exit(void (*cb)(int ret))
  104. {
  105. program_exit = cb;
  106. }
  107. void exit_program(int ret)
  108. {
  109. if (program_exit)
  110. program_exit(ret);
  111. exit(ret);
  112. }
  113. double parse_number_or_die(const char *context, const char *numstr, int type,
  114. double min, double max)
  115. {
  116. char *tail;
  117. const char *error;
  118. double d = av_strtod(numstr, &tail);
  119. if (*tail)
  120. error = "Expected number for %s but found: %s\n";
  121. else if (d < min || d > max)
  122. error = "The value for %s was %s which is not within %f - %f\n";
  123. else if (type == OPT_INT64 && (int64_t)d != d)
  124. error = "Expected int64 for %s but found %s\n";
  125. else if (type == OPT_INT && (int)d != d)
  126. error = "Expected int for %s but found %s\n";
  127. else
  128. return d;
  129. av_log(NULL, AV_LOG_FATAL, error, context, numstr, min, max);
  130. exit_program(1);
  131. return 0;
  132. }
  133. int64_t parse_time_or_die(const char *context, const char *timestr,
  134. int is_duration)
  135. {
  136. int64_t us;
  137. if (av_parse_time(&us, timestr, is_duration) < 0) {
  138. av_log(NULL, AV_LOG_FATAL, "Invalid %s specification for %s: %s\n",
  139. is_duration ? "duration" : "date", context, timestr);
  140. exit_program(1);
  141. }
  142. return us;
  143. }
  144. void show_help_options(const OptionDef *options, const char *msg, int req_flags,
  145. int rej_flags, int alt_flags)
  146. {
  147. const OptionDef *po;
  148. int first;
  149. first = 1;
  150. for (po = options; po->name; po++) {
  151. char buf[64];
  152. if (((po->flags & req_flags) != req_flags) ||
  153. (alt_flags && !(po->flags & alt_flags)) ||
  154. (po->flags & rej_flags))
  155. continue;
  156. if (first) {
  157. printf("%s\n", msg);
  158. first = 0;
  159. }
  160. av_strlcpy(buf, po->name, sizeof(buf));
  161. if (po->argname) {
  162. av_strlcat(buf, " ", sizeof(buf));
  163. av_strlcat(buf, po->argname, sizeof(buf));
  164. }
  165. printf("-%-17s %s\n", buf, po->help);
  166. }
  167. printf("\n");
  168. }
  169. void show_help_children(const AVClass *class, int flags)
  170. {
  171. const AVClass *child = NULL;
  172. if (class->option) {
  173. av_opt_show2(&class, NULL, flags, 0);
  174. printf("\n");
  175. }
  176. while (child = av_opt_child_class_next(class, child))
  177. show_help_children(child, flags);
  178. }
  179. static const OptionDef *find_option(const OptionDef *po, const char *name)
  180. {
  181. const char *p = strchr(name, ':');
  182. int len = p ? p - name : strlen(name);
  183. while (po->name) {
  184. if (!strncmp(name, po->name, len) && strlen(po->name) == len)
  185. break;
  186. po++;
  187. }
  188. return po;
  189. }
  190. /* _WIN32 means using the windows libc - cygwin doesn't define that
  191. * by default. HAVE_COMMANDLINETOARGVW is true on cygwin, while
  192. * it doesn't provide the actual command line via GetCommandLineW(). */
  193. #if HAVE_COMMANDLINETOARGVW && defined(_WIN32)
  194. #include <windows.h>
  195. #include <shellapi.h>
  196. /* Will be leaked on exit */
  197. static char** win32_argv_utf8 = NULL;
  198. static int win32_argc = 0;
  199. /**
  200. * Prepare command line arguments for executable.
  201. * For Windows - perform wide-char to UTF-8 conversion.
  202. * Input arguments should be main() function arguments.
  203. * @param argc_ptr Arguments number (including executable)
  204. * @param argv_ptr Arguments list.
  205. */
  206. static void prepare_app_arguments(int *argc_ptr, char ***argv_ptr)
  207. {
  208. char *argstr_flat;
  209. wchar_t **argv_w;
  210. int i, buffsize = 0, offset = 0;
  211. if (win32_argv_utf8) {
  212. *argc_ptr = win32_argc;
  213. *argv_ptr = win32_argv_utf8;
  214. return;
  215. }
  216. win32_argc = 0;
  217. argv_w = CommandLineToArgvW(GetCommandLineW(), &win32_argc);
  218. if (win32_argc <= 0 || !argv_w)
  219. return;
  220. /* determine the UTF-8 buffer size (including NULL-termination symbols) */
  221. for (i = 0; i < win32_argc; i++)
  222. buffsize += WideCharToMultiByte(CP_UTF8, 0, argv_w[i], -1,
  223. NULL, 0, NULL, NULL);
  224. win32_argv_utf8 = av_mallocz(sizeof(char *) * (win32_argc + 1) + buffsize);
  225. argstr_flat = (char *)win32_argv_utf8 + sizeof(char *) * (win32_argc + 1);
  226. if (!win32_argv_utf8) {
  227. LocalFree(argv_w);
  228. return;
  229. }
  230. for (i = 0; i < win32_argc; i++) {
  231. win32_argv_utf8[i] = &argstr_flat[offset];
  232. offset += WideCharToMultiByte(CP_UTF8, 0, argv_w[i], -1,
  233. &argstr_flat[offset],
  234. buffsize - offset, NULL, NULL);
  235. }
  236. win32_argv_utf8[i] = NULL;
  237. LocalFree(argv_w);
  238. *argc_ptr = win32_argc;
  239. *argv_ptr = win32_argv_utf8;
  240. }
  241. #else
  242. static inline void prepare_app_arguments(int *argc_ptr, char ***argv_ptr)
  243. {
  244. /* nothing to do */
  245. }
  246. #endif /* HAVE_COMMANDLINETOARGVW */
  247. static int write_option(void *optctx, const OptionDef *po, const char *opt,
  248. const char *arg)
  249. {
  250. /* new-style options contain an offset into optctx, old-style address of
  251. * a global var*/
  252. void *dst = po->flags & (OPT_OFFSET | OPT_SPEC) ?
  253. (uint8_t *)optctx + po->u.off : po->u.dst_ptr;
  254. int *dstcount;
  255. if (po->flags & OPT_SPEC) {
  256. SpecifierOpt **so = dst;
  257. char *p = strchr(opt, ':');
  258. char *str;
  259. dstcount = (int *)(so + 1);
  260. *so = grow_array(*so, sizeof(**so), dstcount, *dstcount + 1);
  261. str = av_strdup(p ? p + 1 : "");
  262. if (!str)
  263. return AVERROR(ENOMEM);
  264. (*so)[*dstcount - 1].specifier = str;
  265. dst = &(*so)[*dstcount - 1].u;
  266. }
  267. if (po->flags & OPT_STRING) {
  268. char *str;
  269. str = av_strdup(arg);
  270. av_freep(dst);
  271. if (!str)
  272. return AVERROR(ENOMEM);
  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. { "trace" , AV_LOG_TRACE },
  737. };
  738. char *tail;
  739. int level;
  740. int flags;
  741. int i;
  742. flags = av_log_get_flags();
  743. tail = strstr(arg, "repeat");
  744. if (tail)
  745. flags &= ~AV_LOG_SKIP_REPEATED;
  746. else
  747. flags |= AV_LOG_SKIP_REPEATED;
  748. av_log_set_flags(flags);
  749. if (tail == arg)
  750. arg += 6 + (arg[6]=='+');
  751. if(tail && !*arg)
  752. return 0;
  753. for (i = 0; i < FF_ARRAY_ELEMS(log_levels); i++) {
  754. if (!strcmp(log_levels[i].name, arg)) {
  755. av_log_set_level(log_levels[i].level);
  756. return 0;
  757. }
  758. }
  759. level = strtol(arg, &tail, 10);
  760. if (*tail) {
  761. av_log(NULL, AV_LOG_FATAL, "Invalid loglevel \"%s\". "
  762. "Possible levels are numbers or:\n", arg);
  763. for (i = 0; i < FF_ARRAY_ELEMS(log_levels); i++)
  764. av_log(NULL, AV_LOG_FATAL, "\"%s\"\n", log_levels[i].name);
  765. exit_program(1);
  766. }
  767. av_log_set_level(level);
  768. return 0;
  769. }
  770. static void expand_filename_template(AVBPrint *bp, const char *template,
  771. struct tm *tm)
  772. {
  773. int c;
  774. while ((c = *(template++))) {
  775. if (c == '%') {
  776. if (!(c = *(template++)))
  777. break;
  778. switch (c) {
  779. case 'p':
  780. av_bprintf(bp, "%s", program_name);
  781. break;
  782. case 't':
  783. av_bprintf(bp, "%04d%02d%02d-%02d%02d%02d",
  784. tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday,
  785. tm->tm_hour, tm->tm_min, tm->tm_sec);
  786. break;
  787. case '%':
  788. av_bprint_chars(bp, c, 1);
  789. break;
  790. }
  791. } else {
  792. av_bprint_chars(bp, c, 1);
  793. }
  794. }
  795. }
  796. static int init_report(const char *env)
  797. {
  798. char *filename_template = NULL;
  799. char *key, *val;
  800. int ret, count = 0;
  801. time_t now;
  802. struct tm *tm;
  803. AVBPrint filename;
  804. if (report_file) /* already opened */
  805. return 0;
  806. time(&now);
  807. tm = localtime(&now);
  808. while (env && *env) {
  809. if ((ret = av_opt_get_key_value(&env, "=", ":", 0, &key, &val)) < 0) {
  810. if (count)
  811. av_log(NULL, AV_LOG_ERROR,
  812. "Failed to parse FFREPORT environment variable: %s\n",
  813. av_err2str(ret));
  814. break;
  815. }
  816. if (*env)
  817. env++;
  818. count++;
  819. if (!strcmp(key, "file")) {
  820. av_free(filename_template);
  821. filename_template = val;
  822. val = NULL;
  823. } else if (!strcmp(key, "level")) {
  824. char *tail;
  825. report_file_level = strtol(val, &tail, 10);
  826. if (*tail) {
  827. av_log(NULL, AV_LOG_FATAL, "Invalid report file level\n");
  828. exit_program(1);
  829. }
  830. } else {
  831. av_log(NULL, AV_LOG_ERROR, "Unknown key '%s' in FFREPORT\n", key);
  832. }
  833. av_free(val);
  834. av_free(key);
  835. }
  836. av_bprint_init(&filename, 0, 1);
  837. expand_filename_template(&filename,
  838. av_x_if_null(filename_template, "%p-%t.log"), tm);
  839. av_free(filename_template);
  840. if (!av_bprint_is_complete(&filename)) {
  841. av_log(NULL, AV_LOG_ERROR, "Out of memory building report file name\n");
  842. return AVERROR(ENOMEM);
  843. }
  844. report_file = fopen(filename.str, "w");
  845. if (!report_file) {
  846. int ret = AVERROR(errno);
  847. av_log(NULL, AV_LOG_ERROR, "Failed to open report \"%s\": %s\n",
  848. filename.str, strerror(errno));
  849. return ret;
  850. }
  851. av_log_set_callback(log_callback_report);
  852. av_log(NULL, AV_LOG_INFO,
  853. "%s started on %04d-%02d-%02d at %02d:%02d:%02d\n"
  854. "Report written to \"%s\"\n",
  855. program_name,
  856. tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday,
  857. tm->tm_hour, tm->tm_min, tm->tm_sec,
  858. filename.str);
  859. av_bprint_finalize(&filename, NULL);
  860. return 0;
  861. }
  862. int opt_report(const char *opt)
  863. {
  864. return init_report(NULL);
  865. }
  866. int opt_max_alloc(void *optctx, const char *opt, const char *arg)
  867. {
  868. char *tail;
  869. size_t max;
  870. max = strtol(arg, &tail, 10);
  871. if (*tail) {
  872. av_log(NULL, AV_LOG_FATAL, "Invalid max_alloc \"%s\".\n", arg);
  873. exit_program(1);
  874. }
  875. av_max_alloc(max);
  876. return 0;
  877. }
  878. int opt_timelimit(void *optctx, const char *opt, const char *arg)
  879. {
  880. #if HAVE_SETRLIMIT
  881. int lim = parse_number_or_die(opt, arg, OPT_INT64, 0, INT_MAX);
  882. struct rlimit rl = { lim, lim + 1 };
  883. if (setrlimit(RLIMIT_CPU, &rl))
  884. perror("setrlimit");
  885. #else
  886. av_log(NULL, AV_LOG_WARNING, "-%s not implemented on this OS\n", opt);
  887. #endif
  888. return 0;
  889. }
  890. void print_error(const char *filename, int err)
  891. {
  892. char errbuf[128];
  893. const char *errbuf_ptr = errbuf;
  894. if (av_strerror(err, errbuf, sizeof(errbuf)) < 0)
  895. errbuf_ptr = strerror(AVUNERROR(err));
  896. av_log(NULL, AV_LOG_ERROR, "%s: %s\n", filename, errbuf_ptr);
  897. }
  898. static int warned_cfg = 0;
  899. #define INDENT 1
  900. #define SHOW_VERSION 2
  901. #define SHOW_CONFIG 4
  902. #define SHOW_COPYRIGHT 8
  903. #define PRINT_LIB_INFO(libname, LIBNAME, flags, level) \
  904. if (CONFIG_##LIBNAME) { \
  905. const char *indent = flags & INDENT? " " : ""; \
  906. if (flags & SHOW_VERSION) { \
  907. unsigned int version = libname##_version(); \
  908. av_log(NULL, level, \
  909. "%slib%-11s %2d.%3d.%3d / %2d.%3d.%3d\n", \
  910. indent, #libname, \
  911. LIB##LIBNAME##_VERSION_MAJOR, \
  912. LIB##LIBNAME##_VERSION_MINOR, \
  913. LIB##LIBNAME##_VERSION_MICRO, \
  914. version >> 16, version >> 8 & 0xff, version & 0xff); \
  915. } \
  916. if (flags & SHOW_CONFIG) { \
  917. const char *cfg = libname##_configuration(); \
  918. if (strcmp(FFMPEG_CONFIGURATION, cfg)) { \
  919. if (!warned_cfg) { \
  920. av_log(NULL, level, \
  921. "%sWARNING: library configuration mismatch\n", \
  922. indent); \
  923. warned_cfg = 1; \
  924. } \
  925. av_log(NULL, level, "%s%-11s configuration: %s\n", \
  926. indent, #libname, cfg); \
  927. } \
  928. } \
  929. } \
  930. static void print_all_libs_info(int flags, int level)
  931. {
  932. PRINT_LIB_INFO(avutil, AVUTIL, flags, level);
  933. PRINT_LIB_INFO(avcodec, AVCODEC, flags, level);
  934. PRINT_LIB_INFO(avformat, AVFORMAT, flags, level);
  935. PRINT_LIB_INFO(avdevice, AVDEVICE, flags, level);
  936. PRINT_LIB_INFO(avfilter, AVFILTER, flags, level);
  937. PRINT_LIB_INFO(avresample, AVRESAMPLE, flags, level);
  938. PRINT_LIB_INFO(swscale, SWSCALE, flags, level);
  939. PRINT_LIB_INFO(swresample,SWRESAMPLE, flags, level);
  940. PRINT_LIB_INFO(postproc, POSTPROC, flags, level);
  941. }
  942. static void print_program_info(int flags, int level)
  943. {
  944. const char *indent = flags & INDENT? " " : "";
  945. av_log(NULL, level, "%s version " FFMPEG_VERSION, program_name);
  946. if (flags & SHOW_COPYRIGHT)
  947. av_log(NULL, level, " Copyright (c) %d-%d the FFmpeg developers",
  948. program_birth_year, CONFIG_THIS_YEAR);
  949. av_log(NULL, level, "\n");
  950. av_log(NULL, level, "%sbuilt with %s\n", indent, CC_IDENT);
  951. av_log(NULL, level, "%sconfiguration: " FFMPEG_CONFIGURATION "\n", indent);
  952. }
  953. static void print_buildconf(int flags, int level)
  954. {
  955. const char *indent = flags & INDENT ? " " : "";
  956. char str[] = { FFMPEG_CONFIGURATION };
  957. char *conflist, *remove_tilde, *splitconf;
  958. // Change all the ' --' strings to '~--' so that
  959. // they can be identified as tokens.
  960. while ((conflist = strstr(str, " --")) != NULL) {
  961. strncpy(conflist, "~--", 3);
  962. }
  963. // Compensate for the weirdness this would cause
  964. // when passing 'pkg-config --static'.
  965. while ((remove_tilde = strstr(str, "pkg-config~")) != NULL) {
  966. strncpy(remove_tilde, "pkg-config ", 11);
  967. }
  968. splitconf = strtok(str, "~");
  969. av_log(NULL, level, "\n%sconfiguration:\n", indent);
  970. while (splitconf != NULL) {
  971. av_log(NULL, level, "%s%s%s\n", indent, indent, splitconf);
  972. splitconf = strtok(NULL, "~");
  973. }
  974. }
  975. void show_banner(int argc, char **argv, const OptionDef *options)
  976. {
  977. int idx = locate_option(argc, argv, options, "version");
  978. if (hide_banner || idx)
  979. return;
  980. print_program_info (INDENT|SHOW_COPYRIGHT, AV_LOG_INFO);
  981. print_all_libs_info(INDENT|SHOW_CONFIG, AV_LOG_INFO);
  982. print_all_libs_info(INDENT|SHOW_VERSION, AV_LOG_INFO);
  983. }
  984. int show_version(void *optctx, const char *opt, const char *arg)
  985. {
  986. av_log_set_callback(log_callback_help);
  987. print_program_info (SHOW_COPYRIGHT, AV_LOG_INFO);
  988. print_all_libs_info(SHOW_VERSION, AV_LOG_INFO);
  989. return 0;
  990. }
  991. int show_buildconf(void *optctx, const char *opt, const char *arg)
  992. {
  993. av_log_set_callback(log_callback_help);
  994. print_buildconf (INDENT|0, AV_LOG_INFO);
  995. return 0;
  996. }
  997. int show_license(void *optctx, const char *opt, const char *arg)
  998. {
  999. #if CONFIG_NONFREE
  1000. printf(
  1001. "This version of %s has nonfree parts compiled in.\n"
  1002. "Therefore it is not legally redistributable.\n",
  1003. program_name );
  1004. #elif CONFIG_GPLV3
  1005. printf(
  1006. "%s is free software; you can redistribute it and/or modify\n"
  1007. "it under the terms of the GNU General Public License as published by\n"
  1008. "the Free Software Foundation; either version 3 of the License, or\n"
  1009. "(at your option) any later version.\n"
  1010. "\n"
  1011. "%s is distributed in the hope that it will be useful,\n"
  1012. "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
  1013. "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n"
  1014. "GNU General Public License for more details.\n"
  1015. "\n"
  1016. "You should have received a copy of the GNU General Public License\n"
  1017. "along with %s. If not, see <http://www.gnu.org/licenses/>.\n",
  1018. program_name, program_name, program_name );
  1019. #elif CONFIG_GPL
  1020. printf(
  1021. "%s is free software; you can redistribute it and/or modify\n"
  1022. "it under the terms of the GNU General Public License as published by\n"
  1023. "the Free Software Foundation; either version 2 of the License, or\n"
  1024. "(at your option) any later version.\n"
  1025. "\n"
  1026. "%s is distributed in the hope that it will be useful,\n"
  1027. "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
  1028. "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n"
  1029. "GNU General Public License for more details.\n"
  1030. "\n"
  1031. "You should have received a copy of the GNU General Public License\n"
  1032. "along with %s; if not, write to the Free Software\n"
  1033. "Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n",
  1034. program_name, program_name, program_name );
  1035. #elif CONFIG_LGPLV3
  1036. printf(
  1037. "%s is free software; you can redistribute it and/or modify\n"
  1038. "it under the terms of the GNU Lesser General Public License as published by\n"
  1039. "the Free Software Foundation; either version 3 of the License, or\n"
  1040. "(at your option) any later version.\n"
  1041. "\n"
  1042. "%s is distributed in the hope that it will be useful,\n"
  1043. "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
  1044. "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n"
  1045. "GNU Lesser General Public License for more details.\n"
  1046. "\n"
  1047. "You should have received a copy of the GNU Lesser General Public License\n"
  1048. "along with %s. If not, see <http://www.gnu.org/licenses/>.\n",
  1049. program_name, program_name, program_name );
  1050. #else
  1051. printf(
  1052. "%s is free software; you can redistribute it and/or\n"
  1053. "modify it under the terms of the GNU Lesser General Public\n"
  1054. "License as published by the Free Software Foundation; either\n"
  1055. "version 2.1 of the License, or (at your option) any later version.\n"
  1056. "\n"
  1057. "%s is distributed in the hope that it will be useful,\n"
  1058. "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
  1059. "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n"
  1060. "Lesser General Public License for more details.\n"
  1061. "\n"
  1062. "You should have received a copy of the GNU Lesser General Public\n"
  1063. "License along with %s; if not, write to the Free Software\n"
  1064. "Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n",
  1065. program_name, program_name, program_name );
  1066. #endif
  1067. return 0;
  1068. }
  1069. static int is_device(const AVClass *avclass)
  1070. {
  1071. if (!avclass)
  1072. return 0;
  1073. return AV_IS_INPUT_DEVICE(avclass->category) || AV_IS_OUTPUT_DEVICE(avclass->category);
  1074. }
  1075. static int show_formats_devices(void *optctx, const char *opt, const char *arg, int device_only)
  1076. {
  1077. AVInputFormat *ifmt = NULL;
  1078. AVOutputFormat *ofmt = NULL;
  1079. const char *last_name;
  1080. int is_dev;
  1081. printf("%s\n"
  1082. " D. = Demuxing supported\n"
  1083. " .E = Muxing supported\n"
  1084. " --\n", device_only ? "Devices:" : "File formats:");
  1085. last_name = "000";
  1086. for (;;) {
  1087. int decode = 0;
  1088. int encode = 0;
  1089. const char *name = NULL;
  1090. const char *long_name = NULL;
  1091. while ((ofmt = av_oformat_next(ofmt))) {
  1092. is_dev = is_device(ofmt->priv_class);
  1093. if (!is_dev && device_only)
  1094. continue;
  1095. if ((!name || strcmp(ofmt->name, name) < 0) &&
  1096. strcmp(ofmt->name, last_name) > 0) {
  1097. name = ofmt->name;
  1098. long_name = ofmt->long_name;
  1099. encode = 1;
  1100. }
  1101. }
  1102. while ((ifmt = av_iformat_next(ifmt))) {
  1103. is_dev = is_device(ifmt->priv_class);
  1104. if (!is_dev && device_only)
  1105. continue;
  1106. if ((!name || strcmp(ifmt->name, name) < 0) &&
  1107. strcmp(ifmt->name, last_name) > 0) {
  1108. name = ifmt->name;
  1109. long_name = ifmt->long_name;
  1110. encode = 0;
  1111. }
  1112. if (name && strcmp(ifmt->name, name) == 0)
  1113. decode = 1;
  1114. }
  1115. if (!name)
  1116. break;
  1117. last_name = name;
  1118. printf(" %s%s %-15s %s\n",
  1119. decode ? "D" : " ",
  1120. encode ? "E" : " ",
  1121. name,
  1122. long_name ? long_name:" ");
  1123. }
  1124. return 0;
  1125. }
  1126. int show_formats(void *optctx, const char *opt, const char *arg)
  1127. {
  1128. return show_formats_devices(optctx, opt, arg, 0);
  1129. }
  1130. int show_devices(void *optctx, const char *opt, const char *arg)
  1131. {
  1132. return show_formats_devices(optctx, opt, arg, 1);
  1133. }
  1134. #define PRINT_CODEC_SUPPORTED(codec, field, type, list_name, term, get_name) \
  1135. if (codec->field) { \
  1136. const type *p = codec->field; \
  1137. \
  1138. printf(" Supported " list_name ":"); \
  1139. while (*p != term) { \
  1140. get_name(*p); \
  1141. printf(" %s", name); \
  1142. p++; \
  1143. } \
  1144. printf("\n"); \
  1145. } \
  1146. static void print_codec(const AVCodec *c)
  1147. {
  1148. int encoder = av_codec_is_encoder(c);
  1149. printf("%s %s [%s]:\n", encoder ? "Encoder" : "Decoder", c->name,
  1150. c->long_name ? c->long_name : "");
  1151. if (c->type == AVMEDIA_TYPE_VIDEO ||
  1152. c->type == AVMEDIA_TYPE_AUDIO) {
  1153. printf(" Threading capabilities: ");
  1154. switch (c->capabilities & (CODEC_CAP_FRAME_THREADS |
  1155. CODEC_CAP_SLICE_THREADS)) {
  1156. case CODEC_CAP_FRAME_THREADS |
  1157. CODEC_CAP_SLICE_THREADS: printf("frame and slice"); break;
  1158. case CODEC_CAP_FRAME_THREADS: printf("frame"); break;
  1159. case CODEC_CAP_SLICE_THREADS: printf("slice"); break;
  1160. default: printf("no"); break;
  1161. }
  1162. printf("\n");
  1163. }
  1164. if (c->supported_framerates) {
  1165. const AVRational *fps = c->supported_framerates;
  1166. printf(" Supported framerates:");
  1167. while (fps->num) {
  1168. printf(" %d/%d", fps->num, fps->den);
  1169. fps++;
  1170. }
  1171. printf("\n");
  1172. }
  1173. PRINT_CODEC_SUPPORTED(c, pix_fmts, enum AVPixelFormat, "pixel formats",
  1174. AV_PIX_FMT_NONE, GET_PIX_FMT_NAME);
  1175. PRINT_CODEC_SUPPORTED(c, supported_samplerates, int, "sample rates", 0,
  1176. GET_SAMPLE_RATE_NAME);
  1177. PRINT_CODEC_SUPPORTED(c, sample_fmts, enum AVSampleFormat, "sample formats",
  1178. AV_SAMPLE_FMT_NONE, GET_SAMPLE_FMT_NAME);
  1179. PRINT_CODEC_SUPPORTED(c, channel_layouts, uint64_t, "channel layouts",
  1180. 0, GET_CH_LAYOUT_DESC);
  1181. if (c->priv_class) {
  1182. show_help_children(c->priv_class,
  1183. AV_OPT_FLAG_ENCODING_PARAM |
  1184. AV_OPT_FLAG_DECODING_PARAM);
  1185. }
  1186. }
  1187. static char get_media_type_char(enum AVMediaType type)
  1188. {
  1189. switch (type) {
  1190. case AVMEDIA_TYPE_VIDEO: return 'V';
  1191. case AVMEDIA_TYPE_AUDIO: return 'A';
  1192. case AVMEDIA_TYPE_DATA: return 'D';
  1193. case AVMEDIA_TYPE_SUBTITLE: return 'S';
  1194. case AVMEDIA_TYPE_ATTACHMENT:return 'T';
  1195. default: return '?';
  1196. }
  1197. }
  1198. static const AVCodec *next_codec_for_id(enum AVCodecID id, const AVCodec *prev,
  1199. int encoder)
  1200. {
  1201. while ((prev = av_codec_next(prev))) {
  1202. if (prev->id == id &&
  1203. (encoder ? av_codec_is_encoder(prev) : av_codec_is_decoder(prev)))
  1204. return prev;
  1205. }
  1206. return NULL;
  1207. }
  1208. static int compare_codec_desc(const void *a, const void *b)
  1209. {
  1210. const AVCodecDescriptor * const *da = a;
  1211. const AVCodecDescriptor * const *db = b;
  1212. return (*da)->type != (*db)->type ? (*da)->type - (*db)->type :
  1213. strcmp((*da)->name, (*db)->name);
  1214. }
  1215. static unsigned get_codecs_sorted(const AVCodecDescriptor ***rcodecs)
  1216. {
  1217. const AVCodecDescriptor *desc = NULL;
  1218. const AVCodecDescriptor **codecs;
  1219. unsigned nb_codecs = 0, i = 0;
  1220. while ((desc = avcodec_descriptor_next(desc)))
  1221. nb_codecs++;
  1222. if (!(codecs = av_calloc(nb_codecs, sizeof(*codecs)))) {
  1223. av_log(NULL, AV_LOG_ERROR, "Out of memory\n");
  1224. exit_program(1);
  1225. }
  1226. desc = NULL;
  1227. while ((desc = avcodec_descriptor_next(desc)))
  1228. codecs[i++] = desc;
  1229. av_assert0(i == nb_codecs);
  1230. qsort(codecs, nb_codecs, sizeof(*codecs), compare_codec_desc);
  1231. *rcodecs = codecs;
  1232. return nb_codecs;
  1233. }
  1234. static void print_codecs_for_id(enum AVCodecID id, int encoder)
  1235. {
  1236. const AVCodec *codec = NULL;
  1237. printf(" (%s: ", encoder ? "encoders" : "decoders");
  1238. while ((codec = next_codec_for_id(id, codec, encoder)))
  1239. printf("%s ", codec->name);
  1240. printf(")");
  1241. }
  1242. int show_codecs(void *optctx, const char *opt, const char *arg)
  1243. {
  1244. const AVCodecDescriptor **codecs;
  1245. unsigned i, nb_codecs = get_codecs_sorted(&codecs);
  1246. printf("Codecs:\n"
  1247. " D..... = Decoding supported\n"
  1248. " .E.... = Encoding supported\n"
  1249. " ..V... = Video codec\n"
  1250. " ..A... = Audio codec\n"
  1251. " ..S... = Subtitle codec\n"
  1252. " ...I.. = Intra frame-only codec\n"
  1253. " ....L. = Lossy compression\n"
  1254. " .....S = Lossless compression\n"
  1255. " -------\n");
  1256. for (i = 0; i < nb_codecs; i++) {
  1257. const AVCodecDescriptor *desc = codecs[i];
  1258. const AVCodec *codec = NULL;
  1259. if (strstr(desc->name, "_deprecated"))
  1260. continue;
  1261. printf(" ");
  1262. printf(avcodec_find_decoder(desc->id) ? "D" : ".");
  1263. printf(avcodec_find_encoder(desc->id) ? "E" : ".");
  1264. printf("%c", get_media_type_char(desc->type));
  1265. printf((desc->props & AV_CODEC_PROP_INTRA_ONLY) ? "I" : ".");
  1266. printf((desc->props & AV_CODEC_PROP_LOSSY) ? "L" : ".");
  1267. printf((desc->props & AV_CODEC_PROP_LOSSLESS) ? "S" : ".");
  1268. printf(" %-20s %s", desc->name, desc->long_name ? desc->long_name : "");
  1269. /* print decoders/encoders when there's more than one or their
  1270. * names are different from codec name */
  1271. while ((codec = next_codec_for_id(desc->id, codec, 0))) {
  1272. if (strcmp(codec->name, desc->name)) {
  1273. print_codecs_for_id(desc->id, 0);
  1274. break;
  1275. }
  1276. }
  1277. codec = NULL;
  1278. while ((codec = next_codec_for_id(desc->id, codec, 1))) {
  1279. if (strcmp(codec->name, desc->name)) {
  1280. print_codecs_for_id(desc->id, 1);
  1281. break;
  1282. }
  1283. }
  1284. printf("\n");
  1285. }
  1286. av_free(codecs);
  1287. return 0;
  1288. }
  1289. static void print_codecs(int encoder)
  1290. {
  1291. const AVCodecDescriptor **codecs;
  1292. unsigned i, nb_codecs = get_codecs_sorted(&codecs);
  1293. printf("%s:\n"
  1294. " V..... = Video\n"
  1295. " A..... = Audio\n"
  1296. " S..... = Subtitle\n"
  1297. " .F.... = Frame-level multithreading\n"
  1298. " ..S... = Slice-level multithreading\n"
  1299. " ...X.. = Codec is experimental\n"
  1300. " ....B. = Supports draw_horiz_band\n"
  1301. " .....D = Supports direct rendering method 1\n"
  1302. " ------\n",
  1303. encoder ? "Encoders" : "Decoders");
  1304. for (i = 0; i < nb_codecs; i++) {
  1305. const AVCodecDescriptor *desc = codecs[i];
  1306. const AVCodec *codec = NULL;
  1307. while ((codec = next_codec_for_id(desc->id, codec, encoder))) {
  1308. printf(" %c", get_media_type_char(desc->type));
  1309. printf((codec->capabilities & CODEC_CAP_FRAME_THREADS) ? "F" : ".");
  1310. printf((codec->capabilities & CODEC_CAP_SLICE_THREADS) ? "S" : ".");
  1311. printf((codec->capabilities & CODEC_CAP_EXPERIMENTAL) ? "X" : ".");
  1312. printf((codec->capabilities & CODEC_CAP_DRAW_HORIZ_BAND)?"B" : ".");
  1313. printf((codec->capabilities & CODEC_CAP_DR1) ? "D" : ".");
  1314. printf(" %-20s %s", codec->name, codec->long_name ? codec->long_name : "");
  1315. if (strcmp(codec->name, desc->name))
  1316. printf(" (codec %s)", desc->name);
  1317. printf("\n");
  1318. }
  1319. }
  1320. av_free(codecs);
  1321. }
  1322. int show_decoders(void *optctx, const char *opt, const char *arg)
  1323. {
  1324. print_codecs(0);
  1325. return 0;
  1326. }
  1327. int show_encoders(void *optctx, const char *opt, const char *arg)
  1328. {
  1329. print_codecs(1);
  1330. return 0;
  1331. }
  1332. int show_bsfs(void *optctx, const char *opt, const char *arg)
  1333. {
  1334. AVBitStreamFilter *bsf = NULL;
  1335. printf("Bitstream filters:\n");
  1336. while ((bsf = av_bitstream_filter_next(bsf)))
  1337. printf("%s\n", bsf->name);
  1338. printf("\n");
  1339. return 0;
  1340. }
  1341. int show_protocols(void *optctx, const char *opt, const char *arg)
  1342. {
  1343. void *opaque = NULL;
  1344. const char *name;
  1345. printf("Supported file protocols:\n"
  1346. "Input:\n");
  1347. while ((name = avio_enum_protocols(&opaque, 0)))
  1348. printf(" %s\n", name);
  1349. printf("Output:\n");
  1350. while ((name = avio_enum_protocols(&opaque, 1)))
  1351. printf(" %s\n", name);
  1352. return 0;
  1353. }
  1354. int show_filters(void *optctx, const char *opt, const char *arg)
  1355. {
  1356. #if CONFIG_AVFILTER
  1357. const AVFilter *filter = NULL;
  1358. char descr[64], *descr_cur;
  1359. int i, j;
  1360. const AVFilterPad *pad;
  1361. printf("Filters:\n"
  1362. " T.. = Timeline support\n"
  1363. " .S. = Slice threading\n"
  1364. " ..C = Command support\n"
  1365. " A = Audio input/output\n"
  1366. " V = Video input/output\n"
  1367. " N = Dynamic number and/or type of input/output\n"
  1368. " | = Source or sink filter\n");
  1369. while ((filter = avfilter_next(filter))) {
  1370. descr_cur = descr;
  1371. for (i = 0; i < 2; i++) {
  1372. if (i) {
  1373. *(descr_cur++) = '-';
  1374. *(descr_cur++) = '>';
  1375. }
  1376. pad = i ? filter->outputs : filter->inputs;
  1377. for (j = 0; pad && pad[j].name; j++) {
  1378. if (descr_cur >= descr + sizeof(descr) - 4)
  1379. break;
  1380. *(descr_cur++) = get_media_type_char(pad[j].type);
  1381. }
  1382. if (!j)
  1383. *(descr_cur++) = ((!i && (filter->flags & AVFILTER_FLAG_DYNAMIC_INPUTS)) ||
  1384. ( i && (filter->flags & AVFILTER_FLAG_DYNAMIC_OUTPUTS))) ? 'N' : '|';
  1385. }
  1386. *descr_cur = 0;
  1387. printf(" %c%c%c %-16s %-10s %s\n",
  1388. filter->flags & AVFILTER_FLAG_SUPPORT_TIMELINE ? 'T' : '.',
  1389. filter->flags & AVFILTER_FLAG_SLICE_THREADS ? 'S' : '.',
  1390. filter->process_command ? 'C' : '.',
  1391. filter->name, descr, filter->description);
  1392. }
  1393. #else
  1394. printf("No filters available: libavfilter disabled\n");
  1395. #endif
  1396. return 0;
  1397. }
  1398. int show_colors(void *optctx, const char *opt, const char *arg)
  1399. {
  1400. const char *name;
  1401. const uint8_t *rgb;
  1402. int i;
  1403. printf("%-32s #RRGGBB\n", "name");
  1404. for (i = 0; name = av_get_known_color_name(i, &rgb); i++)
  1405. printf("%-32s #%02x%02x%02x\n", name, rgb[0], rgb[1], rgb[2]);
  1406. return 0;
  1407. }
  1408. int show_pix_fmts(void *optctx, const char *opt, const char *arg)
  1409. {
  1410. const AVPixFmtDescriptor *pix_desc = NULL;
  1411. printf("Pixel formats:\n"
  1412. "I.... = Supported Input format for conversion\n"
  1413. ".O... = Supported Output format for conversion\n"
  1414. "..H.. = Hardware accelerated format\n"
  1415. "...P. = Paletted format\n"
  1416. "....B = Bitstream format\n"
  1417. "FLAGS NAME NB_COMPONENTS BITS_PER_PIXEL\n"
  1418. "-----\n");
  1419. #if !CONFIG_SWSCALE
  1420. # define sws_isSupportedInput(x) 0
  1421. # define sws_isSupportedOutput(x) 0
  1422. #endif
  1423. while ((pix_desc = av_pix_fmt_desc_next(pix_desc))) {
  1424. enum AVPixelFormat pix_fmt = av_pix_fmt_desc_get_id(pix_desc);
  1425. printf("%c%c%c%c%c %-16s %d %2d\n",
  1426. sws_isSupportedInput (pix_fmt) ? 'I' : '.',
  1427. sws_isSupportedOutput(pix_fmt) ? 'O' : '.',
  1428. pix_desc->flags & AV_PIX_FMT_FLAG_HWACCEL ? 'H' : '.',
  1429. pix_desc->flags & AV_PIX_FMT_FLAG_PAL ? 'P' : '.',
  1430. pix_desc->flags & AV_PIX_FMT_FLAG_BITSTREAM ? 'B' : '.',
  1431. pix_desc->name,
  1432. pix_desc->nb_components,
  1433. av_get_bits_per_pixel(pix_desc));
  1434. }
  1435. return 0;
  1436. }
  1437. int show_layouts(void *optctx, const char *opt, const char *arg)
  1438. {
  1439. int i = 0;
  1440. uint64_t layout, j;
  1441. const char *name, *descr;
  1442. printf("Individual channels:\n"
  1443. "NAME DESCRIPTION\n");
  1444. for (i = 0; i < 63; i++) {
  1445. name = av_get_channel_name((uint64_t)1 << i);
  1446. if (!name)
  1447. continue;
  1448. descr = av_get_channel_description((uint64_t)1 << i);
  1449. printf("%-14s %s\n", name, descr);
  1450. }
  1451. printf("\nStandard channel layouts:\n"
  1452. "NAME DECOMPOSITION\n");
  1453. for (i = 0; !av_get_standard_channel_layout(i, &layout, &name); i++) {
  1454. if (name) {
  1455. printf("%-14s ", name);
  1456. for (j = 1; j; j <<= 1)
  1457. if ((layout & j))
  1458. printf("%s%s", (layout & (j - 1)) ? "+" : "", av_get_channel_name(j));
  1459. printf("\n");
  1460. }
  1461. }
  1462. return 0;
  1463. }
  1464. int show_sample_fmts(void *optctx, const char *opt, const char *arg)
  1465. {
  1466. int i;
  1467. char fmt_str[128];
  1468. for (i = -1; i < AV_SAMPLE_FMT_NB; i++)
  1469. printf("%s\n", av_get_sample_fmt_string(fmt_str, sizeof(fmt_str), i));
  1470. return 0;
  1471. }
  1472. static void show_help_codec(const char *name, int encoder)
  1473. {
  1474. const AVCodecDescriptor *desc;
  1475. const AVCodec *codec;
  1476. if (!name) {
  1477. av_log(NULL, AV_LOG_ERROR, "No codec name specified.\n");
  1478. return;
  1479. }
  1480. codec = encoder ? avcodec_find_encoder_by_name(name) :
  1481. avcodec_find_decoder_by_name(name);
  1482. if (codec)
  1483. print_codec(codec);
  1484. else if ((desc = avcodec_descriptor_get_by_name(name))) {
  1485. int printed = 0;
  1486. while ((codec = next_codec_for_id(desc->id, codec, encoder))) {
  1487. printed = 1;
  1488. print_codec(codec);
  1489. }
  1490. if (!printed) {
  1491. av_log(NULL, AV_LOG_ERROR, "Codec '%s' is known to FFmpeg, "
  1492. "but no %s for it are available. FFmpeg might need to be "
  1493. "recompiled with additional external libraries.\n",
  1494. name, encoder ? "encoders" : "decoders");
  1495. }
  1496. } else {
  1497. av_log(NULL, AV_LOG_ERROR, "Codec '%s' is not recognized by FFmpeg.\n",
  1498. name);
  1499. }
  1500. }
  1501. static void show_help_demuxer(const char *name)
  1502. {
  1503. const AVInputFormat *fmt = av_find_input_format(name);
  1504. if (!fmt) {
  1505. av_log(NULL, AV_LOG_ERROR, "Unknown format '%s'.\n", name);
  1506. return;
  1507. }
  1508. printf("Demuxer %s [%s]:\n", fmt->name, fmt->long_name);
  1509. if (fmt->extensions)
  1510. printf(" Common extensions: %s.\n", fmt->extensions);
  1511. if (fmt->priv_class)
  1512. show_help_children(fmt->priv_class, AV_OPT_FLAG_DECODING_PARAM);
  1513. }
  1514. static void show_help_muxer(const char *name)
  1515. {
  1516. const AVCodecDescriptor *desc;
  1517. const AVOutputFormat *fmt = av_guess_format(name, NULL, NULL);
  1518. if (!fmt) {
  1519. av_log(NULL, AV_LOG_ERROR, "Unknown format '%s'.\n", name);
  1520. return;
  1521. }
  1522. printf("Muxer %s [%s]:\n", fmt->name, fmt->long_name);
  1523. if (fmt->extensions)
  1524. printf(" Common extensions: %s.\n", fmt->extensions);
  1525. if (fmt->mime_type)
  1526. printf(" Mime type: %s.\n", fmt->mime_type);
  1527. if (fmt->video_codec != AV_CODEC_ID_NONE &&
  1528. (desc = avcodec_descriptor_get(fmt->video_codec))) {
  1529. printf(" Default video codec: %s.\n", desc->name);
  1530. }
  1531. if (fmt->audio_codec != AV_CODEC_ID_NONE &&
  1532. (desc = avcodec_descriptor_get(fmt->audio_codec))) {
  1533. printf(" Default audio codec: %s.\n", desc->name);
  1534. }
  1535. if (fmt->subtitle_codec != AV_CODEC_ID_NONE &&
  1536. (desc = avcodec_descriptor_get(fmt->subtitle_codec))) {
  1537. printf(" Default subtitle codec: %s.\n", desc->name);
  1538. }
  1539. if (fmt->priv_class)
  1540. show_help_children(fmt->priv_class, AV_OPT_FLAG_ENCODING_PARAM);
  1541. }
  1542. #if CONFIG_AVFILTER
  1543. static void show_help_filter(const char *name)
  1544. {
  1545. #if CONFIG_AVFILTER
  1546. const AVFilter *f = avfilter_get_by_name(name);
  1547. int i, count;
  1548. if (!name) {
  1549. av_log(NULL, AV_LOG_ERROR, "No filter name specified.\n");
  1550. return;
  1551. } else if (!f) {
  1552. av_log(NULL, AV_LOG_ERROR, "Unknown filter '%s'.\n", name);
  1553. return;
  1554. }
  1555. printf("Filter %s\n", f->name);
  1556. if (f->description)
  1557. printf(" %s\n", f->description);
  1558. if (f->flags & AVFILTER_FLAG_SLICE_THREADS)
  1559. printf(" slice threading supported\n");
  1560. printf(" Inputs:\n");
  1561. count = avfilter_pad_count(f->inputs);
  1562. for (i = 0; i < count; i++) {
  1563. printf(" #%d: %s (%s)\n", i, avfilter_pad_get_name(f->inputs, i),
  1564. media_type_string(avfilter_pad_get_type(f->inputs, i)));
  1565. }
  1566. if (f->flags & AVFILTER_FLAG_DYNAMIC_INPUTS)
  1567. printf(" dynamic (depending on the options)\n");
  1568. else if (!count)
  1569. printf(" none (source filter)\n");
  1570. printf(" Outputs:\n");
  1571. count = avfilter_pad_count(f->outputs);
  1572. for (i = 0; i < count; i++) {
  1573. printf(" #%d: %s (%s)\n", i, avfilter_pad_get_name(f->outputs, i),
  1574. media_type_string(avfilter_pad_get_type(f->outputs, i)));
  1575. }
  1576. if (f->flags & AVFILTER_FLAG_DYNAMIC_OUTPUTS)
  1577. printf(" dynamic (depending on the options)\n");
  1578. else if (!count)
  1579. printf(" none (sink filter)\n");
  1580. if (f->priv_class)
  1581. show_help_children(f->priv_class, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_FILTERING_PARAM |
  1582. AV_OPT_FLAG_AUDIO_PARAM);
  1583. if (f->flags & AVFILTER_FLAG_SUPPORT_TIMELINE)
  1584. printf("This filter has support for timeline through the 'enable' option.\n");
  1585. #else
  1586. av_log(NULL, AV_LOG_ERROR, "Build without libavfilter; "
  1587. "can not to satisfy request\n");
  1588. #endif
  1589. }
  1590. #endif
  1591. int show_help(void *optctx, const char *opt, const char *arg)
  1592. {
  1593. char *topic, *par;
  1594. av_log_set_callback(log_callback_help);
  1595. topic = av_strdup(arg ? arg : "");
  1596. if (!topic)
  1597. return AVERROR(ENOMEM);
  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. ret = AVERROR(errno);
  1635. av_log(NULL, AV_LOG_ERROR, "Cannot read file '%s': %s\n", filename,
  1636. strerror(errno));
  1637. return ret;
  1638. }
  1639. ret = fseek(f, 0, SEEK_END);
  1640. if (ret == -1) {
  1641. ret = AVERROR(errno);
  1642. goto out;
  1643. }
  1644. ret = ftell(f);
  1645. if (ret < 0) {
  1646. ret = AVERROR(errno);
  1647. goto out;
  1648. }
  1649. *size = ret;
  1650. ret = fseek(f, 0, SEEK_SET);
  1651. if (ret == -1) {
  1652. ret = AVERROR(errno);
  1653. goto out;
  1654. }
  1655. *bufptr = av_malloc(*size + 1);
  1656. if (!*bufptr) {
  1657. av_log(NULL, AV_LOG_ERROR, "Could not allocate file buffer\n");
  1658. ret = AVERROR(ENOMEM);
  1659. goto out;
  1660. }
  1661. ret = fread(*bufptr, 1, *size, f);
  1662. if (ret < *size) {
  1663. av_free(*bufptr);
  1664. if (ferror(f)) {
  1665. ret = AVERROR(errno);
  1666. av_log(NULL, AV_LOG_ERROR, "Error while reading file '%s': %s\n",
  1667. filename, strerror(errno));
  1668. } else
  1669. ret = AVERROR_EOF;
  1670. } else {
  1671. ret = 0;
  1672. (*bufptr)[(*size)++] = '\0';
  1673. }
  1674. out:
  1675. if (ret < 0)
  1676. av_log(NULL, AV_LOG_ERROR, "IO error: %s\n", av_err2str(ret));
  1677. fclose(f);
  1678. return ret;
  1679. }
  1680. FILE *get_preset_file(char *filename, size_t filename_size,
  1681. const char *preset_name, int is_path,
  1682. const char *codec_name)
  1683. {
  1684. FILE *f = NULL;
  1685. int i;
  1686. const char *base[3] = { getenv("FFMPEG_DATADIR"),
  1687. getenv("HOME"),
  1688. FFMPEG_DATADIR, };
  1689. if (is_path) {
  1690. av_strlcpy(filename, preset_name, filename_size);
  1691. f = fopen(filename, "r");
  1692. } else {
  1693. #ifdef _WIN32
  1694. char datadir[MAX_PATH], *ls;
  1695. base[2] = NULL;
  1696. if (GetModuleFileNameA(GetModuleHandleA(NULL), datadir, sizeof(datadir) - 1))
  1697. {
  1698. for (ls = datadir; ls < datadir + strlen(datadir); ls++)
  1699. if (*ls == '\\') *ls = '/';
  1700. if (ls = strrchr(datadir, '/'))
  1701. {
  1702. *ls = 0;
  1703. strncat(datadir, "/ffpresets", sizeof(datadir) - 1 - strlen(datadir));
  1704. base[2] = datadir;
  1705. }
  1706. }
  1707. #endif
  1708. for (i = 0; i < 3 && !f; i++) {
  1709. if (!base[i])
  1710. continue;
  1711. snprintf(filename, filename_size, "%s%s/%s.ffpreset", base[i],
  1712. i != 1 ? "" : "/.ffmpeg", preset_name);
  1713. f = fopen(filename, "r");
  1714. if (!f && codec_name) {
  1715. snprintf(filename, filename_size,
  1716. "%s%s/%s-%s.ffpreset",
  1717. base[i], i != 1 ? "" : "/.ffmpeg", codec_name,
  1718. preset_name);
  1719. f = fopen(filename, "r");
  1720. }
  1721. }
  1722. }
  1723. return f;
  1724. }
  1725. int check_stream_specifier(AVFormatContext *s, AVStream *st, const char *spec)
  1726. {
  1727. int ret = avformat_match_stream_specifier(s, st, spec);
  1728. if (ret < 0)
  1729. av_log(s, AV_LOG_ERROR, "Invalid stream specifier: %s.\n", spec);
  1730. return ret;
  1731. }
  1732. AVDictionary *filter_codec_opts(AVDictionary *opts, enum AVCodecID codec_id,
  1733. AVFormatContext *s, AVStream *st, AVCodec *codec)
  1734. {
  1735. AVDictionary *ret = NULL;
  1736. AVDictionaryEntry *t = NULL;
  1737. int flags = s->oformat ? AV_OPT_FLAG_ENCODING_PARAM
  1738. : AV_OPT_FLAG_DECODING_PARAM;
  1739. char prefix = 0;
  1740. const AVClass *cc = avcodec_get_class();
  1741. if (!codec)
  1742. codec = s->oformat ? avcodec_find_encoder(codec_id)
  1743. : avcodec_find_decoder(codec_id);
  1744. switch (st->codec->codec_type) {
  1745. case AVMEDIA_TYPE_VIDEO:
  1746. prefix = 'v';
  1747. flags |= AV_OPT_FLAG_VIDEO_PARAM;
  1748. break;
  1749. case AVMEDIA_TYPE_AUDIO:
  1750. prefix = 'a';
  1751. flags |= AV_OPT_FLAG_AUDIO_PARAM;
  1752. break;
  1753. case AVMEDIA_TYPE_SUBTITLE:
  1754. prefix = 's';
  1755. flags |= AV_OPT_FLAG_SUBTITLE_PARAM;
  1756. break;
  1757. }
  1758. while (t = av_dict_get(opts, "", t, AV_DICT_IGNORE_SUFFIX)) {
  1759. char *p = strchr(t->key, ':');
  1760. /* check stream specification in opt name */
  1761. if (p)
  1762. switch (check_stream_specifier(s, st, p + 1)) {
  1763. case 1: *p = 0; break;
  1764. case 0: continue;
  1765. default: exit_program(1);
  1766. }
  1767. if (av_opt_find(&cc, t->key, NULL, flags, AV_OPT_SEARCH_FAKE_OBJ) ||
  1768. !codec ||
  1769. (codec->priv_class &&
  1770. av_opt_find(&codec->priv_class, t->key, NULL, flags,
  1771. AV_OPT_SEARCH_FAKE_OBJ)))
  1772. av_dict_set(&ret, t->key, t->value, 0);
  1773. else if (t->key[0] == prefix &&
  1774. av_opt_find(&cc, t->key + 1, NULL, flags,
  1775. AV_OPT_SEARCH_FAKE_OBJ))
  1776. av_dict_set(&ret, t->key + 1, t->value, 0);
  1777. if (p)
  1778. *p = ':';
  1779. }
  1780. return ret;
  1781. }
  1782. AVDictionary **setup_find_stream_info_opts(AVFormatContext *s,
  1783. AVDictionary *codec_opts)
  1784. {
  1785. int i;
  1786. AVDictionary **opts;
  1787. if (!s->nb_streams)
  1788. return NULL;
  1789. opts = av_mallocz_array(s->nb_streams, sizeof(*opts));
  1790. if (!opts) {
  1791. av_log(NULL, AV_LOG_ERROR,
  1792. "Could not alloc memory for stream options.\n");
  1793. return NULL;
  1794. }
  1795. for (i = 0; i < s->nb_streams; i++)
  1796. opts[i] = filter_codec_opts(codec_opts, s->streams[i]->codec->codec_id,
  1797. s, s->streams[i], NULL);
  1798. return opts;
  1799. }
  1800. void *grow_array(void *array, int elem_size, int *size, int new_size)
  1801. {
  1802. if (new_size >= INT_MAX / elem_size) {
  1803. av_log(NULL, AV_LOG_ERROR, "Array too big.\n");
  1804. exit_program(1);
  1805. }
  1806. if (*size < new_size) {
  1807. uint8_t *tmp = av_realloc_array(array, new_size, elem_size);
  1808. if (!tmp) {
  1809. av_log(NULL, AV_LOG_ERROR, "Could not alloc buffer.\n");
  1810. exit_program(1);
  1811. }
  1812. memset(tmp + *size*elem_size, 0, (new_size-*size) * elem_size);
  1813. *size = new_size;
  1814. return tmp;
  1815. }
  1816. return array;
  1817. }
  1818. double get_rotation(AVStream *st)
  1819. {
  1820. AVDictionaryEntry *rotate_tag = av_dict_get(st->metadata, "rotate", NULL, 0);
  1821. uint8_t* displaymatrix = av_stream_get_side_data(st,
  1822. AV_PKT_DATA_DISPLAYMATRIX, NULL);
  1823. double theta = 0;
  1824. if (rotate_tag && *rotate_tag->value && strcmp(rotate_tag->value, "0")) {
  1825. char *tail;
  1826. theta = av_strtod(rotate_tag->value, &tail);
  1827. if (*tail)
  1828. theta = 0;
  1829. }
  1830. if (displaymatrix && !theta)
  1831. theta = av_display_rotation_get((int32_t*) displaymatrix);
  1832. theta -= 360*floor(theta/360 + 0.9/360);
  1833. if (fabs(theta - 90*round(theta/90)) > 2)
  1834. av_log_ask_for_sample(NULL, "Odd rotation angle\n");
  1835. return theta;
  1836. }
  1837. #if CONFIG_AVDEVICE
  1838. static int print_device_sources(AVInputFormat *fmt, AVDictionary *opts)
  1839. {
  1840. int ret, i;
  1841. AVDeviceInfoList *device_list = NULL;
  1842. if (!fmt || !fmt->priv_class || !AV_IS_INPUT_DEVICE(fmt->priv_class->category))
  1843. return AVERROR(EINVAL);
  1844. printf("Audo-detected sources for %s:\n", fmt->name);
  1845. if (!fmt->get_device_list) {
  1846. ret = AVERROR(ENOSYS);
  1847. printf("Cannot list sources. Not implemented.\n");
  1848. goto fail;
  1849. }
  1850. if ((ret = avdevice_list_input_sources(fmt, NULL, opts, &device_list)) < 0) {
  1851. printf("Cannot list sources.\n");
  1852. goto fail;
  1853. }
  1854. for (i = 0; i < device_list->nb_devices; i++) {
  1855. printf("%s %s [%s]\n", device_list->default_device == i ? "*" : " ",
  1856. device_list->devices[i]->device_name, device_list->devices[i]->device_description);
  1857. }
  1858. fail:
  1859. avdevice_free_list_devices(&device_list);
  1860. return ret;
  1861. }
  1862. static int print_device_sinks(AVOutputFormat *fmt, AVDictionary *opts)
  1863. {
  1864. int ret, i;
  1865. AVDeviceInfoList *device_list = NULL;
  1866. if (!fmt || !fmt->priv_class || !AV_IS_OUTPUT_DEVICE(fmt->priv_class->category))
  1867. return AVERROR(EINVAL);
  1868. printf("Audo-detected sinks for %s:\n", fmt->name);
  1869. if (!fmt->get_device_list) {
  1870. ret = AVERROR(ENOSYS);
  1871. printf("Cannot list sinks. Not implemented.\n");
  1872. goto fail;
  1873. }
  1874. if ((ret = avdevice_list_output_sinks(fmt, NULL, opts, &device_list)) < 0) {
  1875. printf("Cannot list sinks.\n");
  1876. goto fail;
  1877. }
  1878. for (i = 0; i < device_list->nb_devices; i++) {
  1879. printf("%s %s [%s]\n", device_list->default_device == i ? "*" : " ",
  1880. device_list->devices[i]->device_name, device_list->devices[i]->device_description);
  1881. }
  1882. fail:
  1883. avdevice_free_list_devices(&device_list);
  1884. return ret;
  1885. }
  1886. static int show_sinks_sources_parse_arg(const char *arg, char **dev, AVDictionary **opts)
  1887. {
  1888. int ret;
  1889. if (arg) {
  1890. char *opts_str = NULL;
  1891. av_assert0(dev && opts);
  1892. *dev = av_strdup(arg);
  1893. if (!*dev)
  1894. return AVERROR(ENOMEM);
  1895. if ((opts_str = strchr(*dev, ','))) {
  1896. *(opts_str++) = '\0';
  1897. if (opts_str[0] && ((ret = av_dict_parse_string(opts, opts_str, "=", ":", 0)) < 0)) {
  1898. av_freep(dev);
  1899. return ret;
  1900. }
  1901. }
  1902. } else
  1903. printf("\nDevice name is not provided.\n"
  1904. "You can pass devicename[,opt1=val1[,opt2=val2...]] as an argument.\n\n");
  1905. return 0;
  1906. }
  1907. int show_sources(void *optctx, const char *opt, const char *arg)
  1908. {
  1909. AVInputFormat *fmt = NULL;
  1910. char *dev = NULL;
  1911. AVDictionary *opts = NULL;
  1912. int ret = 0;
  1913. int error_level = av_log_get_level();
  1914. av_log_set_level(AV_LOG_ERROR);
  1915. if ((ret = show_sinks_sources_parse_arg(arg, &dev, &opts)) < 0)
  1916. goto fail;
  1917. do {
  1918. fmt = av_input_audio_device_next(fmt);
  1919. if (fmt) {
  1920. if (!strcmp(fmt->name, "lavfi"))
  1921. continue; //it's pointless to probe lavfi
  1922. if (dev && !av_match_name(dev, fmt->name))
  1923. continue;
  1924. print_device_sources(fmt, opts);
  1925. }
  1926. } while (fmt);
  1927. do {
  1928. fmt = av_input_video_device_next(fmt);
  1929. if (fmt) {
  1930. if (dev && !av_match_name(dev, fmt->name))
  1931. continue;
  1932. print_device_sources(fmt, opts);
  1933. }
  1934. } while (fmt);
  1935. fail:
  1936. av_dict_free(&opts);
  1937. av_free(dev);
  1938. av_log_set_level(error_level);
  1939. return ret;
  1940. }
  1941. int show_sinks(void *optctx, const char *opt, const char *arg)
  1942. {
  1943. AVOutputFormat *fmt = NULL;
  1944. char *dev = NULL;
  1945. AVDictionary *opts = NULL;
  1946. int ret = 0;
  1947. int error_level = av_log_get_level();
  1948. av_log_set_level(AV_LOG_ERROR);
  1949. if ((ret = show_sinks_sources_parse_arg(arg, &dev, &opts)) < 0)
  1950. goto fail;
  1951. do {
  1952. fmt = av_output_audio_device_next(fmt);
  1953. if (fmt) {
  1954. if (dev && !av_match_name(dev, fmt->name))
  1955. continue;
  1956. print_device_sinks(fmt, opts);
  1957. }
  1958. } while (fmt);
  1959. do {
  1960. fmt = av_output_video_device_next(fmt);
  1961. if (fmt) {
  1962. if (dev && !av_match_name(dev, fmt->name))
  1963. continue;
  1964. print_device_sinks(fmt, opts);
  1965. }
  1966. } while (fmt);
  1967. fail:
  1968. av_dict_free(&opts);
  1969. av_free(dev);
  1970. av_log_set_level(error_level);
  1971. return ret;
  1972. }
  1973. #endif