1 #include "audio_mixer.h"
5 #include <bmusb/bmusb.h>
13 using namespace bmusb;
18 // TODO: If these prove to be a bottleneck, they can be SSSE3-optimized.
20 void convert_fixed24_to_fp32(float *dst, size_t out_channels, const uint8_t *src, size_t in_channels, size_t num_samples)
22 assert(in_channels >= out_channels);
23 for (size_t i = 0; i < num_samples; ++i) {
24 for (size_t j = 0; j < out_channels; ++j) {
28 uint32_t s = s1 | (s1 << 8) | (s2 << 16) | (s3 << 24);
29 dst[i * out_channels + j] = int(s) * (1.0f / 2147483648.0f);
31 src += 3 * (in_channels - out_channels);
35 void convert_fixed32_to_fp32(float *dst, size_t out_channels, const uint8_t *src, size_t in_channels, size_t num_samples)
37 assert(in_channels >= out_channels);
38 for (size_t i = 0; i < num_samples; ++i) {
39 for (size_t j = 0; j < out_channels; ++j) {
40 int32_t s = le32toh(*(int32_t *)src);
41 dst[i * out_channels + j] = s * (1.0f / 2147483648.0f);
44 src += 4 * (in_channels - out_channels);
50 AudioMixer::AudioMixer(unsigned num_cards)
51 : num_cards(num_cards),
52 level_compressor(OUTPUT_FREQUENCY),
53 limiter(OUTPUT_FREQUENCY),
54 compressor(OUTPUT_FREQUENCY)
56 locut.init(FILTER_HPF, 2);
58 set_locut_enabled(global_flags.locut_enabled);
59 set_gain_staging_db(global_flags.initial_gain_staging_db);
60 set_gain_staging_auto(global_flags.gain_staging_auto);
61 set_compressor_enabled(global_flags.compressor_enabled);
62 set_limiter_enabled(global_flags.limiter_enabled);
63 set_final_makeup_gain_auto(global_flags.final_makeup_gain_auto);
65 // Generate a very simple, default input mapping.
66 InputMapping::Bus input;
68 input.input_source_type = InputSourceType::CAPTURE_CARD;
69 input.input_source_index = 0;
70 input.source_channel[0] = 0;
71 input.source_channel[1] = 1;
73 InputMapping new_input_mapping;
74 new_input_mapping.buses.push_back(input);
75 set_input_mapping(new_input_mapping);
78 void AudioMixer::reset_card(unsigned card_index)
80 lock_guard<mutex> lock(audio_mutex);
81 reset_card_mutex_held(card_index);
84 void AudioMixer::reset_card_mutex_held(unsigned card_index)
86 CaptureCard *card = &cards[card_index];
87 if (card->interesting_channels.empty()) {
88 card->resampling_queue.reset();
90 card->resampling_queue.reset(new ResamplingQueue(card_index, OUTPUT_FREQUENCY, OUTPUT_FREQUENCY, card->interesting_channels.size()));
92 card->next_local_pts = 0;
95 void AudioMixer::add_audio(unsigned card_index, const uint8_t *data, unsigned num_samples, AudioFormat audio_format, int64_t frame_length)
97 lock_guard<mutex> lock(audio_mutex);
98 CaptureCard *card = &cards[card_index];
100 if (card->resampling_queue == nullptr) {
101 // No buses use this card; throw it away.
105 unsigned num_channels = card->interesting_channels.size();
106 assert(num_channels > 0);
108 // Convert the audio to stereo fp32.
109 // FIXME: Pick out the right channels; this takes the first ones.
111 audio.resize(num_samples * num_channels);
112 switch (audio_format.bits_per_sample) {
114 assert(num_samples == 0);
117 convert_fixed24_to_fp32(&audio[0], num_channels, data, audio_format.num_channels, num_samples);
120 convert_fixed32_to_fp32(&audio[0], num_channels, data, audio_format.num_channels, num_samples);
123 fprintf(stderr, "Cannot handle audio with %u bits per sample\n", audio_format.bits_per_sample);
128 int64_t local_pts = card->next_local_pts;
129 card->resampling_queue->add_input_samples(local_pts / double(TIMEBASE), audio.data(), num_samples);
130 card->next_local_pts = local_pts + frame_length;
133 void AudioMixer::add_silence(unsigned card_index, unsigned samples_per_frame, unsigned num_frames, int64_t frame_length)
135 CaptureCard *card = &cards[card_index];
136 lock_guard<mutex> lock(audio_mutex);
138 if (card->resampling_queue == nullptr) {
139 // No buses use this card; throw it away.
143 unsigned num_channels = card->interesting_channels.size();
144 assert(num_channels > 0);
146 vector<float> silence(samples_per_frame * num_channels, 0.0f);
147 for (unsigned i = 0; i < num_frames; ++i) {
148 card->resampling_queue->add_input_samples(card->next_local_pts / double(TIMEBASE), silence.data(), samples_per_frame);
149 // Note that if the format changed in the meantime, we have
150 // no way of detecting that; we just have to assume the frame length
151 // is always the same.
152 card->next_local_pts += frame_length;
156 void AudioMixer::find_sample_src_from_capture_card(const vector<float> *samples_card, unsigned card_index, int source_channel, const float **srcptr, unsigned *stride)
158 static float zero = 0.0f;
159 if (source_channel == -1) {
164 // FIXME: map back through the interesting_channels squeeze map instead of using source_channel
165 // directly, which will be wrong (and might even overrun).
166 *srcptr = &samples_card[card_index][source_channel];
167 *stride = cards[card_index].interesting_channels.size();
170 vector<float> AudioMixer::get_output(double pts, unsigned num_samples, ResamplingQueue::RateAdjustmentPolicy rate_adjustment_policy)
172 vector<float> samples_card[MAX_CARDS];
173 vector<float> samples_bus;
175 lock_guard<mutex> lock(audio_mutex);
177 // Pick out all the interesting channels from all the cards.
178 for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
179 CaptureCard *card = &cards[card_index];
180 if (!card->interesting_channels.empty()) {
181 samples_card[card_index].resize(num_samples * card->interesting_channels.size());
182 card->resampling_queue->get_output_samples(
184 &samples_card[card_index][0],
186 rate_adjustment_policy);
190 // TODO: Move lo-cut etc. into each bus.
191 vector<float> samples_out;
192 samples_out.resize(num_samples * 2);
193 samples_bus.resize(num_samples * 2);
194 for (unsigned bus_index = 0; bus_index < input_mapping.buses.size(); ++bus_index) {
195 const InputMapping::Bus &input = input_mapping.buses[bus_index];
196 if (input.input_source_type == InputSourceType::SILENCE) {
197 memset(&samples_bus[0], 0, samples_bus.size() * sizeof(samples_bus[0]));
199 // TODO: Move this into its own function. Can be SSSE3-optimized if need be.
200 assert(input.input_source_type == InputSourceType::CAPTURE_CARD);
201 const float *lsrc, *rsrc;
202 unsigned lstride, rstride;
203 float *dptr = &samples_bus[0];
204 find_sample_src_from_capture_card(samples_card, input.input_source_index, input.source_channel[0], &lsrc, &lstride);
205 find_sample_src_from_capture_card(samples_card, input.input_source_index, input.source_channel[1], &rsrc, &rstride);
206 for (unsigned i = 0; i < num_samples; ++i) {
214 float volume = from_db(fader_volume_db[bus_index]);
215 if (bus_index == 0) {
216 for (unsigned i = 0; i < num_samples * 2; ++i) {
217 samples_out[i] = samples_bus[i] * volume;
220 for (unsigned i = 0; i < num_samples * 2; ++i) {
221 samples_out[i] += samples_bus[i] * volume;
226 // Cut away everything under 120 Hz (or whatever the cutoff is);
227 // we don't need it for voice, and it will reduce headroom
228 // and confuse the compressor. (In particular, any hums at 50 or 60 Hz
229 // should be dampened.)
231 locut.render(samples_out.data(), samples_out.size() / 2, locut_cutoff_hz * 2.0 * M_PI / OUTPUT_FREQUENCY, 0.5f);
235 lock_guard<mutex> lock(compressor_mutex);
237 // Apply a level compressor to get the general level right.
238 // Basically, if it's over about -40 dBFS, we squeeze it down to that level
239 // (or more precisely, near it, since we don't use infinite ratio),
240 // then apply a makeup gain to get it to -14 dBFS. -14 dBFS is, of course,
241 // entirely arbitrary, but from practical tests with speech, it seems to
242 // put ut around -23 LUFS, so it's a reasonable starting point for later use.
244 if (level_compressor_enabled) {
245 float threshold = 0.01f; // -40 dBFS.
247 float attack_time = 0.5f;
248 float release_time = 20.0f;
249 float makeup_gain = from_db(ref_level_dbfs - (-40.0f)); // +26 dB.
250 level_compressor.process(samples_out.data(), samples_out.size() / 2, threshold, ratio, attack_time, release_time, makeup_gain);
251 gain_staging_db = to_db(level_compressor.get_attenuation() * makeup_gain);
253 // Just apply the gain we already had.
254 float g = from_db(gain_staging_db);
255 for (size_t i = 0; i < samples_out.size(); ++i) {
262 printf("level=%f (%+5.2f dBFS) attenuation=%f (%+5.2f dB) end_result=%+5.2f dB\n",
263 level_compressor.get_level(), to_db(level_compressor.get_level()),
264 level_compressor.get_attenuation(), to_db(level_compressor.get_attenuation()),
265 to_db(level_compressor.get_level() * level_compressor.get_attenuation() * makeup_gain));
268 // float limiter_att, compressor_att;
270 // The real compressor.
271 if (compressor_enabled) {
272 float threshold = from_db(compressor_threshold_dbfs);
274 float attack_time = 0.005f;
275 float release_time = 0.040f;
276 float makeup_gain = 2.0f; // +6 dB.
277 compressor.process(samples_out.data(), samples_out.size() / 2, threshold, ratio, attack_time, release_time, makeup_gain);
278 // compressor_att = compressor.get_attenuation();
281 // Finally a limiter at -4 dB (so, -10 dBFS) to take out the worst peaks only.
282 // Note that since ratio is not infinite, we could go slightly higher than this.
283 if (limiter_enabled) {
284 float threshold = from_db(limiter_threshold_dbfs);
286 float attack_time = 0.0f; // Instant.
287 float release_time = 0.020f;
288 float makeup_gain = 1.0f; // 0 dB.
289 limiter.process(samples_out.data(), samples_out.size() / 2, threshold, ratio, attack_time, release_time, makeup_gain);
290 // limiter_att = limiter.get_attenuation();
293 // printf("limiter=%+5.1f compressor=%+5.1f\n", to_db(limiter_att), to_db(compressor_att));
296 // At this point, we are most likely close to +0 LU, but all of our
297 // measurements have been on raw sample values, not R128 values.
298 // So we have a final makeup gain to get us to +0 LU; the gain
299 // adjustments required should be relatively small, and also, the
300 // offset shouldn't change much (only if the type of audio changes
301 // significantly). Thus, we shoot for updating this value basically
302 // “whenever we process buffers”, since the R128 calculation isn't exactly
303 // something we get out per-sample.
305 // Note that there's a feedback loop here, so we choose a very slow filter
306 // (half-time of 30 seconds).
307 double target_loudness_factor, alpha;
308 double loudness_lu = loudness_lufs - ref_level_lufs;
309 double current_makeup_lu = to_db(final_makeup_gain);
310 target_loudness_factor = final_makeup_gain * from_db(-loudness_lu);
312 // If we're outside +/- 5 LU uncorrected, we don't count it as
313 // a normal signal (probably silence) and don't change the
314 // correction factor; just apply what we already have.
315 if (fabs(loudness_lu - current_makeup_lu) >= 5.0 || !final_makeup_gain_auto) {
318 // Formula adapted from
319 // https://en.wikipedia.org/wiki/Low-pass_filter#Simple_infinite_impulse_response_filter.
320 const double half_time_s = 30.0;
321 const double fc_mul_2pi_delta_t = 1.0 / (half_time_s * OUTPUT_FREQUENCY);
322 alpha = fc_mul_2pi_delta_t / (fc_mul_2pi_delta_t + 1.0);
326 lock_guard<mutex> lock(compressor_mutex);
327 double m = final_makeup_gain;
328 for (size_t i = 0; i < samples_out.size(); i += 2) {
329 samples_out[i + 0] *= m;
330 samples_out[i + 1] *= m;
331 m += (target_loudness_factor - m) * alpha;
333 final_makeup_gain = m;
339 vector<string> AudioMixer::get_names() const
341 lock_guard<mutex> lock(audio_mutex);
342 vector<string> names;
343 for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
344 const CaptureCard *card = &cards[card_index];
345 names.push_back(card->name);
350 void AudioMixer::set_name(unsigned card_index, const string &name)
352 lock_guard<mutex> lock(audio_mutex);
353 CaptureCard *card = &cards[card_index];
357 void AudioMixer::set_input_mapping(const InputMapping &new_input_mapping)
359 lock_guard<mutex> lock(audio_mutex);
361 map<unsigned, set<unsigned>> interesting_channels;
362 for (const InputMapping::Bus &bus : new_input_mapping.buses) {
363 if (bus.input_source_type == InputSourceType::CAPTURE_CARD) {
364 for (unsigned channel = 0; channel < 2; ++channel) {
365 if (bus.source_channel[channel] != -1) {
366 interesting_channels[bus.input_source_index].insert(bus.source_channel[channel]);
372 // Reset resamplers for all cards that don't have the exact same state as before.
373 for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
374 CaptureCard *card = &cards[card_index];
375 if (card->interesting_channels != interesting_channels[card_index]) {
376 card->interesting_channels = interesting_channels[card_index];
377 reset_card_mutex_held(card_index);
381 input_mapping = new_input_mapping;
384 InputMapping AudioMixer::get_input_mapping() const
386 lock_guard<mutex> lock(audio_mutex);
387 return input_mapping;