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.

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