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