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