Fix a typo in HiAndLowPass.lua
[ardour.git] / scripts / HiAndLowPass.lua
1 ardour {
2         ["type"]    = "dsp",
3         name        = "a-High/Low Pass Filter",
4         category    = "Filter",
5         license     = "GPLv2",
6         author      = "Ardour Team",
7         description = [[High and Low Pass Filter with de-zipped controls, written in Ardour-Lua]]
8 }
9
10 function dsp_ioconfig ()
11         return
12         {
13                 -- allow any number of I/O as long as port-count matches
14                 { audio_in = -1, audio_out = -1},
15         }
16 end
17
18
19 function dsp_params ()
20         return
21         {
22                 { ["type"] = "input", name = "High Pass Steepness", min = 0, max = 4, default = 1, enum = true, scalepoints =
23                         {
24                                 ["Off"] = 0,
25                                 ["12dB/oct"] = 1,
26                                 ["24dB/oct"] = 2,
27                                 ["36dB/oct"] = 3,
28                                 ["48dB/oct"] = 4,
29                         }
30                 },
31                 { ["type"] = "input", name = "High Pass Cut off frequency", min =   5, max = 20000, default = 100, unit="Hz", logarithmic = true },
32                 { ["type"] = "input", name = "High Pass Resonance",         min = 0.1, max = 6,     default = .707, logarithmic = true },
33
34                 { ["type"] = "input", name = "Low Pass Steepness", min = 0, max = 4, default = 1, enum = true, scalepoints =
35                         {
36                                 ["Off"] = 0,
37                                 ["12dB/oct"] = 1,
38                                 ["24dB/oct"] = 2,
39                                 ["36dB/oct"] = 3,
40                                 ["48dB/oct"] = 4,
41                         }
42                 },
43                 { ["type"] = "input", name = "Low Pass Cut off frequency",  min =  20, max = 20000, default = 18000, unit="Hz", logarithmic = true },
44                 { ["type"] = "input", name = "Low Pass Resonance",          min = 0.1, max = 6,     default = .707, logarithmic = true },
45         }
46 end
47
48 -- these globals are *not* shared between DSP and UI
49 local hp = {}  -- the biquad high-pass filter instances (DSP)
50 local lp = {}  -- the biquad high-pass filter instances (DSP)
51 local filt = nil -- the biquad filter instance (GUI, response)
52 local cur = {0, 0, 0, 0, 0, 0} -- current parameters
53 local lpf = 0.03 -- parameter low-pass filter time-constant
54 local chn = 0 -- channel/filter count
55 local lpf_chunk = 0 -- chunk size for audio processing when interpolating parameters
56
57 local mem = nil -- memory x-fade buffer
58
59 function dsp_init (rate)
60         -- allocate some mix-buffer
61         mem = ARDOUR.DSP.DspShm (8192)
62
63         -- create a table of objects to share with the GUI
64         local tbl = {}
65         tbl['samplerate'] = rate
66         self:table ():set (tbl)
67
68         -- Parameter smoothing: we want to filter out parameter changes that are
69         -- faster than 15Hz, and interpolate between parameter values.
70         -- For performance reasons, we want to ensure that two consecutive values
71         -- of the interpolated "steepness" are less that 1 apart. By choosing the
72         -- interpolation chunk size to be 64 in most cases, but 32 if the rate is
73         -- strictly less than 22kHz (there's only 8kHz in standard rates), we can
74         -- ensure that steepness interpolation will never change the parameter by
75         -- more than ~0.86.
76         lpf_chunk = 64
77         if rate < 22000 then lpf_chunk = 32 end
78         -- We apply a discrete version of the standard RC low-pass, with a cutoff
79         -- frequency of 15Hz. For more information about the underlying math, see
80         -- https://en.wikipedia.org/wiki/Low-pass_filter#Discrete-time_realization
81         -- (here Δt is lpf_chunk / rate)
82         local R = 2 * math.pi * lpf_chunk * 15 -- Hz
83         lpf = R / (R + rate)
84 end
85
86 function dsp_configure (ins, outs)
87         assert (ins:n_audio () == outs:n_audio ())
88         local tbl = self:table ():get () -- get shared memory table
89
90         chn = ins:n_audio ()
91         cur = {0, 0, 0, 0, 0, 0}
92
93         hp = {}
94         lp = {}
95
96         collectgarbage ()
97
98         for c = 1, chn do
99                 hp[c] = {}
100                 lp[c] = {}
101                 -- initialize filters
102                 -- http://manual.ardour.org/lua-scripting/class_reference/#ARDOUR:DSP:Biquad
103
104                 -- A different Biquad is needed for each pass and channel because they
105                 -- remember the last two samples seen during the last call of Biquad:run().
106                 -- For continuity these have to come from the previous audio chunk of the
107                 -- same channel and pass and would be clobbered if the same Biquad was
108                 -- called several times by cycle.
109                 for k = 1,4 do
110                         hp[c][k] = ARDOUR.DSP.Biquad (tbl['samplerate'])
111                         lp[c][k] = ARDOUR.DSP.Biquad (tbl['samplerate'])
112                 end
113         end
114 end
115
116 -- helper functions for parameter interpolation
117 function param_changed (ctrl)
118         for p = 1,6 do
119                 if ctrl[p] ~= cur[p] then
120                         return true
121                 end
122         end
123         return false
124 end
125
126 function low_pass_filter_param (old, new, limit)
127         if math.abs (old - new) < limit  then
128                 return new
129         else
130                 return old + lpf * (new - old)
131         end
132 end
133
134 -- apply parameters, re-compute filter coefficients if needed
135 function apply_params (ctrl)
136         if not param_changed (ctrl) then
137                 return
138         end
139
140         -- low-pass filter ctrl parameter values, smooth transition
141         cur[1] = low_pass_filter_param (cur[1], ctrl[1], 0.05) -- HP order x-fade
142         cur[2] = low_pass_filter_param (cur[2], ctrl[2], 1.0)  -- HP freq/Hz
143         cur[3] = low_pass_filter_param (cur[3], ctrl[3], 0.01) -- HP quality
144         cur[4] = low_pass_filter_param (cur[4], ctrl[4], 0.05) -- LP order x-fade
145         cur[5] = low_pass_filter_param (cur[5], ctrl[5], 1.0)  -- LP freq/Hz
146         cur[6] = low_pass_filter_param (cur[6], ctrl[6], 0.01) -- LP quality
147
148         for c = 1, chn do
149                 for k = 1,4 do
150                         hp[c][k]:compute (ARDOUR.DSP.BiquadType.HighPass, cur[2], cur[3], 0)
151                         lp[c][k]:compute (ARDOUR.DSP.BiquadType.LowPass,  cur[5], cur[6], 0)
152                 end
153         end
154 end
155
156
157 -- the actual DSP callback
158 function dsp_run (ins, outs, n_samples)
159         assert (n_samples < 8192)
160         assert (#ins == chn)
161
162         local changed = false
163         local siz = n_samples
164         local off = 0
165
166         -- if a parameter was changed, process at most lpf_chunk samples
167         -- at a time and interpolate parameters until the current settings
168         -- match the target values
169         if param_changed (CtrlPorts:array ()) then
170                 changed = true
171                 siz = lpf_chunk
172         end
173
174         while n_samples > 0 do
175                 if changed then apply_params (CtrlPorts:array ()) end
176                 if siz > n_samples then siz = n_samples end
177
178                 local ho = math.floor(cur[1])
179                 local lo = math.floor(cur[4])
180
181                 -- process all channels
182                 for c = 1, #ins do
183
184                         -- High Pass
185                         local xfade = cur[1] - ho
186
187                         -- prepare scratch memory
188                         ARDOUR.DSP.copy_vector (mem:to_float (off), ins[c]:offset (off), siz)
189
190                         -- run at least |ho| biquads...
191                         for k = 1,ho do
192                                 hp[c][k]:run (mem:to_float (off), siz)
193                         end
194                         ARDOUR.DSP.copy_vector (outs[c]:offset (off), mem:to_float (off), siz)
195
196                         -- mix the output of |ho| biquads (with weight |1-xfade|)
197                         -- with the output of |ho+1| biquads (with weight |xfade|)
198                         if xfade > 0 then
199                                 ARDOUR.DSP.apply_gain_to_buffer (outs[c]:offset (off), siz, 1 - xfade)
200                                 hp[c][ho+1]:run (mem:to_float (off), siz)
201                                 ARDOUR.DSP.mix_buffers_with_gain (outs[c]:offset (off), mem:to_float (off), siz, xfade)
202                                 -- also run the next biquad because it needs to have the correct state
203                                 -- in case it start affecting the next chunck of output. Higher order
204                                 -- ones are guaranteed not to be needed for the next run because the
205                                 -- interpolated order won't increase more than 0.86 in one step thanks
206                                 -- to the choice of the value of |lpf|.
207                                 if ho + 2 <= 4 then hp[c][ho+2]:run (mem:to_float (off), siz) end
208                         elseif ho + 1 <= 4 then
209                                 -- run the next biquad in case it is used next chunk
210                                 hp[c][ho+1]:run (mem:to_float (off), siz)
211                         end
212
213                         -- Low Pass
214                         xfade = cur[4] - lo
215
216                         -- prepare scratch memory (from high pass output)
217                         ARDOUR.DSP.copy_vector (mem:to_float (off), outs[c]:offset (off), siz)
218
219                         -- run at least |lo| biquads...
220                         for k = 1,lo do
221                                 lp[c][k]:run (mem:to_float (off), siz)
222                         end
223                         ARDOUR.DSP.copy_vector (outs[c]:offset (off), mem:to_float (off), siz)
224
225                         -- mix the output of |lo| biquads (with weight |1-xfade|)
226                         -- with the output of |lo+1| biquads (with weight |xfade|)
227                         if xfade > 0 then
228                                 ARDOUR.DSP.apply_gain_to_buffer (outs[c]:offset (off), siz, 1 - xfade)
229                                 lp[c][lo+1]:run (mem:to_float (off), siz)
230                                 ARDOUR.DSP.mix_buffers_with_gain (outs[c]:offset (off), mem:to_float (off), siz, xfade)
231                                 -- also run the next biquad in case it start affecting the next
232                                 -- chunck of output.
233                                 if lo + 2 <= 4 then lp[c][lo+2]:run (mem:to_float (off), siz) end
234                         elseif lo + 1 <= 4 then
235                                 -- run the next biquad in case it is used next chunk
236                                 lp[c][lo+1]:run (mem:to_float (off), siz)
237                         end
238
239                 end
240
241                 n_samples = n_samples - siz
242                 off = off + siz
243         end
244
245         if changed then
246                 -- notify display
247                 self:queue_draw ()
248         end
249 end
250
251
252 -------------------------------------------------------------------------------
253 --- inline display
254
255 function round (n)
256         return math.floor (n + .5)
257 end
258
259 function freq_at_x (x, w)
260         -- frequency in Hz at given x-axis pixel
261         return 20 * 1000 ^ (x / w)
262 end
263
264 function x_at_freq (f, w)
265         -- x-axis pixel for given frequency, power-scale
266         return w * math.log (f / 20.0) / math.log (1000.0)
267 end
268
269 function db_to_y (db, h)
270         -- y-axis gain mapping
271         if db < -60 then db = -60 end
272         if db >  12 then db =  12 end
273         return -.5 + round (0.2 * h) - h * db / 60
274 end
275
276 function grid_db (ctx, w, h, db)
277         -- draw horizontal grid line
278         -- note that a cairo pixel at Y spans [Y - 0.5 to Y + 0.5]
279         local y = -.5 + round (db_to_y (db, h))
280         ctx:move_to (0, y)
281         ctx:line_to (w, y)
282         ctx:stroke ()
283 end
284
285 function grid_freq (ctx, w, h, f)
286         -- draw vertical grid line
287         local x = -.5 + round (x_at_freq (f, w))
288         ctx:move_to (x, 0)
289         ctx:line_to (x, h)
290         ctx:stroke ()
291 end
292
293 function response (ho, lo, f)
294         -- calculate transfer function response for given
295         -- hi/po pass order at given frequency [Hz]
296         local db = ho * filt['hp']:dB_at_freq (f)
297         return db + lo * filt['lp']:dB_at_freq (f)
298 end
299
300 function render_inline (ctx, w, max_h)
301         if not filt then
302                 local tbl = self:table ():get () -- get shared memory table
303                 -- instantiate filter (to calculate the transfer function's response)
304                 filt = {}
305                 filt['hp'] = ARDOUR.DSP.Biquad (tbl['samplerate'])
306                 filt['lp'] = ARDOUR.DSP.Biquad (tbl['samplerate'])
307         end
308
309         -- set filter coefficients if they have changed
310         if param_changed (CtrlPorts:array ()) then
311                 local ctrl = CtrlPorts:array ()
312                 for k = 1,6 do cur[k] = ctrl[k] end
313                 filt['hp']:compute (ARDOUR.DSP.BiquadType.HighPass, cur[2], cur[3], 0)
314                 filt['lp']:compute (ARDOUR.DSP.BiquadType.LowPass,  cur[5], cur[6], 0)
315         end
316
317         -- calc height of inline display
318         local h = 1 | math.ceil (w * 9 / 16) -- use 16:9 aspect, odd number of y pixels
319         if (h > max_h) then h = max_h end -- but at most max-height
320
321         -- ctx is a http://cairographics.org/ context
322         -- http://manual.ardour.org/lua-scripting/class_reference/#Cairo:Context
323
324         -- clear background
325         ctx:rectangle (0, 0, w, h)
326         ctx:set_source_rgba (.2, .2, .2, 1.0)
327         ctx:fill ()
328         ctx:rectangle (0, 0, w, h)
329         ctx:clip ()
330
331         -- set line width: 1px
332         ctx:set_line_width (1.0)
333
334         -- draw grid
335         local dash3 = C.DoubleVector ()
336         local dash2 = C.DoubleVector ()
337         dash2:add ({1, 2})
338         dash3:add ({1, 3})
339         ctx:set_dash (dash2, 2) -- dotted line: 1 pixel 2 space
340         ctx:set_source_rgba (.5, .5, .5, .8)
341         grid_db (ctx, w, h, 0)
342         ctx:set_dash (dash3, 2) -- dashed line: 1 pixel 3 space
343         ctx:set_source_rgba (.5, .5, .5, .5)
344         grid_db (ctx, w, h, -12)
345         grid_db (ctx, w, h, -24)
346         grid_db (ctx, w, h, -36)
347         grid_freq (ctx, w, h, 100)
348         grid_freq (ctx, w, h, 1000)
349         grid_freq (ctx, w, h, 10000)
350         ctx:unset_dash ()
351
352         -- draw transfer function line
353         local ho = math.floor(cur[1])
354         local lo = math.floor(cur[4])
355
356         ctx:set_source_rgba (.8, .8, .8, 1.0)
357         ctx:move_to (-.5, db_to_y (response(ho, lo, freq_at_x (0, w)), h))
358         for x = 1,w do
359                 local db = response(ho, lo, freq_at_x (x, w))
360                 ctx:line_to (-.5 + x, db_to_y (db, h))
361         end
362         -- stoke a line, keep the path
363         ctx:stroke_preserve ()
364
365         -- fill area to zero under the curve
366         ctx:line_to (w, -.5 + round (db_to_y (0, h)))
367         ctx:line_to (0, -.5 + round (db_to_y (0, h)))
368         ctx:close_path ()
369         ctx:set_source_rgba (.5, .5, .5, .5)
370         ctx:fill ()
371
372         return {w, h}
373 end