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