]> git.sesse.net Git - nageru/blob - resampling_queue.cpp
Fix an issue where the mixer lagging too much behind CEF would cause us to display...
[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 <stdio.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <zita-resampler/vresampler.h>
27 #include <algorithm>
28 #include <cmath>
29
30 using namespace std;
31 using namespace std::chrono;
32
33 ResamplingQueue::ResamplingQueue(unsigned card_num, unsigned freq_in, unsigned freq_out, unsigned num_channels, double expected_delay_seconds)
34         : card_num(card_num), freq_in(freq_in), freq_out(freq_out), num_channels(num_channels),
35           current_estimated_freq_in(freq_in),
36           ratio(double(freq_out) / double(freq_in)), expected_delay(expected_delay_seconds * OUTPUT_FREQUENCY)
37 {
38         vresampler.setup(ratio, num_channels, /*hlen=*/32);
39
40         // Prime the resampler so there's no more delay.
41         vresampler.inp_count = vresampler.inpsize() / 2 - 1;
42         vresampler.out_count = 1048576;
43         vresampler.process ();
44 }
45
46 void ResamplingQueue::add_input_samples(steady_clock::time_point ts, const float *samples, ssize_t num_samples, ResamplingQueue::RateAdjustmentPolicy rate_adjustment_policy)
47 {
48         if (num_samples == 0) {
49                 return;
50         }
51
52         bool good_sample = (rate_adjustment_policy == ADJUST_RATE);
53         if (good_sample && a1.good_sample) {
54                 a0 = a1;
55         }
56         a1.ts = ts;
57         a1.input_samples_received += num_samples;
58         a1.good_sample = good_sample;
59         if (a0.good_sample && a1.good_sample) {
60                 current_estimated_freq_in = (a1.input_samples_received - a0.input_samples_received) / duration<double>(a1.ts - a0.ts).count();
61                 assert(current_estimated_freq_in >= 0.0);
62
63                 // Bound the frequency, so that a single wild result won't throw the filter off guard.
64                 current_estimated_freq_in = min(current_estimated_freq_in, 1.2 * freq_in);
65                 current_estimated_freq_in = max(current_estimated_freq_in, 0.8 * freq_in);
66         }
67
68         buffer.insert(buffer.end(), samples, samples + num_samples * num_channels);
69 }
70
71 bool ResamplingQueue::get_output_samples(steady_clock::time_point ts, float *samples, ssize_t num_samples, ResamplingQueue::RateAdjustmentPolicy rate_adjustment_policy)
72 {
73         assert(num_samples > 0);
74         if (a1.input_samples_received == 0) {
75                 // No data yet, just return zeros.
76                 memset(samples, 0, num_samples * num_channels * sizeof(float));
77                 return true;
78         }
79
80         // This can happen when we get dropped frames on the master card.
81         if (duration<double>(ts.time_since_epoch()).count() <= 0.0) {
82                 rate_adjustment_policy = DO_NOT_ADJUST_RATE;
83         }
84
85         if (rate_adjustment_policy == ADJUST_RATE && (a0.good_sample || a1.good_sample)) {
86                 // Estimate the current number of input samples produced at
87                 // this instant in time, by extrapolating from the last known
88                 // good point. Note that we could be extrapolating backward or
89                 // forward, depending on the timing of the calls.
90                 const InputPoint &base_point = a1.good_sample ? a1 : a0;
91                 const double input_samples_received = base_point.input_samples_received +
92                         current_estimated_freq_in * duration<double>(ts - base_point.ts).count();
93
94                 // Estimate the number of input samples _consumed_ after we've run the resampler.
95                 const double input_samples_consumed = total_consumed_samples +
96                         num_samples / (ratio * rcorr);
97
98                 double actual_delay = input_samples_received - input_samples_consumed;
99                 actual_delay += vresampler.inpdist();    // Delay in the resampler itself.
100                 double err = actual_delay - expected_delay;
101                 if (first_output) {
102                         // Before the very first block, insert artificial delay based on our initial estimate,
103                         // so that we don't need a long period to stabilize at the beginning.
104                         if (err < 0.0) {
105                                 int delay_samples_to_add = lrintf(-err);
106                                 for (ssize_t i = 0; i < delay_samples_to_add * num_channels; ++i) {
107                                         buffer.push_front(0.0f);
108                                 }
109                                 total_consumed_samples -= delay_samples_to_add;  // Equivalent to increasing input_samples_received on a0 and a1.
110                                 err += delay_samples_to_add;
111                         } else if (err > 0.0) {
112                                 int delay_samples_to_remove = min<int>(lrintf(err), buffer.size() / num_channels);
113                                 buffer.erase(buffer.begin(), buffer.begin() + delay_samples_to_remove * num_channels);
114                                 total_consumed_samples += delay_samples_to_remove;
115                                 err -= delay_samples_to_remove;
116                         }
117                 }
118                 first_output = false;
119
120                 // Compute loop filter coefficients for the two filters. We need to compute them
121                 // every time, since they depend on the number of samples the user asked for.
122                 //
123                 // The loop bandwidth is at 0.02 Hz; our jitter is pretty large
124                 // since none of the threads involved run at real-time priority.
125                 // However, the first four seconds, we use a larger loop bandwidth (2 Hz),
126                 // because there's a lot going on during startup, and thus the
127                 // initial estimate might be tainted by jitter during that phase,
128                 // and we want to converge faster.
129                 //
130                 // NOTE: The above logic might only hold during Nageru startup
131                 // (we start ResamplingQueues also when we e.g. switch sound sources),
132                 // but in general, a little bit of increased timing jitter is acceptable
133                 // right after a setup change like this.
134                 double loop_bandwidth_hz = (total_consumed_samples < 4 * freq_in) ? 0.2 : 0.02;
135
136                 // Set filters. The first filter much wider than the first one (20x as wide).
137                 double w = (2.0 * M_PI) * loop_bandwidth_hz * num_samples / freq_out;
138                 double w0 = 1.0 - exp(-20.0 * w);
139                 double w1 = w * 1.5 / num_samples / ratio;
140                 double w2 = w / 1.5;
141
142                 // Filter <err> through the loop filter to find the correction ratio.
143                 z1 += w0 * (w1 * err - z1);
144                 z2 += w0 * (z1 - z2);
145                 z3 += w2 * z2;
146                 rcorr = 1.0 - z2 - z3;
147                 if (rcorr > 1.05) rcorr = 1.05;
148                 if (rcorr < 0.95) rcorr = 0.95;
149                 assert(!isnan(rcorr));
150                 vresampler.set_rratio(rcorr);
151         }
152
153         // Finally actually resample, producing exactly <num_samples> output samples.
154         vresampler.out_data = samples;
155         vresampler.out_count = num_samples;
156         while (vresampler.out_count > 0) {
157                 if (buffer.empty()) {
158                         // This should never happen unless delay is set way too low,
159                         // or we're dropping a lot of data.
160                         fprintf(stderr, "Card %u: PANIC: Out of input samples to resample, still need %d output samples! (correction factor is %f)\n",
161                                 card_num, int(vresampler.out_count), rcorr);
162                         memset(vresampler.out_data, 0, vresampler.out_count * num_channels * sizeof(float));
163
164                         // Reset the loop filter.
165                         z1 = z2 = z3 = 0.0;
166
167                         return false;
168                 }
169
170                 float inbuf[1024];
171                 size_t num_input_samples = sizeof(inbuf) / (sizeof(float) * num_channels);
172                 if (num_input_samples * num_channels > buffer.size()) {
173                         num_input_samples = buffer.size() / num_channels;
174                 }
175                 copy(buffer.begin(), buffer.begin() + num_input_samples * num_channels, inbuf);
176
177                 vresampler.inp_count = num_input_samples;
178                 vresampler.inp_data = inbuf;
179
180                 int err = vresampler.process();
181                 assert(err == 0);
182
183                 size_t consumed_samples = num_input_samples - vresampler.inp_count;
184                 total_consumed_samples += consumed_samples;
185                 buffer.erase(buffer.begin(), buffer.begin() + consumed_samples * num_channels);
186         }
187         return true;
188 }