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.

552 lines
16KB

  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/mathematics.h"
  34. #include "libavutil/opt.h"
  35. #include "libavutil/samplefmt.h"
  36. #include "audio.h"
  37. #include "avfilter.h"
  38. #include "formats.h"
  39. #include "internal.h"
  40. #define INPUT_OFF 0 /**< input has reached EOF */
  41. #define INPUT_ON 1 /**< input is active */
  42. #define INPUT_INACTIVE 2 /**< input is on, but is currently inactive */
  43. #define DURATION_LONGEST 0
  44. #define DURATION_SHORTEST 1
  45. #define DURATION_FIRST 2
  46. typedef struct FrameInfo {
  47. int nb_samples;
  48. int64_t pts;
  49. struct FrameInfo *next;
  50. } FrameInfo;
  51. /**
  52. * Linked list used to store timestamps and frame sizes of all frames in the
  53. * FIFO for the first input.
  54. *
  55. * This is needed to keep timestamps synchronized for the case where multiple
  56. * input frames are pushed to the filter for processing before a frame is
  57. * requested by the output link.
  58. */
  59. typedef struct FrameList {
  60. int nb_frames;
  61. int nb_samples;
  62. FrameInfo *list;
  63. FrameInfo *end;
  64. } FrameList;
  65. static void frame_list_clear(FrameList *frame_list)
  66. {
  67. if (frame_list) {
  68. while (frame_list->list) {
  69. FrameInfo *info = frame_list->list;
  70. frame_list->list = info->next;
  71. av_free(info);
  72. }
  73. frame_list->nb_frames = 0;
  74. frame_list->nb_samples = 0;
  75. frame_list->end = NULL;
  76. }
  77. }
  78. static int frame_list_next_frame_size(FrameList *frame_list)
  79. {
  80. if (!frame_list->list)
  81. return 0;
  82. return frame_list->list->nb_samples;
  83. }
  84. static int64_t frame_list_next_pts(FrameList *frame_list)
  85. {
  86. if (!frame_list->list)
  87. return AV_NOPTS_VALUE;
  88. return frame_list->list->pts;
  89. }
  90. static void frame_list_remove_samples(FrameList *frame_list, int nb_samples)
  91. {
  92. if (nb_samples >= frame_list->nb_samples) {
  93. frame_list_clear(frame_list);
  94. } else {
  95. int samples = nb_samples;
  96. while (samples > 0) {
  97. FrameInfo *info = frame_list->list;
  98. av_assert0(info != NULL);
  99. if (info->nb_samples <= samples) {
  100. samples -= info->nb_samples;
  101. frame_list->list = info->next;
  102. if (!frame_list->list)
  103. frame_list->end = NULL;
  104. frame_list->nb_frames--;
  105. frame_list->nb_samples -= info->nb_samples;
  106. av_free(info);
  107. } else {
  108. info->nb_samples -= samples;
  109. info->pts += samples;
  110. frame_list->nb_samples -= samples;
  111. samples = 0;
  112. }
  113. }
  114. }
  115. }
  116. static int frame_list_add_frame(FrameList *frame_list, int nb_samples, int64_t pts)
  117. {
  118. FrameInfo *info = av_malloc(sizeof(*info));
  119. if (!info)
  120. return AVERROR(ENOMEM);
  121. info->nb_samples = nb_samples;
  122. info->pts = pts;
  123. info->next = NULL;
  124. if (!frame_list->list) {
  125. frame_list->list = info;
  126. frame_list->end = info;
  127. } else {
  128. av_assert0(frame_list->end != NULL);
  129. frame_list->end->next = info;
  130. frame_list->end = info;
  131. }
  132. frame_list->nb_frames++;
  133. frame_list->nb_samples += nb_samples;
  134. return 0;
  135. }
  136. typedef struct MixContext {
  137. const AVClass *class; /**< class for AVOptions */
  138. int nb_inputs; /**< number of inputs */
  139. int active_inputs; /**< number of input currently active */
  140. int duration_mode; /**< mode for determining duration */
  141. float dropout_transition; /**< transition time when an input drops out */
  142. int nb_channels; /**< number of channels */
  143. int sample_rate; /**< sample rate */
  144. AVAudioFifo **fifos; /**< audio fifo for each input */
  145. uint8_t *input_state; /**< current state of each input */
  146. float *input_scale; /**< mixing scale factor for each input */
  147. float scale_norm; /**< normalization factor for all inputs */
  148. int64_t next_pts; /**< calculated pts for next output frame */
  149. FrameList *frame_list; /**< list of frame info for the first input */
  150. } MixContext;
  151. #define OFFSET(x) offsetof(MixContext, x)
  152. #define A AV_OPT_FLAG_AUDIO_PARAM
  153. static const AVOption options[] = {
  154. { "inputs", "Number of inputs.",
  155. OFFSET(nb_inputs), AV_OPT_TYPE_INT, { 2 }, 1, 32, A },
  156. { "duration", "How to determine the end-of-stream.",
  157. OFFSET(duration_mode), AV_OPT_TYPE_INT, { DURATION_LONGEST }, 0, 2, A, "duration" },
  158. { "longest", "Duration of longest input.", 0, AV_OPT_TYPE_CONST, { DURATION_LONGEST }, INT_MIN, INT_MAX, A, "duration" },
  159. { "shortest", "Duration of shortest input.", 0, AV_OPT_TYPE_CONST, { DURATION_SHORTEST }, INT_MIN, INT_MAX, A, "duration" },
  160. { "first", "Duration of first input.", 0, AV_OPT_TYPE_CONST, { DURATION_FIRST }, INT_MIN, INT_MAX, A, "duration" },
  161. { "dropout_transition", "Transition time, in seconds, for volume "
  162. "renormalization when an input stream ends.",
  163. OFFSET(dropout_transition), AV_OPT_TYPE_FLOAT, { 2.0 }, 0, INT_MAX, A },
  164. { NULL },
  165. };
  166. static const AVClass amix_class = {
  167. .class_name = "amix",
  168. .item_name = av_default_item_name,
  169. .option = options,
  170. .version = LIBAVUTIL_VERSION_INT,
  171. .category = AV_CLASS_CATEGORY_FILTER,
  172. };
  173. /**
  174. * Update the scaling factors to apply to each input during mixing.
  175. *
  176. * This balances the full volume range between active inputs and handles
  177. * volume transitions when EOF is encountered on an input but mixing continues
  178. * with the remaining inputs.
  179. */
  180. static void calculate_scales(MixContext *s, int nb_samples)
  181. {
  182. int i;
  183. if (s->scale_norm > s->active_inputs) {
  184. s->scale_norm -= nb_samples / (s->dropout_transition * s->sample_rate);
  185. s->scale_norm = FFMAX(s->scale_norm, s->active_inputs);
  186. }
  187. for (i = 0; i < s->nb_inputs; i++) {
  188. if (s->input_state[i] == INPUT_ON)
  189. s->input_scale[i] = 1.0f / s->scale_norm;
  190. else
  191. s->input_scale[i] = 0.0f;
  192. }
  193. }
  194. static int config_output(AVFilterLink *outlink)
  195. {
  196. AVFilterContext *ctx = outlink->src;
  197. MixContext *s = ctx->priv;
  198. int i;
  199. char buf[64];
  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:%"PRId64" cl:%s\n", s->nb_inputs,
  228. av_get_sample_fmt_name(outlink->format), outlink->sample_rate, buf);
  229. return 0;
  230. }
  231. /* TODO: move optimized version from DSPContext to libavutil */
  232. static void vector_fmac_scalar(float *dst, const float *src, float mul, int len)
  233. {
  234. int i;
  235. for (i = 0; i < len; i++)
  236. dst[i] += src[i] * mul;
  237. }
  238. /**
  239. * Read samples from the input FIFOs, mix, and write to the output link.
  240. */
  241. static int output_frame(AVFilterLink *outlink, int nb_samples)
  242. {
  243. AVFilterContext *ctx = outlink->src;
  244. MixContext *s = ctx->priv;
  245. AVFilterBufferRef *out_buf, *in_buf;
  246. int i;
  247. calculate_scales(s, nb_samples);
  248. out_buf = ff_get_audio_buffer(outlink, AV_PERM_WRITE, nb_samples);
  249. if (!out_buf)
  250. return AVERROR(ENOMEM);
  251. in_buf = ff_get_audio_buffer(outlink, AV_PERM_WRITE, nb_samples);
  252. if (!in_buf)
  253. return AVERROR(ENOMEM);
  254. for (i = 0; i < s->nb_inputs; i++) {
  255. if (s->input_state[i] == INPUT_ON) {
  256. av_audio_fifo_read(s->fifos[i], (void **)in_buf->extended_data,
  257. nb_samples);
  258. vector_fmac_scalar((float *)out_buf->extended_data[0],
  259. (float *) in_buf->extended_data[0],
  260. s->input_scale[i], nb_samples * s->nb_channels);
  261. }
  262. }
  263. avfilter_unref_buffer(in_buf);
  264. out_buf->pts = s->next_pts;
  265. if (s->next_pts != AV_NOPTS_VALUE)
  266. s->next_pts += nb_samples;
  267. ff_filter_samples(outlink, out_buf);
  268. return 0;
  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)
  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 0;
  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)
  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. available_samples = get_available_samples(s);
  375. if (!available_samples)
  376. return 0;
  377. available_samples = FFMIN(available_samples, wanted_samples);
  378. } else {
  379. available_samples = wanted_samples;
  380. }
  381. s->next_pts = frame_list_next_pts(s->frame_list);
  382. frame_list_remove_samples(s->frame_list, available_samples);
  383. return output_frame(outlink, available_samples);
  384. }
  385. static void filter_samples(AVFilterLink *inlink, AVFilterBufferRef *buf)
  386. {
  387. AVFilterContext *ctx = inlink->dst;
  388. MixContext *s = ctx->priv;
  389. AVFilterLink *outlink = ctx->outputs[0];
  390. int i;
  391. for (i = 0; i < ctx->nb_inputs; i++)
  392. if (ctx->inputs[i] == inlink)
  393. break;
  394. if (i >= ctx->nb_inputs) {
  395. av_log(ctx, AV_LOG_ERROR, "unknown input link\n");
  396. return;
  397. }
  398. if (i == 0) {
  399. int64_t pts = av_rescale_q(buf->pts, inlink->time_base,
  400. outlink->time_base);
  401. frame_list_add_frame(s->frame_list, buf->audio->nb_samples, pts);
  402. }
  403. av_audio_fifo_write(s->fifos[i], (void **)buf->extended_data,
  404. buf->audio->nb_samples);
  405. avfilter_unref_buffer(buf);
  406. }
  407. static int init(AVFilterContext *ctx, const char *args, void *opaque)
  408. {
  409. MixContext *s = ctx->priv;
  410. int i, ret;
  411. s->class = &amix_class;
  412. av_opt_set_defaults(s);
  413. if ((ret = av_set_options_string(s, args, "=", ":")) < 0) {
  414. av_log(ctx, AV_LOG_ERROR, "Error parsing options string '%s'.\n", args);
  415. return ret;
  416. }
  417. av_opt_free(s);
  418. for (i = 0; i < s->nb_inputs; i++) {
  419. char name[32];
  420. AVFilterPad pad = { 0 };
  421. snprintf(name, sizeof(name), "input%d", i);
  422. pad.type = AVMEDIA_TYPE_AUDIO;
  423. pad.name = av_strdup(name);
  424. pad.filter_samples = filter_samples;
  425. ff_insert_inpad(ctx, i, &pad);
  426. }
  427. return 0;
  428. }
  429. static void uninit(AVFilterContext *ctx)
  430. {
  431. int i;
  432. MixContext *s = ctx->priv;
  433. if (s->fifos) {
  434. for (i = 0; i < s->nb_inputs; i++)
  435. av_audio_fifo_free(s->fifos[i]);
  436. av_freep(&s->fifos);
  437. }
  438. frame_list_clear(s->frame_list);
  439. av_freep(&s->frame_list);
  440. av_freep(&s->input_state);
  441. av_freep(&s->input_scale);
  442. for (i = 0; i < ctx->nb_inputs; i++)
  443. av_freep(&ctx->input_pads[i].name);
  444. }
  445. static int query_formats(AVFilterContext *ctx)
  446. {
  447. AVFilterFormats *formats = NULL;
  448. ff_add_format(&formats, AV_SAMPLE_FMT_FLT);
  449. ff_set_common_formats(ctx, formats);
  450. ff_set_common_channel_layouts(ctx, ff_all_channel_layouts());
  451. ff_set_common_samplerates(ctx, ff_all_samplerates());
  452. return 0;
  453. }
  454. AVFilter avfilter_af_amix = {
  455. .name = "amix",
  456. .description = NULL_IF_CONFIG_SMALL("Audio mixing."),
  457. .priv_size = sizeof(MixContext),
  458. .init = init,
  459. .uninit = uninit,
  460. .query_formats = query_formats,
  461. .inputs = (const AVFilterPad[]) {{ .name = NULL}},
  462. .outputs = (const AVFilterPad[]) {{ .name = "default",
  463. .type = AVMEDIA_TYPE_AUDIO,
  464. .config_props = config_output,
  465. .request_frame = request_frame },
  466. { .name = NULL}},
  467. };