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