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_fixed16_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 * 2;
31 for (size_t i = 0; i < num_samples; ++i) {
32 int16_t s = le16toh(*(int16_t *)src);
33 *dst = s * (1.0f / 32768.0f);
35 src += 2 * in_num_channels;
36 dst += out_num_channels;
40 void convert_fixed24_to_fp32(float *dst, size_t out_channel, size_t out_num_channels,
41 const uint8_t *src, size_t in_channel, size_t in_num_channels,
44 assert(in_channel < in_num_channels);
45 assert(out_channel < out_num_channels);
46 src += in_channel * 3;
49 for (size_t i = 0; i < num_samples; ++i) {
53 uint32_t s = s1 | (s1 << 8) | (s2 << 16) | (s3 << 24);
54 *dst = int(s) * (1.0f / 2147483648.0f);
56 src += 3 * in_num_channels;
57 dst += out_num_channels;
61 void convert_fixed32_to_fp32(float *dst, size_t out_channel, size_t out_num_channels,
62 const uint8_t *src, size_t in_channel, size_t in_num_channels,
65 assert(in_channel < in_num_channels);
66 assert(out_channel < out_num_channels);
67 src += in_channel * 4;
70 for (size_t i = 0; i < num_samples; ++i) {
71 int32_t s = le32toh(*(int32_t *)src);
72 *dst = s * (1.0f / 2147483648.0f);
74 src += 4 * in_num_channels;
75 dst += out_num_channels;
81 AudioMixer::AudioMixer(unsigned num_cards)
82 : num_cards(num_cards),
83 level_compressor(OUTPUT_FREQUENCY),
84 limiter(OUTPUT_FREQUENCY),
85 compressor(OUTPUT_FREQUENCY)
87 locut.init(FILTER_HPF, 2);
89 set_locut_enabled(global_flags.locut_enabled);
90 set_gain_staging_db(global_flags.initial_gain_staging_db);
91 set_gain_staging_auto(global_flags.gain_staging_auto);
92 set_compressor_enabled(global_flags.compressor_enabled);
93 set_limiter_enabled(global_flags.limiter_enabled);
94 set_final_makeup_gain_auto(global_flags.final_makeup_gain_auto);
96 // Generate a very simple, default input mapping.
97 InputMapping::Bus input;
99 input.device.type = InputSourceType::CAPTURE_CARD;
100 input.device.index = 0;
101 input.source_channel[0] = 0;
102 input.source_channel[1] = 1;
104 InputMapping new_input_mapping;
105 new_input_mapping.buses.push_back(input);
106 set_input_mapping(new_input_mapping);
109 void AudioMixer::reset_device(DeviceSpec device_spec)
111 lock_guard<mutex> lock(audio_mutex);
112 reset_device_mutex_held(device_spec);
115 void AudioMixer::reset_device_mutex_held(DeviceSpec device_spec)
117 AudioDevice *device = find_audio_device(device_spec);
118 if (device->interesting_channels.empty()) {
119 device->resampling_queue.reset();
121 // TODO: ResamplingQueue should probably take the full device spec.
122 // (It's only used for console output, though.)
123 device->resampling_queue.reset(new ResamplingQueue(device_spec.index, device->capture_frequency, OUTPUT_FREQUENCY, device->interesting_channels.size()));
125 device->next_local_pts = 0;
128 void AudioMixer::add_audio(DeviceSpec device_spec, const uint8_t *data, unsigned num_samples, AudioFormat audio_format, int64_t frame_length)
130 AudioDevice *device = find_audio_device(device_spec);
132 lock_guard<mutex> lock(audio_mutex);
133 if (device->resampling_queue == nullptr) {
134 // No buses use this device; throw it away.
138 unsigned num_channels = device->interesting_channels.size();
139 assert(num_channels > 0);
141 // Convert the audio to fp32.
143 audio.resize(num_samples * num_channels);
144 unsigned channel_index = 0;
145 for (auto channel_it = device->interesting_channels.cbegin(); channel_it != device->interesting_channels.end(); ++channel_it, ++channel_index) {
146 switch (audio_format.bits_per_sample) {
148 assert(num_samples == 0);
151 convert_fixed16_to_fp32(&audio[0], channel_index, num_channels, data, *channel_it, audio_format.num_channels, num_samples);
154 convert_fixed24_to_fp32(&audio[0], channel_index, num_channels, data, *channel_it, audio_format.num_channels, num_samples);
157 convert_fixed32_to_fp32(&audio[0], channel_index, num_channels, data, *channel_it, audio_format.num_channels, num_samples);
160 fprintf(stderr, "Cannot handle audio with %u bits per sample\n", audio_format.bits_per_sample);
166 int64_t local_pts = device->next_local_pts;
167 device->resampling_queue->add_input_samples(local_pts / double(TIMEBASE), audio.data(), num_samples);
168 device->next_local_pts = local_pts + frame_length;
171 void AudioMixer::add_silence(DeviceSpec device_spec, unsigned samples_per_frame, unsigned num_frames, int64_t frame_length)
173 AudioDevice *device = find_audio_device(device_spec);
175 lock_guard<mutex> lock(audio_mutex);
176 if (device->resampling_queue == nullptr) {
177 // No buses use this device; throw it away.
181 unsigned num_channels = device->interesting_channels.size();
182 assert(num_channels > 0);
184 vector<float> silence(samples_per_frame * num_channels, 0.0f);
185 for (unsigned i = 0; i < num_frames; ++i) {
186 device->resampling_queue->add_input_samples(device->next_local_pts / double(TIMEBASE), silence.data(), samples_per_frame);
187 // Note that if the format changed in the meantime, we have
188 // no way of detecting that; we just have to assume the frame length
189 // is always the same.
190 device->next_local_pts += frame_length;
194 AudioMixer::AudioDevice *AudioMixer::find_audio_device(DeviceSpec device)
196 switch (device.type) {
197 case InputSourceType::CAPTURE_CARD:
198 return &cards[device.index];
200 case InputSourceType::SILENCE:
207 void AudioMixer::find_sample_src_from_device(const vector<float> *samples_card, DeviceSpec device_spec, int source_channel, const float **srcptr, unsigned *stride)
209 static float zero = 0.0f;
210 if (source_channel == -1 || device_spec.type == InputSourceType::SILENCE) {
215 AudioDevice *device = find_audio_device(device_spec);
216 unsigned channel_index = 0;
217 for (int channel : device->interesting_channels) {
218 if (channel == source_channel) break;
221 assert(channel_index < device->interesting_channels.size());
222 *srcptr = &samples_card[device_spec.index][channel_index];
223 *stride = device->interesting_channels.size();
226 // TODO: Can be SSSE3-optimized if need be.
227 void AudioMixer::fill_audio_bus(const vector<float> *samples_card, const InputMapping::Bus &bus, unsigned num_samples, float *output)
229 if (bus.device.type == InputSourceType::SILENCE) {
230 memset(output, 0, num_samples * sizeof(*output));
232 assert(bus.device.type == InputSourceType::CAPTURE_CARD);
233 const float *lsrc, *rsrc;
234 unsigned lstride, rstride;
235 float *dptr = output;
236 find_sample_src_from_device(samples_card, bus.device, bus.source_channel[0], &lsrc, &lstride);
237 find_sample_src_from_device(samples_card, bus.device, bus.source_channel[1], &rsrc, &rstride);
238 for (unsigned i = 0; i < num_samples; ++i) {
247 vector<float> AudioMixer::get_output(double pts, unsigned num_samples, ResamplingQueue::RateAdjustmentPolicy rate_adjustment_policy)
249 vector<float> samples_card[MAX_CARDS]; // TODO: Needs room for other kinds of capture cards.
250 vector<float> samples_bus;
252 lock_guard<mutex> lock(audio_mutex);
254 // Pick out all the interesting channels from all the cards.
255 // TODO: If the card has been hotswapped, the number of channels
256 // might have changed; if so, we need to do some sort of remapping
258 for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
259 AudioDevice *device = &cards[card_index];
260 if (!device->interesting_channels.empty()) {
261 samples_card[card_index].resize(num_samples * device->interesting_channels.size());
262 device->resampling_queue->get_output_samples(
264 &samples_card[card_index][0],
266 rate_adjustment_policy);
270 // TODO: Move lo-cut etc. into each bus.
271 vector<float> samples_out;
272 samples_out.resize(num_samples * 2);
273 samples_bus.resize(num_samples * 2);
274 for (unsigned bus_index = 0; bus_index < input_mapping.buses.size(); ++bus_index) {
275 fill_audio_bus(samples_card, input_mapping.buses[bus_index], num_samples, &samples_bus[0]);
277 float volume = from_db(fader_volume_db[bus_index]);
278 if (bus_index == 0) {
279 for (unsigned i = 0; i < num_samples * 2; ++i) {
280 samples_out[i] = samples_bus[i] * volume;
283 for (unsigned i = 0; i < num_samples * 2; ++i) {
284 samples_out[i] += samples_bus[i] * volume;
289 // Cut away everything under 120 Hz (or whatever the cutoff is);
290 // we don't need it for voice, and it will reduce headroom
291 // and confuse the compressor. (In particular, any hums at 50 or 60 Hz
292 // should be dampened.)
294 locut.render(samples_out.data(), samples_out.size() / 2, locut_cutoff_hz * 2.0 * M_PI / OUTPUT_FREQUENCY, 0.5f);
298 lock_guard<mutex> lock(compressor_mutex);
300 // Apply a level compressor to get the general level right.
301 // Basically, if it's over about -40 dBFS, we squeeze it down to that level
302 // (or more precisely, near it, since we don't use infinite ratio),
303 // then apply a makeup gain to get it to -14 dBFS. -14 dBFS is, of course,
304 // entirely arbitrary, but from practical tests with speech, it seems to
305 // put ut around -23 LUFS, so it's a reasonable starting point for later use.
307 if (level_compressor_enabled) {
308 float threshold = 0.01f; // -40 dBFS.
310 float attack_time = 0.5f;
311 float release_time = 20.0f;
312 float makeup_gain = from_db(ref_level_dbfs - (-40.0f)); // +26 dB.
313 level_compressor.process(samples_out.data(), samples_out.size() / 2, threshold, ratio, attack_time, release_time, makeup_gain);
314 gain_staging_db = to_db(level_compressor.get_attenuation() * makeup_gain);
316 // Just apply the gain we already had.
317 float g = from_db(gain_staging_db);
318 for (size_t i = 0; i < samples_out.size(); ++i) {
325 printf("level=%f (%+5.2f dBFS) attenuation=%f (%+5.2f dB) end_result=%+5.2f dB\n",
326 level_compressor.get_level(), to_db(level_compressor.get_level()),
327 level_compressor.get_attenuation(), to_db(level_compressor.get_attenuation()),
328 to_db(level_compressor.get_level() * level_compressor.get_attenuation() * makeup_gain));
331 // float limiter_att, compressor_att;
333 // The real compressor.
334 if (compressor_enabled) {
335 float threshold = from_db(compressor_threshold_dbfs);
337 float attack_time = 0.005f;
338 float release_time = 0.040f;
339 float makeup_gain = 2.0f; // +6 dB.
340 compressor.process(samples_out.data(), samples_out.size() / 2, threshold, ratio, attack_time, release_time, makeup_gain);
341 // compressor_att = compressor.get_attenuation();
344 // Finally a limiter at -4 dB (so, -10 dBFS) to take out the worst peaks only.
345 // Note that since ratio is not infinite, we could go slightly higher than this.
346 if (limiter_enabled) {
347 float threshold = from_db(limiter_threshold_dbfs);
349 float attack_time = 0.0f; // Instant.
350 float release_time = 0.020f;
351 float makeup_gain = 1.0f; // 0 dB.
352 limiter.process(samples_out.data(), samples_out.size() / 2, threshold, ratio, attack_time, release_time, makeup_gain);
353 // limiter_att = limiter.get_attenuation();
356 // printf("limiter=%+5.1f compressor=%+5.1f\n", to_db(limiter_att), to_db(compressor_att));
359 // At this point, we are most likely close to +0 LU, but all of our
360 // measurements have been on raw sample values, not R128 values.
361 // So we have a final makeup gain to get us to +0 LU; the gain
362 // adjustments required should be relatively small, and also, the
363 // offset shouldn't change much (only if the type of audio changes
364 // significantly). Thus, we shoot for updating this value basically
365 // “whenever we process buffers”, since the R128 calculation isn't exactly
366 // something we get out per-sample.
368 // Note that there's a feedback loop here, so we choose a very slow filter
369 // (half-time of 30 seconds).
370 double target_loudness_factor, alpha;
371 double loudness_lu = loudness_lufs - ref_level_lufs;
372 double current_makeup_lu = to_db(final_makeup_gain);
373 target_loudness_factor = final_makeup_gain * from_db(-loudness_lu);
375 // If we're outside +/- 5 LU uncorrected, we don't count it as
376 // a normal signal (probably silence) and don't change the
377 // correction factor; just apply what we already have.
378 if (fabs(loudness_lu - current_makeup_lu) >= 5.0 || !final_makeup_gain_auto) {
381 // Formula adapted from
382 // https://en.wikipedia.org/wiki/Low-pass_filter#Simple_infinite_impulse_response_filter.
383 const double half_time_s = 30.0;
384 const double fc_mul_2pi_delta_t = 1.0 / (half_time_s * OUTPUT_FREQUENCY);
385 alpha = fc_mul_2pi_delta_t / (fc_mul_2pi_delta_t + 1.0);
389 lock_guard<mutex> lock(compressor_mutex);
390 double m = final_makeup_gain;
391 for (size_t i = 0; i < samples_out.size(); i += 2) {
392 samples_out[i + 0] *= m;
393 samples_out[i + 1] *= m;
394 m += (target_loudness_factor - m) * alpha;
396 final_makeup_gain = m;
402 map<DeviceSpec, DeviceInfo> AudioMixer::get_devices() const
404 lock_guard<mutex> lock(audio_mutex);
405 map<DeviceSpec, DeviceInfo> devices;
406 for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
407 const DeviceSpec spec{ InputSourceType::CAPTURE_CARD, card_index };
408 const AudioDevice *device = &cards[card_index];
410 info.name = device->name;
411 info.num_channels = 8; // FIXME: This is wrong for fake cards.
412 devices.insert(make_pair(spec, info));
417 void AudioMixer::set_name(DeviceSpec device_spec, const string &name)
419 AudioDevice *device = find_audio_device(device_spec);
421 lock_guard<mutex> lock(audio_mutex);
425 void AudioMixer::set_input_mapping(const InputMapping &new_input_mapping)
427 lock_guard<mutex> lock(audio_mutex);
429 map<DeviceSpec, set<unsigned>> interesting_channels;
430 for (const InputMapping::Bus &bus : new_input_mapping.buses) {
431 if (bus.device.type == InputSourceType::CAPTURE_CARD) {
432 for (unsigned channel = 0; channel < 2; ++channel) {
433 if (bus.source_channel[channel] != -1) {
434 interesting_channels[bus.device].insert(bus.source_channel[channel]);
440 // Reset resamplers for all cards that don't have the exact same state as before.
441 for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
442 DeviceSpec device_spec{InputSourceType::CAPTURE_CARD, card_index};
443 AudioDevice *device = &cards[card_index];
444 if (device->interesting_channels != interesting_channels[device_spec]) {
445 device->interesting_channels = interesting_channels[device_spec];
446 reset_device_mutex_held(DeviceSpec{InputSourceType::CAPTURE_CARD, card_index});
450 input_mapping = new_input_mapping;
453 InputMapping AudioMixer::get_input_mapping() const
455 lock_guard<mutex> lock(audio_mutex);
456 return input_mapping;