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.

647 lines
20KB

  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. #define T AV_OPT_FLAG_RUNTIME_PARAM
  165. static const AVOption amix_options[] = {
  166. { "inputs", "Number of inputs.",
  167. OFFSET(nb_inputs), AV_OPT_TYPE_INT, { .i64 = 2 }, 1, INT16_MAX, A|F },
  168. { "duration", "How to determine the end-of-stream.",
  169. OFFSET(duration_mode), AV_OPT_TYPE_INT, { .i64 = DURATION_LONGEST }, 0, 2, A|F, "duration" },
  170. { "longest", "Duration of longest input.", 0, AV_OPT_TYPE_CONST, { .i64 = DURATION_LONGEST }, 0, 0, A|F, "duration" },
  171. { "shortest", "Duration of shortest input.", 0, AV_OPT_TYPE_CONST, { .i64 = DURATION_SHORTEST }, 0, 0, A|F, "duration" },
  172. { "first", "Duration of first input.", 0, AV_OPT_TYPE_CONST, { .i64 = DURATION_FIRST }, 0, 0, A|F, "duration" },
  173. { "dropout_transition", "Transition time, in seconds, for volume "
  174. "renormalization when an input stream ends.",
  175. OFFSET(dropout_transition), AV_OPT_TYPE_FLOAT, { .dbl = 2.0 }, 0, INT_MAX, A|F },
  176. { "weights", "Set weight for each input.",
  177. OFFSET(weights_str), AV_OPT_TYPE_STRING, {.str="1 1"}, 0, 0, A|F|T },
  178. { NULL }
  179. };
  180. AVFILTER_DEFINE_CLASS(amix);
  181. /**
  182. * Update the scaling factors to apply to each input during mixing.
  183. *
  184. * This balances the full volume range between active inputs and handles
  185. * volume transitions when EOF is encountered on an input but mixing continues
  186. * with the remaining inputs.
  187. */
  188. static void calculate_scales(MixContext *s, int nb_samples)
  189. {
  190. float weight_sum = 0.f;
  191. int i;
  192. for (i = 0; i < s->nb_inputs; i++)
  193. if (s->input_state[i] & INPUT_ON)
  194. weight_sum += FFABS(s->weights[i]);
  195. for (i = 0; i < s->nb_inputs; i++) {
  196. if (s->input_state[i] & INPUT_ON) {
  197. if (s->scale_norm[i] > weight_sum / FFABS(s->weights[i])) {
  198. s->scale_norm[i] -= ((s->weight_sum / FFABS(s->weights[i])) / s->nb_inputs) *
  199. nb_samples / (s->dropout_transition * s->sample_rate);
  200. s->scale_norm[i] = FFMAX(s->scale_norm[i], weight_sum / FFABS(s->weights[i]));
  201. }
  202. }
  203. }
  204. for (i = 0; i < s->nb_inputs; i++) {
  205. if (s->input_state[i] & INPUT_ON)
  206. s->input_scale[i] = 1.0f / s->scale_norm[i] * FFSIGN(s->weights[i]);
  207. else
  208. s->input_scale[i] = 0.0f;
  209. }
  210. }
  211. static int config_output(AVFilterLink *outlink)
  212. {
  213. AVFilterContext *ctx = outlink->src;
  214. MixContext *s = ctx->priv;
  215. int i;
  216. char buf[64];
  217. s->planar = av_sample_fmt_is_planar(outlink->format);
  218. s->sample_rate = outlink->sample_rate;
  219. outlink->time_base = (AVRational){ 1, outlink->sample_rate };
  220. s->next_pts = AV_NOPTS_VALUE;
  221. s->frame_list = av_mallocz(sizeof(*s->frame_list));
  222. if (!s->frame_list)
  223. return AVERROR(ENOMEM);
  224. s->fifos = av_mallocz_array(s->nb_inputs, sizeof(*s->fifos));
  225. if (!s->fifos)
  226. return AVERROR(ENOMEM);
  227. s->nb_channels = outlink->channels;
  228. for (i = 0; i < s->nb_inputs; i++) {
  229. s->fifos[i] = av_audio_fifo_alloc(outlink->format, s->nb_channels, 1024);
  230. if (!s->fifos[i])
  231. return AVERROR(ENOMEM);
  232. }
  233. s->input_state = av_malloc(s->nb_inputs);
  234. if (!s->input_state)
  235. return AVERROR(ENOMEM);
  236. memset(s->input_state, INPUT_ON, s->nb_inputs);
  237. s->active_inputs = s->nb_inputs;
  238. s->input_scale = av_mallocz_array(s->nb_inputs, sizeof(*s->input_scale));
  239. s->scale_norm = av_mallocz_array(s->nb_inputs, sizeof(*s->scale_norm));
  240. if (!s->input_scale || !s->scale_norm)
  241. return AVERROR(ENOMEM);
  242. for (i = 0; i < s->nb_inputs; i++)
  243. s->scale_norm[i] = s->weight_sum / FFABS(s->weights[i]);
  244. calculate_scales(s, 0);
  245. av_get_channel_layout_string(buf, sizeof(buf), -1, outlink->channel_layout);
  246. av_log(ctx, AV_LOG_VERBOSE,
  247. "inputs:%d fmt:%s srate:%d cl:%s\n", s->nb_inputs,
  248. av_get_sample_fmt_name(outlink->format), outlink->sample_rate, buf);
  249. return 0;
  250. }
  251. /**
  252. * Read samples from the input FIFOs, mix, and write to the output link.
  253. */
  254. static int output_frame(AVFilterLink *outlink)
  255. {
  256. AVFilterContext *ctx = outlink->src;
  257. MixContext *s = ctx->priv;
  258. AVFrame *out_buf, *in_buf;
  259. int nb_samples, ns, i;
  260. if (s->input_state[0] & INPUT_ON) {
  261. /* first input live: use the corresponding frame size */
  262. nb_samples = frame_list_next_frame_size(s->frame_list);
  263. for (i = 1; i < s->nb_inputs; i++) {
  264. if (s->input_state[i] & INPUT_ON) {
  265. ns = av_audio_fifo_size(s->fifos[i]);
  266. if (ns < nb_samples) {
  267. if (!(s->input_state[i] & INPUT_EOF))
  268. /* unclosed input with not enough samples */
  269. return 0;
  270. /* closed input to drain */
  271. nb_samples = ns;
  272. }
  273. }
  274. }
  275. s->next_pts = frame_list_next_pts(s->frame_list);
  276. } else {
  277. /* first input closed: use the available samples */
  278. nb_samples = INT_MAX;
  279. for (i = 1; i < s->nb_inputs; i++) {
  280. if (s->input_state[i] & INPUT_ON) {
  281. ns = av_audio_fifo_size(s->fifos[i]);
  282. nb_samples = FFMIN(nb_samples, ns);
  283. }
  284. }
  285. if (nb_samples == INT_MAX) {
  286. ff_outlink_set_status(outlink, AVERROR_EOF, s->next_pts);
  287. return 0;
  288. }
  289. }
  290. frame_list_remove_samples(s->frame_list, nb_samples);
  291. calculate_scales(s, nb_samples);
  292. if (nb_samples == 0)
  293. return 0;
  294. out_buf = ff_get_audio_buffer(outlink, nb_samples);
  295. if (!out_buf)
  296. return AVERROR(ENOMEM);
  297. in_buf = ff_get_audio_buffer(outlink, nb_samples);
  298. if (!in_buf) {
  299. av_frame_free(&out_buf);
  300. return AVERROR(ENOMEM);
  301. }
  302. for (i = 0; i < s->nb_inputs; i++) {
  303. if (s->input_state[i] & INPUT_ON) {
  304. int planes, plane_size, p;
  305. av_audio_fifo_read(s->fifos[i], (void **)in_buf->extended_data,
  306. nb_samples);
  307. planes = s->planar ? s->nb_channels : 1;
  308. plane_size = nb_samples * (s->planar ? 1 : s->nb_channels);
  309. plane_size = FFALIGN(plane_size, 16);
  310. if (out_buf->format == AV_SAMPLE_FMT_FLT ||
  311. out_buf->format == AV_SAMPLE_FMT_FLTP) {
  312. for (p = 0; p < planes; p++) {
  313. s->fdsp->vector_fmac_scalar((float *)out_buf->extended_data[p],
  314. (float *) in_buf->extended_data[p],
  315. s->input_scale[i], plane_size);
  316. }
  317. } else {
  318. for (p = 0; p < planes; p++) {
  319. s->fdsp->vector_dmac_scalar((double *)out_buf->extended_data[p],
  320. (double *) in_buf->extended_data[p],
  321. s->input_scale[i], plane_size);
  322. }
  323. }
  324. }
  325. }
  326. av_frame_free(&in_buf);
  327. out_buf->pts = s->next_pts;
  328. if (s->next_pts != AV_NOPTS_VALUE)
  329. s->next_pts += nb_samples;
  330. return ff_filter_frame(outlink, out_buf);
  331. }
  332. /**
  333. * Requests a frame, if needed, from each input link other than the first.
  334. */
  335. static int request_samples(AVFilterContext *ctx, int min_samples)
  336. {
  337. MixContext *s = ctx->priv;
  338. int i;
  339. av_assert0(s->nb_inputs > 1);
  340. for (i = 1; i < s->nb_inputs; i++) {
  341. if (!(s->input_state[i] & INPUT_ON) ||
  342. (s->input_state[i] & INPUT_EOF))
  343. continue;
  344. if (av_audio_fifo_size(s->fifos[i]) >= min_samples)
  345. continue;
  346. ff_inlink_request_frame(ctx->inputs[i]);
  347. }
  348. return output_frame(ctx->outputs[0]);
  349. }
  350. /**
  351. * Calculates the number of active inputs and determines EOF based on the
  352. * duration option.
  353. *
  354. * @return 0 if mixing should continue, or AVERROR_EOF if mixing should stop.
  355. */
  356. static int calc_active_inputs(MixContext *s)
  357. {
  358. int i;
  359. int active_inputs = 0;
  360. for (i = 0; i < s->nb_inputs; i++)
  361. active_inputs += !!(s->input_state[i] & INPUT_ON);
  362. s->active_inputs = active_inputs;
  363. if (!active_inputs ||
  364. (s->duration_mode == DURATION_FIRST && !(s->input_state[0] & INPUT_ON)) ||
  365. (s->duration_mode == DURATION_SHORTEST && active_inputs != s->nb_inputs))
  366. return AVERROR_EOF;
  367. return 0;
  368. }
  369. static int activate(AVFilterContext *ctx)
  370. {
  371. AVFilterLink *outlink = ctx->outputs[0];
  372. MixContext *s = ctx->priv;
  373. AVFrame *buf = NULL;
  374. int i, ret;
  375. FF_FILTER_FORWARD_STATUS_BACK_ALL(outlink, ctx);
  376. for (i = 0; i < s->nb_inputs; i++) {
  377. AVFilterLink *inlink = ctx->inputs[i];
  378. if ((ret = ff_inlink_consume_frame(ctx->inputs[i], &buf)) > 0) {
  379. if (i == 0) {
  380. int64_t pts = av_rescale_q(buf->pts, inlink->time_base,
  381. outlink->time_base);
  382. ret = frame_list_add_frame(s->frame_list, buf->nb_samples, pts);
  383. if (ret < 0) {
  384. av_frame_free(&buf);
  385. return ret;
  386. }
  387. }
  388. ret = av_audio_fifo_write(s->fifos[i], (void **)buf->extended_data,
  389. buf->nb_samples);
  390. if (ret < 0) {
  391. av_frame_free(&buf);
  392. return ret;
  393. }
  394. av_frame_free(&buf);
  395. ret = output_frame(outlink);
  396. if (ret < 0)
  397. return ret;
  398. }
  399. }
  400. for (i = 0; i < s->nb_inputs; i++) {
  401. int64_t pts;
  402. int status;
  403. if (ff_inlink_acknowledge_status(ctx->inputs[i], &status, &pts)) {
  404. if (status == AVERROR_EOF) {
  405. if (i == 0) {
  406. s->input_state[i] = 0;
  407. if (s->nb_inputs == 1) {
  408. ff_outlink_set_status(outlink, status, pts);
  409. return 0;
  410. }
  411. } else {
  412. s->input_state[i] |= INPUT_EOF;
  413. if (av_audio_fifo_size(s->fifos[i]) == 0) {
  414. s->input_state[i] = 0;
  415. }
  416. }
  417. }
  418. }
  419. }
  420. if (calc_active_inputs(s)) {
  421. ff_outlink_set_status(outlink, AVERROR_EOF, s->next_pts);
  422. return 0;
  423. }
  424. if (ff_outlink_frame_wanted(outlink)) {
  425. int wanted_samples;
  426. if (!(s->input_state[0] & INPUT_ON))
  427. return request_samples(ctx, 1);
  428. if (s->frame_list->nb_frames == 0) {
  429. ff_inlink_request_frame(ctx->inputs[0]);
  430. return 0;
  431. }
  432. av_assert0(s->frame_list->nb_frames > 0);
  433. wanted_samples = frame_list_next_frame_size(s->frame_list);
  434. return request_samples(ctx, wanted_samples);
  435. }
  436. return 0;
  437. }
  438. static void parse_weights(AVFilterContext *ctx)
  439. {
  440. MixContext *s = ctx->priv;
  441. float last_weight = 1.f;
  442. char *p;
  443. int i;
  444. s->weight_sum = 0.f;
  445. p = s->weights_str;
  446. for (i = 0; i < s->nb_inputs; i++) {
  447. last_weight = av_strtod(p, &p);
  448. s->weights[i] = last_weight;
  449. s->weight_sum += FFABS(last_weight);
  450. if (p && *p) {
  451. p++;
  452. } else {
  453. i++;
  454. break;
  455. }
  456. }
  457. for (; i < s->nb_inputs; i++) {
  458. s->weights[i] = last_weight;
  459. s->weight_sum += FFABS(last_weight);
  460. }
  461. }
  462. static av_cold int init(AVFilterContext *ctx)
  463. {
  464. MixContext *s = ctx->priv;
  465. int i, ret;
  466. for (i = 0; i < s->nb_inputs; i++) {
  467. AVFilterPad pad = { 0 };
  468. pad.type = AVMEDIA_TYPE_AUDIO;
  469. pad.name = av_asprintf("input%d", i);
  470. if (!pad.name)
  471. return AVERROR(ENOMEM);
  472. if ((ret = ff_insert_inpad(ctx, i, &pad)) < 0) {
  473. av_freep(&pad.name);
  474. return ret;
  475. }
  476. }
  477. s->fdsp = avpriv_float_dsp_alloc(0);
  478. if (!s->fdsp)
  479. return AVERROR(ENOMEM);
  480. s->weights = av_mallocz_array(s->nb_inputs, sizeof(*s->weights));
  481. if (!s->weights)
  482. return AVERROR(ENOMEM);
  483. parse_weights(ctx);
  484. return 0;
  485. }
  486. static av_cold void uninit(AVFilterContext *ctx)
  487. {
  488. int i;
  489. MixContext *s = ctx->priv;
  490. if (s->fifos) {
  491. for (i = 0; i < s->nb_inputs; i++)
  492. av_audio_fifo_free(s->fifos[i]);
  493. av_freep(&s->fifos);
  494. }
  495. frame_list_clear(s->frame_list);
  496. av_freep(&s->frame_list);
  497. av_freep(&s->input_state);
  498. av_freep(&s->input_scale);
  499. av_freep(&s->scale_norm);
  500. av_freep(&s->weights);
  501. av_freep(&s->fdsp);
  502. for (i = 0; i < ctx->nb_inputs; i++)
  503. av_freep(&ctx->input_pads[i].name);
  504. }
  505. static int query_formats(AVFilterContext *ctx)
  506. {
  507. static const enum AVSampleFormat sample_fmts[] = {
  508. AV_SAMPLE_FMT_FLT, AV_SAMPLE_FMT_FLTP,
  509. AV_SAMPLE_FMT_DBL, AV_SAMPLE_FMT_DBLP,
  510. AV_SAMPLE_FMT_NONE
  511. };
  512. int ret;
  513. if ((ret = ff_set_common_formats(ctx, ff_make_format_list(sample_fmts))) < 0 ||
  514. (ret = ff_set_common_samplerates(ctx, ff_all_samplerates())) < 0)
  515. return ret;
  516. return ff_set_common_channel_layouts(ctx, ff_all_channel_counts());
  517. }
  518. static int process_command(AVFilterContext *ctx, const char *cmd, const char *args,
  519. char *res, int res_len, int flags)
  520. {
  521. MixContext *s = ctx->priv;
  522. int ret;
  523. ret = ff_filter_process_command(ctx, cmd, args, res, res_len, flags);
  524. if (ret < 0)
  525. return ret;
  526. parse_weights(ctx);
  527. for (int i = 0; i < s->nb_inputs; i++)
  528. s->scale_norm[i] = s->weight_sum / FFABS(s->weights[i]);
  529. calculate_scales(s, 0);
  530. return 0;
  531. }
  532. static const AVFilterPad avfilter_af_amix_outputs[] = {
  533. {
  534. .name = "default",
  535. .type = AVMEDIA_TYPE_AUDIO,
  536. .config_props = config_output,
  537. },
  538. { NULL }
  539. };
  540. AVFilter ff_af_amix = {
  541. .name = "amix",
  542. .description = NULL_IF_CONFIG_SMALL("Audio mixing."),
  543. .priv_size = sizeof(MixContext),
  544. .priv_class = &amix_class,
  545. .init = init,
  546. .uninit = uninit,
  547. .activate = activate,
  548. .query_formats = query_formats,
  549. .inputs = NULL,
  550. .outputs = avfilter_af_amix_outputs,
  551. .process_command = process_command,
  552. .flags = AVFILTER_FLAG_DYNAMIC_INPUTS,
  553. };