prefix blessed scripted DSP plugins with a-*
[ardour.git] / scripts / spectrogram.lua
1 ardour {
2         ["type"]    = "dsp",
3         name        = "a-Inline Spectrogram",
4         category    = "Visualization",
5         license     = "MIT",
6         author      = "Ardour Team",
7         description = [[Mixer strip inline spectrum display]]
8 }
9
10 -- return possible i/o configurations
11 function dsp_ioconfig ()
12         -- -1, -1 = any number of channels as long as input and output count matches
13         return { [1] = { audio_in = -1, audio_out = -1}, }
14 end
15
16 function dsp_params ()
17         return
18         {
19                 { ["type"] = "input", name = "Logscale", min = 0, max = 1, default = 0, toggled = true },
20                 { ["type"] = "input", name = "1/f scale", min = 0, max = 1, default = 1, toggled = true },
21                 { ["type"] = "input", name = "FFT Size", min = 0, max = 4, default = 3, enum = true, scalepoints =
22                         {
23                                 ["512"]  = 0,
24                                 ["1024"] = 1,
25                                 ["2048"] = 2,
26                                 ["4096"] = 3,
27                                 ["8192"] = 4,
28                         }
29                 },
30                 { ["type"] = "input", name = "Height (Aspect)", min = 0, max = 3, default = 1, enum = true, scalepoints =
31                         {
32                                 ["Min"] = 0,
33                                 ["16:10"] = 1,
34                                 ["1:1"] = 2,
35                                 ["Max"] = 3
36                         }
37                 },
38                 { ["type"] = "input", name = "Range", min = 20, max = 160, default = 60, unit="dB"},
39                 { ["type"] = "input", name = "Offset", min = -40, max = 40, default = 0, unit="dB"},
40         }
41 end
42
43 -- a C memory area.
44 -- It needs to be in global scope.
45 -- When the variable is set to nil, the allocated memory is free()ed.
46 -- the memory can be interpeted as float* for use in DSP, or read/write
47 -- to a C++ Ringbuffer instance.
48 -- http://manual.ardour.org/lua-scripting/class_reference/#ARDOUR:DSP:DspShm
49 local cmem = nil
50
51 function dsp_init (rate)
52         -- global variables (DSP part only)
53         dpy_hz = rate / 25
54         dpy_wr = 0
55
56         -- create a ringbuffer to hold (float) audio-data
57         -- http://manual.ardour.org/lua-scripting/class_reference/#PBD:RingBufferF
58         rb = PBD.RingBufferF (2 * rate)
59
60         -- allocate memory, local mix buffer
61         cmem = ARDOUR.DSP.DspShm (8192)
62
63         -- create a table of objects to share with the GUI
64         local tbl = {}
65         tbl['rb'] = rb;
66         tbl['samplerate'] = rate
67
68         -- "self" is a special DSP variable referring
69         -- to the plugin instance itself.
70         --
71         -- "table()" is-a http://manual.ardour.org/lua-scripting/class_reference/#ARDOUR.LuaTableRef
72         -- which allows to store/retrieve lua-tables to share them other interpreters
73         self:table ():set (tbl);
74 end
75
76 -- "dsp_runmap" uses Ardour's internal processor API, eqivalent to
77 -- 'connect_and_run()". There is no overhead (mapping, translating buffers).
78 -- The lua implementation is responsible to map all the buffers directly.
79 function dsp_runmap (bufs, in_map, out_map, n_samples, offset)
80         -- here we sum all audio input channels channels and then copy the data to a ringbuffer
81         -- for the GUI to process later
82
83         local audio_ins = in_map:count (): n_audio () -- number of audio input buffers
84         local ccnt = 0 -- processed channel count
85         local mem = cmem:to_float(0) -- a "FloatArray", float* for direct C API usage from the previously allocated buffer
86         for c = 1,audio_ins do
87                 -- see http://manual.ardour.org/lua-scripting/class_reference/#ARDOUR:ChanMapping
88                 -- Note: lua starts counting at 1, ardour's ChanMapping::get() at 0
89                 local ib = in_map:get (ARDOUR.DataType ("audio"), c - 1) -- get index of mapped input buffer
90                 local ob = out_map:get (ARDOUR.DataType ("audio"), c - 1) -- get index of mapped output buffer
91
92                 -- check if the input is connected to a buffer
93                 if (ib ~= ARDOUR.ChanMapping.Invalid) then
94
95                         -- http://manual.ardour.org/lua-scripting/class_reference/#ARDOUR:AudioBuffer
96                         -- http://manual.ardour.org/lua-scripting/class_reference/#ARDOUR:DSP
97                         if c == 1 then
98                                 -- first channel, copy as-is
99                                 ARDOUR.DSP.copy_vector (mem, bufs:get_audio (ib):data (offset), n_samples)
100                         else
101                                 -- all other channels, add to existing data.
102                                 ARDOUR.DSP.mix_buffers_no_gain (mem, bufs:get_audio (ib):data (offset), n_samples)
103                         end
104                         ccnt = ccnt + 1;
105
106                         -- copy data to output (if not processing in-place)
107                         if (ob ~= ARDOUR.ChanMapping.Invalid and ib ~= ob) then
108                                 ARDOUR.DSP.copy_vector (bufs:get_audio (ob):data (offset), bufs:get_audio (ib):data (offset), n_samples)
109                         end
110                 end
111         end
112
113         -- Clear unconnected output buffers.
114         -- In case we're processing in-place some buffers may be identical,
115         -- so this must be done  *after processing*.
116         for c = 1,audio_ins do
117                 local ib = in_map:get (ARDOUR.DataType ("audio"), c - 1)
118                 local ob = out_map:get (ARDOUR.DataType ("audio"), c - 1)
119                 if (ib == ARDOUR.ChanMapping.Invalid and ob ~= ARDOUR.ChanMapping.Invalid) then
120                         bufs:get_audio (ob):silence (n_samples, offset)
121                 end
122         end
123
124         -- Normalize gain (1 / channel-count)
125         if ccnt > 1 then
126                 ARDOUR.DSP.apply_gain_to_buffer (mem, n_samples, 1 / ccnt)
127         end
128
129         -- if no channels were processed, feed silence.
130         if ccnt == 0 then
131                 ARDOUR.DSP.memset (mem, 0, n_samples)
132         end
133
134         -- write data to the ringbuffer
135         -- http://manual.ardour.org/lua-scripting/class_reference/#PBD:RingBufferF
136         rb:write (mem, n_samples)
137
138         -- emit QueueDraw every FPS
139         -- TODO: call every FFT window-size worth of samples, at most every FPS
140         dpy_wr = dpy_wr + n_samples
141         if (dpy_wr > dpy_hz) then
142                 dpy_wr = dpy_wr % dpy_hz
143                 self:queue_draw ()
144         end
145 end
146
147 ----------------------------------------------------------------
148 -- GUI
149
150 local fft = nil
151 local read_ptr = 0
152 local line = 0
153 local img = nil
154 local fft_size = 0
155 local last_log = false
156
157 function render_inline (ctx, w, max_h)
158         local ctrl = CtrlPorts:array () -- get control port array (read/write)
159         local tbl = self:table ():get () -- get shared memory table
160         local rate = tbl['samplerate']
161         if not cmem then
162                 cmem = ARDOUR.DSP.DspShm (0)
163         end
164
165         -- get settings
166         local logscale = ctrl[1] or 0; logscale = logscale > 0 -- x-axis logscale
167         local pink = ctrl[2] or 0; pink = pink > 0 -- 1/f scale
168         local fftsizeenum = ctrl[3] or 3 -- fft-size enum
169         local hmode = ctrl[4] or 1 -- height mode enum
170         local dbrange = ctrl[5] or 60
171         local gaindb = ctrl[6] or 0
172
173         local fftsize
174         if fftsizeenum == 0 then fftsize = 512
175         elseif fftsizeenum == 1 then fftsize = 1024
176         elseif fftsizeenum == 2 then fftsize = 2048
177         elseif fftsizeenum == 4 then fftsize = 8192
178         else fftsize = 4096
179         end
180
181         if fftsize ~= fft_size then
182                 fft_size = fftsize
183                 fft = nil
184         end
185
186         if dbrange < 20 then dbrange = 20; end
187         if dbrange > 160 then dbrange = 160; end
188         if gaindb < -40 then dbrange = -40; end
189         if gaindb >  40 then dbrange =  40; end
190
191
192         if not fft then
193                 fft = ARDOUR.DSP.FFTSpectrum (fft_size, rate)
194                 cmem:allocate (fft_size)
195         end
196
197         if last_log ~= logscale then
198                 last_log = logscale
199                 img = nil
200                 line = 0
201         end
202
203         -- calc height
204         if hmode == 0 then
205                 h = math.ceil (w * 10 / 16)
206                 if (h > 44) then
207                         h = 44
208                 end
209         elseif (hmode == 2) then
210                 h = w
211         elseif (hmode == 3) then
212                 h = max_h
213         else
214                 h = math.ceil (w * 10 / 16)
215         end
216         if (h > max_h) then
217                 h = max_h
218         end
219
220         -- re-create image surface
221         if not img or img:get_width() ~= w or img:get_height () ~= h then
222                 img = Cairo.ImageSurface (Cairo.Format.ARGB32, w, h)
223                 line = 0
224         end
225         local ictx = img:context ()
226
227         local bins = fft_size / 2 - 1 -- fft bin count
228         local bpx = bins / w  -- bins per x-pixel (linear)
229         local fpb = rate / fft_size -- freq-step per bin
230         local f_e = rate / 2 / fpb -- log-scale exponent
231         local f_b = w / math.log (fft_size / 2) -- inverse log-scale base
232         local f_l = math.log (fft_size / rate) * f_b -- inverse logscale lower-bound
233
234         local rb = tbl['rb'];
235         local mem = cmem:to_float (0)
236
237         while (rb:read_space() >= fft_size) do
238                 -- process one line / buffer
239                 rb:read (mem, fft_size)
240                 fft:set_data_hann (mem, fft_size, 0)
241                 fft:execute ()
242
243                 -- draw spectrum
244                 assert (bpx >= 1)
245
246                 -- scroll
247                 if line == 0 then line = h - 1; else line = line - 1; end
248
249                 -- clear this line
250                 ictx:set_source_rgba (0, 0, 0, 1)
251                 ictx:rectangle (0, line, w, 1)
252                 ictx:fill ()
253
254                 for x = 0, w - 1 do
255                         local pk = 0
256                         local b0, b1
257                         if logscale then
258                                 -- 20 .. 20k
259                                 b0 = math.floor (f_e ^ (x / w))
260                                 b1 = math.floor (f_e ^ ((x + 1) / w))
261                         else
262                                 b0 = math.floor (x * bpx)
263                                 b1 = math.floor ((x + 1) * bpx)
264                         end
265
266                         if b1 >= b0 and b1 <= bins and b0 >= 0 then
267                                 for i = b0, b1 do
268                                         local level = gaindb + fft:power_at_bin (i, pink and i or 1) -- pink ? i : 1
269                                         if level > -dbrange then
270                                                 local p = (dbrange + level) / dbrange
271                                                 if p > pk then pk = p; end
272                                         end
273                                 end
274                         end
275                         if pk > 0.0 then
276                                 if pk > 1.0 then pk = 1.0; end
277                                 ictx:set_source_rgba (ARDOUR.LuaAPI.hsla_to_rgba (.70 - .72 * pk, .9, .3 + pk * .4));
278                                 ictx:rectangle (x, line, 1, 1)
279                                 ictx:fill ()
280                         end
281                 end
282         end
283
284         -- copy image surface
285         if line == 0 then
286                 img:set_as_source (ctx, 0, 0)
287                 ctx:rectangle (0, 0, w, h)
288                 ctx:fill ()
289         else
290                 local yp = h - line - 1;
291                 img:set_as_source (ctx, 0, yp)
292                 ctx:rectangle (0, yp, w, line)
293                 ctx:fill ()
294
295                 img:set_as_source (ctx, 0, -line)
296                 ctx:rectangle (0, 0, w, yp)
297                 ctx:fill ()
298         end
299
300
301         -- draw grid on top
302         function x_at_freq (f)
303                 if logscale then
304                         return f_l + f_b * math.log (f)
305                 else
306                         return 2 * w * f / rate;
307                 end
308         end
309
310         function grid_freq (f)
311                 -- draw vertical grid line
312                 local x = .5 + math.floor (x_at_freq (f))
313                 ctx:move_to (x, 0)
314                 ctx:line_to (x, h)
315                 ctx:stroke ()
316         end
317
318         -- draw grid on top
319         local dash3 = C.DoubleVector ()
320         dash3:add ({1, 3})
321         ctx:set_line_width (1.0)
322         ctx:set_dash (dash3, 2) -- dotted line
323         ctx:set_source_rgba (.5, .5, .5, .8)
324         grid_freq (100)
325         grid_freq (1000)
326         grid_freq (10000)
327         ctx:unset_dash ()
328
329         return {w, h}
330 end