]> git.sesse.net Git - nageru/blob - nageru/resampling_queue.cpp
IWYU-fix nageru/*.h.
[nageru] / nageru / resampling_queue.cpp
1 // Parts of the code is adapted from Adriaensen's project Zita-ajbridge
2 // (as of November 2015), although it has been heavily reworked for this use
3 // case. Original copyright follows:
4 //
5 //  Copyright (C) 2012-2015 Fons Adriaensen <fons@linuxaudio.org>
6 //    
7 //  This program is free software; you can redistribute it and/or modify
8 //  it under the terms of the GNU General Public License as published by
9 //  the Free Software Foundation; either version 3 of the License, or
10 //  (at your option) any later version.
11 //
12 //  This program is distributed in the hope that it will be useful,
13 //  but WITHOUT ANY WARRANTY; without even the implied warranty of
14 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 //  GNU General Public License for more details.
16 //
17 //  You should have received a copy of the GNU General Public License
18 //  along with this program.  If not, see <http://www.gnu.org/licenses/>.
19
20 #include "resampling_queue.h"
21
22 #include <assert.h>
23 #include <math.h>
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <string.h>
27 #include <zita-resampler/vresampler.h>
28 #include <algorithm>
29
30 #include "shared/shared_defs.h"
31
32 using namespace std;
33 using namespace std::chrono;
34
35 ResamplingQueue::ResamplingQueue(const std::string &debug_description, unsigned freq_in, unsigned freq_out, unsigned num_channels, double expected_delay_seconds)
36         : debug_description(debug_description), freq_in(freq_in), freq_out(freq_out), num_channels(num_channels),
37           current_estimated_freq_in(freq_in),
38           ratio(double(freq_out) / double(freq_in)), expected_delay(expected_delay_seconds * OUTPUT_FREQUENCY)
39 {
40         vresampler.setup(ratio, num_channels, /*hlen=*/32);
41
42         // Prime the resampler so there's no more delay.
43         vresampler.inp_count = vresampler.inpsize() / 2 - 1;
44         vresampler.out_count = 1048576;
45         vresampler.process ();
46 }
47
48 void ResamplingQueue::add_input_samples(steady_clock::time_point ts, const float *samples, ssize_t num_samples, ResamplingQueue::RateAdjustmentPolicy rate_adjustment_policy)
49 {
50         if (num_samples == 0) {
51                 return;
52         }
53
54         assert(duration<double>(ts.time_since_epoch()).count() >= 0.0);
55
56         bool good_sample = (rate_adjustment_policy == ADJUST_RATE);
57         if (good_sample && a1.good_sample) {
58                 a0 = a1;
59         }
60         a1.ts = ts;
61         a1.input_samples_received += num_samples;
62         a1.good_sample = good_sample;
63         if (a0.good_sample && a1.good_sample) {
64                 current_estimated_freq_in = (a1.input_samples_received - a0.input_samples_received) / duration<double>(a1.ts - a0.ts).count();
65                 if (!(current_estimated_freq_in >= 0.0)) {
66                         fprintf(stderr, "%s: PANIC: Input audio clock going backwards, ignoring.\n",
67                                 debug_description.c_str());
68                         current_estimated_freq_in = freq_in;
69                 }
70
71                 // Bound the frequency, so that a single wild result won't throw the filter off guard.
72                 current_estimated_freq_in = min(current_estimated_freq_in, 1.2 * freq_in);
73                 current_estimated_freq_in = max(current_estimated_freq_in, 0.8 * freq_in);
74         }
75
76         buffer.insert(buffer.end(), samples, samples + num_samples * num_channels);
77 }
78
79 bool ResamplingQueue::get_output_samples(steady_clock::time_point ts, float *samples, ssize_t num_samples, ResamplingQueue::RateAdjustmentPolicy rate_adjustment_policy)
80 {
81         assert(num_samples > 0);
82         if (a1.input_samples_received == 0) {
83                 // No data yet, just return zeros.
84                 memset(samples, 0, num_samples * num_channels * sizeof(float));
85                 return true;
86         }
87
88         // This can happen when we get dropped frames on the master card.
89         if (duration<double>(ts.time_since_epoch()).count() <= 0.0) {
90                 rate_adjustment_policy = DO_NOT_ADJUST_RATE;
91         }
92
93         if (rate_adjustment_policy == ADJUST_RATE && (a0.good_sample || a1.good_sample)) {
94                 // Estimate the current number of input samples produced at
95                 // this instant in time, by extrapolating from the last known
96                 // good point. Note that we could be extrapolating backward or
97                 // forward, depending on the timing of the calls.
98                 const InputPoint &base_point = a1.good_sample ? a1 : a0;
99                 assert(duration<double>(base_point.ts.time_since_epoch()).count() >= 0.0);
100
101                 // NOTE: Due to extrapolation, input_samples_received can
102                 // actually go negative here the few first calls (ie., we asked
103                 // about a timestamp where we hadn't actually started producing
104                 // samples yet), but that is harmless.
105                 const double input_samples_received = base_point.input_samples_received +
106                         current_estimated_freq_in * duration<double>(ts - base_point.ts).count();
107
108                 // Estimate the number of input samples _consumed_ after we've run the resampler.
109                 const double input_samples_consumed = total_consumed_samples +
110                         num_samples / (ratio * rcorr);
111
112                 double actual_delay = input_samples_received - input_samples_consumed;
113                 actual_delay += vresampler.inpdist();    // Delay in the resampler itself.
114                 double err = actual_delay - expected_delay;
115                 if (first_output) {
116                         // Before the very first block, insert artificial delay based on our initial estimate,
117                         // so that we don't need a long period to stabilize at the beginning.
118                         if (err < 0.0) {
119                                 int delay_samples_to_add = lrintf(-err);
120                                 for (ssize_t i = 0; i < delay_samples_to_add * int(num_channels); ++i) {
121                                         buffer.push_front(0.0f);
122                                 }
123                                 total_consumed_samples -= delay_samples_to_add;  // Equivalent to increasing input_samples_received on a0 and a1.
124                                 err += delay_samples_to_add;
125                         } else if (err > 0.0) {
126                                 int delay_samples_to_remove = min<int>(lrintf(err), buffer.size() / num_channels);
127                                 buffer.erase(buffer.begin(), buffer.begin() + delay_samples_to_remove * num_channels);
128                                 total_consumed_samples += delay_samples_to_remove;
129                                 err -= delay_samples_to_remove;
130                         }
131                 }
132                 first_output = false;
133
134                 // Compute loop filter coefficients for the two filters. We need to compute them
135                 // every time, since they depend on the number of samples the user asked for.
136                 //
137                 // The loop bandwidth is at 0.02 Hz; our jitter is pretty large
138                 // since none of the threads involved run at real-time priority.
139                 // However, the first four seconds, we use a larger loop bandwidth (2 Hz),
140                 // because there's a lot going on during startup, and thus the
141                 // initial estimate might be tainted by jitter during that phase,
142                 // and we want to converge faster.
143                 //
144                 // NOTE: The above logic might only hold during Nageru startup
145                 // (we start ResamplingQueues also when we e.g. switch sound sources),
146                 // but in general, a little bit of increased timing jitter is acceptable
147                 // right after a setup change like this.
148                 double loop_bandwidth_hz = (total_consumed_samples < 4 * int(freq_in)) ? 0.2 : 0.02;
149
150                 // Set filters. The first filter much wider than the first one (20x as wide).
151                 double w = (2.0 * M_PI) * loop_bandwidth_hz * num_samples / freq_out;
152                 double w0 = 1.0 - exp(-20.0 * w);
153                 double w1 = w * 1.5 / num_samples / ratio;
154                 double w2 = w / 1.5;
155
156                 // Filter <err> through the loop filter to find the correction ratio.
157                 z1 += w0 * (w1 * err - z1);
158                 z2 += w0 * (z1 - z2);
159                 z3 += w2 * z2;
160                 rcorr = 1.0 - z2 - z3;
161                 if (rcorr > 1.05) rcorr = 1.05;
162                 if (rcorr < 0.95) rcorr = 0.95;
163                 assert(!isnan(rcorr));
164                 vresampler.set_rratio(rcorr);
165         }
166
167         // Finally actually resample, producing exactly <num_samples> output samples.
168         vresampler.out_data = samples;
169         vresampler.out_count = num_samples;
170         while (vresampler.out_count > 0) {
171                 if (buffer.empty()) {
172                         // This should never happen unless delay is set way too low,
173                         // or we're dropping a lot of data.
174                         fprintf(stderr, "%s: PANIC: Out of input samples to resample, still need %d output samples! (correction factor is %f)\n",
175                                 debug_description.c_str(), int(vresampler.out_count), rcorr);
176                         memset(vresampler.out_data, 0, vresampler.out_count * num_channels * sizeof(float));
177
178                         // Reset the loop filter.
179                         z1 = z2 = z3 = 0.0;
180
181                         return false;
182                 }
183
184                 float inbuf[1024];
185                 size_t num_input_samples = sizeof(inbuf) / (sizeof(float) * num_channels);
186                 if (num_input_samples * num_channels > buffer.size()) {
187                         num_input_samples = buffer.size() / num_channels;
188                 }
189                 copy(buffer.begin(), buffer.begin() + num_input_samples * num_channels, inbuf);
190
191                 vresampler.inp_count = num_input_samples;
192                 vresampler.inp_data = inbuf;
193
194                 int err = vresampler.process();
195                 assert(err == 0);
196
197                 size_t consumed_samples = num_input_samples - vresampler.inp_count;
198                 total_consumed_samples += consumed_samples;
199                 buffer.erase(buffer.begin(), buffer.begin() + consumed_samples * num_channels);
200         }
201         return true;
202 }