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.

627 lines
19KB

  1. /*
  2. * Audio Mix Filter
  3. * Copyright (c) 2012 Justin Ruggles <justin.ruggles@gmail.com>
  4. *
  5. * This file is part of FFmpeg.
  6. *
  7. * FFmpeg 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. * FFmpeg 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 FFmpeg; 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/attributes.h"
  30. #include "libavutil/audio_fifo.h"
  31. #include "libavutil/avassert.h"
  32. #include "libavutil/avstring.h"
  33. #include "libavutil/channel_layout.h"
  34. #include "libavutil/common.h"
  35. #include "libavutil/eval.h"
  36. #include "libavutil/float_dsp.h"
  37. #include "libavutil/mathematics.h"
  38. #include "libavutil/opt.h"
  39. #include "libavutil/samplefmt.h"
  40. #include "audio.h"
  41. #include "avfilter.h"
  42. #include "filters.h"
  43. #include "formats.h"
  44. #include "internal.h"
  45. #define INPUT_ON 1 /**< input is active */
  46. #define INPUT_EOF 2 /**< input has reached EOF (may still be active) */
  47. #define DURATION_LONGEST 0
  48. #define DURATION_SHORTEST 1
  49. #define DURATION_FIRST 2
  50. typedef struct FrameInfo {
  51. int nb_samples;
  52. int64_t pts;
  53. struct FrameInfo *next;
  54. } FrameInfo;
  55. /**
  56. * Linked list used to store timestamps and frame sizes of all frames in the
  57. * FIFO for the first input.
  58. *
  59. * This is needed to keep timestamps synchronized for the case where multiple
  60. * input frames are pushed to the filter for processing before a frame is
  61. * requested by the output link.
  62. */
  63. typedef struct FrameList {
  64. int nb_frames;
  65. int nb_samples;
  66. FrameInfo *list;
  67. FrameInfo *end;
  68. } FrameList;
  69. static void frame_list_clear(FrameList *frame_list)
  70. {
  71. if (frame_list) {
  72. while (frame_list->list) {
  73. FrameInfo *info = frame_list->list;
  74. frame_list->list = info->next;
  75. av_free(info);
  76. }
  77. frame_list->nb_frames = 0;
  78. frame_list->nb_samples = 0;
  79. frame_list->end = NULL;
  80. }
  81. }
  82. static int frame_list_next_frame_size(FrameList *frame_list)
  83. {
  84. if (!frame_list->list)
  85. return 0;
  86. return frame_list->list->nb_samples;
  87. }
  88. static int64_t frame_list_next_pts(FrameList *frame_list)
  89. {
  90. if (!frame_list->list)
  91. return AV_NOPTS_VALUE;
  92. return frame_list->list->pts;
  93. }
  94. static void frame_list_remove_samples(FrameList *frame_list, int nb_samples)
  95. {
  96. if (nb_samples >= frame_list->nb_samples) {
  97. frame_list_clear(frame_list);
  98. } else {
  99. int samples = nb_samples;
  100. while (samples > 0) {
  101. FrameInfo *info = frame_list->list;
  102. av_assert0(info);
  103. if (info->nb_samples <= samples) {
  104. samples -= info->nb_samples;
  105. frame_list->list = info->next;
  106. if (!frame_list->list)
  107. frame_list->end = NULL;
  108. frame_list->nb_frames--;
  109. frame_list->nb_samples -= info->nb_samples;
  110. av_free(info);
  111. } else {
  112. info->nb_samples -= samples;
  113. info->pts += samples;
  114. frame_list->nb_samples -= samples;
  115. samples = 0;
  116. }
  117. }
  118. }
  119. }
  120. static int frame_list_add_frame(FrameList *frame_list, int nb_samples, int64_t pts)
  121. {
  122. FrameInfo *info = av_malloc(sizeof(*info));
  123. if (!info)
  124. return AVERROR(ENOMEM);
  125. info->nb_samples = nb_samples;
  126. info->pts = pts;
  127. info->next = NULL;
  128. if (!frame_list->list) {
  129. frame_list->list = info;
  130. frame_list->end = info;
  131. } else {
  132. av_assert0(frame_list->end);
  133. frame_list->end->next = info;
  134. frame_list->end = info;
  135. }
  136. frame_list->nb_frames++;
  137. frame_list->nb_samples += nb_samples;
  138. return 0;
  139. }
  140. /* FIXME: use directly links fifo */
  141. typedef struct MixContext {
  142. const AVClass *class; /**< class for AVOptions */
  143. AVFloatDSPContext *fdsp;
  144. int nb_inputs; /**< number of inputs */
  145. int active_inputs; /**< number of input currently active */
  146. int duration_mode; /**< mode for determining duration */
  147. float dropout_transition; /**< transition time when an input drops out */
  148. char *weights_str; /**< string for custom weights for every input */
  149. int nb_channels; /**< number of channels */
  150. int sample_rate; /**< sample rate */
  151. int planar;
  152. AVAudioFifo **fifos; /**< audio fifo for each input */
  153. uint8_t *input_state; /**< current state of each input */
  154. float *input_scale; /**< mixing scale factor for each input */
  155. float *weights; /**< custom weights for every input */
  156. float weight_sum; /**< sum of custom weights for every input */
  157. float *scale_norm; /**< normalization factor for every input */
  158. int64_t next_pts; /**< calculated pts for next output frame */
  159. FrameList *frame_list; /**< list of frame info for the first input */
  160. } MixContext;
  161. #define OFFSET(x) offsetof(MixContext, x)
  162. #define A AV_OPT_FLAG_AUDIO_PARAM
  163. #define F AV_OPT_FLAG_FILTERING_PARAM
  164. static const AVOption amix_options[] = {
  165. { "inputs", "Number of inputs.",
  166. OFFSET(nb_inputs), AV_OPT_TYPE_INT, { .i64 = 2 }, 1, INT16_MAX, A|F },
  167. { "duration", "How to determine the end-of-stream.",
  168. OFFSET(duration_mode), AV_OPT_TYPE_INT, { .i64 = DURATION_LONGEST }, 0, 2, A|F, "duration" },
  169. { "longest", "Duration of longest input.", 0, AV_OPT_TYPE_CONST, { .i64 = DURATION_LONGEST }, 0, 0, A|F, "duration" },
  170. { "shortest", "Duration of shortest input.", 0, AV_OPT_TYPE_CONST, { .i64 = DURATION_SHORTEST }, 0, 0, A|F, "duration" },
  171. { "first", "Duration of first input.", 0, AV_OPT_TYPE_CONST, { .i64 = DURATION_FIRST }, 0, 0, A|F, "duration" },
  172. { "dropout_transition", "Transition time, in seconds, for volume "
  173. "renormalization when an input stream ends.",
  174. OFFSET(dropout_transition), AV_OPT_TYPE_FLOAT, { .dbl = 2.0 }, 0, INT_MAX, A|F },
  175. { "weights", "Set weight for each input.",
  176. OFFSET(weights_str), AV_OPT_TYPE_STRING, {.str="1 1"}, 0, 0, A|F },
  177. { NULL }
  178. };
  179. AVFILTER_DEFINE_CLASS(amix);
  180. /**
  181. * Update the scaling factors to apply to each input during mixing.
  182. *
  183. * This balances the full volume range between active inputs and handles
  184. * volume transitions when EOF is encountered on an input but mixing continues
  185. * with the remaining inputs.
  186. */
  187. static void calculate_scales(MixContext *s, int nb_samples)
  188. {
  189. float weight_sum = 0.f;
  190. int i;
  191. for (i = 0; i < s->nb_inputs; i++)
  192. if (s->input_state[i] & INPUT_ON)
  193. weight_sum += FFABS(s->weights[i]);
  194. for (i = 0; i < s->nb_inputs; i++) {
  195. if (s->input_state[i] & INPUT_ON) {
  196. if (s->scale_norm[i] > weight_sum / FFABS(s->weights[i])) {
  197. s->scale_norm[i] -= ((s->weight_sum / FFABS(s->weights[i])) / s->nb_inputs) *
  198. nb_samples / (s->dropout_transition * s->sample_rate);
  199. s->scale_norm[i] = FFMAX(s->scale_norm[i], weight_sum / FFABS(s->weights[i]));
  200. }
  201. }
  202. }
  203. for (i = 0; i < s->nb_inputs; i++) {
  204. if (s->input_state[i] & INPUT_ON)
  205. s->input_scale[i] = 1.0f / s->scale_norm[i] * FFSIGN(s->weights[i]);
  206. else
  207. s->input_scale[i] = 0.0f;
  208. }
  209. }
  210. static int config_output(AVFilterLink *outlink)
  211. {
  212. AVFilterContext *ctx = outlink->src;
  213. MixContext *s = ctx->priv;
  214. int i;
  215. char buf[64];
  216. s->planar = av_sample_fmt_is_planar(outlink->format);
  217. s->sample_rate = outlink->sample_rate;
  218. outlink->time_base = (AVRational){ 1, outlink->sample_rate };
  219. s->next_pts = AV_NOPTS_VALUE;
  220. s->frame_list = av_mallocz(sizeof(*s->frame_list));
  221. if (!s->frame_list)
  222. return AVERROR(ENOMEM);
  223. s->fifos = av_mallocz_array(s->nb_inputs, sizeof(*s->fifos));
  224. if (!s->fifos)
  225. return AVERROR(ENOMEM);
  226. s->nb_channels = outlink->channels;
  227. for (i = 0; i < s->nb_inputs; i++) {
  228. s->fifos[i] = av_audio_fifo_alloc(outlink->format, s->nb_channels, 1024);
  229. if (!s->fifos[i])
  230. return AVERROR(ENOMEM);
  231. }
  232. s->input_state = av_malloc(s->nb_inputs);
  233. if (!s->input_state)
  234. return AVERROR(ENOMEM);
  235. memset(s->input_state, INPUT_ON, s->nb_inputs);
  236. s->active_inputs = s->nb_inputs;
  237. s->input_scale = av_mallocz_array(s->nb_inputs, sizeof(*s->input_scale));
  238. s->scale_norm = av_mallocz_array(s->nb_inputs, sizeof(*s->scale_norm));
  239. if (!s->input_scale || !s->scale_norm)
  240. return AVERROR(ENOMEM);
  241. for (i = 0; i < s->nb_inputs; i++)
  242. s->scale_norm[i] = s->weight_sum / FFABS(s->weights[i]);
  243. calculate_scales(s, 0);
  244. av_get_channel_layout_string(buf, sizeof(buf), -1, outlink->channel_layout);
  245. av_log(ctx, AV_LOG_VERBOSE,
  246. "inputs:%d fmt:%s srate:%d cl:%s\n", s->nb_inputs,
  247. av_get_sample_fmt_name(outlink->format), outlink->sample_rate, buf);
  248. return 0;
  249. }
  250. /**
  251. * Read samples from the input FIFOs, mix, and write to the output link.
  252. */
  253. static int output_frame(AVFilterLink *outlink)
  254. {
  255. AVFilterContext *ctx = outlink->src;
  256. MixContext *s = ctx->priv;
  257. AVFrame *out_buf, *in_buf;
  258. int nb_samples, ns, i;
  259. if (s->input_state[0] & INPUT_ON) {
  260. /* first input live: use the corresponding frame size */
  261. nb_samples = frame_list_next_frame_size(s->frame_list);
  262. for (i = 1; i < s->nb_inputs; i++) {
  263. if (s->input_state[i] & INPUT_ON) {
  264. ns = av_audio_fifo_size(s->fifos[i]);
  265. if (ns < nb_samples) {
  266. if (!(s->input_state[i] & INPUT_EOF))
  267. /* unclosed input with not enough samples */
  268. return 0;
  269. /* closed input to drain */
  270. nb_samples = ns;
  271. }
  272. }
  273. }
  274. } else {
  275. /* first input closed: use the available samples */
  276. nb_samples = INT_MAX;
  277. for (i = 1; i < s->nb_inputs; i++) {
  278. if (s->input_state[i] & INPUT_ON) {
  279. ns = av_audio_fifo_size(s->fifos[i]);
  280. nb_samples = FFMIN(nb_samples, ns);
  281. }
  282. }
  283. if (nb_samples == INT_MAX) {
  284. ff_outlink_set_status(outlink, AVERROR_EOF, s->next_pts);
  285. return 0;
  286. }
  287. }
  288. s->next_pts = frame_list_next_pts(s->frame_list);
  289. frame_list_remove_samples(s->frame_list, nb_samples);
  290. calculate_scales(s, nb_samples);
  291. if (nb_samples == 0)
  292. return 0;
  293. out_buf = ff_get_audio_buffer(outlink, nb_samples);
  294. if (!out_buf)
  295. return AVERROR(ENOMEM);
  296. in_buf = ff_get_audio_buffer(outlink, nb_samples);
  297. if (!in_buf) {
  298. av_frame_free(&out_buf);
  299. return AVERROR(ENOMEM);
  300. }
  301. for (i = 0; i < s->nb_inputs; i++) {
  302. if (s->input_state[i] & INPUT_ON) {
  303. int planes, plane_size, p;
  304. av_audio_fifo_read(s->fifos[i], (void **)in_buf->extended_data,
  305. nb_samples);
  306. planes = s->planar ? s->nb_channels : 1;
  307. plane_size = nb_samples * (s->planar ? 1 : s->nb_channels);
  308. plane_size = FFALIGN(plane_size, 16);
  309. if (out_buf->format == AV_SAMPLE_FMT_FLT ||
  310. out_buf->format == AV_SAMPLE_FMT_FLTP) {
  311. for (p = 0; p < planes; p++) {
  312. s->fdsp->vector_fmac_scalar((float *)out_buf->extended_data[p],
  313. (float *) in_buf->extended_data[p],
  314. s->input_scale[i], plane_size);
  315. }
  316. } else {
  317. for (p = 0; p < planes; p++) {
  318. s->fdsp->vector_dmac_scalar((double *)out_buf->extended_data[p],
  319. (double *) in_buf->extended_data[p],
  320. s->input_scale[i], plane_size);
  321. }
  322. }
  323. }
  324. }
  325. av_frame_free(&in_buf);
  326. out_buf->pts = s->next_pts;
  327. if (s->next_pts != AV_NOPTS_VALUE)
  328. s->next_pts += nb_samples;
  329. return ff_filter_frame(outlink, out_buf);
  330. }
  331. /**
  332. * Requests a frame, if needed, from each input link other than the first.
  333. */
  334. static int request_samples(AVFilterContext *ctx, int min_samples)
  335. {
  336. MixContext *s = ctx->priv;
  337. int i;
  338. av_assert0(s->nb_inputs > 1);
  339. for (i = 1; i < s->nb_inputs; i++) {
  340. if (!(s->input_state[i] & INPUT_ON) ||
  341. (s->input_state[i] & INPUT_EOF))
  342. continue;
  343. if (av_audio_fifo_size(s->fifos[i]) >= min_samples)
  344. continue;
  345. ff_inlink_request_frame(ctx->inputs[i]);
  346. }
  347. return output_frame(ctx->outputs[0]);
  348. }
  349. /**
  350. * Calculates the number of active inputs and determines EOF based on the
  351. * duration option.
  352. *
  353. * @return 0 if mixing should continue, or AVERROR_EOF if mixing should stop.
  354. */
  355. static int calc_active_inputs(MixContext *s)
  356. {
  357. int i;
  358. int active_inputs = 0;
  359. for (i = 0; i < s->nb_inputs; i++)
  360. active_inputs += !!(s->input_state[i] & INPUT_ON);
  361. s->active_inputs = active_inputs;
  362. if (!active_inputs ||
  363. (s->duration_mode == DURATION_FIRST && !(s->input_state[0] & INPUT_ON)) ||
  364. (s->duration_mode == DURATION_SHORTEST && active_inputs != s->nb_inputs))
  365. return AVERROR_EOF;
  366. return 0;
  367. }
  368. static int activate(AVFilterContext *ctx)
  369. {
  370. AVFilterLink *outlink = ctx->outputs[0];
  371. MixContext *s = ctx->priv;
  372. AVFrame *buf = NULL;
  373. int i, ret;
  374. FF_FILTER_FORWARD_STATUS_BACK_ALL(outlink, ctx);
  375. for (i = 0; i < s->nb_inputs; i++) {
  376. AVFilterLink *inlink = ctx->inputs[i];
  377. if ((ret = ff_inlink_consume_frame(ctx->inputs[i], &buf)) > 0) {
  378. if (i == 0) {
  379. int64_t pts = av_rescale_q(buf->pts, inlink->time_base,
  380. outlink->time_base);
  381. ret = frame_list_add_frame(s->frame_list, buf->nb_samples, pts);
  382. if (ret < 0) {
  383. av_frame_free(&buf);
  384. return ret;
  385. }
  386. }
  387. ret = av_audio_fifo_write(s->fifos[i], (void **)buf->extended_data,
  388. buf->nb_samples);
  389. if (ret < 0) {
  390. av_frame_free(&buf);
  391. return ret;
  392. }
  393. av_frame_free(&buf);
  394. ret = output_frame(outlink);
  395. if (ret < 0)
  396. return ret;
  397. }
  398. }
  399. for (i = 0; i < s->nb_inputs; i++) {
  400. int64_t pts;
  401. int status;
  402. if (ff_inlink_acknowledge_status(ctx->inputs[i], &status, &pts)) {
  403. if (status == AVERROR_EOF) {
  404. if (i == 0) {
  405. s->input_state[i] = 0;
  406. if (s->nb_inputs == 1) {
  407. ff_outlink_set_status(outlink, status, pts);
  408. return 0;
  409. }
  410. } else {
  411. s->input_state[i] |= INPUT_EOF;
  412. if (av_audio_fifo_size(s->fifos[i]) == 0) {
  413. s->input_state[i] = 0;
  414. }
  415. }
  416. }
  417. }
  418. }
  419. if (calc_active_inputs(s)) {
  420. ff_outlink_set_status(outlink, AVERROR_EOF, s->next_pts);
  421. return 0;
  422. }
  423. if (ff_outlink_frame_wanted(outlink)) {
  424. int wanted_samples;
  425. if (!(s->input_state[0] & INPUT_ON))
  426. return request_samples(ctx, 1);
  427. if (s->frame_list->nb_frames == 0) {
  428. ff_inlink_request_frame(ctx->inputs[0]);
  429. return 0;
  430. }
  431. av_assert0(s->frame_list->nb_frames > 0);
  432. wanted_samples = frame_list_next_frame_size(s->frame_list);
  433. return request_samples(ctx, wanted_samples);
  434. }
  435. return 0;
  436. }
  437. static av_cold int init(AVFilterContext *ctx)
  438. {
  439. MixContext *s = ctx->priv;
  440. float last_weight = 1.f;
  441. int i, ret;
  442. char *p;
  443. for (i = 0; i < s->nb_inputs; i++) {
  444. AVFilterPad pad = { 0 };
  445. pad.type = AVMEDIA_TYPE_AUDIO;
  446. pad.name = av_asprintf("input%d", i);
  447. if (!pad.name)
  448. return AVERROR(ENOMEM);
  449. if ((ret = ff_insert_inpad(ctx, i, &pad)) < 0) {
  450. av_freep(&pad.name);
  451. return ret;
  452. }
  453. }
  454. s->fdsp = avpriv_float_dsp_alloc(0);
  455. if (!s->fdsp)
  456. return AVERROR(ENOMEM);
  457. s->weights = av_mallocz_array(s->nb_inputs, sizeof(*s->weights));
  458. if (!s->weights)
  459. return AVERROR(ENOMEM);
  460. p = s->weights_str;
  461. for (i = 0; i < s->nb_inputs; i++) {
  462. last_weight = av_strtod(p, &p);
  463. s->weights[i] = last_weight;
  464. s->weight_sum += FFABS(last_weight);
  465. if (p && *p)
  466. p++;
  467. else
  468. break;
  469. }
  470. for (; i < s->nb_inputs; i++) {
  471. s->weights[i] = last_weight;
  472. s->weight_sum += FFABS(last_weight);
  473. }
  474. return 0;
  475. }
  476. static av_cold void uninit(AVFilterContext *ctx)
  477. {
  478. int i;
  479. MixContext *s = ctx->priv;
  480. if (s->fifos) {
  481. for (i = 0; i < s->nb_inputs; i++)
  482. av_audio_fifo_free(s->fifos[i]);
  483. av_freep(&s->fifos);
  484. }
  485. frame_list_clear(s->frame_list);
  486. av_freep(&s->frame_list);
  487. av_freep(&s->input_state);
  488. av_freep(&s->input_scale);
  489. av_freep(&s->scale_norm);
  490. av_freep(&s->weights);
  491. av_freep(&s->fdsp);
  492. for (i = 0; i < ctx->nb_inputs; i++)
  493. av_freep(&ctx->input_pads[i].name);
  494. }
  495. static int query_formats(AVFilterContext *ctx)
  496. {
  497. AVFilterFormats *formats = NULL;
  498. AVFilterChannelLayouts *layouts;
  499. int ret;
  500. layouts = ff_all_channel_counts();
  501. if (!layouts) {
  502. ret = AVERROR(ENOMEM);
  503. goto fail;
  504. }
  505. if ((ret = ff_add_format(&formats, AV_SAMPLE_FMT_FLT )) < 0 ||
  506. (ret = ff_add_format(&formats, AV_SAMPLE_FMT_FLTP)) < 0 ||
  507. (ret = ff_add_format(&formats, AV_SAMPLE_FMT_DBL )) < 0 ||
  508. (ret = ff_add_format(&formats, AV_SAMPLE_FMT_DBLP)) < 0 ||
  509. (ret = ff_set_common_formats (ctx, formats)) < 0 ||
  510. (ret = ff_set_common_channel_layouts(ctx, layouts)) < 0 ||
  511. (ret = ff_set_common_samplerates(ctx, ff_all_samplerates())) < 0)
  512. goto fail;
  513. return 0;
  514. fail:
  515. if (layouts)
  516. av_freep(&layouts->channel_layouts);
  517. av_freep(&layouts);
  518. return ret;
  519. }
  520. static const AVFilterPad avfilter_af_amix_outputs[] = {
  521. {
  522. .name = "default",
  523. .type = AVMEDIA_TYPE_AUDIO,
  524. .config_props = config_output,
  525. },
  526. { NULL }
  527. };
  528. AVFilter ff_af_amix = {
  529. .name = "amix",
  530. .description = NULL_IF_CONFIG_SMALL("Audio mixing."),
  531. .priv_size = sizeof(MixContext),
  532. .priv_class = &amix_class,
  533. .init = init,
  534. .uninit = uninit,
  535. .activate = activate,
  536. .query_formats = query_formats,
  537. .inputs = NULL,
  538. .outputs = avfilter_af_amix_outputs,
  539. .flags = AVFILTER_FLAG_DYNAMIC_INPUTS,
  540. };