af_pan.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  1. /*
  2. * Copyright (c) 2002 Anders Johansson <ajh@atri.curtin.edu.au>
  3. * Copyright (c) 2011 Clément Bœsch <ubitux@gmail.com>
  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 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/opt.h"
  31. #include "libswresample/swresample.h"
  32. #include "avfilter.h"
  33. #define MAX_CHANNELS 63
  34. typedef struct PanContext {
  35. int64_t out_channel_layout;
  36. union {
  37. double d[MAX_CHANNELS][MAX_CHANNELS];
  38. // i is 1:7:8 fixed-point, i.e. in [-128*256; +128*256[
  39. int i[MAX_CHANNELS][MAX_CHANNELS];
  40. } gain;
  41. int64_t need_renorm;
  42. int need_renumber;
  43. int nb_input_channels;
  44. int nb_output_channels;
  45. int pure_gains;
  46. void (*filter_samples)(struct PanContext*,
  47. AVFilterBufferRef*,
  48. AVFilterBufferRef*,
  49. int);
  50. /* channel mapping specific */
  51. int channel_map[SWR_CH_MAX];
  52. struct SwrContext *swr;
  53. } PanContext;
  54. static int parse_channel_name(char **arg, int *rchannel, int *rnamed)
  55. {
  56. char buf[8];
  57. int len, i, channel_id;
  58. int64_t layout, layout0;
  59. if (sscanf(*arg, " %7[A-Z] %n", buf, &len)) {
  60. layout0 = layout = av_get_channel_layout(buf);
  61. for (i = 32; i > 0; i >>= 1) {
  62. if (layout >= (int64_t)1 << i) {
  63. channel_id += i;
  64. layout >>= i;
  65. }
  66. }
  67. if (channel_id >= MAX_CHANNELS || layout0 != (int64_t)1 << channel_id)
  68. return AVERROR(EINVAL);
  69. *rchannel = channel_id;
  70. *rnamed = 1;
  71. *arg += len;
  72. return 0;
  73. }
  74. if (sscanf(*arg, " c%d %n", &channel_id, &len) &&
  75. channel_id >= 0 && channel_id < MAX_CHANNELS) {
  76. *rchannel = channel_id;
  77. *rnamed = 0;
  78. *arg += len;
  79. return 0;
  80. }
  81. return AVERROR(EINVAL);
  82. }
  83. static void skip_spaces(char **arg)
  84. {
  85. int len = 0;
  86. sscanf(*arg, " %n", &len);
  87. *arg += len;
  88. }
  89. static av_cold int init(AVFilterContext *ctx, const char *args0, void *opaque)
  90. {
  91. PanContext *const pan = ctx->priv;
  92. char *arg, *arg0, *tokenizer, *args = av_strdup(args0);
  93. int out_ch_id, in_ch_id, len, named;
  94. int nb_in_channels[2] = { 0, 0 }; // number of unnamed and named input channels
  95. double gain;
  96. if (!args0) {
  97. av_log(ctx, AV_LOG_ERROR,
  98. "pan filter needs a channel layout and a set "
  99. "of channels definitions as parameter\n");
  100. return AVERROR(EINVAL);
  101. }
  102. if (!args)
  103. return AVERROR(ENOMEM);
  104. arg = av_strtok(args, ":", &tokenizer);
  105. pan->out_channel_layout = av_get_channel_layout(arg);
  106. if (!pan->out_channel_layout) {
  107. av_log(ctx, AV_LOG_ERROR, "Unknown channel layout \"%s\"\n", arg);
  108. return AVERROR(EINVAL);
  109. }
  110. pan->nb_output_channels = av_get_channel_layout_nb_channels(pan->out_channel_layout);
  111. /* parse channel specifications */
  112. while ((arg = arg0 = av_strtok(NULL, ":", &tokenizer))) {
  113. /* channel name */
  114. if (parse_channel_name(&arg, &out_ch_id, &named)) {
  115. av_log(ctx, AV_LOG_ERROR,
  116. "Expected out channel name, got \"%.8s\"\n", arg);
  117. return AVERROR(EINVAL);
  118. }
  119. if (named) {
  120. if (!((pan->out_channel_layout >> out_ch_id) & 1)) {
  121. av_log(ctx, AV_LOG_ERROR,
  122. "Channel \"%.8s\" does not exist in the chosen layout\n", arg0);
  123. return AVERROR(EINVAL);
  124. }
  125. /* get the channel number in the output channel layout:
  126. * out_channel_layout & ((1 << out_ch_id) - 1) are all the
  127. * channels that come before out_ch_id,
  128. * so their count is the index of out_ch_id */
  129. out_ch_id = av_get_channel_layout_nb_channels(pan->out_channel_layout & (((int64_t)1 << out_ch_id) - 1));
  130. }
  131. if (out_ch_id < 0 || out_ch_id >= pan->nb_output_channels) {
  132. av_log(ctx, AV_LOG_ERROR,
  133. "Invalid out channel name \"%.8s\"\n", arg0);
  134. return AVERROR(EINVAL);
  135. }
  136. if (*arg == '=') {
  137. arg++;
  138. } else if (*arg == '<') {
  139. pan->need_renorm |= (int64_t)1 << out_ch_id;
  140. arg++;
  141. } else {
  142. av_log(ctx, AV_LOG_ERROR,
  143. "Syntax error after channel name in \"%.8s\"\n", arg0);
  144. return AVERROR(EINVAL);
  145. }
  146. /* gains */
  147. while (1) {
  148. gain = 1;
  149. if (sscanf(arg, " %lf %n* %n", &gain, &len, &len))
  150. arg += len;
  151. if (parse_channel_name(&arg, &in_ch_id, &named)){
  152. av_log(ctx, AV_LOG_ERROR,
  153. "Expected in channel name, got \"%.8s\"\n", arg);
  154. return AVERROR(EINVAL);
  155. }
  156. nb_in_channels[named]++;
  157. if (nb_in_channels[!named]) {
  158. av_log(ctx, AV_LOG_ERROR,
  159. "Can not mix named and numbered channels\n");
  160. return AVERROR(EINVAL);
  161. }
  162. pan->gain.d[out_ch_id][in_ch_id] = gain;
  163. if (!*arg)
  164. break;
  165. if (*arg != '+') {
  166. av_log(ctx, AV_LOG_ERROR, "Syntax error near \"%.8s\"\n", arg);
  167. return AVERROR(EINVAL);
  168. }
  169. arg++;
  170. skip_spaces(&arg);
  171. }
  172. }
  173. pan->need_renumber = !!nb_in_channels[1];
  174. av_free(args);
  175. return 0;
  176. }
  177. static int are_gains_pure(const PanContext *pan)
  178. {
  179. int i, j;
  180. for (i = 0; i < MAX_CHANNELS; i++) {
  181. int nb_gain = 0;
  182. for (j = 0; j < MAX_CHANNELS; j++) {
  183. double gain = pan->gain.d[i][j];
  184. /* channel mapping is effective only if 0% or 100% of a channel is
  185. * selected... */
  186. if (gain != 0. && gain != 1.)
  187. return 0;
  188. /* ...and if the output channel is only composed of one input */
  189. if (gain && nb_gain++)
  190. return 0;
  191. }
  192. }
  193. return 1;
  194. }
  195. static int config_props(AVFilterLink *link)
  196. {
  197. AVFilterContext *ctx = link->dst;
  198. PanContext *pan = ctx->priv;
  199. char buf[1024], *cur;
  200. int i, j, k, r;
  201. double t;
  202. pan->nb_input_channels = av_get_channel_layout_nb_channels(link->channel_layout);
  203. if (pan->need_renumber) {
  204. // input channels were given by their name: renumber them
  205. for (i = j = 0; i < MAX_CHANNELS; i++) {
  206. if ((link->channel_layout >> i) & 1) {
  207. for (k = 0; k < pan->nb_output_channels; k++)
  208. pan->gain.d[k][j] = pan->gain.d[k][i];
  209. j++;
  210. }
  211. }
  212. }
  213. // gains are pure, init the channel mapping
  214. if (pan->pure_gains) {
  215. // sanity check; can't be done in query_formats since the inlink
  216. // channel layout is unknown at that time
  217. if (pan->nb_input_channels > SWR_CH_MAX) {
  218. av_log(ctx, AV_LOG_ERROR,
  219. "libswresample support a maximum of %d channels. "
  220. "Feel free to ask for a higher limit.\n", SWR_CH_MAX);
  221. return AVERROR_PATCHWELCOME;
  222. }
  223. // get channel map from the pure gains
  224. for (i = 0; i < pan->nb_output_channels; i++) {
  225. int ch_id = -1;
  226. for (j = 0; j < pan->nb_input_channels; j++) {
  227. if (pan->gain.d[i][j]) {
  228. ch_id = j;
  229. break;
  230. }
  231. }
  232. pan->channel_map[i] = ch_id;
  233. }
  234. // init libswresample context
  235. pan->swr = swr_alloc_set_opts(pan->swr,
  236. pan->out_channel_layout, link->format, link->sample_rate,
  237. link->channel_layout, link->format, link->sample_rate,
  238. 0, ctx);
  239. if (!pan->swr)
  240. return AVERROR(ENOMEM);
  241. av_opt_set_int(pan->swr, "icl", pan->out_channel_layout, 0);
  242. av_opt_set_int(pan->swr, "uch", pan->nb_output_channels, 0);
  243. swr_set_channel_mapping(pan->swr, pan->channel_map);
  244. r = swr_init(pan->swr);
  245. if (r < 0)
  246. return r;
  247. } else {
  248. // renormalize
  249. for (i = 0; i < pan->nb_output_channels; i++) {
  250. if (!((pan->need_renorm >> i) & 1))
  251. continue;
  252. t = 0;
  253. for (j = 0; j < pan->nb_input_channels; j++)
  254. t += pan->gain.d[i][j];
  255. if (t > -1E-5 && t < 1E-5) {
  256. // t is almost 0 but not exactly, this is probably a mistake
  257. if (t)
  258. av_log(ctx, AV_LOG_WARNING,
  259. "Degenerate coefficients while renormalizing\n");
  260. continue;
  261. }
  262. for (j = 0; j < pan->nb_input_channels; j++)
  263. pan->gain.d[i][j] /= t;
  264. }
  265. }
  266. // summary
  267. for (i = 0; i < pan->nb_output_channels; i++) {
  268. cur = buf;
  269. for (j = 0; j < pan->nb_input_channels; j++) {
  270. r = snprintf(cur, buf + sizeof(buf) - cur, "%s%.3g i%d",
  271. j ? " + " : "", pan->gain.d[i][j], j);
  272. cur += FFMIN(buf + sizeof(buf) - cur, r);
  273. }
  274. av_log(ctx, AV_LOG_INFO, "o%d = %s\n", i, buf);
  275. }
  276. // add channel mapping summary if possible
  277. if (pan->pure_gains) {
  278. av_log(ctx, AV_LOG_INFO, "Pure channel mapping detected:");
  279. for (i = 0; i < pan->nb_output_channels; i++)
  280. if (pan->channel_map[i] < 0)
  281. av_log(ctx, AV_LOG_INFO, " M");
  282. else
  283. av_log(ctx, AV_LOG_INFO, " %d", pan->channel_map[i]);
  284. av_log(ctx, AV_LOG_INFO, "\n");
  285. return 0;
  286. }
  287. // convert to integer
  288. for (i = 0; i < pan->nb_output_channels; i++) {
  289. for (j = 0; j < pan->nb_input_channels; j++) {
  290. if (pan->gain.d[i][j] < -128 || pan->gain.d[i][j] > 128)
  291. av_log(ctx, AV_LOG_WARNING,
  292. "Gain #%d->#%d too large, clamped\n", j, i);
  293. pan->gain.i[i][j] = av_clipf(pan->gain.d[i][j], -128, 128) * 256.0;
  294. }
  295. }
  296. return 0;
  297. }
  298. static void filter_samples_channel_mapping(PanContext *pan,
  299. AVFilterBufferRef *outsamples,
  300. AVFilterBufferRef *insamples,
  301. int n)
  302. {
  303. swr_convert(pan->swr, outsamples->data, n, (void *)insamples->data, n);
  304. }
  305. static void filter_samples_panning(PanContext *pan,
  306. AVFilterBufferRef *outsamples,
  307. AVFilterBufferRef *insamples,
  308. int n)
  309. {
  310. int i, o;
  311. /* input */
  312. const int16_t *in = (int16_t *)insamples->data[0];
  313. const int16_t *in_end = in + n * pan->nb_input_channels;
  314. /* output */
  315. int16_t *out = (int16_t *)outsamples->data[0];
  316. for (; in < in_end; in += pan->nb_input_channels) {
  317. for (o = 0; o < pan->nb_output_channels; o++) {
  318. int v = 0;
  319. for (i = 0; i < pan->nb_input_channels; i++)
  320. v += pan->gain.i[o][i] * in[i];
  321. *(out++) = v >> 8;
  322. }
  323. }
  324. }
  325. static void filter_samples(AVFilterLink *inlink, AVFilterBufferRef *insamples)
  326. {
  327. int n = insamples->audio->nb_samples;
  328. AVFilterLink *const outlink = inlink->dst->outputs[0];
  329. AVFilterBufferRef *outsamples = avfilter_get_audio_buffer(outlink, AV_PERM_WRITE, n);
  330. PanContext *pan = inlink->dst->priv;
  331. pan->filter_samples(pan, outsamples, insamples, n);
  332. avfilter_filter_samples(outlink, outsamples);
  333. avfilter_unref_buffer(insamples);
  334. }
  335. static int query_formats(AVFilterContext *ctx)
  336. {
  337. PanContext *pan = ctx->priv;
  338. AVFilterLink *inlink = ctx->inputs[0];
  339. AVFilterLink *outlink = ctx->outputs[0];
  340. AVFilterFormats *formats;
  341. if (pan->nb_output_channels <= SWR_CH_MAX)
  342. pan->pure_gains = are_gains_pure(pan);
  343. if (pan->pure_gains) {
  344. /* libswr supports any sample and packing formats */
  345. avfilter_set_common_sample_formats(ctx, avfilter_make_all_formats(AVMEDIA_TYPE_AUDIO));
  346. avfilter_set_common_packing_formats(ctx, avfilter_make_all_packing_formats());
  347. pan->filter_samples = filter_samples_channel_mapping;
  348. } else {
  349. const enum AVSampleFormat sample_fmts[] = {AV_SAMPLE_FMT_S16, -1};
  350. const int packing_fmts[] = {AVFILTER_PACKED, -1};
  351. avfilter_set_common_sample_formats (ctx, avfilter_make_format_list(sample_fmts));
  352. avfilter_set_common_packing_formats(ctx, avfilter_make_format_list(packing_fmts));
  353. pan->filter_samples = filter_samples_panning;
  354. }
  355. // inlink supports any channel layout
  356. formats = avfilter_make_all_channel_layouts();
  357. avfilter_formats_ref(formats, &inlink->out_chlayouts);
  358. // outlink supports only requested output channel layout
  359. formats = NULL;
  360. avfilter_add_format(&formats, pan->out_channel_layout);
  361. avfilter_formats_ref(formats, &outlink->in_chlayouts);
  362. return 0;
  363. }
  364. static av_cold void uninit(AVFilterContext *ctx)
  365. {
  366. PanContext *pan = ctx->priv;
  367. swr_free(&pan->swr);
  368. }
  369. AVFilter avfilter_af_pan = {
  370. .name = "pan",
  371. .description = NULL_IF_CONFIG_SMALL("Remix channels with coefficients (panning)."),
  372. .priv_size = sizeof(PanContext),
  373. .init = init,
  374. .uninit = uninit,
  375. .query_formats = query_formats,
  376. .inputs = (const AVFilterPad[]) {
  377. { .name = "default",
  378. .type = AVMEDIA_TYPE_AUDIO,
  379. .config_props = config_props,
  380. .filter_samples = filter_samples,
  381. .min_perms = AV_PERM_READ, },
  382. { .name = NULL}
  383. },
  384. .outputs = (const AVFilterPad[]) {
  385. { .name = "default",
  386. .type = AVMEDIA_TYPE_AUDIO, },
  387. { .name = NULL}
  388. },
  389. };