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