af_amix.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567
  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/audio_fifo.h"
  30. #include "libavutil/avassert.h"
  31. #include "libavutil/avstring.h"
  32. #include "libavutil/channel_layout.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. #define F AV_OPT_FLAG_FILTERING_PARAM
  158. static const AVOption amix_options[] = {
  159. { "inputs", "Number of inputs.",
  160. OFFSET(nb_inputs), AV_OPT_TYPE_INT, { .i64 = 2 }, 1, 32, A|F },
  161. { "duration", "How to determine the end-of-stream.",
  162. OFFSET(duration_mode), AV_OPT_TYPE_INT, { .i64 = DURATION_LONGEST }, 0, 2, A|F, "duration" },
  163. { "longest", "Duration of longest input.", 0, AV_OPT_TYPE_CONST, { .i64 = DURATION_LONGEST }, INT_MIN, INT_MAX, A|F, "duration" },
  164. { "shortest", "Duration of shortest input.", 0, AV_OPT_TYPE_CONST, { .i64 = DURATION_SHORTEST }, INT_MIN, INT_MAX, A|F, "duration" },
  165. { "first", "Duration of first input.", 0, AV_OPT_TYPE_CONST, { .i64 = DURATION_FIRST }, INT_MIN, INT_MAX, A|F, "duration" },
  166. { "dropout_transition", "Transition time, in seconds, for volume "
  167. "renormalization when an input stream ends.",
  168. OFFSET(dropout_transition), AV_OPT_TYPE_FLOAT, { .dbl = 2.0 }, 0, INT_MAX, A|F },
  169. { NULL },
  170. };
  171. AVFILTER_DEFINE_CLASS(amix);
  172. /**
  173. * Update the scaling factors to apply to each input during mixing.
  174. *
  175. * This balances the full volume range between active inputs and handles
  176. * volume transitions when EOF is encountered on an input but mixing continues
  177. * with the remaining inputs.
  178. */
  179. static void calculate_scales(MixContext *s, int nb_samples)
  180. {
  181. int i;
  182. if (s->scale_norm > s->active_inputs) {
  183. s->scale_norm -= nb_samples / (s->dropout_transition * s->sample_rate);
  184. s->scale_norm = FFMAX(s->scale_norm, s->active_inputs);
  185. }
  186. for (i = 0; i < s->nb_inputs; i++) {
  187. if (s->input_state[i] == INPUT_ON)
  188. s->input_scale[i] = 1.0f / s->scale_norm;
  189. else
  190. s->input_scale[i] = 0.0f;
  191. }
  192. }
  193. static int config_output(AVFilterLink *outlink)
  194. {
  195. AVFilterContext *ctx = outlink->src;
  196. MixContext *s = ctx->priv;
  197. int i;
  198. char buf[64];
  199. s->planar = av_sample_fmt_is_planar(outlink->format);
  200. s->sample_rate = outlink->sample_rate;
  201. outlink->time_base = (AVRational){ 1, outlink->sample_rate };
  202. s->next_pts = AV_NOPTS_VALUE;
  203. s->frame_list = av_mallocz(sizeof(*s->frame_list));
  204. if (!s->frame_list)
  205. return AVERROR(ENOMEM);
  206. s->fifos = av_mallocz(s->nb_inputs * sizeof(*s->fifos));
  207. if (!s->fifos)
  208. return AVERROR(ENOMEM);
  209. s->nb_channels = av_get_channel_layout_nb_channels(outlink->channel_layout);
  210. for (i = 0; i < s->nb_inputs; i++) {
  211. s->fifos[i] = av_audio_fifo_alloc(outlink->format, s->nb_channels, 1024);
  212. if (!s->fifos[i])
  213. return AVERROR(ENOMEM);
  214. }
  215. s->input_state = av_malloc(s->nb_inputs);
  216. if (!s->input_state)
  217. return AVERROR(ENOMEM);
  218. memset(s->input_state, INPUT_ON, s->nb_inputs);
  219. s->active_inputs = s->nb_inputs;
  220. s->input_scale = av_mallocz(s->nb_inputs * sizeof(*s->input_scale));
  221. if (!s->input_scale)
  222. return AVERROR(ENOMEM);
  223. s->scale_norm = s->active_inputs;
  224. calculate_scales(s, 0);
  225. av_get_channel_layout_string(buf, sizeof(buf), -1, outlink->channel_layout);
  226. av_log(ctx, AV_LOG_VERBOSE,
  227. "inputs:%d fmt:%s srate:%d cl:%s\n", s->nb_inputs,
  228. av_get_sample_fmt_name(outlink->format), outlink->sample_rate, buf);
  229. return 0;
  230. }
  231. /**
  232. * Read samples from the input FIFOs, mix, and write to the output link.
  233. */
  234. static int output_frame(AVFilterLink *outlink, int nb_samples)
  235. {
  236. AVFilterContext *ctx = outlink->src;
  237. MixContext *s = ctx->priv;
  238. AVFilterBufferRef *out_buf, *in_buf;
  239. int i;
  240. calculate_scales(s, nb_samples);
  241. out_buf = ff_get_audio_buffer(outlink, AV_PERM_WRITE, nb_samples);
  242. if (!out_buf)
  243. return AVERROR(ENOMEM);
  244. in_buf = ff_get_audio_buffer(outlink, AV_PERM_WRITE, nb_samples);
  245. if (!in_buf) {
  246. avfilter_unref_buffer(out_buf);
  247. return AVERROR(ENOMEM);
  248. }
  249. for (i = 0; i < s->nb_inputs; i++) {
  250. if (s->input_state[i] == INPUT_ON) {
  251. int planes, plane_size, p;
  252. av_audio_fifo_read(s->fifos[i], (void **)in_buf->extended_data,
  253. nb_samples);
  254. planes = s->planar ? s->nb_channels : 1;
  255. plane_size = nb_samples * (s->planar ? 1 : s->nb_channels);
  256. plane_size = FFALIGN(plane_size, 16);
  257. for (p = 0; p < planes; p++) {
  258. s->fdsp.vector_fmac_scalar((float *)out_buf->extended_data[p],
  259. (float *) in_buf->extended_data[p],
  260. s->input_scale[i], plane_size);
  261. }
  262. }
  263. }
  264. avfilter_unref_buffer(in_buf);
  265. out_buf->pts = s->next_pts;
  266. if (s->next_pts != AV_NOPTS_VALUE)
  267. s->next_pts += nb_samples;
  268. return ff_filter_frame(outlink, out_buf);
  269. }
  270. /**
  271. * Returns the smallest number of samples available in the input FIFOs other
  272. * than that of the first input.
  273. */
  274. static int get_available_samples(MixContext *s)
  275. {
  276. int i;
  277. int available_samples = INT_MAX;
  278. av_assert0(s->nb_inputs > 1);
  279. for (i = 1; i < s->nb_inputs; i++) {
  280. int nb_samples;
  281. if (s->input_state[i] == INPUT_OFF)
  282. continue;
  283. nb_samples = av_audio_fifo_size(s->fifos[i]);
  284. available_samples = FFMIN(available_samples, nb_samples);
  285. }
  286. if (available_samples == INT_MAX)
  287. return 0;
  288. return available_samples;
  289. }
  290. /**
  291. * Requests a frame, if needed, from each input link other than the first.
  292. */
  293. static int request_samples(AVFilterContext *ctx, int min_samples)
  294. {
  295. MixContext *s = ctx->priv;
  296. int i, ret;
  297. av_assert0(s->nb_inputs > 1);
  298. for (i = 1; i < s->nb_inputs; i++) {
  299. ret = 0;
  300. if (s->input_state[i] == INPUT_OFF)
  301. continue;
  302. while (!ret && av_audio_fifo_size(s->fifos[i]) < min_samples)
  303. ret = ff_request_frame(ctx->inputs[i]);
  304. if (ret == AVERROR_EOF) {
  305. if (av_audio_fifo_size(s->fifos[i]) == 0) {
  306. s->input_state[i] = INPUT_OFF;
  307. continue;
  308. }
  309. } else if (ret < 0)
  310. return ret;
  311. }
  312. return 0;
  313. }
  314. /**
  315. * Calculates the number of active inputs and determines EOF based on the
  316. * duration option.
  317. *
  318. * @return 0 if mixing should continue, or AVERROR_EOF if mixing should stop.
  319. */
  320. static int calc_active_inputs(MixContext *s)
  321. {
  322. int i;
  323. int active_inputs = 0;
  324. for (i = 0; i < s->nb_inputs; i++)
  325. active_inputs += !!(s->input_state[i] != INPUT_OFF);
  326. s->active_inputs = active_inputs;
  327. if (!active_inputs ||
  328. (s->duration_mode == DURATION_FIRST && s->input_state[0] == INPUT_OFF) ||
  329. (s->duration_mode == DURATION_SHORTEST && active_inputs != s->nb_inputs))
  330. return AVERROR_EOF;
  331. return 0;
  332. }
  333. static int request_frame(AVFilterLink *outlink)
  334. {
  335. AVFilterContext *ctx = outlink->src;
  336. MixContext *s = ctx->priv;
  337. int ret;
  338. int wanted_samples, available_samples;
  339. ret = calc_active_inputs(s);
  340. if (ret < 0)
  341. return ret;
  342. if (s->input_state[0] == INPUT_OFF) {
  343. ret = request_samples(ctx, 1);
  344. if (ret < 0)
  345. return ret;
  346. ret = calc_active_inputs(s);
  347. if (ret < 0)
  348. return ret;
  349. available_samples = get_available_samples(s);
  350. if (!available_samples)
  351. return AVERROR(EAGAIN);
  352. return output_frame(outlink, available_samples);
  353. }
  354. if (s->frame_list->nb_frames == 0) {
  355. ret = ff_request_frame(ctx->inputs[0]);
  356. if (ret == AVERROR_EOF) {
  357. s->input_state[0] = INPUT_OFF;
  358. if (s->nb_inputs == 1)
  359. return AVERROR_EOF;
  360. else
  361. return AVERROR(EAGAIN);
  362. } else if (ret < 0)
  363. return ret;
  364. }
  365. av_assert0(s->frame_list->nb_frames > 0);
  366. wanted_samples = frame_list_next_frame_size(s->frame_list);
  367. if (s->active_inputs > 1) {
  368. ret = request_samples(ctx, wanted_samples);
  369. if (ret < 0)
  370. return ret;
  371. ret = calc_active_inputs(s);
  372. if (ret < 0)
  373. return ret;
  374. }
  375. if (s->active_inputs > 1) {
  376. available_samples = get_available_samples(s);
  377. if (!available_samples)
  378. return AVERROR(EAGAIN);
  379. available_samples = FFMIN(available_samples, wanted_samples);
  380. } else {
  381. available_samples = wanted_samples;
  382. }
  383. s->next_pts = frame_list_next_pts(s->frame_list);
  384. frame_list_remove_samples(s->frame_list, available_samples);
  385. return output_frame(outlink, available_samples);
  386. }
  387. static int filter_frame(AVFilterLink *inlink, AVFilterBufferRef *buf)
  388. {
  389. AVFilterContext *ctx = inlink->dst;
  390. MixContext *s = ctx->priv;
  391. AVFilterLink *outlink = ctx->outputs[0];
  392. int i, ret = 0;
  393. for (i = 0; i < ctx->nb_inputs; i++)
  394. if (ctx->inputs[i] == inlink)
  395. break;
  396. if (i >= ctx->nb_inputs) {
  397. av_log(ctx, AV_LOG_ERROR, "unknown input link\n");
  398. ret = AVERROR(EINVAL);
  399. goto fail;
  400. }
  401. if (i == 0) {
  402. int64_t pts = av_rescale_q(buf->pts, inlink->time_base,
  403. outlink->time_base);
  404. ret = frame_list_add_frame(s->frame_list, buf->audio->nb_samples, pts);
  405. if (ret < 0)
  406. goto fail;
  407. }
  408. ret = av_audio_fifo_write(s->fifos[i], (void **)buf->extended_data,
  409. buf->audio->nb_samples);
  410. fail:
  411. avfilter_unref_buffer(buf);
  412. return ret;
  413. }
  414. static int init(AVFilterContext *ctx, const char *args)
  415. {
  416. MixContext *s = ctx->priv;
  417. int i, ret;
  418. s->class = &amix_class;
  419. av_opt_set_defaults(s);
  420. if ((ret = av_set_options_string(s, args, "=", ":")) < 0)
  421. return ret;
  422. av_opt_free(s);
  423. for (i = 0; i < s->nb_inputs; i++) {
  424. char name[32];
  425. AVFilterPad pad = { 0 };
  426. snprintf(name, sizeof(name), "input%d", i);
  427. pad.type = AVMEDIA_TYPE_AUDIO;
  428. pad.name = av_strdup(name);
  429. pad.filter_frame = filter_frame;
  430. ff_insert_inpad(ctx, i, &pad);
  431. }
  432. avpriv_float_dsp_init(&s->fdsp, 0);
  433. return 0;
  434. }
  435. static void uninit(AVFilterContext *ctx)
  436. {
  437. int i;
  438. MixContext *s = ctx->priv;
  439. if (s->fifos) {
  440. for (i = 0; i < s->nb_inputs; i++)
  441. av_audio_fifo_free(s->fifos[i]);
  442. av_freep(&s->fifos);
  443. }
  444. frame_list_clear(s->frame_list);
  445. av_freep(&s->frame_list);
  446. av_freep(&s->input_state);
  447. av_freep(&s->input_scale);
  448. for (i = 0; i < ctx->nb_inputs; i++)
  449. av_freep(&ctx->input_pads[i].name);
  450. }
  451. static int query_formats(AVFilterContext *ctx)
  452. {
  453. AVFilterFormats *formats = NULL;
  454. ff_add_format(&formats, AV_SAMPLE_FMT_FLT);
  455. ff_add_format(&formats, AV_SAMPLE_FMT_FLTP);
  456. ff_set_common_formats(ctx, formats);
  457. ff_set_common_channel_layouts(ctx, ff_all_channel_layouts());
  458. ff_set_common_samplerates(ctx, ff_all_samplerates());
  459. return 0;
  460. }
  461. static const AVFilterPad avfilter_af_amix_outputs[] = {
  462. {
  463. .name = "default",
  464. .type = AVMEDIA_TYPE_AUDIO,
  465. .config_props = config_output,
  466. .request_frame = request_frame
  467. },
  468. { NULL }
  469. };
  470. AVFilter avfilter_af_amix = {
  471. .name = "amix",
  472. .description = NULL_IF_CONFIG_SMALL("Audio mixing."),
  473. .priv_size = sizeof(MixContext),
  474. .init = init,
  475. .uninit = uninit,
  476. .query_formats = query_formats,
  477. .inputs = NULL,
  478. .outputs = avfilter_af_amix_outputs,
  479. .priv_class = &amix_class,
  480. };