prefix blessed scripted DSP plugins with a-*
[ardour.git] / scripts / biquad_filter.lua
1 ardour {
2         ["type"]    = "dsp",
3         name        = "Biquad Filter",
4         category    = "Filter",
5         license     = "MIT",
6         author      = "Ardour Lua Task Force",
7         description = [[A Versatile Filter 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 = "Enable", min = 0, max = 1, default = 1, bypass = true, toggled = true },
23                 { ["type"] = "input", name = "Type", min = 0, max = 4, default = 0, enum = true, scalepoints =
24                         {
25                                 ["Peaking"]    = 0,
26                                 ["Low Shelf"]  = 1,
27                                 ["High Shelf"] = 2,
28                                 ["Low Pass"]   = 3,
29                                 ["High Pass"]  = 4,
30                         }
31                 },
32                 { ["type"] = "input", name = "Gain", min = -20, max = 20,    default = 0,    unit="dB" },
33                 { ["type"] = "input", name = "Freq", min =  20, max = 20000, default = 1000, unit="Hz", logarithmic = true },
34                 { ["type"] = "input", name = "Q",    min = 0.1, max = 8,     default = .707, logarithmic = true },
35         }
36 end
37
38 -- translate type parameter to DSP enum
39 -- http://manual.ardour.org/lua-scripting/class_reference/#ARDOUR.DSP.Biquad.Type
40 function map_type (t)
41         if     t == 1 then
42                 return ARDOUR.DSP.BiquadType.LowShelf
43         elseif t == 2 then
44                 return ARDOUR.DSP.BiquadType.HighShelf
45         elseif t == 3 then
46                 return ARDOUR.DSP.BiquadType.LowPass
47         elseif t == 4 then
48                 return ARDOUR.DSP.BiquadType.HighPass
49         else
50                 return ARDOUR.DSP.BiquadType.Peaking
51         end
52 end
53
54 function ctrl_data ()
55         local ctrl = CtrlPorts:array ()
56         if ctrl[1] <= 0 then -- when disabled
57                 ctrl[3] = 0; -- force gain to 0dB
58         end
59         return ctrl
60 end
61
62 -- these globals are *not* shared between DSP and UI
63 local filters = {}  -- the biquad filter instances (DSP)
64 local filt -- the biquad filter instance (GUI, response)
65 local cur = {0, 0, 0, 0, 0} -- current parameters
66 local lpf = 0.03 -- parameter low-pass filter time-constant
67 local chn = 0 -- channel/filter count
68
69 function dsp_init (rate)
70         self:shmem ():allocate (1) -- shared mem to tell the GUI the samplerate
71         local cfg = self:shmem ():to_int (0):array ()
72         cfg[1] = rate
73         -- http://manual.ardour.org/lua-scripting/class_reference/#ARDOUR:DSP:Biquad
74         filt = ARDOUR.DSP.Biquad (rate) -- initialize filter
75         lpf = 13000 / rate -- interpolation time constant
76 end
77
78 function dsp_configure (ins, outs)
79         assert (ins:n_audio () == outs:n_audio ())
80         local cfg = self:shmem ():to_int (0):array ()
81         local rate = cfg[1]
82         chn = ins:n_audio ()
83         for c = 1, chn do
84                 filters[c] = ARDOUR.DSP.Biquad (rate) -- initialize filters
85         end
86         cur = {0, 0, 0, 0, 0}
87 end
88
89 -- helper functions for parameter interpolation
90 function param_changed (ctrl)
91         if ctrl[2] == cur[2] and ctrl[3] == cur[3] and ctrl[4] == cur[4] and ctrl[5] == cur[5] then
92                 return false
93         end
94         return true
95 end
96
97 function low_pass_filter_param (old, new, limit)
98         if math.abs (old - new) < limit  then
99                 return new
100         else
101                 return old + lpf * (new - old)
102         end
103 end
104
105 -- apply parameters, re-compute filter coefficients if needed
106 function apply_params (ctrl)
107         if not param_changed (ctrl) then
108                 return
109         end
110
111         if cur[2] ~= ctrl[2] then
112                 -- reset filter state when type changes
113                 filt:reset ()
114                 for k = 2,5 do cur[k] = ctrl[k] end
115         else
116                 -- low-pass filter ctrl parameter values, smooth transition
117                 cur[3] = low_pass_filter_param (cur[3], ctrl[3], 0.1) -- gain/dB
118                 cur[4] = low_pass_filter_param (cur[4], ctrl[4], 1.0) -- freq/Hz
119                 cur[5] = low_pass_filter_param (cur[5], ctrl[5], 0.01) -- quality
120         end
121
122         for c = 1, chn do
123                 filters[c]:compute (map_type (cur[2]), cur[4], cur[5], cur[3])
124         end
125 end
126
127
128 -- the actual DSP callback
129 function dsp_run (ins, outs, n_samples)
130         local changed = false
131         local siz = n_samples
132         local off = 0
133         local ctrl = ctrl_data ()
134
135         -- if a parameter was changed, process at most 64 samples at a time
136         -- and interpolate parameters until the current settings match
137         -- the target values
138         if param_changed (ctrl) then
139                 changed = true
140                 siz = 64
141         end
142
143         while n_samples > 0 do
144                 if changed then apply_params (ctrl) 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 ins[c]:sameinstance (outs[c]) then
152                                 filters[c]:run (ins[c]:offset (off), siz) -- in-place processing
153                         else
154                                 -- http://manual.ardour.org/lua-scripting/class_reference/#ARDOUR:DSP
155                                 ARDOUR.DSP.copy_vector (outs[c]:offset (off), ins[c]:offset (off), siz)
156                                 filters[c]:run (outs[c]:offset (off), siz)
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 < -20 then db = -20 end
191         if db >  20 then db =  20 end
192         return -.5 + 0.5 * h * (1 - db / 20)
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 = ctrl_data ()
224                 for k = 2,5 do cur[k] = ctrl[k] end
225                 filt:compute (map_type (cur[2]), cur[4], cur[5], cur[3])
226         end
227
228         -- calc height of inline display
229         local h = math.ceil (w * 10 / 16) -- use 16:10 aspect
230         h = 2 * round (h / 2) -- with an even number of vertical pixels
231         if (h > max_h) then h = max_h end -- but at most max-height
232
233         -- ctx is a http://cairographics.org/ context
234         -- http://manual.ardour.org/lua-scripting/class_reference/#Cairo:Context
235
236         -- clear background
237         ctx:rectangle (0, 0, w, h)
238         ctx:set_source_rgba (.2, .2, .2, 1.0)
239         ctx:fill ()
240
241         -- set line width: 1px
242         -- Note: a cairo pixel at [1,1]  spans [0.5->1.5 , 0.5->1.5]
243         -- hence the offset -0.5 in various move_to(), line_to() calls
244         ctx:set_line_width (1.0)
245
246         -- draw grid
247         local dash3 = C.DoubleVector ()
248         dash3:add ({1, 3})
249         ctx:set_dash (dash3, 2) -- dotted line
250         ctx:set_source_rgba (.5, .5, .5, .5)
251         grid_db (ctx, w, h, 0)
252         grid_db (ctx, w, h, 6)
253         grid_db (ctx, w, h, 12)
254         grid_db (ctx, w, h, 18)
255         grid_db (ctx, w, h, -6)
256         grid_db (ctx, w, h, -12)
257         grid_db (ctx, w, h, -18)
258         grid_freq (ctx, w, h, 100)
259         grid_freq (ctx, w, h, 1000)
260         grid_freq (ctx, w, h, 10000)
261         ctx:unset_dash ()
262
263         -- draw transfer function line
264         ctx:set_source_rgba (.8, .8, .8, 1.0)
265         ctx:move_to (-.5, db_to_y (filt:dB_at_freq (freq_at_x (0, w)), h))
266         for x = 1,w do
267                 local db = filt:dB_at_freq (freq_at_x (x, w))
268                 ctx:line_to (-.5 + x, db_to_y (db, h))
269         end
270         ctx:stroke_preserve ()
271
272         -- fill area to zero under the curve
273         ctx:line_to (w, -.5 + h * .5)
274         ctx:line_to (0, -.5 + h * .5)
275         ctx:close_path ()
276         ctx:set_source_rgba (.5, .5, .5, .5)
277         ctx:fill ()
278
279         return {w, h}
280 end