58908edd2381767520a526cb20793c2007872ff4
[ardour.git] / scripts / HiAndLowPass.lua
1 ardour {
2         ["type"]    = "dsp",
3         name        = "a-High and Low Pass Filter",
4         category    = "Filter",
5         license     = "MIT",
6         author      = "Ardour Team",
7         description = [[Example Ardour Lua DSP Plugin]]
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, 0} -- current parameters
53 local lpf = 0.03 -- parameter low-pass filter time-constant
54 local chn = 0 -- channel/filter count
55
56 local mem = nil -- memory x-fade buffer
57
58 function dsp_init (rate)
59         -- allocate some mix-buffer
60         mem = ARDOUR.DSP.DspShm (8192)
61
62         -- create a table of objects to share with the GUI
63         local tbl = {}
64         tbl['rb'] = rb
65         tbl['samplerate'] = rate
66         self:table ():set (tbl)
67
68         -- interpolation time constant
69         lpf = 13000 / rate
70 end
71
72 function dsp_configure (ins, outs)
73         assert (ins:n_audio () == outs:n_audio ())
74         local tbl = self:table ():get () -- get shared memory table
75         local rate = tbl['samplerate']
76
77         chn = ins:n_audio ()
78
79         for c = 1, chn do
80                 hp[c] = {}
81                 lp[c] = {}
82                 -- initialize filters
83                 -- http://manual.ardour.org/lua-scripting/class_reference/#ARDOUR:DSP:Biquad
84                 for k = 1,4 do
85                         hp[c][k] = ARDOUR.DSP.Biquad (rate)
86                         lp[c][k] = ARDOUR.DSP.Biquad (rate)
87                 end
88         end
89         cur = {0, 0, 0, 0, 0, 0}
90 end
91
92 -- helper functions for parameter interpolation
93 function param_changed (ctrl)
94         for p = 1,6 do
95                 if ctrl[p] ~= cur[p] then
96                         return true
97                 end
98         end
99         return false
100 end
101
102 function low_pass_filter_param (old, new, limit)
103         if math.abs (old - new) < limit  then
104                 return new
105         else
106                 return old + lpf * (new - old)
107         end
108 end
109
110 -- apply parameters, re-compute filter coefficients if needed
111 function apply_params (ctrl)
112         if not param_changed (ctrl) then
113                 return
114         end
115
116         -- low-pass filter ctrl parameter values, smooth transition
117         cur[1] = low_pass_filter_param (cur[1], ctrl[1], 0.05) -- HP order x-fade
118         cur[2] = low_pass_filter_param (cur[2], ctrl[2], 1.0)  -- HP freq/Hz
119         cur[3] = low_pass_filter_param (cur[3], ctrl[3], 0.01) -- HP quality
120         cur[4] = low_pass_filter_param (cur[4], ctrl[4], 0.05) -- LP order x-fade
121         cur[5] = low_pass_filter_param (cur[5], ctrl[5], 1.0)  -- LP freq/Hz
122         cur[6] = low_pass_filter_param (cur[6], ctrl[6], 0.01) -- LP quality
123
124         for c = 1, chn do
125                 for k = 1,4 do
126                         hp[c][k]:compute (ARDOUR.DSP.BiquadType.HighPass, cur[2], cur[3], 0)
127                         lp[c][k]:compute (ARDOUR.DSP.BiquadType.LowPass,  cur[5], cur[6], 0)
128                 end
129         end
130 end
131
132
133 -- the actual DSP callback
134 function dsp_run (ins, outs, n_samples)
135         assert (n_samples < 8192)
136         local changed = false
137         local siz = n_samples
138         local off = 0
139
140         -- if a parameter was changed, process at most 64 samples at a time
141         -- and interpolate parameters until the current settings match
142         -- the target values
143         if param_changed (CtrlPorts:array ()) then
144                 changed = true
145                 siz = 64
146         end
147
148         while n_samples > 0 do
149                 if changed then apply_params (CtrlPorts:array ()) end
150                 if siz > n_samples then siz = n_samples end
151
152                 local ho = math.floor(cur[1])
153                 local lo = math.floor(cur[4])
154                 local hox = cur[1]
155                 local lox = cur[4]
156
157                 -- process all channels
158                 for c = 1, #ins do
159
160                         local xfade = hox - ho
161                         assert (xfade >= 0 and xfade < 1)
162
163                         ARDOUR.DSP.copy_vector (mem:to_float (off), ins[c]:offset (off), siz)
164
165                         -- initialize output
166                         if hox == 0 then
167                                 ARDOUR.DSP.copy_vector (outs[c]:offset (off), mem:to_float (off), siz)
168                         else
169                                 ARDOUR.DSP.memset (outs[c]:offset (off), 0, siz)
170                         end
171
172                         for k = 1,4 do
173                                 if xfade > 0 and k > ho and k <= ho + 1 then
174                                         ARDOUR.DSP.mix_buffers_with_gain (outs[c]:offset (off), mem:to_float (off), siz, 1 - xfade)
175                                 end
176
177                                 hp[c][k]:run (mem:to_float (off), siz)
178
179                                 if k == ho and xfade == 0 then
180                                         ARDOUR.DSP.copy_vector (outs[c]:offset (off), mem:to_float (off), siz)
181                                 elseif k > ho and k <= ho + 1 then
182                                         ARDOUR.DSP.mix_buffers_with_gain (outs[c]:offset (off), mem:to_float (off), siz, xfade)
183                                 end
184                         end
185
186                         -- low pass
187                         xfade = lox - lo
188                         assert (xfade >= 0 and xfade < 1)
189
190                         ARDOUR.DSP.copy_vector (mem:to_float (off), outs[c]:offset (off), siz)
191
192                         if lox > 0 then
193                                 ARDOUR.DSP.memset (outs[c]:offset (off), 0, siz)
194                         end
195
196                         for k = 1,4 do
197                                 if xfade > 0 and k > lo and k <= lo + 1 then
198                                         ARDOUR.DSP.mix_buffers_with_gain (outs[c]:offset (off), mem:to_float (off), siz, 1 - xfade)
199                                 end
200
201                                 lp[c][k]:run (mem:to_float (off), siz)
202
203                                 if k == lo and xfade == 0 then
204                                         ARDOUR.DSP.copy_vector (outs[c]:offset (off), mem:to_float (off), siz)
205                                 elseif k > lo and k <= lo + 1 then
206                                         ARDOUR.DSP.mix_buffers_with_gain (outs[c]:offset (off), mem:to_float (off), siz, xfade)
207                                 end
208                         end
209
210                 end
211
212                 n_samples = n_samples - siz
213                 off = off + siz
214         end
215
216         if changed then
217                 -- notify display
218                 self:queue_draw ()
219         end
220 end
221
222
223 -------------------------------------------------------------------------------
224 --- inline display
225
226 function round (n)
227         return math.floor (n + .5)
228 end
229
230 function freq_at_x (x, w)
231         -- x-axis pixel for given freq, power-scale
232         return 20 * 1000 ^ (x / w)
233 end
234
235 function x_at_freq (f, w)
236         -- frequency at given x-axis pixel
237         return w * math.log (f / 20.0) / math.log (1000.0)
238 end
239
240 function db_to_y (db, h)
241         -- y-axis gain mapping
242         if db < -60 then db = -60 end
243         if db >  12 then db =  12 end
244         return -.5 + round (0.2 * h) - h * db / 60
245 end
246
247 function grid_db (ctx, w, h, db)
248         -- draw horizontal grid line
249         local y = -.5 + round (db_to_y (db, h))
250         ctx:move_to (0, y)
251         ctx:line_to (w, y)
252         ctx:stroke ()
253 end
254
255 function grid_freq (ctx, w, h, f)
256         -- draw vertical grid line
257         local x = -.5 + round (x_at_freq (f, w))
258         ctx:move_to (x, 0)
259         ctx:line_to (x, h)
260         ctx:stroke ()
261 end
262
263 function response (ho, lo, f)
264                 local db = ho * filt['hp']:dB_at_freq (f)
265                 return db + lo * filt['lp']:dB_at_freq (f)
266 end
267
268 function render_inline (ctx, w, max_h)
269         if not filt then
270                 local tbl = self:table ():get () -- get shared memory table
271                 -- instantiate filter (to calculate the transfer function's response)
272                 filt = {}
273                 filt['hp'] = ARDOUR.DSP.Biquad (tbl['samplerate'])
274                 filt['lp'] = ARDOUR.DSP.Biquad (tbl['samplerate'])
275         end
276
277         -- set filter coefficients if they have changed
278         if param_changed (CtrlPorts:array ()) then
279                 local ctrl = CtrlPorts:array ()
280                 for k = 1,6 do cur[k] = ctrl[k] end
281                 filt['hp']:compute (ARDOUR.DSP.BiquadType.HighPass, cur[2], cur[3], 0)
282                 filt['lp']:compute (ARDOUR.DSP.BiquadType.LowPass,  cur[5], cur[6], 0)
283         end
284
285         -- calc height of inline display
286         local h = 1 | math.ceil (w * 9 / 16) -- use 16:9 aspect, odd number of y pixels
287         if (h > max_h) then h = max_h end -- but at most max-height
288
289         -- ctx is a http://cairographics.org/ context
290         -- http://manual.ardour.org/lua-scripting/class_reference/#Cairo:Context
291
292         -- clear background
293         ctx:rectangle (0, 0, w, h)
294         ctx:set_source_rgba (.2, .2, .2, 1.0)
295         ctx:fill ()
296         ctx:rectangle (0, 0, w, h)
297         ctx:clip ()
298
299         -- set line width: 1px
300         -- Note: a cairo pixel at [1,1]  spans [0.5->1.5 , 0.5->1.5]
301         -- hence the offset -0.5 in various move_to(), line_to() calls
302         ctx:set_line_width (1.0)
303
304         -- draw grid
305         local dash3 = C.DoubleVector ()
306         local dash2 = C.DoubleVector ()
307         dash2:add ({1, 2})
308         dash3:add ({1, 3})
309         ctx:set_dash (dash2, 2) -- dotted line
310         ctx:set_source_rgba (.5, .5, .5, .8)
311         grid_db (ctx, w, h, 0)
312         ctx:set_dash (dash3, 2) -- dotted line
313         ctx:set_source_rgba (.5, .5, .5, .5)
314         grid_db (ctx, w, h, -12)
315         grid_db (ctx, w, h, -24)
316         grid_db (ctx, w, h, -36)
317         grid_freq (ctx, w, h, 100)
318         grid_freq (ctx, w, h, 1000)
319         grid_freq (ctx, w, h, 10000)
320         ctx:unset_dash ()
321
322         local ho = math.floor(cur[1])
323         local lo = math.floor(cur[4])
324
325         -- draw transfer function line
326         ctx:set_source_rgba (.8, .8, .8, 1.0)
327         ctx:move_to (-.5, db_to_y (response(ho, lo, freq_at_x (0, w)), h))
328         for x = 1,w do
329                 local db = response(ho, lo, freq_at_x (x, w))
330                 ctx:line_to (-.5 + x, db_to_y (db, h))
331         end
332         ctx:stroke_preserve ()
333
334         -- fill area to zero under the curve
335         ctx:line_to (w, -.5 + round (db_to_y (0, h)))
336         ctx:line_to (0, -.5 + round (db_to_y (0, h)))
337         ctx:close_path ()
338         ctx:set_source_rgba (.5, .5, .5, .5)
339         ctx:fill ()
340
341         return {w, h}
342 end