diff options
Diffstat (limited to 'src/sketch')
| -rw-r--r-- | src/sketch/request.zig | 2 | ||||
| -rw-r--r-- | src/sketch/root.zig | 72 | ||||
| -rw-r--r-- | src/sketch/sfxr.zig | 267 | ||||
| -rw-r--r-- | src/sketch/web.zig | 35 |
4 files changed, 339 insertions, 37 deletions
diff --git a/src/sketch/request.zig b/src/sketch/request.zig index 0b8b400..4a8e414 100644 --- a/src/sketch/request.zig +++ b/src/sketch/request.zig @@ -1,5 +1,5 @@ //! Requests from `update` that `draw` carries out once. `update` sees only -//! State and input, so when a key should do something to Session or Store +//! State and input, so when a key should do something to Session //! (start the microphone, open a dialog, seek a stream), State holds the //! request and Session remembers which ones it has handled: //! diff --git a/src/sketch/root.zig b/src/sketch/root.zig index cb20ab9..755e446 100644 --- a/src/sketch/root.zig +++ b/src/sketch/root.zig @@ -7,19 +7,18 @@ //! pub const height = 600; //! pub const State = struct { ... }; // saved, snapshotted, replayed: no pointers //! pub const Session = struct { ... }; // this process: survives reloads -//! pub const Store = struct { ... }; // on disk: survives restarts too //! pub const commands = .{"hello"}; // console completions //! pub fn init(state: *State, host: sk.Host) void //! pub fn setup(session: *Session, init: *sk.Init) !void //! pub fn update(state: *State, in: *const sk.Input) void -//! pub fn draw(state: *const State, session: *Session, store: *Store, f: *sk.Frame) void -//! pub fn command(state: *State, store: *Store, c: *sk.Console, line: []const u8) !bool +//! pub fn draw(state: *const State, session: *Session, f: *sk.Frame) void +//! pub fn command(state: *State, session: *Session, c: *sk.Console, line: []const u8) !bool //! //! Functions take the parameters they name, by type, in any order: `draw` -//! may ask for `*Session`, `*Store`, both or neither. `update` must be +//! may ask for `*Session` or not. `update` must be //! deterministic, so it gets `State` and `Input` only: the host replays //! recorded input through it. `draw` presents state as pictures and sound, -//! and changes only Session and Store. Geometry and colors are duck-typed: +//! and changes only Session. Geometry and colors are duck-typed: //! see `shape`. const std = @import("std"); pub const abi = @import("abi"); @@ -41,6 +40,8 @@ pub const List = @import("list.zig").List; /// Data computed in draw from a few State fields, kept in Session and rebuilt when they change (or after a reload). pub const Derived = @import("derived.zig").Derived; pub const web = @import("web.zig"); +/// sfxr's sound effects, rendered to samples for `host.newSound`. +pub const sfxr = @import("sfxr.zig"); const request = @import("request.zig"); pub const Request = request.Request; pub const Handled = request.Handled; @@ -65,7 +66,6 @@ pub const Face = abi.Face; pub const Init = struct { host: Host, session: std.mem.Allocator, - store: std.mem.Allocator, }; /// What `draw` receives: input, host services, memory by lifetime and the @@ -80,14 +80,12 @@ pub const Frame = struct { scratch: std.mem.Allocator, /// For Session: this process. session: std.mem.Allocator, - /// For Store: on disk, across restarts. - store: std.mem.Allocator, /// A library's own state for this frame (canim's table of places), in /// `scratch`: null at each frame's start. user: ?*anyopaque = null, pub fn init(ctx: *const abi.Context) Frame { - return .{ .ctx = ctx, .in = ctx.input, .host = ctx.host, .scratch = ctx.scratch, .session = ctx.session, .store = ctx.store }; + return .{ .ctx = ctx, .in = ctx.input, .host = ctx.host, .scratch = ctx.scratch, .session = ctx.session }; } pub fn emit(f: *Frame, command: abi.Command) void { @@ -210,9 +208,20 @@ pub const Frame = struct { pub fn voice(f: *Frame, v: Voice) void { f.emit(.{ .voice = v }); } + /// Scales every voice of `group` this frame (1 when not declared). + pub fn gain(f: *Frame, group: u3, value: f32) void { + f.emit(.{ .gain = .{ .group = group, .gain = value } }); + } pub fn audio(f: *Frame, key: u32, samples: []const f32, options: struct { clear: bool = false }) void { f.emit(.{ .audio = .{ .key = key, .samples = samples, .clear = options.clear } }); } + /// Streams `count` samples a compute shader wrote to `buffer` (f32 from + /// `offset`) on stream `key`, as `audio` streams samples: a GPU synth's + /// output, heard without a readback of the sketch's own. Make + /// `in.lead -| in.stream(key).queued` of them a frame. + pub fn audioBuffer(f: *Frame, key: u32, buffer: abi.Buffer, options: struct { offset: u32 = 0, count: u32 }) void { + f.emit(.{ .audio_buffer = .{ .key = key, .buffer = buffer, .offset = options.offset, .count = options.count } }); + } pub fn pixels(f: *Frame, img: Image, w: u32, h: u32, rgba: []const u8, options: struct { premultiplied: bool = false }) void { f.emit(.{ .pixels = .{ .image = img, .w = w, .h = h, .rgba = rgba, .premultiplied = options.premultiplied } }); } @@ -285,12 +294,11 @@ fn paint(value: anytype) Color { } /// What `command` receives: somewhere to answer, the current input, and the -/// allocators for Session and Store. +/// allocator for Session. pub const Console = struct { host: Host, in: *const Input, session: std.mem.Allocator, - store: std.mem.Allocator, pub fn log(c: *Console, message: []const u8) void { c.host.log(message); @@ -300,15 +308,24 @@ pub const Console = struct { } }; +/// What the build knows of a sketch and passes to `sketch` and +/// `exportSketch` (build.zig's generated roots fill it in). +pub const Build = struct { + /// The repository revision the sketch was built from, "" when unknown. + source: []const u8 = "", + /// Keep history in the save (`abi.Info.record`). + record: bool = false, +}; + /// The entry points of `App`, for a host that links it statically. -pub fn sketch(comptime App: type) abi.Sketch { - const G = Glue(App); +pub fn sketch(comptime App: type, comptime made: Build) abi.Sketch { + const G = Glue(App, made); return .{ .info = G.info, .defaults = G.defaults, .init = G.init, .setup = G.setup, .update = G.update, .draw = G.draw, .command = G.command }; } /// Exports `App` under `abi.Sketch.symbols`, for a hot-reloaded library. -pub fn exportSketch(comptime App: type) void { - const G = Glue(App); +pub fn exportSketch(comptime App: type, comptime made: Build) void { + const G = Glue(App, made); const names = abi.Sketch.symbols; @export(&G.info, .{ .name = names.info }); @export(&G.defaults, .{ .name = names.defaults }); @@ -317,13 +334,15 @@ pub fn exportSketch(comptime App: type) void { @export(&G.update, .{ .name = names.update }); @export(&G.draw, .{ .name = names.draw }); @export(&G.command, .{ .name = names.command }); + @export(&G.build, .{ .name = "sketch_build" }); } -pub fn Glue(comptime App: type) type { +pub fn Glue(comptime App: type, comptime made: Build) type { return struct { pub const State = if (@hasDecl(App, "State")) App.State else struct {}; pub const Session = if (@hasDecl(App, "Session")) App.Session else struct {}; - pub const Store = if (@hasDecl(App, "Store")) App.Store else struct {}; + + const build: [abi.build.len:0]u8 = abi.build.*; pub const description: abi.Info = .{ .abi = abi.hash, @@ -332,8 +351,10 @@ pub fn Glue(comptime App: type) type { .height = if (@hasDecl(App, "height")) App.height else 600, .state = abi.layout.of(State, .state), .session = abi.layout.of(Session, .session), - .store = abi.layout.of(Store, .store), .commands = if (@hasDecl(App, "commands")) &App.commands else &.{}, + .source = made.source ++ " " ++ abi.build, + .record = made.record, + .audio_pull = if (@hasDecl(App, "audio_pull")) App.audio_pull else 0, }; /// What a call can offer, by type. @@ -357,10 +378,10 @@ pub fn Glue(comptime App: type) type { return std.mem.eql(u8, name, n); } }; - if (comptime is.named("update") and (T == *Session or T == *Store)) + if (comptime is.named("update") and T == *Session) @compileError("update must be deterministic: it gets State and Input only, so a replay reproduces it"); if (comptime is.named("setup") and (T == *State or T == *const State or T == *const Input)) - @compileError("setup initializes resources: it gets Session, Store, Init and Host only"); + @compileError("setup initializes resources: it gets Session, Init and Host only"); if (comptime (T == *Init or T == *const Init) and !is.named("setup")) @compileError(name ++ " gets no Init: only setup does"); if (comptime is.named("draw") and T == *State) @compileError("draw only reads State: take *const State"); if (comptime T == *Frame and !is.named("draw")) @compileError(name ++ " gets no Frame: only draw does"); @@ -369,8 +390,6 @@ pub fn Glue(comptime App: type) type { @ptrCast(@alignCast(offer.state)) else if (T == *Session or T == *const Session) @ptrCast(@alignCast(offer.ctx.session_root)) - else if (T == *Store or T == *const Store) - @ptrCast(@alignCast(offer.ctx.store_root)) else if (T == *const Input) offer.ctx.input else if (T == Host) @@ -396,7 +415,6 @@ pub fn Glue(comptime App: type) type { switch (which) { .state => @as(*State, @ptrCast(@alignCast(ptr))).* = .{}, .session => @as(*Session, @ptrCast(@alignCast(ptr))).* = .{}, - .store => @as(*Store, @ptrCast(@alignCast(ptr))).* = .{}, } } pub fn init(ctx: *const abi.Context, s: [*]u8) callconv(.c) void { @@ -404,7 +422,7 @@ pub fn Glue(comptime App: type) type { } pub fn setup(ctx: *const abi.Context) callconv(.c) bool { if (!@hasDecl(App, "setup")) return true; - var resource_init: Init = .{ .host = ctx.host, .session = ctx.session, .store = ctx.store }; + var resource_init: Init = .{ .host = ctx.host, .session = ctx.session }; const result = call(App.setup, "setup", .{ .ctx = ctx, .state = undefined, .resource_init = &resource_init }); if (@typeInfo(@TypeOf(result)) == .error_union) result catch |err| { ctx.host.print("session setup failed: {t}", .{err}); @@ -422,7 +440,7 @@ pub fn Glue(comptime App: type) type { } pub fn command(ctx: *const abi.Context, s: [*]u8, line: *const []const u8) callconv(.c) abi.Outcome { if (!@hasDecl(App, "command")) return .unknown; - var c: Console = .{ .host = ctx.host, .in = ctx.input, .session = ctx.session, .store = ctx.store }; + var c: Console = .{ .host = ctx.host, .in = ctx.input, .session = ctx.session }; const taken = call(App.command, "command", .{ .ctx = ctx, .state = s, .console = &c, .line = line.* }) catch |err| { c.print("{t}. Type help for usage.", .{err}); return .failed; @@ -442,6 +460,7 @@ test { _ = @import("clock.zig"); _ = @import("list.zig"); _ = @import("derived.zig"); + _ = sfxr; } test "setup receives session resources without a Frame and reports errors" { @@ -467,8 +486,7 @@ test "setup receives session resources without a Frame and reports errors" { ctx.host = .{ .ctx = &seen, .vtable = &vtable }; ctx.session_root = std.mem.asBytes(&session); ctx.session = std.testing.allocator; - ctx.store = std.testing.allocator; - const app = sketch(App); + const app = sketch(App, .{}); try std.testing.expect(!app.setup(&ctx)); defer std.testing.allocator.free(session.bytes); try std.testing.expectEqualStrings("ready", session.bytes); diff --git a/src/sketch/sfxr.zig b/src/sketch/sfxr.zig new file mode 100644 index 0000000..01657b5 --- /dev/null +++ b/src/sketch/sfxr.zig @@ -0,0 +1,267 @@ +//! sfxr, DrPetter's sound-effect generator (blips, coins, lasers, +//! explosions): one waveform through an envelope, pitch slides, vibrato, +//! arpeggio, duty sweep, a phaser and two filters, 8× oversampled. Pure and +//! deterministic: the same `Params` and rate give the same samples, so a +//! sketch renders its sounds whenever it likes and plays them as voices: +//! +//! const n = sk.sfxr.render(.{ .freq = 0.5, .decay = 0.2 }, f.in.sample_rate, &buf); +//! ss.blip = f.host.newSound(buf[0..n]); +//! +//! Ported from 02-dont-rat-me-out's synth.zig. sfxr's knobs count in +//! samples at 44.1 kHz; at another rate every length, step and filter +//! coefficient is scaled to keep the same durations, pitches and cutoffs +//! (to first order for the slides and filters), and at 44.1 kHz the +//! samples are the original's to the bit. +const std = @import("std"); + +/// The rate sfxr's knobs were tuned at. +pub const reference_rate = 44_100; + +pub const Wave = enum(u8) { square, sawtooth, sine, noise }; + +/// All sfxr knobs. Most are 0..1, a few -1..1. +pub const Params = struct { + wave: Wave = .square, + // envelope + attack: f32 = 0.0, + sustain: f32 = 0.3, + punch: f32 = 0.0, + decay: f32 = 0.4, + // frequency + freq: f32 = 0.3, + freq_limit: f32 = 0.0, + freq_ramp: f32 = 0.0, + freq_dramp: f32 = 0.0, + // vibrato + vibrato_depth: f32 = 0.0, + vibrato_speed: f32 = 0.0, + // arpeggio + arp_mod: f32 = 0.0, + arp_speed: f32 = 0.0, + // square duty + duty: f32 = 0.0, + duty_ramp: f32 = 0.0, + // phaser + phaser_offset: f32 = 0.0, + phaser_ramp: f32 = 0.0, + // filters + lpf_freq: f32 = 1.0, + lpf_ramp: f32 = 0.0, + lpf_resonance: f32 = 0.0, + hpf_freq: f32 = 0.0, + hpf_ramp: f32 = 0.0, + // repeat + repeat_speed: f32 = 0.0, + // output + volume: f32 = 0.5, +}; + +inline fn sq(x: f32) f32 { + return x * x; +} +inline fn cube(x: f32) f32 { + return x * x * x; +} +inline fn xs(s: *u32) u32 { + s.* ^= s.* << 13; + s.* ^= s.* >> 17; + s.* ^= s.* << 5; + return s.*; +} +fn frnd(s: *u32, range: f32) f32 { + return @as(f32, @floatFromInt(xs(s))) / 4294967295.0 * range; +} + +/// Synthesizes `p` at `rate` samples a second into `out` (mono, -1..1). +/// Returns the number of samples written: the envelope's length, or less +/// when `out` is shorter or the pitch falls to `freq_limit`. +pub fn render(p: Params, rate: u32, out: []f32) usize { + // Samples at `rate` per sample at 44.1 kHz: lengths grow by it, steps + // per sample shrink by it. + const k: f64 = @as(f64, @floatFromInt(rate)) / reference_rate; + const kf: f32 = @floatCast(k); + var rng: u32 = 0x52ad4326; + + var fperiod: f64 = 100.0 / (@as(f64, p.freq) * p.freq + 0.001) * k; + var period: i32 = @intFromFloat(fperiod); + const fmaxperiod: f64 = 100.0 / (@as(f64, p.freq_limit) * p.freq_limit + 0.001) * k; + var fslide: f64 = 1.0 - @as(f64, cube(p.freq_ramp)) * 0.01 / k; + const fdslide: f64 = -@as(f64, cube(p.freq_dramp)) * 0.000001 / (k * k); + + var square_duty: f32 = 0.5 - p.duty * 0.5; + const square_slide: f32 = -p.duty_ramp * 0.00005 / kf; + + const arp_mod: f64 = if (p.arp_mod >= 0) 1.0 - @as(f64, sq(p.arp_mod)) * 0.9 else 1.0 + @as(f64, sq(p.arp_mod)) * 10.0; + var arp_time: i32 = 0; + var arp_limit: i32 = @intFromFloat((sq(p.arp_speed) * 20000 + 32) * kf); + if (p.arp_speed == 1.0) arp_limit = 0; + + var env_vol: f32 = 0; + var env_stage: usize = 0; + var env_time: i32 = 0; + const env_length = [3]i32{ + @intFromFloat(p.attack * p.attack * 100000 * kf), + @intFromFloat(p.sustain * p.sustain * 100000 * kf), + @intFromFloat(p.decay * p.decay * 100000 * kf), + }; + + var fphase: f32 = sq(p.phaser_offset) * 1020 * kf; + if (p.phaser_offset < 0) fphase = -fphase; + var fdphase: f32 = sq(p.phaser_ramp) * 1.0; + if (p.phaser_ramp < 0) fdphase = -fdphase; + var iphase: i32 = @intFromFloat(@min(@abs(fphase), 1023)); + var ipp: i32 = 0; + var phaser_buffer: [1024]f32 = @splat(0); + + var noise_buffer: [32]f32 = undefined; + for (&noise_buffer) |*nb| nb.* = frnd(&rng, 2) - 1; + + var fltp: f32 = 0; + var fltdp: f32 = 0; + var fltw: f32 = cube(p.lpf_freq) * 0.1 / kf; + const fltw_d: f32 = 1.0 + p.lpf_ramp * 0.0001 / kf; + var fltdmp: f32 = 5.0 / (1.0 + sq(p.lpf_resonance) * 20) * (0.01 + fltw); + if (fltdmp > 0.8) fltdmp = 0.8; + var fltphp: f32 = 0; + var flthp: f32 = sq(p.hpf_freq) * 0.1 / kf; + const flthp_d: f32 = 1.0 + p.hpf_ramp * 0.0003 / kf; + + var vib_phase: f32 = 0; + const vib_speed: f32 = sq(p.vibrato_speed) * 0.01 / kf; + const vib_amp: f32 = p.vibrato_depth * 0.5; + + var rep_time: i32 = 0; + var rep_limit: i32 = @intFromFloat((sq(1 - p.repeat_speed) * 20000 + 32) * kf); + if (p.repeat_speed == 0) rep_limit = 0; + + var phase: i32 = 0; + var n: usize = 0; + var finished = false; + while (!finished and n < out.len) : (n += 1) { + rep_time += 1; + if (rep_limit != 0 and rep_time >= rep_limit) { + rep_time = 0; + fperiod = 100.0 / (@as(f64, p.freq) * p.freq + 0.001) * k; + period = @intFromFloat(fperiod); + fslide = 1.0 - @as(f64, cube(p.freq_ramp)) * 0.01 / k; + arp_time = 0; + arp_limit = @intFromFloat((sq(p.arp_speed) * 20000 + 32) * kf); + if (p.arp_speed == 1.0) arp_limit = 0; + } + + arp_time += 1; + if (arp_limit != 0 and arp_time >= arp_limit) { + arp_limit = 0; + fperiod *= arp_mod; + } + + fslide += fdslide; + fperiod *= fslide; + if (fperiod > fmaxperiod) { + fperiod = fmaxperiod; + if (p.freq_limit > 0) finished = true; + } + + var rfperiod: f32 = @floatCast(fperiod); + if (vib_amp > 0) { + vib_phase += vib_speed; + rfperiod = @floatCast(fperiod * (1.0 + @as(f64, @sin(vib_phase) * vib_amp))); + } + period = @intFromFloat(rfperiod); + if (period < 8) period = 8; + + square_duty += square_slide; + square_duty = std.math.clamp(square_duty, 0, 0.5); + + env_time += 1; + if (env_time > env_length[env_stage]) { + env_time = 0; + env_stage += 1; + if (env_stage == 3) finished = true; + } + env_vol = switch (env_stage) { + 0 => @as(f32, @floatFromInt(env_time)) / @as(f32, @floatFromInt(@max(1, env_length[0]))), + 1 => 1.0 + (1.0 - @as(f32, @floatFromInt(env_time)) / @as(f32, @floatFromInt(@max(1, env_length[1])))) * 2.0 * p.punch, + else => 1.0 - @as(f32, @floatFromInt(env_time)) / @as(f32, @floatFromInt(@max(1, env_length[2]))), + }; + + fphase += fdphase; + iphase = @intFromFloat(@min(@abs(fphase), 1023)); + + flthp *= flthp_d; + flthp = std.math.clamp(flthp, 0.00001, 0.1); + + var ssample: f32 = 0; + var oi: u32 = 0; + while (oi < 8) : (oi += 1) { + var sample: f32 = 0; + phase += 1; + if (phase >= period) { + phase = @mod(phase, period); + if (p.wave == .noise) for (&noise_buffer) |*nb| { + nb.* = frnd(&rng, 2) - 1; + }; + } + const fp: f32 = @as(f32, @floatFromInt(phase)) / @as(f32, @floatFromInt(period)); + sample = switch (p.wave) { + .square => if (fp < square_duty) 0.5 else -0.5, + .sawtooth => 1.0 - fp * 2, + .sine => @sin(fp * 2.0 * std.math.pi), + .noise => noise_buffer[@intCast(@as(i32, @intFromFloat(fp * 32)) & 31)], + }; + + const pp = fltp; + fltw *= fltw_d; + fltw = std.math.clamp(fltw, 0, 0.1); + if (p.lpf_freq != 1.0) { + fltdp += (sample - fltp) * fltw; + fltdp -= fltdp * fltdmp; + } else { + fltp = sample; + fltdp = 0; + } + fltp += fltdp; + fltphp += fltp - pp; + fltphp -= fltphp * flthp; + sample = fltphp; + phaser_buffer[@intCast(ipp & 1023)] = sample; + sample += phaser_buffer[@intCast((ipp - iphase + 1024) & 1023)]; + ipp = (ipp + 1) & 1023; + + ssample += sample * env_vol; + } + ssample = ssample / 8.0 * p.volume * 2.0; + out[n] = std.math.clamp(ssample, -1, 1); + } + return n; +} + +/// One parameter set per wave, between them every knob: a coin with punch, +/// arpeggio and a duty sweep; an explosion through both filters; a laser +/// with vibrato, phaser, repeat and a pitch limit; a rising sine. +const sets = [_]Params{ + .{ .wave = .square, .sustain = 0.1, .punch = 0.5, .decay = 0.3, .freq = 0.45, .freq_ramp = -0.2, .arp_mod = 0.4, .arp_speed = 0.6, .duty = 0.3, .duty_ramp = 0.2 }, + .{ .wave = .noise, .sustain = 0.2, .decay = 0.4, .freq = 0.2, .freq_ramp = -0.1, .lpf_freq = 0.6, .lpf_ramp = -0.1, .lpf_resonance = 0.4, .hpf_freq = 0.1, .hpf_ramp = 0.05 }, + .{ .wave = .sawtooth, .sustain = 0.25, .decay = 0.2, .freq = 0.5, .freq_limit = 0.1, .freq_dramp = 0.1, .vibrato_depth = 0.3, .vibrato_speed = 0.5, .phaser_offset = 0.3, .phaser_ramp = -0.1, .repeat_speed = 0.5 }, + .{ .wave = .sine, .attack = 0.2, .sustain = 0.2, .decay = 0.2, .freq = 0.3, .freq_ramp = 0.1, .freq_limit = 0.2, .volume = 0.8 }, +}; + +test "sfxr renders the original's samples at 44.1 kHz, and as long a sound at 48 kHz" { + // Length and Wyhash of the samples the original (02-dont-rat-me-out + // synth.zig) rendered for each set at 44.1 kHz. + const original = [_]struct { usize, u64 }{ + .{ 10003, 0xb969b441e8bd800 }, + .{ 20003, 0x5fc62aaf3122de5a }, + .{ 10253, 0x8d81ee15b98f33ac }, + .{ 12003, 0xe656fadd21b7dedb }, + }; + const out = try std.testing.allocator.alloc(f32, 2 * 48_000); + defer std.testing.allocator.free(out); + for (sets, original) |p, want| { + const n = render(p, reference_rate, out); + try std.testing.expectEqual(want[0], n); + try std.testing.expectEqual(want[1], std.hash.Wyhash.hash(0, std.mem.sliceAsBytes(out[0..n]))); + const at48 = render(p, 48_000, out); + try std.testing.expectApproxEqRel(@as(f64, @floatFromInt(n)) * 48_000 / reference_rate, @as(f64, @floatFromInt(at48)), 0.01); + } +} diff --git a/src/sketch/web.zig b/src/sketch/web.zig index 937b491..804a4df 100644 --- a/src/sketch/web.zig +++ b/src/sketch/web.zig @@ -2,7 +2,7 @@ //! the imports below: drawing on a 2D canvas, GPU work on WebGPU, sound and //! the microphone on Web Audio, files through the page. State, `update` and //! `draw` are the same Zig as on native. There is no timeline, and nothing -//! persists: Store lasts as long as the page. +//! persists. const std = @import("std"); const abi = @import("abi"); const root = @import("root.zig"); @@ -48,6 +48,8 @@ const js = struct { extern "gpu" fn download(id: u32, offset: u32, size: u32, key: u32) void; extern "audio" fn rate() u32; extern "audio" fn push(key: u32, ptr: [*]const f32, len: usize, clear: u32) void; + /// `count` samples from a GPU buffer, queued on arrival. + extern "audio" fn buffer(key: u32, id: u32, offset: u32, count: u32) void; extern "audio" fn queued(key: u32) u32; /// Keeps the microphone open; it answers through `sk_microphone`. extern "audio" fn listen() void; @@ -76,14 +78,12 @@ pub fn exportWeb(comptime App: type) void { } fn Driver(comptime App: type) type { - const G = root.Glue(App); + const G = root.Glue(App, .{}); const gpa = std.heap.wasm_allocator; return struct { var ready = false; var state: G.State = undefined; var session: G.Session = undefined; - // No disk on the web: the store lasts as long as the page. - var store: G.Store = undefined; var events: [1024]abi.Event = undefined; var event_count: usize = 0; var input: abi.Input = .{}; @@ -105,9 +105,7 @@ fn Driver(comptime App: type) type { .input = &input, .scratch = scratch.allocator(), .session = gpa, - .store = gpa, .session_root = std.mem.asBytes(&session), - .store_root = std.mem.asBytes(&store), .commands = &commands, }; } @@ -115,7 +113,6 @@ fn Driver(comptime App: type) type { fn init() callconv(.c) void { G.defaults(.state, std.mem.asBytes(&state)); G.defaults(.session, std.mem.asBytes(&session)); - G.defaults(.store, std.mem.asBytes(&store)); input.width = G.description.width; input.height = G.description.height; if (input.window_width == 0) { @@ -225,6 +222,10 @@ fn Driver(comptime App: type) type { s.pushed += v.samples.len; js.push(v.key, v.samples.ptr, v.samples.len, @intFromBool(v.clear)); }, + .audio_buffer => |v| { + stream(v.key).pushed += v.count; + js.buffer(v.key, @backingInt(v.buffer), v.offset, v.count); + }, .microphone => js.listen(), .upload => |v| _ = js.write(@backingInt(v.buffer), v.offset, v.bytes.ptr, v.bytes.len), .compute => |v| { @@ -241,9 +242,9 @@ fn Driver(comptime App: type) type { }, .download => |v| js.download(@backingInt(v.buffer), v.offset, v.size, v.key), .open_file => |v| js.openFile(v.command.ptr, v.command.len, v.pattern.ptr, v.pattern.len), - // Synthesised voices are not on the web yet; quitting a page + // Voices (and so their groups) are not on the web yet; quitting a page // means nothing; `run` lines go after the frame. - .voice, .quit, .run, .backdrop => {}, + .voice, .gain, .quit, .run, .backdrop => {}, } } @@ -411,8 +412,10 @@ fn Driver(comptime App: type) type { .textSize = textSize, .loadSound = loadSound, .decodeSound = unsupportedSound, + .newSound = newSound, .samples = samples, .readFile = readFile, + .appendFile = appendFile, .env = env, .clock = clock, }; @@ -460,6 +463,16 @@ fn Driver(comptime App: type) type { fn unsupportedSound(_: *anyopaque, _: []const u8) abi.Audio { return .none; } + /// Kept, unnamed, for `samples` (voices are silent on the web). + fn newSound(_: *anyopaque, ptr: [*]const f32, len: usize) callconv(.c) abi.Audio { + for (ptr[0..len]) |v| if (!std.math.isFinite(v)) return .none; + const copy = gpa.dupe(f32, ptr[0..len]) catch return .none; + sounds.append(gpa, .{ .name = "", .samples = copy }) catch { + gpa.free(copy); + return .none; + }; + return @fromBackingInt(@intCast(sounds.items.len)); + } fn samples(_: *anyopaque, a: abi.Audio) []const f32 { const i = @backingInt(a); return if (i == 0 or i > sounds.items.len) &.{} else sounds.items[i - 1].samples; @@ -467,6 +480,10 @@ fn Driver(comptime App: type) type { fn readFile(_: *anyopaque, _: []const u8) []const u8 { return &.{}; } + /// No files on the web: nothing is written, and the path is "". + fn appendFile(_: *anyopaque, _: [*]const u8, _: usize, _: [*]const u8, _: usize, _: bool) callconv(.c) [*:0]const u8 { + return ""; + } fn env(_: *anyopaque, _: []const u8) ?[]const u8 { return null; } |
