1 #include "audio_mixer.h"
5 #include <bmusb/bmusb.h>
14 using namespace bmusb;
19 // TODO: If these prove to be a bottleneck, they can be SSSE3-optimized
20 // (usually including multiple channels at a time).
22 void convert_fixed24_to_fp32(float *dst, size_t out_channel, size_t out_num_channels,
23 const uint8_t *src, size_t in_channel, size_t in_num_channels,
26 assert(in_channel < in_num_channels);
27 assert(out_channel < out_num_channels);
28 src += in_channel * 3;
31 for (size_t i = 0; i < num_samples; ++i) {
35 uint32_t s = s1 | (s1 << 8) | (s2 << 16) | (s3 << 24);
36 *dst = int(s) * (1.0f / 2147483648.0f);
38 src += 3 * in_num_channels;
39 dst += out_num_channels;
43 void convert_fixed32_to_fp32(float *dst, size_t out_channel, size_t out_num_channels,
44 const uint8_t *src, size_t in_channel, size_t in_num_channels,
47 assert(in_channel < in_num_channels);
48 assert(out_channel < out_num_channels);
49 src += in_channel * 4;
52 for (size_t i = 0; i < num_samples; ++i) {
53 int32_t s = le32toh(*(int32_t *)src);
54 *dst = s * (1.0f / 2147483648.0f);
56 src += 4 * in_num_channels;
57 dst += out_num_channels;
63 AudioMixer::AudioMixer(unsigned num_cards)
64 : num_cards(num_cards),
65 level_compressor(OUTPUT_FREQUENCY),
66 limiter(OUTPUT_FREQUENCY),
67 compressor(OUTPUT_FREQUENCY)
69 locut.init(FILTER_HPF, 2);
71 set_locut_enabled(global_flags.locut_enabled);
72 set_gain_staging_db(global_flags.initial_gain_staging_db);
73 set_gain_staging_auto(global_flags.gain_staging_auto);
74 set_compressor_enabled(global_flags.compressor_enabled);
75 set_limiter_enabled(global_flags.limiter_enabled);
76 set_final_makeup_gain_auto(global_flags.final_makeup_gain_auto);
78 // Generate a very simple, default input mapping.
79 InputMapping::Bus input;
81 input.input_source_type = InputSourceType::CAPTURE_CARD;
82 input.input_source_index = 0;
83 input.source_channel[0] = 0;
84 input.source_channel[1] = 1;
86 InputMapping new_input_mapping;
87 new_input_mapping.buses.push_back(input);
88 set_input_mapping(new_input_mapping);
91 void AudioMixer::reset_card(unsigned card_index)
93 lock_guard<mutex> lock(audio_mutex);
94 reset_card_mutex_held(card_index);
97 void AudioMixer::reset_card_mutex_held(unsigned card_index)
99 CaptureCard *card = &cards[card_index];
100 if (card->interesting_channels.empty()) {
101 card->resampling_queue.reset();
103 card->resampling_queue.reset(new ResamplingQueue(card_index, OUTPUT_FREQUENCY, OUTPUT_FREQUENCY, card->interesting_channels.size()));
105 card->next_local_pts = 0;
108 void AudioMixer::add_audio(unsigned card_index, const uint8_t *data, unsigned num_samples, AudioFormat audio_format, int64_t frame_length)
110 lock_guard<mutex> lock(audio_mutex);
111 CaptureCard *card = &cards[card_index];
113 if (card->resampling_queue == nullptr) {
114 // No buses use this card; throw it away.
118 unsigned num_channels = card->interesting_channels.size();
119 assert(num_channels > 0);
121 // Convert the audio to stereo fp32.
123 audio.resize(num_samples * num_channels);
124 unsigned channel_index = 0;
125 for (auto channel_it = card->interesting_channels.cbegin(); channel_it != card->interesting_channels.end(); ++channel_it, ++channel_index) {
126 switch (audio_format.bits_per_sample) {
128 assert(num_samples == 0);
131 convert_fixed24_to_fp32(&audio[0], channel_index, num_channels, data, *channel_it, audio_format.num_channels, num_samples);
134 convert_fixed32_to_fp32(&audio[0], channel_index, num_channels, data, *channel_it, audio_format.num_channels, num_samples);
137 fprintf(stderr, "Cannot handle audio with %u bits per sample\n", audio_format.bits_per_sample);
143 int64_t local_pts = card->next_local_pts;
144 card->resampling_queue->add_input_samples(local_pts / double(TIMEBASE), audio.data(), num_samples);
145 card->next_local_pts = local_pts + frame_length;
148 void AudioMixer::add_silence(unsigned card_index, unsigned samples_per_frame, unsigned num_frames, int64_t frame_length)
150 CaptureCard *card = &cards[card_index];
151 lock_guard<mutex> lock(audio_mutex);
153 if (card->resampling_queue == nullptr) {
154 // No buses use this card; throw it away.
158 unsigned num_channels = card->interesting_channels.size();
159 assert(num_channels > 0);
161 vector<float> silence(samples_per_frame * num_channels, 0.0f);
162 for (unsigned i = 0; i < num_frames; ++i) {
163 card->resampling_queue->add_input_samples(card->next_local_pts / double(TIMEBASE), silence.data(), samples_per_frame);
164 // Note that if the format changed in the meantime, we have
165 // no way of detecting that; we just have to assume the frame length
166 // is always the same.
167 card->next_local_pts += frame_length;
171 void AudioMixer::find_sample_src_from_capture_card(const vector<float> *samples_card, unsigned card_index, int source_channel, const float **srcptr, unsigned *stride)
173 static float zero = 0.0f;
174 if (source_channel == -1) {
179 CaptureCard *card = &cards[card_index];
180 unsigned channel_index = 0;
181 for (int channel : card->interesting_channels) {
182 if (channel == source_channel) break;
185 assert(channel_index < card->interesting_channels.size());
186 *srcptr = &samples_card[card_index][channel_index];
187 *stride = card->interesting_channels.size();
190 // TODO: Can be SSSE3-optimized if need be.
191 void AudioMixer::fill_audio_bus(const vector<float> *samples_card, const InputMapping::Bus &bus, unsigned num_samples, float *output)
193 if (bus.input_source_type == InputSourceType::SILENCE) {
194 memset(output, 0, num_samples * sizeof(*output));
196 assert(bus.input_source_type == InputSourceType::CAPTURE_CARD);
197 const float *lsrc, *rsrc;
198 unsigned lstride, rstride;
199 float *dptr = output;
200 find_sample_src_from_capture_card(samples_card, bus.input_source_index, bus.source_channel[0], &lsrc, &lstride);
201 find_sample_src_from_capture_card(samples_card, bus.input_source_index, bus.source_channel[1], &rsrc, &rstride);
202 for (unsigned i = 0; i < num_samples; ++i) {
211 vector<float> AudioMixer::get_output(double pts, unsigned num_samples, ResamplingQueue::RateAdjustmentPolicy rate_adjustment_policy)
213 vector<float> samples_card[MAX_CARDS];
214 vector<float> samples_bus;
216 lock_guard<mutex> lock(audio_mutex);
218 // Pick out all the interesting channels from all the cards.
219 for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
220 CaptureCard *card = &cards[card_index];
221 if (!card->interesting_channels.empty()) {
222 samples_card[card_index].resize(num_samples * card->interesting_channels.size());
223 card->resampling_queue->get_output_samples(
225 &samples_card[card_index][0],
227 rate_adjustment_policy);
231 // TODO: Move lo-cut etc. into each bus.
232 vector<float> samples_out;
233 samples_out.resize(num_samples * 2);
234 samples_bus.resize(num_samples * 2);
235 for (unsigned bus_index = 0; bus_index < input_mapping.buses.size(); ++bus_index) {
236 fill_audio_bus(samples_card, input_mapping.buses[bus_index], num_samples, &samples_bus[0]);
238 float volume = from_db(fader_volume_db[bus_index]);
239 if (bus_index == 0) {
240 for (unsigned i = 0; i < num_samples * 2; ++i) {
241 samples_out[i] = samples_bus[i] * volume;
244 for (unsigned i = 0; i < num_samples * 2; ++i) {
245 samples_out[i] += samples_bus[i] * volume;
250 // Cut away everything under 120 Hz (or whatever the cutoff is);
251 // we don't need it for voice, and it will reduce headroom
252 // and confuse the compressor. (In particular, any hums at 50 or 60 Hz
253 // should be dampened.)
255 locut.render(samples_out.data(), samples_out.size() / 2, locut_cutoff_hz * 2.0 * M_PI / OUTPUT_FREQUENCY, 0.5f);
259 lock_guard<mutex> lock(compressor_mutex);
261 // Apply a level compressor to get the general level right.
262 // Basically, if it's over about -40 dBFS, we squeeze it down to that level
263 // (or more precisely, near it, since we don't use infinite ratio),
264 // then apply a makeup gain to get it to -14 dBFS. -14 dBFS is, of course,
265 // entirely arbitrary, but from practical tests with speech, it seems to
266 // put ut around -23 LUFS, so it's a reasonable starting point for later use.
268 if (level_compressor_enabled) {
269 float threshold = 0.01f; // -40 dBFS.
271 float attack_time = 0.5f;
272 float release_time = 20.0f;
273 float makeup_gain = from_db(ref_level_dbfs - (-40.0f)); // +26 dB.
274 level_compressor.process(samples_out.data(), samples_out.size() / 2, threshold, ratio, attack_time, release_time, makeup_gain);
275 gain_staging_db = to_db(level_compressor.get_attenuation() * makeup_gain);
277 // Just apply the gain we already had.
278 float g = from_db(gain_staging_db);
279 for (size_t i = 0; i < samples_out.size(); ++i) {
286 printf("level=%f (%+5.2f dBFS) attenuation=%f (%+5.2f dB) end_result=%+5.2f dB\n",
287 level_compressor.get_level(), to_db(level_compressor.get_level()),
288 level_compressor.get_attenuation(), to_db(level_compressor.get_attenuation()),
289 to_db(level_compressor.get_level() * level_compressor.get_attenuation() * makeup_gain));
292 // float limiter_att, compressor_att;
294 // The real compressor.
295 if (compressor_enabled) {
296 float threshold = from_db(compressor_threshold_dbfs);
298 float attack_time = 0.005f;
299 float release_time = 0.040f;
300 float makeup_gain = 2.0f; // +6 dB.
301 compressor.process(samples_out.data(), samples_out.size() / 2, threshold, ratio, attack_time, release_time, makeup_gain);
302 // compressor_att = compressor.get_attenuation();
305 // Finally a limiter at -4 dB (so, -10 dBFS) to take out the worst peaks only.
306 // Note that since ratio is not infinite, we could go slightly higher than this.
307 if (limiter_enabled) {
308 float threshold = from_db(limiter_threshold_dbfs);
310 float attack_time = 0.0f; // Instant.
311 float release_time = 0.020f;
312 float makeup_gain = 1.0f; // 0 dB.
313 limiter.process(samples_out.data(), samples_out.size() / 2, threshold, ratio, attack_time, release_time, makeup_gain);
314 // limiter_att = limiter.get_attenuation();
317 // printf("limiter=%+5.1f compressor=%+5.1f\n", to_db(limiter_att), to_db(compressor_att));
320 // At this point, we are most likely close to +0 LU, but all of our
321 // measurements have been on raw sample values, not R128 values.
322 // So we have a final makeup gain to get us to +0 LU; the gain
323 // adjustments required should be relatively small, and also, the
324 // offset shouldn't change much (only if the type of audio changes
325 // significantly). Thus, we shoot for updating this value basically
326 // “whenever we process buffers”, since the R128 calculation isn't exactly
327 // something we get out per-sample.
329 // Note that there's a feedback loop here, so we choose a very slow filter
330 // (half-time of 30 seconds).
331 double target_loudness_factor, alpha;
332 double loudness_lu = loudness_lufs - ref_level_lufs;
333 double current_makeup_lu = to_db(final_makeup_gain);
334 target_loudness_factor = final_makeup_gain * from_db(-loudness_lu);
336 // If we're outside +/- 5 LU uncorrected, we don't count it as
337 // a normal signal (probably silence) and don't change the
338 // correction factor; just apply what we already have.
339 if (fabs(loudness_lu - current_makeup_lu) >= 5.0 || !final_makeup_gain_auto) {
342 // Formula adapted from
343 // https://en.wikipedia.org/wiki/Low-pass_filter#Simple_infinite_impulse_response_filter.
344 const double half_time_s = 30.0;
345 const double fc_mul_2pi_delta_t = 1.0 / (half_time_s * OUTPUT_FREQUENCY);
346 alpha = fc_mul_2pi_delta_t / (fc_mul_2pi_delta_t + 1.0);
350 lock_guard<mutex> lock(compressor_mutex);
351 double m = final_makeup_gain;
352 for (size_t i = 0; i < samples_out.size(); i += 2) {
353 samples_out[i + 0] *= m;
354 samples_out[i + 1] *= m;
355 m += (target_loudness_factor - m) * alpha;
357 final_makeup_gain = m;
363 vector<string> AudioMixer::get_names() const
365 lock_guard<mutex> lock(audio_mutex);
366 vector<string> names;
367 for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
368 const CaptureCard *card = &cards[card_index];
369 names.push_back(card->name);
374 void AudioMixer::set_name(unsigned card_index, const string &name)
376 lock_guard<mutex> lock(audio_mutex);
377 CaptureCard *card = &cards[card_index];
381 void AudioMixer::set_input_mapping(const InputMapping &new_input_mapping)
383 lock_guard<mutex> lock(audio_mutex);
385 map<unsigned, set<unsigned>> interesting_channels;
386 for (const InputMapping::Bus &bus : new_input_mapping.buses) {
387 if (bus.input_source_type == InputSourceType::CAPTURE_CARD) {
388 for (unsigned channel = 0; channel < 2; ++channel) {
389 if (bus.source_channel[channel] != -1) {
390 interesting_channels[bus.input_source_index].insert(bus.source_channel[channel]);
396 // Reset resamplers for all cards that don't have the exact same state as before.
397 for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
398 CaptureCard *card = &cards[card_index];
399 if (card->interesting_channels != interesting_channels[card_index]) {
400 card->interesting_channels = interesting_channels[card_index];
401 reset_card_mutex_held(card_index);
405 input_mapping = new_input_mapping;
408 InputMapping AudioMixer::get_input_mapping() const
410 lock_guard<mutex> lock(audio_mutex);
411 return input_mapping;