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.

1198 lines
42KB

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