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.

1131 lines
40KB

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