clean up a-HP/LP
[ardour.git] / scripts / hplp.lua
1 ardour {
2         ["type"]    = "dsp",
3         name        = "a-High/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 = "Type", min = 0, max = 1, default = 0, enum = true, scalepoints =
23                         {
24                                 ["High Pass"]  = 0,
25                                 ["Low Pass"]   = 1,
26                         }
27                 },
28                 { ["type"] = "input", name = "Steepness", min = 1, max = 4, default = 1, enum = true, scalepoints =
29                         {
30                                 ["12dB/oct"] = 1,
31                                 ["24dB/oct"] = 2,
32                                 ["36dB/oct"] = 3,
33                                 ["48dB/oct"] = 4,
34                         }
35                 },
36                 { ["type"] = "input", name = "Cut off frequency", min =   5, max = 20000, default = 1000, unit="Hz", logarithmic = true },
37                 { ["type"] = "input", name = "Resonance",         min = 0.1, max = 8,     default = .707, logarithmic = true },
38         }
39 end
40
41 -- translate type parameter to DSP enum
42 -- http://manual.ardour.org/lua-scripting/class_reference/#ARDOUR.DSP.Biquad.Type
43 function map_type (t)
44         if     t == 1 then
45                 return ARDOUR.DSP.BiquadType.LowPass
46         else
47                 return ARDOUR.DSP.BiquadType.HighPass
48         end
49 end
50
51 -- these globals are *not* shared between DSP and UI
52 local filters = {}  -- the biquad filter instances (DSP)
53 local filt -- the biquad filter instance (GUI, response)
54 local cur = {0, 0, 0, 0} -- current parameters
55 local lpf = 0.03 -- parameter low-pass filter time-constant
56 local chn = 0 -- channel/filter count
57
58 function dsp_init (rate)
59         self:shmem ():allocate (1) -- shared mem to tell the GUI the samplerate
60         local cfg = self:shmem ():to_int (0):array ()
61         cfg[1] = rate
62         lpf = 13000 / rate -- interpolation time constant
63 end
64
65 function dsp_configure (ins, outs)
66         assert (ins:n_audio () == outs:n_audio ())
67         local cfg = self:shmem ():to_int (0):array ()
68         local rate = cfg[1]
69         chn = ins:n_audio ()
70         for c = 1, chn do
71                 filters[c] = {}
72                 -- http://manual.ardour.org/lua-scripting/class_reference/#ARDOUR:DSP:Biquad
73                 for k = 1,4 do
74                         filters[c][k] = ARDOUR.DSP.Biquad (rate) -- initialize filters
75                 end
76         end
77         cur = {0, 0, 0, 0}
78 end
79
80 -- helper functions for parameter interpolation
81 function param_changed (ctrl)
82         if math.floor(ctrl[1]) == math.floor(cur[1]) and math.floor(ctrl[2]) == math.floor(cur[2]) and ctrl[3] == cur[3] and ctrl[4] == cur[4] then
83                 return false
84         end
85         return true
86 end
87
88 function low_pass_filter_param (old, new, limit)
89         if math.abs (old - new) < limit  then
90                 return new
91         else
92                 return old + lpf * (new - old)
93         end
94 end
95
96 -- apply parameters, re-compute filter coefficients if needed
97 function apply_params (ctrl)
98         if not param_changed (ctrl) then
99                 return
100         end
101
102         if cur[1] ~= ctrl[1] or cur[2] ~= ctrl[2] then
103                 -- reset filter state when type or order changes
104                 for c = 1, chn do
105                         for k = 1,4 do
106                                 filters[c][k]:reset ()
107                         end
108                 end
109                 for k = 1,4 do cur[k] = ctrl[k] end
110         else
111                 -- low-pass filter ctrl parameter values, smooth transition
112                 cur[3] = low_pass_filter_param (cur[3], ctrl[3], 1.0) -- freq/Hz
113                 cur[4] = low_pass_filter_param (cur[4], ctrl[4], 0.01) -- quality
114         end
115
116         if cur[2] < 1 then cur[2] = 1 end
117         if cur[2] > 4 then cur[2] = 4 end
118
119         for c = 1, chn do
120                 for k = 1,4 do
121                         filters[c][k]:compute (map_type (cur[1]), cur[3], cur[4], 0)
122                 end
123         end
124 end
125
126
127 -- the actual DSP callback
128 function dsp_run (ins, outs, n_samples)
129         local changed = false
130         local siz = n_samples
131         local off = 0
132
133         -- if a parameter was changed, process at most 64 samples at a time
134         -- and interpolate parameters until the current settings match
135         -- the target values
136         if param_changed (CtrlPorts:array ()) then
137                 changed = true
138                 siz = 64
139         end
140
141         local o = math.floor(cur[2])
142
143         while n_samples > 0 do
144                 if changed then apply_params (CtrlPorts:array ()) end
145                 if siz > n_samples then siz = n_samples end
146
147                 -- process all channels
148                 for c = 1,#ins do
149                         -- check if output and input buffers for this channel are identical
150                         -- http://manual.ardour.org/lua-scripting/class_reference/#C:FloatArray
151                         if not ins[c]:sameinstance (outs[c]) then
152                                 -- http://manual.ardour.org/lua-scripting/class_reference/#ARDOUR:DSP
153                                 ARDOUR.DSP.copy_vector (outs[c]:offset (off), ins[c]:offset (off), siz)
154                         end
155                         for k = 1,o do
156                                 filters[c][k]:run (outs[c]:offset (off), siz) -- in-place processing
157                         end
158                 end
159
160                 n_samples = n_samples - siz
161                 off = off + siz
162         end
163
164         if changed then
165                 -- notify display
166                 self:queue_draw ()
167         end
168 end
169
170
171 -------------------------------------------------------------------------------
172 --- inline display
173
174 function round (n)
175         return math.floor (n + .5)
176 end
177
178 function freq_at_x (x, w)
179         -- x-axis pixel for given freq, power-scale
180         return 20 * 1000 ^ (x / w)
181 end
182
183 function x_at_freq (f, w)
184         -- frequency at given x-axis pixel
185         return w * math.log (f / 20.0) / math.log (1000.0)
186 end
187
188 function db_to_y (db, h)
189         -- y-axis gain mapping
190         if db < -60 then db = -60 end
191         if db >  12 then db =  12 end
192         return -.5 + round (0.2 * h) - h * db / 60
193 end
194
195 function grid_db (ctx, w, h, db)
196         -- draw horizontal grid line
197         local y = -.5 + round (db_to_y (db, h))
198         ctx:move_to (0, y)
199         ctx:line_to (w, y)
200         ctx:stroke ()
201 end
202
203 function grid_freq (ctx, w, h, f)
204         -- draw vertical grid line
205         local x = -.5 + round (x_at_freq (f, w))
206         ctx:move_to (x, 0)
207         ctx:line_to (x, h)
208         ctx:stroke ()
209 end
210
211 function render_inline (ctx, w, max_h)
212         if not filt then
213                 -- the GUI is separate from the DSP, but the GUI needs to know
214                 -- the sample-rate that the DSP is using.
215                 local shmem = self:shmem () -- get shared memory region
216                 local cfg = shmem:to_int (0):array () -- "cast" into lua-table
217                 -- instantiate filter (to calculate the transfer function's response)
218                 filt = ARDOUR.DSP.Biquad (cfg[1])
219         end
220
221         -- set filter coefficients if they have changed
222         if param_changed (CtrlPorts:array ()) then
223                 local ctrl = CtrlPorts:array ()
224                 for k = 1,4 do cur[k] = ctrl[k] end
225                 if cur[2] < 1 then cur[2] = 1 end
226                 if cur[2] > 4 then cur[2] = 4 end
227                 filt:compute (map_type (cur[1]), cur[3], cur[4], 0)
228         end
229
230         -- calc height of inline display
231         local h = 1 | math.ceil (w * 9 / 16) -- use 16:9 aspect, odd number of y pixels
232         if (h > max_h) then h = max_h end -- but at most max-height
233
234         -- ctx is a http://cairographics.org/ context
235         -- http://manual.ardour.org/lua-scripting/class_reference/#Cairo:Context
236
237         -- clear background
238         ctx:rectangle (0, 0, w, h)
239         ctx:set_source_rgba (.2, .2, .2, 1.0)
240         ctx:fill ()
241         ctx:rectangle (0, 0, w, h)
242         ctx:clip ();
243
244         -- set line width: 1px
245         -- Note: a cairo pixel at [1,1]  spans [0.5->1.5 , 0.5->1.5]
246         -- hence the offset -0.5 in various move_to(), line_to() calls
247         ctx:set_line_width (1.0)
248
249         -- draw grid
250         local dash3 = C.DoubleVector ()
251         local dash2 = C.DoubleVector ()
252         dash2:add ({1, 2})
253         dash3:add ({1, 3})
254         ctx:set_dash (dash2, 2) -- dotted line
255         ctx:set_source_rgba (.5, .5, .5, .8)
256         grid_db (ctx, w, h, 0)
257         ctx:set_dash (dash3, 2) -- dotted line
258         ctx:set_source_rgba (.5, .5, .5, .5)
259         grid_db (ctx, w, h, -12)
260         grid_db (ctx, w, h, -24)
261         grid_db (ctx, w, h, -36)
262         grid_freq (ctx, w, h, 100)
263         grid_freq (ctx, w, h, 1000)
264         grid_freq (ctx, w, h, 10000)
265         ctx:unset_dash ()
266
267         local o = math.floor(cur[2])
268         -- draw transfer function line
269         ctx:set_source_rgba (.8, .8, .8, 1.0)
270         ctx:move_to (-.5, db_to_y (o * filt:dB_at_freq (freq_at_x (0, w)), h))
271         for x = 1,w do
272                 local db = o * filt:dB_at_freq (freq_at_x (x, w))
273                 ctx:line_to (-.5 + x, db_to_y (db, h))
274         end
275         ctx:stroke_preserve ()
276
277         -- fill area to zero under the curve
278         ctx:line_to (w, -.5 + round (db_to_y (0, h)))
279         ctx:line_to (0, -.5 + round (db_to_y (0, h)))
280         ctx:close_path ()
281         ctx:set_source_rgba (.5, .5, .5, .5)
282         ctx:fill ()
283
284         return {w, h}
285 end