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