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.

431 lines
15KB

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