af_pan.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  1. /*
  2. * Copyright (c) 2002 Anders Johansson <ajh@atri.curtin.edu.au>
  3. * Copyright (c) 2011 Clément Bœsch <u pkh me>
  4. * Copyright (c) 2011 Nicolas George <nicolas.george@normalesup.org>
  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
  16. * GNU 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. /**
  23. * @file
  24. * Audio panning filter (channels mixing)
  25. * Original code written by Anders Johansson for MPlayer,
  26. * reimplemented for FFmpeg.
  27. */
  28. #include <stdio.h>
  29. #include "libavutil/avstring.h"
  30. #include "libavutil/channel_layout.h"
  31. #include "libavutil/opt.h"
  32. #include "libswresample/swresample.h"
  33. #include "audio.h"
  34. #include "avfilter.h"
  35. #include "formats.h"
  36. #include "internal.h"
  37. #define MAX_CHANNELS 64
  38. typedef struct PanContext {
  39. const AVClass *class;
  40. char *args;
  41. int64_t out_channel_layout;
  42. double gain[MAX_CHANNELS][MAX_CHANNELS];
  43. int64_t need_renorm;
  44. int need_renumber;
  45. int nb_output_channels;
  46. int pure_gains;
  47. /* channel mapping specific */
  48. int channel_map[MAX_CHANNELS];
  49. struct SwrContext *swr;
  50. } PanContext;
  51. static void skip_spaces(char **arg)
  52. {
  53. int len = 0;
  54. sscanf(*arg, " %n", &len);
  55. *arg += len;
  56. }
  57. static int parse_channel_name(char **arg, int *rchannel, int *rnamed)
  58. {
  59. char buf[8];
  60. int len, i, channel_id = 0;
  61. int64_t layout, layout0;
  62. skip_spaces(arg);
  63. /* try to parse a channel name, e.g. "FL" */
  64. if (sscanf(*arg, "%7[A-Z]%n", buf, &len)) {
  65. layout0 = layout = av_get_channel_layout(buf);
  66. /* channel_id <- first set bit in layout */
  67. for (i = 32; i > 0; i >>= 1) {
  68. if (layout >= (int64_t)1 << i) {
  69. channel_id += i;
  70. layout >>= i;
  71. }
  72. }
  73. /* reject layouts that are not a single channel */
  74. if (channel_id >= MAX_CHANNELS || layout0 != (int64_t)1 << channel_id)
  75. return AVERROR(EINVAL);
  76. *rchannel = channel_id;
  77. *rnamed = 1;
  78. *arg += len;
  79. return 0;
  80. }
  81. /* try to parse a channel number, e.g. "c2" */
  82. if (sscanf(*arg, "c%d%n", &channel_id, &len) &&
  83. channel_id >= 0 && channel_id < MAX_CHANNELS) {
  84. *rchannel = channel_id;
  85. *rnamed = 0;
  86. *arg += len;
  87. return 0;
  88. }
  89. return AVERROR(EINVAL);
  90. }
  91. static av_cold int init(AVFilterContext *ctx)
  92. {
  93. PanContext *const pan = ctx->priv;
  94. char *arg, *arg0, *tokenizer, *args = av_strdup(pan->args);
  95. int out_ch_id, in_ch_id, len, named, ret, sign = 1;
  96. int nb_in_channels[2] = { 0, 0 }; // number of unnamed and named input channels
  97. int used_out_ch[MAX_CHANNELS] = {0};
  98. double gain;
  99. if (!pan->args) {
  100. av_log(ctx, AV_LOG_ERROR,
  101. "pan filter needs a channel layout and a set "
  102. "of channel definitions as parameter\n");
  103. return AVERROR(EINVAL);
  104. }
  105. if (!args)
  106. return AVERROR(ENOMEM);
  107. arg = av_strtok(args, "|", &tokenizer);
  108. if (!arg) {
  109. av_log(ctx, AV_LOG_ERROR, "Channel layout not specified\n");
  110. ret = AVERROR(EINVAL);
  111. goto fail;
  112. }
  113. ret = ff_parse_channel_layout(&pan->out_channel_layout,
  114. &pan->nb_output_channels, arg, ctx);
  115. if (ret < 0)
  116. goto fail;
  117. /* parse channel specifications */
  118. while ((arg = arg0 = av_strtok(NULL, "|", &tokenizer))) {
  119. int used_in_ch[MAX_CHANNELS] = {0};
  120. /* channel name */
  121. if (parse_channel_name(&arg, &out_ch_id, &named)) {
  122. av_log(ctx, AV_LOG_ERROR,
  123. "Expected out channel name, got \"%.8s\"\n", arg);
  124. ret = AVERROR(EINVAL);
  125. goto fail;
  126. }
  127. if (named) {
  128. if (!((pan->out_channel_layout >> out_ch_id) & 1)) {
  129. av_log(ctx, AV_LOG_ERROR,
  130. "Channel \"%.8s\" does not exist in the chosen layout\n", arg0);
  131. ret = AVERROR(EINVAL);
  132. goto fail;
  133. }
  134. /* get the channel number in the output channel layout:
  135. * out_channel_layout & ((1 << out_ch_id) - 1) are all the
  136. * channels that come before out_ch_id,
  137. * so their count is the index of out_ch_id */
  138. out_ch_id = av_get_channel_layout_nb_channels(pan->out_channel_layout & (((int64_t)1 << out_ch_id) - 1));
  139. }
  140. if (out_ch_id < 0 || out_ch_id >= pan->nb_output_channels) {
  141. av_log(ctx, AV_LOG_ERROR,
  142. "Invalid out channel name \"%.8s\"\n", arg0);
  143. ret = AVERROR(EINVAL);
  144. goto fail;
  145. }
  146. if (used_out_ch[out_ch_id]) {
  147. av_log(ctx, AV_LOG_ERROR,
  148. "Can not reference out channel %d twice\n", out_ch_id);
  149. ret = AVERROR(EINVAL);
  150. goto fail;
  151. }
  152. used_out_ch[out_ch_id] = 1;
  153. skip_spaces(&arg);
  154. if (*arg == '=') {
  155. arg++;
  156. } else if (*arg == '<') {
  157. pan->need_renorm |= (int64_t)1 << out_ch_id;
  158. arg++;
  159. } else {
  160. av_log(ctx, AV_LOG_ERROR,
  161. "Syntax error after channel name in \"%.8s\"\n", arg0);
  162. ret = AVERROR(EINVAL);
  163. goto fail;
  164. }
  165. /* gains */
  166. sign = 1;
  167. while (1) {
  168. gain = 1;
  169. if (sscanf(arg, "%lf%n *%n", &gain, &len, &len))
  170. arg += len;
  171. if (parse_channel_name(&arg, &in_ch_id, &named)){
  172. av_log(ctx, AV_LOG_ERROR,
  173. "Expected in channel name, got \"%.8s\"\n", arg);
  174. ret = AVERROR(EINVAL);
  175. goto fail;
  176. }
  177. nb_in_channels[named]++;
  178. if (nb_in_channels[!named]) {
  179. av_log(ctx, AV_LOG_ERROR,
  180. "Can not mix named and numbered channels\n");
  181. ret = AVERROR(EINVAL);
  182. goto fail;
  183. }
  184. if (used_in_ch[in_ch_id]) {
  185. av_log(ctx, AV_LOG_ERROR,
  186. "Can not reference in channel %d twice\n", in_ch_id);
  187. ret = AVERROR(EINVAL);
  188. goto fail;
  189. }
  190. used_in_ch[in_ch_id] = 1;
  191. pan->gain[out_ch_id][in_ch_id] = sign * gain;
  192. skip_spaces(&arg);
  193. if (!*arg)
  194. break;
  195. if (*arg == '-') {
  196. sign = -1;
  197. } else if (*arg != '+') {
  198. av_log(ctx, AV_LOG_ERROR, "Syntax error near \"%.8s\"\n", arg);
  199. ret = AVERROR(EINVAL);
  200. goto fail;
  201. } else {
  202. sign = 1;
  203. }
  204. arg++;
  205. }
  206. }
  207. pan->need_renumber = !!nb_in_channels[1];
  208. ret = 0;
  209. fail:
  210. av_free(args);
  211. return ret;
  212. }
  213. static int are_gains_pure(const PanContext *pan)
  214. {
  215. int i, j;
  216. for (i = 0; i < MAX_CHANNELS; i++) {
  217. int nb_gain = 0;
  218. for (j = 0; j < MAX_CHANNELS; j++) {
  219. double gain = pan->gain[i][j];
  220. /* channel mapping is effective only if 0% or 100% of a channel is
  221. * selected... */
  222. if (gain != 0. && gain != 1.)
  223. return 0;
  224. /* ...and if the output channel is only composed of one input */
  225. if (gain && nb_gain++)
  226. return 0;
  227. }
  228. }
  229. return 1;
  230. }
  231. static int query_formats(AVFilterContext *ctx)
  232. {
  233. PanContext *pan = ctx->priv;
  234. AVFilterLink *inlink = ctx->inputs[0];
  235. AVFilterLink *outlink = ctx->outputs[0];
  236. AVFilterFormats *formats = NULL;
  237. AVFilterChannelLayouts *layouts;
  238. int ret;
  239. pan->pure_gains = are_gains_pure(pan);
  240. /* libswr supports any sample and packing formats */
  241. if ((ret = ff_set_common_formats(ctx, ff_all_formats(AVMEDIA_TYPE_AUDIO))) < 0)
  242. return ret;
  243. formats = ff_all_samplerates();
  244. if ((ret = ff_set_common_samplerates(ctx, formats)) < 0)
  245. return ret;
  246. // inlink supports any channel layout
  247. layouts = ff_all_channel_counts();
  248. if ((ret = ff_channel_layouts_ref(layouts, &inlink->out_channel_layouts)) < 0)
  249. return ret;
  250. // outlink supports only requested output channel layout
  251. layouts = NULL;
  252. if ((ret = ff_add_channel_layout(&layouts,
  253. pan->out_channel_layout ? pan->out_channel_layout :
  254. FF_COUNT2LAYOUT(pan->nb_output_channels))) < 0)
  255. return ret;
  256. return ff_channel_layouts_ref(layouts, &outlink->in_channel_layouts);
  257. }
  258. static int config_props(AVFilterLink *link)
  259. {
  260. AVFilterContext *ctx = link->dst;
  261. PanContext *pan = ctx->priv;
  262. char buf[1024], *cur;
  263. int i, j, k, r;
  264. double t;
  265. if (pan->need_renumber) {
  266. // input channels were given by their name: renumber them
  267. for (i = j = 0; i < MAX_CHANNELS; i++) {
  268. if ((link->channel_layout >> i) & 1) {
  269. for (k = 0; k < pan->nb_output_channels; k++)
  270. pan->gain[k][j] = pan->gain[k][i];
  271. j++;
  272. }
  273. }
  274. }
  275. // sanity check; can't be done in query_formats since the inlink
  276. // channel layout is unknown at that time
  277. if (link->channels > MAX_CHANNELS ||
  278. pan->nb_output_channels > MAX_CHANNELS) {
  279. av_log(ctx, AV_LOG_ERROR,
  280. "af_pan supports a maximum of %d channels. "
  281. "Feel free to ask for a higher limit.\n", MAX_CHANNELS);
  282. return AVERROR_PATCHWELCOME;
  283. }
  284. // init libswresample context
  285. pan->swr = swr_alloc_set_opts(pan->swr,
  286. pan->out_channel_layout, link->format, link->sample_rate,
  287. link->channel_layout, link->format, link->sample_rate,
  288. 0, ctx);
  289. if (!pan->swr)
  290. return AVERROR(ENOMEM);
  291. if (!link->channel_layout) {
  292. if (av_opt_set_int(pan->swr, "ich", link->channels, 0) < 0)
  293. return AVERROR(EINVAL);
  294. }
  295. if (!pan->out_channel_layout) {
  296. if (av_opt_set_int(pan->swr, "och", pan->nb_output_channels, 0) < 0)
  297. return AVERROR(EINVAL);
  298. }
  299. // gains are pure, init the channel mapping
  300. if (pan->pure_gains) {
  301. // get channel map from the pure gains
  302. for (i = 0; i < pan->nb_output_channels; i++) {
  303. int ch_id = -1;
  304. for (j = 0; j < link->channels; j++) {
  305. if (pan->gain[i][j]) {
  306. ch_id = j;
  307. break;
  308. }
  309. }
  310. pan->channel_map[i] = ch_id;
  311. }
  312. av_opt_set_int(pan->swr, "icl", pan->out_channel_layout, 0);
  313. av_opt_set_int(pan->swr, "uch", pan->nb_output_channels, 0);
  314. swr_set_channel_mapping(pan->swr, pan->channel_map);
  315. } else {
  316. // renormalize
  317. for (i = 0; i < pan->nb_output_channels; i++) {
  318. if (!((pan->need_renorm >> i) & 1))
  319. continue;
  320. t = 0;
  321. for (j = 0; j < link->channels; j++)
  322. t += fabs(pan->gain[i][j]);
  323. if (t > -1E-5 && t < 1E-5) {
  324. // t is almost 0 but not exactly, this is probably a mistake
  325. if (t)
  326. av_log(ctx, AV_LOG_WARNING,
  327. "Degenerate coefficients while renormalizing\n");
  328. continue;
  329. }
  330. for (j = 0; j < link->channels; j++)
  331. pan->gain[i][j] /= t;
  332. }
  333. av_opt_set_int(pan->swr, "icl", link->channel_layout, 0);
  334. av_opt_set_int(pan->swr, "ocl", pan->out_channel_layout, 0);
  335. swr_set_matrix(pan->swr, pan->gain[0], pan->gain[1] - pan->gain[0]);
  336. }
  337. r = swr_init(pan->swr);
  338. if (r < 0)
  339. return r;
  340. // summary
  341. for (i = 0; i < pan->nb_output_channels; i++) {
  342. cur = buf;
  343. for (j = 0; j < link->channels; j++) {
  344. r = snprintf(cur, buf + sizeof(buf) - cur, "%s%.3g i%d",
  345. j ? " + " : "", pan->gain[i][j], j);
  346. cur += FFMIN(buf + sizeof(buf) - cur, r);
  347. }
  348. av_log(ctx, AV_LOG_VERBOSE, "o%d = %s\n", i, buf);
  349. }
  350. // add channel mapping summary if possible
  351. if (pan->pure_gains) {
  352. av_log(ctx, AV_LOG_INFO, "Pure channel mapping detected:");
  353. for (i = 0; i < pan->nb_output_channels; i++)
  354. if (pan->channel_map[i] < 0)
  355. av_log(ctx, AV_LOG_INFO, " M");
  356. else
  357. av_log(ctx, AV_LOG_INFO, " %d", pan->channel_map[i]);
  358. av_log(ctx, AV_LOG_INFO, "\n");
  359. return 0;
  360. }
  361. return 0;
  362. }
  363. static int filter_frame(AVFilterLink *inlink, AVFrame *insamples)
  364. {
  365. int ret;
  366. int n = insamples->nb_samples;
  367. AVFilterLink *const outlink = inlink->dst->outputs[0];
  368. AVFrame *outsamples = ff_get_audio_buffer(outlink, n);
  369. PanContext *pan = inlink->dst->priv;
  370. if (!outsamples) {
  371. av_frame_free(&insamples);
  372. return AVERROR(ENOMEM);
  373. }
  374. swr_convert(pan->swr, outsamples->extended_data, n,
  375. (void *)insamples->extended_data, n);
  376. av_frame_copy_props(outsamples, insamples);
  377. outsamples->channel_layout = outlink->channel_layout;
  378. outsamples->channels = outlink->channels;
  379. ret = ff_filter_frame(outlink, outsamples);
  380. av_frame_free(&insamples);
  381. return ret;
  382. }
  383. static av_cold void uninit(AVFilterContext *ctx)
  384. {
  385. PanContext *pan = ctx->priv;
  386. swr_free(&pan->swr);
  387. }
  388. #define OFFSET(x) offsetof(PanContext, x)
  389. static const AVOption pan_options[] = {
  390. { "args", NULL, OFFSET(args), AV_OPT_TYPE_STRING, { .str = NULL }, CHAR_MIN, CHAR_MAX, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_FILTERING_PARAM },
  391. { NULL }
  392. };
  393. AVFILTER_DEFINE_CLASS(pan);
  394. static const AVFilterPad pan_inputs[] = {
  395. {
  396. .name = "default",
  397. .type = AVMEDIA_TYPE_AUDIO,
  398. .config_props = config_props,
  399. .filter_frame = filter_frame,
  400. },
  401. { NULL }
  402. };
  403. static const AVFilterPad pan_outputs[] = {
  404. {
  405. .name = "default",
  406. .type = AVMEDIA_TYPE_AUDIO,
  407. },
  408. { NULL }
  409. };
  410. AVFilter ff_af_pan = {
  411. .name = "pan",
  412. .description = NULL_IF_CONFIG_SMALL("Remix channels with coefficients (panning)."),
  413. .priv_size = sizeof(PanContext),
  414. .priv_class = &pan_class,
  415. .init = init,
  416. .uninit = uninit,
  417. .query_formats = query_formats,
  418. .inputs = pan_inputs,
  419. .outputs = pan_outputs,
  420. };