]> git.sesse.net Git - nageru/blob - audio_mixer.cpp
Update to a bmusb version where fake cards output 8-channel audio.
[nageru] / audio_mixer.cpp
1 #include "audio_mixer.h"
2
3 #include <assert.h>
4 #include <endian.h>
5 #include <bmusb/bmusb.h>
6 #include <stdio.h>
7 #include <endian.h>
8 #include <cmath>
9 #ifdef __SSE__
10 #include <immintrin.h>
11 #endif
12
13 #include "db.h"
14 #include "flags.h"
15 #include "mixer.h"
16 #include "timebase.h"
17
18 using namespace bmusb;
19 using namespace std;
20 using namespace std::placeholders;
21
22 namespace {
23
24 // TODO: If these prove to be a bottleneck, they can be SSSE3-optimized
25 // (usually including multiple channels at a time).
26
27 void convert_fixed16_to_fp32(float *dst, size_t out_channel, size_t out_num_channels,
28                              const uint8_t *src, size_t in_channel, size_t in_num_channels,
29                              size_t num_samples)
30 {
31         assert(in_channel < in_num_channels);
32         assert(out_channel < out_num_channels);
33         src += in_channel * 2;
34         dst += out_channel;
35
36         for (size_t i = 0; i < num_samples; ++i) {
37                 int16_t s = le16toh(*(int16_t *)src);
38                 *dst = s * (1.0f / 32768.0f);
39
40                 src += 2 * in_num_channels;
41                 dst += out_num_channels;
42         }
43 }
44
45 void convert_fixed24_to_fp32(float *dst, size_t out_channel, size_t out_num_channels,
46                              const uint8_t *src, size_t in_channel, size_t in_num_channels,
47                              size_t num_samples)
48 {
49         assert(in_channel < in_num_channels);
50         assert(out_channel < out_num_channels);
51         src += in_channel * 3;
52         dst += out_channel;
53
54         for (size_t i = 0; i < num_samples; ++i) {
55                 uint32_t s1 = src[0];
56                 uint32_t s2 = src[1];
57                 uint32_t s3 = src[2];
58                 uint32_t s = s1 | (s1 << 8) | (s2 << 16) | (s3 << 24);
59                 *dst = int(s) * (1.0f / 2147483648.0f);
60
61                 src += 3 * in_num_channels;
62                 dst += out_num_channels;
63         }
64 }
65
66 void convert_fixed32_to_fp32(float *dst, size_t out_channel, size_t out_num_channels,
67                              const uint8_t *src, size_t in_channel, size_t in_num_channels,
68                              size_t num_samples)
69 {
70         assert(in_channel < in_num_channels);
71         assert(out_channel < out_num_channels);
72         src += in_channel * 4;
73         dst += out_channel;
74
75         for (size_t i = 0; i < num_samples; ++i) {
76                 int32_t s = le32toh(*(int32_t *)src);
77                 *dst = s * (1.0f / 2147483648.0f);
78
79                 src += 4 * in_num_channels;
80                 dst += out_num_channels;
81         }
82 }
83
84 float find_peak_plain(const float *samples, size_t num_samples) __attribute__((unused));
85
86 float find_peak_plain(const float *samples, size_t num_samples)
87 {
88         float m = fabs(samples[0]);
89         for (size_t i = 1; i < num_samples; ++i) {
90                 m = max(m, fabs(samples[i]));
91         }
92         return m;
93 }
94
95 #ifdef __SSE__
96 static inline float horizontal_max(__m128 m)
97 {
98         __m128 tmp = _mm_shuffle_ps(m, m, _MM_SHUFFLE(1, 0, 3, 2));
99         m = _mm_max_ps(m, tmp);
100         tmp = _mm_shuffle_ps(m, m, _MM_SHUFFLE(2, 3, 0, 1));
101         m = _mm_max_ps(m, tmp);
102         return _mm_cvtss_f32(m);
103 }
104
105 float find_peak(const float *samples, size_t num_samples)
106 {
107         const __m128 abs_mask = _mm_castsi128_ps(_mm_set1_epi32(0x7fffffffu));
108         __m128 m = _mm_setzero_ps();
109         for (size_t i = 0; i < (num_samples & ~3); i += 4) {
110                 __m128 x = _mm_loadu_ps(samples + i);
111                 x = _mm_and_ps(x, abs_mask);
112                 m = _mm_max_ps(m, x);
113         }
114         float result = horizontal_max(m);
115
116         for (size_t i = (num_samples & ~3); i < num_samples; ++i) {
117                 result = max(result, fabs(samples[i]));
118         }
119
120 #if 0
121         // Self-test. We should be bit-exact the same.
122         float reference_result = find_peak_plain(samples, num_samples);
123         if (result != reference_result) {
124                 fprintf(stderr, "Error: Peak is %f [%f %f %f %f]; should be %f.\n",
125                         result,
126                         _mm_cvtss_f32(_mm_shuffle_ps(m, m, _MM_SHUFFLE(0, 0, 0, 0))),
127                         _mm_cvtss_f32(_mm_shuffle_ps(m, m, _MM_SHUFFLE(1, 1, 1, 1))),
128                         _mm_cvtss_f32(_mm_shuffle_ps(m, m, _MM_SHUFFLE(2, 2, 2, 2))),
129                         _mm_cvtss_f32(_mm_shuffle_ps(m, m, _MM_SHUFFLE(3, 3, 3, 3))),
130                         reference_result);
131                 abort();
132         }
133 #endif
134         return result;
135 }
136 #else
137 float find_peak(const float *samples, size_t num_samples)
138 {
139         return find_peak_plain(samples, num_samples);
140 }
141 #endif
142
143 void deinterleave_samples(const vector<float> &in, vector<float> *out_l, vector<float> *out_r)
144 {
145         size_t num_samples = in.size() / 2;
146         out_l->resize(num_samples);
147         out_r->resize(num_samples);
148
149         const float *inptr = in.data();
150         float *lptr = &(*out_l)[0];
151         float *rptr = &(*out_r)[0];
152         for (size_t i = 0; i < num_samples; ++i) {
153                 *lptr++ = *inptr++;
154                 *rptr++ = *inptr++;
155         }
156 }
157
158 }  // namespace
159
160 AudioMixer::AudioMixer(unsigned num_cards)
161         : num_cards(num_cards),
162           limiter(OUTPUT_FREQUENCY),
163           correlation(OUTPUT_FREQUENCY)
164 {
165         for (unsigned bus_index = 0; bus_index < MAX_BUSES; ++bus_index) {
166                 locut[bus_index].init(FILTER_HPF, 2);
167                 locut_enabled[bus_index] = global_flags.locut_enabled;
168                 eq[bus_index][EQ_BAND_BASS].init(FILTER_LOW_SHELF, 1);
169                 // Note: EQ_BAND_MID isn't used (see comments in apply_eq()).
170                 eq[bus_index][EQ_BAND_TREBLE].init(FILTER_HIGH_SHELF, 1);
171
172                 gain_staging_db[bus_index] = global_flags.initial_gain_staging_db;
173                 compressor[bus_index].reset(new StereoCompressor(OUTPUT_FREQUENCY));
174                 compressor_threshold_dbfs[bus_index] = ref_level_dbfs - 12.0f;  // -12 dB.
175                 compressor_enabled[bus_index] = global_flags.compressor_enabled;
176                 level_compressor[bus_index].reset(new StereoCompressor(OUTPUT_FREQUENCY));
177                 level_compressor_enabled[bus_index] = global_flags.gain_staging_auto;
178         }
179         set_limiter_enabled(global_flags.limiter_enabled);
180         set_final_makeup_gain_auto(global_flags.final_makeup_gain_auto);
181
182         // Generate a very simple, default input mapping.
183         InputMapping::Bus input;
184         input.name = "Main";
185         input.device.type = InputSourceType::CAPTURE_CARD;
186         input.device.index = 0;
187         input.source_channel[0] = 0;
188         input.source_channel[1] = 1;
189
190         InputMapping new_input_mapping;
191         new_input_mapping.buses.push_back(input);
192         set_input_mapping(new_input_mapping);
193
194         alsa_pool.init();
195
196         r128.init(2, OUTPUT_FREQUENCY);
197         r128.integr_start();
198
199         // hlen=16 is pretty low quality, but we use quite a bit of CPU otherwise,
200         // and there's a limit to how important the peak meter is.
201         peak_resampler.setup(OUTPUT_FREQUENCY, OUTPUT_FREQUENCY * 4, /*num_channels=*/2, /*hlen=*/16, /*frel=*/1.0);
202 }
203
204 void AudioMixer::reset_resampler(DeviceSpec device_spec)
205 {
206         lock_guard<timed_mutex> lock(audio_mutex);
207         reset_resampler_mutex_held(device_spec);
208 }
209
210 void AudioMixer::reset_resampler_mutex_held(DeviceSpec device_spec)
211 {
212         AudioDevice *device = find_audio_device(device_spec);
213
214         if (device->interesting_channels.empty()) {
215                 device->resampling_queue.reset();
216         } else {
217                 // TODO: ResamplingQueue should probably take the full device spec.
218                 // (It's only used for console output, though.)
219                 device->resampling_queue.reset(new ResamplingQueue(device_spec.index, device->capture_frequency, OUTPUT_FREQUENCY, device->interesting_channels.size()));
220         }
221         device->next_local_pts = 0;
222 }
223
224 bool AudioMixer::add_audio(DeviceSpec device_spec, const uint8_t *data, unsigned num_samples, AudioFormat audio_format, int64_t frame_length)
225 {
226         AudioDevice *device = find_audio_device(device_spec);
227
228         unique_lock<timed_mutex> lock(audio_mutex, defer_lock);
229         if (!lock.try_lock_for(chrono::milliseconds(10))) {
230                 return false;
231         }
232         if (device->resampling_queue == nullptr) {
233                 // No buses use this device; throw it away.
234                 return true;
235         }
236
237         unsigned num_channels = device->interesting_channels.size();
238         assert(num_channels > 0);
239
240         // Convert the audio to fp32.
241         unique_ptr<float[]> audio(new float[num_samples * num_channels]);
242         unsigned channel_index = 0;
243         for (auto channel_it = device->interesting_channels.cbegin(); channel_it != device->interesting_channels.end(); ++channel_it, ++channel_index) {
244                 switch (audio_format.bits_per_sample) {
245                 case 0:
246                         assert(num_samples == 0);
247                         break;
248                 case 16:
249                         convert_fixed16_to_fp32(audio.get(), channel_index, num_channels, data, *channel_it, audio_format.num_channels, num_samples);
250                         break;
251                 case 24:
252                         convert_fixed24_to_fp32(audio.get(), channel_index, num_channels, data, *channel_it, audio_format.num_channels, num_samples);
253                         break;
254                 case 32:
255                         convert_fixed32_to_fp32(audio.get(), channel_index, num_channels, data, *channel_it, audio_format.num_channels, num_samples);
256                         break;
257                 default:
258                         fprintf(stderr, "Cannot handle audio with %u bits per sample\n", audio_format.bits_per_sample);
259                         assert(false);
260                 }
261         }
262
263         // Now add it.
264         int64_t local_pts = device->next_local_pts;
265         device->resampling_queue->add_input_samples(local_pts / double(TIMEBASE), audio.get(), num_samples);
266         device->next_local_pts = local_pts + frame_length;
267         return true;
268 }
269
270 bool AudioMixer::add_silence(DeviceSpec device_spec, unsigned samples_per_frame, unsigned num_frames, int64_t frame_length)
271 {
272         AudioDevice *device = find_audio_device(device_spec);
273
274         unique_lock<timed_mutex> lock(audio_mutex, defer_lock);
275         if (!lock.try_lock_for(chrono::milliseconds(10))) {
276                 return false;
277         }
278         if (device->resampling_queue == nullptr) {
279                 // No buses use this device; throw it away.
280                 return true;
281         }
282
283         unsigned num_channels = device->interesting_channels.size();
284         assert(num_channels > 0);
285
286         vector<float> silence(samples_per_frame * num_channels, 0.0f);
287         for (unsigned i = 0; i < num_frames; ++i) {
288                 device->resampling_queue->add_input_samples(device->next_local_pts / double(TIMEBASE), silence.data(), samples_per_frame);
289                 // Note that if the format changed in the meantime, we have
290                 // no way of detecting that; we just have to assume the frame length
291                 // is always the same.
292                 device->next_local_pts += frame_length;
293         }
294         return true;
295 }
296
297 bool AudioMixer::silence_card(DeviceSpec device_spec, bool silence)
298 {
299         AudioDevice *device = find_audio_device(device_spec);
300
301         unique_lock<timed_mutex> lock(audio_mutex, defer_lock);
302         if (!lock.try_lock_for(chrono::milliseconds(10))) {
303                 return false;
304         }
305
306         if (device->silenced && !silence) {
307                 reset_resampler_mutex_held(device_spec);
308         }
309         device->silenced = silence;
310         return true;
311 }
312
313 AudioMixer::AudioDevice *AudioMixer::find_audio_device(DeviceSpec device)
314 {
315         switch (device.type) {
316         case InputSourceType::CAPTURE_CARD:
317                 return &video_cards[device.index];
318         case InputSourceType::ALSA_INPUT:
319                 return &alsa_inputs[device.index];
320         case InputSourceType::SILENCE:
321         default:
322                 assert(false);
323         }
324         return nullptr;
325 }
326
327 // Get a pointer to the given channel from the given device.
328 // The channel must be picked out earlier and resampled.
329 void AudioMixer::find_sample_src_from_device(const map<DeviceSpec, vector<float>> &samples_card, DeviceSpec device_spec, int source_channel, const float **srcptr, unsigned *stride)
330 {
331         static float zero = 0.0f;
332         if (source_channel == -1 || device_spec.type == InputSourceType::SILENCE) {
333                 *srcptr = &zero;
334                 *stride = 0;
335                 return;
336         }
337         AudioDevice *device = find_audio_device(device_spec);
338         assert(device->interesting_channels.count(source_channel) != 0);
339         unsigned channel_index = 0;
340         for (int channel : device->interesting_channels) {
341                 if (channel == source_channel) break;
342                 ++channel_index;
343         }
344         assert(channel_index < device->interesting_channels.size());
345         const auto it = samples_card.find(device_spec);
346         assert(it != samples_card.end());
347         *srcptr = &(it->second)[channel_index];
348         *stride = device->interesting_channels.size();
349 }
350
351 // TODO: Can be SSSE3-optimized if need be.
352 void AudioMixer::fill_audio_bus(const map<DeviceSpec, vector<float>> &samples_card, const InputMapping::Bus &bus, unsigned num_samples, float *output)
353 {
354         if (bus.device.type == InputSourceType::SILENCE) {
355                 memset(output, 0, num_samples * sizeof(*output));
356         } else {
357                 assert(bus.device.type == InputSourceType::CAPTURE_CARD ||
358                        bus.device.type == InputSourceType::ALSA_INPUT);
359                 const float *lsrc, *rsrc;
360                 unsigned lstride, rstride;
361                 float *dptr = output;
362                 find_sample_src_from_device(samples_card, bus.device, bus.source_channel[0], &lsrc, &lstride);
363                 find_sample_src_from_device(samples_card, bus.device, bus.source_channel[1], &rsrc, &rstride);
364                 for (unsigned i = 0; i < num_samples; ++i) {
365                         *dptr++ = *lsrc;
366                         *dptr++ = *rsrc;
367                         lsrc += lstride;
368                         rsrc += rstride;
369                 }
370         }
371 }
372
373 vector<DeviceSpec> AudioMixer::get_active_devices() const
374 {
375         vector<DeviceSpec> ret;
376         for (unsigned card_index = 0; card_index < MAX_VIDEO_CARDS; ++card_index) {
377                 const DeviceSpec device_spec{InputSourceType::CAPTURE_CARD, card_index};
378                 if (!find_audio_device(device_spec)->interesting_channels.empty()) {
379                         ret.push_back(device_spec);
380                 }
381         }
382         for (unsigned card_index = 0; card_index < MAX_ALSA_CARDS; ++card_index) {
383                 const DeviceSpec device_spec{InputSourceType::ALSA_INPUT, card_index};
384                 if (!find_audio_device(device_spec)->interesting_channels.empty()) {
385                         ret.push_back(device_spec);
386                 }
387         }
388         return ret;
389 }
390
391 vector<float> AudioMixer::get_output(double pts, unsigned num_samples, ResamplingQueue::RateAdjustmentPolicy rate_adjustment_policy)
392 {
393         map<DeviceSpec, vector<float>> samples_card;
394         vector<float> samples_bus;
395
396         lock_guard<timed_mutex> lock(audio_mutex);
397
398         // Pick out all the interesting channels from all the cards.
399         for (const DeviceSpec &device_spec : get_active_devices()) {
400                 AudioDevice *device = find_audio_device(device_spec);
401                 samples_card[device_spec].resize(num_samples * device->interesting_channels.size());
402                 if (device->silenced) {
403                         memset(&samples_card[device_spec][0], 0, samples_card[device_spec].size() * sizeof(float));
404                 } else {
405                         device->resampling_queue->get_output_samples(
406                                 pts,
407                                 &samples_card[device_spec][0],
408                                 num_samples,
409                                 rate_adjustment_policy);
410                 }
411         }
412
413         vector<float> samples_out, left, right;
414         samples_out.resize(num_samples * 2);
415         samples_bus.resize(num_samples * 2);
416         for (unsigned bus_index = 0; bus_index < input_mapping.buses.size(); ++bus_index) {
417                 fill_audio_bus(samples_card, input_mapping.buses[bus_index], num_samples, &samples_bus[0]);
418                 apply_eq(bus_index, &samples_bus);
419
420                 {
421                         lock_guard<mutex> lock(compressor_mutex);
422
423                         // Apply a level compressor to get the general level right.
424                         // Basically, if it's over about -40 dBFS, we squeeze it down to that level
425                         // (or more precisely, near it, since we don't use infinite ratio),
426                         // then apply a makeup gain to get it to -14 dBFS. -14 dBFS is, of course,
427                         // entirely arbitrary, but from practical tests with speech, it seems to
428                         // put ut around -23 LUFS, so it's a reasonable starting point for later use.
429                         if (level_compressor_enabled[bus_index]) {
430                                 float threshold = 0.01f;   // -40 dBFS.
431                                 float ratio = 20.0f;
432                                 float attack_time = 0.5f;
433                                 float release_time = 20.0f;
434                                 float makeup_gain = from_db(ref_level_dbfs - (-40.0f));  // +26 dB.
435                                 level_compressor[bus_index]->process(samples_bus.data(), samples_bus.size() / 2, threshold, ratio, attack_time, release_time, makeup_gain);
436                                 gain_staging_db[bus_index] = to_db(level_compressor[bus_index]->get_attenuation() * makeup_gain);
437                         } else {
438                                 // Just apply the gain we already had.
439                                 float g = from_db(gain_staging_db[bus_index]);
440                                 for (size_t i = 0; i < samples_bus.size(); ++i) {
441                                         samples_bus[i] *= g;
442                                 }
443                         }
444
445 #if 0
446                         printf("level=%f (%+5.2f dBFS) attenuation=%f (%+5.2f dB) end_result=%+5.2f dB\n",
447                                 level_compressor.get_level(), to_db(level_compressor.get_level()),
448                                 level_compressor.get_attenuation(), to_db(level_compressor.get_attenuation()),
449                                 to_db(level_compressor.get_level() * level_compressor.get_attenuation() * makeup_gain));
450 #endif
451
452                         // The real compressor.
453                         if (compressor_enabled[bus_index]) {
454                                 float threshold = from_db(compressor_threshold_dbfs[bus_index]);
455                                 float ratio = 20.0f;
456                                 float attack_time = 0.005f;
457                                 float release_time = 0.040f;
458                                 float makeup_gain = 2.0f;  // +6 dB.
459                                 compressor[bus_index]->process(samples_bus.data(), samples_bus.size() / 2, threshold, ratio, attack_time, release_time, makeup_gain);
460                 //              compressor_att = compressor.get_attenuation();
461                         }
462                 }
463
464                 add_bus_to_master(bus_index, samples_bus, &samples_out);
465                 deinterleave_samples(samples_bus, &left, &right);
466                 measure_bus_levels(bus_index, left, right);
467         }
468
469         {
470                 lock_guard<mutex> lock(compressor_mutex);
471
472                 // Finally a limiter at -4 dB (so, -10 dBFS) to take out the worst peaks only.
473                 // Note that since ratio is not infinite, we could go slightly higher than this.
474                 if (limiter_enabled) {
475                         float threshold = from_db(limiter_threshold_dbfs);
476                         float ratio = 30.0f;
477                         float attack_time = 0.0f;  // Instant.
478                         float release_time = 0.020f;
479                         float makeup_gain = 1.0f;  // 0 dB.
480                         limiter.process(samples_out.data(), samples_out.size() / 2, threshold, ratio, attack_time, release_time, makeup_gain);
481         //              limiter_att = limiter.get_attenuation();
482                 }
483
484         //      printf("limiter=%+5.1f  compressor=%+5.1f\n", to_db(limiter_att), to_db(compressor_att));
485         }
486
487         // At this point, we are most likely close to +0 LU (at least if the
488         // faders sum to 0 dB and the compressors are on), but all of our
489         // measurements have been on raw sample values, not R128 values.
490         // So we have a final makeup gain to get us to +0 LU; the gain
491         // adjustments required should be relatively small, and also, the
492         // offset shouldn't change much (only if the type of audio changes
493         // significantly). Thus, we shoot for updating this value basically
494         // “whenever we process buffers”, since the R128 calculation isn't exactly
495         // something we get out per-sample.
496         //
497         // Note that there's a feedback loop here, so we choose a very slow filter
498         // (half-time of 30 seconds).
499         double target_loudness_factor, alpha;
500         double loudness_lu = r128.loudness_M() - ref_level_lufs;
501         double current_makeup_lu = to_db(final_makeup_gain);
502         target_loudness_factor = final_makeup_gain * from_db(-loudness_lu);
503
504         // If we're outside +/- 5 LU uncorrected, we don't count it as
505         // a normal signal (probably silence) and don't change the
506         // correction factor; just apply what we already have.
507         if (fabs(loudness_lu - current_makeup_lu) >= 5.0 || !final_makeup_gain_auto) {
508                 alpha = 0.0;
509         } else {
510                 // Formula adapted from
511                 // https://en.wikipedia.org/wiki/Low-pass_filter#Simple_infinite_impulse_response_filter.
512                 const double half_time_s = 30.0;
513                 const double fc_mul_2pi_delta_t = 1.0 / (half_time_s * OUTPUT_FREQUENCY);
514                 alpha = fc_mul_2pi_delta_t / (fc_mul_2pi_delta_t + 1.0);
515         }
516
517         {
518                 lock_guard<mutex> lock(compressor_mutex);
519                 double m = final_makeup_gain;
520                 for (size_t i = 0; i < samples_out.size(); i += 2) {
521                         samples_out[i + 0] *= m;
522                         samples_out[i + 1] *= m;
523                         m += (target_loudness_factor - m) * alpha;
524                 }
525                 final_makeup_gain = m;
526         }
527
528         update_meters(samples_out);
529
530         return samples_out;
531 }
532
533 void AudioMixer::apply_eq(unsigned bus_index, vector<float> *samples_bus)
534 {
535         constexpr float bass_freq_hz = 200.0f;
536         constexpr float treble_freq_hz = 4700.0f;
537
538         // Cut away everything under 120 Hz (or whatever the cutoff is);
539         // we don't need it for voice, and it will reduce headroom
540         // and confuse the compressor. (In particular, any hums at 50 or 60 Hz
541         // should be dampened.)
542         if (locut_enabled[bus_index]) {
543                 locut[bus_index].render(samples_bus->data(), samples_bus->size() / 2, locut_cutoff_hz * 2.0 * M_PI / OUTPUT_FREQUENCY, 0.5f);
544         }
545
546         // Apply the rest of the EQ. Since we only have a simple three-band EQ,
547         // we can implement it with two shelf filters. We use a simple gain to
548         // set the mid-level filter, and then offset the low and high bands
549         // from that if we need to. (We could perhaps have folded the gain into
550         // the next part, but it's so cheap that the trouble isn't worth it.)
551         if (fabs(eq_level_db[bus_index][EQ_BAND_MID]) > 0.01f) {
552                 float g = from_db(eq_level_db[bus_index][EQ_BAND_MID]);
553                 for (size_t i = 0; i < samples_bus->size(); ++i) {
554                         (*samples_bus)[i] *= g;
555                 }
556         }
557
558         float bass_adj_db = eq_level_db[bus_index][EQ_BAND_BASS] - eq_level_db[bus_index][EQ_BAND_MID];
559         if (fabs(bass_adj_db) > 0.01f) {
560                 eq[bus_index][EQ_BAND_BASS].render(samples_bus->data(), samples_bus->size() / 2,
561                         bass_freq_hz * 2.0 * M_PI / OUTPUT_FREQUENCY, 0.5f, bass_adj_db / 40.0f);
562         }
563
564         float treble_adj_db = eq_level_db[bus_index][EQ_BAND_TREBLE] - eq_level_db[bus_index][EQ_BAND_MID];
565         if (fabs(treble_adj_db) > 0.01f) {
566                 eq[bus_index][EQ_BAND_TREBLE].render(samples_bus->data(), samples_bus->size() / 2,
567                         treble_freq_hz * 2.0 * M_PI / OUTPUT_FREQUENCY, 0.5f, treble_adj_db / 40.0f);
568         }
569 }
570
571 void AudioMixer::add_bus_to_master(unsigned bus_index, const vector<float> &samples_bus, vector<float> *samples_out)
572 {
573         assert(samples_bus.size() == samples_out->size());
574         assert(samples_bus.size() % 2 == 0);
575         unsigned num_samples = samples_bus.size() / 2;
576         if (fabs(fader_volume_db[bus_index] - last_fader_volume_db[bus_index]) > 1e-3) {
577                 // The volume has changed; do a fade over the course of this frame.
578                 // (We might have some numerical issues here, but it seems to sound OK.)
579                 // For the purpose of fading here, the silence floor is set to -90 dB
580                 // (the fader only goes to -84).
581                 float old_volume = from_db(max<float>(last_fader_volume_db[bus_index], -90.0f));
582                 float volume = from_db(max<float>(fader_volume_db[bus_index], -90.0f));
583
584                 float volume_inc = pow(volume / old_volume, 1.0 / num_samples);
585                 volume = old_volume;
586                 if (bus_index == 0) {
587                         for (unsigned i = 0; i < num_samples; ++i) {
588                                 (*samples_out)[i * 2 + 0] = samples_bus[i * 2 + 0] * volume;
589                                 (*samples_out)[i * 2 + 1] = samples_bus[i * 2 + 1] * volume;
590                                 volume *= volume_inc;
591                         }
592                 } else {
593                         for (unsigned i = 0; i < num_samples; ++i) {
594                                 (*samples_out)[i * 2 + 0] += samples_bus[i * 2 + 0] * volume;
595                                 (*samples_out)[i * 2 + 1] += samples_bus[i * 2 + 1] * volume;
596                                 volume *= volume_inc;
597                         }
598                 }
599         } else {
600                 float volume = from_db(fader_volume_db[bus_index]);
601                 if (bus_index == 0) {
602                         for (unsigned i = 0; i < num_samples; ++i) {
603                                 (*samples_out)[i * 2 + 0] = samples_bus[i * 2 + 0] * volume;
604                                 (*samples_out)[i * 2 + 1] = samples_bus[i * 2 + 1] * volume;
605                         }
606                 } else {
607                         for (unsigned i = 0; i < num_samples; ++i) {
608                                 (*samples_out)[i * 2 + 0] += samples_bus[i * 2 + 0] * volume;
609                                 (*samples_out)[i * 2 + 1] += samples_bus[i * 2 + 1] * volume;
610                         }
611                 }
612         }
613
614         last_fader_volume_db[bus_index] = fader_volume_db[bus_index];
615 }
616
617 void AudioMixer::measure_bus_levels(unsigned bus_index, const vector<float> &left, const vector<float> &right)
618 {
619         assert(left.size() == right.size());
620         const float volume = from_db(fader_volume_db[bus_index]);
621         const float peak_levels[2] = {
622                 find_peak(left.data(), left.size()) * volume,
623                 find_peak(right.data(), right.size()) * volume
624         };
625         for (unsigned channel = 0; channel < 2; ++channel) {
626                 // Compute the current value, including hold and falloff.
627                 // The constants are borrowed from zita-mu1 by Fons Adriaensen.
628                 static constexpr float hold_sec = 0.5f;
629                 static constexpr float falloff_db_sec = 15.0f;  // dB/sec falloff after hold.
630                 float current_peak;
631                 PeakHistory &history = peak_history[bus_index][channel];
632                 history.historic_peak = max(history.historic_peak, peak_levels[channel]);
633                 if (history.age_seconds < hold_sec) {
634                         current_peak = history.last_peak;
635                 } else {
636                         current_peak = history.last_peak * from_db(-falloff_db_sec * (history.age_seconds - hold_sec));
637                 }
638
639                 // See if we have a new peak to replace the old (possibly falling) one.
640                 if (peak_levels[channel] > current_peak) {
641                         history.last_peak = peak_levels[channel];
642                         history.age_seconds = 0.0f;  // Not 100% correct, but more than good enough given our frame sizes.
643                         current_peak = peak_levels[channel];
644                 } else {
645                         history.age_seconds += float(left.size()) / OUTPUT_FREQUENCY;
646                 }
647                 history.current_level = peak_levels[channel];
648                 history.current_peak = current_peak;
649         }
650 }
651
652 void AudioMixer::update_meters(const vector<float> &samples)
653 {
654         // Upsample 4x to find interpolated peak.
655         peak_resampler.inp_data = const_cast<float *>(samples.data());
656         peak_resampler.inp_count = samples.size() / 2;
657
658         vector<float> interpolated_samples;
659         interpolated_samples.resize(samples.size());
660         {
661                 lock_guard<mutex> lock(audio_measure_mutex);
662
663                 while (peak_resampler.inp_count > 0) {  // About four iterations.
664                         peak_resampler.out_data = &interpolated_samples[0];
665                         peak_resampler.out_count = interpolated_samples.size() / 2;
666                         peak_resampler.process();
667                         size_t out_stereo_samples = interpolated_samples.size() / 2 - peak_resampler.out_count;
668                         peak = max<float>(peak, find_peak(interpolated_samples.data(), out_stereo_samples * 2));
669                         peak_resampler.out_data = nullptr;
670                 }
671         }
672
673         // Find R128 levels and L/R correlation.
674         vector<float> left, right;
675         deinterleave_samples(samples, &left, &right);
676         float *ptrs[] = { left.data(), right.data() };
677         {
678                 lock_guard<mutex> lock(audio_measure_mutex);
679                 r128.process(left.size(), ptrs);
680                 correlation.process_samples(samples);
681         }
682
683         send_audio_level_callback();
684 }
685
686 void AudioMixer::reset_meters()
687 {
688         lock_guard<mutex> lock(audio_measure_mutex);
689         peak_resampler.reset();
690         peak = 0.0f;
691         r128.reset();
692         r128.integr_start();
693         correlation.reset();
694 }
695
696 void AudioMixer::send_audio_level_callback()
697 {
698         if (audio_level_callback == nullptr) {
699                 return;
700         }
701
702         lock_guard<mutex> lock(audio_measure_mutex);
703         double loudness_s = r128.loudness_S();
704         double loudness_i = r128.integrated();
705         double loudness_range_low = r128.range_min();
706         double loudness_range_high = r128.range_max();
707
708         vector<BusLevel> bus_levels;
709         bus_levels.resize(input_mapping.buses.size());
710         {
711                 lock_guard<mutex> lock(compressor_mutex);
712                 for (unsigned bus_index = 0; bus_index < bus_levels.size(); ++bus_index) {
713                         bus_levels[bus_index].current_level_dbfs[0] = to_db(peak_history[bus_index][0].current_level);
714                         bus_levels[bus_index].current_level_dbfs[1] = to_db(peak_history[bus_index][1].current_level);
715                         bus_levels[bus_index].peak_level_dbfs[0] = to_db(peak_history[bus_index][0].current_peak);
716                         bus_levels[bus_index].peak_level_dbfs[1] = to_db(peak_history[bus_index][1].current_peak);
717                         bus_levels[bus_index].historic_peak_dbfs = to_db(
718                                 max(peak_history[bus_index][0].historic_peak,
719                                     peak_history[bus_index][1].historic_peak));
720                         bus_levels[bus_index].gain_staging_db = gain_staging_db[bus_index];
721                         if (compressor_enabled[bus_index]) {
722                                 bus_levels[bus_index].compressor_attenuation_db = -to_db(compressor[bus_index]->get_attenuation());
723                         } else {
724                                 bus_levels[bus_index].compressor_attenuation_db = 0.0;
725                         }
726                 }
727         }
728
729         audio_level_callback(loudness_s, to_db(peak), bus_levels,
730                 loudness_i, loudness_range_low, loudness_range_high,
731                 to_db(final_makeup_gain),
732                 correlation.get_correlation());
733 }
734
735 map<DeviceSpec, DeviceInfo> AudioMixer::get_devices()
736 {
737         lock_guard<timed_mutex> lock(audio_mutex);
738
739         map<DeviceSpec, DeviceInfo> devices;
740         for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
741                 const DeviceSpec spec{ InputSourceType::CAPTURE_CARD, card_index };
742                 const AudioDevice *device = &video_cards[card_index];
743                 DeviceInfo info;
744                 info.name = device->name;
745                 info.num_channels = 8;
746                 devices.insert(make_pair(spec, info));
747         }
748         vector<ALSAPool::Device> available_alsa_devices = alsa_pool.get_devices();
749         for (unsigned card_index = 0; card_index < available_alsa_devices.size(); ++card_index) {
750                 const DeviceSpec spec{ InputSourceType::ALSA_INPUT, card_index };
751                 const ALSAPool::Device &device = available_alsa_devices[card_index];
752                 DeviceInfo info;
753                 info.name = device.name + " (" + device.info + ")";
754                 info.num_channels = device.num_channels;
755                 devices.insert(make_pair(spec, info));
756         }
757         return devices;
758 }
759
760 void AudioMixer::set_name(DeviceSpec device_spec, const string &name)
761 {
762         AudioDevice *device = find_audio_device(device_spec);
763
764         lock_guard<timed_mutex> lock(audio_mutex);
765         device->name = name;
766 }
767
768 void AudioMixer::set_input_mapping(const InputMapping &new_input_mapping)
769 {
770         lock_guard<timed_mutex> lock(audio_mutex);
771
772         map<DeviceSpec, set<unsigned>> interesting_channels;
773         for (const InputMapping::Bus &bus : new_input_mapping.buses) {
774                 if (bus.device.type == InputSourceType::CAPTURE_CARD ||
775                     bus.device.type == InputSourceType::ALSA_INPUT) {
776                         for (unsigned channel = 0; channel < 2; ++channel) {
777                                 if (bus.source_channel[channel] != -1) {
778                                         interesting_channels[bus.device].insert(bus.source_channel[channel]);
779                                 }
780                         }
781                 }
782         }
783
784         // Reset resamplers for all cards that don't have the exact same state as before.
785         for (unsigned card_index = 0; card_index < MAX_VIDEO_CARDS; ++card_index) {
786                 const DeviceSpec device_spec{InputSourceType::CAPTURE_CARD, card_index};
787                 AudioDevice *device = find_audio_device(device_spec);
788                 if (device->interesting_channels != interesting_channels[device_spec]) {
789                         device->interesting_channels = interesting_channels[device_spec];
790                         reset_resampler_mutex_held(device_spec);
791                 }
792         }
793         for (unsigned card_index = 0; card_index < MAX_ALSA_CARDS; ++card_index) {
794                 const DeviceSpec device_spec{InputSourceType::ALSA_INPUT, card_index};
795                 AudioDevice *device = find_audio_device(device_spec);
796                 if (interesting_channels[device_spec].empty()) {
797                         alsa_pool.release_device(card_index);
798                 } else {
799                         alsa_pool.hold_device(card_index);
800                 }
801                 if (device->interesting_channels != interesting_channels[device_spec]) {
802                         device->interesting_channels = interesting_channels[device_spec];
803                         alsa_pool.reset_device(device_spec.index);
804                         reset_resampler_mutex_held(device_spec);
805                 }
806         }
807
808         input_mapping = new_input_mapping;
809 }
810
811 InputMapping AudioMixer::get_input_mapping() const
812 {
813         lock_guard<timed_mutex> lock(audio_mutex);
814         return input_mapping;
815 }
816
817 void AudioMixer::reset_peak(unsigned bus_index)
818 {
819         lock_guard<timed_mutex> lock(audio_mutex);
820         for (unsigned channel = 0; channel < 2; ++channel) {
821                 PeakHistory &history = peak_history[bus_index][channel];
822                 history.current_level = 0.0f;
823                 history.historic_peak = 0.0f;
824                 history.current_peak = 0.0f;
825                 history.last_peak = 0.0f;
826                 history.age_seconds = 0.0f;
827         }
828 }
829
830 AudioMixer *global_audio_mixer = nullptr;