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