]> git.sesse.net Git - nageru/blob - audio_mixer.cpp
Store an input mapping, and show it in the UI.
[nageru] / audio_mixer.cpp
1 #include "audio_mixer.h"
2
3 #include <assert.h>
4 #include <endian.h>
5 #include <bmusb/bmusb.h>
6 #include <stdio.h>
7 #include <cmath>
8
9 #include "db.h"
10 #include "flags.h"
11 #include "timebase.h"
12
13 using namespace bmusb;
14 using namespace std;
15
16 namespace {
17
18 void convert_fixed24_to_fp32(float *dst, size_t out_channels, const uint8_t *src, size_t in_channels, size_t num_samples)
19 {
20         assert(in_channels >= out_channels);
21         for (size_t i = 0; i < num_samples; ++i) {
22                 for (size_t j = 0; j < out_channels; ++j) {
23                         uint32_t s1 = *src++;
24                         uint32_t s2 = *src++;
25                         uint32_t s3 = *src++;
26                         uint32_t s = s1 | (s1 << 8) | (s2 << 16) | (s3 << 24);
27                         dst[i * out_channels + j] = int(s) * (1.0f / 2147483648.0f);
28                 }
29                 src += 3 * (in_channels - out_channels);
30         }
31 }
32
33 void convert_fixed32_to_fp32(float *dst, size_t out_channels, const uint8_t *src, size_t in_channels, size_t num_samples)
34 {
35         assert(in_channels >= out_channels);
36         for (size_t i = 0; i < num_samples; ++i) {
37                 for (size_t j = 0; j < out_channels; ++j) {
38                         int32_t s = le32toh(*(int32_t *)src);
39                         dst[i * out_channels + j] = s * (1.0f / 2147483648.0f);
40                         src += 4;
41                 }
42                 src += 4 * (in_channels - out_channels);
43         }
44 }
45
46 }  // namespace
47
48 AudioMixer::AudioMixer(unsigned num_cards)
49         : num_cards(num_cards),
50           level_compressor(OUTPUT_FREQUENCY),
51           limiter(OUTPUT_FREQUENCY),
52           compressor(OUTPUT_FREQUENCY)
53 {
54         locut.init(FILTER_HPF, 2);
55
56         set_locut_enabled(global_flags.locut_enabled);
57         set_gain_staging_db(global_flags.initial_gain_staging_db);
58         set_gain_staging_auto(global_flags.gain_staging_auto);
59         set_compressor_enabled(global_flags.compressor_enabled);
60         set_limiter_enabled(global_flags.limiter_enabled);
61         set_final_makeup_gain_auto(global_flags.final_makeup_gain_auto);
62
63         // Generate a very simple, default input mapping.
64         InputMapping::Input input;
65         input.name = "Main";
66         input.input_source_type = InputSourceType::CAPTURE_CARD;
67         input.input_source_index = 0;
68         input.source_channel[0] = 0;
69         input.source_channel[1] = 1;
70
71         input_mapping.inputs.push_back(input);
72 }
73
74 void AudioMixer::reset_card(unsigned card_index)
75 {
76         CaptureCard *card = &cards[card_index];
77
78         unique_lock<mutex> lock(card->audio_mutex);
79         card->resampling_queue.reset(new ResamplingQueue(card_index, OUTPUT_FREQUENCY, OUTPUT_FREQUENCY, 2));
80         card->next_local_pts = 0;
81 }
82
83 void AudioMixer::add_audio(unsigned card_index, const uint8_t *data, unsigned num_samples, AudioFormat audio_format, int64_t frame_length)
84 {
85         CaptureCard *card = &cards[card_index];
86
87         // Convert the audio to stereo fp32.
88         vector<float> audio;
89         audio.resize(num_samples * 2);
90         switch (audio_format.bits_per_sample) {
91         case 0:
92                 assert(num_samples == 0);
93                 break;
94         case 24:
95                 convert_fixed24_to_fp32(&audio[0], 2, data, audio_format.num_channels, num_samples);
96                 break;
97         case 32:
98                 convert_fixed32_to_fp32(&audio[0], 2, data, audio_format.num_channels, num_samples);
99                 break;
100         default:
101                 fprintf(stderr, "Cannot handle audio with %u bits per sample\n", audio_format.bits_per_sample);
102                 assert(false);
103         }
104
105         // Now add it.
106         {
107                 unique_lock<mutex> lock(card->audio_mutex);
108
109                 int64_t local_pts = card->next_local_pts;
110                 card->resampling_queue->add_input_samples(local_pts / double(TIMEBASE), audio.data(), num_samples);
111                 card->next_local_pts = local_pts + frame_length;
112         }
113 }
114
115 void AudioMixer::add_silence(unsigned card_index, unsigned samples_per_frame, unsigned num_frames, int64_t frame_length)
116 {
117         CaptureCard *card = &cards[card_index];
118         unique_lock<mutex> lock(card->audio_mutex);
119
120         vector<float> silence(samples_per_frame * 2, 0.0f);
121         for (unsigned i = 0; i < num_frames; ++i) {
122                 card->resampling_queue->add_input_samples(card->next_local_pts / double(TIMEBASE), silence.data(), samples_per_frame);
123                 // Note that if the format changed in the meantime, we have
124                 // no way of detecting that; we just have to assume the frame length
125                 // is always the same.
126                 card->next_local_pts += frame_length;
127         }
128 }
129
130 vector<float> AudioMixer::get_output(double pts, unsigned num_samples, ResamplingQueue::RateAdjustmentPolicy rate_adjustment_policy)
131 {
132         vector<float> samples_card;
133         vector<float> samples_out;
134         samples_out.resize(num_samples * 2);
135
136         // TODO: Allow more flexible input mapping.
137         for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
138                 samples_card.resize(num_samples * 2);
139                 {
140                         unique_lock<mutex> lock(cards[card_index].audio_mutex);
141                         cards[card_index].resampling_queue->get_output_samples(
142                                 pts,
143                                 &samples_card[0],
144                                 num_samples,
145                                 rate_adjustment_policy);
146                 }
147
148                 float volume = from_db(cards[card_index].fader_volume_db);
149                 if (card_index == 0) {
150                         for (unsigned i = 0; i < num_samples * 2; ++i) {
151                                 samples_out[i] = samples_card[i] * volume;
152                         }
153                 } else {
154                         for (unsigned i = 0; i < num_samples * 2; ++i) {
155                                 samples_out[i] += samples_card[i] * volume;
156                         }
157                 }
158         }
159
160         // Cut away everything under 120 Hz (or whatever the cutoff is);
161         // we don't need it for voice, and it will reduce headroom
162         // and confuse the compressor. (In particular, any hums at 50 or 60 Hz
163         // should be dampened.)
164         if (locut_enabled) {
165                 locut.render(samples_out.data(), samples_out.size() / 2, locut_cutoff_hz * 2.0 * M_PI / OUTPUT_FREQUENCY, 0.5f);
166         }
167
168         {
169                 unique_lock<mutex> lock(compressor_mutex);
170
171                 // Apply a level compressor to get the general level right.
172                 // Basically, if it's over about -40 dBFS, we squeeze it down to that level
173                 // (or more precisely, near it, since we don't use infinite ratio),
174                 // then apply a makeup gain to get it to -14 dBFS. -14 dBFS is, of course,
175                 // entirely arbitrary, but from practical tests with speech, it seems to
176                 // put ut around -23 LUFS, so it's a reasonable starting point for later use.
177                 {
178                         if (level_compressor_enabled) {
179                                 float threshold = 0.01f;   // -40 dBFS.
180                                 float ratio = 20.0f;
181                                 float attack_time = 0.5f;
182                                 float release_time = 20.0f;
183                                 float makeup_gain = from_db(ref_level_dbfs - (-40.0f));  // +26 dB.
184                                 level_compressor.process(samples_out.data(), samples_out.size() / 2, threshold, ratio, attack_time, release_time, makeup_gain);
185                                 gain_staging_db = to_db(level_compressor.get_attenuation() * makeup_gain);
186                         } else {
187                                 // Just apply the gain we already had.
188                                 float g = from_db(gain_staging_db);
189                                 for (size_t i = 0; i < samples_out.size(); ++i) {
190                                         samples_out[i] *= g;
191                                 }
192                         }
193                 }
194
195         #if 0
196                 printf("level=%f (%+5.2f dBFS) attenuation=%f (%+5.2f dB) end_result=%+5.2f dB\n",
197                         level_compressor.get_level(), to_db(level_compressor.get_level()),
198                         level_compressor.get_attenuation(), to_db(level_compressor.get_attenuation()),
199                         to_db(level_compressor.get_level() * level_compressor.get_attenuation() * makeup_gain));
200         #endif
201
202         //      float limiter_att, compressor_att;
203
204                 // The real compressor.
205                 if (compressor_enabled) {
206                         float threshold = from_db(compressor_threshold_dbfs);
207                         float ratio = 20.0f;
208                         float attack_time = 0.005f;
209                         float release_time = 0.040f;
210                         float makeup_gain = 2.0f;  // +6 dB.
211                         compressor.process(samples_out.data(), samples_out.size() / 2, threshold, ratio, attack_time, release_time, makeup_gain);
212         //              compressor_att = compressor.get_attenuation();
213                 }
214
215                 // Finally a limiter at -4 dB (so, -10 dBFS) to take out the worst peaks only.
216                 // Note that since ratio is not infinite, we could go slightly higher than this.
217                 if (limiter_enabled) {
218                         float threshold = from_db(limiter_threshold_dbfs);
219                         float ratio = 30.0f;
220                         float attack_time = 0.0f;  // Instant.
221                         float release_time = 0.020f;
222                         float makeup_gain = 1.0f;  // 0 dB.
223                         limiter.process(samples_out.data(), samples_out.size() / 2, threshold, ratio, attack_time, release_time, makeup_gain);
224         //              limiter_att = limiter.get_attenuation();
225                 }
226
227         //      printf("limiter=%+5.1f  compressor=%+5.1f\n", to_db(limiter_att), to_db(compressor_att));
228         }
229
230         // At this point, we are most likely close to +0 LU, but all of our
231         // measurements have been on raw sample values, not R128 values.
232         // So we have a final makeup gain to get us to +0 LU; the gain
233         // adjustments required should be relatively small, and also, the
234         // offset shouldn't change much (only if the type of audio changes
235         // significantly). Thus, we shoot for updating this value basically
236         // “whenever we process buffers”, since the R128 calculation isn't exactly
237         // something we get out per-sample.
238         //
239         // Note that there's a feedback loop here, so we choose a very slow filter
240         // (half-time of 30 seconds).
241         double target_loudness_factor, alpha;
242         double loudness_lu = loudness_lufs - ref_level_lufs;
243         double current_makeup_lu = to_db(final_makeup_gain);
244         target_loudness_factor = final_makeup_gain * from_db(-loudness_lu);
245
246         // If we're outside +/- 5 LU uncorrected, we don't count it as
247         // a normal signal (probably silence) and don't change the
248         // correction factor; just apply what we already have.
249         if (fabs(loudness_lu - current_makeup_lu) >= 5.0 || !final_makeup_gain_auto) {
250                 alpha = 0.0;
251         } else {
252                 // Formula adapted from
253                 // https://en.wikipedia.org/wiki/Low-pass_filter#Simple_infinite_impulse_response_filter.
254                 const double half_time_s = 30.0;
255                 const double fc_mul_2pi_delta_t = 1.0 / (half_time_s * OUTPUT_FREQUENCY);
256                 alpha = fc_mul_2pi_delta_t / (fc_mul_2pi_delta_t + 1.0);
257         }
258
259         {
260                 unique_lock<mutex> lock(compressor_mutex);
261                 double m = final_makeup_gain;
262                 for (size_t i = 0; i < samples_out.size(); i += 2) {
263                         samples_out[i + 0] *= m;
264                         samples_out[i + 1] *= m;
265                         m += (target_loudness_factor - m) * alpha;
266                 }
267                 final_makeup_gain = m;
268         }
269
270         return samples_out;
271 }
272
273 vector<string> AudioMixer::get_names() const
274 {
275         vector<string> names;
276         for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
277                 const CaptureCard *card = &cards[card_index];
278                 unique_lock<mutex> lock(card->audio_mutex);
279                 names.push_back(card->name);
280         }
281         return names;
282 }
283
284 void AudioMixer::set_name(unsigned card_index, const string &name)
285 {
286         CaptureCard *card = &cards[card_index];
287         unique_lock<mutex> lock(card->audio_mutex);
288         card->name = name;
289 }
290
291 void AudioMixer::set_input_mapping(const InputMapping &input_mapping)
292 {
293         lock_guard<mutex> lock(mapping_mutex);
294         this->input_mapping = input_mapping;
295 }
296
297 InputMapping AudioMixer::get_input_mapping() const
298 {
299         lock_guard<mutex> lock(mapping_mutex);
300         return input_mapping;
301 }