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.

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