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.

1978 lines
61KB

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