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.

574 lines
17KB

  1. /*
  2. * Audio Mix Filter
  3. * Copyright (c) 2012 Justin Ruggles <justin.ruggles@gmail.com>
  4. *
  5. * This file is part of Libav.
  6. *
  7. * Libav is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU Lesser General Public
  9. * License as published by the Free Software Foundation; either
  10. * version 2.1 of the License, or (at your option) any later version.
  11. *
  12. * Libav is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public
  18. * License along with Libav; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. */
  21. /**
  22. * @file
  23. * Audio Mix Filter
  24. *
  25. * Mixes audio from multiple sources into a single output. The channel layout,
  26. * sample rate, and sample format will be the same for all inputs and the
  27. * output.
  28. */
  29. #include "libavutil/audioconvert.h"
  30. #include "libavutil/audio_fifo.h"
  31. #include "libavutil/avassert.h"
  32. #include "libavutil/avstring.h"
  33. #include "libavutil/common.h"
  34. #include "libavutil/float_dsp.h"
  35. #include "libavutil/mathematics.h"
  36. #include "libavutil/opt.h"
  37. #include "libavutil/samplefmt.h"
  38. #include "audio.h"
  39. #include "avfilter.h"
  40. #include "formats.h"
  41. #include "internal.h"
  42. #define INPUT_OFF 0 /**< input has reached EOF */
  43. #define INPUT_ON 1 /**< input is active */
  44. #define INPUT_INACTIVE 2 /**< input is on, but is currently inactive */
  45. #define DURATION_LONGEST 0
  46. #define DURATION_SHORTEST 1
  47. #define DURATION_FIRST 2
  48. typedef struct FrameInfo {
  49. int nb_samples;
  50. int64_t pts;
  51. struct FrameInfo *next;
  52. } FrameInfo;
  53. /**
  54. * Linked list used to store timestamps and frame sizes of all frames in the
  55. * FIFO for the first input.
  56. *
  57. * This is needed to keep timestamps synchronized for the case where multiple
  58. * input frames are pushed to the filter for processing before a frame is
  59. * requested by the output link.
  60. */
  61. typedef struct FrameList {
  62. int nb_frames;
  63. int nb_samples;
  64. FrameInfo *list;
  65. FrameInfo *end;
  66. } FrameList;
  67. static void frame_list_clear(FrameList *frame_list)
  68. {
  69. if (frame_list) {
  70. while (frame_list->list) {
  71. FrameInfo *info = frame_list->list;
  72. frame_list->list = info->next;
  73. av_free(info);
  74. }
  75. frame_list->nb_frames = 0;
  76. frame_list->nb_samples = 0;
  77. frame_list->end = NULL;
  78. }
  79. }
  80. static int frame_list_next_frame_size(FrameList *frame_list)
  81. {
  82. if (!frame_list->list)
  83. return 0;
  84. return frame_list->list->nb_samples;
  85. }
  86. static int64_t frame_list_next_pts(FrameList *frame_list)
  87. {
  88. if (!frame_list->list)
  89. return AV_NOPTS_VALUE;
  90. return frame_list->list->pts;
  91. }
  92. static void frame_list_remove_samples(FrameList *frame_list, int nb_samples)
  93. {
  94. if (nb_samples >= frame_list->nb_samples) {
  95. frame_list_clear(frame_list);
  96. } else {
  97. int samples = nb_samples;
  98. while (samples > 0) {
  99. FrameInfo *info = frame_list->list;
  100. av_assert0(info != NULL);
  101. if (info->nb_samples <= samples) {
  102. samples -= info->nb_samples;
  103. frame_list->list = info->next;
  104. if (!frame_list->list)
  105. frame_list->end = NULL;
  106. frame_list->nb_frames--;
  107. frame_list->nb_samples -= info->nb_samples;
  108. av_free(info);
  109. } else {
  110. info->nb_samples -= samples;
  111. info->pts += samples;
  112. frame_list->nb_samples -= samples;
  113. samples = 0;
  114. }
  115. }
  116. }
  117. }
  118. static int frame_list_add_frame(FrameList *frame_list, int nb_samples, int64_t pts)
  119. {
  120. FrameInfo *info = av_malloc(sizeof(*info));
  121. if (!info)
  122. return AVERROR(ENOMEM);
  123. info->nb_samples = nb_samples;
  124. info->pts = pts;
  125. info->next = NULL;
  126. if (!frame_list->list) {
  127. frame_list->list = info;
  128. frame_list->end = info;
  129. } else {
  130. av_assert0(frame_list->end != NULL);
  131. frame_list->end->next = info;
  132. frame_list->end = info;
  133. }
  134. frame_list->nb_frames++;
  135. frame_list->nb_samples += nb_samples;
  136. return 0;
  137. }
  138. typedef struct MixContext {
  139. const AVClass *class; /**< class for AVOptions */
  140. AVFloatDSPContext fdsp;
  141. int nb_inputs; /**< number of inputs */
  142. int active_inputs; /**< number of input currently active */
  143. int duration_mode; /**< mode for determining duration */
  144. float dropout_transition; /**< transition time when an input drops out */
  145. int nb_channels; /**< number of channels */
  146. int sample_rate; /**< sample rate */
  147. int planar;
  148. AVAudioFifo **fifos; /**< audio fifo for each input */
  149. uint8_t *input_state; /**< current state of each input */
  150. float *input_scale; /**< mixing scale factor for each input */
  151. float scale_norm; /**< normalization factor for all inputs */
  152. int64_t next_pts; /**< calculated pts for next output frame */
  153. FrameList *frame_list; /**< list of frame info for the first input */
  154. } MixContext;
  155. #define OFFSET(x) offsetof(MixContext, x)
  156. #define A AV_OPT_FLAG_AUDIO_PARAM
  157. static const AVOption options[] = {
  158. { "inputs", "Number of inputs.",
  159. OFFSET(nb_inputs), AV_OPT_TYPE_INT, { .i64 = 2 }, 1, 32, A },
  160. { "duration", "How to determine the end-of-stream.",
  161. OFFSET(duration_mode), AV_OPT_TYPE_INT, { .i64 = DURATION_LONGEST }, 0, 2, A, "duration" },
  162. { "longest", "Duration of longest input.", 0, AV_OPT_TYPE_CONST, { .i64 = DURATION_LONGEST }, INT_MIN, INT_MAX, A, "duration" },
  163. { "shortest", "Duration of shortest input.", 0, AV_OPT_TYPE_CONST, { .i64 = DURATION_SHORTEST }, INT_MIN, INT_MAX, A, "duration" },
  164. { "first", "Duration of first input.", 0, AV_OPT_TYPE_CONST, { .i64 = DURATION_FIRST }, INT_MIN, INT_MAX, A, "duration" },
  165. { "dropout_transition", "Transition time, in seconds, for volume "
  166. "renormalization when an input stream ends.",
  167. OFFSET(dropout_transition), AV_OPT_TYPE_FLOAT, { .dbl = 2.0 }, 0, INT_MAX, A },
  168. { NULL },
  169. };
  170. static const AVClass amix_class = {
  171. .class_name = "amix filter",
  172. .item_name = av_default_item_name,
  173. .option = options,
  174. .version = LIBAVUTIL_VERSION_INT,
  175. };
  176. /**
  177. * Update the scaling factors to apply to each input during mixing.
  178. *
  179. * This balances the full volume range between active inputs and handles
  180. * volume transitions when EOF is encountered on an input but mixing continues
  181. * with the remaining inputs.
  182. */
  183. static void calculate_scales(MixContext *s, int nb_samples)
  184. {
  185. int i;
  186. if (s->scale_norm > s->active_inputs) {
  187. s->scale_norm -= nb_samples / (s->dropout_transition * s->sample_rate);
  188. s->scale_norm = FFMAX(s->scale_norm, s->active_inputs);
  189. }
  190. for (i = 0; i < s->nb_inputs; i++) {
  191. if (s->input_state[i] == INPUT_ON)
  192. s->input_scale[i] = 1.0f / s->scale_norm;
  193. else
  194. s->input_scale[i] = 0.0f;
  195. }
  196. }
  197. static int config_output(AVFilterLink *outlink)
  198. {
  199. AVFilterContext *ctx = outlink->src;
  200. MixContext *s = ctx->priv;
  201. int i;
  202. char buf[64];
  203. s->planar = av_sample_fmt_is_planar(outlink->format);
  204. s->sample_rate = outlink->sample_rate;
  205. outlink->time_base = (AVRational){ 1, outlink->sample_rate };
  206. s->next_pts = AV_NOPTS_VALUE;
  207. s->frame_list = av_mallocz(sizeof(*s->frame_list));
  208. if (!s->frame_list)
  209. return AVERROR(ENOMEM);
  210. s->fifos = av_mallocz(s->nb_inputs * sizeof(*s->fifos));
  211. if (!s->fifos)
  212. return AVERROR(ENOMEM);
  213. s->nb_channels = av_get_channel_layout_nb_channels(outlink->channel_layout);
  214. for (i = 0; i < s->nb_inputs; i++) {
  215. s->fifos[i] = av_audio_fifo_alloc(outlink->format, s->nb_channels, 1024);
  216. if (!s->fifos[i])
  217. return AVERROR(ENOMEM);
  218. }
  219. s->input_state = av_malloc(s->nb_inputs);
  220. if (!s->input_state)
  221. return AVERROR(ENOMEM);
  222. memset(s->input_state, INPUT_ON, s->nb_inputs);
  223. s->active_inputs = s->nb_inputs;
  224. s->input_scale = av_mallocz(s->nb_inputs * sizeof(*s->input_scale));
  225. if (!s->input_scale)
  226. return AVERROR(ENOMEM);
  227. s->scale_norm = s->active_inputs;
  228. calculate_scales(s, 0);
  229. av_get_channel_layout_string(buf, sizeof(buf), -1, outlink->channel_layout);
  230. av_log(ctx, AV_LOG_VERBOSE,
  231. "inputs:%d fmt:%s srate:%d cl:%s\n", s->nb_inputs,
  232. av_get_sample_fmt_name(outlink->format), outlink->sample_rate, buf);
  233. return 0;
  234. }
  235. /**
  236. * Read samples from the input FIFOs, mix, and write to the output link.
  237. */
  238. static int output_frame(AVFilterLink *outlink, int nb_samples)
  239. {
  240. AVFilterContext *ctx = outlink->src;
  241. MixContext *s = ctx->priv;
  242. AVFilterBufferRef *out_buf, *in_buf;
  243. int i;
  244. calculate_scales(s, nb_samples);
  245. out_buf = ff_get_audio_buffer(outlink, AV_PERM_WRITE, nb_samples);
  246. if (!out_buf)
  247. return AVERROR(ENOMEM);
  248. in_buf = ff_get_audio_buffer(outlink, AV_PERM_WRITE, nb_samples);
  249. if (!in_buf) {
  250. avfilter_unref_buffer(out_buf);
  251. return AVERROR(ENOMEM);
  252. }
  253. for (i = 0; i < s->nb_inputs; i++) {
  254. if (s->input_state[i] == INPUT_ON) {
  255. int planes, plane_size, p;
  256. av_audio_fifo_read(s->fifos[i], (void **)in_buf->extended_data,
  257. nb_samples);
  258. planes = s->planar ? s->nb_channels : 1;
  259. plane_size = nb_samples * (s->planar ? 1 : s->nb_channels);
  260. plane_size = FFALIGN(plane_size, 16);
  261. for (p = 0; p < planes; p++) {
  262. s->fdsp.vector_fmac_scalar((float *)out_buf->extended_data[p],
  263. (float *) in_buf->extended_data[p],
  264. s->input_scale[i], plane_size);
  265. }
  266. }
  267. }
  268. avfilter_unref_buffer(in_buf);
  269. out_buf->pts = s->next_pts;
  270. if (s->next_pts != AV_NOPTS_VALUE)
  271. s->next_pts += nb_samples;
  272. return ff_filter_samples(outlink, out_buf);
  273. }
  274. /**
  275. * Returns the smallest number of samples available in the input FIFOs other
  276. * than that of the first input.
  277. */
  278. static int get_available_samples(MixContext *s)
  279. {
  280. int i;
  281. int available_samples = INT_MAX;
  282. av_assert0(s->nb_inputs > 1);
  283. for (i = 1; i < s->nb_inputs; i++) {
  284. int nb_samples;
  285. if (s->input_state[i] == INPUT_OFF)
  286. continue;
  287. nb_samples = av_audio_fifo_size(s->fifos[i]);
  288. available_samples = FFMIN(available_samples, nb_samples);
  289. }
  290. if (available_samples == INT_MAX)
  291. return 0;
  292. return available_samples;
  293. }
  294. /**
  295. * Requests a frame, if needed, from each input link other than the first.
  296. */
  297. static int request_samples(AVFilterContext *ctx, int min_samples)
  298. {
  299. MixContext *s = ctx->priv;
  300. int i, ret;
  301. av_assert0(s->nb_inputs > 1);
  302. for (i = 1; i < s->nb_inputs; i++) {
  303. ret = 0;
  304. if (s->input_state[i] == INPUT_OFF)
  305. continue;
  306. while (!ret && av_audio_fifo_size(s->fifos[i]) < min_samples)
  307. ret = ff_request_frame(ctx->inputs[i]);
  308. if (ret == AVERROR_EOF) {
  309. if (av_audio_fifo_size(s->fifos[i]) == 0) {
  310. s->input_state[i] = INPUT_OFF;
  311. continue;
  312. }
  313. } else if (ret < 0)
  314. return ret;
  315. }
  316. return 0;
  317. }
  318. /**
  319. * Calculates the number of active inputs and determines EOF based on the
  320. * duration option.
  321. *
  322. * @return 0 if mixing should continue, or AVERROR_EOF if mixing should stop.
  323. */
  324. static int calc_active_inputs(MixContext *s)
  325. {
  326. int i;
  327. int active_inputs = 0;
  328. for (i = 0; i < s->nb_inputs; i++)
  329. active_inputs += !!(s->input_state[i] != INPUT_OFF);
  330. s->active_inputs = active_inputs;
  331. if (!active_inputs ||
  332. (s->duration_mode == DURATION_FIRST && s->input_state[0] == INPUT_OFF) ||
  333. (s->duration_mode == DURATION_SHORTEST && active_inputs != s->nb_inputs))
  334. return AVERROR_EOF;
  335. return 0;
  336. }
  337. static int request_frame(AVFilterLink *outlink)
  338. {
  339. AVFilterContext *ctx = outlink->src;
  340. MixContext *s = ctx->priv;
  341. int ret;
  342. int wanted_samples, available_samples;
  343. ret = calc_active_inputs(s);
  344. if (ret < 0)
  345. return ret;
  346. if (s->input_state[0] == INPUT_OFF) {
  347. ret = request_samples(ctx, 1);
  348. if (ret < 0)
  349. return ret;
  350. ret = calc_active_inputs(s);
  351. if (ret < 0)
  352. return ret;
  353. available_samples = get_available_samples(s);
  354. if (!available_samples)
  355. return AVERROR(EAGAIN);
  356. return output_frame(outlink, available_samples);
  357. }
  358. if (s->frame_list->nb_frames == 0) {
  359. ret = ff_request_frame(ctx->inputs[0]);
  360. if (ret == AVERROR_EOF) {
  361. s->input_state[0] = INPUT_OFF;
  362. if (s->nb_inputs == 1)
  363. return AVERROR_EOF;
  364. else
  365. return AVERROR(EAGAIN);
  366. } else if (ret < 0)
  367. return ret;
  368. }
  369. av_assert0(s->frame_list->nb_frames > 0);
  370. wanted_samples = frame_list_next_frame_size(s->frame_list);
  371. if (s->active_inputs > 1) {
  372. ret = request_samples(ctx, wanted_samples);
  373. if (ret < 0)
  374. return ret;
  375. ret = calc_active_inputs(s);
  376. if (ret < 0)
  377. return ret;
  378. }
  379. if (s->active_inputs > 1) {
  380. available_samples = get_available_samples(s);
  381. if (!available_samples)
  382. return AVERROR(EAGAIN);
  383. available_samples = FFMIN(available_samples, wanted_samples);
  384. } else {
  385. available_samples = wanted_samples;
  386. }
  387. s->next_pts = frame_list_next_pts(s->frame_list);
  388. frame_list_remove_samples(s->frame_list, available_samples);
  389. return output_frame(outlink, available_samples);
  390. }
  391. static int filter_samples(AVFilterLink *inlink, AVFilterBufferRef *buf)
  392. {
  393. AVFilterContext *ctx = inlink->dst;
  394. MixContext *s = ctx->priv;
  395. AVFilterLink *outlink = ctx->outputs[0];
  396. int i, ret = 0;
  397. for (i = 0; i < ctx->nb_inputs; i++)
  398. if (ctx->inputs[i] == inlink)
  399. break;
  400. if (i >= ctx->nb_inputs) {
  401. av_log(ctx, AV_LOG_ERROR, "unknown input link\n");
  402. ret = AVERROR(EINVAL);
  403. goto fail;
  404. }
  405. if (i == 0) {
  406. int64_t pts = av_rescale_q(buf->pts, inlink->time_base,
  407. outlink->time_base);
  408. ret = frame_list_add_frame(s->frame_list, buf->audio->nb_samples, pts);
  409. if (ret < 0)
  410. goto fail;
  411. }
  412. ret = av_audio_fifo_write(s->fifos[i], (void **)buf->extended_data,
  413. buf->audio->nb_samples);
  414. fail:
  415. avfilter_unref_buffer(buf);
  416. return ret;
  417. }
  418. static int init(AVFilterContext *ctx, const char *args)
  419. {
  420. MixContext *s = ctx->priv;
  421. int i, ret;
  422. s->class = &amix_class;
  423. av_opt_set_defaults(s);
  424. if ((ret = av_set_options_string(s, args, "=", ":")) < 0) {
  425. av_log(ctx, AV_LOG_ERROR, "Error parsing options string '%s'.\n", args);
  426. return ret;
  427. }
  428. av_opt_free(s);
  429. for (i = 0; i < s->nb_inputs; i++) {
  430. char name[32];
  431. AVFilterPad pad = { 0 };
  432. snprintf(name, sizeof(name), "input%d", i);
  433. pad.type = AVMEDIA_TYPE_AUDIO;
  434. pad.name = av_strdup(name);
  435. pad.filter_samples = filter_samples;
  436. ff_insert_inpad(ctx, i, &pad);
  437. }
  438. avpriv_float_dsp_init(&s->fdsp, 0);
  439. return 0;
  440. }
  441. static void uninit(AVFilterContext *ctx)
  442. {
  443. int i;
  444. MixContext *s = ctx->priv;
  445. if (s->fifos) {
  446. for (i = 0; i < s->nb_inputs; i++)
  447. av_audio_fifo_free(s->fifos[i]);
  448. av_freep(&s->fifos);
  449. }
  450. frame_list_clear(s->frame_list);
  451. av_freep(&s->frame_list);
  452. av_freep(&s->input_state);
  453. av_freep(&s->input_scale);
  454. for (i = 0; i < ctx->nb_inputs; i++)
  455. av_freep(&ctx->input_pads[i].name);
  456. }
  457. static int query_formats(AVFilterContext *ctx)
  458. {
  459. AVFilterFormats *formats = NULL;
  460. ff_add_format(&formats, AV_SAMPLE_FMT_FLT);
  461. ff_add_format(&formats, AV_SAMPLE_FMT_FLTP);
  462. ff_set_common_formats(ctx, formats);
  463. ff_set_common_channel_layouts(ctx, ff_all_channel_layouts());
  464. ff_set_common_samplerates(ctx, ff_all_samplerates());
  465. return 0;
  466. }
  467. static const AVFilterPad avfilter_af_amix_outputs[] = {
  468. {
  469. .name = "default",
  470. .type = AVMEDIA_TYPE_AUDIO,
  471. .config_props = config_output,
  472. .request_frame = request_frame
  473. },
  474. { NULL }
  475. };
  476. AVFilter avfilter_af_amix = {
  477. .name = "amix",
  478. .description = NULL_IF_CONFIG_SMALL("Audio mixing."),
  479. .priv_size = sizeof(MixContext),
  480. .init = init,
  481. .uninit = uninit,
  482. .query_formats = query_formats,
  483. .inputs = NULL,
  484. .outputs = avfilter_af_amix_outputs,
  485. };