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.

1169 lines
41KB

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