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.

1242 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. break; \
  540. } \
  541. \
  542. for (k = 0; k < out_link->in_ ## list->nb; k++) \
  543. if (fmts->var[k] == fmt) { \
  544. fmts->var[0] = fmt; \
  545. fmts->nb = 1; \
  546. ret = 1; \
  547. break; \
  548. } \
  549. } \
  550. } \
  551. } while (0)
  552. static int reduce_formats_on_filter(AVFilterContext *filter)
  553. {
  554. int i, j, k, ret = 0;
  555. REDUCE_FORMATS(int, AVFilterFormats, formats, formats,
  556. nb_formats, ff_add_format);
  557. REDUCE_FORMATS(int, AVFilterFormats, samplerates, formats,
  558. nb_formats, ff_add_format);
  559. /* reduce channel layouts */
  560. for (i = 0; i < filter->nb_inputs; i++) {
  561. AVFilterLink *inlink = filter->inputs[i];
  562. uint64_t fmt;
  563. if (!inlink->out_channel_layouts ||
  564. inlink->out_channel_layouts->nb_channel_layouts != 1)
  565. continue;
  566. fmt = inlink->out_channel_layouts->channel_layouts[0];
  567. for (j = 0; j < filter->nb_outputs; j++) {
  568. AVFilterLink *outlink = filter->outputs[j];
  569. AVFilterChannelLayouts *fmts;
  570. fmts = outlink->in_channel_layouts;
  571. if (inlink->type != outlink->type || fmts->nb_channel_layouts == 1)
  572. continue;
  573. if (fmts->all_layouts) {
  574. /* Turn the infinite list into a singleton */
  575. fmts->all_layouts = fmts->all_counts = 0;
  576. ff_add_channel_layout(&outlink->in_channel_layouts, fmt);
  577. break;
  578. }
  579. for (k = 0; k < outlink->in_channel_layouts->nb_channel_layouts; k++) {
  580. if (fmts->channel_layouts[k] == fmt) {
  581. fmts->channel_layouts[0] = fmt;
  582. fmts->nb_channel_layouts = 1;
  583. ret = 1;
  584. break;
  585. }
  586. }
  587. }
  588. }
  589. return ret;
  590. }
  591. static void reduce_formats(AVFilterGraph *graph)
  592. {
  593. int i, reduced;
  594. do {
  595. reduced = 0;
  596. for (i = 0; i < graph->nb_filters; i++)
  597. reduced |= reduce_formats_on_filter(graph->filters[i]);
  598. } while (reduced);
  599. }
  600. static void swap_samplerates_on_filter(AVFilterContext *filter)
  601. {
  602. AVFilterLink *link = NULL;
  603. int sample_rate;
  604. int i, j;
  605. for (i = 0; i < filter->nb_inputs; i++) {
  606. link = filter->inputs[i];
  607. if (link->type == AVMEDIA_TYPE_AUDIO &&
  608. link->out_samplerates->nb_formats== 1)
  609. break;
  610. }
  611. if (i == filter->nb_inputs)
  612. return;
  613. sample_rate = link->out_samplerates->formats[0];
  614. for (i = 0; i < filter->nb_outputs; i++) {
  615. AVFilterLink *outlink = filter->outputs[i];
  616. int best_idx, best_diff = INT_MAX;
  617. if (outlink->type != AVMEDIA_TYPE_AUDIO ||
  618. outlink->in_samplerates->nb_formats < 2)
  619. continue;
  620. for (j = 0; j < outlink->in_samplerates->nb_formats; j++) {
  621. int diff = abs(sample_rate - outlink->in_samplerates->formats[j]);
  622. if (diff < best_diff) {
  623. best_diff = diff;
  624. best_idx = j;
  625. }
  626. }
  627. FFSWAP(int, outlink->in_samplerates->formats[0],
  628. outlink->in_samplerates->formats[best_idx]);
  629. }
  630. }
  631. static void swap_samplerates(AVFilterGraph *graph)
  632. {
  633. int i;
  634. for (i = 0; i < graph->nb_filters; i++)
  635. swap_samplerates_on_filter(graph->filters[i]);
  636. }
  637. #define CH_CENTER_PAIR (AV_CH_FRONT_LEFT_OF_CENTER | AV_CH_FRONT_RIGHT_OF_CENTER)
  638. #define CH_FRONT_PAIR (AV_CH_FRONT_LEFT | AV_CH_FRONT_RIGHT)
  639. #define CH_STEREO_PAIR (AV_CH_STEREO_LEFT | AV_CH_STEREO_RIGHT)
  640. #define CH_WIDE_PAIR (AV_CH_WIDE_LEFT | AV_CH_WIDE_RIGHT)
  641. #define CH_SIDE_PAIR (AV_CH_SIDE_LEFT | AV_CH_SIDE_RIGHT)
  642. #define CH_DIRECT_PAIR (AV_CH_SURROUND_DIRECT_LEFT | AV_CH_SURROUND_DIRECT_RIGHT)
  643. #define CH_BACK_PAIR (AV_CH_BACK_LEFT | AV_CH_BACK_RIGHT)
  644. /* allowable substitutions for channel pairs when comparing layouts,
  645. * ordered by priority for both values */
  646. static const uint64_t ch_subst[][2] = {
  647. { CH_FRONT_PAIR, CH_CENTER_PAIR },
  648. { CH_FRONT_PAIR, CH_WIDE_PAIR },
  649. { CH_FRONT_PAIR, AV_CH_FRONT_CENTER },
  650. { CH_CENTER_PAIR, CH_FRONT_PAIR },
  651. { CH_CENTER_PAIR, CH_WIDE_PAIR },
  652. { CH_CENTER_PAIR, AV_CH_FRONT_CENTER },
  653. { CH_WIDE_PAIR, CH_FRONT_PAIR },
  654. { CH_WIDE_PAIR, CH_CENTER_PAIR },
  655. { CH_WIDE_PAIR, AV_CH_FRONT_CENTER },
  656. { AV_CH_FRONT_CENTER, CH_FRONT_PAIR },
  657. { AV_CH_FRONT_CENTER, CH_CENTER_PAIR },
  658. { AV_CH_FRONT_CENTER, CH_WIDE_PAIR },
  659. { CH_SIDE_PAIR, CH_DIRECT_PAIR },
  660. { CH_SIDE_PAIR, CH_BACK_PAIR },
  661. { CH_SIDE_PAIR, AV_CH_BACK_CENTER },
  662. { CH_BACK_PAIR, CH_DIRECT_PAIR },
  663. { CH_BACK_PAIR, CH_SIDE_PAIR },
  664. { CH_BACK_PAIR, AV_CH_BACK_CENTER },
  665. { AV_CH_BACK_CENTER, CH_BACK_PAIR },
  666. { AV_CH_BACK_CENTER, CH_DIRECT_PAIR },
  667. { AV_CH_BACK_CENTER, CH_SIDE_PAIR },
  668. };
  669. static void swap_channel_layouts_on_filter(AVFilterContext *filter)
  670. {
  671. AVFilterLink *link = NULL;
  672. int i, j, k;
  673. for (i = 0; i < filter->nb_inputs; i++) {
  674. link = filter->inputs[i];
  675. if (link->type == AVMEDIA_TYPE_AUDIO &&
  676. link->out_channel_layouts->nb_channel_layouts == 1)
  677. break;
  678. }
  679. if (i == filter->nb_inputs)
  680. return;
  681. for (i = 0; i < filter->nb_outputs; i++) {
  682. AVFilterLink *outlink = filter->outputs[i];
  683. int best_idx = -1, best_score = INT_MIN, best_count_diff = INT_MAX;
  684. if (outlink->type != AVMEDIA_TYPE_AUDIO ||
  685. outlink->in_channel_layouts->nb_channel_layouts < 2)
  686. continue;
  687. for (j = 0; j < outlink->in_channel_layouts->nb_channel_layouts; j++) {
  688. uint64_t in_chlayout = link->out_channel_layouts->channel_layouts[0];
  689. uint64_t out_chlayout = outlink->in_channel_layouts->channel_layouts[j];
  690. int in_channels = av_get_channel_layout_nb_channels(in_chlayout);
  691. int out_channels = av_get_channel_layout_nb_channels(out_chlayout);
  692. int count_diff = out_channels - in_channels;
  693. int matched_channels, extra_channels;
  694. int score = 100000;
  695. if (FF_LAYOUT2COUNT(in_chlayout) || FF_LAYOUT2COUNT(out_chlayout)) {
  696. /* Compute score in case the input or output layout encodes
  697. a channel count; in this case the score is not altered by
  698. the computation afterwards, as in_chlayout and
  699. out_chlayout have both been set to 0 */
  700. if (FF_LAYOUT2COUNT(in_chlayout))
  701. in_channels = FF_LAYOUT2COUNT(in_chlayout);
  702. if (FF_LAYOUT2COUNT(out_chlayout))
  703. out_channels = FF_LAYOUT2COUNT(out_chlayout);
  704. score -= 10000 + FFABS(out_channels - in_channels) +
  705. (in_channels > out_channels ? 10000 : 0);
  706. in_chlayout = out_chlayout = 0;
  707. /* Let the remaining computation run, even if the score
  708. value is not altered */
  709. }
  710. /* channel substitution */
  711. for (k = 0; k < FF_ARRAY_ELEMS(ch_subst); k++) {
  712. uint64_t cmp0 = ch_subst[k][0];
  713. uint64_t cmp1 = ch_subst[k][1];
  714. if (( in_chlayout & cmp0) && (!(out_chlayout & cmp0)) &&
  715. (out_chlayout & cmp1) && (!( in_chlayout & cmp1))) {
  716. in_chlayout &= ~cmp0;
  717. out_chlayout &= ~cmp1;
  718. /* add score for channel match, minus a deduction for
  719. having to do the substitution */
  720. score += 10 * av_get_channel_layout_nb_channels(cmp1) - 2;
  721. }
  722. }
  723. /* no penalty for LFE channel mismatch */
  724. if ( (in_chlayout & AV_CH_LOW_FREQUENCY) &&
  725. (out_chlayout & AV_CH_LOW_FREQUENCY))
  726. score += 10;
  727. in_chlayout &= ~AV_CH_LOW_FREQUENCY;
  728. out_chlayout &= ~AV_CH_LOW_FREQUENCY;
  729. matched_channels = av_get_channel_layout_nb_channels(in_chlayout &
  730. out_chlayout);
  731. extra_channels = av_get_channel_layout_nb_channels(out_chlayout &
  732. (~in_chlayout));
  733. score += 10 * matched_channels - 5 * extra_channels;
  734. if (score > best_score ||
  735. (count_diff < best_count_diff && score == best_score)) {
  736. best_score = score;
  737. best_idx = j;
  738. best_count_diff = count_diff;
  739. }
  740. }
  741. av_assert0(best_idx >= 0);
  742. FFSWAP(uint64_t, outlink->in_channel_layouts->channel_layouts[0],
  743. outlink->in_channel_layouts->channel_layouts[best_idx]);
  744. }
  745. }
  746. static void swap_channel_layouts(AVFilterGraph *graph)
  747. {
  748. int i;
  749. for (i = 0; i < graph->nb_filters; i++)
  750. swap_channel_layouts_on_filter(graph->filters[i]);
  751. }
  752. static void swap_sample_fmts_on_filter(AVFilterContext *filter)
  753. {
  754. AVFilterLink *link = NULL;
  755. int format, bps;
  756. int i, j;
  757. for (i = 0; i < filter->nb_inputs; i++) {
  758. link = filter->inputs[i];
  759. if (link->type == AVMEDIA_TYPE_AUDIO &&
  760. link->out_formats->nb_formats == 1)
  761. break;
  762. }
  763. if (i == filter->nb_inputs)
  764. return;
  765. format = link->out_formats->formats[0];
  766. bps = av_get_bytes_per_sample(format);
  767. for (i = 0; i < filter->nb_outputs; i++) {
  768. AVFilterLink *outlink = filter->outputs[i];
  769. int best_idx = -1, best_score = INT_MIN;
  770. if (outlink->type != AVMEDIA_TYPE_AUDIO ||
  771. outlink->in_formats->nb_formats < 2)
  772. continue;
  773. for (j = 0; j < outlink->in_formats->nb_formats; j++) {
  774. int out_format = outlink->in_formats->formats[j];
  775. int out_bps = av_get_bytes_per_sample(out_format);
  776. int score;
  777. if (av_get_packed_sample_fmt(out_format) == format ||
  778. av_get_planar_sample_fmt(out_format) == format) {
  779. best_idx = j;
  780. break;
  781. }
  782. /* for s32 and float prefer double to prevent loss of information */
  783. if (bps == 4 && out_bps == 8) {
  784. best_idx = j;
  785. break;
  786. }
  787. /* prefer closest higher or equal bps */
  788. score = -abs(out_bps - bps);
  789. if (out_bps >= bps)
  790. score += INT_MAX/2;
  791. if (score > best_score) {
  792. best_score = score;
  793. best_idx = j;
  794. }
  795. }
  796. av_assert0(best_idx >= 0);
  797. FFSWAP(int, outlink->in_formats->formats[0],
  798. outlink->in_formats->formats[best_idx]);
  799. }
  800. }
  801. static void swap_sample_fmts(AVFilterGraph *graph)
  802. {
  803. int i;
  804. for (i = 0; i < graph->nb_filters; i++)
  805. swap_sample_fmts_on_filter(graph->filters[i]);
  806. }
  807. static int pick_formats(AVFilterGraph *graph)
  808. {
  809. int i, j, ret;
  810. int change;
  811. do{
  812. change = 0;
  813. for (i = 0; i < graph->nb_filters; i++) {
  814. AVFilterContext *filter = graph->filters[i];
  815. if (filter->nb_inputs){
  816. for (j = 0; j < filter->nb_inputs; j++){
  817. if(filter->inputs[j]->in_formats && filter->inputs[j]->in_formats->nb_formats == 1) {
  818. if ((ret = pick_format(filter->inputs[j], NULL)) < 0)
  819. return ret;
  820. change = 1;
  821. }
  822. }
  823. }
  824. if (filter->nb_outputs){
  825. for (j = 0; j < filter->nb_outputs; j++){
  826. if(filter->outputs[j]->in_formats && filter->outputs[j]->in_formats->nb_formats == 1) {
  827. if ((ret = pick_format(filter->outputs[j], NULL)) < 0)
  828. return ret;
  829. change = 1;
  830. }
  831. }
  832. }
  833. if (filter->nb_inputs && filter->nb_outputs && filter->inputs[0]->format>=0) {
  834. for (j = 0; j < filter->nb_outputs; j++) {
  835. if(filter->outputs[j]->format<0) {
  836. if ((ret = pick_format(filter->outputs[j], filter->inputs[0])) < 0)
  837. return ret;
  838. change = 1;
  839. }
  840. }
  841. }
  842. }
  843. }while(change);
  844. for (i = 0; i < graph->nb_filters; i++) {
  845. AVFilterContext *filter = graph->filters[i];
  846. for (j = 0; j < filter->nb_inputs; j++)
  847. if ((ret = pick_format(filter->inputs[j], NULL)) < 0)
  848. return ret;
  849. for (j = 0; j < filter->nb_outputs; j++)
  850. if ((ret = pick_format(filter->outputs[j], NULL)) < 0)
  851. return ret;
  852. }
  853. return 0;
  854. }
  855. /**
  856. * Configure the formats of all the links in the graph.
  857. */
  858. static int graph_config_formats(AVFilterGraph *graph, AVClass *log_ctx)
  859. {
  860. int ret;
  861. /* find supported formats from sub-filters, and merge along links */
  862. while ((ret = query_formats(graph, log_ctx)) == AVERROR(EAGAIN))
  863. av_log(graph, AV_LOG_DEBUG, "query_formats not finished\n");
  864. if (ret < 0)
  865. return ret;
  866. /* Once everything is merged, it's possible that we'll still have
  867. * multiple valid media format choices. We try to minimize the amount
  868. * of format conversion inside filters */
  869. reduce_formats(graph);
  870. /* for audio filters, ensure the best format, sample rate and channel layout
  871. * is selected */
  872. swap_sample_fmts(graph);
  873. swap_samplerates(graph);
  874. swap_channel_layouts(graph);
  875. if ((ret = pick_formats(graph)) < 0)
  876. return ret;
  877. return 0;
  878. }
  879. static int ff_avfilter_graph_config_pointers(AVFilterGraph *graph,
  880. AVClass *log_ctx)
  881. {
  882. unsigned i, j;
  883. int sink_links_count = 0, n = 0;
  884. AVFilterContext *f;
  885. AVFilterLink **sinks;
  886. for (i = 0; i < graph->nb_filters; i++) {
  887. f = graph->filters[i];
  888. for (j = 0; j < f->nb_inputs; j++) {
  889. f->inputs[j]->graph = graph;
  890. f->inputs[j]->age_index = -1;
  891. }
  892. for (j = 0; j < f->nb_outputs; j++) {
  893. f->outputs[j]->graph = graph;
  894. f->outputs[j]->age_index= -1;
  895. }
  896. if (!f->nb_outputs) {
  897. if (f->nb_inputs > INT_MAX - sink_links_count)
  898. return AVERROR(EINVAL);
  899. sink_links_count += f->nb_inputs;
  900. }
  901. }
  902. sinks = av_calloc(sink_links_count, sizeof(*sinks));
  903. if (!sinks)
  904. return AVERROR(ENOMEM);
  905. for (i = 0; i < graph->nb_filters; i++) {
  906. f = graph->filters[i];
  907. if (!f->nb_outputs) {
  908. for (j = 0; j < f->nb_inputs; j++) {
  909. sinks[n] = f->inputs[j];
  910. f->inputs[j]->age_index = n++;
  911. }
  912. }
  913. }
  914. av_assert0(n == sink_links_count);
  915. graph->sink_links = sinks;
  916. graph->sink_links_count = sink_links_count;
  917. return 0;
  918. }
  919. static int graph_insert_fifos(AVFilterGraph *graph, AVClass *log_ctx)
  920. {
  921. AVFilterContext *f;
  922. int i, j, ret;
  923. int fifo_count = 0;
  924. for (i = 0; i < graph->nb_filters; i++) {
  925. f = graph->filters[i];
  926. for (j = 0; j < f->nb_inputs; j++) {
  927. AVFilterLink *link = f->inputs[j];
  928. AVFilterContext *fifo_ctx;
  929. AVFilter *fifo;
  930. char name[32];
  931. if (!link->dstpad->needs_fifo)
  932. continue;
  933. fifo = f->inputs[j]->type == AVMEDIA_TYPE_VIDEO ?
  934. avfilter_get_by_name("fifo") :
  935. avfilter_get_by_name("afifo");
  936. snprintf(name, sizeof(name), "auto-inserted fifo %d", fifo_count++);
  937. ret = avfilter_graph_create_filter(&fifo_ctx, fifo, name, NULL,
  938. NULL, graph);
  939. if (ret < 0)
  940. return ret;
  941. ret = avfilter_insert_filter(link, fifo_ctx, 0, 0);
  942. if (ret < 0)
  943. return ret;
  944. }
  945. }
  946. return 0;
  947. }
  948. int avfilter_graph_config(AVFilterGraph *graphctx, void *log_ctx)
  949. {
  950. int ret;
  951. if ((ret = graph_check_validity(graphctx, log_ctx)))
  952. return ret;
  953. if ((ret = graph_insert_fifos(graphctx, log_ctx)) < 0)
  954. return ret;
  955. if ((ret = graph_config_formats(graphctx, log_ctx)))
  956. return ret;
  957. if ((ret = graph_config_links(graphctx, log_ctx)))
  958. return ret;
  959. if ((ret = ff_avfilter_graph_config_pointers(graphctx, log_ctx)))
  960. return ret;
  961. return 0;
  962. }
  963. int avfilter_graph_send_command(AVFilterGraph *graph, const char *target, const char *cmd, const char *arg, char *res, int res_len, int flags)
  964. {
  965. int i, r = AVERROR(ENOSYS);
  966. if (!graph)
  967. return r;
  968. if ((flags & AVFILTER_CMD_FLAG_ONE) && !(flags & AVFILTER_CMD_FLAG_FAST)) {
  969. r = avfilter_graph_send_command(graph, target, cmd, arg, res, res_len, flags | AVFILTER_CMD_FLAG_FAST);
  970. if (r != AVERROR(ENOSYS))
  971. return r;
  972. }
  973. if (res_len && res)
  974. res[0] = 0;
  975. for (i = 0; i < graph->nb_filters; i++) {
  976. AVFilterContext *filter = graph->filters[i];
  977. if (!strcmp(target, "all") || (filter->name && !strcmp(target, filter->name)) || !strcmp(target, filter->filter->name)) {
  978. r = avfilter_process_command(filter, cmd, arg, res, res_len, flags);
  979. if (r != AVERROR(ENOSYS)) {
  980. if ((flags & AVFILTER_CMD_FLAG_ONE) || r < 0)
  981. return r;
  982. }
  983. }
  984. }
  985. return r;
  986. }
  987. int avfilter_graph_queue_command(AVFilterGraph *graph, const char *target, const char *command, const char *arg, int flags, double ts)
  988. {
  989. int i;
  990. if(!graph)
  991. return 0;
  992. for (i = 0; i < graph->nb_filters; i++) {
  993. AVFilterContext *filter = graph->filters[i];
  994. if(filter && (!strcmp(target, "all") || !strcmp(target, filter->name) || !strcmp(target, filter->filter->name))){
  995. AVFilterCommand **queue = &filter->command_queue, *next;
  996. while (*queue && (*queue)->time <= ts)
  997. queue = &(*queue)->next;
  998. next = *queue;
  999. *queue = av_mallocz(sizeof(AVFilterCommand));
  1000. (*queue)->command = av_strdup(command);
  1001. (*queue)->arg = av_strdup(arg);
  1002. (*queue)->time = ts;
  1003. (*queue)->flags = flags;
  1004. (*queue)->next = next;
  1005. if(flags & AVFILTER_CMD_FLAG_ONE)
  1006. return 0;
  1007. }
  1008. }
  1009. return 0;
  1010. }
  1011. static void heap_bubble_up(AVFilterGraph *graph,
  1012. AVFilterLink *link, int index)
  1013. {
  1014. AVFilterLink **links = graph->sink_links;
  1015. while (index) {
  1016. int parent = (index - 1) >> 1;
  1017. if (links[parent]->current_pts >= link->current_pts)
  1018. break;
  1019. links[index] = links[parent];
  1020. links[index]->age_index = index;
  1021. index = parent;
  1022. }
  1023. links[index] = link;
  1024. link->age_index = index;
  1025. }
  1026. static void heap_bubble_down(AVFilterGraph *graph,
  1027. AVFilterLink *link, int index)
  1028. {
  1029. AVFilterLink **links = graph->sink_links;
  1030. while (1) {
  1031. int child = 2 * index + 1;
  1032. if (child >= graph->sink_links_count)
  1033. break;
  1034. if (child + 1 < graph->sink_links_count &&
  1035. links[child + 1]->current_pts < links[child]->current_pts)
  1036. child++;
  1037. if (link->current_pts < links[child]->current_pts)
  1038. break;
  1039. links[index] = links[child];
  1040. links[index]->age_index = index;
  1041. index = child;
  1042. }
  1043. links[index] = link;
  1044. link->age_index = index;
  1045. }
  1046. void ff_avfilter_graph_update_heap(AVFilterGraph *graph, AVFilterLink *link)
  1047. {
  1048. heap_bubble_up (graph, link, link->age_index);
  1049. heap_bubble_down(graph, link, link->age_index);
  1050. }
  1051. int avfilter_graph_request_oldest(AVFilterGraph *graph)
  1052. {
  1053. while (graph->sink_links_count) {
  1054. AVFilterLink *oldest = graph->sink_links[0];
  1055. int r = ff_request_frame(oldest);
  1056. if (r != AVERROR_EOF)
  1057. return r;
  1058. av_log(oldest->dst, AV_LOG_DEBUG, "EOF on sink link %s:%s.\n",
  1059. oldest->dst ? oldest->dst->name : "unknown",
  1060. oldest->dstpad ? oldest->dstpad->name : "unknown");
  1061. /* EOF: remove the link from the heap */
  1062. if (oldest->age_index < --graph->sink_links_count)
  1063. heap_bubble_down(graph, graph->sink_links[graph->sink_links_count],
  1064. oldest->age_index);
  1065. oldest->age_index = -1;
  1066. }
  1067. return AVERROR_EOF;
  1068. }