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.

1408 lines
45KB

  1. /*
  2. * Various utilities for command line tools
  3. * Copyright (c) 2000-2003 Fabrice Bellard
  4. *
  5. * This file is part of Libav.
  6. *
  7. * Libav 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. * Libav 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 Libav; 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 "libavformat/avformat.h"
  30. #include "libavfilter/avfilter.h"
  31. #include "libavdevice/avdevice.h"
  32. #include "libavresample/avresample.h"
  33. #include "libswscale/swscale.h"
  34. #include "libavutil/avassert.h"
  35. #include "libavutil/avstring.h"
  36. #include "libavutil/mathematics.h"
  37. #include "libavutil/imgutils.h"
  38. #include "libavutil/parseutils.h"
  39. #include "libavutil/pixdesc.h"
  40. #include "libavutil/eval.h"
  41. #include "libavutil/dict.h"
  42. #include "libavutil/opt.h"
  43. #include "cmdutils.h"
  44. #include "version.h"
  45. #if CONFIG_NETWORK
  46. #include "libavformat/network.h"
  47. #endif
  48. #if HAVE_SYS_RESOURCE_H
  49. #include <sys/resource.h>
  50. #endif
  51. struct SwsContext *sws_opts;
  52. AVDictionary *format_opts, *codec_opts;
  53. static const int this_year = 2012;
  54. void init_opts(void)
  55. {
  56. #if CONFIG_SWSCALE
  57. sws_opts = sws_getContext(16, 16, 0, 16, 16, 0, SWS_BICUBIC,
  58. NULL, NULL, NULL);
  59. #endif
  60. }
  61. void uninit_opts(void)
  62. {
  63. #if CONFIG_SWSCALE
  64. sws_freeContext(sws_opts);
  65. sws_opts = NULL;
  66. #endif
  67. av_dict_free(&format_opts);
  68. av_dict_free(&codec_opts);
  69. }
  70. void log_callback_help(void *ptr, int level, const char *fmt, va_list vl)
  71. {
  72. vfprintf(stdout, fmt, vl);
  73. }
  74. double parse_number_or_die(const char *context, const char *numstr, int type,
  75. double min, double max)
  76. {
  77. char *tail;
  78. const char *error;
  79. double d = av_strtod(numstr, &tail);
  80. if (*tail)
  81. error = "Expected number for %s but found: %s\n";
  82. else if (d < min || d > max)
  83. error = "The value for %s was %s which is not within %f - %f\n";
  84. else if (type == OPT_INT64 && (int64_t)d != d)
  85. error = "Expected int64 for %s but found %s\n";
  86. else if (type == OPT_INT && (int)d != d)
  87. error = "Expected int for %s but found %s\n";
  88. else
  89. return d;
  90. av_log(NULL, AV_LOG_FATAL, error, context, numstr, min, max);
  91. exit_program(1);
  92. return 0;
  93. }
  94. int64_t parse_time_or_die(const char *context, const char *timestr,
  95. int is_duration)
  96. {
  97. int64_t us;
  98. if (av_parse_time(&us, timestr, is_duration) < 0) {
  99. av_log(NULL, AV_LOG_FATAL, "Invalid %s specification for %s: %s\n",
  100. is_duration ? "duration" : "date", context, timestr);
  101. exit_program(1);
  102. }
  103. return us;
  104. }
  105. void show_help_options(const OptionDef *options, const char *msg, int req_flags,
  106. int rej_flags, int alt_flags)
  107. {
  108. const OptionDef *po;
  109. int first;
  110. first = 1;
  111. for (po = options; po->name != NULL; po++) {
  112. char buf[64];
  113. if (((po->flags & req_flags) != req_flags) ||
  114. (alt_flags && !(po->flags & alt_flags)) ||
  115. (po->flags & rej_flags))
  116. continue;
  117. if (first) {
  118. printf("%s\n", msg);
  119. first = 0;
  120. }
  121. av_strlcpy(buf, po->name, sizeof(buf));
  122. if (po->argname) {
  123. av_strlcat(buf, " ", sizeof(buf));
  124. av_strlcat(buf, po->argname, sizeof(buf));
  125. }
  126. printf("-%-17s %s\n", buf, po->help);
  127. }
  128. printf("\n");
  129. }
  130. void show_help_children(const AVClass *class, int flags)
  131. {
  132. const AVClass *child = NULL;
  133. av_opt_show2(&class, NULL, flags, 0);
  134. printf("\n");
  135. while (child = av_opt_child_class_next(class, child))
  136. show_help_children(child, flags);
  137. }
  138. static const OptionDef *find_option(const OptionDef *po, const char *name)
  139. {
  140. const char *p = strchr(name, ':');
  141. int len = p ? p - name : strlen(name);
  142. while (po->name != NULL) {
  143. if (!strncmp(name, po->name, len) && strlen(po->name) == len)
  144. break;
  145. po++;
  146. }
  147. return po;
  148. }
  149. #if defined(_WIN32) && !defined(__MINGW32CE__)
  150. #include <windows.h>
  151. #include <shellapi.h>
  152. /* Will be leaked on exit */
  153. static char** win32_argv_utf8 = NULL;
  154. static int win32_argc = 0;
  155. /**
  156. * Prepare command line arguments for executable.
  157. * For Windows - perform wide-char to UTF-8 conversion.
  158. * Input arguments should be main() function arguments.
  159. * @param argc_ptr Arguments number (including executable)
  160. * @param argv_ptr Arguments list.
  161. */
  162. static void prepare_app_arguments(int *argc_ptr, char ***argv_ptr)
  163. {
  164. char *argstr_flat;
  165. wchar_t **argv_w;
  166. int i, buffsize = 0, offset = 0;
  167. if (win32_argv_utf8) {
  168. *argc_ptr = win32_argc;
  169. *argv_ptr = win32_argv_utf8;
  170. return;
  171. }
  172. win32_argc = 0;
  173. argv_w = CommandLineToArgvW(GetCommandLineW(), &win32_argc);
  174. if (win32_argc <= 0 || !argv_w)
  175. return;
  176. /* determine the UTF-8 buffer size (including NULL-termination symbols) */
  177. for (i = 0; i < win32_argc; i++)
  178. buffsize += WideCharToMultiByte(CP_UTF8, 0, argv_w[i], -1,
  179. NULL, 0, NULL, NULL);
  180. win32_argv_utf8 = av_mallocz(sizeof(char *) * (win32_argc + 1) + buffsize);
  181. argstr_flat = (char *)win32_argv_utf8 + sizeof(char *) * (win32_argc + 1);
  182. if (win32_argv_utf8 == NULL) {
  183. LocalFree(argv_w);
  184. return;
  185. }
  186. for (i = 0; i < win32_argc; i++) {
  187. win32_argv_utf8[i] = &argstr_flat[offset];
  188. offset += WideCharToMultiByte(CP_UTF8, 0, argv_w[i], -1,
  189. &argstr_flat[offset],
  190. buffsize - offset, NULL, NULL);
  191. }
  192. win32_argv_utf8[i] = NULL;
  193. LocalFree(argv_w);
  194. *argc_ptr = win32_argc;
  195. *argv_ptr = win32_argv_utf8;
  196. }
  197. #else
  198. static inline void prepare_app_arguments(int *argc_ptr, char ***argv_ptr)
  199. {
  200. /* nothing to do */
  201. }
  202. #endif /* WIN32 && !__MINGW32CE__ */
  203. int parse_option(void *optctx, const char *opt, const char *arg,
  204. const OptionDef *options)
  205. {
  206. const OptionDef *po;
  207. int bool_val = 1;
  208. int *dstcount;
  209. void *dst;
  210. po = find_option(options, opt);
  211. if (!po->name && opt[0] == 'n' && opt[1] == 'o') {
  212. /* handle 'no' bool option */
  213. po = find_option(options, opt + 2);
  214. if ((po->name && (po->flags & OPT_BOOL)))
  215. bool_val = 0;
  216. }
  217. if (!po->name)
  218. po = find_option(options, "default");
  219. if (!po->name) {
  220. av_log(NULL, AV_LOG_ERROR, "Unrecognized option '%s'\n", opt);
  221. return AVERROR(EINVAL);
  222. }
  223. if (po->flags & HAS_ARG && !arg) {
  224. av_log(NULL, AV_LOG_ERROR, "Missing argument for option '%s'\n", opt);
  225. return AVERROR(EINVAL);
  226. }
  227. /* new-style options contain an offset into optctx, old-style address of
  228. * a global var*/
  229. dst = po->flags & (OPT_OFFSET | OPT_SPEC) ? (uint8_t *)optctx + po->u.off
  230. : po->u.dst_ptr;
  231. if (po->flags & OPT_SPEC) {
  232. SpecifierOpt **so = dst;
  233. char *p = strchr(opt, ':');
  234. dstcount = (int *)(so + 1);
  235. *so = grow_array(*so, sizeof(**so), dstcount, *dstcount + 1);
  236. (*so)[*dstcount - 1].specifier = av_strdup(p ? p + 1 : "");
  237. dst = &(*so)[*dstcount - 1].u;
  238. }
  239. if (po->flags & OPT_STRING) {
  240. char *str;
  241. str = av_strdup(arg);
  242. av_freep(dst);
  243. *(char **)dst = str;
  244. } else if (po->flags & OPT_BOOL) {
  245. *(int *)dst = bool_val;
  246. } else if (po->flags & OPT_INT) {
  247. *(int *)dst = parse_number_or_die(opt, arg, OPT_INT64, INT_MIN, INT_MAX);
  248. } else if (po->flags & OPT_INT64) {
  249. *(int64_t *)dst = parse_number_or_die(opt, arg, OPT_INT64, INT64_MIN, INT64_MAX);
  250. } else if (po->flags & OPT_TIME) {
  251. *(int64_t *)dst = parse_time_or_die(opt, arg, 1);
  252. } else if (po->flags & OPT_FLOAT) {
  253. *(float *)dst = parse_number_or_die(opt, arg, OPT_FLOAT, -INFINITY, INFINITY);
  254. } else if (po->flags & OPT_DOUBLE) {
  255. *(double *)dst = parse_number_or_die(opt, arg, OPT_DOUBLE, -INFINITY, INFINITY);
  256. } else if (po->u.func_arg) {
  257. int ret = po->flags & OPT_FUNC2 ? po->u.func2_arg(optctx, opt, arg)
  258. : po->u.func_arg(opt, arg);
  259. if (ret < 0) {
  260. av_log(NULL, AV_LOG_ERROR,
  261. "Failed to set value '%s' for option '%s'\n", arg, opt);
  262. return ret;
  263. }
  264. }
  265. if (po->flags & OPT_EXIT)
  266. exit_program(0);
  267. return !!(po->flags & HAS_ARG);
  268. }
  269. void parse_options(void *optctx, int argc, char **argv, const OptionDef *options,
  270. void (*parse_arg_function)(void *, const char*))
  271. {
  272. const char *opt;
  273. int optindex, handleoptions = 1, ret;
  274. /* perform system-dependent conversions for arguments list */
  275. prepare_app_arguments(&argc, &argv);
  276. /* parse options */
  277. optindex = 1;
  278. while (optindex < argc) {
  279. opt = argv[optindex++];
  280. if (handleoptions && opt[0] == '-' && opt[1] != '\0') {
  281. if (opt[1] == '-' && opt[2] == '\0') {
  282. handleoptions = 0;
  283. continue;
  284. }
  285. opt++;
  286. if ((ret = parse_option(optctx, opt, argv[optindex], options)) < 0)
  287. exit_program(1);
  288. optindex += ret;
  289. } else {
  290. if (parse_arg_function)
  291. parse_arg_function(optctx, opt);
  292. }
  293. }
  294. }
  295. int locate_option(int argc, char **argv, const OptionDef *options,
  296. const char *optname)
  297. {
  298. const OptionDef *po;
  299. int i;
  300. for (i = 1; i < argc; i++) {
  301. const char *cur_opt = argv[i];
  302. if (*cur_opt++ != '-')
  303. continue;
  304. po = find_option(options, cur_opt);
  305. if (!po->name && cur_opt[0] == 'n' && cur_opt[1] == 'o')
  306. po = find_option(options, cur_opt + 2);
  307. if ((!po->name && !strcmp(cur_opt, optname)) ||
  308. (po->name && !strcmp(optname, po->name)))
  309. return i;
  310. if (!po || po->flags & HAS_ARG)
  311. i++;
  312. }
  313. return 0;
  314. }
  315. void parse_loglevel(int argc, char **argv, const OptionDef *options)
  316. {
  317. int idx = locate_option(argc, argv, options, "loglevel");
  318. if (!idx)
  319. idx = locate_option(argc, argv, options, "v");
  320. if (idx && argv[idx + 1])
  321. opt_loglevel("loglevel", argv[idx + 1]);
  322. }
  323. #define FLAGS (o->type == AV_OPT_TYPE_FLAGS) ? AV_DICT_APPEND : 0
  324. int opt_default(const char *opt, const char *arg)
  325. {
  326. const AVOption *o;
  327. char opt_stripped[128];
  328. const char *p;
  329. const AVClass *cc = avcodec_get_class(), *fc = avformat_get_class(), *sc = sws_get_class();
  330. if (!(p = strchr(opt, ':')))
  331. p = opt + strlen(opt);
  332. av_strlcpy(opt_stripped, opt, FFMIN(sizeof(opt_stripped), p - opt + 1));
  333. if ((o = av_opt_find(&cc, opt_stripped, NULL, 0,
  334. AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ)) ||
  335. ((opt[0] == 'v' || opt[0] == 'a' || opt[0] == 's') &&
  336. (o = av_opt_find(&cc, opt + 1, NULL, 0, AV_OPT_SEARCH_FAKE_OBJ))))
  337. av_dict_set(&codec_opts, opt, arg, FLAGS);
  338. else if ((o = av_opt_find(&fc, opt, NULL, 0,
  339. AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ)))
  340. av_dict_set(&format_opts, opt, arg, FLAGS);
  341. else if ((o = av_opt_find(&sc, opt, NULL, 0,
  342. AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ))) {
  343. // XXX we only support sws_flags, not arbitrary sws options
  344. int ret = av_opt_set(sws_opts, opt, arg, 0);
  345. if (ret < 0) {
  346. av_log(NULL, AV_LOG_ERROR, "Error setting option %s.\n", opt);
  347. return ret;
  348. }
  349. }
  350. if (o)
  351. return 0;
  352. av_log(NULL, AV_LOG_ERROR, "Unrecognized option '%s'\n", opt);
  353. return AVERROR_OPTION_NOT_FOUND;
  354. }
  355. int opt_loglevel(const char *opt, const char *arg)
  356. {
  357. const struct { const char *name; int level; } log_levels[] = {
  358. { "quiet" , AV_LOG_QUIET },
  359. { "panic" , AV_LOG_PANIC },
  360. { "fatal" , AV_LOG_FATAL },
  361. { "error" , AV_LOG_ERROR },
  362. { "warning", AV_LOG_WARNING },
  363. { "info" , AV_LOG_INFO },
  364. { "verbose", AV_LOG_VERBOSE },
  365. { "debug" , AV_LOG_DEBUG },
  366. };
  367. char *tail;
  368. int level;
  369. int i;
  370. for (i = 0; i < FF_ARRAY_ELEMS(log_levels); i++) {
  371. if (!strcmp(log_levels[i].name, arg)) {
  372. av_log_set_level(log_levels[i].level);
  373. return 0;
  374. }
  375. }
  376. level = strtol(arg, &tail, 10);
  377. if (*tail) {
  378. av_log(NULL, AV_LOG_FATAL, "Invalid loglevel \"%s\". "
  379. "Possible levels are numbers or:\n", arg);
  380. for (i = 0; i < FF_ARRAY_ELEMS(log_levels); i++)
  381. av_log(NULL, AV_LOG_FATAL, "\"%s\"\n", log_levels[i].name);
  382. exit_program(1);
  383. }
  384. av_log_set_level(level);
  385. return 0;
  386. }
  387. int opt_timelimit(const char *opt, const char *arg)
  388. {
  389. #if HAVE_SETRLIMIT
  390. int lim = parse_number_or_die(opt, arg, OPT_INT64, 0, INT_MAX);
  391. struct rlimit rl = { lim, lim + 1 };
  392. if (setrlimit(RLIMIT_CPU, &rl))
  393. perror("setrlimit");
  394. #else
  395. av_log(NULL, AV_LOG_WARNING, "-%s not implemented on this OS\n", opt);
  396. #endif
  397. return 0;
  398. }
  399. void print_error(const char *filename, int err)
  400. {
  401. char errbuf[128];
  402. const char *errbuf_ptr = errbuf;
  403. if (av_strerror(err, errbuf, sizeof(errbuf)) < 0)
  404. errbuf_ptr = strerror(AVUNERROR(err));
  405. av_log(NULL, AV_LOG_ERROR, "%s: %s\n", filename, errbuf_ptr);
  406. }
  407. static int warned_cfg = 0;
  408. #define INDENT 1
  409. #define SHOW_VERSION 2
  410. #define SHOW_CONFIG 4
  411. #define PRINT_LIB_INFO(libname, LIBNAME, flags, level) \
  412. if (CONFIG_##LIBNAME) { \
  413. const char *indent = flags & INDENT? " " : ""; \
  414. if (flags & SHOW_VERSION) { \
  415. unsigned int version = libname##_version(); \
  416. av_log(NULL, level, \
  417. "%slib%-10s %2d.%3d.%2d / %2d.%3d.%2d\n", \
  418. indent, #libname, \
  419. LIB##LIBNAME##_VERSION_MAJOR, \
  420. LIB##LIBNAME##_VERSION_MINOR, \
  421. LIB##LIBNAME##_VERSION_MICRO, \
  422. version >> 16, version >> 8 & 0xff, version & 0xff); \
  423. } \
  424. if (flags & SHOW_CONFIG) { \
  425. const char *cfg = libname##_configuration(); \
  426. if (strcmp(LIBAV_CONFIGURATION, cfg)) { \
  427. if (!warned_cfg) { \
  428. av_log(NULL, level, \
  429. "%sWARNING: library configuration mismatch\n", \
  430. indent); \
  431. warned_cfg = 1; \
  432. } \
  433. av_log(NULL, level, "%s%-11s configuration: %s\n", \
  434. indent, #libname, cfg); \
  435. } \
  436. } \
  437. } \
  438. static void print_all_libs_info(int flags, int level)
  439. {
  440. PRINT_LIB_INFO(avutil, AVUTIL, flags, level);
  441. PRINT_LIB_INFO(avcodec, AVCODEC, flags, level);
  442. PRINT_LIB_INFO(avformat, AVFORMAT, flags, level);
  443. PRINT_LIB_INFO(avdevice, AVDEVICE, flags, level);
  444. PRINT_LIB_INFO(avfilter, AVFILTER, flags, level);
  445. PRINT_LIB_INFO(avresample, AVRESAMPLE, flags, level);
  446. PRINT_LIB_INFO(swscale, SWSCALE, flags, level);
  447. }
  448. void show_banner(void)
  449. {
  450. av_log(NULL, AV_LOG_INFO,
  451. "%s version " LIBAV_VERSION ", Copyright (c) %d-%d the Libav developers\n",
  452. program_name, program_birth_year, this_year);
  453. av_log(NULL, AV_LOG_INFO, " built on %s %s with %s\n",
  454. __DATE__, __TIME__, CC_IDENT);
  455. av_log(NULL, AV_LOG_VERBOSE, " configuration: " LIBAV_CONFIGURATION "\n");
  456. print_all_libs_info(INDENT|SHOW_CONFIG, AV_LOG_VERBOSE);
  457. print_all_libs_info(INDENT|SHOW_VERSION, AV_LOG_VERBOSE);
  458. }
  459. int show_version(const char *opt, const char *arg)
  460. {
  461. av_log_set_callback(log_callback_help);
  462. printf("%s " LIBAV_VERSION "\n", program_name);
  463. print_all_libs_info(SHOW_VERSION, AV_LOG_INFO);
  464. return 0;
  465. }
  466. int show_license(const char *opt, const char *arg)
  467. {
  468. printf(
  469. #if CONFIG_NONFREE
  470. "This version of %s has nonfree parts compiled in.\n"
  471. "Therefore it is not legally redistributable.\n",
  472. program_name
  473. #elif CONFIG_GPLV3
  474. "%s is free software; you can redistribute it and/or modify\n"
  475. "it under the terms of the GNU General Public License as published by\n"
  476. "the Free Software Foundation; either version 3 of the License, or\n"
  477. "(at your option) any later version.\n"
  478. "\n"
  479. "%s is distributed in the hope that it will be useful,\n"
  480. "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
  481. "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n"
  482. "GNU General Public License for more details.\n"
  483. "\n"
  484. "You should have received a copy of the GNU General Public License\n"
  485. "along with %s. If not, see <http://www.gnu.org/licenses/>.\n",
  486. program_name, program_name, program_name
  487. #elif CONFIG_GPL
  488. "%s is free software; you can redistribute it and/or modify\n"
  489. "it under the terms of the GNU General Public License as published by\n"
  490. "the Free Software Foundation; either version 2 of the License, or\n"
  491. "(at your option) any later version.\n"
  492. "\n"
  493. "%s is distributed in the hope that it will be useful,\n"
  494. "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
  495. "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n"
  496. "GNU General Public License for more details.\n"
  497. "\n"
  498. "You should have received a copy of the GNU General Public License\n"
  499. "along with %s; if not, write to the Free Software\n"
  500. "Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n",
  501. program_name, program_name, program_name
  502. #elif CONFIG_LGPLV3
  503. "%s is free software; you can redistribute it and/or modify\n"
  504. "it under the terms of the GNU Lesser General Public License as published by\n"
  505. "the Free Software Foundation; either version 3 of the License, or\n"
  506. "(at your option) any later version.\n"
  507. "\n"
  508. "%s is distributed in the hope that it will be useful,\n"
  509. "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
  510. "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n"
  511. "GNU Lesser General Public License for more details.\n"
  512. "\n"
  513. "You should have received a copy of the GNU Lesser General Public License\n"
  514. "along with %s. If not, see <http://www.gnu.org/licenses/>.\n",
  515. program_name, program_name, program_name
  516. #else
  517. "%s is free software; you can redistribute it and/or\n"
  518. "modify it under the terms of the GNU Lesser General Public\n"
  519. "License as published by the Free Software Foundation; either\n"
  520. "version 2.1 of the License, or (at your option) any later version.\n"
  521. "\n"
  522. "%s is distributed in the hope that it will be useful,\n"
  523. "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
  524. "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n"
  525. "Lesser General Public License for more details.\n"
  526. "\n"
  527. "You should have received a copy of the GNU Lesser General Public\n"
  528. "License along with %s; if not, write to the Free Software\n"
  529. "Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n",
  530. program_name, program_name, program_name
  531. #endif
  532. );
  533. return 0;
  534. }
  535. int show_formats(const char *opt, const char *arg)
  536. {
  537. AVInputFormat *ifmt = NULL;
  538. AVOutputFormat *ofmt = NULL;
  539. const char *last_name;
  540. printf("File formats:\n"
  541. " D. = Demuxing supported\n"
  542. " .E = Muxing supported\n"
  543. " --\n");
  544. last_name = "000";
  545. for (;;) {
  546. int decode = 0;
  547. int encode = 0;
  548. const char *name = NULL;
  549. const char *long_name = NULL;
  550. while ((ofmt = av_oformat_next(ofmt))) {
  551. if ((name == NULL || strcmp(ofmt->name, name) < 0) &&
  552. strcmp(ofmt->name, last_name) > 0) {
  553. name = ofmt->name;
  554. long_name = ofmt->long_name;
  555. encode = 1;
  556. }
  557. }
  558. while ((ifmt = av_iformat_next(ifmt))) {
  559. if ((name == NULL || strcmp(ifmt->name, name) < 0) &&
  560. strcmp(ifmt->name, last_name) > 0) {
  561. name = ifmt->name;
  562. long_name = ifmt->long_name;
  563. encode = 0;
  564. }
  565. if (name && strcmp(ifmt->name, name) == 0)
  566. decode = 1;
  567. }
  568. if (name == NULL)
  569. break;
  570. last_name = name;
  571. printf(" %s%s %-15s %s\n",
  572. decode ? "D" : " ",
  573. encode ? "E" : " ",
  574. name,
  575. long_name ? long_name:" ");
  576. }
  577. return 0;
  578. }
  579. #define PRINT_CODEC_SUPPORTED(codec, field, type, list_name, term, get_name) \
  580. if (codec->field) { \
  581. const type *p = c->field; \
  582. \
  583. printf(" Supported " list_name ":"); \
  584. while (*p != term) { \
  585. get_name(*p); \
  586. printf(" %s", name); \
  587. p++; \
  588. } \
  589. printf("\n"); \
  590. } \
  591. static void print_codec(const AVCodec *c)
  592. {
  593. int encoder = av_codec_is_encoder(c);
  594. printf("%s %s [%s]:\n", encoder ? "Encoder" : "Decoder", c->name,
  595. c->long_name ? c->long_name : "");
  596. if (c->type == AVMEDIA_TYPE_VIDEO) {
  597. printf(" Threading capabilities: ");
  598. switch (c->capabilities & (CODEC_CAP_FRAME_THREADS |
  599. CODEC_CAP_SLICE_THREADS)) {
  600. case CODEC_CAP_FRAME_THREADS |
  601. CODEC_CAP_SLICE_THREADS: printf("frame and slice"); break;
  602. case CODEC_CAP_FRAME_THREADS: printf("frame"); break;
  603. case CODEC_CAP_SLICE_THREADS: printf("slice"); break;
  604. default: printf("no"); break;
  605. }
  606. printf("\n");
  607. }
  608. if (c->supported_framerates) {
  609. const AVRational *fps = c->supported_framerates;
  610. printf(" Supported framerates:");
  611. while (fps->num) {
  612. printf(" %d/%d", fps->num, fps->den);
  613. fps++;
  614. }
  615. printf("\n");
  616. }
  617. PRINT_CODEC_SUPPORTED(c, pix_fmts, enum PixelFormat, "pixel formats",
  618. PIX_FMT_NONE, GET_PIX_FMT_NAME);
  619. PRINT_CODEC_SUPPORTED(c, supported_samplerates, int, "sample rates", 0,
  620. GET_SAMPLE_RATE_NAME);
  621. PRINT_CODEC_SUPPORTED(c, sample_fmts, enum AVSampleFormat, "sample formats",
  622. AV_SAMPLE_FMT_NONE, GET_SAMPLE_FMT_NAME);
  623. PRINT_CODEC_SUPPORTED(c, channel_layouts, uint64_t, "channel layouts",
  624. 0, GET_CH_LAYOUT_DESC);
  625. if (c->priv_class) {
  626. show_help_children(c->priv_class,
  627. AV_OPT_FLAG_ENCODING_PARAM |
  628. AV_OPT_FLAG_DECODING_PARAM);
  629. }
  630. }
  631. static char get_media_type_char(enum AVMediaType type)
  632. {
  633. switch (type) {
  634. case AVMEDIA_TYPE_VIDEO: return 'V';
  635. case AVMEDIA_TYPE_AUDIO: return 'A';
  636. case AVMEDIA_TYPE_SUBTITLE: return 'S';
  637. default: return '?';
  638. }
  639. }
  640. static const AVCodec *next_codec_for_id(enum AVCodecID id, const AVCodec *prev,
  641. int encoder)
  642. {
  643. while ((prev = av_codec_next(prev))) {
  644. if (prev->id == id &&
  645. (encoder ? av_codec_is_encoder(prev) : av_codec_is_decoder(prev)))
  646. return prev;
  647. }
  648. return NULL;
  649. }
  650. static void print_codecs_for_id(enum AVCodecID id, int encoder)
  651. {
  652. const AVCodec *codec = NULL;
  653. printf(" (%s: ", encoder ? "encoders" : "decoders");
  654. while ((codec = next_codec_for_id(id, codec, encoder)))
  655. printf("%s ", codec->name);
  656. printf(")");
  657. }
  658. int show_codecs(const char *opt, const char *arg)
  659. {
  660. const AVCodecDescriptor *desc = NULL;
  661. printf("Codecs:\n"
  662. " D... = Decoding supported\n"
  663. " .E.. = Encoding supported\n"
  664. " ..V. = Video codec\n"
  665. " ..A. = Audio codec\n"
  666. " ..S. = Subtitle codec\n"
  667. " ...I = Intra frame-only codec\n"
  668. " -----\n");
  669. while ((desc = avcodec_descriptor_next(desc))) {
  670. const AVCodec *codec = NULL;
  671. printf(avcodec_find_decoder(desc->id) ? "D" : ".");
  672. printf(avcodec_find_encoder(desc->id) ? "E" : ".");
  673. printf("%c", get_media_type_char(desc->type));
  674. printf((desc->props & AV_CODEC_PROP_INTRA_ONLY) ? "I" : ".");
  675. printf(" %-20s %s", desc->name, desc->long_name ? desc->long_name : "");
  676. /* print decoders/encoders when there's more than one or their
  677. * names are different from codec name */
  678. while ((codec = next_codec_for_id(desc->id, codec, 0))) {
  679. if (strcmp(codec->name, desc->name)) {
  680. print_codecs_for_id(desc->id, 0);
  681. break;
  682. }
  683. }
  684. codec = NULL;
  685. while ((codec = next_codec_for_id(desc->id, codec, 1))) {
  686. if (strcmp(codec->name, desc->name)) {
  687. print_codecs_for_id(desc->id, 1);
  688. break;
  689. }
  690. }
  691. printf("\n");
  692. }
  693. return 0;
  694. }
  695. static void print_codecs(int encoder)
  696. {
  697. const AVCodecDescriptor *desc = NULL;
  698. printf("%s:\n"
  699. " V... = Video\n"
  700. " A... = Audio\n"
  701. " S... = Subtitle\n"
  702. " .F.. = Frame-level multithreading\n"
  703. " ..S. = Slice-level multithreading\n"
  704. " ...X = Codec is experimental\n"
  705. " ---\n",
  706. encoder ? "Encoders" : "Decoders");
  707. while ((desc = avcodec_descriptor_next(desc))) {
  708. const AVCodec *codec = NULL;
  709. while ((codec = next_codec_for_id(desc->id, codec, encoder))) {
  710. printf("%c", get_media_type_char(desc->type));
  711. printf((codec->capabilities & CODEC_CAP_FRAME_THREADS) ? "F" : ".");
  712. printf((codec->capabilities & CODEC_CAP_SLICE_THREADS) ? "S" : ".");
  713. printf((codec->capabilities & CODEC_CAP_EXPERIMENTAL) ? "X" : ".");
  714. printf(" %-20s %s", codec->name, codec->long_name ? codec->long_name : "");
  715. if (strcmp(codec->name, desc->name))
  716. printf(" (codec %s)", desc->name);
  717. printf("\n");
  718. }
  719. }
  720. }
  721. int show_decoders(const char *opt, const char *arg)
  722. {
  723. print_codecs(0);
  724. return 0;
  725. }
  726. int show_encoders(const char *opt, const char *arg)
  727. {
  728. print_codecs(1);
  729. return 0;
  730. }
  731. int show_bsfs(const char *opt, const char *arg)
  732. {
  733. AVBitStreamFilter *bsf = NULL;
  734. printf("Bitstream filters:\n");
  735. while ((bsf = av_bitstream_filter_next(bsf)))
  736. printf("%s\n", bsf->name);
  737. printf("\n");
  738. return 0;
  739. }
  740. int show_protocols(const char *opt, const char *arg)
  741. {
  742. void *opaque = NULL;
  743. const char *name;
  744. printf("Supported file protocols:\n"
  745. "Input:\n");
  746. while ((name = avio_enum_protocols(&opaque, 0)))
  747. printf("%s\n", name);
  748. printf("Output:\n");
  749. while ((name = avio_enum_protocols(&opaque, 1)))
  750. printf("%s\n", name);
  751. return 0;
  752. }
  753. int show_filters(const char *opt, const char *arg)
  754. {
  755. AVFilter av_unused(**filter) = NULL;
  756. printf("Filters:\n");
  757. #if CONFIG_AVFILTER
  758. while ((filter = av_filter_next(filter)) && *filter)
  759. printf("%-16s %s\n", (*filter)->name, (*filter)->description);
  760. #endif
  761. return 0;
  762. }
  763. int show_pix_fmts(const char *opt, const char *arg)
  764. {
  765. enum PixelFormat pix_fmt;
  766. printf("Pixel formats:\n"
  767. "I.... = Supported Input format for conversion\n"
  768. ".O... = Supported Output format for conversion\n"
  769. "..H.. = Hardware accelerated format\n"
  770. "...P. = Paletted format\n"
  771. "....B = Bitstream format\n"
  772. "FLAGS NAME NB_COMPONENTS BITS_PER_PIXEL\n"
  773. "-----\n");
  774. #if !CONFIG_SWSCALE
  775. # define sws_isSupportedInput(x) 0
  776. # define sws_isSupportedOutput(x) 0
  777. #endif
  778. for (pix_fmt = 0; pix_fmt < PIX_FMT_NB; pix_fmt++) {
  779. const AVPixFmtDescriptor *pix_desc = &av_pix_fmt_descriptors[pix_fmt];
  780. printf("%c%c%c%c%c %-16s %d %2d\n",
  781. sws_isSupportedInput (pix_fmt) ? 'I' : '.',
  782. sws_isSupportedOutput(pix_fmt) ? 'O' : '.',
  783. pix_desc->flags & PIX_FMT_HWACCEL ? 'H' : '.',
  784. pix_desc->flags & PIX_FMT_PAL ? 'P' : '.',
  785. pix_desc->flags & PIX_FMT_BITSTREAM ? 'B' : '.',
  786. pix_desc->name,
  787. pix_desc->nb_components,
  788. av_get_bits_per_pixel(pix_desc));
  789. }
  790. return 0;
  791. }
  792. int show_sample_fmts(const char *opt, const char *arg)
  793. {
  794. int i;
  795. char fmt_str[128];
  796. for (i = -1; i < AV_SAMPLE_FMT_NB; i++)
  797. printf("%s\n", av_get_sample_fmt_string(fmt_str, sizeof(fmt_str), i));
  798. return 0;
  799. }
  800. static void show_help_codec(const char *name, int encoder)
  801. {
  802. const AVCodecDescriptor *desc;
  803. const AVCodec *codec;
  804. if (!name) {
  805. av_log(NULL, AV_LOG_ERROR, "No codec name specified.\n");
  806. return;
  807. }
  808. codec = encoder ? avcodec_find_encoder_by_name(name) :
  809. avcodec_find_decoder_by_name(name);
  810. if (codec)
  811. print_codec(codec);
  812. else if ((desc = avcodec_descriptor_get_by_name(name))) {
  813. int printed = 0;
  814. while ((codec = next_codec_for_id(desc->id, codec, encoder))) {
  815. printed = 1;
  816. print_codec(codec);
  817. }
  818. if (!printed) {
  819. av_log(NULL, AV_LOG_ERROR, "Codec '%s' is known to Libav, "
  820. "but no %s for it are available. Libav might need to be "
  821. "recompiled with additional external libraries.\n",
  822. name, encoder ? "encoders" : "decoders");
  823. }
  824. } else {
  825. av_log(NULL, AV_LOG_ERROR, "Codec '%s' is not recognized by Libav.\n",
  826. name);
  827. }
  828. }
  829. static void show_help_demuxer(const char *name)
  830. {
  831. const AVInputFormat *fmt = av_find_input_format(name);
  832. if (!fmt) {
  833. av_log(NULL, AV_LOG_ERROR, "Unknown format '%s'.\n", name);
  834. return;
  835. }
  836. printf("Demuxer %s [%s]:\n", fmt->name, fmt->long_name);
  837. if (fmt->extensions)
  838. printf(" Common extensions: %s.\n", fmt->extensions);
  839. if (fmt->priv_class)
  840. show_help_children(fmt->priv_class, AV_OPT_FLAG_DECODING_PARAM);
  841. }
  842. static void show_help_muxer(const char *name)
  843. {
  844. const AVCodecDescriptor *desc;
  845. const AVOutputFormat *fmt = av_guess_format(name, NULL, NULL);
  846. if (!fmt) {
  847. av_log(NULL, AV_LOG_ERROR, "Unknown format '%s'.\n", name);
  848. return;
  849. }
  850. printf("Muxer %s [%s]:\n", fmt->name, fmt->long_name);
  851. if (fmt->extensions)
  852. printf(" Common extensions: %s.\n", fmt->extensions);
  853. if (fmt->mime_type)
  854. printf(" Mime type: %s.\n", fmt->mime_type);
  855. if (fmt->video_codec != AV_CODEC_ID_NONE &&
  856. (desc = avcodec_descriptor_get(fmt->video_codec))) {
  857. printf(" Default video codec: %s.\n", desc->name);
  858. }
  859. if (fmt->audio_codec != AV_CODEC_ID_NONE &&
  860. (desc = avcodec_descriptor_get(fmt->audio_codec))) {
  861. printf(" Default audio codec: %s.\n", desc->name);
  862. }
  863. if (fmt->subtitle_codec != AV_CODEC_ID_NONE &&
  864. (desc = avcodec_descriptor_get(fmt->subtitle_codec))) {
  865. printf(" Default subtitle codec: %s.\n", desc->name);
  866. }
  867. if (fmt->priv_class)
  868. show_help_children(fmt->priv_class, AV_OPT_FLAG_ENCODING_PARAM);
  869. }
  870. int show_help(const char *opt, const char *arg)
  871. {
  872. char *topic, *par;
  873. av_log_set_callback(log_callback_help);
  874. topic = av_strdup(arg ? arg : "");
  875. par = strchr(topic, '=');
  876. if (par)
  877. *par++ = 0;
  878. if (!*topic) {
  879. show_help_default(topic, par);
  880. } else if (!strcmp(topic, "decoder")) {
  881. show_help_codec(par, 0);
  882. } else if (!strcmp(topic, "encoder")) {
  883. show_help_codec(par, 1);
  884. } else if (!strcmp(topic, "demuxer")) {
  885. show_help_demuxer(par);
  886. } else if (!strcmp(topic, "muxer")) {
  887. show_help_muxer(par);
  888. } else {
  889. show_help_default(topic, par);
  890. }
  891. av_freep(&topic);
  892. return 0;
  893. }
  894. int read_yesno(void)
  895. {
  896. int c = getchar();
  897. int yesno = (toupper(c) == 'Y');
  898. while (c != '\n' && c != EOF)
  899. c = getchar();
  900. return yesno;
  901. }
  902. int cmdutils_read_file(const char *filename, char **bufptr, size_t *size)
  903. {
  904. int ret;
  905. FILE *f = fopen(filename, "rb");
  906. if (!f) {
  907. av_log(NULL, AV_LOG_ERROR, "Cannot read file '%s': %s\n", filename,
  908. strerror(errno));
  909. return AVERROR(errno);
  910. }
  911. fseek(f, 0, SEEK_END);
  912. *size = ftell(f);
  913. fseek(f, 0, SEEK_SET);
  914. *bufptr = av_malloc(*size + 1);
  915. if (!*bufptr) {
  916. av_log(NULL, AV_LOG_ERROR, "Could not allocate file buffer\n");
  917. fclose(f);
  918. return AVERROR(ENOMEM);
  919. }
  920. ret = fread(*bufptr, 1, *size, f);
  921. if (ret < *size) {
  922. av_free(*bufptr);
  923. if (ferror(f)) {
  924. av_log(NULL, AV_LOG_ERROR, "Error while reading file '%s': %s\n",
  925. filename, strerror(errno));
  926. ret = AVERROR(errno);
  927. } else
  928. ret = AVERROR_EOF;
  929. } else {
  930. ret = 0;
  931. (*bufptr)[*size++] = '\0';
  932. }
  933. fclose(f);
  934. return ret;
  935. }
  936. void init_pts_correction(PtsCorrectionContext *ctx)
  937. {
  938. ctx->num_faulty_pts = ctx->num_faulty_dts = 0;
  939. ctx->last_pts = ctx->last_dts = INT64_MIN;
  940. }
  941. int64_t guess_correct_pts(PtsCorrectionContext *ctx, int64_t reordered_pts,
  942. int64_t dts)
  943. {
  944. int64_t pts = AV_NOPTS_VALUE;
  945. if (dts != AV_NOPTS_VALUE) {
  946. ctx->num_faulty_dts += dts <= ctx->last_dts;
  947. ctx->last_dts = dts;
  948. }
  949. if (reordered_pts != AV_NOPTS_VALUE) {
  950. ctx->num_faulty_pts += reordered_pts <= ctx->last_pts;
  951. ctx->last_pts = reordered_pts;
  952. }
  953. if ((ctx->num_faulty_pts<=ctx->num_faulty_dts || dts == AV_NOPTS_VALUE)
  954. && reordered_pts != AV_NOPTS_VALUE)
  955. pts = reordered_pts;
  956. else
  957. pts = dts;
  958. return pts;
  959. }
  960. FILE *get_preset_file(char *filename, size_t filename_size,
  961. const char *preset_name, int is_path,
  962. const char *codec_name)
  963. {
  964. FILE *f = NULL;
  965. int i;
  966. const char *base[3] = { getenv("AVCONV_DATADIR"),
  967. getenv("HOME"),
  968. AVCONV_DATADIR, };
  969. if (is_path) {
  970. av_strlcpy(filename, preset_name, filename_size);
  971. f = fopen(filename, "r");
  972. } else {
  973. for (i = 0; i < 3 && !f; i++) {
  974. if (!base[i])
  975. continue;
  976. snprintf(filename, filename_size, "%s%s/%s.avpreset", base[i],
  977. i != 1 ? "" : "/.avconv", preset_name);
  978. f = fopen(filename, "r");
  979. if (!f && codec_name) {
  980. snprintf(filename, filename_size,
  981. "%s%s/%s-%s.avpreset",
  982. base[i], i != 1 ? "" : "/.avconv", codec_name,
  983. preset_name);
  984. f = fopen(filename, "r");
  985. }
  986. }
  987. }
  988. return f;
  989. }
  990. int check_stream_specifier(AVFormatContext *s, AVStream *st, const char *spec)
  991. {
  992. if (*spec <= '9' && *spec >= '0') /* opt:index */
  993. return strtol(spec, NULL, 0) == st->index;
  994. else if (*spec == 'v' || *spec == 'a' || *spec == 's' || *spec == 'd' ||
  995. *spec == 't') { /* opt:[vasdt] */
  996. enum AVMediaType type;
  997. switch (*spec++) {
  998. case 'v': type = AVMEDIA_TYPE_VIDEO; break;
  999. case 'a': type = AVMEDIA_TYPE_AUDIO; break;
  1000. case 's': type = AVMEDIA_TYPE_SUBTITLE; break;
  1001. case 'd': type = AVMEDIA_TYPE_DATA; break;
  1002. case 't': type = AVMEDIA_TYPE_ATTACHMENT; break;
  1003. default: av_assert0(0);
  1004. }
  1005. if (type != st->codec->codec_type)
  1006. return 0;
  1007. if (*spec++ == ':') { /* possibly followed by :index */
  1008. int i, index = strtol(spec, NULL, 0);
  1009. for (i = 0; i < s->nb_streams; i++)
  1010. if (s->streams[i]->codec->codec_type == type && index-- == 0)
  1011. return i == st->index;
  1012. return 0;
  1013. }
  1014. return 1;
  1015. } else if (*spec == 'p' && *(spec + 1) == ':') {
  1016. int prog_id, i, j;
  1017. char *endptr;
  1018. spec += 2;
  1019. prog_id = strtol(spec, &endptr, 0);
  1020. for (i = 0; i < s->nb_programs; i++) {
  1021. if (s->programs[i]->id != prog_id)
  1022. continue;
  1023. if (*endptr++ == ':') {
  1024. int stream_idx = strtol(endptr, NULL, 0);
  1025. return stream_idx >= 0 &&
  1026. stream_idx < s->programs[i]->nb_stream_indexes &&
  1027. st->index == s->programs[i]->stream_index[stream_idx];
  1028. }
  1029. for (j = 0; j < s->programs[i]->nb_stream_indexes; j++)
  1030. if (st->index == s->programs[i]->stream_index[j])
  1031. return 1;
  1032. }
  1033. return 0;
  1034. } else if (!*spec) /* empty specifier, matches everything */
  1035. return 1;
  1036. av_log(s, AV_LOG_ERROR, "Invalid stream specifier: %s.\n", spec);
  1037. return AVERROR(EINVAL);
  1038. }
  1039. AVDictionary *filter_codec_opts(AVDictionary *opts, enum AVCodecID codec_id,
  1040. AVFormatContext *s, AVStream *st, AVCodec *codec)
  1041. {
  1042. AVDictionary *ret = NULL;
  1043. AVDictionaryEntry *t = NULL;
  1044. int flags = s->oformat ? AV_OPT_FLAG_ENCODING_PARAM
  1045. : AV_OPT_FLAG_DECODING_PARAM;
  1046. char prefix = 0;
  1047. const AVClass *cc = avcodec_get_class();
  1048. if (!codec)
  1049. codec = s->oformat ? avcodec_find_encoder(codec_id)
  1050. : avcodec_find_decoder(codec_id);
  1051. if (!codec)
  1052. return NULL;
  1053. switch (codec->type) {
  1054. case AVMEDIA_TYPE_VIDEO:
  1055. prefix = 'v';
  1056. flags |= AV_OPT_FLAG_VIDEO_PARAM;
  1057. break;
  1058. case AVMEDIA_TYPE_AUDIO:
  1059. prefix = 'a';
  1060. flags |= AV_OPT_FLAG_AUDIO_PARAM;
  1061. break;
  1062. case AVMEDIA_TYPE_SUBTITLE:
  1063. prefix = 's';
  1064. flags |= AV_OPT_FLAG_SUBTITLE_PARAM;
  1065. break;
  1066. }
  1067. while (t = av_dict_get(opts, "", t, AV_DICT_IGNORE_SUFFIX)) {
  1068. char *p = strchr(t->key, ':');
  1069. /* check stream specification in opt name */
  1070. if (p)
  1071. switch (check_stream_specifier(s, st, p + 1)) {
  1072. case 1: *p = 0; break;
  1073. case 0: continue;
  1074. default: return NULL;
  1075. }
  1076. if (av_opt_find(&cc, t->key, NULL, flags, AV_OPT_SEARCH_FAKE_OBJ) ||
  1077. (codec && codec->priv_class &&
  1078. av_opt_find(&codec->priv_class, t->key, NULL, flags,
  1079. AV_OPT_SEARCH_FAKE_OBJ)))
  1080. av_dict_set(&ret, t->key, t->value, 0);
  1081. else if (t->key[0] == prefix &&
  1082. av_opt_find(&cc, t->key + 1, NULL, flags,
  1083. AV_OPT_SEARCH_FAKE_OBJ))
  1084. av_dict_set(&ret, t->key + 1, t->value, 0);
  1085. if (p)
  1086. *p = ':';
  1087. }
  1088. return ret;
  1089. }
  1090. AVDictionary **setup_find_stream_info_opts(AVFormatContext *s,
  1091. AVDictionary *codec_opts)
  1092. {
  1093. int i;
  1094. AVDictionary **opts;
  1095. if (!s->nb_streams)
  1096. return NULL;
  1097. opts = av_mallocz(s->nb_streams * sizeof(*opts));
  1098. if (!opts) {
  1099. av_log(NULL, AV_LOG_ERROR,
  1100. "Could not alloc memory for stream options.\n");
  1101. return NULL;
  1102. }
  1103. for (i = 0; i < s->nb_streams; i++)
  1104. opts[i] = filter_codec_opts(codec_opts, s->streams[i]->codec->codec_id,
  1105. s, s->streams[i], NULL);
  1106. return opts;
  1107. }
  1108. void *grow_array(void *array, int elem_size, int *size, int new_size)
  1109. {
  1110. if (new_size >= INT_MAX / elem_size) {
  1111. av_log(NULL, AV_LOG_ERROR, "Array too big.\n");
  1112. exit_program(1);
  1113. }
  1114. if (*size < new_size) {
  1115. uint8_t *tmp = av_realloc(array, new_size*elem_size);
  1116. if (!tmp) {
  1117. av_log(NULL, AV_LOG_ERROR, "Could not alloc buffer.\n");
  1118. exit_program(1);
  1119. }
  1120. memset(tmp + *size*elem_size, 0, (new_size-*size) * elem_size);
  1121. *size = new_size;
  1122. return tmp;
  1123. }
  1124. return array;
  1125. }
  1126. static int alloc_buffer(FrameBuffer **pool, AVCodecContext *s, FrameBuffer **pbuf)
  1127. {
  1128. FrameBuffer *buf = av_mallocz(sizeof(*buf));
  1129. int i, ret;
  1130. const int pixel_size = av_pix_fmt_descriptors[s->pix_fmt].comp[0].step_minus1+1;
  1131. int h_chroma_shift, v_chroma_shift;
  1132. int edge = 32; // XXX should be avcodec_get_edge_width(), but that fails on svq1
  1133. int w = s->width, h = s->height;
  1134. if (!buf)
  1135. return AVERROR(ENOMEM);
  1136. if (!(s->flags & CODEC_FLAG_EMU_EDGE)) {
  1137. w += 2*edge;
  1138. h += 2*edge;
  1139. }
  1140. avcodec_align_dimensions(s, &w, &h);
  1141. if ((ret = av_image_alloc(buf->base, buf->linesize, w, h,
  1142. s->pix_fmt, 32)) < 0) {
  1143. av_freep(&buf);
  1144. return ret;
  1145. }
  1146. /* XXX this shouldn't be needed, but some tests break without this line
  1147. * those decoders are buggy and need to be fixed.
  1148. * the following tests fail:
  1149. * cdgraphics, ansi, aasc, fraps-v1, qtrle-1bit
  1150. */
  1151. memset(buf->base[0], 128, ret);
  1152. avcodec_get_chroma_sub_sample(s->pix_fmt, &h_chroma_shift, &v_chroma_shift);
  1153. for (i = 0; i < FF_ARRAY_ELEMS(buf->data); i++) {
  1154. const int h_shift = i==0 ? 0 : h_chroma_shift;
  1155. const int v_shift = i==0 ? 0 : v_chroma_shift;
  1156. if (s->flags & CODEC_FLAG_EMU_EDGE)
  1157. buf->data[i] = buf->base[i];
  1158. else
  1159. buf->data[i] = buf->base[i] +
  1160. FFALIGN((buf->linesize[i]*edge >> v_shift) +
  1161. (pixel_size*edge >> h_shift), 32);
  1162. }
  1163. buf->w = s->width;
  1164. buf->h = s->height;
  1165. buf->pix_fmt = s->pix_fmt;
  1166. buf->pool = pool;
  1167. *pbuf = buf;
  1168. return 0;
  1169. }
  1170. int codec_get_buffer(AVCodecContext *s, AVFrame *frame)
  1171. {
  1172. FrameBuffer **pool = s->opaque;
  1173. FrameBuffer *buf;
  1174. int ret, i;
  1175. if (!*pool && (ret = alloc_buffer(pool, s, pool)) < 0)
  1176. return ret;
  1177. buf = *pool;
  1178. *pool = buf->next;
  1179. buf->next = NULL;
  1180. if (buf->w != s->width || buf->h != s->height || buf->pix_fmt != s->pix_fmt) {
  1181. av_freep(&buf->base[0]);
  1182. av_free(buf);
  1183. if ((ret = alloc_buffer(pool, s, &buf)) < 0)
  1184. return ret;
  1185. }
  1186. buf->refcount++;
  1187. frame->opaque = buf;
  1188. frame->type = FF_BUFFER_TYPE_USER;
  1189. frame->extended_data = frame->data;
  1190. frame->pkt_pts = s->pkt ? s->pkt->pts : AV_NOPTS_VALUE;
  1191. frame->width = buf->w;
  1192. frame->height = buf->h;
  1193. frame->format = buf->pix_fmt;
  1194. frame->sample_aspect_ratio = s->sample_aspect_ratio;
  1195. for (i = 0; i < FF_ARRAY_ELEMS(buf->data); i++) {
  1196. frame->base[i] = buf->base[i]; // XXX h264.c uses base though it shouldn't
  1197. frame->data[i] = buf->data[i];
  1198. frame->linesize[i] = buf->linesize[i];
  1199. }
  1200. return 0;
  1201. }
  1202. static void unref_buffer(FrameBuffer *buf)
  1203. {
  1204. FrameBuffer **pool = buf->pool;
  1205. av_assert0(buf->refcount);
  1206. buf->refcount--;
  1207. if (!buf->refcount) {
  1208. buf->next = *pool;
  1209. *pool = buf;
  1210. }
  1211. }
  1212. void codec_release_buffer(AVCodecContext *s, AVFrame *frame)
  1213. {
  1214. FrameBuffer *buf = frame->opaque;
  1215. int i;
  1216. for (i = 0; i < FF_ARRAY_ELEMS(frame->data); i++)
  1217. frame->data[i] = NULL;
  1218. unref_buffer(buf);
  1219. }
  1220. void filter_release_buffer(AVFilterBuffer *fb)
  1221. {
  1222. FrameBuffer *buf = fb->priv;
  1223. av_free(fb);
  1224. unref_buffer(buf);
  1225. }
  1226. void free_buffer_pool(FrameBuffer **pool)
  1227. {
  1228. FrameBuffer *buf = *pool;
  1229. while (buf) {
  1230. *pool = buf->next;
  1231. av_freep(&buf->base[0]);
  1232. av_free(buf);
  1233. buf = *pool;
  1234. }
  1235. }