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