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.

397 lines
13KB

  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. /* channel mapping specific */
  47. int channel_map[SWR_CH_MAX];
  48. struct SwrContext *swr;
  49. } PanContext;
  50. static int parse_channel_name(char **arg, int *rchannel, int *rnamed)
  51. {
  52. char buf[8];
  53. int len, i, channel_id = 0;
  54. int64_t layout, layout0;
  55. /* try to parse a channel name, e.g. "FL" */
  56. if (sscanf(*arg, " %7[A-Z] %n", buf, &len)) {
  57. layout0 = layout = av_get_channel_layout(buf);
  58. /* channel_id <- first set bit in layout */
  59. for (i = 32; i > 0; i >>= 1) {
  60. if (layout >= (int64_t)1 << i) {
  61. channel_id += i;
  62. layout >>= i;
  63. }
  64. }
  65. /* reject layouts that are not a single channel */
  66. if (channel_id >= MAX_CHANNELS || layout0 != (int64_t)1 << channel_id)
  67. return AVERROR(EINVAL);
  68. *rchannel = channel_id;
  69. *rnamed = 1;
  70. *arg += len;
  71. return 0;
  72. }
  73. /* try to parse a channel number, e.g. "c2" */
  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 query_formats(AVFilterContext *ctx)
  196. {
  197. PanContext *pan = ctx->priv;
  198. AVFilterLink *inlink = ctx->inputs[0];
  199. AVFilterLink *outlink = ctx->outputs[0];
  200. AVFilterFormats *formats;
  201. pan->pure_gains = are_gains_pure(pan);
  202. /* libswr supports any sample and packing formats */
  203. avfilter_set_common_sample_formats(ctx, avfilter_make_all_formats(AVMEDIA_TYPE_AUDIO));
  204. avfilter_set_common_packing_formats(ctx, avfilter_make_all_packing_formats());
  205. // inlink supports any channel layout
  206. formats = avfilter_make_all_channel_layouts();
  207. avfilter_formats_ref(formats, &inlink->out_chlayouts);
  208. // outlink supports only requested output channel layout
  209. formats = NULL;
  210. avfilter_add_format(&formats, pan->out_channel_layout);
  211. avfilter_formats_ref(formats, &outlink->in_chlayouts);
  212. return 0;
  213. }
  214. static int config_props(AVFilterLink *link)
  215. {
  216. AVFilterContext *ctx = link->dst;
  217. PanContext *pan = ctx->priv;
  218. char buf[1024], *cur;
  219. int i, j, k, r;
  220. double t;
  221. pan->nb_input_channels = av_get_channel_layout_nb_channels(link->channel_layout);
  222. if (pan->need_renumber) {
  223. // input channels were given by their name: renumber them
  224. for (i = j = 0; i < MAX_CHANNELS; i++) {
  225. if ((link->channel_layout >> i) & 1) {
  226. for (k = 0; k < pan->nb_output_channels; k++)
  227. pan->gain.d[k][j] = pan->gain.d[k][i];
  228. j++;
  229. }
  230. }
  231. }
  232. // sanity check; can't be done in query_formats since the inlink
  233. // channel layout is unknown at that time
  234. if (pan->nb_input_channels > SWR_CH_MAX ||
  235. pan->nb_output_channels > SWR_CH_MAX) {
  236. av_log(ctx, AV_LOG_ERROR,
  237. "libswresample support a maximum of %d channels. "
  238. "Feel free to ask for a higher limit.\n", SWR_CH_MAX);
  239. return AVERROR_PATCHWELCOME;
  240. }
  241. // init libswresample context
  242. pan->swr = swr_alloc_set_opts(pan->swr,
  243. pan->out_channel_layout, link->format, link->sample_rate,
  244. link->channel_layout, link->format, link->sample_rate,
  245. 0, ctx);
  246. if (!pan->swr)
  247. return AVERROR(ENOMEM);
  248. // gains are pure, init the channel mapping
  249. if (pan->pure_gains) {
  250. // get channel map from the pure gains
  251. for (i = 0; i < pan->nb_output_channels; i++) {
  252. int ch_id = -1;
  253. for (j = 0; j < pan->nb_input_channels; j++) {
  254. if (pan->gain.d[i][j]) {
  255. ch_id = j;
  256. break;
  257. }
  258. }
  259. pan->channel_map[i] = ch_id;
  260. }
  261. av_opt_set_int(pan->swr, "icl", pan->out_channel_layout, 0);
  262. av_opt_set_int(pan->swr, "uch", pan->nb_output_channels, 0);
  263. swr_set_channel_mapping(pan->swr, pan->channel_map);
  264. } else {
  265. // renormalize
  266. for (i = 0; i < pan->nb_output_channels; i++) {
  267. if (!((pan->need_renorm >> i) & 1))
  268. continue;
  269. t = 0;
  270. for (j = 0; j < pan->nb_input_channels; j++)
  271. t += pan->gain.d[i][j];
  272. if (t > -1E-5 && t < 1E-5) {
  273. // t is almost 0 but not exactly, this is probably a mistake
  274. if (t)
  275. av_log(ctx, AV_LOG_WARNING,
  276. "Degenerate coefficients while renormalizing\n");
  277. continue;
  278. }
  279. for (j = 0; j < pan->nb_input_channels; j++)
  280. pan->gain.d[i][j] /= t;
  281. }
  282. av_opt_set_int(pan->swr, "icl", link->channel_layout, 0);
  283. av_opt_set_int(pan->swr, "ocl", pan->out_channel_layout, 0);
  284. swr_set_matrix(pan->swr, pan->gain.d[0],
  285. pan->gain.d[1] - pan->gain.d[0]);
  286. }
  287. r = swr_init(pan->swr);
  288. if (r < 0)
  289. return r;
  290. // summary
  291. for (i = 0; i < pan->nb_output_channels; i++) {
  292. cur = buf;
  293. for (j = 0; j < pan->nb_input_channels; j++) {
  294. r = snprintf(cur, buf + sizeof(buf) - cur, "%s%.3g i%d",
  295. j ? " + " : "", pan->gain.d[i][j], j);
  296. cur += FFMIN(buf + sizeof(buf) - cur, r);
  297. }
  298. av_log(ctx, AV_LOG_INFO, "o%d = %s\n", i, buf);
  299. }
  300. // add channel mapping summary if possible
  301. if (pan->pure_gains) {
  302. av_log(ctx, AV_LOG_INFO, "Pure channel mapping detected:");
  303. for (i = 0; i < pan->nb_output_channels; i++)
  304. if (pan->channel_map[i] < 0)
  305. av_log(ctx, AV_LOG_INFO, " M");
  306. else
  307. av_log(ctx, AV_LOG_INFO, " %d", pan->channel_map[i]);
  308. av_log(ctx, AV_LOG_INFO, "\n");
  309. return 0;
  310. }
  311. // convert to integer
  312. for (i = 0; i < pan->nb_output_channels; i++) {
  313. for (j = 0; j < pan->nb_input_channels; j++) {
  314. if (pan->gain.d[i][j] < -128 || pan->gain.d[i][j] > 128)
  315. av_log(ctx, AV_LOG_WARNING,
  316. "Gain #%d->#%d too large, clamped\n", j, i);
  317. pan->gain.i[i][j] = av_clipf(pan->gain.d[i][j], -128, 128) * 256.0;
  318. }
  319. }
  320. return 0;
  321. }
  322. static void filter_samples(AVFilterLink *inlink, AVFilterBufferRef *insamples)
  323. {
  324. int n = insamples->audio->nb_samples;
  325. AVFilterLink *const outlink = inlink->dst->outputs[0];
  326. AVFilterBufferRef *outsamples = avfilter_get_audio_buffer(outlink, AV_PERM_WRITE, n);
  327. PanContext *pan = inlink->dst->priv;
  328. swr_convert(pan->swr, outsamples->data, n, (void *)insamples->data, n);
  329. avfilter_copy_buffer_ref_props(outsamples, insamples);
  330. outsamples->audio->channel_layout = outlink->channel_layout;
  331. outsamples->audio->planar = outlink->planar;
  332. avfilter_filter_samples(outlink, outsamples);
  333. avfilter_unref_buffer(insamples);
  334. }
  335. static av_cold void uninit(AVFilterContext *ctx)
  336. {
  337. PanContext *pan = ctx->priv;
  338. swr_free(&pan->swr);
  339. }
  340. AVFilter avfilter_af_pan = {
  341. .name = "pan",
  342. .description = NULL_IF_CONFIG_SMALL("Remix channels with coefficients (panning)."),
  343. .priv_size = sizeof(PanContext),
  344. .init = init,
  345. .uninit = uninit,
  346. .query_formats = query_formats,
  347. .inputs = (const AVFilterPad[]) {
  348. { .name = "default",
  349. .type = AVMEDIA_TYPE_AUDIO,
  350. .config_props = config_props,
  351. .filter_samples = filter_samples,
  352. .min_perms = AV_PERM_READ, },
  353. { .name = NULL}
  354. },
  355. .outputs = (const AVFilterPad[]) {
  356. { .name = "default",
  357. .type = AVMEDIA_TYPE_AUDIO, },
  358. { .name = NULL}
  359. },
  360. };