lib/Peta/Synth/Engine/GPU.pm

filter: Statementstmt 60.0% 3 / 5 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 2 / 2 Podpod n/a totaltotal 71.4% 5 / 7 CC 1 SCAR 1.4
CC
1
Cov
60%
BEGIN
1.3
BEGIN
1.0
CRAP 1.1
« lib/Peta/Vorbis/Encode/MDCT/PDL.pm ↑ Summary lib/Peta/MP3/Encode/Tables.pm »
1 package Peta::Synth::Engine::GPU;
2 # ABSTRACT: the voices rendered on the graphics card
3  
4 # The engine on the graphics card (pperl's Peta::WebGPU): every partial of
5 # every voice of a quantum at once, in 32-bit floats.
6 #
7 # A quantum is four compute passes, sent to the card as one batch:
8 #
9 # edges one invocation per partial: its amplitude at every block's edge
10 # and its phase where every block begins. The phase goes on block
11 # by block, wrapped, so that it never grows past what a 32-bit
12 # float holds to a hundred-thousandth of a radian.
13 # noise one invocation per voice with noise: its bands' filters, and
14 # the low-pass of its noise on the partials, are recursions,
15 # sample after sample, and stay so.
16 # voices one invocation per sample of every voice: the sum of its
17 # partials (sin of the phase brought back to [-pi, pi], where the
18 # card computes it accurately), its noise, under its envelope.
19 # A workgroup of 64 is a control block.
20 # mix one invocation per sample: the voices under their channels'
21 # gains, into left, right and the reverb send.
22 #
23 # The phases are carried from quantum to quantum on the CPU, in double
24 # precision: where a quantum ends is where it began plus the partial's
25 # angle through it, one multiplication per partial. So is the band-pass's
26 # state, which the card returns with the samples.
27 #
28 # render_reverb runs Peta::Synth::Reverb on the card too, in the same
29 # batch: its lines are longer than a chunk of the quantum (a chunk is no
30 # longer than the shortest), so within a chunk every line reads what was
31 # written before it. Per chunk three passes: the lines read, one per
32 # sample and line; the damping, a recursion, one invocation per line; the
33 # lines mixed (Hadamard), the wet sound and the lines written, one per
34 # sample. The predelay before them, read and then written. The lines stay
35 # on the card, one reverb's at a time; the reverb can fetch them back
36 # (its elsewhere), which it does before it goes on in Perl, and which
37 # another reverb taking the card does for it.
38  
39 2 ▶use v5.36;
Subroutine BEGIN: called CC=1 SCAR=0.0
40  
41 0 ▶use Peta::WebGPU;
Subroutine BEGIN: called CC=1 SCAR=2.6
42 use Peta::Synth::Voice;
43 use Scalar::Util qw(weaken);
44  
45 our $VERSION = '0.2610180';
46  
47 use constant BLOCK => 64;
48 use constant TWO_PI => 6.283185307179586;
49 use constant STATE => 34; # floats of a voice's state in `out`, after the samples
50  
51 # Every pass sees the same parameters. A voice's controls are a row of
52 # `stride` floats in `ctl`:
53 #
54 # 0 first block 1 partials 2 its first partial in `parts` 3 bands of noise (0 .. 3)
55 # 4 t0 5 the filter's mode (0 none) 6, 7 the noise on the partials: depth, a
56 # 8 + 3 b: band b's g, k, mode (0 band-, 1 high-, 2 low-pass; 4 more: four poles)
57 # 17 a string (0, 1) 18 its level 19 g 20 s1
58 # 21 FM (0, 1) 22 its level 23 feedback 24 + o: operator o's ratio
59 # 28 .. 33 a34 a24 a23 a14 a13 a12 34 + o: operator o a carrier (0, 1)
60 # 38 the string's delay besides the line 39 its stiffness's allpasses (0, 4) 40 their a
61 # 41 copies read from wave sequences (0: none; its partials then are none)
62 # 42 where their controls begin in `ctl`, after every voice's row: for
63 # each copy, for each block, 7 floats: the two tables' first samples in
64 # `wav` (u32, bitcast), the crossfade where the block begins and its
65 # step, where in the period it begins and the read step (table
66 # samples), the period (Peta::Synth::Engine::Perl::wave_blocks)
67 # 43 (HEAD) w[nb]; then, nb + 1 each (E): env gl gr gs fx fq, the bands'
68 # levels (3), the operators' levels (4)
69 #
70 # `wav` holds every wave sequence's tables, each uploaded once and kept.
71 use constant HEAD => 43;
72 my $COMMON = <<'WGSL';
73 struct Params { n: u32, nb: u32, voices: u32, stride: u32, dt: f32, b: f32, pad0: f32, pad1: f32 }
74 const TWO_PI: f32 = 6.283185307179586;
75 const HEAD: u32 = 43u;
76 const STATE: u32 = 34u;
77 WGSL
78  
79 # name => [ bindings ("r" read-only, "w" read-write; "4" an array of vec4,
80 # "2" of vec2, else of f32), body ]. The parameters are the last binding, `u`.
81 my %SHADER = (
82  
83 # (ratio, amp, decay, attack) of partial `at`; tab[at][j] = (phase where
84 # block j begins, amplitude at edge j). Before a voice's first block its
85 # envelope is zero; the amplitude is taken at time 0 there, which is finite.
86 edges => [ [qw(r4:parts r:phase r:ctl w2:tab)], <<'WGSL' ],
87 let k = id.x; let v = id.y;
88 if (v >= u.voices) { return; }
89 let c = v * u.stride;
90 if (k >= u32(ctl[c + 1u])) { return; }
91 let first = u32(ctl[c]);
92 let at = u32(ctl[c + 2u]) + k;
93 let q = parts[at];
94 let t0 = ctl[c + 4u];
95 var ph = phase[at];
96 let row = at * (u.nb + 1u);
97 let mode = u32(ctl[c + 5u]);
98 let fx = c + HEAD + u.nb + 4u * (u.nb + 1u);
99 let fq = fx + u.nb + 1u;
100 for (var j = 0u; j <= u.nb; j++) {
101 let t = max(t0 + f32(j) * u.dt, 0.0);
102 var a = q.y * exp(-q.z * t);
103 if (q.w > 0.0) { a *= 1.0 - exp(-t / q.w); }
104 if (mode != 0u) {
105 // The filter's gain (Peta::Synth::Voice::filter_gain).
106 let x = q.x * ctl[fx + j]; let x2 = x * x; let r = ctl[fq + j];
107 let d = sqrt((1.0 - x2) * (1.0 - x2) + x2 / (r * r));
108 let steep = sqrt(1.0 + x2 * x2);
109 if (mode == 1u) { a /= d; }
110 else if (mode == 2u) { a /= d * steep; }
111 else if (mode == 3u) { a *= x2 / d; }
112 else if (mode == 4u) { a *= x2 * x2 / (d * steep); }
113 else { a *= x / r / d; }
114 }
115 tab[row + j] = vec2<f32>(ph, a);
116 if (j < u.nb && j >= first) {
117 ph += q.x * ctl[c + HEAD + j] * u.b;
118 ph -= TWO_PI * floor(ph / TWO_PI);
119 }
120 }
121 WGSL
122  
123 # The bands of noise: white noise from the table through each band's
124 # filter (state-variable: band-, high- or low-pass; with four poles, a
125 # second the same after it), under its level, summed into nz; the noise
126 # on the partials, white noise through a one-pole low-pass, as the
127 # factor am. Their states come in nstate, eight vec4 a voice (band b's
128 # ic1, ic2, table position at b, its second stage's at 4 + b; the
129 # low-pass's and its position at 3), and are returned after the samples
130 # (band b's at 4 b and 28 + 2 b; the low-pass's at 12).
131 noise => [ [qw(r:ctl r4:nstate r:table w:nz w:am w:out)], <<'WGSL' ],
132 let v = id.x;
133 if (v >= u.voices) { return; }
134 let c = v * u.stride;
135 let first = u32(ctl[c]);
136 let bands = u32(ctl[c + 3u]);
137 let size = arrayLength(&table);
138 let o = 3u * u.n + STATE * v;
139 for (var b = 0u; b < bands; b++) {
140 let g = ctl[c + 8u + 3u * b]; let kq = ctl[c + 9u + 3u * b]; let kind = u32(ctl[c + 10u + 3u * b]);
141 let mode = kind & 3u; let four = kind >= 4u;
142 let a1 = 1.0 / (1.0 + g * (g + kq)); let a2 = g * a1; let a3 = g * a2;
143 let s = nstate[8u * v + b];
144 var ic1 = s.x; var ic2 = s.y; var index = u32(s.z);
145 let s2 = nstate[8u * v + 4u + b];
146 var jc1 = s2.x; var jc2 = s2.y;
147 let ne = c + HEAD + u.nb + (6u + b) * (u.nb + 1u);
148 for (var j = first; j < u.nb; j++) {
149 var level = ctl[ne + j];
150 let step = (ctl[ne + j + 1u] - level) / u.b;
151 let base = v * u.n + j * 64u;
152 for (var m = 0u; m < 64u; m++) {
153 let v0 = table[index];
154 index += 1u;
155 if (index >= size) { index = 0u; }
156 let v3 = v0 - ic2;
157 let v1 = a1 * ic1 + a2 * v3;
158 let v2 = ic2 + a2 * ic1 + a3 * v3;
159 ic1 = 2.0 * v1 - ic1;
160 ic2 = 2.0 * v2 - ic2;
161 var y = kq * v1;
162 if (mode == 1u) { y = v0 - kq * v1 - v2; } else if (mode == 2u) { y = v2; }
163 if (four) {
164 let u0 = y;
165 let u3 = u0 - jc2;
166 let u1 = a1 * jc1 + a2 * u3;
167 let u2 = jc2 + a2 * jc1 + a3 * u3;
168 jc1 = 2.0 * u1 - jc1;
169 jc2 = 2.0 * u2 - jc2;
170 y = kq * u1;
171 if (mode == 1u) { y = u0 - kq * u1 - u2; } else if (mode == 2u) { y = u2; }
172 }
173 if (b == 0u) { nz[base + m] = level * y; } else { nz[base + m] += level * y; }
174 level += step;
175 }
176 }
177 out[o + 4u * b] = ic1; out[o + 4u * b + 1u] = ic2; out[o + 4u * b + 2u] = f32(index);
178 out[o + 28u + 2u * b] = jc1; out[o + 29u + 2u * b] = jc2;
179 }
180 let depth = ctl[c + 6u];
181 if (depth != 0.0) {
182 let a = ctl[c + 7u];
183 var y = nstate[8u * v + 3u].x; var index = u32(nstate[8u * v + 3u].y);
184 for (var i = first * 64u; i < u.n; i++) {
185 y += a * (table[index] - y);
186 index += 1u;
187 if (index >= size) { index = 0u; }
188 am[v * u.n + i] = 1.0 + depth * y;
189 }
190 out[o + 12u] = y; out[o + 13u] = f32(index);
191 }
192 WGSL
193  
194 # The strings (Peta::Synth::Engine::Perl::string): one invocation per
195 # voice, a recursion through its delay line in sbuf (sst[2 v]: where it
196 # begins, its size, where it writes, the low-pass's last input; sst[2 v
197 # + 1]: the fractional allpass's last input and output, how much of the
198 # pluck is fed, how much there is), after the line in sbuf the
199 # stiffness's allpasses' last inputs and outputs (8), then the pluck
200 # while it is fed; sample after sample into st; the state after the
201 # samples, at 16 and 26 of the voice's STATE floats (the stiffness's in
202 # sbuf).
203 strings => [ [qw(r:ctl r4:sst w:sbuf w:st w:out)], <<'WGSL' ],
204 let v = id.x;
205 if (v >= u.voices) { return; }
206 let c = v * u.stride;
207 if (ctl[c + 17u] == 0.0) { return; }
208 let first = u32(ctl[c]);
209 let level = ctl[c + 18u]; let g = ctl[c + 19u]; let s1 = ctl[c + 20u]; let s0 = 1.0 - s1;
210 let off = ctl[c + 38u]; let stiff = ctl[c + 39u] != 0.0; let a = ctl[c + 40u];
211 let base = u32(sst[2u * v].x); let size = i32(sst[2u * v].y);
212 var pos = i32(sst[2u * v].z); var prev = sst[2u * v].w;
213 var ax = sst[2u * v + 1u].x; var ay = sst[2u * v + 1u].y;
214 let ds = base + u32(size);
215 var dx = vec4<f32>(sbuf[ds], sbuf[ds + 1u], sbuf[ds + 2u], sbuf[ds + 3u]);
216 var dy = vec4<f32>(sbuf[ds + 4u], sbuf[ds + 5u], sbuf[ds + 6u], sbuf[ds + 7u]);
217 var fed = u32(sst[2u * v + 1u].z); let todo = u32(sst[2u * v + 1u].w);
218 for (var j = first; j < u.nb; j++) {
219 let d = clamp(TWO_PI / ctl[c + HEAD + j] - off, 1.1, f32(size) - 2.0);
220 let whole = i32(floor(d - 0.1));
221 let frac = d - f32(whole);
222 let eta = (1.0 - frac) / (1.0 + frac);
223 for (var m = 0u; m < 64u; m++) {
224 var r = pos - whole;
225 if (r < 0) { r += size; }
226 let x = sbuf[base + u32(r)];
227 var y = eta * x + ax - eta * ay;
228 ax = x; ay = y;
229 if (stiff) {
230 var t = a * (y - dy.x) + dx.x; dx.x = y; dy.x = t;
231 y = a * (t - dy.y) + dx.y; dx.y = t; dy.y = y;
232 t = a * (y - dy.z) + dx.z; dx.z = y; dy.z = t;
233 y = a * (t - dy.w) + dx.w; dx.w = t; dy.w = y;
234 }
235 var o = g * (s0 * y + s1 * prev);
236 if (fed < todo) { o += sbuf[ds + 8u + fed]; fed += 1u; }
237 prev = y;
238 sbuf[base + u32(pos)] = o;
239 pos += 1;
240 if (pos >= size) { pos = 0; }
241 st[v * u.n + j * 64u + m] = level * o;
242 }
243 }
244 let o = 3u * u.n + STATE * v + 16u;
245 out[o] = f32(pos); out[o + 1u] = prev; out[o + 2u] = ax; out[o + 3u] = ay; out[o + 10u] = f32(fed);
246 sbuf[ds] = dx.x; sbuf[ds + 1u] = dx.y; sbuf[ds + 2u] = dx.z; sbuf[ds + 3u] = dx.w;
247 sbuf[ds + 4u] = dy.x; sbuf[ds + 5u] = dy.y; sbuf[ds + 6u] = dy.z; sbuf[ds + 7u] = dy.w;
248 WGSL
249  
250 # FM (Peta::Synth::Engine::Perl::fm): one invocation per voice, operator
251 # 4's feedback a recursion; added to st (where a string is, after it).
252 # fst[2 v]: the phases; fst[2 v + 1]: operator 4's last two outputs; the
253 # same after the samples, at 20 of the voice's STATE floats.
254 fm => [ [qw(r:ctl r4:fst w:st w:out)], <<'WGSL' ],
255 let v = id.x;
256 if (v >= u.voices) { return; }
257 let c = v * u.stride;
258 if (ctl[c + 21u] == 0.0) { return; }
259 let first = u32(ctl[c]);
260 let level = ctl[c + 22u]; let fb = ctl[c + 23u];
261 let a34 = ctl[c + 28u]; let a24 = ctl[c + 29u]; let a23 = ctl[c + 30u];
262 let a14 = ctl[c + 31u]; let a13 = ctl[c + 32u]; let a12 = ctl[c + 33u];
263 let add = ctl[c + 17u] != 0.0;
264 var p = fst[2u * v];
265 var h1 = fst[2u * v + 1u].x; var h2 = fst[2u * v + 1u].y;
266 let e = u.nb + 1u;
267 let lv = c + HEAD + u.nb + 9u * e;
268 for (var j = first; j < u.nb; j++) {
269 let w = ctl[c + HEAD + j];
270 let d = w * vec4<f32>(ctl[c + 24u], ctl[c + 25u], ctl[c + 26u], ctl[c + 27u]);
271 var l = vec4<f32>(ctl[lv + j], ctl[lv + e + j], ctl[lv + 2u * e + j], ctl[lv + 3u * e + j]);
272 let s = (vec4<f32>(ctl[lv + j + 1u], ctl[lv + e + j + 1u], ctl[lv + 2u * e + j + 1u], ctl[lv + 3u * e + j + 1u]) - l) / u.b;
273 for (var m = 0u; m < 64u; m++) {
274 // The phases from the block's start: one rounding, not 64.
275 let q = p + d * f32(m);
276 let u4 = sin(q.w + fb * 0.5 * (h1 + h2));
277 h2 = h1; h1 = u4;
278 let o4 = l.w * u4;
279 let o3 = l.z * sin(q.z + a34 * o4);
280 let o2 = l.y * sin(q.y + a24 * o4 + a23 * o3);
281 let o1 = l.x * sin(q.x + a14 * o4 + a13 * o3 + a12 * o2);
282 let x = level * (ctl[c + 34u] * o1 + ctl[c + 35u] * o2 + ctl[c + 36u] * o3 + ctl[c + 37u] * o4);
283 let at = v * u.n + j * 64u + m;
284 if (add) { st[at] += x; } else { st[at] = x; }
285 l += s;
286 }
287 p += d * 64.0;
288 p -= TWO_PI * floor(p / TWO_PI);
289 }
290 let o = 3u * u.n + STATE * v + 20u;
291 out[o] = p.x; out[o + 1u] = p.y; out[o + 2u] = p.z; out[o + 3u] = p.w; out[o + 4u] = h1; out[o + 5u] = h2;
292 WGSL
293  
294 # y[v][i]: voice v's sample i, its partials (or its wave sequences),
295 # string and noise under its envelope.
296 voices => [ [qw(r4:parts r:ctl r2:tab r:nz r:am r:st r:wav w:y)], <<'WGSL' ],
297 let i = id.x; let v = id.y;
298 if (i >= u.n || v >= u.voices) { return; }
299 let c = v * u.stride;
300 let j = i / 64u;
301 var x = 0.0;
302 if (j >= u32(ctl[c])) {
303 let m = f32(i % 64u);
304 let frac = m / u.b;
305 let count = u32(ctl[c + 1u]);
306 let off = u32(ctl[c + 2u]);
307 let w = m * ctl[c + HEAD + j];
308 for (var k = 0u; k < count; k++) {
309 let row = (off + k) * (u.nb + 1u) + j;
310 let e0 = tab[row];
311 let a1 = tab[row + 1u].y;
312 var arg = e0.x + w * parts[off + k].x;
313 arg -= TWO_PI * round(arg / TWO_PI);
314 x += (e0.y + (a1 - e0.y) * frac) * sin(arg);
315 }
316 let copies = u32(ctl[c + 41u]);
317 for (var q = 0u; q < copies; q++) {
318 let b = u32(ctl[c + 42u]) + (q * u.nb + j) * 7u;
319 let oa = bitcast<u32>(ctl[b]);
320 let ob = bitcast<u32>(ctl[b + 1u]);
321 let size = ctl[b + 6u];
322 var pos = ctl[b + 4u] + m * ctl[b + 5u];
323 pos -= size * floor(pos / size);
324 let at = min(u32(pos), u32(size) - 1u);
325 let f = pos - f32(at);
326 let ta = wav[oa + at] + f * (wav[oa + at + 1u] - wav[oa + at]);
327 let tb = wav[ob + at] + f * (wav[ob + at + 1u] - wav[ob + at]);
328 x += ta + (ctl[b + 2u] + m * ctl[b + 3u]) * (tb - ta);
329 }
330 if (ctl[c + 17u] != 0.0 || ctl[c + 21u] != 0.0) { x += st[v * u.n + i]; }
331 if (ctl[c + 6u] != 0.0) { x *= am[v * u.n + i]; }
332 if (ctl[c + 3u] != 0.0) { x += nz[v * u.n + i]; }
333 let ev = c + HEAD + u.nb + j;
334 x *= ctl[ev] + (ctl[ev + 1u] - ctl[ev]) * frac;
335 }
336 y[v * u.n + i] = x;
337 WGSL
338  
339 # left, right, send: the voices under their channels' gains.
340 mix => [ [qw(r:ctl r:y w:out)], <<'WGSL' ],
341 let i = id.x;
342 if (i >= u.n) { return; }
343 let j = i / 64u;
344 let frac = f32(i % 64u) / u.b;
345 let edges = u.nb + 1u;
346 var l = 0.0; var r = 0.0; var s = 0.0;
347 for (var v = 0u; v < u.voices; v++) {
348 let x = y[v * u.n + i];
349 if (x == 0.0) { continue; }
350 let gl = v * u.stride + HEAD + u.nb + edges + j;
351 let gr = gl + edges;
352 let gs = gr + edges;
353 l += x * (ctl[gl] + (ctl[gl + 1u] - ctl[gl]) * frac);
354 r += x * (ctl[gr] + (ctl[gr + 1u] - ctl[gr]) * frac);
355 s += x * (ctl[gs] + (ctl[gs + 1u] - ctl[gs]) * frac);
356 }
357 out[i] = l; out[u.n + i] = r; out[2u * u.n + i] = s;
358 WGSL
359 );
360  
361 # The reverb. rvp, its parameters for a chunk: 0-8 the lines' and the
362 # predelay's offsets in rvl, 9-17 their lengths, 18-26 their positions
363 # where the quantum begins; 27 damp, 28 1 - damp, 29 the wet level, 30-37
364 # the lines' gains; 38 where the chunk begins, 39 its length, 40 where in
365 # out the wet left and right go. rvx: the predelayed input (n), then the
366 # lines' outputs (8 n). rvs: the lines' low-passes.
367 $SHADER{rv_in} = [ [qw(r:out r:rvl r:rvp w:rvx)], <<'WGSL' ];
368 let i = id.x;
369 if (i >= u.n) { return; }
370 let lp = u32(rvp[17]);
371 if (i >= lp) { rvx[i] = out[2u * u.n + i - lp]; }
372 else { rvx[i] = rvl[u32(rvp[8]) + (u32(rvp[26]) + i) % lp]; }
373 WGSL
374 $SHADER{rv_inw} = [ [qw(r:out r:rvp w:rvl)], <<'WGSL' ];
375 let i = id.x;
376 let lp = u32(rvp[17]);
377 if (i >= u.n || i + lp < u.n) { return; }
378 rvl[u32(rvp[8]) + (u32(rvp[26]) + i) % lp] = out[2u * u.n + i];
379 WGSL
380 $SHADER{rv_read} = [ [qw(r:rvl r:rvp w:rvx)], <<'WGSL' ];
381 let i = id.x; let l = id.y;
382 if (i >= u32(rvp[39]) || l >= 8u) { return; }
383 let t = u32(rvp[38]) + i;
384 rvx[u.n + l * u.n + t] = rvl[u32(rvp[l]) + (u32(rvp[18u + l]) + t) % u32(rvp[9u + l])];
385 WGSL
386 $SHADER{rv_damp} = [ [qw(r:rvp w:rvx w:rvs)], <<'WGSL' ];
387 let l = id.x;
388 if (l >= 8u) { return; }
389 let damp = rvp[27]; let keep = rvp[28];
390 let base = u.n + l * u.n + u32(rvp[38]);
391 let count = u32(rvp[39]);
392 var s = rvs[l];
393 for (var i = 0u; i < count; i++) {
394 s = keep * rvx[base + i] + damp * s;
395 rvx[base + i] = s;
396 }
397 rvs[l] = s;
398 WGSL
399 $SHADER{rv_mix} = [ [qw(r:rvp r:rvx w:rvl w:out)], <<'WGSL' ];
400 let i = id.x;
401 if (i >= u32(rvp[39])) { return; }
402 let t = u32(rvp[38]) + i;
403 var s: array<f32, 8>;
404 for (var l = 0u; l < 8u; l++) { s[l] = rvx[u.n + l * u.n + t]; }
405 let level = rvp[29];
406 let wb = u32(rvp[40]);
407 out[wb + t] = level * (s[0] - s[1] + s[2] - s[3] + s[4] - s[5] + s[6] - s[7]);
408 out[wb + u.n + t] = level * (s[0] + s[1] - s[2] - s[3] + s[4] + s[5] - s[6] - s[7]);
409 let a0 = s[0] + s[1]; let a1 = s[0] - s[1]; let a2 = s[2] + s[3]; let a3 = s[2] - s[3];
410 let a4 = s[4] + s[5]; let a5 = s[4] - s[5]; let a6 = s[6] + s[7]; let a7 = s[6] - s[7];
411 let b0 = a0 + a2; let b1 = a1 + a3; let b2 = a0 - a2; let b3 = a1 - a3;
412 let b4 = a4 + a6; let b5 = a5 + a7; let b6 = a4 - a6; let b7 = a5 - a7;
413 let h = 0.35355339059327373;
414 let x = rvx[t];
415 var v: array<f32, 8>;
416 v[0] = (b0 + b4) * h + x; v[1] = (b1 + b5) * h + x; v[2] = (b2 + b6) * h + x; v[3] = (b3 + b7) * h + x;
417 v[4] = (b0 - b4) * h - x; v[5] = (b1 - b5) * h - x; v[6] = (b2 - b6) * h - x; v[7] = (b3 - b7) * h - x;
418 for (var l = 0u; l < 8u; l++) {
419 rvl[u32(rvp[l]) + (u32(rvp[18u + l]) + t) % u32(rvp[9u + l])] = rvp[30u + l] * v[l];
420 }
421 WGSL
422  
423 my %ACCESS = (r => 'read', w => 'read_write');
424 my %TYPE = ('' => 'f32', 2 => 'vec2<f32>', 4 => 'vec4<f32>');
425  
426 # One device per process: a device does not cross a fork, so a forked
427 # child opens its own the first time it renders.
428 my ($DEVICE, $OWNER, %PIPELINE, %BUFFER, %BINDING, $PARAMS, $TABLE);
429 # The wave sequences' tables: as they went to the card, how much of that
430 # has gone, and where each sequence's begin there (floats).
431 my ($WAV_BYTES, $WAV_SENT, %WAV_AT) = ('', 0);
432 # The reverb whose lines the card holds, and their version.
433 my ($CARD_REVERB, $CARD_VERSION);
434  
435 sub new ($class, %arg) {
436 die "no usable GPU adapter\n" if !Peta::WebGPU::have_gpu();
437 _device();
438 return bless { %arg }, $class;
439 }
440  
441 sub name ($self) { return 'gpu' }
442  
443 # Whether voices should be read from wave sequences here: the card turns
444 # partials for next to nothing, while a wave sequence's controls are worked
445 # out and packed in Perl, block by block (on a band piece, 17.3 s against 21.0).
446 # It reads them all the same where they are asked for.
447 sub reads_waves ($self) { return 0 }
448  
449 sub adapter ($self) { return _device()->info }
450  
451 sub _device () {
452 if (!$DEVICE || $OWNER != $$) {
453 (%PIPELINE, %BUFFER, %BINDING, %WAV_AT) = ();
454 ($WAV_BYTES, $WAV_SENT) = ('', 0);
455 $CARD_REVERB = undef;
456 $DEVICE = Peta::WebGPU::Device->new(power => 'high-performance');
457 $OWNER = $$;
458 $PARAMS = $DEVICE->uniform_buffer(32);
459 $TABLE = $DEVICE->storage_buffer(pack 'f*', @{ Peta::Synth::Voice::noise_table() });
460 }
461 return $DEVICE;
462 }
463  
464 sub _pipeline ($name) {
465 return $PIPELINE{$name} //= do {
466 my ($bindings, $body) = @{ $SHADER{$name} };
467 my $source = $COMMON;
468 my $slot = 0;
469 for my $binding (@$bindings) {
470 my ($access, $type, $var) = $binding =~ /\A([rw])(\d?):(\w+)\z/ or die "bad binding $binding";
471 $source .= sprintf "\@group(0) \@binding(%d) var<storage, %s> %s: array<%s>;\n", $slot++, $ACCESS{$access}, $var, $TYPE{$type};
472 }
473 $source .= sprintf "\@group(0) \@binding(%d) var<uniform> u: Params;\n", $slot;
474 $source .= "\@compute \@workgroup_size(64)\nfn main(\@builtin(global_invocation_id) id: vec3<u32>) {\n$body}\n";
475 $DEVICE->pipeline($DEVICE->shader($source), 'main');
476 };
477 }
478  
479 # A buffer of at least $bytes, kept and grown by doubling; the bindings
480 # that held the old one go with it.
481 sub _buffer ($name, $bytes) {
482 $bytes = 16 if $bytes < 16;
483 my $buffer = $BUFFER{$name};
484 return $buffer if $buffer && $buffer->size >= $bytes;
485 my $size = 1024;
486 $size *= 2 while $size < $bytes;
487 %BINDING = ();
488 return $BUFFER{$name} = $DEVICE->storage_buffer($size);
489 }
490  
491 my %BUFFERS_OF = (
492 edges => [qw(parts phase ctl tab)],
493 noise => [qw(ctl nstate table nz am out)],
494 strings => [qw(ctl sst sbuf st out)],
495 fm => [qw(ctl fst st out)],
496 voices => [qw(parts ctl tab nz am st wav y)],
497 mix => [qw(ctl y out)],
498 rv_in => [qw(out rvl rvp rvx)],
499 rv_inw => [qw(out rvp rvl)],
500 rv_read => [qw(rvl rvp rvx)],
501 rv_damp => [qw(rvp rvx rvs)],
502 rv_mix => [qw(rvp rvx rvl out)],
503 );
504  
505 # Where a wave sequence's tables begin in `wav` (floats): added to what goes
506 # to the card the first time, kept after.
507 sub _wav_at ($sequence) {
508 return $WAV_AT{$sequence} //= do {
509 my $at = length($WAV_BYTES) / 4;
510 $WAV_BYTES .= pack 'f*', map { @$_ } @{ $sequence->{tables} };
511 $at;
512 };
513 }
514  
515 # What is new of the tables onto the card; all of them into a larger buffer
516 # when they outgrow it.
517 sub _wav_upload () {
518 my $buffer = $BUFFER{wav};
519 if (!$buffer || $buffer->size < length $WAV_BYTES) {
520 $buffer = _buffer(wav => length $WAV_BYTES);
521 $WAV_SENT = 0;
522 }
523 $buffer->write(substr($WAV_BYTES, $WAV_SENT), $WAV_SENT) if length($WAV_BYTES) > $WAV_SENT;
524 $WAV_SENT = length $WAV_BYTES;
525 return;
526 }
527  
528 sub _run ($name, $x, $y = 1) {
529 my $binding = $BINDING{$name} //= _pipeline($name)->bind([ (map { $_ eq 'table' ? $TABLE : $BUFFER{$_} } @{ $BUFFERS_OF{$name} }), $PARAMS ]);
530 $DEVICE->run($binding, $x, $y);
531 return;
532 }
533  
534 sub render ($self, $voices, $n, $rate) { return $self->_render($voices, $n, $rate, undef) }
535  
536 # The voices and the reverb of their send: left, right, send, and the wet
537 # left and right (none when the reverb is off).
538 sub render_reverb ($self, $voices, $n, $rate, $reverb) {
539 return $self->_render($voices, $n, $rate, $reverb->active ? $reverb : undef);
540 }
541  
542 # The reverb's lines onto the card, unless they are there: another
543 # reverb's given back to it first.
544 sub _reverb_onto_card ($reverb) {
545 return if $CARD_REVERB && $CARD_REVERB == $reverb && $CARD_VERSION == $reverb->{version} && $reverb->{elsewhere};
546 if ($CARD_REVERB && $CARD_REVERB != $reverb && (my $back = delete $CARD_REVERB->{elsewhere})) { $back->() }
547 my $lines = pack 'f*', @{ $reverb->{buffer} };
548 _buffer(rvl => length $lines)->write($lines, 0);
549 _buffer(rvs => 32)->write(pack('f8', @{ $reverb->{lp} }), 0);
550 ($CARD_REVERB, $CARD_VERSION) = ($reverb, $reverb->{version});
551 weaken $CARD_REVERB;
552 my $owner = $$;
553 my $weak = $reverb;
554 weaken $weak;
555 $reverb->{elsewhere} = sub {
556 return if !$weak || $owner != $$ || !$CARD_REVERB || $CARD_REVERB != $weak; # the card is not this process's
557 my ($l, $s);
558 $DEVICE->batch(sub { $l = $BUFFER{rvl}->read(0, length $lines); $s = $BUFFER{rvs}->read(0, 32) });
559 $weak->{buffer} = [ unpack 'f*', $l ];
560 $weak->{lp} = [ unpack 'f8', $s ];
561 $CARD_REVERB = undef;
562 };
563 return;
564 }
565  
566 sub _render ($self, $voices, $n, $rate, $reverb) {
567 my $B = BLOCK;
568 my $nb = $n / $B;
569 return ([ (0.0) x $n ], [ (0.0) x $n ], [ (0.0) x $n ]) if !@$voices && !$reverb;
570 _device();
571  
572 my $V = @$voices;
573 my $stride = HEAD + $nb + 13 * ($nb + 1);
574 my $packed = _pack_voices($voices, $nb, $rate, $stride);
575 _upload_voices($packed, $V, $n, $nb) if $V;
576  
577 my $wet = 3 * $n + STATE * $V; # where the wet sound goes in out
578 my $floats = $wet + ($reverb ? 2 * $n : 0);
579 my $out = _buffer(out => 4 * $floats);
580 $PARAMS->write(pack('L4 f4', $n, $nb, $V, $stride, $B / $rate, $B, 0, 0), 0);
581  
582 my ($chunks, $fixed) = $reverb ? _reverb_chunks($reverb, $n) : ([], []);
583  
584 my ($bytes, $sbytes);
585 my $groups = sub ($count) { int(($count + 63) / 64) }; # workgroups of 64
586 $DEVICE->batch(sub {
587 if ($V) {
588 _run(edges => $groups->($packed->{most}), $V) if $packed->{most};
589 _run(noise => $groups->($V));
590 _run(strings => $groups->($V)) if $packed->{sfloats};
591 _run(fm => $groups->($V)) if $packed->{fms};
592 _run(voices => $nb, $V);
593 _run(mix => $groups->($n));
594 }
595 else {
596 $out->write(pack('f*', (0.0) x (3 * $n)), 0);
597 }
598 for my $k (0 .. $#$chunks) {
599 my ($c0, $len) = @{ $chunks->[$k] };
600 $BUFFER{rvp}->write(pack('f*', @$fixed, $c0, $len, $wet), 0);
601 if ($k == 0) {
602 _run(rv_in => $groups->($n));
603 _run(rv_inw => $groups->($n));
604 }
605 _run(rv_read => $groups->($len), 8);
606 _run(rv_damp => 1);
607 _run(rv_mix => $groups->($len));
608 }
609 $bytes = $out->read(0, 4 * $floats);
610 $sbytes = $BUFFER{sbuf}->read(0, 4 * $packed->{sfloats}) if $packed->{sfloats};
611 });
612  
613 my @f = unpack 'f*', $bytes;
614 my @strings = $packed->{sfloats} ? unpack('f*', $sbytes) : ();
615 _carry_on($voices, \@f, \@strings, $n);
616  
617 my @mix = map { [ @f[ $_ * $n .. ($_ + 1) * $n - 1 ] ] } 0 .. 2;
618 return @mix if !$reverb;
619  
620 my @wet = map { [ @f[ $wet + $_ * $n .. $wet + ($_ + 1) * $n - 1 ] ] } 0, 1;
621 $reverb->advance($n, $mix[2], @wet);
622 return (@mix, @wet);
623 }
624  
625 # Every voice packed for the card: { parts, phase, ctl (and the wave
626 # sequences' controls after it), nstate, sst, sbuf, fst; offset (the
627 # partials), most (the most partials a voice has), sfloats (the strings'
628 # floats), fms (voices with FM) }.
629 sub _pack_voices ($voices, $nb, $rate, $stride) {
630 my %p = map { $_ => '' } qw(parts phase ctl waves nstate sst sbuf fst);
631 @p{qw(offset most sfloats fms)} = (0, 0, 0, 0);
632 my $wave_at = @$voices * $stride; # where the wave sequences' controls begin in ctl
633  
634 for my $voice (@$voices) {
635 my $count = $voice->{wave} ? 0 : @{ $voice->{ratio} }; # read from wave sequences instead
636 if (!$voice->{wave}) {
637 $p{parts} .= $voice->{gpu_parts} //= pack 'f*', map {
638 ($voice->{ratio}[$_], $voice->{amp}[$_], $voice->{decay}[$_], $voice->{attack}[$_])
639 } 0 .. $count - 1;
640 $p{phase} .= pack 'f*', @{ $voice->{phase} };
641 }
642  
643 my $controls = $wave_at + length($p{waves}) / 4;
644 my $copies = 0;
645 for my $c (@{ $voice->{wave} ? Peta::Synth::Engine::Perl::wave_blocks($voice, $nb, $rate) : [] }) {
646 $p{waves} .= _wave_controls($c, $nb);
647 $copies++;
648 }
649  
650 my $string = $voice->{string};
651 if ($string) {
652 my $size = @{ $string->{buf} };
653 my $todo = @{ $string->{exc} };
654 $p{sst} .= pack 'f8', $p{sfloats}, $size, @$string{qw(pos prev ax ay fed)}, $todo;
655 $p{sbuf} .= pack 'f*', @{ $string->{buf} }, @{ $string->{disp} }, @{ $string->{exc} };
656 $p{sfloats} += $size + 8 + $todo;
657 }
658 else {
659 $p{sst} .= pack 'f8', (0) x 8;
660 }
661  
662 my $fm = $voice->{fm};
663 $p{fst} .= $fm ? pack('f8', @{ $fm->{phase} }, @{ $fm->{hist} }, 0, 0) : pack('f8', (0) x 8);
664 $p{fms}++ if $fm;
665  
666 my @bands = @{ $voice->{bands} // [] };
667 $p{nstate} .= pack 'f32',
668 (map { $bands[$_] ? (@{ $bands[$_]{state} }[ 0 .. 2 ], 0) : (0, 0, 0, 0) } 0 .. 2),
669 $voice->{rough} ? (@{ $voice->{rstate} }, 0, 0) : (0, 0, 0, 0),
670 (map { $bands[$_] ? (@{ $bands[$_]{state} }[ 3, 4 ], 0, 0) : (0, 0, 0, 0) } 0 .. 2),
671 0, 0, 0, 0;
672  
673 $p{ctl} .= _control_row($voice, $nb, $count, $p{offset}, $copies, $controls);
674 $p{offset} += $count;
675 $p{most} = $count if $count > $p{most};
676 }
677 $p{ctl} .= delete $p{waves};
678 return \%p;
679 }
680  
681 # A copy's wave sequence controls, block by block: the two tables' first
682 # samples in `wav`, the crossfade and its step, where in the period the
683 # block begins and the read step, the period.
684 sub _wave_controls ($c, $nb) {
685 my $at = _wav_at($c->{sequence});
686 my ($size, $last) = @$c{qw(size last)};
687 my @table = @{ $c->{table} };
688 return join '', map {
689 my $k = $table[$_];
690 my $next = $k < $last ? $k + 1 : $k;
691 pack 'L2 f5', $at + $k * ($size + 1), $at + $next * ($size + 1),
692 $c->{mix}[$_], $c->{dmix}[$_], $c->{start}[$_], $c->{step}[$_], $size;
693 } 0 .. $nb - 1;
694 }
695  
696 # A voice's row of controls in `ctl`, as the table above HEAD lays it out.
697 sub _control_row ($voice, $nb, $count, $offset, $copies, $controls) {
698 my $mode = $voice->{fmode} // 0;
699 my @bands = @{ $voice->{bands} // [] };
700 my $rough = $voice->{rough};
701 my $string = $voice->{string};
702 my $fm = $voice->{fm};
703 my $edges = $nb + 1;
704  
705 return pack 'f*',
706 $voice->{first}, $count, $offset, scalar @bands, # 0 .. 3
707 $voice->{t0}, $mode, # 4, 5
708 $rough ? @$rough : (0, 0), # 6, 7
709 (map { $bands[$_] ? _band_row($bands[$_]) : (0, 0, 0) } 0 .. 2), # 8 .. 16
710 $string ? (1, @$string{qw(level g s1)}) : (0, 0, 0, 0), # 17 .. 20
711 $fm ? (1, $fm->{level}, $fm->{fb}, @{ $fm->{ratio} }, @{ $fm->{coef} }, @{ $fm->{carrier} })
712 : (0) x 17, # 21 .. 37
713 $string ? @$string{qw(off stages a)} : (0, 0, 0), # 38 .. 40
714 $copies, $controls, # 41, 42
715 @{ $voice->{w} }, # HEAD: w[nb]
716 @{ $voice->{env} }, @{ $voice->{gl} }, @{ $voice->{gr} }, @{ $voice->{gs} },
717 $mode ? (@{ $voice->{fx} }, @{ $voice->{fq} }) : ((0.0) x $edges, (1.0) x $edges),
718 (map { $bands[$_] ? @{ $bands[$_]{env} } : (0.0) x $edges } 0 .. 2),
719 (map { $fm ? @{ $fm->{lv}[$_] } : (0.0) x $edges } 0 .. 3);
720 }
721  
722 # A band of noise's filter in a voice's row: g, k, and its mode, 4 more with four poles.
723 sub _band_row ($band) { return (@$band{qw(g k)}, $band->{mode} + ($band->{poles} == 4 ? 4 : 0)) }
724  
725 # The packed voices onto the card, and room for what the passes write.
726 sub _upload_voices ($p, $V, $n, $nb) {
727 # The voice pass binds the partials even when no voice has any (a
728 # string, a drum of noise alone).
729 my $partials = _buffer(parts => length $p->{parts});
730 $partials->write($p->{parts}, 0) if length $p->{parts};
731 _buffer(phase => length $p->{phase})->write($p->{phase}, 0) if length $p->{phase};
732 _buffer(ctl => length $p->{ctl})->write($p->{ctl}, 0);
733 _wav_upload();
734 _buffer(nstate => length $p->{nstate})->write($p->{nstate}, 0);
735 _buffer(tab => 8 * $p->{offset} * ($nb + 1));
736 _buffer(nz => 4 * $V * $n);
737 _buffer(am => 4 * $V * $n);
738 _buffer(st => 4 * $V * $n);
739 _buffer(sst => length $p->{sst})->write($p->{sst}, 0);
740 _buffer(sbuf => length $p->{sbuf})->write($p->{sbuf}, 0) if length $p->{sbuf};
741 _buffer(fst => length $p->{fst})->write($p->{fst}, 0);
742 _buffer(y => 4 * $V * $n);
743 return;
744 }
745  
746 # The reverb onto the card, and its chunks: [ where each begins, its
747 # length ], as long as the shortest line at most; and the parameters every
748 # chunk shares (rvp's first 38).
749 sub _reverb_chunks ($reverb, $n) {
750 _reverb_onto_card($reverb);
751 _buffer(rvx => 4 * 9 * $n);
752 _buffer(rvp => 4 * 41);
753  
754 my $damp = $reverb->{damp};
755 my @fixed = (@{ $reverb->{offset} }, @{ $reverb->{len} }, $reverb->{pre}, @{ $reverb->{pos} },
756 $damp, 1.0 - $damp, $reverb->{level} * 0.35, @{ $reverb->{g} });
757  
758 my $shortest = $n;
759 for (@{ $reverb->{len} }) { $shortest = $_ if $_ < $shortest }
760 my @chunks;
761 for (my $c0 = 0; $c0 < $n; $c0 += $shortest) {
762 push @chunks, [ $c0, $n - $c0 < $shortest ? $n - $c0 : $shortest ];
763 }
764 return (\@chunks, \@fixed);
765 }
766  
767 # Where the quantum leaves the voices, from what the card returned: the
768 # partials' phases (carried on here, in double precision), the noise's
769 # filters, FM's phases, the strings.
770 sub _carry_on ($voices, $f, $strings, $n) {
771 my $B = BLOCK;
772 my $sfrom = 0;
773 for my $v (0 .. $#$voices) {
774 my $voice = $voices->[$v];
775 if (!$voice->{wave}) { # a voice read from wave sequences went on in wave_blocks
776 my $turn = 0.0;
777 $turn += $_ for @{ $voice->{w} };
778 $turn *= $B;
779 my @ratio = @{ $voice->{ratio} };
780 my @phase = @{ $voice->{phase} };
781 for my $k (0 .. $#phase) {
782 my $p = $phase[$k] + $ratio[$k] * $turn;
783 $phase[$k] = $p - TWO_PI * int($p / TWO_PI);
784 }
785 $voice->{phase} = \@phase;
786 }
787  
788 my $o = 3 * $n + STATE * $v; # the voice's state in out
789 my $b = 0;
790 for my $band (@{ $voice->{bands} // [] }) {
791 $band->{state} = [ @$f[ $o + 4 * $b, $o + 4 * $b + 1 ], int $f->[ $o + 4 * $b + 2 ], @$f[ $o + 28 + 2 * $b, $o + 29 + 2 * $b ] ];
792 $b++;
793 }
794 $voice->{rstate} = [ $f->[ $o + 12 ], int $f->[ $o + 13 ] ] if $voice->{rough};
795 if (my $fm = $voice->{fm}) {
796 $fm->{phase} = [ @$f[ $o + 20 .. $o + 23 ] ];
797 $fm->{hist} = [ @$f[ $o + 24, $o + 25 ] ];
798 }
799 if (my $string = $voice->{string}) {
800 my $size = @{ $string->{buf} };
801 @$string{qw(pos prev ax ay)} = (int $f->[ $o + 16 ], @$f[ $o + 17 .. $o + 19 ]);
802 $string->{buf} = [ @$strings[ $sfrom .. $sfrom + $size - 1 ] ];
803 $string->{disp} = [ @$strings[ $sfrom + $size .. $sfrom + $size + 7 ] ];
804 $sfrom += $size + 8 + @{ $string->{exc} };
805 $string->{fed} = int $f->[ $o + 26 ];
806 $string->{exc} = [] if $string->{fed} >= @{ $string->{exc} };
807 }
808 }
809 return;
810 }
811  
812 1;
813  
814 __END__
« lib/Peta/Vorbis/Encode/MDCT/PDL.pm ↑ Summary lib/Peta/MP3/Encode/Tables.pm »