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.

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