JackFilters.h 11.4 KB
Newer Older
sletz's avatar
sletz committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/*
Copyright (C) 2008 Grame

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

*/

#ifndef __JackFilters__
#define __JackFilters__

#include "jack.h"
sletz's avatar
sletz committed
24
#include "JackAtomicState.h"
sletz's avatar
sletz committed
25
#include <math.h>
26
#include <stdlib.h>
sletz's avatar
sletz committed
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56

namespace Jack
{

    #define MAX_SIZE 64
    
	struct JackFilter 
    {
    
        jack_time_t fTable[MAX_SIZE];
        
        JackFilter()
        {
            for (int i = 0; i < MAX_SIZE; i++)
                fTable[i] = 0;
        }
        
        void AddValue(jack_time_t val)
        {
            memcpy(&fTable[1], &fTable[0], sizeof(jack_time_t) * (MAX_SIZE - 1));
            fTable[0] = val;
        }
        
        jack_time_t GetVal()
        {
            jack_time_t mean = 0;
            for (int i = 0; i < MAX_SIZE; i++)
                mean += fTable[i];
            return mean / MAX_SIZE;
        }
57
58
        
    } POST_PACKED_STRUCTURE;
sletz's avatar
sletz committed
59
    
sletz's avatar
sletz committed
60
61
62
63
64
65
66
67
68
69
70
71
72
73
    class JackDelayLockedLoop
    {
    
        private:
        
            jack_nframes_t fFrames;
            jack_time_t	fCurrentWakeup;
            jack_time_t	fCurrentCallback;
            jack_time_t	fNextWakeUp;
            float fSecondOrderIntegrator;
            jack_nframes_t fBufferSize;
            jack_nframes_t fSampleRate;
            jack_time_t fPeriodUsecs;
            float fFilterCoefficient;	/* set once, never altered */
sletz's avatar
sletz committed
74
            bool fUpdating;
sletz's avatar
sletz committed
75
76
77
        
        public:
        
sletz's avatar
sletz committed
78
79
80
            JackDelayLockedLoop()
            {}
            
sletz's avatar
sletz committed
81
            JackDelayLockedLoop(jack_nframes_t buffer_size, jack_nframes_t sample_rate)
sletz's avatar
sletz committed
82
83
84
85
86
            {
                Init(buffer_size, sample_rate);
            }
            
            void Init(jack_nframes_t buffer_size, jack_nframes_t sample_rate)
sletz's avatar
sletz committed
87
88
89
90
91
92
93
94
95
96
97
98
99
100
            {
                fFrames = 0;
                fCurrentWakeup = 0;
                fCurrentCallback = 0;
                fNextWakeUp = 0;
                fFilterCoefficient = 0.01f;
                fSecondOrderIntegrator = 0.0f;
                fBufferSize = buffer_size;
                fSampleRate = sample_rate;
                fPeriodUsecs = jack_time_t(1000000.f / fSampleRate * fBufferSize);	// in microsec
            }
        
            void Init(jack_time_t callback_usecs)
            {
sletz's avatar
sletz committed
101
102
                fFrames = 0;
                fCurrentWakeup = 0;
sletz's avatar
sletz committed
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
                fSecondOrderIntegrator = 0.0f;
                fCurrentCallback = callback_usecs;
                fNextWakeUp = callback_usecs + fPeriodUsecs;
            }
            
            void IncFrame(jack_time_t callback_usecs)
            {
                float delta = (int64_t)callback_usecs - (int64_t)fNextWakeUp;
                fCurrentWakeup = fNextWakeUp;
                fCurrentCallback = callback_usecs;
                fFrames += fBufferSize;
                fSecondOrderIntegrator += 0.5f * fFilterCoefficient * delta;
                fNextWakeUp = fCurrentWakeup + fPeriodUsecs + (int64_t) floorf((fFilterCoefficient * (delta + fSecondOrderIntegrator)));
            }
            
            jack_nframes_t Time2Frames(jack_time_t time)
            {
120
                long delta = (long) rint(((double) ((long long)(time - fCurrentWakeup)) / ((long long)(fNextWakeUp - fCurrentWakeup))) * fBufferSize);
121
                return (delta < 0) ? ((fFrames > 0) ? fFrames : 1) : (fFrames + delta);
sletz's avatar
sletz committed
122
123
124
125
            }
            
            jack_time_t Frames2Time(jack_nframes_t frames)
            {
126
                long delta = (long) rint(((double) ((long long)(frames - fFrames)) * ((long long)(fNextWakeUp - fCurrentWakeup))) / fBufferSize);
127
                return (delta < 0) ? ((fCurrentWakeup > 0) ? fCurrentWakeup : 1) : (fCurrentWakeup + delta);
sletz's avatar
sletz committed
128
129
            }
            
sletz's avatar
sletz committed
130
            jack_nframes_t CurFrame()
sletz's avatar
sletz committed
131
            {
sletz's avatar
sletz committed
132
                return fFrames;
sletz's avatar
sletz committed
133
            }
sletz's avatar
sletz committed
134
135
                 
            jack_time_t CurTime()
sletz's avatar
sletz committed
136
            {
sletz's avatar
sletz committed
137
                return fCurrentWakeup;
sletz's avatar
sletz committed
138
            }
sletz's avatar
sletz committed
139
  
140
    } POST_PACKED_STRUCTURE;
sletz's avatar
sletz committed
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
    
    class JackAtomicDelayLockedLoop : public JackAtomicState<JackDelayLockedLoop>
    {
         public:
         
            JackAtomicDelayLockedLoop(jack_nframes_t buffer_size, jack_nframes_t sample_rate)
            {
                fState[0].Init(buffer_size, sample_rate);
                fState[1].Init(buffer_size, sample_rate);
            }
            
            void Init(jack_time_t callback_usecs)
            {
                JackDelayLockedLoop* dll = WriteNextStateStart();
                dll->Init(callback_usecs);
                WriteNextStateStop();
                TrySwitchState(); // always succeed since there is only one writer
            }
            
160
161
162
163
164
165
166
167
            void Init(jack_nframes_t buffer_size, jack_nframes_t sample_rate)
            {
                JackDelayLockedLoop* dll = WriteNextStateStart();
                dll->Init(buffer_size, sample_rate);
                WriteNextStateStop();
                TrySwitchState(); // always succeed since there is only one writer
            }
            
sletz's avatar
sletz committed
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
            void IncFrame(jack_time_t callback_usecs)
            {
                JackDelayLockedLoop* dll = WriteNextStateStart();
                dll->IncFrame(callback_usecs);
                WriteNextStateStop();
                TrySwitchState(); // always succeed since there is only one writer
            }
            
            jack_nframes_t Time2Frames(jack_time_t time)
            {
                UInt16 next_index = GetCurrentIndex();
                UInt16 cur_index;
                jack_nframes_t res;
                
                do {
                    cur_index = next_index;
                    res = ReadCurrentState()->Time2Frames(time);
                    next_index = GetCurrentIndex();
                } while (cur_index != next_index); // Until a coherent state has been read
                
                return res;
            }
             
            jack_time_t Frames2Time(jack_nframes_t frames)
            {
                UInt16 next_index = GetCurrentIndex();
                UInt16 cur_index;
                jack_time_t res;
                
                do {
                    cur_index = next_index;
                    res = ReadCurrentState()->Frames2Time(frames);
                    next_index = GetCurrentIndex();
                } while (cur_index != next_index); // Until a coherent state has been read
                
                return res;
            }
205
    } POST_PACKED_STRUCTURE;
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
    
    /*
    Torben Hohn PI controler from JACK1
    */
    
    struct JackPIControler {
    
        double resample_mean;
        double static_resample_factor;

        double* offset_array;
        double* window_array;
        int offset_differential_index;

        double offset_integral;

        double catch_factor;
        double catch_factor2;
        double pclamp;
        double controlquant;
        int smooth_size;
    
        double hann(double x)
        {
            return 0.5 * (1.0 - cos(2 * M_PI * x));
        }
        
        JackPIControler(double resample_factor, int fir_size)
        {
            resample_mean = resample_factor;
            static_resample_factor = resample_factor;
            offset_array = new double[fir_size];
            window_array = new double[fir_size];
            offset_differential_index = 0;
            offset_integral = 0.0;
            smooth_size = fir_size;
            
            for (int i = 0; i < fir_size; i++) {
                offset_array[i] = 0.0;
                window_array[i] = hann(double(i) / (double(fir_size) - 1.0));
            }

            // These values could be configurable
            catch_factor = 100000;
            catch_factor2 = 10000;
            pclamp = 15.0;
            controlquant = 10000.0;
        }
        
        ~JackPIControler()
        {
            delete[] offset_array;
            delete[] window_array;
        }
        
        void Init(double resample_factor)
        {
            resample_mean = resample_factor;
            static_resample_factor = resample_factor;
        }
        
267
        /*
268
269
270
271
272
273
        double GetRatio(int fill_level)
        {
            double offset = fill_level;

            // Save offset.
            offset_array[(offset_differential_index++) % smooth_size] = offset;
274
            
275
276
277
278
279
280
            // Build the mean of the windowed offset array basically fir lowpassing.
            double smooth_offset = 0.0;
            for (int i = 0; i < smooth_size; i++) {
                smooth_offset += offset_array[(i + offset_differential_index - 1) % smooth_size] * window_array[i];
            }
            smooth_offset /= double(smooth_size);
281
        
282
283
284
285
286
287
288
            // This is the integral of the smoothed_offset
            offset_integral += smooth_offset;

            // Clamp offset : the smooth offset still contains unwanted noise which would go straigth onto the resample coeff.
            // It only used in the P component and the I component is used for the fine tuning anyways.
            if (fabs(smooth_offset) < pclamp)
                smooth_offset = 0.0;
289
         
290
291
292
293
294
            // Ok, now this is the PI controller. 
            // u(t) = K * (e(t) + 1/T \int e(t') dt')
            // Kp = 1/catch_factor and T = catch_factor2  Ki = Kp/T 
            double current_resample_factor 
                = static_resample_factor - smooth_offset / catch_factor - offset_integral / catch_factor / catch_factor2;
295
            
296
297
298
299
300
301
302
            // Now quantize this value around resample_mean, so that the noise which is in the integral component doesnt hurt.
            current_resample_factor = floor((current_resample_factor - resample_mean) * controlquant + 0.5) / controlquant + resample_mean;

            // Calculate resample_mean so we can init ourselves to saner values.
            resample_mean = 0.9999 * resample_mean + 0.0001 * current_resample_factor;
            return current_resample_factor;
        }
303
304
305
306
307
308
309
310
311
312
313
314
315
316
        */

        double GetRatio(int error)
        {
            double smooth_offset = error;

            // This is the integral of the smoothed_offset
            offset_integral += smooth_offset;

            // Ok, now this is the PI controller. 
            // u(t) = K * (e(t) + 1/T \int e(t') dt')
            // Kp = 1/catch_factor and T = catch_factor2 Ki = Kp/T 
            return static_resample_factor - smooth_offset/catch_factor - offset_integral/catch_factor/catch_factor2;
        }
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
        
        void OurOfBounds()
        {
            int i;
            // Set the resample_rate... we need to adjust the offset integral, to do this.
            // first look at the PI controller, this code is just a special case, which should never execute once
            // everything is swung in. 
            offset_integral = - (resample_mean - static_resample_factor) * catch_factor * catch_factor2;
            // Also clear the array. we are beginning a new control cycle.
            for (i = 0; i < smooth_size; i++) {
                offset_array[i] = 0.0;
            }
        }
    
    };
sletz's avatar
sletz committed
332

sletz's avatar
sletz committed
333
334
335
}

#endif