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.

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