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