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.

1418 lines
46KB

  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 defined(_WIN32) && !defined(__MINGW32CE__)
  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 /* WIN32 && !__MINGW32CE__ */
  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(), *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(void *optctx, 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(1);
  383. }
  384. av_log_set_level(level);
  385. return 0;
  386. }
  387. int opt_timelimit(void *optctx, 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(void *optctx, 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(void *optctx, 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(void *optctx, 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 AVPixelFormat, "pixel formats",
  618. AV_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(void *optctx, 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. " ....L. = Lossy compression\n"
  669. " .....S = Lossless compression\n"
  670. " -------\n");
  671. while ((desc = avcodec_descriptor_next(desc))) {
  672. const AVCodec *codec = NULL;
  673. printf(avcodec_find_decoder(desc->id) ? "D" : ".");
  674. printf(avcodec_find_encoder(desc->id) ? "E" : ".");
  675. printf("%c", get_media_type_char(desc->type));
  676. printf((desc->props & AV_CODEC_PROP_INTRA_ONLY) ? "I" : ".");
  677. printf((desc->props & AV_CODEC_PROP_LOSSY) ? "L" : ".");
  678. printf((desc->props & AV_CODEC_PROP_LOSSLESS) ? "S" : ".");
  679. printf(" %-20s %s", desc->name, desc->long_name ? desc->long_name : "");
  680. /* print decoders/encoders when there's more than one or their
  681. * names are different from codec name */
  682. while ((codec = next_codec_for_id(desc->id, codec, 0))) {
  683. if (strcmp(codec->name, desc->name)) {
  684. print_codecs_for_id(desc->id, 0);
  685. break;
  686. }
  687. }
  688. codec = NULL;
  689. while ((codec = next_codec_for_id(desc->id, codec, 1))) {
  690. if (strcmp(codec->name, desc->name)) {
  691. print_codecs_for_id(desc->id, 1);
  692. break;
  693. }
  694. }
  695. printf("\n");
  696. }
  697. return 0;
  698. }
  699. static void print_codecs(int encoder)
  700. {
  701. const AVCodecDescriptor *desc = NULL;
  702. printf("%s:\n"
  703. " V... = Video\n"
  704. " A... = Audio\n"
  705. " S... = Subtitle\n"
  706. " .F.. = Frame-level multithreading\n"
  707. " ..S. = Slice-level multithreading\n"
  708. " ...X = Codec is experimental\n"
  709. " ---\n",
  710. encoder ? "Encoders" : "Decoders");
  711. while ((desc = avcodec_descriptor_next(desc))) {
  712. const AVCodec *codec = NULL;
  713. while ((codec = next_codec_for_id(desc->id, codec, encoder))) {
  714. printf("%c", get_media_type_char(desc->type));
  715. printf((codec->capabilities & CODEC_CAP_FRAME_THREADS) ? "F" : ".");
  716. printf((codec->capabilities & CODEC_CAP_SLICE_THREADS) ? "S" : ".");
  717. printf((codec->capabilities & CODEC_CAP_EXPERIMENTAL) ? "X" : ".");
  718. printf(" %-20s %s", codec->name, codec->long_name ? codec->long_name : "");
  719. if (strcmp(codec->name, desc->name))
  720. printf(" (codec %s)", desc->name);
  721. printf("\n");
  722. }
  723. }
  724. }
  725. int show_decoders(void *optctx, const char *opt, const char *arg)
  726. {
  727. print_codecs(0);
  728. return 0;
  729. }
  730. int show_encoders(void *optctx, const char *opt, const char *arg)
  731. {
  732. print_codecs(1);
  733. return 0;
  734. }
  735. int show_bsfs(void *optctx, const char *opt, const char *arg)
  736. {
  737. AVBitStreamFilter *bsf = NULL;
  738. printf("Bitstream filters:\n");
  739. while ((bsf = av_bitstream_filter_next(bsf)))
  740. printf("%s\n", bsf->name);
  741. printf("\n");
  742. return 0;
  743. }
  744. int show_protocols(void *optctx, const char *opt, const char *arg)
  745. {
  746. void *opaque = NULL;
  747. const char *name;
  748. printf("Supported file protocols:\n"
  749. "Input:\n");
  750. while ((name = avio_enum_protocols(&opaque, 0)))
  751. printf("%s\n", name);
  752. printf("Output:\n");
  753. while ((name = avio_enum_protocols(&opaque, 1)))
  754. printf("%s\n", name);
  755. return 0;
  756. }
  757. int show_filters(void *optctx, const char *opt, const char *arg)
  758. {
  759. AVFilter av_unused(**filter) = NULL;
  760. printf("Filters:\n");
  761. #if CONFIG_AVFILTER
  762. while ((filter = av_filter_next(filter)) && *filter)
  763. printf("%-16s %s\n", (*filter)->name, (*filter)->description);
  764. #endif
  765. return 0;
  766. }
  767. int show_pix_fmts(void *optctx, const char *opt, const char *arg)
  768. {
  769. const AVPixFmtDescriptor *pix_desc = NULL;
  770. printf("Pixel formats:\n"
  771. "I.... = Supported Input format for conversion\n"
  772. ".O... = Supported Output format for conversion\n"
  773. "..H.. = Hardware accelerated format\n"
  774. "...P. = Paletted format\n"
  775. "....B = Bitstream format\n"
  776. "FLAGS NAME NB_COMPONENTS BITS_PER_PIXEL\n"
  777. "-----\n");
  778. #if !CONFIG_SWSCALE
  779. # define sws_isSupportedInput(x) 0
  780. # define sws_isSupportedOutput(x) 0
  781. #endif
  782. while ((pix_desc = av_pix_fmt_desc_next(pix_desc))) {
  783. enum AVPixelFormat pix_fmt = av_pix_fmt_desc_get_id(pix_desc);
  784. printf("%c%c%c%c%c %-16s %d %2d\n",
  785. sws_isSupportedInput (pix_fmt) ? 'I' : '.',
  786. sws_isSupportedOutput(pix_fmt) ? 'O' : '.',
  787. pix_desc->flags & PIX_FMT_HWACCEL ? 'H' : '.',
  788. pix_desc->flags & PIX_FMT_PAL ? 'P' : '.',
  789. pix_desc->flags & PIX_FMT_BITSTREAM ? 'B' : '.',
  790. pix_desc->name,
  791. pix_desc->nb_components,
  792. av_get_bits_per_pixel(pix_desc));
  793. }
  794. return 0;
  795. }
  796. int show_sample_fmts(void *optctx, const char *opt, const char *arg)
  797. {
  798. int i;
  799. char fmt_str[128];
  800. for (i = -1; i < AV_SAMPLE_FMT_NB; i++)
  801. printf("%s\n", av_get_sample_fmt_string(fmt_str, sizeof(fmt_str), i));
  802. return 0;
  803. }
  804. static void show_help_codec(const char *name, int encoder)
  805. {
  806. const AVCodecDescriptor *desc;
  807. const AVCodec *codec;
  808. if (!name) {
  809. av_log(NULL, AV_LOG_ERROR, "No codec name specified.\n");
  810. return;
  811. }
  812. codec = encoder ? avcodec_find_encoder_by_name(name) :
  813. avcodec_find_decoder_by_name(name);
  814. if (codec)
  815. print_codec(codec);
  816. else if ((desc = avcodec_descriptor_get_by_name(name))) {
  817. int printed = 0;
  818. while ((codec = next_codec_for_id(desc->id, codec, encoder))) {
  819. printed = 1;
  820. print_codec(codec);
  821. }
  822. if (!printed) {
  823. av_log(NULL, AV_LOG_ERROR, "Codec '%s' is known to Libav, "
  824. "but no %s for it are available. Libav might need to be "
  825. "recompiled with additional external libraries.\n",
  826. name, encoder ? "encoders" : "decoders");
  827. }
  828. } else {
  829. av_log(NULL, AV_LOG_ERROR, "Codec '%s' is not recognized by Libav.\n",
  830. name);
  831. }
  832. }
  833. static void show_help_demuxer(const char *name)
  834. {
  835. const AVInputFormat *fmt = av_find_input_format(name);
  836. if (!fmt) {
  837. av_log(NULL, AV_LOG_ERROR, "Unknown format '%s'.\n", name);
  838. return;
  839. }
  840. printf("Demuxer %s [%s]:\n", fmt->name, fmt->long_name);
  841. if (fmt->extensions)
  842. printf(" Common extensions: %s.\n", fmt->extensions);
  843. if (fmt->priv_class)
  844. show_help_children(fmt->priv_class, AV_OPT_FLAG_DECODING_PARAM);
  845. }
  846. static void show_help_muxer(const char *name)
  847. {
  848. const AVCodecDescriptor *desc;
  849. const AVOutputFormat *fmt = av_guess_format(name, NULL, NULL);
  850. if (!fmt) {
  851. av_log(NULL, AV_LOG_ERROR, "Unknown format '%s'.\n", name);
  852. return;
  853. }
  854. printf("Muxer %s [%s]:\n", fmt->name, fmt->long_name);
  855. if (fmt->extensions)
  856. printf(" Common extensions: %s.\n", fmt->extensions);
  857. if (fmt->mime_type)
  858. printf(" Mime type: %s.\n", fmt->mime_type);
  859. if (fmt->video_codec != AV_CODEC_ID_NONE &&
  860. (desc = avcodec_descriptor_get(fmt->video_codec))) {
  861. printf(" Default video codec: %s.\n", desc->name);
  862. }
  863. if (fmt->audio_codec != AV_CODEC_ID_NONE &&
  864. (desc = avcodec_descriptor_get(fmt->audio_codec))) {
  865. printf(" Default audio codec: %s.\n", desc->name);
  866. }
  867. if (fmt->subtitle_codec != AV_CODEC_ID_NONE &&
  868. (desc = avcodec_descriptor_get(fmt->subtitle_codec))) {
  869. printf(" Default subtitle codec: %s.\n", desc->name);
  870. }
  871. if (fmt->priv_class)
  872. show_help_children(fmt->priv_class, AV_OPT_FLAG_ENCODING_PARAM);
  873. }
  874. int show_help(void *optctx, const char *opt, const char *arg)
  875. {
  876. char *topic, *par;
  877. av_log_set_callback(log_callback_help);
  878. topic = av_strdup(arg ? arg : "");
  879. par = strchr(topic, '=');
  880. if (par)
  881. *par++ = 0;
  882. if (!*topic) {
  883. show_help_default(topic, par);
  884. } else if (!strcmp(topic, "decoder")) {
  885. show_help_codec(par, 0);
  886. } else if (!strcmp(topic, "encoder")) {
  887. show_help_codec(par, 1);
  888. } else if (!strcmp(topic, "demuxer")) {
  889. show_help_demuxer(par);
  890. } else if (!strcmp(topic, "muxer")) {
  891. show_help_muxer(par);
  892. } else {
  893. show_help_default(topic, par);
  894. }
  895. av_freep(&topic);
  896. return 0;
  897. }
  898. int read_yesno(void)
  899. {
  900. int c = getchar();
  901. int yesno = (toupper(c) == 'Y');
  902. while (c != '\n' && c != EOF)
  903. c = getchar();
  904. return yesno;
  905. }
  906. int cmdutils_read_file(const char *filename, char **bufptr, size_t *size)
  907. {
  908. int ret;
  909. FILE *f = fopen(filename, "rb");
  910. if (!f) {
  911. av_log(NULL, AV_LOG_ERROR, "Cannot read file '%s': %s\n", filename,
  912. strerror(errno));
  913. return AVERROR(errno);
  914. }
  915. fseek(f, 0, SEEK_END);
  916. *size = ftell(f);
  917. fseek(f, 0, SEEK_SET);
  918. *bufptr = av_malloc(*size + 1);
  919. if (!*bufptr) {
  920. av_log(NULL, AV_LOG_ERROR, "Could not allocate file buffer\n");
  921. fclose(f);
  922. return AVERROR(ENOMEM);
  923. }
  924. ret = fread(*bufptr, 1, *size, f);
  925. if (ret < *size) {
  926. av_free(*bufptr);
  927. if (ferror(f)) {
  928. av_log(NULL, AV_LOG_ERROR, "Error while reading file '%s': %s\n",
  929. filename, strerror(errno));
  930. ret = AVERROR(errno);
  931. } else
  932. ret = AVERROR_EOF;
  933. } else {
  934. ret = 0;
  935. (*bufptr)[(*size)++] = '\0';
  936. }
  937. fclose(f);
  938. return ret;
  939. }
  940. void init_pts_correction(PtsCorrectionContext *ctx)
  941. {
  942. ctx->num_faulty_pts = ctx->num_faulty_dts = 0;
  943. ctx->last_pts = ctx->last_dts = INT64_MIN;
  944. }
  945. int64_t guess_correct_pts(PtsCorrectionContext *ctx, int64_t reordered_pts,
  946. int64_t dts)
  947. {
  948. int64_t pts = AV_NOPTS_VALUE;
  949. if (dts != AV_NOPTS_VALUE) {
  950. ctx->num_faulty_dts += dts <= ctx->last_dts;
  951. ctx->last_dts = dts;
  952. }
  953. if (reordered_pts != AV_NOPTS_VALUE) {
  954. ctx->num_faulty_pts += reordered_pts <= ctx->last_pts;
  955. ctx->last_pts = reordered_pts;
  956. }
  957. if ((ctx->num_faulty_pts<=ctx->num_faulty_dts || dts == AV_NOPTS_VALUE)
  958. && reordered_pts != AV_NOPTS_VALUE)
  959. pts = reordered_pts;
  960. else
  961. pts = dts;
  962. return pts;
  963. }
  964. FILE *get_preset_file(char *filename, size_t filename_size,
  965. const char *preset_name, int is_path,
  966. const char *codec_name)
  967. {
  968. FILE *f = NULL;
  969. int i;
  970. const char *base[3] = { getenv("AVCONV_DATADIR"),
  971. getenv("HOME"),
  972. AVCONV_DATADIR, };
  973. if (is_path) {
  974. av_strlcpy(filename, preset_name, filename_size);
  975. f = fopen(filename, "r");
  976. } else {
  977. for (i = 0; i < 3 && !f; i++) {
  978. if (!base[i])
  979. continue;
  980. snprintf(filename, filename_size, "%s%s/%s.avpreset", base[i],
  981. i != 1 ? "" : "/.avconv", preset_name);
  982. f = fopen(filename, "r");
  983. if (!f && codec_name) {
  984. snprintf(filename, filename_size,
  985. "%s%s/%s-%s.avpreset",
  986. base[i], i != 1 ? "" : "/.avconv", codec_name,
  987. preset_name);
  988. f = fopen(filename, "r");
  989. }
  990. }
  991. }
  992. return f;
  993. }
  994. int check_stream_specifier(AVFormatContext *s, AVStream *st, const char *spec)
  995. {
  996. if (*spec <= '9' && *spec >= '0') /* opt:index */
  997. return strtol(spec, NULL, 0) == st->index;
  998. else if (*spec == 'v' || *spec == 'a' || *spec == 's' || *spec == 'd' ||
  999. *spec == 't') { /* opt:[vasdt] */
  1000. enum AVMediaType type;
  1001. switch (*spec++) {
  1002. case 'v': type = AVMEDIA_TYPE_VIDEO; break;
  1003. case 'a': type = AVMEDIA_TYPE_AUDIO; break;
  1004. case 's': type = AVMEDIA_TYPE_SUBTITLE; break;
  1005. case 'd': type = AVMEDIA_TYPE_DATA; break;
  1006. case 't': type = AVMEDIA_TYPE_ATTACHMENT; break;
  1007. default: av_assert0(0);
  1008. }
  1009. if (type != st->codec->codec_type)
  1010. return 0;
  1011. if (*spec++ == ':') { /* possibly followed by :index */
  1012. int i, index = strtol(spec, NULL, 0);
  1013. for (i = 0; i < s->nb_streams; i++)
  1014. if (s->streams[i]->codec->codec_type == type && index-- == 0)
  1015. return i == st->index;
  1016. return 0;
  1017. }
  1018. return 1;
  1019. } else if (*spec == 'p' && *(spec + 1) == ':') {
  1020. int prog_id, i, j;
  1021. char *endptr;
  1022. spec += 2;
  1023. prog_id = strtol(spec, &endptr, 0);
  1024. for (i = 0; i < s->nb_programs; i++) {
  1025. if (s->programs[i]->id != prog_id)
  1026. continue;
  1027. if (*endptr++ == ':') {
  1028. int stream_idx = strtol(endptr, NULL, 0);
  1029. return stream_idx >= 0 &&
  1030. stream_idx < s->programs[i]->nb_stream_indexes &&
  1031. st->index == s->programs[i]->stream_index[stream_idx];
  1032. }
  1033. for (j = 0; j < s->programs[i]->nb_stream_indexes; j++)
  1034. if (st->index == s->programs[i]->stream_index[j])
  1035. return 1;
  1036. }
  1037. return 0;
  1038. } else if (!*spec) /* empty specifier, matches everything */
  1039. return 1;
  1040. av_log(s, AV_LOG_ERROR, "Invalid stream specifier: %s.\n", spec);
  1041. return AVERROR(EINVAL);
  1042. }
  1043. AVDictionary *filter_codec_opts(AVDictionary *opts, enum AVCodecID codec_id,
  1044. AVFormatContext *s, AVStream *st, AVCodec *codec)
  1045. {
  1046. AVDictionary *ret = NULL;
  1047. AVDictionaryEntry *t = NULL;
  1048. int flags = s->oformat ? AV_OPT_FLAG_ENCODING_PARAM
  1049. : AV_OPT_FLAG_DECODING_PARAM;
  1050. char prefix = 0;
  1051. const AVClass *cc = avcodec_get_class();
  1052. if (!codec)
  1053. codec = s->oformat ? avcodec_find_encoder(codec_id)
  1054. : avcodec_find_decoder(codec_id);
  1055. if (!codec)
  1056. return NULL;
  1057. switch (codec->type) {
  1058. case AVMEDIA_TYPE_VIDEO:
  1059. prefix = 'v';
  1060. flags |= AV_OPT_FLAG_VIDEO_PARAM;
  1061. break;
  1062. case AVMEDIA_TYPE_AUDIO:
  1063. prefix = 'a';
  1064. flags |= AV_OPT_FLAG_AUDIO_PARAM;
  1065. break;
  1066. case AVMEDIA_TYPE_SUBTITLE:
  1067. prefix = 's';
  1068. flags |= AV_OPT_FLAG_SUBTITLE_PARAM;
  1069. break;
  1070. }
  1071. while (t = av_dict_get(opts, "", t, AV_DICT_IGNORE_SUFFIX)) {
  1072. char *p = strchr(t->key, ':');
  1073. /* check stream specification in opt name */
  1074. if (p)
  1075. switch (check_stream_specifier(s, st, p + 1)) {
  1076. case 1: *p = 0; break;
  1077. case 0: continue;
  1078. default: return NULL;
  1079. }
  1080. if (av_opt_find(&cc, t->key, NULL, flags, AV_OPT_SEARCH_FAKE_OBJ) ||
  1081. (codec && codec->priv_class &&
  1082. av_opt_find(&codec->priv_class, t->key, NULL, flags,
  1083. AV_OPT_SEARCH_FAKE_OBJ)))
  1084. av_dict_set(&ret, t->key, t->value, 0);
  1085. else if (t->key[0] == prefix &&
  1086. av_opt_find(&cc, t->key + 1, NULL, flags,
  1087. AV_OPT_SEARCH_FAKE_OBJ))
  1088. av_dict_set(&ret, t->key + 1, t->value, 0);
  1089. if (p)
  1090. *p = ':';
  1091. }
  1092. return ret;
  1093. }
  1094. AVDictionary **setup_find_stream_info_opts(AVFormatContext *s,
  1095. AVDictionary *codec_opts)
  1096. {
  1097. int i;
  1098. AVDictionary **opts;
  1099. if (!s->nb_streams)
  1100. return NULL;
  1101. opts = av_mallocz(s->nb_streams * sizeof(*opts));
  1102. if (!opts) {
  1103. av_log(NULL, AV_LOG_ERROR,
  1104. "Could not alloc memory for stream options.\n");
  1105. return NULL;
  1106. }
  1107. for (i = 0; i < s->nb_streams; i++)
  1108. opts[i] = filter_codec_opts(codec_opts, s->streams[i]->codec->codec_id,
  1109. s, s->streams[i], NULL);
  1110. return opts;
  1111. }
  1112. void *grow_array(void *array, int elem_size, int *size, int new_size)
  1113. {
  1114. if (new_size >= INT_MAX / elem_size) {
  1115. av_log(NULL, AV_LOG_ERROR, "Array too big.\n");
  1116. exit(1);
  1117. }
  1118. if (*size < new_size) {
  1119. uint8_t *tmp = av_realloc(array, new_size*elem_size);
  1120. if (!tmp) {
  1121. av_log(NULL, AV_LOG_ERROR, "Could not alloc buffer.\n");
  1122. exit(1);
  1123. }
  1124. memset(tmp + *size*elem_size, 0, (new_size-*size) * elem_size);
  1125. *size = new_size;
  1126. return tmp;
  1127. }
  1128. return array;
  1129. }
  1130. static int alloc_buffer(FrameBuffer **pool, AVCodecContext *s, FrameBuffer **pbuf)
  1131. {
  1132. const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(s->pix_fmt);
  1133. FrameBuffer *buf;
  1134. int i, ret;
  1135. int pixel_size;
  1136. int h_chroma_shift, v_chroma_shift;
  1137. int edge = 32; // XXX should be avcodec_get_edge_width(), but that fails on svq1
  1138. int w = s->width, h = s->height;
  1139. if (!desc)
  1140. return AVERROR(EINVAL);
  1141. pixel_size = desc->comp[0].step_minus1 + 1;
  1142. buf = av_mallocz(sizeof(*buf));
  1143. if (!buf)
  1144. return AVERROR(ENOMEM);
  1145. if (!(s->flags & CODEC_FLAG_EMU_EDGE)) {
  1146. w += 2*edge;
  1147. h += 2*edge;
  1148. }
  1149. avcodec_align_dimensions(s, &w, &h);
  1150. if ((ret = av_image_alloc(buf->base, buf->linesize, w, h,
  1151. s->pix_fmt, 32)) < 0) {
  1152. av_freep(&buf);
  1153. return ret;
  1154. }
  1155. /* XXX this shouldn't be needed, but some tests break without this line
  1156. * those decoders are buggy and need to be fixed.
  1157. * the following tests fail:
  1158. * cdgraphics, ansi, aasc, fraps-v1, qtrle-1bit
  1159. */
  1160. memset(buf->base[0], 128, ret);
  1161. avcodec_get_chroma_sub_sample(s->pix_fmt, &h_chroma_shift, &v_chroma_shift);
  1162. for (i = 0; i < FF_ARRAY_ELEMS(buf->data); i++) {
  1163. const int h_shift = i==0 ? 0 : h_chroma_shift;
  1164. const int v_shift = i==0 ? 0 : v_chroma_shift;
  1165. if (s->flags & CODEC_FLAG_EMU_EDGE)
  1166. buf->data[i] = buf->base[i];
  1167. else if (buf->base[i])
  1168. buf->data[i] = buf->base[i] +
  1169. FFALIGN((buf->linesize[i]*edge >> v_shift) +
  1170. (pixel_size*edge >> h_shift), 32);
  1171. }
  1172. buf->w = s->width;
  1173. buf->h = s->height;
  1174. buf->pix_fmt = s->pix_fmt;
  1175. buf->pool = pool;
  1176. *pbuf = buf;
  1177. return 0;
  1178. }
  1179. int codec_get_buffer(AVCodecContext *s, AVFrame *frame)
  1180. {
  1181. FrameBuffer **pool = s->opaque;
  1182. FrameBuffer *buf;
  1183. int ret, i;
  1184. if (!*pool && (ret = alloc_buffer(pool, s, pool)) < 0)
  1185. return ret;
  1186. buf = *pool;
  1187. *pool = buf->next;
  1188. buf->next = NULL;
  1189. if (buf->w != s->width || buf->h != s->height || buf->pix_fmt != s->pix_fmt) {
  1190. av_freep(&buf->base[0]);
  1191. av_free(buf);
  1192. if ((ret = alloc_buffer(pool, s, &buf)) < 0)
  1193. return ret;
  1194. }
  1195. buf->refcount++;
  1196. frame->opaque = buf;
  1197. frame->type = FF_BUFFER_TYPE_USER;
  1198. frame->extended_data = frame->data;
  1199. frame->pkt_pts = s->pkt ? s->pkt->pts : AV_NOPTS_VALUE;
  1200. frame->width = buf->w;
  1201. frame->height = buf->h;
  1202. frame->format = buf->pix_fmt;
  1203. frame->sample_aspect_ratio = s->sample_aspect_ratio;
  1204. for (i = 0; i < FF_ARRAY_ELEMS(buf->data); i++) {
  1205. frame->base[i] = buf->base[i]; // XXX h264.c uses base though it shouldn't
  1206. frame->data[i] = buf->data[i];
  1207. frame->linesize[i] = buf->linesize[i];
  1208. }
  1209. return 0;
  1210. }
  1211. static void unref_buffer(FrameBuffer *buf)
  1212. {
  1213. FrameBuffer **pool = buf->pool;
  1214. av_assert0(buf->refcount);
  1215. buf->refcount--;
  1216. if (!buf->refcount) {
  1217. buf->next = *pool;
  1218. *pool = buf;
  1219. }
  1220. }
  1221. void codec_release_buffer(AVCodecContext *s, AVFrame *frame)
  1222. {
  1223. FrameBuffer *buf = frame->opaque;
  1224. int i;
  1225. for (i = 0; i < FF_ARRAY_ELEMS(frame->data); i++)
  1226. frame->data[i] = NULL;
  1227. unref_buffer(buf);
  1228. }
  1229. void filter_release_buffer(AVFilterBuffer *fb)
  1230. {
  1231. FrameBuffer *buf = fb->priv;
  1232. av_free(fb);
  1233. unref_buffer(buf);
  1234. }
  1235. void free_buffer_pool(FrameBuffer **pool)
  1236. {
  1237. FrameBuffer *buf = *pool;
  1238. while (buf) {
  1239. *pool = buf->next;
  1240. av_freep(&buf->base[0]);
  1241. av_free(buf);
  1242. buf = *pool;
  1243. }
  1244. }