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.

1243 lines
43KB

  1. /*
  2. * filter graphs
  3. * Copyright (c) 2008 Vitor Sessak
  4. * Copyright (c) 2007 Bobby Bingham
  5. *
  6. * This file is part of FFmpeg.
  7. *
  8. * FFmpeg is free software; you can redistribute it and/or
  9. * modify it under the terms of the GNU Lesser General Public
  10. * License as published by the Free Software Foundation; either
  11. * version 2.1 of the License, or (at your option) any later version.
  12. *
  13. * FFmpeg is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  16. * Lesser General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU Lesser General Public
  19. * License along with FFmpeg; if not, write to the Free Software
  20. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  21. */
  22. #include "config.h"
  23. #include <string.h>
  24. #include "libavutil/avassert.h"
  25. #include "libavutil/avstring.h"
  26. #include "libavutil/bprint.h"
  27. #include "libavutil/channel_layout.h"
  28. #include "libavutil/opt.h"
  29. #include "libavutil/pixdesc.h"
  30. #include "libavcodec/avcodec.h" // avcodec_find_best_pix_fmt_of_2()
  31. #include "avfilter.h"
  32. #include "formats.h"
  33. #include "internal.h"
  34. #include "thread.h"
  35. #define OFFSET(x) offsetof(AVFilterGraph, x)
  36. #define FLAGS AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_FILTERING_PARAM
  37. static const AVOption filtergraph_options[] = {
  38. { "thread_type", "Allowed thread types", OFFSET(thread_type), AV_OPT_TYPE_FLAGS,
  39. { .i64 = AVFILTER_THREAD_SLICE }, 0, INT_MAX, FLAGS, "thread_type" },
  40. { "slice", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AVFILTER_THREAD_SLICE }, .flags = FLAGS, .unit = "thread_type" },
  41. { "threads", "Maximum number of threads", OFFSET(nb_threads),
  42. AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, FLAGS },
  43. {"scale_sws_opts" , "default scale filter options" , OFFSET(scale_sws_opts) ,
  44. AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, FLAGS },
  45. {"aresample_swr_opts" , "default aresample filter options" , OFFSET(aresample_swr_opts) ,
  46. AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, FLAGS },
  47. { NULL },
  48. };
  49. static const AVClass filtergraph_class = {
  50. .class_name = "AVFilterGraph",
  51. .item_name = av_default_item_name,
  52. .version = LIBAVUTIL_VERSION_INT,
  53. .option = filtergraph_options,
  54. .category = AV_CLASS_CATEGORY_FILTER,
  55. };
  56. #if !HAVE_THREADS
  57. void ff_graph_thread_free(AVFilterGraph *graph)
  58. {
  59. }
  60. int ff_graph_thread_init(AVFilterGraph *graph)
  61. {
  62. graph->thread_type = 0;
  63. graph->nb_threads = 1;
  64. return 0;
  65. }
  66. #endif
  67. AVFilterGraph *avfilter_graph_alloc(void)
  68. {
  69. AVFilterGraph *ret = av_mallocz(sizeof(*ret));
  70. if (!ret)
  71. return NULL;
  72. ret->internal = av_mallocz(sizeof(*ret->internal));
  73. if (!ret->internal) {
  74. av_freep(&ret);
  75. return NULL;
  76. }
  77. ret->av_class = &filtergraph_class;
  78. av_opt_set_defaults(ret);
  79. return ret;
  80. }
  81. void ff_filter_graph_remove_filter(AVFilterGraph *graph, AVFilterContext *filter)
  82. {
  83. int i;
  84. for (i = 0; i < graph->nb_filters; i++) {
  85. if (graph->filters[i] == filter) {
  86. FFSWAP(AVFilterContext*, graph->filters[i],
  87. graph->filters[graph->nb_filters - 1]);
  88. graph->nb_filters--;
  89. return;
  90. }
  91. }
  92. }
  93. void avfilter_graph_free(AVFilterGraph **graph)
  94. {
  95. if (!*graph)
  96. return;
  97. while ((*graph)->nb_filters)
  98. avfilter_free((*graph)->filters[0]);
  99. ff_graph_thread_free(*graph);
  100. av_freep(&(*graph)->sink_links);
  101. av_freep(&(*graph)->scale_sws_opts);
  102. av_freep(&(*graph)->aresample_swr_opts);
  103. av_freep(&(*graph)->resample_lavr_opts);
  104. av_freep(&(*graph)->filters);
  105. av_freep(&(*graph)->internal);
  106. av_freep(graph);
  107. }
  108. #if FF_API_AVFILTER_OPEN
  109. int avfilter_graph_add_filter(AVFilterGraph *graph, AVFilterContext *filter)
  110. {
  111. AVFilterContext **filters = av_realloc(graph->filters,
  112. sizeof(*filters) * (graph->nb_filters + 1));
  113. if (!filters)
  114. return AVERROR(ENOMEM);
  115. graph->filters = filters;
  116. graph->filters[graph->nb_filters++] = filter;
  117. #if FF_API_FOO_COUNT
  118. graph->filter_count_unused = graph->nb_filters;
  119. #endif
  120. filter->graph = graph;
  121. return 0;
  122. }
  123. #endif
  124. int avfilter_graph_create_filter(AVFilterContext **filt_ctx, AVFilter *filt,
  125. const char *name, const char *args, void *opaque,
  126. AVFilterGraph *graph_ctx)
  127. {
  128. int ret;
  129. *filt_ctx = avfilter_graph_alloc_filter(graph_ctx, filt, name);
  130. if (!*filt_ctx)
  131. return AVERROR(ENOMEM);
  132. ret = avfilter_init_str(*filt_ctx, args);
  133. if (ret < 0)
  134. goto fail;
  135. return 0;
  136. fail:
  137. if (*filt_ctx)
  138. avfilter_free(*filt_ctx);
  139. *filt_ctx = NULL;
  140. return ret;
  141. }
  142. void avfilter_graph_set_auto_convert(AVFilterGraph *graph, unsigned flags)
  143. {
  144. graph->disable_auto_convert = flags;
  145. }
  146. AVFilterContext *avfilter_graph_alloc_filter(AVFilterGraph *graph,
  147. const AVFilter *filter,
  148. const char *name)
  149. {
  150. AVFilterContext **filters, *s;
  151. if (graph->thread_type && !graph->internal->thread) {
  152. int ret = ff_graph_thread_init(graph);
  153. if (ret < 0) {
  154. av_log(graph, AV_LOG_ERROR, "Error initializing threading.\n");
  155. return NULL;
  156. }
  157. }
  158. s = ff_filter_alloc(filter, name);
  159. if (!s)
  160. return NULL;
  161. filters = av_realloc(graph->filters, sizeof(*filters) * (graph->nb_filters + 1));
  162. if (!filters) {
  163. avfilter_free(s);
  164. return NULL;
  165. }
  166. graph->filters = filters;
  167. graph->filters[graph->nb_filters++] = s;
  168. #if FF_API_FOO_COUNT
  169. graph->filter_count_unused = graph->nb_filters;
  170. #endif
  171. s->graph = graph;
  172. return s;
  173. }
  174. /**
  175. * Check for the validity of graph.
  176. *
  177. * A graph is considered valid if all its input and output pads are
  178. * connected.
  179. *
  180. * @return 0 in case of success, a negative value otherwise
  181. */
  182. static int graph_check_validity(AVFilterGraph *graph, AVClass *log_ctx)
  183. {
  184. AVFilterContext *filt;
  185. int i, j;
  186. for (i = 0; i < graph->nb_filters; i++) {
  187. const AVFilterPad *pad;
  188. filt = graph->filters[i];
  189. for (j = 0; j < filt->nb_inputs; j++) {
  190. if (!filt->inputs[j] || !filt->inputs[j]->src) {
  191. pad = &filt->input_pads[j];
  192. av_log(log_ctx, AV_LOG_ERROR,
  193. "Input pad \"%s\" with type %s of the filter instance \"%s\" of %s not connected to any source\n",
  194. pad->name, av_get_media_type_string(pad->type), filt->name, filt->filter->name);
  195. return AVERROR(EINVAL);
  196. }
  197. }
  198. for (j = 0; j < filt->nb_outputs; j++) {
  199. if (!filt->outputs[j] || !filt->outputs[j]->dst) {
  200. pad = &filt->output_pads[j];
  201. av_log(log_ctx, AV_LOG_ERROR,
  202. "Output pad \"%s\" with type %s of the filter instance \"%s\" of %s not connected to any destination\n",
  203. pad->name, av_get_media_type_string(pad->type), filt->name, filt->filter->name);
  204. return AVERROR(EINVAL);
  205. }
  206. }
  207. }
  208. return 0;
  209. }
  210. /**
  211. * Configure all the links of graphctx.
  212. *
  213. * @return 0 in case of success, a negative value otherwise
  214. */
  215. static int graph_config_links(AVFilterGraph *graph, AVClass *log_ctx)
  216. {
  217. AVFilterContext *filt;
  218. int i, ret;
  219. for (i = 0; i < graph->nb_filters; i++) {
  220. filt = graph->filters[i];
  221. if (!filt->nb_outputs) {
  222. if ((ret = avfilter_config_links(filt)))
  223. return ret;
  224. }
  225. }
  226. return 0;
  227. }
  228. AVFilterContext *avfilter_graph_get_filter(AVFilterGraph *graph, char *name)
  229. {
  230. int i;
  231. for (i = 0; i < graph->nb_filters; i++)
  232. if (graph->filters[i]->name && !strcmp(name, graph->filters[i]->name))
  233. return graph->filters[i];
  234. return NULL;
  235. }
  236. static void sanitize_channel_layouts(void *log, AVFilterChannelLayouts *l)
  237. {
  238. if (!l)
  239. return;
  240. if (l->nb_channel_layouts) {
  241. if (l->all_layouts || l->all_counts)
  242. av_log(log, AV_LOG_WARNING, "All layouts set on non-empty list\n");
  243. l->all_layouts = l->all_counts = 0;
  244. } else {
  245. if (l->all_counts && !l->all_layouts)
  246. av_log(log, AV_LOG_WARNING, "All counts without all layouts\n");
  247. l->all_layouts = 1;
  248. }
  249. }
  250. static int filter_query_formats(AVFilterContext *ctx)
  251. {
  252. int ret, i;
  253. AVFilterFormats *formats;
  254. AVFilterChannelLayouts *chlayouts;
  255. AVFilterFormats *samplerates;
  256. enum AVMediaType type = ctx->inputs && ctx->inputs [0] ? ctx->inputs [0]->type :
  257. ctx->outputs && ctx->outputs[0] ? ctx->outputs[0]->type :
  258. AVMEDIA_TYPE_VIDEO;
  259. if ((ret = ctx->filter->query_formats(ctx)) < 0) {
  260. if (ret != AVERROR(EAGAIN))
  261. av_log(ctx, AV_LOG_ERROR, "Query format failed for '%s': %s\n",
  262. ctx->name, av_err2str(ret));
  263. return ret;
  264. }
  265. for (i = 0; i < ctx->nb_inputs; i++)
  266. sanitize_channel_layouts(ctx, ctx->inputs[i]->out_channel_layouts);
  267. for (i = 0; i < ctx->nb_outputs; i++)
  268. sanitize_channel_layouts(ctx, ctx->outputs[i]->in_channel_layouts);
  269. formats = ff_all_formats(type);
  270. if (!formats)
  271. return AVERROR(ENOMEM);
  272. ff_set_common_formats(ctx, formats);
  273. if (type == AVMEDIA_TYPE_AUDIO) {
  274. samplerates = ff_all_samplerates();
  275. if (!samplerates)
  276. return AVERROR(ENOMEM);
  277. ff_set_common_samplerates(ctx, samplerates);
  278. chlayouts = ff_all_channel_layouts();
  279. if (!chlayouts)
  280. return AVERROR(ENOMEM);
  281. ff_set_common_channel_layouts(ctx, chlayouts);
  282. }
  283. return 0;
  284. }
  285. static int formats_declared(AVFilterContext *f)
  286. {
  287. int i;
  288. for (i = 0; i < f->nb_inputs; i++) {
  289. if (!f->inputs[i]->out_formats)
  290. return 0;
  291. if (f->inputs[i]->type == AVMEDIA_TYPE_AUDIO &&
  292. !(f->inputs[i]->out_samplerates &&
  293. f->inputs[i]->out_channel_layouts))
  294. return 0;
  295. }
  296. for (i = 0; i < f->nb_outputs; i++) {
  297. if (!f->outputs[i]->in_formats)
  298. return 0;
  299. if (f->outputs[i]->type == AVMEDIA_TYPE_AUDIO &&
  300. !(f->outputs[i]->in_samplerates &&
  301. f->outputs[i]->in_channel_layouts))
  302. return 0;
  303. }
  304. return 1;
  305. }
  306. /**
  307. * Perform one round of query_formats() and merging formats lists on the
  308. * filter graph.
  309. * @return >=0 if all links formats lists could be queried and merged;
  310. * AVERROR(EAGAIN) some progress was made in the queries or merging
  311. * and a later call may succeed;
  312. * AVERROR(EIO) (may be changed) plus a log message if no progress
  313. * was made and the negotiation is stuck;
  314. * a negative error code if some other error happened
  315. */
  316. static int query_formats(AVFilterGraph *graph, AVClass *log_ctx)
  317. {
  318. int i, j, ret;
  319. int scaler_count = 0, resampler_count = 0;
  320. int count_queried = 0; /* successful calls to query_formats() */
  321. int count_merged = 0; /* successful merge of formats lists */
  322. int count_already_merged = 0; /* lists already merged */
  323. int count_delayed = 0; /* lists that need to be merged later */
  324. for (i = 0; i < graph->nb_filters; i++) {
  325. AVFilterContext *f = graph->filters[i];
  326. if (formats_declared(f))
  327. continue;
  328. if (f->filter->query_formats)
  329. ret = filter_query_formats(f);
  330. else
  331. ret = ff_default_query_formats(f);
  332. if (ret < 0 && ret != AVERROR(EAGAIN))
  333. return ret;
  334. /* note: EAGAIN could indicate a partial success, not counted yet */
  335. count_queried += ret >= 0;
  336. }
  337. /* go through and merge as many format lists as possible */
  338. for (i = 0; i < graph->nb_filters; i++) {
  339. AVFilterContext *filter = graph->filters[i];
  340. for (j = 0; j < filter->nb_inputs; j++) {
  341. AVFilterLink *link = filter->inputs[j];
  342. int convert_needed = 0;
  343. if (!link)
  344. continue;
  345. #define MERGE_DISPATCH(field, statement) \
  346. if (!(link->in_ ## field && link->out_ ## field)) { \
  347. count_delayed++; \
  348. } else if (link->in_ ## field == link->out_ ## field) { \
  349. count_already_merged++; \
  350. } else { \
  351. count_merged++; \
  352. statement \
  353. }
  354. MERGE_DISPATCH(formats,
  355. if (!ff_merge_formats(link->in_formats, link->out_formats,
  356. link->type))
  357. convert_needed = 1;
  358. )
  359. if (link->type == AVMEDIA_TYPE_AUDIO) {
  360. MERGE_DISPATCH(channel_layouts,
  361. if (!ff_merge_channel_layouts(link->in_channel_layouts,
  362. link->out_channel_layouts))
  363. convert_needed = 1;
  364. )
  365. MERGE_DISPATCH(samplerates,
  366. if (!ff_merge_samplerates(link->in_samplerates,
  367. link->out_samplerates))
  368. convert_needed = 1;
  369. )
  370. }
  371. #undef MERGE_DISPATCH
  372. if (convert_needed) {
  373. AVFilterContext *convert;
  374. AVFilter *filter;
  375. AVFilterLink *inlink, *outlink;
  376. char scale_args[256];
  377. char inst_name[30];
  378. /* couldn't merge format lists. auto-insert conversion filter */
  379. switch (link->type) {
  380. case AVMEDIA_TYPE_VIDEO:
  381. if (!(filter = avfilter_get_by_name("scale"))) {
  382. av_log(log_ctx, AV_LOG_ERROR, "'scale' filter "
  383. "not present, cannot convert pixel formats.\n");
  384. return AVERROR(EINVAL);
  385. }
  386. snprintf(inst_name, sizeof(inst_name), "auto-inserted scaler %d",
  387. scaler_count++);
  388. if ((ret = avfilter_graph_create_filter(&convert, filter,
  389. inst_name, graph->scale_sws_opts, NULL,
  390. graph)) < 0)
  391. return ret;
  392. break;
  393. case AVMEDIA_TYPE_AUDIO:
  394. if (!(filter = avfilter_get_by_name("aresample"))) {
  395. av_log(log_ctx, AV_LOG_ERROR, "'aresample' filter "
  396. "not present, cannot convert audio formats.\n");
  397. return AVERROR(EINVAL);
  398. }
  399. snprintf(inst_name, sizeof(inst_name), "auto-inserted resampler %d",
  400. resampler_count++);
  401. scale_args[0] = '\0';
  402. if (graph->aresample_swr_opts)
  403. snprintf(scale_args, sizeof(scale_args), "%s",
  404. graph->aresample_swr_opts);
  405. if ((ret = avfilter_graph_create_filter(&convert, filter,
  406. inst_name, graph->aresample_swr_opts,
  407. NULL, graph)) < 0)
  408. return ret;
  409. break;
  410. default:
  411. return AVERROR(EINVAL);
  412. }
  413. if ((ret = avfilter_insert_filter(link, convert, 0, 0)) < 0)
  414. return ret;
  415. filter_query_formats(convert);
  416. inlink = convert->inputs[0];
  417. outlink = convert->outputs[0];
  418. if (!ff_merge_formats( inlink->in_formats, inlink->out_formats, inlink->type) ||
  419. !ff_merge_formats(outlink->in_formats, outlink->out_formats, outlink->type))
  420. ret |= AVERROR(ENOSYS);
  421. if (inlink->type == AVMEDIA_TYPE_AUDIO &&
  422. (!ff_merge_samplerates(inlink->in_samplerates,
  423. inlink->out_samplerates) ||
  424. !ff_merge_channel_layouts(inlink->in_channel_layouts,
  425. inlink->out_channel_layouts)))
  426. ret |= AVERROR(ENOSYS);
  427. if (outlink->type == AVMEDIA_TYPE_AUDIO &&
  428. (!ff_merge_samplerates(outlink->in_samplerates,
  429. outlink->out_samplerates) ||
  430. !ff_merge_channel_layouts(outlink->in_channel_layouts,
  431. outlink->out_channel_layouts)))
  432. ret |= AVERROR(ENOSYS);
  433. if (ret < 0) {
  434. av_log(log_ctx, AV_LOG_ERROR,
  435. "Impossible to convert between the formats supported by the filter "
  436. "'%s' and the filter '%s'\n", link->src->name, link->dst->name);
  437. return ret;
  438. }
  439. }
  440. }
  441. }
  442. av_log(graph, AV_LOG_DEBUG, "query_formats: "
  443. "%d queried, %d merged, %d already done, %d delayed\n",
  444. count_queried, count_merged, count_already_merged, count_delayed);
  445. if (count_delayed) {
  446. AVBPrint bp;
  447. /* if count_queried > 0, one filter at least did set its formats,
  448. that will give additional information to its neighbour;
  449. if count_merged > 0, one pair of formats lists at least was merged,
  450. that will give additional information to all connected filters;
  451. in both cases, progress was made and a new round must be done */
  452. if (count_queried || count_merged)
  453. return AVERROR(EAGAIN);
  454. av_bprint_init(&bp, 0, AV_BPRINT_SIZE_AUTOMATIC);
  455. for (i = 0; i < graph->nb_filters; i++)
  456. if (!formats_declared(graph->filters[i]))
  457. av_bprintf(&bp, "%s%s", bp.len ? ", " : "",
  458. graph->filters[i]->name);
  459. av_log(graph, AV_LOG_ERROR,
  460. "The following filters could not choose their formats: %s\n"
  461. "Consider inserting the (a)format filter near their input or "
  462. "output.\n", bp.str);
  463. return AVERROR(EIO);
  464. }
  465. return 0;
  466. }
  467. static int pick_format(AVFilterLink *link, AVFilterLink *ref)
  468. {
  469. if (!link || !link->in_formats)
  470. return 0;
  471. if (link->type == AVMEDIA_TYPE_VIDEO) {
  472. if(ref && ref->type == AVMEDIA_TYPE_VIDEO){
  473. int has_alpha= av_pix_fmt_desc_get(ref->format)->nb_components % 2 == 0;
  474. enum AVPixelFormat best= AV_PIX_FMT_NONE;
  475. int i;
  476. for (i=0; i<link->in_formats->nb_formats; i++) {
  477. enum AVPixelFormat p = link->in_formats->formats[i];
  478. best= avcodec_find_best_pix_fmt_of_2(best, p, ref->format, has_alpha, NULL);
  479. }
  480. av_log(link->src,AV_LOG_DEBUG, "picking %s out of %d ref:%s alpha:%d\n",
  481. av_get_pix_fmt_name(best), link->in_formats->nb_formats,
  482. av_get_pix_fmt_name(ref->format), has_alpha);
  483. link->in_formats->formats[0] = best;
  484. }
  485. }
  486. link->in_formats->nb_formats = 1;
  487. link->format = link->in_formats->formats[0];
  488. if (link->type == AVMEDIA_TYPE_AUDIO) {
  489. if (!link->in_samplerates->nb_formats) {
  490. av_log(link->src, AV_LOG_ERROR, "Cannot select sample rate for"
  491. " the link between filters %s and %s.\n", link->src->name,
  492. link->dst->name);
  493. return AVERROR(EINVAL);
  494. }
  495. link->in_samplerates->nb_formats = 1;
  496. link->sample_rate = link->in_samplerates->formats[0];
  497. if (link->in_channel_layouts->all_layouts) {
  498. av_log(link->src, AV_LOG_ERROR, "Cannot select channel layout for"
  499. " the link between filters %s and %s.\n", link->src->name,
  500. link->dst->name);
  501. return AVERROR(EINVAL);
  502. }
  503. link->in_channel_layouts->nb_channel_layouts = 1;
  504. link->channel_layout = link->in_channel_layouts->channel_layouts[0];
  505. if ((link->channels = FF_LAYOUT2COUNT(link->channel_layout)))
  506. link->channel_layout = 0;
  507. else
  508. link->channels = av_get_channel_layout_nb_channels(link->channel_layout);
  509. }
  510. ff_formats_unref(&link->in_formats);
  511. ff_formats_unref(&link->out_formats);
  512. ff_formats_unref(&link->in_samplerates);
  513. ff_formats_unref(&link->out_samplerates);
  514. ff_channel_layouts_unref(&link->in_channel_layouts);
  515. ff_channel_layouts_unref(&link->out_channel_layouts);
  516. return 0;
  517. }
  518. #define REDUCE_FORMATS(fmt_type, list_type, list, var, nb, add_format) \
  519. do { \
  520. for (i = 0; i < filter->nb_inputs; i++) { \
  521. AVFilterLink *link = filter->inputs[i]; \
  522. fmt_type fmt; \
  523. \
  524. if (!link->out_ ## list || link->out_ ## list->nb != 1) \
  525. continue; \
  526. fmt = link->out_ ## list->var[0]; \
  527. \
  528. for (j = 0; j < filter->nb_outputs; j++) { \
  529. AVFilterLink *out_link = filter->outputs[j]; \
  530. list_type *fmts; \
  531. \
  532. if (link->type != out_link->type || \
  533. out_link->in_ ## list->nb == 1) \
  534. continue; \
  535. fmts = out_link->in_ ## list; \
  536. \
  537. if (!out_link->in_ ## list->nb) { \
  538. add_format(&out_link->in_ ##list, fmt); \
  539. ret = 1; \
  540. break; \
  541. } \
  542. \
  543. for (k = 0; k < out_link->in_ ## list->nb; k++) \
  544. if (fmts->var[k] == fmt) { \
  545. fmts->var[0] = fmt; \
  546. fmts->nb = 1; \
  547. ret = 1; \
  548. break; \
  549. } \
  550. } \
  551. } \
  552. } while (0)
  553. static int reduce_formats_on_filter(AVFilterContext *filter)
  554. {
  555. int i, j, k, ret = 0;
  556. REDUCE_FORMATS(int, AVFilterFormats, formats, formats,
  557. nb_formats, ff_add_format);
  558. REDUCE_FORMATS(int, AVFilterFormats, samplerates, formats,
  559. nb_formats, ff_add_format);
  560. /* reduce channel layouts */
  561. for (i = 0; i < filter->nb_inputs; i++) {
  562. AVFilterLink *inlink = filter->inputs[i];
  563. uint64_t fmt;
  564. if (!inlink->out_channel_layouts ||
  565. inlink->out_channel_layouts->nb_channel_layouts != 1)
  566. continue;
  567. fmt = inlink->out_channel_layouts->channel_layouts[0];
  568. for (j = 0; j < filter->nb_outputs; j++) {
  569. AVFilterLink *outlink = filter->outputs[j];
  570. AVFilterChannelLayouts *fmts;
  571. fmts = outlink->in_channel_layouts;
  572. if (inlink->type != outlink->type || fmts->nb_channel_layouts == 1)
  573. continue;
  574. if (fmts->all_layouts) {
  575. /* Turn the infinite list into a singleton */
  576. fmts->all_layouts = fmts->all_counts = 0;
  577. ff_add_channel_layout(&outlink->in_channel_layouts, fmt);
  578. break;
  579. }
  580. for (k = 0; k < outlink->in_channel_layouts->nb_channel_layouts; k++) {
  581. if (fmts->channel_layouts[k] == fmt) {
  582. fmts->channel_layouts[0] = fmt;
  583. fmts->nb_channel_layouts = 1;
  584. ret = 1;
  585. break;
  586. }
  587. }
  588. }
  589. }
  590. return ret;
  591. }
  592. static void reduce_formats(AVFilterGraph *graph)
  593. {
  594. int i, reduced;
  595. do {
  596. reduced = 0;
  597. for (i = 0; i < graph->nb_filters; i++)
  598. reduced |= reduce_formats_on_filter(graph->filters[i]);
  599. } while (reduced);
  600. }
  601. static void swap_samplerates_on_filter(AVFilterContext *filter)
  602. {
  603. AVFilterLink *link = NULL;
  604. int sample_rate;
  605. int i, j;
  606. for (i = 0; i < filter->nb_inputs; i++) {
  607. link = filter->inputs[i];
  608. if (link->type == AVMEDIA_TYPE_AUDIO &&
  609. link->out_samplerates->nb_formats== 1)
  610. break;
  611. }
  612. if (i == filter->nb_inputs)
  613. return;
  614. sample_rate = link->out_samplerates->formats[0];
  615. for (i = 0; i < filter->nb_outputs; i++) {
  616. AVFilterLink *outlink = filter->outputs[i];
  617. int best_idx, best_diff = INT_MAX;
  618. if (outlink->type != AVMEDIA_TYPE_AUDIO ||
  619. outlink->in_samplerates->nb_formats < 2)
  620. continue;
  621. for (j = 0; j < outlink->in_samplerates->nb_formats; j++) {
  622. int diff = abs(sample_rate - outlink->in_samplerates->formats[j]);
  623. if (diff < best_diff) {
  624. best_diff = diff;
  625. best_idx = j;
  626. }
  627. }
  628. FFSWAP(int, outlink->in_samplerates->formats[0],
  629. outlink->in_samplerates->formats[best_idx]);
  630. }
  631. }
  632. static void swap_samplerates(AVFilterGraph *graph)
  633. {
  634. int i;
  635. for (i = 0; i < graph->nb_filters; i++)
  636. swap_samplerates_on_filter(graph->filters[i]);
  637. }
  638. #define CH_CENTER_PAIR (AV_CH_FRONT_LEFT_OF_CENTER | AV_CH_FRONT_RIGHT_OF_CENTER)
  639. #define CH_FRONT_PAIR (AV_CH_FRONT_LEFT | AV_CH_FRONT_RIGHT)
  640. #define CH_STEREO_PAIR (AV_CH_STEREO_LEFT | AV_CH_STEREO_RIGHT)
  641. #define CH_WIDE_PAIR (AV_CH_WIDE_LEFT | AV_CH_WIDE_RIGHT)
  642. #define CH_SIDE_PAIR (AV_CH_SIDE_LEFT | AV_CH_SIDE_RIGHT)
  643. #define CH_DIRECT_PAIR (AV_CH_SURROUND_DIRECT_LEFT | AV_CH_SURROUND_DIRECT_RIGHT)
  644. #define CH_BACK_PAIR (AV_CH_BACK_LEFT | AV_CH_BACK_RIGHT)
  645. /* allowable substitutions for channel pairs when comparing layouts,
  646. * ordered by priority for both values */
  647. static const uint64_t ch_subst[][2] = {
  648. { CH_FRONT_PAIR, CH_CENTER_PAIR },
  649. { CH_FRONT_PAIR, CH_WIDE_PAIR },
  650. { CH_FRONT_PAIR, AV_CH_FRONT_CENTER },
  651. { CH_CENTER_PAIR, CH_FRONT_PAIR },
  652. { CH_CENTER_PAIR, CH_WIDE_PAIR },
  653. { CH_CENTER_PAIR, AV_CH_FRONT_CENTER },
  654. { CH_WIDE_PAIR, CH_FRONT_PAIR },
  655. { CH_WIDE_PAIR, CH_CENTER_PAIR },
  656. { CH_WIDE_PAIR, AV_CH_FRONT_CENTER },
  657. { AV_CH_FRONT_CENTER, CH_FRONT_PAIR },
  658. { AV_CH_FRONT_CENTER, CH_CENTER_PAIR },
  659. { AV_CH_FRONT_CENTER, CH_WIDE_PAIR },
  660. { CH_SIDE_PAIR, CH_DIRECT_PAIR },
  661. { CH_SIDE_PAIR, CH_BACK_PAIR },
  662. { CH_SIDE_PAIR, AV_CH_BACK_CENTER },
  663. { CH_BACK_PAIR, CH_DIRECT_PAIR },
  664. { CH_BACK_PAIR, CH_SIDE_PAIR },
  665. { CH_BACK_PAIR, AV_CH_BACK_CENTER },
  666. { AV_CH_BACK_CENTER, CH_BACK_PAIR },
  667. { AV_CH_BACK_CENTER, CH_DIRECT_PAIR },
  668. { AV_CH_BACK_CENTER, CH_SIDE_PAIR },
  669. };
  670. static void swap_channel_layouts_on_filter(AVFilterContext *filter)
  671. {
  672. AVFilterLink *link = NULL;
  673. int i, j, k;
  674. for (i = 0; i < filter->nb_inputs; i++) {
  675. link = filter->inputs[i];
  676. if (link->type == AVMEDIA_TYPE_AUDIO &&
  677. link->out_channel_layouts->nb_channel_layouts == 1)
  678. break;
  679. }
  680. if (i == filter->nb_inputs)
  681. return;
  682. for (i = 0; i < filter->nb_outputs; i++) {
  683. AVFilterLink *outlink = filter->outputs[i];
  684. int best_idx = -1, best_score = INT_MIN, best_count_diff = INT_MAX;
  685. if (outlink->type != AVMEDIA_TYPE_AUDIO ||
  686. outlink->in_channel_layouts->nb_channel_layouts < 2)
  687. continue;
  688. for (j = 0; j < outlink->in_channel_layouts->nb_channel_layouts; j++) {
  689. uint64_t in_chlayout = link->out_channel_layouts->channel_layouts[0];
  690. uint64_t out_chlayout = outlink->in_channel_layouts->channel_layouts[j];
  691. int in_channels = av_get_channel_layout_nb_channels(in_chlayout);
  692. int out_channels = av_get_channel_layout_nb_channels(out_chlayout);
  693. int count_diff = out_channels - in_channels;
  694. int matched_channels, extra_channels;
  695. int score = 100000;
  696. if (FF_LAYOUT2COUNT(in_chlayout) || FF_LAYOUT2COUNT(out_chlayout)) {
  697. /* Compute score in case the input or output layout encodes
  698. a channel count; in this case the score is not altered by
  699. the computation afterwards, as in_chlayout and
  700. out_chlayout have both been set to 0 */
  701. if (FF_LAYOUT2COUNT(in_chlayout))
  702. in_channels = FF_LAYOUT2COUNT(in_chlayout);
  703. if (FF_LAYOUT2COUNT(out_chlayout))
  704. out_channels = FF_LAYOUT2COUNT(out_chlayout);
  705. score -= 10000 + FFABS(out_channels - in_channels) +
  706. (in_channels > out_channels ? 10000 : 0);
  707. in_chlayout = out_chlayout = 0;
  708. /* Let the remaining computation run, even if the score
  709. value is not altered */
  710. }
  711. /* channel substitution */
  712. for (k = 0; k < FF_ARRAY_ELEMS(ch_subst); k++) {
  713. uint64_t cmp0 = ch_subst[k][0];
  714. uint64_t cmp1 = ch_subst[k][1];
  715. if (( in_chlayout & cmp0) && (!(out_chlayout & cmp0)) &&
  716. (out_chlayout & cmp1) && (!( in_chlayout & cmp1))) {
  717. in_chlayout &= ~cmp0;
  718. out_chlayout &= ~cmp1;
  719. /* add score for channel match, minus a deduction for
  720. having to do the substitution */
  721. score += 10 * av_get_channel_layout_nb_channels(cmp1) - 2;
  722. }
  723. }
  724. /* no penalty for LFE channel mismatch */
  725. if ( (in_chlayout & AV_CH_LOW_FREQUENCY) &&
  726. (out_chlayout & AV_CH_LOW_FREQUENCY))
  727. score += 10;
  728. in_chlayout &= ~AV_CH_LOW_FREQUENCY;
  729. out_chlayout &= ~AV_CH_LOW_FREQUENCY;
  730. matched_channels = av_get_channel_layout_nb_channels(in_chlayout &
  731. out_chlayout);
  732. extra_channels = av_get_channel_layout_nb_channels(out_chlayout &
  733. (~in_chlayout));
  734. score += 10 * matched_channels - 5 * extra_channels;
  735. if (score > best_score ||
  736. (count_diff < best_count_diff && score == best_score)) {
  737. best_score = score;
  738. best_idx = j;
  739. best_count_diff = count_diff;
  740. }
  741. }
  742. av_assert0(best_idx >= 0);
  743. FFSWAP(uint64_t, outlink->in_channel_layouts->channel_layouts[0],
  744. outlink->in_channel_layouts->channel_layouts[best_idx]);
  745. }
  746. }
  747. static void swap_channel_layouts(AVFilterGraph *graph)
  748. {
  749. int i;
  750. for (i = 0; i < graph->nb_filters; i++)
  751. swap_channel_layouts_on_filter(graph->filters[i]);
  752. }
  753. static void swap_sample_fmts_on_filter(AVFilterContext *filter)
  754. {
  755. AVFilterLink *link = NULL;
  756. int format, bps;
  757. int i, j;
  758. for (i = 0; i < filter->nb_inputs; i++) {
  759. link = filter->inputs[i];
  760. if (link->type == AVMEDIA_TYPE_AUDIO &&
  761. link->out_formats->nb_formats == 1)
  762. break;
  763. }
  764. if (i == filter->nb_inputs)
  765. return;
  766. format = link->out_formats->formats[0];
  767. bps = av_get_bytes_per_sample(format);
  768. for (i = 0; i < filter->nb_outputs; i++) {
  769. AVFilterLink *outlink = filter->outputs[i];
  770. int best_idx = -1, best_score = INT_MIN;
  771. if (outlink->type != AVMEDIA_TYPE_AUDIO ||
  772. outlink->in_formats->nb_formats < 2)
  773. continue;
  774. for (j = 0; j < outlink->in_formats->nb_formats; j++) {
  775. int out_format = outlink->in_formats->formats[j];
  776. int out_bps = av_get_bytes_per_sample(out_format);
  777. int score;
  778. if (av_get_packed_sample_fmt(out_format) == format ||
  779. av_get_planar_sample_fmt(out_format) == format) {
  780. best_idx = j;
  781. break;
  782. }
  783. /* for s32 and float prefer double to prevent loss of information */
  784. if (bps == 4 && out_bps == 8) {
  785. best_idx = j;
  786. break;
  787. }
  788. /* prefer closest higher or equal bps */
  789. score = -abs(out_bps - bps);
  790. if (out_bps >= bps)
  791. score += INT_MAX/2;
  792. if (score > best_score) {
  793. best_score = score;
  794. best_idx = j;
  795. }
  796. }
  797. av_assert0(best_idx >= 0);
  798. FFSWAP(int, outlink->in_formats->formats[0],
  799. outlink->in_formats->formats[best_idx]);
  800. }
  801. }
  802. static void swap_sample_fmts(AVFilterGraph *graph)
  803. {
  804. int i;
  805. for (i = 0; i < graph->nb_filters; i++)
  806. swap_sample_fmts_on_filter(graph->filters[i]);
  807. }
  808. static int pick_formats(AVFilterGraph *graph)
  809. {
  810. int i, j, ret;
  811. int change;
  812. do{
  813. change = 0;
  814. for (i = 0; i < graph->nb_filters; i++) {
  815. AVFilterContext *filter = graph->filters[i];
  816. if (filter->nb_inputs){
  817. for (j = 0; j < filter->nb_inputs; j++){
  818. if(filter->inputs[j]->in_formats && filter->inputs[j]->in_formats->nb_formats == 1) {
  819. if ((ret = pick_format(filter->inputs[j], NULL)) < 0)
  820. return ret;
  821. change = 1;
  822. }
  823. }
  824. }
  825. if (filter->nb_outputs){
  826. for (j = 0; j < filter->nb_outputs; j++){
  827. if(filter->outputs[j]->in_formats && filter->outputs[j]->in_formats->nb_formats == 1) {
  828. if ((ret = pick_format(filter->outputs[j], NULL)) < 0)
  829. return ret;
  830. change = 1;
  831. }
  832. }
  833. }
  834. if (filter->nb_inputs && filter->nb_outputs && filter->inputs[0]->format>=0) {
  835. for (j = 0; j < filter->nb_outputs; j++) {
  836. if(filter->outputs[j]->format<0) {
  837. if ((ret = pick_format(filter->outputs[j], filter->inputs[0])) < 0)
  838. return ret;
  839. change = 1;
  840. }
  841. }
  842. }
  843. }
  844. }while(change);
  845. for (i = 0; i < graph->nb_filters; i++) {
  846. AVFilterContext *filter = graph->filters[i];
  847. for (j = 0; j < filter->nb_inputs; j++)
  848. if ((ret = pick_format(filter->inputs[j], NULL)) < 0)
  849. return ret;
  850. for (j = 0; j < filter->nb_outputs; j++)
  851. if ((ret = pick_format(filter->outputs[j], NULL)) < 0)
  852. return ret;
  853. }
  854. return 0;
  855. }
  856. /**
  857. * Configure the formats of all the links in the graph.
  858. */
  859. static int graph_config_formats(AVFilterGraph *graph, AVClass *log_ctx)
  860. {
  861. int ret;
  862. /* find supported formats from sub-filters, and merge along links */
  863. while ((ret = query_formats(graph, log_ctx)) == AVERROR(EAGAIN))
  864. av_log(graph, AV_LOG_DEBUG, "query_formats not finished\n");
  865. if (ret < 0)
  866. return ret;
  867. /* Once everything is merged, it's possible that we'll still have
  868. * multiple valid media format choices. We try to minimize the amount
  869. * of format conversion inside filters */
  870. reduce_formats(graph);
  871. /* for audio filters, ensure the best format, sample rate and channel layout
  872. * is selected */
  873. swap_sample_fmts(graph);
  874. swap_samplerates(graph);
  875. swap_channel_layouts(graph);
  876. if ((ret = pick_formats(graph)) < 0)
  877. return ret;
  878. return 0;
  879. }
  880. static int ff_avfilter_graph_config_pointers(AVFilterGraph *graph,
  881. AVClass *log_ctx)
  882. {
  883. unsigned i, j;
  884. int sink_links_count = 0, n = 0;
  885. AVFilterContext *f;
  886. AVFilterLink **sinks;
  887. for (i = 0; i < graph->nb_filters; i++) {
  888. f = graph->filters[i];
  889. for (j = 0; j < f->nb_inputs; j++) {
  890. f->inputs[j]->graph = graph;
  891. f->inputs[j]->age_index = -1;
  892. }
  893. for (j = 0; j < f->nb_outputs; j++) {
  894. f->outputs[j]->graph = graph;
  895. f->outputs[j]->age_index= -1;
  896. }
  897. if (!f->nb_outputs) {
  898. if (f->nb_inputs > INT_MAX - sink_links_count)
  899. return AVERROR(EINVAL);
  900. sink_links_count += f->nb_inputs;
  901. }
  902. }
  903. sinks = av_calloc(sink_links_count, sizeof(*sinks));
  904. if (!sinks)
  905. return AVERROR(ENOMEM);
  906. for (i = 0; i < graph->nb_filters; i++) {
  907. f = graph->filters[i];
  908. if (!f->nb_outputs) {
  909. for (j = 0; j < f->nb_inputs; j++) {
  910. sinks[n] = f->inputs[j];
  911. f->inputs[j]->age_index = n++;
  912. }
  913. }
  914. }
  915. av_assert0(n == sink_links_count);
  916. graph->sink_links = sinks;
  917. graph->sink_links_count = sink_links_count;
  918. return 0;
  919. }
  920. static int graph_insert_fifos(AVFilterGraph *graph, AVClass *log_ctx)
  921. {
  922. AVFilterContext *f;
  923. int i, j, ret;
  924. int fifo_count = 0;
  925. for (i = 0; i < graph->nb_filters; i++) {
  926. f = graph->filters[i];
  927. for (j = 0; j < f->nb_inputs; j++) {
  928. AVFilterLink *link = f->inputs[j];
  929. AVFilterContext *fifo_ctx;
  930. AVFilter *fifo;
  931. char name[32];
  932. if (!link->dstpad->needs_fifo)
  933. continue;
  934. fifo = f->inputs[j]->type == AVMEDIA_TYPE_VIDEO ?
  935. avfilter_get_by_name("fifo") :
  936. avfilter_get_by_name("afifo");
  937. snprintf(name, sizeof(name), "auto-inserted fifo %d", fifo_count++);
  938. ret = avfilter_graph_create_filter(&fifo_ctx, fifo, name, NULL,
  939. NULL, graph);
  940. if (ret < 0)
  941. return ret;
  942. ret = avfilter_insert_filter(link, fifo_ctx, 0, 0);
  943. if (ret < 0)
  944. return ret;
  945. }
  946. }
  947. return 0;
  948. }
  949. int avfilter_graph_config(AVFilterGraph *graphctx, void *log_ctx)
  950. {
  951. int ret;
  952. if ((ret = graph_check_validity(graphctx, log_ctx)))
  953. return ret;
  954. if ((ret = graph_insert_fifos(graphctx, log_ctx)) < 0)
  955. return ret;
  956. if ((ret = graph_config_formats(graphctx, log_ctx)))
  957. return ret;
  958. if ((ret = graph_config_links(graphctx, log_ctx)))
  959. return ret;
  960. if ((ret = ff_avfilter_graph_config_pointers(graphctx, log_ctx)))
  961. return ret;
  962. return 0;
  963. }
  964. int avfilter_graph_send_command(AVFilterGraph *graph, const char *target, const char *cmd, const char *arg, char *res, int res_len, int flags)
  965. {
  966. int i, r = AVERROR(ENOSYS);
  967. if (!graph)
  968. return r;
  969. if ((flags & AVFILTER_CMD_FLAG_ONE) && !(flags & AVFILTER_CMD_FLAG_FAST)) {
  970. r = avfilter_graph_send_command(graph, target, cmd, arg, res, res_len, flags | AVFILTER_CMD_FLAG_FAST);
  971. if (r != AVERROR(ENOSYS))
  972. return r;
  973. }
  974. if (res_len && res)
  975. res[0] = 0;
  976. for (i = 0; i < graph->nb_filters; i++) {
  977. AVFilterContext *filter = graph->filters[i];
  978. if (!strcmp(target, "all") || (filter->name && !strcmp(target, filter->name)) || !strcmp(target, filter->filter->name)) {
  979. r = avfilter_process_command(filter, cmd, arg, res, res_len, flags);
  980. if (r != AVERROR(ENOSYS)) {
  981. if ((flags & AVFILTER_CMD_FLAG_ONE) || r < 0)
  982. return r;
  983. }
  984. }
  985. }
  986. return r;
  987. }
  988. int avfilter_graph_queue_command(AVFilterGraph *graph, const char *target, const char *command, const char *arg, int flags, double ts)
  989. {
  990. int i;
  991. if(!graph)
  992. return 0;
  993. for (i = 0; i < graph->nb_filters; i++) {
  994. AVFilterContext *filter = graph->filters[i];
  995. if(filter && (!strcmp(target, "all") || !strcmp(target, filter->name) || !strcmp(target, filter->filter->name))){
  996. AVFilterCommand **queue = &filter->command_queue, *next;
  997. while (*queue && (*queue)->time <= ts)
  998. queue = &(*queue)->next;
  999. next = *queue;
  1000. *queue = av_mallocz(sizeof(AVFilterCommand));
  1001. (*queue)->command = av_strdup(command);
  1002. (*queue)->arg = av_strdup(arg);
  1003. (*queue)->time = ts;
  1004. (*queue)->flags = flags;
  1005. (*queue)->next = next;
  1006. if(flags & AVFILTER_CMD_FLAG_ONE)
  1007. return 0;
  1008. }
  1009. }
  1010. return 0;
  1011. }
  1012. static void heap_bubble_up(AVFilterGraph *graph,
  1013. AVFilterLink *link, int index)
  1014. {
  1015. AVFilterLink **links = graph->sink_links;
  1016. while (index) {
  1017. int parent = (index - 1) >> 1;
  1018. if (links[parent]->current_pts >= link->current_pts)
  1019. break;
  1020. links[index] = links[parent];
  1021. links[index]->age_index = index;
  1022. index = parent;
  1023. }
  1024. links[index] = link;
  1025. link->age_index = index;
  1026. }
  1027. static void heap_bubble_down(AVFilterGraph *graph,
  1028. AVFilterLink *link, int index)
  1029. {
  1030. AVFilterLink **links = graph->sink_links;
  1031. while (1) {
  1032. int child = 2 * index + 1;
  1033. if (child >= graph->sink_links_count)
  1034. break;
  1035. if (child + 1 < graph->sink_links_count &&
  1036. links[child + 1]->current_pts < links[child]->current_pts)
  1037. child++;
  1038. if (link->current_pts < links[child]->current_pts)
  1039. break;
  1040. links[index] = links[child];
  1041. links[index]->age_index = index;
  1042. index = child;
  1043. }
  1044. links[index] = link;
  1045. link->age_index = index;
  1046. }
  1047. void ff_avfilter_graph_update_heap(AVFilterGraph *graph, AVFilterLink *link)
  1048. {
  1049. heap_bubble_up (graph, link, link->age_index);
  1050. heap_bubble_down(graph, link, link->age_index);
  1051. }
  1052. int avfilter_graph_request_oldest(AVFilterGraph *graph)
  1053. {
  1054. while (graph->sink_links_count) {
  1055. AVFilterLink *oldest = graph->sink_links[0];
  1056. int r = ff_request_frame(oldest);
  1057. if (r != AVERROR_EOF)
  1058. return r;
  1059. av_log(oldest->dst, AV_LOG_DEBUG, "EOF on sink link %s:%s.\n",
  1060. oldest->dst ? oldest->dst->name : "unknown",
  1061. oldest->dstpad ? oldest->dstpad->name : "unknown");
  1062. /* EOF: remove the link from the heap */
  1063. if (oldest->age_index < --graph->sink_links_count)
  1064. heap_bubble_down(graph, graph->sink_links[graph->sink_links_count],
  1065. oldest->age_index);
  1066. oldest->age_index = -1;
  1067. }
  1068. return AVERROR_EOF;
  1069. }