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.

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