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